Inferensys

Prompt

Plan Composition Prompt from Multiple Archived Plans

A practical prompt playbook for composing a new execution plan by merging steps from multiple archived plans, resolving ordering conflicts, deduplicating redundant steps, and producing a single coherent workflow with conflict annotations.
Developer designing multi-agent workflow on laptop, architecture diagram on screen, casual home office setup with afternoon light.
PROMPT PLAYBOOK

When to Use This Prompt

Defines the precise job-to-be-done for the Plan Composition Prompt, the required input context, and the boundaries that separate it from single-plan adaptation or abstract pattern extraction.

This prompt is designed for agent orchestrators and plan library systems that need to build a new plan by combining steps from two or more previously archived plans. Use it when a new goal shares partial overlap with multiple existing plans and no single archived plan covers the full scope. The prompt instructs the model to merge steps, resolve ordering dependencies, deduplicate functionally equivalent steps, and flag conflicts that cannot be automatically resolved. The ideal user is an engineering lead or AI builder integrating a plan reuse module into an agent runtime, where the system must programmatically compose a coherent execution plan from a set of candidate plans retrieved by similarity matching.

The prompt assumes the input plans are already serialized in a consistent schema with explicit step definitions, dependencies, and tool references. Each input plan must include a goal description, an ordered steps array with step_id, description, depends_on, and tool fields, and any known constraints. The output is a single merged plan containing a unified steps array, a conflict_log for unresolvable ordering or constraint clashes, and a merge_notes section explaining deduplication decisions. Before calling this prompt, run a precondition check to confirm that at least two candidate plans exist and that their schemas are compatible. After receiving the output, validate that no duplicate step_id values remain, that all depends_on references resolve within the merged step list, and that the conflict_log is empty or contains only acknowledged, documented conflicts.

This is not a prompt for adapting a single plan to a new goal. For single-plan adaptation, use the Plan Adaptation Prompt for Similar Goal Transfer. For abstract pattern extraction, use the Reusable Plan Pattern Extraction Prompt. Do not use this prompt when the input plans come from different agent frameworks with incompatible tool ecosystems unless you have already run the Plan Tool Mapping Prompt to normalize tool references. In high-risk domains where merged plans will execute irreversible actions, always route the composed plan through a human approval step before execution, regardless of the model's confidence.

PRACTICAL GUARDRAILS

Use Case Fit

Where the Plan Composition Prompt works, where it fails, and the operational prerequisites for safe reuse.

01

Good Fit: Consolidating Redundant Workflows

Use when: your team has multiple archived plans for similar goals (e.g., different customer onboarding variants) and needs a single canonical plan. Guardrail: always run the deduplication eval to confirm the merged plan has fewer steps than the sum of inputs.

02

Bad Fit: Novel, Uncharted Objectives

Avoid when: the target goal has no meaningful overlap with any archived plan. Risk: the model will force-fit unrelated steps, creating a plausible but incoherent plan. Guardrail: gate composition behind a similarity threshold; if no source plan scores above 0.7, route to a fresh plan generation prompt instead.

03

Required Inputs: Structured Plan Archives

What to watch: feeding raw conversation logs or unstructured notes instead of serialized plan JSON. Guardrail: enforce a strict input schema that requires steps[], dependencies[], and tool_calls[] arrays. Reject inputs that don't parse against the Completed Plan Serialization schema before composition begins.

04

Operational Risk: Silent Ordering Conflicts

What to watch: two source plans specify contradictory step orders (e.g., Plan A requires 'create user' before 'send email', Plan B requires the reverse). Guardrail: the prompt must output an explicit conflicts[] array in the response. Post-process with a validator that blocks execution if any unresolved conflicts remain.

05

Operational Risk: Tool Drift Across Archives

What to watch: archived plans reference deprecated tools or API versions that no longer exist in the current environment. Guardrail: pair this prompt with a Plan Tool Mapping check. Before finalizing the composed plan, validate every tool_call against the current tool registry and flag mismatches for human review.

06

Cost Risk: Context Window Overload

What to watch: attempting to compose from too many large archived plans simultaneously, leading to truncation or mid-context amnesia. Guardrail: set a hard limit of 3-5 source plans. If more candidates exist, use the Plan Similarity Matching prompt first to select only the top-ranked sources before composition.

PROMPT PLAYBOOK

Copy-Ready Prompt Template

A reusable prompt for composing a new plan by merging steps from multiple archived plans, with placeholders for your specific inputs.

This prompt template is designed to be pasted directly into your planning module. It instructs the model to act as a plan composer, synthesizing a new, coherent plan from a set of provided archived plans. The core task is to merge steps, resolve ordering conflicts, and deduplicate redundant actions while preserving the logic of the source material. The output is a single, actionable plan with explicit conflict notes.

text
You are a Plan Composer agent. Your task is to generate a single, new, multi-step plan by combining and reconciling the following [NUMBER] archived plans, which are provided in the [ARCHIVED_PLANS] section below. The new plan must achieve the goal described in [GOAL_DESCRIPTION], operating under the constraints listed in [CONSTRAINTS].

Follow these rules:
1.  **Merge and Deduplicate:** Combine all steps from the source plans into a single list. Identify and remove semantically duplicate steps, keeping the most detailed version.
2.  **Resolve Ordering:** Analyze dependencies across all steps from all source plans. Produce a valid execution order. If steps from different plans have conflicting ordering requirements, flag this as a conflict.
3.  **Handle Conflicts:** If two source plans suggest contradictory steps, tools, or constraints that cannot be simultaneously satisfied, do not arbitrarily choose one. Instead, include both in a "Conflict Notes" section with a clear explanation of the trade-off.
4.  **Output Format:** You must output a valid JSON object conforming to the schema in [OUTPUT_SCHEMA]. Do not include any text outside the JSON object.

[ARCHIVED_PLANS]:
[INSERT_ARCHIVED_PLANS_HERE]

[GOAL_DESCRIPTION]: [INSERT_GOAL_DESCRIPTION_HERE]

[CONSTRAINTS]: [INSERT_CONSTRAINTS_HERE]

[OUTPUT_SCHEMA]:
{
  "new_plan": {
    "goal": "string",
    "steps": [
      {
        "step_id": "string",
        "action": "string",
        "depends_on": ["step_id"],
        "source_plan_ids": ["string"]
      }
    ],
    "conflict_notes": [
      {
        "conflict_type": "ordering_conflict | tool_conflict | constraint_conflict",
        "description": "string",
        "source_plan_ids": ["string"],
        "unresolved_options": ["string"]
      }
    ]
  }
}

To adapt this template, replace the bracketed placeholders with your specific data. [NUMBER] should be the count of plans you're providing. [ARCHIVED_PLANS] must contain the full text of each plan, clearly delimited and labeled with a unique ID. [GOAL_DESCRIPTION] is a concise statement of what the new plan must accomplish. [CONSTRAINTS] should list any non-negotiable rules, such as required tools, rate limits, or mandatory human approval steps. The [OUTPUT_SCHEMA] is a critical contract; ensure your application's parser strictly validates the generated JSON against this structure. For high-risk workflows, add a constraint requiring human review of all conflict_notes before execution begins.

IMPLEMENTATION TABLE

Prompt Variables

Inputs the prompt needs to compose a merged plan from multiple archived plans. Validate each before sending to the model.

PlaceholderPurposeExampleValidation Notes

[ARCHIVED_PLANS]

Array of archived plan objects with steps, dependencies, tool calls, and outcomes

[{"plan_id": "p1", "goal": "Deploy auth service", "steps": [...]}, {"plan_id": "p2", "goal": "Deploy payment service", "steps": [...]}]

Must be a non-empty array. Each element must have plan_id, goal, and steps fields. Reject if steps array is empty or missing.

[COMPOSITION_GOAL]

The new objective that the merged plan must satisfy

"Deploy a unified customer onboarding flow combining auth and payment"

Must be a non-empty string. Check for goal drift: if goal is too dissimilar from source plan goals, flag for human review before composition.

[CONSTRAINTS]

Environment constraints that apply to the merged plan

{"rate_limit": "100 req/s", "max_latency_ms": 500, "required_tools": ["k8s", "terraform"]}

Must be a valid JSON object. Validate that constraint keys match known constraint types. Null allowed if no constraints.

[TOOL_CATALOG]

Available tools and their capabilities in the target execution environment

["k8s_deploy", "terraform_apply", "db_migrate", "dns_update"]

Must be a non-empty array of tool names. Cross-reference with tool references in archived plans; flag any referenced tool not in catalog.

[OUTPUT_SCHEMA]

Expected JSON schema for the merged plan output

{"type": "object", "properties": {"merged_plan": {"type": "object"}, "conflicts": {"type": "array"}, "deduplicated_steps": {"type": "array"}}}

Must be a valid JSON Schema object. Validate schema syntax before passing to model. Reject if schema is malformed.

[CONFLICT_RESOLUTION_POLICY]

Rules for resolving conflicts between source plans

"prefer_newer_plan: true, max_step_merge_depth: 3, on_irreconcilable: flag_for_review"

Must be a non-empty string or object. Validate that policy keys are recognized. If policy is missing, default to flag_for_review for all conflicts.

[MAX_PLAN_SIZE]

Upper bound on the number of steps in the merged plan

50

Must be a positive integer. If merged plan exceeds this, model should prioritize deduplication and flag overflow steps. Reject if value is 0 or negative.

[SOURCE_PLAN_WEIGHTS]

Optional priority weights for source plans when resolving ordering conflicts

{"p1": 0.8, "p2": 0.5}

Must be a valid JSON object mapping plan_id to float between 0 and 1. Null allowed. If provided, validate all plan_ids exist in [ARCHIVED_PLANS].

PROMPT PLAYBOOK

Implementation Harness Notes

How to wire the plan composition prompt into an agent planning module or plan library system.

This prompt is designed to be called programmatically by an agent orchestrator or a plan library service, not by an end user. The caller must supply a list of archived plans (each with steps, dependencies, tool references, and constraints) and a new goal specification. The prompt returns a merged plan that resolves ordering, deduplicates steps, and flags conflicts. The output is structured JSON, which makes it suitable for direct consumption by a downstream execution engine or for storage as a new plan candidate in the library.

Before calling the prompt, validate that each input plan conforms to the expected schema: a unique plan ID, an ordered list of steps with dependencies, tool requirements, and any constraints. If a plan is missing required fields, reject it early rather than letting the model hallucinate missing data. On the output side, apply a structural validator that checks for duplicate step IDs, circular dependencies, and unresolved tool references. If validation fails, retry the prompt once with the validation errors appended as [CONSTRAINTS]. If the retry also fails, log the failure, store the partial output with an error flag, and escalate for human review. For high-stakes workflows, require a human to approve the composed plan before it enters the execution queue.

Model choice matters here. Use a model with strong reasoning and structured output capabilities, such as GPT-4o or Claude 3.5 Sonnet, and set response_format to json_schema with the expected output schema. Enable prompt caching on the static instruction prefix to reduce latency and cost when composing multiple plans in a batch. Log every composition request with the input plan IDs, the new goal, the raw model output, validation results, and the final accepted or rejected status. This audit trail is essential for debugging plan conflicts and for governance when plans are reused across teams. Avoid using this prompt for real-time execution paths where latency is critical; plan composition is a batch or pre-execution step that should complete before the agent begins acting.

IMPLEMENTATION TABLE

Expected Output Contract

Validation rules for the merged plan output. Use this contract to build a post-generation validator that rejects malformed, redundant, or inconsistent plans before they reach the execution engine.

Field or ElementType or FormatRequiredValidation Rule

merged_plan

object

Top-level object must contain steps, metadata, and conflict_notes arrays. Reject if absent or not an object.

merged_plan.steps

array of step objects

Array must contain at least 1 step. Reject if empty. Each step must have a unique step_id within the array.

merged_plan.steps[].step_id

string

Must be non-empty and unique across all steps. Pattern: alphanumeric with underscores, no spaces. Reject duplicates.

merged_plan.steps[].source_plan_ids

array of strings

Each entry must reference a plan_id present in the [ARCHIVED_PLANS] input. Reject orphan references.

merged_plan.steps[].action

string

Must be a non-empty instruction string. Reject if identical to another step's action unless explicitly flagged as intentional repetition in conflict_notes.

merged_plan.steps[].dependencies

array of step_id strings

If present, every referenced step_id must exist in merged_plan.steps. Reject dangling dependency references. Null or empty array allowed.

merged_plan.conflict_notes

array of conflict objects

If present, each conflict object must reference at least two conflicting step_ids and include a resolution field. Reject malformed conflict objects.

merged_plan.metadata.ordering_rationale

string

Must be a non-empty string explaining the execution order logic. Reject if missing or whitespace-only. Minimum 20 characters.

PRACTICAL GUARDRAILS

Common Failure Modes

When composing a new plan from multiple archived plans, these failures surface first in production. Each card pairs a specific failure with a concrete guardrail you can implement before deployment.

01

Duplicate Steps Survive Merge

What to watch: Two archived plans contain semantically identical steps with different labels, and the composition prompt includes both without deduplication. The merged plan bloats with redundant work that wastes tokens and confuses execution loops. Guardrail: Add an explicit deduplication pass after composition. Use a separate prompt or deterministic step that compares step descriptions, tool calls, and expected outputs, then removes near-duplicates with a confidence threshold below which human review is required.

02

Ordering Conflicts Produce Deadlocks

What to watch: Plan A requires step X before step Y, but Plan B requires step Y before step X. The composition prompt resolves the conflict silently by picking one ordering without surfacing the contradiction, creating a plan that deadlocks at runtime. Guardrail: Require the composition prompt to output an explicit conflicts array with unresolved ordering contradictions. Route any plan with non-empty conflicts to a human reviewer or a conflict-resolution prompt before execution.

03

Tool Assumptions Drift Across Plans

What to watch: Archived plans reference tools, API versions, or function signatures that have changed or are unavailable in the target environment. The composed plan inherits stale tool calls that fail at execution time with no recovery path. Guardrail: Run a tool-availability check against the composed plan before execution. Validate every tool reference against the current tool manifest and flag any mismatch. For missing tools, require a tool-mapping prompt to propose substitutions or mark steps as blocked.

04

Constraint Contamination Across Contexts

What to watch: An archived plan was built under constraints—rate limits, data schemas, permission boundaries—that differ from the current goal. The composition prompt carries forward those constraints without revalidation, producing a plan that violates the new environment's rules. Guardrail: Include current constraints as a required input to the composition prompt and instruct the model to reject any archived step whose preconditions conflict with active constraints. Add a post-composition constraint-validation pass that checks each step against the constraint manifest.

05

Missing Precondition Chains

What to watch: The composition prompt stitches steps from multiple plans but drops intermediate steps that established necessary preconditions—authentication, data fetching, state initialization. The merged plan looks coherent but fails at step N because step N-1 never produced the required state. Guardrail: Require the composition prompt to output explicit precondition fields for every step. Run a precondition-satisfaction check that verifies each step's preconditions are produced by a prior step or are available as initial inputs. Flag unsatisfied preconditions for human review.

06

Conflicting Success Criteria Go Undetected

What to watch: Two archived plans define different success criteria for similar steps—one considers a partial result acceptable, the other requires full completion. The composition prompt merges the steps without reconciling the criteria, so the execution loop cannot determine when a step is truly done. Guardrail: Add a success-criteria reconciliation field to the composition output schema. Require the prompt to either unify conflicting criteria with explicit rationale or flag the conflict as unresolved. Post-composition, validate that every step has exactly one set of measurable completion conditions.

IMPLEMENTATION TABLE

Evaluation Rubric

Use this rubric to test the quality of a composed plan before shipping it to production. Each criterion targets a specific failure mode in plan composition—redundancy, ordering conflicts, missing dependencies, and hallucinated steps. Run these checks programmatically or via LLM-as-judge before the composed plan enters an execution loop.

CriterionPass StandardFailure SignalTest Method

Step Deduplication

No two steps in the composed plan describe the same action with the same inputs and expected outputs. Near-duplicate steps are merged or explicitly annotated as intentional variants.

Two or more steps share identical or near-identical descriptions, tool calls, and target resources without a documented reason for duplication.

LLM-as-judge pairwise comparison of all step descriptions. Flag pairs with cosine similarity above 0.92 and no differentiating annotation.

Dependency Ordering Consistency

All explicit dependencies from source plans are preserved. No step depends on an output produced by a later step. The composed plan forms a valid DAG.

A step references an output or state that is not produced until a later step, or a dependency edge from a source plan is missing in the composed plan.

Topological sort check on the composed step graph. Compare dependency edges against the union of source-plan dependency graphs. Flag missing or reversed edges.

Conflict Annotation Completeness

Every identified conflict between source plans is documented with a conflict note that includes the conflicting steps, the nature of the conflict, and the resolution chosen.

The composed plan contains merged steps from conflicting source plans but no corresponding conflict note, or the conflict note lacks resolution rationale.

Extract conflict annotations from the composed plan output. Cross-reference with a pre-computed conflict list from the source plans. Flag unannotated conflicts.

Tool and Resource Reference Validity

All tool names, resource identifiers, and API references in the composed plan match the provided [TOOL_CATALOG] and [RESOURCE_MAP]. No hallucinated tools or endpoints.

A step references a tool, endpoint, or resource identifier not present in the input catalogs, or uses a deprecated version without a substitution note.

Schema validation: extract all tool and resource references from composed steps. Check membership against the provided [TOOL_CATALOG] and [RESOURCE_MAP] sets. Flag any unknown references.

Precondition Preservation

Every precondition from source-plan steps that is retained in the composed plan is still satisfiable given the new step ordering and merged context. No orphaned preconditions.

A step's precondition references a state or input that is no longer produced by any preceding step in the composed plan, or the producing step was removed without updating the dependent step.

For each retained step with a precondition, trace backward through the composed plan to verify a producing step exists. Flag unsatisfiable preconditions.

Step Count and Bloat Control

The composed plan has fewer steps than the sum of source-plan steps. Merged steps reduce count proportionally to overlap. No unexplained step inflation.

The composed plan has more steps than the sum of source-plan steps, or step count reduction is less than 10% when source plans share significant overlap.

Count steps in the composed plan and compare to the sum of source-plan step counts. Calculate overlap ratio from source-plan step similarity. Flag if composed count exceeds sum or reduction is below threshold given overlap.

Goal Coverage

Every required sub-goal from [GOAL_DECOMPOSITION] is addressed by at least one step in the composed plan. No sub-goal is dropped during composition.

A sub-goal from the input goal decomposition has no corresponding step in the composed plan, or the covering step lacks the necessary outputs to satisfy the sub-goal.

Map each sub-goal from [GOAL_DECOMPOSITION] to the composed plan steps that produce its required outputs. Flag any sub-goal with zero covering steps or insufficient output coverage.

Output Schema Compliance

The composed plan output matches the [OUTPUT_SCHEMA] exactly. All required fields are present, step ordering is represented in the specified format, and conflict notes follow the defined structure.

The composed plan output is missing required fields, uses incorrect types, nests steps incorrectly, or places conflict notes outside the designated schema location.

JSON Schema validation against [OUTPUT_SCHEMA]. Flag any schema violations. Additionally, verify that the step list and conflict notes arrays are non-empty when source plans have content.

ADAPTATION OPTIONS

Adapt This Prompt

How to adapt

Use the base prompt with a frontier model (GPT-4o, Claude 3.5 Sonnet) and minimal validation. Focus on getting a merged plan that looks reasonable for a single test case. Skip the eval harness and accept raw text or loosely structured JSON output.

  • Remove strict [OUTPUT_SCHEMA] enforcement; accept a markdown plan with numbered steps.
  • Replace [CONFLICT_RESOLUTION_POLICY] with a simple instruction: "If steps conflict, pick the most recent or most specific one and note why."
  • Drop the deduplication threshold and ask the model to "combine similar steps where it makes sense."

Watch for

  • The model silently dropping steps from one source plan because it favors the longer or more recent plan.
  • Ordering that looks plausible but violates a hard dependency from an archived plan.
  • No conflict notes when steps genuinely contradict each other—the model may harmonize away real disagreements.
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.