apra-qa
CLAUDE.md0 starsChanged 4 months agoMITView on GitHub
Project instructions for Claude Code. Read this before making changes. An agentic RAG system over Australian prudential (APRA) standards, deployed at https://apraqa.mlstudios.ai. A user asks a regulatory question. A LangGraph agent plans, retrieves from the standards corpus, reorders and reasons across the retrieved material, and returns a grounded answer citing the specific standard and clause — or explicitly declines when the corpus does not contain the answer. The deployed app uses strict retrieval only: the model answers solely from retrieved…
The file
Show its rules and text
We split this CLAUDE.md into the rules it gives an agent
25 rules. About 0 are common, 17 are distinctive, and 8 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈17
Distinctive · estimate
This author's own choices. Worth a look.
8
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- Distinctive: line 33
Strict grounding on regulatory turns: When a turn concerns banking or prudential regulation, the agent answers *only* from retrieved …
- Very specific: line 45
All infrastructure in Terraform: No console clicking. If it exists in AWS, it exists in terraform/.
- Distinctive: line 48
Secrets in AWS Secrets Manager: Never in env vars, never in the repo.
- Very specific: line 166
Function URL auth type
AWS_IAM, fronted by CloudFront OAC: Never NONE. An open Function URL is a direct, unmetered path to model spend. - Very specific: line 177
Next.js static export to S3: Not Amplify, not SSR. Full IaC control, near-zero cost, and SSR buys nothing for an SPA talking to an API.
- Very specific: line 224
DynamoDB checkpointer: Use a current community implementation if one exists.
- Distinctive: line 227
No routing logic buried in node bodies.
- Distinctive: line 228
Use LangGraph streaming so tokens reach the client as generation proceeds.
- Distinctive: line 269
Split each document individually before chunking: Never concatenate the corpus then split — that produces chunks spanning two standards and …
- Very specific: line 343
Look up the existing hosted zone via a data source — do not create it, do not manage other records in it
- Distinctive: line 346
Create the validation CNAME and A/AAAA alias records to CloudFront
- Distinctive: line 347
Leave the rest of the zone untouched
- Distinctive: line 376
Design consequence: every visitor is the same Cognito user, so per-user quotas do not bound total spend.
- Distinctive: line 395
If a change increases per-request cost, say so explicitly in the summary.
- Distinctive: line 419
Never deploy from a laptop: All deploys via GitHub Actions.
- Distinctive: line 436
OIDC to AWS: No stored access keys. Deploy role scoped to what it deploys.
- Distinctive: line 448
No PII, no full question text in logs — that belongs in the audit table with defined retention.
- Very specific: line 495
All configuration through typed settings in core/config.py.
- Very specific: line 498
No bare except. Node failures must surface in Langfuse traces.
- Very specific: line 500
Every non-obvious decision gets a short note in docs/ARCHITECTURE.md — what was chosen, what was rejected, why.
- Distinctive: line 522
If you defer something not on this list, add it with a rationale.
- Distinctive: line 529
Do not jump ahead.
- Distinctive: line 544
Alarms, dashboard, runbook: Test the DR rebuild once.
- Distinctive: line 551
Do not build, do not suggest:
- Distinctive: line 574
If something in this file seems wrong, say so rather than working around it.
≈ “Common” is an estimate: at least 1 in 5 of the 12,729 CLAUDE.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
CLAUDE.md — APRA-QA
Project instructions for Claude Code. Read this before making changes.
1. What this is
An agentic RAG system over Australian prudential (APRA) standards, deployed at https://apraqa.mlstudios.ai.
A user asks a regulatory question. A LangGraph agent plans, retrieves from the standards corpus, reorders and reasons across the retrieved material, and returns a grounded answer citing the specific standard and clause — or explicitly declines when the corpus does not contain the answer.
The deployed app uses strict retrieval only: the model answers solely from retrieved context. That behaviour is the product, not a limitation. In a regulated domain, confidently answering outside the evidence base is the failure that matters.
Engineering standard
Production-grade, with enterprise practice applied deliberately and proportionately. Enterprise-grade does not mean every control that exists in a bank; it means every control is a decision, and decisions not taken are recorded rather than overlooked. See §19 — Accepted Risks. That register is part of the deliverable.
2. Non-negotiables
- Strict grounding on regulatory turns. When a turn concerns banking or prudential regulation, the agent answers only from retrieved context — no parametric fallback. No relevant context, no answer: it refuses. General, non-regulatory conversation is allowed and answers normally. The boundary is safety-critical: when unsure whether a turn is regulatory, treat it as regulatory (retrieve, and refuse if the corpus is silent) rather than answering from model knowledge.
- Every regulatory answer cites its sources — standard ID and clause. General conversational replies do not retrieve and do not cite.
- Cost caps exist before any deployed component calls a model.
- Nothing runs always-on. Scale to zero everywhere.
- Every request is traced in Langfuse — spans per node, tokens, cost, latency.
- All infrastructure in Terraform. No console clicking. If it exists in AWS,
it exists in
terraform/. - No long-lived AWS credentials anywhere. CI authenticates via OIDC.
- Secrets in AWS Secrets Manager. Never in env vars, never in the repo.
- Nothing reaches production without passing the eval gate.
3. Stack
| Concern | Choice |
| Agent orchestration | LangGraph |
| Observability | Langfuse + CloudWatch |
| LLM + embeddings | Amazon Bedrock |
| Safety | Bedrock Guardrails (contextual grounding) |
| Vector store | Pinecone serverless |
| State / quota / audit | DynamoDB (on-demand) |
| API | FastAPI on Lambda via AWS Lambda Web Adapter |
| Frontend | Next.js static export → S3 |
| Edge | CloudFront + ACM + Route53 |
| Auth | Cognito |
| IaC | Terraform |
| CI/CD | GitHub Actions, OIDC to AWS |
| Language | Python 3.12 / TypeScript |
4. Repository structure
backend/
app/
api/ FastAPI routes, dependencies, error handlers
agent/
graph.py LangGraph StateGraph definition
state.py typed graph state
nodes/ one file per node
tools/ retrieval and supporting tools
prompts/ versioned prompt files — never inline
ingestion/ extract, chunk, embed, upsert
core/
config.py typed settings, no magic numbers
auth.py Cognito JWT verification
quota.py session + global spend caps
tracing.py Langfuse setup, flush handling
guardrail.py Bedrock Guardrails invocation
logging.py structured JSON logging, correlation IDs
models/ Pydantic schemas
eval/
questions.yaml fixed eval set incl. refusal cases
judge.py LLM-as-judge criteria
runner.py
tests/
unit/
integration/
Dockerfile
pyproject.toml
frontend/
app/ components/ lib/ tests/
terraform/
bootstrap/ local-state root: creates the S3 state bucket + lock table
global/ account-scoped state: ECR, CI + deploy roles, budget
modules/ by-concern, shared by both envs:
data · auth · guardrails · compute · edge · observability
envs/
dev/ thin roots — one module block per concern + tfvars;
prod/ plumbing only (backend, providers, data, variables, outputs)
.github/workflows/
ci.yml lint, test, scan on every PR
deploy.yml build, eval gate, deploy on merge
scripts/ all deploy, test, ingest, and verification scripts live here —
CI and the Makefile call these, never inline shell
docs/
ARCHITECTURE.md
MODEL_CARD.md scope, limitations, evaluation results
RUNBOOK.md alarms, failure modes, rollback
ACCEPTED_RISKS.md see §19
CLAUDE.md5. Architecture
apraqa.mlstudios.ai (Route53)
└─ CloudFront
├─ /* → S3 (Next.js static export, OAC)
└─ /api/* → Lambda Function URL (OAC, RESPONSE_STREAM)
│ FastAPI + Lambda Web Adapter
│ LangGraph agent
│
├─ Cognito JWT verification
├─ DynamoDB checkpointer / quota / audit / cache
├─ Pinecone vector store
├─ Bedrock embeddings, generation, guardrails
└─ Langfuse traces (async, flushed per request)
Ingestion Lambda — same image, different entrypoint
S3 → extract → chunk → embed → PineconeDecisions that must not be changed silently
AWS Lambda Web Adapter, not Mangum. Mangum cannot stream responses. LWA can,
and runs FastAPI unmodified. Function URL invoke mode RESPONSE_STREAM. An agent
that returns nothing for eight seconds reads as broken.
One CloudFront distribution for SPA and API. Function URLs do not support custom domains, so CloudFront is required regardless. One origin means same-origin, which removes CORS entirely.
ACM certificate in us-east-1. CloudFront requirement regardless of stack region.
Function URL auth type AWS_IAM, fronted by CloudFront OAC. Never NONE. An
open Function URL is a direct, unmetered path to model spend.
Container image, not zip. LangGraph and dependencies exceed the 250MB zip limit.
One image, two Lambdas. API and ingestion share code and image; differ by entrypoint, timeout, memory, concurrency.
DynamoDB, not Postgres. The checkpointer needs persistence. RDS is always-on cost; DynamoDB on-demand scales to zero.
Next.js static export to S3. Not Amplify, not SSR. Full IaC control, near-zero cost, and SSR buys nothing for an SPA talking to an API.
6. LangGraph agent
The agent is a tool-calling loop, not a fixed classifier. It holds an ordinary
conversation and owns one tool — search_regulations. The model decides when a turn
is regulatory and calls the tool; general turns are answered directly.
Graph shape
agent ─┬─ general turn ──────────────────────────────► converse ──► END
│
└─ regulatory turn ─► retrieve ─► reorder ─► generate ─► guardrail ─► cite ─► END
│ │
│ no relevant context │ ungrounded / blocked
└───────────► refuse ◄────┘- agent — the conversational LLM. Replies directly to general turns; for a
regulatory turn it emits a
search_regulationstool call rather than answering from its own knowledge. Cheap model for this routing/tool-decision hop. - converse — normal, non-grounded reply for clearly non-regulatory turns. No retrieval, no citation. Never used to answer a regulatory question.
- retrieve — embed query, similarity search, return chunks with metadata.
- reorder — reassemble chunks sharing a
doc_idintochunk_indexorder. - generate — strict prompt, retrieved context only.
- guardrail — Bedrock contextual-grounding check (§10). Verifies the drafted
answer is supported by the retrieved passages, independently of the model. Below
threshold routes to
refuse. - cite — attach standard ID and clause references to the response payload.
- refuse — return the fixed refusal string. Taken when retrieval finds no relevant context or the guardrail blocks an ungrounded draft. A first-class path, not an error.
Rules
- Typed state.
state.pydefines state carrying query, retrieved chunks, reordered context, draft response, citations, guardrail verdict. Named fields only, never a loose dict. - Nodes are pure functions of state where possible, independently testable without the graph.
- Hard recursion limit on the compiled graph (default 8). A runaway loop is the largest single cost risk in an agent system.
- DynamoDB checkpointer. Use a current community implementation if one exists;
otherwise implement
BaseCheckpointSaver. Do not introduce Postgres. - Conditional edges explicit, routing conditions in their own tested functions. No routing logic buried in node bodies.
- Use LangGraph streaming so tokens reach the client as generation proceeds.
7. Langfuse observability
Wired in from the first deployed request, not added at the end.
- Langfuse callback handler passed via LangGraph config on every invocation — trace per request, span per node, automatically.
session_id= demo session,user_id= session identifier, so traffic is groupable per visitor.- Tag traces with the path taken (
answered/refused/guardrail_blocked) so behaviour distribution is queryable. - Record per trace: tokens in/out, model, per-node latency, retrieved chunk IDs, guardrail grounding and relevance scores, computed cost.
- Correlation ID shared between the Langfuse trace, structured logs, and the audit record, so one request is traceable across all three.
Lambda-specific gotcha
The Langfuse SDK batches and sends asynchronously. Lambda freezes the execution
environment the moment the handler returns, so buffered events are lost. Call
langfuse.flush() before the response completes — FastAPI dependency teardown or an
explicit finally. Verify traces appear after a cold start; this fails silently.
Beyond tracing
- Datasets — hold the eval question set in Langfuse; run evaluations against it so eval results and production traces live together.
- Scores — write LLM-as-judge scores back onto traces, making production quality queryable over time rather than a point-in-time CI artifact.
Prompts stay in the repo as source of truth, versioned with the code that uses them. Do not move prompt management into Langfuse — deployed code and prompt version must not diverge.
8. Retrieval design
- Split each document individually before chunking. Never concatenate the corpus then split — that produces chunks spanning two standards and fabricates relationships between unrelated regulations. Correctness requirement.
- Chunk metadata:
doc_id,chunk_index, standard title, clause identifier where available. - Post-retrieval reordering — chunks from the same
doc_idreassembled inchunk_indexorder before generation. - Large chunks with overlap — accuracy over recall economy in a regulatory domain.
.docxsources where available: heading and table structure survives extraction in a way it does not from PDF.- Retrieval separately evaluable from generation. Do not couple them.
9. Prompt behaviour
Two prompts, matching the two roles the model plays.
Agent / system prompt — governs the conversation and tool use:
- Role — a helpful assistant and expert on Australian APRA prudential standards
- Tool discipline — any turn concerning banking or prudential regulation must
be answered via the
search_regulationstool, never from model knowledge. When unsure whether a turn is regulatory, retrieve. - General conversation — greetings, capability questions, and clearly non-regulatory turns are answered directly and briefly, without retrieval.
Strict generation prompt — used only after retrieval, to draft the grounded regulatory answer:
- Role — expert on Australian APRA prudential standards
- Source restriction — answer only from the retrieved context provided
- Task — answer clearly, with citations (standard ID and clause)
- Refusal — if the context does not contain the answer, respond exactly:
I don't have the information to answer this.
Refusal is correct behaviour and must survive every prompt revision. The eval suite asserts it explicitly, and the guardrail (§10) enforces grounding independently of whether the prompt is obeyed.
10. Bedrock Guardrails
The prompt asks the model to stay within context. Guardrails verify that it did, independently of the model. Two layers, not one.
- Contextual grounding check — primary control. Configure both thresholds: grounding (is the response supported by the passages?) and relevance (does it address the query?). Pass retrieved chunks as grounding source on every generation. Below threshold is blocked at the platform layer.
- Denied topics — refuse personalised legal or financial advice. This system explains what standards say; it does not advise on compliance decisions.
- Prompt attack filter — enabled. Public endpoint.
- PII filter — mask on input; users may paste institution details.
Tune thresholds against the eval set: high enough to catch ungrounded generation, low
enough not to block correct answers that paraphrase heavily. Record chosen values
and reasoning in MODEL_CARD.md.
Cost note: contextual grounding is priced per text unit and processes full source passages — the most expensive guardrail feature. Include it in the per-request cost model. If too expensive at demo volume, apply to generation only; never disable it silently.
Log every intervention to the audit trail and tag the Langfuse trace. A blocked response is signal, not an error to swallow.
11. Domain, DNS, and edge security
Root mlstudios.ai exists in Route53 but is not live. Terraform must:
- Look up the existing hosted zone via a
datasource — do not create it, do not manage other records in it - Request an ACM certificate for
apraqa.mlstudios.aiinus-east-1, DNS validated - Create the validation CNAME and A/AAAA alias records to CloudFront
- Leave the rest of the zone untouched
CloudFront:
- HTTPS only, HTTP redirected, minimum TLS 1.2
- Response headers policy: HSTS with preload,
X-Content-Type-Options: nosniff,X-Frame-Options: DENY,Referrer-Policy: strict-origin-when-cross-origin, CSP - Origin Access Control on both S3 and the Function URL — neither publicly reachable except through CloudFront
- S3: public access fully blocked, encryption at rest, versioning enabled
- Access logs to a separate bucket with a lifecycle rule
AWS WAF is deferred — see §19. Rely on quotas, reserved concurrency, and the global spend cap. Add if abuse appears.
12. Access model
- Cognito user pool, one pre-created demo user. Full implementation — JWT issued by Cognito, verified in FastAPI on every request. Not a stub.
- Server-side auth exchange. Frontend calls
POST /api/session(unauthenticated). Backend performsAdminInitiateAuthwith credentials from Secrets Manager, returns JWT plus server-issued session ID. Demo credentials never reach the browser. - Auto-login on page load. One click to a working chat.
- Session quota: 50 questions, DynamoDB, 24h TTL, remaining count shown in UI. On exhaustion, explain clearly — never fail silently.
Design consequence: every visitor is the same Cognito user, so per-user quotas do not bound total spend. The global daily cap is the real protection.
13. Cost controls — build before anything calls a model
- AWS Budget with alarm — first Terraform file written.
- Global daily spend cap. Token counter in DynamoDB. Threshold crossed → return "demo limit reached, resets tomorrow" before invoking the model. Trigger it deliberately in testing. An untested cap is not a cap.
- Graph recursion limit (default 8).
- Model tiering. Cheap fast model for classification and query rewriting; the stronger model only for synthesis.
- Never re-embed unchanged documents. Content hash, skip if unchanged.
- Query cache in DynamoDB on normalised query text with TTL.
- Lambda
reserved_concurrencyon the API function. - CloudWatch alarm on invocation anomalies.
If a change increases per-request cost, say so explicitly in the summary.
14. Testing
| Layer | Requirement |
| Unit | Every graph node, quota logic, auth, citation extraction, chunking |
| Integration | Full graph against a fixture corpus, mocked Bedrock |
| Contract | Pydantic schemas at every boundary; response shape asserted |
| Eval | Fixed question set, LLM-as-judge, lexical + semantic metrics |
| Refusal | Out-of-corpus questions assert refusal — the safety test |
| Infra | terraform validate, tfsec, terraform plan on every PR |
- Coverage floor enforced in CI. Failing tests block merge.
- Fixture corpus committed — small, representative, no external dependency.
- Bedrock calls mocked in unit and integration tests. Real calls only in the eval job.
- Refusal tests are not optional and must not be weakened to make a build pass.
15. CI/CD
Never deploy from a laptop. All deploys via GitHub Actions.
ci.yml — on every PR:
- Lint (
ruff), format check, type check (mypy) - Unit + integration tests, coverage gate
- Dependency vulnerability scan (
pip-audit,npm audit) terraform fmt -check,validate,tfsecterraform planposted as a PR comment
deploy.yml — on merge to main:
- Build image, scan (ECR scan-on-push or Trivy), push to ECR by digest
- Deploy to dev
- Run the eval suite against dev. Below threshold, stop.
terraform applyto prod — image referenced by digest, neverlatest- Smoke test the live health endpoint
- On failure, roll back to the previous Lambda version
- OIDC to AWS. No stored access keys. Deploy role scoped to what it deploys.
- Lambda versions and aliases —
prodalias moves between immutable versions, so rollback is an alias update. - Terraform state per environment, S3 backend, DynamoDB locking, versioned bucket.
- Environments are separate Terraform workspaces/directories, never a shared account resource with a name suffix.
16. Operations
Structured logging. JSON to CloudWatch. Every line carries the correlation ID. No PII, no full question text in logs — that belongs in the audit table with defined retention.
Alarms (SNS to email):
- Lambda error rate > threshold
- p99 latency > threshold
- Daily spend approaching cap
- Guardrail block rate anomaly — a spike means retrieval degraded or someone is probing
- DynamoDB throttling
- Certificate expiry (belt and braces; ACM auto-renews)
Dashboard — CloudWatch: request volume, error rate, latency percentiles, token spend, refusal rate, guardrail block rate.
RUNBOOK.md — for each alarm: what it means, how to diagnose, how to fix,
how to roll back. Written as if someone else is on call.
Health endpoint — /api/health checks Bedrock reachability, Pinecone
reachability, and DynamoDB. Used by the deploy smoke test.
Disaster recovery — the entire stack is reproducible from terraform apply plus
a re-ingest. Document the rebuild procedure and actually test it once in dev.
Untested DR is a plan, not a capability.
17. Data governance and responsible AI
- Corpus provenance — source URL and retrieval date recorded per document. Regulatory standards change; stale advice is the domain risk.
- Audit trail — every query: timestamp, session, question, retrieved chunk IDs, model, tokens, latency, guardrail verdict, response. Retention period defined and enforced via TTL.
- PII — masked at the guardrail on input, never written to logs.
- Encryption — at rest on every store, in transit everywhere.
MODEL_CARD.md— intended use, out-of-scope use, corpus and its date, models, guardrail thresholds and rationale, evaluation results, known limitations, and an explicit statement that this is not legal or compliance advice.- UI disclaimer — visible, not buried. This system explains what standards say; it does not advise.
18. Conventions
- Prompts are versioned files in
app/agent/prompts/. Never inline strings. - All configuration through typed settings in
core/config.py. No magic numbers, no bareos.environreads scattered through the code. - Type hints throughout;
mypyin CI. - No bare
except. Node failures must surface in Langfuse traces. - Conventional commits. Commit messages describe the decision, not just the change.
- Every non-obvious decision gets a short note in
docs/ARCHITECTURE.md— what was chosen, what was rejected, why. - All scripts live in
scripts/— deployment, testing, ingestion runs, and the per-step verification drills. CI workflows and the Makefile call these scripts; they do not inline shell. A script is runnable locally and in CI unchanged.
19. Accepted risks
Recording what was deliberately not built, and why, is itself the practice. Keep
docs/ACCEPTED_RISKS.md current:
| Deferred | Rationale | Trigger to revisit |
| AWS WAF | ~$5/mo + per-rule against a demo budget | Evidence of abuse |
| Multi-region | Single-region acceptable for a demo | Not applicable |
| Per-user accounts | Shared demo account is a deliberate UX choice | Real users |
| Blue/green deploy | Alias rollback sufficient at this scale | Real users |
| Fine-tuned embeddings | Hosted embeddings adequate; cost and time | Retrieval quality plateau |
| Human eval loop | No domain experts available | Production use |
If you defer something not on this list, add it with a rationale. Silent omission is the thing this register exists to prevent.
20. Build order
Do not jump ahead.
- Terraform skeleton — remote state, budget alarm, ECR, dev environment.
- CI pipeline — lint, test, scan, plan. Working before there is much to test.
- Ingestion pipeline, local. Verify retrieval quality standalone. A good agent over bad retrieval is worthless.
- LangGraph agent, local. Full graph, strict, typed state, unit tested.
- Eval harness. Baseline including refusal cases.
- Bedrock Guardrail. Terraform definition, wired into generate, thresholds tuned.
- Langfuse tracing. Callback handler, spans per node, verify flush under cold start.
- FastAPI + Dockerfile with LWA. Confirm streaming locally.
- Deploy to dev — ECR, Lambda, Function URL, CloudFront, ACM, Route53.
- Cognito, session endpoint, quotas, global daily cap. Test the cap fires.
- Eval gate wired into deploy. Promote to prod.
- Alarms, dashboard, runbook. Test the DR rebuild once.
- Next.js frontend. Last. Plain is fine.
21. Explicitly out of scope
Do not build, do not suggest:
- Multi-tenancy or per-user accounts
- Conversation history browsing / management UI
- Admin panels
- Fine-tuning — hosted models are a deliberate choice here
- SSR or any always-on compute
- Non-strict prompt modes as live paths
Optional, only after launch: a precomputed comparison view showing strict vs. passive vs. no-retrieval responses across a fixed question set — demonstrating that three of four configurations will confidently answer outside the corpus. Results stored, never generated live. Do not let this delay launch.
22. Working style
- Propose a plan before large changes. No one-shot multi-file refactors.
- Always
terraform planand show output beforeapply. - Flag any IAM policy broader than strictly necessary.
- Flag any change that adds recurring cost.
- Flag anything that weakens a test to make a build pass.
- If something in this file seems wrong, say so rather than working around it.
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

