Skip to main content

PATTERNS

Constant PATTERNS 

Source
pub const PATTERNS: &str = "---\nrole: best-practices\nsummary: |\n  Design patterns for robust, efficient, and maintainable OpenProse programs.\n  Read this file when authoring new programs or reviewing existing ones.\nsee-also:\n  - prose.md: Execution semantics, how to run programs\n  - compiler.md: Full syntax grammar, validation rules\n  - antipatterns.md: Patterns to avoid\n---\n\n# OpenProse Design Patterns\n\nThis document catalogs proven patterns for orchestrating AI agents effectively. Each pattern addresses specific concerns: robustness, cost efficiency, speed, maintainability, or self-improvement capability.\n\n---\n\n## Structural Patterns\n\n#### parallel-independent-work\n\nWhen tasks have no data dependencies, execute them concurrently. This maximizes throughput and minimizes wall-clock time.\n\n```prose\n# Good: Independent research runs in parallel\nparallel:\n  market = session \"Research market trends\"\n  tech = session \"Research technology landscape\"\n  competition = session \"Analyze competitor products\"\n\nsession \"Synthesize findings\"\n  context: { market, tech, competition }\n```\n\nThe synthesis session waits for all branches, but total time equals the longest branch rather than the sum of all branches.\n\n#### fan-out-fan-in\n\nFor processing collections, fan out to parallel workers then collect results. Use `parallel for` instead of manual parallel branches.\n\n```prose\nlet topics = [\"AI safety\", \"interpretability\", \"alignment\", \"robustness\"]\n\nparallel for topic in topics:\n  session \"Deep dive research on {topic}\"\n\nsession \"Create unified report from all research\"\n```\n\nThis scales naturally with collection size and keeps code DRY.\n\n#### pipeline-composition\n\nChain transformations using pipe operators for readable data flow. Each stage has a single responsibility.\n\n```prose\nlet candidates = session \"Generate 10 startup ideas\"\n\nlet result = candidates\n  | filter:\n      session \"Is this idea technically feasible? yes/no\"\n        context: item\n  | map:\n      session \"Expand this idea into a one-page pitch\"\n        context: item\n  | reduce(best, current):\n      session \"Compare these two pitches, return the stronger one\"\n        context: [best, current]\n```\n\n#### agent-specialization\n\nDefine agents with focused expertise. Specialized agents produce better results than generalist prompts.\n\n```prose\nagent security-reviewer:\n  model: sonnet\n  prompt: \"\"\"\n    You are a security expert. Focus exclusively on:\n    - Authentication and authorization flaws\n    - Injection vulnerabilities\n    - Data exposure risks\n    Ignore style, performance, and other concerns.\n  \"\"\"\n\nagent performance-reviewer:\n  model: sonnet\n  prompt: \"\"\"\n    You are a performance engineer. Focus exclusively on:\n    - Algorithmic complexity\n    - Memory usage patterns\n    - I/O bottlenecks\n    Ignore security, style, and other concerns.\n  \"\"\"\n```\n\n#### reusable-blocks\n\nExtract repeated workflows into parameterized blocks. Blocks are the functions of OpenProse.\n\n```prose\nblock review-and-revise(artifact, criteria):\n  let feedback = session \"Review {artifact} against {criteria}\"\n  session \"Revise {artifact} based on feedback\"\n    context: feedback\n\n# Reuse the pattern\ndo review-and-revise(\"the architecture doc\", \"clarity and completeness\")\ndo review-and-revise(\"the API design\", \"consistency and usability\")\ndo review-and-revise(\"the test plan\", \"coverage and edge cases\")\n```\n\n---\n\n## Robustness Patterns\n\n#### bounded-iteration\n\nAlways constrain loops with `max:` to prevent runaway execution. Even well-crafted conditions can fail to terminate.\n\n```prose\n# Good: Explicit upper bound\nloop until **all tests pass** (max: 20):\n  session \"Identify and fix the next failing test\"\n\n# The program will terminate even if tests never fully pass\n```\n\n#### graceful-degradation\n\nUse `on-fail: \"continue\"` when partial results are acceptable. Collect what you can rather than failing entirely.\n\n```prose\nparallel (on-fail: \"continue\"):\n  primary = session \"Query primary data source\"\n  backup = session \"Query backup data source\"\n  cache = session \"Check local cache\"\n\n# Continue with whatever succeeded\nsession \"Merge available data\"\n  context: { primary, backup, cache }\n```\n\n#### retry-with-backoff\n\nExternal services fail transiently. Retry with exponential backoff to handle rate limits and temporary outages.\n\n```prose\nsession \"Call external API\"\n  retry: 5\n  backoff: \"exponential\"\n```\n\nFor critical paths, combine retry with fallback:\n\n```prose\ntry:\n  session \"Call primary API\"\n    retry: 3\n    backoff: \"exponential\"\ncatch:\n  session \"Use fallback data source\"\n```\n\n#### error-context-capture\n\nCapture error context for intelligent recovery. The error variable provides information for diagnostic or remediation sessions.\n\n```prose\ntry:\n  session \"Deploy to production\"\ncatch as err:\n  session \"Analyze deployment failure and suggest fixes\"\n    context: err\n  session \"Attempt automatic remediation\"\n    context: err\n```\n\n#### defensive-context\n\nValidate assumptions before expensive operations. Cheap checks prevent wasted computation.\n\n```prose\nlet prereqs = session \"Check all prerequisites: API keys, permissions, dependencies\"\n\nif **prerequisites are not met**:\n  session \"Report missing prerequisites and exit\"\n    context: prereqs\n  throw \"Prerequisites not satisfied\"\n\n# Expensive operations only run if prereqs pass\nsession \"Execute main workflow\"\n```\n\n---\n\n## Cost Efficiency Patterns\n\n#### model-tiering\n\nMatch model capability to task complexity:\n\n| Model          | Best For                                     | Examples                                                     |\n| -------------- | -------------------------------------------- | ------------------------------------------------------------ |\n| **Sonnet 4.5** | Orchestration, control flow, coordination    | VM execution, captain\'s chair, workflow routing              |\n| **Opus 4.5**   | Hard/difficult work requiring deep reasoning | Complex analysis, strategic decisions, novel problem-solving |\n| **Haiku**      | Simple, self-evident tasks (use sparingly)   | Classification, summarization, formatting                    |\n\n**Key insight:** Sonnet 4.5 excels at _orchestrating_ agents and managing control flow\u{2014}it\'s the ideal model for the OpenProse VM itself and for \"captain\" agents that coordinate work. Opus 4.5 should be reserved for agents doing genuinely difficult intellectual work. Haiku can handle simple tasks but should generally be avoided where quality matters.\n\n**Detailed task-to-model mapping:**\n\n| Task Type                                | Model  | Rationale                                 |\n| ---------------------------------------- | ------ | ----------------------------------------- |\n| Orchestration, routing, coordination     | Sonnet | Fast, good at following structure         |\n| Investigation, debugging, diagnosis      | Sonnet | Structured analysis, checklist-style work |\n| Triage, classification, categorization   | Sonnet | Clear criteria, deterministic decisions   |\n| Code review, verification (checklist)    | Sonnet | Following defined review criteria         |\n| Simple implementation, fixes             | Sonnet | Applying known patterns                   |\n| Complex multi-file synthesis             | Opus   | Needs to hold many things in context      |\n| Novel architecture, strategic planning   | Opus   | Requires creative problem-solving         |\n| Ambiguous problems, unclear requirements | Opus   | Needs to reason through uncertainty       |\n\n**Rule of thumb:** If you can write a checklist for the task, Sonnet can do it. If the task requires genuine creativity or navigating ambiguity, use Opus.\n\n```prose\nagent captain:\n  model: sonnet  # Orchestration and coordination\n  persist: true  # Execution-scoped (dies with run)\n  prompt: \"You coordinate the team and review work\"\n\nagent researcher:\n  model: opus  # Hard analytical work\n  prompt: \"You perform deep research and analysis\"\n\nagent formatter:\n  model: haiku  # Simple transformation (use sparingly)\n  prompt: \"You format text into consistent structure\"\n\nagent preferences:\n  model: sonnet\n  persist: user  # User-scoped (survives across projects)\n  prompt: \"You remember user preferences and patterns\"\n\n# Captain orchestrates, specialists do the hard work\nsession: captain\n  prompt: \"Plan the research approach\"\n\nlet findings = session: researcher\n  prompt: \"Investigate the technical architecture\"\n\nresume: captain\n  prompt: \"Review findings and determine next steps\"\n  context: findings\n```\n\n#### context-minimization\n\nPass only relevant context. Large contexts slow processing and increase costs.\n\n```prose\n# Bad: Passing everything\nsession \"Write executive summary\"\n  context: [raw_data, analysis, methodology, appendices, references]\n\n# Good: Pass only what\'s needed\nlet key_findings = session \"Extract key findings from analysis\"\n  context: analysis\n\nsession \"Write executive summary\"\n  context: key_findings\n```\n\n#### early-termination\n\nExit loops as soon as the goal is achieved. Don\'t iterate unnecessarily.\n\n```prose\n# The condition is checked each iteration\nloop until **solution found and verified** (max: 10):\n  session \"Generate potential solution\"\n  session \"Verify solution correctness\"\n# Exits immediately when condition is met, not after max iterations\n```\n\n#### early-signal-exit\n\nWhen observing or monitoring, exit as soon as you have a definitive answer\u{2014}don\'t wait for the full observation window.\n\n```prose\n# Good: Exit on signal\nlet observation = session: observer\n  prompt: \"Watch the stream. Signal immediately if you detect a blocking error.\"\n  timeout: 120s\n  early_exit: **blocking_error detected**\n\n# Bad: Fixed observation window\nloop 30 times:\n  resume: observer\n    prompt: \"Keep watching...\"  # Even if error was obvious at iteration 2\n```\n\nThis respects signals when they arrive rather than waiting for arbitrary timeouts.\n\n#### defaults-over-prompts\n\nFor standard configuration, use constants or environment variables. Only prompt when genuinely variable.\n\n```prose\n# Good: Sensible defaults\nconst API_URL = \"https://api.example.com\"\nconst TEST_PROGRAM = \"# Simple test\\nsession \'Hello\'\"\n\n# Slower: Prompting for known values\nlet api_url = input \"Enter API URL\"  # Usually the same value\nlet program = input \"Enter test program\"  # Usually the same value\n```\n\nIf 90% of runs use the same value, hardcode it. Let users override via CLI args if needed.\n\n#### race-for-speed\n\nWhen any valid result suffices, race multiple approaches and take the first success.\n\n```prose\nparallel (\"first\"):\n  session \"Try algorithm A\"\n  session \"Try algorithm B\"\n  session \"Try algorithm C\"\n\n# Continues as soon as any approach completes\nsession \"Use winning result\"\n```\n\n#### batch-similar-work\n\nGroup similar operations to amortize overhead. One session with structured output beats many small sessions.\n\n```prose\n# Inefficient: Many small sessions\nfor file in files:\n  session \"Analyze {file}\"\n\n# Efficient: Batch analysis\nsession \"Analyze all files and return structured findings for each\"\n  context: files\n```\n\n---\n\n## Self-Improvement Patterns\n\n#### self-verification-in-prompt\n\nFor tasks that would otherwise require a separate verifier, include verification as the final step in the prompt. This saves a round-trip while maintaining rigor.\n\n```prose\n# Good: Combined work + self-verification\nagent investigator:\n  model: sonnet\n  prompt: \"\"\"Diagnose the error.\n  1. Examine code paths\n  2. Check logs and state\n  3. Form hypothesis\n  4. BEFORE OUTPUTTING: Verify your evidence supports your conclusion.\n\n  Output only if confident. If uncertain, state what\'s missing.\"\"\"\n\n# Slower: Separate verifier agent\nlet diagnosis = session: researcher\n  prompt: \"Investigate the error\"\nlet verification = session: verifier\n  prompt: \"Verify this diagnosis\"  # Extra round-trip\n  context: diagnosis\n```\n\nUse a separate verifier when you need genuine adversarial review (different perspective), but for self-consistency checks, bake verification into the prompt.\n\n#### iterative-refinement\n\nUse feedback loops to progressively improve outputs. Each iteration builds on the previous.\n\n```prose\nlet draft = session \"Create initial draft\"\n\nloop until **draft meets quality bar** (max: 5):\n  let critique = session \"Critically evaluate this draft\"\n    context: draft\n  draft = session \"Improve draft based on critique\"\n    context: [draft, critique]\n\nsession \"Finalize and publish\"\n  context: draft\n```\n\n#### multi-perspective-review\n\nGather diverse viewpoints before synthesis. Different lenses catch different issues.\n\n```prose\nparallel:\n  user_perspective = session \"Evaluate from end-user viewpoint\"\n  tech_perspective = session \"Evaluate from engineering viewpoint\"\n  business_perspective = session \"Evaluate from business viewpoint\"\n\nsession \"Synthesize feedback and prioritize improvements\"\n  context: { user_perspective, tech_perspective, business_perspective }\n```\n\n#### adversarial-validation\n\nUse one agent to challenge another\'s work. Adversarial pressure improves robustness.\n\n```prose\nlet proposal = session \"Generate proposal\"\n\nlet critique = session \"Find flaws and weaknesses in this proposal\"\n  context: proposal\n\nlet defense = session \"Address each critique with evidence or revisions\"\n  context: [proposal, critique]\n\nsession \"Produce final proposal incorporating valid critiques\"\n  context: [proposal, critique, defense]\n```\n\n#### consensus-building\n\nFor critical decisions, require agreement between independent evaluators.\n\n```prose\nparallel:\n  eval1 = session \"Independently evaluate the solution\"\n  eval2 = session \"Independently evaluate the solution\"\n  eval3 = session \"Independently evaluate the solution\"\n\nloop until **evaluators agree** (max: 3):\n  session \"Identify points of disagreement\"\n    context: { eval1, eval2, eval3 }\n  parallel:\n    eval1 = session \"Reconsider position given other perspectives\"\n      context: { eval1, eval2, eval3 }\n    eval2 = session \"Reconsider position given other perspectives\"\n      context: { eval1, eval2, eval3 }\n    eval3 = session \"Reconsider position given other perspectives\"\n      context: { eval1, eval2, eval3 }\n\nsession \"Document consensus decision\"\n  context: { eval1, eval2, eval3 }\n```\n\n---\n\n## Maintainability Patterns\n\n#### descriptive-agent-names\n\nName agents for their role, not their implementation. Names should convey purpose.\n\n```prose\n# Good: Role-based naming\nagent code-reviewer:\nagent technical-writer:\nagent data-analyst:\n\n# Bad: Implementation-based naming\nagent opus-agent:\nagent session-1-handler:\nagent helper:\n```\n\n#### prompt-as-contract\n\nWrite prompts that specify expected inputs and outputs. Clear contracts prevent misunderstandings.\n\n```prose\nagent json-extractor:\n  model: haiku\n  prompt: \"\"\"\n    Extract structured data from text.\n\n    Input: Unstructured text containing entity information\n    Output: JSON object with fields: name, date, amount, status\n\n    If a field cannot be determined, use null.\n    Never invent information not present in the input.\n  \"\"\"\n```\n\n#### separation-of-concerns\n\nEach session should do one thing well. Combine simple sessions rather than creating complex ones.\n\n```prose\n# Good: Single responsibility per session\nlet data = session \"Fetch and validate input data\"\nlet analysis = session \"Analyze data for patterns\"\n  context: data\nlet recommendations = session \"Generate recommendations from analysis\"\n  context: analysis\nsession \"Format recommendations as report\"\n  context: recommendations\n\n# Bad: God session\nsession \"Fetch data, analyze it, generate recommendations, and format a report\"\n```\n\n#### explicit-context-flow\n\nMake data flow visible through explicit context passing. Avoid relying on implicit conversation history.\n\n```prose\n# Good: Explicit flow\nlet step1 = session \"First step\"\nlet step2 = session \"Second step\"\n  context: step1\nlet step3 = session \"Third step\"\n  context: [step1, step2]\n\n# Bad: Implicit flow (relies on conversation state)\nsession \"First step\"\nsession \"Second step using previous results\"\nsession \"Third step using all previous\"\n```\n\n---\n\n## Performance Patterns\n\n#### lazy-evaluation\n\nDefer expensive operations until their results are needed. Don\'t compute what might not be used.\n\n```prose\nsession \"Assess situation\"\n\nif **detailed analysis needed**:\n  # Expensive operations only when necessary\n  parallel:\n    deep_analysis = session \"Perform deep analysis\"\n      model: opus\n    historical = session \"Gather historical comparisons\"\n  session \"Comprehensive report\"\n    context: { deep_analysis, historical }\nelse:\n  session \"Quick summary\"\n    model: haiku\n```\n\n#### progressive-disclosure\n\nStart with fast, cheap operations. Escalate to expensive ones only when needed.\n\n```prose\n# Tier 1: Fast screening (haiku)\nlet initial = session \"Quick assessment\"\n  model: haiku\n\nif **needs deeper review**:\n  # Tier 2: Moderate analysis (sonnet)\n  let detailed = session \"Detailed analysis\"\n    model: sonnet\n    context: initial\n\n  if **needs expert review**:\n    # Tier 3: Deep reasoning (opus)\n    session \"Expert-level analysis\"\n      model: opus\n      context: [initial, detailed]\n```\n\n#### work-stealing\n\nUse `parallel (\"any\", count: N)` to get results as fast as possible from a pool of workers.\n\n```prose\n# Get 3 good ideas as fast as possible from 5 parallel attempts\nparallel (\"any\", count: 3, on-fail: \"ignore\"):\n  session \"Generate creative solution approach 1\"\n  session \"Generate creative solution approach 2\"\n  session \"Generate creative solution approach 3\"\n  session \"Generate creative solution approach 4\"\n  session \"Generate creative solution approach 5\"\n\nsession \"Select best from the first 3 completed\"\n```\n\n---\n\n## Composition Patterns\n\n#### workflow-template\n\nCreate blocks that encode entire workflow patterns. Instantiate with different parameters.\n\n```prose\nblock research-report(topic, depth):\n  let research = session \"Research {topic} at {depth} level\"\n  let analysis = session \"Analyze findings about {topic}\"\n    context: research\n  let report = session \"Write {depth}-level report on {topic}\"\n    context: [research, analysis]\n\n# Instantiate for different needs\ndo research-report(\"market trends\", \"executive\")\ndo research-report(\"technical architecture\", \"detailed\")\ndo research-report(\"competitive landscape\", \"comprehensive\")\n```\n\n#### middleware-pattern\n\nWrap sessions with cross-cutting concerns like logging, timing, or validation.\n\n```prose\nblock with-validation(task, validator):\n  let result = session \"{task}\"\n  let valid = session \"{validator}\"\n    context: result\n  if **validation failed**:\n    throw \"Validation failed for: {task}\"\n\ndo with-validation(\"Generate SQL query\", \"Check SQL for injection vulnerabilities\")\ndo with-validation(\"Generate config file\", \"Validate config syntax\")\n```\n\n#### circuit-breaker\n\nAfter repeated failures, stop trying and fail fast. Prevents cascading failures.\n\n```prose\nlet failures = 0\nlet max_failures = 3\n\nloop while **service needed and failures < max_failures** (max: 10):\n  try:\n    session \"Call external service\"\n    # Reset on success\n    failures = 0\n  catch:\n    failures = failures + 1\n    if **failures >= max_failures**:\n      session \"Circuit open - using fallback\"\n      throw \"Service unavailable\"\n```\n\n---\n\n## Observability Patterns\n\n#### checkpoint-narration\n\nFor long workflows, emit progress markers. Helps with debugging and monitoring.\n\n```prose\nsession \"Phase 1: Data Collection\"\n# ... collection work ...\n\nsession \"Phase 2: Analysis\"\n# ... analysis work ...\n\nsession \"Phase 3: Report Generation\"\n# ... report work ...\n\nsession \"Phase 4: Quality Assurance\"\n# ... QA work ...\n```\n\n#### structured-output-contracts\n\nRequest structured outputs that can be reliably parsed and validated.\n\n```prose\nagent structured-reviewer:\n  model: sonnet\n  prompt: \"\"\"\n    Always respond with this exact JSON structure:\n    {\n      \"verdict\": \"pass\" | \"fail\" | \"needs_review\",\n      \"issues\": [{\"severity\": \"high\"|\"medium\"|\"low\", \"description\": \"...\"}],\n      \"suggestions\": [\"...\"]\n    }\n  \"\"\"\n\nlet review = session: structured-reviewer\n  prompt: \"Review this code for security issues\"\n```\n\n---\n\n## Summary\n\nThe most effective OpenProse programs combine these patterns:\n\n1. **Structure**: Parallelize independent work, use blocks for reuse\n2. **Robustness**: Bound loops, handle errors, retry transient failures\n3. **Efficiency**: Tier models, minimize context, terminate early\n4. **Quality**: Iterate, get multiple perspectives, validate adversarially\n5. **Maintainability**: Name clearly, separate concerns, make flow explicit\n\nChoose patterns based on your specific constraints. A quick prototype prioritizes speed over robustness. A production workflow prioritizes reliability over cost. A research exploration prioritizes thoroughness over efficiency.\n";