Factory Foreman Loop Iteration
One unattended pass of the factory foreman: watch the backlog queue, dispatch
the next operator-picked card to an isolated worker, collect completion
evidence, report. The queue surface is moai gtd; the dispatch protocol and
card classes live in the factory dispatch rule (.claude/rules/moai/workflow/factory-dispatch.md).
foreman — an auxiliary role of the leader: the unattended watcher that dispatches the already-picked card to an isolated worker when no leader session is holding the queue.
Running unattended
AskUserQuestion is removed from the tool pool while this skill is active —
that is the mechanical guarantee that the loop cannot stop and ask. Anything
that would have been a question becomes a line in the iteration report, and
anything that genuinely needs the operator's decision becomes a blocked card
under Boundaries below.
Deployment: start a session in the project, run bare /loop, then
background the session — loop tasks carry over to the background session and
keep running without a terminal. Esc cancels the pending wakeup of a
waiting loop. A recurring loop expires seven days after creation; restart it
when the queue still needs a foreman. Background monitors do not survive a
session resume — the first iteration after a resume re-arms the queue watch.
The session's permission settings must already allow what this loop uses
(queue reads, git inspection, the worker spawn). A permission prompt that
surfaces while unattended stalls the iteration until someone attaches;
pre-approving that surface in project settings is the operator's setup step,
not something this loop can do for itself.
Boundaries (hard)
- The operator admits and picks work. Only backlog items whose state is
already
picked are dispatchable. Never run moai gtd add; never run
moai gtd next <n> — that mutation is the operator's pick. Never invent,
reword, or reorder cards. An empty queue is a legitimate state: say so and
idle. A batch authorization (/moai:todo --auto — the operator's typed
invocation-as-approval) is the card-pick gate's autonomous form
(.claude/rules/moai/workflow/auto-semantics.md §9): within it, serial
consumption on its own judgment, outside the keep-set (bar a [보류 card,
which is ranked last, not excluded), is authorized; queue
ADMISSION stays the operator's. A lane takes its card through
moai factory next --card <id>, never through this loop.
- No approval gate is answered on the operator's behalf. When a card's
next step needs a human decision that is not already recorded as made
(plan-to-run kickoff approval, a review severity call, a scope choice),
do not proceed. Leave the card
picked, name it blocked-for-operator in
the report together with the decision it waits on, and move on.
- One write-capable worker at a time. While a worker is in flight the
iteration only reads. This is the foreman's own serialization, stricter than
the doctrine it sits under —
one writer per tree, owned by
.claude/rules/moai/core/agent-common-protocol.md § Background Agent
Execution. The foreman keeps one worker in flight so a failed iteration has
exactly one author to read.
- Every worker runs in its own worktree (
isolation: "worktree" on the
spawn; relative paths in the prompt — the worker's CWD is its worktree
root). Nothing writes to the shared checkout.
- No integration actions. No push, no pull request, no merge, no branch
deletion, no worktree disposal. The card's branch is unpushed and its
worktree is the work's only instance; both stay until the operator
integrates them. The report names the branch and the worktree path.
- Verification is lane-local. The worker runs only the checks its own
change can affect; the full suite belongs to CI. Never spawn background
CPU load — the queue watch below is the only long-running process this
loop arms.
- Completion is read, never trusted. A card advances only on evidence
this iteration actually read.
The iteration
Queue watch. If no backlog monitor is live (first iteration, or after
a resume), arm one Monitor on the queue file, re-arming it at each expiry:
command:
# The queue directory, resolved the way factory.StateDirForRoot does for a
# standard git-repository project: <moai-home>/db/<project-key>/todo,
# keyed by the repository's canonical (primary-checkout) root.
mh=${MOAI_HOME:-$HOME/.moai}
root=$(git rev-parse --show-toplevel 2>/dev/null) || root=$PWD
top=$(git worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p' | head -n 1)
[ -n "$top" ] && root=$top
root=$(cd "$root" && pwd -P)
key=$(basename "$root"); key=$(printf '%s' "$key" | tr -c 'A-Za-z0-9._-' '-')
sum=$(printf '%s' "$root" | sha256sum 2>/dev/null | cut -c1-8)
[ -n "$sum" ] || sum=$(printf '%s' "$root" | shasum -a 256 | cut -c1-8)
d=$mh/db/$key-$sum/todo
last=init
while true; do
cur=$(cksum "$d"/backlog.db "$d"/backlog.db-wal 2>/dev/null)
[ -n "$cur" ] || cur=missing
if [ "$cur" != "$last" ]; then
[ "$last" != init ] && echo "backlog changed"
last=$cur
fi
sleep 5
done
timeout_ms: 1800000
description: backlog queue watch
The persistent option no longer exists — every Monitor now carries a
deadline, timeout_ms is a required input, and the watch above is an
unbounded loop that never ends on its own. 1800000 is the longest
deadline the tool documents accepting; a larger value is capped rather
than honoured. At expiry the loop is killed and one notice arrives with
the event count, so an iteration that still needs the watch re-arms it.
A non-interactive (-p) session is reported to cap the deadline lower
than an interactive one; that lower cap is not observable from the tool
input schema, so treat a shorter-than-requested expiry there as expected
rather than as a fault.
The watch resolves the queue directory the way factory.StateDirForRoot
does for a standard git-repository project — a project-keyed directory
under the moai home (MOAI_HOME when that is set to an absolute path,
otherwise ~/.moai), keyed by the primary checkout's root — so a linked
worktree watches the primary checkout's queue, not a directory local to
its own tree. The queue is the database, and a backlog.json beside it is an export or
a legacy leftover — never the queue — so a watch pointed at the JSON on a
migrated project polls a file that never changes and reports nothing,
forever. The write-ahead log is watched alongside the database because a
committed write can sit in backlog.db-wal with the database image
byte-identical until a checkpoint folds it back; watching the database
alone misses exactly those mutations. The checksum poll emits one line
per change and costs two tiny reads every five seconds. Do not tighten
the interval, and do not arm a second watcher. Each emitted
line, like each scheduled wakeup, is a prompt to run this same idempotent
iteration — an iteration that finds nothing to do ends quickly.
Read the queue. moai gtd list --json (lock-free). A missing queue
file is an empty queue, never an error. Records carry id, text,
spec_id, and state (queued | picked | dropped).
Collect before dispatch. If a worker dispatched by an earlier
iteration has returned, read its evidence file first (step 6). If a
worker is still running, end the iteration with a one-line status.
Choose the dispatchable card. The oldest picked item with no live
worker and no recorded blocker. queued items are not yours to pick outside
a batch authorization.
Dispatch one worker with the Agent tool, isolation: "worktree". The
dispatch is a fixed-field address block — a pointer, not a copy, ten
lines at most:
card: <id>
spec: <SPEC-ID> # only when the card carries one
cmd: <the card's work in one line; the phase command when a SPEC is attached>
evidence: .moai/reports/<card-id>/evidence.md
Route the spawn to the agent the card's work matches under the standard
delegation rules; where no specialist matches, a general-purpose spawn
with a domain whitelist. The worker prompt carries the block plus these
standing orders: rename the worktree branch to WT-<slug> (a
descriptive slug, never the card id) first;
implement the card; verify lane-locally; write the evidence file with
decisions, verbatim output tails of the checks run, explicit gaps, and
residual risk; commit by explicit pathspec; never push.
Collect on evidence. When the worker returns, read the evidence file
it names. Advance the card — moai gtd done <t-id> — only when the
evidence shows the work complete: verbatim passing output present, gaps
named. A missing, unreadable, or stale evidence file is a gap: the card
stays picked, the report says why, and the card is not re-dispatched
this iteration. Absence of a failure signal is not a pass.
Report. Close with two to six lines: queue summary, what was
dispatched or collected, which evidence was read, blocked cards and the
decisions they wait on. This report is what the operator reads on
reattach — name what you read, not what you were told.
Factory seam (reserved, not implemented)
The single-worker dispatch above is the only mode. Fanning a card out to
numbered factory lanes — the multi-lane launcher surface — is
separate work; when the foreman grows that routing, it lands here as a
second dispatch mode chosen per card. Until then this loop spawns one
subagent per card, reads no factory state, and launches no lanes.
Failure handling
Stop the loop (ScheduleWakeup with stop: true), with a one-line reason,
when the loop cannot do its job: the queue file is repeatedly unreadable,
the queue watch cannot be armed, or this skill's own surface is broken. A
transient worker failure is not a loop failure — record it on the card and
let the next iteration decide whether to re-dispatch.
1---2name: moai-factory-foreman3description: >4 One unattended factory foreman iteration: watch the backlog queue, dispatch5 the next operator-picked card to an isolated worker, collect completion6 evidence on read (not on claims), and report. This is the body the7 project's loop.md driver invokes each iteration of a bare /loop; it can8 also be invoked directly to test one cycle by hand.910when_to_use: >11 Use when a bare /loop factory foreman iteration fires (the loop.md driver12 points here), or when the operator asks for a single manual foreman pass13 over the backlog queue.1415license: Apache-2.016compatibility: Designed for Claude Code17allowed-tools: Read, Grep, Glob, Bash(moai gtd:*), Bash(git status:*), Bash(git log:*), Bash(git rev-parse:*), Bash(git diff:*), Bash(git show:*)18disallowed-tools: AskUserQuestion19user-invocable: false20metadata:21 source: https://skillmd.com/skills/tuyv/moai-factory-foreman22 version: "1.0.0"23 category: "workflow"24 status: "active"25 tags: "factory, foreman, loop, backlog, dispatch, unattended"2627# MoAI Extension: Progressive Disclosure28progressive_disclosure:29 enabled: true30---3132# Factory Foreman Loop Iteration3334One unattended pass of the factory foreman: watch the backlog queue, dispatch35the next operator-picked card to an isolated worker, collect completion36evidence, report. The queue surface is `moai gtd`; the dispatch protocol and37card classes live in the factory dispatch rule (`.claude/rules/moai/workflow/factory-dispatch.md`).38`foreman` — an auxiliary role of the leader: the unattended watcher that dispatches the already-picked card to an isolated worker when no leader session is holding the queue.3940## Running unattended4142`AskUserQuestion` is removed from the tool pool while this skill is active —43that is the mechanical guarantee that the loop cannot stop and ask. Anything44that would have been a question becomes a line in the iteration report, and45anything that genuinely needs the operator's decision becomes a blocked card46under Boundaries below.4748Deployment: start a session in the project, run bare `/loop`, then49background the session — loop tasks carry over to the background session and50keep running without a terminal. `Esc` cancels the pending wakeup of a51waiting loop. A recurring loop expires seven days after creation; restart it52when the queue still needs a foreman. Background monitors do not survive a53session resume — the first iteration after a resume re-arms the queue watch.5455The session's permission settings must already allow what this loop uses56(queue reads, git inspection, the worker spawn). A permission prompt that57surfaces while unattended stalls the iteration until someone attaches;58pre-approving that surface in project settings is the operator's setup step,59not something this loop can do for itself.6061## Boundaries (hard)62631. **The operator admits and picks work.** Only backlog items whose state is64 already `picked` are dispatchable. Never run `moai gtd add`; never run65 `moai gtd next <n>` — that mutation is the operator's pick. Never invent,66 reword, or reorder cards. An empty queue is a legitimate state: say so and67 idle. A batch authorization (`/moai:todo --auto` — the operator's typed68 invocation-as-approval) is the card-pick gate's autonomous form69 (`.claude/rules/moai/workflow/auto-semantics.md` §9): within it, serial70 consumption on its own judgment, outside the keep-set (bar a `[보류` card,71 which is ranked last, not excluded), is authorized; queue72 ADMISSION stays the operator's. A lane takes its card through73 `moai factory next --card <id>`, never through this loop.742. **No approval gate is answered on the operator's behalf.** When a card's75 next step needs a human decision that is not already recorded as made76 (plan-to-run kickoff approval, a review severity call, a scope choice),77 do not proceed. Leave the card `picked`, name it blocked-for-operator in78 the report together with the decision it waits on, and move on.793. **One write-capable worker at a time.** While a worker is in flight the80 iteration only reads. This is the foreman's own serialization, stricter than81 the doctrine it sits under — `one writer per tree`, owned by82 `.claude/rules/moai/core/agent-common-protocol.md` § Background Agent83 Execution. The foreman keeps one worker in flight so a failed iteration has84 exactly one author to read.854. **Every worker runs in its own worktree** (`isolation: "worktree"` on the86 spawn; relative paths in the prompt — the worker's CWD is its worktree87 root). Nothing writes to the shared checkout.885. **No integration actions.** No push, no pull request, no merge, no branch89 deletion, no worktree disposal. The card's branch is unpushed and its90 worktree is the work's only instance; both stay until the operator91 integrates them. The report names the branch and the worktree path.926. **Verification is lane-local.** The worker runs only the checks its own93 change can affect; the full suite belongs to CI. Never spawn background94 CPU load — the queue watch below is the only long-running process this95 loop arms.967. **Completion is read, never trusted.** A card advances only on evidence97 this iteration actually read.9899## The iteration1001011. **Queue watch.** If no backlog monitor is live (first iteration, or after102 a resume), arm one Monitor on the queue file, re-arming it at each expiry:103104 - `command`:105106 ```sh107 # The queue directory, resolved the way factory.StateDirForRoot does for a108 # standard git-repository project: <moai-home>/db/<project-key>/todo,109 # keyed by the repository's canonical (primary-checkout) root.110 mh=${MOAI_HOME:-$HOME/.moai}111 root=$(git rev-parse --show-toplevel 2>/dev/null) || root=$PWD112 top=$(git worktree list --porcelain 2>/dev/null | sed -n 's/^worktree //p' | head -n 1)113 [ -n "$top" ] && root=$top114 root=$(cd "$root" && pwd -P)115 key=$(basename "$root"); key=$(printf '%s' "$key" | tr -c 'A-Za-z0-9._-' '-')116 sum=$(printf '%s' "$root" | sha256sum 2>/dev/null | cut -c1-8)117 [ -n "$sum" ] || sum=$(printf '%s' "$root" | shasum -a 256 | cut -c1-8)118 d=$mh/db/$key-$sum/todo119 last=init120 while true; do121 cur=$(cksum "$d"/backlog.db "$d"/backlog.db-wal 2>/dev/null)122 [ -n "$cur" ] || cur=missing123 if [ "$cur" != "$last" ]; then124 [ "$last" != init ] && echo "backlog changed"125 last=$cur126 fi127 sleep 5128 done129 ```130131 - `timeout_ms: 1800000`132 - `description: backlog queue watch`133134 The `persistent` option no longer exists — every Monitor now carries a135 deadline, `timeout_ms` is a required input, and the watch above is an136 unbounded loop that never ends on its own. `1800000` is the longest137 deadline the tool documents accepting; a larger value is capped rather138 than honoured. At expiry the loop is killed and one notice arrives with139 the event count, so an iteration that still needs the watch re-arms it.140 A non-interactive (`-p`) session is reported to cap the deadline lower141 than an interactive one; that lower cap is not observable from the tool142 input schema, so treat a shorter-than-requested expiry there as expected143 rather than as a fault.144145 The watch resolves the queue directory the way `factory.StateDirForRoot`146 does for a standard git-repository project — a project-keyed directory147 under the moai home (`MOAI_HOME` when that is set to an absolute path,148 otherwise `~/.moai`), keyed by the primary checkout's root — so a linked149 worktree watches the primary checkout's queue, not a directory local to150 its own tree. The queue is the database, and a `backlog.json` beside it is an export or151 a legacy leftover — never the queue — so a watch pointed at the JSON on a152 migrated project polls a file that never changes and reports nothing,153 forever. The write-ahead log is watched alongside the database because a154 committed write can sit in `backlog.db-wal` with the database image155 byte-identical until a checkpoint folds it back; watching the database156 alone misses exactly those mutations. The checksum poll emits one line157 per change and costs two tiny reads every five seconds. Do not tighten158 the interval, and do not arm a second watcher. Each emitted159 line, like each scheduled wakeup, is a prompt to run this same idempotent160 iteration — an iteration that finds nothing to do ends quickly.1611622. **Read the queue.** `moai gtd list --json` (lock-free). A missing queue163 file is an empty queue, never an error. Records carry `id`, `text`,164 `spec_id`, and `state` (`queued` | `picked` | `dropped`).1651663. **Collect before dispatch.** If a worker dispatched by an earlier167 iteration has returned, read its evidence file first (step 6). If a168 worker is still running, end the iteration with a one-line status.1691704. **Choose the dispatchable card.** The oldest `picked` item with no live171 worker and no recorded blocker. `queued` items are not yours to pick outside172 a batch authorization.1731745. **Dispatch one worker** with the Agent tool, `isolation: "worktree"`. The175 dispatch is a fixed-field address block — a pointer, not a copy, ten176 lines at most:177178 ```179 card: <id>180 spec: <SPEC-ID> # only when the card carries one181 cmd: <the card's work in one line; the phase command when a SPEC is attached>182 evidence: .moai/reports/<card-id>/evidence.md183 ```184185 Route the spawn to the agent the card's work matches under the standard186 delegation rules; where no specialist matches, a general-purpose spawn187 with a domain whitelist. The worker prompt carries the block plus these188 standing orders: rename the worktree branch to `WT-<slug>` (a189 descriptive slug, never the card id) first;190 implement the card; verify lane-locally; write the evidence file with191 decisions, verbatim output tails of the checks run, explicit gaps, and192 residual risk; commit by explicit pathspec; never push.1931946. **Collect on evidence.** When the worker returns, read the evidence file195 it names. Advance the card — `moai gtd done <t-id>` — only when the196 evidence shows the work complete: verbatim passing output present, gaps197 named. A missing, unreadable, or stale evidence file is a gap: the card198 stays `picked`, the report says why, and the card is not re-dispatched199 this iteration. Absence of a failure signal is not a pass.2002017. **Report.** Close with two to six lines: queue summary, what was202 dispatched or collected, which evidence was read, blocked cards and the203 decisions they wait on. This report is what the operator reads on204 reattach — name what you read, not what you were told.205206## Factory seam (reserved, not implemented)207208The single-worker dispatch above is the only mode. Fanning a card out to209numbered factory lanes — the multi-lane launcher surface — is210separate work; when the foreman grows that routing, it lands here as a211second dispatch mode chosen per card. Until then this loop spawns one212subagent per card, reads no factory state, and launches no lanes.213214## Failure handling215216Stop the loop (`ScheduleWakeup` with `stop: true`), with a one-line reason,217when the loop cannot do its job: the queue file is repeatedly unreadable,218the queue watch cannot be armed, or this skill's own surface is broken. A219transient worker failure is not a loop failure — record it on the card and220let the next iteration decide whether to re-dispatch.