Autonomous development for real products. Governed agents build from specs you approve, follow the rules you set, and nothing merges until another agent proves it. Your decisions, judgement and taste are the bar that work must clear. Declare your vision and let agents build it.
JavaScript agentic-codingai-agentsai-governanceautonomous-agentsclaude-codeclicode-reviewcodexcoding-agentsdeveloper-toolsgit-hooksllmlocal-firstmulti-agentsoftware-factoryspec-driven-developmentverificationvibe-coding
feat(line): enforce recorded capacity and idle takeover [N2,B13,H16]
Corey Olson7d7c7e7c4c71
diff --git a/docs/formats.md b/docs/formats.mdindex 5d3d4970..7ad1b496 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -624,3 +624,9 @@ notice per overlapping item, linked to its item thread; the edit remains allowedUnchanged paths, prose, reordered lists and removals do not resend notices. Olderrecorded edits retain their silent behavior. The unassigned feature leaf receivesits number at landing; no event-log or envelope format changes.++### Line capacity decisions++With `reviewsFirst` on, ordinary `next` offers an eligible review before a build when outstanding submissions exceed `wipPerReviewer` times the active-reviewer count (or ratio 3 while that numeric control is off). No permanent builder/reviewer seat type or role flag is required. Active reviewers are distinct registered seats with a reservation or verdict inside the flow window; its default is the last hour, and an empty window counts as one reviewer. The window uses the same validated boundaries as `stats --window`.++With numeric `wipPerReviewer` on, a new claim that would exceed that limit is refused as `LINE_WIP_LIMIT`, naming the oldest eligible pending review when there is one. Live claimed items and outstanding submissions count; expired claims do not. Renewals remain possible. The native claim carries the configured verifier and family policies so its suggested review never relaxes those guards. With `takeoverMinutes` on, a sent-back item's idle interval can end its original builder's first-refusal window early; a live claim is never stolen, and normal claim appends preserve the old history. Disabled controls retain the previous behavior. New claims under these controls carry the line-capacity engine floor; older recorded claims keep their historical meaning during replay.diff --git a/docs/lifecycle.md b/docs/lifecycle.mdindex 7be0c9ea..ddc15fdd 100644--- a/docs/lifecycle.md+++ b/docs/lifecycle.md@@ -56,7 +56,7 @@ Each move checks its guards in this order and refuses with the first one that do| Move | From | To | Who | Guards, in order; result refusals || --- | --- | --- | --- | --- || intake | open | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), outsideSubmission (OUTSIDE_SOURCE) |-| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE or OUTSIDE_NATIVE_BUILD), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) |+| claim | open, claimed | claimed | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_CLAIMABLE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), itemNotHeld (ITEM_HELD), inLane (WRONG_LANE or OUTSIDE_NATIVE_BUILD), routeAllows (ROUTE), dependenciesVerified (BLOCKED), notHeldByAnother (HELD), builderFirstRefusal (REOPEN_HELD_FOR_BUILDER), correctionRefrozen (PENDING_REFREEZE), laneOpen (LANE_HELD), lineCapacity (LINE_WIP_LIMIT), oneLiveClaim (ONE_CLAIM), rowsInForce (UNKNOWN_SPEC or A5_GRAMMAR_VERSION or NO_POLICY or BAD_CONFIG or SPEC_BEHIND_MAIN or AGENT_APPROVAL_REQUIRED or BAR_NOT_READY) || release | open, claimed | open | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), releaseOwnsWork (NOT_YOURS), reviewReleaseExplained (NOTE_REQUIRED) || lapse | claimed | open | clock, when its lease runs out | none || submit | claimed | submitted | agent, coordinator | joined (NOT_JOINED or SESSION_LEDGER), itemExists (NO_ITEM), inState (NOT_YOURS), isHolder (NOT_YOURS or OUTSIDE_NATIVE_BUILD), correctionRefrozen (PENDING_REFREEZE), checkProvesSomething (CRITERION_PROVES_NOTHING), barReady (BAR_NOT_READY), criterionUnchanged (CRITERIA_CHANGED), treeClean (DIRTY), nothingUntracked (UNTRACKED), hasCommit (NO_COMMIT or HOST_NAME), withinLane (OUTSIDE_LANE or NO_POLICY or BAD_CONFIG or GIT_GRAFTS), trunkMergeClean (MERGE_CONFLICT or MERGE_CHECK_FAILED or NO_POLICY or NO_TRUNK), trunkInCandidate (MAIN_NOT_COMPOSED), noUnverifiedStack (STACKED_ON_UNVERIFIED), infraExplained (INFRA_NOTE_REQUIRED), doctrineHolds (RATCHET_ROSE or RATCHET_UNCOUNTED), gateConfigured (NO_GATE), queuedItemLease (ITEM_LEASE_LOST or A5_GRAMMAR_VERSION or SPEC_BEHIND_MAIN or NOT_A_REPO or NO_CONFIG), gateGreen (GATE_RED or LAND_TIMEOUT_CUSTODY or LAND_GATE_OUTPUT or SLOT_DB_LOCKED or TIMING_SLOT_REQUIRED or RUNNER_BROWSER_SLOT_REQUIRED or PIPEFAIL_UNAVAILABLE), treeStillDuringGate (MOVED_DURING_GATE), submissionProofValid (SUBMISSION_PROOF), childrenDone (CHILDREN_OPEN), headIsNew (HEAD_NOT_NEW) |@@ -113,6 +113,7 @@ Each move checks its guards in this order and refuses with the first one that do| LANE_HELD | nobody holds its lane, unless the caller is renewing its own live claim | pullboard next --wait 9 (minutes) || ITEM_HELD | the coordinator has not put this item on hold, unless the caller is renewing its own live claim | the coordinator lifts it with pullboard hold <id> --off || PENDING_REFREEZE | no coordinator correction to a claimed criterion or check is waiting to be frozen | pullboard refreeze <id> |+| LINE_WIP_LIMIT | a new claim stays within recorded WIP per active reviewer, only for new claims while wipPerReviewer is on | review the oldest eligible waiting submission: pullboard next --verify || ONE_CLAIM | the caller holds no other live top-level claim, reworks of its own rejected items aside | submit or release the other item first; child items are free || UNKNOWN_SPEC | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | fix the spec, or the coordinator withdraws the item || A5_GRAMMAR_VERSION | every row the item cites exists and is in force, only where the criterion freezes: claiming an item with no frozen criterion, and refreeze | upgrade Pullboard or use a file written for grammar 1 |diff --git a/src/board.js b/src/board.jsindex b1272a9f..a293caff 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,4 @@+import { capacitySettings, lineCapacitySnapshot, lineCapacityProblem } from './line-capacity.js';import {lineOrderEnabled,lineBuildOrder,@@ -961,7 +962,7 @@ export function recordAttempt(board, id, { agentId, n, seconds, result }) {* @param {{ agentId: string, lane: string, leaseMs: number, freeze: (item: any) => { text: string, digest: string }, head?: string | null, reviewSkipped?: object | null }} who* @returns {{ leaseUntil: string, digest: string, renewed: boolean }}*/-export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null, reviewSkipped = null }) {+export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null, reviewSkipped = null, reviewPolicy = 'any', familyPolicy = 'off' }) {return atomic(board, () => {const leaseUntil = new Date(board.clock.now().getTime() + leaseMs).toISOString();const isRenewal = (item) => item.item_owner === agentId && isHeld(board, item);@@ -1017,6 +1018,8 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null,? new Refused('ITEM_HELD', `item #${id} is held by coordinator: ${held.item_hold_reason}; wait for the coordinator to lift it with pullboard hold ${id} --off`): null;},+ lineCapacity: found => lineCapacityProblem(board, { renewal: isRenewal(found), oldestReview: pending =>+ oldestCapacityReview(board, pending, { agentId, policy: reviewPolicy, familyPolicy }) }),oneLiveClaim: (found) => {if (found.item_parent_id !== null || isRework(found)) return null;const other = board.db@@ -1262,11 +1265,21 @@ export { reviewQueue } from './board-query.js';/** Offer an eligible review at the queue ratio without claiming or reserving anything [Q1,V15]. */export function reviewOffer(board, { agentId, lane, policy = 'any', familyPolicy = 'off', ratio = 3, runnable = false, routes = ROUTES }) {const queue = reviewQueue(board);- if (queue.pending < ratio * Math.max(queue.reviewing, 1)) return null;+ const settings = capacitySettings(board);+ const capacity = settings.reviewsFirst === true ? lineCapacitySnapshot(board) : null;+ if (capacity) ratio = typeof settings.wipPerReviewer === 'number' ? settings.wipPerReviewer : 3;+ if (capacity ? queue.pending <= ratio * capacity.activeReviewers : queue.pending < ratio * Math.max(queue.reviewing, 1)) return null;const { item } = nextFor(board, { agentId, lane, verify: true, policy, familyPolicy, runnable, routes });return item ? { item, queue, ratio } : null;}+/** Find the oldest eligible submission with exactly the reservation guards, including cooldown and ownership. */+function oldestCapacityReview(board, pending, who) {+ const checks = Object.values(reviewerChecks(board, who));+ return pending.find(item => !reviewHolder(board, item) && !reviewReleaseCooldown(board, item.item_id, who.agentId)+ && checks.every(check => !check(item))) ?? null;+}+/*** What a verifier must pass before it reviews an item, alike when it reserves the review and when* it gives its verdict: it did not build the item, its route covers the item's, the repo's verifydiff --git a/src/claims.js b/src/claims.jsindex 0c7b88ef..cf7df5eb 100644--- a/src/claims.js+++ b/src/claims.js@@ -1,3 +1,4 @@+import { takeoverReady } from './line-capacity.js';/** Durable first-refusal windows for reopened work [B13,B5]. */import { Refused } from './refused.js';@@ -26,7 +27,7 @@ export function firstRefusalProblem(board, id, agentId) {/** Explain ineligible build work without raising an item refusal from review selection. */export function firstRefusalReason(board, id, agentId) {const window = firstRefusal(board, id);- return window && window.builder !== agentId+ return window && window.builder !== agentId && !takeoverReady(board, id)? `item #${id} waits for ${window.builder} until ${window.until}; claim it after that time, or ask its builder to release it`: null;}diff --git a/src/cli.js b/src/cli.jsindex d25ac89e..8826f40c 100644--- a/src/cli.js+++ b/src/cli.js@@ -613,7 +613,8 @@ export async function ordered(ctx, board, operation, args) {/** Order a claim on every route (claim, next, run) only after a check green on main is not held [V4]. */export async function claimOrdered(ctx, board, args) {refuseClaimProvesNothing(ctx.info.root, board, args[0]);- return await ordered(ctx, board, 'claim', args);+ return await ordered(ctx, board, 'claim', [args[0], { ...args[1],+ reviewPolicy: ctx.config.verify.policy, familyPolicy: ctx.config.verify.family }]);}/**@@ -1536,7 +1537,7 @@ function nextPick(ctx, board, values) {if (offer && !values.build) return { item: offer.item, offer, build: item ?? null };if (!item) return { reasons, laneWork: ctx.info.isMain ? mainLaneWork(store.listItems(board)) : null };const reviewSkipped = values.build && !held- ? { offeredItem: offer?.item.item_id ?? null, ratio: ctx.config.verify.reviewRatio, ...store.reviewQueue(board) } : null;+ ? { offeredItem: offer?.item.item_id ?? null, ratio: offer?.ratio ?? ctx.config.verify.reviewRatio, ...store.reviewQueue(board) } : null;return { claim: true, me, item, held, shared, reasons, reviewSkipped, seats };}diff --git a/src/engine.js b/src/engine.jsindex c332cfcd..ada98e94 100644--- a/src/engine.js+++ b/src/engine.js@@ -1,3 +1,5 @@+import { LINE_CAPACITY_ENGINE } from './line-capacity-engine.js';+import { lineSettings } from './line-settings.js';import { outsideSource } from './outside-source.js';import { requireOutsideReceipt } from './outside-proof.js';import { OUTSIDE_INTAKE_ENGINE } from './outside-intake-engine.js';@@ -103,7 +105,8 @@ const OPERATION_ENGINE = Object.freeze({ setLineSetting: LINE_SETTINGS_ENGINE, dfunction minimumOperationEngine(operation, args, board, at) {const outside = ['intakeOutside', 'approveOutside'].includes(operation) || operation === 'verify' && args[1]?.sandbox !== undefined|| board && ['claim', 'submit', 'verify', 'merged'].includes(operation) && Boolean(outsideSource(board, args[0]));- return Math.max(outside ? OUTSIDE_INTAKE_ENGINE : 1, minimumExistingOperationEngine(operation, args, board, at));+ const capacity = board && operation === 'claim' && ['wipPerReviewer', 'takeoverMinutes'].some(key => typeof lineSettings(board)[key] === 'number');+ return Math.max(outside ? OUTSIDE_INTAKE_ENGINE : 1, capacity ? LINE_CAPACITY_ENGINE : 1, minimumExistingOperationEngine(operation, args, board, at));}/** Preserve each pre-existing move's required feature level when composing outside metadata. */diff --git a/src/line-capacity-engine.js b/src/line-capacity-engine.jsnew file mode 100644index 00000000..58577a9f--- /dev/null+++ b/src/line-capacity-engine.js@@ -0,0 +1,3 @@+/** Recorded line-capacity enforcement receives its permanent replay number at landing [N2,H16]. */+import { unassignedEngine } from './engine-next.js';+export const LINE_CAPACITY_ENGINE = unassignedEngine();diff --git a/src/line-capacity.js b/src/line-capacity.jsnew file mode 100644index 00000000..862d4e9d--- /dev/null+++ b/src/line-capacity.js@@ -0,0 +1,51 @@+/** Board-owned capacity uses recorded review work, never a seat's lane as its permanent role [N2,B13,H16]. */+import { ENGINE_VERSION } from './machine.js';+import { LINE_CAPACITY_ENGINE } from './line-capacity-engine.js';+import { lineSettings } from './line-settings.js';+import { flowWindowBounds } from './stats-flow-window.js';+import { Refused } from './refused.js';++/** Old ordered claims keep their original semantics even beside newer recorded controls. */+export function capacitySettings(board) {+ return (board.executionEngineVersion ?? ENGINE_VERSION) >= LINE_CAPACITY_ENGINE ? lineSettings(board) : {};+}++/** The controller and capacity count use the same validated flow-window boundaries; the default is one hour. */+export function lineCapacitySnapshot(board, { windowMinutes = 60 } = {}) {+ const at = board.clock.now().getTime();+ const window = flowWindowBounds(windowMinutes, at);+ const reviewers = board.db.prepare(`SELECT DISTINCT event_by FROM event JOIN agent ON agent_id=event_by+ WHERE event_kind IN ('reserve','accept','reject','verify') AND event_at>=? AND event_at<=?`).all(window.since, window.until);+ const pending = board.db.prepare(`SELECT item.*, MAX(event.event_id) AS submitted_order FROM item+ JOIN event ON event.item_id=item.item_id AND event_kind='submit' WHERE item_status='submitted'+ GROUP BY item.item_id ORDER BY submitted_order, item.item_id`).all();+ const building = board.db.prepare("SELECT COUNT(*) AS count FROM item WHERE item_status='claimed' AND item_lease_until>?").get(window.until).count;+ return { ...window, activeReviewers: Math.max(reviewers.length, 1), pending, building, wip: pending.length + building };+}++/** Enforce only a new claim; renewals cannot be stranded by a setting changed during their existing work. */+export function lineCapacityProblem(board, { renewal, oldestReview } = {}) {+ const ratio = capacitySettings(board).wipPerReviewer;+ if (renewal || typeof ratio !== 'number') return null;+ const snapshot = lineCapacitySnapshot(board);+ const limit = ratio * snapshot.activeReviewers;+ if (snapshot.wip + 1 <= limit) return null;+ const review = oldestReview?.(snapshot.pending);+ return new Refused('LINE_WIP_LIMIT', `the line has ${snapshot.wip} live claims and submissions against limit ${limit}; `+ + (review ? `review oldest waiting item #${review.item_id}: pullboard next --verify ${review.item_id}`+ : 'no waiting review is eligible for this seat; ask the coordinator to arrange an eligible reviewer'));+}++/** A recorded idle wait may shorten a send-back's builder reservation, but never steals a live claim. */+export function takeoverReady(board, id) {+ const minutes = capacitySettings(board).takeoverMinutes;+ if (typeof minutes !== 'number') return false;+ const item = board.db.prepare('SELECT item_status, item_lease_until FROM item WHERE item_id=?').get(id);+ const now = board.clock.now().getTime();+ if (item?.item_status === 'claimed' && Date.parse(item.item_lease_until) > now) return false;+ const returned = board.db.prepare("SELECT event_id, event_at, event_kind FROM event WHERE item_id=? AND event_kind IN ('reject','reopen','submit') ORDER BY event_id DESC LIMIT 1").get(id);+ if (!returned || returned.event_kind === 'submit') return false;+ const activity = board.db.prepare("SELECT event_at FROM event WHERE item_id=? AND event_id>? AND event_kind IN ('claim','renew','release') ORDER BY event_id DESC LIMIT 1").get(id, returned.event_id);+ const since = Date.parse(activity?.event_at ?? returned.event_at);+ return Number.isFinite(since) && now >= since + minutes * 60_000;+}diff --git a/src/machine.js b/src/machine.jsindex 495fc6ef..5d107539 100644--- a/src/machine.js+++ b/src/machine.js@@ -113,6 +113,7 @@ export const GUARDS = [{ id: 'laneOpen', refuse: 'LANE_HELD', rule: 'nobody holds its lane', next: 'pullboard next --wait 9 (minutes)', source: 'board', when: 'unless the caller is renewing its own live claim' },{ id: 'itemNotHeld', refuse: 'ITEM_HELD', rule: 'the coordinator has not put this item on hold', next: 'the coordinator lifts it with pullboard hold <id> --off', source: 'board', when: 'unless the caller is renewing its own live claim' },{ id: 'correctionRefrozen', refuse: 'PENDING_REFREEZE', rule: 'no coordinator correction to a claimed criterion or check is waiting to be frozen', next: 'pullboard refreeze <id>', source: 'board' },+ { id: 'lineCapacity', refuse: 'LINE_WIP_LIMIT', rule: 'a new claim stays within recorded WIP per active reviewer', next: 'review the oldest eligible waiting submission: pullboard next --verify', source: 'board', when: 'only for new claims while wipPerReviewer is on' },{ id: 'oneLiveClaim', refuse: 'ONE_CLAIM', rule: 'the caller holds no other live top-level claim, reworks of its own rejected items aside', next: 'submit or release the other item first; child items are free', source: 'board' },{ id: 'rowsInForce', refuse: 'UNKNOWN_SPEC', alsoRefuses: [{ code: 'A5_GRAMMAR_VERSION', next: 'upgrade Pullboard or use a file written for grammar 1' }, { code: 'NO_POLICY', next: 'restore the committed coordinator policy' }, { code: 'BAD_CONFIG', next: 'repair and commit the coordinator configuration' }, { code: 'SPEC_BEHIND_MAIN', next: 'merge main from this worktree, then retry the claim' }, { code: 'AGENT_APPROVAL_REQUIRED', next: 'ask the coordinator to arrange the person’s confirmation or decline, or change the explicit refuse setting' }, { code: 'BAR_NOT_READY', next: 'another parent session signs coverage for the current accepted test inventory and runner' }], rule: 'every row the item cites exists and is in force', next: 'fix the spec, or the coordinator withdraws the item', source: 'board', when: 'only where the criterion freezes: claiming an item with no frozen criterion, and refreeze' },{ id: 'criterionUnchanged', refuse: 'CRITERIA_CHANGED', rule: 'the criterion and the rows it cites read as they did at claim', next: 'the coordinator runs pullboard refreeze <id>', source: 'cli' },@@ -162,7 +163,7 @@ export const MOVES = [guards: ['joined', 'itemExists', IN_STATE, 'outsideSubmission'], sets: ['item_built_by', 'item_commit', 'item_frozen_digest'], command: 'pullboard intake <PR> --criterion \"...\" --check \"...\"' },{verb: 'claim', from: ['open', 'claimed'], to: 'claimed', by: ['agent', 'coordinator'], refuse: 'NOT_CLAIMABLE',- guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'barReady', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'builderFirstRefusal', 'correctionRefrozen', 'laneOpen', 'oneLiveClaim', 'rowsInForce'],+ guards: ['joined', 'itemExists', IN_STATE, 'checkProvesSomething', 'barReady', 'itemNotHeld', 'inLane', 'routeAllows', 'dependenciesVerified', 'notHeldByAnother', 'builderFirstRefusal', 'correctionRefrozen', 'laneOpen', 'lineCapacity', 'oneLiveClaim', 'rowsInForce'],sets: ['item_owner', 'item_lease_until', 'item_frozen_digest'], command: 'pullboard claim <id>',},{diff --git a/src/next-step-words.js b/src/next-step-words.jsindex 5903c9c1..c2f24141 100644--- a/src/next-step-words.js+++ b/src/next-step-words.js@@ -56,6 +56,7 @@ export function personRequestGuidance(message, { caller, leading = false } = {})/** @type {Readonly<Record<string, string>>} */export const NEXT_STEPS = Object.freeze({+ LINE_WIP_LIMIT: 'review the oldest eligible waiting submission: pullboard next --verify; if none is eligible, ask the coordinator to arrange a reviewer',OUTSIDE_NATIVE_BUILD: 'the outside author revises the PR; ask the coordinator to return it, then intake its new exact head',CHECK_NO_PROOF: 'strengthen the trusted criterion so it fails before the outside change, then ask the coordinator to refreeze it',OUTSIDE_URL: 'use a GitHub issue or pull request URL with owner/repository and its positive number',diff --git a/src/stats-flow-window.js b/src/stats-flow-window.jsindex e96fc03b..c5dca51a 100644--- a/src/stats-flow-window.js+++ b/src/stats-flow-window.js@@ -120,10 +120,8 @@ function stageTraffic(items, stage, since, now) {/** Project landed item totals and stage traffic from the same prepared canonical lifecycle facts. */export function projectFlowWindow(prepared, minutes, now) {- if (!(minutes > 0) || !Number.isFinite(minutes) || !Number.isFinite(new Date(now - minutes * MINUTE).getTime())) {- throw new Refused('USAGE', 'use pullboard stats --window with a positive finite duration, for example --window 6h');- }- const since = now - minutes * MINUTE;+ const bounds = flowWindowBounds(minutes, now);+ const since = Date.parse(bounds.since);const landed = prepared.items.filter(item => item.mergeAt >= since && item.mergeAt <= now);const stages = Object.fromEntries(WINDOW_STAGES.map(stage => {const measured = landed.map(item => ({ item, minutes: stageMinutes(item, stage) })).filter(row => row.minutes !== null);@@ -136,7 +134,7 @@ export function projectFlowWindow(prepared, minutes, now) {.map(row => tailItem(row.item, stage, row.minutes)) }];}));const constraint = WINDOW_STAGES.reduce((largest, stage) => stages[stage].overTargetMinutes > (largest ? stages[largest].overTargetMinutes : 0) ? stage : largest, null);- return { since: new Date(since).toISOString(), until: new Date(now).toISOString(), durationMinutes: minutes,+ return { ...bounds,landedItems: landed.length,arrivals: { added: prepared.dailyEvents.filter(event => event.kind === 'added' && event.at >= since && event.at <= now).length, landed: landed.length },stages, constraint: { stage: constraint, overTargetMinutes: constraint ? stages[constraint].overTargetMinutes : 0 } };@@ -154,3 +152,12 @@ export function flowWindowLines(window) {}),`constraint: ${window.constraint.stage ? LABELS[window.constraint.stage] : 'none measured over target'} · ${time(window.constraint.overTargetMinutes)} over target`];}++/** Share exact validated window boundaries with line-capacity decisions. */+export function flowWindowBounds(minutes, now) {+ if (!(minutes > 0) || !Number.isFinite(minutes) || !Number.isFinite(new Date(now - minutes * MINUTE).getTime())) {+ throw new Refused('USAGE', 'use pullboard stats --window with a positive finite duration, for example --window 6h');+ }+ const since = now - minutes * MINUTE;+ return { since: new Date(since).toISOString(), until: new Date(now).toISOString(), durationMinutes: minutes };+}diff --git a/test/line-capacity.test.js b/test/line-capacity.test.jsnew file mode 100644index 00000000..66342f35--- /dev/null+++ b/test/line-capacity.test.js@@ -0,0 +1,97 @@+/** Capacity uses real SQLite lifecycle observations and versioned claims, not modelled permanent seat roles [N2,B13,H16]. */+import assert from 'node:assert/strict';+import { test } from 'node:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import * as store from '../src/board.js';+import { submitFixture } from './board-submit-fixture.js';+import { lineCapacitySnapshot } from '../src/line-capacity.js';+import { LINE_CAPACITY_ENGINE } from '../src/line-capacity-engine.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { exportBoard, importBoard } from '../src/exchange.js';++const HOUR = 3_600_000;+const FREEZE = () => ({ text: 'private lifecycle bar', digest: 'private-lifecycle-bar' });+/** Create one real board with explicit actor identities and an adjustable observation clock. */+function fixture(t) {+ const root = mkdtempSync(join(tmpdir(), 'pullboard-line-capacity-'));+ let at = Date.parse('2026-10-24T00:00:00Z');+ const clock = { now: () => new Date(at) };+ const board = store.openBoard(join(root, 'board.sqlite'), clock);+ t.after(() => { store.closeBoard(board); rmSync(root, { recursive: true, force: true }); });+ store.register(board, { lane: 'coordinator', path: root });+ const author = store.register(board, { lane: 'core', path: join(root, 'author'), route: 'strong', parent: 'A', session: 'a' });+ const reviewer = store.register(board, { lane: 'core', path: join(root, 'reviewer'), route: 'strong', parent: 'R', session: 'r' });+ /** Record normal private claims without asserting a gate execution. */+ function claim(id, agentId = author, options = {}) {+ return store.claim(board, id, { agentId, lane: 'core', leaseMs: HOUR, freeze: FREEZE, ...options });+ }+ /** Seed a submitted lifecycle through its normal moves. */+ function submit(title = 'waiting') {+ const id = store.addItem(board, { by: 'coordinator', lane: 'core', title });+ claim(id);+ submitFixture(board, id, { agentId: author, commit: String(id).padStart(40, 'a'), tree: String(id).padStart(40, 'b') });+ return id;+ }+ /** Change one recorded board input, leaving machine settings untouched. */+ function setting(key, value) {+ return store.setLineSetting(board, { agentId: 'coordinator', key, value, reason: 'private capacity proof', window: { activeReviewers: 1 } });+ }+ return { board, root, author, reviewer, claim, submit, setting, advance: ms => { at += ms; } };+}++test('capacity counts distinct review actors in the same bounded flow window, not their lane [N2,H16]', t => {+ const f = fixture(t), first = f.submit('first'), second = f.submit('second');+ assert.equal(lineCapacitySnapshot(f.board).activeReviewers, 1, 'no observations retains the denominator floor');+ store.reserveReview(f.board, first, { agentId: f.reviewer, leaseMs: HOUR, policy: 'any' });+ store.reserveReview(f.board, first, { agentId: f.reviewer, leaseMs: HOUR, policy: 'any' });+ store.reserveReview(f.board, second, { agentId: 'coordinator', leaseMs: HOUR, policy: 'any' });+ assert.equal(lineCapacitySnapshot(f.board).activeReviewers, 2, 'a core seat and coordinator are both observed reviewers; renewals do not duplicate them');+ f.advance(2 * HOUR);+ assert.equal(lineCapacitySnapshot(f.board).activeReviewers, 1);+ assert.equal(lineCapacitySnapshot(f.board, { windowMinutes: 180 }).activeReviewers, 2, 'the explicit flow window changes both bounds');+ assert.throws(() => lineCapacitySnapshot(f.board, { windowMinutes: Infinity }), { code: 'USAGE' });+});++test('WIP counts live claims and pending submissions, refuses atomically, and preserves renewals [N2,B13,H16]', t => {+ const f = fixture(t), waiting = f.submit();+ const a = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'one live claim' });+ const b = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'new claim' });+ f.claim(a);+ f.setting('wipPerReviewer', 1.5);+ const before = store.events(f.board).length;+ assert.throws(() => f.claim(b, f.reviewer), error => error.code === 'LINE_WIP_LIMIT' && error.message.includes(`#${waiting}`));+ assert.equal(store.events(f.board).length, before, 'a refused claim appends no history');+ assert.equal(store.getItem(f.board, b).item_frozen_digest, null);+ assert.equal(f.claim(a).renewed, true, 'a changed setting never strands a held claim');+ f.advance(HOUR + 1);+ assert.equal(lineCapacitySnapshot(f.board).wip, 1, 'an expired claim no longer consumes capacity');+ f.setting('wipPerReviewer', false);+ f.claim(b, f.reviewer);+ assert.equal(store.getItem(f.board, b).item_owner, f.reviewer, 'off restores ordinary claim behavior');+});++test('the offered oldest review respects the actual claim caller policy and author independence [N2,B13,H16]', t => {+ const f = fixture(t), waiting = f.submit();+ const id = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'blocked new work' });+ f.setting('wipPerReviewer', 1.5);+ assert.throws(() => f.claim(id, f.author), error => error.code === 'LINE_WIP_LIMIT' && !error.message.includes(`review oldest waiting item #${waiting}`));+ assert.throws(() => f.claim(id, f.reviewer, { reviewPolicy: 'coordinator' }), error => error.code === 'LINE_WIP_LIMIT' && !error.message.includes(`review oldest waiting item #${waiting}`));+});++test('old recorded claims ignore new capacity while new claims retain the feature floor on replay [N2,H16]', t => {+ const f = fixture(t); f.submit(); f.submit(); f.setting('wipPerReviewer', 1.5);+ const id = store.addItem(f.board, { by: 'coordinator', lane: 'core', title: 'old recorded claim' });+ const snapshot = exportBoard(f.board);+ const options = { agentId: f.reviewer, lane: 'core', leaseMs: HOUR, freeze: FREEZE };+ const move = prepareEngineMove(f.board, 'claim', [id, options]);+ const old = applyEngineMove(f.board, { ...move, engine: LINE_CAPACITY_ENGINE - 1 }, { sequence: 1, at: f.board.clock.now().toISOString() });+ assert.equal(old.error, undefined, JSON.stringify(old.error));+ const replica = store.openBoard(join(f.root, 'replica.sqlite'), f.board.clock);+ t.after(() => store.closeBoard(replica));+ importBoard(replica, snapshot);+ const current = applyEngineMove(replica, move, { sequence: 1, at: f.board.clock.now().toISOString() });+ assert.equal(current.error?.code, 'LINE_WIP_LIMIT');+ assert.equal(store.getItem(replica, id).item_status, 'open');+});diff --git a/test/review-queue-cli.test.js b/test/review-queue-cli.test.jsindex 02bd366c..f8d0a5a0 100644--- a/test/review-queue-cli.test.js+++ b/test/review-queue-cli.test.js@@ -264,3 +264,22 @@ test('[Q1,V15,N14] the unattended runner keeps building and records its review bassert.ok(Number.isSafeInteger(skipped.offeredItem));assert.equal(store.listItems(box.board).some((item) => item.item_review_by === box.builderId), false, 'the runner reserves no review');});++test('[N2,B13,H16] plain next follows recorded line capacity without a reviewer role flag', async t => {+ const box = await project(t, 99);+ const ids = Array.from({ length: 5 }, () => submitted(box));+ const id = build(box);+ for (const [key, value] of [['reviewsFirst', true], ['wipPerReviewer', 1.5]]) {+ store.setLineSetting(box.board, { agentId: 'coordinator', key, value, reason: 'private five-item capacity window', window: { activeReviewers: 1 } });+ }+ const offered = await run(box, box.builder, ['next', '--json']);+ assert.equal(offered.code, 0, offered.stderr);+ assert.equal(offered.data.review, true);+ assert.ok(ids.includes(offered.data.offer.item));+ assert.equal(offered.data.offer.ratio, 1.5);+ assert.equal(store.getItem(box.board, id).item_status, 'open');+ const refused = await run(box, box.builder, ['claim', String(id), '--json']);+ assert.equal(refused.code, 1);+ assert.equal(refused.data.error.code, 'LINE_WIP_LIMIT');+ assert.match(refused.data.error.message, new RegExp(`#${ids[0]}`));+});