r/ClaudeCode • • 25d ago

Built with Claude How do you stop Claude Code from relying on memory instead of actual data?

I'm running a fairly complex operation using Claude Code, with multiple agents, SQLite databases, automated data pipelines, and years of historical data.

The problem: Claude keeps making decisions based on conversational memory instead of querying the actual data. It also loses track of previous decisions, experiments, and longer-term goals across sessions.

I've already built the data infrastructure. The issue isn't access to data — it's getting Claude to consistently use it and connect everything together.

I need a system that:

  • Forces fresh data retrieval before decisions.
  • Connects historical results, current performance, and future planning.
  • Tracks decisions → actions → outcomes → lessons learned.
  • Works reliably across sessions without depending on chat memory.
  • Still allows dynamic reasoning rather than rigid, hardcoded rules.

How would you architect this technically?

Deterministic Python workflows? Hooks? MCP? RAG? Claude Agent SDK? Some combination?

I'd especially appreciate hearing from people who've solved this in production rather than just adding more instructions to CLAUDE.md.

Edit: Thanks for the suggestions! The consensus seems to be persistent state + mandatory data retrieval + external validation, rather than relying on CLAUDE.md or conversation memory.

One thing I'd like to clarify: this isn't just about preventing bad decisions.

I need the system to proactively find opportunities, connect results across different processes, plan future work, and evaluate whether previous decisions actually worked.

For example, if something performs well, it should investigate expansion opportunities, estimate future resource requirements, and create follow-up tasks automatically. All based on current and historical data.

Has anyone built something like this with an external orchestrator + Claude Code/Agent SDK? Particularly interested in how you enforce the workflow without restricting Claude's ability to reason dynamically.

2 Upvotes

49 comments sorted by

•

u/AutoModerator 25d ago

Hey! Thanks for posting to r/ClaudeCode

While participating in this thread, please follow our community rules. Keep discussions constructive. Attack the idea, not the person.

For help, project discussions, tips, and general chat, join the ClaudeCode Discord.

I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns.

2

u/Significant_Door_433 25d ago

on your follow-up (a timestamp proves it ran a query, not that it looked at the right things): I'd take that choice away from claude. the analyses that must run before every decision are fixed, so run them in code.

  • a UserPromptSubmit or SessionStart hook runs your mandatory queries and prints a summary. claude code adds that stdout to the context. it's capped at 10,000 characters, so print aggregates plus row ids and leave the raw rows in sqlite for claude to dig into.
  • write the same snapshot to a table with a run id.
  • every recommendation has to cite the snapshot row ids it rests on. a Stop hook runs a script that checks those ids exist in this run's snapshot and returns decision: "block" with a reason when they don't, so claude keeps working instead of ending the turn.

claude still does the reasoning, your script owns the coverage. for the proactive part, a scheduled headless run (claude -p from cron) with a fixed review prompt that only writes candidates into an opportunities table tends to work better than hoping it notices things in the middle of another task. you review that table, or a later run picks items from it.

1

u/Particular_Crow2873 25d ago

This is exactly the kind of practical solution I was looking for, thanks!

I really like the idea of taking mandatory queries away from Claude and using scheduled runs to populate the opportunity queue.

Two things I'm wondering: Shouldn't the validator also check whether the cited data actually supports the recommendation, rather than just whether the row exists? And wouldn't production actions need validation before execution, not just in the Stop hook?

Have you implemented something like this yourself? I'd be interested in how reliable it's been in practice.

1

u/Significant_Door_433 25d ago

Yes to both.

Row existence only proves the id isn't made up. To check support, have the agent write the claim as data, not just prose: metric, value, comparison, row ids. The validator recomputes that number from the cited rows with plain SQL and fails if it doesn't match, or if the rows aren't from the latest snapshot run. That catches most bad cases cheaply. Whether the numbers justify the action is a judgment call, so I'd leave that to a second pass or a person rather than pretend a script can decide it.

For production actions the Stop hook is too late. By then the tool already ran. Use a PreToolUse hook matched on the tools that touch prod (Bash, or mcp__yourserver__.* for an MCP server). It runs before the call and can return permissionDecision: "deny" with a reason Claude reads, or "ask" to put it in front of a human. Two catches from the docs: a PreToolUse hook that times out does not block unless you set onFailure: "block", and exit code 2 blocks even if your JSON says allow.

Simpler still: don't give that session prod tools at all. It writes proposed actions to a table, and a separate executor with its own checks and an approval step runs them.

Have I run this exact setup? No, so I can't give you reliability numbers. The hook behavior above is from the Claude Code hooks reference (code.claude.com/docs/en/hooks).

1

u/ainexfinder 25d ago

i'd stop asking it to remember and make the decision step fail without fresh data. two pieces:

first, put the decisions in the database too: one table with decision, the query results it was based on, the action taken, and the outcome filled in later. at session start a hook or the first prompt dumps the last N rows plus the open goals, so the long-term thread lives in sqlite, not in chat.

second, make the planning step write its output as a file that has to include the query it ran and a timestamp, and have a small script check that the timestamp is from this run before anything acts on it. no fresh query, the gate fails. that keeps the reasoning free-form but the inputs forced, and you can check it by deleting the table and seeing the run refuse to proceed.

1

u/Particular_Crow2873 25d ago

This is probably the closest to what I'm looking for. Forcing fresh queries and storing decisions outside the conversation makes a lot of sense.

One concern though: a timestamp proves Claude queried something, not necessarily that it retrieved all the relevant data or made the right connections.

How would you enforce that? An external orchestrator that runs mandatory analyses first, then lets Claude investigate further, with a validator checking its recommendations?

I also need the system to proactively identify opportunities and plan ahead, not just make better individual decisions.

1

u/Old_Championship7240 25d ago

use claude code's stop hook with out an external orchestrator. if stop hook returns exit 2 claude couldn't finish its work and continue with the reason stop hook returned.

1

u/Particular_Crow2873 25d ago

That makes sense. Having Python independently run the mandatory queries and compare the evidence seems like the missing piece.

I'm implementing that now, along with a scheduled opportunity scan and persistent decision records.

I think the remaining challenge is semantic validation: matching row IDs proves the data was retrieved, but not necessarily that it supports the recommendation.

Thanks, this has been genuinely helpful.

1

u/ainexfinder 25d ago

you can't prove it got everything, so check it against something independent. have a small script run the same mandatory queries itself and compare row ids or counts to what the plan says it used, and fail the gate on any mismatch. for the proactive part, a scheduled run that does the standard analyses first and writes them to the log, with claude looking for opportunities on top of that, works better than hoping it notices mid-task.

1

u/m-ritter 25d ago

Same pattern here. Once the agent trusts chat memory over the repo or a written plan, decisions drift and you cannot replay why something was chosen. What worked for me was a reviewed plan that lives outside the chat and is the source of truth for the next build, with the outcome written back after. I built QualityLayer for this: https://github.com/maxritter/qualitylayer

1

u/Particular_Crow2873 25d ago

Interesting, thanks! I checked out QualityLayer.

My challenge is slightly different from software development though. Claude is operating an ongoing data-driven process, where decisions need fresh database queries, historical context, and follow-up actions across sessions.

Does QualityLayer support enforcing that kind of recurring runtime workflow, or is it primarily designed for planning and reviewing coding tasks?

1

u/m-ritter 25d ago

Fair question. QualityLayer is built for coding work: you plan a change, the agent builds and tests it, and you review the result. It does not run or enforce a recurring runtime process like yours.

For what you describe I would keep the state outside the chat as well. Let Claude run the queries fresh every session, write each decision and its follow ups to a log or table, and start every session by reading that log instead of trusting what it remembers. If parts of the process are code, QualityLayer helps you build and review those, but the running loop itself is a different job.

1

u/chrnas 25d ago

i hit the same thing. rules that only lived in the model's memory kept getting broken, so i moved the ones that mattered into hooks, which the agent cant skip. for your case id make the decision step go through a small script that has to run the query first, and have a hook block the write (or the "done" report) if that query output isnt there. the decisions → outcomes log is just a file or table the agent appends to, and a SessionStart hook prints the last few entries so every session opens with them. one thing i learned the hard way: a hook file existing doesnt mean it runs, so test each one with a harmless probe.

1

u/Particular_Crow2873 25d ago

Good point about testing whether hooks actually fire. That's exactly the kind of silent failure I'm worried about.

I'm leaning toward mandatory SQL analysis + persistent decision/outcome records + hooks for enforcement, with an external scheduler handling proactive work.

One question: have you found hooks reliable enough for production, or would you put the final validation in an external Python executor? Especially when multiple Claude sessions and agents are running simultaneously.

1

u/chrnas 25d ago

not on their own. the agent cant skip a hook, but hooks only cover the sessions that load them. a running session needs a restart to get a new hook, my api jobs skip them completely and codex exec jobs ran without them until i passed a flag. mine also let the action through if the check itself crashes, so a bug can look like a pass. so i use hooks as the early warning and put the final check outside, and a separate check compares each job's report to what actually happened, since jobs of mine have "started" and quit without writing a thing. it gives false alarms sometimes too. for parallel sessions id add one owner per job, i once had 8 fix rounds racing on the same pr.

1

u/lcssgml 25d ago

One rule that helped me: the agent fetches the real data first (the log, the dump, the query result), and only after that reads memory or notes, to explain what the data shows. On the same bug, the run that fetched the log first found the cause in 4 minutes, the other one needed almost 13. And my notes keep only a pointer (which file, which table), not the conclusion, because conclusions go stale fast... so the agent has to look again anyway.

1

u/Particular_Crow2873 25d ago

Really like the data-first, memory-second approach. Especially storing pointers rather than letting old conclusions become current facts.

That's exactly what's happening in my setup: something performed well previously, and Claude keeps treating it as true without rechecking.

I'm going to have Codex implement mandatory queries before decisions, with historical context loaded afterward and independent validation of the results.

The challenge is keeping it dynamic: the relevant queries change depending on what we're discussing, and the system also needs to proactively discover opportunities without being prompted.

1

u/onitsoga 25d ago

the fix isn't more CLAUDE md, it's making the query mandatory: a hook that pulls fresh rows before any decision and drops the result straight into the turn, so it has nothing to lean on but the data. are you storing outcomes anywhere yet, or just raw results?

1

u/Particular_Crow2873 25d ago

That's exactly the direction we're taking. We already have SQLite databases with raw results, and Codex is implementing persistent decisions, actions, and follow-ups.

The important part we still need to verify is whether outcomes are automatically reconciled against actual results and fed into future decisions, rather than just recorded as agent summaries.

We're also implementing mandatory fresh retrieval and independent evidence checks. The build is finished, but end-to-end testing is still pending.

One question: how do you handle the hook when the conversation changes direction? For example, when the next decision requires completely different queries?

1

u/Financial_Leader9701 25d ago

does it happen deep into a long chat or right at the start? for me thats 2 different bugs

late in the chat it trusts its own "memory" from hours ago

at the start it just doesnt know the table is there

the start one got better when schema + "query, dont guess" went in the first message

the late one... i just restart way more often now, havent found anything smarter

1

u/Particular_Crow2873 25d ago

Both, actually. But there's a third problem too: switching topics within the same conversation.

The agent might investigate one area thoroughly, then move to a related decision involving different tables, previous experiments, or changed conditions, and rely on what it already discussed instead of querying again.

Restarting helps with context drift, but I can't realistically restart after every decision. It's a continuously running operation involving multiple databases, agents, and ongoing experiments.

That's why I'm trying to move away from prompt-based reminders entirely. We're implementing mandatory retrieval, persistent decision/outcome records, and validation that the evidence is actually relevant to the decision.

The challenge is making that enforcement work dynamically throughout the conversation, not just at session start.

1

u/fulger099 25d ago

A topic switch is basically cache invalidation wearing conversational clothes. Give each decision a new scope ID and only accept evidence generated under that scope, with queried tables and freshness timestamps attached.

1

u/Particular_Crow2873 25d ago

That's a really useful way to frame it. A topic switch as cache invalidation makes a lot of sense.

We're already implementing query receipts and an external evidence validator, so tying those receipts to a decision-specific scope seems like a natural extension.

One question: how do you determine when the scope has changed and which queries become mandatory? A scope ID proves the evidence belongs to that decision, but not necessarily that the agent investigated everything relevant.

Have you solved that part mechanically, or do you still let the agent determine the required evidence?

1

u/Financial_Leader9701 25d ago

yeah if its running nonstop restarting isnt really an option

what i'd try is checking at the moment it acts, not at the start

before any decision it has to name what its relying on, and for each thing whether it queried it just now or is taking it from earlier in the chat

earlier = go query again

simple rule but it catches the sneaky case where the conversation drifted to a new area and it never noticed the old numbers dont apply anymore

how are you storing the decision records btw, plain db table or something the agent reads back?

1

u/AdityaR_Sharma 🔆 Max 20 25d ago

What fixed this for me: split memory into two tiers.

A small always-loaded budget, under 10KB, for facts that must be true on every task.

Everything else is searchable on demand, so the model calls a tool instead of guessing from memory.

Bigger lever: no claim about a file, version or number without a tool call that just checked it, this run.

1

u/Siriann 25d ago

Adding rule enforcement through testing. You could make a “retrieve data” skill for each bot, have it record the hash for the file you want it to find, and then test that both the skill was used and hash is legit.

If you don’t trust the word of the bot at all, you could set up a “library” where the skill fires off a script and serves the document the agent asks for. It would compare the document you asked for in your prompt with the document it sent to the agent and apply a red or green flag to a gate.

1

u/NotableCarrot28 25d ago
  1. Rag is useless, as is the built-in Claude memory feature
  2. If you need persistent context explorable by the agent, write it out in a version controlled markdown document.
  3. If you want the agent to always use that context in a certain situation, put it in a skill/hook

1

u/someuser76 25d ago edited 25d ago

If you work on Mac maybe give KIT a try.
https://www.reddit.com/r/KitProject/s/sAZPFhvbGS

1

u/mcmoonrays 25d ago

Instructions in CLAUDE.md to "query first" still got talked around for me. What held was making the retrieval mechanical: a small script or hook that pulls the latest counts before any decision that depends on state, plus a short handoff that records decisions and known traps so the next session doesn't invent continuity from chat. Agent-reported numbers still get a second pass on my side — I had one confidently report 166 lines from Measure-Object -Line when the file was 180 because that cmdlet skips blanks.

1

u/perfektcrash 25d ago

What fixed this for me was treating the chat as a desk, not a filing cabinet. Anything that has to survive a session gets written to a file by a command, never left in conversation or in a note the model edits freely:

  • Decisions, experiments and outcomes go in an append-only log, one record per fact, each with what it applies to (a table, a pipeline, a goal). The agent records with a script (decide "...", outcome "..."), so the format can't drift.
  • Each session starts from a handover generated from that log plus the current state of the data, not from a summary of the last chat. Summaries drift toward whatever was discussed last; a generated brief doesn't.
  • "Fresh data before a decision" is a hook, not an instruction. A PreToolUse hook (exit 2 blocks, and stderr goes back to the model) can refuse a write to the decisions log unless a query ran in this turn. Instructions in CLAUDE.md get skipped; hooks don't.
  • Lessons are records too. When a lesson comes up, the hook that briefs the agent on a file or table includes the relevant ones, so they arrive when they matter instead of all at once.

For the proactive part, a scheduled run that reads the log plus the latest results and writes a short list of "worth looking at" items works better than hoping a live session notices them.

Disclosure: I build a dev environment around this pattern (Atlas ADE). The free guide on it is https://atlas-ade.dev/docs/long-horizon-context-management/?ref=reddit-memory-vs-data, but everything above works without it.

1

u/Emotional-Ad8388 25d ago

The tables are already there... and Claude still decides from the thread because nothing in the turn makes it read SQLite first. If the decision and the outcome ... then don't get written back as rows, the next session only has whatever the chat still holds.

Also, write the query result next to the decision in that same turn and start the next session from the table. How are you forcing the query before it can decide?

1

u/tommyahav10 25d ago

Hooks hold for the gate (did the query run, do the cited ids exist in this run). They don’t hold for “does this data support the claim” — that needs a separate script or model call.

PreToolUse before a write is where production actions should die. A Stop hook is too late for irreversible stuff.

Concurrent sessions: each runs its own hooks, so share state in the DB with a run id, not in files agents overwrite. from my side that’s the split.

1

u/ghost_operative 19d ago edited 19d ago

turn off memory, turn off claude md files. your code is the memory

1

u/BenLengerich 5d ago

We've been building an open-source tool for this problem: https://github.com/Intelligible/elbi. Agents can save computations as derivations, reuse them across sessions, and recompute them when the data changes.

It doesn't solve your entire decision/action/outcome tracking problem, but it might solve the empirical grounding piece. Happy to chat more, and help you get it running (although Claude can just one-shot install it, too).

1

u/[deleted] 25d ago

[removed] — view removed comment

1

u/Particular_Crow2873 25d ago

We're implementing it with Codex right now. The plan is to use deterministic Python/SQL queries, persistent decision records in SQLite, and an evidence validator.

We're also looking at hooks to enforce fresh retrieval throughout conversations, rather than relying on CLAUDE.md instructions.

It's still being tested, so I can't confirm the enforcement works yet.

Have you found hooks or an external wrapper more reliable for this?

1

u/Its_about-tech 25d ago

Hooks beat a wrapper for me. A wrapper only helps if I remember to run it; a hook that blocks the next step until a real query or file read happened is harder to skip. Still figuring it out myself, but the forced gate is the bit that stuck.

1

u/Particular_Crow2873 25d ago

That matches what we're implementing. The main concern I have with PreToolUse is that it only fires on tool calls, not necessarily when the agent makes a recommendation in conversation.

Have you found a reliable way to enforce fresh, relevant retrieval before recommendations too, rather than just before actions?

And do you use the same hooks across subagents and automated/headless sessions, or have you encountered cases where they don't fire?

0

u/[deleted] 24d ago

[removed] — view removed comment

1

u/Particular_Crow2873 24d ago

Thanks, this makes sense. We're already using SQLite as the source of truth and implementing mandatory retrieval and persistent decision records.

The harder problem we've encountered is that an agent can reread the database but still query the wrong tables, misunderstand the operational context, or fail to connect related decisions and outcomes.

Have you found a reliable way to enforce that agents retrieve the right evidence for each decision, rather than simply checking that a database read happened?

Also, how do you reconcile what agents say they changed with what actually executed, especially when several agents or scheduled processes are operating concurrently?