This prompt is for agent runtime developers and operators who need a reliable mechanism to save agent state and shut down cleanly when an external signal, timeout, or resource exhaustion event occurs. The primary job is to produce a shutdown checkpoint that captures in-flight task status, resource cleanup notes, and a priority-ordered resumption queue so that execution can resume later without losing work or replaying expensive steps. The ideal user is an engineering lead or AI infrastructure developer building autonomous agent systems that run for extended periods, consume billable resources, or operate in environments where interruptions are expected—such as cloud spot instances, CI/CD pipelines with timeouts, or human-in-the-loop workflows with approval gates.
Prompt
Graceful Shutdown and State Save Prompt

When to Use This Prompt
Define the job, reader, and constraints for the Graceful Shutdown and State Save Prompt.
Use this prompt when your agent runtime must respond to a shutdown signal by saving state before the process terminates. This includes scenarios where the agent receives a SIGTERM, hits a context-window limit, exhausts a token budget, or encounters a resource quota. The prompt expects structured input describing the current plan, completed steps, in-progress tasks, tool outputs, and any pending human decisions. It is designed for agents that already maintain an execution plan and track step-level progress—if your agent lacks these primitives, you need the Agent State Snapshot Prompt Template first to establish baseline state serialization. Do not use this prompt for routine checkpointing during normal execution; the Checkpoint Frequency Decision Prompt handles that scheduling concern. Do not use it when the agent has already crashed or lost state—the Agent Context Reconstruction Prompt After Failure addresses post-crash recovery.
This prompt is not a replacement for application-level signal handling or process supervision. Your runtime must catch the shutdown signal, invoke the prompt with current state, persist the output, and then terminate. The prompt assumes the model has access to the full execution context at shutdown time; if context has already been truncated, pair this with the Context Window Overflow Recovery Prompt before invoking shutdown. For high-risk domains where in-flight task loss could cause financial, safety, or compliance damage, always log the shutdown checkpoint to an append-only audit store and require human review before resumption. The next section provides the copy-ready template you can adapt to your agent's state schema and shutdown triggers.
Use Case Fit
Where the Graceful Shutdown and State Save Prompt works, where it fails, and what inputs it assumes before you wire it into an agent runtime.
Good Fit: Long-Running Autonomous Agents
Use when: agents execute multi-step workflows over minutes or hours where losing intermediate state forces an expensive full replay. Guardrail: wire the shutdown signal to trigger this prompt before any forced termination, and validate the resumption queue is priority-ordered before clearing the agent's working memory.
Bad Fit: Stateless Single-Turn Calls
Avoid when: the agent completes its entire task in one model call with no intermediate state worth preserving. Guardrail: skip the shutdown prompt entirely for stateless calls to avoid unnecessary token overhead and latency. Only invoke it when the agent has accumulated non-trivial state across multiple steps.
Required Inputs
Must provide: the agent's current plan with completed and in-flight steps, active tool outputs, pending decisions, resource handles, and the shutdown trigger reason. Guardrail: if any of these inputs are missing or stale, the checkpoint will be incomplete and resumption may skip critical work or duplicate completed steps.
Operational Risk: In-Flight Task Loss
Risk: tasks that were mid-execution at shutdown time may be lost if the prompt doesn't explicitly capture partial progress and tool call state. Guardrail: require the prompt output to include an explicit 'in_flight_tasks' section with partial results, pending tool calls, and resumption instructions. Validate this section is non-empty before accepting the checkpoint.
Operational Risk: Resource Leak on Shutdown
Risk: file handles, database connections, API sessions, or locks held by the agent may not be released during shutdown, causing resource exhaustion or deadlocks. Guardrail: the prompt must produce a 'resource_cleanup_notes' section listing all acquired resources and their release status. The agent runtime should execute cleanup before terminating.
Operational Risk: Stale Resumption Context
Risk: the saved checkpoint may reference tool outputs, API responses, or environmental state that has changed by the time the agent resumes. Guardrail: include a 'validity_window' field in the checkpoint indicating how long the saved state is expected to remain valid. The resumption handler should re-validate critical assumptions before executing the next step.
Copy-Ready Prompt Template
A reusable prompt template with square-bracket placeholders for generating a shutdown checkpoint that captures in-flight tasks, resource state, and a priority-ordered resumption queue.
This template is designed to be copied directly into your agent's shutdown handler. It instructs the model to produce a structured checkpoint when a shutdown signal, timeout, or resource-exhaustion threshold is triggered. The prompt forces the agent to account for in-flight tasks, note any resources that require cleanup, and build an explicit resumption queue so the next session can pick up execution without replaying completed work. Use it as the core instruction block inside a broader system prompt or as a standalone message dispatched by your orchestration layer when a preemption event fires.
textYou are an agent that must perform a graceful shutdown and save your complete execution state. Your current context: [CURRENT_PLAN] [COMPLETED_STEPS] [IN_FLIGHT_TASKS] [TOOL_OUTPUTS] [RESOURCE_STATE] Shutdown trigger: [SHUTDOWN_REASON] Time available before forced termination: [TIME_BUDGET_SECONDS] seconds. Produce a shutdown checkpoint using the exact schema below. Do not start any new tasks. Do not make any tool calls. [OUTPUT_SCHEMA] Constraints: [CONSTRAINTS] Examples of valid checkpoints: [EXAMPLES] Risk level for this workflow: [RISK_LEVEL]
Adapt this template by replacing each square-bracket placeholder with concrete values from your agent runtime. [CURRENT_PLAN] should contain the full plan object, including dependencies and statuses. [IN_FLIGHT_TASKS] must list every task that has started but not yet been confirmed complete—this is the highest-risk data for resumption. [TIME_BUDGET_SECONDS] lets you bound how long the model spends on the shutdown prompt itself; set this based on your infrastructure's grace period. If your agent uses tools, include [TOOLS] with their current availability status so the resuming agent can detect tool-level changes. For high-risk workflows, add a [HUMAN_REVIEW_FLAG] constraint that marks the checkpoint as requiring operator approval before resumption. Always validate the output against [OUTPUT_SCHEMA] before persisting the checkpoint to storage.
Prompt Variables
Required inputs for the Graceful Shutdown and State Save Prompt. Each placeholder must be populated before the prompt is sent. Missing or invalid variables will cause incomplete checkpoints and unreliable resumption.
| Placeholder | Purpose | Example | Validation Notes |
|---|---|---|---|
[SHUTDOWN_SIGNAL] | The trigger event that initiated the shutdown sequence | SIGTERM received; context window at 92% capacity | Must be one of: timeout, resource_exhaustion, external_signal, human_interrupt, error_cascade. Reject null or empty. |
[ACTIVE_PLAN] | The current execution plan with completed, in-progress, and pending steps | Step 3/7 in-progress: 'validate_schema' with tool output pending | Must contain step IDs, status enum per step, and dependency edges. Schema-validate before prompt assembly. |
[IN_FLIGHT_TASKS] | Tasks currently executing with unresolved outcomes | tool_call_id: tcx-441, function: db_query, status: awaiting_response | Each entry requires tool_call_id, function_name, start_time, timeout_ms. Null allowed if no in-flight tasks. |
[RESOURCE_STATE] | External resources held, modified, or locked by the agent | DB transaction tx-882 open; file handle /tmp/out-12.csv locked | Must list resource type, identifier, lock status, and cleanup action. Empty array allowed if no resources held. |
[RECENT_OUTPUTS] | Outputs from the last N completed steps for context continuity | Step 2 output: schema validation passed with 3 warnings | Include step ID, output payload or summary, and timestamp. Truncate to last 5 steps if context budget is tight. |
[ERROR_LOG] | Errors encountered before shutdown signal | Step 4 failed: API timeout after 3 retries; partial write detected | Each entry requires step_id, error_type, retry_count, and is_recoverable flag. Null allowed if no errors. |
[CONSTRAINTS] | Resumption constraints: max tokens, available tools, model version, time limit | Resume model: claude-sonnet-4-20250514; max 120K tokens; tools: db, fs, api-v2 | Must specify model_id, token_budget, tool_allowlist, and max_resumption_delay_seconds. Reject if tool_allowlist is empty. |
[PRIORITY_HINTS] | User or system hints about which pending tasks matter most for resumption | User marked 'generate_report' as P0; 'cleanup_logs' is deferrable | Optional. If provided, each hint needs task_id and priority enum: P0, P1, P2, deferrable. Null allowed. |
Implementation Harness Notes
How to wire the graceful shutdown prompt into an agent runtime with signal handlers, timeouts, and persistent storage.
This prompt is not a standalone chat interaction—it is a runtime safeguard that must be triggered by the agent harness, not by the model's own initiative. The harness should invoke this prompt when it receives an OS signal (SIGTERM, SIGINT), when a configurable execution timeout is reached, or when resource monitors detect memory/CPU exhaustion. The prompt expects a structured snapshot of the agent's current state as input, including the active plan, completed steps, in-flight tool calls, and any partial outputs. The harness is responsible for assembling this context and injecting it into the [AGENT_STATE] placeholder before the model call.
Wiring pattern: Register a shutdown hook in your agent runtime that (1) sets a shutting_down flag to block new tool dispatches, (2) waits for in-flight tool calls to complete or times them out individually (recommended: 5-second per-call grace period), (3) serializes the current plan state, tool outputs, and pending decisions into a structured object, (4) calls the model with this prompt and the serialized state, and (5) persists the model's JSON output to durable storage (S3, database, or local disk with fsync) before exiting. The model call itself should have a separate timeout (e.g., 10 seconds) to prevent the shutdown sequence from hanging indefinitely. If the model call fails, the harness must fall back to saving the raw serialized state as a best-effort checkpoint and log the failure for operator review.
Validation before persistence: The harness must validate the model's output against the expected schema before writing it to storage. At minimum, confirm that resumption_queue is a non-empty array, that each item has a priority field, and that in_flight_task_handling contains explicit dispositions (retry, discard, await-human) for every task that was in flight. If validation fails, retry once with a stripped-down prompt that asks only for the resumption queue. If that also fails, save the raw state and emit a critical alert—do not silently persist an invalid checkpoint. For high-risk workflows (healthcare, finance, infrastructure), route the checkpoint to a human review queue before marking it as the authoritative resumption state. The checkpoint should include a timestamp, agent session ID, and a hash of the pre-shutdown state for audit trail integrity.
Storage and resumption contract: Persist the checkpoint with a well-known key pattern (e.g., checkpoints/{session_id}/{timestamp}.json) and update a pointer to the latest valid checkpoint atomically. When the agent runtime restarts, it must check for an existing checkpoint before initializing a new session. If a checkpoint exists, load it, validate schema integrity, and pass the resumption_queue to the agent's planning module. Do not assume the checkpoint is valid just because it exists—run the Resume-from-Checkpoint Validation Prompt (sibling playbook) before executing any resumed tasks. If the checkpoint is corrupted or references tools that are no longer available, fall back to a human operator or a safe re-initialization path rather than silently skipping or hallucinating state.
What to avoid: Do not call this prompt inside the agent's normal reasoning loop—it is a shutdown path only. Do not rely on the model to decide when to save state; the harness owns checkpoint timing. Do not skip validation because 'the shutdown was clean'—corrupted checkpoints are most common during resource exhaustion, which is exactly when this prompt is triggered. Finally, test shutdown-and-resume end-to-end in your CI pipeline with injected signals, forced timeouts, and simulated partial tool failures. A checkpoint that saves successfully but cannot be resumed is worse than no checkpoint at all because it creates a false sense of safety.
Expected Output Contract
Fields, data types, and validation rules for the shutdown checkpoint object. Use this contract to build a parser that rejects incomplete or malformed shutdown payloads before state is persisted.
| Field or Element | Type or Format | Required | Validation Rule |
|---|---|---|---|
shutdown_checkpoint_id | string (UUID v4) | Must match UUID v4 regex. Reject if nil or empty. | |
shutdown_trigger | enum string | Must be one of: SIGNAL, TIMEOUT, RESOURCE_EXHAUSTION, USER_REQUEST. Reject unknown values. | |
agent_id | string | Non-empty string. Must match agent identifier format defined in system config. | |
timestamp_utc | string (ISO 8601) | Must parse as valid ISO 8601 UTC datetime. Reject if in future beyond 60s clock skew tolerance. | |
in_flight_tasks | array of objects | Each element must contain task_id (string), status (enum: RUNNING, WAITING), and last_observation (string or null). Array may be empty but must not be null. | |
completed_steps | array of strings | Each string must be a non-empty step identifier. Duplicates allowed but should trigger a warning log, not rejection. | |
resource_cleanup_notes | string or null | If non-null, length must not exceed 2000 characters. Null allowed when no cleanup is required. | |
priority_resumption_queue | array of objects | Each element must contain task_id (string) and priority (integer 1-5). Array must be ordered by priority descending. Reject if any priority is outside 1-5 range. |
Common Failure Modes
What breaks first when an agent tries to save state and shut down cleanly, and how to guard against silent data loss, corrupted checkpoints, and unresumable workflows.
In-Flight Task Loss on Shutdown Signal
What to watch: The agent receives a shutdown signal mid-tool-call and terminates without recording the in-progress step, its partial output, or the tool's side effects. On resume, the agent either repeats the step (double-execution) or skips it entirely (missing work). Guardrail: Wrap every tool call in a try/finally that writes an in_flight marker to the checkpoint before execution and clears it only after the result is saved. On resume, scan for unresolved in_flight markers and reconcile before continuing.
Corrupted Checkpoint from Partial Writes
What to watch: The agent writes state to disk or a database but the write operation is interrupted mid-stream, producing a malformed JSON blob, truncated file, or inconsistent record that fails deserialization on resume. Guardrail: Write checkpoints atomically using a temp-file-and-rename pattern or a database transaction. Validate the checkpoint against its schema and a checksum immediately after writing, and discard any checkpoint that fails validation before marking it as the active resume point.
Resumption Queue with Wrong Priority Order
What to watch: The shutdown prompt produces a resumption queue, but the ordering is based on the original plan rather than the actual state at shutdown. High-priority tasks that were partially complete are deprioritized behind lower-priority unstarted work. Guardrail: Include explicit priority-recalculation logic in the shutdown prompt: rank remaining tasks by (original priority × completion percentage × dependency status). Validate the queue by checking that no blocked task appears before its dependencies.
Resource Cleanup Notes Missing Side Effects
What to watch: The shutdown prompt generates cleanup notes for open file handles, database connections, or API sessions, but misses ephemeral resources like temp files, in-memory caches, or child processes that will leak on termination. Guardrail: Maintain a resource registry that tracks every acquired resource (lock, connection, temp file, subprocess) with its acquisition timestamp. The shutdown prompt must iterate the registry, not rely on the agent's memory of what it opened.
Stale State on Resume After External Changes
What to watch: The agent saves state and shuts down. While it's offline, an external system modifies a resource the agent was working on (a database row is updated, a file is moved, an API state changes). The agent resumes with a stale snapshot and acts on invalid assumptions. Guardrail: Include a preconditions block in the checkpoint that lists expected external state (e.g., record versions, file hashes). On resume, re-validate all preconditions before executing any step that depends on them, and trigger replanning if any precondition fails.
Checkpoint Size Exceeds Context Window on Resume
What to watch: The agent diligently saves complete state including full tool outputs, conversation history, and plan details. On resume, the checkpoint alone consumes 80% of the context window, leaving no room for new reasoning or tool calls. Guardrail: Apply tiered compression in the shutdown prompt: keep full detail for the current step and its immediate dependencies, summarize completed steps, and drop verbose tool outputs that have already been processed into decisions. Validate that the compressed checkpoint fits within a defined token budget before finalizing.
Evaluation Rubric
Use this rubric to evaluate the quality and safety of a Graceful Shutdown and State Save Prompt output before deploying it in a production agent harness. Each criterion targets a specific failure mode that can cause task loss or corrupt resumption state.
| Criterion | Pass Standard | Failure Signal | Test Method |
|---|---|---|---|
In-Flight Task Capture | All active tasks from [ACTIVE_TASKS] appear in the shutdown checkpoint with their exact status and last output reference | Missing task ID, stale status, or null output reference for a task that was in progress | Parse checkpoint JSON; diff task IDs and status fields against the input [ACTIVE_TASKS] list |
Priority-Ordered Resumption Queue | Resumption queue lists tasks in descending priority order with explicit dependencies resolved; no lower-priority task precedes a higher-priority one | Queue order contradicts [PRIORITY_RULES]; dependency chain broken; orphaned task with unmet prerequisite | Validate queue ordering against [PRIORITY_RULES] schema; check each task's dependencies exist earlier in the queue |
Resource Cleanup Notes | Every resource in [ALLOCATED_RESOURCES] has a corresponding cleanup instruction or an explicit 'safe to retain' flag with justification | Resource present in input but absent from cleanup section; ambiguous instruction like 'handle later' without concrete action | Cross-reference [ALLOCATED_RESOURCES] keys against checkpoint cleanup section; reject any missing or vague entries |
Shutdown Reason Documentation | Checkpoint includes the exact [SHUTDOWN_SIGNAL] value, timestamp, and a one-line cause classification | Generic reason like 'shutdown requested'; missing timestamp; signal value does not match input | String-match [SHUTDOWN_SIGNAL] against checkpoint field; confirm ISO 8601 timestamp present and parseable |
Resumption Readiness Flag | Checkpoint contains a boolean | Flag set to true despite missing required fields; flag set to false without listing blocking conditions | Schema validation: require |
State Size and Token Estimate | Checkpoint includes an estimated token count for the serialized state, enabling the harness to decide if it fits within the next model's context window | Token estimate missing; estimate off by more than 50% from actual tokenized length; estimate exceeds [MAX_CHECKPOINT_TOKENS] | Tokenize the serialized checkpoint with the target model's tokenizer; compare to reported estimate; fail if absent or deviation exceeds threshold |
Partial Output Handling | Incomplete tool call results or streaming outputs are captured with a | Partial output stored without flag; flag present but no byte count or replay instruction; completed output incorrectly marked partial | Scan checkpoint for any output with |
Human-Readable Summary for Operator | Checkpoint includes a plain-language summary block suitable for an on-call operator to understand agent state without parsing full JSON | Summary missing; summary contains hallucinated details not present in structured fields; summary omits a critical failure or blocking condition | Manual review by operator persona against structured fields; automated check for summary presence and minimum length; flag contradictions with structured data |
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
Start with the base prompt and a simple JSON schema for the shutdown checkpoint. Use a single [SHUTDOWN_TRIGGER] placeholder that accepts 'signal', 'timeout', or 'resource_exhaustion'. Skip formal eval harnesses and test with 3-5 hand-crafted agent state scenarios. Keep the resumption queue flat (no priority tiers) and omit resource cleanup notes until you validate the core save behavior.
Watch for
- In-flight tasks silently dropped when the model fails to enumerate all active steps
- The model producing prose instead of structured JSON under time-pressure language
- Overly conservative shutdown that saves everything, burning tokens and latency
- Missing the distinction between completed, in-progress, and not-started tasks in the resumption queue

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