Imported from WhereAreMySOCKS/guiji (
AGENTS.md). Install upstream withnpx skills add WhereAreMySOCKS/guiji. Copyright stays with the author.
AGENTS.md
This file guides coding agents working in /Users/paul/Project/guiji.
Project Overview
龟迹 (Gui Ji / CheloniaTrace) is a turtle care platform with four components:
| Directory | Stack | Purpose |
|---|---|---|
guiji-backend/ |
FastAPI + async SQLAlchemy + PostgreSQL + Redis | Authoritative API backend for accounts, workspaces, pets, tanks, equipment, records, taxonomy, AI guides, strategy lifecycle, notifications, admin |
guiji-ios/ |
SwiftUI + SwiftData | iOS app; SwiftData is a local cache/offline draft layer, not the authority |
guiji-next/ |
Next.js 16 + Tailwind v4 + Cloudflare Pages | Public taxonomy encyclopedia and SEO pages |
guiji-admin/ |
React 19 + Vite + TanStack Query | Admin SPA for taxonomy, traits, strategy config, statistics, strategy inspection |
Research materials live outside the runtime apps:
| Directory | Purpose |
|---|---|
species-research/ |
Literature and source collection for turtle taxonomy, husbandry, thermal biology, diet, growth, reproduction, conservation status, and taxon_traits provenance |
Species Research Workflow
Use the local guiji-species-research skill for turtle literature collection, strategy-parameter source discovery, taxon_traits provenance extraction, or research-backed strategy improvement ideas. In the research-only repository, the skill is copied at guiji-species-research/SKILL.md. The live material inventory is species-research/00-research-inventory.md; keep it updated when new PDFs, spreadsheets, manual sources, or blocked-source notes are added.
Use this source hierarchy when collecting or extracting trait evidence:
| Level | Source type | Use |
|---|---|---|
| L1 | Peer-reviewed papers, theses, primary datasets | Preferred source for numeric biological parameters such as temperature, diet, growth, reproductive timing, activity, and hibernation |
| L2 | Taxonomic authorities and conservation databases, including TTWG/TFTSG, IUCN, CITES, Reptile Database | Baseline for accepted names, synonyms, distribution, conservation, maximum size, and range |
| L3 | Zoo/aquarium husbandry manuals and veterinary care sheets, including EAZA, AZA, Tortoise Trust, RSPCA, IHS, LafeberVet | Captive-care calibration when L1/L2 evidence is missing or too coarse |
| L4 | Chinese books, CNKI/Wanfang papers, breeder notes, rescue-center notes, regional practice records | Local context and fallback evidence; mark confidence conservatively |
For every extracted trait or strategy parameter, preserve provenance: species/taxon, parameter, value, unit, source title, source level, page or table when available, confidence, and last verified date. Do not write research-derived values into backend seed data or taxon_traits without a source reference.
Current Architecture Principles
- Backend is the single source of truth for business data.
- Every user-owned business entity belongs to a
workspace_id. - iOS keeps local SwiftData cache and offline-friendly drafts, then syncs backend IDs and
version. - No old strategy status endpoints should be used by the app.
- No compatibility split, version-suffixed replacement API, or duplicate old endpoint should be added.
- Apple Developer Program dependent features are still simulated where needed: APNs, Sign in with Apple, app distribution.
Local Python / pip Environment
For host-side Python commands, scripts, literature tooling, one-off data extraction, or package installation, agents must use the conda environment named opencode.
Use conda run -n opencode ... so commands do not accidentally use system Python, base conda, or another project environment:
conda run -n opencode python -V
conda run -n opencode python path/to/script.py
conda run -n opencode python -m pip install <package>
conda run -n opencode python -m pip show <package>
Do not run host-side pip install, pip3 install, or python -m pip install outside opencode. If a Python command runs inside Docker, such as docker compose exec api python ..., use the container's Python instead and do not involve the host conda environment.
Backend Commands
cd guiji-backend
docker compose up -d
docker compose restart api
docker compose logs -f api
docker compose exec api alembic upgrade head
docker compose exec api python -m compileall app scripts
Content seed/import:
docker compose run --rm api python scripts/import_taxonomy.py
docker compose run --rm api python scripts/seed_traits.py
docker compose run --rm api python scripts/import_pdf_guides.py
docker compose run --rm api python scripts/link_guides_to_species.py
pdf_page_guides_data.sql is required content data. It contains the AI guide rows for pdf_page_guides. Production deploy imports it automatically when the table is empty, then rebuilds pdf_page_species links.
Database
Alembic now uses one destructive canonical migration:
guiji-backend/alembic/versions/001_core_schema.py
revision = "001_core_schema"
Old migration chains were intentionally removed. Do not reintroduce incremental compatibility migrations for the pre-refactor schema.
Core tables:
| Table | Purpose |
|---|---|
users |
Account subject only |
auth_accounts |
Login providers: phone, apple, wechat |
workspaces |
Personal/family data space |
workspace_members |
User membership and role in workspace |
devices |
App device, push token, app/os metadata |
tanks |
Backend-authoritative tank profile; feeding/environment/location mode |
pets |
Backend-authoritative pet profile; tank relation and feeding membership |
pet_measurements |
Weight/length history |
equipment |
Tank equipment and lifecycle |
equipment_assignments |
Equipment assignment to tank/pet scopes |
pet_records |
Feeding, measurement, water change, health, note records |
batch_record_groups |
Batch quick-record grouping |
feeding_strategies |
Only authoritative feeding strategy lifecycle table |
feeding_plan_states |
Current per-pet countdown/state derived from active strategy |
feeding_executions |
Confirmed feeding executions |
strategy_refresh_logs |
Strategy preview/create/refresh/rule-preview logs |
entitlements |
Workspace feature quota, including AI strategy quota |
entitlement_usages |
Quota reserve/release/consume history |
taxonomy_nodes |
Taxonomy tree |
taxon_traits |
Strategy-relevant inherited species traits |
taxonomy_media |
Taxonomy images/media metadata |
pdf_page_guides |
AI guide content generated from PDF pages |
pdf_page_species |
Bridge from guide entries to taxonomy nodes |
strategy_config_overrides |
Admin-editable strategy config overrides |
audit_logs |
Key audit events |
sync_events |
Incremental sync events |
Backend API Shape
Platform CRUD endpoints:
GET/POST/PUT/DELETE /api/v1/tanks
GET/POST/PUT/DELETE /api/v1/pets
GET/POST/PUT/DELETE /api/v1/equipment
GET/POST /api/v1/pet-records
GET /api/v1/sync/changes
Unified feeding strategy endpoints:
GET /api/v1/strategy/feeding-strategies
GET /api/v1/strategy/feeding-strategies/active
POST /api/v1/strategy/feeding-strategies/preview
POST /api/v1/strategy/feeding-strategies
POST /api/v1/strategy/feeding-strategies/{id}/refresh
POST /api/v1/strategy/feeding-strategies/{id}/rule-preview
POST /api/v1/strategy/feeding-strategies/{id}/confirm
POST /api/v1/strategy/feeding-strategies/{id}/pause
POST /api/v1/strategy/feeding-strategies/{id}/resume
DELETE /api/v1/strategy/feeding-strategies/{id}
Do not call or recreate pre-refactor app strategy endpoints. The app must use the unified feeding strategy endpoints above.
Feeding Strategy Rules
feeding_strategiesis the only lifecycle authority.scopeispetortank.modeisruleorai.- Preview never persists, never consumes quota, never updates current state.
- Create/refresh persists
result_snapshot,params_snapshot, plan states, logs, and refresh counters. - AI create reserves entitlement quota; deleting an active AI strategy releases quota.
- Confirm writes
feeding_executionsandpet_records, then recalculates next countdown. - Tank strategy only applies to pets whose
feeding_membership == "batch". - Changing tank batch organization does not auto-create strategies.
- Automatic temperature normalization is backend-authoritative: when
is_manual_temp=false, backend derives effective temperature from weather/location.
AI Strategy
AI strategy calls are backend-only. iOS and frontend never receive API keys or prompts.
Important files:
guiji-backend/app/domain/strategy_ai/service.py
guiji-backend/app/domain/strategy_ai/prompts/system_individual.zh.md
guiji-backend/app/domain/strategy_ai/prompts/system_tank.zh.md
DeepSeek config lives in .env:
AI_STRATEGY_MOCK_ENABLED=false
AI_STRATEGY_API_KEY=
AI_STRATEGY_BASE_URL=https://api.deepseek.com
AI_STRATEGY_MODEL=deepseek-chat
iOS Architecture
Core services:
| File | Role |
|---|---|
Core/PlatformSyncService.swift |
Backend CRUD sync for tanks, pets, equipment, records |
Core/StrategyService.swift |
Unified feeding strategy API client |
Core/StrategySyncService.swift |
Orchestrates strategy refresh/confirm/delete and SwiftData cache updates |
Core/FeedingStrategyDomain.swift |
Local strategy cache model and mapping |
Core/TankStrategyService.swift |
Outlier-only tank strategy helper |
SwiftData models still contain UI/cache mirrors for strategy card display. Treat backend strategy state as authoritative and write cache only through strategy sync/coordinator paths.
iOS build check:
cd guiji-ios
xcodebuild -project "Gui Ji.xcodeproj" -scheme "Gui Ji" -sdk iphonesimulator -destination 'generic/platform=iOS Simulator' build
Do not launch Simulator unless explicitly requested.
Admin
Admin must use the current schema:
- strategy scope filter:
pet | tank - strategy list includes
workspace_id - statistics read strategy counts, AI/Rule counts, refresh logs, entitlement quota
- taxonomy CRUD uses
taxonomy_nodes + taxon_traits, not a separatespeciestable
Build:
cd guiji-admin
npm run build
Next.js
Public encyclopedia uses backend taxonomy tree/search and taxonomy detail pages.
taxonomy_nodes.slug/name_zh/name_en/latin_name/image_url/seo_summaryfeed SEO pages.- AI guide detail content comes from
/api/v1/taxonomy/nodes/{node_id}/guide. - Taxonomy images come from backend
image_urlor PDF page image fallback.
Build:
cd guiji-next
npm run build
Known warning: Next.js 16 warns that middleware.ts should migrate to proxy.ts; this is not a database refactor blocker.
Coding Constraints
- Prefer
rgfor search. - Keep route handlers thin; domain logic belongs under
app/domain. - Avoid lazy-creating pets/tanks inside strategy logic.
- Use backend IDs for strategy ownership.
- Keep prompt templates outside Python business code.
- Do not reintroduce removed compatibility endpoints.
- Do not revert user changes or unrelated dirty work.
