UnifyWeaver

Playbook Format Specification

This document details the standardized format for creating playbooks, which serve as detailed execution guides for LLM agents within UnifyWeaver workflows. Playbooks are Markdown-based and incorporate specific callouts and structures to facilitate clear communication and automated parsing by the agent.

What is a Playbook?

A playbook is a specific, detailed plan for accomplishing a particular task within the UnifyWeaver framework. Unlike workflows (which define high-level strategies), playbooks provide:

Think of a playbook as a detailed recipe that an AI agent can follow to complete a task reliably and consistently.

Core Structure

A well-designed playbook consists of the following sections:

YAML frontmatter for metadata and classification.

---
id: playbook-factorial-compile-v1
name: "Factorial Compilation Playbook"
version: 1.0
workflow_id: compile-and-test
pattern: linear_recursion
target: bash
difficulty: beginner
estimated_time: 5_minutes
prerequisites: [swipl, unifyweaver_installed]
---

Common fields:

2. Goal/Objective

A clear, concise statement (1-2 sentences) of what the playbook achieves.

## Goal

Compile a factorial predicate from Prolog to optimized Bash, generate a test runner, and verify the compiled script produces correct results for factorial(0) through factorial(10).

Guidelines:

3. Context

Background information, assumptions, and prerequisites.

## Context

This playbook demonstrates linear recursion compilation - one of the most common and straightforward patterns in UnifyWeaver. The factorial function has:
- A clear base case (0! = 1)
- A single recursive call with decremented argument
- Simple arithmetic operations

**Assumptions**:
- UnifyWeaver is installed at `$UNIFYWEAVER_HOME`
- SWI-Prolog is available in PATH
- You have write access to `/tmp/` and `education/output/`

**Background**:
Linear recursion is automatically optimized by UnifyWeaver's compiler to use tail recursion and memoization where appropriate.

4. Strategies (When Multiple Approaches Exist)

Description of different approaches with economic trade-offs.

## Strategies

### Strategy A: Direct Compilation
- **Cost**: Low (single compilation step)
- **Speed**: Fast (<5 seconds)
- **Quality**: Standard (no special optimizations)
- **When to use**: Quick prototyping, simple predicates

### Strategy B: Optimized Compilation with Memoization
- **Cost**: Medium (requires analysis step)
- **Speed**: Slower to compile (~15 seconds), faster at runtime
- **Quality**: High (optimized for repeated calls)
- **When to use**: Production use, performance-critical code

**Heuristic**: Use Strategy A for development/testing, Strategy B for deployment.

Note: If only one approach exists, omit this section.

5. Tool Usage

Step-by-step instructions with specific commands.

## Execution Steps

### Step 1: Create Prolog Source

Create the factorial predicate in `/tmp/factorial.pl`:

\```bash
cat > /tmp/factorial.pl <<'EOF'
% factorial(+N, -F) - F is the factorial of N
factorial(0, 1).
factorial(N, F) :-
    N > 0,
    N1 is N - 1,
    factorial(N1, F1),
    F is N * F1.
EOF
\```

**Verification**: File should exist and contain 5 lines
\```bash
test -f /tmp/factorial.pl && wc -l /tmp/factorial.pl
# Expected: 5 /tmp/factorial.pl
\```

Guidelines:

6. Output Specifications

Use the [!output] callout to define expected outputs.

## Expected Outputs

> [!output]
> language: bash
> purpose: Compiled factorial function
> format: executable
> location: education/output/advanced/factorial.sh
>
> \```bash
> # Generated by UnifyWeaver
> # Pattern: Linear Recursion
>
> factorial() {
>     local N=$1
>     if [ "$N" -eq 0 ]; then
>         echo 1
>     else
>         # ... recursive logic ...
>     fi
> }
> \```

Callout Types

Playbooks leverage GitHub-style callouts (admonitions) for structured information.

1. [!output] Callout (New)

This callout specifies the expected output from the agent’s execution. It includes metadata to provide context about the output.

Structure:

> [!output]
> language: <language_name> (e.g., prolog, bash, markdown, json, text)
> purpose: <brief_description_of_the_output>
> # Optional additional metadata
> format: <e.g., executable, data, documentation, configuration>
> expected_size: <e.g., small, medium, large>
>
> ```<language_name>
> # The generated output will go here.
> # This block serves as a template or placeholder for the agent's output.
> ```

Guidelines:

2. [!example-record] Callout (Existing, for reference)

Used to embed or reference examples, as seen in log_examples.md and recursion_examples.md.

Structure:

> [!example-record]
> id: <unique_id>
> name: <descriptive_name>
>
> ```<language_name>
> # Example content
> ```

Referencing Example Libraries

Playbooks can and should reference examples from the examples_library or other designated example directories. This promotes reusability and provides concrete instances for the agent.

Mechanism: Use standard Markdown links to point to relevant example files or sections within them.

For an example of an ancestor relationship in Prolog, refer to [Prolog Recursion Examples](../../examples_library/recursion_examples.md).

7. Verification and Testing

How to confirm the playbook succeeded.

## Verification

### Test the Compiled Script

Run the factorial script with known inputs:

\```bash
bash education/output/advanced/factorial.sh <<EOF
0
5
10
EOF
\```

**Expected output**:
\```
1
120
3628800
\```

### Automated Testing

Use the generated test runner:

\```bash
./education/output/advanced/test_runner.sh
\```

**Expected**: All tests PASS, exit code 0

### Success Criteria

✅ All of the following must be true:
- `factorial.sh` exists and is executable
- `factorial 0` returns `1`
- `factorial 5` returns `120`
- `factorial 10` returns `3628800`
- Test runner exits with code 0

8. Error Handling

Common problems and solutions.

## Troubleshooting

### Error: "No such file or directory: compiler_driver.pl"

**Cause**: `file_search_path` not set correctly

**Solution**:
\```bash
export UNIFYWEAVER_HOME=/path/to/UnifyWeaver
cd $UNIFYWEAVER_HOME
# Then retry
\```

### Error: "Predicate factorial/2 not found"

**Cause**: Prolog file not loaded before compilation

**Solution**: Ensure `['/tmp/factorial.pl']` appears before `compile(...)` in the swipl command.

Callout Types Reference

Playbooks leverage GitHub-style callouts (admonitions) for structured information.

1. [!output] - Expected Output Callout

Specifies the expected output from the agent’s execution.

Purpose: Define what the agent should generate or produce

Structure:

> [!output]
> language: <language_name> (e.g., prolog, bash, markdown, json, text)
> purpose: <brief_description_of_the_output>
> format: <e.g., executable, data, documentation, configuration>
> location: <path_where_output_should_be_created>
> expected_size: <e.g., small, medium, large> (optional)
>
> ```<language_name>
> # Template or example of expected output
> # This serves as a guide for the agent
> ```

Mandatory fields:

Optional fields:

Guidelines:

Examples:

> [!output]
> language: prolog
> purpose: Factorial predicate definition
> format: source_code
> location: /tmp/factorial.pl
>
> ```prolog
> factorial(0, 1).
> factorial(N, F) :- N > 0, N1 is N-1, factorial(N1, F1), F is N * F1.
> ```
> [!output]
> language: json
> purpose: Compilation configuration
> format: configuration
> expected_size: small
>
> ```json
> {
>   "predicate": "factorial/2",
>   "target": "bash",
>   "optimize": true,
>   "output_dir": "education/output/advanced"
> }
> ```

2. [!example-record] - Example Library Reference

Tags reusable examples in library files.

Purpose: Identify and classify examples for reuse and cross-referencing

Structure:

> [!example-record]
> id: <unique_id>
> name: <namespaced_name>
> pattern: <pattern_classification>
> parent_example: <parent_id> (optional)
> child_examples: [<child_id1>, <child_id2>] (optional)
> related: [<related_id1>, <related_id2>] (optional)
> difficulty: <beginner|intermediate|advanced> (optional)
> tags: [<tag1>, <tag2>] (optional)
>
> <example content>

Mandatory fields:

Optional fields:

Examples:

> [!example-record]
> id: 20251117-factorial-basic
> name: unifyweaver.recursion.factorial_basic
> pattern: linear_recursion
> difficulty: beginner
> child_examples: [unifyweaver.testing.factorial_runner]
> tags: [arithmetic, tail_recursion_candidate]
>
> Basic factorial implementation with base case and recursive step.
> ```prolog
> factorial(0, 1).
> factorial(N, F) :- N > 0, N1 is N-1, factorial(N1, F1), F is N * F1.
> ```

3. [!note] - Additional Information

Provide supplementary information, tips, or warnings.

Structure:

> [!note]
> **Title** (optional)
>
> Note content here

Usage:

> [!note]
> **Performance Tip**
>
> For factorials >20, consider using memoization to avoid redundant calculations.

4. [!warning] - Cautionary Information

Highlight potential pitfalls or important cautions.

Structure:

> [!warning]
> Warning content

Usage:

> [!warning]
> The compilation step modifies files in `education/output/`. Ensure you have backups if running in a production environment.

5. [!tip] - Best Practices

Share optimization tips or best practices.

Structure:

> [!tip]
> Tip content

Usage:

> [!tip]
> Run `test_runner.sh` after every compilation to catch regressions early.

Referencing Example Libraries

Playbooks should reference examples from examples_library rather than embedding large code blocks.

Benefits:

Mechanism: Use standard Markdown links

For a complete factorial example, see [Factorial Compilation](/UnifyWeaver/education/book-04-workflows/examples_library/compilation_examples.html#factorial-compilation) in the compilation examples library.

The ancestor relationship demonstrates transitive closure. Refer to [Prolog Recursion Examples](/UnifyWeaver/education/book-04-workflows/examples_library/recursion_examples.html#ancestor-relationship) for details.

Best practices:

Prolog Generation Guidance

When a playbook requires the agent to generate Prolog code for UnifyWeaver compilation:

Predicate Specifications

Provide clear specifications:

### Predicate: `factorial/2`

**Signature**: `factorial(+N:integer, -F:integer)`

**Semantics**:
- Computes F = N! (factorial of N)
- N must be non-negative integer
- F is the result

**Modes**:
- `factorial(+, -)`: Deterministic (single solution)
- Input N must be ground (instantiated)
- Output F will be bound to result

**Examples**:
\```prolog
?- factorial(0, F).
F = 1.

?- factorial(5, F).
F = 120.

?- factorial(-1, F).
false.  % Negative inputs should fail
\```

Structure Guidance

Show desired Prolog structures:

### Expected Structure

1. **Base case(s)**: Define terminating conditions
   \```prolog
   factorial(0, 1).
   \```

2. **Recursive case**: Define reduction step
   \```prolog
   factorial(N, F) :-
       N > 0,
       N1 is N - 1,
       factorial(N1, F1),
       F is N * F1.
   \```

3. **Guards**: Use constraints to ensure correctness
   - `N > 0`: Ensures positive input for recursive case
   - Arithmetic evaluation: Use `is/2` for computation

Compilation Instructions

Provide exact compiler_driver invocation:

### Compilation Command

Navigate to `$UNIFYWEAVER_HOME` and run:

\```bash
swipl -q -g "
    asserta(file_search_path(unifyweaver, 'src/unifyweaver')),
    ['/tmp/factorial.pl'],
    use_module(unifyweaver(core/compiler_driver)),
    compile(factorial/2, [
        output_dir('education/output/advanced'),
        target(bash),
        optimize(true)
    ], Scripts),
    format('Generated scripts: ~w~n', [Scripts]),
    halt"
\```

**Parameters**:
- `factorial/2`: Predicate to compile
- `output_dir`: Where to write generated scripts
- `target`: Output format (bash, csharp, etc.)
- `optimize`: Enable optimizations
- `Scripts`: Unifies with list of generated file paths

Output Handling

Guide the agent on what to do with compiled output:

### Post-Compilation

After successful compilation:

1. **Verify output exists**:
   \```bash
   ls -lh education/output/advanced/factorial.sh
   \```

2. **Make executable** (if needed):
   \```bash
   chmod +x education/output/advanced/factorial.sh
   \```

3. **Test manually**:
   \```bash
   echo "5" | bash education/output/advanced/factorial.sh
   # Expected: 120
   \```

4. **Generate test runner** (automated testing):
   - See [Testing Examples](/UnifyWeaver/education/book-04-workflows/examples_library/testing_examples.html)
   - Run test_runner_inference to create test suite

Complete Playbook Template

Here’s a complete template incorporating all sections:

---
id: playbook-<task>-v1
name: "<Task Name> Playbook"
version: 1.0
workflow_id: <parent-workflow>
pattern: <pattern_type>
target: <output_format>
difficulty: <beginner|intermediate|advanced>
estimated_time: <X>_minutes
prerequisites: [<tool1>, <tool2>]
---

# <Task Name> Playbook

## Goal

<Clear statement of what this playbook achieves>

## Context

<Background information, assumptions, prerequisites>

**Assumptions**:
- <Assumption 1>
- <Assumption 2>

**Background**:
<Relevant background information>

## Strategies

### Strategy A: <Approach Name>
- **Cost**: <Low|Medium|High>
- **Speed**: <Fast|Medium|Slow>
- **Quality**: <Standard|High|Optimal>
- **When to use**: <Guidance>

### Strategy B: <Alternative Approach>
- **Cost**: <Low|Medium|High>
- **Speed**: <Fast|Medium|Slow>
- **Quality**: <Standard|High|Optimal>
- **When to use**: <Guidance>

**Heuristic**: <Decision guidance>

## Execution Steps

### Step 1: <Action Name>

<Description of what this step does>

\```bash
<exact command>
\```

**Verification**:
\```bash
<verification command>
# Expected: <expected output>
\```

### Step 2: <Next Action>

<Continue with sequential steps>

## Expected Outputs

> [!output]
> language: <language>
> purpose: <description>
> format: <format_type>
> location: <file_path>
>
> \```<language>
> <template or example output>
> \```

## Verification

### Test <Aspect>

\```bash
<test command>
\```

**Expected output**:
\```
<expected result>
\```

### Success Criteria<Criterion 1><Criterion 2><Criterion 3>

## Troubleshooting

### Error: "<error message>"

**Cause**: <Why this happens>

**Solution**:
\```bash
<how to fix>
\```

## References

- [Example Library Link](examples_library/file.md#section)
- [Tool Documentation](path/to/docs)
- [Related Playbook](path/to/playbook.md)

## Notes

> [!note]
> <Additional helpful information>

> [!tip]
> <Best practice or optimization tip>

> [!warning]
> <Important caution>

Best Practices

For Playbook Authors

  1. Be explicit: Provide exact commands, not vague descriptions
  2. Verify everything: Include verification after each critical step
  3. Reference examples: Link to example libraries instead of embedding code
  4. Show, don’t tell: Include expected outputs, not just descriptions
  5. Handle errors: Anticipate common failures and provide solutions
  6. Keep it focused: One playbook = one specific task
  7. Use callouts appropriately: Structure information for parsing
  8. Maintain metadata: Fill in frontmatter completely
  9. Test thoroughly: Execute the playbook before publishing
  10. Update regularly: Keep commands and outputs current

For AI Agents

  1. Follow sequentially: Execute steps in order
  2. Verify between steps: Run verification commands
  3. Check success criteria: Confirm all criteria met before declaring success
  4. Handle errors gracefully: Use troubleshooting section when failures occur
  5. Extract examples dynamically: Use example extraction tools when needed
  6. Report progress: Log what you’re doing at each step
  7. Respect constraints: Keep [!output] blocks <10% of total content
  8. Maintain context: Remember the goal throughout execution

Playbook Quality Checklist

Before publishing a playbook, verify:

Version History