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 code style.
Of the AGENTS.md files we read, the 35,337 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.
- CLAUDE.mdCLAUDE.md
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
- Very specific: line 175
Use cargo fmt before committing
- Distinctive: line 237
Keep files under 500 lines — split into submodules when exceeding
- Very specific: line 255
All shared dependencies go in the workspace Cargo.toml:
- Very specific: line 271
Run cargo check after writing code
- Very specific: line 272
Run cargo test after completing a feature
- Very specific: line 273
Run cargo clippy -- -D warnings before committing
- Very specific: line 274
All public APIs must have /// doc comments
- Very specific: line 276
After any change: verify cargo test shows 1,100+ tests, 0 failures
- Distinctive: line 281
Before infra changes: read SSOT, apply changes, then update SSOT + endpoint registry in same task.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 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.
Files
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 listCurrent Status
- Tests: 563 passing, 0 failing, 0 clippy warnings
- Phases complete: 0–8 + Multi-provider AI system
- Binary:
./target/debug/fetchiumwith 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 serverData 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)
| Provider | Credential Location | Auth Type |
| Anthropic | macOS Keychain "Claude Code-credentials" | OAuth Bearer (sk-ant-oat01-…) |
| Gemini | ~/.gemini/oauth_creds.json | Google OAuth Bearer, auto-refreshed |
| OpenAI | ~/.codex/auth.json | JWT Bearer from ChatGPT OAuth |
| OpenRouter | ~/.openrouter/config.json OR env | API key |
| Ollama | None (localhost:11434) | Local |
| GeminiCli | gemini binary in PATH | Local subprocess |
Priority order (per provider)
- Config file
api_keyfield - Environment variable (
ANTHROPIC_API_KEY,GEMINI_API_KEY,OPENAI_API_KEY, etc.) - Subscription CLI session (auto-detected)
Key types
ProviderKind— enum: Ollama, OpenAi, Anthropic, Gemini, GeminiCli, OpenRouterProvidersConfig.fallback_chain: Vec<String>— ordered slugs, tried in sequencechat_with_fallback()— tries each provider, returns first successcheck_provider()— availability check without LLM call (used byfetchium doctorandfetchium 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, ...) // OAuthGemini 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 fmtbefore committing - Max line width: 100 characters (default)
- Zero warnings:
cargo clippy -- -D warningsmust 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
| Type | Convention | Example |
| Structs | PascalCase | SearchMeta, ResultItem |
| Enums | PascalCase | PdsTier, BackendId |
| Functions | snake_case | fetch_text |
| Variables | snake_case | max_results |
| Constants | SCREAMING_SNAKE | MAX_REDIRECTS |
| Crate prefix | fetchium- | 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 = trueNever add version numbers directly in crate Cargo.toml for dependencies already in workspace.
Task Workflow
- Run
cargo checkafter writing code - Run
cargo testafter completing a feature - Run
cargo clippy -- -D warningsbefore committing - All public APIs must have
///doc comments - Reference PRD sections in comments:
(PRD §16) - After any change: verify
cargo testshows 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.
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
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.

