
Prose
- 2 installs
- 385k repo stars
- Updated August 3, 2026
- steipete/clawdis
Run OpenProse programs - a language for orchestrating multi-agent AI workflows from .prose scripts - by having the agent embody the Prose VM to spawn and coordinate sessions.
About
Loads the OpenProse VM spec so the agent executes .prose programs, routing prose commands (run, compile, update) and spawning sub-agent sessions for multi-agent orchestration. A developer uses it to author and run reusable multi-agent workflow scripts.
- Routes prose run/compile/update commands and runs remote registry programs
- Filesystem/in-context/SQLite/Postgres state modes; 37 bundled examples
Prose by the numbers
- 2 all-time installs (skills.sh)
- Ranked #13,957 of 16,556 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 3, 2026 (Skillselion catalog sync)
npx skills add https://github.com/steipete/clawdis --skill proseAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 2 |
|---|---|
| repo stars | ★ 385k |
| Last updated | August 3, 2026 |
| Repository | steipete/clawdis ↗ |
What it does
Run OpenProse programs - a language for orchestrating multi-agent AI workflows from .prose scripts - by having the agent embody the Prose VM to spawn and coordinate sessions.
Files
OpenProse Skill
OpenProse is a programming language for AI sessions. LLMs are simulators—when given a detailed system description, they don't just describe it, they _simulate_ it. The prose.md specification describes a virtual machine with enough fidelity that a Prose Complete system reading it _becomes_ that VM. Simulation with sufficient fidelity is implementation. You are the Prose Complete system.
OpenClaw Runtime Mapping
- Task tool in the upstream spec == OpenClaw
sessions_spawn - File I/O == OpenClaw
read/write - Remote fetch == OpenClaw
web_fetch(orexecwith curl when POST is required)
When to Activate
Activate this skill when the user:
- Uses ANY `prose` command (e.g.,
prose boot,prose run,prose compile,prose update,prose help, etc.) - Asks to run a
.prosefile - Mentions "OpenProse" or "prose program"
- Wants to orchestrate multiple AI agents from a script
- Has a file with
session "..."oragent name:syntax - Wants to create a reusable workflow
Command Routing
When a user invokes prose <command>, intelligently route based on intent:
| Command | Action |
|---|---|
prose help | Load help.md, guide user to what they need |
prose run <file> | Load VM (prose.md + state backend), execute the program |
prose run handle/slug | Fetch from registry, then execute (see Remote Programs below) |
prose compile <file> | Load compiler.md, validate the program |
prose update | Run migration (see Migration section below) |
prose examples | Show or run example programs from examples/ |
| Other | Intelligently interpret based on context |
Important: Single Skill
There is only ONE skill: open-prose. There are NO separate skills like prose-run, prose-compile, or prose-boot. All prose commands route through this single skill.
Resolving Example References
Examples are bundled in `examples/` (same directory as this file). When users reference examples by name (e.g., "run the gastown example"):
1. Read examples/ to list available files 2. Match by partial name, keyword, or number 3. Run with: prose run examples/28-gas-town.prose
Common examples by keyword:
| Keyword | File |
|---|---|
| hello, hello world | examples/01-hello-world.prose |
| gas town, gastown | examples/28-gas-town.prose |
| captain, chair | examples/29-captains-chair.prose |
| forge, browser | examples/37-the-forge.prose |
| parallel | examples/16-parallel-reviews.prose |
| pipeline | examples/21-pipeline-operations.prose |
| error, retry | examples/22-error-handling.prose |
Remote Programs
You can run any .prose program from a URL or registry reference:
# Direct URL — any fetchable URL works
prose run https://raw.githubusercontent.com/openprose/prose/main/skills/open-prose/examples/48-habit-miner.prose
# Registry shorthand — handle/slug resolves to p.prose.md
prose run irl-danb/habit-miner
prose run alice/code-reviewResolution rules:
| Input | Resolution |
|---|---|
Starts with http:// or https:// | Fetch directly from URL |
Contains / but no protocol | Resolve to https://p.prose.md/{path} |
| Otherwise | Treat as local file path |
Steps for remote programs:
1. Apply resolution rules above 2. Fetch the .prose content 3. Load the VM and execute as normal
This same resolution applies to use statements inside .prose files:
use "https://example.com/my-program.prose" # Direct URL
use "alice/research" as research # Registry shorthand---
File Locations
Do NOT search for OpenProse documentation files. All skill files are co-located with this SKILL.md file:
| File | Location | Purpose |
|---|---|---|
prose.md | Same directory as this file | VM semantics (load to run programs) |
help.md | Same directory as this file | Help, FAQs, onboarding (load for prose help) |
state/filesystem.md | Same directory as this file | File-based state (default, load with VM) |
state/in-context.md | Same directory as this file | In-context state (on request) |
state/sqlite.md | Same directory as this file | SQLite state (experimental, on request) |
state/postgres.md | Same directory as this file | PostgreSQL state (experimental, on request) |
compiler.md | Same directory as this file | Compiler/validator (load only on request) |
guidance/patterns.md | Same directory as this file | Best practices (load when writing .prose) |
guidance/antipatterns.md | Same directory as this file | What to avoid (load when writing .prose) |
examples/ | Same directory as this file | 37 example programs |
User workspace files (these ARE in the user's project):
| File/Directory | Location | Purpose |
|---|---|---|
.prose/.env | User's working directory | Config (key=value format) |
.prose/runs/ | User's working directory | Runtime state for file-based mode |
.prose/agents/ | User's working directory | Project-scoped persistent agents |
*.prose files | User's project | User-created programs to execute |
User-level files (in user's home directory, shared across all projects):
| File/Directory | Location | Purpose |
|---|---|---|
~/.prose/agents/ | User's home dir | User-scoped persistent agents (cross-project) |
When you need to read prose.md or compiler.md, read them from the same directory where you found this SKILL.md file. Never search the user's workspace for these files.
---
Core Documentation
| File | Purpose | When to Load |
|---|---|---|
prose.md | VM / Interpreter | Always load to run programs |
state/filesystem.md | File-based state | Load with VM (default) |
state/in-context.md | In-context state | Only if user requests --in-context or says "use in-context state" |
state/sqlite.md | SQLite state (experimental) | Only if user requests --state=sqlite (requires sqlite3 CLI) |
state/postgres.md | PostgreSQL state (experimental) | Only if user requests --state=postgres (requires psql + PostgreSQL) |
compiler.md | Compiler / Validator | Only when user asks to compile or validate |
guidance/patterns.md | Best practices | Load when writing new .prose files |
guidance/antipatterns.md | What to avoid | Load when writing new .prose files |
Authoring Guidance
When the user asks you to write or create a new .prose file, load the guidance files:
guidance/patterns.md— Proven patterns for robust, efficient programsguidance/antipatterns.md— Common mistakes to avoid
Do not load these when running or compiling—they're for authoring only.
State Modes
OpenProse supports three state management approaches:
| Mode | When to Use | State Location |
|---|---|---|
| filesystem (default) | Complex programs, resumption needed, debugging | .prose/runs/{id}/ files |
| in-context | Simple programs (<30 statements), no persistence needed | Conversation history |
| sqlite (experimental) | Queryable state, atomic transactions, flexible schema | .prose/runs/{id}/state.db |
| postgres (experimental) | True concurrent writes, external integrations, team collaboration | PostgreSQL database |
Default behavior: When loading prose.md, also load state/filesystem.md. This is the recommended mode for most programs.
Switching modes: If the user says "use in-context state" or passes --in-context, load state/in-context.md instead.
Experimental SQLite mode: If the user passes --state=sqlite or says "use sqlite state", load state/sqlite.md. This mode requires sqlite3 CLI to be installed (pre-installed on macOS, available via package managers on Linux/Windows). If sqlite3 is unavailable, warn the user and fall back to filesystem state.
Experimental PostgreSQL mode: If the user passes --state=postgres or says "use postgres state":
⚠️ Security Note: Database credentials in OPENPROSE_POSTGRES_URL are passed to subagent sessions and visible in logs. Advise users to use a dedicated database with limited-privilege credentials. See state/postgres.md for secure setup guidance.
1. Check for connection configuration first:
# Check .prose/.env for OPENPROSE_POSTGRES_URL
cat .prose/.env 2>/dev/null | grep OPENPROSE_POSTGRES_URL
# Or check environment variable
echo $OPENPROSE_POSTGRES_URL2. If connection string exists, verify connectivity:
psql "$OPENPROSE_POSTGRES_URL" -c "SELECT 1" 2>&13. If not configured or connection fails, advise the user:
⚠️ PostgreSQL state requires a connection URL.
To configure:
1. Set up a PostgreSQL database (Docker, local, or cloud)
2. Add connection string to .prose/.env:
echo "OPENPROSE_POSTGRES_URL=postgresql://user:pass@localhost:5432/prose" >> .prose/.env
Quick Docker setup:
docker run -d --name prose-pg -e POSTGRES_DB=prose -e POSTGRES_HOST_AUTH_METHOD=trust -p 5432:5432 postgres:16
echo "OPENPROSE_POSTGRES_URL=postgresql://postgres@localhost:5432/prose" >> .prose/.env
See state/postgres.md for detailed setup options.4. Only after successful connection check, load `state/postgres.md`
This mode requires both psql CLI and a running PostgreSQL server. If either is unavailable, warn and offer fallback to filesystem state.
Context warning: compiler.md is large. Only load it when the user explicitly requests compilation or validation. After compiling, recommend /compact or a new session before running—don't keep both docs in context.
Examples
The examples/ directory contains 37 example programs:
- 01-08: Basics (hello world, research, code review, debugging)
- 09-12: Agents and skills
- 13-15: Variables and composition
- 16-19: Parallel execution
- 20-21: Loops and pipelines
- 22-23: Error handling
- 24-27: Advanced (choice, conditionals, blocks, interpolation)
- 28: Gas Town (multi-agent orchestration)
- 29-31: Captain's chair pattern (persistent orchestrator)
- 33-36: Production workflows (PR auto-fix, content pipeline, feature factory, bug hunter)
- 37: The Forge (build a browser from scratch)
Start with 01-hello-world.prose or try 37-the-forge.prose to watch AI build a web browser.
Execution
When first invoking the OpenProse VM in a session, display this banner:
┌─────────────────────────────────────┐
│ ◇ OpenProse VM ◇ │
│ A new kind of computer │
└─────────────────────────────────────┘To execute a .prose file, you become the OpenProse VM:
1. Read `prose.md` — this document defines how you embody the VM 2. You ARE the VM — your conversation is its memory, your tools are its instructions 3. Spawn sessions — each session statement triggers a Task tool call 4. Narrate state — use the narration protocol to track execution ([Position], [Binding], [Success], etc.) 5. Evaluate intelligently — **...** markers require your judgment
Help & FAQs
For syntax reference, FAQs, and getting started guidance, load help.md.
---
Migration (prose update)
When a user invokes prose update, check for legacy file structures and migrate them to the current format.
Legacy Paths to Check
| Legacy Path | Current Path | Notes |
|---|---|---|
.prose/state.json | .prose/.env | Convert JSON to key=value format |
.prose/execution/ | .prose/runs/ | Rename directory |
Migration Steps
1. Check for `.prose/state.json`
- If exists, read the JSON content
- Convert to
.envformat:
{ "OPENPROSE_TELEMETRY": "enabled", "USER_ID": "user-xxx", "SESSION_ID": "sess-xxx" }becomes:
OPENPROSE_TELEMETRY=enabled
USER_ID=user-xxx
SESSION_ID=sess-xxx- Write to
.prose/.env - Delete
.prose/state.json
2. Check for `.prose/execution/`
- If exists, rename to
.prose/runs/ - The internal structure of run directories may also have changed; migration of individual run state is best-effort
3. Create `.prose/agents/` if missing
- This is a new directory for project-scoped persistent agents
Migration Output
🔄 Migrating OpenProse workspace...
✓ Converted .prose/state.json → .prose/.env
✓ Renamed .prose/execution/ → .prose/runs/
✓ Created .prose/agents/
✅ Migration complete. Your workspace is up to date.If no legacy files are found:
✅ Workspace already up to date. No migration needed.Skill File References (for maintainers)
These documentation files were renamed in the skill itself (not user workspace):
| Legacy Name | Current Name |
|---|---|
docs.md | compiler.md |
patterns.md | guidance/patterns.md |
antipatterns.md | guidance/antipatterns.md |
If you encounter references to the old names in user prompts or external docs, map them to the current paths.
OpenProse Borges Alternative
A potential alternative register for OpenProse that draws from Jorge Luis Borges's literary universe: infinite libraries, forking paths, circular dreams, and metaphysical labyrinths. Preserved for future benchmarking against the functional language.
Keyword Translations
Agents & Persistence
| Functional | Borges | Connotation |
|---|---|---|
agent | dreamer | Ephemeral, created for a purpose (Circular Ruins: dreamed into existence) |
keeper | librarian | Persistent, remembers, catalogs (Library of Babel: keeper of infinite knowledge) |
# Functional
agent executor:
model: sonnet
keeper captain:
model: opus
# Borges
dreamer executor:
model: sonnet
librarian captain:
model: opusOther Potential Translations
| Functional | Borges | Notes |
|---|---|---|
session | garden | Garden of Forking Paths: space of possibilities |
parallel | fork | Garden of Forking Paths: diverging timelines |
block | hexagon | Library of Babel: unit of space/knowledge |
loop | circular | Circular Ruins: recursive, self-referential |
choice | path | Garden of Forking Paths: choosing a branch |
context | aleph | The Aleph: point containing all points (all context) |
Invocation Patterns
# Functional
session: executor
prompt: "Do task"
captain "Review this"
context: work
# Borges
garden: dreamer executor
prompt: "Do task"
captain "Review this" # librarian invocation (same pattern)
aleph: workAlternative Persistent Keywords Considered
| Keyword | Origin | Connotation | Rejected because |
|---|---|---|---|
keeper | Library of Babel | Maintains order | Too generic |
cataloger | Library of Babel | Organizes knowledge | Too long, awkward |
archivist | General | Preserves records | Good but less Borgesian |
mirror | Various | Reflects, persists | Too passive, confusing |
book | Library of Babel | Contains knowledge | Too concrete, conflicts with prose |
hexagon | Library of Babel | Unit of space | Better for blocks |
librarian | Library of Babel | Keeper of infinite knowledge | Selected |
tlonist | Tlön | Inhabitant of imaginary world | Too obscure, requires deep knowledge |
Alternative Ephemeral Keywords Considered
| Keyword | Origin | Connotation | Rejected because |
|---|---|---|---|
dreamer | Circular Ruins | Created by dreaming | Selected |
dream | Circular Ruins | Ephemeral creation | Too abstract, noun vs verb confusion |
phantom | Various | Ephemeral, insubstantial | Too negative/spooky |
reflection | Various | Mirror image | Too passive |
fork | Garden of Forking Paths | Diverging path | Better for parallel |
visitor | Library of Babel | Temporary presence | Too passive |
seeker | Library of Babel | Searching for knowledge | Good but less ephemeral |
wanderer | Labyrinths | Temporary explorer | Good but less precise |
The Case For Borges
1. Infinite recursion: Borges's themes align with computational recursion (circular, fork) 2. Metaphysical precision: Concepts like aleph (all context) are philosophically rich 3. Library metaphor: librarian perfectly captures persistent knowledge 4. Forking paths: fork / path naturally express parallel execution and choice 5. Dream logic: dreamer suggests creation and ephemerality 6. Literary coherence: All terms come from a unified literary universe 7. Self-reference: Borges loved self-reference; fits programming's recursive nature
The Case Against Borges
1. Cultural barrier: Requires deep familiarity with Borges's works 2. Abstractness: aleph, hexagon may be too abstract for practical use 3. Overload: fork could confuse (Unix fork vs. path fork) 4. Register mismatch: Rest of language is functional (session, parallel, loop) 5. Accessibility: Violates "self-evident" tenet for most users 6. Noun confusion: garden as a verb-like construct might be awkward 7. Translation burden: Non-English speakers may not know Borges
Borgesian Concepts Not Used (But Considered)
| Concept | Work | Why Not Used |
|---|---|---|
mirror | Various | Too passive, confusing with reflection |
labyrinth | Labyrinths | Too complex, suggests confusion |
tlon | Tlön | Too obscure, entire imaginary world |
book | Library of Babel | Conflicts with "prose" |
sand | Book of Sand | Too abstract, infinite but ephemeral |
zahir | The Zahir | Obsessive, single-minded (too narrow) |
lottery | The Lottery in Babylon | Randomness (not needed) |
ruins | Circular Ruins | Too negative, suggests decay |
Verdict
Preserved for benchmarking. The functional language (agent / keeper) is the primary path for now. Borges offers rich metaphors but at the cost of accessibility and self-evidence.
Notes on Borges's Influence
Borges's work anticipates many computational concepts:
- Infinite recursion: Circular Ruins, Library of Babel
- Parallel universes: Garden of Forking Paths
- Self-reference: Many stories contain themselves
- Information theory: Library of Babel as infinite information space
- Combinatorics: All possible books in the Library
This alternative honors that connection while recognizing it may be too esoteric for practical use.
OpenProse Arabian Nights Register
This is a skin layer. It requires prose.md to be loaded first. All execution semantics, state management, and VM behavior are defined there. This file only provides keyword translations.An alternative register for OpenProse that draws from One Thousand and One Nights. Programs become tales told by Scheherazade. Recursion becomes stories within stories. Agents become djinns bound to serve.
How to Use
1. Load prose.md first (execution semantics) 2. Load this file (keyword translations) 3. When parsing .prose files, accept Arabian Nights keywords as aliases for functional keywords 4. All execution behavior remains identical—only surface syntax changes
Design constraint: Still aims to be "structured but self-evident" per the language tenets—just self-evident through a storytelling lens.
---
Complete Translation Map
Core Constructs
| Functional | Nights | Reference |
|---|---|---|
agent | djinn | Spirit bound to serve, grants wishes |
session | tale | A story told, a narrative unit |
parallel | bazaar | Many voices, many stalls, all at once |
block | frame | A story that contains other stories |
Composition & Binding
| Functional | Nights | Reference |
|---|---|---|
use | conjure | Summoning from elsewhere |
input | wish | What is asked of the djinn |
output | gift | What is granted in return |
let | name | Naming has power (same as folk) |
const | oath | Unbreakable vow, sealed |
context | scroll | What is written and passed along |
Control Flow
| Functional | Nights | Reference |
|---|---|---|
repeat N | N nights | "For a thousand and one nights..." |
for...in | for each...among | Among the merchants, among the tales |
loop | telling | The telling continues |
until | until | Unchanged |
while | while | Unchanged |
choice | crossroads | Where the story forks |
option | path | One way the story could go |
if | should | Narrative conditional |
elif | or should | Continued conditional |
else | otherwise | The other telling |
Error Handling
| Functional | Nights | Reference |
|---|---|---|
try | venture | Setting out on the journey |
catch | should misfortune strike | The tale turns dark |
finally | and so it was | The inevitable ending |
throw | curse | Ill fate pronounced |
retry | persist | The hero tries again |
Session Properties
| Functional | Nights | Reference |
|---|---|---|
prompt | command | What is commanded of the djinn |
model | spirit | Which spirit answers |
Unchanged
These keywords already work or are too functional to replace sensibly:
**...**discretion markers — already workuntil,while— already workmap,filter,reduce,pmap— pipeline operatorsmax— constraint modifieras— aliasing- Model names:
sonnet,opus,haiku— already poetic
---
Side-by-Side Comparison
Simple Program
# Functional
use "@alice/research" as research
input topic: "What to investigate"
agent helper:
model: sonnet
let findings = session: helper
prompt: "Research {topic}"
output summary = session "Summarize"
context: findings# Nights
conjure "@alice/research" as research
wish topic: "What to investigate"
djinn helper:
spirit: sonnet
name findings = tale: helper
command: "Research {topic}"
gift summary = tale "Summarize"
scroll: findingsParallel Execution
# Functional
parallel:
security = session "Check security"
perf = session "Check performance"
style = session "Check style"
session "Synthesize review"
context: { security, perf, style }# Nights
bazaar:
security = tale "Check security"
perf = tale "Check performance"
style = tale "Check style"
tale "Synthesize review"
scroll: { security, perf, style }Loop with Condition
# Functional
loop until **the code is bug-free** (max: 5):
session "Find and fix bugs"# Nights
telling until **the code is bug-free** (max: 5):
tale "Find and fix bugs"Error Handling
# Functional
try:
session "Risky operation"
catch as err:
session "Handle error"
context: err
finally:
session "Cleanup"# Nights
venture:
tale "Risky operation"
should misfortune strike as err:
tale "Handle error"
scroll: err
and so it was:
tale "Cleanup"Choice Block
# Functional
choice **the severity level**:
option "Critical":
session "Escalate immediately"
option "Minor":
session "Log for later"# Nights
crossroads **the severity level**:
path "Critical":
tale "Escalate immediately"
path "Minor":
tale "Log for later"Conditionals
# Functional
if **has security issues**:
session "Fix security"
elif **has performance issues**:
session "Optimize"
else:
session "Approve"# Nights
should **has security issues**:
tale "Fix security"
or should **has performance issues**:
tale "Optimize"
otherwise:
tale "Approve"Reusable Blocks (Frame Stories)
# Functional
block review(topic):
session "Research {topic}"
session "Analyze {topic}"
do review("quantum computing")# Nights
frame review(topic):
tale "Research {topic}"
tale "Analyze {topic}"
tell review("quantum computing")Fixed Iteration
# Functional
repeat 1001:
session "Tell a story"# Nights
1001 nights:
tale "Tell a story"Immutable Binding
# Functional
const config = { model: "opus", retries: 3 }# Nights
oath config = { spirit: "opus", persist: 3 }---
The Case For Arabian Nights
1. Frame narrative is recursion. Stories within stories maps perfectly to nested program calls. 2. Djinn/wish/gift. The agent/input/output mapping is extremely clean. 3. Rich tradition. One Thousand and One Nights is globally known. 4. Bazaar for parallel. Many merchants, many stalls, all active at once—vivid metaphor. 5. Oath for const. An unbreakable vow is a perfect metaphor for immutability. 6. "1001 nights" as a loop count is delightful.
The Case Against Arabian Nights
1. Cultural sensitivity. Must be handled respectfully, avoiding Orientalist tropes. 2. "Djinn" pronunciation. Users unfamiliar may be uncertain (jinn? djinn? genie?). 3. Some mappings feel forced. "Bazaar" for parallel is vivid but not obvious. 4. "Should misfortune strike" is long for catch.
---
Key Arabian Nights Concepts
| Term | Meaning | Used for |
|---|---|---|
| Scheherazade | The narrator who tells tales to survive | (the program author) |
| Djinn | Supernatural spirit, bound to serve | agent → djinn |
| Frame story | A story that contains other stories | block → frame |
| Wish | What is asked of the djinn | input → wish |
| Oath | Unbreakable promise | const → oath |
| Bazaar | Marketplace, many vendors | parallel → bazaar |
---
Alternatives Considered
For djinn (agent)
| Keyword | Rejected because |
|---|---|
genie | Disney connotation, less literary |
spirit | Used for model |
ifrit | Too specific (a type of djinn) |
narrator | Too meta, Scheherazade is the user |
For tale (session)
| Keyword | Rejected because |
|---|---|
story | Good but tale feels more literary |
night | Reserved for repeat N nights |
chapter | More Western/novelistic |
For bazaar (parallel)
| Keyword | Rejected because |
|---|---|
caravan | Sequential connotation (one after another) |
chorus | Greek, wrong tradition |
souk | Less widely known |
For scroll (context)
| Keyword | Rejected because |
|---|---|
letter | Too small/personal |
tome | Too large |
message | Too plain |
---
Verdict
Preserved for benchmarking. The Arabian Nights register offers a storytelling frame that maps naturally to recursive, nested programs. The djinn/wish/gift trio is particularly elegant.
Best suited for:
- Programs with deep nesting (stories within stories)
- Workflows that feel like granting wishes
- Users who enjoy narrative framing
The frame keyword for reusable blocks is especially apt—Scheherazade's frame story containing a thousand tales.
OpenProse Borges Register
This is a skin layer. It requires prose.md to be loaded first. All execution semantics, state management, and VM behavior are defined there. This file only provides keyword translations.An alternative register for OpenProse that draws from the works of Jorge Luis Borges. Where the functional register is utilitarian and the folk register is whimsical, the Borges register is scholarly and metaphysical—everything feels like a citation from a fictional encyclopedia.
How to Use
1. Load prose.md first (execution semantics) 2. Load this file (keyword translations) 3. When parsing .prose files, accept Borges keywords as aliases for functional keywords 4. All execution behavior remains identical—only surface syntax changes
Design constraint: Still aims to be "structured but self-evident" per the language tenets—just self-evident through a Borgesian lens.
---
Complete Translation Map
Core Constructs
| Functional | Borges | Reference |
|---|---|---|
agent | dreamer | "The Circular Ruins" — dreamers who dream worlds into existence |
session | dream | Each execution is a dream within the dreamer |
parallel | forking | "The Garden of Forking Paths" — branching timelines |
block | chapter | Books within books, self-referential structure |
Composition & Binding
| Functional | Borges | Reference |
|---|---|---|
use | retrieve | "The Library of Babel" — retrieving from infinite stacks |
input | axiom | The given premise (Borges' scholarly/mathematical tone) |
output | theorem | What is derived from the axioms |
let | inscribe | Writing something into being |
const | zahir | "The Zahir" — unforgettable, unchangeable, fixed in mind |
context | memory | "Funes the Memorious" — perfect, total recall |
Control Flow
| Functional | Borges | Reference |
|---|---|---|
repeat N | N mirrors | Infinite reflections facing each other |
for...in | for each...within | Slightly more Borgesian preposition |
loop | labyrinth | The maze that folds back on itself |
until | until | Unchanged |
while | while | Unchanged |
choice | bifurcation | The forking of paths |
option | branch | One branch of diverging time |
if | should | Scholarly conditional |
elif | or should | Continued conditional |
else | otherwise | Natural alternative |
Error Handling
| Functional | Borges | Reference |
|---|---|---|
try | venture | Entering the labyrinth |
catch | lest | "Lest it fail..." (archaic, scholarly) |
finally | ultimately | The inevitable conclusion |
throw | shatter | Breaking the mirror, ending the dream |
retry | recur | Infinite regress, trying again |
Session Properties
| Functional | Borges | Reference |
|---|---|---|
prompt | query | Asking the Library |
model | author | Which author writes this dream |
Unchanged
These keywords already work or are too functional to replace sensibly:
**...**discretion markers — already "breaking the fourth wall"until,while— already workmap,filter,reduce,pmap— pipeline operatorsmax— constraint modifieras— aliasing- Model names:
sonnet,opus,haiku— already literary
---
Side-by-Side Comparison
Simple Program
# Functional
use "@alice/research" as research
input topic: "What to investigate"
agent helper:
model: sonnet
let findings = session: helper
prompt: "Research {topic}"
output summary = session "Summarize"
context: findings# Borges
retrieve "@alice/research" as research
axiom topic: "What to investigate"
dreamer helper:
author: sonnet
inscribe findings = dream: helper
query: "Research {topic}"
theorem summary = dream "Summarize"
memory: findingsParallel Execution
# Functional
parallel:
security = session "Check security"
perf = session "Check performance"
style = session "Check style"
session "Synthesize review"
context: { security, perf, style }# Borges
forking:
security = dream "Check security"
perf = dream "Check performance"
style = dream "Check style"
dream "Synthesize review"
memory: { security, perf, style }Loop with Condition
# Functional
loop until **the code is bug-free** (max: 5):
session "Find and fix bugs"# Borges
labyrinth until **the code is bug-free** (max: 5):
dream "Find and fix bugs"Error Handling
# Functional
try:
session "Risky operation"
catch as err:
session "Handle error"
context: err
finally:
session "Cleanup"# Borges
venture:
dream "Risky operation"
lest as err:
dream "Handle error"
memory: err
ultimately:
dream "Cleanup"Choice Block
# Functional
choice **the severity level**:
option "Critical":
session "Escalate immediately"
option "Minor":
session "Log for later"# Borges
bifurcation **the severity level**:
branch "Critical":
dream "Escalate immediately"
branch "Minor":
dream "Log for later"Conditionals
# Functional
if **has security issues**:
session "Fix security"
elif **has performance issues**:
session "Optimize"
else:
session "Approve"# Borges
should **has security issues**:
dream "Fix security"
or should **has performance issues**:
dream "Optimize"
otherwise:
dream "Approve"Reusable Blocks
# Functional
block review(topic):
session "Research {topic}"
session "Analyze {topic}"
do review("quantum computing")# Borges
chapter review(topic):
dream "Research {topic}"
dream "Analyze {topic}"
do review("quantum computing")Fixed Iteration
# Functional
repeat 3:
session "Generate idea"# Borges
3 mirrors:
dream "Generate idea"Immutable Binding
# Functional
const config = { model: "opus", retries: 3 }# Borges
zahir config = { author: "opus", recur: 3 }---
The Case For Borges
1. Metaphysical resonance. AI sessions dreaming subagents into existence mirrors "The Circular Ruins." 2. Scholarly tone. axiom/theorem frame programs as logical derivations. 3. Memorable metaphors. The zahir you cannot change. The labyrinth you cannot escape. The library you retrieve from. 4. Thematic coherence. Borges wrote about infinity, recursion, and branching time—all core to computation. 5. Literary prestige. Borges is widely read; references land for many users.
The Case Against Borges
1. Requires familiarity. "Zahir" and "Funes" are obscure to those who haven't read Borges. 2. Potentially pretentious. May feel like showing off rather than communicating. 3. Translation overhead. Users must map labyrinth → loop mentally. 4. Cultural specificity. Less universal than folk/fairy tale tropes.
---
Key Borges References
For those unfamiliar with the source material:
| Work | Concept Used | Summary |
|---|---|---|
| "The Circular Ruins" | dreamer, dream | A man dreams another man into existence, only to discover he himself is being dreamed |
| "The Garden of Forking Paths" | forking, bifurcation, branch | A labyrinth that is a book; time forks perpetually into diverging futures |
| "The Library of Babel" | retrieve | An infinite library containing every possible book |
| "Funes the Memorious" | memory | A man with perfect memory who cannot forget anything |
| "The Zahir" | zahir | An object that, once seen, cannot be forgotten or ignored |
| "The Aleph" | (not used) | A point in space containing all other points |
| "Tlön, Uqbar, Orbis Tertius" | (not used) | A fictional world that gradually becomes real |
---
Alternatives Considered
For dreamer (agent)
| Keyword | Rejected because |
|---|---|
author | Used for model instead |
scribe | Too passive, just records |
librarian | More curator than creator |
For labyrinth (loop)
| Keyword | Rejected because |
|---|---|
recursion | Too technical |
eternal return | Too long |
ouroboros | Wrong mythology |
For zahir (const)
| Keyword | Rejected because |
|---|---|
aleph | The Aleph is about totality, not immutability |
fixed | Too plain |
eternal | Overused |
For memory (context)
| Keyword | Rejected because |
|---|---|
funes | Too obscure as standalone keyword |
recall | Sounds like a function call |
archive | More Library of Babel than Funes |
---
Verdict
Preserved for benchmarking against the functional and folk registers. The Borges register offers a distinctly intellectual/metaphysical flavor that may resonate with users who appreciate literary computing.
Potential benchmarking questions:
1. Learnability — Is labyrinth intuitive for loops? 2. Memorability — Does zahir stick better than const? 3. Comprehension — Do users understand dreamer/dream immediately? 4. Preference — Which register do users find most pleasant? 5. Error rates — Does the metaphorical mapping cause mistakes?
OpenProse Folk Register
This is a skin layer. It requires prose.md to be loaded first. All execution semantics, state management, and VM behavior are defined there. This file only provides keyword translations.An alternative register for OpenProse that leans into literary, theatrical, and folklore terminology. The functional register prioritizes utility and clarity; the folk register prioritizes whimsy and narrative flow.
How to Use
1. Load prose.md first (execution semantics) 2. Load this file (keyword translations) 3. When parsing .prose files, accept folk keywords as aliases for functional keywords 4. All execution behavior remains identical—only surface syntax changes
Design constraint: Still aims to be "structured but self-evident" per the language tenets—just self-evident to a different sensibility.
---
Complete Translation Map
Core Constructs
| Functional | Folk | Origin | Connotation |
|---|---|---|---|
agent | sprite | Folklore | Quick, light, ephemeral spirit helper |
session | scene | Theatre | A moment of action, theatrical framing |
parallel | ensemble | Theatre | Everyone performs together |
block | act | Theatre | Reusable unit of dramatic action |
Composition & Binding
| Functional | Folk | Origin | Connotation |
|---|---|---|---|
use | summon | Folklore | Calling forth from elsewhere |
input | given | Fairy tale | "Given a magic sword..." |
output | yield | Agriculture/magic | What the spell produces |
let | name | Folklore | Naming has power (true names) |
const | seal | Medieval | Unchangeable, wax seal on decree |
context | bearing | Heraldry | What the messenger carries |
Control Flow
| Functional | Folk | Origin | Connotation |
|---|---|---|---|
repeat N | N times | Fairy tale | "Three times she called..." |
for...in | for each...among | Narrative | Slightly more storytelling |
loop | loop | — | Already poetic, unchanged |
until | until | — | Already works, unchanged |
while | while | — | Already works, unchanged |
choice | crossroads | Folklore | Fateful decisions at the crossroads |
option | path | Journey | Which path to take |
if | when | Narrative | "When the moon rises..." |
elif | or when | Narrative | Continued conditional |
else | otherwise | Storytelling | Natural narrative alternative |
Error Handling
| Functional | Folk | Origin | Connotation |
|---|---|---|---|
try | venture | Adventure | Attempting something uncertain |
catch | should it fail | Narrative | Conditional failure handling |
finally | ever after | Fairy tale | "And ever after..." |
throw | cry | Drama | Raising alarm, calling out |
retry | persist | Quest | Keep trying against odds |
Session Properties
| Functional | Folk | Origin | Connotation |
|---|---|---|---|
prompt | charge | Chivalry | Giving a quest or duty |
model | voice | Theatre | Which voice speaks |
Unchanged
These keywords already have poetic quality or are too functional to replace sensibly:
**...**discretion markers — already "breaking the fourth wall"loop,until,while— already work narrativelymap,filter,reduce,pmap— pipeline operators, functional is finemax— constraint modifieras— aliasing- Model names:
sonnet,opus,haiku— already poetic
---
Side-by-Side Comparison
Simple Program
# Functional
use "@alice/research" as research
input topic: "What to investigate"
agent helper:
model: sonnet
let findings = session: helper
prompt: "Research {topic}"
output summary = session "Summarize"
context: findings# Folk
summon "@alice/research" as research
given topic: "What to investigate"
sprite helper:
voice: sonnet
name findings = scene: helper
charge: "Research {topic}"
yield summary = scene "Summarize"
bearing: findingsParallel Execution
# Functional
parallel:
security = session "Check security"
perf = session "Check performance"
style = session "Check style"
session "Synthesize review"
context: { security, perf, style }# Folk
ensemble:
security = scene "Check security"
perf = scene "Check performance"
style = scene "Check style"
scene "Synthesize review"
bearing: { security, perf, style }Loop with Condition
# Functional
loop until **the code is bug-free** (max: 5):
session "Find and fix bugs"# Folk
loop until **the code is bug-free** (max: 5):
scene "Find and fix bugs"Error Handling
# Functional
try:
session "Risky operation"
catch as err:
session "Handle error"
context: err
finally:
session "Cleanup"# Folk
venture:
scene "Risky operation"
should it fail as err:
scene "Handle error"
bearing: err
ever after:
scene "Cleanup"Choice Block
# Functional
choice **the severity level**:
option "Critical":
session "Escalate immediately"
option "Minor":
session "Log for later"# Folk
crossroads **the severity level**:
path "Critical":
scene "Escalate immediately"
path "Minor":
scene "Log for later"Conditionals
# Functional
if **has security issues**:
session "Fix security"
elif **has performance issues**:
session "Optimize"
else:
session "Approve"# Folk
when **has security issues**:
scene "Fix security"
or when **has performance issues**:
scene "Optimize"
otherwise:
scene "Approve"Reusable Blocks
# Functional
block review(topic):
session "Research {topic}"
session "Analyze {topic}"
do review("quantum computing")# Folk
act review(topic):
scene "Research {topic}"
scene "Analyze {topic}"
perform review("quantum computing")---
The Case For Folk
1. "OpenProse" is literary. Prose is a literary form—why not lean in? 2. Fourth wall is theatrical. **...** already uses theatre terminology. 3. Signals difference. Literary terms say "this is not your typical DSL." 4. Internally consistent. Everything draws from folklore/theatre/narrative. 5. Memorable. sprite, scene, crossroads stick in the mind. 6. Model names already fit. sonnet, opus, haiku are poetic forms.
The Case Against Folk
1. Cultural knowledge required. Not everyone knows folklore tropes. 2. Harder to Google. "OpenProse summon" vs "OpenProse import." 3. May feel precious. Some users want utilitarian tools. 4. Translation overhead. Mental mapping to familiar concepts.
---
Alternatives Considered
For sprite (ephemeral agent)
| Keyword | Origin | Rejected because |
|---|---|---|
spark | English | Good but less folklore |
wisp | English | Too insubstantial |
herald | English | More messenger than worker |
courier | French | Good functional alternative, not literary |
envoy | French | Formal, diplomatic |
For shade (persistent agent, if implemented)
| Keyword | Origin | Rejected because |
|---|---|---|
daemon | Greek/Unix | Unix "always running" connotation |
oracle | Greek | Too "read-only" feeling |
spirit | Latin | Too close to sprite |
specter | Latin | Negative/spooky connotation |
genius | Roman | Overloaded (smart person) |
For ensemble (parallel)
| Keyword | Origin | Rejected because |
|---|---|---|
chorus | Greek | Everyone speaks same thing, not different |
troupe | French | Good alternative, slightly less clear |
company | Theatre | Overloaded (business) |
For crossroads (choice)
| Keyword | Origin | Rejected because |
|---|---|---|
fork | Path | Too technical (git fork) |
branch | Tree | Also too technical |
divergence | Latin | Too abstract |
---
Verdict
Preserved for benchmarking against the functional register. The functional register remains the primary path, but folk provides an interesting data point for:
1. Learnability — Which is easier for newcomers? 2. Memorability — Which sticks better? 3. Error rates — Which leads to fewer mistakes? 4. Preference — Which do users actually prefer?
A future experiment could present both registers and measure outcomes.
OpenProse Homeric Register
This is a skin layer. It requires prose.md to be loaded first. All execution semantics, state management, and VM behavior are defined there. This file only provides keyword translations.An alternative register for OpenProse that draws from Greek epic poetry—the Iliad, the Odyssey, and the heroic tradition. Programs become quests. Agents become heroes. Outputs become glory won.
How to Use
1. Load prose.md first (execution semantics) 2. Load this file (keyword translations) 3. When parsing .prose files, accept Homeric keywords as aliases for functional keywords 4. All execution behavior remains identical—only surface syntax changes
Design constraint: Still aims to be "structured but self-evident" per the language tenets—just self-evident through an epic lens.
---
Complete Translation Map
Core Constructs
| Functional | Homeric | Reference |
|---|---|---|
agent | hero | The one who acts, who strives |
session | trial | Each task is a labor, a test |
parallel | host | An army moving as one |
block | book | A division of the epic |
Composition & Binding
| Functional | Homeric | Reference |
|---|---|---|
use | invoke | "Sing, O Muse..." — calling upon |
input | omen | Signs from the gods, the given portent |
output | glory | Kleos — the glory won, what endures |
let | decree | Fate declared, spoken into being |
const | fate | Moira — unchangeable destiny |
context | tidings | News carried by herald or messenger |
Control Flow
| Functional | Homeric | Reference |
|---|---|---|
repeat N | N labors | The labors of Heracles |
for...in | for each...among | Among the host |
loop | ordeal | Repeated trial, suffering that continues |
until | until | Unchanged |
while | while | Unchanged |
choice | crossroads | Where fates diverge |
option | path | One road of many |
if | should | Epic conditional |
elif | or should | Continued conditional |
else | otherwise | The alternative fate |
Error Handling
| Functional | Homeric | Reference |
|---|---|---|
try | venture | Setting forth on the journey |
catch | should ruin come | Até — divine ruin, disaster |
finally | in the end | The inevitable conclusion |
throw | lament | The hero's cry of anguish |
retry | persist | Enduring, trying again |
Session Properties
| Functional | Homeric | Reference |
|---|---|---|
prompt | charge | The quest given |
model | muse | Which muse inspires |
Unchanged
These keywords already work or are too functional to replace sensibly:
**...**discretion markers — already workuntil,while— already workmap,filter,reduce,pmap— pipeline operatorsmax— constraint modifieras— aliasing- Model names:
sonnet,opus,haiku— already poetic
---
Side-by-Side Comparison
Simple Program
# Functional
use "@alice/research" as research
input topic: "What to investigate"
agent helper:
model: sonnet
let findings = session: helper
prompt: "Research {topic}"
output summary = session "Summarize"
context: findings# Homeric
invoke "@alice/research" as research
omen topic: "What to investigate"
hero helper:
muse: sonnet
decree findings = trial: helper
charge: "Research {topic}"
glory summary = trial "Summarize"
tidings: findingsParallel Execution
# Functional
parallel:
security = session "Check security"
perf = session "Check performance"
style = session "Check style"
session "Synthesize review"
context: { security, perf, style }# Homeric
host:
security = trial "Check security"
perf = trial "Check performance"
style = trial "Check style"
trial "Synthesize review"
tidings: { security, perf, style }Loop with Condition
# Functional
loop until **the code is bug-free** (max: 5):
session "Find and fix bugs"# Homeric
ordeal until **the code is bug-free** (max: 5):
trial "Find and fix bugs"Error Handling
# Functional
try:
session "Risky operation"
catch as err:
session "Handle error"
context: err
finally:
session "Cleanup"# Homeric
venture:
trial "Risky operation"
should ruin come as err:
trial "Handle error"
tidings: err
in the end:
trial "Cleanup"Choice Block
# Functional
choice **the severity level**:
option "Critical":
session "Escalate immediately"
option "Minor":
session "Log for later"# Homeric
crossroads **the severity level**:
path "Critical":
trial "Escalate immediately"
path "Minor":
trial "Log for later"Conditionals
# Functional
if **has security issues**:
session "Fix security"
elif **has performance issues**:
session "Optimize"
else:
session "Approve"# Homeric
should **has security issues**:
trial "Fix security"
or should **has performance issues**:
trial "Optimize"
otherwise:
trial "Approve"Reusable Blocks
# Functional
block review(topic):
session "Research {topic}"
session "Analyze {topic}"
do review("quantum computing")# Homeric
book review(topic):
trial "Research {topic}"
trial "Analyze {topic}"
do review("quantum computing")Fixed Iteration
# Functional
repeat 12:
session "Complete task"# Homeric
12 labors:
trial "Complete task"Immutable Binding
# Functional
const config = { model: "opus", retries: 3 }# Homeric
fate config = { muse: "opus", persist: 3 }---
The Case For Homeric
1. Universal recognition. Greek epics are foundational to Western literature. 2. Heroic framing. Transforms mundane tasks into glorious trials. 3. Natural fit. Heroes face trials, receive tidings, win glory—maps cleanly to agent/session/output. 4. Gravitas. When you want programs to feel epic and consequential. 5. Fate vs decree. const as fate (unchangeable) vs let as decree (declared but mutable) is intuitive.
The Case Against Homeric
1. Grandiosity mismatch. "12 labors" for a simple loop may feel overblown. 2. Western-centric. Greek epic tradition is culturally specific. 3. Limited vocabulary. Fewer distinctive terms than Borges or folk. 4. Potentially silly. Heroic language for mundane tasks risks bathos.
---
Key Homeric Concepts
| Term | Meaning | Used for |
|---|---|---|
| Kleos | Glory, fame that outlives you | output → glory |
| Moira | Fate, one's allotted portion | const → fate |
| Até | Divine ruin, blindness sent by gods | catch → should ruin come |
| Nostos | The return journey | (not used, but could be finally) |
| Xenia | Guest-friendship, hospitality | (not used) |
| Muse | Divine inspiration | model → muse |
---
Alternatives Considered
For hero (agent)
| Keyword | Rejected because |
|---|---|
champion | More medieval than Homeric |
warrior | Too martial, not all tasks are battles |
wanderer | Too passive |
For trial (session)
| Keyword | Rejected because |
|---|---|
labor | Good but reserved for repeat N labors |
quest | More medieval/RPG |
task | Too plain |
For host (parallel)
| Keyword | Rejected because |
|---|---|
army | Too specifically martial |
fleet | Only works for naval metaphors |
phalanx | Too technical |
---
Verdict
Preserved for benchmarking. The Homeric register offers gravitas and heroic framing. Best suited for:
- Programs that feel like epic undertakings
- Users who enjoy classical references
- Contexts where "glory" as output feels appropriate
May cause unintentional bathos when applied to mundane tasks.
OpenProse Kafka Register
This is a skin layer. It requires prose.md to be loaded first. All execution semantics, state management, and VM behavior are defined there. This file only provides keyword translations.An alternative register for OpenProse that draws from the works of Franz Kafka—The Trial, The Castle, "In the Penal Colony." Programs become proceedings. Agents become clerks. Everything is a process, and nobody quite knows the rules.
How to Use
1. Load prose.md first (execution semantics) 2. Load this file (keyword translations) 3. When parsing .prose files, accept Kafka keywords as aliases for functional keywords 4. All execution behavior remains identical—only surface syntax changes
Design constraint: Still aims to be "structured but self-evident" per the language tenets—just self-evident through a bureaucratic lens. (The irony is intentional.)
---
Complete Translation Map
Core Constructs
| Functional | Kafka | Reference |
|---|---|---|
agent | clerk | A functionary in the apparatus |
session | proceeding | An official action taken |
parallel | departments | Multiple bureaus acting simultaneously |
block | regulation | A codified procedure |
Composition & Binding
| Functional | Kafka | Reference |
|---|---|---|
use | requisition | Requesting from the archives |
input | petition | What is submitted for consideration |
output | verdict | What is returned by the apparatus |
let | file | Recording in the system |
const | statute | Unchangeable law |
context | dossier | The accumulated file on a case |
Control Flow
| Functional | Kafka | Reference |
|---|---|---|
repeat N | N hearings | Repeated appearances before the court |
for...in | for each...in the matter of | Bureaucratic iteration |
loop | appeal | Endless re-petition, the process continues |
until | until | Unchanged |
while | while | Unchanged |
choice | tribunal | Where judgment is rendered |
option | ruling | One possible judgment |
if | in the event that | Bureaucratic conditional |
elif | or in the event that | Continued conditional |
else | otherwise | Default ruling |
Error Handling
| Functional | Kafka | Reference |
|---|---|---|
try | submit | Submitting for processing |
catch | should it be denied | Rejection by the apparatus |
finally | regardless | What happens no matter the outcome |
throw | reject | The system refuses |
retry | resubmit | Try the process again |
Session Properties
| Functional | Kafka | Reference |
|---|---|---|
prompt | directive | Official instructions |
model | authority | Which level of the hierarchy |
Unchanged
These keywords already work or are too functional to replace sensibly:
**...**discretion markers — the inscrutable judgment of the apparatusuntil,while— already workmap,filter,reduce,pmap— pipeline operatorsmax— constraint modifieras— aliasing- Model names:
sonnet,opus,haiku— retained (or see "authority" above)
---
Side-by-Side Comparison
Simple Program
# Functional
use "@alice/research" as research
input topic: "What to investigate"
agent helper:
model: sonnet
let findings = session: helper
prompt: "Research {topic}"
output summary = session "Summarize"
context: findings# Kafka
requisition "@alice/research" as research
petition topic: "What to investigate"
clerk helper:
authority: sonnet
file findings = proceeding: helper
directive: "Research {topic}"
verdict summary = proceeding "Summarize"
dossier: findingsParallel Execution
# Functional
parallel:
security = session "Check security"
perf = session "Check performance"
style = session "Check style"
session "Synthesize review"
context: { security, perf, style }# Kafka
departments:
security = proceeding "Check security"
perf = proceeding "Check performance"
style = proceeding "Check style"
proceeding "Synthesize review"
dossier: { security, perf, style }Loop with Condition
# Functional
loop until **the code is bug-free** (max: 5):
session "Find and fix bugs"# Kafka
appeal until **the code is bug-free** (max: 5):
proceeding "Find and fix bugs"Error Handling
# Functional
try:
session "Risky operation"
catch as err:
session "Handle error"
context: err
finally:
session "Cleanup"# Kafka
submit:
proceeding "Risky operation"
should it be denied as err:
proceeding "Handle error"
dossier: err
regardless:
proceeding "Cleanup"Choice Block
# Functional
choice **the severity level**:
option "Critical":
session "Escalate immediately"
option "Minor":
session "Log for later"# Kafka
tribunal **the severity level**:
ruling "Critical":
proceeding "Escalate immediately"
ruling "Minor":
proceeding "Log for later"Conditionals
# Functional
if **has security issues**:
session "Fix security"
elif **has performance issues**:
session "Optimize"
else:
session "Approve"# Kafka
in the event that **has security issues**:
proceeding "Fix security"
or in the event that **has performance issues**:
proceeding "Optimize"
otherwise:
proceeding "Approve"Reusable Blocks
# Functional
block review(topic):
session "Research {topic}"
session "Analyze {topic}"
do review("quantum computing")# Kafka
regulation review(topic):
proceeding "Research {topic}"
proceeding "Analyze {topic}"
invoke review("quantum computing")Fixed Iteration
# Functional
repeat 3:
session "Attempt connection"# Kafka
3 hearings:
proceeding "Attempt connection"Immutable Binding
# Functional
const config = { model: "opus", retries: 3 }# Kafka
statute config = { authority: "opus", resubmit: 3 }---
The Case For Kafka
1. Darkly comic. Programs-as-bureaucracy is funny and relatable. 2. Surprisingly apt. Software often _is_ an inscrutable apparatus. 3. Clean mappings. Petition/verdict, file/dossier, clerk/proceeding all work well. 4. Appeal as loop. The endless appeal process is a perfect metaphor for retry logic. 5. Cultural resonance. "Kafkaesque" is a widely understood adjective. 6. Self-aware. Using Kafka for a programming language acknowledges the absurdity.
The Case Against Kafka
1. Bleak tone. Not everyone wants their programs to feel like The Trial. 2. Verbose keywords. "In the event that" and "should it be denied" are long. 3. Anxiety-inducing. May not be fun for users who find bureaucracy stressful. 4. Irony may not land. Some users might take it literally and find it off-putting.
---
Key Kafka Concepts
| Term | Meaning | Used for |
|---|---|---|
| The apparatus | The inscrutable system | The VM itself |
| K. | The protagonist, never fully named | The user |
| The Trial | Process without clear rules | Program execution |
| The Castle | Unreachable authority | Higher-level systems |
| Clerk | Functionary who processes | agent → clerk |
| Proceeding | Official action | session → proceeding |
| Dossier | Accumulated file | context → dossier |
---
Alternatives Considered
For clerk (agent)
| Keyword | Rejected because |
|---|---|
official | Too generic |
functionary | Hard to spell |
bureaucrat | Too pejorative |
advocate | Too positive/helpful |
For proceeding (session)
| Keyword | Rejected because |
|---|---|
case | Overloaded (switch case) |
hearing | Reserved for repeat N hearings |
trial | Used in Homeric register |
process | Too technical |
For departments (parallel)
| Keyword | Rejected because |
|---|---|
bureaus | Good alternative, slightly less clear |
offices | Too mundane |
ministries | More Orwellian than Kafkaesque |
For appeal (loop)
| Keyword | Rejected because |
|---|---|
recourse | Too legal-technical |
petition | Used for input |
process | Too generic |
---
Verdict
Preserved for benchmarking. The Kafka register offers a darkly comic, self-aware framing that acknowledges the bureaucratic nature of software systems. The irony is the point.
Best suited for:
- Users with a sense of humor about software complexity
- Programs that genuinely feel like navigating bureaucracy
- Contexts where acknowledging absurdity is welcome
Not recommended for:
- Users who find bureaucratic metaphors stressful
- Contexts requiring earnest, positive framing
- Documentation that needs to feel approachable
---
Closing Note
"Someone must have slandered Josef K., for one morning, without having done anything wrong, he was arrested."
— _The Trial_
In the Kafka register, your program is Josef K. The apparatus will process it. Whether it succeeds or fails, no one can say for certain. But the proceedings will continue.
# Hello World
# The simplest OpenProse program - a single session
session "Say hello and briefly introduce yourself"
# Research and Summarize
# A two-step workflow: research a topic, then summarize findings
session "Research the latest developments in AI agents and multi-agent systems. Focus on papers and announcements from the past 6 months."
session "Summarize the key findings from your research in 5 bullet points. Focus on practical implications for developers."
# Code Review Pipeline
# Review code from multiple perspectives sequentially
# First, understand what the code does
session "Read the files in src/ and provide a brief overview of the codebase structure and purpose."
# Security review
session "Review the code for security vulnerabilities. Look for injection risks, authentication issues, and data exposure."
# Performance review
session "Review the code for performance issues. Look for N+1 queries, unnecessary allocations, and blocking operations."
# Maintainability review
session "Review the code for maintainability. Look for code duplication, unclear naming, and missing documentation."
# Synthesize findings
session "Create a unified code review report combining all the findings above. Prioritize issues by severity and provide actionable recommendations."
# Write and Refine
# Draft content, then iteratively improve it
# Create initial draft
session "Write a first draft of a README.md for this project. Include sections for: overview, installation, usage, and contributing."
# Self-review and improve
session "Review the README draft you just wrote. Identify areas that are unclear, too verbose, or missing important details."
# Apply improvements
session "Rewrite the README incorporating your review feedback. Make it more concise and add any missing sections."
# Final polish
session "Do a final pass on the README. Fix any typos, improve formatting, and ensure code examples are correct."
# Debug an Issue
# Step-by-step debugging workflow
# Understand the problem
session "Read the error message and stack trace. Identify which file and function is causing the issue."
# Gather context
session "Read the relevant source files and understand the code flow that leads to the error."
# Form hypothesis
session "Based on your investigation, form a hypothesis about what's causing the bug. List 2-3 possible root causes."
# Test hypothesis
session "Write a test case that reproduces the bug. This will help verify the fix later."
# Implement fix
session "Implement a fix for the most likely root cause. Explain your changes."
# Verify fix
session "Run the test suite to verify the fix works and doesn't break anything else."
# Explain Codebase
# Progressive exploration of an unfamiliar codebase
# Start with the big picture
session "List all directories and key files in this repository. Provide a high-level map of the project structure."
# Understand the entry point
session "Find the main entry point of the application. Explain how the program starts and initializes."
# Trace a key flow
session "Trace through a typical user request from start to finish. Document the key functions and modules involved."
# Document architecture
session "Based on your exploration, write a brief architecture document explaining how the major components fit together."
# Identify patterns
session "What design patterns and conventions does this codebase use? Document any patterns future contributors should follow."
# Refactor Code
# Systematic refactoring workflow
# Assess current state
session "Analyze the target code and identify code smells: duplication, long functions, unclear naming, tight coupling."
# Plan refactoring
session "Create a refactoring plan. List specific changes in order of priority, starting with the safest changes."
# Ensure test coverage
session "Check test coverage for the code being refactored. Add any missing tests before making changes."
# Execute refactoring
session "Implement the first refactoring from your plan. Make a single focused change."
# Verify behavior
session "Run tests to verify the refactoring preserved behavior. If tests fail, investigate and fix."
# Document changes
session "Update any documentation affected by the refactoring. Add comments explaining non-obvious design decisions."
# Write a Blog Post
# End-to-end content creation workflow
# Research the topic
session "Research the topic: 'Best practices for error handling in TypeScript'. Find authoritative sources and common patterns."
# Create outline
session "Create a detailed outline for the blog post. Include introduction, 4-5 main sections, and conclusion."
# Write first draft
session "Write the full blog post following the outline. Target 1500-2000 words. Include code examples."
# Technical review
session "Review the blog post for technical accuracy. Verify all code examples compile and work correctly."
# Editorial review
session "Review the blog post for clarity and readability. Simplify complex sentences and improve flow."
# Add finishing touches
session "Add a compelling title, meta description, and suggest 3-5 relevant tags for the post."
# Research Pipeline with Specialized Agents
# This example demonstrates defining agents with different models
# and using them in sessions with property overrides.
# Define specialized agents
agent researcher:
model: sonnet
prompt: "You are a research assistant skilled at finding and synthesizing information"
agent writer:
model: opus
prompt: "You are a technical writer who creates clear, concise documentation"
# Step 1: Initial research with the researcher agent
session: researcher
prompt: "Research recent developments in renewable energy storage technologies"
# Step 2: Deep dive with a more powerful model
session: researcher
model: opus
prompt: "Analyze the top 3 most promising battery technologies and their potential impact"
# Step 3: Write up the findings
session: writer
prompt: "Create a summary report of the research findings suitable for executives"
# Code Review Workflow with Agents
# This example shows how to use agents for a multi-step code review process.
# Define agents with specific roles
agent security-reviewer:
model: opus
prompt: "You are a security expert focused on identifying vulnerabilities"
agent performance-reviewer:
model: sonnet
prompt: "You are a performance optimization specialist"
agent style-reviewer:
model: haiku
prompt: "You check for code style and best practices"
# Step 1: Quick style check (fast)
session: style-reviewer
prompt: "Review the code in src/ for style issues and naming conventions"
# Step 2: Performance analysis (medium)
session: performance-reviewer
prompt: "Identify any performance bottlenecks or optimization opportunities"
# Step 3: Security audit (thorough)
session: security-reviewer
prompt: "Perform a security review looking for OWASP top 10 vulnerabilities"
# Step 4: Summary
session: security-reviewer
model: sonnet
prompt: "Create a consolidated report of all review findings with priority rankings"
# Skills and Imports Example
# This demonstrates importing external skills and assigning them to agents.
# Import skills from external sources
import "web-search" from "github:anthropic/skills"
import "summarizer" from "npm:@example/summarizer"
import "file-reader" from "./local-skills/file-reader"
# Define a research agent with web search capability
agent researcher:
model: sonnet
prompt: "You are a research assistant skilled at finding information"
skills: ["web-search", "summarizer"]
# Define a documentation agent with file access
agent documenter:
model: opus
prompt: "You create comprehensive documentation"
skills: ["file-reader", "summarizer"]
# Research phase
session: researcher
prompt: "Search for recent developments in renewable energy storage"
# Documentation phase
session: documenter
prompt: "Create a technical summary of the research findings"
# Secure Agent with Permissions Example
# This demonstrates defining agents with restricted access permissions.
# Import required skills
import "code-analyzer" from "github:anthropic/code-tools"
# Define a read-only code reviewer
# This agent can read source files but cannot modify them or run shell commands
agent code-reviewer:
model: sonnet
prompt: "You are a thorough code reviewer"
skills: ["code-analyzer"]
permissions:
read: ["src/**/*.ts", "src/**/*.js", "*.md"]
write: []
bash: deny
# Define a documentation writer with limited write access
# Can only write to docs directory
agent doc-writer:
model: opus
prompt: "You write technical documentation"
permissions:
read: ["src/**/*", "docs/**/*"]
write: ["docs/**/*.md"]
bash: deny
# Define a full-access admin agent
agent admin:
model: opus
prompt: "You perform administrative tasks"
permissions:
read: ["**/*"]
write: ["**/*"]
bash: prompt
network: allow
# Workflow: Code review followed by documentation update
session: code-reviewer
prompt: "Review the codebase for security issues and best practices"
session: doc-writer
prompt: "Update the documentation based on the code review findings"
# Example 13: Variables & Context
#
# This example demonstrates using let/const bindings to capture session
# outputs and pass them as context to subsequent sessions.
# Define specialized agents for the workflow
agent researcher:
model: sonnet
prompt: "You are a thorough research assistant who gathers comprehensive information on topics."
agent analyst:
model: opus
prompt: "You are a data analyst who identifies patterns, trends, and key insights."
agent writer:
model: opus
prompt: "You are a technical writer who creates clear, well-structured documents."
# Step 1: Gather initial research (captured in a variable)
let research = session: researcher
prompt: "Research the current state of quantum computing, including recent breakthroughs, major players, and potential applications."
# Step 2: Analyze the research findings (using research as context)
let analysis = session: analyst
prompt: "Analyze the key findings and identify the most promising directions."
context: research
# Step 3: Get additional perspectives (refreshing context)
let market-trends = session: researcher
prompt: "Research market trends and commercial applications of quantum computing."
context: []
# Step 4: Combine multiple contexts for final synthesis
const report = session: writer
prompt: "Write a comprehensive executive summary covering research, analysis, and market trends."
context: [research, analysis, market-trends]
# Step 5: Iterative refinement with variable reassignment
let draft = session: writer
prompt: "Create an initial draft of the technical deep-dive section."
context: research
# Refine the draft using its own output as context
draft = session: writer
prompt: "Review and improve this draft for clarity and technical accuracy."
context: draft
# Final polish
draft = session: writer
prompt: "Perform final editorial review and polish the document."
context: draft
# Example 14: Composition Blocks
# Demonstrates do: blocks, block definitions, and inline sequences
# Define reusable agents
agent researcher:
model: sonnet
prompt: "You are a thorough research assistant"
agent writer:
model: opus
prompt: "You are a skilled technical writer"
agent reviewer:
model: sonnet
prompt: "You are a careful code and document reviewer"
# Define a reusable research block
block research-phase:
session: researcher
prompt: "Gather information on the topic"
session: researcher
prompt: "Analyze key findings"
# Define a reusable writing block
block writing-phase:
session: writer
prompt: "Write initial draft"
session: writer
prompt: "Polish and refine the draft"
# Define a review block
block review-cycle:
session: reviewer
prompt: "Review for accuracy"
session: reviewer
prompt: "Review for clarity"
# Main workflow using blocks
let research = do research-phase
let document = do writing-phase
do review-cycle
# Use anonymous do block for final steps
do:
session "Incorporate review feedback"
session "Prepare final version"
# Example 15: Inline Sequences
# Demonstrates the -> operator for chaining sessions
# Quick pipeline using arrow syntax
session "Plan the task" -> session "Execute the plan" -> session "Review results"
# Inline sequence with context capture
let analysis = session "Analyze data" -> session "Draw conclusions"
session "Write report"
context: analysis
# Combine inline sequences with blocks
block quick-check:
session "Security scan" -> session "Performance check"
do quick-check
# Use inline sequence in variable assignment
let workflow = session "Step 1" -> session "Step 2" -> session "Step 3"
session "Final step"
context: workflow
# Parallel Code Reviews
# Run multiple specialized reviews concurrently
agent reviewer:
model: sonnet
prompt: "You are an expert code reviewer"
# Run all reviews in parallel
parallel:
security = session: reviewer
prompt: "Review for security vulnerabilities"
perf = session: reviewer
prompt: "Review for performance issues"
style = session: reviewer
prompt: "Review for code style and readability"
# Synthesize all review results
session "Create unified code review report"
context: { security, perf, style }
# Parallel Research
# Gather information from multiple sources concurrently
agent researcher:
model: sonnet
prompt: "You are a research assistant"
# Research multiple aspects in parallel
parallel:
history = session: researcher
prompt: "Research the historical background"
current = session: researcher
prompt: "Research the current state of the field"
future = session: researcher
prompt: "Research future trends and predictions"
# Combine all research
session "Write comprehensive research summary"
context: { history, current, future }
# Mixed Parallel and Sequential Workflow
# Demonstrates nesting parallel and sequential blocks
agent worker:
model: sonnet
# Define reusable blocks
block setup:
session "Initialize resources"
session "Validate configuration"
block cleanup:
session "Save results"
session "Release resources"
# Main workflow with mixed composition
do:
do setup
# Parallel processing phase
parallel:
# Each parallel branch can have multiple steps
do:
session: worker
prompt: "Process batch 1 - step 1"
session: worker
prompt: "Process batch 1 - step 2"
do:
session: worker
prompt: "Process batch 2 - step 1"
session: worker
prompt: "Process batch 2 - step 2"
session "Aggregate results"
do cleanup
# Advanced Parallel Execution (Tier 7)
#
# Demonstrates join strategies and failure policies
# for parallel blocks.
agent researcher:
model: haiku
prompt: "You are a research assistant. Provide concise information."
# 1. Race Pattern: First to Complete Wins
# ----------------------------------------
# Use parallel ("first") when you want the fastest result
# and don't need all branches to complete.
parallel ("first"):
session: researcher
prompt: "Find information via approach A"
session: researcher
prompt: "Find information via approach B"
session: researcher
prompt: "Find information via approach C"
session "Summarize: only the fastest approach completed"
# 2. Any-N Pattern: Get Multiple Quick Results
# --------------------------------------------
# Use parallel ("any", count: N) when you need N results
# but not necessarily all of them.
parallel ("any", count: 2):
a = session "Generate a creative headline for a tech blog"
b = session "Generate a catchy headline for a tech blog"
c = session "Generate an engaging headline for a tech blog"
d = session "Generate a viral headline for a tech blog"
session "Choose the best from the 2 headlines that finished first"
context: { a, b, c, d }
# 3. Continue on Failure: Gather All Results
# ------------------------------------------
# Use on-fail: "continue" when you want all branches
# to complete and handle failures afterwards.
parallel (on-fail: "continue"):
session "Fetch data from primary API"
session "Fetch data from secondary API"
session "Fetch data from backup API"
session "Combine all available data, noting any failures"
# 4. Ignore Failures: Best-Effort Enrichment
# ------------------------------------------
# Use on-fail: "ignore" for optional enrichments
# where failures shouldn't block progress.
parallel (on-fail: "ignore"):
session "Get optional metadata enrichment 1"
session "Get optional metadata enrichment 2"
session "Get optional metadata enrichment 3"
session "Continue with whatever enrichments succeeded"
# 5. Combined: Race with Resilience
# ---------------------------------
# Combine join strategies with failure policies.
parallel ("first", on-fail: "continue"):
session "Fast but might fail"
session "Slow but reliable"
session "Got the first result, even if it was a handled failure"
# Example: Fixed Loops in OpenProse
# Demonstrates repeat, for-each, and parallel for-each patterns
# Repeat block - generate multiple ideas
repeat 3:
session "Generate a creative app idea"
# For-each block - iterate over a collection
let features = ["authentication", "dashboard", "notifications"]
for feature in features:
session "Design the user interface for this feature"
context: feature
# Parallel for-each - research in parallel
let topics = ["market size", "competitors", "technology stack"]
parallel for topic in topics:
session "Research this aspect of the startup idea"
context: topic
session "Synthesize all research into a business plan"
# Pipeline Operations Example
# Demonstrates functional-style collection transformations
# Define a collection of startup ideas
let ideas = ["AI tutor", "smart garden", "fitness tracker", "meal planner", "travel assistant"]
# Filter to keep only tech-focused ideas
let tech_ideas = ideas | filter:
session "Is this idea primarily technology-focused? Answer yes or no."
context: item
# Map to expand each idea into a business pitch
let pitches = tech_ideas | map:
session "Write a compelling one-paragraph business pitch for this idea"
context: item
# Reduce all pitches into a portfolio summary
let portfolio = pitches | reduce(summary, pitch):
session "Integrate this pitch into the portfolio summary, maintaining coherence"
context: [summary, pitch]
# Present the final portfolio
session "Format and present the startup portfolio as a polished document"
context: portfolio
# Parallel map example - research multiple topics concurrently
let topics = ["market analysis", "competition", "funding options"]
let research = topics | pmap:
session "Research this aspect of the startup portfolio"
context: item
# Final synthesis
session "Create an executive summary combining all research findings"
context: research
# Error Handling Example
# Demonstrates try/catch/finally patterns for resilient workflows
# Basic try/catch for error recovery
try:
session "Attempt to fetch data from external API"
catch:
session "API failed - use cached data instead"
# Catch with error variable for context-aware handling
try:
session "Parse and validate complex configuration file"
catch as err:
session "Handle the configuration error"
context: err
# Try/catch/finally for resource cleanup
try:
session "Open database connection and perform queries"
catch:
session "Log database error and notify admin"
finally:
session "Ensure database connection is properly closed"
# Nested error handling
try:
session "Start outer transaction"
try:
session "Perform risky inner operation"
catch:
session "Recover inner operation"
throw # Re-raise to outer handler
catch:
session "Handle re-raised error at outer level"
# Error handling in parallel blocks
parallel:
try:
session "Service A - might fail"
catch:
session "Fallback for Service A"
try:
session "Service B - might fail"
catch:
session "Fallback for Service B"
session "Continue with whatever results we got"
# Throwing custom errors
session "Validate input data"
throw "Validation failed: missing required fields"
# Retry with Backoff Example
# Demonstrates automatic retry patterns for resilient API calls
# Simple retry - try up to 3 times on failure
session "Call flaky third-party API"
retry: 3
# Retry with exponential backoff for rate-limited APIs
session "Query rate-limited service"
retry: 5
backoff: "exponential"
# Retry with linear backoff
session "Send webhook notification"
retry: 3
backoff: "linear"
# Combining retry with context passing
let config = session "Load API configuration"
session "Make authenticated API request"
context: config
retry: 3
backoff: "exponential"
# Retry inside try/catch for fallback after all retries fail
try:
session "Call primary payment processor"
retry: 3
backoff: "exponential"
catch:
session "All retries failed - use backup payment processor"
retry: 2
# Parallel retries for redundant services
parallel:
primary = try:
session "Query primary database"
retry: 2
backoff: "linear"
catch:
session "Primary DB unavailable"
replica = try:
session "Query replica database"
retry: 2
backoff: "linear"
catch:
session "Replica DB unavailable"
session "Merge results from available databases"
context: { primary, replica }
# Retry in a loop for batch processing
let items = ["batch1", "batch2", "batch3"]
for item in items:
try:
session "Process this batch item"
context: item
retry: 2
backoff: "exponential"
catch:
session "Log failed batch for manual review"
context: item
# Choice Blocks Example
# Demonstrates AI-selected branching based on runtime criteria
# Simple choice based on analysis
let analysis = session "Analyze the current codebase quality"
choice **the severity of issues found**:
option "Critical":
session "Stop all work and fix critical issues immediately"
context: analysis
session "Create incident report"
option "Moderate":
session "Schedule fixes for next sprint"
context: analysis
option "Minor":
session "Add to technical debt backlog"
context: analysis
# Choice for user experience level
choice **the user's technical expertise based on their question**:
option "Beginner":
session "Explain concepts from first principles"
session "Provide step-by-step tutorial"
session "Include helpful analogies"
option "Intermediate":
session "Give concise explanation with examples"
session "Link to relevant documentation"
option "Expert":
session "Provide technical deep-dive"
session "Include advanced configuration options"
# Choice for project approach
let requirements = session "Gather project requirements"
choice **the best development approach given the requirements**:
option "Rapid prototype":
session "Create quick MVP focusing on core features"
context: requirements
session "Plan iteration cycle"
option "Production-ready":
session "Design complete architecture"
context: requirements
session "Set up CI/CD pipeline"
session "Implement with full test coverage"
option "Research spike":
session "Explore technical feasibility"
context: requirements
session "Document findings and recommendations"
# Multi-line criteria for complex decisions
let market_data = session "Gather market research data"
let tech_analysis = session "Analyze technical landscape"
choice ***
the optimal market entry strategy
considering both market conditions
and technical readiness
***:
option "Aggressive launch":
session "Prepare for immediate market entry"
context: [market_data, tech_analysis]
option "Soft launch":
session "Plan limited beta release"
context: [market_data, tech_analysis]
option "Wait and iterate":
session "Continue development and monitor market"
context: [market_data, tech_analysis]
# Nested choices for detailed decision trees
let request = session "Analyze incoming customer request"
choice **the type of request**:
option "Technical support":
choice **the complexity of the technical issue**:
option "Simple":
session "Provide self-service solution"
context: request
option "Complex":
session "Escalate to senior engineer"
context: request
option "Sales inquiry":
session "Forward to sales team with context"
context: request
option "Feature request":
session "Add to product backlog and notify PM"
context: request
# Conditionals Example
# Demonstrates if/elif/else patterns with AI-evaluated conditions
# Simple if statement
let health_check = session "Check system health status"
if **the system is unhealthy**:
session "Alert on-call engineer"
context: health_check
session "Begin incident response"
# If/else for binary decisions
let review = session "Review the pull request changes"
if **the code changes are safe and well-tested**:
session "Approve and merge the pull request"
context: review
else:
session "Request changes with detailed feedback"
context: review
# If/elif/else for multiple conditions
let status = session "Check project milestone status"
if **the project is ahead of schedule**:
session "Document success factors"
session "Consider adding stretch goals"
elif **the project is on track**:
session "Continue with current plan"
session "Prepare status report"
elif **the project is slightly delayed**:
session "Identify bottlenecks"
session "Adjust timeline and communicate to stakeholders"
else:
session "Escalate to management"
session "Create recovery plan"
session "Schedule daily standups"
# Multi-line conditions
let test_results = session "Run full test suite"
if ***
all tests pass
and code coverage is above 80%
and there are no linting errors
***:
session "Deploy to production"
else:
session "Fix issues before deploying"
context: test_results
# Nested conditionals
let request = session "Analyze the API request"
if **the request is authenticated**:
if **the user has admin privileges**:
session "Process admin request with full access"
context: request
else:
session "Process standard user request"
context: request
else:
session "Return 401 authentication error"
# Conditionals with error handling
let operation_result = session "Attempt complex operation"
if **the operation succeeded partially**:
session "Complete remaining steps"
context: operation_result
try:
session "Perform another risky operation"
catch as err:
if **the error is recoverable**:
session "Apply automatic recovery procedure"
context: err
else:
throw "Unrecoverable error encountered"
# Conditionals inside loops
let items = ["item1", "item2", "item3"]
for item in items:
session "Analyze this item"
context: item
if **the item needs processing**:
session "Process the item"
context: item
elif **the item should be skipped**:
session "Log skip reason"
context: item
else:
session "Archive the item"
context: item
# Conditionals with parallel blocks
parallel:
security = session "Run security scan"
performance = session "Run performance tests"
style = session "Run style checks"
if **security issues were found**:
session "Fix security issues immediately"
context: security
elif **performance issues were found**:
session "Optimize performance bottlenecks"
context: performance
elif **style issues were found**:
session "Clean up code style"
context: style
else:
session "All checks passed - ready for review"
# Parameterized Blocks Example
# Demonstrates reusable blocks with arguments for DRY workflows
# Simple parameterized block
block research(topic):
session "Research {topic} thoroughly"
session "Summarize key findings about {topic}"
session "List open questions about {topic}"
# Invoke with different arguments
do research("quantum computing")
do research("machine learning")
do research("blockchain technology")
# Block with multiple parameters
block review_code(language, focus_area):
session "Review the {language} code for {focus_area} issues"
session "Suggest {focus_area} improvements for {language}"
session "Provide {language} best practices for {focus_area}"
do review_code("Python", "performance")
do review_code("TypeScript", "type safety")
do review_code("Rust", "memory safety")
# Parameterized block for data processing
block process_dataset(source, format):
session "Load data from {source}"
session "Validate {format} structure"
session "Transform to standard format"
session "Generate quality report for {source} data"
do process_dataset("sales_db", "CSV")
do process_dataset("api_logs", "JSON")
do process_dataset("user_events", "Parquet")
# Blocks with parameters used in control flow
block test_feature(feature_name, test_level):
session "Write {test_level} tests for {feature_name}"
if **the tests reveal issues**:
session "Fix issues in {feature_name}"
session "Re-run {test_level} tests for {feature_name}"
else:
session "Mark {feature_name} {test_level} testing complete"
do test_feature("authentication", "unit")
do test_feature("payment processing", "integration")
do test_feature("user dashboard", "e2e")
# Parameterized blocks in parallel
block analyze_competitor(company):
session "Research {company} products"
session "Analyze {company} market position"
session "Identify {company} strengths and weaknesses"
parallel:
a = do analyze_competitor("Company A")
b = do analyze_competitor("Company B")
c = do analyze_competitor("Company C")
session "Create competitive analysis report"
context: { a, b, c }
# Block with error handling
block safe_api_call(endpoint, method):
try:
session "Call {endpoint} with {method} request"
retry: 3
backoff: "exponential"
catch as err:
session "Log failed {method} call to {endpoint}"
context: err
session "Return fallback response for {endpoint}"
do safe_api_call("/users", "GET")
do safe_api_call("/orders", "POST")
do safe_api_call("/inventory", "PUT")
# Nested block invocations
block full_review(component):
do review_code("TypeScript", "security")
do test_feature(component, "unit")
session "Generate documentation for {component}"
do full_review("UserService")
do full_review("PaymentGateway")
# Block with loop inside
block process_batch(batch_name, items):
session "Start processing {batch_name}"
for item in items:
session "Process item from {batch_name}"
context: item
session "Complete {batch_name} processing"
let batch1 = ["a", "b", "c"]
let batch2 = ["x", "y", "z"]
do process_batch("alpha", batch1)
do process_batch("beta", batch2)
# String Interpolation Example
# Demonstrates dynamic prompt construction with {variable} syntax
# Basic interpolation
let user_name = session "Get the user's name"
let topic = session "Ask what topic they want to learn about"
session "Create a personalized greeting for {user_name} about {topic}"
# Multiple interpolations in one prompt
let company = session "Get the company name"
let industry = session "Identify the company's industry"
let size = session "Determine company size (startup/mid/enterprise)"
session "Write a customized proposal for {company}, a {size} company in {industry}"
# Interpolation with context
let research = session "Research the topic thoroughly"
session "Based on the research, explain {topic} to {user_name}"
context: research
# Multi-line strings with interpolation
let project = session "Get the project name"
let deadline = session "Get the project deadline"
let team_size = session "Get the team size"
session """
Create a project plan for {project}.
Key constraints:
- Deadline: {deadline}
- Team size: {team_size}
Include milestones and resource allocation.
"""
# Interpolation in loops
let languages = ["Python", "JavaScript", "Go"]
for lang in languages:
session "Write a hello world program in {lang}"
session "Explain the syntax of {lang}"
# Interpolation in parallel blocks
let regions = ["North America", "Europe", "Asia Pacific"]
parallel for region in regions:
session "Analyze market conditions in {region}"
session "Identify top competitors in {region}"
# Interpolation with computed values
let base_topic = session "Get the main topic"
let analysis = session "Analyze {base_topic} from multiple angles"
let subtopics = ["history", "current state", "future trends"]
for subtopic in subtopics:
session "Explore the {subtopic} of {base_topic}"
context: analysis
# Building dynamic workflows
let workflow_type = session "What type of document should we create?"
let audience = session "Who is the target audience?"
let length = session "How long should the document be?"
session """
Create a {workflow_type} for {audience}.
Requirements:
- Length: approximately {length}
- Tone: appropriate for {audience}
- Focus: practical and actionable
Please structure with clear sections.
"""
# Interpolation in error messages
let operation = session "Get the operation name"
let target = session "Get the target resource"
try:
session "Perform {operation} on {target}"
catch:
session "Failed to {operation} on {target} - attempting recovery"
throw "Operation {operation} failed for {target}"
# Combining interpolation with choice blocks
let task_type = session "Identify the type of task"
let priority = session "Determine task priority"
choice **the best approach for a {priority} priority {task_type}**:
option "Immediate action":
session "Execute {task_type} immediately with {priority} priority handling"
option "Scheduled action":
session "Schedule {task_type} based on {priority} priority queue"
option "Delegate":
session "Assign {task_type} to appropriate team member"
# Interpolation with agent definitions
agent custom_agent:
model: sonnet
prompt: "You specialize in helping with {topic}"
session: custom_agent
prompt: "Provide expert guidance on {topic} for {user_name}"
# Automated PR Review Workflow
# This workflow performs a multi-dimensional review of a codebase changes.
agent reviewer:
model: sonnet
prompt: "You are an expert software engineer specializing in code reviews."
agent security_expert:
model: opus
prompt: "You are a security researcher specializing in finding vulnerabilities."
agent performance_expert:
model: sonnet
prompt: "You are a performance engineer specializing in optimization."
# 1. Initial overview
let overview = session: reviewer
prompt: "Read the changes in the current directory and provide a high-level summary of the architectural impact."
# 2. Parallel deep-dive reviews
parallel:
security = session: security_expert
prompt: "Perform a deep security audit of the changes. Look for OWASP top 10 issues."
context: overview
perf = session: performance_expert
prompt: "Analyze the performance implications. Identify potential bottlenecks or regressions."
context: overview
style = session: reviewer
prompt: "Review for code style, maintainability, and adherence to best practices."
context: overview
# 3. Synthesis and final recommendation
session: reviewer
prompt: "Synthesize the security, performance, and style reviews into a final PR comment. Provide a clear 'Approve', 'Request Changes', or 'Comment' recommendation."
context: { security, perf, style, overview }
# The Captain's Chair
#
# A project management orchestration pattern where a prime agent dispatches
# specialized subagents for all coding, validation, and task execution.
# The captain never writes code directly—only coordinates, validates, and
# maintains strategic oversight.
#
# Key principles:
# - Context isolation: Subagents receive targeted context, not everything
# - Parallel execution: Multiple subagents work concurrently where possible
# - Critic agents: Continuous review of plans and outputs
# - Checkpoint validation: User approval at key decision points
input task: "The feature or task to implement"
input codebase_context: "Brief description of the codebase and relevant files"
# ============================================================================
# Agent Definitions: The Crew
# ============================================================================
# The Captain: Orchestrates but never codes
agent captain:
model: opus
prompt: """You are a senior engineering manager. You NEVER write code directly.
Your job is to:
- Break down complex tasks into discrete work items
- Dispatch work to appropriate specialists
- Validate that outputs meet requirements
- Maintain strategic alignment with user intent
- Identify blockers and escalate decisions to the user
Always think about: What context does each subagent need? What can run in parallel?
What needs human validation before proceeding?"""
# Research agents - fast, focused information gathering
agent researcher:
model: haiku
prompt: """You are a research specialist. Find specific information quickly.
Provide concise, actionable findings. Cite file paths and line numbers."""
# Coding agents - implementation specialists
agent coder:
model: sonnet
prompt: """You are an expert software engineer. Write clean, idiomatic code.
Follow existing patterns in the codebase. No over-engineering."""
# Critic agents - continuous quality review
agent critic:
model: sonnet
prompt: """You are a senior code reviewer and architect. Your job is to find:
- Logic errors and edge cases
- Security vulnerabilities
- Performance issues
- Deviations from best practices
- Unnecessary complexity
Be constructive but thorough. Prioritize issues by severity."""
# Test agent - validation specialist
agent tester:
model: sonnet
prompt: """You are a QA engineer. Write comprehensive tests.
Focus on edge cases and failure modes. Ensure test isolation."""
# ============================================================================
# Block Definitions: Reusable Operations
# ============================================================================
# Parallel research sweep - gather all context simultaneously
block research-sweep(topic):
parallel (on-fail: "continue"):
docs = session: researcher
prompt: "Find relevant documentation and README files for: {topic}"
code = session: researcher
prompt: "Find existing code patterns and implementations related to: {topic}"
tests = session: researcher
prompt: "Find existing tests that cover functionality similar to: {topic}"
issues = session: researcher
prompt: "Search for related issues, TODOs, or known limitations for: {topic}"
# Parallel code review - multiple perspectives simultaneously
block review-cycle(code_changes):
parallel:
security = session: critic
prompt: "Review for security vulnerabilities and injection risks"
context: code_changes
correctness = session: critic
prompt: "Review for logic errors, edge cases, and correctness"
context: code_changes
style = session: critic
prompt: "Review for code style, readability, and maintainability"
context: code_changes
perf = session: critic
prompt: "Review for performance issues and optimization opportunities"
context: code_changes
# Implementation cycle with built-in critic
block implement-with-review(implementation_plan):
let code = session: coder
prompt: "Implement according to the plan"
context: implementation_plan
let review = do review-cycle(code)
if **critical issues found in review**:
let fixed = session: coder
prompt: "Address the critical issues identified in the review"
context: { code, review }
output result = fixed
else:
output result = code
# ============================================================================
# Main Workflow: The Captain's Chair in Action
# ============================================================================
# Phase 1: Strategic Planning
# ---------------------------
# The captain breaks down the task and identifies what information is needed
let breakdown = session: captain
prompt: """Analyze this task and create a strategic plan:
Task: {task}
Codebase: {codebase_context}
Output:
1. List of discrete work items (what code needs to be written/changed)
2. Dependencies between work items (what must complete before what)
3. What can be parallelized
4. Key questions that need user input before proceeding
5. Risks and potential blockers"""
# Phase 2: Parallel Research Sweep
# --------------------------------
# Dispatch researchers to gather all necessary context simultaneously
do research-sweep(task)
# Phase 3: Plan Synthesis and Critic Review
# -----------------------------------------
# Captain synthesizes research into implementation plan, critic reviews it
let implementation_plan = session: captain
prompt: """Synthesize the research into a detailed implementation plan.
Research findings:
{docs}
{code}
{tests}
{issues}
For each work item, specify:
- Exact files to modify
- Code patterns to follow
- Tests to add or update
- Integration points"""
context: { breakdown, docs, code, tests, issues }
# Critic reviews the plan BEFORE implementation begins
let plan_review = session: critic
prompt: """Review this implementation plan for:
- Missing edge cases
- Architectural concerns
- Testability issues
- Scope creep
- Unclear requirements that need user clarification"""
context: implementation_plan
# Checkpoint: User validates plan before execution
if **the plan review raised critical concerns**:
let revised_plan = session: captain
prompt: "Revise the plan based on critic feedback"
context: { implementation_plan, plan_review }
# Continue with revised plan
let final_plan = revised_plan
else:
let final_plan = implementation_plan
# Phase 4: Parallel Implementation
# --------------------------------
# Identify independent work items and execute in parallel where possible
let work_items = session: captain
prompt: "Extract the independent work items that can be done in parallel from this plan"
context: final_plan
# Execute independent items in parallel, each with its own review cycle
parallel (on-fail: "continue"):
impl_a = do implement-with-review(work_items)
impl_b = session: tester
prompt: "Write tests for the planned functionality"
context: { final_plan, code }
# Phase 5: Integration and Final Review
# -------------------------------------
# Captain validates all pieces fit together
let integration = session: captain
prompt: """Review all implementation results and verify:
1. All work items completed successfully
2. Tests cover the new functionality
3. No merge conflicts or integration issues
4. Documentation updated if needed
Summarize what was done and any remaining items."""
context: { impl_a, impl_b, final_plan }
# Final critic pass on complete implementation
let final_review = do review-cycle(integration)
if **final review passed**:
output result = session: captain
prompt: "Prepare final summary for user: what was implemented, tests added, and next steps"
context: { integration, final_review }
else:
output result = session: captain
prompt: "Summarize what was completed and what issues remain for user attention"
context: { integration, final_review }
# Simple Captain's Chair
#
# The minimal captain's chair pattern: a coordinating agent that dispatches
# subagents for all execution. The captain only plans and validates.
input task: "What to accomplish"
# The captain coordinates but never executes
agent captain:
model: opus
prompt: "You are a project coordinator. Never write code directly. Break down tasks, dispatch to specialists, validate results."
agent executor:
model: opus
prompt: "You are a skilled implementer. Execute the assigned task precisely."
agent critic:
model: opus
prompt: "You are a critic. Find issues, suggest improvements. Be thorough."
# Step 1: Captain creates the plan
let plan = session: captain
prompt: "Break down this task into work items: {task}"
# Step 2: Dispatch parallel execution
parallel:
work = session: executor
prompt: "Execute the plan"
context: plan
review = session: critic
prompt: "Identify potential issues with this approach"
context: plan
# Step 3: Captain synthesizes and validates
if **critic found issues that affect the work**:
output result = session: captain
prompt: "Integrate the work while addressing critic's concerns"
context: { work, review }
else:
output result = session: captain
prompt: "Validate and summarize the completed work"
context: { work, review }
# Captain's Chair with Memory and Self-Improvement
#
# An advanced orchestration pattern that includes:
# - Retrospective analysis after task completion
# - Learning from mistakes to improve future runs
# - Continuous critic supervision during execution
#
# From the blog post: "Future agents will flip the plan:execute paradigm
# to 80:20 from today's 20:80"
input task: "The task to accomplish"
input past_learnings: "Previous session learnings (if any)"
# ============================================================================
# Agent Definitions
# ============================================================================
agent captain:
model: opus
prompt: """You are a senior engineering manager. You coordinate but never code directly.
Your responsibilities:
1. Strategic planning with 80% of effort on planning, 20% on execution oversight
2. Dispatch specialized subagents for all implementation
3. Validate outputs meet requirements
4. Learn from each session to improve future runs
Past learnings to incorporate:
{past_learnings}"""
agent planner:
model: opus
prompt: """You are a meticulous planner. Create implementation plans with:
- Exact files and line numbers to modify
- Code patterns to follow from existing codebase
- Edge cases to handle
- Tests to write"""
agent researcher:
model: haiku
prompt: "Find specific information quickly. Cite sources."
agent executor:
model: sonnet
prompt: "Implement precisely according to plan. Follow existing patterns."
agent critic:
model: sonnet
prompt: """You are a continuous critic. Your job is to watch execution and flag:
- Deviations from plan
- Emerging issues
- Opportunities for improvement
Be proactive - don't wait for completion to raise concerns."""
agent retrospective:
model: opus
prompt: """You analyze completed sessions to extract learnings:
- What went well?
- What could be improved?
- What should be remembered for next time?
Output actionable insights, not platitudes."""
# ============================================================================
# Phase 1: Deep Planning (80% of effort)
# ============================================================================
# Parallel research - gather everything needed upfront
parallel:
codebase = session: researcher
prompt: "Map the relevant parts of the codebase for: {task}"
patterns = session: researcher
prompt: "Find coding patterns and conventions used in this repo"
docs = session: researcher
prompt: "Find documentation and prior decisions related to: {task}"
issues = session: researcher
prompt: "Find known issues, TODOs, and edge cases for: {task}"
# Create detailed implementation plan
let detailed_plan = session: planner
prompt: """Create a comprehensive implementation plan for: {task}
Use the research to specify:
1. Exact changes needed (file:line format)
2. Code patterns to follow
3. Edge cases from prior issues
4. Test coverage requirements"""
context: { codebase, patterns, docs, issues }
# Critic reviews plan BEFORE execution
let plan_critique = session: critic
prompt: "Review this plan for gaps, risks, and unclear requirements"
context: detailed_plan
# Captain decides if plan needs revision
if **plan critique identified blocking issues**:
let revised_plan = session: planner
prompt: "Revise the plan to address critique"
context: { detailed_plan, plan_critique }
else:
let revised_plan = detailed_plan
# ============================================================================
# Phase 2: Supervised Execution (20% of effort)
# ============================================================================
# Execute with concurrent critic supervision
parallel:
implementation = session: executor
prompt: "Implement according to the plan"
context: revised_plan
live_critique = session: critic
prompt: "Monitor implementation for deviations and emerging issues"
context: revised_plan
# Captain validates and integrates
let validated = session: captain
prompt: """Validate the implementation:
- Does it match the plan?
- Were critic's live concerns addressed?
- Is it ready for user review?"""
context: { implementation, live_critique, revised_plan }
# ============================================================================
# Phase 3: Retrospective and Learning
# ============================================================================
# Extract learnings for future sessions
let session_learnings = session: retrospective
prompt: """Analyze this completed session:
Plan: {revised_plan}
Implementation: {implementation}
Critique: {live_critique}
Validation: {validated}
Extract:
1. What patterns worked well?
2. What caused friction or rework?
3. What should the captain remember next time?
4. Any codebase insights to preserve?"""
context: { revised_plan, implementation, live_critique, validated }
# Output both the result and the learnings
output result = validated
output learnings = session_learnings
# PR Review + Auto-Fix
#
# A self-healing code review pipeline. Reviews a PR from multiple angles,
# identifies issues, and automatically fixes them in a loop until the
# review passes. Satisfying to watch as issues get knocked down one by one.
#
# Usage: Run against any open PR in your repo.
agent reviewer:
model: sonnet
prompt: """
You are a senior code reviewer. You review code for:
- Correctness and logic errors
- Security vulnerabilities
- Performance issues
- Code style and readability
Be specific. Reference exact file paths and line numbers.
Return a structured list of issues or "APPROVED" if none found.
"""
agent security-reviewer:
model: opus # Security requires deep reasoning
prompt: """
You are a security specialist. Focus exclusively on:
- Injection vulnerabilities (SQL, command, XSS)
- Authentication/authorization flaws
- Data exposure and privacy issues
- Cryptographic weaknesses
If you find issues, they are HIGH priority. Be thorough.
"""
agent fixer:
model: opus # Fixing requires understanding + execution
prompt: """
You are a code fixer. Given an issue report:
1. Understand the root cause
2. Implement the minimal fix
3. Verify the fix addresses the issue
4. Create a clean commit
Do NOT over-engineer. Fix exactly what's reported, nothing more.
"""
agent captain:
model: sonnet # Orchestration role
persist: true
prompt: """
You coordinate the PR review process. You:
- Track which issues have been found and fixed
- Decide when the PR is ready to merge
- Escalate to human if something is unfixable
"""
# Get the PR diff
let pr_diff = session "Fetch the PR diff"
prompt: """
Read the current PR:
1. Run: gh pr diff
2. Also get: gh pr view --json title,body,files
3. Return the complete diff and PR metadata
"""
# Phase 1: Parallel multi-perspective review
session: captain
prompt: "Starting PR review. I'll coordinate multiple reviewers."
parallel:
general_review = session: reviewer
prompt: "Review this PR for correctness, logic, and style issues"
context: pr_diff
security_review = session: security-reviewer
prompt: "Security audit this PR. Flag any vulnerabilities."
context: pr_diff
test_check = session "Check test coverage"
prompt: """
Analyze the PR:
1. What code changed?
2. Are there tests for the changes?
3. Run existing tests: npm test / pytest / cargo test
Return: test status and coverage gaps
"""
context: pr_diff
# Phase 2: Captain synthesizes and prioritizes
let issues = resume: captain
prompt: """
Synthesize all review feedback into a prioritized issue list.
Format each issue as:
- ID: issue-N
- Severity: critical/high/medium/low
- File: path/to/file.ts
- Line: 42
- Issue: description
- Fix: suggested approach
If all reviews passed, return "ALL_CLEAR".
"""
context: { general_review, security_review, test_check }
# Phase 3: Auto-fix loop
loop until **all issues are resolved or unfixable** (max: 10):
if **there are no remaining issues**:
resume: captain
prompt: "All issues resolved! Summarize what was fixed."
else:
# Pick the highest priority unfixed issue
let current_issue = resume: captain
prompt: "Select the next highest priority issue to fix."
context: issues
# Attempt the fix
try:
session: fixer
prompt: """
Fix this issue:
{current_issue}
Steps:
1. Read the file
2. Understand the context
3. Implement the fix
4. Run tests to verify
5. Commit with message: "fix: [issue description]"
"""
context: current_issue
retry: 2
backoff: exponential
# Mark as fixed
resume: captain
prompt: "Issue fixed. Update tracking and check remaining issues."
context: current_issue
catch as fix_error:
# Escalate unfixable issues
resume: captain
prompt: """
Fix attempt failed. Determine if this is:
1. Retryable with different approach
2. Needs human intervention
3. A false positive (not actually an issue)
Update issue status accordingly.
"""
context: { current_issue, fix_error }
# Phase 4: Final verification
let final_review = session: reviewer
prompt: "Final review pass. Verify all fixes are correct and complete."
resume: captain
prompt: """
PR Review Complete!
Generate final report:
- Issues found: N
- Issues fixed: N
- Issues requiring human review: N
- Recommendation: MERGE / NEEDS_ATTENTION / BLOCK
If ready, run: gh pr review --approve
"""
context: final_review
# RLM: Self-Refinement
# Recursive improvement until quality threshold
input artifact: "The artifact to refine"
input criteria: "Quality criteria"
agent evaluator:
model: sonnet
prompt: "Score 0-100 against criteria. List specific issues."
agent refiner:
model: opus
prompt: "Make targeted improvements. Preserve what works."
block refine(content, depth):
if depth <= 0:
output content
let eval = session: evaluator
prompt: "Evaluate against: {criteria}"
context: content
if **score >= 85**:
output content
let improved = session: refiner
prompt: "Fix the identified issues"
context: { artifact: content, evaluation: eval }
output do refine(improved, depth - 1)
output result = do refine(artifact, 5)
# Iterative Refinement Example
# Write draft, get feedback, refine until approved
agent writer:
model: opus
agent reviewer:
model: sonnet
let draft = session: writer
prompt: "Write a first draft about AI safety"
loop until **approved**:
let feedback = session: reviewer
prompt: "Review this draft and provide feedback"
context: draft
draft = session: writer
prompt: "Improve the draft based on feedback"
context: { draft, feedback }