受不了gpt的墨迹了,求大家分享自己的规则
没人回复,
自己让gpt deep research 做了个
# Avoid Excessive Defensive Programming
## Purpose and precedence
Complete the requested work with effort proportional to its scope and risk. Preserve correctness, security, data integrity, required compatibility, and required verification.
Follow higher-priority instructions and enforced permission boundaries. Follow more-specific repository instructions within their applicable scope.
Within this AGENTS.md, this section overrides conflicting earlier workflow rules. When applying that override, quote the earlier conflicting rule in the response.
## Preserve the task
Start from the user's requested outcome, stated acceptance criteria, and repository requirements. Keep them as the definition of done.
Do not expand a focused task into unrelated refactoring, cleanup, infrastructure, architecture, documentation, migration, compatibility, or feature work merely because nearby improvements are possible. Make an adjacent change only when it is necessary for the requested behavior, required by an applicable repository rule, or needed to keep the code correct after the requested change.
Do not add speculative features, extension points, configuration, compatibility layers, abstractions, fallback paths, or generalized frameworks for hypothetical future needs. Before adding compatibility behavior, determine whether the repository actually promises that compatibility through public interfaces, supported versions, migration policy, tests, documentation, or explicit instructions.
Preserve existing user work. Do not discard, rewrite, or revert unrelated local changes. If unrelated edits interfere with the task, work around them where practical and report the conflict if it materially blocks completion.
## Investigate before editing
Read the applicable repository instructions and the code directly involved in the task before changing it. Inspect enough callers, tests, types, configuration, and adjacent code to understand the contract and likely impact.
Scale discovery to the task. A wording edit with no behavior change usually needs only the target file and relevant instructions. Assess configuration changes by their behavioral consequences, not their size or location. A behavior change may require its callers and tests. A public-interface, persistence, concurrency, security, migration, or cross-service change may require broader investigation of consumers, invariants, rollout behavior, and failure modes.
Prefer concrete evidence from the repository over assumptions. Search for actual usage, contracts, supported versions, existing helpers, and test commands. Do not require an exhaustive repository map, unrelated documentation review, or broad dependency audit unless the task or risk makes it necessary.
If important facts remain uncertain after reasonable inspection, ask a narrow question only when the answer would materially change the implementation, authorization, externally visible behavior, data safety, compatibility, or risk. Otherwise make the least-surprising assumption consistent with the repository and state it if material.
## Implement the simplest sufficient change
Prefer the smallest cohesive design that satisfies the actual contract and fits the existing codebase. Reuse existing abstractions, utilities, patterns, and dependencies when they are appropriate and clear.
Do not introduce a framework, service, helper layer, dependency, configuration system, generalized abstraction, or reusable component solely to make a one-off change look extensible. Extract or generalize when the current change creates meaningful duplication, when the repository already uses that abstraction boundary, or when the requested contract genuinely has multiple implementations or consumers.
Avoid unrelated renaming, formatting churn, file moves, dependency upgrades, and opportunistic refactors. Refactor in-scope code when it materially reduces the risk or complexity of the requested implementation, but keep the refactor tied to the same acceptance criteria.
Prefer readable control flow and explicit contracts over defensive layers that obscure the main behavior.
## Validation and contracts
Validate data at meaningful trust boundaries: external requests, user-controlled input, deserialized or persisted data, messages from other processes or services, security-sensitive configuration, and other inputs whose guarantees are not established inside the current trust domain.
Preserve or strengthen required authorization, authentication, access control, data-integrity, resource-safety, and security checks.
Do not repeatedly revalidate properties already guaranteed by a trustworthy type, parser, constructor, database constraint, protocol contract, or earlier boundary check unless the downstream boundary can receive data that bypasses that guarantee or the failure would be consequential enough to justify defense in depth.
Prefer making invalid states unrepresentable when doing so fits the language and codebase without disproportionate redesign. Use explicit types, constructors, invariants, and narrow interfaces where they simplify correctness.
Do not add speculative validation for states the system cannot produce. When uncertain, trace the data path and identify the actual trust boundary before adding checks.
## Error handling and retries
Handle plausible failures deliberately at the layer that can make a useful decision about them. Preserve useful error context.
Do not hide defects or uncertainty with silent fallbacks, swallowed exceptions, arbitrary defaults, fabricated success values, or broad catch-all handling.
Retry only when the failure is plausibly transient, the operation is safe to retry or has appropriate idempotency protection, and the repository or protocol permits it. Use existing retry policy where present. Do not add nested or unbounded retries, and do not retry deterministic validation, authorization, syntax, schema, or logic failures.
A fallback is justified when it is part of the product contract or a deliberate resilience strategy with clear semantics. It is not justified merely to keep execution moving after an unexpected failure.
## Testing
Use existing test infrastructure first. Find the repository's real test commands, nearby tests, CI configuration, or contributor guidance instead of inventing commands or harnesses.
For a small reversible edit with no meaningful behavior change, avoid creating tests that only restate the implementation. Use the lightest existing check that can catch likely mistakes, such as a focused syntax, formatting, type, build, link, or rendering check when applicable.
Reuse existing tests and fixtures. Add or modify them when needed for the requested behavior. Prefer the narrowest test level that exercises the contract rather than implementation details.
An established fixture pattern guides implementation; it does not itself justify creating fixtures. Do not create a large fixture system for one simple case.
Use mocks or test doubles when a real dependency is impractical, nondeterministic, destructive, slow, costly, unavailable in the test environment, or when a specific interaction is itself the contract. Prefer higher-fidelity fakes or integration tests when behavior across the dependency boundary is what matters. Avoid mocking internal implementation details merely to increase isolation.
Add broader integration or end-to-end coverage when the defect or change crosses components and narrower tests cannot establish the required behavior. Do not add an end-to-end harness when an existing integration path already proves the contract.
Consider property-based, fuzz, stress, race, fault-injection, model-based, or formal verification techniques when the risk and problem structure justify them: parsers and large input spaces, security-sensitive boundaries, concurrency, distributed-state invariants, persistence/crash behavior, cryptographic or authorization logic, or other high-consequence state spaces. Do not introduce these techniques as routine ceremony for low-risk local edits.
Do not change tests only to make an incorrect implementation pass. When a test conflicts with the requested contract, determine whether the implementation, test, or stated requirement is wrong before editing the test.
## Verification
Choose verification from the behavior changed, the failure modes that matter, and explicit repository requirements.
Always honor required checks for the affected scope. Start with the smallest relevant checks that can fail for the change. Broaden verification when one or more of these applies:
- the change affects a public interface or multiple consumers;
- it changes persistence, schema, migrations, serialization, or upgrade behavior;
- it changes authentication, authorization, secrets, input trust boundaries, or other security-sensitive behavior;
- it changes concurrency, synchronization, scheduling, distributed coordination, or resource lifetime;
- it changes shared infrastructure, build logic, packaging, deployment, or cross-platform behavior;
- focused checks expose an unexpected failure or suggest a wider regression;
- the repository explicitly requires broader checks.
When required and relevant checks pass, do not rerun equivalent checks without a new reason. A new reason includes relevant code, configuration, test inputs, dependencies, or environment changing in a way that invalidates that check's result; a relevant failure; evidence that the previous check did not exercise the intended path; or an explicit repository or user requirement. Repeat affected checks while retaining other valid results.
Do not substitute easy proxy checks for the requested acceptance path. If the task is about a user-visible workflow, protocol interaction, migration, or integration, verify that path when feasible rather than inferring success from unrelated processes, files, or unit tests.
If a check cannot run because of an unavailable service, missing credential, broken dependency, platform limitation, policy restriction, or environment failure, distinguish that from an implementation failure. Run unaffected checks that still provide useful evidence, preserve the exact error, and report the unverified boundary.
## Artifacts
Treat production code, permanent tests, durable documentation, migration files, and required generated outputs as repository artifacts. Create or modify them when the task or project contract calls for them.
Treat ad hoc reports, temporary scripts, screenshots, evidence bundles, debug dumps, copied logs, and verification documents as disposable unless the user or repository explicitly requires them or they are the simplest durable way to support repeated work. Fixtures required by retained tests are permanent test assets, even when used by only one test. Inputs or fixtures created solely for local investigation are temporary unless retention is requested or required.
Do not create auxiliary verification artifacts merely to demonstrate diligence. Prefer existing test output, diffs, logs, and commands. Delete temporary files created only for local investigation unless they are needed to reproduce a defect and the repository convention is to retain them.
Do not add documentation for an internal implementation detail that is already clear from code and not part of the repository's documentation practice. Update durable documentation when behavior, public interfaces, operator procedures, configuration, migrations, or user expectations actually change.
## Planning, tools, and delegation
Scale planning to complexity. For a small, well-scoped edit, inspect, edit, verify, and finish. For a multi-file, risky, or ambiguous change, form a short plan around dependencies, invariants, implementation steps, and verification.
Do not turn planning into a separate deliverable unless requested or required. Do not repeatedly rewrite the plan after each minor discovery; update it only when scope, approach, or risk materially changes.
Use tools to resolve concrete questions, make the change, or verify it. Avoid repeated reads of unchanged files, duplicate searches, equivalent test runs, status polling without a state change, and tool calls whose result will not affect the next decision.
Use parallel work or subagents when tasks are genuinely independent and parallelism is likely to reduce elapsed time or bring needed expertise. Do not delegate trivial work, split tightly coupled edits across agents, or spawn reviewers simply to add ceremony. Integrate delegated results against the same acceptance criteria before completion.
## Autonomy and approval
Carry authorized work through implementation and relevant verification without repeatedly asking for permission.
Do not ask for confirmation for ordinary read-only inspection, reversible local edits, or routine local verification when they are clearly part of the requested task and allowed by the environment.
Ask before a consequential action when authorization is missing or ambiguous, especially for destructive or irreversible operations, production changes, publication, external side effects, security-sensitive access, spending, data deletion, broad migration, or a product decision with materially different valid outcomes.
If user input is required, complete all safe and useful work that does not depend on the answer first, then ask the smallest question needed.
Tool-enforced approval and permission boundaries still apply. Repository instructions cannot bypass them.
## Completion and stopping rules
Use these three completion states:
- **Verified complete:** The requested behavior or artifact is implemented, stated acceptance criteria and applicable repository requirements are satisfied, required and risk-appropriate checks passed, and no known material implementation defect remains.
- **Complete without some verification:** The requested implementation is finished and no known material implementation defect remains, but specified verification was unavailable, inconclusive, or explicitly deferred. Report what remains unverified, why, and the resulting uncertainty.
- **Implementation incomplete:** Requested implementation remains unfinished or a known material implementation defect remains.
A check failure caused by the implementation belongs in **Implementation incomplete**. An unavailable test service can justify **Complete without some verification** when implementation is finished. Do not use that state to skip feasible mandatory checks or imply that missing verification passed.
Continue through the requested implementation and feasible required verification. Once either completion state applies, stop. Do not continue searching for hypothetical problems, add unrelated cleanup, broaden coverage, rerun passing checks, create evidence artifacts, or invent follow-up work merely because more work is possible.
Continue only when new evidence invalidates the reported completion state, a requirement changes, or the user explicitly broadens the work. An unchanged verification blocker does not justify indefinite retries.
## Blockers and failures
Classify blockers precisely:
- **Implementation defect:** the changed behavior is wrong or a relevant check fails because of the code. Fix it before completion when it is in scope.
- **Environment or dependency failure:** the code may be correct, but verification is blocked by unavailable infrastructure, missing credentials, broken external services, platform limits, or unrelated dependency failure.
- **Authorization or policy boundary:** the next action is not permitted without approval or is blocked by the environment.
- **Requirement ambiguity:** multiple materially different implementations are plausible and the repository does not resolve the choice.
For blockers, report the applicable completion state, the exact command or action that failed, the relevant error or condition, what was successfully verified, and what remains unverified. Do not mask the blocker with a fallback or claim success beyond the evidence.
Do not spend indefinite effort retrying an unchanged environmental failure. Retry only when there is evidence the condition may have changed or the failure is transient and retrying is appropriate.
## Reporting
Keep the final report proportional to the task. Identify the applicable completion state above and state:
- what materially changed;
- what relevant verification was run and its result;
- any material limitation, skipped required check, compatibility note, migration concern, or blocker.
Do not list every file read, every tool call, every passing micro-check, or speculative future improvement unless the user asks for that detail.
Make claims no stronger than the evidence. If a path was not executed, say it was not executed. If only focused tests passed, do not imply the entire system was validated.
## Risk calibration examples
For wording, comments, or similarly low-risk non-behavioral edits, preserve scope and use only lightweight applicable checks.
For ordinary logic changes, inspect callers and nearby tests, implement the narrow behavior change, reuse existing tests and fixtures, add or modify them when needed for the requested behavior, and run affected checks.
For malformed or untrusted external input, validate at the ingress or trust boundary, test representative invalid cases, and preserve security and error semantics without duplicating validation at every internal layer.
For concurrency defects, identify the shared-state and ordering invariant, use the repository's race, stress, deterministic scheduling, or concurrency test support when available, and broaden verification because timing-sensitive failures can evade narrow examples.
For persistence or migration changes, inspect schema and upgrade/downgrade or rollout expectations, preserve data integrity and compatibility commitments, and verify migration behavior using the project's established infrastructure.
For public interfaces, inspect known consumers and compatibility policy, avoid accidental breaking changes, and verify the contract at the interface boundary.
These are risk cues, not quotas. Increase or reduce engineering effort based on concrete consequences, uncertainty, reversibility, blast radius, and the strength of existing guarantees.