agentleFS
tusharagg1tusharagg1/aifolimizer/CLAUDE.md

aifolimizer

CLAUDE.md2 starsChanged 5 months agoMITView on GitHub

No frontend - analysis runs in Claude Code / Claude Desktop. FastAPI is exposed for ad-hoc REST testing only. Fresh clone: ./setup.sh (POSIX/Git-Bash) or powershell -File setup.ps1 (Windows) - venv, deps, backend/.env, .mcp.json, MCP registration, doctor. Idempotent. Then python backend/scripts/health_check.py to diagnose. MCP server (mcp_server.py) runs as separate process managed by Claude Code - register once with: Quality gates (run before claiming "done"):

  • Reads credentials

The file

Show its rules and text

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

19 rules. About 0 are common, 9 are distinctive, and 10 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈9

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 10

    Very specific

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

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

    Read .claude/context/changes.md - what built, when

    line 4
  2. Very specific:

    Read .claude/context/architecture.md - data flow, API contracts, file index

    line 5
  3. Very specific:

    Read .claude/context/lessons.md - past corrections, do-not-repeat rules

    line 6
  4. Very specific:

    Call mcp__aifolimizer__get_profile before analysis - never hardcode account types or capital

    line 7
  5. Distinctive:

    No frontend - analysis runs in Claude Code / Claude Desktop.

    line 26
  6. Very specific:

    Crowding: before adding to name, call get_positioning_signals.

    line 113
  7. Very specific:

    No hardcoded capital amounts or account types - always read from get_profile

    line 151
  8. Distinctive:

    No PII in logs, DB, or MCP output

    line 152
  9. Distinctive:

    No comments explaining WHAT - only WHY when non-obvious

    line 155
  10. Very specific:

    Lessons loop: After correction or surprise bug, append rule to .claude/context/lessons.md.

    line 163
  11. Very specific:

    Targeted reads only: Use semantic_search_nodes or get_review_context before Grep/Read.

    line 166
  12. Distinctive:

    Summarize tool output: Never paste full logs. Extract relevant.

    line 167
  13. Very specific:

    NEVER add Co-Authored-By: Claude ...

    line 172
  14. Distinctive:

    NEVER add "Generated with Claude Code" footer or AI-attribution to commits, PRs, or PR bodies

    line 173
  15. Distinctive:

    Commit messages authored solely by human user

    line 174
  16. Distinctive:

    No AI tone or signs of AI authorship anywhere in the repo: docs, code comments, commit messages, PR text, release notes, the GitHub About.

    line 178
  17. Very specific:

    No em dashes or en dashes (use -, a comma, or a colon).

    line 179
  18. Distinctive:

    No narration of the AI/agent process in committed text (no "parallel audit", "the agent found", "verified by analysis").

    line 180
  19. Distinctive:

    Write plainly, like a human engineer.

    line 181

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

aifolimizer - Project Context

Session Startup (read every new session)

  1. Read .claude/context/changes.md - what built, when
  2. Read .claude/context/architecture.md - data flow, API contracts, file index
  3. Read .claude/context/lessons.md - past corrections, do-not-repeat rules
  4. Call mcp__aifolimizer__get_profile before analysis - never hardcode account types or capital

What This Is

AI investment advisor for Canadian Wealthsimple retail investors (growth+income+crypto profile). Live portfolio via local backend. AI analysis in Claude Code/Desktop Pro - no Anthropic API key.

Architecture

Claude Code / Claude Desktop  (Pro subscription - no API key)
        ↓ invokes
   .claude/skills/*  (28 institutional analysis skills)
        ↓ calls MCP tool
   backend/mcp_server.py  (FastMCP, 107 tools)
        ↓ uses
   app/services/{wealthsimple, market_data, fundamentals, technicals, news, macro, quant, portfolio_analytics, health_score, crypto_data}
        ↓ HTTP
   Wealthsimple + yfinance + FRED + CoinGecko (all free, no keys required)

No frontend - analysis runs in Claude Code / Claude Desktop. FastAPI is exposed for ad-hoc REST testing only.

How to Start

Fresh clone: ./setup.sh (POSIX/Git-Bash) or powershell -File setup.ps1 (Windows) - venv, deps, backend/.env, .mcp.json, MCP registration, doctor. Idempotent. Then python backend/scripts/health_check.py to diagnose.

# Backend (FastAPI + shared session store)
cd backend && .venv/Scripts/activate && uvicorn main:app --reload --port 8000

MCP server (mcp_server.py) runs as separate process managed by Claude Code - register once with:

claude mcp add aifolimizer "<venv_python_path>" "backend/mcp_server.py"

Quality gates (run before claiming "done"):

pytest                     # testpaths=backend/tests (run from repo root)
ruff check . ; pyright     # lint + type-check

MCP Tools (107 total - table below is a curated subset; see mcp_server.py for full list)

ToolReturnsCache
get_profileAccount types, cash balances, total invested - PII strippedsession
get_portfolioLive enriched positions + summary - PII strippedlive
get_xrayETF exposure + sector/asset-class breakdownlive
get_concentration_warningsSingle-position / sector over-allocation flagslive
get_tax_loss_candidatesUnderwater positions for tax-loss harvestinglive
get_risk_metricsAnnualized vol, Sharpe, Sortino, VaR 95%, ES, max drawdown1h
get_correlation_matrixPairwise correlation top N holdings1h
get_macro_snapshotFRED: Fed funds, 10Y yield, CPI, CAD/USD, BoC rate, unemployment12h
get_fundamentalsP/E, EPS, div yield, payout, market cap, earnings date, analyst target, beta6h
get_technicalsSMA20/50/200, RSI(14), MACD, Bollinger, trend, RSI signal1h
get_earnings_calendarNext earnings dates per holding, flags next-14-days6h
get_earnings_resultsLast N quarters EPS estimate/actual/surprise/outcome12h
get_news_headlinesRecent headlines per ticker30m
get_positioning_signalsCrowding score, inst. ownership, short interest, headline velocity6h
snapshot_positioning_historyAppend crowding scores to JSONL (idempotent/day)live
get_crowding_shiftsSymbols w/ crowding score shift ≥threshold over lookbacklive
get_crypto_dataCoinGecko: price CAD, market cap, 24h/7d/30d, ATH distance5m
get_triggered_alertsAlert events from jsonl loglive
run_alerts_nowEvaluate alert rules vs live portfoliolive
backtest_portfolioRule-replay per symbol. Supports tx_cost_bps + walk_forward1h
get_skill_track_recordBacktest 13 codified-rule skills over 3-5yr bars. CAGR, Sharpe, Sortino, max DD, hit-rate, alphadisk
log_recommendationLog skill rec to recommendations.jsonllive
score_recommendationsMark-to-market open recs, flag stops/targets hitlive
get_live_track_recordRolling 7/30/90d win-rate + P&L from scored recslive
snapshot_portfolio_equityAppend NAV to portfolio_history.jsonl (idempotent/day)live
get_alpha_attributionAlpha, beta, Sharpe, info ratio, tracking error vs benchmarkslive
get_quote_with_sourceLive quote w/ source attribution (fallback chain)5m
get_quotes_batchBatch quotes for N symbols - 13x faster than serial5m
get_data_source_reliabilityPer-source success rate + avg latencylive
generate_trust_reportWrite TRACK_RECORD.md + jsonl, git-commitlive
list_analysis_modesFilesystem-driven list of all 28 skills + their MCP toolsstatic

L1+L2: in-process dict + cross-process diskcache. MCP+FastAPI share L2.

Analysis Skills (28 in .claude/skills/ - table below highlights core 13)

SkillFrameworkKey MCP tools
daily-briefingMorning digestget_profile, get_portfolio, get_macro_snapshot, get_concentration_warnings, get_triggered_alerts, get_earnings_calendar, get_positioning_signals
portfolio-healthBlackRockget_profile, get_portfolio, get_xray, get_concentration_warnings
risk-assessmentBridgewaterget_profile, get_portfolio, get_risk_metrics, get_correlation_matrix
stock-analysisGoldman + Citadel TAget_profile, get_portfolio, get_fundamentals, get_technicals, get_news_headlines, get_positioning_signals
stock-compareHead-to-headget_profile, get_portfolio, get_fundamentals, get_technicals, get_news_headlines
macro-impactMcKinseyget_profile, get_portfolio, get_macro_snapshot
dividend-strategyHarvard Endowmentget_profile, get_portfolio, get_fundamentals
earnings-analyzerJPMorganget_profile, get_portfolio, get_earnings_calendar, get_fundamentals
earnings-postmortemPost-report EPSget_profile, get_portfolio, get_earnings_results, get_fundamentals, get_news_headlines
sector-rotationRenaissanceget_profile, get_portfolio, get_xray
tax-loss-reviewCanadian harvestingget_profile, get_tax_loss_candidates
adversarial-researchBull/bear/consensusget_profile, get_portfolio, get_fundamentals, get_technicals, get_news_headlines, get_macro_snapshot, get_positioning_signals
cash-deploymentAdd-to-winners w/ crowding guardget_profile, get_portfolio, get_concentration_warnings, get_fundamentals, get_technicals, get_positioning_signals

Each skill: auto-triggers from frontmatter, calls get_profile FIRST.

Investor Profile (verify with get_profile)

  • Canadian retail investor
  • Philosophy: growth stocks, index ETFs (XEQT/VFV), dividends, crypto
  • Risk: mixed - conservative (bonds/GIC), moderate (ETFs), aggressive (stocks, crypto)
  • Horizons: day trading + short-term (<3yr) + long-term (10yr+)
  • Tax: TFSA (tax-free), RRSP (tax-deferred), Non-Reg (50% cap gains inclusion)
  • Capital + balances: ALWAYS pull from get_profile - never hardcode
  • Crowding: before adding to name, call get_positioning_signals. Score ≥70 = consensus-crowded → negative expected alpha. Defer adds; favor contrarian (score ≤30) when fundamentals support.

Tech Stack

LayerTech
Backend APIFastAPI + uvicorn (Python 3.12)
MCP serverFastMCP (shares services with FastAPI)
Technical indicatorsta>=0.11.0 (NOT pandas-ta)
Prices + fundamentalsyfinance (free, no key)
Macro dataFRED public CSV API (free, no key)
Crypto dataCoinGecko v3 free API (no key, 30 req/min)
AI inferenceClaude Code / Claude Desktop Pro (no Anthropic API key)

Supports Python 3.12-3.14 (uses ta, not pandas-ta); 3.13 recommended. CI + the hash-locked requirements.lock target 3.12.

Privacy Rules (NON-NEGOTIABLE)

<important if="touching backend/, .env, mcp_server.py, pii_filter.py, or any MCP tool response"> - WS_EMAIL/WS_PASSWORD: local `.env` only, never committed, logged, or sent to AI. Password NEVER persisted to disk. - WS access + refresh token: server RAM + persisted to `~/.aifolimizer/ws_session.json` (mode 0600 on POSIX; on Windows the file lives in the user profile and relies on NTFS ACL - set BitLocker / strict ACL if hardening). 14-day default TTL (override via `WS_TOKEN_TTL_HOURS`, range 1-720h); auto-cleared when stale/rejected. Delete to force re-auth. Lives outside repo - never committed. - `pii_filter.py` is applied to portfolio/profile/x-ray responses (the tools that surface account-bearing payloads from `wealthsimple.py`). Other tools (technicals, fundamentals, macro, news, etc.) operate on public market data + symbol lists and do not handle PII. When adding a new MCP tool that touches WS account data, route the response through `pii_filter` before returning. - Account IDs, account numbers, email, full name: NEVER leave the local machine. - External LLM fallbacks (GitHub Models / Gemini / OpenRouter / Qwen) fire ONLY if their API key env var is set. Prompts carry symbols, weights (% of NLV), returns %, and scores - NEVER absolute dollar balances, account IDs, email, name, or WS token. Leave keys unset to keep all fallback inference on-machine. - Primary inference path is your Claude Code / Claude Desktop Pro session, which sends prompts (symbols, weights, scores, public market data) to Anthropic per their normal ToS. No separate API key, no third-party LLM, no creds, no PII. </important>

Environment Variables

# backend/.env (local only - never commit)
WS_EMAIL=...
WS_PASSWORD=...
# Optional: Telegram alerts, free-LLM fallback keys, Sentry - see .env.example

Code Rules

  • No hardcoded capital amounts or account types - always read from get_profile
  • No PII in logs, DB, or MCP output
  • Activate PII pre-commit hook once per clone: git config core.hooksPath .githooks. Hook blocks owner-identifying strings (gmail, full-name, legacy IDs); allowlist for LICENSE/README/pyproject.toml. CI runs gitleaks with same rules from .gitleaks.toml.
  • Functions short, single-purpose
  • No comments explaining WHAT - only WHY when non-obvious
  • Append to .claude/context/changes.md after significant changes
  • Skills builder: python backend/scripts/build_skills.py lists tools + skills
  • Scaffold skill: python backend/scripts/build_skills.py --scaffold <tool_name>

Workflow Rules

  • Verify before "done." Compile-clean ≠ working. Run import-check (backend) AND exercise w/ real input.
  • Lessons loop. After correction or surprise bug, append rule to .claude/context/lessons.md.
  • Pause for elegance on non-trivial changes (3+ files or new abstraction). Ask "cleaner path?" before commit.
  • Surgical changes only. Touch only what request requires. Match existing style. Remove only imports/vars your changes made unused.
  • Targeted reads only. Use semantic_search_nodes or get_review_context before Grep/Read. Read only relevant lines. Ask before loading large files, logs, generated files, or full dependency trees.
  • Summarize tool output. Never paste full logs. Extract relevant; drop rest.
  • Final answer format: changes made + verification + blockers only.

Commit Rules

  • NEVER add Co-Authored-By: Claude ... trailer to commits
  • NEVER add "Generated with Claude Code" footer or AI-attribution to commits, PRs, or PR bodies
  • Commit messages authored solely by human user

No AI Tone (repo-wide, non-negotiable)

  • No AI tone or signs of AI authorship anywhere in the repo: docs, code comments, commit messages, PR text, release notes, the GitHub About.
  • No em dashes or en dashes (use -, a comma, or a colon). No words like delve, robust, seamless, comprehensive, leverage, elevate, excels, unleash. No emoji-stuffing, no "not X, but Y" cadence, no redundant restatement, no breathless run-ons.
  • No narration of the AI/agent process in committed text (no "parallel audit", "the agent found", "verified by analysis").
  • Write plainly, like a human engineer.

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.