agentleFS
pocketpawpocketpaw/pocketpaw/.github/copilot-instructions.md

pocketpaw

Copilot instructions886 starsChanged 9 months agoMITView on GitHub

This file gives GitHub Copilot repo-specific guidance so its suggestions align with PocketPaw's architecture and conventions. Read CLAUDE.md for the full picture; this file focuses on the most frequently violated rules. All communication must flow through the message bus (src/pocketpaw/bus/). The three canonical event types are defined in bus/events.py: Rules: - Adapters publish InboundMessage via self._publish_inbound(). They never call agent code directly. - Agents subscribe to InboundMessage and publish OutboundMessage / SystemEvent. They never call adapter methods. - Do not…

The file

Show its rules and text

We split this copilot-instructions.md into the rules it gives an agent

24 rules. About 0 are common, 4 are distinctive, and 20 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 20

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Very specific:

    All communication must flow through the message bus (src/pocketpaw/bus/).

    line 9
  2. Distinctive:

    Do not create new event types without discussion.

    line 20
  3. Very specific:

    Every method that performs I/O (network, file, subprocess) must be async def.

    line 26
  4. Very specific:

    Use asyncio.to_thread() for unavoidable blocking calls (e.g.

    line 27
  5. Very specific:

    Never call asyncio.run() inside library code.

    line 29
  6. Very specific:

    Use Protocol (not ABC) for all public interfaces.

    line 47
  7. Very specific:

    Every backend that implements AgentBackend must yield AgentEvent objects with these fields:

    line 77
  8. Very specific:

    Create src/pocketpaw/agents/<name>.py implementing the AgentBackend protocol.

    line 142
  9. Very specific:

    Import the optional SDK lazily inside __init__ or _initialize().

    line 143
  10. Very specific:

    Add the optional dependency as an extra in pyproject.toml (e.g.

    line 145
  11. Very specific:

    Add any legacy name aliases to _LEGACY_BACKENDS.

    line 146
  12. Distinctive:

    Write tests — mock the external SDK so tests run without the real dep.

    line 147
  13. Very specific:

    Call self._publish_inbound(msg) to push incoming messages to the bus.

    line 154
  14. Very specific:

    Add optional dependencies to pyproject.toml extras.

    line 155
  15. Distinctive:

    Write tests — mock the external client and assert bus events.

    line 157
  16. Very specific:

    Add the class to tools/builtin/__init__.py under the lazy-import block.

    line 164
  17. Very specific:

    Add the tool to the correct policy group in tools/policy.py.

    line 165
  18. Very specific:

    All settings live in config.py as a Pydantic Settings class with POCKETPAW_-prefixed environment variables.

    line 185
  19. Very specific:

    Call get_settings() inside functions, never at module import time (Pydantic reads env vars on construction — module-level calls break …

    line 186
  20. Distinctive:

    Use the existing WebSocket connection for real-time streaming — do not open additional WebSocket connections.

    line 208
  21. Very specific:

    Keep CSS in the existing stylesheet.

    line 209
  22. Very specific:

    Use pytest-asyncio (asyncio_mode = "auto" — no decorator needed).

    line 217
  23. Very specific:

    Use unittest.mock.patch / AsyncMock for async boundaries.

    line 218
  24. Very specific:

    Run the full suite before pushing: uv run pytest --ignore=tests/e2e.

    line 220

≈ “Common” is an estimate: at least 1 in 5 of the 1,644 Copilot instructions files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
copilot-instructions.md

GitHub Copilot Instructions for PocketPaw

This file gives GitHub Copilot repo-specific guidance so its suggestions align with PocketPaw's architecture and conventions. Read CLAUDE.md for the full picture; this file focuses on the most frequently violated rules.


1. Event-driven message bus

All communication must flow through the message bus (src/pocketpaw/bus/). The three canonical event types are defined in bus/events.py:

TypeDirectionPurpose
InboundMessageChannel → BusUser input from any channel
OutboundMessageBus → ChannelAgent response (supports streaming via is_stream_chunk / is_stream_end)
SystemEventInternalTool activity, errors, thinking — consumed by the dashboard Activity panel

Rules:

  • Adapters publish InboundMessage via self._publish_inbound(). They never call agent code directly.
  • Agents subscribe to InboundMessage and publish OutboundMessage / SystemEvent. They never call adapter methods.
  • Do not create new event types without discussion. Extend the metadata dict on existing types first.

2. Async everywhere

  • Every method that performs I/O (network, file, subprocess) must be async def.
  • Use asyncio.to_thread() for unavoidable blocking calls (e.g. a sync-only third-party SDK).
  • Tests use pytest-asyncio in asyncio_mode = "auto" — no @pytest.mark.asyncio decorator needed.
  • Never call asyncio.run() inside library code. Reserve it for entry points only.
# ✅ correct
async def fetch_data(url: str) -> str:
    async with httpx.AsyncClient() as client:
        resp = await client.get(url)
    return resp.text

# ❌ wrong — blocks the event loop
def fetch_data(url: str) -> str:
    return requests.get(url).text

3. Protocol-oriented interfaces

Use Protocol (not ABC) for all public interfaces. Implement the protocol; do not subclass the concrete implementation class.

Key protocols:

ProtocolLocation
AgentBackendagents/backend.py
ToolProtocoltools/protocol.py
ChannelAdapter / BaseChannelAdapterbus/adapters/base.py
MemoryStoreProtocolmemory/protocol.py
# ✅ correct — implement the protocol
from pocketpaw.agents.backend import AgentBackend

class MyBackend:
    async def run(self, prompt: str, **kwargs) -> AsyncIterator[AgentEvent]:
        ...

# ❌ wrong — inheriting from the concrete class couples you to internals
from pocketpaw.agents.claude_sdk import ClaudeAgentBackend

class MyBackend(ClaudeAgentBackend):  # noqa: don't do this
    ...

4. Standardised AgentEvent stream

Every backend that implements AgentBackend must yield AgentEvent objects with these fields:

@dataclass
class AgentEvent:
    type: str      # see valid values below
    content: str   # text payload (may be empty string)
    metadata: dict # arbitrary extra data

Valid type values (do not invent new ones without updating backend.py):

ValueMeaning
"text"Streamed text chunk from the model
"tool_start"A tool invocation is beginning
"tool_result"A tool returned its result
"thinking"Model is reasoning (extended thinking)
"error"Non-fatal error; stream continues
"done"Final event — stream is complete

Rule: always yield "done" last. The agent loop depends on this to close the stream.

async def run(self, prompt, **kwargs):
    async for chunk in self._model.stream(prompt):
        yield AgentEvent(type="text", content=chunk, metadata={})
    yield AgentEvent(type="done", content="", metadata={})  # required

5. Lazy imports for optional dependencies

Optional SDK imports (discord, slack, anthropic, openai, google-genai, etc.) must live inside __init__ or the first-use method — never at module scope.

# ✅ correct — import inside __init__ or first-use method
class DiscordAdapter(BaseChannelAdapter):
    def __init__(self, ...):
        try:
            import discord  # lazy import
            self._discord = discord
        except ImportError as exc:
            raise ImportError("Install pocketpaw[discord]") from exc

# ❌ wrong — top-level import breaks installs that don't have the dep
import discord  # fails for users without pocketpaw[discord]

Register new backends in _BACKEND_REGISTRY inside agents/registry.py:

_BACKEND_REGISTRY: dict[str, str] = {
    "my_new_backend": "pocketpaw.agents.my_module.MyBackend",
    # dotted path is imported lazily by AgentRouter._initialize_agent()
}

6. Where new code goes

Adding a new agent backend

  1. Create src/pocketpaw/agents/<name>.py implementing the AgentBackend protocol.
  2. Import the optional SDK lazily inside __init__ or _initialize().
  3. Register the backend string key in _BACKEND_REGISTRY in agents/registry.py.
  4. Add the optional dependency as an extra in pyproject.toml (e.g. [project.optional-dependencies] mybackend = ["my-sdk>=1.0"]).
  5. Add any legacy name aliases to _LEGACY_BACKENDS.
  6. Write tests — mock the external SDK so tests run without the real dep.

Adding a new channel adapter

  1. Create src/pocketpaw/bus/adapters/<name>.py.
  2. Extend BaseChannelAdapter.
  3. Implement _on_start(), _on_stop(), and send(message: OutboundMessage) -> None.
  4. Call self._publish_inbound(msg) to push incoming messages to the bus.
  5. Add optional dependencies to pyproject.toml extras.
  6. Register the adapter in the dashboard's channel management system.
  7. Write tests — mock the external client and assert bus events.

Adding a new tool

  1. Create src/pocketpaw/tools/builtin/<name>.py.
  2. Subclass BaseTool from tools/protocol.py.
  3. Implement name, description, parameters (JSON Schema), and async execute(**params) -> str.
  4. Add the class to tools/builtin/__init__.py under the lazy-import block.
  5. Add the tool to the correct policy group in tools/policy.py.
  6. Write tests.

7. Security non-negotiables

RuleDetail
Shell command safetyEvery shell-executing tool must pass through security/rails.py before execution.
Secrets in Settings onlyNever hardcode credentials. Use get_settings() and store secrets via credentials.py (Fernet-encrypted). New secret fields must be added to SECRET_FIELDS in credentials.py.
Audit loggingAny action gated on trust_level = "high" or "critical" must emit an audit log entry to ~/.pocketpaw/audit.jsonl.
Channel allowlistsChannel identifiers (guild IDs, user IDs, phone numbers) must be validated against the configured allowlist before processing.
No credentials in logsNever pass API keys, tokens, or user PII to logging.* calls.
API endpoint authEvery new REST endpoint must go through the existing auth middleware — no unauthenticated routes.

8. Configuration

  • All settings live in config.py as a Pydantic Settings class with POCKETPAW_-prefixed environment variables.
  • Call get_settings() inside functions, never at module import time (Pydantic reads env vars on construction — module-level calls break testing).
  • Persist new settings through Settings.save() and the JSON config at ~/.pocketpaw/config.json.
# ✅ correct
async def my_function():
    settings = get_settings()
    token = settings.my_new_token

# ❌ wrong — evaluated at import time, breaks test isolation
settings = get_settings()
TOKEN = settings.my_new_token

Channel-specific env vars follow the pattern POCKETPAW_<CHANNEL>_<FIELD> (e.g. POCKETPAW_DISCORD_BOT_TOKEN).


9. Frontend

  • The web dashboard (frontend/) is vanilla JS / CSS / HTML. No React, Vue, bundlers, or npm. No build step.
  • Serve new UI via FastAPI + Jinja2 templates already wired in dashboard.py.
  • Use the existing WebSocket connection for real-time streaming — do not open additional WebSocket connections.
  • Keep CSS in the existing stylesheet; do not add <style> blocks inline in templates.

10. Testing expectations

  • Write tests before (or alongside) production code. PRs without tests for new behaviour will be asked to add them.
  • Mock external SDKs so the test suite runs without real API keys or network access.
  • Use pytest-asyncio (asyncio_mode = "auto" — no decorator needed).
  • Use unittest.mock.patch / AsyncMock for async boundaries.
  • Tests live in tests/. Name files test_<module>.py and functions test_<what_it_does>.
  • Run the full suite before pushing: uv run pytest --ignore=tests/e2e.
# Example: mocking an optional SDK
from unittest.mock import AsyncMock, patch

async def test_my_backend_streams_done_event():
    with patch("pocketpaw.agents.my_module.my_sdk") as mock_sdk:
        mock_sdk.Client.return_value.stream = AsyncMock(return_value=aiter(["hello"]))
        backend = MyBackend()
        events = [e async for e in backend.run("hi")]
    assert events[-1].type == "done"

11. Code style

RuleValue
Linter / formatterRuff (uv run ruff check . / uv run ruff format .)
Lint rulesE, F, I, UP
Line length100 characters
Target Python3.11
Future annotationsfrom __future__ import annotations at the top of every file
InterfacesProtocol over ABC for all public interfaces
Type hintsRequired on all public functions and methods
ImportsStandard library → third-party → local; sorted by Ruff

Pre-commit hooks enforce ruff on every commit. CI blocks merges on lint or test failures.


12. Common mistakes

MistakeWhy it breaksFix
import discord at module levelImport fails for users who haven't installed pocketpaw[discord]Move import inside __init__ or first-use method
settings = get_settings() at module levelSettings are instantiated at import time — test isolation is brokenCall get_settings() inside each function
Calling agent code directly from an adapterCouples channel to agent; breaks the bus patternPublish an InboundMessage to the bus instead
Forgetting yield AgentEvent(type="done", ...)Agent loop never closes; stream hangsAlways yield "done" as the last event
Inline auth in a new endpointBypasses the security modelUse the existing auth middleware
Logging an API key or tokenLeaks credentials to log filesLog only non-secret identifiers
Synchronous I/O in an async functionBlocks the event loopUse await asyncio.to_thread(...) for blocking calls
Subclassing a concrete backend instead of the protocolTight coupling; breaks when the concrete class changesImplement AgentBackend protocol directly
asyncio.run() inside library codeBreaks when called from an existing event loopReserve asyncio.run() for entry points only
Missing SECRET_FIELDS registrationNew secret field stored in plaintext in configAdd field name to SECRET_FIELDS in credentials.py

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.