SmallCode

repository·master·Indexed 24 days ago

https://github.com/doorman11991/smallcode

A terminal-native AI coding agent optimized for small local LLMs (8B-35B parameters). SmallCode utilizes budget-managed context, TODO-file decomposition, and search-and-replace patching to enable high-performance coding tasks on smaller models. Key features include a RAG harness with hybrid search, knowledge note injection for context, a MarrowScript-based cognition layer, and support for model escalation to cloud providers like Anthropic, OpenAI, and DeepSeek.

Tokens
34.3K
Snippets
57
Records
203
Agent score
83%

What's inside smallcode

  1. Compare SmallCode features with OpenCode and Pi Agent

    master

    SmallCode is specifically optimized for small local LLMs (7B-20B), whereas OpenCode and Pi Agent are designed for frontier models (Claude, GPT) or general-purpose use.

    Key differentiators for SmallCode include:

    • Local Model Optimization: Core design goal focused on small models.
    • Compound Tools: Reduces tool call chains (e.g., read_and_patch) to maintain coherence in smaller models.
    • Model Escalation: Automatically escalates to cloud models (Claude/GPT) if the local model fails.
    • Improvement Loop: Automatically validates code and feeds errors back to the model (retry → decompose → escalate).
    • BoneScript: Allows generating a full project from a single .bone file.
    • Forgiving JSON Parser: Repairs tool call outputs from models that produce messy JSON.
    • Persistent Memory: Uses SQLite + FTS5 for typed, persistent knowledge across sessions.
    • Token Budgeting: Uses auto-compacting and capped retrieval to manage context for small models.
  2. Use the Iterative Retrieval Ladder to manage context

    master

    To prevent small models from losing quality due to context dumping, follow the Iterative Retrieval Ladder. Instead of reading entire files immediately, climb the ladder and stop as soon as you have sufficient context. This approach prioritizes cheaper memory and search operations over expensive file reads.

    The Ladder Steps:

    1. memory_load: Retrieve past decisions, gotchas, and workflows.
    2. search / graph_search: Find relevant paths and code snippets.
    3. read_file: Perform a single, targeted file read.
    4. Full repo reads: Use this only as a last resort.
  3. Rules for the brainstorming skill

    master

    When executing the brainstorming skill, the following rules must be strictly followed:

    • Contextual Search: Always perform a context search before proposing ideas.
    • Minimum Approaches: You must provide at least three approaches.
    • Mandatory Stop: Step 6 (waiting for confirmation) is not optional. Skipping this step defeats the purpose of the skill.
    • Handling Rejections: If the user rejects all three proposed approaches, do not immediately generate more. Instead, ask the user what is missing or what they are looking for to refine the next set of proposals.
  4. Using the Escalation feature for stronger models

    master

    Escalation is an opt-in mechanism that allows SmallCode to call a powerful cloud model (Anthropic, OpenAI, or DeepSeek) when a local model fails to complete a task after exhausting retries and decomposition strategies.

    Configuration and Behavior

    • Provider Preference: The engine detects keys in this order: Anthropic > OpenAI > DeepSeek.
    • Format Conversion: The system automatically converts conversation history to the provider's native format (e.g., converting OpenAI tool_calls to Anthropic tool_use/tool_result blocks).
    • Safety Limits: There is a default session cap of five escalations to prevent unexpected API costs.
    • Requirement: The feature is dormant unless a cloud API key is configured. If no key is found, canEscalate() returns false.
  5. How SmallCode optimizes for small LLMs

    master

    SmallCode is architected specifically for models with 7B-20B parameters to overcome common limitations of smaller models:

    • Context Budget Management: Automatically summarizes large files into signatures and evicts old messages to prevent exceeding context windows.
    • Two-Stage Tool Routing: Reduces schema overhead by having the model first select a category (read/write/search/run/plan) before receiving specific tool schemas.
    • Forgiving Tool Parsing: Uses a multi-format parser (JSON, YAML, XML, Hermes, or plain text) to handle messy outputs from smaller models.
    • Patch-First Editing: Uses search-and-replace (patch) instead of full-file rewrites to prevent truncation and hallucinations.
    • TODO-Driven Planning: Breaks complex tasks into atomic steps tracked in a TODO file, ensuring progress is validated at each step.
    • Working Memory: Provides a persistent notepad for the model to store notes across turns, compensating for limited reasoning depth.
  6. How editing works via the patch primitive

    master

    SmallCode uses a patch primitive for file edits instead of full-file rewrites. This is designed for small models that struggle with long-form generation.

    The Patch Mechanism

    • Mechanism: A search-and-replace operation where the old_str must match exactly one location in the target file.
    • Fallback: If a patch fails because the old_str no longer matches (due to previous edits shifting content), the system uses a semantic merge fallback. This asks the model to merge the intended change into the current file and return the entire corrected file.
    • Read-before-write Guard: To prevent models from overwriting files with incorrect content, the system refuses the first attempt to write to a file that hasn't been read during the current session. A second attempt is permitted if the model needs to perform a full replacement.
  7. How SmallCode code search works

    master

    SmallCode uses a hybrid search approach to retrieve code snippets without requiring an external vector database or cloud embeddings:

    1. BM25 Lexical Search: Searches over identifiers, paths, symbols, tags, and snippet text. Ideal for exact API names and framework constructs.
    2. Local Hashed-Vector Similarity: A dependency-free vector search over snippet text that helps match related naming patterns even when exact words differ.
    3. Hybrid Ranking: Combines BM25 and vector scores to inject the top relevant snippets into the model context.

    This process is optimized for speed and local execution.

  8. Debugging rules and constraints

    master

    When debugging, adhere to these strict rules to ensure reliability:

    • Never skip step 1: Always search prior context first.
    • Never fix without a test: A fix is not valid until confirmed by a test.
    • Reproduction is mandatory: If you cannot reproduce the bug in the reproduction step, you do not yet understand the issue.
  9. Understand the MarrowScript Cognition Layer

    master

    SmallCode's intelligence is defined using MarrowScript. A single .marrow declaration compiles into a production-ready TypeScript runtime that provides advanced features like prompt caching, structured traces, tier-based routing, token budget enforcement, and automatic validation/repair.

    To enable structured traces (trace_id/span_id) for every LLM call, set the environment variable SMALLCODE_COGNITION_LOG=stderr.

    prompt classify_task_type(user_message: string) {
      model: TinyClassifier
      timeout: 3s
      cache: { key: hash(user_message), ttl: 10m }
      retry: { max_attempts: 2, backoff: fixed, interval: 100ms }
      constraints: [output in ["coding", "editing", "search", ...]]
    }
  10. Manage Persistent Shell Sessions

    master

    By default, bash calls share a long-lived shell process, allowing state like cd, environment variables, and shell variables to persist across multiple calls.

    To disable this behavior (making every call a fresh process), set SMALLCODE_SHELL_PERSIST=false.

    Note: SmallCode includes optional cwd-containment to prevent cd or other escapes from leaving the project root.

  11. How session memory and persistence work

    master

    SmallCode employs a two-tier memory system to manage context and project knowledge.

    Memory Tiers

    1. Short-term Working Memory: Lives in the conversation history and is subject to eviction under context pressure.
    2. Long-term Project Memory: Stored in a SQLite database with full-text search. It is keyed by content type (e.g., decision, workflow, gotcha, convention, context). When a new task starts, semantically relevant entries are loaded based on keyword overlap.

    Persistence and Safety

    • Atomic Writes: Sessions are persisted to disk using a write-temp-then-rename strategy to ensure integrity.
    • Snapshots: Before every agent turn, a checkpoint is opened. All writes and patches record the pre-edit file content. If validation fails, the system can perform an auto-rollback to the checkpoint state. Snapshots are stored in the .smallcode/snapshots/ directory.