instruction
stringclasses
100 values
code
stringlengths
78
193k
response
stringlengths
259
170k
file
stringlengths
59
203
Auto-generate documentation strings for this file
# Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. __author__ = 'Guido van Rossum <guido@python.org>' import sys from io import StringIO from typing import List from typing import Optional from typing import Text from typing import Tuple from typing import Union HUGE ...
--- +++ @@ -1,5 +1,13 @@ # Copyright 2006 Google, Inc. All Rights Reserved. # Licensed to PSF under a Contributor Agreement. +""" +Python parse tree definitions. + +This is a very concrete parse tree; we need to keep every token and +even the comments and whitespace between tokens. + +There's also a pattern matching i...
https://raw.githubusercontent.com/google/yapf/HEAD/third_party/yapf_third_party/_ylib2to3/pytree.py
Provide docstrings following PEP 257
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
--- +++ @@ -11,6 +11,13 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""LogicalLine primitive for formatting. + +A logical line is the containing data structure produced by the pars...
https://raw.githubusercontent.com/google/yapf/HEAD/yapf/yapflib/logical_line.py
Create documentation strings for testing functions
import re, collections, logging from explainshell import store tokenstate = collections.namedtuple('tokenstate', 'startpos endpos token') logger = logging.getLogger(__name__) def extract(manpage): for i, p in enumerate(manpage.paragraphs): if p.is_option: s, l = extract_option(p.cleantext())...
--- +++ @@ -7,6 +7,8 @@ logger = logging.getLogger(__name__) def extract(manpage): + '''extract options from all paragraphs that have been classified as containing + options''' for i, p in enumerate(manpage.paragraphs): if p.is_option: s, l = extract_option(p.cleantext()) @@ -48,10 +...
https://raw.githubusercontent.com/idank/explainshell/HEAD/explainshell/options.py
Generate docstrings with examples
# Copyright 2015 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or a...
--- +++ @@ -11,6 +11,15 @@ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. +"""Comment splicer for lib2to3 trees. + +The lib2to3 syntax tree produced by the parser holds comments and white...
https://raw.githubusercontent.com/google/yapf/HEAD/yapf/pytree/comment_splicer.py
Write reusable docstrings
import os, subprocess, re, logging, collections, urllib from explainshell import config, store, errors devnull = open(os.devnull, 'w') SPLITSYNOP = re.compile(r'([^ ]+) - (.*)$') ENV = dict(os.environ) ENV["W3MMAN_MAN"] = "man --no-hyphenation" ENV["MAN_KEEP_FORMATTING"] = "1" ENV["MANWIDTH"] = "115" ENV["LC_ALL"] =...
--- +++ @@ -14,11 +14,33 @@ logger = logging.getLogger(__name__) def extractname(gzname): + ''' + >>> extractname('ab.1.gz') + 'ab' + >>> extractname('ab.1.1.gz') + 'ab.1' + >>> extractname('ab.1xyz.gz') + 'ab' + >>> extractname('ab.1.1xyz.gz') + 'ab.1' + >>> extractname('a/b/c/ab.1.1xy...
https://raw.githubusercontent.com/idank/explainshell/HEAD/explainshell/manpage.py
Add docstrings to meet PEP guidelines
from __future__ import annotations from dataclasses import dataclass, field from typing import Any, Dict, List, Optional, Protocol, Sequence import json import re __all__ = [ "generate_tool_description", "generate_usage_context", "ToolDescriptionEvaluator", "ErrorMessageGenerator", "ToolSchemaBu...
--- +++ @@ -1,3 +1,28 @@+""" +Tool Description Engineering -- Generation and Evaluation Utilities. + +Use when: building, auditing, or iterating on tool descriptions for agent +systems. Provides templates for structured descriptions, a scoring evaluator +that flags vague or incomplete descriptions, error-message gener...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/tool-design/scripts/description_generator.py
Generate docstrings for each module
import hashlib import json from datetime import datetime from typing import Any, Dict, List, Optional import numpy as np __all__ = [ "VectorStore", "PropertyGraph", "TemporalKnowledgeGraph", "IntegratedMemorySystem", ] class VectorStore: def __init__(self, dimension: int = 768) -> None: ...
--- +++ @@ -1,3 +1,25 @@+"""Memory System Implementation. + +Provides composable building blocks for agent memory: vector stores with +metadata indexing, property graphs for entity relationships, and temporal +knowledge graphs for facts that change over time. + +Use when: + - Building a memory persistence layer for ...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/memory-systems/scripts/memory_store.py
Generate docstrings for each module
from dataclasses import dataclass, field from datetime import datetime, timedelta from typing import Optional, Callable, Any from enum import Enum import asyncio __all__ = [ "SandboxState", "UserIdentity", "SandboxConfig", "Sandbox", "RepositoryImage", "ImageBuilder", "WarmSandbox", "W...
--- +++ @@ -1,3 +1,17 @@+""" +Sandbox Manager for Hosted Agent Infrastructure. + +Use when: building background coding agents that need sandboxed execution +environments with pre-built images, warm pools, and session snapshots. + +This module provides composable building blocks for sandbox lifecycle +management. Each c...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/hosted-agents/scripts/sandbox_manager.py
Add return value explanations in docstrings
from dataclasses import dataclass, field from typing import List, Dict, Optional, Callable from enum import Enum import json import re __all__ = [ "ProbeType", "Probe", "CriterionResult", "EvaluationResult", "RUBRIC_CRITERIA", "ProbeGenerator", "CompressionEvaluator", "StructuredSummar...
--- +++ @@ -1,3 +1,38 @@+""" +Context Compression Evaluation + +Public API for evaluating context compression quality using probe-based +assessment. This module provides three composable components: + +- **ProbeGenerator**: Extracts factual claims, file operations, and decisions + from conversation history, then gener...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/context-compression/scripts/compression_evaluator.py
Create structured documentation for my script
from typing import Dict, List, Any, Optional from dataclasses import dataclass from enum import Enum import time __all__ = [ "ScoreLevel", "RubricDimension", "DEFAULT_RUBRIC", "AgentEvaluator", "TestSet", "EvaluationRunner", "ProductionMonitor", ] class ScoreLevel(Enum): EXCELLENT =...
--- +++ @@ -1,3 +1,18 @@+"""Agent Evaluation Framework for context-engineered agent systems. + +Use when: building evaluation pipelines, scoring agent outputs against +multi-dimensional rubrics, managing test sets, or monitoring production +agent quality. Provides composable classes that can be used independently +or w...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/evaluation/scripts/evaluator.py
Please document this code using docstrings
import random import re from typing import Dict, List, Optional __all__ = [ "measure_attention_distribution", "detect_lost_in_middle", "analyze_context_structure", "PoisoningDetector", "ContextHealthAnalyzer", "analyze_agent_context", ] # -----------------------------------------------------...
--- +++ @@ -1,3 +1,28 @@+""" +Context Degradation Detection — Public API +============================================ + +Detect, measure, and diagnose context degradation patterns in LLM agent systems. + +Public API: + measure_attention_distribution — Map attention weight across context positions. + detect_lost...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/context-degradation/scripts/degradation_detector.py
Write docstrings that follow conventions
from __future__ import annotations import hashlib from typing import Any, Dict, List, Optional __all__ = [ "estimate_token_count", "estimate_message_tokens", "count_tokens_by_type", "truncate_context", "truncate_messages", "validate_context_structure", "build_agent_context", "ContextB...
--- +++ @@ -1,3 +1,41 @@+""" +Context Management Utilities for Agent Systems. + +Public API +---------- +Functions: + estimate_token_count — Rough token estimate from text (demo only). + estimate_message_tokens — Token estimate for a message list. + count_tokens_by_type — Break down token usage by con...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/context-fundamentals/scripts/context_manager.py
Provide docstrings following PEP 257
from typing import Dict, List, Any, Optional from dataclasses import dataclass, field from enum import Enum import time import uuid __all__ = [ "MessageType", "AgentMessage", "AgentCommunication", "SupervisorAgent", "HandoffProtocol", "ConsensusManager", "AgentFailureHandler", ] class Me...
--- +++ @@ -1,3 +1,16 @@+""" +Multi-Agent Coordination Utilities + +Provides reusable building blocks for multi-agent coordination patterns: +supervisor/orchestrator, peer-to-peer handoffs, consensus mechanisms, +and failure handling with circuit breakers. + +Use when: building multi-agent systems that need structured ...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/multi-agent-patterns/scripts/coordination.py
Document this code for team use
import argparse import json import re import time from concurrent.futures import ThreadPoolExecutor, as_completed from dataclasses import dataclass, field, asdict from datetime import date from pathlib import Path from typing import Any __all__ = [ "Item", "ParsedResult", "stage_acquire", "stage_prepa...
--- +++ @@ -1,3 +1,31 @@+""" +LLM Batch Processing Pipeline Template. + +A composable, staged pipeline architecture for LLM batch processing. +Each stage is discrete, idempotent, and cacheable. Customize the acquire, +prepare, process, parse, and render functions for your use case. + +Use when: + - Building a new ba...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/project-development/scripts/pipeline_template.py
Help me add docstrings to my project
from typing import List, Dict, Optional, Tuple import hashlib import re import time __all__ = [ "estimate_token_count", "estimate_message_tokens", "categorize_messages", "summarize_content", "summarize_tool_output", "summarize_conversation", "summarize_document", "summarize_general", ...
--- +++ @@ -1,3 +1,36 @@+""" +Context Optimization Utilities — compaction, masking, budgeting, and cache optimization. + +Public API +---------- +Functions: + estimate_token_count(text) -> int + estimate_message_tokens(messages) -> int + categorize_messages(messages) -> dict + summarize_content(content, cat...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/context-optimization/scripts/compaction.py
Add docstrings to incomplete code
from __future__ import annotations import json import os import shutil from dataclasses import dataclass, field from datetime import datetime from pathlib import Path from typing import Any, Dict, List, Optional __all__: list[str] = [ "ScratchPadManager", "PlanStep", "AgentPlan", "ToolOutputHandler",...
--- +++ @@ -1,3 +1,27 @@+""" +Filesystem Context Manager -- composable utilities for filesystem-based context engineering. + +Provides three core patterns for managing agent context through the filesystem: +1. ScratchPadManager -- offload large tool outputs to files, return compact references +2. AgentPlan / PlanStep -...
https://raw.githubusercontent.com/muratcankoylan/Agent-Skills-for-Context-Engineering/HEAD/skills/filesystem-context/scripts/filesystem_context.py
Create simple docstrings for beginners
import io import math import os import re import tempfile import uuid import sys import warnings from datetime import datetime from functools import wraps from html import unescape from timeit import default_timer import argostranslatefiles from argostranslatefiles import get_supported_formats from flask import Bluepr...
--- +++ @@ -505,6 +505,33 @@ @bp.get("/languages") @limiter.exempt def langs(): + """ + Get Supported Languages + --- + tags: + - translate + responses: + 200: + description: List of supported languages + schema: + id:...
https://raw.githubusercontent.com/LibreTranslate/LibreTranslate/HEAD/libretranslate/app.py
Add docstrings to improve readability
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2015 Donne Martin. All Rights Reserved. # # Creative Commons Attribution 4.0 International License (CC BY 4.0) # http://creativecommons.org/licenses/by/4.0/ import click from awesome.awesome import Awesome pass_awesome = click.make_pass_decorator(Awesome) ...
--- +++ @@ -15,10 +15,16 @@ class AwesomeCli(object): + """Awesomeness in CLI form.""" @click.group() @click.pass_context def cli(ctx): + """Main entry point for AwesomeCli. + + :type ctx: :class:`click.core.Context` + :param ctx: Stores an instance of Awesome used to update...
https://raw.githubusercontent.com/donnemartin/awesome-aws/HEAD/awesome/awesome_cli.py
Add documentation for all methods
# coding: utf-8 # Copyright 2015 Donne Martin. All Rights Reserved. # # Creative Commons Attribution 4.0 International License (CC BY 4.0) # http://creativecommons.org/licenses/by/4.0/ import re import click from githubcli.lib.github3 import null from awesome.lib.github import GitHub class Awesome(object): d...
--- +++ @@ -14,6 +14,22 @@ class Awesome(object): + """Awesomeness. + + :type github: :class:`awesome.lib.GitHub` + :param github: Provides integration with the GitHub API. + + :type output: list + :param output: The updated README content. + + :type repos_broken: list + :param repos_broken: De...
https://raw.githubusercontent.com/donnemartin/awesome-aws/HEAD/awesome/awesome.py
Create Google-style docstrings for my code
# -*- coding: utf-8 -*- # Copyright 2015 Donne Martin. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). You # may not use this file except in compliance with the License. A copy of # the License is located at # # http://www.apache.org/licenses/LICENSE-2.0 # # or in the "lice...
--- +++ @@ -28,6 +28,27 @@ class GitHub(object): + """Provides integration with the GitHub API. + + Attributes: + * api: An instance of github3 to interact with the GitHub API. + * CONFIG: A string representing the config file name. + * CONFIG_SECTION: A string representing the main confi...
https://raw.githubusercontent.com/donnemartin/awesome-aws/HEAD/awesome/lib/github.py
Help me comply with documentation standards
import os import nbformat as nbf import mdutils def ktx_to_dict(input_file, keystarter='<'): answer = dict() with open(input_file, 'r+', encoding='utf-8') as f: lines = f.readlines() k, val = '', '' for line in lines: if line.startswith(keystarter): k = line.replace(keyst...
--- +++ @@ -4,6 +4,7 @@ def ktx_to_dict(input_file, keystarter='<'): + """ parsing keyed text to a python dictionary. """ answer = dict() with open(input_file, 'r+', encoding='utf-8') as f: @@ -24,6 +25,7 @@ def dict_to_ktx(input_dict, output_file, keystarter='<'): + """ Store a python diction...
https://raw.githubusercontent.com/rougier/numpy-100/HEAD/generators.py
Add docstrings that explain purpose and usage
import sys import asyncio from urllib.parse import urlparse, urlunparse, urljoin from concurrent.futures import ThreadPoolExecutor from concurrent.futures._base import TimeoutError from functools import partial from typing import Set, Union, List, MutableMapping, Optional import pyppeteer import requests import http.c...
--- +++ @@ -68,6 +68,14 @@ class BaseParser: + """A basic HTML/Element Parser, for Humans. + + :param element: The element from which to base the parsing upon. + :param default_encoding: Which encoding to default to. + :param html: HTML from which to base the parsing upon (optional). + :param url: Th...
https://raw.githubusercontent.com/psf/requests-html/HEAD/requests_html.py
Auto-generate documentation strings for this file
import ipaddress import os from dataclasses import dataclass from urllib.parse import urlparse from jose import jwt class ConfigurationError(Exception): pass @dataclass class EnvironmentConfig: supabase_url: str supabase_service_key: str port: int # Required - no default openai_api_key: str...
--- +++ @@ -1,3 +1,6 @@+""" +Environment configuration management for the MCP server. +""" import ipaddress import os @@ -8,12 +11,14 @@ class ConfigurationError(Exception): + """Raised when there's an error in configuration.""" pass @dataclass class EnvironmentConfig: + """Configuration load...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/config/config.py
Generate helpful docstrings for debugging
import logging import os from dataclasses import dataclass from datetime import datetime from typing import Any from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext from .base_agent import ArchonDependencies, BaseAgent from .mcp_client import get_mcp_client logger = logging.getLogger(__na...
--- +++ @@ -1,3 +1,10 @@+""" +RAG Agent - Conversational Search and Retrieval with PydanticAI + +This agent enables users to search and chat with documents stored in the RAG system. +It uses the perform_rag_query functionality to retrieve relevant content and provide +intelligent responses based on the retrieved inform...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agents/rag_agent.py
Generate docstrings for each module
import os from typing import Any import httpx from fastapi import APIRouter, HTTPException from pydantic import BaseModel from ..config.logfire_config import get_logger from ..config.version import GITHUB_REPO_NAME, GITHUB_REPO_OWNER logger = get_logger(__name__) router = APIRouter(prefix="/api/bug-report", tags=[...
--- +++ @@ -1,3 +1,8 @@+""" +Bug Report API for Archon Beta + +Handles bug report submission to GitHub Issues with automatic context formatting. +""" import os from typing import Any @@ -48,6 +53,7 @@ self.repo = os.getenv("GITHUB_REPO", default_repo) async def create_issue(self, bug_report: BugRepor...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/bug_report_api.py
Create docstrings for API functions
from datetime import datetime, timezone from enum import Enum from pydantic import BaseModel, Field, field_validator class AgentWorkOrderStatus(str, Enum): PENDING = "pending" RUNNING = "running" COMPLETED = "completed" FAILED = "failed" class AgentWorkflowType(str, Enum): PLAN = "agent_work...
--- +++ @@ -1,3 +1,7 @@+"""PRD-Compliant Pydantic Models + +All models follow exact naming from the PRD specification. +""" from datetime import datetime, timezone from enum import Enum @@ -6,6 +10,7 @@ class AgentWorkOrderStatus(str, Enum): + """Work order execution status""" PENDING = "pending" ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/models.py
Add docstrings to meet PEP guidelines
import asyncio import json import logging import os from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import Any import httpx import uvicorn from fastapi import FastAPI, HTTPException from fastapi.responses import StreamingResponse from pydantic import BaseModel # Impo...
--- +++ @@ -1,3 +1,13 @@+""" +Agents Service - Lightweight FastAPI server for PydanticAI agents + +This service ONLY hosts PydanticAI agents. It does NOT contain: +- ML models or embeddings (those are in Server) +- Direct database access (use MCP tools) +- Business logic (that's in Server) + +The agents use MCP tools f...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agents/server.py
Generate documentation strings for clarity
from ..models import SandboxType from .git_branch_sandbox import GitBranchSandbox from .git_worktree_sandbox import GitWorktreeSandbox from .sandbox_protocol import AgentSandbox class SandboxFactory: def create_sandbox( self, sandbox_type: SandboxType, repository_url: str, sandbo...
--- +++ @@ -1,3 +1,7 @@+"""Sandbox Factory + +Creates appropriate sandbox instances based on sandbox type. +""" from ..models import SandboxType from .git_branch_sandbox import GitBranchSandbox @@ -6,6 +10,7 @@ class SandboxFactory: + """Factory for creating sandbox instances""" def create_sandbox( ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/sandbox_manager/sandbox_factory.py
Generate docstrings with parameter types
from datetime import datetime, timezone from typing import Any from supabase import Client from ..database.client import get_agent_work_orders_client from ..models import ( AgentWorkOrderState, AgentWorkOrderStatus, StepExecutionResult, StepHistory, WorkflowStep, ) from ..utils.structured_logger ...
--- +++ @@ -1,3 +1,14 @@+"""Supabase-backed repository for agent work order state management. + +Provides ACID-compliant persistent storage for work order state using PostgreSQL +via Supabase. Implements the same interface as in-memory and file-based repositories +for seamless switching between storage backends. + +Arc...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/state_manager/supabase_repository.py
Add clean documentation to messy code
from datetime import datetime from enum import Enum from typing import Any from pydantic import BaseModel, Field, validator class DocumentType(str, Enum): PRD = "prd" FEATURE_PLAN = "feature_plan" ERD = "erd" TECHNICAL_SPEC = "technical_spec" USER_STORY = "user_story" API_SPEC = "api_spec" ...
--- +++ @@ -1,3 +1,11 @@+""" +Pydantic Models for Archon Project Management + +This module defines Pydantic models for: +- Project Requirements Document (PRD) structure +- General document schema for the docs table +- Project and task data models +""" from datetime import datetime from enum import Enum @@ -7,6 +15,...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/models.py
Add docstrings to existing functions
import hashlib import os import shutil import subprocess from pathlib import Path from typing import TYPE_CHECKING, Any from ..config import config from .port_allocation import create_ports_env_file if TYPE_CHECKING: import structlog def _get_repo_hash(repository_url: str) -> str: return hashlib.sha256(rep...
--- +++ @@ -1,3 +1,8 @@+"""Worktree management operations for isolated agent work order execution. + +Provides utilities for creating and managing git worktrees under trees/<work_order_id>/ +to enable parallel execution in isolated environments. +""" import hashlib import os @@ -14,22 +19,56 @@ def _get_repo_ha...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/worktree_operations.py
Add documentation for all methods
import os from typing import Optional try: from crawl4ai import AsyncWebCrawler, BrowserConfig except ImportError: AsyncWebCrawler = None BrowserConfig = None from ..config.logfire_config import get_logger, safe_logfire_error, safe_logfire_info logger = get_logger(__name__) class CrawlerManager: ...
--- +++ @@ -1,3 +1,9 @@+""" +Crawler Manager Service + +Handles initialization and management of the Crawl4AI crawler instance. +This avoids circular imports by providing a service-level access to the crawler. +""" import os from typing import Optional @@ -14,6 +20,7 @@ class CrawlerManager: + """Manages the...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawler_manager.py
Include argument descriptions in docstrings
import os from ..config import config from ..utils.structured_logger import get_logger from .file_state_repository import FileStateRepository from .supabase_repository import SupabaseWorkOrderRepository from .work_order_repository import WorkOrderRepository logger = get_logger(__name__) # Supported storage types SU...
--- +++ @@ -1,3 +1,8 @@+"""Repository Factory + +Creates appropriate repository instances based on configuration. +Supports in-memory (dev/testing), file-based (legacy), and Supabase (production) storage. +""" import os @@ -14,6 +19,14 @@ def create_repository() -> WorkOrderRepository | FileStateRepository | S...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/state_manager/repository_factory.py
Add docstrings to meet PEP guidelines
from pathlib import Path from ..config import config from ..models import CommandNotFoundError from ..utils.structured_logger import get_logger logger = get_logger(__name__) class ClaudeCommandLoader: def __init__(self, commands_directory: str | None = None): self.commands_directory = Path(commands_di...
--- +++ @@ -1,3 +1,7 @@+"""Claude Command Loader + +Loads command files from .claude/commands directory. +""" from pathlib import Path @@ -9,12 +13,25 @@ class ClaudeCommandLoader: + """Loads Claude command files""" def __init__(self, commands_directory: str | None = None): self.commands_dir...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/command_loader/claude_command_loader.py
Fill in missing docstrings in my code
import asyncio import os import subprocess import time from ..models import CommandExecutionResult, SandboxSetupError from ..utils.git_operations import get_current_branch from ..utils.port_allocation import find_available_port_range from ..utils.structured_logger import get_logger from ..utils.worktree_operations im...
--- +++ @@ -1,3 +1,8 @@+"""Git Worktree Sandbox Implementation + +Provides isolated execution environment using git worktrees. +Enables parallel execution of multiple work orders without conflicts. +""" import asyncio import os @@ -20,6 +25,12 @@ class GitWorktreeSandbox: + """Git worktree-based sandbox impl...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/sandbox_manager/git_worktree_sandbox.py
Add docstrings following best practices
import os from datetime import datetime, timezone from typing import Any from supabase import Client, create_client from ..models import ConfiguredRepository, SandboxType, WorkflowStep from ..utils.structured_logger import get_logger logger = get_logger(__name__) def get_supabase_client() -> Client: url = os....
--- +++ @@ -1,3 +1,8 @@+"""Repository Configuration Repository + +Provides database operations for managing configured GitHub repositories. +Stores repository metadata, verification status, and per-repository preferences. +""" import os from datetime import datetime, timezone @@ -12,6 +17,14 @@ def get_supabase...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/state_manager/repository_config_repository.py
Create docstrings for API functions
import asyncio import json import logging from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP from src.mcp_server.utils.error_handling import MCPErrorFormatter from src.mcp_server.utils.timeout_config import ( get_default_timeout, get_max_polling_attempts, get_po...
--- +++ @@ -1,3 +1,8 @@+""" +Consolidated project management tools for Archon MCP Server. + +Reduces the number of individual CRUD operations while maintaining full functionality. +""" import asyncio import json @@ -23,11 +28,13 @@ DEFAULT_PAGE_SIZE = 10 # Reduced from 50 def truncate_text(text: str, max_length...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/projects/project_tools.py
Write docstrings describing functionality
import time from ..agent_executor.agent_cli_executor import AgentCLIExecutor from ..command_loader.claude_command_loader import ClaudeCommandLoader from ..github_integration.github_client import GitHubClient from ..models import ( AgentWorkOrderStatus, SandboxType, StepHistory, WorkflowExecutionError,...
--- +++ @@ -1,3 +1,7 @@+"""Workflow Orchestrator + +Main orchestration logic for workflow execution. +""" import time @@ -26,6 +30,7 @@ class WorkflowOrchestrator: + """Orchestrates workflow execution""" def __init__( self, @@ -51,6 +56,18 @@ selected_commands: list[str] | None = Non...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/workflow_engine/workflow_orchestrator.py
Write docstrings for this repository
import re from pydantic import BaseModel class LLMsFullSection(BaseModel): section_title: str # Raw H1 text: "# Core Concepts" section_order: int # Position in document: 0, 1, 2, ... content: str # Section content (including H1 header) url: str # Synthetic URL: base.txt#core-concepts word_c...
--- +++ @@ -1,3 +1,9 @@+""" +LLMs-full.txt Section Parser + +Parses llms-full.txt files by splitting on H1 headers (# ) to create separate +"pages" for each section. Each section gets a synthetic URL with a slug anchor. +""" import re @@ -5,6 +11,7 @@ class LLMsFullSection(BaseModel): + """Parsed section fr...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/helpers/llms_full_parser.py
Help me document legacy Python code
import json import logging from typing import Any from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP from src.mcp_server.utils.error_handling import MCPErrorFormatter from src.mcp_server.utils.timeout_config import get_default_timeout from src.server.config.service_discover...
--- +++ @@ -1,3 +1,8 @@+""" +Consolidated version management tools for Archon MCP Server. + +Reduces the number of individual CRUD operations while maintaining full functionality. +""" import json import logging @@ -17,6 +22,7 @@ DEFAULT_PAGE_SIZE = 10 def optimize_version_response(version: dict) -> dict: + "...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/documents/version_tools.py
Add documentation for all methods
import os from pathlib import Path def get_project_root() -> Path: # This file is in python/src/agent_work_orders/config.py # So go up 3 levels to get to project root return Path(__file__).parent.parent.parent.parent class AgentWorkOrdersConfig: # Feature flag - allows disabling agent work orders ...
--- +++ @@ -1,15 +1,21 @@+"""Configuration Management + +Loads configuration from environment variables with sensible defaults. +""" import os from pathlib import Path def get_project_root() -> Path: + """Get the project root directory (one level up from python/)""" # This file is in python/src/agent_w...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/config.py
Provide clean and structured docstrings
from datetime import datetime import logfire from fastapi import APIRouter, Header, HTTPException, Response from pydantic import BaseModel from ..config.version import ARCHON_VERSION from ..services.migration_service import migration_service from ..utils.etag_utils import check_etag, generate_etag # Response model...
--- +++ @@ -1,3 +1,6 @@+""" +API routes for database migration tracking and management. +""" from datetime import datetime @@ -12,6 +15,7 @@ # Response models class MigrationRecord(BaseModel): + """Represents an applied migration.""" version: str migration_name: str @@ -20,6 +24,7 @@ class Pe...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/migration_api.py
Write docstrings describing functionality
from collections.abc import AsyncIterator from contextlib import asynccontextmanager import httpx from .timeout_config import get_default_timeout, get_polling_timeout @asynccontextmanager async def get_http_client( timeout: httpx.Timeout | None = None, for_polling: bool = False ) -> AsyncIterator[httpx.AsyncCl...
--- +++ @@ -1,3 +1,8 @@+""" +HTTP client utilities for MCP Server. + +Provides consistent HTTP client configuration. +""" from collections.abc import AsyncIterator from contextlib import asynccontextmanager @@ -11,9 +16,23 @@ async def get_http_client( timeout: httpx.Timeout | None = None, for_polling: bool = ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/utils/http_client.py
Add detailed documentation for each class
import os import socket # Port allocation configuration PORT_RANGE_SIZE = 10 # Each work order gets 10 ports PORT_BASE = 9000 # Starting port MAX_CONCURRENT_WORK_ORDERS = 20 # 200 ports / 10 = 20 concurrent def get_port_range_for_work_order(work_order_id: str) -> tuple[int, int]: # Convert work order ID to s...
--- +++ @@ -1,3 +1,15 @@+"""Port allocation utilities for isolated agent work order execution. + +Provides deterministic port range allocation (10 ports per work order) +based on work order ID to enable parallel execution without port conflicts. + +Architecture: +- Each work order gets a range of 10 consecutive ports +...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/port_allocation.py
Write docstrings for data processing functions
import json import logging import os import sys import threading import time import traceback from collections.abc import AsyncIterator from contextlib import asynccontextmanager from dataclasses import dataclass from datetime import datetime from pathlib import Path from typing import Any from dotenv import load_dot...
--- +++ @@ -1,3 +1,18 @@+""" +MCP Server for Archon (Microservices Version) + +This is the MCP server that uses HTTP calls to other services +instead of importing heavy dependencies directly. This significantly reduces +the container size from 1.66GB to ~150MB. + +Modules: +- RAG Module: RAG queries, search, and source...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/mcp_server.py
Add professional docstrings to my codebase
import os from typing import Any import httpx from fastapi import APIRouter, HTTPException # Import unified logging from ..config.config import get_mcp_monitoring_config from ..config.logfire_config import api_logger, safe_set_attribute, safe_span from ..config.service_discovery import get_mcp_url router = APIRoute...
--- +++ @@ -1,3 +1,12 @@+""" +MCP API endpoints for Archon + +Provides status and configuration endpoints for the MCP service. +The MCP container is managed by docker-compose, not by this API. + +Status monitoring uses HTTP health checks by default (secure, portable). +Docker socket mode available via ENABLE_DOCKER_SOC...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/mcp_api.py
Add docstrings to improve code quality
from datetime import datetime from email.utils import formatdate from fastapi import APIRouter, Header, HTTPException, Response from fastapi import status as http_status from ..config.logfire_config import get_logger, logfire from ..models.progress_models import create_progress_response from ..utils.etag_utils impor...
--- +++ @@ -1,3 +1,4 @@+"""Progress API endpoints for polling operation status.""" from datetime import datetime from email.utils import formatdate @@ -24,6 +25,12 @@ response: Response, if_none_match: str | None = Header(None) ): + """ + Get progress for an operation with ETag support. + + Retur...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/progress_api.py
Fill in missing docstrings in my code
import secrets def generate_work_order_id() -> str: return f"wo-{secrets.token_hex(4)}" def generate_sandbox_identifier(agent_work_order_id: str) -> str: return f"sandbox-{agent_work_order_id}"
--- +++ @@ -1,10 +1,30 @@+"""ID Generation Utilities + +Generates unique identifiers for work orders and other entities. +""" import secrets def generate_work_order_id() -> str: + """Generate a unique work order ID + + Format: wo-{random_hex} + Example: wo-a3c2f1e4 + + Returns: + Unique work ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/id_generator.py
Write beginner-friendly docstrings
import os import shutil import subprocess from collections.abc import AsyncGenerator from contextlib import asynccontextmanager from typing import Any import httpx from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .api.routes import log_buffer, router from .config import config from...
--- +++ @@ -1,3 +1,7 @@+"""Standalone Server Entry Point + +FastAPI server for independent agent work order service. +""" import os import shutil @@ -21,6 +25,7 @@ @asynccontextmanager async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]: + """Lifespan context manager for startup and shutdown tasks"...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/server.py
Add docstrings with type hints explained
import json import logging from typing import Any import httpx logger = logging.getLogger(__name__) class MCPClient: def __init__(self, mcp_url: str = None): if mcp_url: self.mcp_url = mcp_url else: # Use service discovery to find MCP server try: ...
--- +++ @@ -1,3 +1,10 @@+""" +MCP Client for Agents + +This lightweight client allows PydanticAI agents to call MCP tools via HTTP. +Agents use this client to access all data operations through the MCP protocol +instead of direct database access or service imports. +""" import json import logging @@ -9,8 +16,15 @@ ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agents/mcp_client.py
Write docstrings for backend logic
from fastapi import APIRouter, HTTPException, Query from pydantic import BaseModel from ..config.logfire_config import get_logger, safe_logfire_error from ..utils import get_supabase_client # Get logger for this module logger = get_logger(__name__) # Create router router = APIRouter(prefix="/api", tags=["pages"]) ...
--- +++ @@ -1,3 +1,11 @@+""" +Pages API Module + +This module handles page retrieval operations for RAG: +- List pages for a source +- Get page by ID +- Get page by URL +""" from fastapi import APIRouter, HTTPException, Query from pydantic import BaseModel @@ -16,6 +24,7 @@ class PageSummary(BaseModel): + ""...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/pages_api.py
Create structured documentation for my script
import asyncio import json from collections.abc import AsyncGenerator from datetime import UTC, datetime from typing import Any from ..utils.log_buffer import WorkOrderLogBuffer async def stream_work_order_logs( work_order_id: str, log_buffer: WorkOrderLogBuffer, level_filter: str | None = None, ste...
--- +++ @@ -1,3 +1,8 @@+"""Server-Sent Events (SSE) Streaming for Work Order Logs + +Implements SSE streaming endpoint for real-time log delivery. +Uses sse-starlette for W3C SSE specification compliance. +""" import asyncio import json @@ -15,6 +20,31 @@ step_filter: str | None = None, since_timestamp: st...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/api/sse_streams.py
Add docstrings to improve collaboration
import json import logging from typing import Any from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP from src.mcp_server.utils.error_handling import MCPErrorFormatter from src.mcp_server.utils.timeout_config import get_default_timeout from src.server.config.service_discover...
--- +++ @@ -1,3 +1,8 @@+""" +Consolidated task management tools for Archon MCP Server. + +Reduces the number of individual CRUD operations while maintaining full functionality. +""" import json import logging @@ -18,11 +23,13 @@ DEFAULT_PAGE_SIZE = 10 # Reduced from 50 def truncate_text(text: str, max_length: i...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/tasks/task_tools.py
Add docstrings with type hints explained
import logging import uuid from datetime import datetime from fastapi import APIRouter, HTTPException from pydantic import BaseModel logger = logging.getLogger(__name__) # Create router router = APIRouter(prefix="/api/agent-chat", tags=["agent-chat"]) # Simple in-memory session storage sessions: dict[str, dict] = ...
--- +++ @@ -1,3 +1,6 @@+""" +Agent Chat API - Polling-based chat with SSE proxy to AI agents +""" import logging import uuid @@ -32,6 +35,7 @@ # REST Endpoints (minimal for frontend compatibility) @router.post("/sessions") async def create_session(request: CreateSessionRequest): + """Create a new chat session....
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/agent_chat_api.py
Improve documentation using docstrings
import httpx from fastapi import APIRouter, HTTPException, Path from ..config.logfire_config import logfire from ..services.credential_service import credential_service # Provider validation - simplified inline version router = APIRouter(prefix="/api/providers", tags=["providers"]) async def test_openai_connection...
--- +++ @@ -1,3 +1,8 @@+""" +Provider status API endpoints for testing connectivity + +Handles server-side provider connectivity testing without exposing API keys to frontend. +""" import httpx from fastapi import APIRouter, HTTPException, Path @@ -10,6 +15,7 @@ async def test_openai_connection(api_key: str) ->...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/providers_api.py
Document all public functions with docstrings
import json import logging from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP from src.mcp_server.utils.error_handling import MCPErrorFormatter from src.mcp_server.utils.timeout_config import get_default_timeout from src.server.config.service_discovery import get_api_url l...
--- +++ @@ -1,3 +1,8 @@+""" +Simple feature management tools for Archon MCP Server. + +Provides tools to retrieve and manage project features. +""" import json import logging @@ -14,9 +19,57 @@ def register_feature_tools(mcp: FastMCP): + """Register feature management tools with the MCP server.""" @mc...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/feature_tools.py
Write docstrings for data processing functions
from datetime import datetime from typing import Any from fastapi import APIRouter, HTTPException from pydantic import BaseModel # Import logging from ..config.logfire_config import logfire from ..services.credential_service import credential_service, initialize_credentials from ..utils import get_supabase_client r...
--- +++ @@ -1,3 +1,11 @@+""" +Settings API endpoints for Archon + +Handles: +- OpenAI API key management +- Other credentials and configuration +- Settings storage and retrieval +""" from datetime import datetime from typing import Any @@ -36,6 +44,7 @@ # Credential Management Endpoints @router.get("/credentials")...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/settings_api.py
Create docstrings for each class method
import ipaddress import socket from html.parser import HTMLParser from urllib.parse import urljoin, urlparse import requests from ...config.logfire_config import get_logger logger = get_logger(__name__) class SitemapHTMLParser(HTMLParser): def __init__(self): super().__init__() self.sitemaps ...
--- +++ @@ -1,3 +1,9 @@+""" +Discovery Service for Automatic File Detection + +Handles automatic discovery and parsing of llms.txt, sitemap.xml, and related files +to enhance crawling capabilities with priority-based discovery methods. +""" import ipaddress import socket @@ -12,12 +18,14 @@ class SitemapHTMLPar...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/discovery_service.py
Document functions with detailed explanations
import asyncio import json import re from ..config import config from ..models import GitHubOperationError, GitHubPullRequest, GitHubRepository from ..utils.structured_logger import get_logger logger = get_logger(__name__) class GitHubClient: def __init__(self, gh_cli_path: str | None = None): self.gh...
--- +++ @@ -1,3 +1,7 @@+"""GitHub Client + +Handles GitHub operations via gh CLI. +""" import asyncio import json @@ -11,12 +15,21 @@ class GitHubClient: + """GitHub operations using gh CLI""" def __init__(self, gh_cli_path: str | None = None): self.gh_cli_path = gh_cli_path or config.GH_CLI_...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/github_integration/github_client.py
Add detailed docstrings explaining each function
import json import logging import os from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP # Import service discovery for HTTP communication from src.server.config.service_discovery import get_api_url logger = logging.getLogger(__name__) def get_setting(key: str, default: s...
--- +++ @@ -1,3 +1,14 @@+""" +RAG Module for Archon MCP Server (HTTP-based version) + +This module provides tools for: +- RAG query and search +- Source management +- Code example extraction and search + +This version uses HTTP calls to the server service instead of importing +service modules directly, enabling true mi...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/rag/rag_tools.py
Create docstrings for reusable components
import asyncio import shutil import time from pathlib import Path from ..config import config from ..models import CommandExecutionResult, SandboxSetupError from ..utils.git_operations import get_current_branch from ..utils.structured_logger import get_logger logger = get_logger(__name__) class GitBranchSandbox: ...
--- +++ @@ -1,3 +1,8 @@+"""Git Branch Sandbox Implementation + +Provides isolated execution environment using git branches. +Agent creates the branch during execution (git-first philosophy). +""" import asyncio import shutil @@ -13,6 +18,11 @@ class GitBranchSandbox: + """Git branch-based sandbox implementat...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/sandbox_manager/git_branch_sandbox.py
Write docstrings including parameters and return values
import asyncio from datetime import datetime from ..models import AgentWorkOrderState, AgentWorkOrderStatus, StepHistory from ..utils.structured_logger import get_logger logger = get_logger(__name__) class WorkOrderRepository: def __init__(self): self._work_orders: dict[str, AgentWorkOrderState] = {} ...
--- +++ @@ -1,3 +1,8 @@+"""Work Order Repository + +In-memory storage for agent work orders (MVP). +TODO Phase 2+: Migrate to Supabase persistence. +""" import asyncio from datetime import datetime @@ -9,6 +14,11 @@ class WorkOrderRepository: + """In-memory repository for work order state + + Stores minim...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/state_manager/work_order_repository.py
Write docstrings for utility functions
import asyncio import json import time from pathlib import Path from ..config import config from ..models import CommandExecutionResult from ..utils.structured_logger import get_logger logger = get_logger(__name__) class AgentCLIExecutor: def __init__(self, cli_path: str | None = None): self.cli_path ...
--- +++ @@ -1,3 +1,7 @@+"""Agent CLI Executor + +Executes Claude CLI commands for agent workflows. +""" import asyncio import json @@ -12,6 +16,7 @@ class AgentCLIExecutor: + """Executes Claude CLI commands""" def __init__(self, cli_path: str | None = None): self.cli_path = cli_path or config...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/agent_executor/agent_cli_executor.py
Generate consistent docstrings
import time from collections.abc import Callable from fastapi import Request, Response from fastapi.routing import APIRoute from starlette.middleware.base import BaseHTTPMiddleware from ..config.logfire_config import LOGFIRE_AVAILABLE, get_logger, is_logfire_enabled class LoggingMiddleware(BaseHTTPMiddleware): ...
--- +++ @@ -1,3 +1,9 @@+""" +Logging Middleware for FastAPI + +Automatically logs requests and responses using logfire when available. +Follows 2025 best practices for simple, automatic instrumentation. +""" import time from collections.abc import Callable @@ -10,6 +16,11 @@ class LoggingMiddleware(BaseHTTPMidd...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/middleware/logging_middleware.py
Generate missing documentation strings
import asyncio from collections.abc import Callable from typing import Any from ...config.logfire_config import get_logger, safe_logfire_error, safe_logfire_info from ..source_management_service import extract_source_summary, update_source_info from ..storage.document_storage_service import add_documents_to_supabase ...
--- +++ @@ -1,3 +1,9 @@+""" +Document Storage Operations + +Handles the storage and processing of crawled documents. +Extracted from crawl_orchestration_service.py for better modularity. +""" import asyncio from collections.abc import Callable @@ -13,8 +19,17 @@ class DocumentStorageOperations: + """ + Ha...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/document_storage_operations.py
Add docstrings for production code
import asyncio import logging import time from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Generic, TypeVar from pydantic import BaseModel from pydantic_ai import Agent logger = logging.getLogger(__name__) @dataclass class ArchonDependencies: request_id: str | None...
--- +++ @@ -1,3 +1,8 @@+""" +Base Agent class for all PydanticAI agents in the Archon system. + +This provides common functionality and dependency injection for all agents. +""" import asyncio import logging @@ -14,6 +19,7 @@ @dataclass class ArchonDependencies: + """Base dependencies for all Archon agents.""...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agents/base_agent.py
Add inline docstrings for readability
import subprocess from pathlib import Path async def get_commit_count(branch_name: str, repo_path: str | Path, base_branch: str = "main") -> int: try: result = subprocess.run( ["git", "rev-list", "--count", f"origin/{base_branch}..{branch_name}"], cwd=str(repo_path), c...
--- +++ @@ -1,9 +1,23 @@+"""Git Operations Utilities + +Helper functions for git operations and inspection. +""" import subprocess from pathlib import Path async def get_commit_count(branch_name: str, repo_path: str | Path, base_branch: str = "main") -> int: + """Get the number of commits added on a branch ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/git_operations.py
Include argument descriptions in docstrings
from typing import Any, Literal from pydantic import BaseModel, ConfigDict, Field, field_validator class ProgressDetails(BaseModel): current_chunk: int | None = Field(None, alias="currentChunk") total_chunks: int | None = Field(None, alias="totalChunks") current_batch: int | None = Field(None, alias="c...
--- +++ @@ -1,3 +1,4 @@+"""Standardized progress response models for consistent API responses.""" from typing import Any, Literal @@ -5,6 +6,7 @@ class ProgressDetails(BaseModel): + """Detailed progress information for granular tracking.""" current_chunk: int | None = Field(None, alias="currentChunk"...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/models/progress_models.py
Create documentation strings for testing functions
from datetime import datetime from typing import Any import logfire from fastapi import APIRouter, Header, HTTPException, Response from pydantic import BaseModel from ..config.version import ARCHON_VERSION from ..services.version_service import version_service from ..utils.etag_utils import check_etag, generate_etag...
--- +++ @@ -1,3 +1,6 @@+""" +API routes for version checking and update management. +""" from datetime import datetime from typing import Any @@ -13,6 +16,7 @@ # Response models class ReleaseAsset(BaseModel): + """Represents a downloadable asset from a release.""" name: str size: int @@ -22,6 +26,...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/version_api.py
Generate consistent docstrings
import json from datetime import datetime from typing import Any from fastapi import APIRouter, BackgroundTasks, HTTPException, Query from pydantic import BaseModel, Field from ..config.logfire_config import get_logger from ..services.llm_provider_service import validate_provider_instance from ..services.ollama.embe...
--- +++ @@ -1,3 +1,12 @@+""" +Ollama API endpoints for model discovery and health management. + +Provides comprehensive REST endpoints for interacting with Ollama instances: +- Model discovery across multiple instances +- Health monitoring and status checking +- Instance validation and capability testing +- Embedding r...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/ollama_api.py
Provide docstrings following PEP 257
import logging import httpx from fastapi import APIRouter, HTTPException, Request, Response from ..config.service_discovery import get_agent_work_orders_url logger = logging.getLogger(__name__) router = APIRouter(prefix="/api/agent-work-orders", tags=["agent-work-orders"]) @router.api_route( "/{path:path}", ...
--- +++ @@ -1,3 +1,8 @@+"""Agent Work Orders API Gateway Proxy + +Proxies requests from the main API to the independent agent work orders service. +This provides a single API entry point for the frontend while maintaining service independence. +""" import logging @@ -16,6 +21,21 @@ response_class=Response, ) ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/agent_work_orders_proxy.py
Insert docstrings into my code
import logging import os from contextlib import contextmanager from typing import Any # Try to import logfire (optional dependency) LOGFIRE_AVAILABLE = False logfire = None try: import logfire LOGFIRE_AVAILABLE = True except ImportError: logfire = None # Global state _logfire_configured = False _logfir...
--- +++ @@ -1,3 +1,19 @@+""" +Unified Logging Configuration for Archon (2025 Best Practices) + +This module provides a clean, unified logging setup with optional Pydantic Logfire integration. +Simple toggle: LOGFIRE_ENABLED=true/false controls all logging behavior. + +Usage: + from .config.logfire_config import get_...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/config/logfire_config.py
Write proper docstrings for these functions
import logging import os from contextlib import asynccontextmanager from fastapi import FastAPI, Response from fastapi.middleware.cors import CORSMiddleware from .api_routes.agent_chat_api import router as agent_chat_router from .api_routes.agent_work_orders_proxy import router as agent_work_orders_router from .api_...
--- +++ @@ -1,3 +1,15 @@+""" +FastAPI Backend for Archon Knowledge Engine + +This is the main entry point for the Archon backend API. +It uses a modular approach with separate API modules for different functionality. + +Modules: +- settings_api: Settings and credentials management +- mcp_api: MCP server management and ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/main.py
Can you add docstrings to this Python file?
import time from ..agent_executor.agent_cli_executor import AgentCLIExecutor from ..command_loader.claude_command_loader import ClaudeCommandLoader from ..models import StepExecutionResult, WorkflowStep from ..utils.structured_logger import get_logger from .agent_names import ( BRANCH_CREATOR, COMMITTER, ...
--- +++ @@ -1,3 +1,8 @@+"""Workflow Operations + +Command execution functions for user-selectable workflow. +Each function loads and executes a command file. +""" import time @@ -24,6 +29,20 @@ working_dir: str, context: dict, ) -> StepExecutionResult: + """Execute create-branch.md command + + Crea...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/workflow_engine/workflow_operations.py
Auto-generate documentation strings for this file
from typing import Protocol from ..models import CommandExecutionResult class AgentSandbox(Protocol): sandbox_identifier: str repository_url: str working_dir: str async def setup(self) -> None: ... async def execute_command(self, command: str, timeout: int = 300) -> CommandExecutionRe...
--- +++ @@ -1,3 +1,7 @@+"""Sandbox Protocol + +Defines the interface that all sandbox implementations must follow. +""" from typing import Protocol @@ -5,19 +9,48 @@ class AgentSandbox(Protocol): + """Protocol for agent sandbox implementations + + All sandbox types must implement this interface to provid...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/sandbox_manager/sandbox_protocol.py
Add docstrings for better understanding
import asyncio from datetime import datetime from typing import Any, Callable from fastapi import APIRouter, HTTPException, Query from sse_starlette.sse import EventSourceResponse from ..agent_executor.agent_cli_executor import AgentCLIExecutor from ..command_loader.claude_command_loader import ClaudeCommandLoader f...
--- +++ @@ -1,3 +1,7 @@+"""API Routes + +FastAPI routes for agent work orders. +""" import asyncio from datetime import datetime @@ -43,7 +47,20 @@ def _create_task_done_callback(agent_work_order_id: str) -> Callable[[asyncio.Task], None]: + """Create a done callback for workflow tasks + + Logs except...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/api/routes.py
Add docstrings to improve code quality
import os import httpx def get_default_timeout() -> httpx.Timeout: return httpx.Timeout( timeout=float(os.getenv("MCP_REQUEST_TIMEOUT", "30.0")), connect=float(os.getenv("MCP_CONNECT_TIMEOUT", "5.0")), read=float(os.getenv("MCP_READ_TIMEOUT", "20.0")), write=float(os.getenv("MCP_...
--- +++ @@ -1,3 +1,8 @@+""" +Centralized timeout configuration for MCP Server. + +Provides consistent timeout values across all tools. +""" import os @@ -5,6 +10,18 @@ def get_default_timeout() -> httpx.Timeout: + """ + Get default timeout configuration from environment or defaults. + + Environment va...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/utils/timeout_config.py
Add docstrings to improve code quality
import json import logging from typing import Any import httpx logger = logging.getLogger(__name__) class MCPErrorFormatter: @staticmethod def format_error( error_type: str, message: str, details: dict[str, Any] | None = None, suggestion: str | None = None, http_sta...
--- +++ @@ -1,3 +1,8 @@+""" +Centralized error handling utilities for MCP Server. + +Provides consistent error formatting and helpful context for clients. +""" import json import logging @@ -9,6 +14,7 @@ class MCPErrorFormatter: + """Formats errors consistently for MCP clients.""" @staticmethod d...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/utils/error_handling.py
Document classes and their methods
import logging import os from typing import Any from fastapi import APIRouter, HTTPException, Request from ..services.credential_service import credential_service logger = logging.getLogger(__name__) # Create router with internal prefix router = APIRouter(prefix="/internal", tags=["internal"]) # Simple IP-based a...
--- +++ @@ -1,3 +1,9 @@+""" +Internal API endpoints for inter-service communication. + +These endpoints are meant to be called only by other services in the Archon system, +not by external clients. They provide internal functionality like credential sharing. +""" import logging import os @@ -22,6 +28,7 @@ def i...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/internal_api.py
Write documentation strings for class attributes
import json import logging import os import uuid from dataclasses import dataclass from datetime import datetime, timedelta from typing import Any from pydantic import BaseModel, Field from pydantic_ai import Agent, RunContext from .base_agent import ArchonDependencies, BaseAgent from .mcp_client import get_mcp_clie...
--- +++ @@ -1,3 +1,10 @@+""" +DocumentAgent - Conversational Document Management with PydanticAI + +This agent enables users to create, update, and modify project documents through +natural conversation. It uses the established Pydantic AI patterns and integrates +with our existing MCP project management tools. +""" ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agents/document_agent.py
Can you add docstrings to this Python file?
import asyncio import json import uuid from datetime import datetime from urllib.parse import urlparse from fastapi import APIRouter, File, Form, HTTPException, UploadFile from pydantic import BaseModel # Basic validation - simplified inline version # Import unified logging from ..config.logfire_config import get_l...
--- +++ @@ -1,1280 +1,1349 @@- -import asyncio -import json -import uuid -from datetime import datetime -from urllib.parse import urlparse - -from fastapi import APIRouter, File, Form, HTTPException, UploadFile -from pydantic import BaseModel - -# Basic validation - simplified inline version - -# Import unified logging...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/knowledge_api.py
Add return value explanations in docstrings
import os import re from supabase import Client, create_client from ..config.logfire_config import search_logger def get_supabase_client() -> Client: url = os.getenv("SUPABASE_URL") key = os.getenv("SUPABASE_SERVICE_KEY") if not url or not key: raise ValueError( "SUPABASE_URL and S...
--- +++ @@ -1,3 +1,8 @@+""" +Client Manager Service + +Manages database and API client connections. +""" import os import re @@ -8,6 +13,12 @@ def get_supabase_client() -> Client: + """ + Get a Supabase client instance. + + Returns: + Supabase client instance + """ url = os.getenv("SUPAB...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/client_manager.py
Generate consistent docstrings
import asyncio import re from collections.abc import Callable from typing import Any from ...config.logfire_config import safe_logfire_error, safe_logfire_info from ...services.credential_service import credential_service from ..storage.code_storage_service import ( add_code_examples_to_supabase, generate_cod...
--- +++ @@ -1,3 +1,8 @@+""" +Code Extraction Service + +Handles extraction, processing, and storage of code examples from documents. +""" import asyncio import re @@ -13,6 +18,9 @@ class CodeExtractionService: + """ + Service for extracting and processing code examples from documents. + """ # La...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/code_extraction_service.py
Help me write clear docstrings
import asyncio import uuid from collections.abc import Awaitable, Callable from typing import Any, Optional import tldextract from ...config.logfire_config import get_logger, safe_logfire_error, safe_logfire_info from ...utils import get_supabase_client from ...utils.progress.progress_tracker import ProgressTracker ...
--- +++ @@ -1,3 +1,10 @@+""" +Crawling Service Module for Archon RAG + +This module combines crawling functionality and orchestration. +It handles web crawling operations including single page crawling, +batch crawling, recursive crawling, and overall orchestration with progress tracking. +""" import asyncio import...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/crawling_service.py
Create documentation strings for testing functions
import asyncio import threading import time from collections import defaultdict, deque from datetime import UTC, datetime from typing import Any class WorkOrderLogBuffer: MAX_LOGS_PER_WORK_ORDER = 1000 CLEANUP_THRESHOLD_HOURS = 1 def __init__(self) -> None: self._buffers: dict[str, deque[dict[s...
--- +++ @@ -1,3 +1,8 @@+"""In-Memory Log Buffer for Agent Work Orders + +Thread-safe circular buffer to store recent logs for SSE streaming. +Automatically cleans up old work orders to prevent memory leaks. +""" import asyncio import threading @@ -8,11 +13,18 @@ class WorkOrderLogBuffer: + """Thread-safe cir...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/log_buffer.py
Include argument descriptions in docstrings
import os from enum import Enum from urllib.parse import urlparse import httpx class Environment(Enum): DOCKER_COMPOSE = "docker_compose" LOCAL = "local" class ServiceDiscovery: def __init__(self): # Get ports during initialization server_port = os.getenv("ARCHON_SERVER_PORT") ...
--- +++ @@ -1,3 +1,9 @@+""" +Service Discovery module for Docker and local development environments + +This module provides service discovery capabilities that work seamlessly +across Docker Compose and local development environments. +""" import os from enum import Enum @@ -7,12 +13,19 @@ class Environment(Enu...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/config/service_discovery.py
Add docstrings to incomplete code
import json from datetime import datetime, timezone from email.utils import format_datetime from typing import Any from fastapi import APIRouter, Header, HTTPException, Request, Response from fastapi import status as http_status from pydantic import BaseModel # Removed direct logging import - using unified config # ...
--- +++ @@ -1,3 +1,12 @@+""" +Projects API endpoints for Archon + +Handles: +- Project management (CRUD operations) +- Task management with hierarchical structure +- Streaming project creation with DocumentAgent integration +- HTTP polling for progress updates +""" import json from datetime import datetime, timezon...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/projects_api.py
Add docstrings for better understanding
from fastapi import APIRouter from ..services.openrouter_discovery_service import OpenRouterModelListResponse, openrouter_discovery_service router = APIRouter(prefix="/api/openrouter", tags=["openrouter"]) @router.get("/models", response_model=OpenRouterModelListResponse) async def get_openrouter_models() -> OpenR...
--- +++ @@ -1,3 +1,8 @@+""" +OpenRouter API routes. + +Endpoints for OpenRouter model discovery and configuration. +""" from fastapi import APIRouter @@ -8,6 +13,15 @@ @router.get("/models", response_model=OpenRouterModelListResponse) async def get_openrouter_models() -> OpenRouterModelListResponse: + """ + ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/api_routes/openrouter_api.py
Expand my code with proper documentation strings
import asyncio import json from datetime import datetime, timezone from pathlib import Path from typing import TYPE_CHECKING, Any, cast from ..models import AgentWorkOrderState, AgentWorkOrderStatus, StepHistory from ..utils.structured_logger import get_logger if TYPE_CHECKING: import structlog logger = get_log...
--- +++ @@ -1,3 +1,8 @@+"""File-based Work Order Repository + +Provides persistent JSON-based storage for agent work orders. +Enables state persistence across service restarts and debugging. +""" import asyncio import json @@ -15,6 +20,11 @@ class FileStateRepository: + """File-based repository for work orde...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/state_manager/file_state_repository.py
Add docstrings to improve collaboration
import json import logging from typing import Any from urllib.parse import urljoin import httpx from mcp.server.fastmcp import Context, FastMCP from src.mcp_server.utils.error_handling import MCPErrorFormatter from src.mcp_server.utils.timeout_config import get_default_timeout from src.server.config.service_discover...
--- +++ @@ -1,3 +1,8 @@+""" +Consolidated document management tools for Archon MCP Server. + +Reduces the number of individual CRUD operations while maintaining full functionality. +""" import json import logging @@ -17,6 +22,7 @@ DEFAULT_PAGE_SIZE = 10 def optimize_document_response(doc: dict) -> dict: + """...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/mcp_server/features/documents/document_tools.py
Expand my code with proper documentation strings
import hashlib import re from typing import List, Optional from urllib.parse import urljoin, urlparse from ....config.logfire_config import get_logger logger = get_logger(__name__) class URLHandler: @staticmethod def is_sitemap(url: str) -> bool: try: parsed = urlparse(url) ...
--- +++ @@ -1,3 +1,8 @@+""" +URL Handler Helper + +Handles URL transformations and validations. +""" import hashlib import re @@ -10,9 +15,19 @@ class URLHandler: + """Helper class for URL operations.""" @staticmethod def is_sitemap(url: str) -> bool: + """ + Check if a URL is a sit...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/helpers/url_handler.py
Generate consistent docstrings
from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator from crawl4ai.content_filter_strategy import PruningContentFilter from ....config.logfire_config import get_logger logger = get_logger(__name__) class SiteConfig: # Common code block selectors for various editors and documentation frame...
--- +++ @@ -1,3 +1,8 @@+""" +Site Configuration Helper + +Handles site-specific configurations and detection. +""" from crawl4ai.markdown_generation_strategy import DefaultMarkdownGenerator from crawl4ai.content_filter_strategy import PruningContentFilter @@ -7,6 +12,7 @@ class SiteConfig: + """Helper class ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/helpers/site_config.py
Add verbose docstrings with examples
import os from typing import Any from supabase import Client, create_client from ..utils.structured_logger import get_logger logger = get_logger(__name__) def get_agent_work_orders_client() -> Client: url = os.getenv("SUPABASE_URL") key = os.getenv("SUPABASE_SERVICE_KEY") if not url or not key: ...
--- +++ @@ -1,3 +1,8 @@+"""Supabase client for Agent Work Orders. + +Provides database connection management and health checks for work order state persistence. +Reuses same Supabase credentials as main Archon server (SUPABASE_URL, SUPABASE_SERVICE_KEY). +""" import os from typing import Any @@ -10,6 +15,21 @@ ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/database/client.py
Add docstrings for utility scripts
from collections.abc import MutableMapping from typing import Any import structlog from structlog.contextvars import bind_contextvars, clear_contextvars from .log_buffer import WorkOrderLogBuffer class BufferProcessor: def __init__(self, buffer: WorkOrderLogBuffer) -> None: self.buffer = buffer d...
--- +++ @@ -1,3 +1,8 @@+"""Structured Logging Setup + +Configures structlog for PRD-compliant event logging with SSE streaming support. +Event naming follows: {module}_{noun}_{verb_past_tense} +""" from collections.abc import MutableMapping from typing import Any @@ -9,13 +14,33 @@ class BufferProcessor: + "...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/agent_work_orders/utils/structured_logger.py
Improve documentation using docstrings
import uuid from datetime import datetime, timedelta # Removed direct logging import - using unified config from ..config.logfire_config import get_logger logger = get_logger(__name__) class SimplifiedSessionManager: def __init__(self, timeout: int = 3600): self.sessions: dict[str, datetime] = {} # s...
--- +++ @@ -1,3 +1,9 @@+""" +MCP Session Manager + +This module provides simplified session management for MCP server connections, +enabling clients to reconnect after server restarts. +""" import uuid from datetime import datetime, timedelta @@ -9,18 +15,27 @@ class SimplifiedSessionManager: + """Simplified...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/mcp_session_manager.py
Add missing documentation to my Python functions
from typing import Any from postgrest.exceptions import APIError from ...config.logfire_config import get_logger, safe_logfire_error, safe_logfire_info from .helpers.llms_full_parser import parse_llms_full_sections logger = get_logger(__name__) class PageStorageOperations: def __init__(self, supabase_client)...
--- +++ @@ -1,3 +1,9 @@+""" +Page Storage Operations + +Handles the storage of complete documentation pages in the archon_page_metadata table. +Pages are stored BEFORE chunking to maintain full context for agent retrieval. +""" from typing import Any @@ -10,8 +16,20 @@ class PageStorageOperations: + """ + ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/page_storage_operations.py
Generate docstrings for this script
from dataclasses import dataclass from typing import Any from ...config.logfire_config import get_logger from ..embeddings.multi_dimensional_embedding_service import multi_dimensional_embedding_service from .model_discovery_service import model_discovery_service logger = get_logger(__name__) @dataclass class Routi...
--- +++ @@ -1,3 +1,10 @@+""" +Ollama Embedding Router + +Provides intelligent routing for embeddings based on model capabilities and dimensions. +Integrates with ModelDiscoveryService for real-time dimension detection and supports +automatic fallback strategies for optimal performance across distributed Ollama instance...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/ollama/embedding_router.py
Help me write clear docstrings
from pydantic import BaseModel, Field, field_validator class OpenRouterEmbeddingModel(BaseModel): id: str = Field(..., description="Full model ID with provider prefix (e.g., openai/text-embedding-3-large)") provider: str = Field(..., description="Provider name (openai, google, qwen, mistralai)") name: s...
--- +++ @@ -1,8 +1,14 @@+""" +OpenRouter model discovery service. + +Provides discovery and metadata for OpenRouter embedding models. +""" from pydantic import BaseModel, Field, field_validator class OpenRouterEmbeddingModel(BaseModel): + """OpenRouter embedding model metadata.""" id: str = Field(...,...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/openrouter_discovery_service.py
Create Google-style docstrings for my code
class ProgressMapper: # Define progress ranges for each stage # Reflects actual processing time distribution STAGE_RANGES = { # Common stages "starting": (0, 1), "initializing": (0, 1), "error": (-1, -1), # Special case for errors "cancelled": (-1, -1), ...
--- +++ @@ -1,6 +1,13 @@+""" +Progress Mapper for Background Tasks + +Maps sub-task progress (0-100%) to overall task progress ranges. +This ensures smooth progress reporting without jumping backwards. +""" class ProgressMapper: + """Maps sub-task progress to overall progress ranges""" # Define progress ...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/crawling/progress_mapper.py
Add docstrings to meet PEP guidelines
import hashlib from pathlib import Path from typing import Any import logfire from supabase import Client from .client_manager import get_supabase_client from ..config.version import ARCHON_VERSION class MigrationRecord: def __init__(self, data: dict[str, Any]): self.id = data.get("id") self.v...
--- +++ @@ -1,3 +1,6 @@+""" +Database migration tracking and management service. +""" import hashlib from pathlib import Path @@ -11,6 +14,7 @@ class MigrationRecord: + """Represents a migration record from the database.""" def __init__(self, data: dict[str, Any]): self.id = data.get("id") @@...
https://raw.githubusercontent.com/coleam00/Archon/HEAD/python/src/server/services/migration_service.py