@odla-ai/crm 0.6.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/schema.ts","../src/rules.ts","../src/errors.ts","../src/pipeline.ts","../src/template.ts","../src/validate.ts","../src/config.ts","../src/discussion-reference.ts","../src/deps.ts","../src/query.ts","../src/rank.ts","../src/consent.ts","../src/channels.ts","../src/write-ops.ts","../src/records.ts","../src/stage-rank.ts","../src/tags-links.ts","../src/provenance.ts","../src/activities.ts","../src/views.ts","../src/config-store.ts","../src/email.ts","../src/facets/identity.ts","../src/summary.ts","../src/http.ts","../src/routes/params.ts","../src/routes/activities.ts","../src/routes/actions.ts","../src/routes/records.ts","../src/routes/misc.ts","../src/routes/discussion-references.ts","../src/routes/index.ts","../src/client.ts","../src/descriptor.ts"],"sourcesContent":["// @odla-ai/crm — flexible records, pipelines, follow-ups, consent-gated\n// email, and saved views on odla-db. Zero runtime deps: the db client and\n// email transport are injected structurally. UI components live under the\n// separate \"@odla-ai/crm/ui\" entry (browser-only).\nexport {\n CRM_NS,\n CRM_SLOTS,\n CONSENT_STATES,\n EMAIL_STATUSES,\n ACTIVITY_KINDS,\n TASK_STATUSES,\n SORTABLE_COLUMNS,\n CONFIG_KEY,\n DEFAULT_LIMIT,\n MAX_LIMIT,\n type CrmSlot,\n type ConsentState,\n type EmailStatus,\n type ActivityKind,\n type TaskStatus,\n} from \"./constants\";\nexport {\n CRM_SCHEMA,\n type AttrType,\n type SerializedAttr,\n type SerializedEntity,\n type SerializedLink,\n type SerializedLinkEnd,\n type SerializedSchema,\n} from \"./schema\";\nexport { CRM_RULES, crmRules, type CrmRule, type CrmRules } from \"./rules\";\nexport type {\n CrmScalar,\n CrmLookup,\n CrmEntityRef,\n CrmAttrs,\n CrmOp,\n CrmQuery,\n CrmRow,\n CrmResult,\n CrmAggregateSpec,\n CrmAggregateResult,\n CrmDb,\n CrmEmailSender,\n CrmRecord,\n CrmTag,\n CrmLink,\n CrmActivity,\n CrmContactChannel,\n CrmEmailLogRow,\n CrmView,\n StoredTemplate,\n CrmConfigRow,\n CrmRecordOrigin,\n CrmRecordDelivery,\n PreparedWrite,\n} from \"./types\";\nexport {\n defineCrm,\n composeCrmConfigs,\n type Crm,\n type CrmConfig,\n type TypeDef,\n type TypeFacets,\n type FieldDef,\n type FieldType,\n type PipelineDef,\n type StageDef,\n type RelationDef,\n type TemplateSpec,\n} from \"./config\";\nexport { initialStage, stageIndexOf, canTransition } from \"./pipeline\";\nexport { prepare, searchTextFor } from \"./validate\";\nexport { CrmInputError, CrmNotFoundError } from \"./errors\";\nexport {\n CRM_DISCUSSION_REFERENCE_KINDS,\n crmDiscussionReferenceHref,\n crmDiscussionReferenceId,\n formatCrmDiscussionReference,\n parseCrmDiscussionReference,\n type CrmDiscussionReference,\n type CrmDiscussionReferenceKind,\n type CrmDiscussionReferenceTarget,\n} from \"./discussion-reference\";\nexport { type CrmDeps, resolveDeps } from \"./deps\";\nexport {\n compileList,\n resolveSortColumn,\n type CompiledList,\n type CrmListParams,\n type CrmSort,\n type FieldFilter,\n type ViewFilters,\n} from \"./query\";\nexport { RANK_STEP, RANK_EPSILON, rankBetween, needsRebalance, rebalancePlan } from \"./rank\";\nexport {\n applyConsentEvent,\n canEmail,\n type ConsentEvent,\n type ConsentOutcome,\n} from \"./consent\";\nexport { renderTemplate, templateVars, lintTemplate } from \"./template\";\nexport {\n getRecord,\n mustGetRecord,\n listRecords,\n createRecord,\n updateRecord,\n setArchived,\n rowToRecord,\n} from \"./records\";\nexport { setStage, setRank, rebalanceRanks } from \"./stage-rank\";\nexport {\n addTag,\n removeTag,\n listTags,\n addLink,\n removeLink,\n listLinks,\n normalizeTag,\n} from \"./tags-links\";\nexport {\n recordOriginKey,\n getRecordOrigin,\n getRecordByOrigin,\n upsertRecordOrigin,\n listRecordOrigins,\n recordDeliveryKey,\n recordDeliveryAttempt,\n listRecordDeliveries,\n} from \"./provenance\";\nexport {\n addActivity,\n updateTask,\n listActivities,\n listTasks,\n} from \"./activities\";\nexport {\n channelKey,\n foldEmailStatus,\n listChannels,\n emailChannelOps,\n applyConsent,\n} from \"./channels\";\nexport {\n saveView,\n updateView,\n deleteView,\n listViews,\n type ViewSpec,\n} from \"./views\";\nexport {\n getConfig,\n saveConfig,\n defaultTemplates,\n type ConfigPatch,\n} from \"./config-store\";\nexport {\n sendTemplatedEmail,\n listEmailLog,\n recordCanEmail,\n type SendEmailOpts,\n type SendEmailResult,\n} from \"./email\";\nexport { linkIdentity } from \"./facets/identity\";\nexport { typeSummary, type TypeSummary } from \"./summary\";\nexport type {\n BillingEvent,\n BillingProvider,\n SubscriptionSnapshot,\n} from \"./billing/port\";\nexport {\n createCrmRoutes,\n type CrmActor,\n type CrmDiscussionReferenceActor,\n type CrmRouteOpts,\n} from \"./routes/index\";\nexport { CrmClient, type CrmClientOptions } from \"./client\";\nexport {\n crmIntegration,\n createCrmIntegration,\n type CrmIntegrationDescriptor,\n type CrmIntegrationOptions,\n type CrmIntegrationProbe,\n type CrmIntegrationSeed,\n} from \"./descriptor\";\n","/** The odla-db namespaces @odla-ai/crm installs and writes. */\nexport const CRM_NS = {\n record: \"crm_record\",\n tag: \"crm_tag\",\n link: \"crm_link\",\n activity: \"crm_activity\",\n channel: \"crm_contact_channel\",\n emailLog: \"crm_email_log\",\n view: \"crm_view\",\n config: \"crm_config\",\n origin: \"crm_record_origin\",\n delivery: \"crm_record_delivery\",\n} as const;\n\n/** Generic promoted columns a type's custom fields can claim for indexed\n * sort/filter: four strings, three numbers, two dates. Slots are per-type\n * virtual — every slot query is ANDed with `type`, so \"person.n1\" and\n * \"company.n1\" can mean different fields. */\nexport const CRM_SLOTS = [\"s1\", \"s2\", \"s3\", \"s4\", \"n1\", \"n2\", \"n3\", \"d1\", \"d2\"] as const;\n/** One generic promoted column a field can claim. */\nexport type CrmSlot = (typeof CRM_SLOTS)[number];\n\n/** Consent state of a contact channel (see `applyConsentEvent`). */\nexport const CONSENT_STATES = [\"subscribed\", \"unsubscribed\", \"bounced\", \"suppressed\"] as const;\n/** A contact channel's consent standing. */\nexport type ConsentState = (typeof CONSENT_STATES)[number];\n\n/** Denormalized per-record contactability, folded from the primary email\n * channel so list views can filter/sort on it: `none` = no email channel. */\nexport const EMAIL_STATUSES = [\"ok\", \"unsubscribed\", \"bounced\", \"suppressed\", \"none\"] as const;\n/** The record-level contactability fold. */\nexport type EmailStatus = (typeof EMAIL_STATUSES)[number];\n\n/** Activity kinds; `task` rows additionally carry status/dueAt/waitingOn. */\nexport const ACTIVITY_KINDS = [\"note\", \"task\", \"call\", \"meeting\", \"stage_change\", \"system\"] as const;\n/** What kind of feed entry an activity row is. */\nexport type ActivityKind = (typeof ACTIVITY_KINDS)[number];\n\n/** Task lifecycle for `kind: \"task\"` activities. */\nexport const TASK_STATUSES = [\"open\", \"waiting\", \"done\"] as const;\n/** Where a follow-up task stands. */\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\n\n/** Promoted `crm_record` columns list queries may sort on, beyond per-type\n * slot fields. All are indexed in the schema — odla-db orders on exactly one\n * indexed field per query. */\nexport const SORTABLE_COLUMNS = [\n \"name\",\n \"primaryEmail\",\n \"stageIndex\",\n \"stageChangedAt\",\n \"rank\",\n \"score\",\n \"emailStatus\",\n \"billingStatus\",\n \"renewalAt\",\n \"createdAt\",\n \"updatedAt\",\n] as const;\n\n/** Record field names owned by the engine — type configs may not redefine\n * them as custom fields. */\nexport const RESERVED_FIELDS = new Set([\n \"id\",\n \"type\",\n \"primaryEmail\",\n \"stage\",\n \"stageIndex\",\n \"stageChangedAt\",\n \"rank\",\n \"score\",\n \"ownerId\",\n \"emailStatus\",\n \"clerkUserId\",\n \"stripeCustomerId\",\n \"subscriptionId\",\n \"billingStatus\",\n \"renewalAt\",\n \"mrr\",\n \"fields\",\n \"searchText\",\n \"archived\",\n \"createdAt\",\n \"updatedAt\",\n \"archivedAt\",\n ...CRM_SLOTS,\n]);\n\n/** The singleton `crm_config` row's natural key. */\nexport const CONFIG_KEY = \"default\";\n\n/** Server list-window defaults, aligned with odla-db's query limits\n * (default 100, max 1000). */\nexport const DEFAULT_LIMIT = 50;\n/** Hard per-window row cap for list routes (odla-db allows up to 1000). */\nexport const MAX_LIMIT = 200;\n","// The odla-db schema @odla-ai/crm installs (POST to `/app/:id/schema` as\n// `{ schema: CRM_SCHEMA }`). Ships pre-serialized (the wire shape) so\n// provisioning needs no schema-builder dependency, mirroring @odla-ai/chat.\n//\n// Design note: record types are DATA, not schema. All types share one\n// `crm_record` namespace — promoted columns cover the hot paths every type\n// has (name, stage, rank, contactability, billing cache), nine generic typed\n// slots (s1–s4/n1–n3/d1–d2) carry each type's custom sortable fields, and the\n// complete field payload lives in the `fields` json (slots are an index\n// mirror, never the source of truth). `searchText` is a denormalized FTS\n// haystack rebuilt on every write. Tags and record↔record links are join\n// rows with natural keys (idempotent upserts) because rules/queries have no\n// array-contains, and schema links are label-static while CRM relations are\n// config-declared.\nimport { CRM_NS } from \"./constants\";\n\n/** Wire-shape attribute value kinds odla-db stores. */\nexport type AttrType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n/** One serialized attribute: its type and index/uniqueness flags. */\nexport interface SerializedAttr {\n type: AttrType;\n unique: boolean;\n indexed: boolean;\n optional: boolean;\n}\n/** One serialized namespace: its attribute map. */\nexport interface SerializedEntity {\n attrs: Record<string, SerializedAttr>;\n}\n/** One end of a serialized schema link. */\nexport interface SerializedLinkEnd {\n on: string;\n has: \"one\" | \"many\";\n label: string;\n}\n/** A serialized schema link (unused by crm — relations are rows). */\nexport interface SerializedLink {\n forward: SerializedLinkEnd;\n reverse: SerializedLinkEnd;\n}\n/** The wire-shape schema POSTed to `/app/:id/schema`. */\nexport interface SerializedSchema {\n entities: Record<string, SerializedEntity>;\n links: Record<string, SerializedLink>;\n}\n\ntype Opt = Partial<Omit<SerializedAttr, \"type\">>;\nconst a = (type: AttrType, o: Opt = {}): SerializedAttr => ({\n type,\n unique: false,\n indexed: false,\n optional: false,\n ...o,\n});\nconst uniq = (type: AttrType): SerializedAttr => a(type, { unique: true, indexed: true });\nconst idx = (type: AttrType, optional = false): SerializedAttr => a(type, { indexed: true, optional });\nconst opt = (type: AttrType): SerializedAttr => a(type, { optional: true });\n\n/**\n * The pre-serialized (wire-shape) odla-db schema for the ten crm\n * namespaces; POST it to `/app/:id/schema` as `{ schema: CRM_SCHEMA }`.\n * One generic `crm_record` holds every record type (the type registry is\n * app config, not schema); natural-key uniqueness on tags, links, channels,\n * and the config row makes those writes idempotent upserts.\n */\nexport const CRM_SCHEMA: SerializedSchema = {\n entities: {\n [CRM_NS.record]: {\n attrs: {\n // Entity ids are not attributes in odla-db, so `where: { id }` matches\n // nothing unless the id is mirrored as a written attr — the getRecord /\n // tag-filter / neighbor reads all filter by id. Mirror it as unique.\n id: uniq(\"string\"),\n type: idx(\"string\"),\n name: idx(\"string\"),\n primaryEmail: idx(\"string\", true),\n stage: idx(\"string\", true),\n stageIndex: idx(\"number\", true),\n stageChangedAt: idx(\"date\", true),\n rank: idx(\"number\", true),\n score: idx(\"number\", true),\n ownerId: idx(\"string\", true),\n emailStatus: idx(\"string\", true),\n clerkUserId: a(\"string\", { unique: true, indexed: true, optional: true }),\n stripeCustomerId: idx(\"string\", true),\n subscriptionId: opt(\"string\"),\n billingStatus: idx(\"string\", true),\n renewalAt: idx(\"date\", true),\n mrr: opt(\"number\"),\n s1: idx(\"string\", true),\n s2: idx(\"string\", true),\n s3: idx(\"string\", true),\n s4: idx(\"string\", true),\n n1: idx(\"number\", true),\n n2: idx(\"number\", true),\n n3: idx(\"number\", true),\n d1: idx(\"date\", true),\n d2: idx(\"date\", true),\n fields: a(\"json\"),\n searchText: a(\"string\"),\n archived: idx(\"boolean\"),\n createdAt: idx(\"date\"),\n updatedAt: idx(\"date\"),\n archivedAt: opt(\"date\"),\n },\n },\n [CRM_NS.tag]: {\n attrs: {\n key: uniq(\"string\"), // `${recordId}:${tag}`\n recordId: idx(\"string\"),\n tag: idx(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.link]: {\n attrs: {\n key: uniq(\"string\"), // `${fromId}:${relation}:${toId}`\n fromId: idx(\"string\"),\n toId: idx(\"string\"),\n relation: idx(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.activity]: {\n attrs: {\n id: uniq(\"string\"), // mirrored so updateTask can read one by id\n recordId: idx(\"string\"),\n kind: idx(\"string\"),\n body: a(\"string\"),\n status: idx(\"string\", true), // tasks: open | waiting | done\n dueAt: idx(\"date\", true),\n waitingOn: opt(\"string\"),\n assigneeId: idx(\"string\", true),\n authorId: idx(\"string\"),\n createdAt: idx(\"date\"),\n completedAt: opt(\"date\"),\n meta: opt(\"json\"),\n },\n },\n [CRM_NS.channel]: {\n attrs: {\n key: uniq(\"string\"), // `${recordId}:${kind}:${value}`\n recordId: idx(\"string\"),\n kind: a(\"string\"), // email | phone\n value: idx(\"string\"), // emails lowercased\n isPrimary: a(\"boolean\"),\n consent: idx(\"string\"),\n consentAt: idx(\"date\"),\n consentSource: opt(\"string\"),\n unsubscribeToken: uniq(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.emailLog]: {\n attrs: {\n recordId: idx(\"string\", true),\n channelId: opt(\"string\"),\n to: a(\"string\"),\n templateId: idx(\"string\"),\n subject: a(\"string\"),\n transport: a(\"string\"), // sent | log-only\n redirected: opt(\"boolean\"),\n dedupeKey: idx(\"string\", true),\n messageId: opt(\"string\"),\n error: opt(\"string\"),\n sentAt: idx(\"date\"),\n },\n },\n [CRM_NS.view]: {\n attrs: {\n id: uniq(\"string\"), // mirrored so getView/updateView can read one by id\n name: a(\"string\"),\n type: idx(\"string\"),\n ownerId: idx(\"string\", true),\n shared: idx(\"boolean\"),\n filters: a(\"json\"),\n sort: a(\"json\"),\n columns: a(\"json\"),\n createdAt: idx(\"date\"),\n updatedAt: idx(\"date\"),\n },\n },\n [CRM_NS.config]: {\n attrs: {\n key: uniq(\"string\"), // CONFIG_KEY singleton\n notificationEmail: opt(\"string\"),\n replyTo: opt(\"string\"),\n debugEmail: opt(\"string\"),\n emailTemplates: a(\"json\"), // Record<templateId, {subject, text, enabled}>\n settings: a(\"json\"),\n updatedAt: idx(\"date\"),\n },\n },\n [CRM_NS.origin]: {\n attrs: {\n // One upstream record maps to one local record. The structured source\n // survives tag edits and supports more than one upstream site.\n key: uniq(\"string\"), // `${sourceId}:${sourceRecordId}`\n recordId: idx(\"string\"),\n sourceId: idx(\"string\"),\n sourceRecordId: idx(\"string\"),\n sourceUrl: opt(\"string\"),\n payloadVersion: idx(\"number\"),\n firstReceivedAt: idx(\"date\"),\n lastReceivedAt: idx(\"date\"),\n },\n },\n [CRM_NS.delivery]: {\n attrs: {\n // The latest delivery state for one local record → target edge.\n key: uniq(\"string\"), // `${recordId}:${targetId}`\n recordId: idx(\"string\"),\n targetId: idx(\"string\"),\n remoteRecordId: idx(\"string\", true),\n status: idx(\"string\"),\n attempts: idx(\"number\"),\n payloadVersion: idx(\"number\"),\n lastAttemptAt: idx(\"date\"),\n deliveredAt: idx(\"date\", true),\n error: opt(\"string\"),\n },\n },\n },\n links: {},\n};\n","// Default-deny CEL rules for the crm namespaces (POST to `/app/:id/admin/rules`).\n//\n// CRM access is worker-mediated BY DESIGN: slot mapping, searchText rebuild,\n// pipeline gates, and field validation are functions of the app's crm config\n// and cannot be expressed in CEL, so every crm_* namespace is closed to\n// end-user credentials and all reads/writes flow through `createCrmRoutes`\n// running with the app's admin key (which bypasses rules).\nimport { CRM_NS } from \"./constants\";\n\n/** Per-namespace CEL rule strings (missing action = deny). */\nexport interface CrmRule {\n view?: string;\n create?: string;\n update?: string;\n delete?: string;\n}\n/** Namespace → rule set, as installed at `/app/:id/admin/rules`. */\nexport type CrmRules = Record<string, CrmRule>;\n\nconst DENY: CrmRule = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n\n/**\n * Deny-all rules for every crm namespace; install at `/app/:id/admin/rules`.\n * The route factory (admin key) is the only door — see the header note for\n * why the CRM cannot be rule-governed client-side.\n */\nexport const CRM_RULES: CrmRules = Object.fromEntries(\n Object.values(CRM_NS).map((ns) => [ns, { ...DENY }]),\n);\n\n/**\n * Rules factory, mirroring `chatRules()`. Today it returns the deny-all set;\n * it exists so a future member-facing surface (e.g. \"records I own are\n * visible to me\") can widen specific namespaces without apps changing their\n * provisioning call shape.\n */\nexport function crmRules(): CrmRules {\n return Object.fromEntries(Object.entries(CRM_RULES).map(([ns, r]) => [ns, { ...r }]));\n}\n","/** Caller-fault error (bad type, unknown field, blocked transition…) — the\n * route layer maps it to a 400. `fields` carries per-field messages when the\n * failure came from input validation. */\nexport class CrmInputError extends Error {\n readonly fields?: Record<string, string>;\n constructor(message: string, fields?: Record<string, string>) {\n super(message);\n this.name = \"CrmInputError\";\n this.fields = fields;\n }\n}\n\n/** Missing entity — the route layer maps it to a 404. */\nexport class CrmNotFoundError extends Error {\n constructor(what: string) {\n super(`${what} not found`);\n this.name = \"CrmNotFoundError\";\n }\n}\n","// Pipeline mechanics: stage order, allowed edges, and gates. Pure functions\n// of (type config, record) — the route layer applies the resulting decision.\nimport type { TypeDef } from \"./config\";\nimport { CrmInputError } from \"./errors\";\nimport type { CrmRecord } from \"./types\";\n\n/** The stage a new record of this type starts in (first declared stage). */\nexport function initialStage(def: TypeDef): string | undefined {\n return def.pipeline?.stages[0]?.id;\n}\n\n/** Position of a stage in the declared order — denormalized onto the record\n * as `stageIndex` so \"sort by pipeline position\" is a single-field order. */\nexport function stageIndexOf(def: TypeDef, stage: string): number {\n const at = (def.pipeline?.stages ?? []).findIndex((s) => s.id === stage);\n if (at === -1) throw new CrmInputError(`unknown stage \"${stage}\"`);\n return at;\n}\n\n/**\n * Why this record may not move to `to` — or null when the move is allowed.\n * Checks, in order: the type has a pipeline, the target exists, the source\n * isn't terminal (unless it declares explicit outgoing transitions), the\n * edge is allowed, and the target's gate passes.\n */\nexport function canTransition(def: TypeDef, record: CrmRecord, to: string): string | null {\n const pipeline = def.pipeline;\n if (!pipeline) return \"type has no pipeline\";\n const stages = new Map(pipeline.stages.map((s) => [s.id, s]));\n if (!stages.has(to)) return `unknown stage \"${to}\"`;\n const from = record.stage;\n if (from === to) return \"already in that stage\";\n if (from != null) {\n if (!stages.has(from)) return `record is in unknown stage \"${from}\"`;\n const declared = pipeline.transitions?.[from];\n if (declared) {\n if (!declared.includes(to)) return `cannot move from \"${from}\" to \"${to}\"`;\n } else if (stages.get(from)?.terminal) {\n return `\"${from}\" is terminal`;\n }\n }\n const gate = pipeline.gates?.[to];\n if (gate) {\n const blocked = gate(record);\n if (blocked) return blocked;\n }\n return null;\n}\n","// Owner-editable {{var}} templates (the S&S groups.emailTemplates model,\n// generalized). Rendering is deliberately dumb — plain token substitution,\n// missing vars become \"\" — and `lintTemplate` gives the admin UI a way to\n// surface typos before a send ever runs.\n\nconst TOKEN_RE = /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g;\n\n/** Substitute `{{var}}` tokens from `vars`; unknown tokens render as \"\". */\nexport function renderTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(TOKEN_RE, (_, name: string) => vars[name] ?? \"\");\n}\n\n/** The distinct `{{var}}` names a template references, in first-seen order. */\nexport function templateVars(template: string): string[] {\n const seen = new Set<string>();\n for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1] as string);\n return [...seen];\n}\n\n/**\n * Template health check for the settings UI: which referenced vars aren't\n * in the declared contract (typos — they'd silently render as \"\"), and which\n * declared vars go unused (usually fine, occasionally a forgotten insert).\n */\nexport function lintTemplate(\n template: string,\n knownVars: readonly string[],\n): { unknown: string[]; unused: string[] } {\n const used = templateVars(template);\n const known = new Set(knownVars);\n return {\n unknown: used.filter((v) => !known.has(v)),\n unused: knownVars.filter((v) => !used.includes(v)),\n };\n}\n","// Input validation + coercion for record writes. `prepare` is the single\n// enforcement point (all writes are worker-mediated): it maps config fields\n// onto the promoted columns, mirrors slotted values, and rebuilds the FTS\n// haystack — returning either the exact attrs to write or per-field errors.\nimport type { FieldDef, TypeDef } from \"./config\";\nimport type { CrmAttrs, CrmRecord, PreparedWrite } from \"./types\";\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst STRINGISH: ReadonlySet<string> = new Set([\"string\", \"email\", \"url\", \"enum\"]);\n\ntype Coerced = { ok: true; value: unknown } | { ok: false; error: string };\nconst bad = (error: string): Coerced => ({ ok: false, error });\nconst good = (value: unknown): Coerced => ({ ok: true, value });\n\nfunction coerce(def: FieldDef, raw: unknown): Coerced {\n if (raw === null) return good(null);\n switch (def.type) {\n case \"string\":\n return typeof raw === \"string\" ? good(raw.trim()) : bad(\"expected a string\");\n case \"email\": {\n if (typeof raw !== \"string\") return bad(\"expected an email address\");\n const email = raw.trim().toLowerCase();\n return EMAIL_RE.test(email) ? good(email) : bad(\"not a valid email address\");\n }\n case \"url\": {\n if (typeof raw !== \"string\") return bad(\"expected a URL\");\n const url = raw.trim();\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n return bad(\"must be an http(s) URL\");\n return good(url);\n } catch {\n return bad(\"not a valid URL\");\n }\n }\n case \"number\":\n return typeof raw === \"number\" && Number.isFinite(raw) ? good(raw) : bad(\"expected a number\");\n case \"boolean\":\n return typeof raw === \"boolean\" ? good(raw) : bad(\"expected true or false\");\n case \"date\": {\n if (typeof raw === \"number\" && Number.isFinite(raw)) return good(raw);\n if (typeof raw === \"string\") {\n const t = Date.parse(raw);\n if (!Number.isNaN(t)) return good(t);\n }\n return bad(\"expected epoch ms or an ISO date string\");\n }\n case \"enum\":\n return typeof raw === \"string\" && (def.options ?? []).includes(raw)\n ? good(raw)\n : bad(`expected one of: ${(def.options ?? []).join(\", \")}`);\n case \"json\":\n return raw === undefined ? bad(\"expected a value\") : good(raw);\n }\n}\n\nconst empty = (def: FieldDef, value: unknown): boolean =>\n value == null || (STRINGISH.has(def.type) && value === \"\");\n\n/** The FTS haystack: name + email + every searchable field value, lowercased.\n * String-ish fields are searchable by default; other types opt in with\n * `search: true`. Exported for the write paths that must rebuild it. */\nexport function searchTextFor(def: TypeDef, name: string, email: string | null, fields: Record<string, unknown>): string {\n const parts: string[] = [name];\n if (email) parts.push(email);\n for (const [fieldName, field] of Object.entries(def.fields)) {\n // The name/email fields already contributed via the promoted columns.\n if (fieldName === (def.nameField ?? \"name\") || fieldName === def.emailField) continue;\n const searchable = field.search ?? STRINGISH.has(field.type);\n const value = fields[fieldName];\n if (searchable && value != null && value !== \"\") parts.push(String(value));\n }\n return parts.join(\" \").toLowerCase();\n}\n\n/**\n * Validate + coerce `input` (keyed by config field name) for one type.\n * Create (no `existing`): required fields must be present, and the\n * `nameField` always (a record without a name is unlistable). Update:\n * partial — unnamed fields keep their stored values. On success returns the\n * columns to write — promoted `name`, `primaryEmail` and each claimed slot\n * that has a value, the complete `fields` json (source of truth), and the\n * rebuilt `searchText` — plus `retract`, the columns whose field went empty\n * (odla-db can't store a scalar null, so an empty column is omitted on create\n * and retracted on update). Otherwise `{ ok: false, errors }` keyed by field.\n */\nexport function prepare(\n def: TypeDef,\n input: Record<string, unknown>,\n existing?: CrmRecord,\n): PreparedWrite {\n const errors: Record<string, string> = {};\n for (const key of Object.keys(input))\n if (!def.fields[key]) errors[key] = \"unknown field\";\n\n const fields: Record<string, unknown> = { ...(existing?.fields ?? {}) };\n for (const [fieldName, field] of Object.entries(def.fields)) {\n const supplied = Object.hasOwn(input, fieldName);\n if (supplied) {\n const coerced = coerce(field, input[fieldName]);\n if (!coerced.ok) {\n errors[fieldName] = coerced.error;\n continue;\n }\n fields[fieldName] = coerced.value;\n }\n const settled = fields[fieldName];\n if (field.required && (existing ? supplied || !(fieldName in fields) : true) && empty(field, settled))\n errors[fieldName] = errors[fieldName] ?? \"required\";\n }\n\n const nameField = def.nameField ?? \"name\";\n const name = fields[nameField];\n if (typeof name !== \"string\" || name === \"\") errors[nameField] = errors[nameField] ?? \"required\";\n\n let primaryEmail: string | null = null;\n if (def.emailField) {\n const email = fields[def.emailField];\n primaryEmail = typeof email === \"string\" && email !== \"\" ? email : null;\n }\n\n if (Object.keys(errors).length > 0) return { ok: false, errors };\n\n const attrs: CrmAttrs = {\n name: name as string,\n fields,\n searchText: searchTextFor(def, name as string, primaryEmail, fields),\n };\n // odla-db has no storable scalar null: a promoted column / slot is either\n // WRITTEN with a value or CLEARED (its triple retracted). On update we retract\n // the ones that went empty so the index mirror can't go stale; on create there\n // is nothing to clear, so an empty column is simply omitted.\n const retract: string[] = [];\n const clear = (column: string) => {\n if (existing) retract.push(column);\n };\n if (def.emailField) {\n if (primaryEmail === null) clear(\"primaryEmail\");\n else attrs.primaryEmail = primaryEmail;\n }\n for (const [fieldName, field] of Object.entries(def.fields)) {\n if (!field.slot) continue;\n const value = fields[fieldName];\n if (empty(field, value)) clear(field.slot);\n else attrs[field.slot] = value;\n }\n return { ok: true, attrs, retract };\n}\n","// The app-facing configuration surface: record types are DATA layered over\n// the fixed CRM_SCHEMA. `defineCrm` validates the whole config at boot —\n// slot collisions, enum/slot type agreement, pipeline edges — so a bad\n// config fails at startup, never at request time.\nimport { CRM_SLOTS, RESERVED_FIELDS, type CrmSlot } from \"./constants\";\nimport { CrmInputError } from \"./errors\";\nimport { CRM_SCHEMA, type SerializedSchema } from \"./schema\";\nimport { CRM_RULES, type CrmRules } from \"./rules\";\nimport { canTransition, initialStage, stageIndexOf } from \"./pipeline\";\nimport { lintTemplate } from \"./template\";\nimport { prepare } from \"./validate\";\nimport type { CrmRecord, PreparedWrite } from \"./types\";\n\n/** Value kinds a custom field can hold. `email`/`url`/`enum` are validated\n * strings; `date` accepts epoch ms or ISO strings and stores epoch ms. */\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"email\" | \"url\" | \"enum\" | \"json\";\n\n/** One custom field of a record type: value kind, validation, slot promotion. */\nexport interface FieldDef {\n type: FieldType;\n label?: string;\n required?: boolean;\n /** Allowed values — `enum` fields only. */\n options?: readonly string[];\n /** Promote to an indexed slot column for server-side sort/filter. String-ish\n * fields take `s1`–`s4`, numbers `n1`–`n3`, dates `d1`–`d2`. */\n slot?: CrmSlot;\n /** Include in the FTS haystack. Defaults to true for string-ish fields. */\n search?: boolean;\n}\n\n/** One pipeline stage; declaration order is the sort order (`stageIndex`). */\nexport interface StageDef {\n id: string;\n label?: string;\n /** Terminal stages have no outgoing transitions unless `transitions`\n * explicitly declares some. */\n terminal?: boolean;\n}\n\n/** A type's stage machine: ordered stages, allowed edges, gates. */\nexport interface PipelineDef {\n stages: readonly StageDef[];\n /** Allowed edges per stage id. A stage with no entry accepts any move\n * (unless terminal). */\n transitions?: Record<string, readonly string[]>;\n /** Per-target-stage gate: return an error string to block, null to allow. */\n gates?: Record<string, (record: CrmRecord) => string | null>;\n}\n\n/** Opt-in built-in concerns for a type (identity/billing/email/rank). */\nexport interface TypeFacets {\n identity?: boolean;\n billing?: boolean;\n email?: boolean;\n rank?: \"manual\" | \"score\" | \"both\";\n}\n\n/** One record type: its fields, pipeline, facets, and hooks. */\nexport interface TypeDef {\n label: string;\n labelPlural?: string;\n /** Optional admin collection group. Hosts can keep people and portfolio\n * records in separate workspaces without moving either outside the CRM. */\n workspace?: string;\n /** Field mapped to the promoted `name` column. Default `\"name\"`. */\n nameField?: string;\n /** `email`-typed field mapped to `primaryEmail` (lowercased) and backed by\n * a consent-bearing contact channel. */\n emailField?: string;\n fields: Record<string, FieldDef>;\n pipeline?: PipelineDef;\n facets?: TypeFacets;\n /** Computes the record's `score` column (rank facet \"score\"/\"both\"). */\n scorer?: (record: CrmRecord) => number;\n /** Post-commit hooks per target stage id — e.g. S&S \"approved\" promotes the\n * member's Clerk role. Fired by the route layer AFTER the stage write. */\n onTransition?: Record<string, (record: CrmRecord) => void | Promise<void>>;\n}\n\n/** A typed record↔record relation (e.g. person works_at company). */\nexport interface RelationDef {\n from: string;\n to: string;\n label: string;\n reverseLabel?: string;\n}\n\n/** Declares a template's contract in code: its variables and its consent\n * CLASS. Subject/body/enabled live on the data row (owner-editable). */\nexport interface TemplateSpec {\n vars: readonly string[];\n class: \"transactional\" | \"marketing\";\n defaults?: { subject: string; text: string };\n}\n\n/** The whole app-level CRM configuration `defineCrm` validates. */\nexport interface CrmConfig {\n types: Record<string, TypeDef>;\n relations?: Record<string, RelationDef>;\n templates?: Record<string, TemplateSpec>;\n}\n\n/** The resolved engine `defineCrm` returns: static schema/rules plus the\n * config-aware operations the route factory and ops modules run on. */\nexport interface Crm {\n config: CrmConfig;\n schema: SerializedSchema;\n rules: CrmRules;\n type(name: string): TypeDef;\n prepare(type: string, input: Record<string, unknown>, existing?: CrmRecord): PreparedWrite;\n canTransition(type: string, record: CrmRecord, to: string): string | null;\n initialStage(type: string): string | undefined;\n stageIndex(type: string, stage: string): number;\n}\n\nconst NAME_RE = /^[a-z][a-z0-9_-]*$/;\nconst FIELD_RE = /^[a-z][a-zA-Z0-9_]*$/; // camelCase welcome; no spaces/dashes\nconst SLOT_KIND: Record<CrmSlot, FieldType[]> = {\n s1: [\"string\", \"email\", \"url\", \"enum\"],\n s2: [\"string\", \"email\", \"url\", \"enum\"],\n s3: [\"string\", \"email\", \"url\", \"enum\"],\n s4: [\"string\", \"email\", \"url\", \"enum\"],\n n1: [\"number\"],\n n2: [\"number\"],\n n3: [\"number\"],\n d1: [\"date\"],\n d2: [\"date\"],\n};\n\nfunction fail(path: string, message: string): never {\n throw new Error(`defineCrm: ${path} ${message}`);\n}\n\nfunction checkType(typeName: string, def: TypeDef): void {\n const at = `types.${typeName}`;\n if (!NAME_RE.test(typeName)) fail(at, \"must match /^[a-z][a-z0-9_-]*$/\");\n if (def.workspace != null && !NAME_RE.test(def.workspace)) {\n fail(`${at}.workspace`, \"must match /^[a-z][a-z0-9_-]*$/\");\n }\n const claimed = new Map<CrmSlot, string>();\n for (const [fieldName, field] of Object.entries(def.fields)) {\n const fat = `${at}.fields.${fieldName}`;\n if (RESERVED_FIELDS.has(fieldName)) fail(fat, \"is a reserved column name\");\n if (!FIELD_RE.test(fieldName)) fail(fat, \"must match /^[a-z][a-zA-Z0-9_]*$/\");\n if (field.type === \"enum\" && !(field.options && field.options.length > 0))\n fail(fat, \"enum fields need non-empty options\");\n if (field.type !== \"enum\" && field.options) fail(fat, \"options are for enum fields only\");\n if (field.slot) {\n if (!CRM_SLOTS.includes(field.slot)) fail(fat, `unknown slot ${field.slot}`);\n if (!SLOT_KIND[field.slot].includes(field.type))\n fail(fat, `slot ${field.slot} cannot hold a ${field.type} field`);\n const holder = claimed.get(field.slot);\n if (holder) fail(fat, `slot ${field.slot} already claimed by ${holder}`);\n claimed.set(field.slot, fieldName);\n }\n }\n const nameField = def.nameField ?? \"name\";\n if (!def.fields[nameField]) fail(at, `nameField \"${nameField}\" is not a declared field`);\n if (def.emailField) {\n const emailDef = def.fields[def.emailField];\n if (!emailDef) fail(at, `emailField \"${def.emailField}\" is not a declared field`);\n if (emailDef.type !== \"email\") fail(at, `emailField \"${def.emailField}\" must have type \"email\"`);\n }\n checkPipeline(at, def);\n}\n\nfunction checkPipeline(at: string, def: TypeDef): void {\n const pipeline = def.pipeline;\n if (!pipeline) return;\n if (pipeline.stages.length === 0) fail(at, \"pipeline.stages must not be empty\");\n const ids = new Set<string>();\n for (const stage of pipeline.stages) {\n if (ids.has(stage.id)) fail(at, `duplicate stage \"${stage.id}\"`);\n ids.add(stage.id);\n }\n for (const [from, targets] of Object.entries(pipeline.transitions ?? {})) {\n if (!ids.has(from)) fail(at, `transitions from unknown stage \"${from}\"`);\n for (const to of targets) if (!ids.has(to)) fail(at, `transition to unknown stage \"${to}\"`);\n }\n for (const gated of Object.keys(pipeline.gates ?? {}))\n if (!ids.has(gated)) fail(at, `gate on unknown stage \"${gated}\"`);\n for (const hooked of Object.keys(def.onTransition ?? {}))\n if (!ids.has(hooked)) fail(at, `onTransition hook on unknown stage \"${hooked}\"`);\n}\n\n/**\n * Validate an app's CRM configuration and return the resolved {@link Crm}\n * engine. Throws (with a `types.person.fields.…`-style path) on slot\n * collisions, enum/slot type disagreements, unknown pipeline edges, reserved\n * field names, or dangling name/email field references — at boot, before any\n * request runs.\n */\nexport function defineCrm(config: CrmConfig): Crm {\n if (Object.keys(config.types).length === 0) fail(\"types\", \"must declare at least one type\");\n for (const [typeName, def] of Object.entries(config.types)) checkType(typeName, def);\n for (const [relName, rel] of Object.entries(config.relations ?? {})) {\n const at = `relations.${relName}`;\n if (!config.types[rel.from]) fail(at, `unknown from-type \"${rel.from}\"`);\n if (!config.types[rel.to]) fail(at, `unknown to-type \"${rel.to}\"`);\n if (!rel.label) fail(at, \"needs a label\");\n }\n for (const [tplName, tpl] of Object.entries(config.templates ?? {})) {\n const at = `templates.${tplName}`;\n if (tpl.class !== \"transactional\" && tpl.class !== \"marketing\")\n fail(at, `class must be transactional|marketing`);\n for (const v of tpl.vars) if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v)) fail(at, `bad var \"${v}\"`);\n if (tpl.defaults) {\n const lint = lintTemplate(`${tpl.defaults.subject}\\n${tpl.defaults.text}`, tpl.vars);\n if (lint.unknown.length) fail(at, `defaults reference unknown vars: ${lint.unknown.join(\", \")}`);\n }\n }\n\n const type = (name: string): TypeDef => {\n const def = config.types[name];\n if (!def) throw new CrmInputError(`unknown record type \"${name}\"`);\n return def;\n };\n return {\n config,\n schema: CRM_SCHEMA,\n rules: CRM_RULES,\n type,\n prepare: (name, input, existing) => prepare(type(name), input, existing),\n canTransition: (name, record, to) => canTransition(type(name), record, to),\n initialStage: (name) => initialStage(type(name)),\n stageIndex: (name, stage) => stageIndexOf(type(name), stage),\n };\n}\n\n/**\n * Compose independently-owned CRM config fragments. Duplicate type, relation,\n * or template ids fail closed so adopting a feature preset cannot silently\n * replace a host's operating pipeline or email classification.\n */\nexport function composeCrmConfigs(...configs: readonly CrmConfig[]): CrmConfig {\n if (configs.length === 0) throw new Error(\"composeCrmConfigs: at least one config is required\");\n const result: CrmConfig = { types: {} };\n const merge = <T>(\n kind: string,\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n ) => {\n for (const [id, value] of Object.entries(source ?? {})) {\n if (Object.hasOwn(target, id)) throw new Error(`composeCrmConfigs: duplicate ${kind} \"${id}\"`);\n target[id] = value;\n }\n };\n for (const config of configs) {\n merge(\"type\", result.types, config.types);\n if (config.relations) {\n result.relations ??= {};\n merge(\"relation\", result.relations, config.relations);\n }\n if (config.templates) {\n result.templates ??= {};\n merge(\"template\", result.templates, config.templates);\n }\n }\n return result;\n}\n","/** CRM resources that can be shared into a Discussion message. */\nexport const CRM_DISCUSSION_REFERENCE_KINDS = [\n \"crm:record\",\n \"crm:activity\",\n] as const;\n\n/** One CRM resource kind understood by the native CRM destination. */\nexport type CrmDiscussionReferenceKind =\n (typeof CRM_DISCUSSION_REFERENCE_KINDS)[number];\n\n/** Canonical CRM destination target parsed from an `odla-ref` deep link. */\nexport interface CrmDiscussionReferenceTarget {\n kind: CrmDiscussionReferenceKind;\n type: string;\n recordId: string;\n activityId?: string;\n}\n\n/** Product-owned projection returned to Discussion typeahead and exact lookup. */\nexport interface CrmDiscussionReference {\n /** Canonical CRM kind used in stored Discussion ref markup. */\n kind: CrmDiscussionReferenceKind;\n /** Opaque durable product id; never infer CRM access from its segments. */\n id: string;\n /** Product-authored primary display name. */\n label: string;\n /** Short product-authored secondary context for the picker. */\n hint: string;\n /** Bounded product-authored context safe to show an LLM or person. */\n summary: string;\n /** Current product status at inspection time. */\n status: string;\n /** Human-readable native surface the link opens. */\n destination: string;\n /** Same-origin native link; navigation is not mutation authority. */\n href: string;\n}\n\nconst SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,199}$/;\n\n/** Durable ref id: `type/recordId`, plus an activity id for feed entries. */\nexport function crmDiscussionReferenceId(\n target: CrmDiscussionReferenceTarget,\n): string {\n const root = `${target.type}/${target.recordId}`;\n return target.activityId ? `${root}/${target.activityId}` : root;\n}\n\n/** Canonical value stored in the stable `odla-ref` query parameter. */\nexport function formatCrmDiscussionReference(\n target: CrmDiscussionReferenceTarget,\n): string {\n return `${target.kind}/${crmDiscussionReferenceId(target)}`;\n}\n\n/** Parse and validate a CRM `odla-ref`; malformed and cross-product refs fail closed. */\nexport function parseCrmDiscussionReference(\n input: URL | string,\n): CrmDiscussionReferenceTarget | null {\n let raw: string | null;\n try {\n raw = input instanceof URL\n ? input.searchParams.get(\"odla-ref\")\n : new URL(input, \"https://crm.invalid\").searchParams.get(\"odla-ref\");\n } catch {\n return null;\n }\n if (!raw) return null;\n const [kind, type, recordId, activityId, extra] = raw.split(\"/\");\n if (\n extra !== undefined ||\n !CRM_DISCUSSION_REFERENCE_KINDS.includes(\n kind as CrmDiscussionReferenceKind,\n ) ||\n !type ||\n !recordId ||\n !SEGMENT.test(type) ||\n !SEGMENT.test(recordId)\n ) return null;\n if (kind === \"crm:record\") {\n return activityId === undefined\n ? { kind, type, recordId }\n : null;\n }\n return activityId && SEGMENT.test(activityId)\n ? { kind: \"crm:activity\", type, recordId, activityId }\n : null;\n}\n\n/** Build a Chapter-compatible CRM deep link and retain the exact ref for focus. */\nexport function crmDiscussionReferenceHref(\n current: URL,\n target: CrmDiscussionReferenceTarget,\n basePath = \"/admin/\",\n): string {\n const next = new URL(current.origin);\n next.pathname = basePath.startsWith(\"/\") ? basePath : `/${basePath}`;\n next.searchParams.set(\"odla-ref\", formatCrmDiscussionReference(target));\n next.hash = [\n \"people\",\n target.type,\n target.recordId,\n target.kind === \"crm:activity\" ? \"notes\" : \"profile\",\n ].map(encodeURIComponent).join(\"/\");\n return next.toString();\n}\n","// The dependency bundle every op takes. `now`/`newId` are injectable so\n// tests can pin time and ids and assert exact written attrs.\nimport type { Crm } from \"./config\";\nimport type { CrmDb } from \"./types\";\n\n/** What every op needs: the resolved config, the injected db, test overrides. */\nexport interface CrmDeps {\n crm: Crm;\n db: CrmDb;\n /** Clock override (default `Date.now`). */\n now?: () => number;\n /** Id/token factory override (default `crypto.randomUUID`). */\n newId?: () => string;\n}\n\n/** {@link CrmDeps} with the injectable defaults filled in. */\nexport interface ResolvedDeps {\n crm: Crm;\n db: CrmDb;\n now: () => number;\n newId: () => string;\n}\n\n/** Fill the injectable defaults. */\nexport function resolveDeps(deps: CrmDeps): ResolvedDeps {\n return {\n crm: deps.crm,\n db: deps.db,\n now: deps.now ?? Date.now,\n newId: deps.newId ?? (() => crypto.randomUUID()),\n };\n}\n","// Compiles list/view filters into odla-db QueryOpts under its real limits:\n// FTS `search` + recursive `where` + ORDER ON EXACTLY ONE INDEXED FIELD +\n// limit/offset. Sortable fields are the promoted columns plus the type's\n// slotted custom fields; tag filtering is a two-step id intersection the\n// records op performs before calling this.\nimport { DEFAULT_LIMIT, MAX_LIMIT, SORTABLE_COLUMNS, type CrmSlot } from \"./constants\";\nimport type { Crm } from \"./config\";\nimport { CrmInputError } from \"./errors\";\nimport type { CrmScalar } from \"./types\";\n\n/** Comparison filter for one slotted custom field. */\nexport interface FieldFilter {\n eq?: CrmScalar;\n in?: CrmScalar[];\n gte?: number | string;\n lte?: number | string;\n}\n\n/** The serializable filter set (also the saved-view `filters` payload). */\nexport interface ViewFilters {\n search?: string;\n stage?: string[];\n emailStatus?: string[];\n billingStatus?: string[];\n ownerId?: string;\n /** Exact tag — resolved to record ids first (join rows). */\n tag?: string;\n /** Include archived records (default: live only). */\n archived?: boolean;\n /** Slotted-field predicates, keyed by config field name. */\n fields?: Record<string, FieldFilter>;\n}\n\n/** One-field sort (odla-db orders on exactly one indexed field). */\nexport interface CrmSort {\n field: string;\n dir: \"asc\" | \"desc\";\n}\n\n/** Everything a list window can ask for: filters + sort + paging. */\nexport interface CrmListParams extends ViewFilters {\n type: string;\n sort?: CrmSort;\n limit?: number;\n offset?: number;\n}\n\ntype Where = Record<string, unknown>;\n\n/** Resolve a sort field to its physical indexed column: a promoted column\n * name as-is, or a slotted config field via the type's slot claim. Throws\n * {@link CrmInputError} for anything else (odla-db cannot order on it). */\nexport function resolveSortColumn(crm: Crm, type: string, field: string): string {\n if ((SORTABLE_COLUMNS as readonly string[]).includes(field)) return field;\n const slot = crm.type(type).fields[field]?.slot;\n if (slot) return slot;\n throw new CrmInputError(\n `cannot sort by \"${field}\" — not a promoted column or a slotted field of ${type}`,\n );\n}\n\nfunction slotFor(crm: Crm, type: string, field: string): CrmSlot {\n const slot = crm.type(type).fields[field]?.slot;\n if (!slot) throw new CrmInputError(`cannot filter by \"${field}\" — not a slotted field of ${type}`);\n return slot;\n}\n\nfunction inOrEq(values: string[]): unknown {\n return values.length === 1 ? values[0] : { $in: values };\n}\n\n/** The compiled odla-db query options for one list window. */\nexport interface CompiledList {\n opts: {\n where: { and: Where[] };\n order: Record<string, \"asc\" | \"desc\">;\n limit: number;\n offset: number;\n search?: string;\n };\n limit: number;\n offset: number;\n}\n\n/**\n * Compile list params into `QueryOpts` for `crm_record`. `tagRecordIds`\n * (when the caller pre-resolved a tag filter) narrows via `id $in`; an empty\n * id list is the caller's short-circuit — don't compile, the result is [].\n */\nexport function compileList(crm: Crm, params: CrmListParams, tagRecordIds?: string[]): CompiledList {\n crm.type(params.type); // throws for unknown types\n const and: Where[] = [{ type: params.type }, { archived: params.archived ?? false }];\n if (params.stage?.length) and.push({ stage: inOrEq(params.stage) });\n if (params.emailStatus?.length) and.push({ emailStatus: inOrEq(params.emailStatus) });\n if (params.billingStatus?.length) and.push({ billingStatus: inOrEq(params.billingStatus) });\n if (params.ownerId) and.push({ ownerId: params.ownerId });\n if (tagRecordIds) and.push({ id: { $in: tagRecordIds } });\n for (const [field, filter] of Object.entries(params.fields ?? {})) {\n if (filter == null) continue; // tolerate sparse JSON payloads\n const slot = slotFor(crm, params.type, field);\n if (filter.eq !== undefined) and.push({ [slot]: filter.eq });\n if (filter.in !== undefined) and.push({ [slot]: { $in: filter.in } });\n if (filter.gte !== undefined) and.push({ [slot]: { $gte: filter.gte } });\n if (filter.lte !== undefined) and.push({ [slot]: { $lte: filter.lte } });\n }\n\n const sort = params.sort ?? { field: \"createdAt\", dir: \"desc\" as const };\n if (sort.dir !== \"asc\" && sort.dir !== \"desc\") throw new CrmInputError(\"sort.dir must be asc|desc\");\n const column = resolveSortColumn(crm, params.type, sort.field);\n\n const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n const offset = Math.max(params.offset ?? 0, 0);\n const search = params.search?.trim();\n return {\n opts: {\n where: { and },\n order: { [column]: sort.dir },\n limit,\n offset,\n ...(search ? { search } : {}),\n },\n limit,\n offset,\n };\n}\n","// Manual ordering as fractional numeric ranks: inserting between neighbors\n// writes their midpoint, so a reorder is one single-field write and lists\n// sort by `rank` under odla-db's one-field `order`. (LexoRank-style string\n// ranks were rejected: numbers sort natively and the midpoint is ~20 lines;\n// both schemes need an occasional rebalance anyway.)\nimport { CrmInputError } from \"./errors\";\n\n/** Spacing between ranks after a rebalance (and the first record's rank). */\nexport const RANK_STEP = 1024;\n\n/** Below this gap between neighbors, float64 midpoints are getting close to\n * exhaustion (each insert halves the gap; 2^-20 leaves ~30 more halvings). */\nexport const RANK_EPSILON = 2 ** -20;\n\n/**\n * The rank to write for a record placed between `before` and `after`\n * (either may be absent at the list edges; both absent = first record).\n * `before` is the neighbor that sorts earlier (smaller rank).\n */\nexport function rankBetween(before?: number, after?: number): number {\n if (before == null && after == null) return RANK_STEP;\n if (before == null) return (after as number) - RANK_STEP;\n if (after == null) return before + RANK_STEP;\n if (after <= before)\n throw new CrmInputError(`rankBetween: after (${after}) must exceed before (${before})`);\n return before + (after - before) / 2;\n}\n\n/** True when two neighbors have converged so far that midpoint inserts\n * between them are about to stop producing distinct ranks. */\nexport function needsRebalance(before: number, after: number): boolean {\n return after - before < RANK_EPSILON;\n}\n\n/**\n * Fresh evenly-spaced ranks for records in their current display order.\n * Returns one `{ id, rank }` per input, `RANK_STEP` apart starting at\n * `RANK_STEP` — apply as a batch update.\n */\nexport function rebalancePlan(orderedIds: readonly string[]): Array<{ id: string; rank: number }> {\n return orderedIds.map((id, i) => ({ id, rank: (i + 1) * RANK_STEP }));\n}\n","// Contact-channel consent as a table-driven pure state machine. The rules\n// encode who may move a channel where: suppression is sticky (admin-only\n// exit), an unsubscribe can only be undone by the CONTACT's own opt-in\n// (never an admin bulk action), and hard bounces land from any non-\n// suppressed state.\nimport type { ConsentState } from \"./constants\";\n\n/** Everything that can change a channel's consent. `unsubscribe.token` is\n * the emailed link, `unsubscribe.oneclick` the RFC 8058 POST; `contact.optin`\n * is an action by the contact themself (form, reply, re-confirmation). */\nexport type ConsentEvent =\n | \"unsubscribe.token\"\n | \"unsubscribe.oneclick\"\n | \"bounce.hard\"\n | \"admin.suppress\"\n | \"admin.resubscribe\"\n | \"contact.optin\";\n\n/** The machine's answer: the next state, or why the move is invalid. */\nexport type ConsentOutcome = { state: ConsentState } | { error: string };\n\n// state → event → next state; missing = invalid (returns an error).\nconst TABLE: Record<ConsentState, Partial<Record<ConsentEvent, ConsentState>>> = {\n subscribed: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\",\n \"contact.optin\": \"subscribed\",\n },\n unsubscribed: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"contact.optin\": \"subscribed\",\n // no admin.resubscribe: undoing an unsubscribe needs the contact's opt-in\n },\n bounced: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\", // admin says the address was fixed\n \"contact.optin\": \"subscribed\",\n },\n suppressed: {\n // sticky: everything except an explicit admin release keeps suppression\n \"unsubscribe.token\": \"suppressed\",\n \"unsubscribe.oneclick\": \"suppressed\",\n \"bounce.hard\": \"suppressed\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\",\n \"contact.optin\": \"suppressed\",\n },\n};\n\n/**\n * Apply one consent event to a channel's current state. Returns the next\n * state, or an error for the one invalid move (admin-resubscribing an\n * unsubscribed contact). Idempotent by construction: repeating an event\n * never changes the outcome.\n */\nexport function applyConsentEvent(current: ConsentState, event: ConsentEvent): ConsentOutcome {\n const next = TABLE[current]?.[event];\n if (next === undefined)\n return { error: `cannot ${event} a ${current} channel — requires the contact's own opt-in` };\n return { state: next };\n}\n\n/** May this channel receive a send of the given class right now?\n * `suppressed`/`bounced` block everything; `unsubscribed` blocks marketing\n * only (transactional lifecycle mail still delivers). */\nexport function canEmail(consent: ConsentState, cls: \"transactional\" | \"marketing\"): boolean {\n if (consent === \"suppressed\" || consent === \"bounced\") return false;\n if (consent === \"unsubscribed\") return cls === \"transactional\";\n return true;\n}\n","// Contact-channel plumbing: natural-key upserts for email channels, the\n// consent flips, and the fold of the primary channel's consent onto the\n// record's denormalized `emailStatus` (what list views filter on).\nimport { CRM_NS, type ConsentState, type EmailStatus } from \"./constants\";\nimport { applyConsentEvent, type ConsentEvent } from \"./consent\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport type { CrmContactChannel, CrmOp, CrmRow } from \"./types\";\n\n/** The natural key of a contact channel row. */\nexport const channelKey = (recordId: string, kind: string, value: string): string =>\n `${recordId}:${kind}:${value}`;\n\n/** A record's `emailStatus` is its primary channel's consent, with\n * \"subscribed\" reading as \"ok\" and no channel at all as \"none\". */\nexport function foldEmailStatus(consent: ConsentState | null): EmailStatus {\n return consent === null ? \"none\" : consent === \"subscribed\" ? \"ok\" : consent;\n}\n\nexport function rowToChannel(row: CrmRow): CrmContactChannel {\n return row as unknown as CrmContactChannel;\n}\n\n/** All channels of a record (a handful of rows — no paging). */\nexport async function listChannels(deps: CrmDeps, recordId: string): Promise<CrmContactChannel[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.channel]: { $: { where: { recordId }, order: { createdAt: \"asc\" }, limit: 100 } },\n });\n return (result[CRM_NS.channel] ?? []).map(rowToChannel);\n}\n\n/**\n * Ops that make `email` the record's primary email channel: upsert by\n * natural key (an address the record had before keeps its consent history),\n * demote any other primary, or — with `email: null` — just demote. Returns\n * the ops plus the `emailStatus` the record should fold to.\n */\nexport function emailChannelOps(\n deps: CrmDeps,\n recordId: string,\n email: string | null,\n existing: readonly CrmContactChannel[],\n): { ops: CrmOp[]; emailStatus: EmailStatus } {\n const { now, newId } = resolveDeps(deps);\n const ops: CrmOp[] = [];\n const current = existing.filter((c) => c.kind === \"email\" && c.isPrimary);\n const match = email ? existing.find((c) => c.kind === \"email\" && c.value === email) : undefined;\n for (const old of current)\n if (old !== match) ops.push({ t: \"update\", ns: CRM_NS.channel, id: old.id, attrs: { isPrimary: false } });\n if (email === null) return { ops, emailStatus: \"none\" };\n if (match) {\n if (!match.isPrimary)\n ops.push({ t: \"update\", ns: CRM_NS.channel, id: match.id, attrs: { isPrimary: true } });\n return { ops, emailStatus: foldEmailStatus(match.consent) };\n }\n const key = channelKey(recordId, \"email\", email);\n ops.push({\n t: \"update\",\n ns: CRM_NS.channel,\n id: { ns: CRM_NS.channel, attr: \"key\", value: key },\n attrs: {\n key,\n recordId,\n kind: \"email\",\n value: email,\n isPrimary: true,\n consent: \"subscribed\",\n consentAt: now(),\n consentSource: \"record-write\",\n unsubscribeToken: newId(),\n createdAt: now(),\n },\n });\n return { ops, emailStatus: \"ok\" };\n}\n\n/**\n * Apply one consent event to the channel holding `token` (unsubscribe links)\n * or to `channelId` (admin actions). Writes the channel's new consent and,\n * when it is the record's primary email channel, folds the record's\n * `emailStatus`. Idempotent under `mutationId`.\n */\nexport async function applyConsent(\n deps: CrmDeps,\n opts: { token?: string; channelId?: string; event: ConsentEvent; mutationId?: string },\n): Promise<{ state: ConsentState; recordId: string; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const where = opts.token\n ? { unsubscribeToken: opts.token }\n : opts.channelId\n ? { id: opts.channelId }\n : null;\n if (!where) throw new CrmInputError(\"token or channelId required\");\n const result = await db.query({ [CRM_NS.channel]: { $: { where, limit: 1 } } });\n const row = (result[CRM_NS.channel] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"contact channel\");\n const channel = rowToChannel(row);\n const outcome = applyConsentEvent(channel.consent, opts.event);\n if (\"error\" in outcome) throw new CrmInputError(outcome.error);\n const ops: CrmOp[] = [\n {\n t: \"update\",\n ns: CRM_NS.channel,\n id: channel.id,\n attrs: { consent: outcome.state, consentAt: now(), consentSource: opts.event },\n },\n ];\n if (channel.isPrimary && channel.kind === \"email\")\n ops.push({\n t: \"update\",\n ns: CRM_NS.record,\n id: channel.recordId,\n attrs: { emailStatus: foldEmailStatus(outcome.state), updatedAt: now() },\n });\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { state: outcome.state, recordId: channel.recordId, duplicate };\n}\n","// Turning a \"patch\" (a plain field→value map) into odla-db ops. odla-db has no\n// storable scalar null — a typed column is either written with a value or its\n// triple is retracted — so `null` in a patch means CLEAR and becomes a\n// `retract`, a non-null value becomes an `update`, and `undefined` is dropped\n// (leave the stored value untouched). This is the single choke-point that keeps\n// the crm from ever sending null to a typed scalar column.\nimport type { CrmAttrs, CrmEntityRef, CrmOp } from \"./types\";\n\n/**\n * Build the ops that apply `patch` to one entity: non-null keys collect into an\n * `update`, explicit-`null` keys (plus any `alsoClear` columns the caller\n * already knows to retract, e.g. a validator's emptied slots) into a `retract`.\n * `undefined` values are dropped. Emits the `update` first, then the `retract`;\n * either is omitted when it would carry nothing.\n */\nexport function patchOps(\n ns: string,\n id: CrmEntityRef,\n patch: Record<string, unknown>,\n alsoClear: string[] = [],\n): CrmOp[] {\n const attrs: CrmAttrs = {};\n const retract = [...alsoClear];\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) retract.push(key);\n else if (value !== undefined) attrs[key] = value;\n }\n const ops: CrmOp[] = [];\n if (Object.keys(attrs).length > 0) ops.push({ t: \"update\", ns, id, attrs });\n if (retract.length > 0) ops.push({ t: \"retract\", ns, id, attrs: retract });\n return ops;\n}\n\n/**\n * Apply a null-means-clear `patch` to `base` in memory, mirroring what\n * {@link patchOps} commits: set non-null values, drop `null` / `alsoClear`\n * keys, ignore `undefined`. Used to build the row a write returns to its caller\n * so the returned shape matches what was stored.\n */\nexport function applyPatch<T extends object>(\n base: T,\n patch: Record<string, unknown>,\n alsoClear: string[] = [],\n): T {\n const out = { ...base } as Record<string, unknown>;\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete out[key];\n else if (value !== undefined) out[key] = value;\n }\n for (const key of alsoClear) delete out[key];\n return out as T;\n}\n","// Record CRUD over the injected db: create/update run through `prepare`\n// (validation + slot mirror + searchText), keep the primary email channel in\n// sync, and recompute the score when the type declares a scorer. Every write\n// takes an optional mutationId for exactly-once application.\nimport { CRM_NS } from \"./constants\";\nimport { emailChannelOps, listChannels } from \"./channels\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { compileList, type CrmListParams } from \"./query\";\nimport { applyPatch, patchOps } from \"./write-ops\";\nimport type { CrmAttrs, CrmOp, CrmRecord, CrmRow } from \"./types\";\n\n/** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */\nexport function rowToRecord(row: CrmRow): CrmRecord {\n const record = row as unknown as CrmRecord;\n return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? \"\" };\n}\n\n/** Load one record by id, or null. */\nexport async function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.record]: { $: { where: { id }, limit: 1 } } });\n const row = (result[CRM_NS.record] ?? [])[0];\n return row ? rowToRecord(row) : null;\n}\n\n/** Load one record by id; {@link CrmNotFoundError} (404) when missing. */\nexport async function mustGetRecord(deps: CrmDeps, id: string): Promise<CrmRecord> {\n const record = await getRecord(deps, id);\n if (!record) throw new CrmNotFoundError(\"record\");\n return record;\n}\n\n/** One list window + the total matching count (for pagination). A `tag`\n * filter resolves to record ids first (join rows, capped at 1000). */\nexport async function listRecords(\n deps: CrmDeps,\n params: CrmListParams,\n): Promise<{ records: CrmRecord[]; total: number; limit: number; offset: number }> {\n const { crm, db } = resolveDeps(deps);\n let tagRecordIds: string[] | undefined;\n if (params.tag) {\n const tag = params.tag.trim().toLowerCase();\n const tagResult = await db.query({ [CRM_NS.tag]: { $: { where: { tag }, limit: 1000 } } });\n tagRecordIds = (tagResult[CRM_NS.tag] ?? []).map((row) => row[\"recordId\"] as string);\n if (tagRecordIds.length === 0)\n return { records: [], total: 0, limit: params.limit ?? 0, offset: params.offset ?? 0 };\n }\n const { opts, limit, offset } = compileList(crm, params, tagRecordIds);\n const [result, agg] = await Promise.all([\n db.query({ [CRM_NS.record]: { $: opts } }),\n db.aggregate(\n CRM_NS.record,\n { count: true },\n opts.search ? { where: opts.where, search: opts.search } : { where: opts.where },\n ),\n ]);\n return {\n records: (result[CRM_NS.record] ?? []).map(rowToRecord),\n total: agg.count ?? 0,\n limit,\n offset,\n };\n}\n\nfunction scoreOf(deps: CrmDeps, type: string, candidate: CrmRecord): number | undefined {\n const def = resolveDeps(deps).crm.type(type);\n const wantsScore = def.facets?.rank === \"score\" || def.facets?.rank === \"both\";\n if (!wantsScore || !def.scorer) return undefined;\n return def.scorer(candidate);\n}\n\n/** Create a record of `type` from custom-field input. Also creates (or\n * upserts) the primary email contact channel when the type declares an\n * `emailField`. New records rank at `now` so manual order defaults to\n * creation order. */\nexport async function createRecord(\n deps: CrmDeps,\n opts: { type: string; input: Record<string, unknown>; ownerId?: string; stage?: string; mutationId?: string },\n): Promise<{ id: string; duplicate: boolean; record: CrmRecord }> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const prepared = crm.prepare(opts.type, opts.input);\n if (!prepared.ok) throw new CrmInputError(\"invalid input\", prepared.errors);\n const id = newId();\n const at = now();\n const stage = opts.stage ?? crm.initialStage(opts.type);\n const attrs: CrmAttrs = {\n id, // mirror the entity id as an attr so `where: { id }` reads can find it\n type: opts.type,\n ...prepared.attrs,\n archived: false,\n rank: at,\n createdAt: at,\n updatedAt: at,\n };\n if (opts.ownerId != null) attrs.ownerId = opts.ownerId;\n if (stage != null) {\n attrs.stage = stage;\n attrs.stageIndex = crm.stageIndex(opts.type, stage); // throws on unknown stage\n attrs.stageChangedAt = at;\n }\n const ops: CrmOp[] = [];\n const email = (prepared.attrs[\"primaryEmail\"] as string | null | undefined) ?? null;\n if (crm.type(opts.type).emailField) {\n const channel = emailChannelOps(deps, id, email, []);\n attrs.emailStatus = channel.emailStatus;\n ops.push(...channel.ops);\n } else {\n attrs.emailStatus = \"none\";\n }\n const candidate = { id, ...attrs } as unknown as CrmRecord;\n const score = scoreOf(deps, opts.type, candidate);\n if (score !== undefined) attrs.score = score;\n ops.unshift({ t: \"update\", ns: CRM_NS.record, id, attrs });\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { id, duplicate, record: { id, ...attrs } as unknown as CrmRecord };\n}\n\n/** Partial update of custom fields (+ owner). A changed `emailField` value\n * repoints the primary channel — the old address keeps its consent history,\n * a returning address keeps its earlier consent. */\nexport async function updateRecord(\n deps: CrmDeps,\n opts: { id: string; input: Record<string, unknown>; ownerId?: string | null; mutationId?: string },\n): Promise<{ record: CrmRecord; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const existing = await mustGetRecord(deps, opts.id);\n const prepared = crm.prepare(existing.type, opts.input, existing);\n if (!prepared.ok) throw new CrmInputError(\"invalid input\", prepared.errors);\n // `ownerId: undefined` leaves the owner untouched; `null` clears it (retract).\n const patch: Record<string, unknown> = { ...prepared.attrs, updatedAt: now(), ownerId: opts.ownerId };\n const channelOps: CrmOp[] = [];\n if (crm.type(existing.type).emailField) {\n const nextEmail = (prepared.attrs[\"primaryEmail\"] as string | null | undefined) ?? null;\n if (nextEmail !== (existing.primaryEmail ?? null)) {\n const channels = await listChannels(deps, existing.id);\n const channel = emailChannelOps(deps, existing.id, nextEmail, channels);\n patch.emailStatus = channel.emailStatus;\n channelOps.push(...channel.ops);\n }\n }\n const candidate = { ...existing, ...prepared.attrs } as CrmRecord;\n const score = scoreOf(deps, existing.type, candidate);\n if (score !== undefined) patch.score = score;\n const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { record: applyPatch(existing, patch, prepared.retract), duplicate };\n}\n\n/** Archive (soft-delete) or restore. Archived records drop out of default\n * list windows but keep every tag/activity/channel row. */\nexport async function setArchived(\n deps: CrmDeps,\n opts: { id: string; archived: boolean; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.id);\n const at = now();\n // Restore clears `archivedAt` (null → retract; a typed date can't be nulled).\n const patch: Record<string, unknown> = opts.archived\n ? { archived: true, archivedAt: at, updatedAt: at }\n : { archived: false, archivedAt: null, updatedAt: at };\n const { duplicate } = await db.transact(\n patchOps(CRM_NS.record, opts.id, patch),\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n","// Stage transitions (gate-checked, audited) and manual reordering\n// (fractional ranks). Both are single-record writes; the stage move also\n// appends a `stage_change` activity so the pipeline history is queryable.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { needsRebalance, rankBetween, rebalancePlan } from \"./rank\";\nimport { mustGetRecord, rowToRecord } from \"./records\";\nimport type { CrmOp, CrmRecord } from \"./types\";\n\n/**\n * Move a record to stage `to`. Refused (400-style {@link CrmInputError})\n * when the pipeline's transitions/gates say no. Appends the audit activity\n * in the same tx; returns the type's `onTransition` hook for the caller to\n * fire AFTER commit (post-commit side effects like a Clerk role promotion\n * never hold the write hostage).\n */\nexport async function setStage(\n deps: CrmDeps,\n opts: { id: string; to: string; authorId: string; mutationId?: string },\n): Promise<{\n record: CrmRecord;\n from: string | null;\n duplicate: boolean;\n hook?: (record: CrmRecord) => void | Promise<void>;\n}> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.id);\n const blocked = crm.canTransition(record.type, record, opts.to);\n if (blocked) throw new CrmInputError(blocked);\n const at = now();\n const attrs = {\n stage: opts.to,\n stageIndex: crm.stageIndex(record.type, opts.to),\n stageChangedAt: at,\n updatedAt: at,\n };\n const activityId = newId();\n const ops: CrmOp[] = [\n { t: \"update\", ns: CRM_NS.record, id: record.id, attrs },\n {\n t: \"update\",\n ns: CRM_NS.activity,\n id: activityId,\n attrs: {\n id: activityId, // mirror the entity id so the activity is readable by id\n recordId: record.id,\n kind: \"stage_change\",\n body: `${record.stage ?? \"(none)\"} → ${opts.to}`,\n authorId: opts.authorId,\n createdAt: at,\n },\n },\n ];\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n const updated = { ...record, ...attrs } as CrmRecord;\n return {\n record: updated,\n from: record.stage ?? null,\n duplicate,\n hook: crm.type(record.type).onTransition?.[opts.to],\n };\n}\n\n/**\n * Place a record between two neighbors (either end open). Neighbors must be\n * same-type records that already carry ranks; reports `rebalanceNeeded`\n * when the gap between them has nearly collapsed.\n */\nexport async function setRank(\n deps: CrmDeps,\n opts: { id: string; beforeId?: string; afterId?: string; mutationId?: string },\n): Promise<{ rank: number; rebalanceNeeded: boolean; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.id);\n const neighborIds = [opts.beforeId, opts.afterId].filter((v): v is string => v != null);\n const neighbors = new Map<string, CrmRecord>();\n if (neighborIds.length > 0) {\n const result = await db.query({\n [CRM_NS.record]: { $: { where: { id: { $in: neighborIds } }, limit: 2 } },\n });\n for (const row of result[CRM_NS.record] ?? []) {\n const neighbor = rowToRecord(row);\n if (neighbor.type !== record.type)\n throw new CrmInputError(\"neighbors must be records of the same type\");\n neighbors.set(neighbor.id, neighbor);\n }\n }\n const rankOf = (id?: string): number | undefined => {\n if (id == null) return undefined;\n const neighbor = neighbors.get(id);\n if (!neighbor) throw new CrmInputError(`neighbor ${id} not found`);\n if (neighbor.rank == null)\n throw new CrmInputError(`neighbor ${id} has no rank — run a rebalance first`);\n return neighbor.rank;\n };\n const before = rankOf(opts.beforeId);\n const after = rankOf(opts.afterId);\n const rank = rankBetween(before, after);\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: CRM_NS.record, id: record.id, attrs: { rank, updatedAt: now() } }],\n { mutationId: opts.mutationId },\n );\n return {\n rank,\n rebalanceNeeded: before != null && after != null && needsRebalance(before, after),\n duplicate,\n };\n}\n\n/** Rewrite a type's live records to evenly-spaced ranks in their current\n * rank order (first 1000 — beyond that, rebalance in windows). */\nexport async function rebalanceRanks(\n deps: CrmDeps,\n opts: { type: string; mutationId?: string },\n): Promise<{ count: number; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n crm.type(opts.type); // throws for unknown types\n const result = await db.query({\n [CRM_NS.record]: {\n $: {\n where: { and: [{ type: opts.type }, { archived: false }] },\n order: { rank: \"asc\" },\n limit: 1000,\n },\n },\n });\n const ids = (result[CRM_NS.record] ?? []).map((row) => row.id);\n const at = now();\n const ops: CrmOp[] = rebalancePlan(ids).map(({ id, rank }) => ({\n t: \"update\",\n ns: CRM_NS.record,\n id,\n attrs: { rank, updatedAt: at },\n }));\n if (ops.length === 0) return { count: 0, duplicate: false };\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { count: ops.length, duplicate };\n}\n","// Tags and record↔record links as natural-key join rows: upserts are\n// idempotent by key, removal is a lookup delete, and both double as\n// provenance (tag rows timestamp when a record entered a cohort).\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { mustGetRecord, rowToRecord } from \"./records\";\nimport type { CrmLink, CrmTag } from \"./types\";\n\n/** Tags are lowercased, trimmed, ≤ 64 chars — exact-match filters, so case\n * variants must collapse to one cohort. */\nexport function normalizeTag(raw: string): string {\n const tag = raw.trim().toLowerCase();\n if (tag.length === 0 || tag.length > 64) throw new CrmInputError(\"tag must be 1–64 characters\");\n return tag;\n}\n\n/** Idempotently tag a record (natural-key upsert). */\nexport async function addTag(\n deps: CrmDeps,\n opts: { recordId: string; tag: string; mutationId?: string },\n): Promise<{ tag: string; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const tag = normalizeTag(opts.tag);\n await mustGetRecord(deps, opts.recordId);\n const key = `${opts.recordId}:${tag}`;\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.tag,\n id: { ns: CRM_NS.tag, attr: \"key\", value: key },\n attrs: { key, recordId: opts.recordId, tag, createdAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { tag, duplicate };\n}\n\n/** Remove a tag by natural key; a no-op when absent. */\nexport async function removeTag(\n deps: CrmDeps,\n opts: { recordId: string; tag: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const tag = normalizeTag(opts.tag);\n const { duplicate } = await db.transact(\n [{ t: \"delete\", ns: CRM_NS.tag, id: { ns: CRM_NS.tag, attr: \"key\", value: `${opts.recordId}:${tag}` } }],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** A record's tags, oldest first. */\nexport async function listTags(deps: CrmDeps, recordId: string): Promise<CrmTag[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.tag]: { $: { where: { recordId }, order: { createdAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.tag] ?? []).map((row) => row as unknown as CrmTag);\n}\n\n/** Create a config-declared relation between two records after checking the\n * endpoints' types match the relation's from/to declaration. */\nexport async function addLink(\n deps: CrmDeps,\n opts: { relation: string; fromId: string; toId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const rel = crm.config.relations?.[opts.relation];\n if (!rel) throw new CrmInputError(`unknown relation \"${opts.relation}\"`);\n if (opts.fromId === opts.toId) throw new CrmInputError(\"cannot link a record to itself\");\n const result = await db.query({\n [CRM_NS.record]: { $: { where: { id: { $in: [opts.fromId, opts.toId] } }, limit: 2 } },\n });\n const byId = new Map((result[CRM_NS.record] ?? []).map((row) => [row.id, rowToRecord(row)]));\n const from = byId.get(opts.fromId);\n const to = byId.get(opts.toId);\n if (!from || !to) throw new CrmInputError(\"both records must exist\");\n if (from.type !== rel.from || to.type !== rel.to)\n throw new CrmInputError(\n `relation \"${opts.relation}\" links ${rel.from} → ${rel.to}, got ${from.type} → ${to.type}`,\n );\n const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.link,\n id: { ns: CRM_NS.link, attr: \"key\", value: key },\n attrs: { key, fromId: opts.fromId, toId: opts.toId, relation: opts.relation, createdAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** Remove a relation by natural key; a no-op when absent. */\nexport async function removeLink(\n deps: CrmDeps,\n opts: { relation: string; fromId: string; toId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;\n const { duplicate } = await db.transact(\n [{ t: \"delete\", ns: CRM_NS.link, id: { ns: CRM_NS.link, attr: \"key\", value: key } }],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** Every link touching a record, either direction. */\nexport async function listLinks(deps: CrmDeps, recordId: string): Promise<CrmLink[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.link]: {\n $: { where: { or: [{ fromId: recordId }, { toId: recordId }] }, order: { createdAt: \"asc\" }, limit: 200 },\n },\n });\n return (result[CRM_NS.link] ?? []).map((row) => row as unknown as CrmLink);\n}\n","// Durable cross-system record identity and delivery state. Tags remain useful\n// user-editable cohorts; these rows are the machine contract and cannot be\n// destroyed by renaming or removing a display tag.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { getRecord, mustGetRecord } from \"./records\";\nimport type { CrmOp, CrmRecord, CrmRecordDelivery, CrmRecordOrigin } from \"./types\";\n\nconst SOURCE_ID = /^[a-z0-9][a-z0-9-]{1,127}$/;\nconst TARGET_ID = SOURCE_ID;\n\nfunction required(value: string, label: string, max = 512): string {\n const normalized = value.trim();\n if (!normalized || normalized.length > max) throw new CrmInputError(`${label} must be 1–${max} characters`);\n return normalized;\n}\n\n/** Stable natural key for an upstream record identity. */\nexport function recordOriginKey(sourceId: string, sourceRecordId: string): string {\n const source = required(sourceId, \"sourceId\", 128);\n const record = required(sourceRecordId, \"sourceRecordId\");\n if (!SOURCE_ID.test(source)) throw new CrmInputError(\"sourceId must be a lowercase app slug\");\n return `${source}:${record}`;\n}\n\n/** Look up a structured origin row by upstream site + record id. */\nexport async function getRecordOrigin(\n deps: CrmDeps,\n sourceId: string,\n sourceRecordId: string,\n): Promise<CrmRecordOrigin | null> {\n const { db } = resolveDeps(deps);\n const key = recordOriginKey(sourceId, sourceRecordId);\n const result = await db.query({ [CRM_NS.origin]: { $: { where: { key }, limit: 1 } } });\n return ((result[CRM_NS.origin] ?? [])[0] as unknown as CrmRecordOrigin | undefined) ?? null;\n}\n\n/** Resolve the local CRM record identified by an upstream origin. */\nexport async function getRecordByOrigin(\n deps: CrmDeps,\n sourceId: string,\n sourceRecordId: string,\n): Promise<CrmRecord | null> {\n const origin = await getRecordOrigin(deps, sourceId, sourceRecordId);\n return origin ? getRecord(deps, origin.recordId) : null;\n}\n\n/** Idempotently bind one upstream record identity to a local CRM record. */\nexport async function upsertRecordOrigin(\n deps: CrmDeps,\n opts: {\n recordId: string;\n sourceId: string;\n sourceRecordId: string;\n sourceUrl?: string;\n payloadVersion: number;\n mutationId?: string;\n },\n): Promise<{ origin: CrmRecordOrigin; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.recordId);\n const key = recordOriginKey(opts.sourceId, opts.sourceRecordId);\n if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {\n throw new CrmInputError(\"payloadVersion must be a positive integer\");\n }\n const sourceUrl = opts.sourceUrl == null ? undefined : required(opts.sourceUrl, \"sourceUrl\", 2048);\n const existing = await getRecordOrigin(deps, opts.sourceId, opts.sourceRecordId);\n if (existing && existing.recordId !== opts.recordId) {\n throw new CrmInputError(\"upstream record is already bound to another local record\");\n }\n const at = now();\n const attrs = {\n key,\n recordId: opts.recordId,\n sourceId: opts.sourceId,\n sourceRecordId: opts.sourceRecordId,\n payloadVersion: opts.payloadVersion,\n firstReceivedAt: existing?.firstReceivedAt ?? at,\n lastReceivedAt: at,\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: CRM_NS.origin, id: { ns: CRM_NS.origin, attr: \"key\", value: key }, attrs }],\n { mutationId: opts.mutationId },\n );\n return {\n duplicate,\n origin: {\n id: existing?.id ?? key,\n ...attrs,\n },\n };\n}\n\n/** List every upstream identity attached to a local record. */\nexport async function listRecordOrigins(deps: CrmDeps, recordId: string): Promise<CrmRecordOrigin[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.origin]: { $: { where: { recordId }, order: { firstReceivedAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.origin] ?? []) as unknown as CrmRecordOrigin[];\n}\n\n/** Stable natural key for one local record → target delivery edge. */\nexport function recordDeliveryKey(recordId: string, targetId: string): string {\n const record = required(recordId, \"recordId\");\n const target = required(targetId, \"targetId\", 128);\n if (!TARGET_ID.test(target)) throw new CrmInputError(\"targetId must be a lowercase app slug\");\n return `${record}:${target}`;\n}\n\n/** Record one success or failure while retaining the latest edge state. */\nexport async function recordDeliveryAttempt(\n deps: CrmDeps,\n opts: {\n recordId: string;\n targetId: string;\n status: \"delivered\" | \"failed\";\n payloadVersion: number;\n remoteRecordId?: string;\n error?: string;\n mutationId?: string;\n },\n): Promise<{ delivery: CrmRecordDelivery; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.recordId);\n const key = recordDeliveryKey(opts.recordId, opts.targetId);\n if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {\n throw new CrmInputError(\"payloadVersion must be a positive integer\");\n }\n const found = await db.query({ [CRM_NS.delivery]: { $: { where: { key }, limit: 1 } } });\n const existing = (found[CRM_NS.delivery] ?? [])[0] as unknown as CrmRecordDelivery | undefined;\n const at = now();\n const remoteRecordId = opts.remoteRecordId == null\n ? existing?.remoteRecordId\n : required(opts.remoteRecordId, \"remoteRecordId\");\n const error = opts.error == null ? undefined : required(opts.error, \"error\", 1000);\n const attrs = {\n key,\n recordId: opts.recordId,\n targetId: opts.targetId,\n status: opts.status,\n attempts: (existing?.attempts ?? 0) + 1,\n payloadVersion: opts.payloadVersion,\n lastAttemptAt: at,\n ...(remoteRecordId ? { remoteRecordId } : {}),\n ...(opts.status === \"delivered\" ? { deliveredAt: at } : existing?.deliveredAt ? { deliveredAt: existing.deliveredAt } : {}),\n ...(error ? { error } : {}),\n };\n const ref = { ns: CRM_NS.delivery, attr: \"key\", value: key } as const;\n const ops: CrmOp[] = [{ t: \"update\", ns: CRM_NS.delivery, id: ref, attrs }];\n if (opts.status === \"delivered\" && existing?.error) {\n ops.push({ t: \"retract\", ns: CRM_NS.delivery, id: ref, attrs: [\"error\"] });\n }\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return {\n duplicate,\n delivery: {\n id: existing?.id ?? key,\n ...attrs,\n },\n };\n}\n\n/** List delivery state for one record, or every edge to one target. */\nexport async function listRecordDeliveries(\n deps: CrmDeps,\n filter: { recordId?: string; targetId?: string },\n): Promise<CrmRecordDelivery[]> {\n if (!filter.recordId && !filter.targetId) throw new CrmInputError(\"recordId or targetId is required\");\n const { db } = resolveDeps(deps);\n const where = {\n ...(filter.recordId ? { recordId: required(filter.recordId, \"recordId\") } : {}),\n ...(filter.targetId ? { targetId: required(filter.targetId, \"targetId\", 128) } : {}),\n };\n const result = await db.query({\n [CRM_NS.delivery]: { $: { where, order: { lastAttemptAt: \"desc\" }, limit: 500 } },\n });\n return (result[CRM_NS.delivery] ?? []) as unknown as CrmRecordDelivery[];\n}\n","// Notes, calls, and follow-up tasks on a record — the TASKS.md replacement.\n// Tasks carry dueAt/status/waitingOn/assigneeId, all indexed, so \"my open\n// follow-ups by due date\" is a single-field-order query.\nimport { ACTIVITY_KINDS, CRM_NS, TASK_STATUSES, type ActivityKind, type TaskStatus } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { mustGetRecord } from \"./records\";\nimport { applyPatch, patchOps } from \"./write-ops\";\nimport type { CrmActivity, CrmAttrs } from \"./types\";\n\nconst rowToActivity = (row: Record<string, unknown>): CrmActivity => row as unknown as CrmActivity;\n\n/** Append a note/call/meeting or open a follow-up task on a record. */\nexport async function addActivity(\n deps: CrmDeps,\n opts: {\n recordId: string;\n kind: ActivityKind;\n body: string;\n authorId: string;\n dueAt?: number;\n assigneeId?: string;\n waitingOn?: string;\n meta?: Record<string, unknown>;\n mutationId?: string;\n },\n): Promise<{ id: string; duplicate: boolean }> {\n const { db, now, newId } = resolveDeps(deps);\n if (!ACTIVITY_KINDS.includes(opts.kind)) throw new CrmInputError(`unknown kind \"${opts.kind}\"`);\n const body = opts.body.trim();\n if (!body) throw new CrmInputError(\"body is required\");\n await mustGetRecord(deps, opts.recordId);\n const id = newId();\n const attrs: CrmAttrs = {\n id, // mirror the entity id so updateTask's `where: { id }` read can find it\n recordId: opts.recordId,\n kind: opts.kind,\n body,\n authorId: opts.authorId,\n createdAt: now(),\n };\n if (opts.kind === \"task\") {\n attrs.status = \"open\";\n if (opts.dueAt != null) attrs.dueAt = opts.dueAt;\n if (opts.assigneeId != null) attrs.assigneeId = opts.assigneeId;\n if (opts.waitingOn != null) attrs.waitingOn = opts.waitingOn;\n }\n if (opts.meta) attrs.meta = opts.meta;\n const { duplicate } = await db.transact([{ t: \"update\", ns: CRM_NS.activity, id, attrs }], {\n mutationId: opts.mutationId,\n });\n return { id, duplicate };\n}\n\n/** Patch a task's lifecycle fields. Moving to `done` stamps `completedAt`;\n * reopening clears it. Only `task` activities accept status changes. */\nexport async function updateTask(\n deps: CrmDeps,\n opts: {\n id: string;\n status?: TaskStatus;\n dueAt?: number | null;\n assigneeId?: string | null;\n waitingOn?: string | null;\n body?: string;\n mutationId?: string;\n },\n): Promise<{ activity: CrmActivity; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.activity]: { $: { where: { id: opts.id }, limit: 1 } } });\n const row = (result[CRM_NS.activity] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"activity\");\n const activity = rowToActivity(row);\n if (activity.kind !== \"task\") throw new CrmInputError(\"only tasks can be updated\");\n // A patch whose `null` values mean CLEAR: reopening a task retracts\n // `completedAt`, and dueAt/assigneeId/waitingOn clear when passed null (a\n // typed scalar can't store null — patchOps turns those into a `retract`).\n const patch: Record<string, unknown> = {};\n if (opts.status !== undefined) {\n if (!TASK_STATUSES.includes(opts.status)) throw new CrmInputError(`unknown status \"${opts.status}\"`);\n patch.status = opts.status;\n patch.completedAt = opts.status === \"done\" ? now() : null;\n }\n if (opts.dueAt !== undefined) patch.dueAt = opts.dueAt;\n if (opts.assigneeId !== undefined) patch.assigneeId = opts.assigneeId;\n if (opts.waitingOn !== undefined) patch.waitingOn = opts.waitingOn;\n if (opts.body !== undefined) {\n const body = opts.body.trim();\n if (!body) throw new CrmInputError(\"body is required\");\n patch.body = body;\n }\n if (Object.keys(patch).length === 0) throw new CrmInputError(\"nothing to update\");\n const { duplicate } = await db.transact(patchOps(CRM_NS.activity, opts.id, patch), {\n mutationId: opts.mutationId,\n });\n return { activity: applyPatch(activity, patch) as CrmActivity, duplicate };\n}\n\n/** A record's activity feed, newest first. */\nexport async function listActivities(\n deps: CrmDeps,\n opts: { recordId: string; kind?: ActivityKind; limit?: number; offset?: number },\n): Promise<CrmActivity[]> {\n const { db } = resolveDeps(deps);\n const where = opts.kind\n ? { and: [{ recordId: opts.recordId }, { kind: opts.kind }] }\n : { recordId: opts.recordId };\n const result = await db.query({\n [CRM_NS.activity]: {\n $: {\n where,\n order: { createdAt: \"desc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return (result[CRM_NS.activity] ?? []).map(rowToActivity);\n}\n\n/** Open follow-ups across records, soonest due first — the \"Waiting on\"\n * board. Defaults to open+waiting; filter to one assignee for \"mine\". */\nexport async function listTasks(\n deps: CrmDeps,\n opts: { assigneeId?: string; status?: TaskStatus[]; dueBefore?: number; limit?: number; offset?: number } = {},\n): Promise<CrmActivity[]> {\n const { db } = resolveDeps(deps);\n const and: Record<string, unknown>[] = [{ kind: \"task\" }];\n const statuses = opts.status ?? [\"open\", \"waiting\"];\n and.push({ status: statuses.length === 1 ? statuses[0] : { $in: statuses } });\n if (opts.assigneeId) and.push({ assigneeId: opts.assigneeId });\n if (opts.dueBefore != null) and.push({ dueAt: { $lte: opts.dueBefore } });\n const result = await db.query({\n [CRM_NS.activity]: {\n $: {\n where: { and },\n order: { dueAt: \"asc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return (result[CRM_NS.activity] ?? []).map(rowToActivity);\n}\n","// Saved views: a named, serializable (filters, sort, columns) triple per\n// type — personal by default, shareable to the team. Specs are validated by\n// DRY-RUNNING the query compiler, so a view that saves is a view that runs.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { compileList, type CrmSort, type ViewFilters } from \"./query\";\nimport type { CrmAttrs, CrmView } from \"./types\";\n\n/** The serializable definition of a saved view. */\nexport interface ViewSpec {\n name: string;\n type: string;\n filters: ViewFilters;\n sort: CrmSort | null;\n columns: string[];\n shared: boolean;\n}\n\nconst rowToView = (row: Record<string, unknown>): CrmView => {\n const view = row as unknown as CrmView;\n return { ...view, filters: view.filters ?? {}, columns: view.columns ?? [] };\n};\n\nfunction checkSpec(deps: CrmDeps, spec: ViewSpec): void {\n const { crm } = resolveDeps(deps);\n if (!spec.name.trim()) throw new CrmInputError(\"view name is required\");\n if (!Array.isArray(spec.columns) || spec.columns.some((c) => typeof c !== \"string\"))\n throw new CrmInputError(\"columns must be a string array\");\n // The one true validator: if the compiler accepts it, the list route will.\n compileList(crm, { type: spec.type, ...spec.filters, sort: spec.sort ?? undefined });\n}\n\n/** Persist a new view after dry-running its spec through the compiler. */\nexport async function saveView(\n deps: CrmDeps,\n opts: { spec: ViewSpec; ownerId: string; mutationId?: string },\n): Promise<{ id: string; duplicate: boolean }> {\n const { db, now, newId } = resolveDeps(deps);\n checkSpec(deps, opts.spec);\n const id = newId();\n const at = now();\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.view,\n id,\n attrs: {\n id, // mirror the entity id so getView/updateView can read one by id\n name: opts.spec.name.trim(),\n type: opts.spec.type,\n ownerId: opts.ownerId,\n shared: opts.spec.shared,\n filters: opts.spec.filters,\n sort: opts.spec.sort,\n columns: opts.spec.columns,\n createdAt: at,\n updatedAt: at,\n },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { id, duplicate };\n}\n\nasync function mustGetView(deps: CrmDeps, id: string): Promise<CrmView> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.view]: { $: { where: { id }, limit: 1 } } });\n const row = (result[CRM_NS.view] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"view\");\n return rowToView(row);\n}\n\n/** Update a view you own (shared views are editable by their owner only —\n * the route layer passes the acting admin as `ownerId`). */\nexport async function updateView(\n deps: CrmDeps,\n opts: { id: string; spec: Partial<ViewSpec>; ownerId: string; mutationId?: string },\n): Promise<{ view: CrmView; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const existing = await mustGetView(deps, opts.id);\n if (existing.ownerId && existing.ownerId !== opts.ownerId)\n throw new CrmInputError(\"only the view's owner may change it\");\n const merged: ViewSpec = {\n name: opts.spec.name ?? existing.name,\n type: opts.spec.type ?? existing.type,\n filters: opts.spec.filters ?? (existing.filters as ViewFilters),\n sort: opts.spec.sort !== undefined ? opts.spec.sort : existing.sort,\n columns: opts.spec.columns ?? existing.columns,\n shared: opts.spec.shared ?? existing.shared,\n };\n checkSpec(deps, merged);\n const attrs: CrmAttrs = {\n name: merged.name.trim(),\n type: merged.type,\n shared: merged.shared,\n filters: merged.filters,\n sort: merged.sort,\n columns: merged.columns,\n updatedAt: now(),\n };\n const { duplicate } = await db.transact([{ t: \"update\", ns: CRM_NS.view, id: opts.id, attrs }], {\n mutationId: opts.mutationId,\n });\n return { view: { ...existing, ...attrs } as CrmView, duplicate };\n}\n\n/** Delete a view you own. */\nexport async function deleteView(\n deps: CrmDeps,\n opts: { id: string; ownerId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const existing = await mustGetView(deps, opts.id);\n if (existing.ownerId && existing.ownerId !== opts.ownerId)\n throw new CrmInputError(\"only the view's owner may delete it\");\n const { duplicate } = await db.transact([{ t: \"delete\", ns: CRM_NS.view, id: opts.id }], {\n mutationId: opts.mutationId,\n });\n return { duplicate };\n}\n\n/** Views visible to a viewer: everything shared plus their own, optionally\n * narrowed to one record type. */\nexport async function listViews(\n deps: CrmDeps,\n opts: { viewerId: string; type?: string },\n): Promise<CrmView[]> {\n const { db } = resolveDeps(deps);\n const visible = { or: [{ shared: true }, { ownerId: opts.viewerId }] };\n const where = opts.type ? { and: [{ type: opts.type }, visible] } : visible;\n const result = await db.query({\n [CRM_NS.view]: { $: { where, order: { createdAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.view] ?? []).map(rowToView);\n}\n","// The runtime-editable side of CRM configuration: one `crm_config` row\n// holding destination addresses and the owner-editable template COPY.\n// Template CONTRACTS (vars, consent class) stay in code (`defineCrm`).\nimport { CONFIG_KEY, CRM_NS } from \"./constants\";\nimport type { Crm } from \"./config\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { lintTemplate } from \"./template\";\nimport { patchOps } from \"./write-ops\";\nimport type { CrmConfigRow, StoredTemplate } from \"./types\";\n\n/** Seed copy for every declared template: the spec's defaults, enabled; a\n * spec without defaults seeds empty and DISABLED (nothing sends until the\n * owner writes copy). */\nexport function defaultTemplates(crm: Crm): Record<string, StoredTemplate> {\n const out: Record<string, StoredTemplate> = {};\n for (const [id, spec] of Object.entries(crm.config.templates ?? {})) {\n out[id] = spec.defaults\n ? { subject: spec.defaults.subject, text: spec.defaults.text, enabled: true }\n : { subject: \"\", text: \"\", enabled: false };\n }\n return out;\n}\n\nconst rowToConfig = (row: Record<string, unknown>): CrmConfigRow => {\n const config = row as unknown as CrmConfigRow;\n return { ...config, emailTemplates: config.emailTemplates ?? {}, settings: config.settings ?? {} };\n};\n\n/** Read the crm_config singleton, or null before the first save. */\nexport async function getConfig(deps: CrmDeps): Promise<CrmConfigRow | null> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.config]: { $: { where: { key: CONFIG_KEY }, limit: 1 } } });\n const row = (result[CRM_NS.config] ?? [])[0];\n return row ? rowToConfig(row) : null;\n}\n\n/** Partial config update; explicit null clears an address. */\nexport interface ConfigPatch {\n notificationEmail?: string | null;\n replyTo?: string | null;\n debugEmail?: string | null;\n emailTemplates?: Record<string, Partial<StoredTemplate>>;\n settings?: Record<string, unknown>;\n}\n\n/**\n * Upsert the singleton config row (natural key, idempotent). Template edits\n * are validated against the code-declared registry — an id `defineCrm`\n * never declared is refused, so data rows can't invent send paths. First\n * write seeds every declared template's default copy.\n */\nexport async function saveConfig(\n deps: CrmDeps,\n patch: ConfigPatch,\n opts: { mutationId?: string } = {},\n): Promise<{ config: CrmConfigRow; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const declared = crm.config.templates ?? {};\n for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {\n if (!declared[id]) throw new CrmInputError(`unknown template \"${id}\"`);\n if (tpl.subject !== undefined && typeof tpl.subject !== \"string\")\n throw new CrmInputError(`template \"${id}\": subject must be a string`);\n if (tpl.text !== undefined && typeof tpl.text !== \"string\")\n throw new CrmInputError(`template \"${id}\": text must be a string`);\n if (tpl.enabled !== undefined && typeof tpl.enabled !== \"boolean\")\n throw new CrmInputError(`template \"${id}\": enabled must be a boolean`);\n const copy = [tpl.subject, tpl.text].filter((value): value is string => typeof value === \"string\").join(\"\\n\");\n const unknown = lintTemplate(copy, declared[id]!.vars).unknown;\n if (unknown.length) throw new CrmInputError(`template \"${id}\": unknown vars ${unknown.join(\", \")}`);\n }\n const existing = await getConfig(deps);\n const base = existing ?? {\n id: \"\",\n key: CONFIG_KEY,\n emailTemplates: defaultTemplates(crm),\n settings: {},\n updatedAt: 0,\n };\n const templates: Record<string, StoredTemplate> = { ...defaultTemplates(crm), ...base.emailTemplates };\n for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {\n const prev = templates[id] ?? { subject: \"\", text: \"\", enabled: false };\n templates[id] = { ...prev, ...tpl };\n }\n const merged: CrmConfigRow = {\n ...base,\n notificationEmail:\n patch.notificationEmail !== undefined\n ? (patch.notificationEmail ?? undefined)\n : base.notificationEmail,\n replyTo: patch.replyTo !== undefined ? (patch.replyTo ?? undefined) : base.replyTo,\n debugEmail: patch.debugEmail !== undefined ? (patch.debugEmail ?? undefined) : base.debugEmail,\n emailTemplates: templates,\n settings: patch.settings !== undefined ? patch.settings : base.settings,\n updatedAt: now(),\n };\n // An unset optional email is null in `write`, which patchOps turns into a\n // retract (odla-db can't store a scalar null). The `update` half also creates\n // the singleton on first save, so the retract's key lookup then resolves.\n const write: Record<string, unknown> = {\n key: CONFIG_KEY,\n notificationEmail: merged.notificationEmail ?? null,\n replyTo: merged.replyTo ?? null,\n debugEmail: merged.debugEmail ?? null,\n emailTemplates: merged.emailTemplates,\n settings: merged.settings,\n updatedAt: merged.updatedAt,\n };\n const { duplicate } = await db.transact(\n patchOps(CRM_NS.config, { ns: CRM_NS.config, attr: \"key\", value: CONFIG_KEY }, write),\n { mutationId: opts.mutationId },\n );\n return { config: merged, duplicate };\n}\n","// The audited, consent-gated send path (S&S's sendTemplated generalized).\n// Gate order: template declared → copy enabled → consent (class-aware) →\n// dedupe → dev-redirect/log-only → transport. Success rows are written with\n// `mutationId email:{dedupeKey}` so a replayed trigger never double-logs;\n// FAILURE rows are written unconditionally so a retry's success is never\n// swallowed by its own earlier failure.\nimport { CRM_NS } from \"./constants\";\nimport { listChannels } from \"./channels\";\nimport { canEmail } from \"./consent\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { getConfig } from \"./config-store\";\nimport { mustGetRecord } from \"./records\";\nimport { renderTemplate } from \"./template\";\nimport type { CrmAttrs, CrmContactChannel, CrmEmailSender } from \"./types\";\n\n/** Inputs for one templated send (see {@link sendTemplatedEmail}). */\nexport interface SendEmailOpts {\n recordId: string;\n /** Defaults to the record's primary email channel. */\n channelId?: string;\n templateId: string;\n vars: Record<string, string>;\n /** Retry identity: a prior successful send with this key short-circuits. */\n dedupeKey: string;\n /** Sender address (env-owned, e.g. the verified EMAIL_FROM). */\n from: string;\n /** Anything but \"production\" redirects to the config debugEmail (subject\n * gets a \"[dev] \" prefix) or falls back to log-only. */\n envName: string;\n /** Absolute origin for links (unsubscribe). */\n baseUrl: string;\n /** Route mount point for the unsubscribe link. Default \"/api/crm\". */\n basePath?: string;\n /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */\n force?: boolean;\n}\n\n/** What happened to the send — delivered, gated, logged, or failed. */\nexport interface SendEmailResult {\n sent: boolean;\n /** Why nothing was delivered (gates, log-only, transport error). */\n reason?: string;\n transport?: \"sent\" | \"log-only\";\n}\n\n/**\n * Render and send one templated email to a record's contact channel, with\n * consent gating, dedupe, dev redirection, and an unconditional audit row.\n * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click\n * headers automatically.\n */\nexport async function sendTemplatedEmail(\n deps: CrmDeps & { sender?: CrmEmailSender },\n opts: SendEmailOpts,\n): Promise<SendEmailResult> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const spec = crm.config.templates?.[opts.templateId];\n if (!spec) return { sent: false, reason: \"unknown_template\" };\n const config = await getConfig(deps);\n const stored = config?.emailTemplates[opts.templateId] ?? null;\n if (!stored || (!stored.subject && !stored.text)) return { sent: false, reason: \"no_template_copy\" };\n if (!stored.enabled && !opts.force) return { sent: false, reason: \"disabled\" };\n\n const record = await mustGetRecord(deps, opts.recordId);\n const channels = await listChannels(deps, record.id);\n const channel: CrmContactChannel | undefined = opts.channelId\n ? channels.find((c) => c.id === opts.channelId)\n : channels.find((c) => c.kind === \"email\" && c.isPrimary);\n if (!channel) return { sent: false, reason: \"no_channel\" };\n if (!canEmail(channel.consent, spec.class)) return { sent: false, reason: \"blocked_by_consent\" };\n\n const prior = await db.query({\n [CRM_NS.emailLog]: { $: { where: { dedupeKey: opts.dedupeKey }, limit: 10 } },\n });\n // Only a real delivery is a duplicate — log-only rows (dev, missing\n // sender) must never block the eventual production send.\n if ((prior[CRM_NS.emailLog] ?? []).some((row) => !row[\"error\"] && row[\"transport\"] === \"sent\"))\n return { sent: false, reason: \"duplicate\" };\n\n const vars = { ...opts.vars };\n const headers: Record<string, string> = {};\n if (spec.class === \"marketing\") {\n const unsubscribeUrl = `${opts.baseUrl}${opts.basePath ?? \"/api/crm\"}/unsubscribe?token=${channel.unsubscribeToken}`;\n vars[\"unsubscribeUrl\"] = vars[\"unsubscribeUrl\"] ?? unsubscribeUrl;\n headers[\"List-Unsubscribe\"] = `<${unsubscribeUrl}>`;\n headers[\"List-Unsubscribe-Post\"] = \"List-Unsubscribe=One-Click\";\n }\n let subject = renderTemplate(stored.subject, vars);\n const text = renderTemplate(stored.text, vars);\n\n let to = channel.value;\n let redirected = false;\n let logOnly = !deps.sender;\n if (opts.envName !== \"production\") {\n if (config?.debugEmail) {\n to = config.debugEmail;\n subject = `[dev] ${subject}`;\n redirected = true;\n } else {\n logOnly = true;\n }\n }\n\n const logRow = (extra: CrmAttrs, mutationId?: string): Promise<unknown> =>\n db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.emailLog,\n id: newId(),\n attrs: {\n recordId: opts.recordId,\n channelId: channel.id,\n to,\n templateId: opts.templateId,\n subject,\n redirected,\n dedupeKey: opts.dedupeKey,\n sentAt: now(),\n ...extra,\n },\n },\n ],\n { mutationId },\n );\n\n if (logOnly || !deps.sender) {\n // Distinct mutation identity: must not consume `email:{dedupeKey}`,\n // which belongs to the eventual real delivery's log row.\n await logRow({ transport: \"log-only\" }, `email-log:${opts.dedupeKey}`);\n return { sent: false, reason: \"log_only\", transport: \"log-only\" };\n }\n try {\n const receipt = await deps.sender.send({\n from: opts.from,\n to: [to],\n subject,\n text,\n ...(config?.replyTo ? { replyTo: config.replyTo } : {}),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n });\n await logRow({ transport: \"sent\", messageId: receipt.messageId }, `email:${opts.dedupeKey}`);\n return { sent: true, transport: \"sent\" };\n } catch (error) {\n // Unconditional failure row (fresh id, no mutationId): a later retry's\n // success must not be suppressed by this failure's identity.\n await logRow({ transport: \"sent\", error: error instanceof Error ? error.message : String(error) });\n return { sent: false, reason: \"transport_error\" };\n }\n}\n\n/** Recent sends for the settings audit table, newest first. */\nexport async function listEmailLog(\n deps: CrmDeps,\n opts: { recordId?: string; limit?: number; offset?: number } = {},\n): Promise<Record<string, unknown>[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.emailLog]: {\n $: {\n ...(opts.recordId ? { where: { recordId: opts.recordId } } : {}),\n order: { sentAt: \"desc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return result[CRM_NS.emailLog] ?? [];\n}\n\n/** Guard for host-owned send paths (broadcasts, billing emails): may this\n * record receive `cls` mail right now? */\nexport async function recordCanEmail(\n deps: CrmDeps,\n recordId: string,\n cls: \"transactional\" | \"marketing\",\n): Promise<boolean> {\n const channels = await listChannels(deps, recordId);\n const primary = channels.find((c) => c.kind === \"email\" && c.isPrimary);\n if (!primary) return false;\n return canEmail(primary.consent, cls);\n}\n","// Identity facet: connect a record to the app's Clerk-synced `$users` row by\n// email (the S&S lazy-link pattern — members appear in $users at first\n// sign-in, and the CRM record picks up the account when the emails meet).\nimport { CRM_NS } from \"../constants\";\nimport { resolveDeps, type CrmDeps } from \"../deps\";\nimport { CrmInputError } from \"../errors\";\nimport { mustGetRecord } from \"../records\";\n\n/**\n * Look up `$users` by (lowercased) email and stamp the record's\n * `clerkUserId`. Uses the record's `primaryEmail` unless an explicit email\n * is given. Returns `linked: false` when no account exists yet — call again\n * after the person signs in (idempotent under `mutationId`).\n */\nexport async function linkIdentity(\n deps: CrmDeps,\n opts: { recordId: string; email?: string; mutationId?: string },\n): Promise<{ linked: boolean; clerkUserId?: string; duplicate?: boolean }> {\n const { db, now } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.recordId);\n const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();\n if (!email) throw new CrmInputError(\"record has no email to match on\");\n const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });\n const user = (result[\"$users\"] ?? []).find((row) => !row[\"deleted\"]);\n if (!user) return { linked: false };\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.record,\n id: record.id,\n attrs: { clerkUserId: user.id, updatedAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { linked: true, clerkUserId: user.id, duplicate };\n}\n","// Batched aggregates for the shell's summary tiles: odla-db has no faceted\n// counts, so each tile is one `aggregate` call — this module runs them\n// concurrently and returns a single payload.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\n\n/** Tile counts for one record type. */\nexport interface TypeSummary {\n type: string;\n total: number;\n /** Live records per pipeline stage (types with a pipeline). */\n stages: Record<string, number>;\n /** Open + waiting follow-up tasks across all records. */\n openTasks: number;\n}\n\n/**\n * Tile counts for one record type: total live records, per-stage counts,\n * and the open-task load. Each count is an indexed-where aggregate; a type\n * with S stages costs S+2 calls, issued concurrently.\n */\nexport async function typeSummary(deps: CrmDeps, type: string): Promise<TypeSummary> {\n const { crm, db } = resolveDeps(deps);\n const def = crm.type(type);\n const live = (extra: Record<string, unknown>[]) => ({\n where: { and: [{ type }, { archived: false }, ...extra] },\n });\n const stageIds = (def.pipeline?.stages ?? []).map((s) => s.id);\n const [total, openTasks, ...stageCounts] = await Promise.all([\n db.aggregate(CRM_NS.record, { count: true }, live([])),\n db.aggregate(CRM_NS.activity, { count: true }, {\n where: { and: [{ kind: \"task\" }, { status: { $in: [\"open\", \"waiting\"] } }] },\n }),\n ...stageIds.map((stage) => db.aggregate(CRM_NS.record, { count: true }, live([{ stage }]))),\n ]);\n const stages: Record<string, number> = {};\n stageIds.forEach((stage, i) => {\n stages[stage] = stageCounts[i]?.count ?? 0;\n });\n return { type, total: total?.count ?? 0, stages, openTasks: openTasks?.count ?? 0 };\n}\n","// HTTP plumbing for the route factory: option resolution, JSON helpers, the\n// error → status mapping, list-param parsing, and the unsubscribe page HTML.\nimport type { Crm } from \"./config\";\nimport type { CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport type { CrmListParams } from \"./query\";\nimport type { CrmDb, CrmEmailSender } from \"./types\";\n\n/** The authenticated admin performing a request (host-resolved — the crm\n * routes are an admin surface; end-user access is a future rules story). */\nexport interface CrmActor {\n userId: string;\n email?: string;\n /** Explicit product ACL for the read-only Discussion projection. Ordinary\n * CRM routes do not consult or grant this marker. */\n discussionReferenceScope?: \"all\";\n}\n\n/** Actor accepted by the product-owned CRM reference projection. */\nexport interface CrmDiscussionReferenceActor extends CrmActor {\n discussionReferenceScope: \"all\";\n}\n\n/** Everything `createCrmRoutes` needs from the host worker. */\nexport interface CrmRouteOpts {\n crm: Crm;\n db: CrmDb;\n /** Host-owned auth: resolve the request to an admin actor or null (401).\n * The unsubscribe endpoints are the only routes that skip this. */\n authorize: (req: Request) => Promise<CrmActor | null> | CrmActor | null;\n /** Optional host authority seam for read-only Discussion reference lookup.\n * Verify exact CRM product, crm.read capability, canonical audience,\n * principal, current app lifetime/environment, and agent grant provenance. */\n authorizeDiscussionReferences?: (\n req: Request,\n ) =>\n | Promise<CrmDiscussionReferenceActor | null>\n | CrmDiscussionReferenceActor\n | null;\n /** Email transport; omit for log-only behavior. */\n sender?: CrmEmailSender;\n /** Sender address for outbound mail (verified from-address). */\n from?: string;\n /** Only exactly \"production\" delivers to real recipients — anything else\n * dev-redirects or logs only. Defaults fail-safe to \"development\". */\n envName?: string;\n /** Absolute origin for links in emails (unsubscribe). */\n baseUrl?: string;\n /** Mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Native UI mount used by returned Discussion deep links. Default \"/admin/\". */\n discussionBasePath?: string;\n /** Injectable clock/id factory (tests). */\n now?: () => number;\n newId?: () => string;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteCtx {\n deps: CrmDeps & { sender?: CrmEmailSender };\n opts: Required<\n Pick<\n CrmRouteOpts,\n \"basePath\" | \"envName\" | \"baseUrl\" | \"discussionBasePath\"\n >\n > & CrmRouteOpts;\n actor: CrmActor;\n}\n\nexport const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n\nexport const errorResponse = (error: unknown): Response => {\n if (error instanceof CrmInputError)\n return json({ error: error.message, ...(error.fields ? { fields: error.fields } : {}) }, 400);\n if (error instanceof CrmNotFoundError) return json({ error: error.message }, 404);\n return json({ error: \"internal error\" }, 500);\n};\n\n/** Parse a JSON object body; CrmInputError (→ 400) on anything else. */\nexport async function readJson(req: Request): Promise<Record<string, unknown>> {\n let body: unknown;\n try {\n body = await req.json();\n } catch {\n throw new CrmInputError(\"invalid JSON body\");\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body))\n throw new CrmInputError(\"body must be a JSON object\");\n return body as Record<string, unknown>;\n}\n\nconst csv = (value: string | null): string[] | undefined =>\n value ? value.split(\",\").map((v) => v.trim()).filter(Boolean) : undefined;\n\nconst int = (value: string | null): number | undefined => {\n if (value == null || value === \"\") return undefined;\n const n = Number(value);\n if (!Number.isInteger(n)) throw new CrmInputError(`not an integer: \"${value}\"`);\n return n;\n};\n\n/** Decode `GET /records` search params into {@link CrmListParams}.\n * `sort=field:dir`, csv multi-filters, `fields` as URL-encoded JSON. */\nexport function parseListParams(url: URL): CrmListParams {\n const q = url.searchParams;\n const type = q.get(\"type\");\n if (!type) throw new CrmInputError(\"type is required\");\n const params: CrmListParams = { type };\n const search = q.get(\"search\");\n if (search) params.search = search;\n params.stage = csv(q.get(\"stage\"));\n params.emailStatus = csv(q.get(\"emailStatus\"));\n params.billingStatus = csv(q.get(\"billingStatus\"));\n const ownerId = q.get(\"ownerId\");\n if (ownerId) params.ownerId = ownerId;\n const tag = q.get(\"tag\");\n if (tag) params.tag = tag;\n if (q.get(\"archived\") === \"true\") params.archived = true;\n const sort = q.get(\"sort\");\n if (sort) {\n const [field, dir] = sort.split(\":\");\n if (!field || (dir !== \"asc\" && dir !== \"desc\"))\n throw new CrmInputError('sort must be \"field:asc\" or \"field:desc\"');\n params.sort = { field, dir };\n }\n params.limit = int(q.get(\"limit\"));\n params.offset = int(q.get(\"offset\"));\n const fields = q.get(\"fields\");\n if (fields) {\n try {\n params.fields = JSON.parse(fields) as CrmListParams[\"fields\"];\n } catch {\n throw new CrmInputError(\"fields must be URL-encoded JSON\");\n }\n }\n return params;\n}\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n\n/** The unsubscribe confirmation page. A GET must NEVER mutate (mail\n * scanners prefetch links); the form's POST performs the flip. */\nexport function unsubscribePage(token: string, done: boolean): Response {\n const body = done\n ? \"<p>You're unsubscribed. You can close this page.</p>\"\n : `<form method=\"post\"><input type=\"hidden\" name=\"token\" value=\"${escapeHtml(token)}\">` +\n `<p>Stop receiving these emails?</p><button type=\"submit\">Unsubscribe</button></form>`;\n return new Response(\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">` +\n `<title>Unsubscribe</title><main style=\"font-family:system-ui;max-width:32rem;margin:4rem auto\">${body}</main>`,\n { status: 200, headers: { \"content-type\": \"text/html; charset=utf-8\" } },\n );\n}\n","// Tiny body-field extractors: consistent CrmInputError messages so every\n// handler validates the same way without a schema library.\nimport { CrmInputError } from \"../errors\";\n\ntype Body = Record<string, unknown>;\n\nexport function str(body: Body, key: string): string {\n const value = body[key];\n if (typeof value !== \"string\" || value === \"\")\n throw new CrmInputError(`\"${key}\" must be a non-empty string`);\n return value;\n}\n\nexport function optStr(body: Body, key: string): string | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") throw new CrmInputError(`\"${key}\" must be a string`);\n return value;\n}\n\n/** Distinguishes \"absent\" (undefined) from an explicit null (clear). */\nexport function nullableStr(body: Body, key: string): string | null | undefined {\n const value = body[key];\n if (value === undefined) return undefined;\n if (value === null) return null;\n if (typeof value !== \"string\") throw new CrmInputError(`\"${key}\" must be a string or null`);\n return value;\n}\n\nexport function optNum(body: Body, key: string): number | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new CrmInputError(`\"${key}\" must be a number`);\n return value;\n}\n\nexport function nullableNum(body: Body, key: string): number | null | undefined {\n const value = body[key];\n if (value === undefined) return undefined;\n if (value === null) return null;\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new CrmInputError(`\"${key}\" must be a number or null`);\n return value;\n}\n\nexport function optBool(body: Body, key: string): boolean | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw new CrmInputError(`\"${key}\" must be a boolean`);\n return value;\n}\n\nexport function obj(body: Body, key: string): Record<string, unknown> {\n const value = body[key];\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n throw new CrmInputError(`\"${key}\" must be an object`);\n return value as Record<string, unknown>;\n}\n\nexport function optObj(body: Body, key: string): Record<string, unknown> | undefined {\n if (body[key] === undefined) return undefined;\n return obj(body, key);\n}\n","// Activity + follow-up handlers: a record's feed, the cross-record task\n// board, and task lifecycle patches.\nimport { addActivity, listActivities, listTasks, updateTask } from \"../activities\";\nimport type { ActivityKind, TaskStatus } from \"../constants\";\nimport { CrmInputError } from \"../errors\";\nimport { json, readJson, type RouteCtx } from \"../http\";\nimport { nullableNum, nullableStr, optNum, optObj, optStr, str } from \"./params\";\n\nexport async function handleRecordActivities(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n recordId: string,\n): Promise<Response> {\n if (req.method === \"GET\") {\n const activities = await listActivities(ctx.deps, {\n recordId,\n kind: (url.searchParams.get(\"kind\") as ActivityKind | null) ?? undefined,\n limit: numParam(url, \"limit\"),\n offset: numParam(url, \"offset\"),\n });\n return json({ activities });\n }\n if (req.method === \"POST\") {\n const body = await readJson(req);\n const created = await addActivity(ctx.deps, {\n recordId,\n kind: str(body, \"kind\") as ActivityKind,\n body: str(body, \"body\"),\n authorId: ctx.actor.userId,\n dueAt: optNum(body, \"dueAt\"),\n assigneeId: optStr(body, \"assigneeId\"),\n waitingOn: optStr(body, \"waitingOn\"),\n meta: optObj(body, \"meta\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(created, 201);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleActivityItem(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"PATCH\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const status = optStr(body, \"status\");\n const result = await updateTask(ctx.deps, {\n id,\n status: status as TaskStatus | undefined,\n dueAt: nullableNum(body, \"dueAt\"),\n assigneeId: nullableStr(body, \"assigneeId\"),\n waitingOn: nullableStr(body, \"waitingOn\"),\n body: optStr(body, \"body\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleTasks(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const statusCsv = url.searchParams.get(\"status\");\n const tasks = await listTasks(ctx.deps, {\n assigneeId: url.searchParams.get(\"assigneeId\") ?? undefined,\n status: statusCsv ? (statusCsv.split(\",\").filter(Boolean) as TaskStatus[]) : undefined,\n dueBefore: numParam(url, \"dueBefore\"),\n limit: numParam(url, \"limit\"),\n offset: numParam(url, \"offset\"),\n });\n return json({ tasks });\n}\n\nfunction numParam(url: URL, key: string): number | undefined {\n const raw = url.searchParams.get(key);\n if (raw == null || raw === \"\") return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n)) throw new CrmInputError(`\"${key}\" must be a number`);\n return n;\n}\n","// Per-record actions: stage moves (post-commit hook fired here, failures\n// reported but never un-commit the write), rank placement, tags, links,\n// identity linking, and templated sends.\nimport { sendTemplatedEmail } from \"../email\";\nimport { CrmInputError } from \"../errors\";\nimport { linkIdentity } from \"../facets/identity\";\nimport { json, readJson, type RouteCtx } from \"../http\";\nimport { resolveDeps } from \"../deps\";\nimport { setRank, setStage } from \"../stage-rank\";\nimport { addLink, addTag, removeLink, removeTag } from \"../tags-links\";\nimport { optBool, optObj, optStr, str } from \"./params\";\n\nexport async function handleStage(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const moved = await setStage(ctx.deps, {\n id,\n to: str(body, \"to\"),\n authorId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n let hookError: string | undefined;\n if (moved.hook && !moved.duplicate) {\n // Post-commit side effect (e.g. Clerk role promotion). Its failure is\n // surfaced to the admin but the stage change stands — retry the hook,\n // not the transition.\n try {\n await moved.hook(moved.record);\n } catch (error) {\n hookError = error instanceof Error ? error.message : String(error);\n }\n }\n return json({\n record: moved.record,\n from: moved.from,\n duplicate: moved.duplicate,\n ...(hookError ? { hookError } : {}),\n });\n}\n\nexport async function handleRank(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await setRank(ctx.deps, {\n id,\n beforeId: optStr(body, \"beforeId\"),\n afterId: optStr(body, \"afterId\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleTags(ctx: RouteCtx, req: Request, id: string, rest: string[]): Promise<Response> {\n if (req.method === \"POST\" && rest.length === 0) {\n const body = await readJson(req);\n const result = await addTag(ctx.deps, {\n recordId: id,\n tag: str(body, \"tag\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result, 201);\n }\n if (req.method === \"DELETE\" && rest.length === 1) {\n const result = await removeTag(ctx.deps, { recordId: id, tag: decodeURIComponent(rest[0]!) });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleLinks(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const opts = {\n relation: str(body, \"relation\"),\n fromId: id,\n toId: str(body, \"toId\"),\n mutationId: optStr(body, \"mutationId\"),\n };\n const result = optBool(body, \"remove\")\n ? await removeLink(ctx.deps, opts)\n : await addLink(ctx.deps, opts);\n return json(result);\n}\n\nexport async function handleLinkIdentity(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await linkIdentity(ctx.deps, {\n recordId: id,\n email: optStr(body, \"email\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleSendEmail(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const from = ctx.opts.from;\n if (!from) throw new CrmInputError(\"email sending is not configured (missing from address)\");\n const vars: Record<string, string> = {};\n for (const [key, value] of Object.entries(optObj(body, \"vars\") ?? {})) {\n if (typeof value !== \"string\") throw new CrmInputError(`var \"${key}\" must be a string`);\n vars[key] = value;\n }\n const result = await sendTemplatedEmail(ctx.deps, {\n recordId: id,\n channelId: optStr(body, \"channelId\"),\n templateId: str(body, \"templateId\"),\n vars,\n dedupeKey: optStr(body, \"dedupeKey\") ?? `manual:${resolveDeps(ctx.deps).newId()}`,\n force: optBool(body, \"force\"),\n from,\n envName: ctx.opts.envName,\n baseUrl: ctx.opts.baseUrl,\n basePath: ctx.opts.basePath,\n });\n return json(result);\n}\n","// /records handlers: the list window, record detail (record + tags +\n// channels + links composed), create/patch, and archive/restore.\nimport { listChannels } from \"../channels\";\nimport { parseListParams, json, type RouteCtx } from \"../http\";\nimport {\n createRecord,\n getRecord,\n listRecords,\n setArchived,\n updateRecord,\n} from \"../records\";\nimport { listLinks, listTags } from \"../tags-links\";\nimport { readJson } from \"../http\";\nimport { CrmNotFoundError } from \"../errors\";\nimport { listRecordDeliveries, listRecordOrigins } from \"../provenance\";\nimport { nullableStr, obj, optBool, optObj, optStr, str } from \"./params\";\n\nexport async function handleRecordsRoot(ctx: RouteCtx, req: Request, url: URL): Promise<Response | null> {\n if (req.method === \"GET\") {\n const result = await listRecords(ctx.deps, parseListParams(url));\n return json(result);\n }\n if (req.method === \"POST\") {\n const body = await readJson(req);\n const created = await createRecord(ctx.deps, {\n type: str(body, \"type\"),\n input: obj(body, \"input\"),\n ownerId: optStr(body, \"ownerId\"),\n stage: optStr(body, \"stage\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleRecordItem(ctx: RouteCtx, req: Request, id: string): Promise<Response | null> {\n if (req.method === \"GET\") {\n const record = await getRecord(ctx.deps, id);\n if (!record) throw new CrmNotFoundError(\"record\");\n const [tags, channels, links, origins, deliveries] = await Promise.all([\n listTags(ctx.deps, id),\n listChannels(ctx.deps, id),\n listLinks(ctx.deps, id),\n listRecordOrigins(ctx.deps, id),\n listRecordDeliveries(ctx.deps, { recordId: id }),\n ]);\n return json({ record, tags, channels, links, origins, deliveries });\n }\n if (req.method === \"PATCH\") {\n const body = await readJson(req);\n const updated = await updateRecord(ctx.deps, {\n id,\n input: optObj(body, \"input\") ?? {},\n ownerId: nullableStr(body, \"ownerId\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json({ record: updated.record, duplicate: updated.duplicate });\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleArchive(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await setArchived(ctx.deps, {\n id,\n archived: optBool(body, \"archived\") ?? true,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n","// Views, summary tiles, config, the email audit log, rank rebalance, and\n// the PUBLIC unsubscribe pair (GET renders, POST mutates — never the\n// reverse; scanners prefetch GETs).\nimport { applyConsent } from \"../channels\";\nimport { getConfig, saveConfig, type ConfigPatch } from \"../config-store\";\nimport { listEmailLog } from \"../email\";\nimport { CrmInputError } from \"../errors\";\nimport { json, readJson, unsubscribePage, type RouteCtx } from \"../http\";\nimport type { CrmDeps } from \"../deps\";\nimport type { CrmSort, ViewFilters } from \"../query\";\nimport { rebalanceRanks } from \"../stage-rank\";\nimport { typeSummary } from \"../summary\";\nimport { deleteView, listViews, saveView, updateView, type ViewSpec } from \"../views\";\nimport { obj, optBool, optObj, optStr, str } from \"./params\";\n\nfunction specFrom(body: Record<string, unknown>): ViewSpec {\n const spec = obj(body, \"spec\");\n return {\n name: str(spec, \"name\"),\n type: str(spec, \"type\"),\n filters: (optObj(spec, \"filters\") ?? {}) as ViewFilters,\n sort: (spec[\"sort\"] ?? null) as CrmSort | null,\n columns: Array.isArray(spec[\"columns\"]) ? (spec[\"columns\"] as string[]) : [],\n shared: optBool(spec, \"shared\") ?? false,\n };\n}\n\nexport async function handleViews(ctx: RouteCtx, req: Request, url: URL, rest: string[]): Promise<Response> {\n if (rest.length === 0 && req.method === \"GET\") {\n const views = await listViews(ctx.deps, {\n viewerId: ctx.actor.userId,\n type: url.searchParams.get(\"type\") ?? undefined,\n });\n return json({ views });\n }\n if (rest.length === 0 && req.method === \"POST\") {\n const body = await readJson(req);\n const created = await saveView(ctx.deps, {\n spec: specFrom(body),\n ownerId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(created, 201);\n }\n const id = rest[0];\n if (id && req.method === \"PATCH\") {\n const body = await readJson(req);\n const spec = optObj(body, \"spec\") ?? {};\n const result = await updateView(ctx.deps, {\n id,\n spec: spec as Partial<ViewSpec>,\n ownerId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n }\n if (id && req.method === \"DELETE\") {\n const result = await deleteView(ctx.deps, { id, ownerId: ctx.actor.userId });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleSummary(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const type = url.searchParams.get(\"type\");\n if (!type) throw new CrmInputError(\"type is required\");\n return json(await typeSummary(ctx.deps, type));\n}\n\nexport async function handleConfig(ctx: RouteCtx, req: Request): Promise<Response> {\n if (req.method === \"GET\") {\n const config = await getConfig(ctx.deps);\n return json({ config });\n }\n if (req.method === \"PUT\") {\n const body = await readJson(req);\n const result = await saveConfig(ctx.deps, body as ConfigPatch, {\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleEmailLog(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const limitRaw = url.searchParams.get(\"limit\");\n const rows = await listEmailLog(ctx.deps, {\n recordId: url.searchParams.get(\"recordId\") ?? undefined,\n limit: limitRaw ? Number(limitRaw) : undefined,\n });\n return json({ log: rows });\n}\n\nexport async function handleRebalance(ctx: RouteCtx, req: Request): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await rebalanceRanks(ctx.deps, {\n type: str(body, \"type\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\n/** No auth here — the token IS the credential (unique, unguessable, scoped\n * to one channel). GET renders the confirm form; POST flips consent,\n * idempotently (`consent:{token}:{event}`), accepting the RFC 8058\n * one-click body, a form post, or JSON. */\nexport async function handleUnsubscribe(deps: CrmDeps, req: Request, url: URL): Promise<Response> {\n if (req.method === \"GET\") {\n const token = url.searchParams.get(\"token\");\n if (!token) return json({ error: \"token is required\" }, 400);\n return unsubscribePage(token, false);\n }\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n let token = url.searchParams.get(\"token\") ?? \"\";\n let oneClick = false;\n const contentType = req.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"form\")) {\n const form = await req.formData();\n token = String(form.get(\"token\") ?? token);\n oneClick = String(form.get(\"List-Unsubscribe\") ?? \"\") === \"One-Click\";\n } else if (contentType.includes(\"json\")) {\n const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;\n if (typeof body[\"token\"] === \"string\") token = body[\"token\"];\n }\n if (!token) return json({ error: \"token is required\" }, 400);\n const event = oneClick ? \"unsubscribe.oneclick\" : \"unsubscribe.token\";\n await applyConsent(deps, { token, event, mutationId: `consent:${token}:unsubscribe` });\n return oneClick ? json({ ok: true }) : unsubscribePage(token, true);\n}\n","import { CRM_NS } from \"../constants\";\nimport {\n crmDiscussionReferenceHref,\n crmDiscussionReferenceId,\n parseCrmDiscussionReference,\n type CrmDiscussionReference,\n type CrmDiscussionReferenceTarget,\n} from \"../discussion-reference\";\nimport { getRecord, listRecords } from \"../records\";\nimport type { CrmActivity, CrmRecord } from \"../types\";\nimport { json, type RouteCtx } from \"../http\";\n\nconst capLimit = (raw: string | null): number => {\n const parsed = Number(raw ?? 20);\n return Number.isInteger(parsed) ? Math.max(1, Math.min(parsed, 20)) : 20;\n};\n\nconst targetFromQuery = (url: URL): CrmDiscussionReferenceTarget | null => {\n const kind = url.searchParams.get(\"kind\");\n const id = url.searchParams.get(\"id\");\n if (!kind || !id) return null;\n const value = new URL(\"https://crm.invalid\");\n value.searchParams.set(\"odla-ref\", `${kind}/${id}`);\n return parseCrmDiscussionReference(value);\n};\n\nconst recordItem = (\n ctx: RouteCtx,\n req: Request,\n record: CrmRecord,\n): CrmDiscussionReference => {\n const typeLabel = ctx.deps.crm.type(record.type).label;\n const status = record.archived\n ? \"archived\"\n : record.stage ?? \"record\";\n const target: CrmDiscussionReferenceTarget = {\n kind: \"crm:record\",\n type: record.type,\n recordId: record.id,\n };\n return {\n kind: target.kind,\n id: crmDiscussionReferenceId(target),\n label: record.name,\n hint: `${typeLabel} · ${status}`,\n summary: `${typeLabel} record for ${record.name}`,\n status,\n destination: `CRM · ${typeLabel} profile`,\n href: crmDiscussionReferenceHref(\n new URL(req.url),\n target,\n ctx.opts.discussionBasePath,\n ),\n };\n};\n\nconst activityItem = (\n ctx: RouteCtx,\n req: Request,\n record: CrmRecord,\n activity: CrmActivity,\n): CrmDiscussionReference => {\n const target: CrmDiscussionReferenceTarget = {\n kind: \"crm:activity\",\n type: record.type,\n recordId: record.id,\n activityId: activity.id,\n };\n return {\n kind: target.kind,\n id: crmDiscussionReferenceId(target),\n label: activity.body,\n hint: `${record.name} · ${activity.kind}${\n activity.status ? ` · ${activity.status}` : \"\"\n }`,\n summary: `${activity.kind} on ${record.name}: ${activity.body}`,\n status: activity.status ?? activity.kind,\n destination: `CRM · ${record.name} notes`,\n href: crmDiscussionReferenceHref(\n new URL(req.url),\n target,\n ctx.opts.discussionBasePath,\n ),\n };\n};\n\nasync function exact(\n ctx: RouteCtx,\n req: Request,\n target: CrmDiscussionReferenceTarget,\n): Promise<CrmDiscussionReference[]> {\n const record = await getRecord(ctx.deps, target.recordId);\n if (!record || record.type !== target.type) return [];\n if (target.kind === \"crm:record\") return [recordItem(ctx, req, record)];\n const result = await ctx.deps.db.query({\n [CRM_NS.activity]: {\n $: { where: { id: target.activityId }, limit: 1 },\n },\n });\n const activity = (result[CRM_NS.activity] ?? [])[0] as\n | CrmActivity\n | undefined;\n return activity && activity.recordId === record.id\n ? [activityItem(ctx, req, record, activity)]\n : [];\n}\n\nconst matches = (item: CrmDiscussionReference, needle: string): boolean =>\n !needle ||\n `${item.label}\\n${item.hint}\\n${item.id}`.toLowerCase().includes(needle);\n\nasync function searchableActivities(\n ctx: RouteCtx,\n req: Request,\n needle: string,\n): Promise<CrmDiscussionReference[]> {\n const result = await ctx.deps.db.query({\n [CRM_NS.activity]: {\n $: { order: { createdAt: \"desc\" }, limit: 100 },\n },\n });\n const rows = (result[CRM_NS.activity] ?? []) as unknown as CrmActivity[];\n const matching = rows.filter((activity) =>\n !needle || activity.body.toLowerCase().includes(needle)\n );\n const records = await Promise.all(\n [...new Set(matching.map((activity) => activity.recordId))]\n .map((id) => getRecord(ctx.deps, id)),\n );\n const byId = new Map(\n records.filter((record): record is CrmRecord => record !== null)\n .map((record) => [record.id, record]),\n );\n return matching.flatMap((activity) => {\n const record = byId.get(activity.recordId);\n return record ? [activityItem(ctx, req, record, activity)] : [];\n });\n}\n\nasync function search(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n): Promise<CrmDiscussionReference[]> {\n const limit = capLimit(url.searchParams.get(\"limit\"));\n const needle = (url.searchParams.get(\"q\") ?? \"\").trim().toLowerCase()\n .slice(0, 120);\n const recordPages = await Promise.all(\n Object.keys(ctx.deps.crm.config.types).map((type) =>\n listRecords(ctx.deps, {\n type,\n ...(needle ? { search: needle } : {}),\n limit,\n offset: 0,\n })\n ),\n );\n const records = recordPages.flatMap((page) =>\n page.records.map((record) => recordItem(ctx, req, record))\n );\n const activities = await searchableActivities(ctx, req, needle);\n return [...records, ...activities]\n .filter((item) => matches(item, needle))\n .slice(0, limit);\n}\n\n/**\n * Authenticated product-owned CRM reference search and exact resolution.\n * The host supplies an explicit all-record reference ACL; row existence and\n * parentage are checked before any projection.\n */\nexport async function handleCrmDiscussionReferences(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n if (ctx.actor.discussionReferenceScope !== \"all\") {\n return json({ error: \"forbidden\" }, 403);\n }\n const kind = url.searchParams.get(\"kind\");\n const id = url.searchParams.get(\"id\");\n if ((kind && !id) || (!kind && id)) {\n return json({ error: \"kind and id must be paired\" }, 400);\n }\n const target = targetFromQuery(url);\n if ((kind || id) && !target) return json({ items: [] });\n return json({\n items: target ? await exact(ctx, req, target) : await search(ctx, req, url),\n });\n}\n","// The mountable route factory: everything S&S's worker hand-rolls as\n// /api/admin/* matches, formalized. The host worker composes it —\n// const crmRoutes = createCrmRoutes({ crm, db, authorize, … });\n// return (await crmRoutes(request)) ?? next(request);\n// — and keeps full ownership of auth (`authorize`) and the admin key.\nimport {\n errorResponse,\n json,\n type CrmActor,\n type CrmDiscussionReferenceActor,\n type CrmRouteOpts,\n type RouteCtx,\n} from \"../http\";\nimport { handleActivityItem, handleRecordActivities, handleTasks } from \"./activities\";\nimport {\n handleLinkIdentity,\n handleLinks,\n handleRank,\n handleSendEmail,\n handleStage,\n handleTags,\n} from \"./actions\";\nimport { handleArchive, handleRecordItem, handleRecordsRoot } from \"./records\";\nimport {\n handleConfig,\n handleEmailLog,\n handleRebalance,\n handleSummary,\n handleUnsubscribe,\n handleViews,\n} from \"./misc\";\nimport { handleCrmDiscussionReferences } from \"./discussion-references\";\n\nexport type { CrmActor, CrmDiscussionReferenceActor, CrmRouteOpts };\n\nasync function route(ctx: RouteCtx, req: Request, url: URL, seg: string[]): Promise<Response | null> {\n const [head, id, action, ...rest] = seg;\n if (head === \"discussion-references\" && id === undefined)\n return handleCrmDiscussionReferences(ctx, req, url);\n if (head === \"records\") {\n if (id === undefined) return handleRecordsRoot(ctx, req, url);\n if (action === undefined) return handleRecordItem(ctx, req, id);\n if (action === \"archive\") return handleArchive(ctx, req, id);\n if (action === \"stage\") return handleStage(ctx, req, id);\n if (action === \"rank\") return handleRank(ctx, req, id);\n if (action === \"tags\") return handleTags(ctx, req, id, rest);\n if (action === \"links\") return handleLinks(ctx, req, id);\n if (action === \"link-identity\") return handleLinkIdentity(ctx, req, id);\n if (action === \"email\") return handleSendEmail(ctx, req, id);\n if (action === \"activities\") return handleRecordActivities(ctx, req, url, id);\n return null;\n }\n if (head === \"activities\" && id !== undefined && action === undefined)\n return handleActivityItem(ctx, req, id);\n if (head === \"tasks\" && id === undefined) return handleTasks(ctx, req, url);\n if (head === \"views\") return handleViews(ctx, req, url, seg.slice(1));\n if (head === \"summary\" && id === undefined) return handleSummary(ctx, req, url);\n if (head === \"config\" && id === undefined) return handleConfig(ctx, req);\n if (head === \"email-log\" && id === undefined) return handleEmailLog(ctx, req, url);\n if (head === \"rank\" && id === \"rebalance\" && action === undefined)\n return handleRebalance(ctx, req);\n return null;\n}\n\n/**\n * Build the crm fetch handler. Returns `null` for requests outside\n * `basePath` (default `/api/crm`) so the host worker falls through to its\n * own routes; inside it, every route requires `authorize` to resolve an\n * admin actor (401 otherwise) EXCEPT the public unsubscribe pair, where the\n * per-channel token is the credential. Domain errors map to 400/404 JSON;\n * anything unexpected is a 500 without internals.\n */\nexport function createCrmRoutes(options: CrmRouteOpts): (req: Request) => Promise<Response | null> {\n const basePath = options.basePath ?? \"/api/crm\";\n const opts = {\n ...options,\n basePath,\n envName: options.envName ?? \"development\",\n baseUrl: options.baseUrl ?? \"\",\n discussionBasePath: options.discussionBasePath ?? \"/admin/\",\n };\n const deps = {\n crm: options.crm,\n db: options.db,\n now: options.now,\n newId: options.newId,\n sender: options.sender,\n };\n return async (req: Request): Promise<Response | null> => {\n const url = new URL(req.url);\n if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) return null;\n const segments = url.pathname.slice(basePath.length).split(\"/\").filter(Boolean);\n try {\n if (segments[0] === \"unsubscribe\" && segments.length === 1)\n return await handleUnsubscribe(deps, req, url);\n const discussionReferences = segments[0] === \"discussion-references\";\n const actor = discussionReferences && options.authorizeDiscussionReferences\n ? await options.authorizeDiscussionReferences(req)\n : await options.authorize(req);\n if (!actor) return json({ error: \"unauthorized\" }, 401);\n const ctx: RouteCtx = {\n deps,\n opts,\n actor: discussionReferences && !options.authorizeDiscussionReferences\n ? { ...actor, discussionReferenceScope: \"all\" }\n : actor,\n };\n return (await route(ctx, req, url, segments)) ?? json({ error: \"not found\" }, 404);\n } catch (error) {\n return errorResponse(error);\n }\n };\n}\n","// Browser client for the crm routes — a thin, typed fetch wrapper the UI\n// kit's hooks use. Inject `fetch` and auth `headers` (e.g. a Clerk session\n// token getter runs outside; pass the resolved header).\nimport type { CrmListParams } from \"./query\";\nimport type { ViewSpec } from \"./views\";\nimport type { ConfigPatch } from \"./config-store\";\nimport type {\n CrmActivity,\n CrmConfigRow,\n CrmContactChannel,\n CrmLink,\n CrmRecord,\n CrmRecordDelivery,\n CrmRecordOrigin,\n CrmTag,\n CrmView,\n} from \"./types\";\nimport type { TypeSummary } from \"./summary\";\n\n/** Where the routes live and how to authenticate against them. */\nexport interface CrmClientOptions {\n /** Origin of the host worker, e.g. \"\" (same-origin) or a full URL. */\n baseUrl?: string;\n /** Route mount point. Default \"/api/crm\". */\n basePath?: string;\n fetch?: typeof globalThis.fetch;\n /** Per-request auth headers (called each request — tokens rotate). */\n headers?: () => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/** Error carrying the route's status + JSON error payload. */\nexport class CrmClientError extends Error {\n readonly status: number;\n readonly fields?: Record<string, string>;\n constructor(status: number, message: string, fields?: Record<string, string>) {\n super(message);\n this.name = \"CrmClientError\";\n this.status = status;\n this.fields = fields;\n }\n}\n\n/** A record composed with its tags, channels, and links. */\nexport interface RecordDetail {\n record: CrmRecord;\n tags: CrmTag[];\n channels: CrmContactChannel[];\n links: CrmLink[];\n /** Structured upstream identities; absent only from pre-upgrade custom APIs. */\n origins?: CrmRecordOrigin[];\n /** Latest outbound state per target; absent only from pre-upgrade custom APIs. */\n deliveries?: CrmRecordDelivery[];\n}\n\n/** One list window plus the total matching count. */\nexport interface RecordPage {\n records: CrmRecord[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/** Typed access to every crm route. Methods reject with\n * {@link CrmClientError} on non-2xx responses. */\nexport class CrmClient {\n private readonly base: string;\n private readonly doFetch: typeof globalThis.fetch;\n private readonly headers?: CrmClientOptions[\"headers\"];\n\n constructor(options: CrmClientOptions = {}) {\n this.base = `${options.baseUrl ?? \"\"}${options.basePath ?? \"/api/crm\"}`;\n this.doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.headers = options.headers;\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { ...(await this.headers?.()) };\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n const response = await this.doFetch(`${this.base}${path}`, {\n method,\n headers,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n if (!response.ok)\n throw new CrmClientError(\n response.status,\n typeof payload[\"error\"] === \"string\" ? payload[\"error\"] : `HTTP ${response.status}`,\n payload[\"fields\"] as Record<string, string> | undefined,\n );\n return payload as T;\n }\n\n listRecords(params: CrmListParams): Promise<RecordPage> {\n const q = new URLSearchParams({ type: params.type });\n if (params.search) q.set(\"search\", params.search);\n if (params.stage?.length) q.set(\"stage\", params.stage.join(\",\"));\n if (params.emailStatus?.length) q.set(\"emailStatus\", params.emailStatus.join(\",\"));\n if (params.billingStatus?.length) q.set(\"billingStatus\", params.billingStatus.join(\",\"));\n if (params.ownerId) q.set(\"ownerId\", params.ownerId);\n if (params.tag) q.set(\"tag\", params.tag);\n if (params.archived) q.set(\"archived\", \"true\");\n if (params.sort) q.set(\"sort\", `${params.sort.field}:${params.sort.dir}`);\n if (params.limit != null) q.set(\"limit\", String(params.limit));\n if (params.offset != null) q.set(\"offset\", String(params.offset));\n if (params.fields) q.set(\"fields\", JSON.stringify(params.fields));\n return this.request(\"GET\", `/records?${q}`);\n }\n\n getRecord(id: string): Promise<RecordDetail> {\n return this.request(\"GET\", `/records/${encodeURIComponent(id)}`);\n }\n createRecord(body: {\n type: string;\n input: Record<string, unknown>;\n ownerId?: string;\n stage?: string;\n mutationId?: string;\n }): Promise<{ id: string; duplicate: boolean; record: CrmRecord }> {\n return this.request(\"POST\", \"/records\", body);\n }\n updateRecord(\n id: string,\n body: { input?: Record<string, unknown>; ownerId?: string | null; mutationId?: string },\n ): Promise<{ record: CrmRecord; duplicate: boolean }> {\n return this.request(\"PATCH\", `/records/${encodeURIComponent(id)}`, body);\n }\n setArchived(id: string, archived: boolean): Promise<{ duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/archive`, { archived });\n }\n setStage(\n id: string,\n to: string,\n mutationId?: string,\n ): Promise<{ record: CrmRecord; from: string | null; duplicate: boolean; hookError?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/stage`, { to, mutationId });\n }\n setRank(\n id: string,\n body: { beforeId?: string; afterId?: string },\n ): Promise<{ rank: number; rebalanceNeeded: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/rank`, body);\n }\n addTag(id: string, tag: string): Promise<{ tag: string; duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/tags`, { tag });\n }\n removeTag(id: string, tag: string): Promise<{ duplicate: boolean }> {\n return this.request(\n \"DELETE\",\n `/records/${encodeURIComponent(id)}/tags/${encodeURIComponent(tag)}`,\n );\n }\n setLink(\n id: string,\n body: { relation: string; toId: string; remove?: boolean },\n ): Promise<{ duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/links`, body);\n }\n linkIdentity(id: string, email?: string): Promise<{ linked: boolean; clerkUserId?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/link-identity`, { email });\n }\n sendEmail(\n id: string,\n body: {\n templateId: string;\n vars?: Record<string, string>;\n dedupeKey?: string;\n channelId?: string;\n force?: boolean;\n },\n ): Promise<{ sent: boolean; reason?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/email`, body);\n }\n listActivities(recordId: string, opts: { kind?: string; limit?: number } = {}): Promise<{ activities: CrmActivity[] }> {\n const q = new URLSearchParams();\n if (opts.kind) q.set(\"kind\", opts.kind);\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/records/${encodeURIComponent(recordId)}/activities?${q}`);\n }\n addActivity(\n recordId: string,\n body: { kind: string; body: string; dueAt?: number; assigneeId?: string; waitingOn?: string },\n ): Promise<{ id: string; duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(recordId)}/activities`, body);\n }\n updateTask(\n id: string,\n body: { status?: string; dueAt?: number | null; assigneeId?: string | null; waitingOn?: string | null; body?: string },\n ): Promise<{ activity: CrmActivity; duplicate: boolean }> {\n return this.request(\"PATCH\", `/activities/${encodeURIComponent(id)}`, body);\n }\n listTasks(opts: { assigneeId?: string; status?: string[]; limit?: number } = {}): Promise<{ tasks: CrmActivity[] }> {\n const q = new URLSearchParams();\n if (opts.assigneeId) q.set(\"assigneeId\", opts.assigneeId);\n if (opts.status?.length) q.set(\"status\", opts.status.join(\",\"));\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/tasks?${q}`);\n }\n listViews(type?: string): Promise<{ views: CrmView[] }> {\n return this.request(\"GET\", `/views${type ? `?type=${encodeURIComponent(type)}` : \"\"}`);\n }\n saveView(spec: ViewSpec): Promise<{ id: string; duplicate: boolean }> {\n return this.request(\"POST\", \"/views\", { spec });\n }\n updateView(id: string, spec: Partial<ViewSpec>): Promise<{ view: CrmView; duplicate: boolean }> {\n return this.request(\"PATCH\", `/views/${encodeURIComponent(id)}`, { spec });\n }\n deleteView(id: string): Promise<{ duplicate: boolean }> {\n return this.request(\"DELETE\", `/views/${encodeURIComponent(id)}`);\n }\n summary(type: string): Promise<TypeSummary> {\n return this.request(\"GET\", `/summary?type=${encodeURIComponent(type)}`);\n }\n getConfig(): Promise<{ config: CrmConfigRow | null }> {\n return this.request(\"GET\", \"/config\");\n }\n saveConfig(patch: ConfigPatch): Promise<{ config: CrmConfigRow; duplicate: boolean }> {\n return this.request(\"PUT\", \"/config\", patch);\n }\n emailLog(opts: { recordId?: string; limit?: number } = {}): Promise<{ log: Record<string, unknown>[] }> {\n const q = new URLSearchParams();\n if (opts.recordId) q.set(\"recordId\", opts.recordId);\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/email-log?${q}`);\n }\n rebalance(type: string): Promise<{ count: number }> {\n return this.request(\"POST\", \"/rank/rebalance\", { type });\n }\n}\n","// The integration descriptor: documentation-as-data for the CRM capability,\n// extending the auth-clerk/chat pattern with the schema + rules to install.\n// The base shapes are inlined so the zero-dependency package does not depend\n// on the CLI. The CLI consumes descriptors structurally from odla.config.mjs.\nimport { CRM_SCHEMA, type SerializedSchema } from \"./schema\";\nimport { CRM_RULES, type CrmRules } from \"./rules\";\nimport { CONFIG_KEY, CRM_NS } from \"./constants\";\nimport { defaultTemplates } from \"./config-store\";\nimport type { Crm } from \"./config\";\n\nexport interface IntegrationSetting {\n key: string;\n description: string;\n public: boolean;\n pattern?: string;\n perEnv: boolean;\n source: string;\n}\n\nexport interface IntegrationSecret {\n key: string;\n description: string;\n pattern?: string;\n vault: boolean;\n}\n\nexport interface IntegrationProvision {\n human: string[];\n cli: string[];\n doctor: string[];\n smoke?: string[];\n}\n\n/** Natural-key config row the CLI creates only when no CRM config exists. */\nexport interface CrmIntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\n/** Unauthenticated route check run by `odla-ai smoke`. */\nexport interface CrmIntegrationProbe {\n path: string;\n expectedStatus: number;\n}\n\n/** The CRM's descriptor shape: the shared base plus the schema + deny-all\n * rules provisioning installs (the chat-style extension). */\nexport interface CrmIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n settings: IntegrationSetting[];\n secrets: IntegrationSecret[];\n schema: SerializedSchema;\n rules: CrmRules;\n seeds?: CrmIntegrationSeed[];\n probes?: CrmIntegrationProbe[];\n provision: IntegrationProvision;\n}\n\n/** Initial owner-editable CRM settings seeded during first provisioning. */\nexport interface CrmIntegrationOptions {\n /** Worker mount path; defaults to `/api/crm`. */\n basePath?: string;\n notificationEmail?: string;\n replyTo?: string;\n debugEmail?: string;\n settings?: Record<string, unknown>;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\n/**\n * The static documentation descriptor for @odla-ai/crm. Data only: it\n * describes what installing the\n * CRM means (push {@link CRM_SCHEMA}, install deny-all {@link CRM_RULES},\n * seed the `crm_config` row, mount `createCrmRoutes` in the app worker); it\n * performs none of it. Use {@link createCrmIntegration} in `odla.config.mjs`\n * to add the config seed and live route probe the CLI can execute. Billing is\n * an optional injected provider seam and the core CRM needs no vault entries.\n */\nexport const crmIntegration: CrmIntegrationDescriptor = {\n id: \"crm\",\n title: \"CRM records, pipelines & contactability\",\n npm: \"@odla-ai/crm\",\n settings: [\n {\n key: \"basePath\",\n description: 'Route mount point the app worker serves the CRM under. Default \"/api/crm\".',\n public: true,\n perEnv: false,\n source: \"createCrmRoutes({ basePath }) in the app worker\",\n },\n {\n key: \"notificationEmail / replyTo / debugEmail\",\n description:\n \"Destination addresses for owner notifications, reply routing, and the dev redirect — runtime-editable.\",\n public: false,\n perEnv: false,\n source: \"crm_config row (odla-db), edited in the app's CRM settings UI\",\n },\n ],\n secrets: [],\n schema: CRM_SCHEMA,\n rules: CRM_RULES,\n provision: {\n human: [\n \"None for the core install — records/pipelines/email-consent need no external accounts.\",\n \"If the app injects billing, configure that provider's webhook and vault secrets according to the app-owned adapter.\",\n ],\n cli: [\n \"POST the merged CRM_SCHEMA to /app/:id/schema.\",\n \"Install CRM_RULES (deny-all) at /app/:id/admin/rules.\",\n \"Seed the crm_config row from the app's defineCrm template defaults.\",\n ],\n doctor: [\n \"Every crm_* namespace has rules installed (deny-all: no rule = exposed to nothing, but assert explicitly).\",\n \"The guarded crm_config seed targets the declared-unique crm_config.key attribute.\",\n \"Code-declared template defaults have no unknown {{vars}}; owner-edited copies are checked when saved.\",\n ],\n smoke: [\n \"A GET probe of <basePath>/records without credentials answers 401 (routes mounted, authorize enforced).\",\n ],\n },\n};\n\n/**\n * Build the project-specific, CLI-consumable CRM integration descriptor.\n * The returned schema/rules merge structurally with app-authored db config;\n * the config singleton is seeded only when absent, preserving later owner\n * edits, and `smoke` verifies the mounted records route rejects anonymous\n * access. Mounting `createCrmRoutes` remains app-owned source work.\n */\nexport function createCrmIntegration(\n crm: Crm,\n options: CrmIntegrationOptions = {},\n): CrmIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n if (!/^\\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/.test(basePath) || basePath.endsWith(\"/\")) {\n throw new Error(\"createCrmIntegration: basePath must be an absolute path without a trailing slash\");\n }\n const attrs: Record<string, unknown> = {\n emailTemplates: defaultTemplates(crm),\n settings: options.settings ?? {},\n updatedAt: options.now ?? Date.now(),\n };\n if (options.notificationEmail !== undefined) attrs.notificationEmail = options.notificationEmail;\n if (options.replyTo !== undefined) attrs.replyTo = options.replyTo;\n if (options.debugEmail !== undefined) attrs.debugEmail = options.debugEmail;\n return {\n ...crmIntegration,\n seeds: [{\n id: \"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ACE;AAAA,MACF,QAAQ;AAAA,MACR,QAAQ;AAAA,MACR,QAAQ;AAAA,IACV;AAAA,EACF;AAAA,EACA,SAAS,CAAC;AAAA,EACV,QAAQ;AAAA,EACR,OAAO;AAAA,EACP,WAAW;AAAA,IACT,OAAO;AAAA,MACL;AAAA,MACA;AAAA,IACF;AAAA,IACA,KAAK;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,QAAQ;AAAA,MACN;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,IACA,OAAO;AAAA,MACL;AAAA,IACF;AAAA,EACF;AACF;AASO,SAAS,qBACd,KACA,UAAiC,CAAC,GACR;AAC1B,QAAM,WAAW,QAAQ,YAAY;AACrC,MAAI,CAAC,sCAAsC,KAAK,QAAQ,KAAK,SAAS,SAAS,GAAG,GAAG;AACnF,UAAM,IAAI,MAAM,kFAAkF;AAAA,EACpG;AACA,QAAM,QAAiC;AAAA,IACrC,gBAAgB,iBAAiB,GAAG;AAAA,IACpC,UAAU,QAAQ,YAAY,CAAC;AAAA,IAC/B,WAAW,QAAQ,OAAO,KAAK,IAAI;AAAA,EACrC;AACA,MAAI,QAAQ,sBAAsB,OAAW,OAAM,oBAAoB,QAAQ;AAC/E,MAAI,QAAQ,YAAY,OAAW,OAAM,UAAU,QAAQ;AAC3D,MAAI,QAAQ,eAAe,OAAW,OAAM,aAAa,QAAQ;AACjE,SAAO;AAAA,IACL,GAAG;AAAA,IACH,OAAO,CAAC;AAAA,MACN,IAAI;AAAA,MACJ,IAAI,OAAO;AAAA,MACX,KAAK,EAAE,MAAM,OAAO,OAAO,WAAW;AAAA,MACtC;AAAA,IACF,CAAC;AAAA,IACD,QAAQ,CAAC,EAAE,MAAM,GAAG,QAAQ,YAAY,gBAAgB,IAAI,CAAC;AAAA,EAC/D;AACF;","names":["search","search","token"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/schema.ts","../src/rules.ts","../src/errors.ts","../src/pipeline.ts","../src/template.ts","../src/field-conditions.ts","../src/validate.ts","../src/config.ts","../src/discussion-reference.ts","../src/deps.ts","../src/query.ts","../src/rank.ts","../src/consent.ts","../src/channels.ts","../src/write-ops.ts","../src/records.ts","../src/stage-rank.ts","../src/tags-links.ts","../src/provenance.ts","../src/activities.ts","../src/views.ts","../src/config-store.ts","../src/email.ts","../src/facets/identity.ts","../src/summary.ts","../src/http.ts","../src/routes/params.ts","../src/routes/activities.ts","../src/routes/actions.ts","../src/routes/records.ts","../src/routes/misc.ts","../src/routes/discussion-references.ts","../src/routes/index.ts","../src/client.ts","../src/descriptor.ts"],"sourcesContent":["// @odla-ai/crm — flexible records, pipelines, follow-ups, consent-gated\n// email, and saved views on odla-db. The db client and email transport are\n// injected structurally. One runtime dependency: @marcbachmann/cel-js, which\n// evaluates conditional-form-field conditions in the same language odla-db\n// permission rules use. UI components live under the separate\n// \"@odla-ai/crm/ui\" entry (browser-only).\nexport {\n CRM_NS,\n CRM_SLOTS,\n CONSENT_STATES,\n EMAIL_STATUSES,\n ACTIVITY_KINDS,\n TASK_STATUSES,\n SORTABLE_COLUMNS,\n CONFIG_KEY,\n DEFAULT_LIMIT,\n MAX_LIMIT,\n type CrmSlot,\n type ConsentState,\n type EmailStatus,\n type ActivityKind,\n type TaskStatus,\n} from \"./constants\";\nexport {\n CRM_SCHEMA,\n type AttrType,\n type SerializedAttr,\n type SerializedEntity,\n type SerializedLink,\n type SerializedLinkEnd,\n type SerializedSchema,\n} from \"./schema\";\nexport { CRM_RULES, crmRules, type CrmRule, type CrmRules } from \"./rules\";\nexport type {\n CrmScalar,\n CrmLookup,\n CrmEntityRef,\n CrmAttrs,\n CrmOp,\n CrmQuery,\n CrmRow,\n CrmResult,\n CrmAggregateSpec,\n CrmAggregateResult,\n CrmDb,\n CrmEmailSender,\n CrmRecord,\n CrmTag,\n CrmLink,\n CrmActivity,\n CrmContactChannel,\n CrmEmailLogRow,\n CrmView,\n StoredTemplate,\n CrmConfigRow,\n CrmRecordOrigin,\n CrmRecordDelivery,\n PreparedWrite,\n} from \"./types\";\nexport {\n defineCrm,\n composeCrmConfigs,\n type Crm,\n type CrmConfig,\n type TypeDef,\n type TypeFacets,\n type FieldDef,\n type FieldType,\n type PipelineDef,\n type StageDef,\n type RelationDef,\n type TemplateSpec,\n} from \"./config\";\nexport { initialStage, stageIndexOf, canTransition } from \"./pipeline\";\nexport { prepare, searchTextFor } from \"./validate\";\nexport { CrmInputError, CrmNotFoundError } from \"./errors\";\nexport {\n CRM_DISCUSSION_REFERENCE_KINDS,\n crmDiscussionReferenceHref,\n crmDiscussionReferenceId,\n formatCrmDiscussionReference,\n parseCrmDiscussionReference,\n type CrmDiscussionReference,\n type CrmDiscussionReferenceKind,\n type CrmDiscussionReferenceTarget,\n} from \"./discussion-reference\";\nexport { type CrmDeps, resolveDeps } from \"./deps\";\nexport {\n compileList,\n resolveSortColumn,\n type CompiledList,\n type CrmListParams,\n type CrmSort,\n type FieldFilter,\n type ViewFilters,\n} from \"./query\";\nexport { RANK_STEP, RANK_EPSILON, rankBetween, needsRebalance, rebalancePlan } from \"./rank\";\nexport {\n applyConsentEvent,\n canEmail,\n type ConsentEvent,\n type ConsentOutcome,\n} from \"./consent\";\nexport { renderTemplate, templateVars, lintTemplate } from \"./template\";\nexport {\n getRecord,\n mustGetRecord,\n listRecords,\n createRecord,\n updateRecord,\n setArchived,\n rowToRecord,\n} from \"./records\";\nexport { setStage, setRank, rebalanceRanks } from \"./stage-rank\";\nexport {\n addTag,\n removeTag,\n listTags,\n addLink,\n removeLink,\n listLinks,\n normalizeTag,\n} from \"./tags-links\";\nexport {\n recordOriginKey,\n getRecordOrigin,\n getRecordByOrigin,\n upsertRecordOrigin,\n listRecordOrigins,\n recordDeliveryKey,\n recordDeliveryAttempt,\n listRecordDeliveries,\n} from \"./provenance\";\nexport {\n addActivity,\n updateTask,\n listActivities,\n listTasks,\n} from \"./activities\";\nexport {\n channelKey,\n foldEmailStatus,\n listChannels,\n emailChannelOps,\n applyConsent,\n} from \"./channels\";\nexport {\n saveView,\n updateView,\n deleteView,\n listViews,\n type ViewSpec,\n} from \"./views\";\nexport {\n getConfig,\n saveConfig,\n defaultTemplates,\n type ConfigPatch,\n} from \"./config-store\";\nexport {\n sendTemplatedEmail,\n listEmailLog,\n recordCanEmail,\n type SendEmailOpts,\n type SendEmailResult,\n} from \"./email\";\nexport { linkIdentity } from \"./facets/identity\";\nexport { typeSummary, type TypeSummary } from \"./summary\";\nexport type {\n BillingEvent,\n BillingProvider,\n SubscriptionSnapshot,\n} from \"./billing/port\";\nexport {\n createCrmRoutes,\n type CrmActor,\n type CrmDiscussionReferenceActor,\n type CrmRouteOpts,\n} from \"./routes/index\";\nexport { CrmClient, type CrmClientOptions } from \"./client\";\nexport {\n crmIntegration,\n createCrmIntegration,\n type CrmIntegrationDescriptor,\n type CrmIntegrationOptions,\n type CrmIntegrationProbe,\n type CrmIntegrationSeed,\n} from \"./descriptor\";\n\nexport {\n assertFieldCondition,\n evaluateFieldCondition,\n resolveFieldState,\n resolveFieldStates,\n} from \"./field-conditions\";\nexport type { FieldCondition, FieldConditions, FieldState } from \"./field-conditions\";\n","/** The odla-db namespaces @odla-ai/crm installs and writes. */\nexport const CRM_NS = {\n record: \"crm_record\",\n tag: \"crm_tag\",\n link: \"crm_link\",\n activity: \"crm_activity\",\n channel: \"crm_contact_channel\",\n emailLog: \"crm_email_log\",\n view: \"crm_view\",\n config: \"crm_config\",\n origin: \"crm_record_origin\",\n delivery: \"crm_record_delivery\",\n} as const;\n\n/** Generic promoted columns a type's custom fields can claim for indexed\n * sort/filter: four strings, three numbers, two dates. Slots are per-type\n * virtual — every slot query is ANDed with `type`, so \"person.n1\" and\n * \"company.n1\" can mean different fields. */\nexport const CRM_SLOTS = [\"s1\", \"s2\", \"s3\", \"s4\", \"n1\", \"n2\", \"n3\", \"d1\", \"d2\"] as const;\n/** One generic promoted column a field can claim. */\nexport type CrmSlot = (typeof CRM_SLOTS)[number];\n\n/** Consent state of a contact channel (see `applyConsentEvent`). */\nexport const CONSENT_STATES = [\"subscribed\", \"unsubscribed\", \"bounced\", \"suppressed\"] as const;\n/** A contact channel's consent standing. */\nexport type ConsentState = (typeof CONSENT_STATES)[number];\n\n/** Denormalized per-record contactability, folded from the primary email\n * channel so list views can filter/sort on it: `none` = no email channel. */\nexport const EMAIL_STATUSES = [\"ok\", \"unsubscribed\", \"bounced\", \"suppressed\", \"none\"] as const;\n/** The record-level contactability fold. */\nexport type EmailStatus = (typeof EMAIL_STATUSES)[number];\n\n/** Activity kinds; `task` rows additionally carry status/dueAt/waitingOn. */\nexport const ACTIVITY_KINDS = [\"note\", \"task\", \"call\", \"meeting\", \"stage_change\", \"system\"] as const;\n/** What kind of feed entry an activity row is. */\nexport type ActivityKind = (typeof ACTIVITY_KINDS)[number];\n\n/** Task lifecycle for `kind: \"task\"` activities. */\nexport const TASK_STATUSES = [\"open\", \"waiting\", \"done\"] as const;\n/** Where a follow-up task stands. */\nexport type TaskStatus = (typeof TASK_STATUSES)[number];\n\n/** Promoted `crm_record` columns list queries may sort on, beyond per-type\n * slot fields. All are indexed in the schema — odla-db orders on exactly one\n * indexed field per query. */\nexport const SORTABLE_COLUMNS = [\n \"name\",\n \"primaryEmail\",\n \"stageIndex\",\n \"stageChangedAt\",\n \"rank\",\n \"score\",\n \"emailStatus\",\n \"billingStatus\",\n \"renewalAt\",\n \"createdAt\",\n \"updatedAt\",\n] as const;\n\n/** Record field names owned by the engine — type configs may not redefine\n * them as custom fields. */\nexport const RESERVED_FIELDS = new Set([\n \"id\",\n \"type\",\n \"primaryEmail\",\n \"stage\",\n \"stageIndex\",\n \"stageChangedAt\",\n \"rank\",\n \"score\",\n \"ownerId\",\n \"emailStatus\",\n \"clerkUserId\",\n \"stripeCustomerId\",\n \"subscriptionId\",\n \"billingStatus\",\n \"renewalAt\",\n \"mrr\",\n \"fields\",\n \"searchText\",\n \"archived\",\n \"createdAt\",\n \"updatedAt\",\n \"archivedAt\",\n ...CRM_SLOTS,\n]);\n\n/** The singleton `crm_config` row's natural key. */\nexport const CONFIG_KEY = \"default\";\n\n/** Server list-window defaults, aligned with odla-db's query limits\n * (default 100, max 1000). */\nexport const DEFAULT_LIMIT = 50;\n/** Hard per-window row cap for list routes (odla-db allows up to 1000). */\nexport const MAX_LIMIT = 200;\n","// The odla-db schema @odla-ai/crm installs (POST to `/app/:id/schema` as\n// `{ schema: CRM_SCHEMA }`). Ships pre-serialized (the wire shape) so\n// provisioning needs no schema-builder dependency, mirroring @odla-ai/chat.\n//\n// Design note: record types are DATA, not schema. All types share one\n// `crm_record` namespace — promoted columns cover the hot paths every type\n// has (name, stage, rank, contactability, billing cache), nine generic typed\n// slots (s1–s4/n1–n3/d1–d2) carry each type's custom sortable fields, and the\n// complete field payload lives in the `fields` json (slots are an index\n// mirror, never the source of truth). `searchText` is a denormalized FTS\n// haystack rebuilt on every write. Tags and record↔record links are join\n// rows with natural keys (idempotent upserts) because rules/queries have no\n// array-contains, and schema links are label-static while CRM relations are\n// config-declared.\nimport { CRM_NS } from \"./constants\";\n\n/** Wire-shape attribute value kinds odla-db stores. */\nexport type AttrType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"json\";\n/** One serialized attribute: its type and index/uniqueness flags. */\nexport interface SerializedAttr {\n type: AttrType;\n unique: boolean;\n indexed: boolean;\n optional: boolean;\n}\n/** One serialized namespace: its attribute map. */\nexport interface SerializedEntity {\n attrs: Record<string, SerializedAttr>;\n}\n/** One end of a serialized schema link. */\nexport interface SerializedLinkEnd {\n on: string;\n has: \"one\" | \"many\";\n label: string;\n}\n/** A serialized schema link (unused by crm — relations are rows). */\nexport interface SerializedLink {\n forward: SerializedLinkEnd;\n reverse: SerializedLinkEnd;\n}\n/** The wire-shape schema POSTed to `/app/:id/schema`. */\nexport interface SerializedSchema {\n entities: Record<string, SerializedEntity>;\n links: Record<string, SerializedLink>;\n}\n\ntype Opt = Partial<Omit<SerializedAttr, \"type\">>;\nconst a = (type: AttrType, o: Opt = {}): SerializedAttr => ({\n type,\n unique: false,\n indexed: false,\n optional: false,\n ...o,\n});\nconst uniq = (type: AttrType): SerializedAttr => a(type, { unique: true, indexed: true });\nconst idx = (type: AttrType, optional = false): SerializedAttr => a(type, { indexed: true, optional });\nconst opt = (type: AttrType): SerializedAttr => a(type, { optional: true });\n\n/**\n * The pre-serialized (wire-shape) odla-db schema for the ten crm\n * namespaces; POST it to `/app/:id/schema` as `{ schema: CRM_SCHEMA }`.\n * One generic `crm_record` holds every record type (the type registry is\n * app config, not schema); natural-key uniqueness on tags, links, channels,\n * and the config row makes those writes idempotent upserts.\n */\nexport const CRM_SCHEMA: SerializedSchema = {\n entities: {\n [CRM_NS.record]: {\n attrs: {\n // Entity ids are not attributes in odla-db, so `where: { id }` matches\n // nothing unless the id is mirrored as a written attr — the getRecord /\n // tag-filter / neighbor reads all filter by id. Mirror it as unique.\n id: uniq(\"string\"),\n type: idx(\"string\"),\n name: idx(\"string\"),\n primaryEmail: idx(\"string\", true),\n stage: idx(\"string\", true),\n stageIndex: idx(\"number\", true),\n stageChangedAt: idx(\"date\", true),\n rank: idx(\"number\", true),\n score: idx(\"number\", true),\n ownerId: idx(\"string\", true),\n emailStatus: idx(\"string\", true),\n clerkUserId: a(\"string\", { unique: true, indexed: true, optional: true }),\n stripeCustomerId: idx(\"string\", true),\n subscriptionId: opt(\"string\"),\n billingStatus: idx(\"string\", true),\n renewalAt: idx(\"date\", true),\n mrr: opt(\"number\"),\n s1: idx(\"string\", true),\n s2: idx(\"string\", true),\n s3: idx(\"string\", true),\n s4: idx(\"string\", true),\n n1: idx(\"number\", true),\n n2: idx(\"number\", true),\n n3: idx(\"number\", true),\n d1: idx(\"date\", true),\n d2: idx(\"date\", true),\n fields: a(\"json\"),\n searchText: a(\"string\"),\n archived: idx(\"boolean\"),\n createdAt: idx(\"date\"),\n updatedAt: idx(\"date\"),\n archivedAt: opt(\"date\"),\n },\n },\n [CRM_NS.tag]: {\n attrs: {\n key: uniq(\"string\"), // `${recordId}:${tag}`\n recordId: idx(\"string\"),\n tag: idx(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.link]: {\n attrs: {\n key: uniq(\"string\"), // `${fromId}:${relation}:${toId}`\n fromId: idx(\"string\"),\n toId: idx(\"string\"),\n relation: idx(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.activity]: {\n attrs: {\n id: uniq(\"string\"), // mirrored so updateTask can read one by id\n recordId: idx(\"string\"),\n kind: idx(\"string\"),\n body: a(\"string\"),\n status: idx(\"string\", true), // tasks: open | waiting | done\n dueAt: idx(\"date\", true),\n waitingOn: opt(\"string\"),\n assigneeId: idx(\"string\", true),\n authorId: idx(\"string\"),\n createdAt: idx(\"date\"),\n completedAt: opt(\"date\"),\n meta: opt(\"json\"),\n },\n },\n [CRM_NS.channel]: {\n attrs: {\n key: uniq(\"string\"), // `${recordId}:${kind}:${value}`\n recordId: idx(\"string\"),\n kind: a(\"string\"), // email | phone\n value: idx(\"string\"), // emails lowercased\n isPrimary: a(\"boolean\"),\n consent: idx(\"string\"),\n consentAt: idx(\"date\"),\n consentSource: opt(\"string\"),\n unsubscribeToken: uniq(\"string\"),\n createdAt: idx(\"date\"),\n },\n },\n [CRM_NS.emailLog]: {\n attrs: {\n recordId: idx(\"string\", true),\n channelId: opt(\"string\"),\n to: a(\"string\"),\n templateId: idx(\"string\"),\n subject: a(\"string\"),\n transport: a(\"string\"), // sent | log-only\n redirected: opt(\"boolean\"),\n dedupeKey: idx(\"string\", true),\n messageId: opt(\"string\"),\n error: opt(\"string\"),\n sentAt: idx(\"date\"),\n },\n },\n [CRM_NS.view]: {\n attrs: {\n id: uniq(\"string\"), // mirrored so getView/updateView can read one by id\n name: a(\"string\"),\n type: idx(\"string\"),\n ownerId: idx(\"string\", true),\n shared: idx(\"boolean\"),\n filters: a(\"json\"),\n sort: a(\"json\"),\n columns: a(\"json\"),\n createdAt: idx(\"date\"),\n updatedAt: idx(\"date\"),\n },\n },\n [CRM_NS.config]: {\n attrs: {\n key: uniq(\"string\"), // CONFIG_KEY singleton\n notificationEmail: opt(\"string\"),\n replyTo: opt(\"string\"),\n debugEmail: opt(\"string\"),\n emailTemplates: a(\"json\"), // Record<templateId, {subject, text, enabled}>\n settings: a(\"json\"),\n updatedAt: idx(\"date\"),\n },\n },\n [CRM_NS.origin]: {\n attrs: {\n // One upstream record maps to one local record. The structured source\n // survives tag edits and supports more than one upstream site.\n key: uniq(\"string\"), // `${sourceId}:${sourceRecordId}`\n recordId: idx(\"string\"),\n sourceId: idx(\"string\"),\n sourceRecordId: idx(\"string\"),\n sourceUrl: opt(\"string\"),\n payloadVersion: idx(\"number\"),\n firstReceivedAt: idx(\"date\"),\n lastReceivedAt: idx(\"date\"),\n },\n },\n [CRM_NS.delivery]: {\n attrs: {\n // The latest delivery state for one local record → target edge.\n key: uniq(\"string\"), // `${recordId}:${targetId}`\n recordId: idx(\"string\"),\n targetId: idx(\"string\"),\n remoteRecordId: idx(\"string\", true),\n status: idx(\"string\"),\n attempts: idx(\"number\"),\n payloadVersion: idx(\"number\"),\n lastAttemptAt: idx(\"date\"),\n deliveredAt: idx(\"date\", true),\n error: opt(\"string\"),\n },\n },\n },\n links: {},\n};\n","// Default-deny CEL rules for the crm namespaces (POST to `/app/:id/admin/rules`).\n//\n// CRM access is worker-mediated BY DESIGN: slot mapping, searchText rebuild,\n// pipeline gates, and field validation are functions of the app's crm config\n// and cannot be expressed in CEL, so every crm_* namespace is closed to\n// end-user credentials and all reads/writes flow through `createCrmRoutes`\n// running with the app's admin key (which bypasses rules).\nimport { CRM_NS } from \"./constants\";\n\n/** Per-namespace CEL rule strings (missing action = deny). */\nexport interface CrmRule {\n view?: string;\n create?: string;\n update?: string;\n delete?: string;\n}\n/** Namespace → rule set, as installed at `/app/:id/admin/rules`. */\nexport type CrmRules = Record<string, CrmRule>;\n\nconst DENY: CrmRule = { view: \"false\", create: \"false\", update: \"false\", delete: \"false\" };\n\n/**\n * Deny-all rules for every crm namespace; install at `/app/:id/admin/rules`.\n * The route factory (admin key) is the only door — see the header note for\n * why the CRM cannot be rule-governed client-side.\n */\nexport const CRM_RULES: CrmRules = Object.fromEntries(\n Object.values(CRM_NS).map((ns) => [ns, { ...DENY }]),\n);\n\n/**\n * Rules factory, mirroring `chatRules()`. Today it returns the deny-all set;\n * it exists so a future member-facing surface (e.g. \"records I own are\n * visible to me\") can widen specific namespaces without apps changing their\n * provisioning call shape.\n */\nexport function crmRules(): CrmRules {\n return Object.fromEntries(Object.entries(CRM_RULES).map(([ns, r]) => [ns, { ...r }]));\n}\n","/** Caller-fault error (bad type, unknown field, blocked transition…) — the\n * route layer maps it to a 400. `fields` carries per-field messages when the\n * failure came from input validation. */\nexport class CrmInputError extends Error {\n readonly fields?: Record<string, string>;\n constructor(message: string, fields?: Record<string, string>) {\n super(message);\n this.name = \"CrmInputError\";\n this.fields = fields;\n }\n}\n\n/** Missing entity — the route layer maps it to a 404. */\nexport class CrmNotFoundError extends Error {\n constructor(what: string) {\n super(`${what} not found`);\n this.name = \"CrmNotFoundError\";\n }\n}\n","// Pipeline mechanics: stage order, allowed edges, and gates. Pure functions\n// of (type config, record) — the route layer applies the resulting decision.\nimport type { TypeDef } from \"./config\";\nimport { CrmInputError } from \"./errors\";\nimport type { CrmRecord } from \"./types\";\n\n/** The stage a new record of this type starts in (first declared stage). */\nexport function initialStage(def: TypeDef): string | undefined {\n return def.pipeline?.stages[0]?.id;\n}\n\n/** Position of a stage in the declared order — denormalized onto the record\n * as `stageIndex` so \"sort by pipeline position\" is a single-field order. */\nexport function stageIndexOf(def: TypeDef, stage: string): number {\n const at = (def.pipeline?.stages ?? []).findIndex((s) => s.id === stage);\n if (at === -1) throw new CrmInputError(`unknown stage \"${stage}\"`);\n return at;\n}\n\n/**\n * Why this record may not move to `to` — or null when the move is allowed.\n * Checks, in order: the type has a pipeline, the target exists, the source\n * isn't terminal (unless it declares explicit outgoing transitions), the\n * edge is allowed, and the target's gate passes.\n */\nexport function canTransition(def: TypeDef, record: CrmRecord, to: string): string | null {\n const pipeline = def.pipeline;\n if (!pipeline) return \"type has no pipeline\";\n const stages = new Map(pipeline.stages.map((s) => [s.id, s]));\n if (!stages.has(to)) return `unknown stage \"${to}\"`;\n const from = record.stage;\n if (from === to) return \"already in that stage\";\n if (from != null) {\n if (!stages.has(from)) return `record is in unknown stage \"${from}\"`;\n const declared = pipeline.transitions?.[from];\n if (declared) {\n if (!declared.includes(to)) return `cannot move from \"${from}\" to \"${to}\"`;\n } else if (stages.get(from)?.terminal) {\n return `\"${from}\" is terminal`;\n }\n }\n const gate = pipeline.gates?.[to];\n if (gate) {\n const blocked = gate(record);\n if (blocked) return blocked;\n }\n return null;\n}\n","// Owner-editable {{var}} templates (the S&S groups.emailTemplates model,\n// generalized). Rendering is deliberately dumb — plain token substitution,\n// missing vars become \"\" — and `lintTemplate` gives the admin UI a way to\n// surface typos before a send ever runs.\n\nconst TOKEN_RE = /\\{\\{\\s*([a-zA-Z][a-zA-Z0-9_]*)\\s*\\}\\}/g;\n\n/** Substitute `{{var}}` tokens from `vars`; unknown tokens render as \"\". */\nexport function renderTemplate(template: string, vars: Record<string, string>): string {\n return template.replace(TOKEN_RE, (_, name: string) => vars[name] ?? \"\");\n}\n\n/** The distinct `{{var}}` names a template references, in first-seen order. */\nexport function templateVars(template: string): string[] {\n const seen = new Set<string>();\n for (const match of template.matchAll(TOKEN_RE)) seen.add(match[1] as string);\n return [...seen];\n}\n\n/**\n * Template health check for the settings UI: which referenced vars aren't\n * in the declared contract (typos — they'd silently render as \"\"), and which\n * declared vars go unused (usually fine, occasionally a forgotten insert).\n */\nexport function lintTemplate(\n template: string,\n knownVars: readonly string[],\n): { unknown: string[]; unused: string[] } {\n const used = templateVars(template);\n const known = new Set(knownVars);\n return {\n unknown: used.filter((v) => !known.has(v)),\n unused: knownVars.filter((v) => !used.includes(v)),\n };\n}\n","// Conditional form fields: show or require a field based on the answers so far.\n//\n// The condition language is CEL — the same language odla-db permission rules\n// use — so an author who has written a rule has nothing new to learn, and we\n// maintain no parser. See the odla-ai decision \"Conditional form fields use CEL,\n// evaluated with form-rule failure semantics\".\n//\n// TWO THINGS DIFFER DELIBERATELY FROM A DB RULE.\n//\n// 1. The context is `values` only — the answers on the form. No auth, no data,\n// no ref(). We share the language, not the surface.\n// 2. A db rule that throws fails CLOSED (deny), which is right for security and\n// wrong here: it would silently hide a field an applicant needs, or demand\n// one nobody can satisfy. Form rules fail OPEN — visible, not required — and\n// the failure is a config defect to surface, not a decision to honour.\nimport { Environment, ParseError } from \"@marcbachmann/cel-js\";\n\n/** A CEL expression over `values`, e.g. `values.country == \"US\"`. */\nexport type FieldCondition = string;\n\n/** Conditions a field declaration may carry. */\nexport interface FieldConditions {\n /** Render the field only while this holds. Absent means always visible. */\n visibleWhen?: FieldCondition;\n /** Demand a value only while this holds. Absent means the static `required`. */\n requiredWhen?: FieldCondition;\n}\n\n/** Whether a field should be shown, and whether it must be answered. */\nexport interface FieldState {\n visible: boolean;\n required: boolean;\n}\n\n// A fresh environment rather than the Durable Object's: that one binds ref()\n// through a module-level slot, which is only safe because a DO is\n// single-threaded. Nothing here needs ref(), so nothing here needs that risk.\nconst env = new Environment({ unlistedVariablesAreDyn: true });\n\n/**\n * Reject an unparseable condition at config time.\n *\n * Called while a chapter or CRM config is being resolved, so a typo is a build\n * error rather than a field that quietly misbehaves on a live join page.\n *\n * @throws Error naming the field and the parse failure.\n */\nexport function assertFieldCondition(expression: string, label: string): void {\n try {\n env.evaluate(expression, { values: {} });\n } catch (error) {\n // A runtime failure against empty values is expected and fine — the\n // expression may reference answers that do not exist yet. Only a genuine\n // parse failure means the author wrote something that can never work.\n if (error instanceof ParseError) {\n throw new Error(`${label}: not a valid CEL condition — ${error.message}`);\n }\n }\n}\n\n// Every `values.<name>` an expression mentions. Used to give unanswered fields\n// a value instead of letting CEL raise a missing-key error for them.\nconst REFERENCED = /\\bvalues\\.([A-Za-z_][A-Za-z0-9_]*)/g;\n\n/**\n * Evaluate one condition against the current answers.\n *\n * An unanswered field reads as the empty string rather than raising. That\n * matters more than it sounds: on first paint nothing is answered, so without\n * it every condition would error at once and each conditional field would\n * flash into view before vanishing. It also makes conditions read the way an\n * author expects — `values.country == \"US\"` is false before anyone has picked\n * a country, and `values.country != \"US\"` is true — with no `has()` ceremony.\n *\n * A genuinely unevaluable expression yields `fallback`. Those are rare by\n * construction, because {@link assertFieldCondition} rejects unparseable\n * conditions when the config is resolved.\n */\nexport function evaluateFieldCondition(\n expression: FieldCondition,\n values: Record<string, unknown>,\n fallback: boolean,\n): boolean {\n const unanswered: Record<string, unknown> = {};\n for (const [, name] of expression.matchAll(REFERENCED)) {\n if (name !== undefined && !(name in values)) unanswered[name] = \"\";\n }\n try {\n return env.evaluate(expression, { values: { ...unanswered, ...values } }) === true;\n } catch {\n return fallback;\n }\n}\n\n/**\n * Resolve a field's live state from its conditions and the answers so far.\n *\n * `staticRequired` is the field's unconditional requiredness, used when it\n * declares no `requiredWhen`. A field that is not visible is never required —\n * demanding an answer to a question nobody was asked is unsatisfiable.\n */\nexport function resolveFieldState(\n conditions: FieldConditions | undefined,\n values: Record<string, unknown>,\n staticRequired = false,\n): FieldState {\n const visible = conditions?.visibleWhen === undefined\n ? true\n : evaluateFieldCondition(conditions.visibleWhen, values, true);\n if (!visible) return { visible: false, required: false };\n const required = conditions?.requiredWhen === undefined\n ? staticRequired\n : evaluateFieldCondition(conditions.requiredWhen, values, false);\n return { visible, required };\n}\n\n/** Resolve every declared field at once, for a renderer or a validator. */\nexport function resolveFieldStates(\n conditions: Readonly<Record<string, FieldConditions>>,\n values: Record<string, unknown>,\n staticRequired: readonly string[] = [],\n): Record<string, FieldState> {\n const required = new Set(staticRequired);\n const out: Record<string, FieldState> = {};\n for (const field of new Set([...Object.keys(conditions), ...required])) {\n out[field] = resolveFieldState(conditions[field], values, required.has(field));\n }\n return out;\n}\n","// Input validation + coercion for record writes. `prepare` is the single\n// enforcement point (all writes are worker-mediated): it maps config fields\n// onto the promoted columns, mirrors slotted values, and rebuilds the FTS\n// haystack — returning either the exact attrs to write or per-field errors.\nimport type { FieldDef, TypeDef } from \"./config\";\nimport type { CrmAttrs, CrmRecord, PreparedWrite } from \"./types\";\n\nconst EMAIL_RE = /^[^\\s@]+@[^\\s@]+\\.[^\\s@]+$/;\nconst STRINGISH: ReadonlySet<string> = new Set([\"string\", \"email\", \"url\", \"enum\"]);\n\ntype Coerced = { ok: true; value: unknown } | { ok: false; error: string };\nconst bad = (error: string): Coerced => ({ ok: false, error });\nconst good = (value: unknown): Coerced => ({ ok: true, value });\n\nfunction coerce(def: FieldDef, raw: unknown): Coerced {\n if (raw === null) return good(null);\n switch (def.type) {\n case \"string\":\n return typeof raw === \"string\" ? good(raw.trim()) : bad(\"expected a string\");\n case \"email\": {\n if (typeof raw !== \"string\") return bad(\"expected an email address\");\n const email = raw.trim().toLowerCase();\n return EMAIL_RE.test(email) ? good(email) : bad(\"not a valid email address\");\n }\n case \"url\": {\n if (typeof raw !== \"string\") return bad(\"expected a URL\");\n const url = raw.trim();\n try {\n const parsed = new URL(url);\n if (parsed.protocol !== \"http:\" && parsed.protocol !== \"https:\")\n return bad(\"must be an http(s) URL\");\n return good(url);\n } catch {\n return bad(\"not a valid URL\");\n }\n }\n case \"number\":\n return typeof raw === \"number\" && Number.isFinite(raw) ? good(raw) : bad(\"expected a number\");\n case \"boolean\":\n return typeof raw === \"boolean\" ? good(raw) : bad(\"expected true or false\");\n case \"date\": {\n if (typeof raw === \"number\" && Number.isFinite(raw)) return good(raw);\n if (typeof raw === \"string\") {\n const t = Date.parse(raw);\n if (!Number.isNaN(t)) return good(t);\n }\n return bad(\"expected epoch ms or an ISO date string\");\n }\n case \"enum\":\n return typeof raw === \"string\" && (def.options ?? []).includes(raw)\n ? good(raw)\n : bad(`expected one of: ${(def.options ?? []).join(\", \")}`);\n case \"json\":\n return raw === undefined ? bad(\"expected a value\") : good(raw);\n }\n}\n\nconst empty = (def: FieldDef, value: unknown): boolean =>\n value == null || (STRINGISH.has(def.type) && value === \"\");\n\n/** The FTS haystack: name + email + every searchable field value, lowercased.\n * String-ish fields are searchable by default; other types opt in with\n * `search: true`. Exported for the write paths that must rebuild it. */\nexport function searchTextFor(def: TypeDef, name: string, email: string | null, fields: Record<string, unknown>): string {\n const parts: string[] = [name];\n if (email) parts.push(email);\n for (const [fieldName, field] of Object.entries(def.fields)) {\n // The name/email fields already contributed via the promoted columns.\n if (fieldName === (def.nameField ?? \"name\") || fieldName === def.emailField) continue;\n const searchable = field.search ?? STRINGISH.has(field.type);\n const value = fields[fieldName];\n if (searchable && value != null && value !== \"\") parts.push(String(value));\n }\n return parts.join(\" \").toLowerCase();\n}\n\n/**\n * Validate + coerce `input` (keyed by config field name) for one type.\n * Create (no `existing`): required fields must be present, and the\n * `nameField` always (a record without a name is unlistable). Update:\n * partial — unnamed fields keep their stored values. On success returns the\n * columns to write — promoted `name`, `primaryEmail` and each claimed slot\n * that has a value, the complete `fields` json (source of truth), and the\n * rebuilt `searchText` — plus `retract`, the columns whose field went empty\n * (odla-db can't store a scalar null, so an empty column is omitted on create\n * and retracted on update). Otherwise `{ ok: false, errors }` keyed by field.\n */\nexport function prepare(\n def: TypeDef,\n input: Record<string, unknown>,\n existing?: CrmRecord,\n): PreparedWrite {\n const errors: Record<string, string> = {};\n for (const key of Object.keys(input))\n if (!def.fields[key]) errors[key] = \"unknown field\";\n\n const fields: Record<string, unknown> = { ...(existing?.fields ?? {}) };\n for (const [fieldName, field] of Object.entries(def.fields)) {\n const supplied = Object.hasOwn(input, fieldName);\n if (supplied) {\n const coerced = coerce(field, input[fieldName]);\n if (!coerced.ok) {\n errors[fieldName] = coerced.error;\n continue;\n }\n fields[fieldName] = coerced.value;\n }\n const settled = fields[fieldName];\n if (field.required && (existing ? supplied || !(fieldName in fields) : true) && empty(field, settled))\n errors[fieldName] = errors[fieldName] ?? \"required\";\n }\n\n const nameField = def.nameField ?? \"name\";\n const name = fields[nameField];\n if (typeof name !== \"string\" || name === \"\") errors[nameField] = errors[nameField] ?? \"required\";\n\n let primaryEmail: string | null = null;\n if (def.emailField) {\n const email = fields[def.emailField];\n primaryEmail = typeof email === \"string\" && email !== \"\" ? email : null;\n }\n\n if (Object.keys(errors).length > 0) return { ok: false, errors };\n\n const attrs: CrmAttrs = {\n name: name as string,\n fields,\n searchText: searchTextFor(def, name as string, primaryEmail, fields),\n };\n // odla-db has no storable scalar null: a promoted column / slot is either\n // WRITTEN with a value or CLEARED (its triple retracted). On update we retract\n // the ones that went empty so the index mirror can't go stale; on create there\n // is nothing to clear, so an empty column is simply omitted.\n const retract: string[] = [];\n const clear = (column: string) => {\n if (existing) retract.push(column);\n };\n if (def.emailField) {\n if (primaryEmail === null) clear(\"primaryEmail\");\n else attrs.primaryEmail = primaryEmail;\n }\n for (const [fieldName, field] of Object.entries(def.fields)) {\n if (!field.slot) continue;\n const value = fields[fieldName];\n if (empty(field, value)) clear(field.slot);\n else attrs[field.slot] = value;\n }\n return { ok: true, attrs, retract };\n}\n","// The app-facing configuration surface: record types are DATA layered over\n// the fixed CRM_SCHEMA. `defineCrm` validates the whole config at boot —\n// slot collisions, enum/slot type agreement, pipeline edges — so a bad\n// config fails at startup, never at request time.\nimport { CRM_SLOTS, RESERVED_FIELDS, type CrmSlot } from \"./constants\";\nimport { CrmInputError } from \"./errors\";\nimport { CRM_SCHEMA, type SerializedSchema } from \"./schema\";\nimport { CRM_RULES, type CrmRules } from \"./rules\";\nimport { canTransition, initialStage, stageIndexOf } from \"./pipeline\";\nimport { lintTemplate } from \"./template\";\nimport { assertFieldCondition, type FieldCondition } from \"./field-conditions\";\nimport { prepare } from \"./validate\";\nimport type { CrmRecord, PreparedWrite } from \"./types\";\n\n/** Value kinds a custom field can hold. `email`/`url`/`enum` are validated\n * strings; `date` accepts epoch ms or ISO strings and stores epoch ms. */\nexport type FieldType = \"string\" | \"number\" | \"boolean\" | \"date\" | \"email\" | \"url\" | \"enum\" | \"json\";\n\n/** One custom field of a record type: value kind, validation, slot promotion. */\nexport interface FieldDef {\n type: FieldType;\n label?: string;\n required?: boolean;\n /** Allowed values — `enum` fields only. */\n options?: readonly string[];\n /** Promote to an indexed slot column for server-side sort/filter. String-ish\n * fields take `s1`–`s4`, numbers `n1`–`n3`, dates `d1`–`d2`. */\n slot?: CrmSlot;\n /** Include in the FTS haystack. Defaults to true for string-ish fields. */\n search?: boolean;\n /** Show this field only while the CEL condition holds, e.g.\n * `values.country == \"US\"`. Absent means always visible. */\n visibleWhen?: FieldCondition;\n /** Demand a value only while the CEL condition holds. Absent falls back to\n * `required`. A hidden field is never required. */\n requiredWhen?: FieldCondition;\n}\n\n/** One pipeline stage; declaration order is the sort order (`stageIndex`). */\nexport interface StageDef {\n id: string;\n label?: string;\n /** Terminal stages have no outgoing transitions unless `transitions`\n * explicitly declares some. */\n terminal?: boolean;\n}\n\n/** A type's stage machine: ordered stages, allowed edges, gates. */\nexport interface PipelineDef {\n stages: readonly StageDef[];\n /** Allowed edges per stage id. A stage with no entry accepts any move\n * (unless terminal). */\n transitions?: Record<string, readonly string[]>;\n /** Per-target-stage gate: return an error string to block, null to allow. */\n gates?: Record<string, (record: CrmRecord) => string | null>;\n}\n\n/** Opt-in built-in concerns for a type (identity/billing/email/rank). */\nexport interface TypeFacets {\n identity?: boolean;\n billing?: boolean;\n email?: boolean;\n rank?: \"manual\" | \"score\" | \"both\";\n}\n\n/** One record type: its fields, pipeline, facets, and hooks. */\nexport interface TypeDef {\n label: string;\n labelPlural?: string;\n /** Optional admin collection group. Hosts can keep people and portfolio\n * records in separate workspaces without moving either outside the CRM. */\n workspace?: string;\n /** Field mapped to the promoted `name` column. Default `\"name\"`. */\n nameField?: string;\n /** `email`-typed field mapped to `primaryEmail` (lowercased) and backed by\n * a consent-bearing contact channel. */\n emailField?: string;\n fields: Record<string, FieldDef>;\n pipeline?: PipelineDef;\n facets?: TypeFacets;\n /** Computes the record's `score` column (rank facet \"score\"/\"both\"). */\n scorer?: (record: CrmRecord) => number;\n /** Post-commit hooks per target stage id — e.g. S&S \"approved\" promotes the\n * member's Clerk role. Fired by the route layer AFTER the stage write. */\n onTransition?: Record<string, (record: CrmRecord) => void | Promise<void>>;\n}\n\n/** A typed record↔record relation (e.g. person works_at company). */\nexport interface RelationDef {\n from: string;\n to: string;\n label: string;\n reverseLabel?: string;\n}\n\n/** Declares a template's contract in code: its variables and its consent\n * CLASS. Subject/body/enabled live on the data row (owner-editable). */\nexport interface TemplateSpec {\n vars: readonly string[];\n class: \"transactional\" | \"marketing\";\n defaults?: { subject: string; text: string };\n}\n\n/** The whole app-level CRM configuration `defineCrm` validates. */\nexport interface CrmConfig {\n types: Record<string, TypeDef>;\n relations?: Record<string, RelationDef>;\n templates?: Record<string, TemplateSpec>;\n}\n\n/** The resolved engine `defineCrm` returns: static schema/rules plus the\n * config-aware operations the route factory and ops modules run on. */\nexport interface Crm {\n config: CrmConfig;\n schema: SerializedSchema;\n rules: CrmRules;\n type(name: string): TypeDef;\n prepare(type: string, input: Record<string, unknown>, existing?: CrmRecord): PreparedWrite;\n canTransition(type: string, record: CrmRecord, to: string): string | null;\n initialStage(type: string): string | undefined;\n stageIndex(type: string, stage: string): number;\n}\n\nconst NAME_RE = /^[a-z][a-z0-9_-]*$/;\nconst FIELD_RE = /^[a-z][a-zA-Z0-9_]*$/; // camelCase welcome; no spaces/dashes\nconst SLOT_KIND: Record<CrmSlot, FieldType[]> = {\n s1: [\"string\", \"email\", \"url\", \"enum\"],\n s2: [\"string\", \"email\", \"url\", \"enum\"],\n s3: [\"string\", \"email\", \"url\", \"enum\"],\n s4: [\"string\", \"email\", \"url\", \"enum\"],\n n1: [\"number\"],\n n2: [\"number\"],\n n3: [\"number\"],\n d1: [\"date\"],\n d2: [\"date\"],\n};\n\nfunction fail(path: string, message: string): never {\n throw new Error(`defineCrm: ${path} ${message}`);\n}\n\nfunction checkType(typeName: string, def: TypeDef): void {\n const at = `types.${typeName}`;\n if (!NAME_RE.test(typeName)) fail(at, \"must match /^[a-z][a-z0-9_-]*$/\");\n if (def.workspace != null && !NAME_RE.test(def.workspace)) {\n fail(`${at}.workspace`, \"must match /^[a-z][a-z0-9_-]*$/\");\n }\n const claimed = new Map<CrmSlot, string>();\n for (const [fieldName, field] of Object.entries(def.fields)) {\n const fat = `${at}.fields.${fieldName}`;\n if (RESERVED_FIELDS.has(fieldName)) fail(fat, \"is a reserved column name\");\n if (!FIELD_RE.test(fieldName)) fail(fat, \"must match /^[a-z][a-zA-Z0-9_]*$/\");\n if (field.type === \"enum\" && !(field.options && field.options.length > 0))\n fail(fat, \"enum fields need non-empty options\");\n if (field.type !== \"enum\" && field.options) fail(fat, \"options are for enum fields only\");\n // A condition is checked here, at boot, so a typo is a startup failure\n // rather than a field that quietly misbehaves on a live form.\n for (const key of [\"visibleWhen\", \"requiredWhen\"] as const) {\n const expression = field[key];\n if (expression === undefined) continue;\n if (typeof expression !== \"string\" || !expression.trim()) {\n fail(`${fat}.${key}`, \"must be a non-empty CEL condition\");\n }\n try {\n assertFieldCondition(expression, `${fat}.${key}`);\n } catch (error) {\n fail(`${fat}.${key}`, error instanceof Error ? error.message : \"invalid condition\");\n }\n }\n if (field.slot) {\n if (!CRM_SLOTS.includes(field.slot)) fail(fat, `unknown slot ${field.slot}`);\n if (!SLOT_KIND[field.slot].includes(field.type))\n fail(fat, `slot ${field.slot} cannot hold a ${field.type} field`);\n const holder = claimed.get(field.slot);\n if (holder) fail(fat, `slot ${field.slot} already claimed by ${holder}`);\n claimed.set(field.slot, fieldName);\n }\n }\n const nameField = def.nameField ?? \"name\";\n if (!def.fields[nameField]) fail(at, `nameField \"${nameField}\" is not a declared field`);\n if (def.emailField) {\n const emailDef = def.fields[def.emailField];\n if (!emailDef) fail(at, `emailField \"${def.emailField}\" is not a declared field`);\n if (emailDef.type !== \"email\") fail(at, `emailField \"${def.emailField}\" must have type \"email\"`);\n }\n checkPipeline(at, def);\n}\n\nfunction checkPipeline(at: string, def: TypeDef): void {\n const pipeline = def.pipeline;\n if (!pipeline) return;\n if (pipeline.stages.length === 0) fail(at, \"pipeline.stages must not be empty\");\n const ids = new Set<string>();\n for (const stage of pipeline.stages) {\n if (ids.has(stage.id)) fail(at, `duplicate stage \"${stage.id}\"`);\n ids.add(stage.id);\n }\n for (const [from, targets] of Object.entries(pipeline.transitions ?? {})) {\n if (!ids.has(from)) fail(at, `transitions from unknown stage \"${from}\"`);\n for (const to of targets) if (!ids.has(to)) fail(at, `transition to unknown stage \"${to}\"`);\n }\n for (const gated of Object.keys(pipeline.gates ?? {}))\n if (!ids.has(gated)) fail(at, `gate on unknown stage \"${gated}\"`);\n for (const hooked of Object.keys(def.onTransition ?? {}))\n if (!ids.has(hooked)) fail(at, `onTransition hook on unknown stage \"${hooked}\"`);\n}\n\n/**\n * Validate an app's CRM configuration and return the resolved {@link Crm}\n * engine. Throws (with a `types.person.fields.…`-style path) on slot\n * collisions, enum/slot type disagreements, unknown pipeline edges, reserved\n * field names, or dangling name/email field references — at boot, before any\n * request runs.\n */\nexport function defineCrm(config: CrmConfig): Crm {\n if (Object.keys(config.types).length === 0) fail(\"types\", \"must declare at least one type\");\n for (const [typeName, def] of Object.entries(config.types)) checkType(typeName, def);\n for (const [relName, rel] of Object.entries(config.relations ?? {})) {\n const at = `relations.${relName}`;\n if (!config.types[rel.from]) fail(at, `unknown from-type \"${rel.from}\"`);\n if (!config.types[rel.to]) fail(at, `unknown to-type \"${rel.to}\"`);\n if (!rel.label) fail(at, \"needs a label\");\n }\n for (const [tplName, tpl] of Object.entries(config.templates ?? {})) {\n const at = `templates.${tplName}`;\n if (tpl.class !== \"transactional\" && tpl.class !== \"marketing\")\n fail(at, `class must be transactional|marketing`);\n for (const v of tpl.vars) if (!/^[a-zA-Z][a-zA-Z0-9_]*$/.test(v)) fail(at, `bad var \"${v}\"`);\n if (tpl.defaults) {\n const lint = lintTemplate(`${tpl.defaults.subject}\\n${tpl.defaults.text}`, tpl.vars);\n if (lint.unknown.length) fail(at, `defaults reference unknown vars: ${lint.unknown.join(\", \")}`);\n }\n }\n\n const type = (name: string): TypeDef => {\n const def = config.types[name];\n if (!def) throw new CrmInputError(`unknown record type \"${name}\"`);\n return def;\n };\n return {\n config,\n schema: CRM_SCHEMA,\n rules: CRM_RULES,\n type,\n prepare: (name, input, existing) => prepare(type(name), input, existing),\n canTransition: (name, record, to) => canTransition(type(name), record, to),\n initialStage: (name) => initialStage(type(name)),\n stageIndex: (name, stage) => stageIndexOf(type(name), stage),\n };\n}\n\n/**\n * Compose independently-owned CRM config fragments. Duplicate type, relation,\n * or template ids fail closed so adopting a feature preset cannot silently\n * replace a host's operating pipeline or email classification.\n */\nexport function composeCrmConfigs(...configs: readonly CrmConfig[]): CrmConfig {\n if (configs.length === 0) throw new Error(\"composeCrmConfigs: at least one config is required\");\n const result: CrmConfig = { types: {} };\n const merge = <T>(\n kind: string,\n target: Record<string, T>,\n source: Record<string, T> | undefined,\n ) => {\n for (const [id, value] of Object.entries(source ?? {})) {\n if (Object.hasOwn(target, id)) throw new Error(`composeCrmConfigs: duplicate ${kind} \"${id}\"`);\n target[id] = value;\n }\n };\n for (const config of configs) {\n merge(\"type\", result.types, config.types);\n if (config.relations) {\n result.relations ??= {};\n merge(\"relation\", result.relations, config.relations);\n }\n if (config.templates) {\n result.templates ??= {};\n merge(\"template\", result.templates, config.templates);\n }\n }\n return result;\n}\n","/** CRM resources that can be shared into a Discussion message. */\nexport const CRM_DISCUSSION_REFERENCE_KINDS = [\n \"crm:record\",\n \"crm:activity\",\n] as const;\n\n/** One CRM resource kind understood by the native CRM destination. */\nexport type CrmDiscussionReferenceKind =\n (typeof CRM_DISCUSSION_REFERENCE_KINDS)[number];\n\n/** Canonical CRM destination target parsed from an `odla-ref` deep link. */\nexport interface CrmDiscussionReferenceTarget {\n kind: CrmDiscussionReferenceKind;\n type: string;\n recordId: string;\n activityId?: string;\n}\n\n/** Product-owned projection returned to Discussion typeahead and exact lookup. */\nexport interface CrmDiscussionReference {\n /** Canonical CRM kind used in stored Discussion ref markup. */\n kind: CrmDiscussionReferenceKind;\n /** Opaque durable product id; never infer CRM access from its segments. */\n id: string;\n /** Product-authored primary display name. */\n label: string;\n /** Short product-authored secondary context for the picker. */\n hint: string;\n /** Bounded product-authored context safe to show an LLM or person. */\n summary: string;\n /** Current product status at inspection time. */\n status: string;\n /** Human-readable native surface the link opens. */\n destination: string;\n /** Same-origin native link; navigation is not mutation authority. */\n href: string;\n}\n\nconst SEGMENT = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,199}$/;\n\n/** Durable ref id: `type/recordId`, plus an activity id for feed entries. */\nexport function crmDiscussionReferenceId(\n target: CrmDiscussionReferenceTarget,\n): string {\n const root = `${target.type}/${target.recordId}`;\n return target.activityId ? `${root}/${target.activityId}` : root;\n}\n\n/** Canonical value stored in the stable `odla-ref` query parameter. */\nexport function formatCrmDiscussionReference(\n target: CrmDiscussionReferenceTarget,\n): string {\n return `${target.kind}/${crmDiscussionReferenceId(target)}`;\n}\n\n/** Parse and validate a CRM `odla-ref`; malformed and cross-product refs fail closed. */\nexport function parseCrmDiscussionReference(\n input: URL | string,\n): CrmDiscussionReferenceTarget | null {\n let raw: string | null;\n try {\n raw = input instanceof URL\n ? input.searchParams.get(\"odla-ref\")\n : new URL(input, \"https://crm.invalid\").searchParams.get(\"odla-ref\");\n } catch {\n return null;\n }\n if (!raw) return null;\n const [kind, type, recordId, activityId, extra] = raw.split(\"/\");\n if (\n extra !== undefined ||\n !CRM_DISCUSSION_REFERENCE_KINDS.includes(\n kind as CrmDiscussionReferenceKind,\n ) ||\n !type ||\n !recordId ||\n !SEGMENT.test(type) ||\n !SEGMENT.test(recordId)\n ) return null;\n if (kind === \"crm:record\") {\n return activityId === undefined\n ? { kind, type, recordId }\n : null;\n }\n return activityId && SEGMENT.test(activityId)\n ? { kind: \"crm:activity\", type, recordId, activityId }\n : null;\n}\n\n/** Build a Chapter-compatible CRM deep link and retain the exact ref for focus. */\nexport function crmDiscussionReferenceHref(\n current: URL,\n target: CrmDiscussionReferenceTarget,\n basePath = \"/admin/\",\n): string {\n const next = new URL(current.origin);\n next.pathname = basePath.startsWith(\"/\") ? basePath : `/${basePath}`;\n next.searchParams.set(\"odla-ref\", formatCrmDiscussionReference(target));\n next.hash = [\n \"people\",\n target.type,\n target.recordId,\n target.kind === \"crm:activity\" ? \"notes\" : \"profile\",\n ].map(encodeURIComponent).join(\"/\");\n return next.toString();\n}\n","// The dependency bundle every op takes. `now`/`newId` are injectable so\n// tests can pin time and ids and assert exact written attrs.\nimport type { Crm } from \"./config\";\nimport type { CrmDb } from \"./types\";\n\n/** What every op needs: the resolved config, the injected db, test overrides. */\nexport interface CrmDeps {\n crm: Crm;\n db: CrmDb;\n /** Clock override (default `Date.now`). */\n now?: () => number;\n /** Id/token factory override (default `crypto.randomUUID`). */\n newId?: () => string;\n}\n\n/** {@link CrmDeps} with the injectable defaults filled in. */\nexport interface ResolvedDeps {\n crm: Crm;\n db: CrmDb;\n now: () => number;\n newId: () => string;\n}\n\n/** Fill the injectable defaults. */\nexport function resolveDeps(deps: CrmDeps): ResolvedDeps {\n return {\n crm: deps.crm,\n db: deps.db,\n now: deps.now ?? Date.now,\n newId: deps.newId ?? (() => crypto.randomUUID()),\n };\n}\n","// Compiles list/view filters into odla-db QueryOpts under its real limits:\n// FTS `search` + recursive `where` + ORDER ON EXACTLY ONE INDEXED FIELD +\n// limit/offset. Sortable fields are the promoted columns plus the type's\n// slotted custom fields; tag filtering is a two-step id intersection the\n// records op performs before calling this.\nimport { DEFAULT_LIMIT, MAX_LIMIT, SORTABLE_COLUMNS, type CrmSlot } from \"./constants\";\nimport type { Crm } from \"./config\";\nimport { CrmInputError } from \"./errors\";\nimport type { CrmScalar } from \"./types\";\n\n/** Comparison filter for one slotted custom field. */\nexport interface FieldFilter {\n eq?: CrmScalar;\n in?: CrmScalar[];\n gte?: number | string;\n lte?: number | string;\n}\n\n/** The serializable filter set (also the saved-view `filters` payload). */\nexport interface ViewFilters {\n search?: string;\n stage?: string[];\n emailStatus?: string[];\n billingStatus?: string[];\n ownerId?: string;\n /** Exact tag — resolved to record ids first (join rows). */\n tag?: string;\n /** Include archived records (default: live only). */\n archived?: boolean;\n /** Slotted-field predicates, keyed by config field name. */\n fields?: Record<string, FieldFilter>;\n}\n\n/** One-field sort (odla-db orders on exactly one indexed field). */\nexport interface CrmSort {\n field: string;\n dir: \"asc\" | \"desc\";\n}\n\n/** Everything a list window can ask for: filters + sort + paging. */\nexport interface CrmListParams extends ViewFilters {\n type: string;\n sort?: CrmSort;\n limit?: number;\n offset?: number;\n}\n\ntype Where = Record<string, unknown>;\n\n/** Resolve a sort field to its physical indexed column: a promoted column\n * name as-is, or a slotted config field via the type's slot claim. Throws\n * {@link CrmInputError} for anything else (odla-db cannot order on it). */\nexport function resolveSortColumn(crm: Crm, type: string, field: string): string {\n if ((SORTABLE_COLUMNS as readonly string[]).includes(field)) return field;\n const slot = crm.type(type).fields[field]?.slot;\n if (slot) return slot;\n throw new CrmInputError(\n `cannot sort by \"${field}\" — not a promoted column or a slotted field of ${type}`,\n );\n}\n\nfunction slotFor(crm: Crm, type: string, field: string): CrmSlot {\n const slot = crm.type(type).fields[field]?.slot;\n if (!slot) throw new CrmInputError(`cannot filter by \"${field}\" — not a slotted field of ${type}`);\n return slot;\n}\n\nfunction inOrEq(values: string[]): unknown {\n return values.length === 1 ? values[0] : { $in: values };\n}\n\n/** The compiled odla-db query options for one list window. */\nexport interface CompiledList {\n opts: {\n where: { and: Where[] };\n order: Record<string, \"asc\" | \"desc\">;\n limit: number;\n offset: number;\n search?: string;\n };\n limit: number;\n offset: number;\n}\n\n/**\n * Compile list params into `QueryOpts` for `crm_record`. `tagRecordIds`\n * (when the caller pre-resolved a tag filter) narrows via `id $in`; an empty\n * id list is the caller's short-circuit — don't compile, the result is [].\n */\nexport function compileList(crm: Crm, params: CrmListParams, tagRecordIds?: string[]): CompiledList {\n crm.type(params.type); // throws for unknown types\n const and: Where[] = [{ type: params.type }, { archived: params.archived ?? false }];\n if (params.stage?.length) and.push({ stage: inOrEq(params.stage) });\n if (params.emailStatus?.length) and.push({ emailStatus: inOrEq(params.emailStatus) });\n if (params.billingStatus?.length) and.push({ billingStatus: inOrEq(params.billingStatus) });\n if (params.ownerId) and.push({ ownerId: params.ownerId });\n if (tagRecordIds) and.push({ id: { $in: tagRecordIds } });\n for (const [field, filter] of Object.entries(params.fields ?? {})) {\n if (filter == null) continue; // tolerate sparse JSON payloads\n const slot = slotFor(crm, params.type, field);\n if (filter.eq !== undefined) and.push({ [slot]: filter.eq });\n if (filter.in !== undefined) and.push({ [slot]: { $in: filter.in } });\n if (filter.gte !== undefined) and.push({ [slot]: { $gte: filter.gte } });\n if (filter.lte !== undefined) and.push({ [slot]: { $lte: filter.lte } });\n }\n\n const sort = params.sort ?? { field: \"createdAt\", dir: \"desc\" as const };\n if (sort.dir !== \"asc\" && sort.dir !== \"desc\") throw new CrmInputError(\"sort.dir must be asc|desc\");\n const column = resolveSortColumn(crm, params.type, sort.field);\n\n const limit = Math.min(Math.max(params.limit ?? DEFAULT_LIMIT, 1), MAX_LIMIT);\n const offset = Math.max(params.offset ?? 0, 0);\n const search = params.search?.trim();\n return {\n opts: {\n where: { and },\n order: { [column]: sort.dir },\n limit,\n offset,\n ...(search ? { search } : {}),\n },\n limit,\n offset,\n };\n}\n","// Manual ordering as fractional numeric ranks: inserting between neighbors\n// writes their midpoint, so a reorder is one single-field write and lists\n// sort by `rank` under odla-db's one-field `order`. (LexoRank-style string\n// ranks were rejected: numbers sort natively and the midpoint is ~20 lines;\n// both schemes need an occasional rebalance anyway.)\nimport { CrmInputError } from \"./errors\";\n\n/** Spacing between ranks after a rebalance (and the first record's rank). */\nexport const RANK_STEP = 1024;\n\n/** Below this gap between neighbors, float64 midpoints are getting close to\n * exhaustion (each insert halves the gap; 2^-20 leaves ~30 more halvings). */\nexport const RANK_EPSILON = 2 ** -20;\n\n/**\n * The rank to write for a record placed between `before` and `after`\n * (either may be absent at the list edges; both absent = first record).\n * `before` is the neighbor that sorts earlier (smaller rank).\n */\nexport function rankBetween(before?: number, after?: number): number {\n if (before == null && after == null) return RANK_STEP;\n if (before == null) return (after as number) - RANK_STEP;\n if (after == null) return before + RANK_STEP;\n if (after <= before)\n throw new CrmInputError(`rankBetween: after (${after}) must exceed before (${before})`);\n return before + (after - before) / 2;\n}\n\n/** True when two neighbors have converged so far that midpoint inserts\n * between them are about to stop producing distinct ranks. */\nexport function needsRebalance(before: number, after: number): boolean {\n return after - before < RANK_EPSILON;\n}\n\n/**\n * Fresh evenly-spaced ranks for records in their current display order.\n * Returns one `{ id, rank }` per input, `RANK_STEP` apart starting at\n * `RANK_STEP` — apply as a batch update.\n */\nexport function rebalancePlan(orderedIds: readonly string[]): Array<{ id: string; rank: number }> {\n return orderedIds.map((id, i) => ({ id, rank: (i + 1) * RANK_STEP }));\n}\n","// Contact-channel consent as a table-driven pure state machine. The rules\n// encode who may move a channel where: suppression is sticky (admin-only\n// exit), an unsubscribe can only be undone by the CONTACT's own opt-in\n// (never an admin bulk action), and hard bounces land from any non-\n// suppressed state.\nimport type { ConsentState } from \"./constants\";\n\n/** Everything that can change a channel's consent. `unsubscribe.token` is\n * the emailed link, `unsubscribe.oneclick` the RFC 8058 POST; `contact.optin`\n * is an action by the contact themself (form, reply, re-confirmation). */\nexport type ConsentEvent =\n | \"unsubscribe.token\"\n | \"unsubscribe.oneclick\"\n | \"bounce.hard\"\n | \"admin.suppress\"\n | \"admin.resubscribe\"\n | \"contact.optin\";\n\n/** The machine's answer: the next state, or why the move is invalid. */\nexport type ConsentOutcome = { state: ConsentState } | { error: string };\n\n// state → event → next state; missing = invalid (returns an error).\nconst TABLE: Record<ConsentState, Partial<Record<ConsentEvent, ConsentState>>> = {\n subscribed: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\",\n \"contact.optin\": \"subscribed\",\n },\n unsubscribed: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"contact.optin\": \"subscribed\",\n // no admin.resubscribe: undoing an unsubscribe needs the contact's opt-in\n },\n bounced: {\n \"unsubscribe.token\": \"unsubscribed\",\n \"unsubscribe.oneclick\": \"unsubscribed\",\n \"bounce.hard\": \"bounced\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\", // admin says the address was fixed\n \"contact.optin\": \"subscribed\",\n },\n suppressed: {\n // sticky: everything except an explicit admin release keeps suppression\n \"unsubscribe.token\": \"suppressed\",\n \"unsubscribe.oneclick\": \"suppressed\",\n \"bounce.hard\": \"suppressed\",\n \"admin.suppress\": \"suppressed\",\n \"admin.resubscribe\": \"subscribed\",\n \"contact.optin\": \"suppressed\",\n },\n};\n\n/**\n * Apply one consent event to a channel's current state. Returns the next\n * state, or an error for the one invalid move (admin-resubscribing an\n * unsubscribed contact). Idempotent by construction: repeating an event\n * never changes the outcome.\n */\nexport function applyConsentEvent(current: ConsentState, event: ConsentEvent): ConsentOutcome {\n const next = TABLE[current]?.[event];\n if (next === undefined)\n return { error: `cannot ${event} a ${current} channel — requires the contact's own opt-in` };\n return { state: next };\n}\n\n/** May this channel receive a send of the given class right now?\n * `suppressed`/`bounced` block everything; `unsubscribed` blocks marketing\n * only (transactional lifecycle mail still delivers). */\nexport function canEmail(consent: ConsentState, cls: \"transactional\" | \"marketing\"): boolean {\n if (consent === \"suppressed\" || consent === \"bounced\") return false;\n if (consent === \"unsubscribed\") return cls === \"transactional\";\n return true;\n}\n","// Contact-channel plumbing: natural-key upserts for email channels, the\n// consent flips, and the fold of the primary channel's consent onto the\n// record's denormalized `emailStatus` (what list views filter on).\nimport { CRM_NS, type ConsentState, type EmailStatus } from \"./constants\";\nimport { applyConsentEvent, type ConsentEvent } from \"./consent\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport type { CrmContactChannel, CrmOp, CrmRow } from \"./types\";\n\n/** The natural key of a contact channel row. */\nexport const channelKey = (recordId: string, kind: string, value: string): string =>\n `${recordId}:${kind}:${value}`;\n\n/** A record's `emailStatus` is its primary channel's consent, with\n * \"subscribed\" reading as \"ok\" and no channel at all as \"none\". */\nexport function foldEmailStatus(consent: ConsentState | null): EmailStatus {\n return consent === null ? \"none\" : consent === \"subscribed\" ? \"ok\" : consent;\n}\n\nexport function rowToChannel(row: CrmRow): CrmContactChannel {\n return row as unknown as CrmContactChannel;\n}\n\n/** All channels of a record (a handful of rows — no paging). */\nexport async function listChannels(deps: CrmDeps, recordId: string): Promise<CrmContactChannel[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.channel]: { $: { where: { recordId }, order: { createdAt: \"asc\" }, limit: 100 } },\n });\n return (result[CRM_NS.channel] ?? []).map(rowToChannel);\n}\n\n/**\n * Ops that make `email` the record's primary email channel: upsert by\n * natural key (an address the record had before keeps its consent history),\n * demote any other primary, or — with `email: null` — just demote. Returns\n * the ops plus the `emailStatus` the record should fold to.\n */\nexport function emailChannelOps(\n deps: CrmDeps,\n recordId: string,\n email: string | null,\n existing: readonly CrmContactChannel[],\n): { ops: CrmOp[]; emailStatus: EmailStatus } {\n const { now, newId } = resolveDeps(deps);\n const ops: CrmOp[] = [];\n const current = existing.filter((c) => c.kind === \"email\" && c.isPrimary);\n const match = email ? existing.find((c) => c.kind === \"email\" && c.value === email) : undefined;\n for (const old of current)\n if (old !== match) ops.push({ t: \"update\", ns: CRM_NS.channel, id: old.id, attrs: { isPrimary: false } });\n if (email === null) return { ops, emailStatus: \"none\" };\n if (match) {\n if (!match.isPrimary)\n ops.push({ t: \"update\", ns: CRM_NS.channel, id: match.id, attrs: { isPrimary: true } });\n return { ops, emailStatus: foldEmailStatus(match.consent) };\n }\n const key = channelKey(recordId, \"email\", email);\n ops.push({\n t: \"update\",\n ns: CRM_NS.channel,\n id: { ns: CRM_NS.channel, attr: \"key\", value: key },\n attrs: {\n key,\n recordId,\n kind: \"email\",\n value: email,\n isPrimary: true,\n consent: \"subscribed\",\n consentAt: now(),\n consentSource: \"record-write\",\n unsubscribeToken: newId(),\n createdAt: now(),\n },\n });\n return { ops, emailStatus: \"ok\" };\n}\n\n/**\n * Apply one consent event to the channel holding `token` (unsubscribe links)\n * or to `channelId` (admin actions). Writes the channel's new consent and,\n * when it is the record's primary email channel, folds the record's\n * `emailStatus`. Idempotent under `mutationId`.\n */\nexport async function applyConsent(\n deps: CrmDeps,\n opts: { token?: string; channelId?: string; event: ConsentEvent; mutationId?: string },\n): Promise<{ state: ConsentState; recordId: string; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const where = opts.token\n ? { unsubscribeToken: opts.token }\n : opts.channelId\n ? { id: opts.channelId }\n : null;\n if (!where) throw new CrmInputError(\"token or channelId required\");\n const result = await db.query({ [CRM_NS.channel]: { $: { where, limit: 1 } } });\n const row = (result[CRM_NS.channel] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"contact channel\");\n const channel = rowToChannel(row);\n const outcome = applyConsentEvent(channel.consent, opts.event);\n if (\"error\" in outcome) throw new CrmInputError(outcome.error);\n const ops: CrmOp[] = [\n {\n t: \"update\",\n ns: CRM_NS.channel,\n id: channel.id,\n attrs: { consent: outcome.state, consentAt: now(), consentSource: opts.event },\n },\n ];\n if (channel.isPrimary && channel.kind === \"email\")\n ops.push({\n t: \"update\",\n ns: CRM_NS.record,\n id: channel.recordId,\n attrs: { emailStatus: foldEmailStatus(outcome.state), updatedAt: now() },\n });\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { state: outcome.state, recordId: channel.recordId, duplicate };\n}\n","// Turning a \"patch\" (a plain field→value map) into odla-db ops. odla-db has no\n// storable scalar null — a typed column is either written with a value or its\n// triple is retracted — so `null` in a patch means CLEAR and becomes a\n// `retract`, a non-null value becomes an `update`, and `undefined` is dropped\n// (leave the stored value untouched). This is the single choke-point that keeps\n// the crm from ever sending null to a typed scalar column.\nimport type { CrmAttrs, CrmEntityRef, CrmOp } from \"./types\";\n\n/**\n * Build the ops that apply `patch` to one entity: non-null keys collect into an\n * `update`, explicit-`null` keys (plus any `alsoClear` columns the caller\n * already knows to retract, e.g. a validator's emptied slots) into a `retract`.\n * `undefined` values are dropped. Emits the `update` first, then the `retract`;\n * either is omitted when it would carry nothing.\n */\nexport function patchOps(\n ns: string,\n id: CrmEntityRef,\n patch: Record<string, unknown>,\n alsoClear: string[] = [],\n): CrmOp[] {\n const attrs: CrmAttrs = {};\n const retract = [...alsoClear];\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) retract.push(key);\n else if (value !== undefined) attrs[key] = value;\n }\n const ops: CrmOp[] = [];\n if (Object.keys(attrs).length > 0) ops.push({ t: \"update\", ns, id, attrs });\n if (retract.length > 0) ops.push({ t: \"retract\", ns, id, attrs: retract });\n return ops;\n}\n\n/**\n * Apply a null-means-clear `patch` to `base` in memory, mirroring what\n * {@link patchOps} commits: set non-null values, drop `null` / `alsoClear`\n * keys, ignore `undefined`. Used to build the row a write returns to its caller\n * so the returned shape matches what was stored.\n */\nexport function applyPatch<T extends object>(\n base: T,\n patch: Record<string, unknown>,\n alsoClear: string[] = [],\n): T {\n const out = { ...base } as Record<string, unknown>;\n for (const [key, value] of Object.entries(patch)) {\n if (value === null) delete out[key];\n else if (value !== undefined) out[key] = value;\n }\n for (const key of alsoClear) delete out[key];\n return out as T;\n}\n","// Record CRUD over the injected db: create/update run through `prepare`\n// (validation + slot mirror + searchText), keep the primary email channel in\n// sync, and recompute the score when the type declares a scorer. Every write\n// takes an optional mutationId for exactly-once application.\nimport { CRM_NS } from \"./constants\";\nimport { emailChannelOps, listChannels } from \"./channels\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { compileList, type CrmListParams } from \"./query\";\nimport { applyPatch, patchOps } from \"./write-ops\";\nimport type { CrmAttrs, CrmOp, CrmRecord, CrmRow } from \"./types\";\n\n/** Cast a raw row to {@link CrmRecord}, defaulting the json fields. */\nexport function rowToRecord(row: CrmRow): CrmRecord {\n const record = row as unknown as CrmRecord;\n return { ...record, fields: record.fields ?? {}, searchText: record.searchText ?? \"\" };\n}\n\n/** Load one record by id, or null. */\nexport async function getRecord(deps: CrmDeps, id: string): Promise<CrmRecord | null> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.record]: { $: { where: { id }, limit: 1 } } });\n const row = (result[CRM_NS.record] ?? [])[0];\n return row ? rowToRecord(row) : null;\n}\n\n/** Load one record by id; {@link CrmNotFoundError} (404) when missing. */\nexport async function mustGetRecord(deps: CrmDeps, id: string): Promise<CrmRecord> {\n const record = await getRecord(deps, id);\n if (!record) throw new CrmNotFoundError(\"record\");\n return record;\n}\n\n/** One list window + the total matching count (for pagination). A `tag`\n * filter resolves to record ids first (join rows, capped at 1000). */\nexport async function listRecords(\n deps: CrmDeps,\n params: CrmListParams,\n): Promise<{ records: CrmRecord[]; total: number; limit: number; offset: number }> {\n const { crm, db } = resolveDeps(deps);\n let tagRecordIds: string[] | undefined;\n if (params.tag) {\n const tag = params.tag.trim().toLowerCase();\n const tagResult = await db.query({ [CRM_NS.tag]: { $: { where: { tag }, limit: 1000 } } });\n tagRecordIds = (tagResult[CRM_NS.tag] ?? []).map((row) => row[\"recordId\"] as string);\n if (tagRecordIds.length === 0)\n return { records: [], total: 0, limit: params.limit ?? 0, offset: params.offset ?? 0 };\n }\n const { opts, limit, offset } = compileList(crm, params, tagRecordIds);\n const [result, agg] = await Promise.all([\n db.query({ [CRM_NS.record]: { $: opts } }),\n db.aggregate(\n CRM_NS.record,\n { count: true },\n opts.search ? { where: opts.where, search: opts.search } : { where: opts.where },\n ),\n ]);\n return {\n records: (result[CRM_NS.record] ?? []).map(rowToRecord),\n total: agg.count ?? 0,\n limit,\n offset,\n };\n}\n\nfunction scoreOf(deps: CrmDeps, type: string, candidate: CrmRecord): number | undefined {\n const def = resolveDeps(deps).crm.type(type);\n const wantsScore = def.facets?.rank === \"score\" || def.facets?.rank === \"both\";\n if (!wantsScore || !def.scorer) return undefined;\n return def.scorer(candidate);\n}\n\n/** Create a record of `type` from custom-field input. Also creates (or\n * upserts) the primary email contact channel when the type declares an\n * `emailField`. New records rank at `now` so manual order defaults to\n * creation order. */\nexport async function createRecord(\n deps: CrmDeps,\n opts: { type: string; input: Record<string, unknown>; ownerId?: string; stage?: string; mutationId?: string },\n): Promise<{ id: string; duplicate: boolean; record: CrmRecord }> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const prepared = crm.prepare(opts.type, opts.input);\n if (!prepared.ok) throw new CrmInputError(\"invalid input\", prepared.errors);\n const id = newId();\n const at = now();\n const stage = opts.stage ?? crm.initialStage(opts.type);\n const attrs: CrmAttrs = {\n id, // mirror the entity id as an attr so `where: { id }` reads can find it\n type: opts.type,\n ...prepared.attrs,\n archived: false,\n rank: at,\n createdAt: at,\n updatedAt: at,\n };\n if (opts.ownerId != null) attrs.ownerId = opts.ownerId;\n if (stage != null) {\n attrs.stage = stage;\n attrs.stageIndex = crm.stageIndex(opts.type, stage); // throws on unknown stage\n attrs.stageChangedAt = at;\n }\n const ops: CrmOp[] = [];\n const email = (prepared.attrs[\"primaryEmail\"] as string | null | undefined) ?? null;\n if (crm.type(opts.type).emailField) {\n const channel = emailChannelOps(deps, id, email, []);\n attrs.emailStatus = channel.emailStatus;\n ops.push(...channel.ops);\n } else {\n attrs.emailStatus = \"none\";\n }\n const candidate = { id, ...attrs } as unknown as CrmRecord;\n const score = scoreOf(deps, opts.type, candidate);\n if (score !== undefined) attrs.score = score;\n ops.unshift({ t: \"update\", ns: CRM_NS.record, id, attrs });\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { id, duplicate, record: { id, ...attrs } as unknown as CrmRecord };\n}\n\n/** Partial update of custom fields (+ owner). A changed `emailField` value\n * repoints the primary channel — the old address keeps its consent history,\n * a returning address keeps its earlier consent. */\nexport async function updateRecord(\n deps: CrmDeps,\n opts: { id: string; input: Record<string, unknown>; ownerId?: string | null; mutationId?: string },\n): Promise<{ record: CrmRecord; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const existing = await mustGetRecord(deps, opts.id);\n const prepared = crm.prepare(existing.type, opts.input, existing);\n if (!prepared.ok) throw new CrmInputError(\"invalid input\", prepared.errors);\n // `ownerId: undefined` leaves the owner untouched; `null` clears it (retract).\n const patch: Record<string, unknown> = { ...prepared.attrs, updatedAt: now(), ownerId: opts.ownerId };\n const channelOps: CrmOp[] = [];\n if (crm.type(existing.type).emailField) {\n const nextEmail = (prepared.attrs[\"primaryEmail\"] as string | null | undefined) ?? null;\n if (nextEmail !== (existing.primaryEmail ?? null)) {\n const channels = await listChannels(deps, existing.id);\n const channel = emailChannelOps(deps, existing.id, nextEmail, channels);\n patch.emailStatus = channel.emailStatus;\n channelOps.push(...channel.ops);\n }\n }\n const candidate = { ...existing, ...prepared.attrs } as CrmRecord;\n const score = scoreOf(deps, existing.type, candidate);\n if (score !== undefined) patch.score = score;\n const ops = [...patchOps(CRM_NS.record, existing.id, patch, prepared.retract), ...channelOps];\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { record: applyPatch(existing, patch, prepared.retract), duplicate };\n}\n\n/** Archive (soft-delete) or restore. Archived records drop out of default\n * list windows but keep every tag/activity/channel row. */\nexport async function setArchived(\n deps: CrmDeps,\n opts: { id: string; archived: boolean; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.id);\n const at = now();\n // Restore clears `archivedAt` (null → retract; a typed date can't be nulled).\n const patch: Record<string, unknown> = opts.archived\n ? { archived: true, archivedAt: at, updatedAt: at }\n : { archived: false, archivedAt: null, updatedAt: at };\n const { duplicate } = await db.transact(\n patchOps(CRM_NS.record, opts.id, patch),\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n","// Stage transitions (gate-checked, audited) and manual reordering\n// (fractional ranks). Both are single-record writes; the stage move also\n// appends a `stage_change` activity so the pipeline history is queryable.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { needsRebalance, rankBetween, rebalancePlan } from \"./rank\";\nimport { mustGetRecord, rowToRecord } from \"./records\";\nimport type { CrmOp, CrmRecord } from \"./types\";\n\n/**\n * Move a record to stage `to`. Refused (400-style {@link CrmInputError})\n * when the pipeline's transitions/gates say no. Appends the audit activity\n * in the same tx; returns the type's `onTransition` hook for the caller to\n * fire AFTER commit (post-commit side effects like a Clerk role promotion\n * never hold the write hostage).\n */\nexport async function setStage(\n deps: CrmDeps,\n opts: { id: string; to: string; authorId: string; mutationId?: string },\n): Promise<{\n record: CrmRecord;\n from: string | null;\n duplicate: boolean;\n hook?: (record: CrmRecord) => void | Promise<void>;\n}> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.id);\n const blocked = crm.canTransition(record.type, record, opts.to);\n if (blocked) throw new CrmInputError(blocked);\n const at = now();\n const attrs = {\n stage: opts.to,\n stageIndex: crm.stageIndex(record.type, opts.to),\n stageChangedAt: at,\n updatedAt: at,\n };\n const activityId = newId();\n const ops: CrmOp[] = [\n { t: \"update\", ns: CRM_NS.record, id: record.id, attrs },\n {\n t: \"update\",\n ns: CRM_NS.activity,\n id: activityId,\n attrs: {\n id: activityId, // mirror the entity id so the activity is readable by id\n recordId: record.id,\n kind: \"stage_change\",\n body: `${record.stage ?? \"(none)\"} → ${opts.to}`,\n authorId: opts.authorId,\n createdAt: at,\n },\n },\n ];\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n const updated = { ...record, ...attrs } as CrmRecord;\n return {\n record: updated,\n from: record.stage ?? null,\n duplicate,\n hook: crm.type(record.type).onTransition?.[opts.to],\n };\n}\n\n/**\n * Place a record between two neighbors (either end open). Neighbors must be\n * same-type records that already carry ranks; reports `rebalanceNeeded`\n * when the gap between them has nearly collapsed.\n */\nexport async function setRank(\n deps: CrmDeps,\n opts: { id: string; beforeId?: string; afterId?: string; mutationId?: string },\n): Promise<{ rank: number; rebalanceNeeded: boolean; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.id);\n const neighborIds = [opts.beforeId, opts.afterId].filter((v): v is string => v != null);\n const neighbors = new Map<string, CrmRecord>();\n if (neighborIds.length > 0) {\n const result = await db.query({\n [CRM_NS.record]: { $: { where: { id: { $in: neighborIds } }, limit: 2 } },\n });\n for (const row of result[CRM_NS.record] ?? []) {\n const neighbor = rowToRecord(row);\n if (neighbor.type !== record.type)\n throw new CrmInputError(\"neighbors must be records of the same type\");\n neighbors.set(neighbor.id, neighbor);\n }\n }\n const rankOf = (id?: string): number | undefined => {\n if (id == null) return undefined;\n const neighbor = neighbors.get(id);\n if (!neighbor) throw new CrmInputError(`neighbor ${id} not found`);\n if (neighbor.rank == null)\n throw new CrmInputError(`neighbor ${id} has no rank — run a rebalance first`);\n return neighbor.rank;\n };\n const before = rankOf(opts.beforeId);\n const after = rankOf(opts.afterId);\n const rank = rankBetween(before, after);\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: CRM_NS.record, id: record.id, attrs: { rank, updatedAt: now() } }],\n { mutationId: opts.mutationId },\n );\n return {\n rank,\n rebalanceNeeded: before != null && after != null && needsRebalance(before, after),\n duplicate,\n };\n}\n\n/** Rewrite a type's live records to evenly-spaced ranks in their current\n * rank order (first 1000 — beyond that, rebalance in windows). */\nexport async function rebalanceRanks(\n deps: CrmDeps,\n opts: { type: string; mutationId?: string },\n): Promise<{ count: number; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n crm.type(opts.type); // throws for unknown types\n const result = await db.query({\n [CRM_NS.record]: {\n $: {\n where: { and: [{ type: opts.type }, { archived: false }] },\n order: { rank: \"asc\" },\n limit: 1000,\n },\n },\n });\n const ids = (result[CRM_NS.record] ?? []).map((row) => row.id);\n const at = now();\n const ops: CrmOp[] = rebalancePlan(ids).map(({ id, rank }) => ({\n t: \"update\",\n ns: CRM_NS.record,\n id,\n attrs: { rank, updatedAt: at },\n }));\n if (ops.length === 0) return { count: 0, duplicate: false };\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return { count: ops.length, duplicate };\n}\n","// Tags and record↔record links as natural-key join rows: upserts are\n// idempotent by key, removal is a lookup delete, and both double as\n// provenance (tag rows timestamp when a record entered a cohort).\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { mustGetRecord, rowToRecord } from \"./records\";\nimport type { CrmLink, CrmTag } from \"./types\";\n\n/** Tags are lowercased, trimmed, ≤ 64 chars — exact-match filters, so case\n * variants must collapse to one cohort. */\nexport function normalizeTag(raw: string): string {\n const tag = raw.trim().toLowerCase();\n if (tag.length === 0 || tag.length > 64) throw new CrmInputError(\"tag must be 1–64 characters\");\n return tag;\n}\n\n/** Idempotently tag a record (natural-key upsert). */\nexport async function addTag(\n deps: CrmDeps,\n opts: { recordId: string; tag: string; mutationId?: string },\n): Promise<{ tag: string; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const tag = normalizeTag(opts.tag);\n await mustGetRecord(deps, opts.recordId);\n const key = `${opts.recordId}:${tag}`;\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.tag,\n id: { ns: CRM_NS.tag, attr: \"key\", value: key },\n attrs: { key, recordId: opts.recordId, tag, createdAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { tag, duplicate };\n}\n\n/** Remove a tag by natural key; a no-op when absent. */\nexport async function removeTag(\n deps: CrmDeps,\n opts: { recordId: string; tag: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const tag = normalizeTag(opts.tag);\n const { duplicate } = await db.transact(\n [{ t: \"delete\", ns: CRM_NS.tag, id: { ns: CRM_NS.tag, attr: \"key\", value: `${opts.recordId}:${tag}` } }],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** A record's tags, oldest first. */\nexport async function listTags(deps: CrmDeps, recordId: string): Promise<CrmTag[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.tag]: { $: { where: { recordId }, order: { createdAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.tag] ?? []).map((row) => row as unknown as CrmTag);\n}\n\n/** Create a config-declared relation between two records after checking the\n * endpoints' types match the relation's from/to declaration. */\nexport async function addLink(\n deps: CrmDeps,\n opts: { relation: string; fromId: string; toId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const rel = crm.config.relations?.[opts.relation];\n if (!rel) throw new CrmInputError(`unknown relation \"${opts.relation}\"`);\n if (opts.fromId === opts.toId) throw new CrmInputError(\"cannot link a record to itself\");\n const result = await db.query({\n [CRM_NS.record]: { $: { where: { id: { $in: [opts.fromId, opts.toId] } }, limit: 2 } },\n });\n const byId = new Map((result[CRM_NS.record] ?? []).map((row) => [row.id, rowToRecord(row)]));\n const from = byId.get(opts.fromId);\n const to = byId.get(opts.toId);\n if (!from || !to) throw new CrmInputError(\"both records must exist\");\n if (from.type !== rel.from || to.type !== rel.to)\n throw new CrmInputError(\n `relation \"${opts.relation}\" links ${rel.from} → ${rel.to}, got ${from.type} → ${to.type}`,\n );\n const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.link,\n id: { ns: CRM_NS.link, attr: \"key\", value: key },\n attrs: { key, fromId: opts.fromId, toId: opts.toId, relation: opts.relation, createdAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** Remove a relation by natural key; a no-op when absent. */\nexport async function removeLink(\n deps: CrmDeps,\n opts: { relation: string; fromId: string; toId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const key = `${opts.fromId}:${opts.relation}:${opts.toId}`;\n const { duplicate } = await db.transact(\n [{ t: \"delete\", ns: CRM_NS.link, id: { ns: CRM_NS.link, attr: \"key\", value: key } }],\n { mutationId: opts.mutationId },\n );\n return { duplicate };\n}\n\n/** Every link touching a record, either direction. */\nexport async function listLinks(deps: CrmDeps, recordId: string): Promise<CrmLink[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.link]: {\n $: { where: { or: [{ fromId: recordId }, { toId: recordId }] }, order: { createdAt: \"asc\" }, limit: 200 },\n },\n });\n return (result[CRM_NS.link] ?? []).map((row) => row as unknown as CrmLink);\n}\n","// Durable cross-system record identity and delivery state. Tags remain useful\n// user-editable cohorts; these rows are the machine contract and cannot be\n// destroyed by renaming or removing a display tag.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { getRecord, mustGetRecord } from \"./records\";\nimport type { CrmOp, CrmRecord, CrmRecordDelivery, CrmRecordOrigin } from \"./types\";\n\nconst SOURCE_ID = /^[a-z0-9][a-z0-9-]{1,127}$/;\nconst TARGET_ID = SOURCE_ID;\n\nfunction required(value: string, label: string, max = 512): string {\n const normalized = value.trim();\n if (!normalized || normalized.length > max) throw new CrmInputError(`${label} must be 1–${max} characters`);\n return normalized;\n}\n\n/** Stable natural key for an upstream record identity. */\nexport function recordOriginKey(sourceId: string, sourceRecordId: string): string {\n const source = required(sourceId, \"sourceId\", 128);\n const record = required(sourceRecordId, \"sourceRecordId\");\n if (!SOURCE_ID.test(source)) throw new CrmInputError(\"sourceId must be a lowercase app slug\");\n return `${source}:${record}`;\n}\n\n/** Look up a structured origin row by upstream site + record id. */\nexport async function getRecordOrigin(\n deps: CrmDeps,\n sourceId: string,\n sourceRecordId: string,\n): Promise<CrmRecordOrigin | null> {\n const { db } = resolveDeps(deps);\n const key = recordOriginKey(sourceId, sourceRecordId);\n const result = await db.query({ [CRM_NS.origin]: { $: { where: { key }, limit: 1 } } });\n return ((result[CRM_NS.origin] ?? [])[0] as unknown as CrmRecordOrigin | undefined) ?? null;\n}\n\n/** Resolve the local CRM record identified by an upstream origin. */\nexport async function getRecordByOrigin(\n deps: CrmDeps,\n sourceId: string,\n sourceRecordId: string,\n): Promise<CrmRecord | null> {\n const origin = await getRecordOrigin(deps, sourceId, sourceRecordId);\n return origin ? getRecord(deps, origin.recordId) : null;\n}\n\n/** Idempotently bind one upstream record identity to a local CRM record. */\nexport async function upsertRecordOrigin(\n deps: CrmDeps,\n opts: {\n recordId: string;\n sourceId: string;\n sourceRecordId: string;\n sourceUrl?: string;\n payloadVersion: number;\n mutationId?: string;\n },\n): Promise<{ origin: CrmRecordOrigin; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.recordId);\n const key = recordOriginKey(opts.sourceId, opts.sourceRecordId);\n if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {\n throw new CrmInputError(\"payloadVersion must be a positive integer\");\n }\n const sourceUrl = opts.sourceUrl == null ? undefined : required(opts.sourceUrl, \"sourceUrl\", 2048);\n const existing = await getRecordOrigin(deps, opts.sourceId, opts.sourceRecordId);\n if (existing && existing.recordId !== opts.recordId) {\n throw new CrmInputError(\"upstream record is already bound to another local record\");\n }\n const at = now();\n const attrs = {\n key,\n recordId: opts.recordId,\n sourceId: opts.sourceId,\n sourceRecordId: opts.sourceRecordId,\n payloadVersion: opts.payloadVersion,\n firstReceivedAt: existing?.firstReceivedAt ?? at,\n lastReceivedAt: at,\n ...(sourceUrl ? { sourceUrl } : {}),\n };\n const { duplicate } = await db.transact(\n [{ t: \"update\", ns: CRM_NS.origin, id: { ns: CRM_NS.origin, attr: \"key\", value: key }, attrs }],\n { mutationId: opts.mutationId },\n );\n return {\n duplicate,\n origin: {\n id: existing?.id ?? key,\n ...attrs,\n },\n };\n}\n\n/** List every upstream identity attached to a local record. */\nexport async function listRecordOrigins(deps: CrmDeps, recordId: string): Promise<CrmRecordOrigin[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.origin]: { $: { where: { recordId }, order: { firstReceivedAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.origin] ?? []) as unknown as CrmRecordOrigin[];\n}\n\n/** Stable natural key for one local record → target delivery edge. */\nexport function recordDeliveryKey(recordId: string, targetId: string): string {\n const record = required(recordId, \"recordId\");\n const target = required(targetId, \"targetId\", 128);\n if (!TARGET_ID.test(target)) throw new CrmInputError(\"targetId must be a lowercase app slug\");\n return `${record}:${target}`;\n}\n\n/** Record one success or failure while retaining the latest edge state. */\nexport async function recordDeliveryAttempt(\n deps: CrmDeps,\n opts: {\n recordId: string;\n targetId: string;\n status: \"delivered\" | \"failed\";\n payloadVersion: number;\n remoteRecordId?: string;\n error?: string;\n mutationId?: string;\n },\n): Promise<{ delivery: CrmRecordDelivery; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n await mustGetRecord(deps, opts.recordId);\n const key = recordDeliveryKey(opts.recordId, opts.targetId);\n if (!Number.isSafeInteger(opts.payloadVersion) || opts.payloadVersion <= 0) {\n throw new CrmInputError(\"payloadVersion must be a positive integer\");\n }\n const found = await db.query({ [CRM_NS.delivery]: { $: { where: { key }, limit: 1 } } });\n const existing = (found[CRM_NS.delivery] ?? [])[0] as unknown as CrmRecordDelivery | undefined;\n const at = now();\n const remoteRecordId = opts.remoteRecordId == null\n ? existing?.remoteRecordId\n : required(opts.remoteRecordId, \"remoteRecordId\");\n const error = opts.error == null ? undefined : required(opts.error, \"error\", 1000);\n const attrs = {\n key,\n recordId: opts.recordId,\n targetId: opts.targetId,\n status: opts.status,\n attempts: (existing?.attempts ?? 0) + 1,\n payloadVersion: opts.payloadVersion,\n lastAttemptAt: at,\n ...(remoteRecordId ? { remoteRecordId } : {}),\n ...(opts.status === \"delivered\" ? { deliveredAt: at } : existing?.deliveredAt ? { deliveredAt: existing.deliveredAt } : {}),\n ...(error ? { error } : {}),\n };\n const ref = { ns: CRM_NS.delivery, attr: \"key\", value: key } as const;\n const ops: CrmOp[] = [{ t: \"update\", ns: CRM_NS.delivery, id: ref, attrs }];\n if (opts.status === \"delivered\" && existing?.error) {\n ops.push({ t: \"retract\", ns: CRM_NS.delivery, id: ref, attrs: [\"error\"] });\n }\n const { duplicate } = await db.transact(ops, { mutationId: opts.mutationId });\n return {\n duplicate,\n delivery: {\n id: existing?.id ?? key,\n ...attrs,\n },\n };\n}\n\n/** List delivery state for one record, or every edge to one target. */\nexport async function listRecordDeliveries(\n deps: CrmDeps,\n filter: { recordId?: string; targetId?: string },\n): Promise<CrmRecordDelivery[]> {\n if (!filter.recordId && !filter.targetId) throw new CrmInputError(\"recordId or targetId is required\");\n const { db } = resolveDeps(deps);\n const where = {\n ...(filter.recordId ? { recordId: required(filter.recordId, \"recordId\") } : {}),\n ...(filter.targetId ? { targetId: required(filter.targetId, \"targetId\", 128) } : {}),\n };\n const result = await db.query({\n [CRM_NS.delivery]: { $: { where, order: { lastAttemptAt: \"desc\" }, limit: 500 } },\n });\n return (result[CRM_NS.delivery] ?? []) as unknown as CrmRecordDelivery[];\n}\n","// Notes, calls, and follow-up tasks on a record — the TASKS.md replacement.\n// Tasks carry dueAt/status/waitingOn/assigneeId, all indexed, so \"my open\n// follow-ups by due date\" is a single-field-order query.\nimport { ACTIVITY_KINDS, CRM_NS, TASK_STATUSES, type ActivityKind, type TaskStatus } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { mustGetRecord } from \"./records\";\nimport { applyPatch, patchOps } from \"./write-ops\";\nimport type { CrmActivity, CrmAttrs } from \"./types\";\n\nconst rowToActivity = (row: Record<string, unknown>): CrmActivity => row as unknown as CrmActivity;\n\n/** Append a note/call/meeting or open a follow-up task on a record. */\nexport async function addActivity(\n deps: CrmDeps,\n opts: {\n recordId: string;\n kind: ActivityKind;\n body: string;\n authorId: string;\n dueAt?: number;\n assigneeId?: string;\n waitingOn?: string;\n meta?: Record<string, unknown>;\n mutationId?: string;\n },\n): Promise<{ id: string; duplicate: boolean }> {\n const { db, now, newId } = resolveDeps(deps);\n if (!ACTIVITY_KINDS.includes(opts.kind)) throw new CrmInputError(`unknown kind \"${opts.kind}\"`);\n const body = opts.body.trim();\n if (!body) throw new CrmInputError(\"body is required\");\n await mustGetRecord(deps, opts.recordId);\n const id = newId();\n const attrs: CrmAttrs = {\n id, // mirror the entity id so updateTask's `where: { id }` read can find it\n recordId: opts.recordId,\n kind: opts.kind,\n body,\n authorId: opts.authorId,\n createdAt: now(),\n };\n if (opts.kind === \"task\") {\n attrs.status = \"open\";\n if (opts.dueAt != null) attrs.dueAt = opts.dueAt;\n if (opts.assigneeId != null) attrs.assigneeId = opts.assigneeId;\n if (opts.waitingOn != null) attrs.waitingOn = opts.waitingOn;\n }\n if (opts.meta) attrs.meta = opts.meta;\n const { duplicate } = await db.transact([{ t: \"update\", ns: CRM_NS.activity, id, attrs }], {\n mutationId: opts.mutationId,\n });\n return { id, duplicate };\n}\n\n/** Patch a task's lifecycle fields. Moving to `done` stamps `completedAt`;\n * reopening clears it. Only `task` activities accept status changes. */\nexport async function updateTask(\n deps: CrmDeps,\n opts: {\n id: string;\n status?: TaskStatus;\n dueAt?: number | null;\n assigneeId?: string | null;\n waitingOn?: string | null;\n body?: string;\n mutationId?: string;\n },\n): Promise<{ activity: CrmActivity; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.activity]: { $: { where: { id: opts.id }, limit: 1 } } });\n const row = (result[CRM_NS.activity] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"activity\");\n const activity = rowToActivity(row);\n if (activity.kind !== \"task\") throw new CrmInputError(\"only tasks can be updated\");\n // A patch whose `null` values mean CLEAR: reopening a task retracts\n // `completedAt`, and dueAt/assigneeId/waitingOn clear when passed null (a\n // typed scalar can't store null — patchOps turns those into a `retract`).\n const patch: Record<string, unknown> = {};\n if (opts.status !== undefined) {\n if (!TASK_STATUSES.includes(opts.status)) throw new CrmInputError(`unknown status \"${opts.status}\"`);\n patch.status = opts.status;\n patch.completedAt = opts.status === \"done\" ? now() : null;\n }\n if (opts.dueAt !== undefined) patch.dueAt = opts.dueAt;\n if (opts.assigneeId !== undefined) patch.assigneeId = opts.assigneeId;\n if (opts.waitingOn !== undefined) patch.waitingOn = opts.waitingOn;\n if (opts.body !== undefined) {\n const body = opts.body.trim();\n if (!body) throw new CrmInputError(\"body is required\");\n patch.body = body;\n }\n if (Object.keys(patch).length === 0) throw new CrmInputError(\"nothing to update\");\n const { duplicate } = await db.transact(patchOps(CRM_NS.activity, opts.id, patch), {\n mutationId: opts.mutationId,\n });\n return { activity: applyPatch(activity, patch) as CrmActivity, duplicate };\n}\n\n/** A record's activity feed, newest first. */\nexport async function listActivities(\n deps: CrmDeps,\n opts: { recordId: string; kind?: ActivityKind; limit?: number; offset?: number },\n): Promise<CrmActivity[]> {\n const { db } = resolveDeps(deps);\n const where = opts.kind\n ? { and: [{ recordId: opts.recordId }, { kind: opts.kind }] }\n : { recordId: opts.recordId };\n const result = await db.query({\n [CRM_NS.activity]: {\n $: {\n where,\n order: { createdAt: \"desc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return (result[CRM_NS.activity] ?? []).map(rowToActivity);\n}\n\n/** Open follow-ups across records, soonest due first — the \"Waiting on\"\n * board. Defaults to open+waiting; filter to one assignee for \"mine\". */\nexport async function listTasks(\n deps: CrmDeps,\n opts: { assigneeId?: string; status?: TaskStatus[]; dueBefore?: number; limit?: number; offset?: number } = {},\n): Promise<CrmActivity[]> {\n const { db } = resolveDeps(deps);\n const and: Record<string, unknown>[] = [{ kind: \"task\" }];\n const statuses = opts.status ?? [\"open\", \"waiting\"];\n and.push({ status: statuses.length === 1 ? statuses[0] : { $in: statuses } });\n if (opts.assigneeId) and.push({ assigneeId: opts.assigneeId });\n if (opts.dueBefore != null) and.push({ dueAt: { $lte: opts.dueBefore } });\n const result = await db.query({\n [CRM_NS.activity]: {\n $: {\n where: { and },\n order: { dueAt: \"asc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return (result[CRM_NS.activity] ?? []).map(rowToActivity);\n}\n","// Saved views: a named, serializable (filters, sort, columns) triple per\n// type — personal by default, shareable to the team. Specs are validated by\n// DRY-RUNNING the query compiler, so a view that saves is a view that runs.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport { compileList, type CrmSort, type ViewFilters } from \"./query\";\nimport type { CrmAttrs, CrmView } from \"./types\";\n\n/** The serializable definition of a saved view. */\nexport interface ViewSpec {\n name: string;\n type: string;\n filters: ViewFilters;\n sort: CrmSort | null;\n columns: string[];\n shared: boolean;\n}\n\nconst rowToView = (row: Record<string, unknown>): CrmView => {\n const view = row as unknown as CrmView;\n return { ...view, filters: view.filters ?? {}, columns: view.columns ?? [] };\n};\n\nfunction checkSpec(deps: CrmDeps, spec: ViewSpec): void {\n const { crm } = resolveDeps(deps);\n if (!spec.name.trim()) throw new CrmInputError(\"view name is required\");\n if (!Array.isArray(spec.columns) || spec.columns.some((c) => typeof c !== \"string\"))\n throw new CrmInputError(\"columns must be a string array\");\n // The one true validator: if the compiler accepts it, the list route will.\n compileList(crm, { type: spec.type, ...spec.filters, sort: spec.sort ?? undefined });\n}\n\n/** Persist a new view after dry-running its spec through the compiler. */\nexport async function saveView(\n deps: CrmDeps,\n opts: { spec: ViewSpec; ownerId: string; mutationId?: string },\n): Promise<{ id: string; duplicate: boolean }> {\n const { db, now, newId } = resolveDeps(deps);\n checkSpec(deps, opts.spec);\n const id = newId();\n const at = now();\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.view,\n id,\n attrs: {\n id, // mirror the entity id so getView/updateView can read one by id\n name: opts.spec.name.trim(),\n type: opts.spec.type,\n ownerId: opts.ownerId,\n shared: opts.spec.shared,\n filters: opts.spec.filters,\n sort: opts.spec.sort,\n columns: opts.spec.columns,\n createdAt: at,\n updatedAt: at,\n },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { id, duplicate };\n}\n\nasync function mustGetView(deps: CrmDeps, id: string): Promise<CrmView> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.view]: { $: { where: { id }, limit: 1 } } });\n const row = (result[CRM_NS.view] ?? [])[0];\n if (!row) throw new CrmNotFoundError(\"view\");\n return rowToView(row);\n}\n\n/** Update a view you own (shared views are editable by their owner only —\n * the route layer passes the acting admin as `ownerId`). */\nexport async function updateView(\n deps: CrmDeps,\n opts: { id: string; spec: Partial<ViewSpec>; ownerId: string; mutationId?: string },\n): Promise<{ view: CrmView; duplicate: boolean }> {\n const { db, now } = resolveDeps(deps);\n const existing = await mustGetView(deps, opts.id);\n if (existing.ownerId && existing.ownerId !== opts.ownerId)\n throw new CrmInputError(\"only the view's owner may change it\");\n const merged: ViewSpec = {\n name: opts.spec.name ?? existing.name,\n type: opts.spec.type ?? existing.type,\n filters: opts.spec.filters ?? (existing.filters as ViewFilters),\n sort: opts.spec.sort !== undefined ? opts.spec.sort : existing.sort,\n columns: opts.spec.columns ?? existing.columns,\n shared: opts.spec.shared ?? existing.shared,\n };\n checkSpec(deps, merged);\n const attrs: CrmAttrs = {\n name: merged.name.trim(),\n type: merged.type,\n shared: merged.shared,\n filters: merged.filters,\n sort: merged.sort,\n columns: merged.columns,\n updatedAt: now(),\n };\n const { duplicate } = await db.transact([{ t: \"update\", ns: CRM_NS.view, id: opts.id, attrs }], {\n mutationId: opts.mutationId,\n });\n return { view: { ...existing, ...attrs } as CrmView, duplicate };\n}\n\n/** Delete a view you own. */\nexport async function deleteView(\n deps: CrmDeps,\n opts: { id: string; ownerId: string; mutationId?: string },\n): Promise<{ duplicate: boolean }> {\n const { db } = resolveDeps(deps);\n const existing = await mustGetView(deps, opts.id);\n if (existing.ownerId && existing.ownerId !== opts.ownerId)\n throw new CrmInputError(\"only the view's owner may delete it\");\n const { duplicate } = await db.transact([{ t: \"delete\", ns: CRM_NS.view, id: opts.id }], {\n mutationId: opts.mutationId,\n });\n return { duplicate };\n}\n\n/** Views visible to a viewer: everything shared plus their own, optionally\n * narrowed to one record type. */\nexport async function listViews(\n deps: CrmDeps,\n opts: { viewerId: string; type?: string },\n): Promise<CrmView[]> {\n const { db } = resolveDeps(deps);\n const visible = { or: [{ shared: true }, { ownerId: opts.viewerId }] };\n const where = opts.type ? { and: [{ type: opts.type }, visible] } : visible;\n const result = await db.query({\n [CRM_NS.view]: { $: { where, order: { createdAt: \"asc\" }, limit: 200 } },\n });\n return (result[CRM_NS.view] ?? []).map(rowToView);\n}\n","// The runtime-editable side of CRM configuration: one `crm_config` row\n// holding destination addresses and the owner-editable template COPY.\n// Template CONTRACTS (vars, consent class) stay in code (`defineCrm`).\nimport { CONFIG_KEY, CRM_NS } from \"./constants\";\nimport type { Crm } from \"./config\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { CrmInputError } from \"./errors\";\nimport { lintTemplate } from \"./template\";\nimport { patchOps } from \"./write-ops\";\nimport type { CrmConfigRow, StoredTemplate } from \"./types\";\n\n/** Seed copy for every declared template: the spec's defaults, enabled; a\n * spec without defaults seeds empty and DISABLED (nothing sends until the\n * owner writes copy). */\nexport function defaultTemplates(crm: Crm): Record<string, StoredTemplate> {\n const out: Record<string, StoredTemplate> = {};\n for (const [id, spec] of Object.entries(crm.config.templates ?? {})) {\n out[id] = spec.defaults\n ? { subject: spec.defaults.subject, text: spec.defaults.text, enabled: true }\n : { subject: \"\", text: \"\", enabled: false };\n }\n return out;\n}\n\nconst rowToConfig = (row: Record<string, unknown>): CrmConfigRow => {\n const config = row as unknown as CrmConfigRow;\n return { ...config, emailTemplates: config.emailTemplates ?? {}, settings: config.settings ?? {} };\n};\n\n/** Read the crm_config singleton, or null before the first save. */\nexport async function getConfig(deps: CrmDeps): Promise<CrmConfigRow | null> {\n const { db } = resolveDeps(deps);\n const result = await db.query({ [CRM_NS.config]: { $: { where: { key: CONFIG_KEY }, limit: 1 } } });\n const row = (result[CRM_NS.config] ?? [])[0];\n return row ? rowToConfig(row) : null;\n}\n\n/** Partial config update; explicit null clears an address. */\nexport interface ConfigPatch {\n notificationEmail?: string | null;\n replyTo?: string | null;\n debugEmail?: string | null;\n emailTemplates?: Record<string, Partial<StoredTemplate>>;\n settings?: Record<string, unknown>;\n}\n\n/**\n * Upsert the singleton config row (natural key, idempotent). Template edits\n * are validated against the code-declared registry — an id `defineCrm`\n * never declared is refused, so data rows can't invent send paths. First\n * write seeds every declared template's default copy.\n */\nexport async function saveConfig(\n deps: CrmDeps,\n patch: ConfigPatch,\n opts: { mutationId?: string } = {},\n): Promise<{ config: CrmConfigRow; duplicate: boolean }> {\n const { crm, db, now } = resolveDeps(deps);\n const declared = crm.config.templates ?? {};\n for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {\n if (!declared[id]) throw new CrmInputError(`unknown template \"${id}\"`);\n if (tpl.subject !== undefined && typeof tpl.subject !== \"string\")\n throw new CrmInputError(`template \"${id}\": subject must be a string`);\n if (tpl.text !== undefined && typeof tpl.text !== \"string\")\n throw new CrmInputError(`template \"${id}\": text must be a string`);\n if (tpl.enabled !== undefined && typeof tpl.enabled !== \"boolean\")\n throw new CrmInputError(`template \"${id}\": enabled must be a boolean`);\n const copy = [tpl.subject, tpl.text].filter((value): value is string => typeof value === \"string\").join(\"\\n\");\n const unknown = lintTemplate(copy, declared[id]!.vars).unknown;\n if (unknown.length) throw new CrmInputError(`template \"${id}\": unknown vars ${unknown.join(\", \")}`);\n }\n const existing = await getConfig(deps);\n const base = existing ?? {\n id: \"\",\n key: CONFIG_KEY,\n emailTemplates: defaultTemplates(crm),\n settings: {},\n updatedAt: 0,\n };\n const templates: Record<string, StoredTemplate> = { ...defaultTemplates(crm), ...base.emailTemplates };\n for (const [id, tpl] of Object.entries(patch.emailTemplates ?? {})) {\n const prev = templates[id] ?? { subject: \"\", text: \"\", enabled: false };\n templates[id] = { ...prev, ...tpl };\n }\n const merged: CrmConfigRow = {\n ...base,\n notificationEmail:\n patch.notificationEmail !== undefined\n ? (patch.notificationEmail ?? undefined)\n : base.notificationEmail,\n replyTo: patch.replyTo !== undefined ? (patch.replyTo ?? undefined) : base.replyTo,\n debugEmail: patch.debugEmail !== undefined ? (patch.debugEmail ?? undefined) : base.debugEmail,\n emailTemplates: templates,\n settings: patch.settings !== undefined ? patch.settings : base.settings,\n updatedAt: now(),\n };\n // An unset optional email is null in `write`, which patchOps turns into a\n // retract (odla-db can't store a scalar null). The `update` half also creates\n // the singleton on first save, so the retract's key lookup then resolves.\n const write: Record<string, unknown> = {\n key: CONFIG_KEY,\n notificationEmail: merged.notificationEmail ?? null,\n replyTo: merged.replyTo ?? null,\n debugEmail: merged.debugEmail ?? null,\n emailTemplates: merged.emailTemplates,\n settings: merged.settings,\n updatedAt: merged.updatedAt,\n };\n const { duplicate } = await db.transact(\n patchOps(CRM_NS.config, { ns: CRM_NS.config, attr: \"key\", value: CONFIG_KEY }, write),\n { mutationId: opts.mutationId },\n );\n return { config: merged, duplicate };\n}\n","// The audited, consent-gated send path (S&S's sendTemplated generalized).\n// Gate order: template declared → copy enabled → consent (class-aware) →\n// dedupe → dev-redirect/log-only → transport. Success rows are written with\n// `mutationId email:{dedupeKey}` so a replayed trigger never double-logs;\n// FAILURE rows are written unconditionally so a retry's success is never\n// swallowed by its own earlier failure.\nimport { CRM_NS } from \"./constants\";\nimport { listChannels } from \"./channels\";\nimport { canEmail } from \"./consent\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\nimport { getConfig } from \"./config-store\";\nimport { mustGetRecord } from \"./records\";\nimport { renderTemplate } from \"./template\";\nimport type { CrmAttrs, CrmContactChannel, CrmEmailSender } from \"./types\";\n\n/** Inputs for one templated send (see {@link sendTemplatedEmail}). */\nexport interface SendEmailOpts {\n recordId: string;\n /** Defaults to the record's primary email channel. */\n channelId?: string;\n templateId: string;\n vars: Record<string, string>;\n /** Retry identity: a prior successful send with this key short-circuits. */\n dedupeKey: string;\n /** Sender address (env-owned, e.g. the verified EMAIL_FROM). */\n from: string;\n /** Anything but \"production\" redirects to the config debugEmail (subject\n * gets a \"[dev] \" prefix) or falls back to log-only. */\n envName: string;\n /** Absolute origin for links (unsubscribe). */\n baseUrl: string;\n /** Route mount point for the unsubscribe link. Default \"/api/crm\". */\n basePath?: string;\n /** Admin test-send: bypasses the enabled flag — NEVER the consent gate. */\n force?: boolean;\n}\n\n/** What happened to the send — delivered, gated, logged, or failed. */\nexport interface SendEmailResult {\n sent: boolean;\n /** Why nothing was delivered (gates, log-only, transport error). */\n reason?: string;\n transport?: \"sent\" | \"log-only\";\n}\n\n/**\n * Render and send one templated email to a record's contact channel, with\n * consent gating, dedupe, dev redirection, and an unconditional audit row.\n * Marketing-class sends get `{{unsubscribeUrl}}` plus RFC 8058 one-click\n * headers automatically.\n */\nexport async function sendTemplatedEmail(\n deps: CrmDeps & { sender?: CrmEmailSender },\n opts: SendEmailOpts,\n): Promise<SendEmailResult> {\n const { crm, db, now, newId } = resolveDeps(deps);\n const spec = crm.config.templates?.[opts.templateId];\n if (!spec) return { sent: false, reason: \"unknown_template\" };\n const config = await getConfig(deps);\n const stored = config?.emailTemplates[opts.templateId] ?? null;\n if (!stored || (!stored.subject && !stored.text)) return { sent: false, reason: \"no_template_copy\" };\n if (!stored.enabled && !opts.force) return { sent: false, reason: \"disabled\" };\n\n const record = await mustGetRecord(deps, opts.recordId);\n const channels = await listChannels(deps, record.id);\n const channel: CrmContactChannel | undefined = opts.channelId\n ? channels.find((c) => c.id === opts.channelId)\n : channels.find((c) => c.kind === \"email\" && c.isPrimary);\n if (!channel) return { sent: false, reason: \"no_channel\" };\n if (!canEmail(channel.consent, spec.class)) return { sent: false, reason: \"blocked_by_consent\" };\n\n const prior = await db.query({\n [CRM_NS.emailLog]: { $: { where: { dedupeKey: opts.dedupeKey }, limit: 10 } },\n });\n // Only a real delivery is a duplicate — log-only rows (dev, missing\n // sender) must never block the eventual production send.\n if ((prior[CRM_NS.emailLog] ?? []).some((row) => !row[\"error\"] && row[\"transport\"] === \"sent\"))\n return { sent: false, reason: \"duplicate\" };\n\n const vars = { ...opts.vars };\n const headers: Record<string, string> = {};\n if (spec.class === \"marketing\") {\n const unsubscribeUrl = `${opts.baseUrl}${opts.basePath ?? \"/api/crm\"}/unsubscribe?token=${channel.unsubscribeToken}`;\n vars[\"unsubscribeUrl\"] = vars[\"unsubscribeUrl\"] ?? unsubscribeUrl;\n headers[\"List-Unsubscribe\"] = `<${unsubscribeUrl}>`;\n headers[\"List-Unsubscribe-Post\"] = \"List-Unsubscribe=One-Click\";\n }\n let subject = renderTemplate(stored.subject, vars);\n const text = renderTemplate(stored.text, vars);\n\n let to = channel.value;\n let redirected = false;\n let logOnly = !deps.sender;\n if (opts.envName !== \"production\") {\n if (config?.debugEmail) {\n to = config.debugEmail;\n subject = `[dev] ${subject}`;\n redirected = true;\n } else {\n logOnly = true;\n }\n }\n\n const logRow = (extra: CrmAttrs, mutationId?: string): Promise<unknown> =>\n db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.emailLog,\n id: newId(),\n attrs: {\n recordId: opts.recordId,\n channelId: channel.id,\n to,\n templateId: opts.templateId,\n subject,\n redirected,\n dedupeKey: opts.dedupeKey,\n sentAt: now(),\n ...extra,\n },\n },\n ],\n { mutationId },\n );\n\n if (logOnly || !deps.sender) {\n // Distinct mutation identity: must not consume `email:{dedupeKey}`,\n // which belongs to the eventual real delivery's log row.\n await logRow({ transport: \"log-only\" }, `email-log:${opts.dedupeKey}`);\n return { sent: false, reason: \"log_only\", transport: \"log-only\" };\n }\n try {\n const receipt = await deps.sender.send({\n from: opts.from,\n to: [to],\n subject,\n text,\n ...(config?.replyTo ? { replyTo: config.replyTo } : {}),\n ...(Object.keys(headers).length > 0 ? { headers } : {}),\n });\n await logRow({ transport: \"sent\", messageId: receipt.messageId }, `email:${opts.dedupeKey}`);\n return { sent: true, transport: \"sent\" };\n } catch (error) {\n // Unconditional failure row (fresh id, no mutationId): a later retry's\n // success must not be suppressed by this failure's identity.\n await logRow({ transport: \"sent\", error: error instanceof Error ? error.message : String(error) });\n return { sent: false, reason: \"transport_error\" };\n }\n}\n\n/** Recent sends for the settings audit table, newest first. */\nexport async function listEmailLog(\n deps: CrmDeps,\n opts: { recordId?: string; limit?: number; offset?: number } = {},\n): Promise<Record<string, unknown>[]> {\n const { db } = resolveDeps(deps);\n const result = await db.query({\n [CRM_NS.emailLog]: {\n $: {\n ...(opts.recordId ? { where: { recordId: opts.recordId } } : {}),\n order: { sentAt: \"desc\" },\n limit: Math.min(opts.limit ?? 50, 200),\n offset: opts.offset ?? 0,\n },\n },\n });\n return result[CRM_NS.emailLog] ?? [];\n}\n\n/** Guard for host-owned send paths (broadcasts, billing emails): may this\n * record receive `cls` mail right now? */\nexport async function recordCanEmail(\n deps: CrmDeps,\n recordId: string,\n cls: \"transactional\" | \"marketing\",\n): Promise<boolean> {\n const channels = await listChannels(deps, recordId);\n const primary = channels.find((c) => c.kind === \"email\" && c.isPrimary);\n if (!primary) return false;\n return canEmail(primary.consent, cls);\n}\n","// Identity facet: connect a record to the app's Clerk-synced `$users` row by\n// email (the S&S lazy-link pattern — members appear in $users at first\n// sign-in, and the CRM record picks up the account when the emails meet).\nimport { CRM_NS } from \"../constants\";\nimport { resolveDeps, type CrmDeps } from \"../deps\";\nimport { CrmInputError } from \"../errors\";\nimport { mustGetRecord } from \"../records\";\n\n/**\n * Look up `$users` by (lowercased) email and stamp the record's\n * `clerkUserId`. Uses the record's `primaryEmail` unless an explicit email\n * is given. Returns `linked: false` when no account exists yet — call again\n * after the person signs in (idempotent under `mutationId`).\n */\nexport async function linkIdentity(\n deps: CrmDeps,\n opts: { recordId: string; email?: string; mutationId?: string },\n): Promise<{ linked: boolean; clerkUserId?: string; duplicate?: boolean }> {\n const { db, now } = resolveDeps(deps);\n const record = await mustGetRecord(deps, opts.recordId);\n const email = (opts.email ?? record.primaryEmail)?.trim().toLowerCase();\n if (!email) throw new CrmInputError(\"record has no email to match on\");\n const result = await db.query({ $users: { $: { where: { email }, limit: 1 } } });\n const user = (result[\"$users\"] ?? []).find((row) => !row[\"deleted\"]);\n if (!user) return { linked: false };\n const { duplicate } = await db.transact(\n [\n {\n t: \"update\",\n ns: CRM_NS.record,\n id: record.id,\n attrs: { clerkUserId: user.id, updatedAt: now() },\n },\n ],\n { mutationId: opts.mutationId },\n );\n return { linked: true, clerkUserId: user.id, duplicate };\n}\n","// Batched aggregates for the shell's summary tiles: odla-db has no faceted\n// counts, so each tile is one `aggregate` call — this module runs them\n// concurrently and returns a single payload.\nimport { CRM_NS } from \"./constants\";\nimport { resolveDeps, type CrmDeps } from \"./deps\";\n\n/** Tile counts for one record type. */\nexport interface TypeSummary {\n type: string;\n total: number;\n /** Live records per pipeline stage (types with a pipeline). */\n stages: Record<string, number>;\n /** Open + waiting follow-up tasks across all records. */\n openTasks: number;\n}\n\n/**\n * Tile counts for one record type: total live records, per-stage counts,\n * and the open-task load. Each count is an indexed-where aggregate; a type\n * with S stages costs S+2 calls, issued concurrently.\n */\nexport async function typeSummary(deps: CrmDeps, type: string): Promise<TypeSummary> {\n const { crm, db } = resolveDeps(deps);\n const def = crm.type(type);\n const live = (extra: Record<string, unknown>[]) => ({\n where: { and: [{ type }, { archived: false }, ...extra] },\n });\n const stageIds = (def.pipeline?.stages ?? []).map((s) => s.id);\n const [total, openTasks, ...stageCounts] = await Promise.all([\n db.aggregate(CRM_NS.record, { count: true }, live([])),\n db.aggregate(CRM_NS.activity, { count: true }, {\n where: { and: [{ kind: \"task\" }, { status: { $in: [\"open\", \"waiting\"] } }] },\n }),\n ...stageIds.map((stage) => db.aggregate(CRM_NS.record, { count: true }, live([{ stage }]))),\n ]);\n const stages: Record<string, number> = {};\n stageIds.forEach((stage, i) => {\n stages[stage] = stageCounts[i]?.count ?? 0;\n });\n return { type, total: total?.count ?? 0, stages, openTasks: openTasks?.count ?? 0 };\n}\n","// HTTP plumbing for the route factory: option resolution, JSON helpers, the\n// error → status mapping, list-param parsing, and the unsubscribe page HTML.\nimport type { Crm } from \"./config\";\nimport type { CrmDeps } from \"./deps\";\nimport { CrmInputError, CrmNotFoundError } from \"./errors\";\nimport type { CrmListParams } from \"./query\";\nimport type { CrmDb, CrmEmailSender } from \"./types\";\n\n/** The authenticated admin performing a request (host-resolved — the crm\n * routes are an admin surface; end-user access is a future rules story). */\nexport interface CrmActor {\n userId: string;\n email?: string;\n /** Explicit product ACL for the read-only Discussion projection. Ordinary\n * CRM routes do not consult or grant this marker. */\n discussionReferenceScope?: \"all\";\n}\n\n/** Actor accepted by the product-owned CRM reference projection. */\nexport interface CrmDiscussionReferenceActor extends CrmActor {\n discussionReferenceScope: \"all\";\n}\n\n/** Everything `createCrmRoutes` needs from the host worker. */\nexport interface CrmRouteOpts {\n crm: Crm;\n db: CrmDb;\n /** Host-owned auth: resolve the request to an admin actor or null (401).\n * The unsubscribe endpoints are the only routes that skip this. */\n authorize: (req: Request) => Promise<CrmActor | null> | CrmActor | null;\n /** Optional host authority seam for read-only Discussion reference lookup.\n * Verify exact CRM product, crm.read capability, canonical audience,\n * principal, current app lifetime/environment, and agent grant provenance. */\n authorizeDiscussionReferences?: (\n req: Request,\n ) =>\n | Promise<CrmDiscussionReferenceActor | null>\n | CrmDiscussionReferenceActor\n | null;\n /** Email transport; omit for log-only behavior. */\n sender?: CrmEmailSender;\n /** Sender address for outbound mail (verified from-address). */\n from?: string;\n /** Only exactly \"production\" delivers to real recipients — anything else\n * dev-redirects or logs only. Defaults fail-safe to \"development\". */\n envName?: string;\n /** Absolute origin for links in emails (unsubscribe). */\n baseUrl?: string;\n /** Mount point. Default \"/api/crm\". */\n basePath?: string;\n /** Native UI mount used by returned Discussion deep links. Default \"/admin/\". */\n discussionBasePath?: string;\n /** Injectable clock/id factory (tests). */\n now?: () => number;\n newId?: () => string;\n}\n\n/** Per-request context handed to route handlers. */\nexport interface RouteCtx {\n deps: CrmDeps & { sender?: CrmEmailSender };\n opts: Required<\n Pick<\n CrmRouteOpts,\n \"basePath\" | \"envName\" | \"baseUrl\" | \"discussionBasePath\"\n >\n > & CrmRouteOpts;\n actor: CrmActor;\n}\n\nexport const json = (body: unknown, status = 200): Response =>\n new Response(JSON.stringify(body), {\n status,\n headers: { \"content-type\": \"application/json\" },\n });\n\nexport const errorResponse = (error: unknown): Response => {\n if (error instanceof CrmInputError)\n return json({ error: error.message, ...(error.fields ? { fields: error.fields } : {}) }, 400);\n if (error instanceof CrmNotFoundError) return json({ error: error.message }, 404);\n return json({ error: \"internal error\" }, 500);\n};\n\n/** Parse a JSON object body; CrmInputError (→ 400) on anything else. */\nexport async function readJson(req: Request): Promise<Record<string, unknown>> {\n let body: unknown;\n try {\n body = await req.json();\n } catch {\n throw new CrmInputError(\"invalid JSON body\");\n }\n if (typeof body !== \"object\" || body === null || Array.isArray(body))\n throw new CrmInputError(\"body must be a JSON object\");\n return body as Record<string, unknown>;\n}\n\nconst csv = (value: string | null): string[] | undefined =>\n value ? value.split(\",\").map((v) => v.trim()).filter(Boolean) : undefined;\n\nconst int = (value: string | null): number | undefined => {\n if (value == null || value === \"\") return undefined;\n const n = Number(value);\n if (!Number.isInteger(n)) throw new CrmInputError(`not an integer: \"${value}\"`);\n return n;\n};\n\n/** Decode `GET /records` search params into {@link CrmListParams}.\n * `sort=field:dir`, csv multi-filters, `fields` as URL-encoded JSON. */\nexport function parseListParams(url: URL): CrmListParams {\n const q = url.searchParams;\n const type = q.get(\"type\");\n if (!type) throw new CrmInputError(\"type is required\");\n const params: CrmListParams = { type };\n const search = q.get(\"search\");\n if (search) params.search = search;\n params.stage = csv(q.get(\"stage\"));\n params.emailStatus = csv(q.get(\"emailStatus\"));\n params.billingStatus = csv(q.get(\"billingStatus\"));\n const ownerId = q.get(\"ownerId\");\n if (ownerId) params.ownerId = ownerId;\n const tag = q.get(\"tag\");\n if (tag) params.tag = tag;\n if (q.get(\"archived\") === \"true\") params.archived = true;\n const sort = q.get(\"sort\");\n if (sort) {\n const [field, dir] = sort.split(\":\");\n if (!field || (dir !== \"asc\" && dir !== \"desc\"))\n throw new CrmInputError('sort must be \"field:asc\" or \"field:desc\"');\n params.sort = { field, dir };\n }\n params.limit = int(q.get(\"limit\"));\n params.offset = int(q.get(\"offset\"));\n const fields = q.get(\"fields\");\n if (fields) {\n try {\n params.fields = JSON.parse(fields) as CrmListParams[\"fields\"];\n } catch {\n throw new CrmInputError(\"fields must be URL-encoded JSON\");\n }\n }\n return params;\n}\n\nconst escapeHtml = (s: string): string =>\n s.replace(/[&<>\"']/g, (c) => `&#${c.charCodeAt(0)};`);\n\n/** The unsubscribe confirmation page. A GET must NEVER mutate (mail\n * scanners prefetch links); the form's POST performs the flip. */\nexport function unsubscribePage(token: string, done: boolean): Response {\n const body = done\n ? \"<p>You're unsubscribed. You can close this page.</p>\"\n : `<form method=\"post\"><input type=\"hidden\" name=\"token\" value=\"${escapeHtml(token)}\">` +\n `<p>Stop receiving these emails?</p><button type=\"submit\">Unsubscribe</button></form>`;\n return new Response(\n `<!doctype html><meta charset=\"utf-8\"><meta name=\"robots\" content=\"noindex\">` +\n `<title>Unsubscribe</title><main style=\"font-family:system-ui;max-width:32rem;margin:4rem auto\">${body}</main>`,\n { status: 200, headers: { \"content-type\": \"text/html; charset=utf-8\" } },\n );\n}\n","// Tiny body-field extractors: consistent CrmInputError messages so every\n// handler validates the same way without a schema library.\nimport { CrmInputError } from \"../errors\";\n\ntype Body = Record<string, unknown>;\n\nexport function str(body: Body, key: string): string {\n const value = body[key];\n if (typeof value !== \"string\" || value === \"\")\n throw new CrmInputError(`\"${key}\" must be a non-empty string`);\n return value;\n}\n\nexport function optStr(body: Body, key: string): string | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"string\") throw new CrmInputError(`\"${key}\" must be a string`);\n return value;\n}\n\n/** Distinguishes \"absent\" (undefined) from an explicit null (clear). */\nexport function nullableStr(body: Body, key: string): string | null | undefined {\n const value = body[key];\n if (value === undefined) return undefined;\n if (value === null) return null;\n if (typeof value !== \"string\") throw new CrmInputError(`\"${key}\" must be a string or null`);\n return value;\n}\n\nexport function optNum(body: Body, key: string): number | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new CrmInputError(`\"${key}\" must be a number`);\n return value;\n}\n\nexport function nullableNum(body: Body, key: string): number | null | undefined {\n const value = body[key];\n if (value === undefined) return undefined;\n if (value === null) return null;\n if (typeof value !== \"number\" || !Number.isFinite(value))\n throw new CrmInputError(`\"${key}\" must be a number or null`);\n return value;\n}\n\nexport function optBool(body: Body, key: string): boolean | undefined {\n const value = body[key];\n if (value === undefined || value === null) return undefined;\n if (typeof value !== \"boolean\") throw new CrmInputError(`\"${key}\" must be a boolean`);\n return value;\n}\n\nexport function obj(body: Body, key: string): Record<string, unknown> {\n const value = body[key];\n if (typeof value !== \"object\" || value === null || Array.isArray(value))\n throw new CrmInputError(`\"${key}\" must be an object`);\n return value as Record<string, unknown>;\n}\n\nexport function optObj(body: Body, key: string): Record<string, unknown> | undefined {\n if (body[key] === undefined) return undefined;\n return obj(body, key);\n}\n","// Activity + follow-up handlers: a record's feed, the cross-record task\n// board, and task lifecycle patches.\nimport { addActivity, listActivities, listTasks, updateTask } from \"../activities\";\nimport type { ActivityKind, TaskStatus } from \"../constants\";\nimport { CrmInputError } from \"../errors\";\nimport { json, readJson, type RouteCtx } from \"../http\";\nimport { nullableNum, nullableStr, optNum, optObj, optStr, str } from \"./params\";\n\nexport async function handleRecordActivities(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n recordId: string,\n): Promise<Response> {\n if (req.method === \"GET\") {\n const activities = await listActivities(ctx.deps, {\n recordId,\n kind: (url.searchParams.get(\"kind\") as ActivityKind | null) ?? undefined,\n limit: numParam(url, \"limit\"),\n offset: numParam(url, \"offset\"),\n });\n return json({ activities });\n }\n if (req.method === \"POST\") {\n const body = await readJson(req);\n const created = await addActivity(ctx.deps, {\n recordId,\n kind: str(body, \"kind\") as ActivityKind,\n body: str(body, \"body\"),\n authorId: ctx.actor.userId,\n dueAt: optNum(body, \"dueAt\"),\n assigneeId: optStr(body, \"assigneeId\"),\n waitingOn: optStr(body, \"waitingOn\"),\n meta: optObj(body, \"meta\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(created, 201);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleActivityItem(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"PATCH\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const status = optStr(body, \"status\");\n const result = await updateTask(ctx.deps, {\n id,\n status: status as TaskStatus | undefined,\n dueAt: nullableNum(body, \"dueAt\"),\n assigneeId: nullableStr(body, \"assigneeId\"),\n waitingOn: nullableStr(body, \"waitingOn\"),\n body: optStr(body, \"body\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleTasks(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const statusCsv = url.searchParams.get(\"status\");\n const tasks = await listTasks(ctx.deps, {\n assigneeId: url.searchParams.get(\"assigneeId\") ?? undefined,\n status: statusCsv ? (statusCsv.split(\",\").filter(Boolean) as TaskStatus[]) : undefined,\n dueBefore: numParam(url, \"dueBefore\"),\n limit: numParam(url, \"limit\"),\n offset: numParam(url, \"offset\"),\n });\n return json({ tasks });\n}\n\nfunction numParam(url: URL, key: string): number | undefined {\n const raw = url.searchParams.get(key);\n if (raw == null || raw === \"\") return undefined;\n const n = Number(raw);\n if (!Number.isFinite(n)) throw new CrmInputError(`\"${key}\" must be a number`);\n return n;\n}\n","// Per-record actions: stage moves (post-commit hook fired here, failures\n// reported but never un-commit the write), rank placement, tags, links,\n// identity linking, and templated sends.\nimport { sendTemplatedEmail } from \"../email\";\nimport { CrmInputError } from \"../errors\";\nimport { linkIdentity } from \"../facets/identity\";\nimport { json, readJson, type RouteCtx } from \"../http\";\nimport { resolveDeps } from \"../deps\";\nimport { setRank, setStage } from \"../stage-rank\";\nimport { addLink, addTag, removeLink, removeTag } from \"../tags-links\";\nimport { optBool, optObj, optStr, str } from \"./params\";\n\nexport async function handleStage(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const moved = await setStage(ctx.deps, {\n id,\n to: str(body, \"to\"),\n authorId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n let hookError: string | undefined;\n if (moved.hook && !moved.duplicate) {\n // Post-commit side effect (e.g. Clerk role promotion). Its failure is\n // surfaced to the admin but the stage change stands — retry the hook,\n // not the transition.\n try {\n await moved.hook(moved.record);\n } catch (error) {\n hookError = error instanceof Error ? error.message : String(error);\n }\n }\n return json({\n record: moved.record,\n from: moved.from,\n duplicate: moved.duplicate,\n ...(hookError ? { hookError } : {}),\n });\n}\n\nexport async function handleRank(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await setRank(ctx.deps, {\n id,\n beforeId: optStr(body, \"beforeId\"),\n afterId: optStr(body, \"afterId\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleTags(ctx: RouteCtx, req: Request, id: string, rest: string[]): Promise<Response> {\n if (req.method === \"POST\" && rest.length === 0) {\n const body = await readJson(req);\n const result = await addTag(ctx.deps, {\n recordId: id,\n tag: str(body, \"tag\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result, 201);\n }\n if (req.method === \"DELETE\" && rest.length === 1) {\n const result = await removeTag(ctx.deps, { recordId: id, tag: decodeURIComponent(rest[0]!) });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleLinks(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const opts = {\n relation: str(body, \"relation\"),\n fromId: id,\n toId: str(body, \"toId\"),\n mutationId: optStr(body, \"mutationId\"),\n };\n const result = optBool(body, \"remove\")\n ? await removeLink(ctx.deps, opts)\n : await addLink(ctx.deps, opts);\n return json(result);\n}\n\nexport async function handleLinkIdentity(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await linkIdentity(ctx.deps, {\n recordId: id,\n email: optStr(body, \"email\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\nexport async function handleSendEmail(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const from = ctx.opts.from;\n if (!from) throw new CrmInputError(\"email sending is not configured (missing from address)\");\n const vars: Record<string, string> = {};\n for (const [key, value] of Object.entries(optObj(body, \"vars\") ?? {})) {\n if (typeof value !== \"string\") throw new CrmInputError(`var \"${key}\" must be a string`);\n vars[key] = value;\n }\n const result = await sendTemplatedEmail(ctx.deps, {\n recordId: id,\n channelId: optStr(body, \"channelId\"),\n templateId: str(body, \"templateId\"),\n vars,\n dedupeKey: optStr(body, \"dedupeKey\") ?? `manual:${resolveDeps(ctx.deps).newId()}`,\n force: optBool(body, \"force\"),\n from,\n envName: ctx.opts.envName,\n baseUrl: ctx.opts.baseUrl,\n basePath: ctx.opts.basePath,\n });\n return json(result);\n}\n","// /records handlers: the list window, record detail (record + tags +\n// channels + links composed), create/patch, and archive/restore.\nimport { listChannels } from \"../channels\";\nimport { parseListParams, json, type RouteCtx } from \"../http\";\nimport {\n createRecord,\n getRecord,\n listRecords,\n setArchived,\n updateRecord,\n} from \"../records\";\nimport { listLinks, listTags } from \"../tags-links\";\nimport { readJson } from \"../http\";\nimport { CrmNotFoundError } from \"../errors\";\nimport { listRecordDeliveries, listRecordOrigins } from \"../provenance\";\nimport { nullableStr, obj, optBool, optObj, optStr, str } from \"./params\";\n\nexport async function handleRecordsRoot(ctx: RouteCtx, req: Request, url: URL): Promise<Response | null> {\n if (req.method === \"GET\") {\n const result = await listRecords(ctx.deps, parseListParams(url));\n return json(result);\n }\n if (req.method === \"POST\") {\n const body = await readJson(req);\n const created = await createRecord(ctx.deps, {\n type: str(body, \"type\"),\n input: obj(body, \"input\"),\n ownerId: optStr(body, \"ownerId\"),\n stage: optStr(body, \"stage\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json({ id: created.id, duplicate: created.duplicate, record: created.record }, 201);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleRecordItem(ctx: RouteCtx, req: Request, id: string): Promise<Response | null> {\n if (req.method === \"GET\") {\n const record = await getRecord(ctx.deps, id);\n if (!record) throw new CrmNotFoundError(\"record\");\n const [tags, channels, links, origins, deliveries] = await Promise.all([\n listTags(ctx.deps, id),\n listChannels(ctx.deps, id),\n listLinks(ctx.deps, id),\n listRecordOrigins(ctx.deps, id),\n listRecordDeliveries(ctx.deps, { recordId: id }),\n ]);\n return json({ record, tags, channels, links, origins, deliveries });\n }\n if (req.method === \"PATCH\") {\n const body = await readJson(req);\n const updated = await updateRecord(ctx.deps, {\n id,\n input: optObj(body, \"input\") ?? {},\n ownerId: nullableStr(body, \"ownerId\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json({ record: updated.record, duplicate: updated.duplicate });\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleArchive(ctx: RouteCtx, req: Request, id: string): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await setArchived(ctx.deps, {\n id,\n archived: optBool(body, \"archived\") ?? true,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n","// Views, summary tiles, config, the email audit log, rank rebalance, and\n// the PUBLIC unsubscribe pair (GET renders, POST mutates — never the\n// reverse; scanners prefetch GETs).\nimport { applyConsent } from \"../channels\";\nimport { getConfig, saveConfig, type ConfigPatch } from \"../config-store\";\nimport { listEmailLog } from \"../email\";\nimport { CrmInputError } from \"../errors\";\nimport { json, readJson, unsubscribePage, type RouteCtx } from \"../http\";\nimport type { CrmDeps } from \"../deps\";\nimport type { CrmSort, ViewFilters } from \"../query\";\nimport { rebalanceRanks } from \"../stage-rank\";\nimport { typeSummary } from \"../summary\";\nimport { deleteView, listViews, saveView, updateView, type ViewSpec } from \"../views\";\nimport { obj, optBool, optObj, optStr, str } from \"./params\";\n\nfunction specFrom(body: Record<string, unknown>): ViewSpec {\n const spec = obj(body, \"spec\");\n return {\n name: str(spec, \"name\"),\n type: str(spec, \"type\"),\n filters: (optObj(spec, \"filters\") ?? {}) as ViewFilters,\n sort: (spec[\"sort\"] ?? null) as CrmSort | null,\n columns: Array.isArray(spec[\"columns\"]) ? (spec[\"columns\"] as string[]) : [],\n shared: optBool(spec, \"shared\") ?? false,\n };\n}\n\nexport async function handleViews(ctx: RouteCtx, req: Request, url: URL, rest: string[]): Promise<Response> {\n if (rest.length === 0 && req.method === \"GET\") {\n const views = await listViews(ctx.deps, {\n viewerId: ctx.actor.userId,\n type: url.searchParams.get(\"type\") ?? undefined,\n });\n return json({ views });\n }\n if (rest.length === 0 && req.method === \"POST\") {\n const body = await readJson(req);\n const created = await saveView(ctx.deps, {\n spec: specFrom(body),\n ownerId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(created, 201);\n }\n const id = rest[0];\n if (id && req.method === \"PATCH\") {\n const body = await readJson(req);\n const spec = optObj(body, \"spec\") ?? {};\n const result = await updateView(ctx.deps, {\n id,\n spec: spec as Partial<ViewSpec>,\n ownerId: ctx.actor.userId,\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n }\n if (id && req.method === \"DELETE\") {\n const result = await deleteView(ctx.deps, { id, ownerId: ctx.actor.userId });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleSummary(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const type = url.searchParams.get(\"type\");\n if (!type) throw new CrmInputError(\"type is required\");\n return json(await typeSummary(ctx.deps, type));\n}\n\nexport async function handleConfig(ctx: RouteCtx, req: Request): Promise<Response> {\n if (req.method === \"GET\") {\n const config = await getConfig(ctx.deps);\n return json({ config });\n }\n if (req.method === \"PUT\") {\n const body = await readJson(req);\n const result = await saveConfig(ctx.deps, body as ConfigPatch, {\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n }\n return json({ error: \"method not allowed\" }, 405);\n}\n\nexport async function handleEmailLog(ctx: RouteCtx, req: Request, url: URL): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n const limitRaw = url.searchParams.get(\"limit\");\n const rows = await listEmailLog(ctx.deps, {\n recordId: url.searchParams.get(\"recordId\") ?? undefined,\n limit: limitRaw ? Number(limitRaw) : undefined,\n });\n return json({ log: rows });\n}\n\nexport async function handleRebalance(ctx: RouteCtx, req: Request): Promise<Response> {\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n const body = await readJson(req);\n const result = await rebalanceRanks(ctx.deps, {\n type: str(body, \"type\"),\n mutationId: optStr(body, \"mutationId\"),\n });\n return json(result);\n}\n\n/** No auth here — the token IS the credential (unique, unguessable, scoped\n * to one channel). GET renders the confirm form; POST flips consent,\n * idempotently (`consent:{token}:{event}`), accepting the RFC 8058\n * one-click body, a form post, or JSON. */\nexport async function handleUnsubscribe(deps: CrmDeps, req: Request, url: URL): Promise<Response> {\n if (req.method === \"GET\") {\n const token = url.searchParams.get(\"token\");\n if (!token) return json({ error: \"token is required\" }, 400);\n return unsubscribePage(token, false);\n }\n if (req.method !== \"POST\") return json({ error: \"method not allowed\" }, 405);\n let token = url.searchParams.get(\"token\") ?? \"\";\n let oneClick = false;\n const contentType = req.headers.get(\"content-type\") ?? \"\";\n if (contentType.includes(\"form\")) {\n const form = await req.formData();\n token = String(form.get(\"token\") ?? token);\n oneClick = String(form.get(\"List-Unsubscribe\") ?? \"\") === \"One-Click\";\n } else if (contentType.includes(\"json\")) {\n const body = (await req.json().catch(() => ({}))) as Record<string, unknown>;\n if (typeof body[\"token\"] === \"string\") token = body[\"token\"];\n }\n if (!token) return json({ error: \"token is required\" }, 400);\n const event = oneClick ? \"unsubscribe.oneclick\" : \"unsubscribe.token\";\n await applyConsent(deps, { token, event, mutationId: `consent:${token}:unsubscribe` });\n return oneClick ? json({ ok: true }) : unsubscribePage(token, true);\n}\n","import { CRM_NS } from \"../constants\";\nimport {\n crmDiscussionReferenceHref,\n crmDiscussionReferenceId,\n parseCrmDiscussionReference,\n type CrmDiscussionReference,\n type CrmDiscussionReferenceTarget,\n} from \"../discussion-reference\";\nimport { getRecord, listRecords } from \"../records\";\nimport type { CrmActivity, CrmRecord } from \"../types\";\nimport { json, type RouteCtx } from \"../http\";\n\nconst capLimit = (raw: string | null): number => {\n const parsed = Number(raw ?? 20);\n return Number.isInteger(parsed) ? Math.max(1, Math.min(parsed, 20)) : 20;\n};\n\nconst targetFromQuery = (url: URL): CrmDiscussionReferenceTarget | null => {\n const kind = url.searchParams.get(\"kind\");\n const id = url.searchParams.get(\"id\");\n if (!kind || !id) return null;\n const value = new URL(\"https://crm.invalid\");\n value.searchParams.set(\"odla-ref\", `${kind}/${id}`);\n return parseCrmDiscussionReference(value);\n};\n\nconst recordItem = (\n ctx: RouteCtx,\n req: Request,\n record: CrmRecord,\n): CrmDiscussionReference => {\n const typeLabel = ctx.deps.crm.type(record.type).label;\n const status = record.archived\n ? \"archived\"\n : record.stage ?? \"record\";\n const target: CrmDiscussionReferenceTarget = {\n kind: \"crm:record\",\n type: record.type,\n recordId: record.id,\n };\n return {\n kind: target.kind,\n id: crmDiscussionReferenceId(target),\n label: record.name,\n hint: `${typeLabel} · ${status}`,\n summary: `${typeLabel} record for ${record.name}`,\n status,\n destination: `CRM · ${typeLabel} profile`,\n href: crmDiscussionReferenceHref(\n new URL(req.url),\n target,\n ctx.opts.discussionBasePath,\n ),\n };\n};\n\nconst activityItem = (\n ctx: RouteCtx,\n req: Request,\n record: CrmRecord,\n activity: CrmActivity,\n): CrmDiscussionReference => {\n const target: CrmDiscussionReferenceTarget = {\n kind: \"crm:activity\",\n type: record.type,\n recordId: record.id,\n activityId: activity.id,\n };\n return {\n kind: target.kind,\n id: crmDiscussionReferenceId(target),\n label: activity.body,\n hint: `${record.name} · ${activity.kind}${\n activity.status ? ` · ${activity.status}` : \"\"\n }`,\n summary: `${activity.kind} on ${record.name}: ${activity.body}`,\n status: activity.status ?? activity.kind,\n destination: `CRM · ${record.name} notes`,\n href: crmDiscussionReferenceHref(\n new URL(req.url),\n target,\n ctx.opts.discussionBasePath,\n ),\n };\n};\n\nasync function exact(\n ctx: RouteCtx,\n req: Request,\n target: CrmDiscussionReferenceTarget,\n): Promise<CrmDiscussionReference[]> {\n const record = await getRecord(ctx.deps, target.recordId);\n if (!record || record.type !== target.type) return [];\n if (target.kind === \"crm:record\") return [recordItem(ctx, req, record)];\n const result = await ctx.deps.db.query({\n [CRM_NS.activity]: {\n $: { where: { id: target.activityId }, limit: 1 },\n },\n });\n const activity = (result[CRM_NS.activity] ?? [])[0] as\n | CrmActivity\n | undefined;\n return activity && activity.recordId === record.id\n ? [activityItem(ctx, req, record, activity)]\n : [];\n}\n\nconst matches = (item: CrmDiscussionReference, needle: string): boolean =>\n !needle ||\n `${item.label}\\n${item.hint}\\n${item.id}`.toLowerCase().includes(needle);\n\nasync function searchableActivities(\n ctx: RouteCtx,\n req: Request,\n needle: string,\n): Promise<CrmDiscussionReference[]> {\n const result = await ctx.deps.db.query({\n [CRM_NS.activity]: {\n $: { order: { createdAt: \"desc\" }, limit: 100 },\n },\n });\n const rows = (result[CRM_NS.activity] ?? []) as unknown as CrmActivity[];\n const matching = rows.filter((activity) =>\n !needle || activity.body.toLowerCase().includes(needle)\n );\n const records = await Promise.all(\n [...new Set(matching.map((activity) => activity.recordId))]\n .map((id) => getRecord(ctx.deps, id)),\n );\n const byId = new Map(\n records.filter((record): record is CrmRecord => record !== null)\n .map((record) => [record.id, record]),\n );\n return matching.flatMap((activity) => {\n const record = byId.get(activity.recordId);\n return record ? [activityItem(ctx, req, record, activity)] : [];\n });\n}\n\nasync function search(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n): Promise<CrmDiscussionReference[]> {\n const limit = capLimit(url.searchParams.get(\"limit\"));\n const needle = (url.searchParams.get(\"q\") ?? \"\").trim().toLowerCase()\n .slice(0, 120);\n const recordPages = await Promise.all(\n Object.keys(ctx.deps.crm.config.types).map((type) =>\n listRecords(ctx.deps, {\n type,\n ...(needle ? { search: needle } : {}),\n limit,\n offset: 0,\n })\n ),\n );\n const records = recordPages.flatMap((page) =>\n page.records.map((record) => recordItem(ctx, req, record))\n );\n const activities = await searchableActivities(ctx, req, needle);\n return [...records, ...activities]\n .filter((item) => matches(item, needle))\n .slice(0, limit);\n}\n\n/**\n * Authenticated product-owned CRM reference search and exact resolution.\n * The host supplies an explicit all-record reference ACL; row existence and\n * parentage are checked before any projection.\n */\nexport async function handleCrmDiscussionReferences(\n ctx: RouteCtx,\n req: Request,\n url: URL,\n): Promise<Response> {\n if (req.method !== \"GET\") return json({ error: \"method not allowed\" }, 405);\n if (ctx.actor.discussionReferenceScope !== \"all\") {\n return json({ error: \"forbidden\" }, 403);\n }\n const kind = url.searchParams.get(\"kind\");\n const id = url.searchParams.get(\"id\");\n if ((kind && !id) || (!kind && id)) {\n return json({ error: \"kind and id must be paired\" }, 400);\n }\n const target = targetFromQuery(url);\n if ((kind || id) && !target) return json({ items: [] });\n return json({\n items: target ? await exact(ctx, req, target) : await search(ctx, req, url),\n });\n}\n","// The mountable route factory: everything S&S's worker hand-rolls as\n// /api/admin/* matches, formalized. The host worker composes it —\n// const crmRoutes = createCrmRoutes({ crm, db, authorize, … });\n// return (await crmRoutes(request)) ?? next(request);\n// — and keeps full ownership of auth (`authorize`) and the admin key.\nimport {\n errorResponse,\n json,\n type CrmActor,\n type CrmDiscussionReferenceActor,\n type CrmRouteOpts,\n type RouteCtx,\n} from \"../http\";\nimport { handleActivityItem, handleRecordActivities, handleTasks } from \"./activities\";\nimport {\n handleLinkIdentity,\n handleLinks,\n handleRank,\n handleSendEmail,\n handleStage,\n handleTags,\n} from \"./actions\";\nimport { handleArchive, handleRecordItem, handleRecordsRoot } from \"./records\";\nimport {\n handleConfig,\n handleEmailLog,\n handleRebalance,\n handleSummary,\n handleUnsubscribe,\n handleViews,\n} from \"./misc\";\nimport { handleCrmDiscussionReferences } from \"./discussion-references\";\n\nexport type { CrmActor, CrmDiscussionReferenceActor, CrmRouteOpts };\n\nasync function route(ctx: RouteCtx, req: Request, url: URL, seg: string[]): Promise<Response | null> {\n const [head, id, action, ...rest] = seg;\n if (head === \"discussion-references\" && id === undefined)\n return handleCrmDiscussionReferences(ctx, req, url);\n if (head === \"records\") {\n if (id === undefined) return handleRecordsRoot(ctx, req, url);\n if (action === undefined) return handleRecordItem(ctx, req, id);\n if (action === \"archive\") return handleArchive(ctx, req, id);\n if (action === \"stage\") return handleStage(ctx, req, id);\n if (action === \"rank\") return handleRank(ctx, req, id);\n if (action === \"tags\") return handleTags(ctx, req, id, rest);\n if (action === \"links\") return handleLinks(ctx, req, id);\n if (action === \"link-identity\") return handleLinkIdentity(ctx, req, id);\n if (action === \"email\") return handleSendEmail(ctx, req, id);\n if (action === \"activities\") return handleRecordActivities(ctx, req, url, id);\n return null;\n }\n if (head === \"activities\" && id !== undefined && action === undefined)\n return handleActivityItem(ctx, req, id);\n if (head === \"tasks\" && id === undefined) return handleTasks(ctx, req, url);\n if (head === \"views\") return handleViews(ctx, req, url, seg.slice(1));\n if (head === \"summary\" && id === undefined) return handleSummary(ctx, req, url);\n if (head === \"config\" && id === undefined) return handleConfig(ctx, req);\n if (head === \"email-log\" && id === undefined) return handleEmailLog(ctx, req, url);\n if (head === \"rank\" && id === \"rebalance\" && action === undefined)\n return handleRebalance(ctx, req);\n return null;\n}\n\n/**\n * Build the crm fetch handler. Returns `null` for requests outside\n * `basePath` (default `/api/crm`) so the host worker falls through to its\n * own routes; inside it, every route requires `authorize` to resolve an\n * admin actor (401 otherwise) EXCEPT the public unsubscribe pair, where the\n * per-channel token is the credential. Domain errors map to 400/404 JSON;\n * anything unexpected is a 500 without internals.\n */\nexport function createCrmRoutes(options: CrmRouteOpts): (req: Request) => Promise<Response | null> {\n const basePath = options.basePath ?? \"/api/crm\";\n const opts = {\n ...options,\n basePath,\n envName: options.envName ?? \"development\",\n baseUrl: options.baseUrl ?? \"\",\n discussionBasePath: options.discussionBasePath ?? \"/admin/\",\n };\n const deps = {\n crm: options.crm,\n db: options.db,\n now: options.now,\n newId: options.newId,\n sender: options.sender,\n };\n return async (req: Request): Promise<Response | null> => {\n const url = new URL(req.url);\n if (url.pathname !== basePath && !url.pathname.startsWith(`${basePath}/`)) return null;\n const segments = url.pathname.slice(basePath.length).split(\"/\").filter(Boolean);\n try {\n if (segments[0] === \"unsubscribe\" && segments.length === 1)\n return await handleUnsubscribe(deps, req, url);\n const discussionReferences = segments[0] === \"discussion-references\";\n const actor = discussionReferences && options.authorizeDiscussionReferences\n ? await options.authorizeDiscussionReferences(req)\n : await options.authorize(req);\n if (!actor) return json({ error: \"unauthorized\" }, 401);\n const ctx: RouteCtx = {\n deps,\n opts,\n actor: discussionReferences && !options.authorizeDiscussionReferences\n ? { ...actor, discussionReferenceScope: \"all\" }\n : actor,\n };\n return (await route(ctx, req, url, segments)) ?? json({ error: \"not found\" }, 404);\n } catch (error) {\n return errorResponse(error);\n }\n };\n}\n","// Browser client for the crm routes — a thin, typed fetch wrapper the UI\n// kit's hooks use. Inject `fetch` and auth `headers` (e.g. a Clerk session\n// token getter runs outside; pass the resolved header).\nimport type { CrmListParams } from \"./query\";\nimport type { ViewSpec } from \"./views\";\nimport type { ConfigPatch } from \"./config-store\";\nimport type {\n CrmActivity,\n CrmConfigRow,\n CrmContactChannel,\n CrmLink,\n CrmRecord,\n CrmRecordDelivery,\n CrmRecordOrigin,\n CrmTag,\n CrmView,\n} from \"./types\";\nimport type { TypeSummary } from \"./summary\";\n\n/** Where the routes live and how to authenticate against them. */\nexport interface CrmClientOptions {\n /** Origin of the host worker, e.g. \"\" (same-origin) or a full URL. */\n baseUrl?: string;\n /** Route mount point. Default \"/api/crm\". */\n basePath?: string;\n fetch?: typeof globalThis.fetch;\n /** Per-request auth headers (called each request — tokens rotate). */\n headers?: () => Promise<Record<string, string>> | Record<string, string>;\n}\n\n/** Error carrying the route's status + JSON error payload. */\nexport class CrmClientError extends Error {\n readonly status: number;\n readonly fields?: Record<string, string>;\n constructor(status: number, message: string, fields?: Record<string, string>) {\n super(message);\n this.name = \"CrmClientError\";\n this.status = status;\n this.fields = fields;\n }\n}\n\n/** A record composed with its tags, channels, and links. */\nexport interface RecordDetail {\n record: CrmRecord;\n tags: CrmTag[];\n channels: CrmContactChannel[];\n links: CrmLink[];\n /** Structured upstream identities; absent only from pre-upgrade custom APIs. */\n origins?: CrmRecordOrigin[];\n /** Latest outbound state per target; absent only from pre-upgrade custom APIs. */\n deliveries?: CrmRecordDelivery[];\n}\n\n/** One list window plus the total matching count. */\nexport interface RecordPage {\n records: CrmRecord[];\n total: number;\n limit: number;\n offset: number;\n}\n\n/** Typed access to every crm route. Methods reject with\n * {@link CrmClientError} on non-2xx responses. */\nexport class CrmClient {\n private readonly base: string;\n private readonly doFetch: typeof globalThis.fetch;\n private readonly headers?: CrmClientOptions[\"headers\"];\n\n constructor(options: CrmClientOptions = {}) {\n this.base = `${options.baseUrl ?? \"\"}${options.basePath ?? \"/api/crm\"}`;\n this.doFetch = options.fetch ?? globalThis.fetch.bind(globalThis);\n this.headers = options.headers;\n }\n\n private async request<T>(method: string, path: string, body?: unknown): Promise<T> {\n const headers: Record<string, string> = { ...(await this.headers?.()) };\n if (body !== undefined) headers[\"content-type\"] = \"application/json\";\n const response = await this.doFetch(`${this.base}${path}`, {\n method,\n headers,\n ...(body !== undefined ? { body: JSON.stringify(body) } : {}),\n });\n const payload = (await response.json().catch(() => ({}))) as Record<string, unknown>;\n if (!response.ok)\n throw new CrmClientError(\n response.status,\n typeof payload[\"error\"] === \"string\" ? payload[\"error\"] : `HTTP ${response.status}`,\n payload[\"fields\"] as Record<string, string> | undefined,\n );\n return payload as T;\n }\n\n listRecords(params: CrmListParams): Promise<RecordPage> {\n const q = new URLSearchParams({ type: params.type });\n if (params.search) q.set(\"search\", params.search);\n if (params.stage?.length) q.set(\"stage\", params.stage.join(\",\"));\n if (params.emailStatus?.length) q.set(\"emailStatus\", params.emailStatus.join(\",\"));\n if (params.billingStatus?.length) q.set(\"billingStatus\", params.billingStatus.join(\",\"));\n if (params.ownerId) q.set(\"ownerId\", params.ownerId);\n if (params.tag) q.set(\"tag\", params.tag);\n if (params.archived) q.set(\"archived\", \"true\");\n if (params.sort) q.set(\"sort\", `${params.sort.field}:${params.sort.dir}`);\n if (params.limit != null) q.set(\"limit\", String(params.limit));\n if (params.offset != null) q.set(\"offset\", String(params.offset));\n if (params.fields) q.set(\"fields\", JSON.stringify(params.fields));\n return this.request(\"GET\", `/records?${q}`);\n }\n\n getRecord(id: string): Promise<RecordDetail> {\n return this.request(\"GET\", `/records/${encodeURIComponent(id)}`);\n }\n createRecord(body: {\n type: string;\n input: Record<string, unknown>;\n ownerId?: string;\n stage?: string;\n mutationId?: string;\n }): Promise<{ id: string; duplicate: boolean; record: CrmRecord }> {\n return this.request(\"POST\", \"/records\", body);\n }\n updateRecord(\n id: string,\n body: { input?: Record<string, unknown>; ownerId?: string | null; mutationId?: string },\n ): Promise<{ record: CrmRecord; duplicate: boolean }> {\n return this.request(\"PATCH\", `/records/${encodeURIComponent(id)}`, body);\n }\n setArchived(id: string, archived: boolean): Promise<{ duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/archive`, { archived });\n }\n setStage(\n id: string,\n to: string,\n mutationId?: string,\n ): Promise<{ record: CrmRecord; from: string | null; duplicate: boolean; hookError?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/stage`, { to, mutationId });\n }\n setRank(\n id: string,\n body: { beforeId?: string; afterId?: string },\n ): Promise<{ rank: number; rebalanceNeeded: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/rank`, body);\n }\n addTag(id: string, tag: string): Promise<{ tag: string; duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/tags`, { tag });\n }\n removeTag(id: string, tag: string): Promise<{ duplicate: boolean }> {\n return this.request(\n \"DELETE\",\n `/records/${encodeURIComponent(id)}/tags/${encodeURIComponent(tag)}`,\n );\n }\n setLink(\n id: string,\n body: { relation: string; toId: string; remove?: boolean },\n ): Promise<{ duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/links`, body);\n }\n linkIdentity(id: string, email?: string): Promise<{ linked: boolean; clerkUserId?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/link-identity`, { email });\n }\n sendEmail(\n id: string,\n body: {\n templateId: string;\n vars?: Record<string, string>;\n dedupeKey?: string;\n channelId?: string;\n force?: boolean;\n },\n ): Promise<{ sent: boolean; reason?: string }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(id)}/email`, body);\n }\n listActivities(recordId: string, opts: { kind?: string; limit?: number } = {}): Promise<{ activities: CrmActivity[] }> {\n const q = new URLSearchParams();\n if (opts.kind) q.set(\"kind\", opts.kind);\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/records/${encodeURIComponent(recordId)}/activities?${q}`);\n }\n addActivity(\n recordId: string,\n body: { kind: string; body: string; dueAt?: number; assigneeId?: string; waitingOn?: string },\n ): Promise<{ id: string; duplicate: boolean }> {\n return this.request(\"POST\", `/records/${encodeURIComponent(recordId)}/activities`, body);\n }\n updateTask(\n id: string,\n body: { status?: string; dueAt?: number | null; assigneeId?: string | null; waitingOn?: string | null; body?: string },\n ): Promise<{ activity: CrmActivity; duplicate: boolean }> {\n return this.request(\"PATCH\", `/activities/${encodeURIComponent(id)}`, body);\n }\n listTasks(opts: { assigneeId?: string; status?: string[]; limit?: number } = {}): Promise<{ tasks: CrmActivity[] }> {\n const q = new URLSearchParams();\n if (opts.assigneeId) q.set(\"assigneeId\", opts.assigneeId);\n if (opts.status?.length) q.set(\"status\", opts.status.join(\",\"));\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/tasks?${q}`);\n }\n listViews(type?: string): Promise<{ views: CrmView[] }> {\n return this.request(\"GET\", `/views${type ? `?type=${encodeURIComponent(type)}` : \"\"}`);\n }\n saveView(spec: ViewSpec): Promise<{ id: string; duplicate: boolean }> {\n return this.request(\"POST\", \"/views\", { spec });\n }\n updateView(id: string, spec: Partial<ViewSpec>): Promise<{ view: CrmView; duplicate: boolean }> {\n return this.request(\"PATCH\", `/views/${encodeURIComponent(id)}`, { spec });\n }\n deleteView(id: string): Promise<{ duplicate: boolean }> {\n return this.request(\"DELETE\", `/views/${encodeURIComponent(id)}`);\n }\n summary(type: string): Promise<TypeSummary> {\n return this.request(\"GET\", `/summary?type=${encodeURIComponent(type)}`);\n }\n getConfig(): Promise<{ config: CrmConfigRow | null }> {\n return this.request(\"GET\", \"/config\");\n }\n saveConfig(patch: ConfigPatch): Promise<{ config: CrmConfigRow; duplicate: boolean }> {\n return this.request(\"PUT\", \"/config\", patch);\n }\n emailLog(opts: { recordId?: string; limit?: number } = {}): Promise<{ log: Record<string, unknown>[] }> {\n const q = new URLSearchParams();\n if (opts.recordId) q.set(\"recordId\", opts.recordId);\n if (opts.limit != null) q.set(\"limit\", String(opts.limit));\n return this.request(\"GET\", `/email-log?${q}`);\n }\n rebalance(type: string): Promise<{ count: number }> {\n return this.request(\"POST\", \"/rank/rebalance\", { type });\n }\n}\n","// The integration descriptor: documentation-as-data for the CRM capability,\n// extending the auth-clerk/chat pattern with the schema + rules to install.\n// The base shapes are inlined so the zero-dependency package does not depend\n// on the CLI. The CLI consumes descriptors structurally from odla.config.mjs.\nimport { CRM_SCHEMA, type SerializedSchema } from \"./schema\";\nimport { CRM_RULES, type CrmRules } from \"./rules\";\nimport { CONFIG_KEY, CRM_NS } from \"./constants\";\nimport { defaultTemplates } from \"./config-store\";\nimport type { Crm } from \"./config\";\n\nexport interface IntegrationSetting {\n key: string;\n description: string;\n public: boolean;\n pattern?: string;\n perEnv: boolean;\n source: string;\n}\n\nexport interface IntegrationSecret {\n key: string;\n description: string;\n pattern?: string;\n vault: boolean;\n}\n\nexport interface IntegrationProvision {\n human: string[];\n cli: string[];\n doctor: string[];\n smoke?: string[];\n}\n\n/** Natural-key config row the CLI creates only when no CRM config exists. */\nexport interface CrmIntegrationSeed {\n id: string;\n ns: string;\n key: { attr: string; value: string };\n attrs: Record<string, unknown>;\n}\n\n/** Unauthenticated route check run by `odla-ai smoke`. */\nexport interface CrmIntegrationProbe {\n path: string;\n expectedStatus: number;\n}\n\n/** The CRM's descriptor shape: the shared base plus the schema + deny-all\n * rules provisioning installs (the chat-style extension). */\nexport interface CrmIntegrationDescriptor {\n id: string;\n title: string;\n npm: string;\n settings: IntegrationSetting[];\n secrets: IntegrationSecret[];\n schema: SerializedSchema;\n rules: CrmRules;\n seeds?: CrmIntegrationSeed[];\n probes?: CrmIntegrationProbe[];\n provision: IntegrationProvision;\n}\n\n/** Initial owner-editable CRM settings seeded during first provisioning. */\nexport interface CrmIntegrationOptions {\n /** Worker mount path; defaults to `/api/crm`. */\n basePath?: string;\n notificationEmail?: string;\n replyTo?: string;\n debugEmail?: string;\n settings?: Record<string, unknown>;\n /** Seed timestamp override for reproducible builds/tests. */\n now?: number;\n}\n\n/**\n * The static documentation descriptor for @odla-ai/crm. Data only: it\n * describes what installing the\n * CRM means (push {@link CRM_SCHEMA}, install deny-all {@link CRM_RULES},\n * seed the `crm_config` row, mount `createCrmRoutes` in the app worker); it\n * performs none of it. Use {@link createCrmIntegration} in `odla.config.mjs`\n * to add the config seed and live route probe the CLI can execute. Billing is\n * an optional injected provider seam and the core CRM needs no vault entries.\n */\nexport const crmIntegration: CrmIntegrationDescriptor = {\n id: \"crm\",\n title: \"CRM records, pipelines & contactability\",\n npm: \"@odla-ai/crm\",\n settings: [\n {\n key: \"basePath\",\n description: 'Route mount point the app worker serves the CRM under. Default \"/api/crm\".',\n public: true,\n perEnv: false,\n source: \"createCrmRoutes({ basePath }) in the app worker\",\n },\n {\n key: \"notificationEmail / replyTo / debugEmail\",\n description:\n \"Destination addresses for owner notifications, reply routing, and the dev redirect — runtime-editable.\",\n public: false,\n perEnv: false,\n source: \"crm_config row (odla-db), edited in the app's CRM settings UI\",\n },\n ],\n secrets: [],\n schema: CRM_SCHEMA,\n rules: CRM_RULES,\n provision: {\n human: [\n \"None for the core install — records/pipelines/email-consent need no external accounts.\",\n \"If the app injects billing, configure that provider's webhook and vault secrets according to the app-owned adapter.\",\n ],\n cli: [\n \"POST the merged CRM_SCHEMA to /app/:id/schema.\",\n \"Install CRM_RULES (deny-all) at /app/:id/admin/rules.\",\n \"Seed the crm_config row from the app's defineCrm template defaults.\",\n ],\n doctor: [\n \"Every crm_* namespace has rules installed (deny-all: no rule = exposed to nothing, but assert explicitly).\",\n \"The guarded crm_config seed targets the declared-unique crm_config.key attribute.\",\n \"Code-declared template defaults have no unknown {{vars}}; owner-edited copies are checked when saved.\",\n ],\n smoke: [\n \"A GET probe of <basePath>/records without credentials answers 401 (routes mounted, authorize enforced).\",\n ],\n },\n};\n\n/**\n * Build the project-specific, CLI-consumable CRM integration descriptor.\n * The returned schema/rules merge structurally with app-authored db config;\n * the config singleton is seeded only when absent, preserving later owner\n * edits, and `smoke` verifies the mounted records route rejects anonymous\n * access. Mounting `createCrmRoutes` remains app-owned source work.\n */\nexport function createCrmIntegration(\n crm: Crm,\n options: CrmIntegrationOptions = {},\n): CrmIntegrationDescriptor {\n const basePath = options.basePath ?? \"/api/crm\";\n if (!/^\\/[A-Za-z0-9._~!$&'()*+,;=:@%/-]*$/.test(basePath) || basePath.endsWith(\"/\")) {\n throw new Error(\"createCrmIntegration: basePath must be an absolute path without a trailing slash\");\n }\n const attrs: Record<string, unknown> = {\n emailTemplates: defaultTemplates(crm),\n settings: options.settings ?? {},\n updatedAt: options.now ?? Date.now(),\n };\n if (options.notificationEmail !== undefined) attrs.notificationEmail = options.notificationEmail;\n if (options.replyTo !== undefined) attrs.replyTo = options.replyTo;\n if (options.debugEmail !== undefined) attrs.debugEmail = options.debugEmail;\n return {\n ...crmIntegration,\n seeds: [{\n id: \"config\",\n ns: CRM_NS.config,\n key: { attr: \"key\", value: CONFIG_KEY },\n attrs,\n }],\n probes: [{ path: `${basePath}/records`, expectedStatus: 401 }],\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCO,IAAM,SAAS;AAAA,EACpB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