All project documentation is organized in the .docs/ folder:
- Individual File Summaries:
.docs/summary-<normalized-path>.md- Detailed summaries of each working file - Comprehensive Overview:
.docs/summary.md- Consolidated project overview and architecture analysis - Agent Instructions:
.docs/agents_instructions.json- Machine-readable agent configuration and workflows
When user executes /init command, you MUST perform these two steps in order:
Can you summarize the working files? Save each file's summary in .docs/summary-<normalized-path>.md
- Identify all relevant working files in the project
- Create individual summaries for each file
- Save summaries using the pattern:
.docs/summary-<normalized-path>.md - Include file purpose, key functionality, and important details
- Normalize file paths (replace slashes with hyphens, remove special characters)
Can you summarize your context files ".docs/summary-*.md" and save the result in .docs/summary.md
- Read all individual summary files created in Step 1
- Synthesize into a comprehensive project overview
- Include architecture, security, testing, and business value analysis
- Save the consolidated summary as
.docs/summary.md - Update any relevant documentation references
Both steps are MANDATORY for every /init command execution.
- Git pull/push only — never use
scp,cp, or manual file copying to sync code between machines. Always commit locally, push to origin, thengit pullon bigbox. - Weather report dependency —
terraphim_weather_reportdepends onterraphim_orchestratorfrom the registry. On bigbox, override to local agents repo:This is a targeted override on one crate's Cargo.toml. Do NOT usesed -i 's|terraphim_orchestrator = { version = "1.20.2", registry = "terraphim" }|terraphim_orchestrator = { path = "/home/alex/projects/terraphim/terraphim-agents/crates/terraphim_orchestrator" }|' crates/terraphim_weather_report/Cargo.toml[patch]in workspace Cargo.toml — it triggers workspace-wide re-resolution and breaks unrelated crates (serenity/reqwest conflict). Do NOT commit this override (machine-specific path). - Orchestrator binary — built from
/home/alex/projects/terraphim/terraphim-agents, NOT from/data/projects/terraphim/terraphim-ai. Deploy with:cd /home/alex/projects/terraphim/terraphim-agents && cargo build --release -p terraphim_orchestrator sudo systemctl stop adf-orchestrator.service && sudo cp target/release/adf /usr/local/bin/adf && sudo systemctl start adf-orchestrator.service
- Terraphim-ai target dir — safe to
cargo cleanon bigbox. The binary is built from the agents repo, not terraphim-ai. Reclaims ~1TB.
# Build all workspace crates
cargo build --workspace
# Run single test
cargo test -p <crate_name> <test_name>
# Run tests with features
cargo test --features openrouter
cargo test --features mcp-rust-sdk
# Format and lint
cargo fmt
cargo clippycd desktop
yarn install
yarn run dev # Development server
yarn run build # Production build
yarn run check # Type checking
yarn test # Unit tests
yarn e2e # End-to-end testsTerraphim has its own file and content search stack. Use it — do NOT rely on
opencode's bundled FFF grep/find/glob tools, which have a known
directory-path-filter bug (returns nothing for directory paths; tracked at
anomalyco/opencode#32688) and are not under Terraphim's control.
Use terraphim-grep via Bash. It is installed with the code-search feature by default
and works without a thesaurus in search-only mode.
# Search code for a symbol (works without a thesaurus)
terraphim-grep "fn ensure_thesaurus_loaded" --haystack code
# Search with context lines
terraphim-grep "DeviceStorage::init" --haystack code -C 3
# Search a specific directory
terraphim-grep "haystack" --haystack code --paths terraphim_server/src/For KG-boosted ranking, keep a project-level .terraphim/ directory in the repo root.
terraphim-grep auto-discovers .terraphim/thesaurus-<role>.json.
# Use an explicit thesaurus
terraphim-grep "session persistence" --paths . --thesaurus .terraphim/thesaurus.json -n 8 -C 2
# Structured output with concepts and boost scores
terraphim-grep "provider" --paths . --thesaurus .terraphim/thesaurus.json --jsonConcept markdown format (.terraphim/kg/<concept>.md):
# Provider
Abstract LLM backend implementing the Provider trait.
synonyms:: provider, llm backend, anthropic, openai, gemini, cohere, azure, bedrock, vertex, copilot, kimiGenerate .terraphim/thesaurus.json from kg/*.md:
python3 - <<'PY'
import os, json, glob
data, cid = {}, 100
for f in sorted(glob.glob(".terraphim/kg/*.md")):
nterm = os.path.splitext(os.path.basename(f))[0]
txt = open(f, encoding="utf-8").read()
syn = next((l.split("::",1)[1] for l in txt.splitlines()
if l.strip().lower().startswith("synonyms::")), "")
for t in dict.fromkeys([nterm] + [s.strip().lower() for s in syn.split(",") if s.strip()]):
data.setdefault(t.lower(), {"id": cid, "nterm": nterm})
cid += 1
json.dump({"name": "Project Engineer", "data": data}, open(".terraphim/thesaurus.json","w"), indent=2)
PY- Keep
kg/*.mdin version control. - Regenerate
thesaurus.jsonafter any concept or code-identifier change. - Enrich concepts with real code anchors mined by ast-grep (struct/trait/impl names).
- Use name-based mapping rules and avoid file-wide catch-alls that add noise.
Full details and a working enrichment loop are in docs/terraphim-grep-offline-setup.md
and the terraphim-grep-offline skill.
Use standard POSIX tools — do NOT use opencode FFF find_files:
# Find Rust source files matching a pattern
git ls-files '*.rs' | grep "haystack"
# Find files by name (non-git directories)
fd "config.toml" crates/
# POSIX fallback
find crates/ -name "*.toml" -not -path "*/target/*"- opencode FFF
grep— directorypathfilter is broken - opencode FFF
find_files— same bug; usegit ls-filesorfdinstead - opencode FFF
glob— usegit ls-filesglob syntax instead
- Use
tokiofor async runtime withasync fnsyntax - Snake_case for variables/functions, PascalCase for types
- Use
Result<T, E>with?operator for error handling - Prefer
thiserror/anyhowfor custom error types - Use
dynkeyword for trait objects (e.g.,Arc<dyn StateManager>) - Remove unused imports regularly
- Feature gates:
#[cfg(feature = "openrouter")]
- Svelte with TypeScript, Vite build tool
- Bulma CSS framework (no Tailwind)
- Use
yarnpackage manager - Component naming: PascalCase
- File naming: kebab-case
- Never use
sleepbeforecurl(Cursor rule) - Commit only relevant changes with clear technical descriptions
- All commits must pass pre-commit checks (format, lint, compilation)
- Use structured concurrency with scoped tasks
- Implement graceful degradation for network failures
- Never use
timeoutin command line; this command does not exist on macOS - Never use mocks in tests
- Use IDE diagnostics to find and fix errors
- Always check test coverage after implementation
- Keep track of all tasks in Gitea issues using
gitea-robotandteaCLI tools (see Gitea PageRank Workflow below) - Commit every change and keep Gitea issues updated with progress using
tea comment IDX - Use
tmuxto spin off background tasks, read their output, and drive interaction - Use
tmuxinstead ofsleepto continue working on a project and then read log output
- Create individual summaries for each working file in
.docs/summary-<normalized-path>.md - Include file purpose, key functionality, and important details
- Normalize file paths (replace slashes with hyphens, remove special characters)
- Maintain consolidated overview in
.docs/summary.md - Include architecture, security, testing, and business value analysis
- Update documentation references when making changes
- Use
.docs/agents_instructions.jsonas primary reference for project patterns - Contains machine-readable instructions for AI agents
- Includes project context, critical lessons, and established practices
## UBS Quick Reference for AI Agents
UBS stands for "Ultimate Bug Scanner": **The AI Coding Agent's Secret Weapon: Flagging Likely Bugs for Fixing Early On**
**Install:** `curl -sSL https://raw.githubusercontent.com/Dicklesworthstone/ultimate_bug_scanner/master/install.sh | bash`
**Golden Rule:** `ubs <changed-files>` before every commit. Exit 0 = safe. Exit >0 = fix & re-run.
**Commands:**
```bash
ubs file.ts file2.py # Specific files (< 1s) — USE THIS
ubs $(git diff --name-only --cached) # Staged files — before commit
ubs --only=js,python src/ # Language filter (3-5x faster)
ubs --ci --fail-on-warning . # CI mode — before PR
ubs --help # Full command reference
ubs sessions --entries 1 # Tail the latest install session log
ubs . # Whole project (ignores things like .venv and node_modules automatically)
```
**Output Format:**
```
⚠️ Category (N errors)
file.ts:42:5 – Issue description
💡 Suggested fix
Exit code: 1
```
Parse: `file:line:col` → location | 💡 → how to fix | Exit 0/1 → pass/fail
**Fix Workflow:**
1. Read finding → category + fix suggestion
2. Navigate `file:line:col` → view context
3. Verify real issue (not false positive)
4. Fix root cause (not symptom)
5. Re-run `ubs <file>` → exit 0
6. Commit
**Speed Critical:** Scope to changed files. `ubs src/file.ts` (< 1s) vs `ubs .` (30s). Never full scan for small edits.
**Bug Severity:**
- **Critical** (always fix): Null safety, XSS/injection, async/await, memory leaks
- **Important** (production): Type narrowing, division-by-zero, resource leaks
- **Contextual** (judgment): TODO/FIXME, console logs
**Anti-Patterns:**
- ❌ Ignore findings → ✅ Investigate each
- ❌ Full scan per edit → ✅ Scope to file
- ❌ Fix symptom (`if (x) { x.y }`) → ✅ Root cause (`x?.y`)Use gitea-robot MCP tools for task tracking
Gitea at https://git.terraphim.cloud is the authoritative system for all task management. ALL agents (human and AI) MUST use gitea-robot and tea for issue tracking.
source ~/.profile # Loads GITEA_URL and GITEA_TOKENRequired env vars (set in ~/.profile):
GITEA_URL=https://git.terraphim.cloudGITEA_TOKEN-- API token for authentication
- gitea-robot (
/home/alex/go/bin/gitea-robot): PageRank-based issue prioritisation - tea (
/home/alex/go/bin/tea): Gitea CLI for issues, comments, PRs
# Get issues ranked by dependency impact (highest PageRank first)
gitea-robot ready --owner terraphim --repo terraphim-ai
# Full triage with blocked/unblocked status
gitea-robot triage --owner terraphim --repo terraphim-ai
# View dependency graph
gitea-robot graph --owner terraphim --repo terraphim-ai
# Add dependency: issue X is blocked by issue Y
gitea-robot add-dep --owner terraphim --repo terraphim-ai --issue X --blocks YPageRank scores reflect how many downstream issues each task unblocks. Higher score = fix first.
# List open issues
tea issues list --repo terraphim/terraphim-ai --state open
# Create issue
tea issues create --title "..." --repo terraphim/terraphim-ai
# Comment on issue (progress updates, implementation notes)
tea comment IDX "progress update" --repo terraphim/terraphim-ai
# Close issue
tea issues close IDX --repo terraphim/terraphim-aiEach agent session starts with zero memory of prior work. To prevent re-work loops, every implementation agent MUST run this checkpoint BEFORE picking any issue:
git fetch origin 2>/dev/null
echo "=== Existing task branches ===" && git branch -r | grep "task/" || true
echo "=== Open PRs ===" && gtr list-pulls --owner terraphim --repo terraphim-ai --state open 2>/dev/null | head -30Rules:
- SKIP any issue where a remote branch or open PR already exists
- Pick the NEXT unblocked issue from
gtr readyinstead - NEVER re-create a PR that already exists (409 Conflict = skip). Comment on the existing PR instead.
This checkpoint is configured in all ADF developer agent task blocks (conf.d/*.toml) and MUST NOT be removed.
- Start:
source ~/.profile(load Gitea env vars) - Checkpoint: Run the session checkpoint above to skip already-in-progress issues
- Pick work:
gitea-robot ready --owner terraphim --repo terraphim-ai-- choose highest PageRank unblocked issue - Branch:
git checkout -b task/IDX-short-title - Implement: TDD, commit with
Refs #IDX - Update Gitea:
tea comment IDX "Implementation complete. Summary." --repo terraphim/terraphim-ai - PR: Push branch, create PR on GitHub referencing
Refs terraphim/terraphim-ai#IDX (Gitea) - Close:
tea issues close IDX --repo terraphim/terraphim-aiafter merge
feat(module): short description Refs #IDX
Use ONLY subscription-based models:
kimi-for-coding/k2p6-- Moonshot subscription (implementation)opencode-go/minimax-m2.5-- MiniMax subscription/home/alex/.local/bin/claude --model sonnet-- Anthropic subscription (verification)codex-- ChatGPT OAuth
NEVER use opencode/ prefix (Zen pay-per-use).
NEVER use github-copilot/ prefix on bigbox.
This repository has two remotes that MUST stay in sync:
- origin (GitHub:
github.com/terraphim/terraphim-ai) - primary, push here first - gitea (Gitea:
git.terraphim.cloud/terraphim/terraphim-ai) - mirror, push after origin succeeds
Every push to main MUST follow this order:
git fetch origin
git merge origin/main --no-edit
git push origin main
git push gitea mainRules:
- Never force-push to either remote
- Always merge origin into local before pushing (prevents divergence)
- If origin push fails, do NOT push to gitea -- fix the issue first
- If gitea push is blocked by branch protection, create a PR using the status-check workaround:
# Temporarily disable status checks (admin only) curl -X PATCH "$GITEA_URL/api/v1/repos/terraphim/terraphim-ai/branch_protections/main" \ -H "Authorization: token $GITEA_TOKEN" \ -H "Content-Type: application/json" \ -d '{"enable_status_check": false}' # Merge PR, then re-enable curl -X PATCH "$GITEA_URL/api/v1/repos/terraphim/terraphim-ai/branch_protections/main" \ -H "Authorization: token $GITEA_TOKEN" \ -H "Content-Type: application/json" \ -d '{"enable_status_check": true, "status_check_contexts": ["adf/build", "adf/pr-reviewer"]}'
After pushing, verify both remotes are content-identical:
git diff origin/main gitea/main --stat # Must be emptyIf remotes diverge:
- Fetch both:
git fetch origin && git fetch gitea - Diff:
git diff origin/main gitea/main --stat - Merge the richer branch into local
- Push to both remotes using the mandatory sequence above
- Check for duplicates before creating issues (search existing first)
- One issue per task -- no overlapping tickets
- Close issues immediately when work is verified on both remotes
- Close agent-generated issues without clear acceptance criteria
- Autonomous agents can generate duplicate noise -- batch-close with comment explaining reason
When ending a work session, you MUST complete ALL steps below. Work is NOT complete until git push succeeds.
MANDATORY WORKFLOW:
- File issues for remaining work - Create issues for anything that needs follow-up
- Run quality gates (if code changed) - Tests, linters, builds
- Update issue status - Close finished work, update in-progress items
- PUSH TO BOTH REMOTES - This is MANDATORY:
git fetch origin git merge origin/main --no-edit git push origin main git push gitea main git diff origin/main gitea/main --stat # Must be empty - Clean up - Clear stashes, prune remote branches
- Verify - All changes committed AND pushed
- Hand off - Provide context for next session
CRITICAL RULES:
- Work is NOT complete until
git pushsucceeds - NEVER stop before pushing - that leaves work stranded locally
- NEVER say "ready to push when you are" - YOU must push
- If push fails, resolve and retry until it succeeds
The orchestrator can track agent evolution (versioned memory, task history, lessons) across runs. This is supplementary to SharedLearningStore.
# orchestrator.toml
[evolution]
enabled = true
max_memory_tokens = 1500 # Max chars of evolution context in prompts
max_snapshots_per_agent = 100 # Max snapshots before pruning
consolidation_interval_ticks = 200 # Reconcile ticks between memory consolidation
[[agents]]
name = "security-sentinel"
evolution_enabled = true # Opt-in per agentRequires evolution Cargo feature:
cargo build -p terraphim_orchestrator --features evolution
cargo test -p terraphim_orchestrator --features evolutioncrates/terraphim_orchestrator/src/evolution.rs- EvolutionManager wrapperHandoffContext.evolution_snapshot_key- Inter-agent snapshot transferAgentDefinition.evolution_enabled- Per-agent opt-in- Project-level skill:
.skills/terraphim-evolution/SKILL.md - Project-level agent:
.claude/agents/evolution-manager.md