Dicklesworthstone/automated_plan_reviser_pro
About
Iterative specification refinement tool: feeds your docs through GPT Pro Extended Reasoning via Oracle for multiple revision rounds until production-ready
Developer ToolsWhat you can do
- One-Command Iterations - apr run 5 kicks off round 5 without manual copy-paste
- Document Bundling - Automatically combines README, spec, and implementation docs
- Background Processing - 10-60 minute reviews run in background with notifications
- Session Management - Attach/detach from running sessions, check status anytime
Measured star growth
- in 24h
- 0
- in 7 days
- 0
- in 15 days
- -1
- in 1 month
- 0
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
OriginalAutomated Plan Reviser Pro (apr)
Iterative specification refinement with GPT Pro Extended Reasoning via Oracle. The missing link between your specification documents and production-ready designs.
Quick Install
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/automated_plan_reviser_pro/main/install.sh?$(date +%s)" | bash
Works on Linux and macOS. Auto-installs to ~/.local/bin with PATH detection.
TL;DR
The Problem: Complex specifications, especially security-sensitive protocols, need multiple rounds of review. A single pass by even the best AI misses architectural issues, edge cases, and subtle flaws. Manually running 15-20 review cycles is tedious and error-prone.
The Solution: apr automates iterative specification refinement using GPT Pro 5.2 Extended Reasoning via Oracle. Each round builds on the last, converging toward optimal architecture like a numerical optimizer.
Why Use apr?
| Feature | What It Does |
|---|---|
| One-Command Iterations | apr run 5 kicks off round 5 without manual copy-paste |
| Document Bundling | Automatically combines README, spec, and implementation docs |
| Background Processing | 10-60 minute reviews run in background with notifications |
| Session Management | Attach/detach from running sessions, check status anytime |
| Round History | All outputs saved to .apr/rounds/ with git integration |
| Beautiful TUI | Gum-powered interface with graceful ANSI fallback |
| Robot Mode | JSON API for coding agents (apr robot run 5) |
Quick Example
# Set up your workflow once
$ apr setup
# → Interactive wizard: select README, spec, and implementation files
# Run iterative reviews
$ apr run 1 --login --wait # First time: manual ChatGPT login
$ apr run 2 # Background execution
$ apr run 3 --include-impl # Include implementation every few rounds
# Monitor progress
$ apr status # Check all sessions
$ apr attach apr-default-round-3 # Attach to specific session
The Convergence Pattern
Round 1-3: Major architectural fixes, security gaps identified
Round 4-7: Architecture refinements, interface improvements
Round 8-12: Nuanced optimizations, edge case handling
Round 13+: Polishing abstractions, converging on steady state
Each round, GPT Pro focuses on finer details because major issues were already addressed, similar to gradient descent settling into a minimum.
Prepared Blurb for AGENTS.md Files
Include this in your AGENTS.md file for any projects where you want to have access to APR:
# APR (Automated Plan Reviser Pro) - Agent Reference
Iterative spec refinement via GPT Pro Extended Reasoning. Multi-round AI review
with structured outputs for Claude Code integration.
## Commands
# Workflow
apr setup # Interactive wizard (first time)
apr run <N> # Run revision round N
apr run <N> -i # Include implementation doc
apr run <N> -d # Dry-run preview
apr show <N> # View round output
# Analysis
apr diff <N> [M] # Compare rounds (N vs M, or N vs N-1)
apr stats # Convergence analytics + remaining rounds estimate
apr integrate <N> -c # Claude Code prompt → clipboard (KEY COMMAND)
# Management
apr status [--hours 24] # Oracle session status
apr attach <slug> # Reattach to session
apr list # List workflows
apr history # Round history
apr backfill # Generate metrics from existing rounds
apr update # Self-update
## Robot Mode (JSON API)
Robot mode defaults to JSON, and can also emit TOON (token-optimized) when
`tru` (toon_rust) is installed:
```bash
apr robot status --format toon
Format precedence:
--format > APR_OUTPUT_FORMAT > TOON_DEFAULT_FORMAT > json.
apr robot status # {configured, workflows, oracle_available} apr robot workflows # [{name, description}, ...] apr robot init # Create .apr/ apr robot validate # Pre-flight → {valid, errors[], warnings[]} apr robot run # Execute → {slug, pid, output_file, log_file, status} apr robot history # List completed rounds apr robot help # API docs
Response: {ok, code, data, hint?, meta: {v, ts}} Codes: ok | usage_error | not_configured | config_error | validation_failed | dependency_missing | busy | internal_error
Key Paths
.apr/rounds//round_N.md # ← GPT output (INTEGRATE THIS) .apr/analytics//metrics.json # Round analytics data .apr/logs/oracle_.log # Oracle output log (robot mode) .apr/workflows/.yaml # Workflow definition .apr/config.yaml # Default workflow
Agent Workflow
1. Validate (saves 30+ min on failures)
apr robot validate 5 -w myspec | jq -e '.data.valid' || exit 1
2. Run
result=$(apr robot run 5 -w myspec -i)
3. After completion, use integrate command or read file directly
apr integrate 5 -w myspec --copy
File: .apr/rounds/myspec/round_5.md
4. Check convergence to know when to stop
apr stats -w myspec # Score ≥0.75 = approaching stability
Reliability Features
- Pre-flight validation before expensive Oracle runs
- Auto-retry with exponential backoff (10s → 30s → 90s)
- Session locking prevents concurrent runs
- Configurable via APR_MAX_RETRIES, APR_INITIAL_BACKOFF
Options
-w, --workflow NAME Workflow (default: from config) -i, --include-impl Include implementation doc -d, --dry-run Preview oracle command -c, --copy Copy to clipboard -o, --output FILE Output to file -v, --verbose Debug output --wait Block until completion --login Browser login (first time) --no-preflight Skip validation --hours NUM Status window (default: 72) --compact Minified JSON (robot mode) --json JSON output for stats command --detailed Detailed metrics for stats command
Dependencies
Required: bash 4+, Node.js 24+ with npm, oracle (or npx @steipete/oracle) Optional: gum (TUI), jq (robot mode), delta (prettier diffs)
---
## The Core Insight: Iterative Convergence
When you're designing a complex protocol specification, especially when security is involved, just one iteration of review by GPT Pro 5.2 with Extended Reasoning doesn't cut it.
**APR automates the multi-round revision workflow:**
┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Round 1 │────▶│ Round 2 │────▶│ Round 3 │────▶ ... │ Major fixes │ │ Architecture │ │ Refinements │ │ Security gaps │ │ improvements │ │ Optimizations │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ │ │ ▼ ▼ ▼ Wild swings Dampening Converging in design oscillations on optimal
**It very much reminds me of a numerical optimizer gradually converging on a steady state after wild swings in the initial iterations.**
With each round, the specification becomes "less wrong." Not only is this a good thing because the protocol improves, but it also means that in the next round of review, GPT Pro can focus its considerable intellectual energies on the nuanced particulars and in finding just the right abstractions and interfaces because it doesn't need to put out fires in terms of outright mistakes or security problems that preoccupy it in earlier rounds.
---
## Table of Contents
- [For Coding Agents](#for-coding-agents)
- [The Core Insight](#the-core-insight-iterative-convergence)
- [Why APR Exists](#-why-apr-exists)
- [Highlights](#-highlights)
- [Quickstart](#-quickstart)
- [Usage](#-usage)
- [Commands](#commands)
- [Options](#options)
- [The Workflow](#-the-workflow)
- [Interactive Setup](#-interactive-setup)
- [Session Monitoring](#-session-monitoring)
- [Analysis Commands](#-analysis-commands)
- [View Round Output](#view-round-output-apr-show)
- [Compare Rounds](#compare-rounds-apr-diff)
- [Claude Code Integration](#claude-code-integration-apr-integrate)
- [Convergence Analytics](#-convergence-analytics)
- [The Stats Command](#the-stats-command)
- [Convergence Algorithm](#convergence-algorithm)
- [Backfill Historical Data](#backfill-historical-data)
- [Reliability Features](#-reliability-features)
- [Pre-Flight Validation](#pre-flight-validation)
- [Auto-Retry with Backoff](#auto-retry-with-exponential-backoff)
- [Session Locking](#session-locking)
- [Robot Mode](#-robot-mode-automation-api)
- [Self-Update](#-self-update)
- [The Inspiration](#-the-inspiration-flywheel-connector-protocol)
- [Design Principles](#-design-principles)
- [Architecture](#-architecture)
- [Testing Framework](#-testing-framework)
- [Terminal Styling](#-terminal-styling)
- [Dependencies](#-dependencies)
- [Environment Variables](#-environment-variables)
- [Oracle Remote Setup](#-oracle-remote-setup-headlessssh-environments)
- [Troubleshooting](#-troubleshooting)
- [Contributing](#-contributing)
- [License](#-license)
---
## 💡 Why APR Exists
Specification review is an iterative process, not a single pass:
| Problem | Why It's Hard | How APR Solves It |
|---------|---------------|-------------------|
| **Context loss** | Each new GPT session starts fresh | Structured prompts carry full context |
| **Manual bundling** | Copying README + spec + impl is tedious | Automatic document bundling |
| **No tracking** | Easy to lose track of which round you're on | Round history with git integration |
| **Slow feedback loop** | Extended reasoning takes 10-60 minutes | Background execution with monitoring |
| **Authentication friction** | ChatGPT login expires, cookies fail | Manual login mode with persistent profile |
| **Integration gaps** | GPT output sits in a chat window | Saved to files for Claude Code integration |
APR lets you set up a workflow once, then iterate with a single command per round.
---
## ✨ Highlights
<table>
<tr>
<td width="50%">
### Beautiful Terminal UI
Powered by [gum](https://github.com/charmbracelet/gum):
- Styled banners and headers
- Interactive file picker
- Confirmation dialogs
- Graceful ANSI fallback
</td>
<td width="50%">
### Interactive Setup Wizard
Configure your workflow once:
- Select README, spec, implementation files
- Choose GPT model and reasoning level
- Automatic round output management
- Multiple workflow support
</td>
</tr>
<tr>
<td width="50%">
### Session Management
Never lose a review:
- Background execution with PID tracking
- Session status checking
- Reattachment to running sessions
- Desktop notifications on completion
</td>
<td width="50%">
### Round Tracking
Full revision history:
- Numbered round outputs
- Git-integrated workflow
- History command for review
- Multiple workflow support
</td>
</tr>
<tr>
<td width="50%">
### Robot Mode for Automation
JSON API for coding agents:
- Structured output for machine parsing
- Pre-flight validation before expensive runs
- Full status and workflow introspection
- Seamless CI/CD integration
</td>
<td width="50%">
### Secure Self-Update
Keep APR current effortlessly:
- One-command updates with `apr update`
- SHA-256 checksum verification
- Atomic installation (no partial updates)
- Optional daily update checking
</td>
</tr>
</table>
---
## ⚡ Quickstart
### Installation
**One-liner (recommended):**
```bash
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/automated_plan_reviser_pro/main/install.sh" | bash
Manual installation
# Download script
curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/automated_plan_reviser_pro/main/apr -o ~/.local/bin/apr
chmod +x ~/.local/bin/apr
# Ensure ~/.local/bin is in PATH
echo 'export PATH="$HOME/.local/bin:$PATH"' >> ~/.zshrc # or ~/.bashrc
source ~/.zshrc
# Install Oracle (required)
npm install -g @steipete/oracle
First Run
Important: Run APR from your project directory (where your README, spec, and implementation files live). The .apr/ configuration directory will be created there.
# Navigate to your project
cd /path/to/your/project
# 1. Run the setup wizard
apr setup
# 2. First round with manual login (required first time)
apr run 1 --login --wait
# 3. Subsequent rounds
apr run 2
apr run 3 --include-impl # Include implementation doc every few rounds
🚀 Usage
apr [command] [options]
Commands
| Command | Description |
|---|---|
| Core Workflow | |
run <round> |
Run a revision round (default if number given) |
setup |
Interactive workflow setup wizard |
status |
Check Oracle session status |
attach <session> |
Attach to a running/completed session |
| Management | |
list |
List all configured workflows |
history |
Show revision history for current workflow |
backfill |
Generate metrics from existing rounds |
update |
Check for and install updates |
help |
Show help message |
| Analysis | |
show <round> |
View round output with pager support |
diff <N> [M] |
Compare round outputs (N vs M, or N vs N-1) |
integrate <round> or integrate <target> |
Generate Claude Code integration prompt for the selected review |
stats |
Show round analytics and convergence signals |
| Automation | |
robot <cmd> |
Machine-friendly JSON interface for coding agents |
Options
| Flag | Description |
|---|---|
-w, --workflow NAME |
Workflow to use (default: from config) |
-i, --include-impl |
Include implementation document |
-d, --dry-run |
Preview without sending to GPT Pro |
-r, --render |
Render bundle for manual paste |
-c, --copy |
Copy rendered bundle to clipboard |
--wait |
Wait for completion (blocking) |
--login |
Manual login mode (first-time setup) |
--keep-browser |
Keep browser open after completion |
-q, --quiet |
Minimal output (errors only) |
--version |
Show version |
Examples
# First-time setup
apr setup
# Run revision round 1 (first time requires --login)
apr run 1 --login --wait
# Run round 2 in background
apr run 2
# Run round 3 with implementation doc
apr run 3 --include-impl
# Check session status
apr status
# Attach to a running session
apr attach apr-default-round-3
# Preview what will be sent
apr run 4 --dry-run
# Render for manual paste into ChatGPT
apr run 4 --render --copy
# Use a different workflow
apr run 1 -w my-other-project
🔄 The Workflow
APR automates this workflow:
┌─────────────────────────────────────────────────────────────────────────────┐
│ APR REVISION WORKFLOW │
├─────────────────────────────────────────────────────────────────────────────┤
│ │
│ ┌─────────────┐ ┌──────────────────────────────────────────────────┐ │
│ │ START │────▶│ 1. BUNDLE: Collect docs for GPT Pro review │ │
│ │ Round N │ │ - README (project overview) │ │
│ └─────────────┘ │ - Specification (the design) │ │
│ │ - Implementation (optional, every 3-4 rounds)│ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 2. ORACLE: Send to GPT Pro 5.2 Extended │ │
│ │ - Browser automation mode │ │
│ │ - 10-60 minute processing time │ │
│ │ - Desktop notification on completion │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 3. CAPTURE: Save GPT Pro output │ │
│ │ → .apr/rounds/<workflow>/round_N.md │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 4. INTEGRATE: (Manual) Paste into Claude Code │ │
│ │ - Prime CC with AGENTS.md, README, spec │ │
│ │ - Apply revisions to specification │ │
│ │ - Update README to match │ │
│ │ - Harmonize implementation doc │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌──────────────────────────────────────────────────┐ │
│ │ 5. COMMIT: Push to git │ │
│ │ - Logical commit groupings │ │
│ │ - Detailed commit messages │ │
│ │ - Audit trail in git history │ │
│ └──────────────────────────────────────────────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────┐ │
│ │ READY │ → Start Round N+1 │
│ │ for next │ │
│ └─────────────┘ │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Why Include Implementation Every Few Rounds?
You might object that it's pointless to update the README and implementation document if we know already that we are going to make many more revisions to the specification document. But when you start thinking of each round of iteration as a sort of perturbation in an optimization process, you want these changes mirrored in the implementation as you go.
This reduces the shock of trying to apply N revisions all at once and helps to surface problems better. After all, when you start turning ideas into code, the faulty assumptions get surfaced earlier and can feed back into your specification revisions.
Automatic Implementation Inclusion
Instead of manually adding --include-impl every few rounds, you can configure automatic periodic inclusion in your workflow:
# .apr/workflows/fcp.yaml
rounds:
output_dir: .apr/rounds/fcp
impl_every_n: 4 # Include implementation every 4th round (4, 8, 12, ...)
With impl_every_n: 4:
- Rounds 1, 2, 3: README + spec only
- Round 4: README + impl + spec (automatic)
- Rounds 5, 6, 7: README + spec only
- Round 8: README + impl + spec (automatic)
- ...and so on
This ensures implementation-grounded feedback at regular intervals without manual intervention. You can still override with --include-impl for any specific round.
🧙 Interactive Setup
Run apr setup to launch the interactive wizard:
╔════════════════════════════════════════════════════════════╗
║ Automated Plan Reviser Pro v1.2.0 ║
║ Iterative AI-Powered Spec Refinement ║
╚════════════════════════════════════════════════════════════╝
╭────────────────────────────────────────────────────────────╮
│ Welcome to the APR Setup Wizard! │
│ │
│ This will help you configure a new revision workflow. │
│ You'll specify your documents and review preferences. │
╰────────────────────────────────────────────────────────────╯
[1/6] Workflow name
Workflow name: fcp-spec
[2/6] Project description
Brief description: Flywheel Connector Protocol specification
[3/6] README/Overview document
Select README file: README.md
✓ README: README.md
[4/6] Specification document
Select specification file: FCP_Specification_V2.md
✓ Specification: FCP_Specification_V2.md
[5/6] Implementation document (optional)
Do you have an implementation/reference document? [y/N] y
Select implementation file: docs/fcp_model_connectors_rust.md
✓ Implementation: docs/fcp_model_connectors_rust.md
[6/6] Review preferences
Select model for reviews:
> 5.2 Thinking (Extended Reasoning)
gpt-5.2-pro
gpt-5.2
Custom / Other (any Oracle model id)
╭────────────────────────────────────────────────────────────╮
│ ✓ Workflow 'fcp-spec' created successfully! │
│ │
│ To run your first revision round: │
│ apr run 1 │
│ │
│ To run with implementation doc: │
│ apr run 1 --include-impl │
╰────────────────────────────────────────────────────────────╯
📡 Session Monitoring
APR provides multiple ways to monitor long-running reviews:
Check All Sessions
apr status
Attach to a Specific Session
apr attach apr-fcp-spec-round-5
Oracle Direct Commands
# Check status
npx -y @steipete/oracle status --hours 24
# Attach with rendered output
npx -y @steipete/oracle session apr-fcp-spec-round-5 --render
Desktop Notifications
APR automatically enables desktop notifications (via Oracle's --notify flag) so you'll be alerted when a review completes.
🔍 Analysis Commands
Once you've accumulated rounds of feedback, APR provides powerful tools to navigate, compare, and integrate the outputs. These commands transform raw GPT Pro output into actionable insights.
Changing a workflow's output_dir applies to future reviews. History, show,
diff, and inter-round metrics can still locate a recorded answer through that
run's saved configuration and verify its digest, even if the new directory
has no reviews yet. Keep the original answer and its retained run directory.
View Round Output (apr show)
View any round's output with intelligent paging:
# View a specific round
apr show 5
# View from a specific workflow
apr show 3 -w my-protocol
The show command:
- Automatically uses your preferred pager (
$PAGER, falling back tolessormore) - Supports all standard pager navigation (search with
/, page up/down, etc.) - Falls back to direct output when piped or in non-interactive mode
Compare Rounds (apr diff)
Track how the specification evolves across iterations:
# Compare round 3 to round 4
apr diff 3 4
# Compare round 5 to its predecessor (round 4)
apr diff 5
# Use a specific diff tool
apr diff 3 5 --tool delta
The diff command intelligently selects the best available diff tool:
- delta: Beautiful syntax-highlighted diffs with line numbers
- diff: Standard UNIX diff as fallback
Why diffs help: Seeing what changed between rounds reveals the convergence pattern. Early diffs show major structural changes; later diffs show increasingly subtle refinements, confirming you're approaching a stable design.
Claude Code Integration (apr integrate)
The integrate command generates prompts optimized for handing GPT Pro's feedback to Claude Code:
# Generate integration prompt
apr integrate 5
# Copy directly to clipboard
apr integrate 5 --copy
# Output to file for later use
apr integrate 5 --output round5_prompt.md
# Keep a handoff bound to one exact run, even after round 5 is rerun
apr integrate run:default:round_5.ABC123 --copy
# A queue receipt also works, including requests that reused a paid review
apr robot integrate queue:default:entry-... --compact
# Integrate an answer recovered from an earlier failed producer
apr integrate recovery:default:round_5.ABC123 --output recovered_integration.md
For a recorded review, the integration prompt names the specification, README,
and reviewer model selected for that run. Changing the workflow for a later
round leaves earlier integration targets bound to their original review. If the
specification has since been edited, the prompt asks the coding agent to
reconcile the feedback with the current text. A missing original specification
stops integration. apr robot integrate includes the run ID, reviewed and
current specification hashes, and spec_status in data.provenance.
Archives predating the ledger use the current workflow and report
spec_status: "unverified".
A round number selects that round's latest successful review. To integrate the
exact answer returned to a controller, pass the same result_target used by
apr result: run:<workflow>:<run_id>, queue:<workflow>:<entry_id>, or
recovery:<workflow>:<run_id>. A queue receipt follows the request to its
recorded paid run, including reuse. A recovery receipt selects its separately
verified answer while preserving the original producer's reviewed documents
and model. Integration applies the recovered answer's trust checks and refuses
a recorded composer-transcript mismatch. The workflow inside an exact target takes
precedence over the current default or -w. The target remains bound to the
original generation after a forced rerun, and its recorded paths and reviewer
model remain available when the workflow configuration is moved or changed.
Robot integration returns the requested receipt in data.result_target.
Integration checks local retained evidence without contacting Oracle or
checking for updates. Pending run or queue targets return busy (exit 12);
collect the result with apr result "$target" --wait and retry integration.
Failed or canceled targets, altered answers, conflicting records, and a
recorded composer transcript mismatch refuse prompt generation. An exact
target never falls back to a different successful review. File export refuses
destinations that alias the reviewed specification, README, or saved answer.
The generated prompt:
- Includes context priming (instructs Claude to read AGENTS.md, README, spec)
- Wraps the GPT Pro output in appropriate delimiters
- Adds integration instructions for applying changes
Workflow tip: Run apr integrate 5 -c, then paste directly into Claude Code. The prompt is structured to maximize Claude's understanding of the context and desired changes.
📊 Convergence Analytics
APR tracks metrics over time alongside running rounds, so you can see when your specification is converging toward a stable design. This turns the subjective "are we done yet?" into quantifiable signals.
The Stats Command
# Show analytics for current workflow
apr stats
# Detailed metrics with document statistics
apr stats --detailed
# JSON output for programmatic use
apr stats --json
Example output:
╭────────────────────────────────────────────────────────────╮
│ CONVERGENCE ANALYTICS │
│ Workflow: fcp-spec │
├────────────────────────────────────────────────────────────┤
│ Rounds completed: 12 │
│ Convergence score: 0.82 (HIGH - approaching stability) │
│ Estimated remaining: 2-3 rounds │
│ │
│ Signal Analysis: │
│ Output size trend: ↓ decreasing (0.89) │
│ Change velocity: ↓ slowing (0.78) │
│ Content similarity: ↑ increasing (0.79) │
╰────────────────────────────────────────────────────────────╯
Convergence Algorithm
The convergence detector uses a weighted combination of three signals:
Score = (0.35 × output_trend) + (0.35 × change_velocity) + (0.30 × similarity_trend)
| Signal | Weight | What It Measures |
|---|---|---|
| Output Size Trend | 35% | Are GPT Pro's responses getting shorter? Early rounds produce lengthy analyses; convergence shows as more focused, briefer feedback. |
| Change Velocity | 35% | Is the rate of change slowing? Measured by comparing delta sizes between consecutive rounds. |
| Content Similarity | 30% | Are successive rounds becoming more similar? Uses the intersection divided by the union of distinct lines; repeated headings, blank lines, and boilerplate count once in each set. |
Interpretation:
- Score ≥ 0.75: High confidence of convergence. The specification is stabilizing.
- Score 0.50-0.74: Moderate convergence. Significant work remains but progress is visible.
- Score < 0.50: Low convergence. Still in early iteration phase with major changes likely.
The algorithm also estimates remaining rounds based on the current convergence trajectory, helping you plan your workflow.
Analytics use jq for arithmetic and do not require bc. Similarity stays
between zero and one. Change ratios count a final line without a newline and
remain nonzero when a review is deleted down to an empty file. Failed reads or
comparisons remain unavailable evidence; missing or invalid observations cannot
contribute a positive convergence signal. At least three rounds are required.
Changing the recorded specification path starts a new sequence. Editing the
contents at the same path is part of normal revision and keeps that sequence
intact. A filtered export also respects intervening specification changes and
failed document acknowledgements, even if those rounds are outside the filter.
Reports derive convergence from their captured round observations instead of trusting an older cached conclusion. Reading human/robot statistics, dashboard data, or exports does not rewrite the metrics file. These measurements describe review text and remain a heuristic for deciding when another review is useful.
If a review requests a document acknowledgement and the response omits it
or reports different hashes, that round breaks the convergence trend. APR
keeps the review in history and waits for three subsequent eligible reviews
before estimating stability again. The JSON reason unverified_document_ack
identifies the affected round and the number of eligible reviews since it.
Workflows with acknowledgements disabled can use the ordinary text metrics.
Completing a review publishes its round metrics, the next review's updated
comparison, and the convergence score together. If collection or comparison
fails, readers retain the previous complete report. Convergence writers
calculate from the current round index while holding the workflow analytics
lock. Concurrent reruns can therefore revise the evidence before a waiting
writer publishes its score. Analytics writers use descriptor
locks with flock or BSD lockf. The portable fallback waits up to five
seconds for its owner. After an interrupted fallback writer, inspect the PID
in .apr/analytics/<workflow>/.metrics.lock before clearing the file.
Backfill Historical Data
If you've been running rounds before metrics collection was added, the backfill command generates metrics retroactively:
# Backfill metrics for all rounds
apr backfill
# Backfill for a specific workflow
apr backfill -w my-protocol
# Force regeneration even if metrics exist
apr backfill --force
Backfill analyzes each round's output file and generates:
- Character, word, and line counts
- Heading and section counts
- Timestamps from file metadata
- Baseline data for convergence calculations
Use apr backfill --force to regenerate existing historical change metrics
with the corrected distinct-line calculation. Reports discount invalid legacy
similarity values until their underlying comparisons are regenerated.
For a review with a retained input bundle, backfill verifies the bundle and recreates the original document statistics using the reviewed snapshots. It uses the completion time from the ledger. Earlier rounds with only a Markdown answer use the answer's file timestamp and output statistics.
Backfill publishes the complete round history and its convergence score together. Stats readers can continue using the previous report during a rebuild. If collection fails or a selected answer changes during the scan, APR retains the previous report and returns an error.
Execution History
apr stats, apr robot stats, the dashboard, and JSON/CSV/Markdown exports
also report retained executions and queue requests. Failed reviews are visible
even before a successful review creates metrics.json. Reporting reads the
run ledgers and queue history without changing those artifacts or manufacturing
successful review rounds.
JSON includes a separately versioned execution object with runs,
queue, summary, and warnings. Each execution retains its outcome,
native Oracle exit, attempts, retries, busy waits and wait duration. Queue
observations include enqueue/start/finish times, controller identity, waiting
state, cancellation, and reuse. Canonical and private copies of the same run
count once. Reusing an answer increases the request count without adding
another producer attempt.
Each execution's composer_preview records the local Oracle preview check,
including its status, rejection reason, affected document role, and measured
byte and file counts when available. execution.summary.composer_previews
counts matched, mismatched, unverifiable, and unrecorded previews in the
selected history. A rerun keeps its predecessor's outcome. An older run or
a run without this check has a null preview. These figures describe inputs
prepared before submission. The document acknowledgement is a separate
observation from the returned review.
Each execution also retains composer_transcript, ack_requested, ack, and
ack_status. execution.summary.composer_transcripts counts matched,
mismatch, unavailable, unverifiable, and unrecorded observations.
An unavailable transcript could not be obtained; an unverifiable one could not
be validated and compared with the retained prompt; a null, unrecorded value
means no observation was retained. Neither is a confirmed mismatch. Matched and mismatched
transcripts retain their artifact and observed prompt digests in JSON and CSV.
execution.summary.acknowledgements distinguishes these states:
| State | Meaning |
|---|---|
matched |
The answer's acknowledgement matches the selected document manifest |
missing |
The answer was checked and contained no acknowledgement block |
mismatch |
A block was present but incomplete or different from the manifest |
unrecorded |
An acknowledgement was requested, but no answer check was retained, such as a failed execution |
not_requested |
The run explicitly recorded that acknowledgement was disabled |
unknown |
The retained record does not establish whether acknowledgement was requested |
Human stats and the dashboard identify confirmed transcript mismatches and missing or incorrect acknowledgements by round and exact run ID. A successful rerun does not hide its predecessor's trust warnings. Reporting refreshes a cached round's ACK and transcript fields from its validated terminal record before calculating convergence. These checks compare locally retained prompts and returned acknowledgements; they do not establish provider receipt or model understanding.
Stats, the dashboard, and exports also reconcile interrupted metrics updates in
memory. They follow each round's retained lineage to its latest successful
generation; a started or failed rerun does not displace that success. A newer
validated answer replaces a stale cached row, and a successful round missing
from the cache is reconstructed when its answer can be verified. Adjacent
comparisons are recalculated from available verified answers, including when
the cache already contains a new predecessor row but its successor still has
an older comparison. Newly reconstructed document counts require that
generation's retained input snapshots; unavailable snapshots yield
documents: null, never another generation's counts.
JSON reports include review_evidence.refreshed_rounds and
review_evidence.barriers. A barrier identifies the affected round, selected
and cached run IDs, and the reason current review evidence or a comparison
cannot be used. Human reports and Markdown exports show these warnings. Missing,
altered, conflicting, or unsafe evidence for a newly selected success prevents
the old cache from recommending convergence. A successful round whose answer
is unavailable still creates a barrier even if it has no cached row. Whole
reports include these later barriers; filtered historical exports consider
barriers through their last selected round, including intervening rounds
excluded from the export. When too few trustworthy subsequent reviews remain,
convergence reports reason: "unavailable_review_evidence".
Unchanged archived observations and their timestamps remain usable after old
answers or input snapshots have been pruned. Existing evidence that contradicts
the recorded answer is reported as a barrier. When a round has retained
successful reruns and an adjacent comparison can no longer be verified, the
report conservatively withholds convergence even if its cached rows appear
current: old caches do not record which predecessor generation produced that
comparison. Restore the retained evidence and retry the report, or use
apr backfill --force to deliberately rebuild the persisted cache. Reporting
itself leaves both the metrics cache and run records unchanged.
Human reports also show failures and contention prominently. Malformed, conflicting, symlinked, or incomplete evidence produces warnings and marks execution totals as incomplete. The report describes available local records, not remote service liveness. Convergence continues to use successful review-round metrics only.
CSV preserves its original columns and appends runtime and trust fields. Its
record_type distinguishes execution, queue_request, and historical
round rows. Queue request rows leave producer counters empty so summing
those columns does not count reused work twice. Execution rows use their own
acknowledgement and transcript observations even when a later run replaced the
selected round. Markdown includes both checks in the execution table and
highlights affected retained runs. CSV also appends review_evidence_status
and review_evidence_reasons for unavailable evidence affecting the selected
logical round, including when the row describes a retained older execution.
Blank evidence fields make no additional verification claim. Its
convergence_reason and convergence_unverified_round columns preserve the
reason for an unavailable stopping signal when a filter excludes the affected
round. Round and time export filters also filter execution/request history and
recompute execution and trust totals.
Interactive Dashboard
For a full-screen analytics experience:
apr dashboard
The dashboard provides:
- Real-time convergence gauge visualization
- Round-by-round output size trends
- Navigation with keyboard shortcuts (↑↓ navigate, Enter view details, d diff, q quit)
- Summary statistics at a glance
Data Export
Export metrics for external analysis or reporting:
# JSON format (full metrics structure)
apr stats --export json > metrics.json
# CSV format (tabular data for spreadsheets)
apr stats --export csv > metrics.csv
# Markdown report (human-readable summary)
apr stats --export md > report.md
# Export specific round range
apr stats --export json --rounds 3-5
# Export to file directly
apr stats --export csv -o metrics.csv
Round and date filters recalculate convergence on the selected reviews. An exported round has a change comparison only when its original predecessor also appears in the selection. A one-round export therefore cannot report convergence from later reviews.
Example JSON export structure:
{
"schema_version": "1.0.0",
"workflow": "my-project",
"rounds": [
{
"round": 1,
"timestamp": "2026-01-10T14:30:00Z",
"output": {
"char_count": 15200,
"word_count": 2500,
"line_count": 320
}
}
],
"convergence": {
"detected": false,
"confidence": 0.78,
"signals": {
"output_trend": 0.85,
"change_velocity": 0.75,
"similarity_trend": 0.72
}
}
}
Example CSV export:
"round","timestamp","output_chars","output_words","output_lines","similarity","convergence_score"
1,"2026-01-10T14:30:00Z",15200,2500,320,"",0.0
2,"2026-01-10T16:45:00Z",14100,2350,298,0.72,0.45
3,"2026-01-11T09:15:00Z",12800,2150,275,0.81,0.68
🛡️ Reliability Features
Extended reasoning sessions can take 30-60 minutes. APR includes multiple features to ensure these expensive operations succeed reliably.
Review a round before launch
Run apr run 5 --confirm from an interactive terminal to check the selected
workflow, model, route, document hashes, prompt size and resolved instructions
before APR starts Oracle. The default preview shows 40 prompt lines.
APR_CONFIRM_LINES=0 apr run 5 --confirm shows the whole prompt. Approval
applies to the displayed prompt and document hashes. If an input changes before
APR retains it, the review stops.
An approved run records the decision time and prompt hash in its ledger and
metrics. Declining exits with status 130 and saves a private decision record in
.apr/confirmations/<workflow>/. Existing round outputs and ledgers stay
available. Confirmation is opt-in for human runs. Use --no-confirm to override
an earlier --confirm in a shell alias.
Pre-Flight Validation
Run apr doctor to check the Oracle installation before starting a review. It works outside a project. Use apr doctor --json for a list of checks with stable IDs, or apr robot doctor for the robot response envelope.
With ORACLE_REMOTE_HOST and ORACLE_REMOTE_TOKEN configured, doctor sends a single authenticated GET to Oracle's /health endpoint with a five-second timeout. It distinguishes connection failures, rejected tokens, incompatible responses, and occupied execution slots. A server without capacity counters reports capacity as unknown. A successful check is a snapshot, so availability can change before a run starts. The command never submits documents or starts a browser review.
Before sending anything to Oracle, APR validates that all preconditions are met:
# Run with explicit pre-flight (default behavior)
apr run 5
# Skip pre-flight for faster startup
apr run 5 --no-preflight
Pre-flight checks verify:
| Check | What It Validates |
|---|---|
| Oracle availability | Oracle is installed and accessible (global or npx) |
| Workflow exists | The specified workflow configuration is readable |
| README exists | The project README file is present |
| Spec exists | The specification document is accessible |
| Implementation exists | If --include-impl, verifies the implementation doc |
| Previous round | For round N > 1, verifies round N-1 exists |
Why this matters: Discovering a missing file 30 minutes into a GPT Pro session is frustrating. Pre-flight catches these issues in under a second.
Auto-Retry with Exponential Backoff
Network issues, rate limits, and transient failures shouldn't require manual intervention. APR automatically retries failed Oracle operations:
Attempt 1 → fail → wait 10s
Attempt 2 → fail → wait 30s (10s × 3)
Attempt 3 → success (or final failure)
Configuration via environment variables:
# Maximum retry attempts (default: 3)
export APR_MAX_RETRIES=5
# Initial backoff in seconds (default: 10)
export APR_INITIAL_BACKOFF=15
The exponential backoff (multiplier of 3) prevents hammering the service while giving transient issues time to resolve.
A failed Oracle client can leave its browser review running. APR checks the
current attempt's uniquely bound local session metadata after a client failure
and immediately before another attempt. If Oracle still marks that review as
running, APR returns busy (exit 12), preserves the partial answer privately,
and keeps the run ledger nonterminal with the original client exit, execution
counters, and retry_guard session observation. Use the reported
apr attach run:<workflow>:<run-id> target to inspect that same review.
If the client fails after Oracle has marked the review completed, APR also
holds the round when the session identifies one specific browser conversation.
Use apr recover run:<workflow>:<run-id> to retrieve the answer. Recovery checks
the pinned conversation and submitted prompt hash, requires a successful
identity-matched harvest, and validates the answer before publishing it. The
ledger retains the original client exit. The corresponding robot reason is
oracle_session_completed.
This hold applies to foreground, detached, robot, and queued execution,
including --no-retry. Subsequent direct runs, --resume, --force, and queue
restarts retain the unresolved run instead of launching another review for that
round. Robot responses expose reason: "oracle_session_running",
status: "unresolved", and the exact attach target. The observation describes
Oracle's local record; it does not certify remote liveness or completed output.
A fresh session can show that a review may have been submitted without identifying
one recoverable conversation. APR retains a session_uncertain hold when multiple
new sessions name the same private output, a completed session lacks conversation
metadata, or observed identities conflict or change during verification. The run
stays nonterminal, retains its actual native exit and execution counters, and
cannot be retried, deferred as an ordinary busy refusal, replaced with --force,
or bypassed by restarting the queue.
apr run-status run:<workflow>:<run-id> shows the hold reason and retained
candidate IDs. Robot run-status, result, and refused resume responses expose the
same evidence as submission_hold while the run remains held. Automatic
apr attach run:... refuses an uncertain identity. An operator can deliberately
inspect a candidate with apr attach <session-id>; doing so does not clear the
hold or authorize another submission.
If the sole original completed session was missing its conversation metadata,
apr recover can harvest it after that metadata becomes available. The original
session ID and creation timestamp must still match, as must any previously
observed prompt hash. Already observed conversation identities are retained too,
including while a session is running. Substituted sessions, recreated IDs,
changed known conversations, and changed known prompt hashes cannot qualify.
A recorded conflict between multiple sessions or conversations stays unresolved
even if one candidate later disappears. Successful recovery removes the active
submission_hold from status responses and retains the original observation in
the run ledger.
A new Oracle session directory can appear before its metadata is written, or
remain after a client disconnect leaves a partial write. APR also holds the run
when a directory absent from the pre-launch inventory has missing, unreadable,
malformed, unsafe, or incomplete metadata that cannot be ruled unrelated.
submission_hold.unbound_sessions retains each directory name and a concrete
reason such as metadata_missing or metadata_invalid. These observations
do not identify a session or conversation; the selected session ID and creation
time stay null. They prevent another submission without claiming that a
particular review was accepted.
Repairing or removing unbound metadata does not clear the retained hold or authorize automatic attachment or recovery. Inspect the evidence before intervening. Existing directories and valid metadata that proves a different output destination do not cause this hold, and identified error-only sessions retain the ordinary retry behavior. A remote-only submission that leaves no observable local session artifact remains outside this detection.
The same local identity check runs when an APR worker receives SIGINT or
SIGTERM. Interrupting the client does not prove that its browser review was
canceled. A matching running review or completed conversation stays available
for apr recover; --force and queue restarts cannot submit a duplicate.
Foreground interruption still returns the signal exit (130 or 143), while the
retained run remains unresolved until recovery completes. No provider or network
call runs during this cleanup check.
The ledger distinguishes that worker exit from an observed native Oracle exit.
outcome.oracle_exit_code stays null if the worker was interrupted before it
could observe the current producer's exit; it never inherits an earlier
attempt's status or assumes success. If the producer had already exited before
an interrupted harvest, its actual exit is retained. Recovery records its own
harvest exit separately, so recovering an interrupted review does not invent a
native producer result.
APR recognizes Oracle's failing stderr diagnostics ERROR: busy and
User error (browser-automation): busy as single-flight contention. Hosts
with queued admission can return queue_full when every slot in their queue
is occupied. APR applies the same bounded busy policy to that response. Foreground
runs that exhaust their busy budget return exit 12 with APR_ERROR_CODE=busy;
a robot worker that exhausts its configured policy before the launch check
returns the JSON busy code with data.busy: true and data.policy. A worker still
retrying remains running. The final attempt determines the result, so an
earlier busy response cannot relabel a later authentication or network error.
Successful output, stdout prose and unrelated errors such as “device busy” are
not busy signals. Other failures retain the ordinary retry settings above.
Human runs wait for busy Oracle operations for up to 300 seconds, independently
of APR_MAX_RETRIES. Busy responses do not consume ordinary retries while this
wait policy is enabled. Delays double from 5 seconds up to a 30-second cap.
Each update includes elapsed time, the next delay and single-flight guidance.
--no-retry remains one-shot, including when a busy wait is configured.
# Finite busy budget; min/max delays and advisory status timeout (seconds)
APR_BUSY_WAIT_SECONDS=600 APR_BUSY_MIN_SLEEP=5 APR_BUSY_MAX_SLEEP=30 apr run 5 --wait
# Explicit unbounded wait; useful when another long review must finish first
APR_BUSY_WAIT_SECONDS=infinite apr run 5 --wait
# Disable the separate busy wait and use the ordinary retry policy
APR_BUSY_WAIT_SECONDS=0 apr run 5 --wait
# Robot workers opt into waiting explicitly; default remains ordinary retries
APR_BUSY_WAIT_SECONDS=600 apr robot run 5 --compact
Finite values are decimal whole seconds from 0 through 86400; invalid or oversized
values use the documented defaults. Min/max delays must be positive; zero min
uses 5, and a max below the min is raised to the min. APR_BUSY_STATUS_TIMEOUT
defaults to 2 seconds (zero uses the default). Status probes and sleeps consume
the same busy budget, and APR does not start a new review at/after its deadline.
A review already started is allowed to finish normally.
When timeout or gtimeout is available, APR runs a bounded no-ID oracle status
diagnostic. It lists local sessions and cannot establish remote availability;
only a successful review attempt ends contention. Probe errors/timeouts cannot
replace the producer's error. Without a bounded timeout utility, APR skips this
optional diagnostic and continues its bounded retry policy. APR never attaches
to another session while polling. Robot launch JSON includes data.busy_policy
(retry, wait, or enqueue). Use apr robot run 5 --enqueue-if-busy
to hand the round to the persistent FIFO after Oracle explicitly refuses
its first submission with busy or queue_full. This flag takes precedence
over the busy wait budget. An immediate handoff returns success with
data.status="queued" and data.queue_entry_id. If the launcher has
already returned running, use apr robot run-status <attach_target>.
The original attempt retains its busy outcome and deferred_queue_entry_id
identifies its queued successor. Use apr robot queue status to inspect it
and apr robot queue run to drain it.
Setting APR_REDACT=1 at enqueue time preserves redaction for that request,
including a later drain with the variable unset. This applies to explicit
busy handoffs and manual queue additions. A worker can also enable redaction
for entries that were added without an explicit setting.
A busy handoff records the approved review inputs and Oracle route. On drain,
APR checks the captured workflow, documents, template directive sources and
prompt before sending them to Oracle or reusing a completed answer. An edit
after the handoff produces attachment_mismatch on a fresh execution. Submit
a fresh request to review the edited inputs. Workers can apply redaction to
the originally approved sources.
If a handoff receipt is lost, repeat apr robot run N --enqueue-if-busy.
For a matching queued or running handoff, APR returns the existing queue ID
with data.reused=true. It checks the resolved documents, prompt, execution
policy, and configured route locally. A changed request, an older handoff
without a recorded fingerprint, or multiple pending handoffs for that round
returns busy with data.kind="deferred_request_conflict". Inspect the queue
before canceling or draining it. A settled cancellation or failure allows a
fresh submission. Use --resume to verify and reuse a completed answer.
Deferred entries retain the workflow, round, requested implementation flag,
ACK setting, size policy and both byte limits. An enabled strict lint or
composer verification check stays enabled on drain. The runner validates
the current project documents and supplies the remote host or pool and its
credentials. Configure that route on the runner when the destination matters.
Ordinary queue add entries use the runner's policies. An occupied local
round, a partial answer, a possibly related new Oracle session or an earlier
producer attempt prevents automatic handoff. Queue workers apply their own
busy policy. --force and --no-lint are incompatible with this option.
If the worker has already completed successfully at the launch check, APR
validates and retains its output instead of reporting a startup failure; robot
mode returns status: "completed". An incomplete or missing output is never
reported as completed. Diagnostic-capture failures stop without launching a
duplicate review.
Preview Document Metadata Without Oracle
Inspect the documents selected by a workflow without starting a review or even probing Oracle:
apr run 4 --show-manifest # Human text on stderr
apr run 4 --show-manifest --json # Deterministic JSON on stdout
apr run 3 --show-manifest --include-impl # Explicit implementation selection
The preview records each document's role, path, basename, exact observed byte
count, SHA256 and inclusion reason (required, optional, or impl_every_n).
It applies the existing workflow cadence and records skipped implementation
documents explicitly, with no invented hash or size. Duplicate basenames remain
distinct by role/path. Paths are safely quoted, JSON keys/rows have stable
ordering, and binary file contents are hashed as bytes. Invalid UTF-8 paths are
rejected rather than silently replaced.
Hash and size come from the same byte stream. They describe the current local
observation; a later writer or Oracle read may see different bytes. This
preview does not send documents, acquire a run lock, create output/log artifacts,
or assemble a review prompt. Required-file, unreadable-file and hashing failures return a
configuration error with no partial JSON manifest. --show-manifest takes
precedence over review/render flags.
Normal human and robot runs automatically prepend this observed metadata to
their review prompt, using the same selected files and inclusion reasons as the
Oracle file arguments. Templates need no metadata placeholders. Dry-run prints
the complete assembled prompt on stderr; render passes that same prompt to
Oracle's renderer and preserves its stdout. apr robot validate checks both
template variants and the selected assembled prompt, including document read
and hashing failures. Literal braces in generated JSON-quoted filenames are
escaped reversibly; unresolved template placeholders still fail prompt QC.
Oracle treats file arguments as search patterns. APR supplies private copies
with literal filenames when a configured path could be interpreted as a pattern
or option, such as docs/plan [v2].md. The manifest and replay keep the
original name, role, size and digest. Human render and dry-run use private
preview copies for these paths too.
This binding describes local observations before Oracle reads the files. It does not establish immutable transmitted bytes or model acknowledgement. Human, robot and queue execution record these observations and the final prompt hash in the persistent run ledger.
Set APR_REQUIRE_ACK=1 on a run or queue worker to ask the model to start its
answer with an acknowledgement of each selected document's role, SHA256, and
byte count. The dry run and retained prompt show the exact block. Roles
distinguish files with identical basenames. APR checks for a complete block
within the first 50 lines, accepts reordered rows and extra whitespace, and
flags missing, extra, duplicated, or mismatched entries. The ledger records
inputs.ack_requested and the completed answer's trust.ack fields
(ack_present, ack_complete, and ack_matches_manifest). A missing or
mismatched acknowledgement warns and preserves the review. A matching block
shows that the answer repeated the expected metadata. This policy is opt-in
and applies to human and robot runs.
apr stats and the dashboard list the rounds with missing or incorrect
acknowledgements. apr robot stats and JSON exports include each canonical
answer's run ID, input digests, prompt hash, and acknowledgement result.
CSV and Markdown exports also include the acknowledgement result. Detached
runs write analytics when they finish. Backfill restores trust fields when a
finished ledger matches the historical output file and its digest.
Safe Template Directives
Workflows can include additional project context directly in their instructions.
Enable directives explicitly with the top-level template_directives: true
setting. They are disabled by default. The same setting applies to template
and template_with_impl.
documents:
readme: README.md
spec: SPECIFICATION.md
oracle:
model: "5.2 Thinking"
thinking_time: heavy
template_directives: true
template: |
Review the attached README and specification against these design decisions:
[[APR:FILE "docs/design decisions.md"]]
Source digest: [[APR:SHA "docs/design decisions.md"]]
Source size in bytes: [[APR:SIZE "docs/design decisions.md"]]
Relevant implementation excerpt:
[[APR:EXCERPT src/main.rs 2000]]
| Directive | Expansion |
|---|---|
[[APR:FILE path]] |
The file's text, without added Markdown fences or headings |
[[APR:SHA path]] |
Lowercase SHA-256 of the complete file's bytes |
[[APR:SIZE path]] |
Decimal byte size of the complete file |
[[APR:EXCERPT path N]] |
The first N bytes, or the complete file when shorter; no truncation marker |
Directive names are uppercase. Each directive must open and close on one
template line; its expansion can span several lines. Use a simple single- or
double-quoted path for spaces. Quotes only delimit a path: APR does not expand
shell variables, wildcards, commands, or escape sequences. For an excerpt, N
must be a positive decimal integer of at most nine digits. An excerpt that cuts
through a UTF-8 character fails validation; choose a complete character boundary.
Paths resolve from the project root. Absolute paths, .. path segments and
symlink escapes are refused; symlinks that resolve inside the project are allowed.
Every directive requires a readable regular text file. Missing, unreadable,
binary or invalid UTF-8 inputs fail before Oracle starts. EXCERPT bounds the
amount of context included; APR does not silently trim an oversized inclusion.
APR checks two local byte budgets before provider discovery. The exact final
-p argument, including the manifest and expanded instructions, defaults to
120,000 bytes (APR_MAX_PROMPT_BYTES). The entire review bundle defaults to
200,000 bytes (APR_MAX_BUNDLE_BYTES): exact -p bytes plus the raw bytes of
every selected README, specification and implementation attachment, plus a
4,096-byte framing reserve per attachment. An unselected or absent optional
implementation contributes no bytes or reserve. Content repeated through a
FILE directive and an attachment counts in both places because both are sent.
The framing reserve allows for Oracle's file headings and separators. It is
an explicit allowance, not a measurement of Oracle's final browser payload;
provider versions and UI limits can differ. APR reports exact supplied content
bytes separately from this reserve. Neither budget guarantees acceptance by
every provider or operating system. Raising the bundle limit leaves the
independent -p limit in effect.
Set either environment variable to a positive decimal byte count of at most
nine digits to change its limit. The default APR_SIZE_POLICY=strict refuses
oversized runs locally with an actionable finding before any Oracle probe or
review starts. Shorten selected documents, omit optional implementation
context, use EXCERPT for large directive inclusions, or choose one of the
explicit policies below. The existing --no-lint bypass skips both budgets
and records that choice; it requires the default strict size policy. Queue
workers always run local validation under their selected size policy.
Lint's resolved object and robot render's data object report prompt_bytes,
max_prompt_bytes, and bundle_budget. The latter contains prompt_bytes,
attachment_bytes, their sum content_bytes, framing_reserve_bytes,
per_file_framing_reserve_bytes, total_bytes, max_bytes, and
per_file_bytes (role, path and byte count for each selected attachment).
Its accounting value is content_plus_framing_reserve. Human lint and run
output print the same component counts to stderr. Run ledgers retain this
observation under validation.bundle_budget for accepted and refused runs;
explicitly bypassed validation records null. Retained copies and prompt hashes
are checked against the accepted observation before a producer can start, so
files growing after validation cannot silently substitute a larger bundle.
Oversized review policy. Set APR_SIZE_POLICY explicitly when you want
another response to an oversized review:
| Policy | Behavior |
|---|---|
strict (default) |
Refuse a prompt or complete bundle above its configured limit. Preserve every source byte. |
warn-only |
Report the same budget findings as warnings and preserve every source byte. --fail-on-warn still promotes those warnings to errors. |
auto-trim |
Reduce selected document prefixes deterministically until both limits fit, or refuse if the preserved content cannot fit. |
# Inspect the exact prompt and transformation decisions without Oracle.
APR_SIZE_POLICY=auto-trim apr robot render 1 --compact
# Execute with the same explicit policy and independent byte limits.
APR_SIZE_POLICY=auto-trim apr run 1 --wait
APR_SIZE_POLICY=auto-trim APR_MAX_BUNDLE_BYTES=180000 apr queue run --until-empty
# Inspect an oversized bundle while retaining all its content.
APR_SIZE_POLICY=warn-only apr lint 1 --json
Auto-trim reduces the selected implementation document first, then the specification, and README last. It preserves the longest UTF-8 prefix that fits at the selected step, backing off an incomplete final character. Each reduced document includes an explicit marker such as:
--- TRUNCATED: "SPECIFICATION.md" (kept first 24000 bytes of 180233) ---
The marker's bytes, any repeated inclusions, and the framing reserve count
toward the budget. The manifest and review instructions are never shortened.
Original project files remain unchanged: execution sends independent private
copies. Human --dry-run, --render, and --render --copy under auto-trim
retain the exact preview files, prompt, manifest, and size plan in a private
.apr/previews/review.*/ directory and use those copies for Oracle rendering.
FILE, SHA, and SIZE directives referring to a selected, reduced document
use its transformed bytes, including when an in-project symlink or alternate
relative spelling identifies the same file. An explicit EXCERPT path N
continues to mean the first N bytes of the original file; auto-trim does
not change that authored cap. Other included files and the instruction text
remain intact. If these fixed contributions prevent the request from fitting,
APR refuses before provider discovery and asks you to shorten them or change
the limits. When trimming is necessary, APR also refuses a single physical
source assigned to multiple document roles, because the trimming priority
would be ambiguous; ordinary reviews that already fit retain that support.
Lint and robot render expose size_policy alongside the exact byte budgets.
It records the mode, both limits, the original source manifest, and each
selected file's original and sent hashes and byte counts, retained prefix
length, and marker size. Reduced manifest rows carry the same original
observation in trim; their ordinary bytes and sha256 describe the sent
copy. Run ledgers, replay, and execution analytics retain this policy. An ACK
requests the sent hashes, and replay verifies the retained sent bytes without
reading today's source files. Full original hashes also bind discarded tails:
a source change during capture refuses the run. For records with a retained
size policy, --resume requires the same source observations, policy, and
limits even when the retained prefix would be unchanged. The metadata
preserves the original digest; replay does not reconstruct discarded source
content.
Both warn-only and auto-trim require local validation and cannot be combined
with --no-lint. Neither policy changes provider limits or guarantees that a
browser will accept a bundle; warn-only can still encounter an operating
system argument limit or provider rejection.
Expansion is a single pass over authored template text. Included contents are
never interpreted as more directives. An unknown or malformed directive, a
reserved [[APR: token left in the final prompt, or a directive used while the
setting is disabled is a fatal error. Reserved directive tokens are checked
inside code fences too; there is no literal-escape form. To discuss the syntax
in a prompt, spell out the delimiter in words instead of including that token.
Other placeholder checks run on the expanded prompt with the existing QC
settings, so an included file cannot silently introduce an unfilled placeholder.
Errors identify the template and directive line where possible.
Preview the expanded instructions before sending the review:
apr lint 1 --json
apr robot render 1 --compact
apr run 1 --dry-run
Lint and robot render stay offline without probing Oracle. Human dry-run may query the installed Oracle's supported flags to display its command, without starting a review.
Lint and robot render report whether directives are enabled. Robot render's
data.prompt contains the complete expanded instructions and data.prompt_hash
binds those bytes. Human, robot and queue execution use the same expansion and
final quality checks. Real runs record inputs.template_expansion in the ledger:
the enabled flag, directive count, and each directive's type, path, template line,
source byte count, source SHA-256 and emitted byte count. These records describe
the context used to build the retained prompt; they contain no file bodies.
Exact replay preserves the already-expanded prompt. It does not reread the
current supporting files or expand directives again, so changing or removing
the original context after a run cannot change its saved prompt. Replay also
reports template_expansion. Supporting context included through directives is
part of the prompt, while the document manifest and optional acknowledgement
continue to describe the selected documents.* attachments.
Migrate Legacy Workflow Templates
Use the offline migration command to replace older document placeholders with safe file directives:
apr workflow migrate -w my-protocol # Preview a diff and validate it
apr workflow migrate --all # Preview every workflow
apr workflow migrate -w my-protocol --apply # Review, then confirm interactively
apr workflow migrate -w my-protocol --yes # Explicitly apply without prompting
apr robot workflow migrate --all --compact # Structured preview
apr robot workflow migrate --all --yes --compact
Migration recognizes {{README}}, {{SPEC}}, and {{IMPL}} in the
top-level multiline template and template_with_impl blocks, including
case and surrounding-space variants. Each becomes a literal
[[APR:FILE "<configured document path>"]] directive, and the candidate
workflow enables template_directives: true. Private nested mappings and
unrelated settings are preserved. Unknown or incomplete placeholders, missing
role mappings, unsupported scalar templates, and paths that cannot be expressed
safely require manual correction. A single leading --- and trailing ...
document boundary is preserved; multiple YAML documents and % directives
require manual migration.
Both implementation selections pass through the normal offline validator before an apply is allowed. This includes directive expansion, placeholder checks, document policy, and prompt/bundle budgets. A newly included document that contains unresolved placeholders or exceeds a budget therefore blocks the migration rather than weakening lint. No Oracle discovery, network request, or review is performed.
The default command leaves workflow files unchanged. It retains private
candidates, exact original copies, diffs, and validation reports under
.apr/migrations/migrate.*/ for inspection. --yes explicitly authorizes
application; --apply requires an interactive confirmation and is refused
without a terminal. Repeating migration on an already migrated workflow leaves
its bytes unchanged.
--all validates every candidate before changing any workflow. Apply
preserves each file's permissions, checks that the source still matches the
reviewed original, and replaces each workflow atomically while retaining its
backup. If a later file cannot be published, earlier successful writes remain
recorded in applied/applied_count and the per-workflow results; inspect
those results and the retained originals before retrying. Robot responses and
human --json output include the paths, diffs, replacement counts, validation
results, and per-workflow apply status.
Run Ledger Contract
The ledger contract is version 1.0.0. Its canonical path is
.apr/rounds/<workflow>/round_<N>.meta.json, independently of a custom output
directory. A run has an immutable run_id; its workflow, round and slug identify
the selected review. A later run must preserve the earlier ledger as a separate
run record before publishing the new canonical record. Optional fields may be
added within version 1; removing or renaming fields requires a major version
change. Readers reject unsupported versions and contradictory outcomes.
The writer retains each private record candidate, atomically renames a hard-link
alias in the canonical directory, and retains the previous terminal record in
the next run's private .apr/runs/<workflow>/round_<N>.* directory. A stable lock
file is never unlinked. A new run refuses to replace a started record; updates
compare both run identity and the entire previous record to reject stale writers.
Malformed candidates and failed publication leave the canonical bytes intact.
This protects whole JSON records against process interruption; it does not claim
power-loss durability or a transaction spanning multiple files. Kernel locking
requires flock or BSD lockf and fails closed if neither is available.
The required fields are:
| Field | Meaning |
|---|---|
schema_version, run_id, workflow, round, slug |
Version and run identity; round is a nonnegative integer |
state |
started, finished, failed, or canceled |
started_at, finished_at, duration_ms |
UTC RFC3339 timestamps; finish and duration are null until terminal |
config.path, config.sha256 |
Configured workflow path and observed config bytes digest; null until available |
inputs.status |
pending, complete, or failed; unavailable metadata never receives an invented hash |
inputs.files[] |
Role, configured path, basename, observed bytes/SHA256, included boolean, inclusion_reason, and skip_reason |
inputs.manifest, inputs.prompt_hash |
Original observed manifest and SHA256 of the exact final -p argument bytes, with no added newline |
invocation |
Browser engine, model, thinking time, sanitized remote host, flag names and redacted Oracle args |
execution |
attempts_count, ordinary retries_count, busy_wait_count, busy_wait_total_ms, retry_reasons[] |
outcome |
ok, canonical code, actual caller exit_code, native oracle_exit_code, and output path |
Included files have nonnegative byte sizes and lowercase SHA256; skipped optional
files have null sizes/hashes and an explicit reason. A complete observation has
one README, one specification and one implementation row (possibly skipped),
the manifest and the final prompt hash. Metadata failures may retain partial
observations with inputs.status: "failed"; they never claim a complete bundle.
Input hashes remain local observations rather than immutable sent bytes.
The inline manifest retains the shared helper's reason and display path;
ledger file rows use inclusion_reason and the configured path. An optional
display_path records a differing normalized display name. After that explicit
mapping, all three rows must agree on role, basename, bytes, hash, inclusion and
skip reason; an unrelated three-row manifest is invalid.
Started records have null finish/duration and null outcome ok/code/exit_code.
Successful records require state: "finished", complete observed inputs,
ok: true, code: "ok" and exit 0. Failed/canceled records require a finish
timestamp, duration, ok: false, a non-ok code from APR's existing taxonomy and
a nonzero exit. Cancellation uses internal_error with the actual signal exit
(for example 130), with a separate interruption reason when available. Native
Oracle status is retained separately from the caller exit; legacy human and
robot exits may differ until the broader error-contract work is complete.
If a background worker finishes before its launcher returns, the launcher reads
that exact run's retained outcome. Recovery/storage errors and worker signals
keep their recorded code and exit status; a completed producer is not reported
as a failure to start. Robot failures include the run/result reference, retained
outcome and execution counters, log path, and observed worker_exit_code.
An interrupted terminal publication remains unresolved (busy) until its
evidence can be reconciled. Use the same result reference to inspect the review
without submitting another one.
Remote hosts contain only host/port authority, never user information, URLs,
query parameters or tokens. Ledger metadata embeds no environment dump, raw
configuration, cookies or prompt body. Oracle arguments redact authentication values
and the prompt body; the prompt hash binds the latter. Attempt counts include
every actual producer launch; retry counts exclude busy-policy retries. Busy
wait duration measures status-probe/sleep time, not useful model execution, at
the available clock resolution. Optional warnings, overrides, trim and
redaction fields may extend the record without changing these meanings.
The executable ledger_validate check and state fixtures exercise this contract.
ledger_write_start, ledger_bind_inputs, ledger_write_finish_success and
ledger_write_finish_error provide the shared writer API. Writer tests exercise
real files, separate-process interruption, both kernel lock backends, publication
failure and concurrent readers. Human and robot execution now write started
observations before the producer and terminal records after validating its own
fresh output. Detached launch acknowledgement is separate from terminal success;
robot launch data includes ledger_path, run_id and run_record_path. The last
path names the immutable terminal record once the worker finishes. A worker owns finalization
after its parent exits. Early refused runs retain partial failed records, and a
busy contender retains a private attempt.meta.json without replacing the active
run. Manifest previews, dry runs and renders create no execution ledger.
Each run writes to its own private output sink. An earlier public answer is copied
into the new run directory before execution; a producer that writes nothing cannot
reuse that answer as its own successful result. Useful prior answers and new partial
answers are retained, including when automatic recovery fails. A successful human
rerun saves a distinct round_<N>.<run_id>.md result while retaining the earlier
public answer. Publication uses an atomic non-overwriting hard link: an arriving
peer file blocks publication, and a failed producer cannot replace a good answer. A native
Oracle success with incomplete output is a failed APR result. Robot diagnostics
use unique private log files rather than replacing an earlier run's log. These
checks use APR's existing output-completeness heuristic; they do not establish
that a live model answered correctly or acknowledged immutable attachments.
Producer stderr, the session marker, harvested answers and harvest diagnostics remain in the private run directory. Successful recovery retains the initial producer partial and the harvested answer before selecting the latter. Failed recovery retains both partial answers. Raw Oracle diagnostics may contain sensitive console output; they are private local artifacts and are not embedded in the redacted ledger or public JSON.
Successful runs also retain output_observation.sha256 and bytes. Queue
execution adds queue_entry_id, binding the actual run to its durable request.
New executions retain a private input bundle for deterministic local replay
after original files or templates change or disappear. This pins local producer
input bytes; it does not establish live model acknowledgement.
Exact Input Replay
apr replay 4 --json # Validate saved bundle; metadata only
apr replay 4 --json --include-bytes # Export exact prompt/doc bytes as base64
apr robot replay 4 --compact
apr replay .apr/runs/default/<run-id>/terminal.meta.json --json
Each real human/robot/queue execution captures selected independent document
copies under .apr/runs/<workflow>/<run-id>/inputs/<role>/<original-basename>.
Role directories distinguish duplicate basenames. Every producer and retry uses
those saved paths and the same final prompt, preserving configured/display
identity, inclusion reason and file order in metadata. Capture verifies the
accepted document hashes and resolved routing/selection; conflicting concurrent
changes fail before a producer. Previews still create no execution bundle.
The private prompt.txt preserves the exact -p bytes. A safe config.yaml
retains APR-applied scalars and template blocks, excluding unknown authentication
keys and unrelated comments. Its digest is distinct from the digest of the
single observed original configuration stream. bundle.json binds run identity,
the manifest, saved file sizes/hashes, safe resolved configuration and prompt
digest. Ledger replay references that completed descriptor by path and SHA256;
public metadata contains no raw input/configuration/prompt body or credentials.
Saved files have private, read-only modes. Partial failed captures are retained.
Replay resolves the bundle relative to the retained canonical/private record, including historical generations and invocation from another working directory. It validates every saved file/hash and run/manifest binding, refuses symlinks, and never rebuilds with current templates or falls back to changed live files. Legacy hash-only records, missing snapshots and changed saved bytes fail clearly. No Oracle, package fallback, update probe, network call or paid review occurs.
--include-bytes explicitly exports private document and prompt contents; keep
that export private. Without it, both human and robot JSON report verified
metadata only. Original raw configuration is not exported. This reproduces
local producer inputs, including binary bytes and trailing newlines, rather
than promising identical future model responses, browser/model ACK, authenticated
custody against an owner rewriting hashes, or power-loss durability.
Private Diagnostic Bundles
Export the retained evidence for one exact run without contacting Oracle:
apr bundle run:default:round_5.ABC123
apr bundle run:default:round_5.ABC123 --json
apr robot bundle run:default:round_5.ABC123 --compact
Use the actual attach_target returned by the run. APR writes a private directory
under .apr/bundles/<workflow>/<run_id>/<ledger-sha256>/, builds it away
from the published path, and publishes it only after checking every file.
Repeated requests verify and reuse that snapshot; later ledger versions receive
different directories. A snapshot of an active run remains a snapshot of that
moment. Use apr run-status to query its current state.
Each bundle contains the manifest, applied configuration, sanitized Oracle
arguments, a ledger projection, outcome/timing/counter metadata, a log inventory,
and a bundle.json index of payload byte counts and SHA-256 values. When
input_snapshot is complete, it also includes the exact verified retained
prompt.txt and selected document bytes under documents/. The original
paths and any input transformations remain in inputs.meta.json.
Unavailable or altered retained inputs produce a clearly marked metadata-only
bundle; APR never substitutes today's project files.
Logs come only from APR's own known capture files. stderr.log contains
bounded diagnostic excerpts and combined.log contains retained robot output
when available. Foreground stdout was not retained, so stdout.log is empty
and the inventory states that limitation. Excerpts remove recognized credential
lines and private-key blocks before keeping the final 64 lines per capture
(up to 1,000 bytes per line). No environment dump, browser cookie files, or
Oracle internal session files are copied.
Keep these bundles private. Prompt and document bytes are intentionally exact, and other project secrets may appear in inputs or logs. Log filtering is best effort; inspect every file before sharing. Bundles provide local integrity checks, not authenticated evidence of browser delivery.
To request a diagnostic snapshot when a retained run fails:
APR_BUNDLE_ON_FAIL=1 apr run 5 --wait
APR_BUNDLE_ON_FAIL=1 apr robot run 5 --compact
The failure hook runs after APR retains the failure record and prints the bundle path to stderr. If capture fails, APR keeps the original run outcome and evidence. Successful runs do not create automatic bundles. Failures that occur before a usable run record exists may have no exportable diagnostic snapshot.
Verified Resume and Reruns
Use --resume when restarting an interrupted command or requesting a round
that may already be complete:
apr run 5 --resume
apr robot run 5 --resume --compact
A completed result is reused offline only when its retained terminal record,
selected document manifest, prompt/configuration hashes, model/thinking settings,
remote host, and published output bytes all match the current request. The
original run ID and provenance are preserved; robot output reports
status: "completed" and reused: true with zero new producer attempts.
No Oracle discovery or update check is needed for this reuse.
If a worker exits after publishing its terminal ledger but before retaining the private terminal record, resume and queue restart can repair that interrupted publication offline. APR requires the round lock, a dead recorded owner, an intact retained input bundle, and unchanged canonical ledger bytes. Successful answers must also match their original output location, byte count, and digest. The repair retains the exact terminal record without changing the ledger or answer, or starting another review. Failed terminal outcomes with complete retained inputs can likewise be reconciled by the queue and retain their original failure. Conflicting private records fail validation instead of blocking queue restart in a polling loop.
If there is no prior output or run record, --resume starts the ordinary
validated run. Changed, unverified, or incomplete evidence is refused instead
of silently starting another review. A started record remains busy even if
its local PID has exited, because the remote browser may still be running.
The response includes a retained-run attach target such as
apr attach run:default:round_5.ABC123; this is a lookup reference, not a
claim that a particular Oracle session is currently alive.
Noninteractive direct runs now refuse occupied outputs by default. To deliberately request another review, use:
apr run 5 --force --wait
apr robot run 5 --force --compact
A forced rerun preserves the original answer and publishes its own separately
named answer. It does not bypass active run ownership or local validation.
--resume and --force are mutually exclusive. Queue reuse follows the same
completed-result verification as direct resume.
After a successful rerun, show, history, diff, integrate, and their robot
equivalents select the latest successful published answer for that round.
They follow the retained run lineage and verify the answer's path, byte count,
and SHA-256. A newer failed or still-running attempt leaves the preceding
successful review selected. A missing, changed, or unsafe latest successful
answer is an error; APR will not silently integrate an older review instead.
An answer from a failed first attempt is kept for diagnosis but is excluded
from review history and integration. Legacy archives without a run ledger
continue to use their original round_N.md files.
Analytics also use the latest successful answer, retaining one entry per
logical round. Rerunning an earlier round refreshes its successor's comparison
and the convergence calculation. backfill --force uses the same verified
selection and checks all selected answers before replacing existing metrics.
Original answers and each attempt's run records remain available on disk.
Inspect a retained run offline
Use the exact attach_target returned by a robot launch or resume response
to poll that run, independently of newer attempts for the same round:
apr run-status run:default:round_5.ABC123
apr run-status run:default:round_5.ABC123 --json
apr robot run-status run:default:round_5.ABC123 --compact
The result is a read-only snapshot of APR's local ledger. status is
running (the recorded local PID is signalable), unresolved (no such
observation), publication_pending (terminal canonical record exists but
its private copy is not published), completed, failed, or canceled.
PID reuse, permissions, and remote browser state cannot be established by
this check; remote_liveness remains unknown. No Oracle discovery,
update request, session probe, new review, or ledger repair occurs.
Controllers should wait for data.terminal and inspect data.outcome.
Only completed with output_verified: true means the saved successful
output currently matches its recorded byte count and SHA-256. Altered or
missing output returns config_error and status: output_unverified.
A valid recorded failed or canceled execution is a successful status query
with its original outcome nested in data.outcome; the query exit code is
not the review's exit code. The result includes the original execution
counters, queue entry ID, and exact record path, not prompt or document
contents. Historical generations use their own private terminal records,
never a newer round's answer. Conflicting or unsafe records fail closed.
Input custody can be independently reverified using apr replay.
To collect the answer from the same run, use the launch response’s
result_target. An ordinary launch also returns that run reference in
attach_target. This also works after a forced rerun has replaced the current
generation for that round.
apr result run:default:round_5.ABC123 --wait > review.md
apr robot result run:default:round_5.ABC123 --timeout 120 --compact
The human command writes the verified answer bytes to stdout. Robot mode
returns the same answer in data.answer.content, alongside its SHA-256 and
byte count. For non-UTF-8 data it uses content_base64. The default is a
single check. --wait follows the run and --timeout SECONDS sets a limit on
waiting. A timeout returns busy and leaves the review running. A failed or
canceled review returns its recorded failure code.
A detached run can encounter a busy provider after returning a run reference.
Its run-status and result responses then include deferred_result_target
once APR verifies the corresponding queue entry. The original reference still
reports the admission attempt. Pass deferred_result_target to apr result
to follow the queued request.
A deferred admission or manual queue addition returns a result_target such
as queue:default:entry-.... Pass it to apr result or apr robot result.
The target stays valid when another caller drains the queue, when the request
reuses an earlier paid review, and after a forced rerun of the same round.
target=$(apr robot queue add 5 --compact | jq -r .data.result_target)
apr result "$target" --wait > review.md
apr robot integrate "$target" --compact | jq -r .data.prompt > integration.md
Result collection reads the queue history. A separate apr queue run drains
the queue. The timeout covers the entire wait. Cancellation returns canceled
(exit 1), and a failed entry returns its recorded failure code. A successful
result includes the request’s queue entry ID and the exact paid run ID.
Stream a review's progress
Set APR_EVENT_LOG=1 when starting a human, robot, or queued review to retain
progress in the private run directory. Use the exact attach_target from the
launch response to read the JSONL from another terminal.
APR_EVENT_LOG=1 apr robot run 5 --compact
apr tail run:default:round_5.ABC123 --follow
apr tail round_5.ABC123 -w default | jq -c 'select(.event_type=="producer_exited")'
Each line includes event_version, a UTC timestamp, workflow, round,
run_id, event_type, and fields. Events record the start of a run, input
binding, each producer launch intent and observed exit, busy and retry waits,
a session held for recovery, and the published ledger outcome. The native
producer exit and the overall review outcome have separate events. An empty
or interrupted timeline can end before either observation. Check run-status
for the authoritative ledger and output verification.
apr tail prints existing events and exits. With --follow it also streams
subsequent events through the terminal outcome. Ctrl-C stops observation.
A run held for recovery can remain open until a later apr recover. Logging
is off by default. A logging failure warns and the review continues. Events
contain run identifiers, timings, counters, and outcome codes. The prompt,
document contents, provider arguments and diagnostic text stay out of the stream.
Recovering an orphaned review
APR records the worker's process start time and boot identifier when available.
A reused PID from the same boot can then be recognized by run-status,
queue recovery and terminal repair. owner_identity_status distinguishes a
matching process, a reused PID and a PID-only observation on older records.
If the local APR worker stopped after submitting a review, use its retained run reference to recover the original completed Oracle session:
apr recover run:default:round_5.ABC123
apr recover run:default:round_5.ABC123 --json
apr robot recover run:default:round_5.ABC123 --compact
apr queue run --once # Reconcile a queue entry held by that run
Use the actual reference from the run/resume response. Recovery requires the
round lock, a dead recorded worker, the current matching run ledger, intact saved
inputs, and one verified Oracle session bound to that run's private output.
When APR retained a running session after a client disconnect, recovery also
requires that exact session ID and creation time; a later session cannot replace
it even if Oracle has pruned the original metadata.
Restore the original ORACLE_REMOTE_HOST for a single-host remote review. For
a pooled review, recovery accepts the original ordered ORACLE_REMOTE_POOL
and a configured ORACLE_REMOTE_TOKEN. It restores the host recorded by the
producer, including during queue run --recover, without probing the pool.
An explicit ORACLE_REMOTE_HOST must match the recorded selection. Oracle
harvest uses the session's saved browser connection and conversation;
that connection must be reachable from the recovering machine. APR harvests that
session without submitting another review or rebuilding inputs from today's files.
Live ownership, uncertain session identity, changed evidence, conflicting output,
and incomplete harvests leave the run unresolved with its existing files retained.
A successful recovery publishes the answer and terminal ledger for the same run ID, allowing resume and queue restart to reuse it normally. Forced reruns retain the prior public answer and publish their distinct result. Verified capture evidence is retained before publication, so an interrupted recovery can finish offline; repeating a completed recovery also verifies and returns the retained result without contacting Oracle. Recovery refreshes analytics from the selected successful result, including a forced rerun, and recomputes the next recorded round's comparison. Repeating recovery repairs interrupted analytics updates from the same verified inputs and answer.
Execution counters come from the last durable launch checkpoint. Older runs
without those checkpoints are explicitly marked legacy_record, so their counts
may be incomplete. Recovery preserves an observed native producer exit, such as a
client-disconnect failure; an unobserved exit remains null. The harvest's
successful exit is recorded separately under recovery.
These checks establish local input/session/output identity, not review quality.
Recovering an answer after a terminal failure
A review can be retained as failed after its first automatic harvest fails or returns incomplete output. Once the original conversation can be harvested, use the same installed command:
apr recover run:default:round_5.ABC123
apr robot recover run:default:round_5.ABC123 --compact
# Use the result_target returned by recovery:
apr result recovery:default:round_5.ABC123 > recovered-review.md
apr robot result recovery:default:round_5.ABC123 --compact
apr robot integrate recovery:default:round_5.ABC123 --compact
For a failed terminal run, recovery saves an independent answer and publishes
a separate recovery:<workflow>:<run-id> receipt. The original producer's
failure, its execution counters, public round output, and any failed queue entry
keep their recorded state. The recovered result reports new_producer_attempts: 0
and retains the original producer_outcome alongside the successful recovery.
run-status and the original run's result expose recovered_result_target
when that receipt verifies; collecting the original run still returns its
recorded failure.
Recovery requires intact saved inputs, the run's terminal record and creation evidence, the round lock, and a worker that is no longer active. It checks the original Oracle route and exact session/conversation, including the identity retained by a previous automatic recovery attempt. A later rerun does not prevent harvesting the older failed generation, and its newer answer and ledger stay intact.
Repeated recovery and collection verify the receipt, retained input bundle, session evidence, harvest confirmation, and answer digest locally. They can reuse an existing successful recovery without contacting Oracle, even after the original session metadata is gone. Changed or redirected evidence is rejected. A failed harvest keeps its diagnostics and permits a later explicit attempt against the same verified conversation. No new model review is submitted.
Persistent Queue and Local Lint
apr lint 1 --json # Local checks; no Oracle or update probes
apr queue add 1 # Prints the stable request ID on stderr
apr queue add 2 --include-impl
apr queue status
apr queue run # FIFO until empty; waits for each result
apr queue run --once # Process one request
apr queue run --recover # Harvest verified orphaned reviews and continue draining
apr queue run --max 5 # Bound the number processed
apr queue cancel <entry-id> # Retain history and any active worker
apr queue retry <entry-id> # Requeue a verified busy refusal; keeps its result target
apr queue doctor --json # Inspect state and trailing-record warnings
apr robot queue add 3 --compact # Same operations in the robot JSON envelope
apr robot queue run --until-empty --compact
All commands accept --workflow NAME. Human --json emits raw data; robot
commands use ok/code/data/hint/meta. Local lint returns typed errors[] and
warnings[], source paths, resolved document selection and observed hashes.
It checks both template variants, selected files and the assembled prompt.
The queue uses the same locally validated robot execution path and shared
ledger/output/busy helpers. robot validate uses the same offline decision and
canonical codes. It preserves legacy message arrays and exposes the identical
typed core result in data.findings. Oracle readiness is checked when execution
starts, rather than making offline validity depend on an installed provider.
Queue commands reject preview/render/copy flags before executing or changing
requests; use lint or run --show-manifest for an offline preview.
Local validation policies
Use apr workflow explain --workflow NAME --round N to see which documents
and template a round selects, the model and thinking time, the Oracle session
slug and the output file. This uses local inputs and can run offline. Add
--include-impl to preview an explicit implementation request. For automation,
--json and apr robot workflow explain expose the settings under resolved
in the local validation result, along with any errors and warnings.
History, show, diff, integrate, statistics and backfill read reviews from the
workflow's rounds.output_dir. Archived workflows without this setting use
.apr/rounds/<workflow>. Run ledgers and replay records have their own paths
under .apr.
apr lint --round 1 --json
apr robot validate 1 --compact
apr run 1 --fail-on-warn --wait
APR_FAIL_ON_WARN=1 apr robot run 1 --compact
Human/robot execution and dry/render previews use the shared local validator
before provider discovery. Errors identify files, best-effort YAML lines,
prompt line hits and remediation. Required selected documents must be nonempty.
By default, selected documents below64 bytes warn; customize per-role scalars
readme_warn_bytes, spec_warn_bytes, implementation_warn_bytes (for example
under lint:). A zero warning threshold permits intentionally tiny nonempty
documents. Optional readme_strict_bytes, spec_strict_bytes, and
implementation_strict_bytes add fatal minimums in strict mode. Thresholds and
normalized round/cadence values must be nonnegative integers of at most nine
digits. Invalid policy values are errors even for an unselected document role.
--fail-on-warn or APR_FAIL_ON_WARN=1 promotes every remaining warning to a
fatal finding, including a missing prior review.
Lint reports unknown or misplaced workflow settings at their YAML line. APR
accepts the documented documents, oracle, rounds, and lint sections
and legacy flat settings. Duplicate declarations of a recognized setting
fail validation, including a flat key repeated inside a section. Put custom
instructions in a template: | or template_with_impl: | block. YAML-like
examples inside those blocks stay part of the instructions.
APR warns once for an unknown mapping and ignores its contents when
selecting settings or retaining configuration for replay.
QC rejects unfilled mustache markers, ${VAR}/uppercase $VAR, high-signal
<REPLACE_ME>/<INSERT>/<FILL_ME>/<YOUR_NAME> markers, TODO: and TBD.
Default QC ignores actual backtick/tilde fenced examples; strict mode scans
their contents. Closing fences must match their opening type and width.
Inline backtick spans and indented code do not open fences. Fence info strings
are checked for placeholders even when literal code bodies are excluded.
APR_QC_SCAN_FENCES=1 enables that scan independently. Explicitly set
APR_QC_SHELL_PLACEHOLDERS=0 for literal shell-variable discussions, or
APR_QC_IGNORE_QUOTES=1 to skip blockquote examples. For isolated literal
tokens use newline-separated APR_QC_ALLOW_TOKENS; allowing $FOO does not
allow $FOOBAR. Legacy APR_ALLOW_CURLY_PLACEHOLDERS=1 permits curly syntax
only. Template variants and final generated prompts are checked. JSON-quoted
manifest filenames escape marker characters without altering actual names;
authored lines resembling metadata are still checked.
Set APR_VERIFY_COMPOSER=1 to check the material Oracle prepares for a browser
review. APR asks Oracle for its local --dry-run json preview after retaining
the selected inputs. It checks the instructions, document order, section paths
and text (including Oracle's line-number formatting) and measures the composed
UTF-8 bytes against APR_MAX_BUNDLE_BYTES. This catches omissions and the size
overhead of many short lines before submitting a review. Verification requires
UTF-8 documents and an Oracle version that emits the browser preview JSON.
Unrecognized formats and mismatches stop the run. A verified run can be reused
offline with --resume. The ledger and robot run-status retain the local
preview outcome. A preview rejection retains the locally accepted input hashes
and files. Use apr replay to inspect those inputs or apr bundle to collect
them with the failure details, even after editing the working documents. Its
execution counter stays at zero until a producer actually starts.
When Oracle retains a browser transcript, APR compares its prepared prompt with
the verified preview. The check binds the transcript to the run’s private output
path, the recorded artifact digest and the complete published answer. The
composer_transcript field in robot run-status records matched, mismatch,
unavailable or unverifiable. A confirmed mismatch blocks round reuse and
integration, and resets the sequence used to recommend stopping. The review
remains available through apr show. This evidence covers the prompt Oracle
prepared. The provider’s receipt of the prompt is a separate observation.
Lint scans the assembled prompt and selected outgoing documents for common
credential formats, including private-key headers, AWS access key IDs, API and
GitHub tokens, Slack tokens, and bearer authorization headers. Each warning
identifies the input, line, and credential family. JSON includes up to eight
matching lines per input as line numbers and family names. Fenced examples
are scanned because their contents also go to Oracle. Auto-trim scans the
retained prefix. A finding warns by default and blocks submission with
--fail-on-warn. For an intentional public test fixture, set
APR_SECRET_SCAN_ALLOW_SHA256 to its outgoing SHA-256 from the manifest
(one digest per line). Approval expires when the input changes. Review the
outgoing material before approving it. The check recognizes specific patterns
and leaves submitted bytes intact by default.
Set APR_REDACT=1 to replace recognized credentials before rendering,
copying, or running a review. APR masks matches in selected documents,
prompt templates, and directive text before applying excerpt or auto-trim
limits. A private-key opening marker masks through the closing marker
or the end of the document. Each included manifest row records the original
SHA-256, original byte count, and per-family match counts in redaction.
Its top-level SHA-256 and byte count describe the bytes prepared for review.
The run retains those prepared bytes for replay. With the same setting,
apr integrate and apr robot integrate mask credentials in the selected
review before exporting the coding-agent prompt, including reviews archived
before redaction was enabled. Project files and archived answers remain untouched.
Review the rendered bundle for credentials outside these patterns.
Models outside 5.2 Thinking/gpt-5.2-pro and missing or lighter thinking time
produce concrete policy warnings. Setup's strong/heavy defaults remain quiet.
Intentional experiments can set APR_ALLOW_NONPRO_MODELS=1 and/or
APR_ALLOW_LIGHT_THINKING=1. Run ledgers retain fired policy warnings, override
categories and strictness, including refused attempts; no environment dump or
raw prompt is added. These are local quality heuristics, not model-quality proof.
--no-preflight skips legacy readiness extras while retaining local lint.
Direct run --no-lint explicitly bypasses local policy, warns, and records
validation.bypassed; required attachment custody and round bounds still apply.
Queue entries always apply lint, even if the caller set APR_NO_LINT=1.
History is .apr/queue/<workflow>.events.jsonl: version 1.0.0, UTC timestamp,
monotonic sequence, event ID, workflow and entry ID on every whole-line event.
enqueue records round and implementation selection; start records controller
identity/time; bind pins run identity and private terminal record; finish
and fail retain observed outcome, execution counters and diagnostic digest.
An explicit retry records the refused run's identity, terminal-record digest,
execution counters and accepted input policy. Folded queue status retains each
earlier binding in retry_history while the same entry returns to queued.
bind_before_submit on a start means the controller must persist its run ID
before submitting to Oracle. If that controller stops before allocating a run,
the next runner checks for a ledger or binding and records release when both
are absent. The original request keeps its FIFO position and a canceled request
stays canceled. Earlier claims with an uncertain launch remain held.
cancel preserves scheduling precedence; a started worker may finish and its
useful result is still audited with execution_status. Canceling queued work
prevents execution. Canceling started work never kills or replays it.
Short mutations serialize on the stable .apr/.locks/queue.<workflow>.lock.
One controller owns .apr/.locks/queue-runner.<workflow>.lock; its detached
worker inherits that ownership through completion. Stable lock files and private
pending events are retained. Reads tolerate a trailing partial/invalid record
and warn; writes repair only an exact raw-byte prefix of one retained valid
next event. Unknown or ambiguous tails, invalid earlier records, symlink logs
and conflicting run bindings are held without truncating history.
The runner waits for a validated private terminal record, not launch acknowledgement. Restart reconciles the same completed queue-bound run and checks successful output bytes against its digest without another producer. If a worker stopped after publishing its terminal ledger but before linking its private record, restart can repair that link from the exact retained predecessor even after a later rerun has finished. It verifies the original queue binding, saved inputs and successful answer, preserving the newer run's canonical ledger and both generations' outputs. Changed, ambiguous or unsafe predecessor records remain unresolved.
If the worker died before publishing its answer, use apr queue run --recover
or apr robot queue run --recover --compact. The runner checks the queue entry
and run identity under the round lock, then uses the same verified session
harvest as apr recover. On success it records the original execution counters
and continues to the next request. An unverified harvest holds the FIFO and
reports the blocked entry and round. If a previous recovery already saved and
verified the answer, an ordinary drain can finish publication offline.
Unresolved started executions or altered completed output block later work
and preserve useful files. A new request can reuse the current successful round
offline. APR checks local lint, the selected document manifest, prompt and
workflow hashes, model settings, remote host and the published answer's byte
count and SHA-256 against its private terminal record. A matching request moves
straight from queued to done with a reuse event, the original run ID and zero
new attempts. An occupied output without matching evidence keeps the existing
validation failure and preserves the answer.
Queue busy waits default to infinite; ordinary human/robot defaults remain
unchanged. If a direct run holds the head request's round lock, the runner
leaves that request queued and waits. It rechecks cancellation and FIFO order
between attempts, then checks for a reusable answer once the lock clears.
An admission timeout returns exit 12 with data.blocked.kind: "queue_admission"
in robot output. The request stays queued so the next runner can try again.
Admission and Oracle each use the configured wait budget. If an Oracle
attempt exhausts an explicit finite APR_BUSY_WAIT_SECONDS, APR records a
wait event and keeps the request pending (running, waiting_code: "busy"),
stopping later jobs with exit 12. It never silently replays that attempt. Inspect
its ledger, then use apr queue retry <entry-id> or
apr robot queue retry <entry-id> --compact to requeue an explicitly refused
request. Retry preserves its original FIFO position and result_target; a later
queue run performs the review and apr result follows that same receipt.
Retry itself is offline and starts no review. It requires every producer
attempt to have retained a verifiable explicit busy refusal, with no output,
ordinary failed attempt, related or ambiguous Oracle session, active owner,
or conflicting run generation. Older runs without refusal evidence remain
held. Cancellation, completed work and uncertain submissions cannot be retried.
The retained input bundle must still verify. Retry pins those accepted sources,
Oracle route, ACK and size settings, plus enabled strict lint, composer
verification and redaction. Changed sources or routing fail before submission;
create a fresh request when intentionally changing the review. The next worker
rechecks prior refusal evidence for late-arriving sessions before launching.
All refused generations remain inspectable through retry_history and their
original run: references, including after repeated retries or a controller
restart. An output-publication conflict is a terminal failure rather than an
Oracle-busy deferral. Batch failures are audited and processing continues; the
batch returns the first failed exit/code. These are local filesystem/process
guarantees, not model correctness, live-service or power-loss qualification.
GPT Pro Extended Thinking Stability
GPT Pro Extended Thinking can pause for 10-30+ seconds during its reasoning phase. A completion check based only on "the text stopped changing" would capture a truncated answer during such a pause.
Oracle 0.16 and later do not rely on that alone. A turn counts as finished only when the stop button is gone, ChatGPT's finished-turn action bar has stayed visible for several polls with no content change, no thinking activity is visible, and the content has been stable for a minimum time. APR leaves Oracle's installed files alone and passes its environment through to every Oracle process, so Oracle's own knobs lengthen that gate:
| Variable (read by Oracle 0.16+) | Oracle Default | Purpose |
|---|---|---|
ORACLE_TERMINAL_MIN_STABLE_MS |
1200 |
Time the content must stay unchanged before the turn counts as finished |
ORACLE_BAR_CONFIRM_CYCLES |
3 |
Polls the finished-turn action bar must stay confirmed |
APR versions up to 1.3.1 tried to sed-patch Oracle's assistantResponse.js. That patch only ever matched Oracle 0.8.0-0.8.4 and has been removed, together with its APR_ORACLE_* threshold variables and its per-run "may be truncated" warnings. If one of those variables is still set, pre-flight names it and points to the Oracle variables above.
Automatic recovery: When Oracle exits successfully with an incomplete answer, APR waits 30 seconds (APR_RECOVERY_WAIT_SECS) and harvests the same verified Oracle conversation. The shared completion path below applies to foreground, detached, robot, and queued runs.
Automatic Recovery in Every Run Mode
Foreground, detached human, robot, and queued runs share one completion path. When Oracle exits successfully but its answer fails APR's completeness checks, APR attempts one harvest of that same run's verified Oracle conversation.
Recovery requires a unique session bound to the private output destination and pre-launch inventory, a consistent saved conversation before and after capture, and an Oracle harvest summary confirming both completion and matching capture identity. Unknown, changed, or still-generating captures remain failed; a zero harvest exit alone is insufficient. Recovery never submits another review.
Each attempt retains the producer's partial output, session evidence, harvest,
stdout and stderr in a private auto-recovery.* directory. Accepted bytes are
copied into an independent read-only file before normal guarded publication.
The terminal ledger's recovery object records the outcome and retained paths.
Detached workers continue recovery after the launch acknowledgement; queues wait
for the terminal record before treating the request as done.
APR_RECOVERY_WAIT_SECS controls the wait before harvest in all run modes.
Oracle failures with a nonzero native exit retain the existing failure/manual
recovery path. Automatic recovery observations establish local capture
provenance, not the correctness of the review's recommendations.
Session Locking
Concurrent runs of the same workflow can cause data corruption or wasted Oracle sessions. APR uses file-based locking:
.apr/rounds/<workflow>/.lock
When a run starts:
- APR attempts to acquire the lock
- If locked, it displays who holds it and when it was acquired
- Stale locks (from crashed processes) are automatically cleaned after 2 hours
╭────────────────────────────────────────────────────────────╮
│ ⚠ WORKFLOW LOCKED │
│ │
│ Workflow 'fcp-spec' is currently in use. │
│ Locked by: PID 12345 at 2026-01-12 14:30:00 │
│ │
│ Use 'apr status' to check the running session. │
╰────────────────────────────────────────────────────────────╯
🤖 Robot Mode: Automation API
APR's human-friendly terminal output is beautiful for interactive use, but coding agents and automation pipelines need structured, machine-readable data. Robot mode provides a complete JSON API that makes APR a first-class citizen in automated workflows.
Why Robot Mode Matters
The iterative refinement workflow APR enables is exactly the kind of repetitive, multi-step process that benefits from automation. A coding agent like Claude Code can:
- Validate before running: Check that all preconditions are met before kicking off an expensive 30-minute GPT Pro review
- Run rounds programmatically: Execute
apr robot run 5and parse the structured response - Monitor progress: Query status and workflow information in a parseable format
- Handle errors gracefully: Semantic error codes and structured error messages enable intelligent retry logic
Response Format
All robot mode commands return a consistent JSON envelope:
{
"ok": true,
"code": "ok",
"data": { ... },
"hint": "Optional helpful message for debugging",
"meta": {
"v": "1.2.0",
"ts": "2026-01-12T19:14:00Z"
}
}
On failure, ok becomes false and code contains a stable, semantic failure class. For grep-friendly automation, fatal failures also emit a single-line stderr tag:
APR_ERROR_CODE=<code>
| Code | Meaning |
|---|---|
ok |
Success |
usage_error |
Bad arguments (missing/invalid round/workflow/option) |
not_configured |
No .apr/ directory / not initialized |
config_error |
Workflow/config invalid (missing fields/files, cannot create dirs) |
validation_failed |
Preconditions not met (prompt QC, output exists, metrics missing) |
dependency_missing |
Required dependency missing (e.g. oracle/jq) |
busy |
Single-flight/busy (lock held / cannot proceed without waiting) |
network_error |
Network/remote unreachable (when remote mode is used) |
update_error |
Self-update failed |
not_implemented |
Feature unsupported in this install |
internal_error |
Unexpected failure (bug/unknown state) |
Commands
apr robot status
Returns complete configuration and environment status:
apr robot status
{
"ok": true,
"code": "ok",
"data": {
"configured": true,
"default_workflow": "fcp-spec",
"workflow_count": 2,
"workflows": ["fcp-spec", "auth-protocol"],
"oracle_available": true,
"oracle_method": "global",
"config_dir": "/home/user/project/.apr",
"apr_home": "/home/user/.local/share/apr"
}
}
apr robot workflows
Lists all configured workflows with their descriptions:
apr robot workflows
{
"ok": true,
"code": "ok",
"data": {
"workflows": [
{"name": "fcp-spec", "description": "Flywheel Connector Protocol specification"},
{"name": "auth-protocol", "description": "Authentication protocol design"}
]
}
}
apr robot init
Initializes the .apr/ directory structure. It is idempotent and safe to call multiple times:
apr robot init
{
"ok": true,
"code": "ok",
"data": {
"created": true,
"existed": false
}
}
apr robot validate <round>
Pre-flight validation before running a round. This is the key command for automation; it checks all preconditions without actually running anything:
apr robot validate 5 --workflow fcp-spec
{
"ok": true,
"code": "ok",
"data": {
"valid": true,
"errors": [],
"warnings": [],
"workflow": "fcp-spec",
"round": "5"
}
}
If validation fails:
{
"ok": false,
"code": "validation_failed",
"data": {
"valid": false,
"errors": [
"Previous round output not found: .apr/rounds/fcp-spec/round_4.md",
"Specification file not found: SPEC.md"
],
"warnings": ["Implementation file not configured"],
"workflow": "fcp-spec",
"round": "5"
}
}
Validation checks:
- Round number is valid and numeric
- Configuration directory exists
- Workflow exists and is readable
- README and spec files exist
- Oracle is available
- Previous round exists (if round > 1)
apr robot render <round>
Preview the exact text APR would pass as Oracle’s -p argument for the
selected workflow, round and implementation cadence. The response includes
the prompt, its SHA-256, the manifest preamble, structured document metadata
and any lint warnings. A later run observes the inputs again.
apr robot render 4 -w myspec --compact | jq -j '.data.prompt'
apr robot render 1 -w myspec -i --compact | jq '.data.manifest'
Use jq -j to preserve the prompt’s exact bytes. Render checks local inputs
without starting Oracle, contacting the update service or creating run records.
apr robot run <round>
Executes a revision round and returns structured status:
apr robot run 5 --workflow fcp-spec --include-impl
{
"ok": true,
"code": "ok",
"data": {
"slug": "apr-fcp-spec-round-5",
"session_id": "apr-fcp-spec-round-5",
"requested_slug": "apr-fcp-spec-round-5-with-impl",
"pid": 12345,
"output_file": ".apr/rounds/fcp-spec/round_5.md",
"log_file": ".apr/logs/oracle_round_5.ABC123.log.XYZ789",
"workflow": "fcp-spec",
"round": 5,
"include_impl": true,
"status": "running"
}
}
The session_id (also returned as slug) is Oracle's actual session identifier and can be used with apr attach. requested_slug retains APR's original label; Oracle may shorten it or add a collision suffix. If identity cannot yet be verified, session_id and slug are null. The attach_target is a stable APR run reference (run:<workflow>:<run_id>): pass it to apr attach to resolve the actual session after startup or a retry. APR verifies identity using the private output destination, Oracle's creation timestamp, and a fresh session inventory for each producer attempt; ambiguous or stale candidates are never automatically attached or harvested. The output_file will contain the GPT Pro response once complete, and log_file captures Oracle output.
apr robot help
Returns complete API documentation in JSON format, useful for coding agents to discover capabilities:
apr robot help
Options
| Flag | Description |
|---|---|
--workflow NAME |
Specify workflow (default: from config) |
--include-impl, -i |
Include implementation document |
--compact |
Minified JSON output (no pretty-printing) |
Integration Example
Here's how a coding agent might use robot mode:
# 1. Check environment
status=$(apr robot status)
if ! echo "$status" | jq -e '.data.oracle_available' > /dev/null; then
echo "Oracle not available"
exit 1
fi
# 2. Validate before running
validation=$(apr robot validate 5 --workflow fcp-spec)
if ! echo "$validation" | jq -e '.data.valid' > /dev/null; then
echo "Validation failed:"
echo "$validation" | jq '.data.errors[]'
exit 1
fi
# 3. Run the round
result=$(apr robot run 5 --workflow fcp-spec)
slug=$(echo "$result" | jq -r '.data.slug')
output_file=$(echo "$result" | jq -r '.data.output_file')
echo "Started session: $slug"
echo "Output will be at: $output_file"
Why This Design?
Robot mode follows these principles:
- Semantic error codes: Machine-parseable error types enable intelligent error handling, not just string matching
- Pre-flight validation: Expensive Oracle runs (10-60 minutes) shouldn't fail due to missing files; validate first
- Consistent envelope: Every response has the same structure, making parsing trivial
- Self-documenting: The
helpcommand returns structured documentation - Minimal dependencies: Only requires
jqfor JSON output formatting
🔄 Self-Update
APR includes a secure self-update mechanism that keeps your installation current without requiring manual downloads or reinstallation.
How It Works
apr update
The update command:
- Fetches the latest version from GitHub with a 5-second timeout
- Compares versions using semantic versioning (e.g.,
1.2.0 → 1.2.1) - Shows what's available and asks for confirmation
- Downloads the new version to a temporary location
- Verifies the download with multiple security checks
- Installs atomically: the old version is only replaced after verification succeeds
Security Features
Self-update is designed with security as a priority:
| Feature | Purpose |
|---|---|
| SHA-256 checksums | Verifies download integrity against published checksums |
| Script validation | Confirms downloaded file is a valid bash script (has shebang) |
| Syntax checking | Runs bash -n to verify script parses correctly |
| Atomic installation | Uses temp file + move to prevent partial updates |
| Sudo detection | Automatically elevates privileges for system directories |
Interactive Confirmation
Updates always require confirmation:
╭────────────────────────────────────────────────────────────╮
│ UPDATE AVAILABLE │
│ │
│ Current version: 1.2.0 │
│ Latest version: 1.2.1 │
│ │
│ Install update? [y/N] │
╰────────────────────────────────────────────────────────────╯
Daily Update Checking
For users who want to stay current, APR supports opt-in daily update notifications:
export APR_CHECK_UPDATES=1
With this enabled, APR checks for updates once per day (tracked in ~/.local/share/apr/.last_update_check) and displays a non-blocking notification if a new version is available. The check uses a 5-second timeout and never interrupts your workflow.
Why Self-Update?
APR is a rapidly evolving tool. New features, bug fixes, and improvements are released frequently. Self-update ensures:
- Low friction: No need to re-run the installer or remember download URLs
- Security: Checksum verification prevents tampering
- Reliability: Atomic updates mean no corrupted installations
- User control: Updates are never automatic; you always confirm
📖 The Inspiration: Flywheel Connector Protocol
APR was built to automate the workflow used to develop the Flywheel Connector Protocol:
The goal is to have security and isolation built in at the protocol level, and also extreme performance and reliability, with everything done in Rust in a uniform manner that conforms to the protocol specification.
The Original Manual Workflow
This is the process APR automates:
Step 1: Send to GPT Pro 5.2 Extended Reasoning
First, read this README:
\`\`\`
<paste contents of readme file>
\`\`\`
---
NOW: Carefully review this entire plan for me and come up with your best
revisions in terms of better architecture, new features, changed features,
etc. to make it better, more robust/reliable, more performant, more
compelling/useful, etc.
For each proposed change, give me your detailed analysis and
rationale/justification for why it would make the project better along
with the git-diff style change versus the original plan shown below:
\`\`\`
<paste contents of spec document>
\`\`\`
Step 2: Prime Claude Code
First read ALL of the AGENTS.md file and README.md file super carefully
and understand ALL of both! Then use your code investigation agent mode
to fully understand the code, and technical architecture and purpose of
the project. Read ALL of the V2 spec doc and the connector doc.
Step 3: Integrate Feedback
Now integrate all of this feedback (and let me know what you think of it,
whether you agree with each thing and how much) from gpt 5.2:
\`\`\`[Pasted GPT output]\`\`\`
Be meticulous and use ultrathink.
Step 4: Update README
We need to revise the README too for these changes (don't write about
these as "changes" however, make it read like it was always like that,
we don't have any users yet!) Use ultrathink.
Step 5: Harmonize Implementation
Now review docs/fcp_model_connectors_rust.md ultra carefully and ensure
it is 100% harmonized with the V2 spec and as optimized as possible
subject to those constraints.
Step 6: Commit and Push
Now, based on your knowledge of the project, commit all changed files
now in a series of logically connected groupings with super detailed
commit messages for each and then push. Take your time to do it right.
Extended Template (Every 3-4 Rounds)
Once every few review sessions, include the implementation document:
First, read this README:
\`\`\`<readme>\`\`\`
---
And here is a document detailing Rust implementations for the canonical
connector types that follow the specification document given below; you
should also keep the implementation in mind as you think about the
specification, since ultimately the specification needs to be translated
into the Rust code eventually!
\`\`\`<implementation>\`\`\`
---
NOW: Carefully review this entire plan...
\`\`\`<spec>\`\`\`
🧭 Design Principles
1. Iterative Convergence
Like numerical optimization, specification design converges over multiple iterations:
- Early rounds fix major issues (security gaps, architectural flaws)
- Middle rounds refine architecture
- Later rounds polish abstractions and interfaces
2. Grounded Abstraction
Every few rounds, including the implementation document keeps abstract specifications grounded in concrete reality. Faulty assumptions surface earlier when ideas meet code.
3. Audit Trail
Every round creates artifacts:
- GPT Pro output saved to
.apr/rounds/ - Git commits capture evolution
- Both abstract "specification space" and concrete "implementation space" are tracked
4. Graceful Degradation
Everything has fallbacks:
- gum → ANSI colors
- Oracle global → npx
- Interactive → CLI flags
5. Dual Interface
APR serves two audiences with the same codebase:
- Humans get beautiful gum-styled output, interactive wizards, and progress indicators
- Machines get structured JSON via robot mode, semantic error codes, and pre-flight validation
Two output formats exist because iterative refinement workflows benefit from automation; a tool that only works interactively leaves value on the table.
6. Secure by Default
Security considerations are woven throughout:
- No credential storage: APR never touches your ChatGPT credentials; Oracle uses browser cookies
- Checksum verification: Downloads are verified against published SHA-256 checksums
- Atomic operations: Updates either complete fully or don't happen at all
- User consent: Nothing destructive happens without explicit confirmation
🏗️ Architecture
Component Overview
apr (bash script, ~5000 LOC)
├── Core Commands
│ ├── run # Execute revision rounds with retry logic
│ ├── setup # Interactive workflow wizard
│ ├── status # Oracle session status
│ ├── attach # Reattach to sessions
│ ├── list # List workflows
│ ├── history # Round history
│ ├── show # View round output
│ ├── diff # Compare rounds
│ ├── integrate # Claude Code prompts
│ ├── stats # Convergence analytics
│ └── backfill # Retroactive metrics
├── Robot Mode # JSON API for automation
│ ├── status # Environment introspection
│ ├── workflows # List workflows
│ ├── init # Initialize .apr/
│ ├── validate # Pre-flight checks
│ ├── run # Execute rounds
│ ├── history # Round history (JSON)
│ └── help # API documentation
├── Reliability Layer
│ ├── Pre-flight validation
│ ├── Auto-retry with exponential backoff
│ ├── Session locking
│ └── Graceful error handling
├── Analytics Engine
│ ├── Metrics collection
│ ├── Convergence detection
│ └── Round comparison
├── Self-Update # Secure update mechanism
│ ├── Version comparison
│ ├── Checksum verification
│ └── Atomic installation
├── Gum Integration # Beautiful TUI with ANSI fallback
└── Oracle Detection # Global or npx fallback
.apr/ (per-project configuration)
├── config.yaml # Global settings
├── workflows/ # Workflow definitions
│ └── <name>.yaml
├── analytics/ # Convergence + metrics data
│ └── <workflow>/
│ └── metrics.json
├── rounds/ # Round outputs
│ └── <workflow>/
│ └── round_N.md
├── logs/ # Oracle logs (robot mode)
│ └── oracle_<slug>.log
└── templates/ # Custom prompt templates
~/.local/share/apr/ (user data)
└── .last_update_check # Daily update check timestamp
Workflow YAMLs can include template and template_with_impl block scalars to
override the Oracle prompt. If omitted, APR uses the built-in default prompt,
which names the attached README, implementation (when included) and spec.
Oracle does not substitute anything inside the prompt: it pastes each document
after the prompt, in that order, under a ### File: <path> heading. A custom
template should therefore refer to the documents by name instead of leaving
empty slots for them; apr lint warns about the old
<contents of … will be included by oracle> slots.
File Locations
| Path | Purpose |
|---|---|
~/.local/bin/apr |
Main script (default install) |
~/.local/share/apr/ |
User data directory (XDG-compliant) |
~/.cache/apr/ |
Cache directory (XDG-compliant) |
.apr/ |
Per-project configuration directory |
.apr/config.yaml |
Global APR config for this project |
.apr/workflows/*.yaml |
Workflow definitions |
.apr/rounds/<workflow>/ |
GPT Pro outputs per round |
.apr/analytics/<workflow>/metrics.json |
Round analytics data |
.apr/logs/oracle_<slug>.log |
Oracle output log (robot mode) |
🧪 Testing Framework
APR includes a comprehensive test suite built on BATS (Bash Automated Testing System). The test infrastructure validates everything from individual functions to complete end-to-end workflows.
Test Structure
tests/
├── helpers/
│ └── test_helper.bash # Shared fixtures and assertions
├── unit/
│ ├── test_yaml_parser.bats # YAML parsing edge cases
│ ├── test_exit_codes.bats # Exit code contract verification
│ └── ... # Function-level tests
├── e2e/
│ └── test_full_workflow.bats # Complete workflow tests
└── logs/
└── test_run_*.log # Test execution logs
Running Tests
# Run all tests
./tests/run_tests.sh
# Run only unit tests
bats tests/unit/
# Run only e2e tests
bats tests/e2e/
# Run with verbose output
bats --verbose-run tests/
Test Categories
| Category | Purpose | Count |
|---|---|---|
| Unit Tests | Individual function validation | ~160 |
| Exit Code Tests | Verify semantic exit codes | ~30 |
| YAML Parser Tests | Edge cases in config parsing | ~25 |
| E2E Tests | Complete workflow journeys | ~20 |
Key Testing Principles
- No Oracle dependency: Tests use mocked Oracle responses to run quickly and offline
- Isolated environments: Each test creates a fresh project directory in
/tmp - Semantic exit codes: Tests verify that specific error conditions produce specific exit codes
- Stream separation: Tests validate that JSON goes to stdout, errors to stderr
- Robot mode coverage: Full JSON API contract validation
Custom Assertions
The test helper provides domain-specific assertions:
# File and directory assertions
assert_file_exists ".apr/config.yaml"
assert_dir_exists ".apr/workflows"
# Exit code verification
assert_exit_code 0 # Success
assert_exit_code 2 # Usage error
assert_exit_code 4 # Config error
# JSON validation
assert_valid_json "$output"
assert_json_value "$output" ".ok" "true"
assert_json_value "$output" ".code" "ok"
# Stream capture
capture_streams "$APR_SCRIPT" robot status
assert_valid_json "$CAPTURED_STDOUT"
🎨 Terminal Styling
APR uses gum for beautiful terminal output:
╔════════════════════════════════════════════════════════════╗
║ Automated Plan Reviser Pro v1.2.0 ║
║ Iterative AI-Powered Spec Refinement ║
╚════════════════════════════════════════════════════════════╝
╭────────────────────────────────────────────────────────────╮
│ REVISION ROUND 5 │
│ │
│ Workflow: fcp-spec │
│ Model: 5.2 Thinking │
│ Include impl: true │
│ Output: .apr/rounds/fcp-spec/round_5.md │
╰────────────────────────────────────────────────────────────╯
✓ Oracle running in background (PID: 12345)
╭────────────────────────────────────────────────────────────╮
│ MONITORING COMMANDS │
├────────────────────────────────────────────────────────────┤
│ Check status: apr status │
│ Attach to session: apr attach apr-fcp-spec-round-5 │
╰────────────────────────────────────────────────────────────╯
Styling Behavior
| Environment | Output Style |
|---|---|
| TTY with gum installed | Full gum styling |
| TTY without gum | ANSI color codes |
| Non-TTY (piped) | Plain text |
CI environment ($CI set) |
Plain text |
APR_NO_GUM=1 |
Force ANSI fallback |
NO_COLOR=1 |
Plain text (no colors) |
Accessibility
APR respects the NO_COLOR standard. When NO_COLOR is set (to any value), all colored output is disabled. This is useful for:
- Screen readers and assistive technologies
- Users with color vision deficiency
- Piping output to files or other tools
- Environments where ANSI codes cause issues
📦 Dependencies
Required
| Package | Purpose |
|---|---|
| Bash 4+ | Script runtime |
| Oracle | GPT Pro browser automation (excellent tool by Peter Steinberger) |
| Node.js 24+ with npm | Oracle runtime (@steipete/oracle requires Node 24 or newer) |
| curl or wget | Installation |
Optional
| Package | Purpose |
|---|---|
| gum | Beautiful terminal UI |
| jq | Required for robot mode JSON output |
Install Dependencies
# Node.js 24+ with npm (Oracle requires Node 24 or newer)
# macOS
brew install node
# Ubuntu/Debian: the distribution's nodejs is usually older than 24 and ships npm as a
# separate package, so use NodeSource's Node 24 feed (this adds an apt source)
curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash -
sudo apt-get install -y nodejs
# Oracle
npm install -g @steipete/oracle
# gum (optional, for beautiful UI)
# macOS
brew install gum
# Linux
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://repo.charm.sh/apt/gpg.key | sudo gpg --dearmor -o /etc/apt/keyrings/charm.gpg
echo "deb [signed-by=/etc/apt/keyrings/charm.gpg] https://repo.charm.sh/apt/ * *" | sudo tee /etc/apt/sources.list.d/charm.list
sudo apt update && sudo apt install gum
# jq (optional, for robot mode)
# macOS
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
🌐 Environment Variables
Core Settings
| Variable | Description | Default |
|---|---|---|
APR_HOME |
Data directory | ~/.local/share/apr |
APR_CACHE |
Cache directory | ~/.cache/apr |
APR_CHECK_UPDATES |
Enable daily update checking | unset (set to 1 to enable) |
APR_NO_NPX |
Disable npx fallback for Oracle (require global oracle) |
unset |
Reliability Configuration
| Variable | Description | Default |
|---|---|---|
APR_MAX_RETRIES |
Maximum Oracle retry attempts | 3 |
APR_INITIAL_BACKOFF |
Initial retry delay (seconds) | 10 |
APR_MAX_PROMPT_BYTES |
Maximum exact final -p argument bytes |
120000 |
APR_MAX_BUNDLE_BYTES |
Maximum prompt and selected attachment bytes plus 4096 framing bytes per attachment | 200000 |
Oracle Completion Gate and Recovery
| Variable | Description | Default |
|---|---|---|
ORACLE_TERMINAL_MIN_STABLE_MS |
Read by Oracle 0.16+: time the content must stay unchanged before the turn counts as finished | Oracle's (1200) |
ORACLE_BAR_CONFIRM_CYCLES |
Read by Oracle 0.16+: polls the finished-turn action bar must stay confirmed | Oracle's (3) |
APR_RECOVERY_WAIT_SECS |
Seconds to wait before reattaching to recover a truncated answer (0 skips the wait) |
30 |
Status & Monitoring
| Variable | Description | Default |
|---|---|---|
APR_STATUS_HOURS |
Time window for status checks (hours) | 72 |
APR_VERBOSE |
Enable verbose/debug output | unset |
Display Settings
| Variable | Description | Default |
|---|---|---|
APR_NO_GUM |
Disable gum even if available | unset |
NO_COLOR |
Disable colored output (accessibility) | unset |
CI |
Detected CI environment (disables gum) | unset |
PAGER |
Pager for apr show output |
less or more |
🌐 Oracle Remote Setup (Headless/SSH Environments)
If you're running APR on a headless server (SSH session, remote VM, CI runner), Oracle can't open a browser locally. The solution is Oracle's serve mode: run the browser automation on a local machine with a GUI, and have the remote server connect to it.
Why This Is Needed
┌─────────────────────────────────────────────────────────────────────────────┐
│ THE PROBLEM │
│ │
│ [Remote Server] [ChatGPT] │
│ SSH ───────→ No browser ──────✕──→ Can't authenticate │
│ │
├─────────────────────────────────────────────────────────────────────────────┤
│ THE SOLUTION: Oracle Serve Mode │
│ │
│ [Remote Server] [Local Machine] [ChatGPT] │
│ APR ──────────→ Oracle Serve ──────→ Browser ──────→ ✓ │
│ TCP/9333 ▲ │
│ (Tailscale) └── Has GUI, can run Chrome │
│ │
└─────────────────────────────────────────────────────────────────────────────┘
Step 1: Start Oracle Serve on Your Local Machine
On the machine with a browser (your laptop, desktop, Mac Mini, etc.):
# Install Oracle if needed
npm install -g @steipete/oracle
# Start the server (keep this terminal open)
oracle serve --port 9333 --token "your-secret-token"
Important: Use port 9333, not 9222. Port 9222 is used internally by Chrome for the DevTools Protocol. Using 9333 for Oracle's server avoids the conflict.
You'll see output like:
Oracle remote server started on port 9333
Waiting for connections...
Step 2: Configure the Remote Server
On your remote machine (the one running APR via SSH):
# Set environment variables (add to ~/.zshrc or ~/.bashrc for persistence)
export ORACLE_REMOTE_HOST="192.168.1.100:9333" # Your local machine's IP
export ORACLE_REMOTE_TOKEN="your-secret-token" # Must match --token above
# Or for Tailscale (recommended for remote servers)
export ORACLE_REMOTE_HOST="100.x.x.x:9333" # Tailscale IP of local machine
Step 3: Test the Connection
oracle -p "Say exactly: Connection successful" -e browser -m "5.2 Thinking"
If successful, you'll see GPT Pro's response. APR will now work normally:
apr run 1 # Works over the remote connection
Multiple Oracle Hosts
Use an ordered pool when you have more than one oracle serve host:
unset ORACLE_REMOTE_HOST
export ORACLE_REMOTE_POOL="mac-a:9333,mac-b:9333"
export ORACLE_REMOTE_TOKEN="your-shared-server-token"
apr doctor
apr run 1 --wait
# Queued rounds select a host separately when each new execution begins.
apr queue run --until-empty
The pool accepts 1–16 distinct host:port or [IPv6]:port addresses, separated
by commas; surrounding spaces are ignored. All hosts use the shared token.
Setting both ORACLE_REMOTE_POOL and ORACLE_REMOTE_HOST is an error.
Before starting a new review, APR checks authenticated /health endpoints in
the configured order. It chooses the first host reporting available capacity.
With apr robot run N --enqueue-if-busy, if every configured host explicitly
reports that it is busy, APR queues the request immediately. The receipt has
reason: "remote_pool_busy" and oracle_exit: null. The ledger records zero
submission attempts. When the queue drains, APR checks capacity again.
If none reports availability, it chooses the first authenticated host whose
capacity is unknown, then the first authenticated busy host. Busy selections
use the existing retry/wait policy; health is an observation, not a reservation.
Unreachable hosts are skipped. If no host passes health checks, APR returns
network_error for transport failures or config_error for rejected credentials
or incompatible responses, without starting a review. Each probe has a
five-second maximum and never follows redirects or uses a proxy.
A selected host remains fixed through retries and recovery: a failed connection
after submission may still have started a browser review. APR explicitly pins
Oracle's host and token options so an Oracle config file cannot silently choose
a different route. APR diagnostics and ledgers redact the token; Oracle receives
it in its child-process arguments, as with its ordinary --remote-token option.
The ledger, robot response, replay JSON, and execution statistics retain the
ordered pool, selected host, selection reason, and sanitized probe observations.
Probe calls do not count as review attempts. --resume and queue reuse compare
the original ordered pool locally and can reuse verified completed work with
servers offline and the token unset. Changing pool membership or order requires
an intentional new execution. Preview/render commands do not probe the pool.
Tailscale Setup (Recommended)
If your local and remote machines are both on a Tailscale network, use Tailscale IPs for reliable connectivity:
# Find your local machine's Tailscale IP
tailscale ip -4 # Run this on your local machine
# On the remote server
export ORACLE_REMOTE_HOST="100.x.x.x:9333" # Use the Tailscale IP
export ORACLE_REMOTE_TOKEN="your-secret-token"
# Verify connectivity
tailscale ping 100.x.x.x # Should succeed
Tailscale provides:
- NAT traversal: Works even when your local machine is behind a firewall
- Encryption: Traffic is encrypted via WireGuard
- Stable IPs: Tailscale IPs don't change when you move networks
Session Persistence
Once authenticated, Oracle maintains the ChatGPT session in the browser. You can:
- Leave
oracle serverunning on your local machine - Run multiple APR rounds from the remote server
- Reattach to sessions:
apr attach <slug>
If the session expires, you may need to re-authenticate by visiting ChatGPT in the browser on your local machine.
How Documents Are Sent (Inline Pasting)
APR uses Oracle's --browser-attachments never mode, which pastes document contents directly into the chat rather than uploading them as file attachments. This is more reliable because:
- No upload failures: File uploads to ChatGPT can fail silently or trigger "duplicate file" errors
- Consistent formatting: Pasted content appears exactly as intended
- No attachment limits: Works regardless of ChatGPT's file upload restrictions
The documents are combined with the prompt template and pasted as a single message. For typical workflows (README + spec + impl ~200KB), this works reliably within GPT's context limits.
Security Considerations
- Token secrecy: The
--tokenvalue is like a password. Use a strong, unique value. - Network exposure: Only expose
oracle serveon trusted networks (Tailscale, local LAN). - Don't use over public internet: Without Tailscale, you'd need firewall rules and the connection isn't encrypted.
🧭 Troubleshooting
Common Issues
Oracle not found
Cause: Node.js or Oracle not installed.
Fix:
# Install Node.js first, then:
npm install -g @steipete/oracle
# Or use npx (works without global install)
npx -y @steipete/oracle --version
If you set APR_NO_NPX=1, APR will not use the npx fallback.
Browser doesn't open / cookies expired
Cause: First run requires manual login, or session expired.
Fix:
apr run 1 --login --wait
# Browser opens - log into ChatGPT
# Session saved for future runs
Session timeout
Cause: Extended reasoning took longer than expected.
Fix:
# Don't re-run! Reattach to the session
apr attach apr-default-round-5
# Or use Oracle directly
npx -y @steipete/oracle session apr-default-round-5 --render
Response appears truncated or incomplete
Cause: GPT Pro Extended Thinking can pause for 10-30+ seconds during reasoning. If Oracle's completion gate closes during such a pause, it captures output prematurely.
Fix:
Update Oracle first (npm install -g @steipete/oracle@latest): 0.16 and later wait for ChatGPT's finished-turn signals, not just for the text to stop changing. If you still see truncation, lengthen Oracle's gate (APR passes the environment through to Oracle):
# Content must stay unchanged this long (milliseconds) before Oracle finishes
export ORACLE_TERMINAL_MIN_STABLE_MS=30000
# Polls the finished-turn action bar must stay confirmed
export ORACLE_BAR_CONFIRM_CYCLES=6
# Then re-run
apr run 5
If output was captured mid-response, try reattaching:
apr attach apr-default-round-5
Workflow not found
Cause: No .apr/ directory or workflow not set up.
Fix:
apr setup # Run the setup wizard
Robot mode returns "jq not found"
Cause: Robot mode requires jq for JSON formatting.
Fix:
# macOS
brew install jq
# Ubuntu/Debian
sudo apt-get install jq
# Fedora
sudo dnf install jq
Update fails with checksum error
Cause: Download was corrupted or tampered with.
Fix:
# Try again - network issues can cause incomplete downloads
apr update
# If it persists, reinstall from scratch
curl -fsSL "https://raw.githubusercontent.com/Dicklesworthstone/automated_plan_reviser_pro/main/install.sh" | bash
Permission denied during update
Cause: APR is installed in a system directory requiring elevated privileges.
Fix: APR automatically detects this and prompts for sudo. If it doesn't:
# Check where apr is installed
which apr
# If in /usr/local/bin, update will prompt for sudo
# If that fails, manually update:
sudo curl -fsSL https://raw.githubusercontent.com/Dicklesworthstone/automated_plan_reviser_pro/main/apr -o /usr/local/bin/apr
sudo chmod +x /usr/local/bin/apr
About Contributions: Please don't take this the wrong way, but I do not accept outside contributions for any of my projects. I simply don't have the mental bandwidth to review anything, and it's my name on the thing, so I'm responsible for any problems it causes; thus, the risk-reward is highly asymmetric from my perspective. I'd also have to worry about other "stakeholders," which seems unwise for tools I mostly make for myself for free. Feel free to submit issues, and even PRs if you want to illustrate a proposed fix, but know I won't merge them directly. Instead, I'll have Claude or Codex review submissions via
ghand independently decide whether and how to address them. Bug reports in particular are welcome. Sorry if this offends, but I want to avoid wasted time and hurt feelings. I understand this isn't in sync with the prevailing open-source ethos that seeks community contributions, but it's the only way I can move at this velocity and keep my sanity.
📄 License
MIT License (with OpenAI/Anthropic Rider). See LICENSE for details.
Built with Oracle, gum, and a healthy appreciation for iterative refinement.
Special thanks to Peter Steinberger for creating Oracle, the excellent browser automation tool that makes APR possible.
Explore related projects
Loading…