--- name: planet-rules description: Planet repository rules split into LLM-loadable modules. --- # Planet Rules **These rules are mandatory. If a requested action conflicts with this file, stop and report the conflict.** ## Loading Protocol Read this top section first, then load only the modules relevant to the task. Always load: - `core` - `security` - `workflow` Load selectively: | Module | Load when | |--------|-----------| | `docs` | Writing, translating, linking, or publishing documentation | | `uiux` | Visual design, layout, interaction, accessibility, responsive behavior | | `frontend` | React, TypeScript, CSS, Vite, Bun, admin console, docs UI | | `backend` | FastAPI, SQLAlchemy, data collectors, database, API performance | | `earth` | 3D Earth, canvas/Three.js, BGP/vessel/satellite/cable layers, map icons | | `ai` | AI Provider, LLM gateway, prompts, model config, AI Playground | | `release` | Version bumps, changelog, version history, commit/tag/push release work | Do not load the entire file by default for small tasks. Use `rg -n "^## Module:" rules.md` to find module boundaries, then read only the needed block. ### Agent Discovery Index Use these shortcuts when the user describes work in product language instead of module names. Matching one of these phrases means the related module is relevant, even if the exact module name is not mentioned. | User wording / touched surface | Load modules | | --- | --- | | `一屏`, `首屏`, `高度没控住`, page grows past viewport, scroll/overflow, spacing/breathing, responsive, accessibility | `uiux`, `frontend` | | Admin console, 控制台, sidebar/menu/search/tabs/dialog/table, theme/language switch, i18n, auth pages, public Docs UI | `frontend`, plus `uiux` for rendered/layout changes | | Docs, 文档, 中英文, public Docs, manual, quickstart, README, plan status, stale route/section links | `docs`, plus the implementation module for the changed behavior | | API, FastAPI, database, SQLAlchemy, collector, datasource, scheduler, credential/connectivity, pagination, slow endpoint | `backend` | | Earth/地球, 3D/canvas/Three.js, BGP/vessel/satellite/cable, terrain/clouds, marker/icon, hover/lock/tooltip, flicker/z-fighting | `earth`, plus `uiux` for visible controls | | Earth HUD 卡片/面板, `卡片材质`, `鼠标跟随发光`, `液态玻璃`, `透光`, `焦点层级`, `置顶`, `UI对齐`, `壳层统一` | `uiux`, `earth` | | AI Provider, model provider, Playground, prompt, mapping, custom collector, base URL, service token, OCR/WebSearch/Tavily integration | `ai`, plus `security` for credentials | | Version/changelog/history/tag/release, `发版`, `发布`, `打包`, `版本号`, commit/push release work | `release`, `workflow` | | Secrets, `.env`, API key, token, password, credential masking, auth/JWT/logout, logs containing sensitive data | `security`, plus touched implementation module | | Dependency/package-manager/tooling, Bun/uv, npm/pnpm/yarn, lockfiles, dirty worktree, generated output | `workflow` | --- ## Module: core ### Load When Always. ### Must - Keep functions small and focused; one concern per file/module. - Write self-documenting code; comments explain why, not what. - Prefer dependency injection for testability. - Use feature flags for incomplete features. - Use config files or environment variables for environment-specific settings. - Maintain one source of truth for business state. Temporary UI state, cached state, and persisted backend state must not become parallel truths. - When behavior is not specified, prefer established behavior and conventions in nearby code. Understand the intent, assumptions, side effects, and scope of an existing implementation before reusing it. Adapt when the new context has a meaningful difference, and explain that difference rather than copying mechanically or inventing unrelated behavior. - Transitional paths are temporary. Once a new implementation is stable, remove old branches, old interfaces, old mocks, and compatibility layers. - Extract repeated request flow, response handling, auth/header assembly, validation, and state reconciliation into helpers or shared layers. - Centralize default values, system prompts, placeholder structures, and fixed constants. - Public interfaces, persisted fields, and state structures must have a current owner and caller. Delete unused ones. - After large feature work, run an explicit cleanup pass for dead code, duplicated helpers, stale interfaces, and naming drift. ### Code Style - Python: 4-space indentation, Black style, max line length 100. - TypeScript: 2-space indentation, Prettier style, max line length 100. - No trailing whitespace. - Empty line at end of file. - Sort imports alphabetically inside groups. - Never use wildcard imports. - Avoid unclear abbreviations except common ones such as `id`, `ok`, `err`. - Prefer descriptive names. - Keep functions around 50 lines or less where practical. - Split files before they become mixed-responsibility modules. ### Import Order Python: ```python # stdlib -> third-party -> local import json from datetime import datetime from fastapi import APIRouter from sqlalchemy.orm import Session from app.core.config import settings ``` TypeScript: ```typescript // React -> third-party -> local import { useEffect, useState } from 'react' import axios from 'axios' import { api } from '@/services/api' ``` ### Type Rules - Use type hints throughout Python. - Define TypeScript interfaces/types for all structured data. - Avoid `Any`; use specific unions, generics, or `unknown` where appropriate. - Prefer typed helpers over repeated type casting. ### Verify - Use deterministic checks before broad manual inspection: ```bash git diff --check rg -n "TODO|FIXME|console\.log|debugger|print\(" ``` --- ## Module: security ### Load When Always. ### Must - Never commit `.env`, secrets, keys, tokens, or credentials. - Use environment variables or the configured settings store for credentials. - Validate and sanitize user input. - Use parameterized database queries. - Never store plain-text passwords. - Hash passwords with bcrypt/argon2. - Use short-lived JWT tokens when auth tokens are involved. - Use token blacklist or equivalent revocation support for logout. - Do not expose full tokens in UI. Show only a short prefix and mask the rest. ### Verify ```bash git diff --name-only HEAD rg -n "api[_-]?key|client_secret|BEGIN .*PRIVATE KEY|AKIA[0-9A-Z]" . ``` --- ## Module: workflow ### Load When Always. ### Harness - `rules.md` is the active repository rule source. Keep durable constraints here instead of duplicating them across prompt files. - Use `.codex/skills/` for specialized Codex workflows such as cleanup, docs, goal-driven work, and release. - Do not add new legacy harness entry points when an existing skill or rule module can carry the same instruction. - Keep confirmed operational failure causes in the error catalog in `docs/technical/{zh,en}/ops-runbook.md`. `planet.sh` diagnostics must read causes and remedies from this catalog. Add a stable error code, matching evidence, and a regression case when fixing a previously unclassified cause; unknown failures must remain explicitly unclassified until verified. - If a harness rule is no longer true for the current toolchain, update or delete it in the same cleanup pass. ### Coding Agent Model Strategy This policy applies to repository development agents, not the product's `aiprovider` model settings. Preserve the user's selected main-agent model; these preferences do not switch a running task or change global Codex settings. When delegation is explicitly authorized by the user or an applicable skill, select workers by task scope and verification difficulty: | Work | Preferred model | Initial reasoning effort | | --- | --- | --- | | Bounded implementation, ordinary bug fixes, focused tests, code review | `gpt-6-sol` | `medium`; `high` for interacting modules | | Narrow file discovery, evidence extraction, mechanical docs updates, small deterministic edits | `gpt-6-luna` | `low` or `medium` | | Architecture, ambiguous requirements, difficult rendering/performance bugs, security-sensitive reasoning, repeated failed fixes | `gpt-6-astra` | `high`; increase only when evidence justifies it | - These are project routing preferences, not measured Planet benchmarks. Model roles follow [OpenAI model guidance](https://developers.openai.com/api/docs/models), checked on 2026-09-23. Use the actual host/tool model and effort catalog; API-supported settings do not automatically imply Codex tool support. - Keep small or tightly coupled tasks with the main agent. Delegate only bounded, independent work that can progress alongside useful main-agent work; avoid parallel edits to the same files and do not create agents merely to fill slots. - Give each worker its objective, owned paths, constraints, relevant evidence, and acceptance checks. Prefer a concise handoff over copying the entire history. - Start directly with the model appropriate to the risk. Escalate Luna to Sol, or Sol to Astra, when scope exceeds the assigned task or a failed verification remains unresolved after one focused correction. Pass the reproduction, attempted fixes, and remaining uncertainty; do not repeat blind retries. - The main agent owns integration and final verification. Luna findings are evidence inputs, not sole sign-off for security, migrations, releases, or complex Earth rendering. All tiers retain the same test and visual gates. - If the preferred model is unavailable, use the current capable model and disclose the fallback. Do not silently downgrade or assume older model names are aliases. Record actual validation outcomes rather than promising savings. ### Git - Do not revert user changes unless explicitly requested. - Do not force push to protected branches. - Use clear commit messages. - Run relevant tests and builds before committing. - Frontend package management must use Bun only. - Never use `npm`, `pnpm`, or `yarn` in the frontend project. - Verify package legitimacy before adding dependencies. - Prefer maintained, widely used libraries. - Pin dependency versions in `pyproject.toml`, `uv.lock`, and `package.json`. ### Visual Evidence Gate - If the user provides a screenshot, image, video frame, visual mock, browser capture, or says something like "as shown", obtain evidence from that artifact before interpreting the request or changing code. - Path resolution is part of the task. If a provided path does not open, try reasonable local equivalents first, such as WSL/Windows path conversion, workspace-relative paths, absolute paths, and attached-file locations. - If the artifact still cannot be found or opened, stop that visual-dependent work and report the exact path/access problem instead of guessing. Ask for an accessible file/path or a fresh screenshot. - Do not infer visual intent from the filename, surrounding text, alt text, logs, or prior assumptions. - OCR is acceptable evidence for text-only questions or when the active environment lacks multimodal image viewing, but state that OCR was the fallback. Layout, color, spacing, pixel, and rendering issues still require a real visual inspection or an explicit "could not verify visually" note. - After inspecting the artifact, ground the work in at least one concrete observed detail when it affects the task. - For UI or rendering fixes that depend on appearance, verify with a real screenshot or browser render when the project can be run locally. ### Deterministic Context - Prefer compact CLI evidence over reading large files or full diffs: ```bash git status --short git diff --stat HEAD git diff --name-only HEAD git diff --unified=0 HEAD -- rg -n "" ``` --- ## Module: docs ### Load When Writing, translating, linking, restructuring, or publishing docs. Also load this module when the user mentions docs in Chinese or product terms: `文档`, `中英文`, `双语`, `public Docs`, `手册`, `quickstart`, `README`, `计划`, `plan`, `过期说明`, `路由文档`, `section 链接`, or asks to make rules easier to discover. ### Must - Chinese docs under `docs/technical/zh/` must be Chinese prose, not copied English placeholders. - Keep technical identifiers, API paths, config keys, code symbols, and product names in English where appropriate. - Choose the format and details that help the intended reader complete the task. Include rationale, examples, file references, or verification steps where they help. - Prefer updating an existing relevant doc over creating a duplicate. - Use `##` and `###` headings; avoid going deeper than three levels. - Use fenced code blocks with language tags. - Do not reference PR numbers, issue numbers, or the current conversation. - Internal links inside `docs/technical/zh/` should point to `docs/technical/zh/...` unless intentionally linking to English-only docs. - Public Docs UI must only expose documents explicitly registered in `frontend/src/pages/Docs/docs-content.ts`. - Development plans and task notes under `docs/plans/` are not automatically public documentation. ### Verify ```bash git diff --stat HEAD git diff --name-only HEAD ls docs/technical/zh/ rg -n "\]\(([^)]+)\)" docs/technical/zh/.md rg -n "/home/ray/dev/linkong/planet/docs/technical/(?!zh|en)" docs/technical/zh --pcre2 ``` Check zh/en duplicates: ```bash python - <<'PY' from pathlib import Path same = [] for en in sorted(Path("docs/technical/en").glob("*.md")): zh = Path("docs/technical/zh") / en.name if zh.exists() and en.read_text() == zh.read_text(): same.append(en.name) if same: raise SystemExit("identical en/zh docs: " + ", ".join(same)) print("no identical en/zh docs") PY ``` --- ## Module: uiux ### Load When Changing layout, visual hierarchy, controls, interaction states, responsive behavior, or accessibility. Also load this module when the user mentions Chinese layout terms such as `一屏`, `首屏`, `高度没控住`, `页面撑出`, `滚动`, `溢出`, `呼吸感`, `间距`, or `响应式`. ### Hard Rule: Admin One-Screen Workspaces Backend/admin pages are compact single-screen workspaces (`一屏` / `首屏`): - The route shell must resolve to the viewport through the existing `html`, `body`, `#root`, route-root, and page-shell `height: 100%` chain. - Intermediate shell nodes such as theme providers must not break the height chain; they need `height: 100%`, `min-height: 0`, and explicit overflow ownership when they wrap the page shell. - Header, summary/controls, main work area, and fixed sidebar account/actions must remain inside the first viewport on common desktop sizes. - Long menus, tables, detail panels, logs, Markdown, JSON, and forms scroll inside their intended region; the document/body/root must not become the scroll owner. - A build is not enough for height-critical changes. Use rendered validation on the affected admin routes, and include 125% / 150% zoom when the change touches shell, sidebar, panel, table, or scroll ownership. - Keep sidebar header (`.admin__brand`) and content topbar (`.admin__topbar` / `.admin__content`) aligned on one shared `--an-header-height` token (`flex: 0 0 var(--an-header-height)` on `.admin__brand`, `grid-template-rows: var(--an-header-height) minmax(0, 1fr)` on `.admin__content`) so the horizontal divider stays flush across desktop and zoom levels. - Transient search spotlights and focus rings must not rely on outward `outline-offset > 0` or wide outer `box-shadow` directly on nodes inside `overflow: hidden` / `overflow: auto` / `overflow-x: auto` regions: - Render Admin search spotlight frames at the shell overlay layer (`AdminSearchSpotlight`) clipped/clamped to the content stage rather than inside scrolled child containers. - Keep `:focus-visible` outlines inset (`outline-offset <= 0`) inside clipped regions, and give horizontal scroll strips like `.an-section-tabs` symmetric negative-margin/padding bleed (`margin: -4px; padding: 4px;`). ### Must - Backend/admin pages are single-screen workspaces first, not long landing pages. - Common desktop viewports should show the page header, summary/controls, and main work area. - The main work area gets most available height. - If text, controls, or tables become unreadable, give that region an internal scrollbar instead of crushing it. - Overflow ownership must be explicit: - parent height chain is valid - height-constrained flex parents use `min-height: 0` - only the intended scroll node owns `overflow: auto` - Do not use `overflow: hidden` as a final fix unless another child owns scrolling. - Tabs define their own scroll strategy; hidden panes must stay hidden. - Long-form content such as AI briefs, logs, Markdown, raw JSON, and help text should stay readable. - Prefer stable readable minimum heights plus scrolling for constrained content. - Avoid brittle `100vh/100vw` in embedded/admin shells; prefer `height: 100%` chains. - Verify layouts under browser zoom 125% and 150% when changing height-critical screens. - Avoid wrapper components with implicit layout behavior, such as `Space`, in height-critical scroll regions unless the generated DOM is accounted for. - Any UI state that hides data or a layer must also reconcile hover, lock, tooltip, and selection state. ### Visual Controls - **Existing-UI Context Inspection Before Editing (Non-New Interfaces)**: When adding or modifying UI in an existing area (anything other than a brand-new standalone screen), first inspect surrounding sibling components, CSS load order, selector specificity, tokens, and icon conventions before authoring DOM or CSS. Do not introduce ad-hoc icon styles, sizes, emojis, or layout patterns that clash with surrounding controls. - Before editing UI, inspect the existing shared component, state transitions, and animations. Preserve and reuse their appearance, timing, easing, and interaction behavior unless the user explicitly requests a change; bug fixes must not silently remove existing animations. - Shared-component reuse includes the actual surface, header, spacing, controls, and motion behavior. Do not wrap a shared class and then replace its appearance with page-local overrides. - **Icon System Consistency**: - In `/earth/` (`frontend/public/earth/`), HUD controls use the local `"Material Symbols Rounded"` icon font (`css/fonts.css`), whereas canvas/Three.js map symbols use SVGs under `frontend/public/earth/assets/icons/`; never place raw Unicode emojis inside desktop HUD controls or workbench blocks. - Because `css/fonts.css` loads after panel CSS and defines `.material-symbols-rounded { font-size: 24px; }` at specificity `(0, 1, 0)`, every sized icon rule in `/earth/css/` must use specificity `>= (0, 2, 0)` targeting `.material-symbols-rounded` (never bare `(0, 1, 0)` `.…-icon` rules and never `!important` overrides), lock `font-variation-settings: 'FILL' 0, 'wght' 400, 'GRAD' 0, 'opsz' 20` (unless an explicit component rule such as toolbar owns its weight), size box bounds to `width: 1em; height: 1em; display: inline-flex; flex: 0 0 auto; overflow: hidden;`, match surrounding sizes (`15–16px` header icons, `12.5–14px` pill/chip/block icons), and use only glyphs supported by `material-symbols-rounded-500.ttf`. - In Admin / Docs React UI (`frontend/src/`), use `lucide-react` icons paired with Tactile UI / Radix primitives matching surrounding button and badge scale rather than raw Unicode emojis, unstyled SVGs, or Material Symbols ligature strings. - Emphasizing primary values must retain essential context, units, dates, coverage, and source access. Do not silently remove or hide information to make the main value larger. - Mobile adaptation must reorganize the workflow for the available screen: concise overview and on-demand settings with preserved selection/scroll. For compute regions, expand the selected short card in place with the existing smooth collapse animation; a second tap collapses it and opening another collapses the previous card. Do not add a separate detail page for this interaction or simply shrink/stack desktop windows inside a mobile drawer. Reuse shared data and mobile controls without duplicating business state. - Distinguish deliberate manipulation from passive viewing. Keep readable overlays stable during scene motion; update their attachment geometry independently, and reconsider placement when the interaction ends or usable layout space changes. - Apply effects only to the requested target: background fading must not fade text, color correction must not impose a colored veil, and a scoped rollback must not trigger new visual tuning. - Verify the complete affected flow on the actual rendered page, including bright/dark backgrounds and relevant screen sizes. Computed CSS, unit tests, or a build alone are not visual acceptance; a correction must be checked for analogous failures in related states. - Use icons in buttons for common tools/actions when an established icon exists. - Keep icon-only buttons accessible with `aria-label` and `title`. - Use segmented controls for modes, switches/checkboxes for binary settings, sliders/inputs for numeric values, menus/selects for option sets, and tabs for views. - Connection-test actions for endpoint/Base URL inputs must use the shared `ConnectionTestInput` pattern: a single plug/connector icon at the input suffix, no adjacent text button; disabled integrations should grey out the field and its test action. - Do not put cards inside cards. - Do not use visible in-app text to explain obvious UI features or styling. - Let layout explain: state, grouping and available actions must be readable from control type, placement and alignment (switches for persistent state, buttons for actions, contextual toolbars that appear with a selection, dimmed rows for out-of-filter items). Fix an unclear layout instead of adding helper captions, hint paragraphs or inline instructions. - Text must fit within its parent on mobile and desktop. - Do not scale font size with viewport width. - Letter spacing should usually be `0`. ### Admin Control Design Contract (Mandatory Baseline) - **Control Density Tiers**: `.admin-theme-root` defines and components reuse 4 explicit height/radius tiers so controls sharing a horizontal row stay optically flush and never cause row-height jumps when dynamic buttons mount or unmount (`heightDelta === 0`): - `--an-control-xs` (`28px`, radius `6px`, `12px`/`500`, `14px` icon): table row `操作` icon buttons (`.an-table-actions .tui-button--icon`) and compact inline micro-actions. - `--an-control-sm` (`32px`, radius `6px`, `13px`/`500` and `600` active, `14–15px` icon): filter-bar controls (segmented bars, `