# Agent Working Contract

> Canonical path: `specs/repository/agent-working-contract.md`
> Status: living policy
> Scope: repository-wide rules for agent execution discipline, implementation quality, testing, documentation sync, pull requests, and commits.

## 1. Purpose

This contract keeps `AGENTS.md` short while preserving the durable working rules agents must follow in AgentTeam. It applies to design, implementation, review, testing, and documentation work unless a closer `AGENTS.md` or a narrower canonical spec adds stricter requirements.

## 2. Execution Discipline

Before proposing a design, implementation plan, or code change, inspect the relevant code, configuration, tests, and documentation until the important behavior, constraints, and interfaces are clear. Do not infer behavior from names alone when the code can be inspected directly.

For trivial tasks, keep the process lightweight, but still avoid guessing when a wrong assumption would change the result.

Before non-trivial implementation, state the working assumptions and success criteria. If a request has multiple plausible meanings that cannot be resolved from local context, ask before editing.

Choose the smallest change that fully solves the real problem. Do not add speculative features, fallback chains, configurability, defensive complexity, or abstractions for single-use code.

Keep edits surgical, but leave touched code coherent. Avoid unrelated cleanup, adjacent formatting churn, or opportunistic refactors.

Match existing style unless local style directly causes the issue being fixed.

If requested work exposes duplicated or awkward code in the touched area, simplify it when that reduces the final diff and preserves behavior.

Remove imports, variables, functions, wrappers, tests, branches, or small local duplication made unused or unnecessary by your own changes.

Mention unrelated dead code or questionable patterns outside the touched area instead of deleting them.

Every changed line should implement the request, verify it, or keep directly touched code simpler than the alternative. If the implementation starts to sprawl, stop and simplify before continuing.

## 3. Maintainability Rules

- Prefer boring code. Obvious, self-explanatory code is better than clever code.
- Keep single responsibility. A function or unit should do one job clearly.
- Keep only what is used. Do not future-proof by default.
- Prefer explicit over implicit.
- Use abstractions only when they reduce cognitive load and make ownership or behavior easier to reason about.
- Keep DRY only when it does not make the code less obvious.
- Do not reinvent a reliable third-party library when it materially simplifies the code.
- Do not treat "looks similar" as "equivalent"; verify semantics before sharing logic or paths.
- Prefer certainty and a single source of truth. Do not introduce optionality or parallel representations unless they are truly necessary.
- When adopting a library that is not widely used or well-known, audit its code before depending on it.

## 4. Performance Expectations

Assume AgentTeam is infrastructure software unless local context clearly indicates otherwise. Optimize for production performance, especially on hot paths such as RPC/read paths, search, scheduling, background workers, and realtime delivery.

Prefer designs that remove unnecessary work instead of layering on checks, fallbacks, or complexity.

When updating performance-sensitive code, explicitly check:

- RPC fanout: avoid N+1 patterns, batch or range-scan where appropriate, deduplicate keys, and do not fetch unused metadata or values.
- IO: avoid broad scans, keep bounds tight, respect limits, and exit early.
- CPU: hoist invariant work out of loops and reduce unnecessary branching in hot loops.
- Memory: avoid per-item allocations, avoid cloning large buffers unless required, and reuse scratch buffers where safe.
- Async and concurrency: parallelize independent async work only with an explicit cap, and never hold locks across `.await`.
- Locks and contention: minimize lock scope and frequency; keep lock ordering deterministic.
- Copies and conversions: reduce encode/decode churn and prefer zero-copy paths where safe.
- Cache friendliness: keep hot data contiguous and give caches explicit budgets and invalidation behavior.
- False sharing: avoid frequent writes to shared cache lines; batch or shard hot counters when needed.
- Failure-mode performance: check timeout, retry, backoff, partial-result, backpressure, and observability cost behavior.

When behavior changes in a hot path, include concise before/after evidence from metrics, logs, a focused benchmark, or targeted test output when feasible.

## 5. Project-Specific Rules

- Repo-owned skills live canonically under `skills/`. If the active runtime needs local installed skills for discovery, sync them into `.agents/skills/`; do not edit `.agents/skills/` independently, and do not install repo-owned skills into user-wide or global skill directories.
- Repo-owned skills use `skills/{skill-name}/SKILL.md`. The directory name and frontmatter `name` must match in lowercase kebab-case, and frontmatter `description` must describe when the skill should trigger. Keep repeated procedural workflows in skills; keep one-off plans, scratch notes, and PR context out of skills.
- Any new user-facing feature, workflow, or UI copy must ship with complete i18n support from the start. Do not hardcode new React UI copy; add locale keys, English and Chinese translations, and relevant test updates.
- For schema, migration, or core storage changes, read `specs/storage/storage.md` and the relevant current implementation notes in `docs/tech_design.md` first.
- The canonical TiDB schema lives in `internal/tidb/bootstrap.sql` and `internal/tidb/migrations/*.sql`; do not update one path without checking whether the other must change.
- Do not introduce a second core storage backend or alternate migration timeline.
- Keep related docs in sync with behavior changes: product behavior changes require the relevant canonical spec; user workflow changes require `docs/public/`; daemon or CLI changes require `desktop/README.md` for user-facing runbooks and `specs/daemon/` for canonical daemon architecture/contracts; local development command changes require `docs/development.md`.
- Treat `docs/public/` as rendered user-facing documentation, not as an independent source of truth. Resolve conflicts against canonical specs and current implementation.
- Do not edit generated or vendored artifacts such as `node_modules/`, `web/dist/`, Electron `dist/`, coverage output, or compiled binaries unless the task explicitly requires investigating or regenerating those artifacts.
- In code already being touched, remove pass-through wrappers that add no validation, naming clarity, ownership boundary, or behavior after verifying callers.
- In code already being touched, remove nil checks that cannot fire because the caller guarantees a non-nil value or the value was just constructed. Keep checks at real trust boundaries.
- Avoid speculative abstractions, hidden fallback chains, and compatibility hacks unless a canonical spec explicitly requires them.
- In Go tests, prefer `testify/require` and direct assertions over clever dynamic helpers.

## 6. Frontend Rules

- Do not introduce card-like containers, tinted panels, or rounded boxed shells unless they clarify a real repeated item, modal, or tool surface. In boards, lanes, page sections, and layout scaffolding, prefer light boundaries over nested card shells.
- For shared frontend primitives such as buttons, inputs, checkboxes, dialogs, popovers, dropdown menus, selects, tabs, and tooltips, use `web/src/agentteam/components/ui/` as the source of truth.
- Do not introduce a separate frontend package abstraction for shared primitives; public-site and ops should reuse public UI from `web/` when more than one app needs the same primitive.

## 7. Design Documents

Design documents must be self-contained, internally consistent, and written for readers who do not have prior conversation context.

Use an objective, documentation-oriented tone. Do not refer to private discussion context or to any specific person who requested the document.

Explain enough background, constraints, and existing behavior for the proposal to be understandable on its own. When discussing existing code, include concrete code locations so readers can verify the context.

When useful, include diagrams, tables, or ASCII charts to explain control flow, data flow, or component relationships.

Clearly describe the problem, goals, non-goals, constraints, proposed design, key trade-offs, and rollout or validation strategy when applicable.

Keep designs simple and implementable. Avoid unnecessary framework-building or over-generalized abstractions.

## 8. Implementation And Review

Before implementing from a design document, verify the design against the current codebase and confirm that it is feasible. If the design is flawed, incomplete, or inconsistent with the actual code, call out the issue and propose concrete corrections before or during implementation.

Implement every critical part required for the system to work according to the intended design, not just surface scaffolding.

Break work into clear modules with explicit interfaces. If the design does not define the module split precisely enough, derive a clean decomposition from the design and codebase.

Implement and validate modules incrementally when the work can be cleanly separated.

Add concise doc comments for public APIs. Add comments for tricky implementation details when they materially improve readability or prevent misunderstanding.

Write focused unit tests for key logic and critical paths. Do not claim completion until relevant verification has run and the result is known. If verification cannot run, explain the blocker clearly.

In review work, prioritize feasibility, correctness, performance implications, boundary clarity, and missing critical pieces over stylistic churn.

## 9. Testing

Any change to code, runtime behavior, schema, build outputs, or test fixtures must run the smallest appropriate regression that covers the changed behavior before completion. Documentation-only changes do not require runtime regression.

For backend Go changes, run the relevant `go test` package, shard, or focused target and keep total runtime under 15 minutes. Broaden to `go test ./... -timeout=15m` only when the change crosses package boundaries broadly or risk justifies a full backend regression. See `docs/development.md` for common regression targets.

If a change adds, removes, or moves a root-module Go package covered by `go list ./...`, update `scripts/ci-backend-required.sh` so backend shard validation still covers the full package set exactly once.

E2E coverage should focus on user journeys and observable behavior rather than implementation details.

Web behavior verification should use the repo's E2E harness and default to the relevant lane, spec, or focused test for the touched user journey. Run the full Web E2E suite only when the change spans broad browser behavior or risk justifies it. The canonical harness guide is `docs/testing/web-e2e.md`.

Keep Web E2E entrypoints focused on browser behavior. Do not add unrelated unit tests, typecheck gates, full `npm run build`, or desktop dashboard builds to smoke/full Web E2E scripts unless the E2E behavior directly requires them. Use `scripts/ensure-web-dist.sh` for preview assets and keep broader validation in normal regression commands.

## 10. Pull Requests

- Use `skills/submitting-pull-requests/SKILL.md` when preparing, opening, or updating a PR.
- Open PRs using `tea`.
- PR titles must follow Conventional Commits style, such as `fix(auth): handle expired tokens` or `feat(api): add workspace export`.
- PR descriptions must use `Problem Summary`, `What is changed and how it works?`, `User Behavior Changes`, and `Tests` sections.
- Before opening a PR, run and report relevant regressions for touched areas, including targeted `go test` coverage for backend Go changes and relevant Web E2E lane or spec coverage for web behavior changes.
- Use broader or full suites only when change impact justifies them.
- If a relevant test requires unavailable external software, state the blocker.
- If a PR has conflicts, rebase the branch onto the target base branch, resolve conflicts, rerun relevant verification, and push with `--force-with-lease`.

## 11. Commits

Do not add `Co-Authored-By` trailers to commit messages.

## 12. Useful References

- Guides: `docs/channel-collaboration-guide.md`, `docs/organizations/usage-guide.md`, `docs/testing/web-e2e.md`.
- Website docs: `docs/public/README.md`.
- Operations: `docs/ksyun-poc-deploy.md`.
- Integrations: `docs/vendor-profiles/feishu/README.md`.

## 13. Guardrail Coverage

No single executable guardrail can enforce this whole working contract because most rules require task-specific engineering judgment. Use the targeted guardrails named by the relevant domain specs, repository guardrails for AGENTS skill references, repo-owned skill metadata, code-shape debt, test-quality debt, static performance debt, and frontend quality / first-paint risk debt, `git diff --check`, focused tests for touched behavior, and `skills/reviewing-long-lived-specs/SKILL.md` when changing canonical policy documents.
