Skip to content
2 changes: 1 addition & 1 deletion docs/self-hosting.md
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,7 @@ What the `code` kind does:
- **Readiness.** `ready: { require_sections: [Acceptance criteria] }`. An issue with no `## Acceptance criteria` section, or an empty one, is not dispatched: Loop comments once and adds `needs-info`.
- **Checks.** `diff_policy` (the guards below), `./gradlew --no-daemon build` and `acceptance_commands`, the runnable criteria of the issue (see [`agents/issue-tracker.md`](agents/issue-tracker.md#runnable-criteria)). `--no-daemon` keeps host side checks off every agent's Gradle daemon (bl-01).
- **Delivery.** Conditional auto merge (m2-28): Loop pushes the verified commit to `loop/<identifier>`, opens a pull request on `soulesidibe/Loop` with the evidence summary, merges the current `main` into the branch and reruns the checks on the result (the merge check), waits for the GitHub Actions runs of the merged head (see [the CI wait](#the-ci-wait)), then asks `claude-sonnet-5-5` for a merge risk review. It merges and moves the issue to `done` only when every hard condition holds and the band is `low`. Otherwise it comments why and the issue waits as `Waiting(approval)`: run `loop approve <identifier>` to merge after a fresh merge check, or `loop send-back <identifier> --reason "<text>"` (m4-32) to send it back. The send back comments the reason, the next attempt runs in the same workspace with the reason as its verify findings, the pull request stays open and the next delivery updates it. It takes no `max_attempts` slot, so no `loop resume` follows. A red CI lands in the same unapproved wait, and `loop send-back` sends it back the same way.
- **Slots.** `agent.max_concurrent_agents` caps the agent Attempts and the merge checks, not the merge risk reviewer. Since bl-173 the reviewer's model session runs in the merge phase, which holds no agent slot, so it can run while Attempts hold every agent slot. Only a machine slot, when `machine.max_concurrent_agents` is set in `<LOOP_HOME>/config.yaml`, and the delivery queue, which merges one pull request at a time, bound it.
- **Slots.** `agent.max_concurrent_agents` caps the agent Attempts and the merge checks, not the merge risk reviewer. Since bl-188 the builds have their own cap: at most `agent.max_concurrent_verifications` verification and merge check builds run at once, `agent.max_concurrent_agents` when it is unset, whether an Attempt submitted, a merge check started or a restart resumed a stored `verify` wait. The others wait their turn, oldest first, and a reload that lowers the cap holds the builds not started yet. Since bl-173 the reviewer's model session runs in the merge phase, which holds no agent slot, so it can run while Attempts hold every agent slot. Only a machine slot, when `machine.max_concurrent_agents` is set in `<LOOP_HOME>/config.yaml`, and the delivery queue, which merges one pull request at a time, bound it.

`loop trace <identifier>` shows the path: the verdict, `pull_request_opened`, `merge_risk_assessed`, then `pull_request_merged` or `auto_merge_fallback` with the failed conditions.

Expand Down
18 changes: 17 additions & 1 deletion docs/spec-decisions.md
Original file line number Diff line number Diff line change
Expand Up @@ -439,6 +439,7 @@ Both behave like the spec's workflow file errors: they block dispatch until fixe
- `polling.interval_ms`
- `hooks.timeout_ms`
- `agent.max_concurrent_agents`
- `agent.max_concurrent_verifications` (bl-188, optional, see [Build gate](#build-gate-extension-bl-188))
- `agent.max_turns`
- `agent.max_wake_turns` (m4-03, see [Wake turns](#wake-turns-extension-m4-03))
- `agent.max_retry_backoff_ms`
Expand All @@ -455,7 +456,7 @@ Both behave like the spec's workflow file errors: they block dispatch until fixe
- **Per state concurrency:** in `agent.max_concurrent_agents_by_state`, state names are trimmed and lowercased, and entries that are not positive integers are ignored, not rejected (17.1).
- **Per tracker concurrency (m4-15):** `agent.max_concurrent_agents_by_tracker` is a map of tracker id to a positive integer. Unlike the per state caps, a key that is no tracker id of the workflow, a value below 1 or not an integer, and a key that is not a map fail preflight with `invalid_config`: `agent.max_concurrent_agents_by_tracker.gh names no tracker of this workflow, use one of local, side`. See [per tracker concurrency limit](#per-tracker-concurrency-limit-and-a-quieter-retry-requeue-extension-m4-15).
- **`codex.command`:** kept as the raw shell string, never expanded and not checked in M1, so `codex.command: ""` passes. The command of the selected runner is checked instead (see [preflight](#preflight-on-each-tick-clarification-of-63-m1-03)).
- **Defaults:** a missing optional key takes the spec default: `polling.interval_ms` 30000, `agent.max_concurrent_agents` 10, `agent.max_turns` 20, `agent.max_wake_turns` 30 (m4-03), `agent.max_retry_backoff_ms` 300000, `hooks.timeout_ms` 60000, `codex.stall_timeout_ms` 300000, `codex.turn_timeout_ms` 3600000, `codex.read_timeout_ms` 5000, `codex.command` `codex app-server`, `budgets.token_threshold_every` 10000000, `context.soft_limit` 0.20, `context.hard_limit` 0.21 (0.25 before m4-02, see [default limits and unknown windows](#default-limits-and-unknown-windows-extension-m4-02)), `context.prompt_limit` 0.05, `context.tool_output_tokens` 2000, `context.max_rotations` 5, `context.windows` `anthropic/claude-opus-5-5: 1000000` and, since m4-02, `openai/gpt-6.1-sol: 475000`, `observability.retention_days` 90. `budgets.per_attempt_tokens` has no default: absent means no ceiling (m1-38). No other spend budget has one either (m2-20): absent means no budget.
- **Defaults:** a missing optional key takes the spec default: `polling.interval_ms` 30000, `agent.max_concurrent_agents` 10, `agent.max_concurrent_verifications` unset, which caps builds at `agent.max_concurrent_agents` (bl-188), `agent.max_turns` 20, `agent.max_wake_turns` 30 (m4-03), `agent.max_retry_backoff_ms` 300000, `hooks.timeout_ms` 60000, `codex.stall_timeout_ms` 300000, `codex.turn_timeout_ms` 3600000, `codex.read_timeout_ms` 5000, `codex.command` `codex app-server`, `budgets.token_threshold_every` 10000000, `context.soft_limit` 0.20, `context.hard_limit` 0.21 (0.25 before m4-02, see [default limits and unknown windows](#default-limits-and-unknown-windows-extension-m4-02)), `context.prompt_limit` 0.05, `context.tool_output_tokens` 2000, `context.max_rotations` 5, `context.windows` `anthropic/claude-opus-5-5: 1000000` and, since m4-02, `openai/gpt-6.1-sol: 475000`, `observability.retention_days` 90. `budgets.per_attempt_tokens` has no default: absent means no ceiling (m1-38). No other spend budget has one either (m2-20): absent means no budget.
- **Hooks:** `hooks.*` are parsed and validated in m1-03 and run from m1-04. `hooks.on_token_threshold` (m1-38) and `hooks.on_budget_warning` (m2-20) are Loop's own optional hooks.

### Command runner shell (deviation from 10.1, m1-02)
Expand Down Expand Up @@ -1727,6 +1728,8 @@ kinds:

The phase a background run starts in decides its slot. A run started in phase `check` keeps its slot through the merge that follows it in the same run under `ci: none`, and through a new round on a moved base. A run started in phase `merge`, after a green CI wait or a merge tried again, holds none, and when the base moved it stops at the new round's phase `check`, which a later tick starts on a free slot.

Since bl-188 the merge check's rerun of the checks also passes the [build gate](#build-gate-extension-bl-188) before it builds, so it waits there behind other verification builds while it holds its agent slot.

So `agent.max_concurrent_agents` caps the agent attempts and the merge checks, not the auto merge reviewer. The reviewer's model session runs in phase `merge`, which asks for no agent slot of its own, so it is bounded only by the machine slot of m3-16, when a machine cap is set, and by the delivery queue below, whose head alone advances. The machine slot is claimed for phase `check` and for a merge phase approved by the auto policy, whose gate runs the merge risk reviewer; a merge phase approved by a human claims none.

The machine slot and the running check are taken before the background job is created, so the job starts atomically (bl-180): on a scope cancelled between the claim and the start, its body still runs, stops at once, and its `finally` releases the machine slot and ends the running check, instead of leaving the slot row until the pid liveness rule clears it.
Expand Down Expand Up @@ -3495,6 +3498,19 @@ Story 138, PLAN 10.4. Lane A, not gating the M4 exit. It calls the verification

Tests: `cli/src/test/kotlin/loop/cli/ReplayCommandTest.kt` (a kept workspace verified on a copy, unchanged afterwards, with the store's events compared before and after; a gone workspace rebuilt as a worktree and removed; a changed workspace with uncommitted changes and a gone `tree:` folder, exit 4 naming both fingerprints; no verdict; both modes; a SIGTERM during a check through the launcher, which stops the check, removes the copy and its worktree registration and records nothing; a `resource:` check that does not run), `spec-core/src/test/kotlin/loop/core/replay/ReplaySitesTest.kt`, `VerificationReplayTest.kt` and `RecordedVerdictTest.kt`.

### Build gate (extension, bl-188)

Seen on Loop's own run of 2026-11-23: the agent slots capped the launches of attempts and merge checks, not the builds they ran. An attempt kept its slot while it verified, so a reload that lowered `agent.max_concurrent_agents` left three Gradle builds running at once, a resubmit after a killed build verified again at once beside the others, and a restart resumed every stored `verify` wait at the same tick, since a restored wait takes no slot (bl-173). One restart ran four builds with the cap at 1.

- **The gate.** Every verification build and merge check build passes the project's build gate (`loop.core.orchestrator.BuildGate`) before it runs: an attempt's verification once its agent submitted, the merge check's rerun of the checks, and the rerun of a restored `verify` wait. A verification with no checks, which gives `unverified` at once, and the `diff_policy` only pass of a merge check whose base is already in the branch (bl-32) build nothing and skip it.
- **Capacity.** `agent.max_concurrent_verifications`, a positive integer, else `agent.max_concurrent_agents`. A separate key, since agent turns are mostly model time and run well in parallel while builds do not; unset, a workflow behaves as before with its builds capped at the agent cap. A value that is not a positive integer fails preflight with `invalid_config`: `agent.max_concurrent_verifications must be a positive integer, got 0`.
- **Queue.** A build that finds no room waits, first in, first out, and logs one INFO line, `event=build_gate outcome=scheduled ahead=<n>` with the issue context and the reason `verification waits for a build slot (<n> ahead)`, `<n>` counting the builds running and queued before it. No event is recorded and `loop status` shows nothing new.
- **Live capacity.** The capacity is read from the effective workflow on every admission. A reload that lowers it starts no new build until the running ones end below it, and never stops a build already running. A reload that raises it admits queued builds at the start of the next `dispatch`.
- **Cancel and failure.** Waiting in the gate can be cancelled, by a reconciliation stop or `loop stop`; the waiter leaves the queue and takes no room. The room of a build is given back when it ends, on an exception or a cancellation too.
- **Agent slots unchanged.** A restored wait still takes no agent slot and no per tracker slot (bl-173), only its build passes the gate. A merge check keeps its agent slot while it waits in the gate, which cannot deadlock, since no build needs an agent slot to end. The gate is per project: the machine slots of `<LOOP_HOME>/config.yaml` do not count builds.

Tests: `spec-core/src/test/kotlin/loop/core/orchestrator/BuildGateTest.kt` (order, a lowered and a raised capacity, a cancelled waiter, a failed build), `BuildGateOrchestratorTest.kt` (two attempts with one verification slot, a reload that lowers the cap during a build), in `OrchestratorRestartTest.kt` `three restored verify waits with max_concurrent_agents 1 rerun their builds one at a time in stored order (bl-188)`, in `MergeCheckOrchestratorTest.kt` `a restored verify rerun and a merge check never build at the same time with capacity 1 (bl-188)`, and `spec-core/src/test/kotlin/loop/core/workflow/VerificationConcurrencyConfigTest.kt`.

## Spec changes log

Each change of the pinned spec commit adds one entry, newest first: the date, the old and new commits, what changed upstream, and what Loop changed in response.
Expand Down
93 changes: 93 additions & 0 deletions spec-core/src/main/kotlin/loop/core/orchestrator/BuildGate.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
package loop.core.orchestrator

import kotlinx.coroutines.CancellationException
import kotlinx.coroutines.CompletableDeferred
import loop.core.log.LogContext

/**
* The build gate of a project (bl-188): at most [capacity] verification builds and merge check builds run at once,
* whoever started them, an attempt's verification, a merge check or the rerun of a restored `verify` wait. A build that
* finds no room waits in a first in, first out queue. [capacity] is read on every admission, so a reload changes what
* starts next and never stops a build already running; a raised capacity admits queued builds at the next [admit].
* Agent slots are a separate matter: a restored wait still takes none (bl-173), only its build passes here.
*
* [onQueued] is told once when a build has to wait, with the number of builds ahead of it, running or queued.
*/
internal class BuildGate(
private val capacity: () -> Int,
private val onQueued: (LogContext, Int) -> Unit = { _, _ -> },
) {
private val lock = Any()
private val queue = ArrayDeque<CompletableDeferred<Unit>>()

private var builds = 0

/** The builds running now. */
val running: Int
get() = synchronized(lock) { builds }

/** The builds waiting for room now. */
val queued: Int
get() = synchronized(lock) { queue.size }

/**
* Runs [block] once the gate has room for it, after every build queued before it. Waiting can be cancelled, which
* leaves the queue; the room is given back when [block] ends, also on an exception or a cancellation.
*/
suspend fun <T> withBuild(
context: LogContext,
block: suspend () -> T,
): T {
acquire(context)
try {
return block()
} finally {
release()
}
}

/** Admits the queued builds the capacity has room for now, oldest first, for a capacity raised since. */
fun admit() {
synchronized(lock) { admitLocked() }
}

private suspend fun acquire(context: LogContext) {
val ticket = CompletableDeferred<Unit>()
val ahead =
synchronized(lock) {
if (queue.isEmpty() && builds < capacity()) {
builds++
return
}
queue.addLast(ticket)
builds + queue.size - 1
}
onQueued(context, ahead)
try {
ticket.await()
} catch (e: CancellationException) {
synchronized(lock) {
// Admitted just before the cancel came: the room it was given goes to the next build.
if (!queue.remove(ticket)) {
builds--
admitLocked()
}
}
throw e
}
}

private fun release() {
synchronized(lock) {
builds--
admitLocked()
}
}

private fun admitLocked() {
while (queue.isNotEmpty() && builds < capacity()) {
builds++
queue.removeFirst().complete(Unit)
}
}
}
31 changes: 28 additions & 3 deletions spec-core/src/main/kotlin/loop/core/orchestrator/Orchestrator.kt
Original file line number Diff line number Diff line change
Expand Up @@ -594,6 +594,23 @@ class Orchestrator(
*/
private val waits = Waits(waiting, projectId)

/**
* bl-188: every verification build and merge check build passes here first, an attempt's, a merge check's and a
* restored wait's rerun, so at most `agent.max_concurrent_verifications` (else `agent.max_concurrent_agents`) run at
* once. Read from [effective] on every admission, so a reload applies to the builds that have not started yet.
*/
private val buildGate =
BuildGate({ effective.config.agent.buildCapacity }) { context, ahead ->
log.log(
LogLevel.INFO,
BUILD_GATE,
LogOutcome.SCHEDULED,
context,
mapOf("ahead" to ahead),
"verification waits for a build slot ($ahead ahead)",
)
}

/** True once [restoreWaiting] resumed the waits a previous process left. */
private var waitingRestored = false

Expand Down Expand Up @@ -804,6 +821,8 @@ class Orchestrator(
// bl-101: before the preflight, so a slot whose release failed is not held while config.yaml stays malformed.
machineGate.retryReleases(pollContext)
if (!passesPreflight()) return Dispatched(candidates = 0, attempts = emptyList())
// bl-188: a reload that raised the build capacity starts the queued builds it now has room for.
buildGate.admit()
// m4-13: each tracker polled with its own active states; one that fails is skipped this tick, the others go on.
val polled = trackers.poll(effective.trackers)
polled.failures.forEach { (id, error) ->
Expand Down Expand Up @@ -2434,7 +2453,7 @@ class Orchestrator(
}
val wait = Wait.verify(projectId, issue.id, issue.identifier, attemptId, runId, clock.now(), to, kind?.name)
return waitingFor(wait, write = true, endOnCancel = { executions[issue.id]?.stop != null }) {
val passed = verification.verify().also { submitted = it }
val passed = buildGate.withBuild(logContext()) { verification.verify() }.also { submitted = it }
progress.verified(verification.failingChecks)
verdicts = true
refuted = verification.findings
Expand Down Expand Up @@ -4801,7 +4820,9 @@ class Orchestrator(
verification.prepare()
if (!verification.hasChecks) return RecheckOutcome.Skipped
}
if (verification.verify()) return RecheckOutcome.Passed
// bl-188: the full rerun is a build and waits for the build gate; the diff policy pass alone builds nothing.
val passed = if (diffPolicyOnly) verification.verify() else buildGate.withBuild(context) { verification.verify() }
if (passed) return RecheckOutcome.Passed
return RecheckOutcome.Failed(verification.unverified, verification.findings?.text)
}

Expand Down Expand Up @@ -4966,7 +4987,8 @@ class Orchestrator(
try {
waitingFor(wait, write = false, endOnCancel = { false }) {
record(ResultSubmitted, mapOf(Results.TO to checkNotNull(to), Results.RESTORED to "true"))
val failure = if (verification.verify()) verification.deliver(to) else null
val passed = buildGate.withBuild(context) { verification.verify() }
val failure = if (passed) verification.deliver(to) else null
// A refuted rerun hands its findings to the issue's next attempt, like an attempt's (m2-06).
verification.findings?.let { verifyFindings[wait.issueId] = it.text }
// An unverified rerun parks the issue before its wait ends, like an attempt's (m2-08).
Expand Down Expand Up @@ -5164,6 +5186,9 @@ class Orchestrator(
/** The operator log event of a pause of the delivery queue and its resume (bl-175). */
const val DELIVERY_QUEUE = "delivery_queue"

/** bl-188: a build that waits for room in the build gate. */
const val BUILD_GATE = "build_gate"

/** The values of the verdict that ends each verification (m2-05). */
const val VERIFIED = Verification.VERIFIED
const val REFUTED = Verification.REFUTED
Expand Down
Loading