ContentΒ OS

Intelligence Layer β€” Technical Reference

Audience: engineers. Non-technical version: overview.md. Back to the Marketing OS index.

Status: 🟑 several instances live; the unified query layer is still proposed. The codebase now has a named home for tenant knowledge β€” apps/backend/src/ai/knowledge/ (query.ts + kinds/) β€” and five instances of the pattern ship: the compliance rulebook, learned compliance exceptions, verified source profiles, compliance-feedback pattern reports, and the Script Framework Library. What does not exist yet is the single budgeted query interface below.


The pattern to generalise

The knowledge layer (apps/backend/src/ai/knowledge/) plus the compliance agent (ai/agents/compliance/agent.ts) already implement every property the full layer needs:

PropertyHow it's done todayFile
Authored, not hard-codedStored per tenant as complianceIntelligenceai/knowledge/kinds/compliance-rule.ts
Normalised on readnormalizeComplianceIntelligence()same
Active subset selectableactiveIntelRules()same
Rendered for a promptrenderIntelRulesForPrompt()same
Carries reasoning + sourceEach rule holds its own rationale and citationsame
BoundedCOMPLIANCE_INTEL_MAX_RULES = 40, COMPLIANCE_RULE_LIMITSsame
One projected read for a promptgetAgentRulebook() β€” rules, guidelines, exceptions in one queryai/knowledge/query.ts
Citations resolved, not trustedattachRuleCitations() drops invented idsai/agents/compliance/agent.ts
Deterministic beats modelmergeComplianceFindings() prefers exact matchessame
Model claims verified before useThe source profiler tests every proposed rule against real pages and drops what failsmodules/news/services/source-profiler.ts

That last pair is the non-negotiable part. The model proposes; the store adjudicates.


The problem it solves

Context assembly is currently duplicated per agent. blog-generator.ts alone does:

const [brand, compliance, competitorBrief, keywords] = await Promise.all([
  resolveBrandContext(tenantId),
  getTenantComplianceRules(tenantId),
  buildCompetitorBrief(tenantId),
  selectBlogKeywords(tenantId, {...}, queuedByUserId),
]);
// then hand-prune each to fit: 6000 / 1200 / 5000 char budgets

Every agent repeats a variant of this, with its own budgets and its own pruning. Nine agents means nine places a brand change can fail to take effect, and nine different answers to "what did the model actually see?"


Proposed shape

A single read interface, one write path, versioned.

// proposed β€” does not exist
interface IntelligenceQuery {
  tenantId: string;
  kinds: KnowledgeKind[];       // which stores to draw from
  subject: { title?, text?, url?, geoState?, category? };
  budget: number;               // total char budget, allocated across kinds
}

interface IntelligenceContext {
  records: KnowledgeRecord[];   // each with id, kind, content, rationale, source
  rendered: string;             // prompt-ready block
  version: string;              // for staleness + reproducibility
  truncated: KnowledgeKind[];   // what did NOT fit β€” never silent
}

KnowledgeRecord mirrors ComplianceIntelRule: an id that can be cited, content, the reasoning it was authored for, and a source. Every agent's output schema then carries cited_ids, validated against the returned record set the same way attachRuleCitations() does today.

Knowledge kinds

KindSource todayState
compliance_rulecomplianceIntelligence (ai/knowledge/kinds/compliance-rule.ts)βœ… correct shape already
compliance_exceptionlearned from dismissals (ai/knowledge/kinds/compliance-exception.ts)βœ… citable, human-armed
source_profileverified scrape rules per news source, on content_news_sourcesβœ… every rule verified against real pages before use
choice_eventcontent_compliance_feedback β€” article approve/reject with a compulsory reason, finding dismissals, gate acknowledgements🟑 live for the compliance-review surfaces; queue/publish/edit events across the rest of the product are still open
brand_guidelinebrandGuidelines, blogPrompt (ai/knowledge/kinds/brand-guideline.ts)🟑 free text, no ids, not citable
seo_keywordkeyword inventory + gaps, now Semrush-backed β€” a worker refreshes rank and volume, and every metric records its source🟑 structured and live, not citable
personacontent_audience_personas🟑
hook_formulalearning profile v2 + the Script Framework Library (ai/knowledge/kinds/script-framework.ts)🟑
competitor_topicops_ca_*🟑 read-only by design
geo_marketgeoState on feed items🟑 tag only, no market records
reader_questionAnswerThePublic searches, ledgered in ops_atp_searches (one platform account, 200/month)🟑 live, consumed only by blog FAQs, not citable
glossary_termβ€”β¬œ needed by Localization
cost_factops_token_usage β€” every provider call priced at read time, per pipeline and piece🟑 live and reporting-shaped on the monitor console; no agent reads it
performance_factInstagram metrics (learning only)⬜ not reporting-shaped
customer_segmentβ€”β¬œ blocked on CRM

The 🟑 rows mostly need ids and a rationale field rather than new storage. That is the bulk of the migration.


Retrieval vs fine-tuning

Decide once, explicitly.

RetrievalFine-tuning
Rule change latencynext callretrain cycle
Attributioncited_ids β†’ recordnone
Bad fact removaldelete rowretrain
Audit trailthe store is the trailnone
Tenant isolationowner filter, already enforcedseparate model per tenant
Costretrieval + context tokenstraining + eval + hosting

Recommendation: retrieval for facts and rules, permanently. Under RBI scrutiny an unciteable answer is not defensible, and the compliance agent's existing design already accepts this.

Fine-tuning stays open for style β€” house voice, script cadence β€” where there is nothing to cite. Even then, prefer few-shot from the layer first.


Design constraints, inherited from what works

  1. Fail open, never fail closed. No layer β†’ agents fall back to today's direct reads. A retrieval outage must not block the feed, matching every existing agent's behaviour.
  2. Truncation is reported, never silent. truncated in the response. The current per-agent prunePromptContext calls drop context invisibly.
  3. Deterministic sources outrank model output on conflict, as mergeComplianceFindings() already does.
  4. Tenant scope through the owner filter. No new access path β€” this layer would otherwise become the one place cross-tenant leakage is possible.
  5. No PII into prompts. When customer_segment lands, records must carry cohort attributes, never identifiers.
  6. Versioned like FEED_ENRICHMENT_VERSION. A context version stamped on every output, so a stale result is detectable β€” the same staleness signal the blog compliance report uses (reviewedVersion vs draft.version).

Migration path

Incremental, each step useful alone:

1  Add id + rationale + source to brand guidelines        β†’ citable brand
2  Wrap existing reads behind one query interface          β†’ no behaviour change
3  Move blog-generator's Promise.all onto it               β†’ one agent proven
4  Add `truncated` reporting                               β†’ stop silent pruning
5  Add choice_event capture (queue/dismiss/publish)         β†’ extends Learning
   (done for the compliance-review surfaces: a durable event log in
    content_compliance_feedback β€” rejects with compulsory reasons,
    dismissals, acknowledgements β€” feeds the shipped Learning agent.
    Queue/publish/edit events on the other surfaces are still open.)
6  Add glossary_term                                        β†’ unblocks Localization
7  Port remaining agents                                    β†’ single context path

Steps 1–4 touch no agent behaviour and are independently shippable. Step 5's first slice shipped with the Learning agent; widening it to every surface is what lets that agent see the whole picture.


Open questions

  • Retrieval strategy. Rule counts are small (≀40) and fit whole; keywords and choice events will not. Embeddings, or structured filters plus recency? Start structured β€” the corpus is not yet large enough to justify a vector store.
  • Who curates. The layer's quality becomes the product's quality. Compliance rules have an admin-only editor; the rest have no ownership model.
  • Write-back authority. Should the Learning agent write records directly, or propose them for human acceptance? Given every other agent stops short of autonomous action, propose is the consistent answer.
  • Conflict resolution between kinds β€” brand voice says one thing, a compliance rule forbids it. Compliance already outranks brand in the blog master prompt; that precedence needs stating layer-wide.

Roadmap source

Deliverable β‘£ "Marketing OS β€” Architecture" (page 5); page 1's data layer (IIFL DATA β†’ CRM, Outside world DATA, MANUAL); page 2's target-state list (data enrichment Β· personalization Β· intelligence agent Β· NBA). See ../../roadmap_ref_extracted.md.

Source: roadmap/marketing-os/intelligence-layer/technical.md