Skip to Content
AgentsContext File Writer

Context File Writer

[Live] · agent__context-file-writer · Claude Sonnet 4.6

Synthesises client research and competitor analysis into the Client Context File — the single Markdown document injected into every other agent in the system.


Overview

FunctionSynthesise clientResearchOutput + competitorResearchOutput into a structured Markdown context file
TypeSetup (final step of the client context pipeline)
ModelClaude Sonnet 4.6
Queueagent__context-file-writer
Concurrency5
Timeout15 min (timeoutSec: 900)
Max turns20 (hard cap added April 2026)
Est. cost / task~$0.27
PlanFree+ (all tenants)

Triggers

Trigger typeWhenWho initiates
Auto (setup chain)After Competitor Researcher completes — final step in the setup chainPlatform (event-chained from Competitor Researcher success)
Auto (skip path)If enableCompetitorResearch = false, fired directly after Client Researcher with a placeholder competitor stringPlatform
Human on-demandRevision flow triggered from Dashboard → Client ContextTenant admin

Input

interface SetupJobData { tenantId: string; tenantName: string; country: string; plan: string; clientResearchOutput: string; // full Markdown from client-researcher competitorResearchOutput: string; // full Markdown from competitor-researcher (or placeholder) revisionNotes?: string; // present on revision runs; guides the synthesis wakeReason: WakeReason; }

Output

The agent writes a Markdown file to its working directory. The worker tries context.md first, then falls back to client-context.md (the agent has been observed writing either name). result.output (the agent’s final summary message) is ignored in favour of the file content.

The file is validated by validateContextOutput() which checks for at least 3 ## section headings and a minimum length of 500 characters. A warning is logged if it falls short but the run still succeeds.

After the agent completes, the worker appends two additional sections directly (not via the agent):

  • Brand Voice — formatted from the BrandVoice DB record if enableBrandVoiceSection = true and status is "active"
  • Key Pages — a list of published blog posts and landing pages from the DB if enableKeyPagesSection = true

How It Works

  1. Receive job — BullMQ dequeues the job. Worker builds the prompt using buildContextFileWriterPrompt() (exported from setup.worker.ts) with tenantName, country, plan, clientResearchOutput, competitorResearchOutput, and optional revisionNotes.

  2. Skills dir createdcreateSkillsDir() writes search_knowledge.js + CLAUDE.md into a temp directory passed via --add-dir.

  3. Agentic loop — Claude Code CLI runs with --dangerously-skip-permissions and a cap of 20 turns. The agent:

    • Writes the context file (context.md or client-context.md) to its working directory using the Write tool
    • Does not call search_knowledge — the system prompt explicitly instructs it not to, since all research is already in the prompt
    • Uses Bash only if needed to verify the file was written
  4. File read + validation — Worker reads context.md from the working directory and runs validateContextOutput().

  5. Brand Voice + Key Pages appended — Worker queries the DB and appends these sections to the output string directly, without re-running the agent.

  6. Persist — Output is saved to ClientContext.content and status set to "ready". A ClientContextLog record is written with action: "research_completed".


System Prompt (live in AgentConfig table)

You are the Context File Writer agent for Leadmetrics, a digital marketing agency AI platform. Your task is to synthesise client and competitor research notes into a single, structured client context file. This context file is the single source of truth injected into every subsequent agent. It must be accurate, comprehensive, and well-structured. DO NOT call search_knowledge or any RAG tool — all research is provided in this prompt. Write the context file directly from the research notes below. CONTEXT FILE REQUIREMENTS: 1. Write a structured Markdown document using exactly these sections (## headings): ## Business Overview ## Products & Services ## Target Audience ## Brand Voice & Tone ## Unique Selling Propositions ## Current Marketing Presence ## Geographic Focus ## Competitive Landscape ## Keyword Opportunities ## Content Gaps & Opportunities ## Technical Notes 2. USE MARKDOWN TABLES for structured, comparative, or list data — never use bullet lists where a table is cleaner: - "Products & Services": table with columns | Product/Service | Description | Target User | Key Benefit | - "Target Audience": table with columns | Segment | Demographics | Pain Points | Goals | - "Current Marketing Presence": table with columns | Channel | Status | Audience Size / Metrics | Notes | - "Competitive Landscape": table with columns | Competitor | Strengths | Weaknesses | Key Differentiator | - "Keyword Opportunities": table with columns | Keyword | Intent | Estimated Volume | Difficulty | - "Content Gaps & Opportunities": table with columns | Gap / Opportunity | Recommended Format | Priority | 3. Use bullet lists only for genuinely unstructured content (Brand Voice attributes, USPs, Technical Notes, Business Overview narrative). 4. Be specific and factual — do not invent information not present in the research notes. 5. Keep the document scannable — agents will use it as reference material during execution. 6. Do not include any commentary, caveats, or meta-notes about the research quality. Output ONLY the context file Markdown document. No preamble, no explanation, no code fences.

The system prompt is stored in AgentConfig.systemPrompt (role context-file-writer) and can be updated via Manage → Agents without a redeploy. The seed in packages/db/src/seed.ts mirrors this value.


Skills Injected

Skill filePurpose
search_knowledge.jsAvailable but the agent is instructed not to call it
CLAUDE.mdUsage guide for search_knowledge

The agent does no RAG. All research arrives in the prompt payload. search_knowledge is present in the skills dir (it’s injected for all setup agents) but the system prompt explicitly suppresses its use.


Tools Used (actual)

ToolCalls per runPurpose
Write1Write context.md to the working directory
Bash0–2Verify file write; previously used to call search_knowledge (removed April 2026)

Total tool calls: 1–3. The 2 Bash calls in runs before April 2026 were unnecessary search_knowledge.js invocations — the agent was querying RAG datasets that contained nothing new at this point in the pipeline.


Cost Profile

Typical tool calls1–3
Est. output tokens~10,000 (the context.md file is comprehensive by design)
Est. cost / task~$0.27
Est. duration~3 min (generation time for 10K tokens)

The output token count is intentionally high — the context file is the canonical reference for all downstream agents, so coverage matters. The output tokens here are a one-time cost that prevents each downstream agent from needing to re-research the same information.


Adapter Config

Set in setup.worker.ts for the context-file-writer role:

{ cwd, model, // from AgentConfig.model dangerouslySkipPermissions: true, timeoutSec: 900, maxTurnsPerRun: 20, // hard cap added April 2026 }

Post-Agent DB Appends

After the agent exits, the worker appends these sections directly from the database — the agent never sees or writes them:

SectionSourceCondition
Brand VoiceBrandVoice DB recordenableBrandVoiceSection = true AND status = "active"
Key PagesBlogPost (client_approved/published) + LandingPage (published)enableKeyPagesSection = true

These are formatted by formatBrandVoiceSection() in setup.worker.ts and appended as ## sections to the final output string before it is persisted.


Error Handling

ErrorResponse
Neither context.md nor client-context.md foundFalls back to result.output (the agent’s final text message — just a summary, not the document)
Output fails validateContextOutput()Warning logged; run still succeeds and proceeds
clientResearchOutput missingJob throws immediately; setup chain fails
competitorResearchOutput missingJob throws immediately (pass the placeholder string if competitor research is disabled)
Max turns reached (20)BullMQ job fails; setup chain retries per BullMQ config

Tenant Settings Used

SettingHow it’s used
contextConfig.enableBrandVoiceSectionControls whether Brand Voice is appended post-generation
contextConfig.enableKeyPagesSectionControls whether Key Pages are appended post-generation
tenantNamePassed in prompt
countryPassed in prompt
planPassed in prompt

© 2026 Leadmetrics — Internal use only