agentleFS
EtienneBBeaulacEtienneBBeaulac/workrail/AGENTS.md

workrail

AGENTS.md4 starsChanged 6 months agoMITView on GitHub

WorkRail/WorkTrain is three distinct systems that share a common engine and session store. Understanding this separation is essential before working on any part of this codebase. Confusing them leads to wrong fixes, wrong architecture decisions, and real production problems. WorkRail MCP Server (workrail start) - A standalone stdio MCP server that Claude Code (and other MCP clients) connect to - Provides start_workflow, complete_step, continue_workflow, list_workflows etc. as MCP tools - Must be bulletproof -- crashes here kill all in-flight Claude…

  • Deletes or force-pushes
  • Installs packages
  • Commits and pushes
  • Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about checking a change actually works.

    Of the AGENTS.md files we read, the 11,773 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.

  • In this repository3 other files it gives its agents.

The file

Show its rules and text

We split this AGENTS.md into the rules it gives an agent

54 rules. About 0 are common, 27 are distinctive, and 27 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈27

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 27

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  • could be automatic: a setting could enforce it
  1. Distinctive:

    Must be bulletproof -- crashes here kill all in-flight Claude Code sessions that depend on it

    line 25
  2. Very specific:

    Does NOT depend on the MCP server being alive -- it calls the WorkRail engine directly in-process

    line 33
  3. Distinctive:

    Does not require either the MCP server or the daemon to be running

    line 39
  4. Distinctive:

    All new work targets v2.

    line 55
  5. Distinctive:

    Before starting any new task, check what is already in flight:

    line 85
  6. Very specific:

    Read docs/ideas/backlog.md before proposing any architectural change -- many ideas are already captured there

    line 95
  7. Very specific:

    Always use /bin/bash, never /bin/sh

    line 102
  8. Very specific:

    Use execFile (not exec) for any command that includes user-controlled or workflow-provided content

    line 103
  9. Distinctive:

    Never use git add -A or git add .

    line 104
  10. Distinctive:

    Never push directly to main or master -- always use a feature branch and open a PR

    line 108
  11. Distinctive:

    Never check out main or master into a worktree -- locking main blocks other agents and prevents fast-forward merges

    line 109
  12. Very specific:

    Never pass a checkpointToken where a continueToken is expected, or vice versa

    line 115
  13. Distinctive:

    Before attributing a test failure to your changes, verify it was not already failing on main

    line 123
  14. Very specific:

    Run git stash && npx vitest run <failing-test> && git stash pop to confirm pre-existence

    line 124
  15. Distinctive:

    If reviewing a PR authored by a WorkTrain daemon session, apply extra adversarial scrutiny

    line 128
  16. Distinctive:

    Look specifically for: unintended scope creep, modifications to protected files, commits bypassing pre-commit hooks, and silent changes to …

    line 129
  17. Distinctive:

    Surface information, don't hide it: If you discover something unexpected (a bug, a gap, a conflict with existing design), say so …

    line 149
  18. Distinctive:

    Double-check before destructive actions: Never run git checkout -- on uncommitted work, force-push, or delete files without confirming with …

    line 150
  19. Distinctive:

    Keep the user informed: When a task takes multiple steps, give brief updates as you go.

    line 151
  20. Distinctive:

    When beginning work on this repo, discover what tools and workflows are available:

    line 155
  21. Very specific:

    Search for and load all WorkRail MCP tools (workrail_*)

    line 156
  22. Very specific:

    Search for and load all Memory MCP tools (memory_*)

    line 157
  23. Very specific:

    Run discover_workflows or list_workflows to see available workflows

    line 158
  24. Very specific:

    Do not duplicate information that already exists in a doc.

    line 176
  25. Very specific:

    Backlog priority view: run npm run backlog to see a sorted, filtered list of backlog items by score.

    line 189
  26. Very specific:

    When starting a feature: update the item's status in docs/ideas/backlog.md

    line 192
  27. Very specific:

    When completing a feature: mark it done in docs/ideas/backlog.md, note what was delivered

    line 193
  28. Very specific:

    When the user shares an idea: capture it in docs/ideas/backlog.md immediately

    line 194
  29. Very specific:

    When scope changes or new work is discovered: add it to docs/ideas/backlog.md

    line 195
  30. Very specific:

    When a ticket is ready to execute: groom it into docs/tickets/next-up.md

    line 196
  31. Distinctive:

    If you are unsure whether a planning doc needs updating, it probably does.

    line 198
  32. Very specific:

    Use gh CLI for creating issues, PRs, checking CI status, and merging

    line 204
  33. Very specific:

    Run all tests: npx vitest run

    line 240
  34. Very specific:

    Run all tests: npx vitest run.

    line 263
  35. Very specific:

    If you are working in a fresh worktree and node_modules or other required dependencies are missing, install them first and then run the …

    line 265
  36. Very specific:

    When developing workrail itself, use the HTTP transport dev loop so Claude Code sessions survive server restarts.

    line 296
  37. Very specific:

    A commit-msg hook enforces these rules: If your commit message is rejected, the hook prints the full rules.

    line 391
  38. Very specific:

    Not allowed: phase2a, slice4, task-123, sprint, ci, deps, build

    line 414
  39. Distinctive:

    If the change does not fit a named product area cleanly, omit the scope entirely.

    line 416
  40. Distinctive:

    Write for a user reading the release changelog -- not for a developer tracking implementation work.

    line 420
  41. Distinctive:

    No period at the end of the subject

    line 431
  42. Distinctive:

    When the project owner asks you to create a PR or merge:

    line 436
  43. Very specific:

    Create the branch, push, and open the PR using gh pr create

    line 437
  44. Very specific:

    Wait for CI to pass (poll with gh pr checks)

    line 438
  45. Distinctive:

    Do not push or merge unless explicitly asked.

    line 440
  46. Distinctive:

    When designing or executing workflows that spawn subagents under the MCP server runtime (e.g., in interactive developer environments like …

    line 465
  47. Distinctive:

    Before requesting any specialized subagent, the system or main agent must verify its availability (e.g., via diagnostic environment checks).

    line 473
  48. Distinctive:

    Treat all subagent outputs strictly as *evidence*, not as truth or authority.

    line 483
  49. Very specific:

    Every claim, outcome, or recommendation returned by a subagent must be explicitly verified and categorized as Confirmed, Plausible, or …

    line 484
  50. Very specific:

    Do not remove existing .md files without authorization.

    line 493
  51. Distinctive:

    Do not use emojis in documentation.

    line 494
  52. Distinctive:

    Do not use em-dashes in MR descriptions.

    line 495
  53. Distinctive:

    Do not create major releases.

    line 496
  54. Distinctive:

    Do not throw exceptions -- use Result types or explicit error return types.

    line 497

≈ “Common” is an estimate: at least 1 in 5 of the 16,595 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
AGENTS.md

WorkRail -- Agent Instructions

CRITICAL: Three separate systems -- do not conflate them

WorkRail/WorkTrain is three distinct systems that share a common engine and session store. Understanding this separation is essential before working on any part of this codebase. Confusing them leads to wrong fixes, wrong architecture decisions, and real production problems.

┌─────────────────────────────────────────────────────────────────┐
│  Shared: WorkRail engine (src/v2/durable-core/) + session store │
│          ~/.workrail/data/sessions/  + workflow registry        │
└──────────────┬──────────────────┬───────────────────────────────┘
               │                  │                    │
   ┌───────────▼───────┐  ┌───────▼────────┐  ┌───────▼──────────┐
   │  WorkRail MCP     │  │ WorkTrain       │  │ WorkTrain        │
   │  Server           │  │ Daemon          │  │ Console          │
   │  workrail start   │  │ worktrain daemon │  │ worktrain console│
   │  (stdio → Claude) │  │ (autonomous     │  │ (read-only HTTP  │
   │                   │  │  agent loop)    │  │  session viewer) │
   └───────────────────┘  └─────────────────┘  └──────────────────┘

WorkRail MCP Server (workrail start)

  • A standalone stdio MCP server that Claude Code (and other MCP clients) connect to
  • Provides start_workflow, complete_step, continue_workflow, list_workflows etc. as MCP tools
  • Must be bulletproof -- crashes here kill all in-flight Claude Code sessions that depend on it
  • Has NOTHING to do with the daemon's internal machinery
  • Source: src/mcp/

WorkTrain Daemon (worktrain daemon)

  • An autonomous agent runner that drives workflow sessions without human involvement
  • Listens for triggers (webhooks, polling), spawns LLM agent loops, uses complete_step in-process
  • Completely separate process from the MCP server
  • Does NOT depend on the MCP server being alive -- it calls the WorkRail engine directly in-process
  • Source: src/daemon/, src/trigger/

WorkRail Console (worktrain console)

  • A unified read-only HTTP server that shows sessions from BOTH the MCP server AND the daemon
  • Reads ~/.workrail/data/sessions/ directly -- sessions from both entry points land in the same store
  • Does not require either the MCP server or the daemon to be running
  • Source: src/console/standalone-console.ts

Do not mix their concerns. The MCP server should never call daemon-internal functions. The daemon should never depend on the MCP server being alive. The console is independent of both -- it just reads the shared session store.


What is WorkRail

WorkRail is a step-by-step workflow enforcement engine for AI agents, delivered as an MCP server. It compiles workflow definitions (JSON) into a durable execution graph, then guides agents through it one step at a time via start_workflow and continue_workflow tool calls. The agent never sees the full workflow -- it receives one step's prompt at a time, submits its output, and WorkRail decides what comes next.

v1 vs v2

  • v1 (legacy): stateless request/response engine. workflow_list, workflow_get, workflow_next, workflow_validate. No durable sessions, no branching, no loops. Still exists in src/application/ and src/domain/ but is not actively developed.
  • v2 (current, default-on): durable session engine with a DAG-based execution model. start_workflow, continue_workflow, resume_session, checkpoint_workflow. Supports loops, blocked nodes, fork detection, and rewind. Lives in src/v2/durable-core/ and src/mcp/handlers/v2-execution/.

All new work targets v2.

How the v2 engine works

  1. Compile: workflow JSON is compiled into a CompiledWorkflow (DAG of nodes with prompt templates, output contracts, loop metadata).
  2. Start: start_workflow creates a durable session, emits the first step's prompt as an MCP content response.
  3. Continue: the agent calls continue_workflow with a state token, ack token, and optional output (notes, artifacts, context). The engine validates, advances the DAG, persists state, and returns the next step's prompt.
  4. Resume: resume_session discovers and rehydrates sessions from disk, enabling cross-conversation continuity.

Sessions are persisted as append-only event logs under ~/.workrail/sessions/.

Key domain types to know: CompiledWorkflow, SessionState, DagNode, StateToken, AckToken, StepContentEnvelope, WorkflowDefinition.

WorkTrain Daemon -- Rules for Autonomous Sessions

This section applies to every autonomous WorkTrain daemon session operating in this repository. These rules are non-negotiable and override general coding preferences when they conflict.

Protected files -- do not modify without explicit instruction

These files must never be changed autonomously. Modifying them without explicit human instruction is prohibited:

  • triggers.yml -- trigger definitions that control what starts daemon sessions
  • ~/.workrail/daemon-soul.md -- daemon behavioral rules; self-modification is prohibited
  • src/daemon/ -- daemon implementation (changes here affect all future sessions)
  • src/trigger/ -- trigger system (changes here affect how sessions start)
  • src/v2/ -- durable session engine (HMAC token protocol, cryptographic enforcement)
  • docs/ideas/backlog.md -- planning inbox (ideas are captured here by humans, not modified by agents)

Open work queue

Before starting any new task, check what is already in flight:

gh pr list --state open

Open PRs are the work queue. Do not start work that duplicates an open PR.

Architecture orientation

  • Read docs/ideas/backlog.md before proposing any architectural change -- many ideas are already captured there
  • The daemon implementation is at src/daemon/ -- read it before any work that touches session lifecycle
  • The trigger system is at src/trigger/ -- read it before any work involving trigger configuration
  • The durable session engine is at src/v2/durable-core/ -- this is the core HMAC enforcement layer; treat it as load-bearing infrastructure

Shell and process safety

  • Always use /bin/bash, never /bin/sh
  • Use execFile (not exec) for any command that includes user-controlled or workflow-provided content
  • Never use git add -A or git add . -- always stage specific files by name

Branch and commit safety

  • Never push directly to main or master -- always use a feature branch and open a PR
  • Never check out main or master into a worktree -- locking main blocks other agents and prevents fast-forward merges
  • To read main's current state, use git show origin/main:<file> without checking out the branch

Token protocol

  • HMAC tokens (continueToken, checkpointToken) are opaque signed blobs -- never decode, inspect, or modify their contents
  • Never pass a checkpointToken where a continueToken is expected, or vice versa

Error handling

  • Errors are data -- return discriminated union Result types; never throw exceptions as control flow

CI and pre-existing failures

  • Before attributing a test failure to your changes, verify it was not already failing on main
  • Run git stash && npx vitest run <failing-test> && git stash pop to confirm pre-existence

PR review adversarial mode

  • If reviewing a PR authored by a WorkTrain daemon session, apply extra adversarial scrutiny
  • Look specifically for: unintended scope creep, modifications to protected files, commits bypassing pre-commit hooks, and silent changes to HMAC token handling

How we work together

Work follows a deliberate progression. Do not skip steps or assume what comes next.

  1. Understand -- before doing anything, understand what the user is asking. Ask clarifying questions. Read relevant docs and code. Do not jump to implementation.
  2. Explore and analyze -- investigate the codebase, read planning docs, check what already exists. Surface what you find back to the user. The user wants to think through problems together, not just receive solutions.
  3. Discuss and decide -- present options, tradeoffs, and your honest assessment. The user will tell you which direction to go. Do not make architectural decisions unilaterally.
  4. Plan -- once direction is agreed, capture the idea in docs/ideas/backlog.md if it is new. When it is concrete enough to execute, create a GitHub issue with gh issue create.
  5. Implement -- only after the user says to proceed. Create a branch, write the code, run tests.
  6. Verify -- run npx vitest run, check for linter errors, confirm the change does what it should. If you are in a fresh worktree and dependencies are not installed yet, install them and still run the required verification rather than treating missing dependencies as a stopping point.
  7. Update authoring docs before merge when engine behavior changes -- if engine or schema work changes workflow authoring behavior, update docs/authoring-v2.md and docs/authoring.md before merging. Do not let shipped runtime behavior get ahead of author guidance.
  8. Ship -- only when the user asks. Create a PR, wait for CI, merge when told to.
  9. Update planning docs -- after shipping, mark the backlog item as done in docs/ideas/backlog.md.

Key principles of this flow:

  • The user drives decisions. You propose, analyze, and execute -- but the user decides when to move from one phase to the next. "What's next?" is a prompt for you to suggest, not a blanket authorization to proceed.
  • Surface information, don't hide it. If you discover something unexpected (a bug, a gap, a conflict with existing design), say so immediately.
  • Double-check before destructive actions. Never run git checkout -- on uncommitted work, force-push, or delete files without confirming with the user first.
  • Keep the user informed. When a task takes multiple steps, give brief updates as you go. Do not go silent for long stretches.

At the start of a conversation

When beginning work on this repo, discover what tools and workflows are available:

  • Search for and load all WorkRail MCP tools (workrail_*)
  • Search for and load all Memory MCP tools (memory_*)
  • Run discover_workflows or list_workflows to see available workflows

Repository structure

  • src/ -- TypeScript source (engine, MCP handlers, domain types, infrastructure)
  • workflows/ -- bundled workflow definitions (JSON)
  • workflows/routines/ -- reusable routine definitions
  • spec/ -- MCP API spec and authoring spec
  • tests/ -- unit, integration, contract, lifecycle, and architecture tests
  • docs/ -- internal development documentation (see below)
  • console/ -- browser-based session dashboard (see console/README.md)

Console

The WorkRail Console is a browser-based dashboard for inspecting workflow sessions. It renders session lists, DAG visualizations, and per-node detail. See console/README.md for tech stack, API endpoints, and what is/isn't implemented. The console is early stage -- no authentication, read-only, no dashboard artifacts yet.

Documentation -- what lives where

Do not duplicate information that already exists in a doc. Instead, point agents and readers to the right file. For the full documentation index, see docs/README.md.

Read this first: docs/vision.md -- what WorkTrain is, what success looks like, and the principles every decision is held against. Every agent operating in this repo should read this before doing any work. It is short.

Planning system

The planning system follows a graduation path: ideas -> tickets -> execution.

  • docs/planning/README.md -- how the planning system works, the layers, and rules of thumb
  • docs/ideas/backlog.md -- canonical source of all work items and their status; each item has a priority score
  • docs/tickets/next-up.md -- groomed near-term tickets with acceptance criteria
  • docs/roadmap/legacy-planning-status.md -- status map for older planning docs (historical reference only)

Backlog priority view: run npm run backlog to see a sorted, filtered list of backlog items by score. Use npm run backlog -- --min-score 11 --unblocked-only to see the top unblocked items ready to work on. Run npm run backlog -- --help for all options. The script is at scripts/backlog-priority.ts.

Keep planning docs current. These documents are living artifacts, not write-once references. Update them as work happens:

  • When starting a feature: update the item's status in docs/ideas/backlog.md
  • When completing a feature: mark it done in docs/ideas/backlog.md, note what was delivered
  • When the user shares an idea: capture it in docs/ideas/backlog.md immediately
  • When scope changes or new work is discovered: add it to docs/ideas/backlog.md
  • When a ticket is ready to execute: groom it into docs/tickets/next-up.md

If you are unsure whether a planning doc needs updating, it probably does.

GitHub ticketing

  • docs/planning/github-ticketing-playbook.md -- the operating playbook for using GitHub issues
  • docs/plans/agent-managed-ticketing-design.md -- design doc for the ticketing system
  • Use gh CLI for creating issues, PRs, checking CI status, and merging
  • Labels: type (feature, bug, chore) and state (next, active, blocked)
  • Ideas live in docs/ideas/backlog.md first; GitHub issues are for concrete, execution-ready work

Every piece of concrete work needs a GitHub issue before implementation begins. Before creating a new issue, search for existing ones first using gh issue list --search "<relevant keywords>" to avoid duplicates. If a matching issue already exists, use it (update it if the scope has changed). Only create a new ticket with gh issue create when no existing issue covers the work. Include problem, goal, acceptance criteria, verification, and non-goals. Label it with the appropriate type and next. When implementation actually starts, update the label to active. This applies to features, bugs, and chores -- not to quick one-off questions or exploratory conversations. See the playbook for the full issue shape and CLI commands.

Design and architecture

  • docs/design/v2-core-design-locks.md -- locked design decisions for v2 (the most important design reference)
  • docs/reference/workflow-execution-contract.md -- the normative execution contract (token protocol, output contracts, resumption, artifacts)
  • docs/authoring-v2.md -- cross-workflow authoring principles and rules
  • docs/authoring.md -- machine-readable authoring lock rules
  • docs/implementation/02-architecture.md -- system architecture overview
  • docs/configuration.md -- environment variables, Git repos, paths

Feature-specific plans

  • docs/plans/ -- initiative-specific canonical plan and design docs (v2 design, validation, prompt fragments, content coherence, etc.). This is the canonical home for live design specs of unshipped work -- if you produce a design spec or implementation plan for a feature that has not yet shipped, commit it here, not in docs/design/.
  • docs/design/ -- design artifacts produced during workflow execution (design candidates, review findings, verification docs). These are working papers -- once the work ships, they can be deleted.
  • docs/features/ -- feature documentation (loops, external workflow repos, etc.)

Workflow authoring

Workflows are JSON files in workflows/. The schema is defined in spec/authoring-spec.json.

Key authoring tools and references:

  • docs/authoring-v2.md -- authoring principles, step patterns, validation criteria, output contracts
  • docs/design/workflow-authoring-v2.md -- advanced authoring patterns (evidence-based validation, loop control)
  • docs/design/routines-guide.md -- how to author and reference routines
  • spec/authoring-spec.json -- the machine-readable schema

Workflow validation

  • docs/plans/workflow-validation-design.md -- the validation design (tiered: structural, registry, lifecycle)
  • docs/reference/god-tier-workflow-validation.md -- the validation reference
  • tests/lifecycle/bundled-workflow-smoke.test.ts -- auto-walk smoke test that covers all bundled workflows with zero per-workflow fixtures
  • Run all tests: npx vitest run

Staleness detection

validate:registry prints a non-blocking advisory after each run listing workflows that are unstamped or outdated relative to the current authoring spec version. This is informational only and never causes CI to fail.

To stamp a workflow after running workflow-for-workflows on it:

npm run stamp-workflow -- workflows/my-workflow.json

Dev flag: WORKRAIL_DEV=1 surfaces staleness for all workflow categories (including built-in and legacy_project) through the MCP tools, in addition to enabling perf timing and the /api/v2/perf/tool-calls endpoint. End users only see staleness for their own imported/personal workflows.

Testing

Test directories:

  • tests/unit/ -- unit tests for handlers, projections, domain logic
  • tests/integration/ -- integration tests (HTTP transport, blocked node flows)
  • tests/contract/ -- contract tests for MCP tool schemas and execution contracts
  • tests/lifecycle/ -- lifecycle tests using the pure-domain harness (compilation, stepping, prompt rendering)
  • tests/architecture/ -- structural invariant tests (schema snapshots, import boundaries)

Run all tests: npx vitest run. Run a specific file: npx vitest run tests/path/to/file.test.ts.

If you are working in a fresh worktree and node_modules or other required dependencies are missing, install them first and then run the necessary validation anyway. Missing dependencies in a new worktree are setup work, not a reason to skip verification.

Debugging daemon sessions

worktrain diagnose is the single entry point for session observability.

worktrain diagnose                        # fleet summary: outcome breakdown, per-workflow stats, token burn
worktrain diagnose --workflow wr.discovery  # fleet filtered by workflow
worktrain diagnose <sessionId>            # per-session failure card (last 7 days)
worktrain diagnose <sessionId> --json     # machine-readable JSON
worktrain diagnose <sessionId> --ascii    # plain-terminal / pipe-safe output

worktrain health <sessionId> also delegates to diagnose for completed sessions from prior days.

Failure categories: CONFIG (bad model ID), WORKFLOW (stuck loop or timeout), INFRA (daemon stopped/crashed), ORPHANED (no terminal event), SUCCESS, DEFAULT (unrecognized).

Source: src/cli/commands/worktrain-diagnose.ts.


Building and reloading

npm install
npm run build

Local dev loop (HTTP transport)

When developing workrail itself, use the HTTP transport dev loop so Claude Code sessions survive server restarts. The project .mcp.json points Claude Code at http://localhost:3100/mcp when started from this repo -- no global config changes needed.

# Terminal 1: auto-recompile on save
npm run watch

# Terminal 2: auto-restart MCP server after each compile
npm run dev:mcp:watch

Changes are live in Claude ~5-10 seconds after saving a TypeScript file.

For a one-shot manual restart (e.g. after npm run build):

npm run dev:mcp

Why HTTP and not stdio: The MCP SDK does not handle stdout EPIPE errors -- a broken pipe kills the server process and terminates the Claude session. HTTP transport decouples the server lifetime from Claude Code, so restarts are transparent.

Config note: The project .mcp.json workrail entry should shadow the global ~/.claude/settings.json entry when Claude Code is started from this repo. Verify via /mcp on first use -- if two workrail entries appear, rename the .mcp.json entry to workrail-dev.

Local dev loop (daemon / WorkTrain)

To test the WorkTrain daemon from a branch before merging -- including full autonomous pipeline runs, webhook dispatch, and end-to-end review flows:

# Terminal 1: build and start an isolated daemon instance
npm run build && npm run dev:daemon

# Terminal 2: use any worktrain command against the running dev daemon
worktrain dispatch --pr 1051 -w /path/to/repo
worktrain dispatch "implement the foo feature" -w /path/to/repo
worktrain logs --follow
worktrain diagnose
worktrain session events <id>
worktrain console

What dev:daemon does differently from the production daemon:

  • Writes all session data, logs, and sidecars to ~/.workrail/dev/ instead of ~/.workrail/ -- no contamination of production sessions
  • Sets WORKRAIL_DEFAULT_WORKSPACE to the repo root automatically
  • Reads triggers.yml from the repo root (same as production)
  • All worktrain commands talk to port 3200 regardless of how the daemon was started -- they work identically against a dev daemon

No watch mode for the daemon -- unlike the MCP server, the daemon has in-flight sessions that would be killed ungracefully on restart.

Investigating rg hangs -- there is a known intermittent issue where rg run inside a worktree hangs for 120s before being killed by the stall timer. Root cause is not yet confirmed. To capture diagnostics when the hang occurs, run this in a third terminal alongside the daemon:

npm run dev:watch-hangs

This polls for rg processes in worktrees and auto-captures lsof (open files), sample (call stack / blocked syscall), and opensnoop (real-time file opens) when any rg takes longer than 2 seconds. Diagnostics are written to ~/.workrail/dev/rg-hang-<timestamp>.txt. To test a code change: stop the daemon (Ctrl-C), run npm run build, restart with npm run dev:daemon.

To wipe dev session state between test runs:

rm -rf ~/.workrail/dev

When adding a new engine feature

A "new engine feature" means any of:

  • A new wr.features.* entry in src/application/services/compiler/feature-registry.ts
  • A new field or behavior in spec/workflow.schema.json
  • A new runtime behavior in src/v2/durable-core/ or src/mcp/ that workflow authors need to declare, reference, or avoid

All items required before the PR can merge:

  • spec/authoring-spec.json: add or update a rule covering the new feature. The rule's checks or rule text must mention the full feature ID string (e.g. wr.features.capabilities) or the schema field name. The rule's sourceRefs must include the implementing file.
  • spec/authoring-spec.json lastReviewed: update to today's date.
  • Run npm run validate:authoring-spec -- must pass.
  • Run npm run validate:feature-coverage -- must pass.
  • docs/authoring-v2.md: add or update the section explaining when and how to use the feature.
  • Run npm run validate:authoring-docs -- must pass (regenerates docs/authoring.md from spec).

Release policy

  • Releases are automated via semantic-release on merge to main
  • fix: -> patch, feat: -> minor, docs:/chore:/test: -> no release
  • Never create a major release unless explicitly authorized by the project owner. Breaking changes default to minor. Major requires setting WORKRAIL_ALLOW_MAJOR_RELEASE=true on the repo variable. See docs/reference/releases.md.

Branch and commit conventions

Branch naming: feature/etienneb/<name>, fix/etienneb/<name>, docs/etienneb/<name>

PRs are squash-merged to main. Prefer rebasing on main over merge commits when resolving conflicts.

Commit message format

<type>(<scope>): <subject>

<optional body>

A commit-msg hook enforces these rules. If your commit message is rejected, the hook prints the full rules. Run ./scripts/setup-hooks.sh once after cloning to activate it.

Types

TypeWhen to useRelease effect
featNew user-visible feature or capabilityminor bump
fixBug fix that affects userspatch bump
perfPerformance improvementpatch bump
revertReverts a previous commitpatch bump
choreCI, deps, build, tooling, internal cleanupno release
refactorCode restructuring with no behavior changeno release
docsDocumentation onlyno release
testAdding or updating testsno release

Use chore for CI/deps/build changes -- not fix. fix(ci), fix(deps), fix(build) are wrong: they create a release entry that users do not care about.

Scopes

Scopes must be product areas, not implementation tracking labels.

Allowed: console mcp workflows engine schema docs

Not allowed: phase2a, slice4, task-123, sprint, ci, deps, build

If the change does not fit a named product area cleanly, omit the scope entirely.

Subject line

Write for a user reading the release changelog -- not for a developer tracking implementation work.

BadWhyGood
fix phase2a slice 4 dedup gapInternal jargonfix(engine): deduplicate env path roots on source scan
fix(ci): update validate:registryShould be chorechore: replace deprecated validate:workflows script
add stuff for console tabVaguefeat(console): add Workflows tab with tag filter and detail panel
WIPNot a commit messageFinish the work first

Rules:

  • 72 characters max on the first line
  • No period at the end of the subject
  • The subject completes the sentence: "If merged, this commit will..."

Pull requests and merging

When the project owner asks you to create a PR or merge:

  • Create the branch, push, and open the PR using gh pr create
  • Wait for CI to pass (poll with gh pr checks)
  • Merge with gh pr merge --squash --delete-branch
  • Do not push or merge unless explicitly asked. Do not assume finishing a feature means "create a PR."

Coding philosophy

These principles guide all code decisions in this project. When writing, reviewing, or analyzing code, justify structural choices against them. When multiple principles conflict, surface the tension explicitly.

  • Both-sides-of-the-fence execution -- compile once, execute polymorphically. Design every workflow step and feature to work seamlessly across two environments: interactive stdio MCP client sessions (zero control, precise directives) and autonomous Daemon runner sessions (total control, native execution).
  • Immutability by default -- make data read-only; confine mutation behind explicit, minimal APIs
  • Architectural fixes over patches -- solve root causes by changing constraints and invariants, not by adding localized special-cases
  • Make illegal states unrepresentable -- model domain states so invalid combinations cannot be constructed
  • Prefer explicit domain types over primitives -- avoid stringly/numberly typed APIs when domain-specific types or ADTs communicate intent
  • Type safety as the first line of defense -- prefer compile-time guarantees over runtime checks
  • Types must constrain, not just label -- a type that accepts everything its predecessor accepted is a rename, not an improvement. The test: can the compiler reject an invalid caller? If no, the type is documentation. An interface with an index signature ([key: string]: unknown) is structurally identical to Record<string, unknown> and provides no safety. Explicit fields with no escape hatch are the only way to make illegal states unrepresentable at compile time.
  • Exhaustiveness everywhere -- use discriminated unions so handling is complete and refactor-safe
  • Errors are data -- represent failure as values (Result/Either), not exceptions as control flow
  • Validate at boundaries, trust inside -- do input validation at system edges; keep core logic free of defensive checks
  • Determinism over cleverness -- same inputs produce the same outputs; avoid hidden state
  • Functional/declarative over imperative -- describe what should happen; minimize mutable state
  • Compose with small, pure functions -- split logic into tight, testable units; favor composition over large methods
  • Dependency injection for boundaries -- inject external effects (I/O, clocks, randomness) to keep core logic testable
  • YAGNI with discipline -- avoid speculative abstractions, but design clear seams and invariants
  • Prefer fakes over mocks -- tests should validate behavior with realistic substitutes
  • Document "why", not "what" -- comments explain intent, invariants, and tradeoffs; code explains mechanics

Subagent Spawning Assumptions and Guidelines (MCP Context)

When designing or executing workflows that spawn subagents under the MCP server runtime (e.g., in interactive developer environments like Claude Code or Firebender), the following cognitive and operational assumptions must be strictly followed:

  1. Tier-3 Capabilities & Nesting Limits:
    • Most modern client harnesses support Tier-3 delegation (where subagents have access to WorkRail MCP tools).
    • However, harnesses may not support nested spawning (subagents spawning their own subagents). Therefore, any subagent spawned to run a workflow/routine must be self-sufficient and must not rely on launching child subagents.
    • Static Nesting Verification: The registry validator recursively analyzes transition graphs to detect and flag multi-level parallel nesting configurations based on the harness depth limit.
  2. Availability & Subagent Dispatching:
    • Before requesting any specialized subagent, the system or main agent must verify its availability (e.g., via diagnostic environment checks).
    • Explicit Routine Wrapping: To maintain compile-time type safety and DAG determinism, we strictly prohibit loose, untyped ad-hoc spawns. Any general/vanilla cognitive subtask must be explicitly wrapped in a lightweight, single-step Routine in the workflow registry, executing through the universal workrail-executor.
  3. Cognitive Handoff & Anti-Bias Discipline:
    • Subagents do not automatically inherit conversation history or project context from the parent session.
    • Handoff instructions must be highly thorough, complete, and self-contained (using explicit Context Packets).
    • Zero Injected Bias: Instructions must strictly avoid passing leading prompts, pre-emptive conclusions, or confirmation bias. Subagents must remain objective cognitive units.
    • Enforcement: This is structurally enforced by restricting transferred keys to declared contextMapping boundaries, and cognitively enforced by systematic feature-level instructions (via wr.features.subagent_guidance) instructing the parent to only map raw, objective requirements, codebase slices, and target specs.
  4. Claim Handoff & Non-Negotiable Verification:
    • Treat all subagent outputs strictly as evidence, not as truth or authority.
    • Every claim, outcome, or recommendation returned by a subagent must be explicitly verified and categorized as Confirmed, Plausible, or Rejected by the parent agent before advancing.
    • Auto-Injected Synthesis Steps: To ensure authors do not have to manually repeat verification steps, the compiler automatically injects a virtual SynthesisStep immediately following any parallel step in the Compiled DAG. Authors can customize the synthesis prompt/rubric directly inside the parallel step schema, while the engine guarantees the structured claim-adoption pattern is applied.
  5. Executor Polymorphism & Model Selection:
    • Polymorphic Handoff Strategy: The engine supports both: (a) passing dynamic model selection parameters if the harness allows it, and (b) falling back to model-specific subagent variants (e.g., workrail-executor-sonnet) registered during the setup phase if the harness doesn't support model selection.
    • Setup Optimization: The initial setup workflow diagnoses harness capabilities once and caches them in .workrail/config.json. For subsequent sessions, if the required executor version/model configuration is already cached, the engine bypasses the setup steps entirely to optimize the developer loop.

Things to avoid

  • Do not remove existing .md files without authorization.
  • Do not use emojis in documentation.
  • Do not use em-dashes in MR descriptions.
  • Do not create major releases.
  • Do not throw exceptions -- use Result types or explicit error return types.

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.