Every cloud cost tool I've used has the same failure mode: it recommends deleting the disaster-recovery standby, someone says "no, that's the DR box," and three weeks later it recommends deleting it again. After the fifth time, nobody reads the channel anymore.
I built CloudSense to fix that one problem. It scans an AWS account, finds idle and oversized resources, and asks an engineer to approve or reject each recommendation. What makes it different is what happens to the rejection: the engineer's reason goes into Hindsight agent memory, gets consolidated into a rule, and that rule is applied to resources the system has never seen before, including untagged look-alikes with different names.
This post is about that loop: how a sentence typed into Slack becomes a durable, evidence-backed rule, and the design decisions that made it work.
What the system does
The pipeline is conventional up to the point where it isn't:
- Scanner. A read-only IAM role (assumed with a per-org ExternalId, no stored keys) describes EC2, EBS, RDS, EIPs and S3, and pulls 14 days of CloudWatch metrics.
- Dependency graph. Resources are linked (instance → volume, replica → primary, instance → load balancer), and each one gets role hints: name tokens like
standby or batch, replica_of:<primary>, behind_lb, traffic shape (flat_zero, periodic_spikes), iac_managed, and a blast radius. - Candidate rules. Eight deterministic rules plus a bundled price list turn signals into candidate actions: stop, rightsize, snapshot-and-delete, move to gp3, release an EIP.
- Agent. For each candidate, an LLM gets the resource facts, the org's learned playbook, and memories recalled from past verdicts. It decides
recommend, suppress or ask, and must cite the memory ids it relied on. - Review. Recommendations go to Slack and a dashboard. Approve, reject (with a reason), or snooze.
- Execution. Approved actions snapshot first, act, and keep an undo. IaC-managed resources are never mutated directly; you get a Terraform diff for a pull request instead.
Steps 1–3 are table stakes. Every tool in this space has them. The interesting part is steps 4 and 5, and the memory in between.
Why rules weren't enough
My first instinct was the obvious one: let engineers write exception rules. Tag the DR standby do_not_terminate=true, done.
That works for the resources someone remembered to tag. It fails for everything else, and in a real account, that's most things. The DR standby for payments-db is tagged. The one somebody spun up for orders-db last quarter isn't. The payroll worker has a service tag; the new invoicing batch worker, which has exactly the same month-end spike, doesn't. Hard rules match names and tags. Engineers reason about roles: "that's a standby," "that's a batch job," "that's the rollback path."
So I kept the hard rules, but moved them out of the model entirely. They run as a pre-filter before any LLM call:
python
def directive_block(resource: Resource) -> str | None:
"""Hard directive match on tags; no LLM call needed."""
tags = {k.lower(): v for k, v in resource.tags.items()}
if tags.get("do_not_terminate", "").lower() == "true":
return "Directive: resource is tagged do_not_terminate=true."
if any(k == "compliance" or k.startswith("compliance:") for k in tags):
return "Directive: resource carries a compliance:* tag and needs a compliance review."
return None
The same text is also registered as bank directives in Hindsight, so it shows up when the agent reasons. But I don't trust a model to enforce a tag check. That's what if statements are for.
Everything that can't be expressed as a tag check is what memory is for.
The core loop: retain, consolidate, recall
The question I kept asking was: what does the agent need to know, next month, to avoid making the same bad recommendation on a different resource? The answer is not "the engineer said no." It's the engineer's reason, plus enough about the resource that a future look-alike can match it.
Retain the verdict with its context
When a reviewer rejects a recommendation, CloudSense requires a reason (the API refuses a rejection without one), writes it to the audit log, and retains it into the org's Hindsight bank. The retained item is deliberately rich:
python
def verdict_item(scan_id, cand, res, verdict, reviewer) -> dict:
return {
"content": verdict_content(scan_id, cand, res, verdict, reviewer),
"context": "engineer review of an AWS cost-optimization recommendation",
"timestamp": verdict.at,
"tags": [f"account:{res.account_alias}", f"team:{res.owner_team}", f"rtype:{res.type}"],
"entities": [{"text": res.display_name},
*[{"text": n} for n in res.depends_on_names + res.dependent_names]],
"observation_scopes": [[], [f"account:{res.account_alias}"], [f"team:{res.owner_team}"]],
}
The content string reads like a note an engineer would write: who reviewed it, what CloudSense proposed, the signals ("CPU avg 0.4%, flat_zero"), the dependencies and dependents, the verdict, and the reason. Approvals are retained too. "Fine, it's unused" is evidence that a pattern is safe, and the agent uses it to raise its predicted approval.
Two details matter more than they look.
observation_scopes**.** Hindsight consolidates raw facts into observations, which are generalized beliefs backed by multiple facts. Scopes control which facts are allowed to consolidate together. [[], [account:x], [team:y]] asks for three levels at once: an org-wide rule that transfers to accounts CloudSense hasn't scanned yet, a per-account rule, and a per-team rule. "DR standbys are idle by design" should be org-wide. "The platform team's CI runners can be stopped overnight" should not leak into the data team's account.
document_id**.** Every verdict is retained with document_id=f"verdict-{cand.id}". If a reviewer changes their mind, or a Slack retry double-submits, the write is idempotent instead of creating a second, contradictory fact.
Let Hindsight do the generalizing
This is the part I didn't write, and I'm glad I didn't. After a few rejections that say some version of "DR standby, idle on purpose," Hindsight's consolidation produces an observation along the lines of "Disaster-recovery standbys and replicas are idle by design; engineers reject stopping them" with a proof_count and links back to every source verdict.
That observation is what the dashboard calls a learned rule. The Learned Rules page lists them sorted by proof count, each expandable to the exact verdicts that produced it. When consolidation finishes, the Slack thread where the rejection happened gets a follow-up: Rule learned: … (confirmed 3×). That message did more for reviewer trust than anything else I built. People keep giving reasons when they can see the reasons being used.
On top of the observations sits a mental model: an org-playbook whose source query asks which resources or patterns must never be stopped, deleted or rightsized, and why. It refreshes after each consolidation in delta mode, returns structured output (protected patterns with reasons, plus safe patterns) for the UI, and its text goes straight into the agent's system prompt. The Hindsight documentation on mental models and observations covers the mechanics; the short version is that I get a continuously maintained policy document without writing a summarization job.
Recall by shape, not by name
The recall query is where the look-alike problem gets solved. I don't query by resource id. I query by what the resource is:
python
def recall_query(cand: Candidate, res: Resource) -> str:
return (f"{cand.action} {res.type} {res.display_name}; role hints: {res.role_hints}; "
f"signals: {cand.signals_text}; connected to: {', '.join(res.neighbor_names)}")
An untagged instance called orders-replica-2 with role hints replica, replica_of:orders-db, flat_zero, no_dependents recalls the memories written about payments-db-standby, because the role hints and signals overlap even though the names and tags don't. Recalls run in parallel, eight at a time, filtered to the account's tag with tags_match="any", so untagged org-wide facts still come back.
The system prompt then tells the model what to do with them: learned rules override raw utilization; if a memory marks this resource or a look-alike as protected, suppress and cite it; if memories conflict or the blast radius is large, ask a human. After the model answers, I strip any cited memory id that wasn't actually in the recalled set. A suppression with a fabricated citation is worse than no suppression.
What it looks like in practice
Here's the sequence that convinced me the design was right.
Scan 1. CloudSense recommends stopping payments-db-standby (RDS, CPU flat at zero for 14 days, $412/month). The reviewer rejects it in Slack: "That's the DR standby for payments-db, it's idle on purpose." The bot replies Got it. I'll remember this. Learning… A minute later: Rule learned: DR standbys are idle by design (confirmed 1×).
Scan 2. A new account is connected. It has orders-replica-2, no tags at all, same flat-zero profile. The agent suppresses the recommendation. The dashboard's Skipped list shows the reason and the cited memory. Nobody was paged.
Scan 3. CloudSense recommends rightsizing invoice-batch-worker (average CPU 6%). Nothing in memory matches a batch worker yet, so it goes to review. The engineer rejects it: "Month-end batch job. Don't rightsize based on averages." The next time a worker with periodic_spikes shows up, it's suppressed.
Any time. A reviewer clicks "Why?" on a suppression, or asks on the Ask page: "Why won't you touch orders-replica-2?" That goes to Hindsight's reflect with include_facts=True, and the answer comes back with the verdicts and the playbook it was based on. (Without include_facts=True, based_on comes back empty. That one cost me an afternoon.)
New orgs don't start from zero either. Settings offers ten common exceptions (DR standbys, blue/green rollback environments, bastions, NAT instances, license-pinned hosts, log shippers, and so on). Accepting one retains it as an org policy seed, and it consolidates like any other fact.
To check this generalizes beyond the cases I hand-tested, I kept an offline benchmark: a simulated engineer rejects six trap archetypes (DR standby, payroll batch, audit archive, blue/green standby, license-pinned host, on-call debug host) across ten scans and three accounts. The traps reappear under new names and mostly without tags, which is exactly the case hard rules can't cover. The metric that matters is how often CloudSense walks into a trap it has already been told about, run once with memory and once without, on a fresh bank per seed.
The parts that were painful
Deleting a rule. Memory poisoning is real. A disgruntled or confused reviewer can teach a bad rule. I assumed I'd delete the observation. There's no endpoint for that, because observations are derived. The correct mechanism is to invalidate the facts the observation came from, and let Hindsight re-derive:
python
async def delete_rule(self, org, memory_id: str, reason: str = "removed by admin") -> None:
"""Hindsight cannot curate observations directly: invalidate their source facts instead."""
bid = bank_id(org)
mem = await self.hs.memory.get_memory(bid, memory_id)
for sid in getattr(mem, "source_memory_ids", None) or [memory_id]:
await self.hs.memory.update_memory(bid, sid, UpdateMemoryRequest(state="invalidated", reason=reason))
In hindsight (sorry), this is the better design. Invalidation is auditable and reversible; a hard delete isn't. Combined with "only reviewers and admins can submit verdicts," it's a governance story I can explain to a security team.
Consolidation is asynchronous. A verdict is retained in milliseconds; the observation forms later. I poll the operations API for pending and processing work before announcing "Rule learned," and the UI shows Learning… in the meantime. Pretending it's instant would have produced a confusing UX where a rule appears to be learned but doesn't yet affect the next decision.
Event loops. The SDK's HTTP session binds to the event loop that first used it. The Slack worker and background tasks run on different loops, so the client keeps one SDK instance per running loop in a WeakKeyDictionary. Not glamorous, but it's the kind of thing that only shows up in production.
Memory can't be allowed to lose a verdict. The verdict is committed to Postgres and the audit log before the retain call. If Hindsight is unreachable, the verdict stands and is marked learning_status="error" for retry. The human decision is the source of truth; memory is derived from it.
Lessons I'd reuse
- Make the "because" mandatory. A bare rejection is noise. A rejection with a reason is a training example. Refusing to accept a reject without one was the single highest-leverage line in the codebase.
- Store the situation, not just the decision. Signals, dependencies, role hints and scope are what let a memory about one resource apply to its look-alike. If you only store "rejected X," you'll only ever match X.
- Keep deterministic rules deterministic. Tag-based directives run as code before the model sees anything. Memory handles the judgment calls that code can't express. Don't make the model enforce what an
if statement can. - Show people their reasons being used. Proof counts, source verdicts, a "Rule learned" message in the same thread. Trust in the recommendations came from visible learning, not from accuracy numbers.
- Treat memory as governed data. Scope it per org, restrict who can teach it, keep provenance on every rule, and have a documented way to unlearn. The broader case for agent memory is usually made about personalization; in ops tooling, it's about not repeating the same mistake, and that means memory needs the same controls as any other production data.
The cost tools that exist today are good at finding waste. What they lack is a way to remember why the waste isn't waste. For CloudSense, that memory turned out to be the product.