This prompt is for platform operators and SREs who need to enforce data retention policies at the moment an agent session terminates. The job-to-be-done is producing a complete, auditable cleanup action plan that identifies every artifact—tool-cached data, temporary files, context artifacts, and derived datasets—that must be deleted based on a specific retention policy. The ideal user is an AI infrastructure engineer integrating this prompt into a session lifecycle manager or a compliance engineer building automated evidence collection for data deletion workflows. You need a defined data retention policy document, a session manifest listing all tools invoked and their output destinations, and the agent's execution trace to use this prompt effectively.
Prompt
Data Retention Enforcement Prompt for Session Cleanup

When to Use This Prompt
Define the job, ideal user, required context, and constraints for the Data Retention Enforcement Prompt.
Do not use this prompt for real-time data minimization during active sessions—that belongs to the Data Minimization Prompt for Search Tool Queries. Do not use it for PII redaction before tool dispatch, which is covered by the PII Redaction Prompt. This prompt is specifically for the terminal cleanup phase, where the session is ending and you need a defensible record that all data subject to retention limits has been identified and scheduled for deletion. It assumes the session has already been logged and that tool outputs are traceable to storage locations. If your system lacks session-level artifact tracking, you will need to implement that instrumentation first before this prompt can produce reliable results.
The prompt requires a structured retention policy as input—not vague principles. You must supply concrete rules like 'delete all temporary files after 30 days' or 'remove cached API responses immediately upon session close.' The output is a machine-readable cleanup plan, not a conversational summary. You should wire the output directly into a deletion orchestrator that executes the plan and logs confirmation. Human review is required when the policy matching confidence is below your threshold or when the agent identifies artifacts in unregistered storage locations. Start by ensuring your session manifest includes tool name, output path, data classification tag, and creation timestamp for every artifact before invoking this prompt.
Use Case Fit
Where the Data Retention Enforcement Prompt works, where it fails, and the operational prerequisites for safe deployment.
Good Fit: Deterministic Session Lifecycles
Use when: The agent platform has a clear session termination event (logout, timeout, task completion) that triggers the cleanup workflow. The prompt excels at producing a structured, auditable deletion plan when the session boundary is unambiguous. Guardrail: Wire the prompt to the platform's session teardown hook so it cannot be skipped.
Bad Fit: Long-Running or Persistent Agents
Avoid when: Agents maintain persistent memory, long-running loops, or shared caches across user sessions. The prompt assumes a clean termination point and will either miss artifacts still in use or prematurely flag shared resources for deletion. Guardrail: For persistent agents, use a time-based or event-driven garbage collection prompt instead of a session-termination trigger.
Required Input: Complete Tool Inventory with Storage Paths
Risk: The prompt cannot enforce retention on tools it does not know about. If a new tool is added to the agent without updating the inventory, its cached data will be missed during cleanup. Guardrail: Maintain a machine-readable tool registry that maps each tool to its cache directories, temporary file paths, and database tables. Feed this registry into the prompt as [TOOL_STORAGE_MAP].
Required Input: Machine-Readable Retention Policy
Risk: Ambiguous policy language like 'delete when no longer needed' produces inconsistent cleanup plans. The model will guess retention periods, leading to over-deletion or data hoarding. Guardrail: Provide a structured policy schema with explicit fields: data category, retention period, deletion method, and exceptions. Use [RETENTION_POLICY_SCHEMA] as a strict input.
Operational Risk: Incomplete Artifact Discovery
Risk: The prompt may miss ephemeral artifacts such as in-memory caches, database temp tables, or files created by subprocesses that are not in the standard tool registry. These orphaned artifacts accumulate and become a compliance liability. Guardrail: Pair the prompt with a pre-termination system scan that enumerates all files and tables modified during the session window. Use the scan output as [DISCOVERED_ARTIFACTS].
Operational Risk: Premature Deletion During Active Workflows
Risk: If the cleanup prompt fires while a downstream async task or webhook is still processing session data, the agent will delete files that are still in use, causing silent failures. Guardrail: Implement a drain-and-confirm pattern: the prompt must check for active handles or in-flight processes on each artifact before issuing a delete command. Require explicit confirmation for each deletion target.
Copy-Ready Prompt Template
A reusable prompt with square-bracket placeholders that generates a session cleanup action plan based on a data retention policy.
This prompt template is designed to be copied directly into your agent's system instructions or a dedicated cleanup step at session termination. It forces the model to act as an auditor, systematically identifying all artifacts created during a session and mapping each one to a specific rule in your data retention policy. The output is a structured action plan, not just a summary, making it suitable for automated execution or human review before deletion.
textYou are a data retention enforcement agent. Your task is to produce a session cleanup action plan at termination. ## INPUTS - Session Artifact Inventory: [SESSION_ARTIFACT_INVENTORY] - Data Retention Policy: [DATA_RETENTION_POLICY] - Session Metadata: [SESSION_METADATA] ## OUTPUT_SCHEMA Return a JSON object with the following structure: { "session_id": "string", "cleanup_plan": [ { "artifact_id": "string", "artifact_type": "string", "storage_location": "string", "contains_pii": boolean, "applicable_policy_rule": "string", "required_action": "DELETE | ARCHIVE | ANONYMIZE | RETAIN", "retention_deadline_utc": "ISO8601 timestamp or null", "justification": "string" } ], "completeness_check": { "total_artifacts_in_inventory": number, "artifacts_in_plan": number, "unmatched_artifacts": ["string"] } } ## CONSTRAINTS 1. Every artifact in the Session Artifact Inventory MUST appear in the cleanup plan. If no policy rule matches, set required_action to "RETAIN" and note the gap in justification. 2. For artifacts containing PII, the justification must cite the specific regulatory basis (e.g., GDPR Art. 17, CCPA 1798.105). 3. If the Data Retention Policy specifies a duration, calculate the retention_deadline_utc from the session end time in Session Metadata. 4. Do not invent artifacts. Only process what is in the inventory. 5. If the inventory is empty, return a plan with an empty cleanup_plan array and a note in completeness_check. ## RISK_LEVEL HIGH — Incorrect deletion can cause data loss; incorrect retention can cause compliance violations. Output must be reviewed by a human before execution.
To adapt this template, replace the placeholders with data from your application layer. [SESSION_ARTIFACT_INVENTORY] should be a structured list generated by your agent harness—do not rely on the model to recall what happened. [DATA_RETENTION_POLICY] is your organization's policy document, injected as text or a structured schema. [SESSION_METADATA] must include at minimum the session_end_time_utc and tenant_id. The output schema is designed to be validated programmatically: check that total_artifacts_in_inventory equals artifacts_in_plan and that every artifact_id from the input appears in the output. Any mismatch is a critical failure that should block automated deletion and escalate for human review.
Prompt Variables
Required inputs for the Data Retention Enforcement Prompt. Each placeholder must be populated before the prompt is assembled and dispatched. Missing or malformed variables will cause incomplete artifact discovery or incorrect policy rule matching.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SESSION_ID] | Unique identifier for the agent session being terminated | sess_4a7b9c2d | Must match ^[a-z0-9_]+$ pattern. Reject if null or empty. Used to scope all tool-call log queries. |
[TOOL_CALL_LOG] | Structured array of all tool invocations made during the session, including arguments and response metadata | [{"tool": "file_write", "path": "/tmp/agent_scratch/sess_4a7b9c2d/output.csv", "timestamp": "2025-01-15T14:22:10Z"}] | Must be valid JSON array. Each object requires tool, timestamp, and at least one resource-locator field (path, key, uri, table). Reject if array is empty without explicit confirmation that session had zero tool calls. |
[RETENTION_POLICY] | Complete data retention policy document with classification tiers, retention periods, and deletion rules | {"tiers": [{"label": "session_scratch", "max_age_hours": 24, "action": "delete"}, {"label": "audit_log", "max_age_days": 365, "action": "archive"}]} | Must be valid JSON with tiers array. Each tier requires label, max_age, and action fields. Action must be one of delete, archive, or review. Reject if policy document is missing or contains no tiers. |
[CURRENT_TIMESTAMP] | ISO-8601 timestamp representing the moment of session termination | 2025-01-15T15:30:00Z | Must parse as valid ISO-8601 datetime. Used as the reference point for all retention period calculations. Reject if in the past relative to the last tool call timestamp by more than 1 hour without explicit override flag. |
[AGENT_IDENTITY] | Identifier for the agent instance requesting cleanup, used for audit trail attribution | agent-prod-us-east-03 | Must be a non-empty string matching the organization's agent naming convention. Included in every generated audit record for non-repudiation. Reject if null. |
[OVERRIDE_FLAGS] | Optional map of policy override instructions for exceptional retention scenarios | {"legal_hold": true, "hold_reason": "Case 2025-0017", "override_tiers": ["audit_log"]} | Nullable. If provided, must be valid JSON object. legal_hold true requires non-empty hold_reason. override_tiers must be a subset of existing policy tier labels. Reject if override references unknown tier. |
[CONNECTED_STORES] | Inventory of all storage systems, volumes, and databases the agent had tool access to during the session | ["s3://agent-scratch-bucket", "postgres://analytics-db/sandbox", "redis://cache-cluster"] | Must be valid JSON array of URI strings. Each URI must include scheme and resource path. Used to cross-reference tool call logs for completeness. Reject if empty when TOOL_CALL_LOG contains write operations. |
Implementation Harness Notes
How to wire the Data Retention Enforcement Prompt into a session termination pipeline with validation, retries, and audit logging.
This prompt is designed to sit at the end of an agent session lifecycle, triggered by a session termination event in your platform. The harness should invoke the prompt after the agent has completed its work but before the session context is destroyed. Pass the full session transcript, tool call history, and any file or cache manifests as [SESSION_CONTEXT]. The [RETENTION_POLICY] input should be a structured policy document—ideally a JSON or YAML object—that maps data categories to retention durations, deletion methods, and any legal-hold overrides. Do not rely on the model to recall policy details from training; always supply the policy inline to prevent drift when policies change.
The output of this prompt is a structured cleanup action plan. Your harness must validate this plan before executing any destructive actions. Implement a schema validator that checks each action item for required fields: artifact_id, artifact_type, storage_location, policy_rule_applied, action (e.g., DELETE, ARCHIVE, HOLD), and verification_step. If the plan references artifacts not present in the session manifest, flag them for human review. For high-risk environments, insert a mandatory human approval gate before executing any DELETE action. Log the full prompt input, output, and validation result to an immutable audit store for compliance evidence. Use a model with strong structured output support—GPT-4o or Claude 3.5 Sonnet with JSON mode enabled—and set temperature=0 to maximize consistency across runs.
Retry logic should be conservative. If validation fails due to missing fields or malformed JSON, retry once with the validation errors appended to the prompt as [PREVIOUS_ERRORS]. If the retry also fails, escalate to a human operator and do not proceed with automated cleanup. For artifact discovery completeness, run a post-execution verification step that queries your storage systems directly to confirm that all artifacts identified in the plan were actually removed or archived. Any mismatch between the plan and observed state should generate an alert and a follow-up remediation ticket. Avoid wiring this prompt into a fully autonomous deletion loop—always keep a human-in-the-loop for the final execution stage, especially when the session involves multi-tenant data stores or regulated data categories.
Expected Output Contract
Defines the structure, types, and validation rules for the cleanup action plan generated by the Data Retention Enforcement Prompt. Use this contract to parse, validate, and integrate the agent's output into your session termination pipeline.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
session_id | string (UUID) | Must match the [SESSION_ID] input exactly. Reject on mismatch or null. | |
termination_timestamp | ISO 8601 UTC string | Must be a valid timestamp within 5 minutes of the current system time. Reject if in the future or unparseable. | |
retention_policy_version | string | Must match the [POLICY_VERSION] input. Reject on mismatch to prevent stale policy application. | |
discovered_artifacts | array of objects | Must be a non-empty array if the session was active. Each object must conform to the artifact schema below. Reject if empty when session log count > 0. | |
discovered_artifacts[].artifact_id | string | Must be a non-empty string unique within the array. Reject on duplicate IDs. | |
discovered_artifacts[].artifact_type | enum: [FILE, DB_RECORD, CACHE_ENTRY, LOG_ENTRY, MEMORY_BLOCK, API_RESPONSE_CACHE] | Must be one of the specified enum values. Reject on unknown types. | |
discovered_artifacts[].storage_path | string (URI or path) | Must be a non-empty string representing a valid path or URI. Reject on null or empty string. | |
discovered_artifacts[].matched_policy_rule | string | Must reference a rule ID from the [POLICY_RULES] input. Reject if the rule ID is not found in the provided policy set. | |
discovered_artifacts[].deletion_action | enum: [DELETE, ANONYMIZE, ARCHIVE, HOLD] | Must be one of the specified enum values. Reject if the action conflicts with the matched policy rule's mandated action. | |
discovered_artifacts[].deletion_deadline | ISO 8601 UTC string | Must be a valid timestamp after termination_timestamp. Reject if deadline exceeds the max retention period specified in the matched policy rule. | |
discovered_artifacts[].justification | string | Must be a non-empty string explaining why the artifact matches the policy rule. Reject if length < 10 characters. | |
undiscovered_risk_notes | array of strings | If present, each string must describe a potential artifact location that could not be fully verified. Null allowed if agent is confident in completeness. | |
human_approval_required | boolean | Must be true if any artifact has action HOLD or if undiscovered_risk_notes is non-empty. Reject if false when risks are present. |
Common Failure Modes
Data retention enforcement prompts fail in predictable ways—usually because the model doesn't know what artifacts exist, can't match them to policy rules, or generates a plan that looks correct but can't be executed. These cards cover the most common failure modes and how to guard against them before the prompt reaches production.
Incomplete Artifact Discovery
What to watch: The model generates a cleanup plan that misses temporary files, in-memory caches, tool-side logs, or derived datasets because it only considers explicitly declared artifacts. Guardrail: Provide a structured artifact manifest as part of the prompt input, listing all tool-cached data, session files, and context artifacts with their storage locations. Add an eval check that verifies every manifest entry appears in the cleanup plan.
Policy Rule Mismatch
What to watch: The model applies the wrong retention rule to an artifact—deleting data that should be archived or retaining data past its expiration window—because policy rules are ambiguous or the artifact type isn't clearly mapped. Guardrail: Include an explicit policy-to-artifact mapping table in the prompt. Validate outputs by checking that each artifact's assigned action matches the policy rule for its classification label.
Orphaned Artifacts in Downstream Systems
What to watch: The cleanup plan covers primary storage but misses backups, replication targets, CDN caches, or log aggregators that hold copies of the same data. Guardrail: Require the prompt to enumerate all connected storage systems and generate deletion verification steps for each. Add an eval that checks for coverage of backup, log, and replication targets listed in the system topology input.
Unverifiable Deletion Claims
What to watch: The model produces a plan that says 'delete file X' but provides no verification step, making it impossible to confirm the deletion actually executed. Guardrail: Require every deletion action in the output to include a verification method—hash check, existence check, or audit log query. Validate that the output contains at least one verification step per deletion target.
Cross-Session Context Leakage
What to watch: The cleanup plan only addresses the current session's artifacts but misses shared context, conversation summaries, or memory entries that persist across sessions and contain data from the terminated session. Guardrail: Include a cross-session artifact inventory in the prompt input. Add an eval that confirms every shared artifact containing the terminated session's data is addressed in the cleanup plan.
Execution Order Dependency Failures
What to watch: The cleanup plan lists deletion steps in an order that fails at runtime—deleting a parent resource before its children, or removing credentials before the cleanup completes. Guardrail: Require the output to include explicit dependency ordering with preconditions for each step. Validate that no step depends on a resource that appears earlier in the deletion sequence without a stated precondition check.
Evaluation Rubric
Use this rubric to evaluate the quality of the Data Retention Enforcement Prompt's output before deploying it in production. Each criterion targets a specific failure mode common in session cleanup workflows.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
Artifact Discovery Completeness | All tool-cached data, temporary files, and context artifacts from the session are identified in the cleanup plan | Missing artifacts from known tool interactions (e.g., browser cache, database temp tables, file system scraps) | Compare generated artifact list against a golden trace of all tool calls made during the session; verify 100% coverage |
Policy Rule Matching Accuracy | Each artifact is mapped to the correct retention rule from [RETENTION_POLICY] with valid justification | Artifact mapped to wrong rule, missing rule citation, or rule applied that doesn't exist in the policy document | Parse output for rule-to-artifact mappings; validate each mapping against a pre-computed expected mapping table |
Deletion Action Specification | Every identified artifact has a concrete deletion action with target path, method, and verification step | Vague actions like 'clean up temp data' without specific paths, or artifacts listed with no corresponding action | Schema validation: check that each artifact entry has non-null 'deletion_target', 'method', and 'verification_step' fields |
Temporal Dependency Handling | Artifacts with interdependencies (e.g., temp file derived from cached data) are ordered correctly in the deletion sequence | Deletion order that would orphan artifacts, break referential integrity, or leave derivative data behind | Topological sort check: verify deletion sequence respects declared dependency edges between artifacts |
Exception and Retention Justification | Artifacts exempted from deletion include explicit policy rule reference and retention duration | Exemptions without policy justification, or artifacts held beyond their stated retention period | Audit each exemption entry for presence of 'policy_rule_ref' and 'retention_until' timestamp; verify timestamp is within policy bounds |
Session Boundary Enforcement | Cleanup plan is scoped strictly to [SESSION_ID] with no cross-session artifact leakage | Artifacts from other sessions appearing in the plan, or session-scoped queries returning data outside the target session | Inject artifacts from adjacent sessions into the tool state; verify output contains zero references to non-target session IDs |
Verification Step Completeness | Each deletion action includes a verification step that confirms removal before the plan is marked complete | Verification steps that only check existence without confirming deletion, or artifacts marked complete without verification | Parse verification steps for each action; confirm each contains a check method and expected post-deletion state |
Output Schema Compliance | Output strictly matches [OUTPUT_SCHEMA] with all required fields present and correctly typed | Missing required fields, extra fields not in schema, or type mismatches in field values | JSON Schema validation against [OUTPUT_SCHEMA]; reject any output that fails structural validation |
Enabling Efficiency, Speed & Accuracy
Intelligent Analysis, Decision & Execution
We build AI systems for teams that need search across company data, workflow automation across tools, or AI features inside products and internal software.
Talk to Us
Search across company data
Give teams answers from docs, tickets, runbooks, and product data with sources and permissions.
Useful when people spend too long searching or get different answers from different systems.

Automate internal workflows
Use AI to route work, draft outputs, trigger actions, and keep approvals and logs in place.
Useful when repetitive work moves across multiple tools and teams.

Add AI to products and internal tools
Build assistants, guided actions, or decision support into the software your team or customers already use.
Useful when AI needs to be part of the product, not a separate tool.
Adapt This Prompt
How to adapt
Use the base prompt with a simplified [RETENTION_POLICY] that lists only a few artifact types and TTLs. Skip strict JSON schema enforcement and accept a markdown checklist. Focus on artifact discovery logic, not policy rule matching.
Watch for
- Missing artifact categories that exist in your real stack
- Overly broad instructions that flag static assets as temporary
- No verification step before deletion

About the author
Prasad Kumkar
CEO & MD, Inference Systems
Prasad Kumkar is the CEO & MD of Inference Systems and writes about AI systems architecture, LLM infrastructure, model serving, evaluation, and production deployment. Over 5+ years, he has worked across computer vision models, L5 autonomous vehicle systems, and LLM research, with a focus on taking complex AI ideas into real-world engineering systems.
His work and writing cover AI systems, large language models, AI agents, multimodal systems, autonomous systems, inference optimization, RAG, evaluation, and production AI engineering.
Partnered with leading AI, data, and software stack.
How We Work
Custom AI workflows for your Business
One-fit-all AI don't work for modern businesses. At Inferensys, we aim to understand your business & custom requirements; which we use to define most efficient agentic workflows, the data, and the tools for your business.
01
Review the use case
We understand the task, the users, and where AI can actually help.
Read more02
Pick the right approach
We define what needs search, automation, or product integration.
Read more03
Build the first useful version
We implement the part that proves the value first.
Read more04
Improve from there
We add the checks and visibility needed to keep it useful.
Read moreThe first call is a practical review of your use case and the right next step.
Talk to Us