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(team): compute item grants in native and replay moves [E21,H16]
Corey Olson4a0f76c80726
diff --git a/src/agent-grant-engine.js b/src/agent-grant-engine.jsnew file mode 100644index 00000000..ce74f63b--- /dev/null+++ b/src/agent-grant-engine.js@@ -0,0 +1,3 @@+/** Computed seat and claim grants, with unchanged legacy replay [E21,H16]. */+import { unassignedEngine } from './engine-next.js';+export const AGENT_GRANT_ENGINE = unassignedEngine();diff --git a/src/agent-grant.js b/src/agent-grant.jsnew file mode 100644index 00000000..37ceb360--- /dev/null+++ b/src/agent-grant.js@@ -0,0 +1,57 @@+/** Derive authority from existing seats and claims; no mutable saved grant supplies permission [E21]. */+import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';+import { MOVE_REGISTRY } from './move-registry.js';+import { Refused } from './refused.js';++const ADMINISTRATIVE = new Set(['shout', 'claim', 'release', 'reserveReview']);++/** Bind only item mutations declared by the public operation, including item creation. */+function target(move) {+ if (move.operation === 'addItem') return { lane: move.args?.[0]?.lane, creating: true };+ if (MOVE_REGISTRY[move.operation]?.itemIdFirstArgument) return { item: move.args?.[0] };+ return null;+}++/** A version marker is not a grant: it only prevents an older engine bypassing a new seat or claim. */+export function agentGrantMinimum(board, move) {+ const actor = MOVE_REGISTRY[move.operation]?.actor(move);+ if (typeof actor !== 'string' || ['person', 'coordinator', 'machine'].includes(actor)) return 1;+ const event = board.db.prepare("SELECT event_detail FROM event WHERE event_by=? AND event_kind IN ('join','claim','renew') ORDER BY event_id DESC LIMIT 1").get(actor);+ if (!event) return 1;+ const version = JSON.parse(event.event_detail).grantEngine;+ return Number.isSafeInteger(version) && version >= AGENT_GRANT_ENGINE ? AGENT_GRANT_ENGINE : 1;+}++/** Refuse out-of-grant item changes at the same ordered instant on every replica. */+export function requireAgentGrant(board, move, at = board.clock.now()) {+ if (move.engine < AGENT_GRANT_ENGINE || ADMINISTRATIVE.has(move.operation)) return;+ const actor = MOVE_REGISTRY[move.operation]?.actor(move);+ if (typeof actor !== 'string' || ['person', 'coordinator', 'machine'].includes(actor)) return;+ const seat = board.db.prepare('SELECT agent_lane FROM agent WHERE agent_id=?').get(actor);+ if (!seat) return; // Existing operation validation owns unknown-seat refusals.+ const scope = target(move);+ if (!scope) return;+ const item = Number.isSafeInteger(scope.item)+ ? board.db.prepare('SELECT * FROM item WHERE item_id=?').get(scope.item) : null;+ if (!scope.creating && !item) return; // Preserve the operation's own malformed/missing-item refusal.+ const now = at.toISOString();+ if (item?.item_review_by === actor && item.item_status === 'submitted' && item.item_review_until > now+ && ['verify', 'appendFact'].includes(move.operation)) return;+ const claims = board.db.prepare("SELECT item_id,item_lease_until FROM item WHERE item_owner=? AND item_status='claimed'").all(actor);+ const own = claims.find(claim => claim.item_id === scope.item);+ const live = claims.filter(claim => claim.item_lease_until > now);+ const previous = board.db.prepare("SELECT event_id FROM event WHERE event_by=? AND event_kind IN ('claim','renew') ORDER BY event_id DESC LIMIT 1").get(actor);+ if ((own && !(own.item_lease_until > now)) || (previous && !live.length)) {+ throw new Refused('AGENT_GRANT_EXPIRED', `${actor} has no live item claim; claim work before changing an item`,+ 'claim the intended item, or shout the coordinator if its claim is unavailable');+ }+ if ((claims.length && !own) || (live.length && scope.creating)) {+ throw new Refused('AGENT_GRANT_ITEM', `${actor} may change only its live claimed item${live.length === 1 ? ` #${live[0].item_id}` : 's'}`,+ 'finish or release the claim, then claim the intended item; use shout for coordination');+ }+ const lane = scope.creating ? scope.lane : item.item_lane;+ if (lane !== seat.agent_lane) {+ throw new Refused('AGENT_GRANT_LANE', `${actor} is in ${seat.agent_lane}, not ${lane}`,+ 'join a seat in the intended lane or ask its owner to make the item change');+ }+}diff --git a/src/board.js b/src/board.jsindex 79f49d64..6d7a4ed3 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,4 @@+import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';import { ensureProofCounters } from './proof-counters.js';import { correctedNoVerdictReopen } from './reopen-history.js';import {@@ -592,7 +593,8 @@ export function register(board, who) {const lineage = createdBy === COORDINATOR ? board.verifierStanding?.lineage ?? null : seatLineage(board, createdBy);if (lineage) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`agent_lineage:${id}`, lineage);}- logEvent(board, id, 'join', null, route === 'strong' ? { lane } : { lane, route });+ logEvent(board, id, 'join', null, { lane, ...(route === 'strong' ? {} : { route }),+ ...(engine >= AGENT_GRANT_ENGINE ? { grantEngine: AGENT_GRANT_ENGINE } : {}) });return id;});}@@ -1080,7 +1082,8 @@ export function claim(board, id, { agentId, lane, leaseMs, freeze, head = null,board.db.prepare('DELETE FROM board_meta WHERE meta_key = ?').run(`item_lineage:${id}`);if (board.verifierStanding.lineage) board.db.prepare('INSERT INTO board_meta (meta_key, meta_value) VALUES (?, ?)').run(`item_lineage:${id}`, board.verifierStanding.lineage);}- logEvent(board, agentId, renewed ? 'renew' : 'claim', id, { leaseUntil, digest, ...(!renewed && reviewSkipped ? { reviewSkipped } : {}) });+ logEvent(board, agentId, renewed ? 'renew' : 'claim', id, { leaseUntil, digest, ...(!renewed && reviewSkipped ? { reviewSkipped } : {}),+ ...((board.executionEngineVersion ?? ENGINE_VERSION) >= AGENT_GRANT_ENGINE ? { grantEngine: AGENT_GRANT_ENGINE } : {}) });return { leaseUntil, digest, renewed };});}diff --git a/src/cli.js b/src/cli.jsindex 6a572f5a..d430e8ed 100644--- a/src/cli.js+++ b/src/cli.js@@ -1,3 +1,5 @@+import { AGENT_GRANT_ENGINE } from './agent-grant-engine.js';+import { requireAgentGrant } from './agent-grant.js';import { requireHandoffActive } from './handoff-state.js';import { requestedCommandMove } from './recorded-move.js';export { barActorForCommand } from './bar-actor.js';@@ -591,7 +593,11 @@ export async function ordered(ctx, board, operation, args) {const actor = ctx.info.isMain ? COORDINATOR : store.agentAt(board, ctx.info.root)?.agent_id;requireHandoffActive(board, actor, operation, args);ensureSpecApprovalCoordinator(ctx, board, initialBaseline);- const write = () => store.atomic(board, () => { requireHandoffActive(board, actor, operation, args); return store[operation](board, ...args); });+ const write = () => store.atomic(board, () => {+ requireHandoffActive(board, actor, operation, args);+ requireAgentGrant(board, { operation, args, engine: AGENT_GRANT_ENGINE });+ return store[operation](board, ...args);+ });if (initialBaseline && actor) await recordBaseline(actor);const requested = requestedCommandMove(ctx.io.relayCommand?.cliOperation, operation);/** Called only for this requested operation, after its store transaction commits, never for bootstrap. */diff --git a/src/engine.js b/src/engine.jsindex c3ea90f7..267918ce 100644--- a/src/engine.js+++ b/src/engine.js@@ -1,3 +1,5 @@+import { agentGrantMinimum } from './agent-grant.js';+import { requireAgentGrant } from './agent-grant.js';import {handoffMoveProblem,requireHandoffActive,@@ -91,7 +93,7 @@ export function prepareEngineMove(board, operation, args, { id = randomUUID(), aif (operation === 'claim' && ['wipPerReviewer', 'takeoverMinutes'].some(key => typeof lineSettings(board)[key] === 'number')) {values[1] = { ...values[1], lineCapacity: true };}- const minimumEngine = minimumOperationEngine(operation, values, board);+ const minimumEngine = Math.max(minimumOperationEngine(operation, values, board), agentGrantMinimum(board, { operation, args: values }));if (ENGINE_VERSION < minimumEngine) throw new Refused('ENGINE_VERSION', `${operation} requires engine version ${minimumEngine}; this pullboard uses engine ${ENGINE_VERSION}; upgrade before sending it`);// A gate run is sealed only as its gate's own receipt; a run made up by hand is refused before it reaches any replica.if (operation === 'recordGateRun') requireBound(board, values[0]?.receipt);@@ -283,7 +285,7 @@ export function applyEngineMove(board, move, { sequence, at, standing = null, enlet outcome = previous?.outcome;if (!outcome) {// Existing receipts replay before consulting newer snapshot semantics.- const minimumEngine = minimumOperationEngine(move.operation, move.args, board, new Date(at));+ const minimumEngine = Math.max(minimumOperationEngine(move.operation, move.args, board, new Date(at)), agentGrantMinimum(board, move));if (move.engine < minimumEngine) throw new Refused('RELAY_MOVE', `${move.operation} cannot act on a checked-composition snapshot from engine ${move.engine}; use engine ${minimumEngine} or newer`);const clock = board.clock;const engineVersion = board.executionEngineVersion;@@ -300,6 +302,7 @@ export function applyEngineMove(board, move, { sequence, at, standing = null, en// One main checkout coordinates a linked board at a time; another is refused by name (#347).requireCoordinatorHold(board, move, standing?.lineage, at);requireHandoffActive(board, relayMoveActor(move), move.operation, move.args);+ requireAgentGrant(board, move);return store[move.operation](board, ...executableArgs(move, board));});const result = standing ? store.withVerifierStanding(board, standing, execute) : execute();diff --git a/test/team.test.js b/test/team.test.jsindex b0591f5d..a92b9cf4 100644--- a/test/team.test.js+++ b/test/team.test.js@@ -922,3 +922,46 @@ test('an agent grant narrows at claim and expires identically on independent repassert.equal(fact(3, 'An agent cannot mutate another lane', expired, freshActor).error?.code, 'AGENT_GRANT_LANE','a fresh unclaimed seat still has only its registered lane');});++test('an agent grant narrows at claim without changing old receipts or permitting an old-engine bypass [E21,H16]', async t => {+ const { AGENT_GRANT_ENGINE } = await import('../src/agent-grant-engine.js');+ const box = helpers.project();+ const clock = { now: () => new Date('2026-10-01T00:00:00.000Z') };+ const boards = ['legacy-authority.sqlite', 'legacy-peer.sqlite'].map(name => store.openBoard(join(box.dir, name), clock));+ t.after(() => boards.forEach(board => store.closeBoard(board)));+ const legacy = AGENT_GRANT_ENGINE - 1;+ const head = box.git(box.repo, 'rev-parse', 'HEAD');+ /** Apply the same actual public engine record on both private replicas. */+ const apply = (operation, args, engine = legacy) => {+ const move = prepareEngineMove(boards[0], operation, args);+ move.engine = engine;+ const sequence = appliedSequence(boards[0]) + 1;+ const outcomes = boards.map(board => applyEngineMove(board, move, { sequence, at: clock.now().toISOString() }));+ assert.deepEqual(outcomes[0], outcomes[1]);+ assert.equal(outcomes[0].error, undefined, JSON.stringify(outcomes[0]));+ return { move, sequence, outcome: outcomes[0] };+ };+ apply('register', [{ lane: 'coordinator', path: box.repo, model: 'fixture-model' }]);+ const actor = apply('register', [{ lane: 'web', path: box.web, model: 'fixture-model' }]).outcome.result;+ for (const title of ['First', 'Second']) apply('addItem', [{ by: 'coordinator', lane: 'web', title,+ criterion: 'A real file must exist', specIds: [], check: 'test -f grant-proof' }]);+ /** Freeze an actual private Git revision; replicas receive only the canonical frozen value. */+ const freeze = item => ({ text: JSON.stringify({ title: item.item_title, criterion: item.item_criterion,+ check: item.item_check, rows: [], policy: { version: 1, commit: head, verify: { policy: 'any', family: 'off' } } }),+ digest: 'private-grant-fixture' });+ const options = { agentId: actor, lane: 'web', leaseMs: 60_000, freeze };+ apply('claim', [1, options]);+ const prior = apply('appendFact', [2, { agentId: actor, kind: 'note', text: 'Legacy behavior stays recorded.' }]);+ const forged = prepareEngineMove(boards[0], 'appendFact', [2, { agentId: actor, kind: 'note', text: 'Old engine cannot bypass the new claim.' }]);+ forged.engine = legacy;+ apply('claim', [1, options], AGENT_GRANT_ENGINE);+ for (const board of boards) {+ const before = store.itemThread(board, 2);+ assert.deepEqual(applyEngineMove(board, prior.move, { sequence: prior.sequence, at: clock.now().toISOString() }),+ prior.outcome, 'an acknowledged legacy outcome is returned unchanged after activation');+ assert.throws(() => applyEngineMove(board, forged, { sequence: appliedSequence(board) + 1, at: clock.now().toISOString() }),+ error => error.code === 'RELAY_MOVE' && error.message.includes(String(AGENT_GRANT_ENGINE)),+ 'a freshly sealed old-engine move cannot bypass new-claim authority');+ assert.deepEqual(store.itemThread(board, 2), before, 'neither old receipt replay nor a forged old move adds a fact');+ }+});