agentleFS
zuhabulzuhabul/Fetchium/AGENTS.md

Fetchium

AGENTS.md4 starsChanged 9 months agoApache-2.0View on GitHub

Guidelines for AI agents (Claude Code, OpenAI Codex, Gemini CLI, etc.) working on the Fetchium codebase. Data flow: CLI args → FetchiumConfig → fetchium-core pipeline → formatted output

  • Reads credentials
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repositoryOne other file it gives its agents.

The file

We split this AGENTS.md into the rules it gives an agent

9 rules. About 0 are common, 2 are distinctive, and 7 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈2

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 7

    Very specific

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

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

    Use cargo fmt before committing

    line 175
  2. Distinctive:

    Keep files under 500 lines — split into submodules when exceeding

    line 237
  3. Very specific:

    All shared dependencies go in the workspace Cargo.toml:

    line 255
  4. Very specific:

    Run cargo check after writing code

    line 271
  5. Very specific:

    Run cargo test after completing a feature

    line 272
  6. Very specific:

    Run cargo clippy -- -D warnings before committing

    line 273
  7. Very specific:

    All public APIs must have /// doc comments

    line 274
  8. Very specific:

    After any change: verify cargo test shows 1,100+ tests, 0 failures

    line 276
  9. Distinctive:

    Before infra changes: read SSOT, apply changes, then update SSOT + endpoint registry in same task.

    line 281

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md 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
AGENTS.md

AGENTS.md

Guidelines for AI agents (Claude Code, OpenAI Codex, Gemini CLI, etc.) working on the Fetchium codebase.

Build, Lint, and Test Commands

# Check compilation (fast, no linking)
cargo check

# Build the fetchium binary
cargo build -p fetchium-cli

# Build release binary
cargo build -p fetchium-cli --release

# Run all tests (currently 563, target: 0 failures)
cargo test

# Run tests for a specific crate
cargo test -p fetchium-core

# Run a single test by name
cargo test -p fetchium-core segment_type_roundtrip

# Lint (zero warnings policy — enforced in CI)
cargo clippy -- -D warnings

# Format code
cargo fmt

# Run the binary
./target/debug/fetchium --help
./target/debug/fetchium doctor
./target/debug/fetchium provider list

Current Status

  • Tests: 563 passing, 0 failing, 0 clippy warnings
  • Phases complete: 0–8 + Multi-provider AI system
  • Binary: ./target/debug/fetchium with 26 commands

Architecture

crates/
├── fetchium-core/     # All algorithms: search, extract, rank, validate, cache, AI, intelligence
├── fetchium-cli/      # Binary: clap derive CLI, one file per command in commands/
├── fetchium-mcp/      # Manual JSON-RPC 2.0 stdio MCP server (5 tools)
└── fetchium-api/      # axum 0.7 REST API server

Data flow: CLI args → FetchiumConfig → fetchium-core pipeline → formatted output

Key Module Map (fetchium-core/src/)

ai/
  credentials.rs      Subscription OAuth detection (Claude Code, Gemini CLI, Codex CLI)
  provider_client.rs  Multi-provider chat client with SSE streaming + fallback chain
  providers.rs        ProviderKind enum, ProvidersConfig, ProviderEntry
  pipeline.rs         run_ai_pipeline() — search → extract → sandwich → provider
  types.rs            AiConfig (providers: ProvidersConfig, fast_model: Option<String>)
  router.rs           select_model(), select_fast_model()
  sandwich.rs         Ms-PoE sandwich layout
  ollama.rs           OllamaClient (local Ollama server)
  prompt.rs           System prompts for synthesis/factual/fallback modes
  setup.rs            DeviceSpec, recommend_models(), format_setup_guide()

search/
  orchestrator.rs     Parallel backend dispatch + BM25 rerank + dedup
  duckduckgo.rs       DDG HTML scraper
  fallback.rs         FallbackChain async executor

extract/
  layer1.rs, layer2.rs  CEP CSS+readability extraction
  pipeline.rs         Speculative parallel extraction
  boilerplate.rs      QADD pre-filter (strips script/style/svg)
  cep_predictor.rs    Decision tree ML predictor for CEP layer selection

token/
  qatbe.rs            BM25 + hybrid embedding ranking, greedy knapsack
  scs.rs              8 segment types, token-efficient JSON
  pds.rs              4-tier progressive streaming
  counter.rs          Heuristic tokenizer + TokenBudget

rank/
  bm25.rs             tantivy-backed Bm25Scorer
  signals.rs          ScoringContext (batch embeddings), HyperFusion 8-signal ranking
  fusion.rs           hyperfusion_rank()

validate/
  cross_source.rs     V4 bigram-Jaccard clustering, negation-aware contradiction
  temporal.rs         V3 exponential decay, intent classification
  authority.rs        V1 domain tiers, SSL/redirect penalties
  rar.rs              5 reflection checkpoints R1-R5

intelligence/
  pie/               STM (source trust), FPM (failure patterns), QPM (query prediction), PKG
  edf.rs             Evidence decay function, domain half-lives
  cce.rs             Confidence calibration (isotonic interpolation)
  acs.rs             Adversarial content shield (shadow/active mode)
  crp.rs             Contradiction resolution protocol
  sgt.rs             Source genealogy tracker (bigram-Jaccard mutation detection)
  totr.rs            Tree-of-Thoughts research

export/
  pandoc.rs          PDF: typst (~1s) → xelatex → default; check_typst() for doctor
  bibtex.rs          Pure Rust BibTeX generator

embeddings/
  engine.rs          fastembed-rs singleton, embed() + embed_batch()
  cache.rs           SHA-256 keyed SQLite cache

qadd/pipeline.rs     5-step DOM pruning, chunked embed_batch (EMBED_BATCH_SIZE=128)

AI Provider System

Credential Detection (automatic, no config needed)

ProviderCredential LocationAuth Type
AnthropicmacOS Keychain "Claude Code-credentials"OAuth Bearer (sk-ant-oat01-…)
Gemini~/.gemini/oauth_creds.jsonGoogle OAuth Bearer, auto-refreshed
OpenAI~/.codex/auth.jsonJWT Bearer from ChatGPT OAuth
OpenRouter~/.openrouter/config.json OR envAPI key
OllamaNone (localhost:11434)Local
GeminiCligemini binary in PATHLocal subprocess

Priority order (per provider)

  1. Config file api_key field
  2. Environment variable (ANTHROPIC_API_KEY, GEMINI_API_KEY, OPENAI_API_KEY, etc.)
  3. Subscription CLI session (auto-detected)

Key types

  • ProviderKind — enum: Ollama, OpenAi, Anthropic, Gemini, GeminiCli, OpenRouter
  • ProvidersConfig.fallback_chain: Vec<String> — ordered slugs, tried in sequence
  • chat_with_fallback() — tries each provider, returns first success
  • check_provider() — availability check without LLM call (used by fetchium doctor and fetchium provider list)

Anthropic OAuth vs API key

// API key: x-api-key header
// OAuth (Claude Code subscription): Authorization: Bearer {sk-ant-oat01-...}
call_anthropic(token, use_oauth=false, ...)  // API key
call_anthropic(token, use_oauth=true, ...)   // OAuth

Gemini OAuth vs API key

// API key: URL ?key={api_key} parameter, no auth header
call_gemini_api_key(api_key, model, ...)

// OAuth: Authorization: Bearer header, no ?key= parameter
call_gemini_oauth(access_token, model, ...)

Code Style Guidelines

Imports

// Order: std → external crates → internal crates → current crate modules
use std::collections::HashMap;
use serde::{Deserialize, Serialize};
use tracing::warn;
use crate::error::FetchiumResult;
use crate::types::{PdsTier, ResourceTier};

Formatting

  • Use cargo fmt before committing
  • Max line width: 100 characters (default)
  • Zero warnings: cargo clippy -- -D warnings must pass

Types and Serialization

// All public types must derive Debug, Clone, Serialize, Deserialize
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Example {
    pub some_field: String,
    #[serde(skip_serializing_if = "Option::is_none")]
    pub optional: Option<String>,
    #[serde(default)]
    pub new_field: bool,
}

// Enums use snake_case in JSON
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Status { Active, Pending, Completed }

Naming Conventions

TypeConventionExample
StructsPascalCaseSearchMeta, ResultItem
EnumsPascalCasePdsTier, BackendId
Functionssnake_casefetch_text
Variablessnake_casemax_results
ConstantsSCREAMING_SNAKEMAX_REDIRECTS
Crate prefixfetchium-fetchium-core, fetchium-cli

Error Handling

// Use FetchiumResult<T> for fallible operations in fetchium-core
use crate::error::{FetchiumError, FetchiumResult};

pub fn do_something() -> FetchiumResult<String> {
    let data = fetch_data()?;
    if data.is_empty() {
        return Err(FetchiumError::Extraction("No data found".into()));
    }
    Ok(data)
}

// CLI commands use anyhow::Result
pub async fn run(config: &FetchiumConfig) -> anyhow::Result<()> { }

Documentation

/// Brief description on first line.
/// Reference PRD sections where applicable: (PRD §43)
pub fn function_name() {}

Module Organization

  • Keep files under 500 lines — split into submodules when exceeding
  • One file per CLI command in crates/fetchium-cli/src/commands/
  • Tests go in the same file with #[cfg(test)] mod tests { }

Async Patterns

#[tokio::main]
async fn main() -> anyhow::Result<()> { }

#[async_trait]
pub trait SearchBackend: Send + Sync {
    async fn search(&self, query: &str) -> FetchiumResult<Vec<ResultItem>>;
}

Dependency Management

All shared dependencies go in the workspace Cargo.toml:

# In workspace Cargo.toml
[workspace.dependencies]
tokio = { version = "1", features = ["full"] }

# In crates/fetchium-core/Cargo.toml
[dependencies]
tokio.workspace = true

Never add version numbers directly in crate Cargo.toml for dependencies already in workspace.

Task Workflow

  1. Run cargo check after writing code
  2. Run cargo test after completing a feature
  3. Run cargo clippy -- -D warnings before committing
  4. All public APIs must have /// doc comments
  5. Reference PRD sections in comments: (PRD §16)
  6. After any change: verify cargo test shows 1,100+ tests, 0 failures

Global Infrastructure SSOT

  • Canonical infrastructure source: /home/echo/INFRASTRUCTURE_SOURCE_OF_TRUTH.md
  • Endpoint registry (machine-friendly): /home/echo/INFRASTRUCTURE_ENDPOINTS.tsv
  • Before infra changes: read SSOT, apply changes, then update SSOT + endpoint registry in same task.

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.