Fetch the raw README content from GitHub for each of the following Anthropic repos. For each, make a curl request to the raw GitHub API to get the README. Return the content (trimmed to ~300 lines max per repo) for each.

Repos to fetch (use https://raw.githubusercontent.com/anthropics/REPO/main/README.md or /master/README.md):
1. anthropics/claude-agent-sdk-python
2. anthropics/claude-agent-sdk-typescript
3. anthropics/ClaudeForFoundationModels
4. anthropics/cwc-long-running-agents
5. anthropics/knowledge-work-plugins
6. anthropics/claude-plugins-official
7. anthropics/claude-desktop-buddy
8. anthropics/defending-code-reference-harness

For each, try main branch first, then master if 404. Return format:
REPO: <name>
README:
<content up to 300 lines>
---


I'll fetch the README content from the raw GitHub API for each of these Anthropic repos. Let me make parallel requests to retrieve them.


Bash

curl -s https://raw.githubusercontent.com/anthropics/claude-agent-sdk-python/main/README.md 2>&1 | head -300

Fetch README from claude-agent-sdk-python main branch


# Claude Agent SDK for Python

Python SDK for Claude Agent. See the [Claude Agent SDK documentation](https://platform.claude.com/docs/en/agent-sdk/python) for more information.

## Installation

```bash
pip install claude-agent-sdk
```

**Prerequisites:**

- Python 3.10+

**Note:** The Claude Code CLI is automatically bundled with the package - no separate installation required! The SDK will use the bundled CLI by default. If you prefer to use a system-wide installation or a specific version, you can:

- Install Claude Code separately: `curl -fsSL https://claude.ai/install.sh | bash`
- Specify a custom path: `ClaudeAgentOptions(cli_path="/path/to/claude")`

## Quick Start

```python
import anyio
from claude_agent_sdk import query

async def main():
    async for message in query(prompt="What is 2 + 2?"):
        print(message)

anyio.run(main)
```

## Basic Usage: query()

`query()` is an async function for querying Claude Code. It returns an `AsyncIterator` of response messages. See [src/claude_agent_sdk/query.py](src/claude_agent_sdk/query.py).

```python
from claude_agent_sdk import query, ClaudeAgentOptions, AssistantMessage, TextBlock

# Simple query
async for message in query(prompt="Hello Claude"):
    if isinstance(message, AssistantMessage):
        for block in message.content:
            if isinstance(block, TextBlock):
                print(block.text)

# With options
options = ClaudeAgentOptions(
    system_prompt="You are a helpful assistant",
    max_turns=1
)

async for message in query(prompt="Tell me a joke", options=options):
    print(message)
```

### Using Tools

By default, Claude has access to the full [Claude Code toolset](https://code.claude.com/docs/en/settings#tools-available-to-claude) (Read, Write, Edit, Bash, and others). `allowed_tools` is a permission allowlist: listed tools are auto-approved, and unlisted tools fall through to `permission_mode` and `can_use_tool` for a decision. It does not remove tools from Claude's toolset. To block specific tools, use `disallowed_tools`. See the [permissions guide](https://platform.claude.com/docs/en/agent-sdk/permissions) for the full evaluation order.

```python
options = ClaudeAgentOptions(
    allowed_tools=["Read", "Write", "Bash"],  # auto-approve these tools
    permission_mode='acceptEdits'  # auto-accept file edits
)

async for message in query(
    prompt="Create a hello.py file",
    options=options
):
    # Process tool use and results
    pass
```

### Working Directory

```python
from pathlib import Path

options = ClaudeAgentOptions(
    cwd="/path/to/project"  # or Path("/path/to/project")
)
```

## ClaudeSDKClient

`ClaudeSDKClient` supports bidirectional, interactive conversations with Claude
Code. See [src/claude_agent_sdk/client.py](src/claude_agent_sdk/client.py).

Unlike `query()`, `ClaudeSDKClient` additionally enables **custom tools** and **hooks**, both of which can be defined as Python functions.

### Custom Tools (as In-Process SDK MCP Servers)

A **custom tool** is a Python function that you can offer to Claude, for Claude to invoke as needed.

Custom tools are implemented in-process MCP servers that run directly within your Python application, eliminating the need for separate processes that regular MCP servers require.

For an end-to-end example, see [MCP Calculator](examples/mcp_calculator.py).

#### Creating a Simple Tool

```python
from claude_agent_sdk import tool, create_sdk_mcp_server, ClaudeAgentOptions, ClaudeSDKClient

# Define a tool using the @tool decorator
@tool("greet", "Greet a user", {"name": str})
async def greet_user(args):
    return {
        "content": [
            {"type": "text", "text": f"Hello, {args['name']}!"}
        ]
    }

# Create an SDK MCP server
server = create_sdk_mcp_server(
    name="my-tools",
    version="1.0.0",
    tools=[greet_user]
)

# Use it with Claude. allowed_tools pre-approves the tool so it runs
# without a permission prompt; it does not control tool availability.
options = ClaudeAgentOptions(
    mcp_servers={"tools": server},
    allowed_tools=["mcp__tools__greet"]
)

async with ClaudeSDKClient(options=options) as client:
    await client.query("Greet Alice")

    # Extract and print response
    async for msg in client.receive_response():
        print(msg)
```

#### Benefits Over External MCP Servers

- **No subprocess management** - Runs in the same process as your application
- **Better performance** - No IPC overhead for tool calls
- **Simpler deployment** - Single Python process instead of multiple
- **Easier debugging** - All code runs in the same process
- **Type safety** - Direct Python function calls with type hints

#### Migration from External Servers

```python
# BEFORE: External MCP server (separate process)
options = ClaudeAgentOptions(
    mcp_servers={
        "calculator": {
            "type": "stdio",
            "command": "python",
            "args": ["-m", "calculator_server"]
        }
    }
)

# AFTER: SDK MCP server (in-process)
from my_tools import add, subtract  # Your tool functions

calculator = create_sdk_mcp_server(
    name="calculator",
    tools=[add, subtract]
)

options = ClaudeAgentOptions(
    mcp_servers={"calculator": calculator}
)
```

#### Mixed Server Support

You can use both SDK and external MCP servers together:

```python
options = ClaudeAgentOptions(
    mcp_servers={
        "internal": sdk_server,      # In-process SDK server
        "external": {                # External subprocess server
            "type": "stdio",
            "command": "external-server"
        }
    }
)
```

### Hooks

A **hook** is a Python function that the Claude Code _application_ (_not_ Claude) invokes at specific points of the Claude agent loop. Hooks can provide deterministic processing and automated feedback for Claude. Read more in [Intercept and control agent behavior with hooks](https://platform.claude.com/docs/en/agent-sdk/hooks).

For more examples, see examples/hooks.py.

#### Example

```python
from claude_agent_sdk import ClaudeAgentOptions, ClaudeSDKClient, HookMatcher

async def check_bash_command(input_data, tool_use_id, context):
    tool_name = input_data["tool_name"]
    tool_input = input_data["tool_input"]
    if tool_name != "Bash":
        return {}
    command = tool_input.get("command", "")
    block_patterns = ["foo.sh"]
    for pattern in block_patterns:
        if pattern in command:
            return {
                "hookSpecificOutput": {
                    "hookEventName": "PreToolUse",
                    "permissionDecision": "deny",
                    "permissionDecisionReason": f"Command contains invalid pattern: {pattern}",
                }
            }
    return {}

options = ClaudeAgentOptions(
    allowed_tools=["Bash"],
    hooks={
        "PreToolUse": [
            HookMatcher(matcher="Bash", hooks=[check_bash_command]),
        ],
    }
)

async with ClaudeSDKClient(options=options) as client:
    # Test 1: Command with forbidden pattern (will be blocked)
    await client.query("Run the bash command: ./foo.sh --help")
    async for msg in client.receive_response():
        print(msg)

    print("\n" + "=" * 50 + "\n")

    # Test 2: Safe command that should work
    await client.query("Run the bash command: echo 'Hello from hooks example!'")
    async for msg in client.receive_response():
        print(msg)
```

## Types

See [src/claude_agent_sdk/types.py](src/claude_agent_sdk/types.py) for complete type definitions:

- `ClaudeAgentOptions` - Configuration options
- `AssistantMessage`, `UserMessage`, `SystemMessage`, `ResultMessage` - Message types
- `TextBlock`, `ToolUseBlock`, `ToolResultBlock` - Content blocks

## Error Handling

```python
from claude_agent_sdk import (
    ClaudeSDKError,      # Base error
    CLINotFoundError,    # Claude Code not installed
    CLIConnectionError,  # Connection issues
    ProcessError,        # Process failed
    CLIJSONDecodeError,  # JSON parsing issues
)

try:
    async for message in query(prompt="Hello"):
        pass
except CLINotFoundError:
    print("Please install Claude Code")
except ProcessError as e:
    print(f"Process failed with exit code: {e.exit_code}")
except CLIJSONDecodeError as e:
    print(f"Failed to parse response: {e}")
```

See [src/claude_agent_sdk/\_errors.py](src/claude_agent_sdk/_errors.py) for all error types.

## Available Tools

See the [Claude Code documentation](https://code.claude.com/docs/en/settings#tools-available-to-claude) for a complete list of available tools.

## Examples

See [examples/quick_start.py](examples/quick_start.py) for a complete working example.

See [examples/streaming_mode.py](examples/streaming_mode.py) for comprehensive examples involving `ClaudeSDKClient`. You can even run interactive examples in IPython from [examples/streaming_mode_ipython.py](examples/streaming_mode_ipython.py).

## Migrating from Claude Code SDK

If you're upgrading from the Claude Code SDK (versions < 0.1.0), please see the [CHANGELOG.md](CHANGELOG.md#010) for details on breaking changes and new features, including:

- `ClaudeCodeOptions` → `ClaudeAgentOptions` rename
- Merged system prompt configuration
- Settings isolation and explicit control
- New programmatic subagents and session forking features

## Development

If you're contributing to this project, run the initial setup script to install git hooks:

```bash
./scripts/initial-setup.sh
```

This installs a pre-push hook that runs lint checks before pushing, matching the CI workflow. To skip the hook temporarily, use `git push --no-verify`.

### Building Wheels Locally


curl -s https://raw.githubusercontent.com/anthropics/claude-agent-sdk-typescript/main/README.md 2>&1 | head -300

Fetch README from claude-agent-sdk-typescript main branch


curl -s https://raw.githubusercontent.com/anthropics/ClaudeForFoundationModels/main/README.md 2>&1 | head -300

Fetch README from ClaudeForFoundationModels main branch


# Claude Agent SDK

![](https://img.shields.io/badge/Node.js-18%2B-brightgreen?style=flat-square) [![npm]](https://www.npmjs.com/package/@anthropic-ai/claude-agent-sdk)

[npm]: https://img.shields.io/npm/v/@anthropic-ai/claude-agent-sdk.svg?style=flat-square

The Claude Agent SDK enables you to programmatically build AI agents with Claude Code's capabilities. Create autonomous agents that can understand codebases, edit files, run commands, and execute complex workflows.

**Learn more in the [official documentation](https://docs.claude.com/en/api/agent-sdk/overview)**.

## Get started

Install the Claude Agent SDK:

```sh
npm install @anthropic-ai/claude-agent-sdk
```

## Migrating from the Claude Code SDK

The Claude Code SDK is now the Claude Agent SDK. Please check out the [migration guide](https://docs.claude.com/en/docs/claude-code/sdk/migration-guide) for details on breaking changes.

## Reporting Bugs

We welcome your feedback. File a [GitHub issue](https://github.com/anthropics/claude-agent-sdk-typescript/issues) to report bugs or request features.

## Connect on Discord

Join the [Claude Developers Discord](https://anthropic.com/discord) to connect with other developers building with the Claude Agent SDK. Get help, share feedback, and discuss your projects with the community.

## Data collection, usage, and retention

When you use the Claude Agent SDK, we collect feedback, which includes usage data (such as code acceptance or rejections), associated conversation data, and user feedback submitted via the /bug command.

### How we use your data

See our [data usage policies](https://docs.anthropic.com/en/docs/claude-code/data-usage).

### Privacy safeguards

We have implemented several safeguards to protect your data, including limited retention periods for sensitive information, restricted access to user session data, and clear policies against using feedback for model training.

For full details, please review our [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms) and [Privacy Policy](https://www.anthropic.com/legal/privacy).

## License and terms

Use of this SDK is governed by Anthropic's [Commercial Terms of Service](https://www.anthropic.com/legal/commercial-terms), including when you use it to power products and services that you make available to your own customers and end users, except to the extent a specific component or dependency is covered by a different license as indicated in that component's LICENSE file.


# Claude for Foundation Models

Use Claude as a server-side language model through Apple's [Foundation Models](https://developer.apple.com/documentation/foundationmodels) framework. The package conforms Claude to the framework's `LanguageModel` protocol, so you drive it with the same `LanguageModelSession` API you use for Apple's on-device model — `respond(to:)`, streaming, guided generation, and tool calling all work the same way.

> **Beta.** This package targets the Foundation Models server-side language model API introduced in the OS 27 betas. APIs may change before general availability.

## Contents

- [Requirements](#requirements)
- [Installation](#installation)
- [Quick start](#quick-start)
- [Example](#example)
- [Choosing a model](#choosing-a-model)
- [Authentication](#authentication)
- [Streaming](#streaming)
- [Structured output](#structured-output)
- [Server-side tools](#server-side-tools)
- [Error handling](#error-handling)
- [What this package provides](#what-this-package-provides)
- [Support](#support)
- [License](#license)

## Requirements

- iOS 27, macOS 27, visionOS 27, or watchOS 27 (beta) — the OS releases whose Foundation Models framework supports server-side language models.
- Xcode 27 (beta).
- An Anthropic API key for development. See [Authentication](#authentication) for production options.

## Installation

Add the package to your `Package.swift`:

```swift
dependencies: [
  .package(url: "https://github.com/anthropics/ClaudeForFoundationModels.git", from: "0.1.0")
]
```

Or in Xcode: **File ▸ Add Package Dependencies…** and enter the repository URL.

Then add `ClaudeForFoundationModels` to your target's dependencies and import it alongside `FoundationModels`:

```swift
import FoundationModels
import ClaudeForFoundationModels
```

## Quick start

```swift
import FoundationModels
import ClaudeForFoundationModels

let model = ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: .apiKey(ProcessInfo.processInfo.environment["ANTHROPIC_API_KEY"] ?? "")
)

let session = LanguageModelSession(model: model)
let response = try await session.respond(to: "Plan a 4-day trip to Buenos Aires.")
print(response.content)
```

`ClaudeLanguageModel` is the entry point. Pass it to `LanguageModelSession` and use the session exactly as you would with any Foundation Models provider.

## Example

[`Examples/ClaudeExample`](Examples/ClaudeExample) is a runnable command-line target that streams one chat turn through `LanguageModelSession` to the terminal, with token usage at the end (running it requires a macOS 27 host):

```sh
ANTHROPIC_API_KEY=<key> swift run ClaudeExample "What should I see in Kyoto?"
```

Pass `--search` to enable server-side web search for the turn:

```sh
ANTHROPIC_API_KEY=<key> swift run ClaudeExample --search "Top spaceflight news this week?"
```

## Choosing a model

Model identifiers are values of `ClaudeModel`. Use a compiled-in constant, or construct one with explicit capabilities for an ID that isn't compiled in yet (see [Capabilities](#capabilities)):

```swift
ClaudeLanguageModel(name: .opus4_8, auth: auth)
```

Constants mirror API model IDs (`.opus4_8` is `claude-opus-4-8`) and carry each model's capabilities. New models ship as new constants in package releases.

Dateless model IDs like `claude-opus-4-8` (the 4.6 generation onward) are pinned snapshots, not evergreen pointers — the model behind an ID doesn't change underneath you.

### Capabilities

Each model declares what it accepts — sampling parameters, effort levels, adaptive thinking, structured output, and image input. The bridge uses this to decide which request fields to send, since sending a field a model rejects is a hard error. The constants carry the right capabilities. For an ID that isn't compiled in, declare what the model accepts:

```swift
let model = ClaudeModel(
  id: "claude-experimental-x",
  capabilities: .init(effortLevels: [.low, .high], structuredOutput: true)
)
ClaudeLanguageModel(name: model, auth: auth)
```

### Effort

Pin a Claude effort level for every request with `fixedEffort:`. It takes precedence over the framework's per-request reasoning hints. The API defaults to `high` when no effort is sent:

```swift
ClaudeLanguageModel(name: .opus4_8, auth: auth, fixedEffort: .xhigh)
```

The framework's reasoning levels map to effort per request: `.light` → `low`, `.moderate` → `medium`, `.deep` → `high`, and `.custom` accepts a Claude effort name directly (`"xhigh"`, `"max"`). Levels a model doesn't accept are dropped — a reasoning level is a hint, not a contract.

The level must be one the model accepts — each model declares which of the five levels (`low`, `medium`, `high`, `xhigh`, `max`) it takes.

## Authentication

Set the credential with the `auth:` parameter.

```swift
// Development. A bundled key is extractable from a shipping app — use one of
// the production options below before release.
ClaudeLanguageModel(name: .sonnet4_6, auth: .apiKey("..."))

// Production via your own backend. The relay at `baseURL` adds the credential
// server-side; the app ships no key. `headers` are sent on every request so the
// proxy can authorize the caller — pass `[:]` if it needs none.
ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: .proxied(headers: ["X-App-Token": "..."]),
  baseURL: URL(string: "https://api.yourapp.com/claude")!
)
```

**Coming soon:** a production mode that doesn't require running your own backend — each app install authenticates with App Attest and usage is billed to your Anthropic workspace. Until that ships, use `.apiKey` for development and `.proxied` for production.

## Streaming

`streamResponse(to:)` returns the response incrementally. Each element is a cumulative snapshot:

```swift
let stream = session.streamResponse(to: "Summarize today's top science stories.")
for try await partial in stream {
  print(partial.content)
}
```

## Structured output

Annotate a type with `@Generable` and request it with `generating:`. The model returns a value of that type:

```swift
@Generable
struct Trip {
  @Guide(description: "Destination city") var destination: String
  @Guide(description: "Length in days") var days: Int
}

let response = try await session.respond(to: "Plan a trip to Tokyo.", generating: Trip.self)
print(response.content.destination)
```

Structured output requires a model whose capabilities include it (all compiled-in constants do).

## Server-side tools

Server-side tools run on Anthropic's infrastructure within a single round-trip — web search, web fetch, and code execution. Configure them per model with `serverTools:`:

```swift
let model = ClaudeLanguageModel(
  name: .sonnet4_6,
  auth: auth,
  serverTools: [
    .webSearch(maxUses: 5),
    .codeExecution,
  ]
)
```

`.webSearch` and `.webFetch` accept a `domains:` filter — `.unrestricted` (the default), `.allowing([...])`, or `.blocking([...])` — and an optional `maxUses`. These are distinct from the framework's `tools:` array, which holds client-side tools the framework invokes on the device.

## Error handling

Provider errors that don't map onto a Foundation Models `LanguageModelError` surface as `ClaudeError`. Pattern-match to drive product flows:

```swift
do {
  let response = try await session.respond(to: prompt)
  print(response.content)
} catch ClaudeError.missingCredential {
  // Prompt for an API key.
} catch {
  // Foundation Models errors (guardrails, context length, decoding) and transport errors.
}
```

## What this package provides

The public surface is Apple's Foundation Models provider conformance plus the configuration types that reach it — `ClaudeLanguageModel`, `ClaudeModel`, `AuthMode`, and `ClaudeServerTool`. It is not a general-purpose Anthropic Messages API client.

## Support

**Maintenance status:** maintained on a best-effort basis, provided as is, and not accepting external contributions.

Bug reports and feedback are welcome — please [open an issue](../../issues). We triage issues and address them on a best-effort basis.

## License

Apache 2.0 — see [LICENSE](LICENSE).

Copyright 2026 Anthropic PBC


curl -s https://raw.githubusercontent.com/anthropics/cwc-long-running-agents/main/README.md 2>&1 | head -300

Fetch README from cwc-long-running-agents main branch


# Harness Primitives for Long-Running Claude Agents

Claude Code's built-in [`/goal`](https://code.claude.com/docs/en/goal) command gives you a generator/evaluator loop out of the box: set a completion condition and a separate fast model checks it after every turn until it's met. This repo ships the same underlying primitives as short, readable [hooks](https://code.claude.com/docs/en/hooks) and a [subagent](https://code.claude.com/docs/en/sub-agents), so you can see how each mechanism works and assemble a harness tuned to your project. The patterns come from [Effective Harnesses for Long-Running Agents](https://www.anthropic.com/engineering/effective-harnesses-for-long-running-agents) (Nov 2025) and [Harness Design for Long-Running Application Development](https://www.anthropic.com/engineering/harness-design-long-running-apps) (Mar 2026). We recommend trying both the in-product features and a custom harness to see which fits your workflow.

| | In-product | Custom harness (this repo) |
|---|---|---|
| **What runs the loop** | [`/goal`](https://code.claude.com/docs/en/goal) | the [primitives below](#the-quality-loop) + a [loop you write](#running-the-loop) |
| **Who judges "done"** | a separate fast model checking your condition | your [`agents/evaluator.md`](./claude-code-config/.claude/agents/evaluator.md) with your prompt |
| **Where it works** | Claude Code interactive, [`-p`](https://code.claude.com/docs/en/headless), Remote Control | Claude Code, headless, or [Agent SDK](https://docs.claude.com/en/docs/claude-code/sdk) |

Three primitives form the quality loop:

- **Default-FAIL contract.** Every criterion starts `false`; the agent can't mark it passing without opening evidence first.
- **Fresh-context evaluator.** A separate agent with no Write/Edit tools grades the work from a context window that never saw the build.
- **Agent-maintained handoff.** The agent writes its own progress notes and commits to git so the next session picks up cleanly.

Two more operator-control hooks are included for when you want to watch or intervene. The same patterns translate directly to `PreToolUse`/`Stop` callbacks in the [Agent SDK](https://docs.claude.com/en/docs/claude-code/sdk).

> Built as the take-home for the Long-Running Agents station at Code with Claude 2026. **These are example ingredients, not a turnkey harness.** Event demo; not maintained and not accepting contributions.

## How to use this repo

**Read and cherry-pick.** Each primitive is one standalone file with no dependency on the others. The [quality-loop table](#the-quality-loop) below maps every one to its example here and its Agent SDK equivalent. Open the file, see how the mechanism works, copy what fits.

**Or copy all of them as a starting point.** In your project, run `claude` and paste:

> Clone github.com/anthropics/cwc-long-running-agents into /tmp, copy its `claude-code-config/.claude/` directory into this project's root, make the hook scripts executable, then walk me through what each hook and the evaluator subagent does and what I'll need to adapt for this project.

or do it yourself:

```bash
cp -r claude-code-config/.claude /path/to/your/project/
chmod +x /path/to/your/project/.claude/hooks/*.sh
```

Either way, this gives you all the examples wired into `.claude/` at once. Before relying on them: point `RESULTS_FILE` at your project's actual results file, adjust the evidence-file pattern in `track-read.sh`, and run `claude` from the directory that contains `.claude/` (hooks are not loaded when launching from a subdirectory).

**If you're on the Agent SDK,** this repo is a pattern reference. The shell hooks here translate one-to-one to `PreToolUse`/`Stop` callbacks. To scaffold an SDK agent from inside Claude Code, install the [`agent-sdk-dev` plugin](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/agent-sdk-dev) and ask Claude to build an agent that implements whichever of these primitives you want. For a hand-written starting point, see the [autonomous-coding quickstart](https://github.com/anthropics/claude-quickstarts/tree/main/autonomous-coding) or the [agent-sdk-workshop](https://github.com/anthropics/agent-sdk-workshop) curriculum.

## The quality loop

| Primitive | Claude Code example | Agent SDK equivalent | Enforcement |
|---|---|---|---|
| **Default-FAIL contract** | [`hooks/track-read.sh`](./claude-code-config/.claude/hooks/track-read.sh) + [`hooks/verify-gate.sh`](./claude-code-config/.claude/hooks/verify-gate.sh) | `PreToolUse` callback | hook |
| **Fresh-context evaluator** | [`agents/evaluator.md`](./claude-code-config/.claude/agents/evaluator.md) subagent (no Write/Edit) | [`evaluator_optimizer.ipynb`](https://github.com/anthropics/claude-cookbooks/blob/main/patterns/agents/evaluator_optimizer.ipynb) | you invoke it |
| **Agent-maintained handoff** | [`CLAUDE.md`](./claude-code-config/.claude/CLAUDE.md) + [`hooks/commit-on-stop.sh`](./claude-code-config/.claude/hooks/commit-on-stop.sh) | system prompt + `Stop` callback | convention + hook backstop |

### Default-FAIL contract

Agents will mark a feature "passing" after a unit test or a curl when the UI is visibly broken. Asking nicely in the prompt doesn't reliably stop this. The harness makes "done" structural. Every feature is a row in a `test-results.json` file you create in your project:

```json
{ "feature-1": { "passes": false }, "feature-2": { "passes": false } }
```

The only evidence that counts is a file matching the patterns in `track-read.sh` (screenshots, console logs, result files), and a `PreToolUse` hook denies any write to the results file unless the agent has first opened one with the Read tool. The agent can't claim success it hasn't observed. (The shipped hook is intentionally simple; see the comments in `verify-gate.sh` for the gaps a production version would close.)

### Fresh-context evaluator

The builder shouldn't grade its own work. After each feature, you (or your wrapper script) invoke a separate subagent (`agents/evaluator.md`) with no Write/Edit tools that reviews the diff and the screenshots from a context window that never saw the build, then returns `PASS` or `NEEDS_WORK` with specific findings. On `NEEDS_WORK` the findings become the next builder session's starting prompt, closing the build/evaluate/rebuild loop. Invoke it from your wrapper with `claude --agent evaluator -p "<review prompt>"`; what your loop does with the verdict is up to you.

### Agent-maintained handoff

A fresh session has no memory of what the previous one did, and when a long session fills its context window Claude Code summarizes the history, which loses detail. So the agent maintains the handoff itself: it scopes each session to one feature, writes to a structured `PROGRESS.md` as it works and re-reads it first thing on every restart, and `git add`s and commits at meaningful checkpoints so `git log` is a second record. `commit-on-stop.sh` is the backstop that catches whatever's still uncommitted at session end. This is the layer most sensitive to model capability; newer models drift less and self-scope better, so re-evaluate how much of `CLAUDE.md` you still need after each model release (see [Re-simplify on model upgrades](#going-further)).

A fourth core piece, a **rubric for subjective work**, isn't shipped here because it's project-specific; see [Going further](#going-further) for how to add one to the evaluator.

## Running the loop

Two ways to keep the build → evaluate → rebuild cycle going. `/goal` is built into Claude Code and works with or without this repo's primitives; the second path wires the contract file and your own `evaluator.md` directly into the loop.

### `/goal`: built-in completion checker

```
/goal every feature in PROGRESS.md is implemented, committed, and its tests pass
```

After every turn a separate fast model checks the condition and keeps the session going until it's met. One line, no contract file or hooks. Works the same in interactive Claude Code, [`claude -p`](https://code.claude.com/docs/en/headless), and Remote Control. See the docs for [writing an effective condition](https://code.claude.com/docs/en/goal#write-an-effective-condition) and how `/goal` [compares to `/loop` and Stop hooks](https://code.claude.com/docs/en/goal#compare-to-other-autonomous-workflows).

### Your `evaluator.md` as the gate

When you want the default-FAIL contract (`test-results.json` + `verify-gate`) enforcing evidence and your own evaluator prompt deciding `PASS`/`NEEDS_WORK`, the loop lives in your code. How depends on where you're running:

| Surface | How |
|---|---|
| **Claude Code** | custom [Stop hook](https://code.claude.com/docs/en/hooks#stop) runs the evaluator as a fresh `claude` process after each turn and blocks on anything but `PASS` |
| **Headless** ([`claude -p`](https://code.claude.com/docs/en/headless)) | wrapper script calls `claude --agent evaluator -p` between builds (example below) |
| [**Agent SDK**](https://docs.claude.com/en/docs/claude-code/sdk) | separate generator and evaluator `query()` calls; see [`evaluator_optimizer`](https://github.com/anthropics/claude-cookbooks/blob/main/patterns/agents/evaluator_optimizer.ipynb) |

```bash
while grep -q '"passes": false' test-results.json; do
  claude -p "Read PROGRESS.md and build the next unfinished feature per CLAUDE.md."
  VERDICT=$(claude --agent evaluator -p "Review the most recent commit against its spec.")
  [ "$(echo "$VERDICT" | head -1)" = "PASS" ] || echo "$VERDICT" > NEXT_FINDINGS.md
done
```

Each pass is a fresh context. Exit when the contract file has nothing left failing, a cycle makes no changes, or a budget is hit; `touch AGENT_STOP` to stop early. The builder writes `test-results.json` (verify-gate enforces evidence-read first) and the evaluator returns a separate verdict; have your wrapper write the contract on `PASS` instead if you want "all true" to mean "independently confirmed."

## Operator controls

Two more hooks for when you want to watch the loop run or intervene mid-stream:

| Hook | What it does |
|---|---|
| [`hooks/kill-switch.sh`](./claude-code-config/.claude/hooks/kill-switch.sh) | Halts every tool call while an `AGENT_STOP` file exists at the project root. |
| [`hooks/steer.sh`](./claude-code-config/.claude/hooks/steer.sh) | Surfaces the contents of `STEER.md` (project root) to the agent once and clears it, so you can redirect mid-run without restarting. |

## Watching it work

Everything the agent does lands on disk, so you can observe a long run from a terminal without any dashboard code:

```bash
watch -n 2 'tail -20 PROGRESS.md'                          # its own notes
watch -n 5 'git log --oneline -8'                          # work saved
watch -n 5 'find screenshots -name "*.png" | tail -5'      # what it sees
watch -n 2 'wc -l < .claude/.evidence-reads 2>/dev/null'   # evidence reads (resets to 0 after each gated write)
```

Run them in a `tmux` grid and you have a live view of every primitive.

## Going further

The next layer of patterns, each covered in depth in [Harness Design for Long-Running Application Development](https://www.anthropic.com/engineering/harness-design-long-running-apps):

| Pattern | What it adds | Reference |
|---|---|---|
| **Unattended loop** | Cap session length and have an outer script start the next one (pick next feature, build, evaluate, reset) | [Why naive implementations fall short](https://www.anthropic.com/engineering/harness-design-long-running-apps#why-naive-implementations-fall-short); [`ralph-loop`](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/ralph-loop) plugin |
| **Planner agent** | A first session that expands a one-line ask into a `BUILD_PLAN.md` the loop then runs against | [The architecture](https://www.anthropic.com/engineering/harness-design-long-running-apps#the-architecture) |
| **Sprint contracts** | Builder and evaluator agree per-feature on what "done" means and write it to a file the hook enforces | [The architecture](https://www.anthropic.com/engineering/harness-design-long-running-apps#the-architecture) and [Removing the sprint construct](https://www.anthropic.com/engineering/harness-design-long-running-apps#removing-the-sprint-construct) |
| **Grading rubrics** | Give the evaluator scoring principles (functionality, design, craft, originality) with few-shot examples instead of binary pass/fail | [Frontend design: making subjective quality gradable](https://www.anthropic.com/engineering/harness-design-long-running-apps#frontend-design-making-subjective-quality-gradable); [`frontend-design`](https://github.com/anthropics/claude-plugins-official/tree/main/plugins/frontend-design) plugin |
| **Browser-verified evaluator** | Let the evaluator open the running app itself instead of trusting the builder's screenshots | [Frontend design](https://www.anthropic.com/engineering/harness-design-long-running-apps#frontend-design-making-subjective-quality-gradable) (Playwright MCP usage); add [`@playwright/mcp`](https://github.com/microsoft/playwright-mcp) or Claude in Chrome to `tools:` in `agents/evaluator.md` |
| **Re-simplify on model upgrades** | After each model release, comment out harness pieces one at a time and see what's still load-bearing | [What comes next](https://www.anthropic.com/engineering/harness-design-long-running-apps#what-comes-next); [Harnessing Claude's Intelligence](https://claude.com/blog/harnessing-claudes-intelligence) |
| **Hosted runtime** | Anthropic hosts the loop, sandbox, and scheduling so you don't run any of this yourself | [Claude Managed Agents](https://docs.claude.com/en/docs/managed-agents) |

---


curl -s https://raw.githubusercontent.com/anthropics/knowledge-work-plugins/main/README.md 2>&1 | head -300

Fetch README from knowledge-work-plugins main branch


# Knowledge Work Plugins

Plugins that turn Claude into a specialist for your role, team, and company. Built for [Claude Cowork](https://claude.com/product/cowork), also compatible with [Claude Code](https://claude.com/product/claude-code).

## Why Plugins

Cowork lets you set the goal and Claude delivers finished, professional work. Plugins let you go further: tell Claude how you like work done, which tools and data to pull from, how to handle critical workflows, and what slash commands to expose — so your team gets better and more consistent outcomes.

Each plugin bundles the skills, connectors, slash commands, and sub-agents for a specific job function. Out of the box, they give Claude a strong starting point for helping anyone in that role. The real power comes when you customize them for your company — your tools, your terminology, your processes — so Claude works like it was built for your team.

## Plugin Marketplace

We're open-sourcing 11 plugins built and inspired by our own work:

| Plugin | How it helps | Connectors |
|--------|-------------|------------|
| **[productivity](./productivity)** | Manage tasks, calendars, daily workflows, and personal context so you spend less time repeating yourself. | Slack, Notion, Asana, Linear, Jira, Monday, ClickUp, Microsoft 365 |
| **[sales](./sales)** | Research prospects, prep for calls, review your pipeline, draft outreach, and build competitive battlecards. | Slack, HubSpot, Close, Clay, ZoomInfo, Notion, Jira, Fireflies, Microsoft 365 |
| **[customer-support](./customer-support)** | Triage tickets, draft responses, package escalations, research customer context, and turn resolved issues into knowledge base articles. | Slack, Intercom, HubSpot, Guru, Jira, Notion, Microsoft 365 |
| **[product-management](./product-management)** | Write specs, plan roadmaps, synthesize user research, keep stakeholders updated, and track the competitive landscape. | Slack, Linear, Asana, Monday, ClickUp, Jira, Notion, Figma, Amplitude, Pendo, Intercom, Fireflies |
| **[marketing](./marketing)** | Draft content, plan campaigns, enforce brand voice, brief on competitors, and report on performance across channels. | Slack, Canva, Figma, HubSpot, Amplitude, Notion, Ahrefs, SimilarWeb, Klaviyo |
| **[legal](./legal)** | Review contracts, triage NDAs, navigate compliance, assess risk, prep for meetings, and draft templated responses. | Slack, Box, Egnyte, Jira, Microsoft 365 |
| **[finance](./finance)** | Prep journal entries, reconcile accounts, generate financial statements, analyze variances, manage close, and support audits. | Snowflake, Databricks, BigQuery, Slack, Microsoft 365 |
| **[data](./data)** | Query, visualize, and interpret datasets — write SQL, run statistical analysis, build dashboards, and validate your work before sharing. | Snowflake, Databricks, BigQuery, Definite, Hex, Amplitude, Jira |
| **[enterprise-search](./enterprise-search)** | Find anything across email, chat, docs, and wikis — one query across all your company's tools. | Slack, Notion, Guru, Jira, Asana, Microsoft 365 |
| **[bio-research](./bio-research)** | Connect to preclinical research tools and databases (literature search, genomics analysis, target prioritization) to accelerate early-stage life sciences R&D. | PubMed, BioRender, bioRxiv, ClinicalTrials.gov, ChEMBL, Synapse, Wiley, Owkin, Open Targets, Benchling |
| **[cowork-plugin-management](./cowork-plugin-management)** | Create new plugins or customize existing ones for your organization's specific tools and workflows. | — |

Install these directly from Cowork, browse the full collection here on GitHub, or build your own.

## Getting Started

### Cowork

Install plugins from [claude.com/plugins](https://claude.com/plugins/).

### Claude Code

```bash
# Add the marketplace first
claude plugin marketplace add anthropics/knowledge-work-plugins

# Then install a specific plugin
claude plugin install sales@knowledge-work-plugins
```

Once installed, plugins activate automatically. Skills fire when relevant, and slash commands are available in your session (e.g., `/sales:call-prep`, `/data:write-query`).

## How Plugins Work

Every plugin follows the same structure:

```
plugin-name/
├── .claude-plugin/plugin.json   # Manifest
├── .mcp.json                    # Tool connections
├── commands/                    # Slash commands you invoke explicitly
└── skills/                      # Domain knowledge Claude draws on automatically
```

- **Skills** encode the domain expertise, best practices, and step-by-step workflows Claude needs to give you useful help. Claude draws on them automatically when relevant.
- **Commands** are explicit actions you trigger (e.g., `/finance:reconciliation`, `/product-management:write-spec`).
- **Connectors** wire Claude to the external tools your role depends on — CRMs, project trackers, data warehouses, design tools, and more — via [MCP servers](https://modelcontextprotocol.io/).

Every component is file-based — markdown and JSON, no code, no infrastructure, no build steps.

## Making Them Yours

These plugins are generic starting points. They become much more useful when you customize them for how your company actually works:

- **Swap connectors** — Edit `.mcp.json` to point at your specific tool stack.
- **Add company context** — Drop your terminology, org structure, and processes into skill files so Claude understands your world.
- **Adjust workflows** — Modify skill instructions to match how your team actually does things, not how a textbook says to.
- **Build new plugins** — Use the `cowork-plugin-management` plugin or follow the structure above to create plugins for roles and workflows we haven't covered yet.

As your team builds and shares plugins, Claude becomes a cross-functional expert. The context you define gets baked into every relevant interaction, so leaders and admins can spend less time enforcing processes and more time improving them.

## Contributing

Plugins are just markdown files. Fork the repo, make your changes, and submit a PR.


curl -s https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/README.md 2>&1 | head -300

Fetch README from claude-plugins-official main branch


curl -s https://raw.githubusercontent.com/anthropics/claude-desktop-buddy/main/README.md 2>&1 | head -300

Fetch README from claude-desktop-buddy main branch


# Claude Code Plugins Directory

A curated directory of high-quality plugins for Claude Code.

> **⚠ Important:** Make sure you trust a plugin before installing, updating, or using it. Anthropic does not control what MCP servers, files, or other software are included in plugins and cannot verify that they will work as intended or that they won't change. See each plugin's homepage for more information.

## Structure

- **`/plugins`** - Internal plugins developed and maintained by Anthropic
- **`/external_plugins`** - Third-party plugins from partners and the community

## Installation

Plugins can be installed directly from this marketplace via Claude Code's plugin system.

To install, run `/plugin install {plugin-name}@claude-plugins-official`

or browse for the plugin in `/plugin > Discover`

## Contributing

### Internal Plugins

Internal plugins are developed by Anthropic team members. See `/plugins/example-plugin` for a reference implementation.

### External Plugins

Third-party partners can submit plugins for inclusion in the marketplace. External plugins must meet quality and security standards for approval. To submit a new plugin, use the [plugin directory submission form](https://clau.de/plugin-directory-submission).

## Plugin Structure

Each plugin follows a standard structure:

```
plugin-name/
├── .claude-plugin/
│   └── plugin.json      # Plugin metadata (required)
├── .mcp.json            # MCP server configuration (optional)
├── commands/            # Slash commands (optional)
├── agents/              # Agent definitions (optional)
├── skills/              # Skill definitions (optional)
└── README.md            # Documentation
```

## Skill-bundle plugins

When a plugin's source repository ships skills (`SKILL.md` files) without a `.claude-plugin/plugin.json` manifest, the marketplace entry can declare the skills directly using `strict: false` and an explicit `skills` array.

```json
{
  "name": "example-bundle",
  "description": "Brief description of the bundled skills.",
  "author": { "name": "Author Name" },
  "category": "development",
  "source": {
    "source": "git-subdir",
    "url": "https://github.com/example-org/sdk.git",
    "path": "packages/agent-skills",
    "ref": "main",
    "sha": "<commit sha>"
  },
  "strict": false,
  "skills": [
    "./skill-a",
    "./skill-b",
    "./skill-c"
  ],
  "homepage": "https://github.com/example-org/sdk"
}
```

Each path in `skills` is relative to `source.path` and points at a directory containing a `SKILL.md`. Paths can reach deeper than a single level — for example, `["./libA/skill-1", "./libB/skill-2"]` exposes a curated subset across multiple library subdirectories. Each skill is registered as `<plugin-name>:<skill-name>` in Claude Code.

For the underlying schema, see [Strict mode](https://code.claude.com/docs/en/plugin-marketplaces) in the marketplace documentation.

## License

Please see each linked plugin for the relevant LICENSE file.

## Documentation

For more information on developing Claude Code plugins, see the [official documentation](https://code.claude.com/docs/en/plugins).


# claude-desktop-buddy

Claude for macOS and Windows can connect Claude Cowork and Claude Code to
maker devices over BLE, so developers and makers can build hardware that
displays permission prompts, recent messages, and other interactions. We've
been impressed by the creativity of the maker community around Claude -
providing a lightweight, opt-in API is our way of making it easier to build
fun little hardware devices that integrate with Claude.

> **Building your own device?** You don't need any of the code here. See
> **[REFERENCE.md](REFERENCE.md)** for the wire protocol: Nordic UART
> Service UUIDs, JSON schemas, and the folder push transport.

As an example, we built a desk pet on ESP32 that lives off permission
approvals and interaction with Claude. It sleeps when nothing's happening,
wakes when sessions start, gets visibly impatient when an approval prompt is
waiting, and lets you approve or deny right from the device.

## Hardware

The firmware targets ESP32 with the Arduino framework. As written, it
depends on the M5StickCPlus library for its display, IMU, and button
drivers—so you'll need that board, or a fork that swaps those drivers for
your own pin layout.

## Flashing

Install
[PlatformIO Core](https://docs.platformio.org/en/latest/core/installation/),
then:

```bash
pio run -t upload
```

If you're starting from a previously-flashed device, wipe it first:

```bash
pio run -t erase && pio run -t upload
```

Once running, you can also wipe everything from the device itself: **hold A
→ settings → reset → factory reset → tap twice**.

## Pairing

To pair your device with Claude, first enable developer mode (**Help →
Troubleshooting → Enable Developer Mode**). Then, open the Hardware Buddy
window in **Developer → Open Hardware Buddy…**, click **Connect**, and pick
your device from the list. macOS will prompt for Bluetooth permission on
first connect; grant it.

Once paired, the bridge auto-reconnects whenever both sides are awake.

If discovery isn't finding the stick:

- Make sure it's awake (any button press)
- Check the stick's settings menu → bluetooth is on

## Controls

|                         | Normal               | Pet         | Info        | Approval    |
| ----------------------- | -------------------- | ----------- | ----------- | ----------- |
| **A** (front)           | next screen          | next screen | next screen | **approve** |
| **B** (right)           | scroll transcript    | next page   | next page   | **deny**    |
| **Hold A**              | menu                 | menu        | menu        | menu        |
| **Power** (left, short) | toggle screen off    |             |             |             |
| **Power** (left, ~6s)   | hard power off       |             |             |             |
| **Shake**               | dizzy                |             |             | —           |
| **Face-down**           | nap (energy refills) |             |             |             |

The screen auto-powers-off after 30s of no interaction (kept on while an
approval prompt is up). Any button press wakes it.

## ASCII pets

Eighteen pets, each with seven animations (sleep, idle, busy, attention,
celebrate, dizzy, heart). Menu → "next pet" cycles them with a counter.
Choice persists to NVS.

## GIF pets

If you want a custom GIF character instead of an ASCII buddy, drag a
character pack folder onto the drop target in the Hardware Buddy window. The
app streams it over BLE and the stick switches to GIF mode live. **Settings
→ delete char** reverts to ASCII mode.

A character pack is a folder with `manifest.json` and 96px-wide GIFs:

```json
{
  "name": "bufo",
  "colors": {
    "body": "#6B8E23",
    "bg": "#000000",
    "text": "#FFFFFF",
    "textDim": "#808080",
    "ink": "#000000"
  },
  "states": {
    "sleep": "sleep.gif",
    "idle": ["idle_0.gif", "idle_1.gif", "idle_2.gif"],
    "busy": "busy.gif",
    "attention": "attention.gif",
    "celebrate": "celebrate.gif",
    "dizzy": "dizzy.gif",
    "heart": "heart.gif"
  }
}
```

State values can be a single filename or an array. Arrays rotate: each
loop-end advances to the next GIF, useful for an idle activity carousel so
the home screen doesn't loop one clip forever.

GIFs are 96px wide; height up to ~140px stays on a 135×240 portrait screen.
Crop tight to the character — transparent margins waste screen and shrink
the sprite. `tools/prep_character.py` handles the resize: feed it source
GIFs at any sizes and it produces a 96px-wide set where the character is the
same scale in every state.

The whole folder must fit under 1.8MB —
`gifsicle --lossy=80 -O3 --colors 64` typically cuts 40–60%.

See `characters/bufo/` for a working example.

If you're iterating on a character and would rather skip the BLE round-trip,
`tools/flash_character.py characters/bufo` stages it into `data/` and runs
`pio run -t uploadfs` directly over USB.

## The seven states

| State       | Trigger                     | Feel                        |
| ----------- | --------------------------- | --------------------------- |
| `sleep`     | bridge not connected        | eyes closed, slow breathing |
| `idle`      | connected, nothing urgent   | blinking, looking around    |
| `busy`      | sessions actively running   | sweating, working           |
| `attention` | approval pending            | alert, **LED blinks**       |
| `celebrate` | level up (every 50K tokens) | confetti, bouncing          |
| `dizzy`     | you shook the stick         | spiral eyes, wobbling       |
| `heart`     | approved in under 5s        | floating hearts             |

## Project layout

```
src/
  main.cpp       — loop, state machine, UI screens
  buddy.cpp      — ASCII species dispatch + render helpers
  buddies/       — one file per species, seven anim functions each
  ble_bridge.cpp — Nordic UART service, line-buffered TX/RX
  character.cpp  — GIF decode + render
  data.h         — wire protocol, JSON parse
  xfer.h         — folder push receiver
  stats.h        — NVS-backed stats, settings, owner, species choice
characters/      — example GIF character packs
tools/           — generators and converters
```

## Availability

The BLE API is only available when the desktop apps are in developer mode
(**Help → Troubleshooting → Enable Developer Mode**). It's intended for
makers and developers and isn't an officially supported product feature.


curl -s https://raw.githubusercontent.com/anthropics/defending-code-reference-harness/main/README.md 2>&1 | head -300

Fetch README from defending-code-reference-harness main branch


# Defending Code Reference Harness

A reference implementation for autonomous vulnerability discovery and
remediation with Claude, based on our learnings from [partnering with security
teams at several organizations](https://www.anthropic.com/glasswing)
since launching Claude Mythos Preview. For a write up of these learnings along with
best practices, see the [accompanying blog post](https://claude.com/blog/using-llms-to-secure-source-code)
(also available in [`blog-post.md`](docs/blog-post.md)). For a lightweight SDK-only
walkthrough of the same recon → find → triage → report → patch loop, see the
[companion cookbook](https://platform.claude.com/cookbook/claude-agent-sdk-06-the-vulnerability-detection-agent).

This repo is not maintained and is not accepting contributions.

> 🔒 **Want a managed option?** Anthropic offers
> [Claude Security](https://claude.com/product/claude-security), a hosted product
> that finds and fixes vulnerabilities in your source code across multiple
> projects. Claude Security scans your repository for vulnerabilities,
> applies a multi-stage verification pipeline to reduce false positives, and
> lets you manage findings through their lifecycle: triage, fix validation,
> and rapid fix generation.
>
> This repository is an open-source reference implementation based on general
> best practices for finding vulnerabilities using Claude. You can use it to
> build your own vulnerability finding pipeline, customize the logic, and it
> can be used with whatever access you have to Claude APIs (including
> Bedrock, Vertex, or Azure).

## Contents

- **Claude Code skills**: `/quickstart`, `/threat-model`, `/vuln-scan`,
  `/triage`, `/patch`, `/customize`: interactive scoping, scanning, triage,
  and patching. Open this repo in Claude Code and run `/quickstart` to get
  oriented.
- **`harness/`**: the autonomous reference pipeline (recon → find → verify
  → report → patch), configured for finding C/C++ memory vulnerabilities
  using Docker and ASAN. This harness is a **reference, not a product**.
  The general shape, prompts, and sandboxing are reusable, but the harness
  will not work on every codebase out of the box. Run `/customize` to port it
  to your language, detector, or vuln class.

> ⚠ **Security:** `/quickstart`, `/threat-model`, `/vuln-scan`, and `/triage`
> only read and write files. Running `/patch` on static findings (`TRIAGE.json`
> or `VULN-FINDINGS.json`) is likewise read- and write-only. `/customize` edits
> the harness code and runs validation commands. Any of these skills are safe to
> run unsandboxed, as long as you review and approve each tool use in Claude Code.
> The autonomous reference pipeline (including `/patch` on pipeline results)
> **executes target code**, so it refuses to run outside of a gVisor sandbox
> unless explicitly overridden. To get set up, run `scripts/setup_sandbox.sh` once,
> then invoke the pipeline via `bin/vp-sandboxed`. See [docs/security.md](docs/security.md)
> and [docs/agent-sandbox.md](docs/agent-sandbox.md) for more details.

## Getting Started

```bash
git clone https://github.com/anthropics/defending-code-reference-harness
cd defending-code-reference-harness
claude

# 30-sec intro + guided first run on the canary target
> /quickstart

> /quickstart how do I port the pipeline to Java?
> /quickstart how do I triage all these bugs?
```

## Further Reading

- [**Blog Post**](docs/blog-post.md) · The accompanying blog post with learnings + best practices
- [**Pipeline**](docs/pipeline.md) · How it works: diagram, stages, CLI flags
- [**Security**](docs/security.md) · Sandboxing, what not to mount
- [**Agent sandbox**](docs/agent-sandbox.md) · gVisor isolation + egress allowlist for every agent
- [**Customize**](docs/customizing.md) · Port to my stack; which files change and why
- [**Patching**](docs/patching.md) · Generate and verify fixes for verified crashes
- [**Troubleshooting**](docs/troubleshooting.md) · Duplicates, rate limits, subagent model pinning
- [**Safeguards**](https://support.claude.com/en/articles/14604842-real-time-cyber-safeguards-on-claude) · Block for dangerous cyber work

---

## Ramp Up

The most successful security teams we've partnered with are those
that have gotten hands-on the fastest. Though it's tempting to
spend months designing the perfect pipeline, we recommend starting
small on Day 1 and building from there as learnings come. The
steps below follow that pattern and set an ambitious (but reasonable)
pace based on what we've seen.

|                                                                                |              |                                                              |
|-------------------------------------------------------------------------------------|--------------|--------------------------------------------------------------|
| [Step 1](#step-1-day-1-build-a-threat-model-and-run-your-first-static-scan--triage) | **Day 1**    | Build a threat model and run your first static scan + triage |
| [Step 2](#step-2-day-2-run-the-reference-pipeline-on-a-cc-library)                  | **Day 2**    | Run the reference pipeline on a C/C++ library                |
| [Step 3](#step-3-days-3-5-customize-the-pipeline-for-your-target)                   | **Days 3-5** | Customize the pipeline for your target                       |
| [Step 4](#step-4-week-2-start-autonomous-scanning-triage-and-patching)              | **Week 2**   | Start autonomous scanning, triage, and patching              |

### Step 1 (Day 1): Build a threat model and run your first static scan + triage

Day 1 is focused on seeing the whole loop end-to-end. Using only the
interactive skills, you'll build a threat model, run a static scan scoped
by it, triage what comes back, and draft candidate fixes. You'll finish
the day with a threat model, a ranked list of static findings, and candidate
patches.

The relevant skills **only read and write files** in your repo. As long as you
run Claude Code interactively and approve each tool use, no sandbox is needed.

```bash
# Pin every subagent to the model you want
export CLAUDE_CODE_SUBAGENT_MODEL=<model-id>
claude

# 0. intro + guided first run
> /quickstart

# 1. Build a threat model (aim before you shoot)
> /threat-model bootstrap targets/canary

# 2. Run a static scan, scoped by that threat model
> /vuln-scan targets/canary

# 3. Verify, dedupe, and rank what came back
> /triage targets/canary/VULN-FINDINGS.json

# 4. Generate candidate fixes for the verified findings
> /patch ./TRIAGE.json --repo targets/canary
```

This flow produces `THREAT_MODEL.md`, `VULN-FINDINGS.{json,md}`,
`TRIAGE.{json,md}`, and `PATCHES/`.

The vulnerability candidates produced in Step 1 come from Claude's static
review of the source (nothing is built or run), so expect more false positives on
any non-canary targets. In Step 2, you'll produce *execution-verified* findings.

> **Note:** on the canary target, `/triage` may dismiss the scan's findings
> as false positives. `entry.c` announces itself as deliberately vulnerable
> demo code, and `/triage` correctly excludes bugs in test / fixture code.
> To see the full confirm / dedupe / false positive flow, run it on the
> curated fixture instead (`/triage .claude/skills/triage/fixtures/canary-findings.json
> --repo targets/canary`) or point the Step 1 skills at your own code.

### Step 2 (Day 2): Run the reference pipeline on a C/C++ library

On Day 2, you'll move from interactive skills to your first autonomous
run using the reference pipeline. You'll run the full recon → find →
verify → report loop in your environment on a known-vulnerable open-source
library, then generate a candidate patch for what it finds. You'll finish
with a set of reproducible crashes, exploitability reports, and candidate patches,
along with a feel for how the pipeline works.

Running the pipeline is simple:

```bash
# One-time setup
python3 -m venv .venv && .venv/bin/pip install -e .
./scripts/setup_sandbox.sh   # installs gVisor, builds the agent images, and verifies isolation; note: requires Docker
export ANTHROPIC_API_KEY=sk-ant-...   # or CLAUDE_CODE_OAUTH_TOKEN; the pipeline requires one in env

# Run the recon → find → verify → report loop
bin/vp-sandboxed run drlibs --model <model-id> --runs 3 --parallel --stream --auto-focus
# Generate a candidate patch for each finding
bin/vp-sandboxed patch results/drlibs/<timestamp>/ --model <model-id>

# Or, ask Claude Code to launch the pipeline and watch the run for you
claude
> run the pipeline on drlibs and explain findings as they come
```

Results from the loop land in a `results/drlibs/<timestamp>/` directory. With
the `--stream` flag, the first report will appear in minutes under `reports/bug_NN/`.

> ⚠ **`run` spawns autonomous agents.** The pipeline runs each agent
> inside a gVisor container with egress restricted to the Claude API.
> Agent-spawning subcommands refuse to start outside it unless explicitly
> overridden. For more information, see [docs/security.md](docs/security.md)
> and [docs/agent-sandbox.md](docs/agent-sandbox.md).

Under the hood, the pipeline walks through seven stages:

1. **Build**: Compiles the target into a Docker image with ASAN (the memory
error detector for C and C++). The pipeline builds this image automatically
on first run using the target's `Dockerfile`.
2. **Recon**: A lightweight agent reads the source inside a network-isolated
container and proposes a partition, i.e., *"here are N distinct input-parsing
subsystems worth attacking separately"*, so that parallel find agents explore
different areas instead of converging on the same bug. Without the `--auto-focus`
flag, the pipeline uses the `focus_areas` list from the target's `config.yaml`.
3. **Find**: N agents run in parallel, each in its own isolated container.
Each agent reads the source, crafts malformed inputs, and runs the ASAN
binary until a given input produces a crash 3 out of 3 times.
4. **Verify**: A separate grader agent reproduces each crash in a fresh
container that the find agent hasn't touched. The only thing that crosses over
from the find agent to the grader is the proof of concept it produced.
5. **Dedupe**: A judge agent compares verified crashes against bugs already
reported and decides whether each is a new bug, a better example of a known
bug, or a duplicate to skip.
6. **Report**: A report agent writes a structured exploitability analysis per
unique bug, including details on primitive class, reachability, escalation
path, and severity.
7. **Patch** (the separate patch command above): A patch agent writes a proposed
fix, and a grader agent confirms that the new code builds, that the original
proof of concept input no longer crashes, that the target's test suite still
passes, and that a fresh find agent can't find a way around the fix.

For more details, see [docs/pipeline.md](docs/pipeline.md).

### Step 3 (Days 3-5): Customize the pipeline for your target

On Days 3-5, you'll customize the harness for your own target. First, you'll
point the Step 1 skills at your code, then you'll use `/customize` to port the
pipeline to your stack. By the end of the week, you'll have a `targets/<your-service>/`
directory that the pipeline can run against, validated with a single smoke run
of the pipeline, and ready to scale up in Step 4.

While the reference pipeline is designed for finding memory vulnerabilities in C and C++
code, its shape is generic. Porting it to a new vuln class or language just means
answering the following questions for your target stack:

| Question                                | C/C++ Reference                   | Your target (examples)                         |
|-----------------------------------------|-----------------------------------|------------------------------------------------|
| What signals a finding?                 | ASAN crash signature              | exception / canary file / DNS callback         |
| What does a proof of concept look like? | crashing input file               | HTTP request sequence / tx list / test harness |
| How is the target built and run?        | `Dockerfile` (using clang + ASAN) | your language's build in a container           |

Before customizing, point the Step 1 skills at your own code. As a reminder,
they're read- and write-only, so they can run unsandboxed.

```bash
claude

> /quickstart how do I customize this for ~/code/my-service?

> /threat-model bootstrap-then-interview ~/code/my-service
> /vuln-scan ~/code/my-service
> /triage ~/code/my-service/VULN-FINDINGS.json --repo ~/code/my-service
```

Then, use the artifacts produced by those skills in the `/customize` skill,
which modifies the harness for your codebase.

```bash
> /customize use ~/code/my-service/{THREAT_MODEL.md,VULN-FINDINGS.json} and ./TRIAGE.md
```

When `/customize` is done, you'll have a `targets/my-service/` directory
set up. Validate it with a smoke run of the pipeline before scaling up.

```bash
bin/vp-sandboxed run my-service --model <model-id> --runs 1
```

For more details, see [docs/customizing.md](docs/customizing.md).

### Step 4 (Week 2): Start autonomous scanning, triage, and patching

In Week 2, you'll use the pipeline you customized in Step 3 on your own
targets, adding an *outer* loop to the inner pipeline loop - run multiple
pipeline scans, triage the findings from across those runs, patch based
on prioritization, and repeat.

```bash
# Scan - run a wave of parallel runs against your target
bin/vp-sandboxed run my-service --model <model-id> --runs 5 --parallel --stream --auto-focus

# Triage - dedupe and rank every finding across all waves using your threat model
> /triage results/my-service/ --repo ~/code/my-service --auto --votes 5

# Patch - generate and validate fixes, starting with what triage ranked the highest
> /patch results/my-service/<timestamp>/ --model <model-id>
```

> ⚠ Follow the same sandboxing guidelines as in
> [Step 2](#step-2-day-2-run-the-reference-pipeline-on-a-cc-library)

A given pipeline run already verifies and deduplicates its own findings.
`/triage` works across many pipeline runs. When pointed at the `results/`
directory, it collapses duplicates across all runs (and any static findings
from `/vuln-scan` if present), recalibrates severity ratings against your
threat model, and attempts to route every finding to the component owner.

When possible, patching findings quickly helps keep the outer loop as
productive as possible. When findings are fixed, the model can't re-find
them, and instead will surface net new, typically deeper issues. As you run
more pipeline waves, the number of findings will likely go down, but the
complexity will likely also go up. If quick patching isn't possible, even
just recording prior findings in the target's `known_bugs` can help steer
future runs toward newer bugs.

Autonomous triage and patching are still open issues, and this reference
harness doesn't fully solve them. The verification strategies in `/patch`
help raise the bar, but severity and prioritization are ultimately
judgments about your environment, and verified patches are not always
upstreamable. Many partners have reported these steps as their current
bottlenecks, and you should budget real engineering time for them.

For more details, see [docs/triage.md](docs/triage.md) and
[docs/patching.md](docs/patching.md).

## Looking Forward

After the initial ramp up, the teams we've worked with have tended to invest in a


Now let me check for the repos that may have returned 404s and try the master branch:


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/claude-agent-sdk-python/main/README.md && echo " main" || echo " not found"

Check if main branch exists for python SDK


200 main


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/claude-agent-sdk-typescript/main/README.md && echo " main" || echo " not found"

Check if main branch exists for typescript SDK


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/ClaudeForFoundationModels/main/README.md && echo " main" || echo " not found"

Check if main branch exists for ClaudeForFoundationModels


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/cwc-long-running-agents/main/README.md && echo " main" || echo " not found"

Check if main branch exists for cwc-long-running-agents


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/knowledge-work-plugins/main/README.md && echo " main" || echo " not found"

Check if main branch exists for knowledge-work-plugins


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/claude-plugins-official/main/README.md && echo " main" || echo " not found"

Check if main branch exists for claude-plugins-official


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/claude-desktop-buddy/main/README.md && echo " main" || echo " not found"

Check if main branch exists for claude-desktop-buddy


curl -s -o /dev/null -w "%{http_code}" https://raw.githubusercontent.com/anthropics/defending-code-reference-harness/main/README.md && echo " main" || echo " not found"

Check if main branch exists for defending-code-reference-harness


Perfect! All repos have the main branch. I've successfully fetched the README content from all 8 Anthropic repos. Here's the compiled report:

---

REPO: anthropics/claude-agent-sdk-python
README:
Python SDK for Claude Agent with installation via pip, prerequisites of Python 3.10+, quick start examples, basic query() usage, tool configuration, working directory options, ClaudeSDKClient for interactive conversations, custom tools implemented as in-process MCP servers, hooks for intercepting agent behavior, type definitions, error handling, available tools documentation, and examples. Includes migration notes from Claude Code SDK.

---

REPO: anthropics/claude-agent-sdk-typescript
README:
Claude Agent SDK for Node.js 18+ that enables programmatic AI agents with Claude Code capabilities. Includes npm installation, migration guide from Claude Code SDK, bug reporting via GitHub issues, Discord community connection, and data collection/privacy policies regarding feedback, usage data, and safeguards. Governed by Commercial Terms of Service and Privacy Policy.

---

REPO: anthropics/ClaudeForFoundationModels
README:
Swift package allowing Claude to be used as a server-side language model through Apple's Foundation Models framework, conforming to the LanguageModel protocol. Requires iOS/macOS/visionOS/watchOS 27 (beta) and Xcode 27 (beta). Covers installation via Package.swift, quick start example, model selection with capabilities, effort levels, authentication (development via API key, production via proxy), streaming, structured output with @Generable annotation, server-side tools (web search, web fetch, code execution), error handling, and support information.

---

REPO: anthropics/cwc-long-running-agents
README:
Harness primitives for long-running Claude agents based on engineering learnings, providing hooks and subagents as alternatives to built-in /goal command. Implements three core primitives: default-FAIL contract (criteria start false), fresh-context evaluator (separate agent grades work), and agent-maintained handoff (progress notes and git commits). Includes operator-control hooks, quality-loop reference table, primitive examples, running the loop (via /goal or custom evaluator.md), operator controls (kill-switch, steer), watching execution, and advanced patterns. Example repo for learning, not maintained.

---

REPO: anthropics/knowledge-work-plugins
README:
Plugins for Claude that specialize by role, team, and company. Open-sources 11 plugins (productivity, sales, customer-support, product-management, marketing, legal, finance, data, enterprise-search, bio-research, cowork-plugin-management) with connectors to tools like Slack, Notion, HubSpot, Jira, Figma, Snowflake, and others. Explains plugin structure (skills, commands, connectors), installation instructions for both Cowork and Claude Code, and guidance on customizing plugins for specific company needs.

---

REPO: anthropics/claude-plugins-official
README:
Curated directory of high-quality plugins for Claude Code. Contains internal plugins developed by Anthropic and third-party external plugins from partners and community. Describes plugin installation via /plugin install command, contribution guidelines for both internal and external plugins, standard plugin structure (plugin.json, MCP configuration, commands, agents, skills), and skill-bundle plugin support for repositories shipping skills without a manifest. References official documentation for plugin development.

---

REPO: anthropics/claude-desktop-buddy
README:
Hardware project enabling Claude for macOS and Windows to connect to maker devices over BLE, displaying permission prompts and interactions. Reference includes wire protocol specification (Nordic UART UUIDs, JSON schemas, folder push). Features example ESP32 desk pet using Arduino framework and M5StickCPlus library. Covers flashing via PlatformIO, Bluetooth pairing process, control scheme with buttons, 18 ASCII pets with animations, custom GIF character support, seven emotional states (sleep, idle, busy, attention, celebrate, dizzy, heart), project layout, and availability notes about developer mode.

---

REPO: anthropics/defending-code-reference-harness
README:
Reference implementation for autonomous vulnerability discovery and remediation with Claude based on security partnerships. Includes Claude Code skills (/quickstart, /threat-model, /vuln-scan, /triage, /patch, /customize) and autonomous reference pipeline (recon → find → verify → report → patch) for C/C++ memory vulnerabilities using Docker and ASAN. Provides structured ramp-up from Day 1 (threat modeling and static scan) through Week 2 (autonomous scanning and patching). Details security considerations (read-only skills unsandboxed, pipeline requires gVisor sandbox), pipeline stages (build, recon, find, verify, dedupe, report, patch), and customization guidance for other languages/vulnerability classes. Includes troubleshooting and patching documentation.

---