0% found this document useful (0 votes)
3 views15 pages

Claude Code Complete Reference

The document is a comprehensive guide for using Claude Code and AI automation, detailing the WAT framework, setup instructions, and automation building with Trigger.dev. It covers the structure of workflows, agents, and tools, as well as the process for creating a personal executive assistant. Additionally, it provides guidelines for deploying automations, error handling, and maintaining workflows effectively.

Uploaded by

abidouabidou77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views15 pages

Claude Code Complete Reference

The document is a comprehensive guide for using Claude Code and AI automation, detailing the WAT framework, setup instructions, and automation building with Trigger.dev. It covers the structure of workflows, agents, and tools, as well as the process for creating a personal executive assistant. Additionally, it provides guidelines for deploying automations, error handling, and maintaining workflows effectively.

Uploaded by

abidouabidou77
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd

Claude Code & AI Automation

Complete Reference Guide for ChatGPT


WAT Framework • [Link] • Executive Assistant Setup • Frontend Rules

Contents
1. Claude Code Beginner Guide (WAT Framework)
2. WAT Agent Instructions ([Link])
3. Executive Assistant / Second Brain Setup
4. [Link] Automation Builder Instructions
5. [Link] API Reference
6. Frontend Website Rules

1. Claude Code Beginner Guide


Source: Master 95% of Claude Code (as a beginner) — by Nate Herk / AIS+

1.1 Interface & Setup


Claude Code lets you build complex coding projects and automations inside your local
development environment (IDE).

• Environment: Visual Studio Code (VS Code)


• Extension: Search for and install the "Claude Code" extension in the VS Code
marketplace.
• Access: Requires a paid Anthropic plan (Claude Pro or Team). Sign in with your
Anthropic account inside the extension.
• Layout:
◦ Left Side (Explorer) — your file structure: Workflows, Tools, Prompts
◦ Right Side (Agent) — the chat interface where you plan and execute tasks
• Bypass Permissions: Enable in extension settings so the agent can edit files without
asking approval on every step.
1.2 The WAT Framework
WAT separates probabilistic reasoning (AI) from deterministic execution (code). This keeps the
system reliable.

Layer 1: Workflows (/workflows)


• Format: .md (Markdown) files
• Purpose: SOPs (Standard Operating Procedures) — define the objective, required
inputs, tool sequences, and edge cases in plain English
• Analogy: the manager telling the worker exactly what steps to take

Layer 2: Agent ([Link])


• Format: .md system prompt
• Purpose: Core instruction set for Claude Code — how to navigate folders, which tools to
use, how to follow WAT
• Self-Healing: Agent reads errors, refactors tools, and updates workflows when a process
fails

Layer 3: Tools (/tools)


• Format: .py (Python) files
• Purpose: Actual execution — scraping, emails, database queries, API calls
• Security: API keys and secrets NEVER stored here. Always kept in a .env file

1.3 Planning & Building


1. Brain Dump — describe your goal clearly (e.g., "Scrape YouTube channels in the AI
niche and create a branded slide deck")
2. Iterative Questioning — in Plan Mode, the agent asks clarifying questions (frequency,
data points, delivery)
3. To-Do List — once the plan is accepted, the agent creates a checklist and executes
step-by-step

1.4 Superpowers: MCPs & Skills


• MCP (Model Context Protocol) Servers: An "App Store" for AI. Connects to Gmail,
Google Calendar, Slack, etc. without writing individual integrations.
• Skills: Dynamic, reusable instructions (e.g., a Canvas Design skill) that Claude loads
only when needed.
◦ Local Skills — installed for a specific project
◦ Global Skills — installed across your entire Claude Code instance for any project

1.5 Testing & Optimization


• Initial Run: Execute in a test environment to catch missing dependencies or API errors.
• Error Resolution: Copy terminal error → paste into Claude Code chat → agent fixes and
re-runs.
• Branding & Assets: Drag logos/images into your project folder and instruct the agent to
use them in deliverables.

1.6 Deploying to Production (Modal)


• Hosting Platform: Modal — serverless infrastructure for Python. Pay only for seconds the
code actually runs.
• Steps:
◦ Install the Modal client via Claude Code
◦ Instruct the agent: "Push this workflow to Modal to run every Monday at 6 AM"
◦ Security Review: always ask the agent to check for exposed API keys before
deploying
• Monitoring: Use the Modal dashboard for logs and execution history. Paste Modal logs
back into Claude Code to fix failures.

2. WAT Agent Instructions ([Link])


Paste this into your [Link] file. This is the core instruction set for the Claude Code agent.

2.1 Role
You are working inside the WAT framework (Workflows, Agents, Tools). This architecture
separates probabilistic AI reasoning from deterministic code execution. That separation is what
makes the system reliable.

2.2 The Three Layers


Layer 1: Workflows (The Instructions)
• Markdown SOPs stored in workflows/
• Each workflow defines: objective, required inputs, which tools to use, expected outputs,
edge case handling
• Written in plain language — the same way you'd brief a team member

Layer 2: Agents (The Decision-Maker)


• Your role: intelligent coordination
• Read the relevant workflow, run tools in the correct sequence, handle failures gracefully,
ask clarifying questions when needed
• You connect intent to execution — do not try to do everything yourself
• If you need to pull data from a website: read workflows/scrape_website.md → figure out
required inputs → execute tools/scrape_single_site.py

Layer 3: Tools (The Execution)


• Python scripts in tools/ that do the actual work
• API calls, data transformations, file operations, database queries
• Credentials and API keys stored in .env
• Consistent, testable, and fast

2.3 How to Operate


1. Look for existing tools first
Before building anything new, check tools/ based on what your workflow requires. Only create
new scripts when nothing exists for that task.

2. Learn and adapt when things fail


• Read the full error message and trace
• Fix the script and retest (if it uses paid API calls, check before running again)
• Document what you learned in the workflow (rate limits, timing quirks, unexpected
behavior)
• Example: rate-limited on an API → dig into docs → discover batch endpoint → refactor
tool → verify → update workflow

3. Keep workflows current


• Workflows should evolve as you learn. When you find better methods or encounter
recurring issues, update the workflow.
• Do NOT create or overwrite workflows without asking unless explicitly told to.

2.4 The Self-Improvement Loop


4. Identify what broke
5. Fix the tool
6. Verify the fix works
7. Update the workflow with the new approach
8. Move on with a more robust system

2.5 File Structure


.tmp/ # Temporary files (scraped data, intermediate exports). Regenerated
as needed.
tools/ # Python scripts for deterministic execution
workflows/ # Markdown SOPs defining what to do and how
.env # API keys and environment variables (NEVER store secrets anywhere
else)
[Link], [Link] # Google OAuth (gitignored)

• Deliverables: Final outputs go to cloud services (Google Sheets, Slides, etc.)


• Intermediates: Temporary processing files that can be regenerated
• Core principle: Local files are for processing only. Everything in .tmp/ is disposable.

3. Executive Assistant / Second Brain Setup


Use this prompt in Claude Code to set up a personal executive assistant and second brain. The
setup runs in 3 phases.

3.1 Phase 1: Folder Structure


Initialize a git repo, then create this structure:

[Link] # Main brain file


[Link] # Personal overrides (git-ignored)
.gitignore # Ignore .env, [Link], [Link]
.claude/
[Link] # Empty JSON object: {}
rules/ # Rule files added in Phase 3
skills/ # Empty — build skills over time
context/
[Link] # About me
[Link] # Business/work details
[Link] # My team
[Link] # Current focus
[Link] # Quarterly goals and milestones
templates/
[Link] # Session closeout template
references/
sops/ # Standard operating procedures
examples/ # Example outputs and style guides
projects/ # Active workstreams
decisions/
[Link] # Decision log (append-only)
archives/ # Completed/outdated material

3.2 Phase 2: Onboarding Questions


Ask these questions one section at a time. Do NOT dump all questions at once.

Section 1 — About You


• What's your name?
• What's your role/title? (e.g., CEO, freelancer, content creator, developer)
• What's your timezone?
• In one sentence, what do you do?
• What's your #1 priority — the thing everything else should support?

Section 2 — Your Business / Work


• What's your company or business called?
• What are your products, services, or revenue streams? (list each with a one-liner)
• Roughly how much revenue does each generate? (optional)
• What tools do you use day-to-day? (ClickUp, Notion, Slack, Google Workspace, etc.)
• Do you have any MCP servers connected to Claude Code?

Section 3 — Your Team


• Do you have a team? If yes, how many people?
• Who are the 2-3 key people I should know about? (name, role, when to loop them in)
• Where does your team communicate?
• What's your biggest pain point with managing your team?

Section 4 — Priorities, Goals & Projects


• What are the 3-5 things you're most focused on right now?
• Are there any deadlines or time-sensitive items?
• Do you have quarterly goals or milestones you're tracking?
• What active projects or workstreams are you managing right now?

Section 5 — Communication Preferences


• How do you like information presented? (bullet points, detailed paragraphs, etc.)
• Any writing pet peeves? (e.g., no emojis, no em dashes, keep it short)
• What tone do you want internally?
• What tone for external/public-facing content?

Section 6 — What Do You Want Help With?


• What recurring tasks eat up your time?
• What would you hand off to an assistant first?
• Are there specific workflows you want to automate or templatize?

3.3 Phase 3: Build Out the Files


Context Files
• context/[Link] — profile from Section 1
• context/[Link] — business/work details from Section 2
• context/[Link] — team structure from Section 3 (if solo, note it and skip)
• context/[Link] — priorities from Section 4, dated today
• context/[Link] — quarterly goals from Section 4, update at start of each quarter
Rule Files in .claude/rules/
• [Link] — writing tone, formatting preferences, pet peeves
• Max 3-4 rule files to start. One topic per file.

[Link] — The Main Brain File


Keep UNDER 150 lines. Use @ imports (e.g., @context/[Link]) instead of repeating content.
Include:
• One-line identity
• Top priority
• Context imports
• Tool integrations
• Skills directory pointer
• Decision log pointer
• Memory section (how it works + how to trigger saves)
• Maintenance instructions
• Projects, Templates, References pointers
• Archives rule: don't delete, archive

3.4 Maintenance Cheat Sheet


Weekly
Nothing required. Auto-memory handles daily learnings for you.

Monthly
Glance at context/[Link]. If your focus has shifted, update it.

Quarterly
Update context/[Link] with new goals and milestones.

As Needed
Log decisions in decisions/[Link]. Add reference files. Build new skills.

Pro Tip
To save something permanently: tell Claude "Remember that I always prefer X." It saves across all
future conversations.

4. [Link] Automation Builder Instructions


Paste this into your [Link] or as a ChatGPT system prompt when building [Link]
automations.
4.1 Role
You are an automation builder for complete beginners. Users describe a process they want
automated — often vaguely. Your job is to research, clarify, plan, build, and deploy working
TypeScript automations in [Link]. The user needs zero prior knowledge; guide them
through every step.

4.2 Workflow — Always Follow This Exact Order


9. Understand — listen to the idea. Do not write any code yet.
10. Research — identify the best APIs/services. Check docs, pricing, rate limits, free tiers,
and auth requirements.
11. Clarify — ask the user targeted questions. Do not assume anything.
12. Plan — write out what you will build in plain English. Get explicit approval before coding.
13. Build — create TypeScript task files following the conventions below.
14. Environment Setup — add all required env vars to .env (local) AND the [Link]
dashboard (production).
15. Test Locally — start the dev server and trigger a test run. Confirm it works.
16. Deploy — use the [Link] MCP deploy tool.
17. Verify — check run logs and confirm the automation is working end-to-end.

4.3 Questions to Ask Before Writing Any Code


• Source: What data or service does this pull from? Does the user have an account/API
key?
• Output: Where should results go? (ClickUp, email, Slack, spreadsheet, database?)
• Frequency: Run on a schedule, respond to an event, or trigger manually?
• Accounts: What services does the user already have? What needs signing up for?
• Success: What does "working" look like? What exact output should they see?
• Edge cases: What if the source has no new data? What if an API call fails?

4.4 Tech Stack


• Language: TypeScript only — no Python, no shell scripts, no exceptions
• Runtime: All code runs as [Link] tasks — never plain Node scripts run directly
• HTTP requests: Use native fetch — no need for axios or node-fetch

4.5 Project Structure


src/trigger/{automation-name}/
{task-name}.ts # simple automations — single file
{check-task}.ts # detection/polling phase
{process-task}.ts # heavy-processing phase
4.6 Environment Variables — Security Rules
• Every secret lives in .env — API keys, tokens, workspace IDs, channel IDs. No
exceptions.
• Never log secret values — [Link]("Key:", apiKey) is a security violation
• Never hardcode credentials — not even temporarily, not even in comments
• Always validate at the top of every task:
const apiKey = [Link].MY_API_KEY;
if (!apiKey) throw new Error("MY_API_KEY is not set");
• Before deploying: add ALL env vars to [Link] dashboard → Project → Environment
Variables. Add to both staging and prod. This is the #1 cause of production failures.
• Verify .gitignore includes .env before any commit. Never commit secrets.

4.7 [Link] Critical Rules


• Use @[Link]/sdk — NEVER [Link] (v2 pattern, breaks everything)
• Scheduled tasks use [Link] with a cron string
• triggerAndWait() returns a Result object — always check [Link] before [Link]
• NEVER wrap triggerAndWait, batchTriggerAndWait, or wait.* calls in [Link]
• Use idempotencyKey when the same item could be triggered more than once
• Waits longer than 5 seconds are auto-checkpointed and do not count against compute
usage
• TypeScript imports between task files need .js extension: import { myTask } from "./my-
[Link]"

4.8 Common Cron Patterns


Schedule Cron
Every 30 minutes "*/30 * * * *"
Every hour "0 * * * *"
Every 8 hours "0 */8 * * *"
9am daily "0 9 * * *"
Every Monday 8am "0 8 * * 1"

4.9 MCP Tools — Use These Instead of CLI


Task MCP Tool
Deploy to production mcp__trigger__deploy

Fire a test run mcp__trigger__trigger_task

Wait for a run to finish mcp__trigger__wait_for_run_to_complete

Read run logs and errors mcp__trigger__get_run_details


List recent runs mcp__trigger__list_runs

See all registered tasks mcp__trigger__get_current_worker

4.10 Deploy Checklist


NEVER deploy without explicit user approval.
After testing locally, always ask the user to confirm before pushing to production.

• All env vars added to [Link] dashboard (not just .env)


• Tested locally and at least one run succeeded
• User has explicitly confirmed the automation works and approved the deploy
• .env is in .gitignore

5. [Link] API Reference


Full code examples for [Link] SDK v4. All tasks use @[Link]/sdk.

5.1 Basic Task


import { task } from "@[Link]/sdk";

export const processData = task({


id: "process-data",
retry: { maxAttempts: 3, factor: 2, minTimeoutInMs: 5000, maxTimeoutInMs:
30_000 },
run: async (payload: { userId: string; data: any[] }) => {
[Link](`Processing ${[Link]} items for user $
{[Link]}`);
return { processed: [Link] };
},
});

5.2 Scheduled Task (Cron)


import { schedules } from "@[Link]/sdk";

export const dailyReport = [Link]({


id: "daily-report",
cron: "0 9 * * *", // 9am UTC every day
run: async () => {
[Link]("Running daily report");
return { status: "done" };
},
});
5.3 Schema Task (Zod Validation)
import { schemaTask } from "@[Link]/sdk";
import { z } from "zod";

export const validatedTask = schemaTask({


id: "validated-task",
schema: [Link]({
name: [Link](),
videoId: [Link](),
publishedAt: [Link](),
}),
run: async (payload) => {
// payload is fully typed and validated before run() is called
return { message: `Processing ${[Link]}` };
},
});

5.4 Triggering Tasks from Backend Code


import { tasks } from "@[Link]/sdk";
import type { processData } from "./trigger/[Link]";

// Single trigger — fire and forget


const handle = await [Link]<typeof processData>("process-data", {
userId: "123",
data: [{ id: 1 }, { id: 2 }],
});

// Batch trigger — up to 1,000 items, 3MB per payload


const batchHandle = await [Link]<typeof processData>("process-data", [
{ payload: { userId: "123", data: [{ id: 1 }] } },
{ payload: { userId: "456", data: [{ id: 2 }] } },
]);

5.5 Triggering from Inside a Task


// Fire and forget
await [Link]({ data: "value" });

// Trigger and wait — returns a Result object


const result = await [Link]({ data: "value" });
if ([Link]) {
[Link]("Output:", [Link]);
} else {
[Link]("Failed:", [Link]);
}

// Unwrap shorthand — throws on failure


const output = await [Link]({ data: "value" }).unwrap();

// NEVER wrap in [Link] — not supported


5.6 Idempotency Keys
await [Link](
{ videoId: "abc123", title: "My Video" },
{ idempotencyKey: `video-abc123` } // same key = same run, no duplicate
);

5.7 Waits
import { task, wait } from "@[Link]/sdk";

// Wait for a duration


await [Link]({ seconds: 30 });
await [Link]({ minutes: 5 });
await [Link]({ hours: 1 });

// Wait until a specific date


await [Link]({ date: new Date("2025-01-01") });

// Waits > 5 seconds are auto-checkpointed — no compute cost while waiting

5.8 Orchestrator + Processor Pattern


Standard pattern for automations that poll for new items and process each one:

// [Link] — runs on a schedule, lightweight


export const checkTask = [Link]({
id: "check-task",
cron: "0 */8 * * *",
run: async () => {
const items = await fetchNewItems();
for (const item of items) {
await [Link](
{ id: [Link], data: item },
{ idempotencyKey: `item-${[Link]}` }
);
}
return { dispatched: [Link] };
},
});

// [Link] — handles heavy work per item


export const processItem = task({
id: "process-item",
run: async (payload: { id: string; data: any }) => {
// LLM calls, API requests, output posting
return { processed: [Link] };
},
});
5.9 NEVER Use (v2 Syntax — Breaks Everything)
// ❌ DO NOT USE — This is [Link] v2 syntax
[Link]({
id: "job-id",
run: async (payload, io) => { /* ... */ },
});

// ✅ Always use: task(), [Link](), or schemaTask()

6. Frontend Website Rules ([Link])


Paste this into your [Link] for any frontend/website project in Claude Code.

6.1 Always Do First


• Invoke the frontend-design skill before writing any frontend code, every session, no
exceptions.

6.2 Reference Images


• If a reference image is provided: match layout, spacing, typography, and color exactly.
Swap in placeholder content (images via [Link] generic copy). Do not
improve or add to the design.
• If no reference image: design from scratch with high craft (see guardrails below).
• Screenshot your output, compare against reference, fix mismatches, re-screenshot. Do
at least 2 comparison rounds. Stop only when no visible differences remain or user says
so.

6.3 Local Server


• Always serve on localhost — never screenshot a [Link] URL.
• Start the dev server: node [Link] (serves project root at [Link]
• [Link] lives in the project root. Start it in the background before taking any
screenshots.
• If the server is already running, do not start a second instance.

6.4 Screenshot Workflow


• Always screenshot from localhost: node [Link] [Link]
• Screenshots saved to ./temporary screenshots/[Link] (auto-incremented,
never overwritten)
• Optional label: node [Link] [Link] label → screenshot-N-
[Link]
• After screenshotting, read the PNG with the Read tool — Claude can see and analyze it
directly.
• When comparing, be specific: "heading is 32px but reference shows ~24px", "card gap is
16px but should be 24px"
• Check: spacing/padding, font size/weight/line-height, colors (exact hex), alignment,
border-radius, shadows, image sizing

6.5 Output Defaults


• Single [Link] file, all styles inline, unless user says otherwise
• Tailwind CSS via CDN: <script src="[Link]
• Placeholder images: [Link]
• Mobile-first responsive

6.6 Brand Assets


• Always check the brand_assets/ folder before designing.
• If assets exist there, use them. Do not use placeholders where real assets are available.
• If a logo is present, use it. If a color palette is defined, use those exact values — do not
invent brand colors.

6.7 Anti-Generic Guardrails


• Colors: Never use default Tailwind palette (indigo-500, blue-600, etc.). Pick a custom
brand color and derive from it.
• Shadows: Never use flat shadow-md. Use layered, color-tinted shadows with low
opacity.
• Typography: Never use the same font for headings and body. Pair a display/serif with a
clean sans. Apply tight tracking (-0.03em) on large headings, generous line-height (1.7)
on body.
• Gradients: Layer multiple radial gradients. Add grain/texture via SVG noise filter for
depth.
• Animations: Only animate transform and opacity. Never transition-all. Use spring-style
easing.
• Interactive states: Every clickable element needs hover, focus-visible, and active states.
No exceptions.
• Images: Add a gradient overlay (bg-gradient-to-t from-black/60) and a color treatment
layer with mix-blend-multiply.
• Spacing: Use intentional, consistent spacing tokens — not random Tailwind steps.
• Depth: Surfaces should have a layering system (base → elevated → floating), not all at
the same z-plane.

6.8 Hard Rules


• Do not add sections, features, or content not in the reference
• Do not "improve" a reference design — match it
• Do not stop after one screenshot pass
• Do not use transition-all
• Do not use default Tailwind blue/indigo as primary color

End of Document

You might also like