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
| Function | Synthesise clientResearchOutput + competitorResearchOutput into a structured Markdown context file |
| Type | Setup (final step of the client context pipeline) |
| Model | Claude Sonnet 4.6 |
| Queue | agent__context-file-writer |
| Concurrency | 5 |
| Timeout | 15 min (timeoutSec: 900) |
| Max turns | 20 (hard cap added April 2026) |
| Est. cost / task | ~$0.27 |
| Plan | Free+ (all tenants) |
Triggers
| Trigger type | When | Who initiates |
|---|---|---|
| Auto (setup chain) | After Competitor Researcher completes — final step in the setup chain | Platform (event-chained from Competitor Researcher success) |
| Auto (skip path) | If enableCompetitorResearch = false, fired directly after Client Researcher with a placeholder competitor string | Platform |
| Human on-demand | Revision flow triggered from Dashboard → Client Context | Tenant 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
BrandVoiceDB record ifenableBrandVoiceSection = trueand status is"active" - Key Pages — a list of published blog posts and landing pages from the DB if
enableKeyPagesSection = true
How It Works
-
Receive job — BullMQ dequeues the job. Worker builds the prompt using
buildContextFileWriterPrompt()(exported fromsetup.worker.ts) with tenantName, country, plan, clientResearchOutput, competitorResearchOutput, and optional revisionNotes. -
Skills dir created —
createSkillsDir()writessearch_knowledge.js+CLAUDE.mdinto a temp directory passed via--add-dir. -
Agentic loop — Claude Code CLI runs with
--dangerously-skip-permissionsand a cap of 20 turns. The agent:- Writes the context file (
context.mdorclient-context.md) to its working directory using theWritetool - Does not call
search_knowledge— the system prompt explicitly instructs it not to, since all research is already in the prompt - Uses
Bashonly if needed to verify the file was written
- Writes the context file (
-
File read + validation — Worker reads
context.mdfrom the working directory and runsvalidateContextOutput(). -
Brand Voice + Key Pages appended — Worker queries the DB and appends these sections to the output string directly, without re-running the agent.
-
Persist — Output is saved to
ClientContext.contentand status set to"ready". AClientContextLogrecord is written withaction: "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 file | Purpose |
|---|---|
search_knowledge.js | Available but the agent is instructed not to call it |
CLAUDE.md | Usage guide for search_knowledge |
The agent does no RAG. All research arrives in the prompt payload.
search_knowledgeis present in the skills dir (it’s injected for all setup agents) but the system prompt explicitly suppresses its use.
Tools Used (actual)
| Tool | Calls per run | Purpose |
|---|---|---|
Write | 1 | Write context.md to the working directory |
Bash | 0–2 | Verify 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 calls | 1–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:
| Section | Source | Condition |
|---|---|---|
| Brand Voice | BrandVoice DB record | enableBrandVoiceSection = true AND status = "active" |
| Key Pages | BlogPost (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
| Error | Response |
|---|---|
Neither context.md nor client-context.md found | Falls 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 missing | Job throws immediately; setup chain fails |
competitorResearchOutput missing | Job 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
| Setting | How it’s used |
|---|---|
contextConfig.enableBrandVoiceSection | Controls whether Brand Voice is appended post-generation |
contextConfig.enableKeyPagesSection | Controls whether Key Pages are appended post-generation |
tenantName | Passed in prompt |
country | Passed in prompt |
plan | Passed in prompt |