Long-running AI agents can become less reliable when their accumulated memories are treated as permanently valid. The AWS Machine Learning Blog describes production cases in which a support agent treated a billing dispute resolved four months earlier as active and another agent repeated deployment guidance from a superseded runbook. These examples frame agent memory as a managed resource: it needs policies for retention, reassessment, consolidation, deletion, and auditability.
AWS’s proposed implementation targets high-volume agents operating over weeks or months, including customer-support, sales, and IT-helpdesk systems. It uses Amazon Bedrock AgentCore memory, AWS Step Functions, Amazon EventBridge, AWS Lambda, Amazon Bedrock, AWS CloudTrail, Amazon S3, Amazon CloudWatch, and Amazon SNS. A deployable AWS Cloud Development Kit stack defines the infrastructure. Lower-volume agents, such as personal assistants, may begin with time-to-live expiration and GDPR-oriented deletion rather than deploy the complete workflow.
Classifying memories before managing them
The design begins with three memory types because their useful lifetimes differ.
- Episodic memory records what happened in past conversations. These entries are timestamped, session-bound, and numerous. AgentCore’s Summary and Episodic strategies store individual entries associated with agent-user sessions. They provide continuity but generally lose relevance over time, making them the first candidates for expiration.
- Semantic memory captures durable facts or preferences outside any one conversation, such as a preference for the US East (N. Virginia) Region,
us-east-1. These memories are compact and valuable, so policies should retain them longer. They can be created by consolidating several episodic observations into one authoritative fact. - Procedural memory represents learned workflows and tool-use patterns. AgentCore stores procedural knowledge as reflections linked to episodic memory. These entries can encode valuable operating expertise, giving them the longest retention period and the highest deletion threshold. They still require validity checks as procedures change.
Three complementary lifecycle policies
Policy 1: Enforce a TTL ceiling
The first policy deletes records older than a configured time-to-live. The supplied implementation defaults to 90 days for episodic memory. AWS recommends considering differentiated production limits: 30–60 days for summary memories, 6–12 months for semantic memories, and potentially no TTL for procedural memories. The example stack exposes one memoryTtlDays setting as a starting point.
AgentCore memory does not offer built-in automatic TTL deletion. The pruner instead calculates a cutoff timestamp and calls ListMemoryRecords using the system-generated x-amz-agentcore-memory-createdAt field and a BEFORE filter. It then deletes the returned records. This step runs before scoring and consolidation so the workflow does not spend compute evaluating memories that have already exceeded the hard retention limit.
TTL is deliberately blunt: it does not determine whether an older memory remains useful. Its value is establishing a firm accumulation and compliance boundary. That limitation is why the design adds a relevance model rather than relying on age alone.
Policy 2: Score relevance with decay and usage
The second policy combines creation recency, last-access recency, and access frequency. Its formula is:
score = W_RECENCY * exp(-decay_rate * days_since_creation)
+ W_ACCESS * exp(-decay_rate * days_since_last_access)
+ W_FREQUENCY * min(access_count / MAX_ACCESS_BASELINE, 1.0)
Operators configure pruneDays, an approximate point at which an unaccessed memory should fall below the relevance threshold. The implementation derives the exponential rate as -ln(threshold) / prune_days, rejects non-positive pruneDays, and requires a threshold strictly between 0 and 1. With pruneDays = 45 and a threshold of 0.3, the decay rate is approximately 0.02676.
The default weights are 0.4 for creation recency, 0.35 for last-access recency, and 0.25 for access frequency. The default MAX_ACCESS_BASELINE is 50, where the frequency contribution saturates. When the weights total 1.0, the resulting score stays between 0.0 and 1.0. The scoring implementation also rejects a zero or negative access baseline.
This construction allows an older but recently and frequently retrieved record to remain valuable. Workload-specific weighting is important: a support agent may favor frequency because it repeatedly needs the same runbook, while an application driven by rapidly changing information may emphasize creation recency.
AWS offers these starting points for pruneDays:
| Agent type | pruneDays | Reason |
|---|---|---|
| Real-time support bot | 7 | Tickets resolve in hours or days. |
| Sales or onboarding agent | 21 | Deals typically progress over weeks. |
| General assistant | 45 | Balances mixed retention needs. |
| IT helpdesk or operations agent | 90 | Incident patterns can recur seasonally. |
| Legal or compliance advisor | 180 | Relevant precedents may persist for months. |
CloudTrail supplies the missing access signal
MemoryRecordSummary does not include a lastAccessedAt field, so the stack reconstructs access history through CloudTrail. Advanced event selectors capture GetMemoryRecord data events, including each record identifier and timestamp, and deliver the logs to S3.
At the beginning of a scoring run, the Memory Scorer examines CloudTrail files from the previous 25 hours, decompresses them, and aggregates retrieval events into per-record access times and counts. An S3 ledger preserves cumulative history. Each invocation merges new events with that ledger, allowing access frequency to represent lifetime activity instead of only one day’s snapshot.
Policy 3: Consolidate before pruning
Low-scoring memories receive a final preservation opportunity. Amazon Bedrock merges related episodic records into a compact semantic entry—for example, five observations about deployment preferences can become one consolidated fact. The prompt directs the model to preserve essential facts, preferences, and actionable knowledge; eliminate redundancy and obsolete information; and return a summary, a confidence value from 0.0 to 1.0, and a list of preserved key facts.
The workflow writes the consolidated entry before deleting its source records. If the Bedrock call fails, it leaves the originals unchanged. Failed deletions are logged for manual review. This ordering limits damage from an incomplete consolidation run, but it does not make summarization lossless.
An LLM can remove nuance when compressing several memories into one. The returned confidence value can identify consolidations requiring human review, and high-stakes deployments can archive originals in cold storage instead of deleting them. AWS also treats Bedrock Guardrails and grounding checks as production requirements for filtering harmful content and verifying that consolidated entries remain faithful to their source material.
Nightly architecture and orchestration
An EventBridge rule starts the Step Functions state machine every day at 2 AM UTC using cron(0 2 * * ? *). Five Lambda-backed stages run in order:
- The Memory Pruner deletes records older than the TTL.
- The Memory Scorer combines record metadata, CloudTrail access events, and the persistent S3 ledger to find entries below the threshold.
- The Memory Consolidator processes low-scoring entries in batches, with a default batch size of 10, invokes Bedrock, writes consolidated semantic records, and removes the originals.
- The Metrics Emitter publishes processed, consolidated, and pruned counts to CloudWatch.
- The Run Output Writer stores results in S3 for auditing.
If no low-scoring entries exist, the Step Functions Choice state skips consolidation and proceeds to metrics and output writing. The state machine has a one-hour timeout and tracing enabled. A Catch path sends failures to a handler that publishes error details through SNS.
Prerequisites and CDK implementation
Deployment requires an AWS account authorized to create Lambda functions, Step Functions state machines, EventBridge rules, SNS topics, CloudWatch dashboards, CloudTrail trails, and S3 buckets. The listed software prerequisites are AWS CDK v2, Node.js 18 or newer with npm, Python 3.12 with pip, and a configured AWS CLI. Operators also need an AgentCore agent with memory enabled and regional Bedrock access to Claude Sonnet 4.5 using model ID anthropic.claude-sonnet-4-5-20250929-v1:0.
The repository’s dependencies are installed from the code directory with npm install. A single stack at code/lib/memory-lifecycle-stack.ts defines the infrastructure. Lambda handlers use Python 3.12, share constants and models through a Lambda Layer, and receive lifecycle settings through environment variables. The Memory Scorer has a five-minute timeout and receives, among other values, a 25-hour trail lookback.
IAM responsibilities are separated. The scorer can list memory records but cannot mutate them. The pruner can list and delete. The consolidator can retrieve, batch-create, and delete memory records and invoke the configured Bedrock model. Configuration values—including TTL, threshold, consolidation batch size, model ID, pruneDays, weights, and access baseline—come from CDK context, so operators can tune deployment without editing the source.
The example deployment overrides TTL to 60 days, threshold to 0.25, batch size to 15, pruneDays to 45, weights to 0.4, 0.35, and 0.25, and the maximum access baseline to 50.
Costs depend mainly on consolidation volume
Bedrock calls during consolidation are the primary cost driver. AWS estimates that an agent holding 1,000 memories, with 20 percent below the threshold, would make roughly 20 Bedrock calls per nightly run at an estimated cost of about $0.01–$0.02. At 100,000 memories, monthly cost could reach $50–$100. These are workload examples rather than universal prices; operators are directed to review Bedrock pricing for their deployment. The source recommends starting with a higher relevance threshold to restrict consolidation volume.
Regression testing memory quality
Deletion and compression are only successful if the agent continues answering correctly. The supplied regression suite defines question-and-criteria pairs, queries the agent before the lifecycle run, executes the lifecycle, repeats the same questions afterward, and compares results.
AgentCore Evaluations acts as an LLM judge, accepting an agent response and human-defined criteria and returning a normalized quality score from 0.0 to 1.0. A test passes when its post-lifecycle result meets or exceeds its configured minimum. The report also computes post_lifecycle_score - baseline_score so operators can see degradation even when a test still passes.
The two default fixtures set minimums of 0.7 for recalling preferred programming languages and 0.6 for summarizing the previous project. In the sample report, the first changes from 0.82 to 0.85, a +0.03 delta. The second changes from 0.74 to 0.71, a -0.03 delta. Both remain above their limits, producing a 2/2 pass result. This automated pattern is intended for CI/CD use, although an LLM-derived score remains an evaluation signal rather than proof that no important nuance was lost.
Privacy, deletion, and audit controls
A separate GDPR Deletion Handler supports right-to-be-forgotten requests. Given a user ID and memory ID, it lists that user’s records under the user namespace and deletes each one individually. Its response reports the deleted count and any failed record identifiers. A run with failures returns partial_failure, enabling operators to investigate and retry rather than treating an incomplete deletion as successful.
Memory operations produce structured JSON logs in CloudWatch Logs containing an action type, memory identifier, and ISO 8601 timestamp. CloudTrail records AgentCore memory API activity in S3 with file validation enabled. The example trail is not multi-Region and excludes global service events. A CloudWatch dashboard displays processed, consolidated, and pruned memories along with workflow execution status.
Limitations and operational cautions
- TTL can delete an old record without assessing whether it is still useful.
- Consolidation is inherently lossy, so confidence review, grounding, and retention of originals may be warranted.
- AgentCore does not supply automatic TTL deletion or
lastAccessedAtin its record summary; the solution implements those capabilities through filtering, CloudTrail, and S3. - Thresholds and weights are starting points, not universal values. They need workload-specific tuning and regression testing.
- Cost estimates vary with memory volume, the percentage falling below threshold, batching, and applicable Bedrock pricing.
- The GDPR handler reports partial failures, which still require investigation and retry.
Cleanup and practical conclusion
The deployed stack can be removed by running npx cdk destroy from the code directory. AWS cautions that Lambda-created CloudWatch log groups may need separate deletion.
The architecture’s central idea is to combine three controls rather than trust any one mechanism: TTL supplies a firm retention boundary, relevance scoring distinguishes active memories from neglected ones, and consolidation preserves useful knowledge before deletion. Metrics, persisted run results, regression tests, audit logs, and user-specific deletion then make the lifecycle observable and governable. The source’s authors are Himanshu Sah, Akarsha Sehwag, and Nicolò Cosimo Albanese.
Source: AWS Machine Learning Blog, “Designing lifecycle policies for AgentCore memory.” The source also provides the complete implementation in its linked GitHub repository.
Definition. An AgentCore memory lifecycle policy is a managed process for retaining, reassessing, consolidating, testing, auditing, and deleting an AI agent’s accumulated memories.
| Memory type | Lifecycle approach |
|---|---|
| Episodic | Numerous, session-bound records that lose relevance over time and are the first candidates for expiration. |
| Semantic | Durable facts and preferences that should generally be retained longer and can result from episodic consolidation. |
| Procedural | Learned workflows and tool-use patterns with the longest retention period and highest deletion threshold, subject to validity checks. |
Key takeaways
- The nightly workflow removes records beyond the TTL before spending compute on scoring or consolidation.
- Relevance scores combine creation recency, last-access recency, and access frequency using configurable weights.
- CloudTrail events and an S3 ledger supply access history that AgentCore memory summaries do not provide.
- Low-scoring episodic memories can be consolidated into semantic entries before their source records are deleted.
- Regression tests compare agent quality before and after lifecycle processing to detect degradation.
- GDPR deletion, structured logs, persisted run results, metrics, and failure reporting support governance and auditability.
FAQ
Why does the workflow use both TTL and relevance scoring?
TTL creates a firm retention boundary, while relevance scoring can preserve older memories that remain recently or frequently used.
How does AWS track when AgentCore memories are accessed?
The scorer aggregates GetMemoryRecord events from CloudTrail files in S3 and merges them into a persistent access-history ledger.
What happens before a low-scoring memory is deleted?
Amazon Bedrock can consolidate related episodic records into a semantic entry; the workflow writes that entry before deleting its sources and keeps the originals if the model call fails.
How is memory quality checked after pruning?
A regression suite asks the same questions before and after the lifecycle run, then uses AgentCore Evaluations to compare results with configured minimum scores.
Does AgentCore memory provide automatic TTL deletion?
No. The described pruner calculates a cutoff, filters records by their system-generated creation timestamp, and deletes records older than the configured TTL.
What is the main cost driver?
Amazon Bedrock calls used for memory consolidation are the primary cost driver, with total cost depending on memory volume, threshold results, and batching.
