The platform is a single Next.js app whose business logic lives underDocumentation Index
Fetch the complete documentation index at: https://docs.kaireonai.com/llms.txt
Use this file to discover all available pages before exploring further.
platform/src/lib/. Each subdirectory owns one concern — infrastructure backends, domain logic, runtime executors, or types. This page is the reverse index for contributors: read it first, grep second.
What it indexes
platform/src/lib/ contains 506 TypeScript source files organised across ~50 subdirectories plus root-level utilities. The Sections below describe what lives in each subdirectory, the entry point file you should open first, the public exports that other code depends on, and the extension point for adding new functionality.
This page is scoped to the 14 subdirectories that did not have an architecture page before — five priority ones (infra/, gitops/, connector-executors/, ai/, flow/) and nine secondaries (audit/, governance/, scoring/, arbitration/, fairness/, explanations/, ml/, negotiation/, qualification/). Subdirectories already covered by their own page (e.g., flow-overview.mdx for the user-facing slice of flow/, dashboards.mdx for dashboards/) are linked from Related at the bottom.
Quick start
Three navigation patterns cover most contributor questions:- “What backend handles X?” — Open
lib/infra/container.ts. Every infrastructure choice (cache, event publisher, interaction store, search index) is selected here from a single env var. Adding a new Kafka or DynamoDB backend means adding one switch case. - “What’s the public API of module Y?” — Open
lib/<module>/index.tsif it exists, otherwise the file whose name matches the module (lib/gitops/apply.ts,lib/scoring/index.ts,lib/qualification/decisioning-gates.ts). - “How does runtime X load executors / handlers?” — Open
lib/<module>/runtime/(currently onlylib/flow/runtime/follows this pattern). Per-node executors register into a registry that the interpreter walks.
lib/formula-engine.ts, lib/decision-flow-engine.ts, lib/pipeline-runner.ts, etc.) read CODEMAP.md at the repo root — it is the generated index of every file with its top-line purpose.
How it works
The codebase follows a consistent layering pattern:| Layer | Location | Purpose |
|---|---|---|
| Factories / DI | lib/infra/container.ts | Reads env vars, returns singleton backend instances bound to interfaces in lib/infra/interfaces.ts |
| Domain logic | lib/<domain>/<file>.ts | Pure functions plus narrow side effects via Prisma. Imports interfaces from lib/infra/, never concrete backends |
| Runtime executors | lib/<domain>/runtime/ (Flow only today) | Per-node handlers registered into an ExecutorRegistry; lib/flow/runtime/default-registry.ts is the canonical example |
| Domain types | lib/<domain>/types.ts or domain/<domain>.ts | Zod schemas + TypeScript types. domain/ is for UI-visible types; lib/<domain>/types.ts is for runtime contracts |
| API entry | src/app/api/v1/<resource>/route.ts | Thin handler that reads request, calls one or more domain functions, returns response |
lib/infra/container.ts getters. This keeps the per-module isolation that makes parallel development possible (see the Module Isolation table in the root CLAUDE.md).
Reference
lib/infra/
The dependency-injection container. Every infrastructure backend (cache, event publisher, interaction store, search index) is registered here behind a single getter that reads one env var to pick the implementation. Business logic imports the getter, never the concrete class.
- Entry point:
lib/infra/container.ts - Public exports:
getCache,getEventPublisher,getInteractionStore,getSearchIndex,resetInfra(container.ts:26, 48, 121, 184, 227).shutdownInfraatcontainer.ts:241is called on SIGTERM by the worker process. - Backends shipped: Redis (cache + event pub/sub), PostgreSQL (interactions + tsvector search), Kafka / Redpanda / MSK / EventBridge / Kinesis (events), ScyllaDB / DynamoDB / Keyspaces (interactions), OpenSearch (search). Each backend lives in its own file:
lib/infra/redis-cache.ts,lib/infra/kafka-events.ts,lib/infra/dynamodb-interaction-store.ts, etc. - Interfaces:
CacheStore,EventPublisher,InteractionStore,SearchIndex,DomainEvent,InteractionEventdeclared atlib/infra/interfaces.ts:11-97. - Extension point: Add a new event-publisher backend by writing a file that implements
EventPublisher, then add acase "yourbackend":branch to the switch atlib/infra/container.ts:48-119. SetEVENT_PUBLISHER=yourbackendin the deployment env and the rest of the platform picks it up with no other code changes. The same pattern applies togetInteractionStore(container.ts:121-182) andgetSearchIndex(container.ts:184-218). - Architecture decision record:
lib/infra/README.mddocuments the why and how — start there for context before extending.
lib/gitops/
Apply-and-diff for tenant configuration as YAML. A ResourceBundle (set of Categories, Channels, Offers, Decision Flows, Qualification Rules, Contact Policies, Arbitration Profiles) is parsed from disk, diffed against the tenant’s DB, and either dry-run-reported or written. Reconciliation key is metadata.name, not id, so the same bundle can be applied across dev / stage / prod with different ids per env.
- Entry point:
lib/gitops/apply.ts - Public exports:
applyBundle(apply.ts:420),diffBundle(apply.ts:489),ApplyOptionsinterface (apply.ts:34),exportTenant(export.ts:263),parseBundleYamlandparseBundleJson(serialize.ts:37, 77). - Resource model:
Resource<TSpec>,ResourceBundle,ResourceDiff,ApplyResultatlib/gitops/types.ts:49-83.API_VERSION = "kaireonai.com/v1"(types.ts:27). Per-kind Zod schemas atlib/gitops/schemas.ts:113. - Drift + three-way merge:
lib/gitops/drift-detector.tsexportsdetectDrift(drift-detector.ts:77) andthreeWayMerge(drift-detector.ts:128) for periodic reconciler runs that compare DB state against a baseline snapshot. - Extension point: Add a new
ResourceKindby adding the literal to the union atlib/gitops/types.ts:29-39, registering its Zod spec schema inRESOURCE_SPEC_SCHEMASatlib/gitops/schemas.ts:113, and adding a case to theapplyResourceswitch inlib/gitops/apply.ts(search for “TODO markers” atapply.ts:18for the comment that flags the per-case insertion). Default behavior for unrecognized kinds is “validated but reported as unchanged”.
lib/connector-executors/
The output side of the connector layer. Every supported destination (Salesforce, Iterable, Klaviyo, Shopify, Snowpipe, Slack, Twilio, etc.) ships a ConnectorExecutor here. Distinct from domain/connector-registry.ts, which is the registry of connector types and their auth fields — the executors are the runtime that calls those endpoints. Routes call getConnectorExecutor(type) to get a per-type send/pull/test handle.
- Entry point:
lib/connector-executors/index.ts - Public exports:
getConnectorExecutor(index.ts:60),IMPLEMENTED_CONNECTOR_TYPES(index.ts:65), plus all named executors re-exported from the per-category files (commerce.ts,cdp.ts,messaging.ts,analytics.ts,mktauto.ts,reverse-etl.ts,workflow-billing.ts,coming-soon.ts). - Categories: Commerce (
shopify,stripe,mailchimpatcommerce.ts:12, 44, 73), CDP (intercom,zendesk,iterable,klaviyo,segment,brazeatcdp.ts:13-227), Messaging (slack,teams,whatsapp,pagerduty,twilio_smsatmessaging.ts:14-148), Analytics (amplitude,mixpanel,posthogatanalytics.ts:8-87), Marketing automation (customer_io,moengage,clevertap,hubspot_marketing,activecampaignatmktauto.ts:8-121), Reverse ETL (snowpipe,fivetran,hightouch,census,databricks,kinesisatreverse-etl.ts:10-176). - Contract:
ConnectorExecutorinterface atlib/connector-executors/types.ts:51requirestype,send(payload, config), optionalpull(opts, config), andtestConnection(config). HelpersconnectorFetch,basicAuth,bearerattypes.ts:98-163. - Coming-soon stub:
comingSoonExecutor(type)atlib/connector-executors/coming-soon.ts:50returns a structured-503 dispatcher for any registered-but-unimplemented connector type. Pre-31 the dispatcher returnedundefinedand the caller had to null-check; since 31, every coming-soon connector is registered with this loud-fail stub. - Extension point: Add a new connector by exporting a
ConnectorExecutorfrom the appropriate category file (or a new file underlib/connector-executors/), then add it to theALL_EXECUTORSarray atlib/connector-executors/index.ts:40-54and toIMPLEMENTED_CONNECTOR_TYPESatindex.ts:65-75. Also add the type to the registry atdomain/connector-registry.tsso the UI renders the auth form.
lib/ai/
The AI authoring + analysis layer. Three responsibilities: (1) provider routing — pick a LanguageModel instance from env config; (2) tool registries — the per-module tool catalogues that the in-app AI panel and the MCP server expose; (3) document import — the V1 PDF/PPTX → typed proposals pipeline.
- Entry point:
lib/ai/provider.ts - Public exports:
getAiConfigAsync,getAiConfig,getLanguageModel(provider.ts:16, 44, 57),AiProviderenum (types.ts:3),AiConfigschema (types.ts:6),AI_ENVenv-var name map (types.ts:14). - Provider routing:
getLanguageModel(cfg?)atprovider.ts:57returns aLanguageModelfor one ofgoogle | anthropic | openai | ollama | lm_studio | bedrock(types.ts:3). The local-dev default is Ollama at127.0.0.1:11434with modelqwen2.5:3b. - Tools registry:
lib/ai/tools/index.tsre-exports the 11 module-scoped tool sets (dataTools,studioTools,algorithmTools,dashboardTools,contentTools,cmsTools,metricsTools,mutationTools,docsTools,intelligenceTools,importTools). Each tool set is an array ofAiTooldefinitions with a Zod-validated input schema and a handler. - ML routing:
MlRouterclass atlib/ai/ml-router.ts:32decides whether an analysis request goes to the LLM or to a heuristic fallback — used by the analyzers underlib/ai/analyzers/(segmentation, policy, content, rule parser, transform parser). - Document import:
lib/ai/import/is the V1 PDF/PPTX → typed proposals pipeline. Entry:import/run-extract.tsfor orchestration,import/extractor.tsfor the hybrid extractor,import/apply.tsfor the apply/revert orchestrator,import/cost-guard.tsfor token budgeting. Storage backends pluggable viaimport/storage/factory.ts:2(getAttachmentStorereadsSTORAGE_BACKENDenv once and returns either local-fs or S3). - Extension point: Add a new AI tool to a module by adding an entry to the corresponding
lib/ai/tools/<module>-tools.tsfile (e.g., a new dashboard tool goes intotools/dashboard-tools.ts’sdashboardToolsarray). Add a new LLM provider by adding a case togetLanguageModelatprovider.ts:57and toAiProviderSchemaattypes.ts:3. Add a new attachment-storage backend by implementingAttachmentBlobStore(import/storage/types.ts:6) and adding a case togetAttachmentStore.
lib/flow/
The data + decisioning fabric — a typed Pipeline IR, an in-process batch interpreter, an AI authoring layer, an MCP server, atomic file ingestion, six target load modes, hook execution, dataset + row-level validators, YAML connectors, row-level lineage, and configurable UI pages. The user-facing surface is documented at Flow Overview; this section covers the internal layout.
- Entry points by sub-area:
- IR:
lib/flow/ir/parse.ts—parsePipelineIR(input)(parse.ts:12) returnsParseResult(parse.ts:8);lib/flow/ir/pipeline.ts—pipelineSchemaandPipelinetype (pipeline.ts:22, 34);lib/flow/ir/types.tsre-exports node/transform/source/target types. - Runtime:
lib/flow/runtime/batch-interpreter.ts—runBatch(args)(batch-interpreter.ts:34) returnsRunResult;lib/flow/runtime/executor-registry.tsdeclares theExecutor<N>andExecutorRegistrytypes (executor-registry.ts:4, 10);lib/flow/runtime/default-registry.tsexportsdefaultExecutors(default-registry.ts:11) — the canonical registry the interpreter walks. - Connectors:
lib/flow/connectors/registry.ts— singletonconnectorRegistryinstance (registry.ts:46);lib/flow/connectors/plugin-sdk.ts—defineConnector(def)(plugin-sdk.ts:36) for plugin authors. - Repo:
lib/flow/repo/pipeline-ir-repo.ts—savePipelineIr,getLatestPipelineIr,getPipelineIrVersion,listPipelineIrVersions(pipeline-ir-repo.ts:33-78);lib/flow/repo/feature-flag.tsfor the runtime feature gate. - AI authoring:
lib/flow/ai/—coordinator.ts,patch-apply.ts,patch-schema.ts,system-prompt.ts, pluspii-redact.tsandaudit.tsfor guardrails. - Observability:
lib/flow/observability/lineage.tsfor row-level lineage,lib/flow/observability/run-metrics.tsfor run-level metrics. - Schedule:
lib/flow/schedule/due-pipelines.ts—selectDuePipelinesfor cron tick;lib/flow/schedule/next-fire-times.tsfor cron / interval / rrule resolution.
- IR:
- Runtime sub-directories under
lib/flow/runtime/:cloud-stores/(S3 / GCS / Azure / SFTP / HTTP-pull source backends),executors/(per-node implementations registered intodefaultExecutors),transforms/(the typed transform op set),load-modes/(six target write strategies includingcdc-mirror.ts),dataset-validators/,file-handler/,hooks/,sql/,streaming/(Phase 6.4 — gated byFLOW_STREAMING_ENABLED). - Extension point: Add a new IR node kind by adding its type under
lib/flow/ir/nodes/, exporting it fromlib/flow/ir/types.ts, then registering its executor inlib/flow/runtime/default-registry.ts:11. Add a new YAML connector by writing a spec underlib/flow/connectors/yaml-spec/(theconnectorRegistrysingleton atlib/flow/connectors/registry.ts:46auto-loads it). Add a custom plugin connector by callingdefineConnector(def)fromlib/flow/connectors/plugin-sdk.ts:36. Add a new streaming runtime by implementing the streaming-runtime contract underlib/flow/runtime/streaming/and gating withFLOW_STREAMING_ENABLED=true.
Other modules
The nine remaining undoc’d subdirectories. Each gets one paragraph plus entry point, top exports, and extension hook.lib/audit/
Single-file SIEM forwarder. audit/sink.ts ships audit-log batches to a configured SIEM backend (Splunk, Datadog, or Elastic). Called by the cron route at src/app/api/v1/cron/siem-ship/route.ts. Distinct from lib/audit.ts (root file) which is the per-tenant hash-chained audit-log writer.
- Entry point:
lib/audit/sink.ts - Public exports:
SiemBackend(sink.ts:23),SiemAuditEvent,SiemConfig,getSiemConfigFromEnv(sink.ts:25, 38, 48),shipToSiem(sink.ts:75). - Extension point: Add a new SIEM backend by extending the
SiemBackendunion atsink.ts:23and adding a transport branch insideshipToSiem.
lib/governance/
Four-eyes approval gate + multi-stage approval policy. four-eyes-gate.ts enforces that the requester and approver of a sensitive action are different users; approval-workflow.ts defines the policy + stage state machine; approval-stages.ts is the per-stage decider used by approval-route handlers.
- Entry point:
lib/governance/four-eyes-gate.ts - Public exports:
isFourEyesEnabled,evaluateFourEyesGate,throwFourEyesViolation(four-eyes-gate.ts:42, 65, 55);ApprovalPolicy,ApprovalStage,ApprovalRequestState,FourEyesViolationError,resolvePolicy,initRequest(approval-workflow.ts:18-90);decideOnStages,buildStageInserts,StageDecisionResult(approval-stages.ts:75, 180, 56). - Extension point: Add a new approval stage by extending
ApprovalStageatapproval-workflow.ts:32and adding the per-stage rule todecideOnStagesatapproval-stages.ts:75.
lib/scoring/
The scoring algorithms — every model used by decision-flow-engine.ts and pipeline-runner.ts to score candidate offers. Includes scorecard, logistic regression, gradient-boosted trees (with TreeSHAP), Bayesian, neural collaborative filtering, ONNX runner, Thompson bandit, epsilon-greedy, online learner, and the auto-learn / auto-upgrade orchestrators.
- Entry point:
lib/scoring/index.ts - Public exports:
scoreWithModel(index.ts:91),trainModel(index.ts:243),scoreOfferSet(index.ts:281),scoreOfferSetExternal(index.ts:367),ScoringResultandScoringOptionstypes (index.ts:46, 69). - Per-algorithm files:
scorecard.ts,logistic-regression.ts,bayesian.ts,gradient-boosted.ts(real LightGBM-trained, walked in-process),tree-shap.ts(exact TreeSHAP attree-shap.ts:412),neural-cf.ts+neural-cf-shap.ts,thompson-bandit.ts,epsilon-greedy.ts,online-learner.ts,external-endpoint.ts,onnx-runner.ts+onnx-blob-store.ts,auto-learn.ts,auto-upgrade.ts. - Extension point: Add a new scoring algorithm by writing a file under
lib/scoring/that exports ascore…function returningScoringResult(index.ts:46), then add a dispatch case toscoreWithModelatindex.ts:91.
lib/arbitration/
Multi-objective arbitration — selects which candidate(s) to surface among scored offers under budget, fairness, and pacing constraints. Includes the realtime apply path (called from recommend/route.ts), Lagrangian solver, EXP3-IX online bandit, goal-seek, budget pacing, and online-tuning weight updater.
- Entry point:
lib/arbitration/realtime-wire.ts - Public exports:
applyRealtimeArbitration(realtime-wire.ts:150);isExp3IxEnabled,isBudgetPacingEnabled,isGoalSeekEnabled,selectBanditArmForRecommend,BanditConfig,readBanditState(apply-online-tuning.ts:60-167);solveLagrangian,LagrangianResult(lagrangian.ts:96, 75); plusapply-lagrangian.ts,budget-pacing.ts,cross-offer.ts,goal-seek.ts,constraints.ts,online-weights.ts,load-cross-offer.ts. - Extension point: Add a new arbitration objective by adding a field to
ArbitrationWeightsandObjectiveScoresin the rootlib/arbitration.ts(perplatform/CLAUDE.mdCommon Tasks). Add a new bandit algorithm by writing a sibling toapply-online-tuning.tsand gating it with a tenant-settings flag analogous toisExp3IxEnabled.
lib/fairness/
Group-fairness + counterfactual-fairness + individual-fairness + intersectional metrics. Used by the model-governance reports and the fairness dashboard. Distinct from lib/scoring/: scoring produces scores; fairness audits the scores’ distribution across groups.
- Entry point:
lib/fairness/metrics.ts - Public exports:
evaluateFairness,FairnessSample,PerGroupStats,FairnessReport(metrics.ts:139, 34, 46, 59);evaluateCounterfactualFairness(advanced.ts:42),evaluateIndividualFairness(advanced.ts:103),evaluateIntersectional(advanced.ts:192); plusreport-export.tsandscorer-resolver.ts. - Extension point: Add a new fairness metric by adding a function to
metrics.ts(group-level) oradvanced.ts(counterfactual / individual / intersectional) and extending the report shape used by the consumer.
lib/explanations/
Decision explanations for the regulator / agent / customer audiences. Includes LIME, counterfactual search, SHAP-narrative LLM generation, multi-language directives, PII redaction, prompt templates, quality scoring, and a result cache.
- Entry point:
lib/explanations/narrative.ts - Public exports:
generateNarrative,NarrativeInput,NarrativeResult,NarrativeNotFoundError,NarrativeGenerationError(narrative.ts:284, 46, 80, 99, 106);computeLime,globalFeatureImportance(lime.ts:61, 189);findCounterfactuals,Counterfactual,CounterfactualScorer(counterfactual.ts:62, 45, 55);runAdvancedExplanation,ExplanationType(explanation-modes.ts:130, 31);SUPPORTED_LANGUAGES,applyLanguageDirective,scanForLanguageLeaks(multi-language.ts:12, 52, 72);scoreQuality(quality-score.ts:45). - Extension point: Add a new explanation type by extending the
ExplanationTypeunion atexplanation-modes.ts:31and adding a branch inrunAdvancedExplanation. Add a new audience mode by extendingNarrativeModeatquality-score.ts:17and the prompt templates atlib/explanations/prompts.ts.
lib/ml/
ML model governance + lifecycle utilities. Distinct from lib/scoring/ (which is the algorithms): lib/ml/ handles registry status (draft / challenger / champion / archived), drift detection (PSI + KS), auto-rollback, counterfactual training, target encoding, auto-binning, and preprocessing.
- Entry point:
lib/ml/registry.ts - Public exports:
RegistryStatus,RegistryMetadata,ModelRegistryError,promoteModel,getRegistryMetadata(registry.ts:38, 40, 57, 146, 353);computePsi,computeKs,DriftSamples,PsiResult,KsResult(drift.ts:64, 141, 35, 42, 48); plusauto-binning.ts,auto-rollback.ts,counterfactual-trainer.ts,preprocessing.ts,target-encoding.ts. - Extension point: Add a new registry status by extending
RegistryStatusatregistry.ts:38and adding the transition rule topromoteModelatregistry.ts:146. Add a new drift metric by writing a sibling tocomputePsi/computeKsindrift.ts.
lib/negotiation/
Customer ↔ offer negotiation. Includes a multi-turn agent loop, single-turn apply-mode, an evaluation harness, the realtime-apply route helper called from recommend/route.ts, and Zod-validated guardrails (discount bands, term bands).
- Entry point:
lib/negotiation/types.ts - Public exports:
DiscountBandSchema,TermBandSchema,NegotiationGuardrailsSchema,NegotiationGuardrails,ProposalSchema(types.ts:36, 43, 48, 62, 66);runNegotiationAgent,NegotiationDisabledError,NegotiationGuardrailError,NegotiationAgentError(agent-loop.ts:160, 58, 65, 72);RealtimeApplyTenantSettings,RealtimeApplyOffer,RealtimeApplyDecision(realtime-apply.ts:38, 48, 54); plusapply-mode.ts,eval-harness.ts,multi-turn.ts,realtime-apply-route.ts,guardrails.ts. - Extension point: Add a new negotiation guardrail by extending
NegotiationGuardrailsSchemaattypes.ts:48and adding the corresponding check insiderunNegotiationAgentatagent-loop.ts:160. Add a new negotiation strategy by writing a sibling toagent-loop.tsand wiring it throughapply-mode.tsormulti-turn.ts.
lib/qualification/
The decisioning-gates classifier and the rule-inheritance walker. Classifies every QualificationRule into one of three stages (eligibility | fit | match), resolves effective rules at the four scope levels (global → category → subcategory → offer), detects conflicts, and applies time-aware windows. Distinct from the root lib/qualification-engine.ts which is the runtime evaluator.
- Entry point:
lib/qualification/decisioning-gates.ts - Public exports:
DECISIONING_STAGES,DecisioningStage,STAGE_DESCRIPTIONS,ClassifiableRule,classifyRuleStage(decisioning-gates.ts:14, 15, 17, 32, 45);ScopedRule,ContextScopes,resolveEffectiveRules,RuleConflict,detectRuleConflicts(inheritance.ts:18, 29, 39, 67, 77); plusstages.ts(deprecated re-export shim),skip-reasons-tally.ts,stage-backfill.ts,time-aware.ts. - Extension point: Add a new decisioning stage by extending
DECISIONING_STAGESatdecisioning-gates.ts:14and the classifier atclassifyRuleStageatdecisioning-gates.ts:45. Add a new rule scope by extendingContextScopesatinheritance.ts:29and the resolver atresolveEffectiveRulesatinheritance.ts:39.
Configuration
Most subdirectories on this page read environment variables vialib/infra/container.ts. Direct env-var dependencies are listed below; cross-link to Environment Variables for the full reference.
| Subdirectory | Env vars (read at runtime) | Default |
|---|---|---|
infra/ | EVENT_PUBLISHER, INTERACTION_STORE, SEARCH_INDEX, plus per-backend envs (KAFKA_BROKERS, MSK_BROKERS, EVENTBRIDGE_REGION, KINESIS_STREAM_NAME, SCYLLA_CONTACT_POINTS, DYNAMODB_TABLE_NAME, KEYSPACES_KEYSPACE, OPENSEARCH_NODE_URL, REDIS_URL) | redis / pg / pg (container.ts:50, 123, 186) |
flow/ | FLOW_STREAMING_ENABLED (gates the streaming runtime under flow/runtime/streaming/) | false (flow/runtime/streaming/feature-flag.ts:11) |
ai/ | STORAGE_BACKEND (gates import/storage/factory.ts); AI_PROVIDER and per-provider envs from AI_ENV (ai/types.ts:14) | provider default is ollama for local dev |
audit/ | SIEM backend env vars read by getSiemConfigFromEnv at audit/sink.ts:48 | none — SIEM forwarder no-ops if unconfigured |
gitops/ | none directly (driven by API request body) | — |
connector-executors/ | none directly (per-connector secrets passed via ConnectorConfig) | — |
governance/ | none directly (driven by tenant settings) | — |
scoring/, arbitration/, fairness/, explanations/, ml/, negotiation/, qualification/ | none directly — all configuration via tenant settings (tenant.settings.aiAnalyzerSettings.*) | — |
Honest limits
lib/audit/has no__tests__/directory —audit/sink.tsis exercised only via the cron route atsrc/app/api/v1/cron/siem-ship/route.ts. Verified byls lib/audit/.lib/cache/is a single file (cache/warmer.ts) and is intentionally not surfaced here — there is no cache abstraction subdirectory; all caching goes throughgetCache()inlib/infra/.lib/pipeline/is vestigial after the legacy ETL deletion (Apr 28). It now contains onlydag.ts,formula-to-sql.ts,sql-safety.ts— utility helpers retained for the new Flow IR runtime. Do not extend it; new pipeline work belongs underlib/flow/.lib/state/is browser-only Zustand stores, not server-side library code. Listed for completeness in the gap matrix but out of scope for this internals page.lib/queue/is a single-file BullMQ wrapper (queue/queues.ts). Worker concurrency is set byWORKER_CONCURRENCYin the worker process; queue topology is not currently documented per-queue.lib/db/ships a Prisma 7 + pg-adapter pattern plus DDL helpers (ddl.ts,partition-migration.ts,rls-ddl.ts,rls.ts,segment-ddl.ts,serialize.ts). The DDL helpers create real PostgreSQL tables for tenant data schemas — this is intentional, see theReal DDLnote inplatform/CLAUDE.md.lib/connector-executors/coming-soon.tsreturns a structured-503 for any registered-but-unimplemented connector. This is the loud-fail replacement for the pre-31 silent-undefined behavior — but it does mean a tenant can configure a connector in the UI that will fail at first dispatch with a 503. Add the executor before promoting the connector indomain/connector-registry.ts.lib/ai/has a fast-changing surface — the tools registry (ai/tools/) gains entries with most product changes. The 11-tool count cited above (ai/tools/index.ts:1-11) is accurate at time of writing but rotates.lib/flow/is the largest and youngest module on this page (Phases 6.0 → 6.6 shipped Apr 27). The streaming runtime underflow/runtime/streaming/is gated byFLOW_STREAMING_ENABLEDand is not wired to any production broker — it is a feature-flag-only scaffold for self-hosters. Verified viaflow/runtime/streaming/feature-flag.ts:11.lib/gitops/apply.ts:18flags V1 scope explicitly: onlyCategory,Channel,ArbitrationProfile,Offer,DecisionFlowreconcile fully. Other recognized kinds report asunchanged— see the TODO markers in that file before extending.
Related
- Flow Overview — user-facing slice of
lib/flow/. - Infrastructure — operator-facing slice of
lib/infra/(per-backend toggles + health). - Environment Variables — full reference for every env var read by this layer.
- Architecture Overview — system-level layering above this page.
- Architecture Engine — decision-flow runtime above the per-module internals here.
- Security Model — multi-tenant isolation that gates every call into these modules.
- GitOps API (when added — see Gap Matrix Section A) for the HTTP surface that calls
gitops/apply.ts. - Repository:
platform/src/lib/— open the source for any subdirectory above.