Inferensys

Prompt

Plan Generation with Postcondition Contracts Prompt

A practical prompt playbook for generating agent plans with embedded postcondition contracts that catch partial failures and state corruption before they compound across steps.
Legal team reviewing AI contract compliance agent on laptop, contract documents visible, modern WeWork meeting room.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the operational boundary for the postcondition-contract planning prompt and when simpler approaches suffice.

This prompt is for agent planning modules that operate on mutable resources such as databases, file systems, cloud infrastructure, or persistent application state. When an agent modifies state across multiple steps, a silent partial failure in step 3 can corrupt the assumptions step 7 depends on. This prompt forces the model to define explicit postcondition contracts for every step: what the expected output is, what side effects must be observable, and what state changes must be verified before the next step can proceed. Use this prompt when your agent framework needs a plan that an execution harness can validate programmatically after each step, not just a list of instructions.

The ideal user is an AI engineer or platform developer building an agent execution loop that must detect and contain failures before they cascade. Required context includes the agent's available tools, their schemas and side-effect profiles, the target resource types, and the execution harness's validation capabilities. The prompt works best when the harness can actually perform the postcondition checks—querying a database row after a write, listing files after a create operation, or checking infrastructure state after a provisioning step. If your harness can only observe tool return values without verifying external state, this prompt will produce contracts you cannot enforce, creating a false sense of safety.

Do not use this prompt for read-only workflows, stateless transformations, or single-step tool calls where postcondition verification adds overhead without reducing risk. If your agent is summarizing documents, classifying text, or generating content without mutating external state, a simpler plan format without postcondition contracts will be faster and cheaper. Similarly, if your execution harness lacks the ability to perform side-effect verification, prefer a plan format that focuses on output validation rather than state-change contracts. The postcondition approach is specifically valuable when state corruption is the primary failure mode you need to defend against, not when output quality or format compliance is the main concern.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Plan Generation with Postcondition Contracts Prompt delivers value and where it creates unnecessary complexity.

01

Good Fit: Mutable Resource Workflows

Use when: agents modify databases, filesystems, cloud resources, or persistent state where partial failures corrupt downstream steps. Why: postcondition contracts catch silent state corruption before it compounds.

02

Good Fit: Multi-Step Agent Pipelines

Use when: plans span 5+ steps with dependencies where one bad output poisons subsequent reasoning. Why: per-step expected outputs and side effects create verifiable checkpoints between stages.

03

Bad Fit: Stateless Read-Only Queries

Avoid when: the agent only retrieves or summarizes data without modifying anything. Why: postcondition contracts add schema overhead with no state to verify, making simple RAG workflows unnecessarily complex.

04

Bad Fit: Single-Step Tool Calls

Avoid when: the task completes in one function call with no subsequent steps depending on its side effects. Why: the contract scaffolding costs more tokens than the execution itself without reducing risk.

05

Required Inputs

Must have: a clarified goal with explicit success criteria, a complete tool manifest with schemas, and known resource identifiers for all mutable targets. Risk: missing tool schemas cause hallucinated postconditions that pass validation but fail execution.

06

Operational Risk: Validation Gap

What to watch: postcondition checks that only validate output shape but not semantic correctness. Guardrail: pair schema validation with assertion hooks that verify actual state matches expected state before proceeding to the next step.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A copy-ready prompt template for generating a multi-step plan where each step defines its expected outputs, side effects, and state changes as a verifiable contract.

This prompt template is the core of the Plan Generation with Postcondition Contracts workflow. It instructs the model to produce a plan where every step is a contract, not just a description. Each step must declare its expected outputs, side effects, and state changes so that an execution harness can programmatically verify success before proceeding. The template is designed to be copied directly into your planning module, with square-bracket placeholders replaced by your specific goal, available tools, current state, and operational constraints.

text
You are an agent planner that produces execution plans with verifiable postcondition contracts.

# OBJECTIVE
[GOAL]

# AVAILABLE TOOLS
[TOOLS]

# CURRENT STATE
[STATE]

# CONSTRAINTS
[CONSTRAINTS]

# OUTPUT SCHEMA
Produce a JSON plan with the following structure:
{
  "plan_id": "string",
  "goal_summary": "string",
  "assumptions": ["string"],
  "steps": [
    {
      "step_id": "string",
      "description": "string",
      "tool": "string",
      "arguments": {},
      "preconditions": ["string"],
      "postconditions": {
        "expected_output": "description of the primary output",
        "expected_side_effects": ["description of each expected side effect"],
        "expected_state_changes": [
          {
            "resource": "string",
            "property": "string",
            "expected_value": "description or value"
          }
        ]
      },
      "on_failure": "retry|skip|escalate|abort",
      "retry_budget": 0,
      "timeout_seconds": 0
    }
  ]
}

# RULES
1. Every step must have a non-empty postconditions block.
2. expected_state_changes must reference specific resources and properties.
3. If a step has no side effects, explicitly state "no side effects".
4. If a step does not modify state, explicitly state "no state changes".
5. Flag any step where postcondition verification is impossible with the given tools.
6. Do not include steps that cannot be executed with the available tools.

After pasting this template, replace [GOAL] with a clear, unambiguous description of the objective. Populate [TOOLS] with a structured list of available functions, their parameters, and their return types—this is critical because the model must map each step to a real tool. [STATE] should describe the current system state, including relevant resource identifiers and their known properties. [CONSTRAINTS] should include budgets, deadlines, permission boundaries, and any immutable rules. The output schema is strict by design: the postconditions block is what separates this prompt from a generic task list. Each expected_state_change must be specific enough that a validator function can compare it against actual state after execution. Before integrating this prompt into a production agent, run it against a set of known goals and manually inspect whether the generated postconditions are verifiable with your toolset.

IMPLEMENTATION TABLE

Prompt Variables

Each placeholder must be replaced with concrete, specific content. Vague inputs produce vague postconditions that cannot be verified.

PlaceholderPurposeExampleValidation Notes

[GOAL]

The high-level objective the agent must achieve

Migrate the user-service database from PostgreSQL 14 to 16 with zero downtime and a verified rollback path

Must contain a verb and a measurable outcome. Reject if purely conversational or missing a deliverable.

[TOOLS_AVAILABLE]

JSON array of tool definitions the agent can use, each with name, description, and parameter schema

[{"name": "run_migration", "description": "Executes a database migration script", "parameters": {"script_path": "string", "target_env": "string"}}]

Validate each entry has name, description, and parameters. Reject if any tool lacks a parameter schema.

[RESOURCE_STATE]

Current state of all mutable resources the plan will modify

{"databases": [{"name": "user-service-db", "version": "14.8", "size_gb": 120, "replication_slots": 2}]}

Must be a valid JSON object. Each resource must include an identifier and current state. Reject if empty or missing identifiers.

[CONSTRAINTS]

Hard boundaries the plan must not violate: budgets, deadlines, permissions, rate limits, safety rules

Max total execution time: 45 minutes. No writes to production during business hours (09:00-17:00 UTC). Token budget: 50K per step.

Each constraint must be falsifiable. Reject constraints like 'be careful' that cannot be checked programmatically.

[SUCCESS_CRITERIA]

Measurable conditions that define plan completion

["user-service-db reports version 16.8", "zero 5xx errors during cutover", "rollback tested and completes in under 3 minutes"]

Each criterion must be a boolean check executable by a validator. Reject criteria that require human judgment without a rubric.

[OUTPUT_SCHEMA]

Strict JSON schema the generated plan must conform to

{"type": "object", "required": ["steps"], "properties": {"steps": {"type": "array", "items": {"$ref": "#/definitions/step"}}}}

Must be a valid JSON Schema draft-07 or later. Validate with a schema parser before passing to the model.

[FAILURE_MODES]

Known failure modes the plan must guard against, with severity and detection method per mode

[{"mode": "replication lag exceeds 5s during cutover", "severity": "critical", "detection": "poll replication lag metric every 10s"}]

Each entry must include mode, severity, and detection. Reject entries without a detection method.

[ESCALATION_POLICY]

Rules for when to pause, retry, or escalate to a human reviewer

Escalate to DBA on-call if any step fails twice. Pause and request approval before any DROP or TRUNCATE operation.

Must define triggers and targets. Reject if escalation target is unspecified or triggers are subjective.

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the postcondition contract prompt into an agent execution loop with programmatic verification.

The Plan Generation with Postcondition Contracts prompt is not a one-shot generator; it is a contract factory. Each step in the generated plan must define expected outputs, side effects, and state changes in a machine-readable schema. The implementation harness wraps this prompt in an execution loop that reads the plan, executes steps sequentially, and runs programmatic postcondition verification after every step before allowing the next step to proceed. Without this harness, the prompt produces a document that looks correct but provides no runtime safety.

The harness should parse the model's output into a typed plan object with a steps array. Each step object must include an id, a description, a tool or action field, an inputs map, and a postconditions block. The postconditions block is the critical contract: it must contain expected_output_schema (a JSON Schema or type descriptor), expected_side_effects (a list of observable state mutations), and expected_state_changes (a map of key-value assertions about system state after execution). After executing a step, the harness runs a validator function that compares actual outputs, side effects, and state against these contracts. If validation fails, the harness must halt execution, log the mismatch with the step ID and actual vs. expected values, and either trigger a replanning prompt or escalate to a human operator. Do not proceed to the next step on a failed postcondition.

For production deployments, implement the harness with a retry budget per step (default 1 retry with the same inputs before escalation), structured logging that captures the plan version, step ID, tool call, raw output, postcondition contract, and validation result, and a dead-letter queue for steps that fail validation after retries are exhausted. Choose a model with strong schema-following behavior (such as GPT-4o or Claude 3.5 Sonnet) and set response_format to json_schema or use tool-calling mode to enforce the plan structure. If the plan involves mutable infrastructure (databases, cloud resources, file systems), add a pre-execution state snapshot so the postcondition validator can compute diffs. The most common production failure is a step that succeeds at the tool level but produces output that fails schema validation—your harness must distinguish tool failures from contract failures and route them differently.

IMPLEMENTATION TABLE

Expected Output Contract

Validate this schema before accepting the plan for execution. Each step must define its expected outputs, side effects, and state changes.

Field or ElementType or FormatRequiredValidation Rule

plan_id

string (UUID)

Must be a valid UUID v4 string. Parse check.

goal_summary

string

Non-empty string with max 500 characters. Length check.

steps

array of step objects

Array must contain at least 1 step. Schema check on each element.

steps[].step_id

string (kebab-case)

Must match pattern ^step-[a-z0-9-]+$. Regex check.

steps[].description

string

Non-empty string describing the action. Length check.

steps[].tool_name

string or null

Must match an available tool name from [TOOL_LIST] or be null for reasoning-only steps. Enum check.

steps[].expected_output

object

Must conform to [OUTPUT_SCHEMA] for the specified tool. Schema validation required.

steps[].expected_side_effects

array of strings

Each string must describe a state mutation. Array can be empty. Null not allowed.

steps[].postcondition_checks

array of check objects

Array must contain at least 1 check per step. Schema check on each element.

steps[].postcondition_checks[].condition

string

Must be a verifiable boolean expression referencing step output fields. Parse check for valid expression syntax.

steps[].postcondition_checks[].failure_action

string (enum)

Must be one of: retry, skip, escalate, abort, rollback. Enum check.

steps[].depends_on

array of step_id strings

Each step_id must reference a valid step_id earlier in the plan. Array can be empty. Reference integrity check.

PRACTICAL GUARDRAILS

Common Failure Modes

Postcondition contracts fail silently when steps produce plausible but incorrect state. These are the most common production failure patterns and how to catch them before execution proceeds.

01

Silent Partial State Corruption

What to watch: A step reports success but only partially updates the target resource, leaving it in an inconsistent state that corrupts downstream reasoning. Guardrail: Require each step's postcondition to assert specific field-level state expectations, not just a binary success flag. Validate actual resource state against the contract before marking the step complete.

02

Postcondition Drift Across Steps

What to watch: Early steps produce outputs that satisfy their individual contracts but violate assumptions baked into later steps' preconditions, causing cascading failures. Guardrail: Include cross-step invariant checks in the plan harness that verify step N's postconditions are compatible with step N+1's preconditions before execution begins.

03

Undetected Side Effects

What to watch: A step produces the expected primary output but also modifies shared state, external systems, or caches that no postcondition checks for. Guardrail: Require each step contract to declare all expected side effects explicitly. Run a diff or audit log comparison after execution to catch undeclared mutations.

04

Validation-Only Success Semantics

What to watch: The postcondition validator checks output shape but not semantic correctness, letting through well-formed but wrong results that poison later steps. Guardrail: Add semantic assertions to postcondition contracts, such as range checks, relationship constraints, and business-rule validations that go beyond schema conformance.

05

Missing Rollback on Postcondition Failure

What to watch: A step fails its postcondition check but the system proceeds without reversing the partial changes already applied, leaving the world in an unknown state. Guardrail: Every step with mutable side effects must include a compensating action or rollback procedure that triggers automatically when postcondition validation fails.

06

Contract Ambiguity Under Load

What to watch: Postconditions written for single-step execution break when steps run concurrently or under retry, producing race conditions and duplicate side effects. Guardrail: Design postcondition contracts to be idempotency-aware. Include concurrency guards such as version stamps, conditional updates, or compare-and-swap semantics in state assertions.

IMPLEMENTATION TABLE

Evaluation Rubric

Score plan quality before execution. Run these checks on every generated plan. Fail the plan if any critical check fails.

CriterionPass StandardFailure SignalTest Method

Postcondition Completeness

Every step defines expected outputs, side effects, and state changes

Step missing output, side effect, or state change field

Schema validation: assert all step objects contain non-null [OUTPUT], [SIDE_EFFECTS], [STATE_CHANGE] fields

State Change Specificity

Each state change names the resource, property, old value, and new value

State change contains only vague description or missing before/after values

Regex check for resource name, property path, old value, and new value in each [STATE_CHANGE] entry

Side Effect Idempotency

Side effects marked as idempotent include a deduplication key or condition

Idempotent side effect missing dedup key or repeat-safe condition

Parse [SIDE_EFFECTS] for idempotent flag; assert [DEDUP_KEY] or [CONDITION] present when flag is true

Output Schema Alignment

Every step output conforms to the declared output schema for that step

Step output type or shape does not match its own declared schema

Validate each step's [OUTPUT] against its [OUTPUT_SCHEMA] using JSON Schema validator

Dependency Chain Integrity

All postcondition inputs reference outputs from prior steps or initial context

Step references output from a future step or undefined source

Build dependency graph from [DEPENDS_ON] fields; assert no forward references or missing nodes

Failure Detection Coverage

Every step includes a validation check that would detect its declared failure modes

Step lists failure modes but has no corresponding validation logic

For each entry in [FAILURE_MODES], assert at least one check in [VALIDATION] that would catch it

Rollback Path Completeness

Every state-changing step has a compensating action or rollback step defined

State-changing step has no rollback or compensating action

Filter steps where [STATE_CHANGE] is not null; assert [ROLLBACK] or [COMPENSATING_ACTION] is present and non-null

Contract Machine-Readability

All postcondition fields use typed, parseable values, not free-text descriptions

Postcondition contains untyped natural language instead of structured values

Parse all [OUTPUT], [SIDE_EFFECTS], [STATE_CHANGE] fields; assert no field contains only unstructured prose without typed data

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Start with the base prompt and a single-step postcondition schema. Use a lightweight validator that checks only for the presence of expected_outputs and side_effects fields per step. Skip state-change verification and run the prompt against synthetic goals with known tool sets.

code
Add to [SYSTEM_PROMPT]:
"For each step, describe what the step should produce and what side effects it may cause."

Watch for

  • Steps that describe intent instead of concrete postconditions
  • Missing side_effects on steps that modify state
  • Overly verbose postconditions that can't be validated programmatically
Prasad Kumkar

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.