Standards

AI-assisted dev architecture

Original: ~/.claude/backups/AI_Assisted_Dev_Architecture.md. Rules already in CODING_STANDARDS.md (naming, comments, folders, headers, ADRs, commits, branches, security basics) are referenced, not repeated.

Index (open only the section you need)

  • §1 Why architecture matters with AI
  • §2 Context economics: token cost, minimal context, prompt shape
  • §3 Agentic loops: plan, feedback, restart, tests as contract
  • §4 Checklists: before task, prompting, review, red/green flags
  • §5 Cross-session consistency: AGENTS.md, ADRs, headers
  • §6 Scope control: boundary statements, surgical phrasing
  • §7 Hallucination: detect, prevent, recover
  • §8 Security blind spots and checklist
  • §9 Human review: explain-it-back, when to hand-write
  • §10 Version control with AI
  • §11 Model selection: tiers, local models

1. Why architecture matters more with AI

  • Bad structure now costs tokens and wrong output immediately.
    • God files → whole file in context, errors.
    • Tangled deps → context balloons.
    • Vague names → misread intent.
    • No interfaces → silent caller breakage.
    • No WHY comments → correct-but-wrong changes.
  • Small focused files = small context, contained edits, reviewable output. Sizes: see CODING_STANDARDS.
  • Best AI work unit: signature + tests + contract → implementable without the rest of the codebase.
  • Layer-sliced legacy code scatters a feature across folders → add a context map.

2. Context economics

  • Cost = input + output (3–5x price) tokens; cached prefix ~90% cheaper. Every agent-loop iteration re-sends all prior context.
  • Rough sizes: 1 word ≈1.3 tokens; 100 lines code ≈500–1,500; system prompt 500–2,000.
  • Don't stuff context: attention dilutes, hallucination rises, middle gets lost.
  • Send minimal sufficient context:
    • Bug: failing function + deps + error + tests.
    • Feature: interface + callees + requirements.
    • Refactor: only the code changing + reason.
  • Context map (<500 words): purpose, stack, folders, domain terms, non-obvious decisions, external services.
  • Conversations:
    • New task → new conversation.
    • Long → summarise, restart.
    • Critical info at start/end.
    • Drop stale traces, failed attempts, discarded code.
  • Prompt = Context → Task → Constraints → Output format.
    • Avoid: vague task, no constraints, too much at once, no output format.
    • Example: "Add payment_intent.payment_failed case to webhookHandler.js; use updateOrderStatus(); no new deps; output only the case block."

3. Agentic loops

  • Loop: goal → plan → act → run/observe → adjust → next subtask → report.
  • Plan first on non-trivial work (wrong plan ≈100 tokens vs 10,000+ later). Good plan: restated goal, files touched, order + why, dependencies, assumptions.
  • Feedback:
    • Specific, quote the bad output.
    • Confirm what's right.
    • Fix and new features in separate messages.
  • Restart when: same misunderstanding corrected 3x; explanation ≠ code; tests pass for wrong reason; approach wrong. Write a sharper first prompt.
  • Tests = contract. Write tests → give tests + signature → implement → paste failures back. Converges in 1–2 loops.
  • Tool use: review diffs before accepting writes; scope the directory; keep secrets out of context; read-only where possible; limit shell permissions.
  • Long tasks:
    • Define end state.
    • Chunks each produce a working testable artifact (<30 min).
    • Sequence in series.
    • Summarise state between chunks.
    • Test at each boundary.

4. Checklists

  • Before a task:
    • List minimal files.
    • Write assertions.
    • One-paragraph what / why / must-not-change.
    • AGENTS.md current?
    • Chunk size?
  • Prompting:
    • Context/task/constraints/format.
    • Exact file names.
    • Plan first.
    • One thing per prompt.
    • Paste relevant code.
    • State correct output.
    • State what not to change.
  • Reviewing output:
    • Does what was asked (read, don't just run)?
    • Edge cases (null, empty, network failure)?
    • Unrequested changes (check diff)?
    • New dependencies?
    • Follows existing patterns?
    • Hardcoded values?
    • Tests assert behavior?
    • Can you explain every line?
    • Security implications?
  • Helpful choices: TypeScript, pure functions, small files, typed errors, dependency injection, ADRs, .gitignore/.claudeignore, lint in CI.
  • Cost cuts:
    • Reduce context.
    • Restart per task.
    • Cache the system prompt.
    • "Just code, no explanation".
    • Restart bad approaches.
    • Scope tightly.
    • Right model (§11).
  • Red flags:
    • New unfamiliar imports.
    • Rewrote unrequested functions.
    • Tests pass but explanation mismatches.
    • Confident but repeatedly failing.
    • Answers its own clarifying question.
    • Unknown API method.
  • Green signs:
    • First pass needs minor fixes.
    • You understand every line.
    • Tests say when done.
    • AI reuses your utilities.
    • Context <10k tokens.
    • You catch hallucinations pre-run.

5. Cross-session consistency

  • AI is stateless; the codebase is memory. Startup context target <2–3k tokens.
  • AGENTS.md/CLAUDE.md (<500 words): purpose, stack, structure, patterns, never-do, decisions + why. Detail → ADRs.
  • ADRs: Status, Context, Decision, Consequences, Alternatives rejected (most valuable). 10–20 lines.
  • File headers: purpose, depends on, called by, IMPORTANT constraints.
  • Behavior-named tests are enforced, non-stale spec (e.g. sets order to payment_failed when Stripe reports failure).
  • Startup ritual: AGENTS.md → relevant ADRs → files to touch → task with constraints.
  • Update AGENTS.md/ADR in the same commit as the architectural change.

6. Scope control

  • AI wanders from: underspecified tasks, open verbs (improve/fix/refactor/clean up), opportunistic fixes, ambiguous "it", no stop condition.
  • Boundary statement on every prompt: "Only modify X. Don't change signatures, rename, reorder imports, or touch code outside X. Note other issues in a comment; don't fix."
  • Surgical phrasing:
    • "Clean up" → "add null check on email, line 8, nothing else".
    • "Refactor" → "extract only the DB calls into getUserFromDb".
    • "Add error handling" → "try/catch around fetchUser(), line 23; log, return null".
  • Ask for diffs/new blocks only. 40 lines when you expected 3 = went wide → reject, restate.
  • Recalibrate: "You changed X unasked. Revert, keep Y. From now, only touch what I name; propose other changes first."
  • Loosen scope only for: greenfield code, explicit refactor sessions (after plan approval), exploration (don't merge unvetted).

7. Hallucination

  • Forms: invented methods; wrong signatures/arg order; fake library APIs; fabricated file paths; invalid config keys; outdated API usage.
  • Most likely with: niche libraries, post-cutoff API changes, library edge cases, your private code, library-combination tasks, long contexts.
  • Detect:
    • Verify every new import and external method.
    • Run the code.
    • Watch for "is not a function" / "Cannot find module".
    • Grep for unfamiliar internal references.
    • Ask for the doc source/version.
  • Prevent:
    • Paste docs.
    • State versions.
    • Use TypeScript.
    • "Use only functions in <file>".
    • Extra scepticism at library-combination points.
  • Recover:
    • Find why.
    • Check neighbouring code (they cluster).
    • Supply the correct API and have it revise.
    • Record the right API in AGENTS.md.
    • Consider hand-writing niche parts.

8. Security (AI blind spots; baseline rules in CODING_STANDARDS)

  • Why: training data full of insecure code; AI reasons about happy paths.
  • Common mistakes:
    • Unsanitised input (queries, shell, HTML).
    • SQL by string concatenation.
    • Hardcoded secrets.
    • Auth holes: authn without authz; session-expiry off-by-one; trusting client user IDs; unprotected routes; JWT without expiry/audience check.
    • IDOR (record by ID without ownership check).
    • No rate limiting.
    • CORS *.
    • No HTTPS/HSTS.
  • Checklist for code touching input/auth/storage/external services:
    • Parameterised queries.
    • HTML escaped.
    • No shell with user input.
    • No secrets.
    • Ownership checks.
    • Authn AND authz.
    • Rate limits.
    • Upload type/size/content validated.
    • No internals in errors.
    • New deps audited.
  • Don't let AI write unreviewed: auth, crypto, payments beyond SDK, access control. Scaffolding only; use audited libraries.

9. Human review

  • Why you over-trust AI code: looks authoritative, fast, long (you skim), not written by you, "it runs" bias, no expressed uncertainty.
  • Review like a PR from an untrusted junior:
    • Read, don't just run.
    • Be more sceptical.
    • Question each design choice (AI optimises for the common case).
    • Check untested cases: empty, null, huge, concurrent, mid-operation failure.
    • Trace user data from entry to use.
  • Explain-it-back:
    • Ask the AI for a line-by-line explanation.
    • Restate it in plain English.
    • Look for gaps.
    • If you can't explain it, don't accept it.
  • Reject and hand-write when: can't understand it; high stakes + non-obvious logic (security, money, migrations); 3 failed attempts; faster by hand; approach you disagree with.

10. Version control with AI (rules in CODING_STANDARDS)

  • Problem: history/blame stop explaining intent, reviews cover code you didn't write.
  • Commits:
    • Incremental, never one giant session commit.
    • Tests first.
    • Separate your edits from AI output.
    • Only commit when right, not just running.
  • Messages: why + behavior change + decisions. Not "Generated by AI", not diff restatement.
  • Branches: feature branch, --no-ff merge, short-lived, tag before big AI refactors.
  • Reviews:
    • Behavior over style.
    • Ask "did you understand this?".
    • Review tests as carefully as code (implementation-testing failure mode).
    • Explicit security pass.
    • "The AI wrote it" is not a defence.

11. Model selection

  • Tier 1 frontier (Opus etc.): architecture, subtle debugging, security review, costly mistakes.
  • Tier 2 mid (Sonnet etc.): default; clear-spec implementation, tests, CRUD, explaining errors.
  • Tier 3 fast (Haiku etc.): boilerplate, renames, quick utilities, factual code questions, throwaway drafts.
  • Tier L local (Ollama): private code/credentials, uncapped volume, long loops, coordinator/reviewer roles. Slower, smaller context, weaker reasoning.
    • qwen3.6:27b coordinator/reviewer (text).
    • qwen3-coder:30b implementation worker.
    • qwen3-vl:8b vision (screenshots, PDFs via ai_workspace.pdf_input).
  • Start at Tier 2. Go up after 2–3 failures, for security/crypto/financial logic, system-wide reasoning, long-term architecture, hard-to-verify output. Go down for mechanical, high-volume or draft work.
  • Don't burn time optimising pennies.

Mental model

  • Architecture: small, named, focused modules with clear interfaces.
  • Context: minimal sufficient; scope, don't stuff.
  • Iteration: plan, test, restart when stuck, decompose.
  • Prompts: Context + Task + Constraints + Output format. One thing at a time.
  • Consistency: AGENTS.md + ADRs + headers.
  • Scope: boundary statements, diffs not rewrites.
  • Hallucination: verify imports and external calls; supply docs.
  • Security: run the checklist on every change touching data/auth/storage.
  • Review: clean code ≠ correct code; explain it or reject it.
  • Git: short branches, incremental commits, commit messages that say why.
  • Models: Tier 2 default.