Skip to content

Latest commit

 

History

History
496 lines (449 loc) · 31.3 KB

AGENTS.md

File metadata and controls

496 lines (449 loc) · 31.3 KB

Repository Agent Contract

This file is the repository-wide instruction source for coding agents. Keep CLAUDE.md as a relative symbolic link to AGENTS.md so Codex and Claude Code read the same rules.

For displaying logs and content output, please use the ASD-STE100 specification, or meet 80% of the ASD-STE100 specification.

Product and Architecture

Capstone Agent Framework builds evidence-backed applications over registered business-domain systems. The first formal application is pandapower grid static analysis. The retired grid-agent distribution and CLI have been removed. Formal pandapower application modules belong to pandapower-application. The repository also contains registered PyPSA applications, capability-named Domain Packs, and an independent operator App.

Preserve the four ownership layers:

Application -> Domain Pack -> Kernel -> registered Authority

This is an ownership and dependency direction, not a requirement to import through every adjacent layer. Applications select bindings, providers, public UI/CLI contracts, and compatibility projections. Domain Packs own semantic tools, contracts, policy, guides, execution, projection, and domain state. The Kernel owns neutral composition, bounded context, turns, trajectory, artifacts, replay, and framework core. Registered authorities own model access, deterministic or source-backed facts, revisions, results, and evidence. Results and evidence return through explicit contracts, never raw objects. Read the framework architecture before changing these boundaries.

A new domain needs a separately installable Domain Pack using the public Kernel SPI, a registered authority, and an application-selected binding. Keep domain semantics out of the Kernel. Do not couple one Domain Pack to another's state. Cross-domain model references require an explicit application grant and typed handoff; a public compatibility projection belongs to its application.

Development and Release Architecture

Capstone has three execution lanes: local Compose plus Vite for high-frequency iteration, an isolated cloud-development stage for remote integration validation, and an isolated user-trial stage for stable releases. The local lane is not a substitute for cloud verification, and the cloud-development lane is not a user-data or production lane. Read the normative development and release lifecycle before changing deployment, release, or environment behavior.

  • Cloud development and user trial must never share PostgreSQL, artifact buckets, operator tokens, public origins, or mutable run/session/evidence data.
  • Provider credentials are separate by default. For the current function validation stage, the user permits existing Provider credentials and explicitly selected open Thread access without a login screen. Keep credentials in backend protected variables; do not expose them to the App.
  • API and worker within one stage must use the same tested backend source revision or exact image digest. A user-trial release promotes that exact verified revision or digest; ordinary development pushes must not update the user-trial stage.
  • The local API, worker, and App path is rebuilt with make capstone-local-rebuild before remote validation. Do not test an old Compose image and call the result current.
  • local-dev serves cloud-dev development tests and release verification. local-demo serves cloud-demo reproduction, emergency repairs and release verification. At rest it follows the accepted cloud-demo source and feature scope; record any temporary repair or release candidate difference. Do not update local-demo with ordinary development builds or make the local versions equal solely for convenience. Preserve existing data during source realignment.
  • Cloud-development validation covers readiness, App health, registered cases, Provider behavior, reports, evidence replay, and API/worker identity before promotion. Failed releases roll back to the last verified user-trial revision.
  • After every cloud-dev deployment passes its required validation, create and push an annotated Git tag for that stage. After every demo deployment passes its required validation, create and push a separate annotated Git tag for demo, even when both stages use the same source revision. Use cloud-dev-<YYYYMMDD-HHMM>-<short-sha> and demo-<YYYYMMDD-HHMM>-<short-sha>. Each tag must point to the exact deployed and verified source commit. Its annotation records the stage, source/image identity, deployment IDs, and verification receipt or report. Failed or incomplete validation must not receive an acceptance tag. Never move or reuse an existing tag.
  • Hosted App build variables may contain only the selected API origin. Provider and operator secrets stay in protected environment variables or ignored authentication state and never enter source, logs, arguments, or artifacts.
  • Public demonstration access, when enabled for a no-login App smoke target, remains limited to registered scripted cases and never grants Provider access.

Authority and Model Boundaries

  • A professional Domain Pack session may call only published, allowlisted semantic tools with exact contracts. Do not give it shell commands, arbitrary subprocesses, Python execution, generic file access, caller-selected endpoints, raw DataFrames, pandapowerNet objects, or authority internals.
  • Application-owned general tasks may delegate to the isolated native Pi executor. Its native tools operate only in private task workspaces, without business files, authority handles, or host credentials. General observations and products never become Authority results or simulator evidence implicitly.
  • New tools must describe reusable domain actions, not a particular question, fixture, network, expected answer, or legacy query alias.
  • For pandapower, numerical and network claims cross gridctl through grid-capability/1.0. gridctl and grid-simulator own registered networks, calculations, model revisions, result datasets, and simulator evidence. Never invent losses, voltages, rankings, topology, contingency outcomes, or evidence.
  • PyPSA calculations and model changes stay behind the registered PyPSA authority and its selected Domain Packs. Do not pass raw PyPSA Networks across application, pack, or Kernel boundaries.
  • The model may compose tools and write reader-facing text. Current-run result and evidence references are admitted and bound by the application and Domain Pack, not asserted by the model. Observation and reporting may diagnose a valid answer without replacing authority truth; required answer or evidence persistence failures remain fatal.

Replies and Failure Recovery

  • Every submitted instruction and task must receive a visible reply. Record what finished, what remains open, and where the user can find saved products. Provide a reply even when the task cannot deliver its full result.
  • Record errors and exceptions as execution diagnostics. Preserve saved work and continue all steps that can still run within their admitted scope. Recovery must use verified progress and must preserve existing evidence and authority rules. When a required dependency blocks further progress, return the partial result and give the exact blocker. Keep that work available for recovery.
  • Treat Capstone as a reasoning system that can continue through partial failures. Apply a block to the affected operation. Keep independent work and new user instructions available. Show the stage, saved work, and available next action in user-facing language. Keep internal codes with the diagnostic record.

Public Contracts and Runtime State

  • Enterprise resources must support GB-scale and larger files by design. Keep upload/storage quotas separate from processing and model-context budgets. Use durable versioned resource references and bounded, on-demand access; do not make full-file base64 task payloads or current small-file limits the architecture. Phased delivery must record unimplemented requirements, not weaken them. The owning contract and acceptance gates are in docs/superpowers/specs/2026-10-15-enterprise-design-final.md, section 9.

  • The pandapower compatibility run, analysis, and report paths write exactly one stdout JSON object containing question_id and answer_output. Progress, tool events, warnings, and diagnostics go to stderr. The generic application path uses its separate core plus domains.<binding_id> output.

  • Offline informational answers create no run evidence. Simulator-backed claims may cite only results and evidence admitted for the current run. runs/ is ignored operator-visible evidence and validation-report storage; .grid-agent/ is ignored internal authentication, runtime, cache, and session state. Versioned runtime configuration belongs in configs/runtime/.

  • The hosted App is a presentation client for the same /api/v1 contract locally and in the cloud. Public demonstration credentials are scoped to registered scripted cases; they must not grant Provider access. The browser receives bounded API projections, not bucket credentials or raw artifacts.

  • The API and worker run from the same backend source/image revision and share the PostgreSQL ledger and private artifact storage. Cloud Run, Railway, and local Compose must preserve this contract. Never put operator or Provider secrets in static App build variables such as VITE_API_ORIGIN.

  • Provider credentials belong in environment variables or project-owned ignored authentication state. Never place them in arguments, logs, commits, simulator environments, or answer artifacts.

Sources of Truth

Read the owning source before changing behavior; do not duplicate changing counts, prices, limits, versions, or deployment state here.

Topic Source
Product overview and local entry points README, 中文 README, runbook
Framework layers, output, and evidence Capstone architecture
pandapower capability registration and LLM composition Capability architecture
Published pandapower coverage Executable capability matrix
Simulator pin grid-simulator manifest
Model-facing grid policy and guides Policy, guides
Hosted App and local operations Runbook
Cloud deployment Railway, Cloud Run + Vercel
Development and release lifecycle Lifecycle architecture
Structural state and recovery baton Current state, resume

Working in This Repository

Capstone skill installation and loading

  • For a skill added to one workspace, use Settings → Skills/MCP, the Capstone /api/v1/managed-resources API, or the granted agent_managed_resource tool. Read the workspace catalog and operation contracts before installing. Use an exact upstream Git commit and the declared package subdirectory. Verify the operation receipt and the enabled resource ID and version in the target workspace. In a task, call agent_managed_resource with load_skill for that exact ID and version, then read the admitted read-only SKILL.md. See the managed resource design.

  • For a skill shipped with the Capstone executor, use its versioned runtime configuration and repository skill sources under configs/runtime/general-pi/. The executor applies task scope and session skill preferences. The model sees admitted names and descriptions and loads relevant instructions on demand with agent_skill, operation load. A workspace managed-resource preinstall manifest is a separate deployment mechanism with exact version pins.

  • Do not install Capstone skills with a generic agent installer or by copying files into a user's Pi or Codex skill directories or a task workspace. If installation fails, keep the request ID and report the Capstone entry point, workspace, source revision and returned status. Check an uncertain operation by its original request ID before retrying. Keep experimental bypasses out of supported installation verification. Report catalog availability, actual task loading and successful use as separate observations.

  • Enforce mechanically decidable behavior in code, not through an LLM's interpretation of prompts. This includes namespace conversion, schema and permission checks, reference ownership, version checks, pagination boundaries, and explicit asynchronous continuation instructions. Derive these operations from the current admitted contracts and responses. Keep business interpretation and analysis with the model; do not encode business tool or provider names. Agreed gateway entry names and their protocol adaptation belong only in the data-gateway MCP adapter. Test deterministic guarantees at that boundary.

  • Capability availability must not impose a fixed first action. The model selects relevant tools and skills from the current instruction, accepted context, descriptions and grants. Apply a service's initialization sequence only after selecting that service as relevant. Previous use of a service does not make it relevant to a new instruction. Do not add keyword-based topic routing to enforce this selection.

  • Enterprise application work follows the accepted design baseline, UI contract, and workspace prototype. Build the enterprise workspace from that design and reuse the existing conversation components and interaction details. Do not replace them with a separate message list, composer, or simplified task-record application. A partial backend milestone does not authorize a new UI design. Keep the released conversation application and enterprise application distinct while sharing presentation and execution mechanisms. Check runtime screenshots against the accepted design before claiming frontend acceptance.

  • dev is the default development integration branch. Feature, fix, docs and chore PRs target dev. Experiments enter dev only as scoped reviewed work. main holds accepted release baselines; release PRs target main and run full verification. Hotfixes start from the actual accepted deployment tag and flow back to dev. Do not rewrite shared history.

  • Every working branch must have an owning package, a destination, an acceptance boundary and a recorded next step in the canonical worklist/control register. Keep planning-only work in the backlog until implementation starts. Independent research must record its scope, delivery relationship and resume conditions. At boundaries, check ancestry, patch/content equivalence, PR state and dirty worktrees before closing or archiving a branch. Preserve exact source refs and uncommitted files. An archive is a recovery source, not an active work stream; an old Git ancestor is not proof that its withdrawn feature is still accepted.

  • Browser verification reuses an existing Capstone tab. Do not create a new tab for each test; preserve other open tabs and the user's browser context.

  • Lightweight CI that takes a few minutes does not require separate approval. Run focused local checks first, then start the required scoped CI, including through a push or PR update, without asking again. A needed lightweight rerun after a fix also does not require separate approval. Avoid duplicate runs. Heavy CI expected to take tens of minutes or longer requires explicit user approval before each run. State its purpose, scope and expected execution duration, then wait for agreement before dispatching it or taking an action that triggers it. Do not expand that approved scope without new agreement. Estimate execution time separately from runner queue time: a long queue does not turn a lightweight check into a heavy check. Investigate overruns instead of treating unfinished checks as passed or repeatedly restarting them. Ordinary development and debugging use local checks first; branch integration CI covers only changed behavior and direct consumers. Full suites and dual-platform CI remain reserved for an explicitly approved version release.

  • Current project control and canonical worklists live on dev. Main copies are release snapshots. Both permanent branches require PRs, with zero mandatory approvals and no force push or deletion. Dev and ordinary feature PRs use macOS checks during development; main and explicit release verification require macOS and Linux checks. Record any administrator emergency bypass. Branch heads do not imply deployment.

  • Ordinary dev branch integration is not release acceptance. Use the affected local checks and dev's required PR gate. Do not run check-release or dispatch release=true merely to merge a development branch or obtain extra platform checks. Full release verification is for an explicit release or baseline task.

  • Non-release operations, including development branch merges, PR closeout, documentation and control-state updates, run only focused checks for the changed behavior and its direct consumers. Do not default to full workbench, full repository, professional solver, or dual-platform suites for these operations. Development CI must select this focused scope; a change that lacks a focused route needs a scoped route, not an automatic release-sized gate. Broader development checks need a concrete cross-boundary risk and a recorded reason. Keep ordinary development CI on macOS; reserve full macOS and Linux acceptance for an explicit product release or baseline verification.

  • Keep project control bidirectionally aligned. Changes to implementation, branches, PRs, validation or deployment update docs/status/VERSION-CONTROL.md and its generated PROJECT-OVERVIEW.html. Decisions made through the control graph update owning designs, executable plans, canonical worklist and affected branch copies before reporting alignment complete. Every graph update uses ui-ux-pro-max, re-layout and browser checks, including source edges and crossings. Close verified merged branches; preserve unmerged work and recovery references. The graph centres on active nodes, exact sources for the four deployments and actual research branches. The dev spine retains important cloud deployments and major branch merges. Move ordinary edits and interim candidates into history details; do not label paused plans or archived references as active.

  • The development control graph and its canonical register are owned by dev. Update and integrate them into dev; a feature-branch copy or screenshot alone is not a completed control update. Main contains only a release snapshot. At each major development boundary, record implementation, verification, merge and deployment state before reporting completion. After a PR merge and dependent branch synchronization, refresh the graph in the actual dev checkout and inspect that page. Show current branch HEADs explicitly, even when ordinary control commits are omitted from the milestone graph. Keep those HEADs distinct from product milestones and exact deployed source revisions. The generated snapshot must include a real graph node and verified ancestry edges when the user requests a specific commit as a node; a HEAD badge or explanatory text is not a substitute. For an authorized correction, implement and verify the fix before closing the task; analysis or an apology alone does not complete the request. The generated snapshot records its generation time; do not create an endless commit cycle merely to embed the snapshot's own commit hash. Apply these controls as standing instructions without asking the user to repeat them or repeatedly restating them in progress updates.

  • Use the project control overview as the shared development and release alignment view. Maintain its canonical version register and regenerate the same HTML after material package, branch, PR, validation or deployment changes, before reporting progress. Keep implemented, verified, merged and deployed states distinct. Do not turn planned edges into actual Git merge claims. Keep an overview of the current development focus, important historical deployment commits and important release versions. Show only necessary and important Git nodes, connected through verified Git ancestry. All Git nodes use one content schema: change title, branch and revision, feature changes, verification state and detail links. Deployment cards connect to their exact source nodes and use a background distinct from main. Mainline, branch and deployment-reference edges use distinct visible styles and boundary-aligned arrowheads. Local and cloud cards use distinct backgrounds. Node summaries and feature/acceptance records come from the canonical register. Keep them aligned with actual project state and affected working-branch copies. Prefer a wide layout that shows the full overview without internal scrolling on desktop. Preserve readable node content and accurate edge attachment when re-layout or scaling changes the graph. The actual dev HEAD must also have a visible Git node, not only a top-card badge. Keep explicitly requested commit nodes as fixed milestones. Resolve the current-head node at generation time and deduplicate it when a fixed node has the same commit, so control-only merges do not repeatedly disappear from the graph. Prefer shared-foundation and application research nodes to the right of dev, while balancing card height, deployment cards and whitespace across both sides. Overall visual balance takes priority over a rigid left/right category rule.

  • Keep secondary architecture research in the Capstone core capability evolution notebook as the shared record. It is not the active delivery worklist. Resume this discussion when the user starts it; offer a reminder only at a particularly important design or implementation boundary. Do not automatically make its open questions the next task. Read it before related design work. Ground proposals in the actual implementation and practical grid work. Update the notebook with conclusions, open questions, and implementation feedback; distinguish proposed designs, accepted decisions, and verified behavior.

  • Preserve unrelated tracked and untracked user work. Stage only task-owned paths. Do not delete or migrate existing main-worktree var/ data.

  • At each coherent implementation or verification boundary, inspect Git status and diffs. Separate completed task changes, deferred work, unrelated work and runtime scratch. Commit verified task-owned changes promptly with explicit dependencies and a reviewable scope; do not carry large uncommitted batches across work boundaries or defer this sorting until merge time. If work must remain uncommitted, record its exact paths, reason and recovery reference before starting another unit. Update the journal and recovery state at the same boundary. Before integration, check ahead/behind state, dirty and untracked files, and unmerged dependencies. Never use bulk staging to hide unclear ownership.

  • Prefer rg and rg --files for discovery. Use apply_patch for text edits and explicit non-destructive commands for filesystem operations.

  • Keep README.md and README.zh-CN.md aligned when shared product facts, commands, headings, or references change. Write for readers; move detailed procedures into the runbook and volatile status into docs/status/.

  • Use temporary branches and isolated worktrees for implementation. Unless the user requests branch-only delivery, run the required focused checks and merge the finished change promptly through a PR into dev. Sync the main development checkout to dev and verify the actual entry point before reporting delivery. Merging dev into a temporary branch only updates that branch. After confirming the merge and preserving any remaining work, close the temporary branch.

  • A fresh worktree lacks ignored runtimes. Before testing Pi, gridctl, or JavaScript tools there, run make setup, make install-pi, and make doctor. Missing managed runtimes are setup failures, not product regressions. Do not copy ignored authentication state from another worktree.

Local rebuild and deployment

  • Group Docker source and resource copies by responsibility. Add new files to existing groups; do not add a separate layer for each file or routine update. Keep stable dependencies before frequently changed source. Add a new layer only for a justified cache boundary, and check the final image layer count and cache effect. Preserve the explicit runtime input allowlist.

  • After each local build and its validation/use, clean this project's unused images and build cache with the scoped deploy/cleanup_local_build_cache.py helper. This is a standing maintenance step, not a new service or global prune. Preserve every image referenced by any running or stopped container, other projects, persistent volumes and user data. The canonical rebuild performs scoped maintenance after readiness; if CAPSTONE_LOCAL_CACHE_CLEANUP=0 is used temporarily, the operator must run the helper with --apply after validation/use ends and any existing cleanup is stopped. Do not expand cleanup beyond proven project ownership or use forced image removal/implicit parent pruning.

When local API, worker, or App source changes, use the checked-in rebuild entrypoint instead of starting Compose with an old image:

make capstone-local-rebuild

deploy/rebuild_local.sh loads the ignored deploy/local.env, validates the Compose configuration, rebuilds the API and worker image from the current checkout, force-recreates both roles, waits for PostgreSQL/object storage and the worker, checks /health/ready, verifies that API and worker run the same image digest, and ensures the Vite App is reachable. If the App is not already running, it starts a background dev server and records its PID/log under the ignored .capstone-agent/ directory. Set CAPSTONE_START_APP=0 to skip that step, CAPSTONE_LOCAL_PULL=1 when base images should also be refreshed, or CAPSTONE_LOCAL_ENV_FILE=/path/to/local.env when using a different local environment file. Before the Docker build, the script verifies the six pinned PyPSA assets in .grid-agent/runtime/pypsa-models (or the directory named by CAPSTONE_PYPSA_MODEL_LIBRARY_DIR) and stages them under the ignored deploy/local-model-assets/ build directory, so a local rebuild does not redownload model files. The script never prints secret values.

The App remains a separate Vite development process because Compose does not host the static App. It listens on 0.0.0.0 by default so a phone on the same LAN can open http://<computer-lan-ip>:5173/; set CAPSTONE_APP_HOST=127.0.0.1 to restrict it to the computer. make capstone-app-dev remains the foreground alternative when interactive logs are needed. A stale browser session should be refreshed or reset before starting a new case.

GitHub connectivity on this Mac (Clash Verge)

  • This Mac uses Clash Verge. The observed system HTTP/HTTPS proxy is http://127.0.0.1:7897. A system proxy does not prove that terminal gh, Git, or curl requests use it. Check the current system proxy and shell proxy variables first; use the observed port if it changes.

  • On 2026-11-14, GitHub merge requests repeatedly returned HTTP 502 while read-only requests worked. An explicit Clash proxy made the same approved PR101 merge succeed (0616023f). Do not conclude that GitHub is unavailable from a failed request on one connection path.

  • For GitHub work on this Mac, use process-scoped proxy settings when the shell has no working proxy. Do not change global Git settings, shell profiles, Clash routing or TLS verification for this task:

    HTTPS_PROXY=http://127.0.0.1:7897 HTTP_PROXY=http://127.0.0.1:7897 gh pr view 101
    git -c http.proxy=http://127.0.0.1:7897 -c http.version=HTTP/1.1 fetch origin dev
  • Before retrying a failed write, read the actual remote PR/ref state through the working connection. A timeout or 502 does not prove the write failed. Retry only the still-needed authorized action, with the expected source SHA. Do not repeat a push, workflow dispatch or PR update merely because its response was lost; check remote state first to avoid duplicate CI runs. Lightweight CI needs no separate approval; heavy CI follows the approval rule above.

  • Compare bounded read-only requests with and without the explicit proxy when diagnosing a connection problem. Do not print proxy credentials, auth tokens, subscription URLs or complete private proxy configuration. Record the result and selected connection path in the project journal.

Verification

During early development, keep CI proportional to the changed layer and its consumers. Use the scoped development gates in the lifecycle document; do not run every professional application suite for an isolated agent/App edit. Use macOS for daily development verification. Preserve macOS and Linux support and full dual-platform release acceptance before Linux user trial. Record measured gate duration and investigate timeouts instead of treating an unfinished check as passed.

Run the smallest focused check for the changed behavior, then the repository gates needed for its scope. Supported offline gates are:

make doctor
make test
make test-e2e
make validate

Use the full gates for integration or release claims; a focused App or documentation change does not itself justify repeating every suite. Documentation-only changes require link and symlink checks, git diff --check, and make doctor. make validate-provider REQUEST=<request.json> is optional and may be billed. The user has authorized model/Provider access for development, integration, debugging and verification without repeated permission requests (2026-10-17). Run the real model checks needed for the task. Keep the existing credential protection and deployment boundaries. Acceptance must use real model responses, tool execution and saved products; offline fixtures do not replace real verification. Stop and report clearly abnormal calls, runaway retries or abnormal consumption rather than requesting approval for routine checks. At this early development stage, prioritize a working real task-session path: submit, execute tools, view products, continue, and restore after refresh. Fix execution blockers first. Track non-blocking polish and completeness gaps separately; do not make them new gates for local trial. Every change must preserve the supported Capstone output contracts, authority boundaries, and current-run evidence rules.