<!-- AUTO-GENERATED by task packs:render -- DO NOT EDIT MANUALLY -->
<!-- deft:deposit-link-rewrite v=1 source="content/coding/coding.md" -->
<!-- Purpose: rendered coding rules -->
<!-- Source of truth: packs/rules/rules-pack-0.1.json -->
<!-- Regenerate with: task packs:render -->
<!-- Edit the source, not this file. Slice instead of loading every coding doc: task packs:slice rules by-tier --tier <TIER> (or by-domain, list) -->

# Coding Guidelines

Software development specific guidelines for AI agents.

Legend (from RFC2119): !=MUST, ~=SHOULD, ≉=SHOULD NOT, ⊗=MUST NOT, ?=MAY.

**⚠️ See also** (load only when needed):
- [../main.md](../main.md) - General AI behavior and agent persona
- [PROJECT.md](../../PROJECT.md) - For project-specific overrides
- [../tools/telemetry.md](../tools/telemetry.md) - When implementing logging/tracing/metrics

## Code Organization

**Documentation:**
- ! All *.md in `docs/` directory (except README.md, AGENTS.md, WARP.md)
- ! Prior tasks/plans in `history/`
- ! When code changes user-visible behavior, update matching user-facing docs in the same PR — see [docs.md](docs.md) (#447; lazy-load, not AGENTS always-on)

**Filenames:**
- ~ Use hyphens not underscores (unless language idiom)

**Secrets:**
- ! ALL secrets in `secrets/` dir as .env files
- ⊗ Secrets in code

## Code Search

- ! use `rg`, or `ast-grep` (when available) instead of grep
- ! Use Warp's built-in grep (which is rg) when running on warp
- ~ Install if missing
- ? Fall back to `grep` command only if tools cannot be installed

## Version Control

See [../scm/git.md](../scm/git.md) for:
- Commit conventions (Conventional Commits)
- Safety rules (no force-push without permission)
- Branch workflows

## Code Design

**Modularity:**
- ! One responsibility per file/module
- ~ Keep files small. Ideal, recommended, and review-trigger line counts are FILE_SIZE_IDEAL_LINES, FILE_SIZE_RECOMMENDED_LINES, and FILE_SIZE_REVIEW_TRIGGER_LINES in the file-size-thresholds policy module (packages/core/src/policy/file-size-thresholds.ts). Split when a file exceeds the review trigger unless it is genuinely single-responsibility (size is a smell, not a hard cap; #1488 / #3424)
- ! Explicit scope in task descriptions
- ~ DRY: extract shared abstractions when logic is duplicated across 2+ call sites
- ⊗ Copy-paste logic with minor variations — parameterise instead

**Dependency Direction:**
- ⊗ Circular imports between modules/packages
- ~ Layered architecture: high-level modules depend on low-level ones, never the reverse
- ! Use dependency inversion (interfaces/protocols) to break coupling across layers
- See [hygiene.md](hygiene.md) for detection tools (madge, pydeps, Go compiler)

**Contract-First:**
- ! Define interfaces/types/protocols before implementation
- ! Changes to public interfaces require explicit versioning or deprecation path
- ! Document all public API contracts clearly

**Immutability:**
- ~ Prefer immutable data + pure functions
- ~ When mutation needed, use narrow owned scopes (context managers, RAII)
- ⊗ Global or singleton mutable state (almost always)

**Error Handling:**
- ~ Prefer Result/Option types or explicit exceptions over None/null/undefined
- ! Document possible exceptions/error codes for all public functions
- ! Validate all inputs at API boundaries
- ⊗ Trust caller without validation
- ⊗ Empty catch/except/recover blocks that swallow errors silently
- ⊗ Returning neutral/zero values (None, {}, [], 0, false, "") to mask errors — propagate explicitly
- ⊗ Log-and-continue: catching an error and proceeding as if it didn't happen, unless provably non-fatal and documented
- See [hygiene.md](hygiene.md) for full error-hiding anti-pattern catalogue

**Readability:**
- ! Follow language idioms strictly
- ! Meaningful names over short names
- ! Comments explain **why**, code shows **what**
- ⊗ Clever code over clear code

**State & Data Modeling (#1695):**
- ! A field MUST encode exactly one fact. Do NOT overload a field's value — or its presence/absence — to also signal a second orthogonal concern. Smuggling decision-, config-, lifecycle-, or control-state through a data field is *in-band signaling*; give that signal its own out-of-band field.
- ! "Absence is not a decision." Distinguish "unset / never considered" from "deliberately set to the default." If a workflow must know a human made a choice, record the choice explicitly — never infer it from whether a value-field is present.
- ~ Orthogonality test: if two facts can vary independently (e.g. value==default while decided ∈ {true,false}), they MUST live in separate slots. If one fact strictly implies the other (true Optional<T>, tombstones), sharing a slot is fine.
- ⊗ Infer decision / onboarding / configuration state from the presence of a value field. Use an explicit out-of-band marker — cf. the resolver `source` provenance pattern (typed | default | default-on-error) directive already uses for *value*-provenance.
- See [../patterns/in-band-signaling.md](../patterns/in-band-signaling.md) for the full model, orthogonality procedure, and the wipCap worked example (#1694).

## Quality Standards

**General:**
- ! Run all relevant checks (lint, fmt, quality, build, test) before submitting changes
- ⊗ Claim checks passed without running them
- ! If checks cannot run, explicitly state why and what would have been executed
- ~ Prioritize code quality and readability over backwards compatibility

**Testing:**
- ! Implementation is INCOMPLETE until tests written AND `task test:coverage` passes
- See [../coding/testing.md](testing.md) for universal requirements

**Security:**
- ! Apply baseline security standards to every project from day one
- See [../coding/security.md](security.md) for input validation, authn/authz, secrets, dependency, TOCTOU / mutable-external-resource rules (#1938), and agent-specific threats (#661)

**Review process (#1471 / #212):**
- ! Apply tool-agnostic review-cycle principles on every PR review response
- See [review.md](review.md) for read-all-findings, severity P0/P1/P2, single batch commit, cross-file grep, no mid-review push, exit on no P0/P1, and post-merge closing-keyword verification
- Greptile/GitHub adapter: [../skills/deft-directive-review-cycle/SKILL.md](../skills/deft-directive-review-cycle/SKILL.md)

**Codebase Hygiene:**
- See [hygiene.md](hygiene.md) for: dead code removal, circular dependency detection, error hiding patterns, legacy/deprecated code cleanup

**Telemetry:**
- See [../tools/telemetry.md](../tools/telemetry.md) for recommendations
- ~ Structured logging for production
- ~ Error tracking (Sentry.io or equivalent)
- ? Distributed tracing for complex systems

## Fail Loud: Completion Claims Require Outcome Verification (#1006)

The failure mode is the agent stating completion at the level of **intent** ("I ran the migration", "the tests pass", "the feature works") rather than at the level of **outcome verification** ("all 167 records migrated, 0 skipped", "42 tests collected, 42 passed, 0 skipped, 0 xfailed", "the edge case asked about was reproduced and now returns the expected value"). Outcome-blind completion claims hide silent skips, swallowed exceptions, suppressed errors, and unverified edge cases behind successful-sounding language. The example from the source: a database migration that completed "successfully" had silently skipped 14% of records on a constraint violation; the skip was logged but not surfaced; the bad reports were discovered 11 days later.

This rule is the OPERATIONAL complement to the EPISTEMIC honesty rules elsewhere in the framework (`main.md` morals section: don't present speculation as fact; label unverified claims). Morals.md says "don't lie". Fail-loud says "count the records, check the logs, run the edge case, **then** claim completion." It is also the output-side complement to [goal-gate-determinism](../patterns/goal-gate-determinism.md) (#852 — the gate specifies what evidence is required) and machine-verifiable-spec (verification commands prevent silent skips) -- without fail-loud, an agent can satisfy the letter of a gate ("tests pass") while hiding the gap ("some tests were skipped").

- ! Before claiming a batch operation succeeded, MUST verify the record count and surface it in the claim ("migrated 167/167 records, 0 skipped, 0 errored" -- not "migration completed")
- ! Before claiming "tests pass", MUST report the count of collected / passed / skipped / xfailed / errored tests ("42 collected, 42 passed, 0 skipped" -- not "tests pass"). A skipped or xfailed test is NOT a passing test for the purpose of this claim
- ! Before claiming "the feature works", MUST report the specific edge case that was verified (if the user asked about a specific edge case, that edge case MUST be in the verification report; "the happy path works" is not equivalent to "the feature works")
- ! Before claiming a migration / data transform / batch job completed, MUST check the error log AND the skip log AND the constraint-violation surface; surface the counts even when zero ("0 skipped, 0 errored" is the load-bearing claim, not silence)
- ! When uncertainty exists about whether something worked, MUST surface the uncertainty explicitly ("the migration completed and reported success but I have not verified the per-record count -- recommend running `<verification-command>` before declaring done")
- ⊗ MUST NOT claim "tests pass" when any test was skipped, xfailed, or run with errors suppressed -- report the full counts instead
- ⊗ MUST NOT claim "migration completed" / "batch succeeded" / "job finished" without checking and reporting the per-record outcome counts
- ⊗ MUST NOT claim "feature works" when only the happy path was verified -- name the edge case that was tested, or surface that it wasn't
- ⊗ MUST NOT use successful-sounding completion phrasing to paper over uncertainty -- default to surfacing uncertainty, not hiding it
- ⊗ MUST NOT suppress error output (`2>$null`, `2>/dev/null`, `try/except: pass` around the verification command) and then claim completion based on the resulting silence

- ! Before claiming "feature complete", "ready for real users", "production-ready", or equivalent area-complete language for a surface that has open graduations (Now+Later dual-path locks; #2899), MUST name the open `graduationRef`s, **or** explicitly state that graduation review was skipped and why — otherwise the claim is outcome-blind under this rule
- ⊗ MUST NOT claim "feature complete" / "production-ready" / "ready for real users" for an area with open graduations without naming those `graduationRef`s or an explicit skip-with-reason

The rule applies to agent completion claims during task execution. It applies equally to claims to the user, claims in commit messages, claims in PR bodies, claims in CHANGELOG entries, and claims in status messages to a parent agent. A short, honest "the migration completed; I did not verify the per-record count" is strictly preferred over a confident "migration completed successfully" that hides the gap.

**Cross-references:** strategies discuss/probe Graduation dual-path locks (#2899); `## Quality Standards` above (`⊗ Claim checks passed without running them` -- the sibling rule that this expands from process to outcome); `hygiene.md` `## Error Handling: No Hiding` (the same hiding pattern at the code-write level, not the claim level); [`patterns/goal-gate-determinism.md`](../patterns/goal-gate-determinism.md) (#852 — rigid goals/gates, flexible path); `skills/deft-directive-pre-pr/SKILL.md` (pre-PR verification claims); `skills/deft-directive-build/SKILL.md` Step 4 Quality Gates (task-completion claims); `skills/deft-directive-review-cycle/SKILL.md` (Greptile adapter; universal review principles in [review.md](review.md); the adapter explicitly checks for hidden incompleteness in fix-batch completion claims).

## Calling LLM APIs (#481)

When the project calls LLM APIs (OpenAI, Anthropic, Cohere, local models, etc.) or builds agentic functionality, the architectural standards in `patterns/llm-app.md` apply alongside the coding rules above. In the directive maintainer repo this section is **guidance for consumer projects** — provider names are illustrative labels under the framework instruction hierarchy, not runtime SDK surfaces (#2414; see `meta/security.md` `## Informational AppSec findings`). The short form:

- ! User input is NEVER placed in the system prompt; the system prompt is the trust boundary
- ! External content is ALWAYS wrapped in explicit delimiters (`<user_input>`, `<document>`, `<tool_result>`) and surfaces its trust tier
- ! Tool call arguments are validated against a schema BEFORE execution (the LLM is a confused deputy)
- ! LLM outputs are validated against expected schemas before being acted upon (no eval-of-output, no shell-of-output, no SQL-of-output)
- ⊗ MUST NOT write LLM outputs back into the retrieval corpus in the same session without validation (RAG poisoning vector)

See [../patterns/llm-app.md](../patterns/llm-app.md) for the full standards: prompt construction, trust tiers, tool/function-call validation, RAG hygiene, output handling, multi-agent orchestration, and LLM-specific observability. See [../tools/telemetry.md](../tools/telemetry.md) `## LLM-specific observability (#481)` for the matching observability surface.

## Debugging and Root-Cause Investigation (#1621)

When a bug, failure, or unexpected behaviour needs diagnosis, the root-cause standards in `debugging.md` apply. The short form:

- ! No fixes without root-cause investigation first (the Iron Law)
- ! Reproduce the failure consistently before proposing a fix — a non-reproducible bug is not yet understood
- ! Every factual claim cites evidence; an uncited claim is a `[HYPOTHESIS]`, not a finding (evidence before narrative)
- ! Runtime/config values are proven from the runtime, never inferred from source code (config is not code)
- ⊗ MUST NOT present a duration or an exit status ("slow because phase X took N minutes", "failed because it timed out") as a root cause — name a mechanism (no tautologies)
- ! After 3 failed distinct fixes, STOP and escalate for architectural review (the 3-fix gate)

See [debugging.md](debugging.md) for the full four-phase process, evidence discipline, Fact vs Hypothesis labeling (#1580), the observability-gap loop, and the rationalization table. For a sustained multi-agent investigation posture, see the `deft-directive-debug` skill.

## Build Automation

**Taskfile:**
- ! Use Task ([go-task](https://taskfile.dev)) for all repeatable operations
- ! If `task` not found, attempt to install go-task
- ! If installation fails, stop and ask user for help
- See [../tools/taskfile.md](../tools/taskfile.md) for standards and common commands

**Toolchain Validation:**
- See [../coding/toolchain.md](toolchain.md) for rules on verifying required tools are installed before implementation begins

**Build Output Validation:**
- See [../coding/build-output.md](build-output.md) for rules on verifying `dist/` artifacts and non-compiled assets after custom build scripts run

## Change Management

**Impact Awareness:**
- ! Before changing shared code, identify affected downstream modules/files
- ~ Prefer additive changes (new functions, fields with defaults) over breaking renames
- ! Make small, reversible changes
- ! Explain impact and migration path for breaking changes

**Production Safety:**
- ! Assume production impact unless stated otherwise
- ! Call out risk when touching: auth, billing, data, APIs, build systems
- ⊗ Silent breaking behavior
- ~ Test changes in staging/dev environment when possible

## Language-Specific Guidelines

**Languages:**
- C++: [../languages/cpp.md](../languages/cpp.md)
- Go: [../languages/go.md](../languages/go.md)
- Office.js: [../languages/officejs.md](../languages/officejs.md)
- Python: [../languages/python.md](../languages/python.md)
- TypeScript: [../languages/typescript.md](../languages/typescript.md)
- VBA: [../languages/vba.md](../languages/vba.md)

**Interface Types:**
- CLI: [../interfaces/cli.md](../interfaces/cli.md)
- TUI: [../interfaces/tui.md](../interfaces/tui.md)
- Web: [../interfaces/web.md](../interfaces/web.md)
- REST API: [../interfaces/rest.md](../interfaces/rest.md)

## Development Workflow

**Localhost:**
- No permission needed for curl localhost

**Plans:**
- ~ Create both:
  1. Warp plan (using `create_plan` tool)
  2. Archive copy in `history/plan-YYYY-MM-DD-description.md`

## Project Context

- ! Check [PROJECT.md](../../PROJECT.md) for project-specific overrides
- ~ Inspect project config (package.json, pyproject.toml, etc.) for available scripts
- ! Follow project-specific testing, coverage, and quality requirements

## Anti-Patterns

- ⊗ Secrets in code or version control
- ⊗ Claiming checks passed without running them
- ⊗ Single files mixing multiple responsibilities (line count at or above FILE_SIZE_REVIEW_TRIGGER_LINES is a cohesion review trigger — not a defect by itself; #1488 / #3424)
- ⊗ Skipping quality checks
- ⊗ Breaking changes without explicit approval
- ⊗ Using `grep` command when `rg` or Warp grep available
- ⊗ Implementing code without tests
- ⊗ Claiming "done" before running test:coverage
- ⊗ Ignoring coverage drops
- ⊗ Weak types (`any`, `interface{}`, untyped `object`) where concrete types are knowable
- ⊗ Dead code: unused functions, unreachable branches, stale feature flags, commented-out blocks
- ⊗ Error hiding: empty catch blocks, silent fallbacks, swallowed exceptions
- ⊗ Circular imports between modules
- ⊗ Duplicate logic across 2+ call sites without shared abstraction
- ⊗ Outcome-blind completion claims: "tests pass" with skipped tests, "migration completed" without per-record counts, "feature works" without naming the verified edge case (#1006 -- see `## Fail Loud` above)
- ⊗ Outcome-blind "feature complete" / "production-ready" claims that ignore open graduations (`graduationRef`s) without naming them or an explicit skip (#2899 / #1006 -- see `## Fail Loud` above)
- ⊗ Averaging contradicting codebase patterns: writing new code that satisfies both of two conflicting patterns simultaneously (#1005 -- see `hygiene.md` `## Surface Conflicts`)
- ⊗ Debugging by guess-and-check: fixing before reproducing, treating the first plausible hypothesis as confirmed, or presenting a duration/exit-status as a root cause (#1621 -- see `debugging.md`)
