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
fix(api): refresh reader state at clock transitions [H5,H16,A2]
Corey Olsoncf5260b36221
diff --git a/src/api.js b/src/api.jsindex 526ff0f6..1079274d 100644--- a/src/api.js+++ b/src/api.js@@ -2,6 +2,7 @@ import { buildLocalBoardState } from './native-board-state.js';import { dependencyIds } from './native-board-state.js';import { stateFileInputs } from './native-board-state.js';import { fileRevision } from './native-board-state.js';+import { nativeStateClockMatches } from './native-state-clock.js';/** The local API v1: the CLI's moves, persistent board identities and live events (A2). */import {createHash,@@ -421,13 +422,13 @@ function searchText(item) {}/** One cached board build: the full state, its item summaries, its delta fingerprint and the lookups that serve them. */-function snapshotEntry(revision, state, preparedFlow, { inputs = null, itemMeta = new Map(), itemMoveCounts = new Map() } = {}) {+function snapshotEntry(revision, state, preparedFlow, { inputs = null, itemMeta = new Map(), itemMoveCounts = new Map(), clockWindow = null } = {}) {const summary = { ...state, items: state.items.map(itemSummary) };const reportValidator = { json: JSON.stringify(state.proofStats?.flow?.report), expiries: [...new Set(preparedFlow.items.flatMap(item =>item.state === 'claimed' ? [item.leaseUntil] : item.state === 'submitted' ? [item.reserve?.until] : []).filter(Number.isFinite))].sort((a, b) => a - b) };reportValidator.digest = createHash('sha256').update(reportValidator.json ?? 'null').digest('hex');return { revision, sequence: state.sequence, state, summary, preparedFlow, reportValidator, summaryFields: prepareStateJson(summary), stateJsonFields: null,- print: fingerprint(summary), items: new Map(state.items.map((item) => [item.id, item])), itemMeta, itemMoveCounts, inputs, searchTexts: null };+ print: fingerprint(summary), items: new Map(state.items.map((item) => [item.id, item])), itemMeta, itemMoveCounts, inputs, clockWindow, searchTexts: null };}/** State fields every delta carries whole: this request's unread count and flow, and the small Needs-you lists. */@@ -856,10 +857,11 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =function withSnapshot(board, read, observedAt = now()) {const before = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });const cached = stateCache.get(before.cacheId);- if (before.cacheable && cached?.revision === before.revision) {+ if (before.cacheable && cached?.revision === before.revision && nativeStateClockMatches(cached.clockWindow, observedAt)) {const result = read(cached, true);const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });if (after.cacheable && after.revision === before.revision) {+ cached.clockWindow.observedAt = observedAt; // A backwards request must rebuild even within the prior constant window.stateCache.delete(before.cacheId);stateCache.set(before.cacheId, cached);return result;@@ -885,6 +887,7 @@ export function createLocalApiHandler({ secret, getPort, runCommand, projects =inputs: before.inputs,itemMeta: built.itemMeta,itemMoveCounts: built.itemMoveCounts,+ clockWindow: built.clockWindow,});entry.cacheId = before.cacheId;const after = boardStateRevision(board.root, board.id, codeIsMain, { projects: apiProjects, scopeCommonDir, observedAt });diff --git a/src/native-board-state.js b/src/native-board-state.jsindex bc30e7d9..d5456509 100644--- a/src/native-board-state.js+++ b/src/native-board-state.js@@ -12,6 +12,7 @@ import { COORDINATOR } from './config.js';import { loadConfig } from './config.js';import { repoInfo } from './git.js';import { listApiProjects } from './projects.js';+import { nativeStateClockWindow } from './native-state-clock.js';import { milestoneRoadmap } from './roadmap.js';import { proofStats } from './stats.js';import { ruleProofCounts } from './rule-proof-counts.js';@@ -116,8 +117,9 @@ export function buildLocalBoardState(root, boardId, board, codeIsMain, { previoumilestone: milestoneNames.get(item.item_id) ?? null,}]));const history = store.events(board);+ const clockWindow = nativeStateClockWindow(listFields.state, history, currentItems, observedAt);board.db.exec('COMMIT');- return { state: listFields.state, itemMeta, itemMoveCounts: listFields.itemMoveCounts, sequence, history };+ return { state: listFields.state, itemMeta, itemMoveCounts: listFields.itemMoveCounts, sequence, history, clockWindow };} catch (error) {try { board.db.exec('ROLLBACK'); } catch { /* Preserve the projection failure. */ }throw error;diff --git a/src/native-state-clock.js b/src/native-state-clock.jsnew file mode 100644index 00000000..e6909386--- /dev/null+++ b/src/native-state-clock.js@@ -0,0 +1,30 @@+/** Piecewise clock windows of complete native state, separate from continuously refreshed flow [H5,H16,A2]. */+import { qualifyingLandingTimes } from './roadmap.js';++const HOUR = 3_600_000;++/** Derive the next real projected block or pace transition from the already captured business snapshot. */+export function nativeStateClockWindow(state, history, items, observedAt) {+ let nextChange = null;+ /** Retain one earliest transition without allocating or spreading a board-sized timestamp array. */+ function consider(at) {+ if (Number.isFinite(at) && at > observedAt && (nextChange === null || at < nextChange)) nextChange = at;+ }+ for (const block of state.blocks ?? []) {+ // readBlocks includes an entry at exactly its twenty-four-hour boundary.+ consider(Date.parse(block.at) + 24 * HOUR + 1);+ }+ if (state.milestones?.length) {+ const current = new Map(items.map(item => [item.item_id, item]));+ for (const at of qualifyingLandingTimes(history, current)) {+ // A future-dated observation enters at its timestamp; strict pace windows expire on the boundary.+ for (const offset of [0, 2 * HOUR, 6 * HOUR, 24 * HOUR]) consider(at + offset);+ }+ }+ return { observedAt, nextChange };+}++/** A cached piecewise state remains valid only forward within its measured clock interval. */+export function nativeStateClockMatches(window, observedAt) {+ return Boolean(window && observedAt >= window.observedAt && (window.nextChange === null || observedAt < window.nextChange));+}diff --git a/src/roadmap.js b/src/roadmap.jsindex 179e373c..a5f58613 100644--- a/src/roadmap.js+++ b/src/roadmap.js@@ -123,16 +123,22 @@ export function milestoneRoadmap(root, board, options = {}) {});}-/** Count distinct currently landed local items at their first recording of the current merge. */-function landingPace(board, items, now) {+/** Exact first matching merge observations shared by roadmap display and its cache-window boundary. */+export function qualifyingLandingTimes(history, items) {const first = new Map();- for (const event of eventsOfKinds(board, ['merged'])) {+ for (const event of history) {+ if (event.event_kind !== 'merged') continue;const item = items.get(event.item_id);if (item?.item_status !== 'verified' || !item.item_merged_commit || first.has(event.item_id)) continue;if (JSON.parse(event.event_detail).commit !== item.item_merged_commit) continue;first.set(event.item_id, Date.parse(event.event_at));}- const times = [...first.values()].filter(at => at <= now);+ return [...first.values()].filter(Number.isFinite);+}++/** Count distinct currently landed local items at their first recording of the current merge. */+function landingPace(board, items, now) {+ const times = qualifyingLandingTimes(eventsOfKinds(board, ['merged']), items).filter(at => at <= now);return { last6h: times.filter(at => at > now - 6 * 3_600_000).length,last2h: times.filter(at => at > now - 2 * 3_600_000).length,last24h: times.filter(at => at > now - 24 * 3_600_000).length };diff --git a/test/relay-parity-clock.test.js b/test/relay-parity-clock.test.jsindex e8007d78..51ffc758 100644--- a/test/relay-parity-clock.test.js+++ b/test/relay-parity-clock.test.js@@ -25,9 +25,10 @@ async function clockFixture(t) {const board = store.openBoard(join(box.root, '.git', 'pullboard', 'board.sqlite'), { now: () => new Date(base) });t.after(() => store.closeBoard(board));const id = store.boardId(board);+ let builds = 0;const secret = randomBytes(24).toString('base64url');const api = await serveApi({ secret, runCommand: main, projects: () => [{ root: box.root, name: 'clock-parity' }],- scope: { projectRoot: box.root }, isMain: true, stateDetail: 'full', now: () => clock.value });+ scope: { projectRoot: box.root }, isMain: true, stateDetail: 'full', now: () => clock.value, onStateBuild: () => { builds++; } });t.after(api.close);/** Compare the complete authenticated native response with the uncached production reader at exactly its clock.* This additional cache witness makes no API2/decryption claim; that transport has its separate real oracle.@@ -42,7 +43,7 @@ async function clockFixture(t) {assert.equal(relay.observedAt, native.observedAt);return { native, relay };}- return { ...box, board, base, clock, read };+ return { ...box, board, base, clock, read, builds: () => builds };}test('native and relay readers expire a person block at the same observedAt without a write [H5,H16,A2]', { timeout: 60_000 }, async t => { // budget: real fixture startup, HTTP and cleanup; clock advancement never sleeps.@@ -95,3 +96,36 @@ test('native and relay readers cross a landing pace window at the same observedAassert.equal(after.relay.milestones.find(row => row.name === 'Clock pace').summary.pace.last2h, 0);assertReaderParity(after.native, after.relay);});+++test('clock windows retain cached reads and refresh exact boundaries and backwards time [H5,H16,A2]', { timeout: 60_000 }, async t => { // budget: real fixture startup and bounded HTTP reads; all clock shifts are immediate.+ const box = await clockFixture(t);+ seedLandingPace(box);+ recordBlock(join(box.root, '.git'), { at: new Date(box.base).toISOString(), code: 'PARITY_BOUNDARY_FIXTURE', command: 'synthetic boundary input',+ by: 'coordinator', path: box.root, audience: 'person', reason: 'Exact inclusive block boundary.', step: 'Inspect the unchanged board.' });+ const inputs = exportBoard(box.board);+ /** Every additional boundary still compares the entire public state at one explicit clock. */+ async function observe(offset, expectedBuilds) {+ box.clock.value = box.base + offset;+ const states = await box.read();+ assertReaderParity(states.native, states.relay);+ assert.equal(box.builds(), expectedBuilds, 'stable clock intervals retain the existing complete-state cache');+ return states.native;+ }+ await observe(2 * HOUR - 2, 1);+ await observe(2 * HOUR - 1, 1);+ const twoHours = await observe(2 * HOUR, 2);+ assert.equal(twoHours.milestones.find(row => row.name === 'Clock pace').summary.pace.last2h, 0, 'pace excludes its exact lower boundary');+ await observe(3 * HOUR, 2);+ await observe(2.5 * HOUR, 3); // A backwards clock rebuilds even without crossing a pace boundary.+ const sixHours = await observe(6 * HOUR, 4);+ assert.equal(sixHours.milestones.find(row => row.name === 'Clock pace').summary.pace.last6h, 0);+ const backwards = await observe(2 * HOUR - 1, 5);+ assert.equal(backwards.milestones.find(row => row.name === 'Clock pace').summary.pace.last2h, 3, 'a backwards clock restores the proper earlier window');+ const day = await observe(24 * HOUR, 6);+ assert.equal(day.blocks.length, 1, 'the block remains visible at its exact inclusive boundary');+ assert.equal(day.milestones.find(row => row.name === 'Clock pace').summary.pace.last24h, 0);+ const expired = await observe(24 * HOUR + 1, 7);+ assert.equal(expired.blocks.length, 0, 'the block expires on the next millisecond');+ assert.deepEqual(exportBoard(box.board), inputs, 'all clock-only reads preserve native business inputs');+});