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.
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.
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:
id: Unique playbook identifiername: Human-readable titleversion: Semantic versionworkflow_id: Parent workflow this belongs topattern: Classification (linear_recursion, transitive_closure, etc.)target: Output format (bash, csharp, prolog, etc.)difficulty: beginner, intermediate, advancedestimated_time: Expected execution timeprerequisites: Required tools/setupA 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:
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.
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.
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:
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
> }
> \```
Playbooks leverage GitHub-style callouts (admonitions) for structured information.
[!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:
language field is mandatory and specifies the programming language or format of the output.purpose field is mandatory and provides a human-readable description of what the output represents. <language_name> ... ) serves as a template or placeholder for the agent’s generated output.[!output] callouts (including metadata and code block) should be kept concise, ideally representing less than 10% of the total playbook content. This ensures playbooks remain focused on strategy and guidance rather than becoming large output containers.[!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
> ```
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).
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
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.
Playbooks leverage GitHub-style callouts (admonitions) for structured information.
[!output] - Expected Output CalloutSpecifies 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:
language: Programming language or formatpurpose: What this output representsOptional fields:
format: Type of output (executable, data, config, etc.)location: Where the output should be savedexpected_size: Approximate size of outputGuidelines:
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"
> }
> ```
[!example-record] - Example Library ReferenceTags 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:
id: Unique identifier (use timestamp format: YYYYMMDD-name)name: Namespaced name (e.g., unifyweaver.pattern.specific_example)Optional fields:
pattern: Classification tag (linear_recursion, transitive_closure, etc.)parent_example: ID of parent in hierarchychild_examples: List of dependent/related examplesrelated: Cross-references to similar examplesdifficulty: Complexity leveltags: Additional classification tagsExamples:
> [!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.
> ```
[!note] - Additional InformationProvide 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.
[!warning] - Cautionary InformationHighlight 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.
[!tip] - Best PracticesShare optimization tips or best practices.
Structure:
> [!tip]
> Tip content
Usage:
> [!tip]
> Run `test_runner.sh` after every compilation to catch regressions early.
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:
#section-name)When a playbook requires the agent to generate Prolog code for UnifyWeaver compilation:
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
\```
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
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
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
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>
[!output] blocks <10% of total contentBefore publishing a playbook, verify:
[!output] callouts