autoresearch
Claude Autoresearch — autonomous goal-directed iteration for Claude Code. 14 commands: iterate, plan, debug, fix, security, ship, scenario, predict, learn, reason, probe, evals, improve, regression.
Safety scan
A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.
Badge for your README
Markdown
[](/listings/uditgoenka-autoresearch)HTML
<a href="/listings/uditgoenka-autoresearch"><img src="/api/listings/uditgoenka-autoresearch/badge.svg" alt="findsafeskills safety rating" /></a>Install
Install instructions from the README
As written by the repo's author. findsafeskills has not verified these steps.
Claude Code
**Option A — npx install (recommended):**
npx skills add uditgoenka/autoresearch
All 14 commands are available after restarting Claude Code.
**Option B — Plugin install:**
/plugin marketplace add uditgoenka/autoresearch /plugin install autoresearch@autoresearch
> **Note:** Start a new Claude Code session after installing. Reference files aren't resolvable in the same session where installation happened — this is a Claude Code platform limitation.
**Updating (no reinstall needed):**
/plugin update autoresearch
Run `/reload-plugins` to activate. No need to uninstall or re-clone.
**Option C — Manual copy:**
git clone https://github.com/uditgoenka/autoresearch.git # Copy skill + subcommands to your project cp -r autoresearch/.claude/skills/autoresearch .claude/skills/autoresearch cp -r autoresearch/.claude/commands/autoresearch .claude/commands/autoresearch cp autoresearch/.claude/commands/autoresearch.md .claude/commands/autoresearch.md
Or install globally:
cp -r autoresearch/.claude/skills/autoresearch ~/.claude/skills/autoresearch cp -r autoresearch/.claude/commands/autoresearch ~/.claude/commands/autoresearch cp autoresearch/.claude/commands/autoresearch.md ~/.claude/commands/autoresearch.md
**Option D — Guided installer:**
git clone https://github.com/uditgoenka/autoresearch.git cd autoresearch ./scripts/install.sh --claude --global
OpenCode Quick Start
**Option A — Guided installer (recommended):**
git clone https://github.com/uditgoenka/autoresearch.git cd autoresearch ./scripts/install.sh --opencode --global
**Option B — Manual copy:**
git clone https://github.com/uditgoenka/autoresearch.git cp -r autoresearch/.opencode/skills/autoresearch .opencode/skills/autoresearch cp autoresearch/.opencode/commands/autoresearch*.md .opencode/commands/
Or globally:
cp -r autoresearch/.opencode/skills/autoresearch ~/.config/opencode/skills/autoresearch cp autoresearch/.opencode/commands/autoresearch*.md ~/.config/opencode/commands/
> All 14 commands available as `/autoresearch_debug`, `/autoresearch_fix`, `/autoresearch_improve`, etc.
Codex Quick Start
**Option A — Guided installer (recommended):**
git clone https://github.com/uditgoenka/autoresearch.git cd autoresearch ./scripts/install.sh --codex --global
**Option B — Manual copy:**
git clone https://github.com/uditgoenka/autoresearch.git cp -r autoresearch/.agents/skills/autoresearch ~/.codex/skills/autoresearch
> Invoke via `$autoresearch` mention syntax. Subcommands are keywords: `$autoresearch plan`, `$autoresearch debug`, `$autoresearch evals`, etc. > The installed Codex package includes the bundled orchestrator and regression helpers under `plugins/autoresearch/skills/autoresearch/` and `.agents/skills/autoresearch/`.
pi Quick Start
**Option A — Guided installer (recommended):**
git clone https://github.com/uditgoenka/autoresearch.git cd autoresearch ./scripts/install.sh --pi --global
**Option B — pi package install:**
pi install git:github.com/uditgoenka/autoresearch
**Option C — Try without installing:**
pi -e ./pi-extension
> Invoke commands as pi prompt templates: `/autoresearch`, `/autoresearch_debug`, `/autoresearch_fix`, … (underscore names). The dispatcher is a skill: `/skill:autoresearch`. > The pi extension ports the Claude hook guardrails (scout/privacy/dangerous-cmd block, iteration context, simplify gate, stop-notify) to pi extension events. See [`pi-extension/README.md`](pi-extension/README.md) for the full hook→event mapping and `AR_DISABLE_*` flags.
Muse Quick Start
**Option A — Guided installer (recommended):**
git clone https://github.com/uditgoenka/autoresearch.git cd autoresearch ./scripts/install.sh --muse --global
**Option B — Manual install with the Muse CLI:**
What was scanned
The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.
.claude-plugin/marketplace.json · Manifest · 23 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- {
- "$schema": "https://anthropic.com/claude-code/marketplace.schema.json",
- "name": "autoresearch",
- "version": "2.3.0",
- "description": "Claude Autoresearch — autonomous goal-directed iteration for Claude Code. 14 commands: iterate, plan, debug, fix, security, ship, scenario, predict, learn, reason, probe, evals, improve, regression.",
- "owner": {
- "name": "Udit Goenka",
- "url": "https://github.com/uditgoenka"
- },
- "plugins": [
- {
- "name": "autoresearch",
- "description": "Autonomous improvement engine. 14 commands with bounded defaults, chain handoff, and adaptive evals checkpoints. 95% token reduction via modular architecture.",
- "version": "2.3.0",
- "author": {
- "name": "Udit Goenka",
- "url": "https://github.com/uditgoenka"
- },
- "source": "./claude-plugin",
- "category": "productivity"
- }
- ]
- }
README.md · README · 862 lines
View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)
- <div align="center">
- # Autoresearch
- **Turn [Claude Code](https://docs.anthropic.com/en/docs/claude-code), [OpenCode](https://opencode.ai), [OpenAI Codex](https://developers.openai.com/codex), [pi](https://github.com/earendil-works/pi-coding-agent), or Muse into a relentless improvement engine.**
- Based on [Karpathy's autoresearch](https://github.com/karpathy/autoresearch) — constraint + mechanical metric + autonomous iteration = compounding gains.
- [](https://docs.anthropic.com/en/docs/claude-code)
- [](https://opencode.ai)
- [](https://developers.openai.com/codex)
- [](https://github.com/earendil-works/pi-coding-agent)
- [](https://github.com/uditgoenka/autoresearch/releases)
- [](LICENSE)
- [](https://github.com/karpathy/autoresearch)
- [](https://x.com/intent/follow?screen_name=iuditg)
- [](https://paypal.me/uditgoenka)
- <br>
- *"Set the GOAL → The agent runs the LOOP → You wake up to results"*
- *You don't need AGI. You need a goal, a metric, and a loop that never quits.*
- **Supports Claude Code, OpenCode, OpenAI Codex, pi, and Muse for the core skill, bundled runtime, installation, and verification surface. Hook guardrails ship for Claude Code (native hooks) and pi (extension events).**
- > **Fork-and-flush:** metric loops escape plateaus the way [Cai et al. (arXiv:2610.07447)](https://arxiv.org/abs/2610.07447) do. At 33% and 66% of the budget, or after 5 iterations with no `keep`, the loop forks fresh-context branches from the best commit so far, runs each briefly, and keeps the winner. Half the branches pick their own ideas (randomness); the other half each get a distinct experiment from a stateless Advisor that reads the results log ([Zhang et al., arXiv:2610.07625](https://arxiv.org/abs/2610.07625)); `Guided: R` sets the split. The orchestrator answers a plateau with `FORK` before it gives up. See [guide/autoresearch.md](guide/autoresearch.md#getting-unstuck-fork-and-flush).
- > **v2.2.0 — Autonomous Orchestrator:** Type a plain-language goal to `/autoresearch` and it classifies your goal, derives a Success predicate, confirms it once, then loops across subcommands until done. No manual chaining required. `Metric:`/`Verify:` invocations run the classic loop unchanged. See [guide/autoresearch-orchestrator.md](guide/autoresearch-orchestrator.md).
- <br>
- [How It Works](#how-it-works) · [Commands](#commands) · [Quick Start](#quick-start) · [Guides](guide/) · [FAQ](#faq)
- </div>
- ---
- ```
- PLAN LOOP DEBUG FIX SECURE SHIP
- ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
- │ Goal │ │ Modify │ │ Find │ │ Fix │ │ STRIDE │ │ Stage │
- │ Metric │────▶│ Verify │────▶│ Bugs │────▶│ Errors │────▶│ OWASP │────▶│ Deploy │
- │ Scope │ │Keep/Drop │ │ Trace │ │ Repair │ │ Red Team │ │ Release │
- └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘ └──────────┘
- /autoresearch: /autoresearch /autoresearch: /autoresearch: /autoresearch: /autoresearch:
- plan debug fix security ship
- ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
- │ Probe │ │ Scenario │ │ Predict │ │ Reason │
- │ Require- │ │ Edge │ │ 5-Expert │ │ Debate │
- │ ments │ │ Cases │ │ Swarm │ │ Converge │
- └──────────┘ └──────────┘ └──────────┘ └──────────┘
- /autoresearch: /autoresearch: /autoresearch: /autoresearch:
- probe scenario predict reason
- ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐
- │ Learn │ │ Improve │ │ Eval │ │ Baseline │
- │ Docs │ │ Research │ │ Analyze │ │ Diff │
- │ Gen │ │ PRDs │ │ Results │ │ Verdict │
- └──────────┘ └──────────┘ └──────────┘ └──────────┘
- /autoresearch: /autoresearch: /autoresearch: /autoresearch:
- learn improve evals regression
- ```
- ---
- ## Why This Exists
- [Karpathy's autoresearch](https://github.com/karpathy/autoresearch) demonstrated that a 630-line Python script could autonomously improve ML models overnight — **100 experiments per night** — by following simple principles: one metric, constrained scope, fast verification, automatic rollback, git as memory.
- **Claude Autoresearch generalizes these principles to ANY domain.** Not just ML — code, content, marketing, sales, HR, DevOps, or anything with a number you can measure.
- **v2.1.0 is a major architecture rebuild.** The monolithic SKILL.md (813 lines, ~100K tokens per invocation) is replaced with a thin 41-line routing file and 12 self-contained command files (94–120 lines each, ~5–8K tokens per invocation). That is a **95% token reduction** with the same capability surface.
- ---
- ## How It Works
- ```
- LOOP (N iterations or until done):
- 1. Review current state + git history + results log
- 2. Pick the next change (based on what worked, what failed, what's untried)
- 3. Make ONE focused change
- 4. Git commit (before verification)
- 5. Run mechanical verification (tests, benchmarks, scores)
- 6. If improved → keep. If worse → git revert. If crashed → fix or skip.
- 7. Log the result
- 8. Repeat until N iterations complete or goal is met.
- ```
- Every improvement stacks. Every failure auto-reverts. Progress is logged in TSV format.
- ### The Setup Phase
- Before looping, Claude performs a one-time setup:
- 1. **Read context** — reads all in-scope files
- 2. **Define goal** — extracts or asks for a mechanical metric
- 3. **Define scope** — which files can be modified vs read-only
- 4. **Establish baseline** — runs verification on current state (iteration #0)
- 5. **Confirm and go** — shows setup, then begins the loop
- ### 8 Critical Rules
- | # | Rule |
- |---|------|
- | 1 | **Bounded by default** — every command has a default iteration count; unlimited is opt-in via `Iterations: unlimited` |
- | 2 | **Read before write** — understand full context before modifying |
- | 3 | **One change per iteration** — atomic changes; if it breaks, you know why |
- | 4 | **Mechanical search signal, independent acceptance** — no subjective "looks good"; the optimized metric never certifies behavior preservation |
- | 5 | **Automatic rollback** — failed changes revert instantly |
- | 6 | **Simplicity wins** — equal results + less code = keep |
- | 7 | **Git is memory** — experiments committed with `experiment:` prefix; agent reads `git log` + `git diff` before each iteration |
- | 8 | **When stuck, think harder** — re-read, combine near-misses, try radical changes |
- ---
- ## Hooks & Safety
- Hooks are defense-in-depth guardrails, not a security sandbox. Claude Code ships the hook surface natively; pi ships the same guardrails as extension events (`tool_call`, `before_agent_start`, `input`, `session_start`, `session_shutdown`). OpenCode, Codex, and Muse ship the core skill/runtime/install surface without hook parity.
- ### What's Protected
- | Hook | What it does | Event |
- |------|-------------|-------|
- | **scout-block** | Blocks node_modules/, .git/, __pycache__/, etc. from filling your context | PreToolUse |
- | **privacy-block** | Blocks .env, SSH keys, credentials from being read in sessions | PreToolUse |
- | **dangerous-cmd-block** | Blocks force-push, `rm -rf`, `git reset --hard` | PreToolUse |
- | **iteration-context** | Injects recent TSV iteration data after context compaction | UserPromptSubmit |
- | **subagent-context** | Gives subagents awareness of active loop state | SubagentStart |
- | **dev-rules-reminder** | Re-injects plan path and code standards after compaction | UserPromptSubmit |
- | **simplify-gate** | Warns at 400 LOC, blocks at 800 LOC before shipping | UserPromptSubmit |
- | **session-init** | Sets up project context at session start | SessionStart |
- | **stop-notify** | Terminal notification + optional webhook on session end | SessionEnd |
- ### Configuration
- All hooks are **on by default**. Disable individually only for troubleshooting:
- ```bash
- # Disable a specific hook
- export AR_DISABLE_SCOUT_BLOCK=1
- export AR_DISABLE_PRIVACY_BLOCK=1
- export AR_DISABLE_DANGEROUS_CMD_BLOCK=1
- # ... etc for each hook name
- ```
- Optional webhook for session completion notifications:
- ```bash
- export AR_NOTIFY_WEBHOOK=https://hooks.slack.com/services/...
- ```
- Customize blocked directories with a `.ckignore` file (gitignore syntax) at your project root.
- See [guide/hooks.md](guide/hooks.md) for full reference.
- Release preparation and contributor verification live in [scripts/release.md](scripts/release.md).
- ---
- ## Commands
- | Command | What it does | Default Iterations |
- |---------|--------------|--------------------|
- | `/autoresearch` | **Classic:** Core iterate loop: modify → verify → keep/discard · **Orchestrator:** free-form goal → auto-select pipeline → loop until predicate met | 25 / goal-bounded |
- | `/autoresearch:plan` | Convert goal into validated config | one-shot |
- | `/autoresearch:debug` | Hunt bugs via hypothesis iteration | 15 |
- | `/autoresearch:fix` | Crush errors one-by-one to zero | 20 |
- | `/autoresearch:security` | STRIDE + OWASP audit with red-team | 15 |
- | `/autoresearch:ship` | Ship through 8 phases | linear |
- | `/autoresearch:scenario` | Generate edge cases across 12 dimensions | 20 |
- | `/autoresearch:predict` | 5 expert personas debate | one-shot |
- | `/autoresearch:learn` | Scout → generate docs → validate → fix | 10 |
- | `/autoresearch:reason` | Adversarial debate with blind judges | 8 |
- | `/autoresearch:probe` | 8 personas interrogate requirements | 15 |
- | `/autoresearch:improve` | Research ICP, discover improvements, generate PRDs | 15 |
- | `/autoresearch:evals` | Analyze iteration results: trends, plateaus | one-shot |
- | `/autoresearch:regression` | Stability gate: baseline vs candidate, verdict STABLE/UNSTABLE | one-shot |
- **Universal flags:** `Iterations: N`, `Iterations: unlimited`, `--evals`, `--evals-interval N`, `--chain <targets>`, `--<subcommand>` shorthand.
- **All commands use interactive setup when invoked without arguments.** Just type the command — the agent asks for what it needs with smart defaults based on your codebase.
- > **OpenCode users:** Commands use underscore naming (`/autoresearch_debug`, `/autoresearch_fix`, etc.). All 14 commands available.
- >
- > **Codex users:** Invoke via `$autoresearch` mention syntax. Subcommands are keywords: `$autoresearch debug`, `$autoresearch plan`, etc.
- ### Quick Decision Guide
- | I want to... | Use |
- |--------------|-----|
- | Give a plain-language goal, let it self-orchestrate | `/autoresearch <goal>` (bare, no Metric/Verify) |
- | Improve test coverage / reduce bundle size / any metric | `/autoresearch` |
- | Run bounded iterations | Add `Iterations: N` to any command |
- | Don't know what metric to use | `/autoresearch:plan` |
- | Run a security audit | `/autoresearch:security` |
- | Ship a PR / deployment / release | `/autoresearch:ship` |
- | Optimize without breaking existing tests | Add `Guard: npm test` |
- | Hunt all bugs in a codebase | `/autoresearch:debug` |
- | Fix all errors (tests, types, lint) | `/autoresearch:fix` |
- | Debug then auto-fix | `/autoresearch:debug --fix` |
- | Check if something is ready to ship | `/autoresearch:ship --checklist-only` |
- | Explore edge cases for a feature | `/autoresearch:scenario` |
- | Generate test scenarios | `/autoresearch:scenario --format test-scenarios` |
- | Get expert opinions before starting | `/autoresearch:predict` |
- | Analyze from multiple angles then debug | `/autoresearch:predict --chain debug` |
- | Generate docs for a new codebase | `/autoresearch:learn --mode init` |
- | Update existing docs after changes | `/autoresearch:learn --mode update` |
- | Debate an architecture decision | `/autoresearch:reason --domain software` |
- | Surface hidden constraints before starting | `/autoresearch:probe` |
- | Pre-flight a fuzzy goal then loop | `/autoresearch:probe --chain plan,autoresearch` |
- | Discover what to build next for your ICP | `/autoresearch:improve` |
- | Research competitors and generate PRDs | `/autoresearch:improve --depth deep` |
- | Probe requirements then research improvements | `/autoresearch:probe --improve` |
- | Analyze trends and plateaus across past runs | `/autoresearch:evals` |
- | Check if a run has stalled | `/autoresearch:evals --file *-results.tsv` |
- | Verify a change won't regress before pushing | `/autoresearch:regression` |
- | Gate a PR: predict, fix, re-gate, then ship | `/autoresearch:regression --predict --fix --ship` |
- ---
- ## Quick Start
- ### Claude Code
- **Option A — npx install (recommended):**
- ```bash
- npx skills add uditgoenka/autoresearch
- ```
- All 14 commands are available after restarting Claude Code.
- **Option B — Plugin install:**
- ```
- /plugin marketplace add uditgoenka/autoresearch
- /plugin install autoresearch@autoresearch
- ```
- > **Note:** Start a new Claude Code session after installing. Reference files aren't resolvable in the same session where installation happened — this is a Claude Code platform limitation.
- **Updating (no reinstall needed):**
- ```
- /plugin update autoresearch
- ```
- Run `/reload-plugins` to activate. No need to uninstall or re-clone.
- **Option C — Manual copy:**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- # Copy skill + subcommands to your project
- cp -r autoresearch/.claude/skills/autoresearch .claude/skills/autoresearch
- cp -r autoresearch/.claude/commands/autoresearch .claude/commands/autoresearch
- cp autoresearch/.claude/commands/autoresearch.md .claude/commands/autoresearch.md
- ```
- Or install globally:
- ```bash
- cp -r autoresearch/.claude/skills/autoresearch ~/.claude/skills/autoresearch
- cp -r autoresearch/.claude/commands/autoresearch ~/.claude/commands/autoresearch
- cp autoresearch/.claude/commands/autoresearch.md ~/.claude/commands/autoresearch.md
- ```
- **Option D — Guided installer:**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cd autoresearch
- ./scripts/install.sh --claude --global
- ```
- ### OpenCode Quick Start
- **Option A — Guided installer (recommended):**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cd autoresearch
- ./scripts/install.sh --opencode --global
- ```
- **Option B — Manual copy:**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cp -r autoresearch/.opencode/skills/autoresearch .opencode/skills/autoresearch
- cp autoresearch/.opencode/commands/autoresearch*.md .opencode/commands/
- ```
- Or globally:
- ```bash
- cp -r autoresearch/.opencode/skills/autoresearch ~/.config/opencode/skills/autoresearch
- cp autoresearch/.opencode/commands/autoresearch*.md ~/.config/opencode/commands/
- ```
- > All 14 commands available as `/autoresearch_debug`, `/autoresearch_fix`, `/autoresearch_improve`, etc.
- ### Codex Quick Start
- **Option A — Guided installer (recommended):**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cd autoresearch
- ./scripts/install.sh --codex --global
- ```
- **Option B — Manual copy:**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cp -r autoresearch/.agents/skills/autoresearch ~/.codex/skills/autoresearch
- ```
- > Invoke via `$autoresearch` mention syntax. Subcommands are keywords: `$autoresearch plan`, `$autoresearch debug`, `$autoresearch evals`, etc.
- > The installed Codex package includes the bundled orchestrator and regression helpers under `plugins/autoresearch/skills/autoresearch/` and `.agents/skills/autoresearch/`.
- ### pi Quick Start
- **Option A — Guided installer (recommended):**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cd autoresearch
- ./scripts/install.sh --pi --global
- ```
- **Option B — pi package install:**
- ```bash
- pi install git:github.com/uditgoenka/autoresearch
- ```
- **Option C — Try without installing:**
- ```bash
- pi -e ./pi-extension
- ```
- > Invoke commands as pi prompt templates: `/autoresearch`, `/autoresearch_debug`, `/autoresearch_fix`, … (underscore names). The dispatcher is a skill: `/skill:autoresearch`.
- > The pi extension ports the Claude hook guardrails (scout/privacy/dangerous-cmd block, iteration context, simplify gate, stop-notify) to pi extension events. See [`pi-extension/README.md`](pi-extension/README.md) for the full hook→event mapping and `AR_DISABLE_*` flags.
- ### Muse Quick Start
- **Option A — Guided installer (recommended):**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- cd autoresearch
- ./scripts/install.sh --muse --global
- ```
- **Option B — Manual install with the Muse CLI:**
- ```bash
- git clone https://github.com/uditgoenka/autoresearch.git
- muse skills install autoresearch/.muse/skills/autoresearch --scope user
- ```
- Or project-local, so every Muse session in that project picks it up. Run it from your project folder:
- ```bash
- cd /path/to/your-project
- bash /path/to/autoresearch/scripts/install.sh --muse --local
- ```
- > Invoke by asking Muse to use the autoresearch skill with a subcommand keyword: `autoresearch plan`, `autoresearch debug`, `autoresearch fix`, etc.
- > The installed Muse package includes the bundled orchestrator and regression helpers under `.muse/skills/autoresearch/`.
- ### Run It
- ```
- /autoresearch
- Goal: Increase test coverage from 72% to 90%
- Scope: src/**/*.test.ts, src/**/*.ts
- Metric: coverage % (higher is better)
- Verify: npm test -- --coverage | grep "All files"
- Iterations: 25
- ```
- Claude reads all files, establishes a baseline, and starts iterating — one change at a time. Keeps improvements, auto-reverts failures, logs everything. Stops after N iterations or when you interrupt.
- ---
- ## /autoresearch:plan — Goal to Config
- The hardest part isn't the loop — it's defining Scope, Metric, and Verify correctly. `/autoresearch:plan` converts your plain-language goal into a validated, ready-to-execute configuration.
- ```
- /autoresearch:plan
- Goal: Make the API respond faster
- ```
- Walks through 5 steps: capture goal → define scope → define metric → define direction → validate verify command (dry-run). Every gate is mechanical — scope must resolve to files, metric must output a number, verify must pass a dry-run. Emits a `handoff.json` for chaining.
- ---
- ## /autoresearch:debug — Autonomous Bug Hunter
- Scientific method meets autoresearch loop. Doesn't stop at one bug — iteratively hunts ALL bugs using falsifiable hypotheses, evidence-based investigation, and 7 investigation techniques.
- ```
- /autoresearch:debug
- Scope: src/api/**/*.ts
- Symptom: API returns 500 on POST /users
- Iterations: 15
- ```
- **How it works:** Gather symptoms → Recon → Hypothesize (specific, testable) → Test (one experiment per iteration) → Classify (confirmed/disproven/inconclusive) → Log → Repeat.
- Every finding requires code evidence (file:line + reproduction steps). Every disproven hypothesis is logged — equally valuable.
- | Flag | Purpose |
- |------|---------|
- | `--fix` | After hunting, auto-switch to `/autoresearch:fix` |
- | `--scope <glob>` | Limit investigation scope |
- | `--symptom "<text>"` | Pre-fill symptom |
- | `--severity <level>` | Minimum severity to report |
- ---
- ## /autoresearch:fix — Autonomous Error Crusher
- Takes a broken state and iteratively repairs it until everything passes. ONE fix per iteration. Atomic, committed, verified, auto-reverted on failure.
- ```
- /autoresearch:fix
- Iterations: 20
- ```
- Auto-detects what's broken (tests, types, lint, build) → Prioritizes (blockers first) → Fixes ONE thing → Commits → Verifies error count decreased → Guard check → Keep/Revert → Repeat. **Stops automatically when error count hits zero.**
- | Flag | Purpose |
- |------|---------|
- | `--target <command>` | Explicit verify command |
- | `--guard <command>` | Safety command that must always pass |
- | `--category <type>` | Only fix specific type (test, type, lint, build) |
- | `--from-debug` | Read findings from latest debug session |
- **Chain them:** `/autoresearch:debug` → `/autoresearch:fix --from-debug`
- ---
- ## /autoresearch:security — Autonomous Security Audit
- Read-only security audit using STRIDE threat modeling, OWASP Top 10 sweeps, and red-team adversarial analysis with 4 hostile personas.
- ```
- /autoresearch:security
- Iterations: 15
- ```
- Codebase recon → asset inventory → trust boundaries → STRIDE threat model → attack surface map → autonomous testing loop → structured report. Every finding requires code evidence (file:line + attack scenario).
- | Flag | Purpose |
- |------|---------|
- | `--diff` | Only audit files changed since last audit |
- | `--fix` | Auto-fix confirmed Critical/High findings |
- | `--fail-on <severity>` | Exit non-zero for CI/CD gating |
- **Output:** Creates `security/{date}-{slug}/` with 7 structured report files.
- ---
- ## /autoresearch:ship — Universal Shipping Workflow
- Ship anything through 8 phases: **Identify → Inventory → Checklist → Prepare → Dry-run → Ship → Verify → Log.**
- ```
- /autoresearch:ship --auto
- ```
- Auto-detects what you're shipping (code PR, deployment, blog post, email campaign, sales deck, research paper, design assets) and generates domain-specific checklists — every item mechanically verifiable.
- | Flag | Purpose |
- |------|---------|
- | `--dry-run` | Validate everything but don't ship |
- | `--auto` | Auto-approve if checklist passes |
- | `--force` | Skip non-critical items (blockers still enforced) |
- | `--rollback` | Undo last ship action |
- | `--monitor N` | Post-ship monitoring for N minutes |
- | `--checklist-only` | Just check readiness |
- **9 supported types:** code-pr, code-release, deployment, content, marketing-email, marketing-campaign, sales, research, design.
- ---
- ## /autoresearch:scenario — Scenario Explorer
- Autonomous scenario exploration engine. Takes a seed scenario and iteratively generates situations across 12 dimensions — happy paths, errors, edge cases, abuse, scale, concurrency, temporal, data variation, permissions, integrations, recovery, and state transitions.
- ```
- /autoresearch:scenario
- Scenario: User attempts to checkout with multiple payment methods
- Iterations: 20
- ```
- Seed analysis → Decompose into 12 dimensions → Generate ONE situation per iteration → Classify (new/variant/duplicate) → Expand edge cases → Log → Repeat.
- | Flag | Purpose |
- |------|---------|
- | `--domain <type>` | software, product, business, security, marketing |
- | `--depth <level>` | shallow (10), standard (20), deep (50+) |
- | `--format <type>` | use-cases, user-stories, test-scenarios, threat-scenarios |
- | `--focus <area>` | edge-cases, failures, security, scale |
- ---
- ## /autoresearch:predict — Multi-Persona Prediction
- Before you debug, fix, or ship — get 5 expert perspectives in 2 minutes.
- Simulates a team (Architect, Security Analyst, Performance Engineer, Reliability Engineer, Devil's Advocate) who independently analyze your code, debate findings, and reach consensus.
- ```
- /autoresearch:predict --chain debug
- ```
- - `--chain debug` — pre-ranked hypotheses before debugging
- - `--chain security` — multi-persona red team analysis
- - `--chain scenario,debug,fix` — full quality pipeline
- ---
- ## /autoresearch:learn — Autonomous Documentation Engine
- Scout codebase → generate docs → validate → fix → repeat. 4 modes: init (create from scratch), update (refresh existing), check (read-only health report), summarize (quick overview).
- ```
- /autoresearch:learn --mode init --depth deep
- Iterations: 10
- ```
- Dynamic doc discovery, project-type detection, validation-fix loop, git-diff scoping for updates, selective single-doc update with `--file`. Auto-generates Mermaid architecture diagrams, API reference, testing guide, config guide, and cross-reference links.
- ---
- ## /autoresearch:reason — Adversarial Refinement
- Extends autoresearch to **subjective domains** where no objective metric exists. The blind judge panel is the fitness function.
- ```
- /autoresearch:reason
- Task: Should we use event sourcing for our order management system?
- Domain: software
- Iterations: 8
- ```
- **How it works:** Generate-A → Critic attacks → Author-B responds → Synthesizer merges → Blind judge panel (randomized labels) picks winner → Winner becomes new A → Repeat until convergence. Every agent is a cold-start fresh invocation — no history bleed.
- | Flag | Purpose |
- |------|---------|
- | `--judges N` | Judge count (3-7, odd preferred) |
- | `--convergence N` | Consecutive wins to converge (default 3) |
- | `--mode <mode>` | convergent (default), creative, debate |
- | `--domain <type>` | software, product, business, security, research, content |
- | `--chain <targets>` | Chain converged output to any autoresearch command |
- **Output:** Creates `reason/{date}-{slug}/` with lineage.md, candidates.md, judge-transcripts.md, reason-results.tsv, handoff.json.
- ---
- ## /autoresearch:probe — Adversarial Requirement Interrogation
- Eight adversarial personas interrogate user and codebase together until net-new constraints saturate. Output is the 5 autoresearch primitives (Goal/Scope/Metric/Direction/Verify) plus a `handoff.json` ready to feed any downstream command.
- ```
- /autoresearch:probe --chain plan,autoresearch
- Topic: Add multi-tenant isolation to the database layer
- ```
- **The 8 personas:** Skeptic, Edge-Case Hunter, Scope Sentinel, Ambiguity Detective, Contradiction Finder, Prior-Art Investigator, Success-Criteria Auditor, Constraint Excavator.
- | Flag | Purpose |
- |------|---------|
- | `--depth <level>` | shallow (5 rounds), standard (15), deep (30) |
- | `--adversarial` | Rotate Skeptic + Contradiction Finder + Edge-Case Hunter to front |
- | `--mode <mode>` | interactive (default) or autonomous |
- | `--chain <targets>` | plan, predict, debug, scenario, reason, fix, ship, learn |
- **Output:** Creates `probe/{date}-{slug}/` with probe-spec.md, constraints.tsv, autoresearch-config.yml, handoff.json.
- ---
- ## /autoresearch:improve — Product Improvement Engine
- Research what to build next. Discovers ICP challenges via deep multi-source research, scores and ranks improvements, generates per-feature PRDs with evidence chains.
- ```
- /autoresearch:improve
- Goal: Improve onboarding conversion
- ICP: B2B SaaS product managers at 50-500 person companies
- ```
- **How it works:** Resolve product context → Research across 5 categories (ICP challenges, competitor gaps, market trends, UX & experience, revenue & growth) → Saturate → ICP binary gate → Tiered ranking (Must-have / Nice-to-have / Moonshot) → User selects features → Generate PRDs.
- | Flag | Purpose |
- |------|---------|
- | `--icp "<text>"` | Ideal customer profile |
- | `--discover` | Force codebase scan even with existing context |
- | `--no-discover` | Skip auto-discover |
- | `--depth <level>` | shallow (5), standard (15), deep (30+) |
- | `--seeds <categories>` | Override default research categories |
- **Output:** Creates `improve/{date}-{slug}/` with research-findings.md, improvement-plan.md, per-feature PRDs, summary.md, improve-results.tsv, handoff.json.
- **Terminal emitter** — improve is the last link in any autoresearch chain. PRDs are consumed by external tools (`/ck:plan`, `/ck:cook`), not by other autoresearch commands.
- **Chain into improve:** `/autoresearch:probe --improve`, `/autoresearch:predict --improve`, `/autoresearch:debug --improve`.
- ---
- ## /autoresearch:evals — Results Analyzer
- Analyzes `*-results.tsv` files from any autoresearch run. Surfaces trends, plateau detection, convergence signals, and iteration efficiency. Backward compatible with v2.0.x TSV format.
- ```
- /autoresearch:evals
- /autoresearch:evals --file coverage-results.tsv
- ```
- **Adaptive checkpoints:** floor(max_iterations/3), minimum 1 checkpoint. Reports per-checkpoint delta, stall detection, best iteration, and a recommendation (continue / stop / change strategy).
- **Inline evals during a run:**
- ```
- /autoresearch
- Goal: Reduce bundle size below 200kb
- Iterations: 30
- --evals-interval 10
- ```
- Prints a checkpoint report every 10 iterations without interrupting the loop.
- ---
- ## /autoresearch:regression — Stability Gate
- Before you push, prove the change didn't break what already worked. Captures baseline behavior from a `git worktree` of the base ref, diffs the candidate across **8 dimensions**, and emits a single **STABLE / UNSTABLE** verdict.
- ```
- /autoresearch:regression --predict --evals --fix --ship
- ```
- **Core invariant:** a regression is a **green→red transition only**. Pre-existing failures (red→red), new tests (absent→red), and flaky tests (flake→red) are classified and excluded — never counted as regressions.
- **Tiered verdict:**
- - **HARD gate** (any green→red = UNSTABLE): `functional`, `api-contract`, `data-migration`, `integration-e2e`
- - **SCORE** (0–100, noise-tolerant, weighted; UNSTABLE below threshold 95): `flakiness` .30, `performance` .30, `resource` .20, `visual-ui` .20
- | Flag | Purpose |
- |------|---------|
- | `--select auto` | Use detected affected-test mapper (jest `--findRelatedTests`, nx affected) else FULL suite — never a silent subset |
- | `--samples N` / `--noise-band %` | Tune the perf statistical gate (default 7 samples/side, Mann–Whitney U) |
- | `--fix` / `--fix-cycles N` | Re-gate after fixing; each cycle must strictly shrink the blocking-set (max 3) |
- | `--predict` | Pre-empt likely regressions before the gate runs |
- | `--reason` | Adversarial root-cause when a regression's cause is ambiguous |
- | `--debug` | Force the bisect Hunter (HARD dims passing 3/3 reproduction) |
- | `--max-runs N` | Ceiling on dims×axes×samples×cells (warn+confirm past 200) |
- **Output:** Creates `regression/{date}-{slug}/` with regression-results.tsv, stability-report.md, dimensions/<dim>.md, baseline/, evals-summary.md, handoff.json.
- > **data-migration is hard-guarded:** opt-in, and refuses any DB URL that isn't ephemeral/allowlisted (`*test*`, `*ci*`, container). Migrations are forward-only by default.
- ---
- ## Guard — Prevent Regressions
- When optimizing a metric, the loop might break existing behavior. **Guard** is an optional safety net.
- ```
- /autoresearch
- Goal: Reduce API response time to under 100ms
- Verify: npm run bench:api | grep "p95"
- Guard: npm test
- ```
- - **Verify** = "Did the metric improve?" (the goal)
- - **Guard** = "Did anything else break?" (the safety net)
- If the metric improves but the guard fails, Claude reworks the optimization (up to 2 attempts). Guard/test files are never modified.
- > **Credit:** Guard was contributed by [@pronskiy](https://github.com/pronskiy) (JetBrains) in [PR #7](https://github.com/uditgoenka/autoresearch/pull/7).
- ---
- ## Results Tracking
- Every iteration is logged in TSV format:
- ```tsv
- iteration commit metric delta status description
- 0 a1b2c3d 85.2 0.0 baseline initial state
- 1 b2c3d4e 87.1 +1.9 keep add tests for auth edge cases
- 2 - 86.5 -0.6 discard refactor test helpers (broke 2 tests)
- 3 c3d4e5f 88.3 +1.2 keep add error handling tests
- ```
- Run `/autoresearch:evals` at any time to analyze trends across any TSV file. Adaptive checkpoints fire at floor(max_iterations/3) intervals.
- ---
- ## Crash Recovery
- | Failure | Response |
- |---------|----------|
- | Syntax error | Fix immediately, don't count as iteration |
- | Runtime error | Attempt fix (max 3 tries), then move on |
- | Resource exhaustion | Revert, try smaller variant |
- | Infinite loop / hang | Kill after timeout, revert |
- | External dependency | Skip, log, try different approach |
- ---
- ## Repository Structure
- ```
- autoresearch/
- ├── README.md
- ├── COMPARISON.md ← Karpathy's vs Claude Autoresearch
- ├── guide/ ← Guides — one per command + advanced patterns
- ├── scripts/
- │ ├── install.sh ← Guided installer (Claude Code + OpenCode + Codex + Muse)
- │ ├── transform.sh ← Single transform: .claude/ → .opencode/ + .agents/ + .muse/
- │ ├── release.sh ← Release automation
- │ └── release.md ← Release checklist
- ├── .claude/
- │ ├── skills/autoresearch/
- │ │ ├── SKILL.md ← Thin routing table (41 lines)
- │ │ └── references/ ← 3 focused reference files
- │ │ ├── security-checklist.md ← STRIDE + OWASP
- │ │ ├── predict-personas.md ← 5 personas + adversarial set
- │ │ └── reason-judge-protocol.md ← Adversarial refinement loop
- │ └── commands/
- │ ├── autoresearch.md ← Core loop (self-contained, ~100 lines)
- │ └── autoresearch/ ← 13 subcommand files (self-contained)
- │ ├── plan.md
- │ ├── debug.md
- │ ├── fix.md
- │ ├── security.md
- │ ├── ship.md
- │ ├── scenario.md
- │ ├── predict.md
- │ ├── learn.md
- │ ├── reason.md
- │ ├── improve.md
- │ ├── probe.md
- │ ├── evals.md
- │ └── regression.md
- ├── .opencode/ ← OpenCode port (via transform.sh)
- │ ├── skills/autoresearch/
- │ └── commands/ ← 14 command files (autoresearch_*.md)
- ├── .agents/ ← Codex port (via transform.sh)
- │ └── skills/autoresearch/
- ├── .muse/ ← Muse port (via transform.sh)
- │ └── skills/autoresearch/
- ├── plugins/ ← Codex plugin metadata
- │ └── openai.yaml
- └── LICENSE
- ```
- ---
- ## FAQ
- **Q: I don't know what metric to use.**
- A: Run `/autoresearch:plan` — it analyzes your codebase, suggests metrics, and dry-runs the verify command before you launch.
- **Q: What changed in v2.2.0?**
- A: The root `/autoresearch` command now supports an autonomous orchestrator mode. Type a plain-language goal (e.g., `/autoresearch help me fix the login bug`) instead of `Metric:`/`Verify:` and the orchestrator classifies your goal, derives a verifiable Success predicate, confirms it once, then loops across subcommands until done. Classic metric-loop behavior is unchanged when `Metric:` or `Verify:` are present.
- **Q: What changed in v2.1.0?**
- A: Architecture rebuild. The monolithic SKILL.md (813 lines, ~100K tokens) is replaced with a thin routing file + 12 self-contained command files (~5–8K tokens each). 95% token reduction. A new `/autoresearch:evals` command analyzes iteration results. Every looping command now has a bounded default instead of running unlimited.
- **Q: How do bounded defaults work?**
- A: Every looping command ships with a sensible default (e.g., `/autoresearch` defaults to 25 iterations). Override inline: `Iterations: 50` for more, `Iterations: unlimited` for the old unbounded behavior.
- **Q: How does /autoresearch:evals work?**
- A: Point it at any `*-results.tsv` file from a previous run. It reports trends, plateau detection, and a recommendation. Use `--evals-interval N` during a live run to get checkpoint reports without interrupting the loop.
- **Q: Does this work with any project?**
- A: Yes. Any language, framework, or domain. Install via plugin (Claude Code), installer script, or manual copy.
- **Q: Does this work with OpenCode?**
- A: Yes. Run `./scripts/install.sh --opencode --global` or manually copy `.opencode/` files. Commands use underscore naming (`/autoresearch_debug`, `/autoresearch_evals`, etc.). All 14 commands available.
- **Q: Does this work with OpenAI Codex?**
- A: Yes. Run `./scripts/install.sh --codex --global` or copy `.agents/skills/autoresearch/` to `~/.codex/skills/autoresearch`. Invoke via `$autoresearch` mention syntax.
- **Q: Does this work with Muse?**
- A: Yes. Run `./scripts/install.sh --muse --global`, or `muse skills install autoresearch/.muse/skills/autoresearch --scope user`. Ask Muse to use the autoresearch skill with a subcommand keyword (`autoresearch plan`, `autoresearch debug`, etc.). Hook guardrails are Claude Code-only.
- **Q: How do I stop the loop?**
- A: `Ctrl+C` or add `Iterations: N` to your inline config. Claude commits before verifying, so your last successful state is always in git.
- **Q: Can I use this for non-code tasks?**
- A: Absolutely. Sales emails, marketing copy, HR policies, runbooks — anything with a measurable metric. See [Examples by Domain](guide/examples-by-domain.md).
- **Q: Does /autoresearch:security modify my code?**
- A: No. Read-only by default. Use `--fix` to opt into auto-remediation of confirmed Critical/High findings.
- **Q: What's the difference between /autoresearch:predict and /autoresearch:reason?**
- A: Predict is a one-shot analysis — 5 experts debate your existing code. Reason is an iterative refinement loop — competing candidates are generated, critiqued, synthesized, and blind-judged over multiple rounds until convergence. Use predict for analysis before acting; use reason for decisions where no objective metric exists.
- **Q: What is handoff.json?**
- A: A structured file emitted by plan, probe, reason, and other commands that carries Goal/Scope/Metric/Verify config for downstream commands. When you `--chain plan,autoresearch`, the chain reads handoff.json automatically.
- ---
- ## Contributing
- Contributions welcome. See [CONTRIBUTING.md](CONTRIBUTING.md).
- Areas of interest: new domain examples, verification script templates, CI/CD integrations, real-world benchmarks. All guides are in [guide/](guide/).
- ---
- ## Star History
- <a href="https://www.star-history.com/?repos=uditgoenka%2Fautoresearch&type=timeline&legend=top-left">
- <picture>
- <source media="(prefers-color-scheme: dark)" srcset="https://api.star-history.com/image?repos=uditgoenka/autoresearch&type=timeline&theme=dark&legend=bottom-right&v=20260319" />
- <source media="(prefers-color-scheme: light)" srcset="https://api.star-history.com/image?repos=uditgoenka/autoresearch&type=timeline&legend=bottom-right&v=20260319" />
- <img alt="Star History Chart" src="https://api.star-history.com/image?repos=uditgoenka/autoresearch&type=timeline&legend=bottom-right&v=20260319" />
- </picture>
- </a>
- ---
- ## License
- MIT — see [LICENSE](LICENSE).
- ---
- ## Credits
- - **[Andrej Karpathy](https://github.com/karpathy)** — for [autoresearch](https://github.com/karpathy/autoresearch)
- - **Cai, Ziakas, Kontonis, Pearce, Sen, Krishnamurthy, Garg, Papailiopoulos** — for [Fork-and-Flush](https://arxiv.org/abs/2610.07447)
- - **Zhang, Ji, Sun, Li, et al.** — for [Stateless Language Agents](https://arxiv.org/abs/2610.07625) (the Advisor behind guided branches)
- - **[Anthropic](https://anthropic.com)** — for [Claude Code](https://docs.anthropic.com/en/docs/claude-code) and the skills system
- - **[OpenCode](https://opencode.ai)** — for the OpenCode terminal agent
- - **[OpenAI](https://openai.com)** — for [Codex](https://developers.openai.com/codex) and the agent skills standard
- ---
- <div align="center">
- ## About the Author
- <a href="https://udit.co">
- <img src="https://avatars.githubusercontent.com/uditgoenka" width="80" style="border-radius: 50%;" alt="Udit Goenka" />
- </a>
- **[Udit Goenka](https://udit.co)** — AI Product Expert, Founder & Angel Investor
- Self-taught builder who went from a slow internet connection in India to founding multiple companies and helping 700+ startups generate over ~$25m in revenue.
- **Building:** [TinyCheque](https://tinycheque.com) (India's first agentic AI venture studio) · [Firstsales.io](https://firstsales.io) (sales automation)
- **Investing:** 38 startups backed, 6 exits. Focused on early-stage AI and SaaS.
- **Connect:** [udit.co](https://udit.co) · [@iuditg](https://x.com/iuditg) · [@uditgoenka](https://github.com/uditgoenka) · [Newsletter](https://udit.co/blog)
- > *"Autonomy scales when you constrain scope, clarify success, mechanize verification, and let agents optimize tactics while humans optimize strategy."*
- </div>
.agents/skills/autoresearch/scripts/orchestrate.sh · Bundled script · 614 lines · 3 findings marked
- #!/usr/bin/env bash
- # orchestrate.sh — deterministic seam for the autoresearch orchestrator loop.
- #
- # classify <goal-string> → Goal archetype label (keyword heuristics)
- # next-hop <state.json> → Next subcommand from router decision table
- # units <results.json> → Units-remaining scalar (lower_is_better)
- # plateau <state.json> → Exit 0 if last N computed values are flat-or-worse
- # screen-cmd <shell-string> → "ok" exit 0 | "refuse" exit 1 safety gate
- # verdict <state.json> → CONVERGED|FORK|PLATEAU|CEILING|BLOCKED + ship-gate
- #
- # All subcommands are pure and CI-usable via exit codes.
- set -uo pipefail
- # Fork-and-flush rounds a plateaued loop runs before verdict gives up. The
- # fork-and-flush paper (arXiv:2610.07447) schedules two rounds per run, at 33%
- # and 66% of the budget; a third rarely pays for its ~24% of budget.
- FORK_ROUNDS_BEFORE_PLATEAU=2
- # ---------------------------------------------------------------------------
- # classify: map a goal string to one of the 9 Goal archetype labels.
- # Priority order matters: higher-stakes archetypes checked first so that
- # "fix and add the broken feature" → fix-broken, not build-feature.
- # ---------------------------------------------------------------------------
- classify() {
- local goal="${1:?usage: classify <goal-string>}"
- local g
- g=$(printf '%s' "$goal" | tr '[:upper:]' '[:lower:]')
- # Keywords match at a word start, so "prefix" is not "fix" and "address" is not "add".
- # Compounds that should still match (debug, hotfix, rebuild) are listed by name.
- # Security/hardening — above build because "secure" is higher stakes than "add"
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(secure|insecure|harden|vuln)'; then
- echo "harden"; return 0
- fi
- # Broken/bugfix
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(fix|bug|broken|hotfix|bugfix)|^[[:space:]]*debug'; then
- echo "fix-broken"; return 0
- fi
- # debug anywhere else, with no build verb present, is still a bug hunt
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])debug' \
- && ! printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])((re)?(build|implement)|add(s|ed|ing)?([^[:alnum:]_]|$))'; then
- echo "fix-broken"; return 0
- fi
- # Ship/release/deploy
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(re)?(ship|release|deploy)'; then
- echo "ship-ready"; return 0
- fi
- # Product direction — requires a "what …" question so bare "next"/"build" in a
- # build-feature goal (e.g. "build the next-gen parser") doesn't mis-route here.
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(what.*build|what.*next)'; then
- echo "what-to-build"; return 0
- fi
- # Build/implement/add — "feature" alone is insufficient; any of these words qualify
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])((re)?(build|implement)|add(s|ed|ing)?([^[:alnum:]_]|$))'; then
- echo "build-feature"; return 0
- fi
- # Metric optimization
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(faster|smaller|reduce|optimize|coverage)'; then
- echo "optimize-metric"; return 0
- fi
- # Documentation
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(document|docs)'; then
- echo "document"; return 0
- fi
- # Design decision — "should we" / "decide" / "approach"
- if printf '%s' "$g" | grep -qE '(^|[^[:alnum:]_])(should we|decide|approach)'; then
- echo "decide-design"; return 0
- fi
- # Default: open-ended investigation
- echo "explore"
- }
- # ---------------------------------------------------------------------------
- # next-hop: cheap router over fields in a state JSON file.
- # Decision order: errors → regression → untested gaps → ship/DONE.
- # ---------------------------------------------------------------------------
- next-hop() {
- local state_file="${1:?usage: next-hop <state.json>}"
- if [[ ! -f "$state_file" ]]; then
- echo "ERROR: missing state file" >&2; return 2
- fi
- # Parse with sed/grep — no jq dependency (score-regression.sh doesn't use jq)
- local errors regression gaps archetype
- errors=$(grep -o '"errors_remaining"[[:space:]]*:[[:space:]]*[0-9]*' "$state_file" \
- | grep -o '[0-9]*$')
- regression=$(grep -o '"regression_verdict"[[:space:]]*:[[:space:]]*"[^"]*"' "$state_file" \
- | grep -o '"[^"]*"$' | tr -d '"')
- gaps=$(grep -o '"untested_gaps"[[:space:]]*:[[:space:]]*[0-9]*' "$state_file" \
- | grep -o '[0-9]*$')
- archetype=$(grep -o '"archetype"[[:space:]]*:[[:space:]]*"[^"]*"' "$state_file" \
- | grep -o '"[^"]*"$' | tr -d '"')
- # Optional: pending_verify gates an independent acceptance check before DONE/ship.
- # Absent (or false) → routing is identical to prior behavior.
- local pending
- pending=$(grep -o '"pending_verify"[[:space:]]*:[[:space:]]*[a-z]*' "$state_file" \
- | grep -o '[a-z]*$')
- # Guard: missing required fields
- if [[ -z "$errors" || -z "$regression" || -z "$gaps" ]]; then
- echo "ERROR: malformed state file" >&2; return 2
- fi
- if [[ "$errors" -gt 0 ]]; then
- echo "fix"; return 0
- fi
- if [[ "$regression" == "UNSTABLE" ]]; then
- echo "regression"; return 0
- fi
- if [[ "$gaps" -gt 0 ]]; then
- echo "debug"; return 0
- fi
- # Gaps clear but an accepted high-impact change still needs a fresh, independent
- # acceptance check (separate from the signal used to choose it) → verify first.
- if [[ "$pending" == "true" ]]; then
- echo "verify"; return 0
- fi
- # All clear: ship if archetype has ship in the pipeline, else DONE
- if [[ "$archetype" == "ship-ready" ]]; then
- echo "ship"; return 0
- fi
- echo "DONE"
- }
- # ---------------------------------------------------------------------------
- # units: compute Units-remaining scalar from a results JSON file.
- # Formula: failing_tests + open_hard_regressions + (metric_delta / metric_target)
- # Prints "unknown" and exits 2 when inputs are missing or uncomputable.
- # ---------------------------------------------------------------------------
- units() {
- local results_file="${1:?usage: units <results.json>}"
- if [[ ! -f "$results_file" ]]; then
- echo "unknown"; return 2
- fi
- local ft regressions delta target
- ft=$(grep -o '"failing_tests"[[:space:]]*:[[:space:]]*[0-9.]*' "$results_file" \
- | grep -o '[0-9.]*$')
- regressions=$(grep -o '"open_hard_regressions"[[:space:]]*:[[:space:]]*[0-9.]*' "$results_file" \
- | grep -o '[0-9.]*$')
- delta=$(grep -o '"metric_delta"[[:space:]]*:[[:space:]]*[0-9.]*' "$results_file" \
- | grep -o '[0-9.]*$')
- target=$(grep -o '"metric_target"[[:space:]]*:[[:space:]]*[0-9.]*' "$results_file" \
- | grep -o '[0-9.]*$')
- if [[ -z "$ft" || -z "$regressions" || -z "$delta" || -z "$target" ]]; then
- echo "unknown"; return 2
- fi
- # Integer check: metric_target must be non-zero to avoid divide-by-zero
- if awk -v t="$target" 'BEGIN { exit !(t + 0 == 0) }'; then
- echo "unknown"; return 2
- fi
- # awk handles floating point; strip trailing .0 for clean integer output
- awk -v ft="$ft" -v r="$regressions" -v d="$delta" -v t="$target" '
- BEGIN {
- val = ft + r + (d / t)
- # Strip unnecessary trailing zeros (e.g. 4.500 → 4.5, 0.000 → 0)
- if (val == int(val)) printf "%d\n", val
- else printf "%g\n", val
- }
- '
- }
- # ---------------------------------------------------------------------------
- # plateau: read state.units_remaining; determine if progress has stalled.
- # Skips interleaved "unknown" cycles; N=5 consecutive trailing unknowns = BLOCKED.
- # Exit 0 = plateau (no net progress); exit 1 = still improving; exit 3 = BLOCKED.
- # ---------------------------------------------------------------------------
- plateau() {
- local state_file="${1:?usage: plateau <state.json>}"
- node - "$state_file" <<'NODE'
- const fs = require('fs');
- const n = 5;
- const blocked = () => { console.log('BLOCKED'); process.exit(3); };
- let history;
- try {
- const state = JSON.parse(fs.readFileSync(process.argv[2], 'utf8'));
- history = state.units_remaining;
- if (!Array.isArray(history) || history.some(value =>
- value !== 'unknown' && (typeof value !== 'number' || !Number.isFinite(value) || value < 0))) {
- blocked();
- }
- } catch {
- blocked();
- }
- let trailingUnknown = 0;
- for (let i = history.length - 1; i >= 0 && history[i] === 'unknown'; i--) trailingUnknown++;
- const values = history.filter(value => value !== 'unknown');
- // An uncomputable runner is BLOCKED; unknown cycles never count as zero progress.
- if (trailingUnknown >= n || values.length === 0) blocked();
- if (values.length < n) process.exit(1);
- // Lower is better. Oscillation with no net improvement is a plateau too.
- process.exit(values[values.length - 1] < values[values.length - n] ? 1 : 0);
- NODE
- }
- # ---------------------------------------------------------------------------
- # screen-cmd: safety gate for shell strings before execution.
- # Prints "ok" / "refuse". Database hosts other than localhost, 127.0.0.1 or a
- # single-label name that starts with a letter need a _test or _ci dbname suffix.
- # Bare substring "test" inside words like "latest" or "precision" must NOT qualify.
- # ---------------------------------------------------------------------------
- screen-cmd() {
- local cmd="${1:?usage: screen-cmd <shell-string>}"
- # A control byte (other than tab and newline) can confuse the readers below, and a
- # backslash before a newline joins two lines into one word (r\<newline>m is rm).
- # Both are refused as a whole kind.
- if printf '%s' "$cmd" | tr -d '\t\n' | LC_ALL=C grep -q '[[:cntrl:]]' \
- || [[ "$cmd" == *\\$'\n'* ]]; then
- echo "refuse"; return 1
- fi
- # The shell drops quotes and backslashes before it runs a name, so 'rm' and \rm are rm.
- local bare=${cmd//[\"\'\\]/}
- # $IFS and brace lists ({rm,-rf,/}) turn into spaces when bash runs them.
- bare=${bare//\$\{IFS\}/ }
- bare=${bare//\$IFS/ }
- bare=${bare//[\{\},]/ }
- # This check cannot expand variables, substitutions or brace lists, and each one can
- # build a name (${X}m, $X, r``m, `printf rm`, $'\x72m', r{m,}). So it refuses the whole
- # kind: any backtick, and any $ outside single quotes unless a closing double quote, a
- # space or the line end follows it (grep "ok$" is fine). A brace list outside quotes is
- # refused too. The scan below reads quotes the way bash does: a backslash escapes the
- # next character, and a single quote inside double quotes is just a character.
- # $"..." is a quoted string to bash, so it is marked like a backtick and refused.
- # Each quoted part is also kept (joined by \002) so a script passed to a nested shell
- # can be checked on its own.
- local scan live unquoted parts
- scan=$(printf '%s' "$cmd" | awk -v sq="'" -v dq='"' -v bs='\\' 'BEGIN { RS = "\001" } {
- q = ""; a = ""; b = ""; part = ""; parts = ""
- for (i = 1; i <= length($0); i++) {
- c = substr($0, i, 1)
- if (q == sq) { if (c == sq) { q = ""; a = a c; b = b c; parts = parts part "\002"; part = "" } else part = part c; continue }
- if (c == bs) { i++; a = a "_"; if (q == "") b = b "_"; else part = part c substr($0, i, 1); continue }
- if (q == dq) { a = a c; if (c == dq) { q = ""; b = b c; parts = parts part "\002"; part = "" } else part = part c; continue }
- if (c == "$" && substr($0, i + 1, 1) == dq) a = a "`"
- if (c == sq || c == dq) q = c
- a = a c; b = b c
- }
- printf "%s\001%s\001%s", a, b, parts part
- }')
- live=${scan%%$'\001'*}
- unquoted=${scan#*$'\001'}
- parts=${unquoted#*$'\001'}
- unquoted=${unquoted%%$'\001'*}
- if printf '%s' "$live" | grep -qE '`|\$[^"[:space:]]' \
- || printf '%s' "$unquoted" | grep -qE '\{[^[:space:]{}]*(,|\.\.)[^[:space:]{}]*\}'; then
- echo "refuse"; return 1
- fi
- # A glob in a command name (r?, /bin/r[m], sudo r*) can match any program, so a glob
- # in the first word of a command, after assignments, reserved words, flags and
- # numbers, is refused. After a launcher, every later word is checked, because an
- # option value (sudo -u root) can come before the name. Globs in arguments
- # (ls *.txt) and the test commands [ and [[ stay fine.
- # Every line is read, and a redirect target (>x, 2>/dev/null) is dropped first so it
- # cannot stand in for the command name.
- if printf '%s' "$unquoted" | awk '{
- line = $0; gsub(/[0-9]*[<>]+[&|]?[[:space:]]*[^[:space:];&|(){}<>]*/, " ", line)
- n = split(line, segs, /[;&|(){}<>]/)
- for (s = 1; s <= n; s++) {
- w = split(segs[s], words, /[[:space:]]+/)
- launched = 0
- for (k = 1; k <= w; k++) {
- x = words[k]
- if (x == "" || x ~ /^[A-Za-z_][A-Za-z0-9_]*=/ || x ~ /^-/ || x ~ /^[0-9]+$/) continue
- if (x ~ /^(if|then|else|elif|do|while|until|!)$/) continue
- y = x; sub(/^[^[:space:]]*[\/]/, "", y)
- if (y ~ /^(sudo|doas|env|exec|command|builtin|nohup|time|nice|ionice|timeout|xargs|stdbuf|chrt|taskset|eval)$/) { launched = 1; continue }
- if (x == "[" || x == "[[") break
- if (x ~ /[*?[]/) found = 1
- if (!launched) break
- }
- }
- }
- END { exit !found }'; then
- echo "refuse"; return 1
- fi
- # A shell or eval runs its quoted script as a new command, so each quoted part is
- # screened on its own too: bash -c 'X=rm; $X -rf /' and eval 'r? -rf /' are seen.
- # The outer shell drops the backslash in \$ and \`, so the inner script sees a live
- # expansion; those are refused outright when a nested shell is present.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`<>])([^[:space:];&|(){`<>]*/)?(eval|sh|bash|zsh|dash|ksh|fish|source|su)([[:space:];&|()<>]|$)' \
- || printf '%s' "$bare" | grep -qE '(^|[;&|(){`])[[:space:]]*\.[[:space:]]'; then
- if [[ "$cmd" == *'\$'* || "$cmd" == *'\`'* ]]; then echo "refuse"; return 1; fi
- local part
- while IFS= read -r -d $'\002' part; do
- [[ -n "${part//[[:space:]]/}" ]] || continue
- screen-cmd "$part" >/dev/null || { echo "refuse"; return 1; }
- done <<< "$parts"$'\002'
- fi
- # env -S splits one argument into a new command line that the matchers cannot read.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`<>])([^[:space:];&|(){`<>]*/)?env([[:space:]]+[^[:space:];&|()<>]+)*[[:space:]]+(-[a-zA-Z]*S|--split-string)'; then
- echo "refuse"; return 1
- fi
- # Each command matcher below starts at a space, ; & | ( ) { ` $ < or >, so `true;rm -rf /`
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 318 on GitHub
- # and `$(rm -rf ~)` are seen too. Flags are read from $bare, so rm "-rf" / is too.
- Note: Quoted as data in code: Runs `rm -rf` against a root or home-directory path
- Line 319 on GitHub
- # rm with recursive AND force, in any flag arrangement: bundled (-rf/-Rf/-fr),
- # separate (-r -f), or long (--recursive --force). Both flags must be present.
- # The optional path prefix catches path-qualified invocations (/bin/rm, ./rm,
- # /usr/local/bin/rm) that a bare command-name anchor would miss.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?rm([[:space:];&|()<>]|$)'; then
- local rm_rec=0 rm_force=0
- printf '%s' "$bare" | grep -qE -- '(^|[[:space:]])-[a-zA-Z]*[rR]|(^|[[:space:]])--r(e(c(u(r(s(i(ve?)?)?)?)?)?)?)?([^[:alnum:]_-]|$)' && rm_rec=1
- printf '%s' "$bare" | grep -qE -- '(^|[[:space:]])-[a-zA-Z]*[fF]|(^|[[:space:]])--f(o(r(ce?)?)?)?([^[:alnum:]_-]|$)' && rm_force=1
- if [[ "$rm_rec" -eq 1 && "$rm_force" -eq 1 ]]; then
- echo "refuse"; return 1
- fi
- fi
- # curl/wget piped to an interpreter (sh/bash/zsh/dash/fish/ksh/python/perl/ruby/
- # node/php), including a path-qualified one (| /bin/bash). Enumerated interpreters
- # rather than "refuse any curl pipe" so a legitimate derived predicate that pipes
- # curl output to a parser (jq/grep/awk) is not falsely refused.
- if printf '%s' "$bare" | grep -qE '(curl|wget)[^|]*\|[[:space:]]*([^[:space:]]*/)?(sh|bash|zsh|dash|fish|ksh|python[0-9.]*|perl|ruby|node|php)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # curl/wget piped through a launcher (sudo, env, exec, ...) into an interpreter.
- if printf '%s' "$bare" | grep -qE '(curl|wget)[^|]*\|[[:space:]]*(sudo|doas|env|exec|command|nohup|time)([[:space:]]+[^[:space:]|]+)*[[:space:]]+([^[:space:]]*/)?(sh|bash|zsh|dash|fish|ksh|python[0-9.]*|perl|ruby|node|php)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # A remote payload run without a pipe: bash <(curl ...), source <(curl ...),
- Note: Runs a downloaded script through process substitution (bash <(curl …))
- Line 346 on GitHub
- # bash -c "$(curl ...)", eval "$(curl ...)".
- if printf '%s' "$bare" | grep -qE '((sh|bash|zsh|dash|fish|ksh|python[0-9.]*|perl|ruby|node|php)|source|\.)[[:space:]]+(<[[:space:]]*)?<\([[:space:]]*(curl|wget)'; then
- echo "refuse"; return 1
- fi
- if printf '%s' "$bare" | grep -qE '((sh|bash|zsh|dash|fish|ksh|python[0-9.]*|perl|ruby|node|php)([[:space:]]+([^[:space:];&|]|[<>]&|&>)+)*[[:space:]]+-[a-zA-Z]*c[a-zA-Z]*|eval)[[:space:]]+["'"'"']?(\$\(|`)[[:space:]]*(curl|wget)'; then
- echo "refuse"; return 1
- fi
- # curl/wget routed through xargs into an interpreter. The xargs wrapper sidesteps the
- # direct pipe matcher above, so a remote payload still reaches a shell.
- if printf '%s' "$bare" | grep -qE '(curl|wget)[^|]*\|.*xargs.*[[:space:]]([^[:space:]]*/)?(sh|bash|zsh|dash|ksh|python[0-9.]*|perl|ruby|node|php)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # Output piped to netcat exfiltrates data off-host.
- if printf '%s' "$bare" | grep -qE '\|[[:space:]]*([^[:space:]]*/)?(nc|ncat|netcat)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # Raw block-device write — dd target or shell redirect onto a disk device wipes it.
- # Scoped to real device families (incl. SD/eMMC mmcblk, mdadm md, device-mapper dm-)
- # so dd/redirect to /dev/null or a regular file stays ok.
- if printf '%s' "$bare" | grep -qE '(of=|>[[:space:]]*)/dev/(sd|hd|vd|nvme|disk|mapper|loop|xvd|mmcblk|md|dm-)'; then
- echo "refuse"; return 1
- fi
- # Filesystem format destroys everything on a partition. Optional path prefix catches a
- # path-qualified invocation (/sbin/mkfs.ext4) that a bare-name anchor would miss.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?(mkfs|mke2fs)'; then
- echo "refuse"; return 1
- fi
- # find ... -delete mass-removes matched files. Both tokens required so a plain find
- # search (no -delete) is not refused; optional path prefix catches /usr/bin/find.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?find([[:space:];&|()<>]|$)' \
- && printf '%s' "$bare" | grep -qE '[[:space:]]-delete([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # shred overwrites then unlinks — irrecoverable.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?shred([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # truncate to zero size destroys file contents in place. Non-zero sizes are allowed.
- # Optional path prefix catches /usr/bin/truncate; size matcher covers -s 0, -s0,
- # --size 0, and --size=0.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?truncate([[:space:];&|()<>]|$)' \
- && printf '%s' "$bare" | grep -qE '(-s[[:space:]]*0|--size[[:space:]]*=?[[:space:]]*0)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # Recursive chmod to a zero mode locks an entire tree out of access. Scoped to the
- # zero lock-out (000/00/0 octal short forms) so ordinary recursive permission changes
- # are not refused; optional path prefix catches /bin/chmod.
- if printf '%s' "$bare" | grep -qE '(^|[[:space:];&|(){`\\$<>])([^[:space:];&|(){`<>]*/)?chmod([[:space:];&|()<>]|$)' \
- && printf '%s' "$bare" | grep -qE '(-R|--recursive)([[:space:];&|()<>]|$)' \
- && printf '%s' "$bare" | grep -qE '(^|[[:space:]])(000|00|0)([[:space:];&|()<>]|$)'; then
- echo "refuse"; return 1
- fi
- # Fork bomb pattern
- if printf '%s' "$cmd" | grep -qF ':(){ :|:'; then
- echo "refuse"; return 1
- fi
- if printf '%s' "$cmd" | grep -qE ':\(\)\{'; then
- echo "refuse"; return 1
- fi
- # AWS credential patterns (key IDs start with AKIA, secret keys are 40-char base64)
- if printf '%s' "$cmd" | grep -qE 'AKIA[0-9A-Z]{16}'; then
- echo "refuse"; return 1
- fi
- # PASSWORD= credential pattern
- if printf '%s' "$cmd" | grep -qE 'PASSWORD[[:space:]]*='; then
- echo "refuse"; return 1
- fi
- # Private key headers — pattern starts with dashes so pass -- to avoid flag misparse
- if printf '%s' "$cmd" | grep -qE -- 'BEGIN (RSA |EC |OPENSSH |DSA )?PRIVATE KEY'; then
- echo "refuse"; return 1
- fi
- # Database URL safety: extract host and dbname from postgres:// or postgresql:// URIs
- # Pattern: postgres(ql)://user:pass@HOST/DBNAME or postgres(ql)://HOST/DBNAME
- # A quote or backslash inside the scheme ('postgres'ql://) still gives the shell a URL,
- # so every URL the shell sees must also appear as plain text here.
- local seen_urls plain_urls
- seen_urls=$(printf '%s' "$bare" | grep -oE 'postgres(ql)?://' | wc -l)
- plain_urls=$(printf '%s' "$cmd" | grep -oE 'postgres(ql)?://' | wc -l)
- if [[ "$seen_urls" -ne "$plain_urls" ]]; then
- echo "refuse"; return 1
- fi
- if printf '%s' "$cmd" | grep -qE 'postgres(ql)?://'; then
- # Check every URL: one safe URL must not vouch for a second, real one.
- # A URL ends at whitespace, quotes or shell punctuation, so `A=url1;B=url2` is two URLs.
- # Each URL is read twice: cut at the first punctuation, and with the user:pass part kept
- # whole. `p&ss@prod` and `prod;x@localhost` each fail one of the two readings.
- # Known limit: a dotted user name with & in the password is refused too; run it by hand.
- # Refuse what this check cannot read safely: encoded text (%), several hosts (,),
- # a backslash (the shell drops it, so ho\st= is host=), and query keys that move
- # the connection (host, hostaddr, dbname, service).
- if printf '%s' "$cmd" | grep -qE 'postgres(ql)?://[^[:space:];|<>()]*[%,#\\]' \
- || printf '%s' "$cmd" | grep -qiE 'postgres(ql)?://[^[:space:];|<>()]*[?&](host|hostaddr|dbname|service)='; then
- echo "refuse"; return 1
- fi
- # A URL with nothing after the scheme leaves the host to PGHOST or -h, and a quoted
- # URL with a space in it (a password such as "p ss") is cut before its real host.
- if printf '%s' "$cmd" | grep -qE 'postgres(ql)?://([[:space:];&|<>()"'"'"'`]|$)' \
- || printf '%s' "$cmd" | grep -qE '["'"'"']postgres(ql)?://[^"'"'"']*[[:space:]]'; then
- echo "refuse"; return 1
- fi
- # A quote inside the URL (not just around it) hides where the host really ends.
- if printf '%s' "$cmd" | grep -qE 'postgres(ql)?://[^[:space:];&|<>()]*["'"'"'`][^[:space:];&|<>()"'"'"'`]'; then
- echo "refuse"; return 1
- fi
- local url rest authority db_path db_host db_name host_ok
- while IFS= read -r url; do
- # Split scheme://[user@]host[:port][/dbname][?query]; the query never feeds dbname.
- rest=${url#*://}
- authority=${rest%%/*}
- # Two @ signs leave it unclear which part is the host.
- if [[ "$authority" == *@*@* ]]; then echo "refuse"; return 1; fi
- # Some URL parsers end the host part at ? or #, so prod?@localhost may mean prod.
- if [[ "$authority" == *[?#]*@* ]]; then echo "refuse"; return 1; fi
- db_host=${authority##*@}
- # A ? after the host starts the query, so any later / is not a dbname path.
- if [[ "$db_host" == *\?* ]]; then db_path=""; else db_path=${rest:${#authority}}; fi
- db_host=${db_host%%[:?]*}
- db_path=${db_path%%\?*}
- db_name=${db_path#/}
- # Shell expansion in the name ($_test is an empty variable) hides the real name.
- if [[ "$db_name" == *[\$\{\}\*\[~]* ]]; then echo "refuse"; return 1; fi
- # Allowed hosts: localhost, 127.0.0.1, or a plain single-label name that starts
- # with a letter, such as a container. Anything else is remote: IPv6, a number
- # (2130706433 and 0x7f000001 are IPv4 addresses), and an empty host, which psql
- # fills from PGHOST or -h.
- host_ok=0
- if [[ "$db_host" == "localhost" || "$db_host" == "127.0.0.1" ]]; then
- host_ok=1
- elif [[ "$db_host" =~ ^[A-Za-z][A-Za-z0-9_-]*$ ]]; then
- host_ok=1
- fi
- # Non-allowlisted host: dbname must end with _test or _ci (anchored suffix, not substring)
- if [[ "$host_ok" -eq 0 ]] && ! printf '%s' "$db_name" | grep -qE '_test$|_ci$'; then
- echo "refuse"; return 1
- fi
- done < <(printf '%s' "$cmd" | grep -oE 'postgres(ql)?://[^[:space:];&|<>()"'"'"'`]+'
- printf '%s' "$cmd" | grep -oE 'postgres(ql)?://([^[:space:]/@]*@)?[^[:space:];&|<>()"'"'"'`]+')
- fi
- echo "ok"; return 0
- }
- # ---------------------------------------------------------------------------
- # verdict: synthesize a convergence verdict from state JSON.
- # Reads: units, plateau, ceiling, fork_rounds_since_progress fields. Prints
- # verdict + ship-gate line. A plateau answers FORK (run a fork-and-flush round)
- # until FORK_ROUNDS_BEFORE_PLATEAU rounds have run since the last progress,
- # then PLATEAU. A reached ceiling is checked first and always answers CEILING.
- # Exit 0 = CONVERGED; exit 1 = not converged; exit 2 = error.
- # ---------------------------------------------------------------------------
- verdict() {
- local state_file="${1:?usage: verdict <state.json>}"
- if [[ ! -f "$state_file" ]]; then
- echo "BLOCKED"; echo "ship=no"; return 2
- fi
- local units_val plateau_val ceiling_val fork_rounds
- units_val=$(grep -o '"units"[[:space:]]*:[[:space:]]*[0-9.]*' "$state_file" \
- | grep -o '[0-9.]*$')
- plateau_val=$(grep -o '"plateau"[[:space:]]*:[[:space:]]*[a-z]*' "$state_file" \
- | grep -o '[a-z]*$')
- ceiling_val=$(grep -o '"ceiling"[[:space:]]*:[[:space:]]*[a-z]*' "$state_file" \
- | grep -o '[a-z]*$')
- fork_rounds=$(grep -o '"fork_rounds_since_progress"[[:space:]]*:[[:space:]]*"\{0,1\}[0-9][0-9]*' "$state_file" \
- | grep -o '[0-9][0-9]*$')
- if [[ -z "$units_val" ]]; then
- echo "BLOCKED"; echo "ship=no"; return 2
- fi
- if [[ "$ceiling_val" == "true" ]]; then
- echo "CEILING"; echo "ship=no"; return 1
- fi
- if [[ "$plateau_val" == "true" ]]; then
- if (( ${fork_rounds:-0} < FORK_ROUNDS_BEFORE_PLATEAU )); then
- echo "FORK"; echo "ship=no"; return 1
- fi
- echo "PLATEAU"; echo "ship=no"; return 1
- fi
- # units==0 with no plateau/ceiling → converged
- if awk -v u="$units_val" 'BEGIN { exit (u == 0 ? 0 : 1) }'; then
- echo "CONVERGED"; echo "ship=yes"; return 0
- fi
- # units > 0, no plateau/ceiling signal yet → still running
- echo "BLOCKED"; echo "ship=no"; return 1
- }
- # ---------------------------------------------------------------------------
- # validate-state: schema gate for orchestrator-state.json. The ledger is the
- # loop's evidence trail; a malformed one must not be trusted to route from.
- # Prints "valid" exit 0 | "invalid" exit 2. Node is a checked installation
- # prerequisite, so use its JSON parser rather than approximating JSON with grep.
- # ---------------------------------------------------------------------------
- validate-state() {
- local state_file="${1:?usage: validate-state <state.json>}"
- if [[ ! -f "$state_file" ]]; then
- echo "invalid"; return 2
- fi
- if ! node -e '
- const fs = require("fs");
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- const strings = ["goal", "archetype", "predicate", "terminal_choice"];
- if (!strings.every((key) => typeof state[key] === "string" && state[key].length > 0)) process.exit(1);
- if (!Number.isInteger(state.cycle) || state.cycle < 0) process.exit(1);
- if (!Array.isArray(state.units_remaining) || !Array.isArray(state.pipeline_log)) process.exit(1);
- ' "$state_file" 2>/dev/null; then
- echo "invalid"; return 2
- fi
- echo "valid"; return 0
- }
- # ---------------------------------------------------------------------------
- # screen-state-predicate: extract the pinned predicate from a persisted state
- # file and re-run it through screen-cmd. Persisted commands are never trusted —
- # a poisoned state file must not re-enter the loop with an unscreened command.
- # Delegates the verdict (ok/refuse + exit) to screen-cmd; "invalid" exit 2 when
- # the state has no pinned predicate.
- # ---------------------------------------------------------------------------
- screen-state-predicate() {
- local state_file="${1:?usage: screen-state-predicate <state.json>}"
- if [[ ! -f "$state_file" ]]; then
- echo "invalid"; return 2
- fi
- local pred
- if ! pred=$(node -e '
- const fs = require("fs");
- const state = JSON.parse(fs.readFileSync(process.argv[1], "utf8"));
- if (typeof state.predicate !== "string" || state.predicate.length === 0 || state.predicate.includes("\0")) process.exit(1);
- process.stdout.write(state.predicate);
- ' "$state_file" 2>/dev/null); then
- echo "invalid"; return 2
- fi
- screen-cmd "$pred"
- }
- case "${1:-}" in
- classify) shift; classify "$@" ;;
- next-hop) shift; next-hop "$@" ;;
- units) shift; units "$@" ;;
- plateau) shift; plateau "$@" ;;
- screen-cmd) shift; screen-cmd "$@" ;;
- verdict) shift; verdict "$@" ;;
- validate-state) shift; validate-state "$@" ;;
- screen-state-predicate) shift; screen-state-predicate "$@" ;;
- *) echo "usage: $0 {classify|next-hop|units|plateau|screen-cmd|verdict|validate-state|screen-state-predicate}" >&2; exit 64 ;;
- esac
Ratings and comments
Sign in to rate this skill.
Sign inFree to use. If it’s helped, pass it on.