Build the MasteryMade Embeddable Agent with Claude Code

A single JavaScript bundle that embeds on any HTML page via a <script> tag. On load, it reads the page content, a JSON config, and a YAML knowledge manifest โ€” then renders a floating chat panel that guides users through the content. One engine. Three deployment modes. Differentiated by config, not code. Claude Code builds it. You verify it.

Traditional Approach

Custom per page
Vector DB, RAG pipeline, separate build per use case, sync maintenance

This Approach

HTML IS the knowledge
Zero sync โ€” update page = update agent. YAML manifest indexes related pages. One bundle, infinite deployments.

Infrastructure

Backend + DB + Auth
Server, database, user accounts, deployment pipeline

Infrastructure

<script> tag
Client-side JS + localStorage + YAML manifest + Anthropic API (or thin proxy)

โš ๏ธ PREREQUISITES

  • Claude Max subscription ($200/month) โ€” gives Claude Code with generous limits
  • Terminal / command line access
  • Node.js 18+ installed (node --version to check)
  • Basic comfort with: running terminal commands, reading code output, copy-pasting
  • This page URL โ€” share it with Claude Code as the spec source
๐Ÿ”ฎ How This Page Works
This page IS the first instance of the product it describes. It carries three machine-readable blocks: (1) #mastery-agent-config JSON โ€” UI and API settings the JS bundle parses, (2) #mastery-agent-knowledge YAML template โ€” enrichment data and related-page manifest the LLM reads directly, (3) #mastery-agent-data JSON โ€” the complete build PRD that Claude Code reads. Share this URL with Claude Code and it gets the full technical spec. The agent you build will read blocks 1 and 2 from future pages.
0

Create Project & Install Dependencies

Setup

Set up the project folder, initialize npm, install esbuild, and create the folder structure. This is the only step you do mostly yourself before handing off to Claude Code.

โŒ Before

  • No project directory
  • No build tooling
  • No structure for the agent source files

โœ… After

  • Clean project with esbuild configured
  • Build + dev scripts ready
  • src/, dist/, test/, styles/ folders created
๐Ÿ“‹ Recipe
  • Open terminal and create project directory: mkdir mastery-agent && cd mastery-agent
  • Give Claude Code the initialization prompt (below)
  • Verify package.json has esbuild in devDependencies
  • Verify build and dev scripts exist in package.json
  • Verify src/, dist/, test/, styles/ folders exist
  • Run npm install to install dependencies
๐Ÿค– Say to Claude Code: Initialize Project
Initialize a Node.js project for a browser-embeddable JavaScript bundle. We need esbuild as a dev dependency. The build script should bundle src/agent.js into dist/mastery-agent.js as an IIFE (self-executing function). Add a dev script that watches for changes and serves the test/ directory. No other dependencies โ€” this is a zero-dependency browser bundle. Create the folder structure: src/, dist/, test/, styles/.
Expected package.json{
  "name": "mastery-agent",
  "version": "1.0.0",
  "scripts": {
    "build": "esbuild src/agent.js --bundle --outfile=dist/mastery-agent.js --minify --format=iife",
    "dev": "esbuild src/agent.js --bundle --outfile=dist/mastery-agent.js --format=iife --watch --servedir=test"
  },
  "devDependencies": {
    "esbuild": "^0.20.0"
  }
}
1

Feed the Full Spec to Claude Code

Core

The most important step. Claude Code needs the complete technical specification before writing a single line of code. This page has three hidden data blocks โ€” the config JSON, the YAML knowledge manifest, and the full PRD JSON. Claude Code needs to read all of them.

โŒ Before

  • Claude Code has no context about the project
  • Will guess at architecture decisions
  • No shared understanding of schemas or specs

โœ… After

  • Claude Code knows the full file structure, all schemas, all specs
  • Understands both the YAML knowledge manifest format and the JSON config format
  • Can reference specific PRD sections during build
๐Ÿ“‹ Recipe
  • Share this page's URL with Claude Code (or paste the enrichment JSON)
  • Wait for Claude Code to confirm it understood the spec
  • Verify Claude Code understands there are THREE data blocks: config JSON, knowledge YAML template, and PRD JSON
  • Verify Claude Code's proposed build order: parser (with knowledge manifest loader) โ†’ config โ†’ heuristics + prompt-builder โ†’ API โ†’ progress โ†’ chat UI โ†’ main entry
๐Ÿค– Say to Claude Code: Load Spec
I'm building an embeddable AI agent. Here is the full spec page: [THIS PAGE'S URL]. Read the entire page including ALL hidden blocks: (1) id="mastery-agent-config" โ€” JSON config the agent's JS parses for UI/API settings, (2) id="mastery-agent-knowledge" โ€” YAML template inside HTML comments that the agent reads as raw text and passes into the LLM system prompt, (3) id="mastery-agent-data" โ€” JSON containing the complete build PRD with file structure, HTML schema, config schema, heuristics spec, parser spec, prompt builder spec, UI spec, and acceptance criteria. Pay special attention to the knowledgeManifest section in the architecture spec and the parserSpec โ€” the agent must support BOTH the new YAML template format AND the legacy JSON format as fallback. Read everything before doing anything, then tell me what you understand the build order should be.
โš ๏ธ If Claude Code Seems Confused About the Knowledge Manifest
Say: "This page has TWO knowledge formats. The NEW format is a <template id='mastery-agent-knowledge'> block with YAML inside HTML comments. The LEGACY format is a <script id='mastery-agent-data'> block with JSON. The agent you're building must check for the template FIRST, fall back to the script block if not found. The LLM reads YAML natively โ€” do NOT parse it in JavaScript. Just read innerHTML, strip comment delimiters, pass as raw string."
2

Build the HTML Parser + Knowledge Manifest Loader

Core

The parser does two things: (1) reads the host page's HTML and extracts structured content via data-mastery attributes (with generic fallback), and (2) loads the knowledge manifest from the YAML <template> block (with JSON fallback). This is what makes the agent work on ANY page.

๐Ÿ“‹ Recipe
  • Give Claude Code the parser prompt
  • Open src/parser.js โ€” verify it has parsePage() function
  • Verify it has loadKnowledgeManifest() that checks <template> FIRST, then falls back to <script> JSON
  • Verify it does NOT import a YAML parsing library โ€” raw string only
  • Verify it queries for ALL data-mastery attributes: title, step, step-title, step-description, substeps, substep, step-links, link, code, content, decision, action-item
  • Verify fallbackParse() function exists for pages without schema
  • Verify it exports both parsePage and loadKnowledgeManifest
๐Ÿค– Say to Claude Code: Build Parser + Knowledge Loader
Build src/parser.js with TWO exported functions: 1) parsePage() โ€” HTML content extractor: - Extract data-mastery attributed elements (title, steps with substeps, content sections, decisions, action items, links, code blocks) - Fall back to generic HTML parsing when no data-mastery attributes found (extract h1-h4 as topics, p as content, pre>code as code, a as links) - Return structured object: { title, steps[], content[], decisions[], actionItems[], links[], codeBlocks[] } 2) loadKnowledgeManifest() โ€” Knowledge loader with fallback chain: - FIRST: Check for <template id="mastery-agent-knowledge">. If found, read innerHTML, strip <!-- and --> comment wrappers, trim whitespace, return as RAW STRING. Do NOT parse YAML โ€” the LLM reads it natively. - SECOND: If no template found, check for <script id="mastery-agent-data">. If found, parse as JSON, stringify with formatting, return as string. - THIRD: If neither found, return null. Agent will work with visible HTML only. - CRITICAL: Do NOT import any YAML parsing library. The entire point is that the LLM reads YAML as text. Export both functions.
๐Ÿ’ก Why Two Knowledge Formats?
The YAML <template> format is ~35% more token-efficient than JSON and easier for content creators to edit. The JSON fallback ensures backward compatibility with pages that haven't migrated. The agent handles both transparently โ€” future pages use the template, existing pages keep working.
3

Build Config Loader + Heuristics + Prompt Builder

Core

Three files that work together: config reads the JSON from the page, heuristics contains the "chef's brain" system prompt template, prompt-builder assembles everything โ€” including the knowledge manifest โ€” into the final system prompt. The heuristics file is the most important single artifact. The prompt builder must place the knowledge manifest BEFORE page content (order matters for LLM attention).

๐Ÿ“‹ Recipe
  • Give Claude Code the combined prompt for all three files
  • CHECK CAREFULLY: Open src/heuristics.js โ€” verify ALL 8 anti-slop rules are present
  • Verify execution mode has all 5 core behaviors: orient, instruct, verify, advance, adapt
  • Verify all 6 progress commands are listed: begin, next, back, step [N], status, help
  • Verify prompt-builder takes 4 inputs (config, pageContent, knowledgeManifest, progress) and places manifest BEFORE page content
  • Verify prompt-builder includes related-pages awareness instructions for Phase 1
  • Verify config.js handles missing/malformed JSON gracefully โ€” returns defaults, doesn't crash
๐Ÿค– Say to Claude Code: Build Config + Heuristics + Prompt Builder
Build three files: 1) src/config.js โ€” reads JSON from <script id="mastery-agent-config">. Validates required fields (minimum: mode). Merges with defaults per the config schema in the spec. Export loadConfig. Note: config is ALWAYS JSON, never YAML. 2) src/heuristics.js โ€” the static system prompt template. Contains ALL the core behaviors, anti-slop rules, mode-specific instructions, and progress commands from the spec. Template placeholders for dynamic content. Export getHeuristics. 3) src/prompt-builder.js โ€” takes (config, pageContent, knowledgeManifest, progress) and assembles the complete system prompt. CRITICAL ORDERING: knowledge manifest goes BEFORE page content in the prompt. Structure: - Role and behavior (from heuristics, parameterized by mode) - Anti-slop rules - KNOWLEDGE MANIFEST: {knowledgeManifest raw text} - PAGE CONTENT: {parsed HTML content} - CURRENT PROGRESS: {step tracking} - RELATED PAGES INSTRUCTION: "The knowledge manifest lists related pages. You cannot fetch their content yet. When a user asks about a topic covered by a related page, mention it exists and provide the URL." Export buildPrompt.
โš ๏ธ If the Heuristics Feel Generic
Say to Claude Code: "The heuristics need more teeth. Add these specific rules: 1) Every response must reference THIS specific page content โ€” if it could apply to any page, redo it. 2) Code snippets must be complete and copy-pasteable, never partial. 3) When a step involves a link, tell the user exactly what to do after they open it. 4) Never say 'it depends' without immediately resolving what it depends on for THIS user's situation."
4

Build API Client + Progress Tracker

Core

Two utility modules: the API client calls the Anthropic Messages API (with proxy support for production), and the progress tracker persists state in localStorage keyed by page URL.

๐Ÿ“‹ Recipe
  • Give Claude Code the combined prompt
  • Verify api.js supports config.api.proxyUrl โ€” calls proxy when set, direct API when null
  • Verify api.js has try/catch with user-friendly error messages (never stack traces)
  • Verify progress.js caps conversation history at 20 messages
  • Verify localStorage key derives from page URL via btoa(url).slice(0,32)
๐Ÿค– Say to Claude Code: Build API + Progress
Build: 1) src/api.js โ€” fetch wrapper for Anthropic Messages API. Takes messages array, system prompt, config. Uses config.api.model, config.api.maxTokens. Supports config.api.proxyUrl (if set, calls proxy instead of api.anthropic.com). Try/catch with friendly error messages, never expose stack traces. Export sendMessage. 2) src/progress.js โ€” localStorage keyed by page URL (btoa(url).slice(0,32) as key). Stores: currentStep, completedSteps[], completedSubsteps{}, conversationHistory (cap at 20 messages), startedAt, lastUpdated timestamps. Export loadProgress, saveProgress.
5

Build the Chat UI

Core

The visual component โ€” a floating chat panel using Shadow DOM for complete CSS isolation from the host page. Collapsed state is a circular button, expanded shows the full chat with messages, code blocks, and progress bar. Must be vanilla JavaScript only โ€” no React, no frameworks.

โŒ Before

  • No user interface
  • All logic but no way to interact
  • Engine exists but is invisible

โœ… After

  • Floating chat panel in bottom-right
  • Messages, code blocks, links all rendered
  • Mobile responsive bottom sheet
  • CSS completely isolated from host page
๐Ÿ“‹ Recipe
  • Give Claude Code the chat UI prompt
  • Verify Shadow DOM usage โ€” look for attachShadow in the code
  • Verify CSS is embedded as string, injected into shadow root (not document.head)
  • Verify NO React or framework imports โ€” must be pure document.createElement
  • Verify: collapsed/expanded toggle, message rendering, code copy button, link new-tab
  • Verify mobile responsive: full-width bottom sheet under 768px
๐Ÿค– Say to Claude Code: Build Chat UI
Build src/chat.js with embedded CSS (no separate file). Requirements: 1) Shadow DOM for complete style isolation from host page. 2) Collapsed state: 48x48px circular button with avatar emoji, subtle pulse animation, positioned per config. 3) Expanded: panel at config width ร— maxHeight, rounded corners, dark background, slide-up animation. 4) Layout: header (name + progress bar) โ†’ message area (scrollable) โ†’ input (text + send button). 5) Messages: user right-aligned tinted primaryColor, agent left-aligned dark. 6) Code blocks in responses: monospace, dark bg, copy button. 7) Links in responses: clickable, open new tab. 8) Responsive: full-width bottom sheet under 768px. 9) CRITICAL: Vanilla JavaScript ONLY โ€” no React, no frameworks. Use document.createElement and DOM manipulation. All CSS injected as string into shadow root.
โš ๏ธ If Claude Code Creates a React Component
Say: "This must be vanilla JavaScript with no framework dependencies. It's a self-contained script that works on any page. No React, no Vue, no build-time framework. Use document.createElement and DOM manipulation."
6

Build Main Entry Point + Bundle

Core

The main entry point orchestrates everything โ€” imports all modules, bootstraps on load, handles the message flow from user input through API call to response rendering. Then bundle it all into a single file.

๐Ÿ“‹ Recipe
  • Give Claude Code the main entry point prompt
  • Verify agent.js imports all other modules and has the bootstrap sequence
  • Verify bootstrap loads knowledge manifest via loadKnowledgeManifest() and passes to buildPrompt()
  • Run: npm run build
  • If build fails โ€” paste the error to Claude Code: "Build failed with [error]. Fix it."
  • Verify dist/mastery-agent.js exists and is under 100KB
๐Ÿค– Say to Claude Code: Build Entry Point + Bundle
Build src/agent.js as the main entry point. Self-executing IIFE on load. Flow: 1) loadConfig(), 2) parsePage(), 3) loadKnowledgeManifest(), 4) loadProgress(window.location.href), 5) buildPrompt(config, pageContent, knowledgeManifest, progress), 6) renderChat(config, progress, systemPrompt). When user sends a message: append to conversation history โ†’ call sendMessage API โ†’ render response โ†’ update progress โ†’ saveProgress. Import all modules we built. Then run npm run build and fix any import/export issues until we get a clean dist/mastery-agent.js bundle.
๐Ÿ’ก Common Build Issue
The most common failure is import/export format mismatch. All modules must use ES module syntax (import/export). esbuild handles the conversion to IIFE format. If you get errors about require or module.exports, tell Claude Code to convert to ES module syntax.
7

Build Test Pages & Run Full Testing

Test

Four test pages โ€” three using the new YAML template format (one per deployment mode) plus one legacy JSON page for backward compatibility. Test every P0 acceptance criterion. Write down every bug, then batch-fix them all.

๐Ÿ“‹ Recipe
  • Give Claude Code the test pages prompt (below)
  • Start dev server: npm run dev
  • Open test-playbook.html โ€” agent button visible in bottom-right
  • Click agent, type "begin" โ€” get step-by-step guidance (not generic)
  • Test "status" command โ€” shows current progress
  • Reload page โ†’ open chat โ†’ "status" โ€” progress persisted from localStorage
  • Ask "What's the weather?" โ€” agent redirects to playbook topic
  • Test mobile: devtools โ†’ device toolbar โ†’ verify bottom sheet layout
  • Open test-proposal.html โ€” QA mode, answers about proposal content
  • Open test-dashboard.html โ€” search mode, finds action items by owner
  • Open test-legacy.html โ€” verify agent works with old JSON format (no <template> block)
  • Paste ALL bugs to Claude Code: "Here are the issues: [list]. Fix all of them."
  • Re-run ALL tests after fixes โ€” everything passes
๐Ÿค– Say to Claude Code: Build Test Pages
Build four test pages that embed dist/mastery-agent.js. The first three use the NEW knowledge manifest format (<template id="mastery-agent-knowledge"> with YAML). The fourth tests backward compatibility. 1) test/test-playbook.html โ€” "Build Your Own 24/7 AI Assistant" playbook using full data-mastery schema. 8 steps with substeps. Config: execution mode. Knowledge manifest (YAML in template): includes enrichment with code snippets for steps 0-3, related pages (deep-dive and prerequisite), and behavior hints. Must look like a real styled content page, not raw HTML. 2) test/test-proposal.html โ€” Mock JV proposal for "Brad Himel - Newsletter Growth Partnership." data-mastery="content" sections for terms, revenue share (50/50), timeline, what each party provides. Config: qa mode, consultative tone. Knowledge manifest: includes related pages pointing to onboarding process (auth: internal) and expert light-scrape (auth: internal). 3) test/test-dashboard.html โ€” Mock MasteryOS meeting dashboard. 3-4 meeting summaries as data-mastery="content", action items with owners (Jason, Will, Derek, Sumit), decisions. Config: search mode. Knowledge manifest: includes indexed-content entries for each meeting page. 4) test/test-legacy.html โ€” Simple playbook using the OLD format: <script id="mastery-agent-data"> with JSON enrichment, NO <template> block. Verify the agent falls back to reading JSON correctly.
โœ… When Something Doesn't Work
Use this prompt: "Show me the flow from [user action] to [expected result]. Where does it break? Add console.log statements at each step so I can see what's happening in the browser console."
8

Clean Up, Build Production, Deploy

Deploy

Remove debug code, create production bundle, set up a Cloudflare Worker proxy to protect your API key, and host the test pages for sharing.

๐Ÿ“‹ Recipe
  • Run cleanup prompt โ€” remove console.logs, commented code, hardcoded values, TODOs
  • Run npm run build โ€” verify clean output, no warnings
  • Verify dist/mastery-agent.js is under 100KB (ideally under 50KB)
  • Build the Cloudflare Worker API proxy (prompt below)
  • Deploy worker, set ANTHROPIC_API_KEY as Cloudflare secret
  • Update test page config: set api.proxyUrl to worker URL
  • Host test pages (GitHub Pages, Vercel, or Cloudflare Pages)
  • Test the hosted version โ€” agent works through proxy, NO API key in client code
  • Create README.md: what it is, how to embed, config schema, knowledge manifest schema, HTML schema
๐Ÿค– Say to Claude Code: Cleanup
Review all source files for: 1) Console.log statements that should be removed, 2) Commented-out code that should be removed, 3) Any hardcoded values that should come from config, 4) Any TODO comments that need resolving. Fix them all. Then run npm run build for the production bundle.
๐Ÿค– Say to Claude Code: Build API Proxy
Build a Cloudflare Worker that proxies Anthropic API requests. It should: 1) Accept POST requests with the same body format as the Anthropic Messages API, 2) Add the API key server-side (stored as a Cloudflare secret called ANTHROPIC_API_KEY), 3) Forward to api.anthropic.com and return the response, 4) Add CORS headers so the test page domain can call it. Give me the worker code and step-by-step deploy instructions.
โš ๏ธ Critical: API Key Security
Do NOT deploy with your API key in the config JSON. For shared/public pages, you MUST use the proxy. The proxy URL goes in config.api.proxyUrl, the API key stays on the Cloudflare Worker as a secret.
9

Share With 3-5 People & Measure

Validate

The entire thesis rests on one question: do users with the AI agent get further through the playbook than users with just the static page? Share with real people and measure.

โŒ Without Agent

  • Users read playbook and get stuck
  • No way to ask questions in context
  • Drop off at first confusing step
  • No data on where people fail

โœ… With Agent

  • Agent walks users through each step
  • Answers questions from page content
  • Diagnoses errors in real time
  • Progress data shows exactly where people drop
๐Ÿ“‹ Recipe
  • Share hosted URL with 3-5 people from your community
  • Ask them to: open page, click agent, say "begin", follow for at least Steps 0-2
  • Collect feedback: where confused, where agent helped, where agent failed, where they quit
  • Compare: how far do people typically get with just the static playbook?
  • If 2x+ completion improvement โ†’ thesis holds โ†’ invest in value ladder tiers
  • If similar completion โ†’ iterate heuristics or format, or thesis needs rethinking
๐Ÿ”ฎ What Success Unlocks
If the agent measurably improves completion rates, the value ladder activates: Tier 0 (free static page) โ†’ Tier 1 (email-gated enhanced prompts) โ†’ Tier 2 (paid embedded agent) โ†’ Tier 3 (pre-built widgets) โ†’ Tier 4 (JV ecosystem). Each tier generates data for the next. The agent isn't the product โ€” it's the data collection system that proves which expert domains have commercial demand.

โœ“ Validate Your Complete Build

Run through this checklist before sharing with anyone. Every item should pass.

  • Agent loads on test-playbook.html via script tag โ€” no other setup
  • Clicking button opens chat panel with smooth animation
  • "begin" command starts step-by-step guidance
  • Agent gives SPECIFIC instructions (not generic advice)
  • Agent asks for confirmation before advancing steps
  • "status" command shows current progress
  • Progress survives page reload (localStorage)
  • Off-topic questions get redirected back to content
  • Code blocks in agent responses have copy buttons
  • Links in agent responses open in new tabs
  • Mobile layout works (full-width bottom sheet)
  • No API key exposed in client code (using proxy)
  • No errors in browser console on load
  • QA mode works on test-proposal.html
  • Search mode works on test-dashboard.html
  • Fallback parsing works on a page with no data-mastery attributes
  • Knowledge manifest loaded from YAML template on test-playbook.html
  • Legacy JSON fallback works on test-legacy.html (no template block)
  • Agent mentions related pages when user asks about topics covered by them
  • README.md exists and documents config, knowledge manifest, and HTML schemas

๐Ÿค– All Claude Code Prompts

Every prompt from each step collected here for batch copying.

Prompt 0: Initialize Project (Step 0)
Initialize a Node.js project for a browser-embeddable JavaScript bundle. We need esbuild as a dev dependency. The build script should bundle src/agent.js into dist/mastery-agent.js as an IIFE (self-executing function). Add a dev script that watches for changes and serves the test/ directory. No other dependencies โ€” this is a zero-dependency browser bundle. Create the folder structure: src/, dist/, test/, styles/.
Prompt 1: Load Full Spec (Step 1)
I'm building an embeddable AI agent. Here is the full spec page: [THIS PAGE'S URL]. Read the entire page including ALL hidden blocks: (1) id="mastery-agent-config" โ€” JSON config the agent's JS parses for UI/API settings, (2) id="mastery-agent-knowledge" โ€” YAML template inside HTML comments that the agent reads as raw text and passes into the LLM system prompt, (3) id="mastery-agent-data" โ€” JSON containing the complete build PRD with file structure, HTML schema, config schema, heuristics spec, parser spec, prompt builder spec, UI spec, and acceptance criteria. Pay special attention to the knowledgeManifest section in the architecture spec and the parserSpec โ€” the agent must support BOTH the new YAML template format AND the legacy JSON format as fallback. Read everything before doing anything, then tell me what you understand the build order should be.
Prompt 2: Build Parser + Knowledge Loader (Step 2)
Build src/parser.js with TWO exported functions: 1) parsePage() โ€” HTML content extractor: - Extract data-mastery attributed elements (title, steps with substeps, content sections, decisions, action items, links, code blocks) - Fall back to generic HTML parsing when no data-mastery attributes found (extract h1-h4 as topics, p as content, pre>code as code, a as links) - Return structured object: { title, steps[], content[], decisions[], actionItems[], links[], codeBlocks[] } 2) loadKnowledgeManifest() โ€” Knowledge loader with fallback chain: - FIRST: Check for <template id="mastery-agent-knowledge">. If found, read innerHTML, strip <!-- and --> comment wrappers, trim whitespace, return as RAW STRING. Do NOT parse YAML โ€” the LLM reads it natively. - SECOND: If no template found, check for <script id="mastery-agent-data">. If found, parse as JSON, stringify with formatting, return as string. - THIRD: If neither found, return null. Agent will work with visible HTML only. - CRITICAL: Do NOT import any YAML parsing library. The entire point is that the LLM reads YAML as text. Export both functions.
Prompt 3: Build Config + Heuristics + Prompt Builder (Step 3)
Build three files: 1) src/config.js โ€” reads JSON from <script id="mastery-agent-config">. Validates required fields (minimum: mode). Merges with defaults per the config schema in the spec. Export loadConfig. Note: config is ALWAYS JSON, never YAML. 2) src/heuristics.js โ€” the static system prompt template. Contains ALL the core behaviors, anti-slop rules, mode-specific instructions, and progress commands from the spec. Template placeholders for dynamic content. Export getHeuristics. 3) src/prompt-builder.js โ€” takes (config, pageContent, knowledgeManifest, progress) and assembles the complete system prompt. CRITICAL ORDERING: knowledge manifest goes BEFORE page content in the prompt. Structure: - Role and behavior (from heuristics, parameterized by mode) - Anti-slop rules - KNOWLEDGE MANIFEST: {knowledgeManifest raw text} - PAGE CONTENT: {parsed HTML content} - CURRENT PROGRESS: {step tracking} - RELATED PAGES INSTRUCTION: "The knowledge manifest lists related pages. You cannot fetch their content yet. When a user asks about a topic covered by a related page, mention it exists and provide the URL." Export buildPrompt.
Prompt 4: Build API + Progress (Step 4)
Build: 1) src/api.js โ€” fetch wrapper for Anthropic Messages API. Takes messages array, system prompt, config. Uses config.api.model, config.api.maxTokens. Supports config.api.proxyUrl (if set, calls proxy instead of api.anthropic.com). Try/catch with friendly error messages, never expose stack traces. Export sendMessage. 2) src/progress.js โ€” localStorage keyed by page URL (btoa(url).slice(0,32) as key). Stores: currentStep, completedSteps[], completedSubsteps{}, conversationHistory (cap at 20 messages), startedAt, lastUpdated timestamps. Export loadProgress, saveProgress.
Prompt 5: Build Chat UI (Step 5)
Build src/chat.js with embedded CSS (no separate file). Requirements: 1) Shadow DOM for complete style isolation from host page. 2) Collapsed state: 48x48px circular button with avatar emoji, subtle pulse animation, positioned per config. 3) Expanded: panel at config width ร— maxHeight, rounded corners, dark background, slide-up animation. 4) Layout: header (name + progress bar) โ†’ message area (scrollable) โ†’ input (text + send button). 5) Messages: user right-aligned tinted primaryColor, agent left-aligned dark. 6) Code blocks in responses: monospace, dark bg, copy button. 7) Links in responses: clickable, open new tab. 8) Responsive: full-width bottom sheet under 768px. 9) CRITICAL: Vanilla JavaScript ONLY โ€” no React, no frameworks. Use document.createElement and DOM manipulation. All CSS injected as string into shadow root.
Prompt 6: Build Entry Point + Bundle (Step 6)
Build src/agent.js as the main entry point. Self-executing IIFE on load. Flow: 1) loadConfig(), 2) parsePage(), 3) loadKnowledgeManifest(), 4) loadProgress(window.location.href), 5) buildPrompt(config, pageContent, knowledgeManifest, progress), 6) renderChat(config, progress, systemPrompt). When user sends a message: append to conversation history โ†’ call sendMessage API โ†’ render response โ†’ update progress โ†’ saveProgress. Import all modules we built. Then run npm run build and fix any import/export issues until we get a clean dist/mastery-agent.js bundle.
Prompt 7: Build Test Pages (Step 7)
Build four test pages that embed dist/mastery-agent.js. The first three use the NEW knowledge manifest format (<template id="mastery-agent-knowledge"> with YAML). The fourth tests backward compatibility. 1) test/test-playbook.html โ€” "Build Your Own 24/7 AI Assistant" playbook using full data-mastery schema. 8 steps with substeps. Config: execution mode. Knowledge manifest (YAML in template): includes enrichment with code snippets for steps 0-3, related pages (deep-dive and prerequisite), and behavior hints. Must look like a real styled content page, not raw HTML. 2) test/test-proposal.html โ€” Mock JV proposal for "Brad Himel - Newsletter Growth Partnership." data-mastery="content" sections for terms, revenue share (50/50), timeline, what each party provides. Config: qa mode, consultative tone. Knowledge manifest: includes related pages pointing to onboarding process (auth: internal) and expert light-scrape (auth: internal). 3) test/test-dashboard.html โ€” Mock MasteryOS meeting dashboard. 3-4 meeting summaries as data-mastery="content", action items with owners (Jason, Will, Derek, Sumit), decisions. Config: search mode. Knowledge manifest: includes indexed-content entries for each meeting page. 4) test/test-legacy.html โ€” Simple playbook using the OLD format: <script id="mastery-agent-data"> with JSON enrichment, NO <template> block. Verify the agent falls back to reading JSON correctly.
Prompt 8a: Cleanup (Step 8)
Review all source files for: 1) Console.log statements that should be removed, 2) Commented-out code that should be removed, 3) Any hardcoded values that should come from config, 4) Any TODO comments that need resolving. Fix them all. Then run npm run build for the production bundle.
Prompt 8b: Build API Proxy (Step 8)
Build a Cloudflare Worker that proxies Anthropic API requests. It should: 1) Accept POST requests with the same body format as the Anthropic Messages API, 2) Add the API key server-side (stored as a Cloudflare secret called ANTHROPIC_API_KEY), 3) Forward to api.anthropic.com and return the response, 4) Add CORS headers so the test page domain can call it. Give me the worker code and step-by-step deploy instructions.

๐Ÿ“š Resources & Architecture

File Structure Reference

  • src/agent.js โ€” Main entry point (IIFE bootstrap)
  • src/parser.js โ€” HTML parser + knowledge manifest loader
  • src/config.js โ€” Config loader (JSON only)
  • src/heuristics.js โ€” System prompt template
  • src/prompt-builder.js โ€” Prompt assembler (manifest + content + progress)
  • src/api.js โ€” Anthropic API client
  • src/progress.js โ€” localStorage tracker
  • src/chat.js โ€” Chat UI (Shadow DOM)
  • dist/mastery-agent.js โ€” Bundled output

Scope Boundaries (Do NOT Build)

  • No user accounts or authentication
  • No backend server (localStorage only)
  • No YAML parsing library (LLM reads YAML as text)
  • No voice features
  • No browser control or automation
  • No sitemap scraping (manifest handles multi-page in Phase 1.5)
  • No analytics, payment, or email gating
  • No streaming responses (add in v2)