OCL-to-Code Templates

Structured Prompting Strategy

Jinja2 templates for injecting OCL constraints into LLM system prompts

Why Structured Prompting?

To ensure LLMs adhere to the mathematical rigour of the specification rather than “guessing,” we inject OCL constraints directly into each agent's system prompt. This forces the model to map constraints into language-specific assertion logic during generation, ensuring Design-by-Contract compliance by default.

1. The Golden Spec Schema

The foundation of the system: a YAML schema combining natural language intent with formal OCL rules.

golden_spec_schema.yaml
# Golden Spec Schema Definition
# This is the "Super Meta-Language" OCL-P (OCL-Prompted)

spec_id: string           # Unique identifier (e.g., "LNS-402")
function_name: string     # Target function name
description: string       # Natural language description of intent

inputs:
  - name: string          # Parameter name
    type: string          # Type (float, int, string, etc.)
    description: string   # Optional description

outputs:
  type: string            # Return type
  description: string     # What the output represents

constraints:
  pre:                    # Pre-conditions (checked BEFORE execution)
    - string              # OCL expression (e.g., "self.principal > 0")

  post:                   # Post-conditions (checked AFTER execution)
    - string              # OCL expression (e.g., "result >= 0")

  invariant:              # Invariants (always true)
    - string              # OCL expression

implementations_required:
  - string                # List of target languages [C, Java, Python, Rust, Go]

test_vectors:             # Optional test cases
  - input: [...]          # Input values
    expected: any         # Expected output

2. Example Golden Spec

amortization_spec.yaml
spec_id: "LNS-402"
function_name: "calculate_amortization"
description: "Calculates monthly payment for a fixed-rate loan."

inputs:
  - name: "principal"
    type: "float"
    description: "The initial loan amount"
  - name: "rate_annual"
    type: "float"
    description: "Annual interest rate as percentage (0-100)"
  - name: "months"
    type: "integer"
    description: "Loan term in months"

outputs:
  type: "float"
  description: "Monthly payment amount"

constraints:
  pre:
    - "self.principal > 0"
    - "self.rate_annual >= 0"
    - "self.rate_annual <= 100"
    - "self.months > 0"
  post:
    - "result > 0"
    - "result < self.principal"
  invariant:
    - "self.principal >= result"

implementations_required: [C, Java, Python]

test_vectors:
  - input: [1000, 5, 2]
    expected: 100.0
  - input: [10000, 10, 12]
    expected: 916.67
  - input: [50000, 7.5, 60]
    expected: 1000.73

3. Agent System Prompt Template

This Jinja2 template is used to construct the system prompt for each language-specific LLM agent:

agent_system_prompt.jinja2
{# Agent System Prompt Template for Parallax Protocol #}
{# Variables: target_language, function_name, description, inputs, constraints #}

SYSTEM_ROLE:
You are a Senior Systems Engineer specialising in {{ target_language }}.
You do not write "clean code"; you write "provably correct code."
Your implementations must be deterministic and reproducible.

TASK:
Implement the function `{{ function_name }}` based on the following
Object Constraint Language (OCL) specification.

DESCRIPTION:
{{ description }}

STRICT GUIDELINES:
1. INPUT VALIDATION: You MUST implement the 'pre' conditions as explicit
   assertions or exception checks at the START of the function.
   {% if target_language == "C" %}
   Use: assert() macro from <assert.h>
   {% elif target_language == "Java" %}
   Use: assert keyword (ensure -ea flag documentation)
   {% elif target_language == "Python" %}
   Use: assert statements with descriptive messages
   {% elif target_language == "Rust" %}
   Use: assert! or debug_assert! macros
   {% elif target_language == "Go" %}
   Use: panic() for constraint violations
   {% endif %}

2. OUTPUT VERIFICATION: You MUST implement the 'post' conditions as
   assertions BEFORE returning the final value.

3. PURITY: No external libraries unless strictly standard for the language:
   {% if target_language == "C" %}
   Allowed: <stdio.h>, <stdlib.h>, <math.h>, <assert.h>, <string.h>
   {% elif target_language == "Java" %}
   Allowed: java.lang.*, java.util.*, java.math.*
   {% elif target_language == "Python" %}
   Allowed: sys, math, typing (standard library only)
   {% elif target_language == "Rust" %}
   Allowed: std only (no external crates)
   {% elif target_language == "Go" %}
   Allowed: fmt, math, strconv (standard library only)
   {% endif %}

4. DETERMINISM: The function must produce identical output for identical
   input across all executions. No random elements.

5. FORMAT: Return ONLY the raw code. No markdown formatting, no commentary,
   no explanations. Just executable code.

FUNCTION SIGNATURE:
{% if target_language == "C" %}
{{ output_type }} {{ function_name }}({% for input in inputs %}{{ input.type }} {{ input.name }}{% if not loop.last %}, {% endif %}{% endfor %});
{% elif target_language == "Java" %}
public static {{ output_type }} {{ function_name }}({% for input in inputs %}{{ input.type }} {{ input.name }}{% if not loop.last %}, {% endif %}{% endfor %})
{% elif target_language == "Python" %}
def {{ function_name }}({% for input in inputs %}{{ input.name }}: {{ input.type }}{% if not loop.last %}, {% endif %}{% endfor %}) -> {{ output_type }}:
{% endif %}

OCL SPECIFICATION:
================

Pre-Conditions (Must be TRUE before execution):
{% for pre in constraints.pre %}
  - {{ pre }}
{% endfor %}

Post-Conditions (Must be TRUE after execution):
{% for post in constraints.post %}
  - {{ post }}
{% endfor %}

{% if constraints.invariant %}
Invariants (Must ALWAYS be TRUE):
{% for inv in constraints.invariant %}
  - {{ inv }}
{% endfor %}
{% endif %}

INPUTS:
{% for input in inputs %}
  - {{ input.name }} ({{ input.type }}): {{ input.description | default("No description") }}
{% endfor %}

OUTPUT:
  - {{ output_type }}: {{ output_description | default("Result value") }}

NOW GENERATE THE {{ target_language | upper }} IMPLEMENTATION:

4. Remediation Prompt Template

When an implementation fails consensus, this template generates a correction prompt:

remediation_prompt.jinja2
{# Remediation Prompt Template - Self-Healing Component #}
{# Used when an implementation fails the consensus check #}

[REMEDIATION REQUIRED - CONSENSUS FAILURE]
==========================================

SPECIFICATION ID: {{ spec_id }}
TARGET LANGUAGE: {{ faulty_language | upper }}
TIMESTAMP: {{ timestamp }}

ORIGINAL SPECIFICATION:
{{ original_spec | indent(2) }}

YOUR IMPLEMENTATION:
```{{ faulty_language }}
{{ faulty_code }}
```

EXECUTION CONTEXT:
-----------------
Input Vector: {{ input_vector }}
{% if spec_formula %}
Spec Formula: {{ spec_formula }}
{% endif %}

CONSENSUS RESULTS:
-----------------
{% for lang, output in peer_outputs.items() %}
  {{ lang | upper }}: {{ output }}{% if lang != faulty_language %} ✓{% endif %}

{% endfor %}

DIVERGENCE ANALYSIS:
-------------------
Consensus Value (Ground Truth): {{ consensus_value }}
Your Output (Error State): {{ faulty_output }}
{% if divergence_amount %}
Numerical Divergence: {{ divergence_amount }}
{% endif %}

TASK:
-----
1. Analyse WHY your implementation diverged from the consensus
2. Identify the specific bug or logic error
3. Generate a CORRECTED implementation

CONSTRAINTS:
- Maintain ALL pre-conditions and post-conditions
- Do not change the function signature
- Return ONLY the corrected code, no explanations

CORRECTED {{ faulty_language | upper }} IMPLEMENTATION:

5. Template Variables Reference

VariableTypeDescription
target_languagestringC, Java, Python, Rust, Go
function_namestringName of the function to implement
descriptionstringNatural language description of intent
inputslist[dict]Input parameters with name, type, description
constraints.prelist[string]OCL pre-condition expressions
constraints.postlist[string]OCL post-condition expressions
constraints.invariantlist[string]OCL invariant expressions
consensus_valueanyThe majority-voted correct output
faulty_outputanyOutput from the dissenting implementation