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(inbox): tailor activity to current work [R2,N26,H16]
Corey Olsonc042635d5e59
diff --git a/docs/api.md b/docs/api.mdindex 3a813921..f558378b 100644--- a/docs/api.md+++ b/docs/api.md@@ -651,3 +651,13 @@ Verification output, current item detail and the ledger qualify affected accepteRun `pullboard handoff` from the outgoing agent worktree. It creates or finds one hand-off item and prints its claims, recent moves, asks and answers, worktree state and existing facts. Record unfinished ownership, principles and taste, open threads, outside files and context only that chat knows with `pullboard fact <id> note "..."`. Pullboard carries board records, not a chat transcript.The incoming agent joins a new worktree and runs `pullboard handoff --take <id>`. It reads the same hand-off and outgoing work card, and records a timed takeover fact. The first incoming seat wins; its repeat is idempotent. Claims are reported rather than silently reassigned. After takeover, the outgoing seat cannot make board moves except `pullboard shout --item <id> "..."` on that exact hand-off. Both seats read and answer that item channel. The command ends with that same sign-off command. The main checkout retains its separate coordinator takeover flow.+++`pullboard inbox --json` retains its `shouts` array for direct coordination and adds optional+`activity: { entries, digests, cursor }`. Entries carry their original event id, timestamp, kind+and item reference where relevant. They select the caller's active builds/reviews and their+upstream/downstream dependencies, files from its plan or actual Git diff, cited row decisions,+and addressed messages. Other lane activity is summarized. Explicit coordinator/person+`shout all <text> --news` announcements appear in a one-line digest at session start;+untyped broadcasts are direct. A missing Git object reports unknown overlap, never zero.+The existing item `show`/`log` paths retain the full evidence behind compact activity entries.diff --git a/docs/formats.md b/docs/formats.mdindex bee4ee4a..6dfc318c 100644--- a/docs/formats.md+++ b/docs/formats.md@@ -447,7 +447,7 @@ The `event` table is a SQLite schema object governed by `SCHEMA_VERSION`; its ap| `guards` | board | `missing`, `changed`, `stale` || `rigor-notice` | rigor | `cause`, `items`, `occurrences`, `neverAgain`, `engine`, automatic-Rigor `drafts` || `rigor-draft` | rigor | `id`, `target`, `cause`, exact typed `source`, `unproved` (always true), `items`, `occurrences`, `engine` |-| `shout` | sender | `shout`, `to`, `decision`, `request`, `answers` |+| `shout` | sender | `shout`, `to`, `decision`, `request`, `answers`, `news`, `newsFormat` || `flake-observation` | reporting agent | `engine`, `observation` || `flake-repair` | reporting agent | `engine`, `key`, `item` || `health-scan` | observing agent | `active`, `engine` |@@ -648,3 +648,21 @@ its number at landing; no event-log or envelope format changes.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`; its native duration is the shared `ACTIVE_REVIEWER_WINDOW_MINUTES` constant (60), not the measurement metadata or a new board setting.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. The shared pure `lineWipLimit` function computes the total cap without rounding, using at least one observed reviewer. 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 a true `lineCapacity` argument and the line-capacity engine floor; marker-absent older recorded claims keep their historical meaning during replay.+++Explicit announcement news adds `news: true, newsFormat: 1` to a shout event without adding a SQLite column.+Only coordinator or person messages to `all` may be news; combining news with an item,+decision, request or answer refuses as `BAD_NEWS`. Its unassigned activity-news engine leaf is+numbered at landing; news takes the maximum applicable feature engine floor. Unversioned old+metadata remains an ordinary message. Older ordinary+shout arguments retain their historical replay conditions. Untyped broadcasts retain their+existing direct delivery, including governing holds and questions.++The inbox's optional JSON v1 `activity` object contains event references, selected entries,+one-line lane/news digests and a continuation cursor. Its private checkout delivery file is+`pullboard-activity.json` in the checkout's Git directory: version 1, board id, agent, current native session+digest, last delivered event id and last session-start news event id. It is local delivery state,+not a native move, parent identity, configuration or authority record. Missing/damaged state+replays activity. Reads freeze an event high-water mark before observing Git; subsequent events+and messages remain pending. News has a separate cursor so an ordinary poll cannot consume a+future session-start digest.diff --git a/docs/formats.test.js b/docs/formats.test.jsindex dcb6a7e0..e0b97039 100644--- a/docs/formats.test.js+++ b/docs/formats.test.js@@ -303,6 +303,7 @@ function recordEventContract() {register(board, { lane: 'small', path: '/small', route: 'light' });ensureCoordinator(board, '/coordinator-moved');shout(board, { from: builder, to: 'all', text: 'sample announcement', lanes: ['docs', 'tests'] });+ shout(board, { from: coordinator, to: 'all', text: 'sample explicit release news', lanes: ['docs', 'tests'], news: true });const passed = shout(board, { from: builder, to: coordinator, text: 'sample decision', lanes: ['docs', 'tests'], decision: true });assert.throws(() => passDecision(board, passed, { agentId: builder, note: 'try to pass it', lanes: ['docs', 'tests'] }),diff --git a/src/activity-feed.js b/src/activity-feed.jsindex 8caeceb2..7c3e812b 100644--- a/src/activity-feed.js+++ b/src/activity-feed.js@@ -1,3 +1,4 @@+import { itemFiles } from './item-files.js';/** Read item activity without duplicating a landing's immutable board-wide receipt [R2,N26]. *//** Include a batch's main-moving receipt only for the exact item ids that receipt records. */@@ -13,3 +14,127 @@ export function itemActivity(board, id) {ORDER BY event_id`).all(id, id);}+++/** Unreadable legacy event detail stays unknown instead of blocking ordinary inbox messages. */+export function activityEventDetail(event) {+ try {+ const detail = JSON.parse(event.event_detail);+ return detail && typeof detail === 'object' && !Array.isArray(detail) ? detail : null;+ } catch { return null; }+}++/** Parse only recorded item dependency ids; a shared prerequisite does not make siblings dependents. */+function prerequisites(item) {+ return String(item.item_after ?? '').split(',').filter(Boolean).map(Number);+}++/** Exact files and explicit directory plans overlap without matching a similarly spelled file. */+function sharedPaths(first, second) {+ return first.filter(path => second.some(other => path === other+ || (other.endsWith('/') && path.startsWith(other)) || (path.endsWith('/') && other.startsWith(path))));+}++/** Resolve each dependency direction independently before adding paths that overlap an active build. */+export function activityInterests(agent, items, { workingFiles = [], at }) {+ const byId = new Map(items.map(item => [item.item_id, item]));+ const builds = items.filter(item => item.item_status === 'claimed' && item.item_owner === agent.agent_id);+ const roots = new Set([...builds, ...items.filter(item => item.item_review_by === agent.agent_id+ && item.item_review_until > at && ['submitted', 'verified'].includes(item.item_status))].map(item => item.item_id));+ /** Traverse one directed relationship while retaining a separate visited set. */+ const closure = next => {+ const found = new Set(roots), pending = [...roots];+ while (pending.length) for (const id of next(pending.pop())) if (byId.has(id) && !found.has(id)) {+ found.add(id); pending.push(id);+ }+ return found;+ };+ const dependents = new Map();+ for (const item of items) for (const before of prerequisites(item)) {+ if (!dependents.has(before)) dependents.set(before, []);+ dependents.get(before).push(item.item_id);+ }+ const upstream = closure(id => prerequisites(byId.get(id)));+ const downstream = closure(id => dependents.get(id) ?? []);+ const related = new Set([...upstream, ...downstream]);+ const rows = new Set(items.filter(item => related.has(item.item_id)).flatMap(item => String(item.item_spec_ids ?? '').split(',').filter(Boolean)));+ const files = builds.length ? [...new Set([...builds.flatMap(itemFiles), ...workingFiles])] : [];+ for (const item of items) if (sharedPaths(itemFiles(item), files).length) related.add(item.item_id);+ return { related, rows, files, lane: agent.agent_lane, byId };+}++/** Turn an observed event into a compact stable reference; full evidence remains on its item. */+function activityEntry(event, text, extra = {}) {+ return { eventId: event.event_id, at: event.event_at, by: event.event_by, kind: event.event_kind,+ ...(event.item_id === null ? {} : { item: event.item_id }), text, ...extra };+}++/** Select one read-only activity stream and compact digests without changing native history or audiences. */+export function projectAgentActivity({ agent, interests, events, shouts, changesForMain,+ sessionStart = false, after = 0, newsAfter = 0, cursor }) {+ const messages = new Map(shouts.map(shout => [shout.shout_id, shout]));+ const entries = [], laneItems = new Set(), announcements = [];+ let laneCount = 0;+ for (const event of events) {+ const detail = activityEventDetail(event);+ if (!detail) {+ if (interests.related.has(event.item_id) || event.item_id === null) {+ entries.push(activityEntry(event, `activity ${event.event_id} has unreadable detail; inspect its item history`, { unknown: true }));+ } else if (interests.byId.get(event.item_id)?.item_lane === interests.lane) { laneCount++; laneItems.add(event.item_id); }+ continue;+ }+ if (event.event_kind === 'shout' && detail.news === true && detail.newsFormat === 1) {+ if (sessionStart && event.event_id > newsAfter && messages.has(detail.shout)) announcements.push(messages.get(detail.shout));+ continue;+ }+ if (event.event_id <= after) continue;+ if (['shout', 'pass', 'answer'].includes(event.event_kind)) {+ const shout = messages.get(detail.shout);+ if (shout) {+ entries.push(activityEntry(event, shout.shout_text, { shout: shout.shout_id }));+ }+ continue;+ }+ if (event.event_kind === 'main-moved') {+ const changed = changesForMain?.(detail.sha, { ...detail, base: event.activityBase });+ if (changed === null || changed === undefined) {+ if (interests.files.length || interests.unknownWorkingFiles) entries.push(activityEntry(event, 'main changed; file overlap is unknown', { unknownFiles: true }));+ } else {+ const files = [...new Set(sharedPaths(Array.isArray(changed) ? changed : changed.files, interests.files))].toSorted();+ if (files.length) entries.push(activityEntry(event, `main changed ${files.length} ${files.length === 1 ? 'file' : 'files'} you are editing${interests.unknownWorkingFiles ? '; additional overlap is unknown' : ''}`,+ { files, ...(interests.unknownWorkingFiles ? { unknownAdditionalFiles: true } : {}) }));+ else if (interests.unknownWorkingFiles) entries.push(activityEntry(event, 'main changed; working-file overlap is unknown', { unknownFiles: true }));+ const rows = (changed.rows ?? []).filter(id => interests.rows.has(id)).toSorted();+ if (rows.length) {+ const existing = entries.find(entry => entry.eventId === event.event_id);+ const text = `main changed cited ${rows.length === 1 ? 'row' : 'rows'} ${rows.join(', ')}`;+ if (existing) { existing.rows = rows; existing.text += `; ${text}`; }+ else entries.push(activityEntry(event, text, { rows }));+ } else if (changed.unknownRows && interests.rows.size) {+ const existing = entries.find(entry => entry.eventId === event.event_id);+ if (existing) { existing.unknownRows = true; existing.text += '; cited-row changes are unknown'; }+ else entries.push(activityEntry(event, 'main changed; cited-row changes are unknown', { unknownRows: true }));+ }+ }+ continue;+ }+ if (['row_decision', 'row_draft', 'row_apply'].includes(event.event_kind)) {+ const rows = (event.event_kind === 'row_apply' ? event.activityRows ?? [] : [detail.record?.id ?? detail.row?.id])+ .filter(id => interests.rows.has(id)).toSorted();+ if (rows.length) entries.push(activityEntry(event, `cited ${rows.length === 1 ? 'row' : 'rows'} ${rows.join(', ')} changed`, { rows }));+ continue;+ }+ if (interests.related.has(event.item_id)) {+ const item = interests.byId.get(event.item_id);+ entries.push(activityEntry(event, `#${event.item_id} ${event.event_kind}: ${item.item_title}`));+ } else if (interests.byId.get(event.item_id)?.item_lane === interests.lane) {+ laneCount++; laneItems.add(event.item_id);+ }+ }+ const digests = [];+ if (laneCount) digests.push({ kind: 'lane', lane: interests.lane, count: laneCount, items: [...laneItems].toSorted((a, b) => a - b),+ text: `${interests.lane}: ${laneCount} other ${laneCount === 1 ? 'activity' : 'activities'} on ${laneItems.size} ${laneItems.size === 1 ? 'item' : 'items'}` });+ if (announcements.length) digests.push({ kind: 'news', shouts: announcements.map(shout => shout.shout_id), count: announcements.length,+ text: `News: ${announcements.map(shout => shout.shout_text.replace(/\s+/gu, ' ').trim()).join(' · ')}` });+ return { entries: entries.toSorted((a, b) => a.eventId - b.eventId), digests, cursor };+}diff --git a/src/activity-inbox.js b/src/activity-inbox.jsnew file mode 100644index 00000000..c50bb17b--- /dev/null+++ b/src/activity-inbox.js@@ -0,0 +1,94 @@+/** Local delivery state and real Git observations for the existing inbox [R2,N26]. */+import { randomUUID } from 'node:crypto';+import { execFileSync } from 'node:child_process';+import {+ readFileSync,+ renameSync,+ rmSync,+ writeFileSync,+} from 'node:fs';+import { gitPath } from './git.js';+import { agentSessionDigest } from './person.js';+import { parseSpec } from './spec.js';++/** Damaged or foreign local cursors replay activity instead of discarding unseen obligations. */+export function readActivityCursor(root, agent, board) {+ const file = gitPath(root, 'pullboard-activity.json');+ const session = agentSessionDigest();+ let saved = {};+ try { saved = JSON.parse(readFileSync(file, 'utf8')); } catch { /* First delivery or damaged local state replays safely. */ }+ const valid = saved?.version === 1 && saved.agent === agent && saved.board === board+ && [saved.after, saved.newsAfter].every(value => Number.isSafeInteger(value) && value >= 0);+ return { file, agent, board, session, after: valid ? saved.after : 0, newsAfter: valid ? saved.newsAfter : 0,+ sessionStart: !valid || saved.session !== session };+}++/** Save only after producing a complete response; failure keeps replay available and never hides it. */+export function saveActivityCursor(state, cursor) {+ const temporary = `${state.file}.${randomUUID()}.tmp`;+ try {+ writeFileSync(temporary, JSON.stringify({ version: 1, agent: state.agent, board: state.board, session: state.session,+ after: cursor, newsAfter: state.sessionStart ? cursor : state.newsAfter }) + '\n', { mode: 0o600, flag: 'wx' });+ renameSync(temporary, state.file);+ return true;+ } catch {+ try { rmSync(temporary); } catch { /* Only this invocation's own temporary file is removed. */ }+ return false;+ }+}++/** Read NUL-delimited paths without trimming or interpreting quoted/newline file names. */+function gitPaths(root, args) {+ return execFileSync('git', ['--no-optional-locks', '--no-replace-objects', '-c', 'core.quotepath=false', ...args],+ { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }).split('\0').filter(Boolean);+}++/** Obtain declared-claim and real current diffs; unavailable ancestry stays explicitly unknown. */+export function activityWorkingFiles(root, builds) {+ if (!builds.length) return [];+ const files = new Set();+ let unknown = false;+ const commands = [['diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', 'HEAD'],+ ['ls-files', '-z', '--others', '--exclude-standard']];+ for (const base of new Set(builds.map(item => item.item_claim_head))) {+ if (!/^[a-f0-9]{40}$/u.test(base ?? '')) { unknown = true; continue; }+ commands.push(['diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', base, 'HEAD']);+ }+ for (const args of commands) {+ try { for (const path of gitPaths(root, args)) files.add(path); } catch { unknown = true; }+ }+ return { files: [...files], unknown };+}++/** Compare exactly the recorded landing base and tip; a missing object is unknown, never zero. */+export function activityMainFiles(root, commit, detail, { rowFiles = [] } = {}) {+ if (![commit, detail.base].every(value => /^[a-f0-9]{40}$/u.test(value ?? ''))) return null;+ let files;+ try { files = gitPaths(root, ['diff', '--no-ext-diff', '--no-textconv', '--name-only', '-z', detail.base, commit]); } catch { return null; }+ const rows = new Set();+ let unknownRows = false;+ for (const file of new Set(rowFiles.filter(file => files.includes(file)))) {+ try {+ const before = committedRows(root, detail.base, file);+ const after = committedRows(root, commit, file);+ for (const id of new Set([...before.keys(), ...after.keys()])) if (before.get(id) !== after.get(id)) rows.add(id);+ } catch { unknownRows = true; }+ }+ return { files, rows: [...rows], unknownRows };+}++/** Compare parsed row content, not line numbers shifted by another row's insertion. */+function committedRows(root, commit, file) {+ const args = ['--no-optional-locks', '--no-replace-objects', 'show', `${commit}:${file}`];+ let source;+ try { source = execFileSync('git', args, { cwd: root, encoding: 'utf8', stdio: ['ignore', 'pipe', 'pipe'] }); }+ catch {+ // A deleted/new configured file has no rows on that side; other read failures remain unknown.+ const listing = gitPaths(root, ['ls-tree', '-z', '--name-only', commit, '--', file]);+ if (listing.length) throw new Error('the committed row file could not be read');+ return new Map();+ }+ const parsed = parseSpec(source);+ if (parsed.problems.length) throw new Error('the committed row file could not be parsed');+ return new Map(parsed.rows.map(({ line, ...row }) => [row.id, JSON.stringify(row)]));+}diff --git a/src/activity-news-engine.js b/src/activity-news-engine.jsnew file mode 100644index 00000000..059870f5--- /dev/null+++ b/src/activity-news-engine.js@@ -0,0 +1,4 @@+import { unassignedEngine } from './engine-next.js';++/** Explicit digest news is numbered only by its landing merge [H16,N26]. */+export const ACTIVITY_NEWS_ENGINE = unassignedEngine();diff --git a/src/activity-news.js b/src/activity-news.jsnew file mode 100644index 00000000..10d54a45--- /dev/null+++ b/src/activity-news.js@@ -0,0 +1,18 @@+import { COORDINATOR } from './config.js';+import { Refused } from './refused.js';+import { ACTIVITY_NEWS_ENGINE } from './activity-news-engine.js';++/** Validate explicitly marked board-wide news without weakening any existing message audience. */+export function activityNewsDetail(message, engine) {+ const { news, from, to, item, decision, request, answers, detail } = message;+ if (engine >= ACTIVITY_NEWS_ENGINE && detail && ['news', 'newsFormat'].some(key => Object.hasOwn(detail, key))) {+ throw new Refused('BAD_NEWS', 'mark news explicitly on the message, not inside internal event detail; send an ordinary message for coordination');+ }+ if (news === undefined || news === false) return {};+ if (news !== true || ![COORDINATOR, 'person'].includes(from) || to !== 'all'+ || item !== undefined || decision || request || (answers !== null && answers !== undefined)) {+ throw new Refused('BAD_NEWS', 'news is a coordinator or person announcement to all, without an item, decision, request or answer; send an ordinary message for coordination');+ }+ if (engine < ACTIVITY_NEWS_ENGINE) throw new Refused('ENGINE_VERSION', `news requires engine ${ACTIVITY_NEWS_ENGINE}; upgrade linked devices before sending it`);+ return { news: true, newsFormat: 1 };+}diff --git a/src/api-moves.js b/src/api-moves.jsindex 6e924741..a727ecee 100644--- a/src/api-moves.js+++ b/src/api-moves.js@@ -23,7 +23,7 @@ const MOVES = {reopen: { item: true, flags: ['note', 'cause'], lists: ['conflict'], booleans: ['withdraw-verdict'] },escalate: { item: true, flags: ['note'] },hold: { positions: ['lane'], flags: ['reason'], booleans: ['off'] },- shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision'], flags: ['evidence', 'outcome', 'item', 'commit'] },+ shout: { positions: ['to', 'text'], optional: ['to'], booleans: ['decision', 'news'], flags: ['evidence', 'outcome', 'item', 'commit'] },answer: { item: true, positions: ['text'], flags: ['as', 'implies', 'supersedes'] },pass: { item: true, positions: ['note'] },next: { flags: ['as'], booleans: ['verify', 'build'] },diff --git a/src/board-query.js b/src/board-query.jsindex 0c9e8055..87110165 100644--- a/src/board-query.js+++ b/src/board-query.js@@ -1,5 +1,10 @@import { itemById } from './board-item-read.js';-import { itemActivity } from './activity-feed.js';+import {+ activityEventDetail,+ activityInterests,+ itemActivity,+ projectAgentActivity,+} from './activity-feed.js';export { itemById };import { outsideSource } from './outside-source.js';import {@@ -427,3 +432,79 @@ export function relatedItems(board, item, limit = 3) {export function agentParent(board, id) {return board.db.prepare('SELECT meta_value FROM board_meta WHERE meta_key = ?').get(`agent_parent_session:${id}`)?.meta_value ?? null;}+++/** Read the adjacent batch receipt, never a per-item scan of all landing history. */+function activityBatchBase(board, event) {+ const detail = activityEventDetail(event);+ if (!detail) return null;+ for (const [operator, order] of [['>', 'ASC'], ['<', 'DESC']]) {+ const batch = board.db.prepare(`SELECT json_extract(CASE WHEN json_valid(event_detail) THEN event_detail ELSE '{}' END,'$.batch.id') AS id,+ json_extract(CASE WHEN json_valid(event_detail) THEN event_detail ELSE '{}' END,'$.batch.base') AS base,+ json_extract(CASE WHEN json_valid(event_detail) THEN event_detail ELSE '{}' END,'$.batch.tip') AS tip+ FROM event WHERE event_kind='landing_batch' AND event_id${operator}? ORDER BY event_id ${order} LIMIT 1`).get(event.event_id);+ if (batch?.id === detail.batch && batch.tip === detail.sha && /^[a-f0-9]{40}$/u.test(batch.base ?? '')) return batch.base;+ }+ return null;+}++/**+ * One canonical activity history boundary for inbox readers; batch item queries rather than+ * re-reading every global landing receipt for each item. Projection never acknowledges messages.+ */+export function agentActivity(board, agentId, { after = 0, newsAfter = 0, workingFiles = [], changesForMain, sessionStart = false } = {}) {+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_id=?').get(agentId);+ if (!agent) throw new Refused('NO_AGENT', `no agent ${agentId}; join your own worktree first`);+ if (![after, newsAfter].every(value => Number.isSafeInteger(value) && value >= 0)) {+ throw new Refused('BAD_ACTIVITY_CURSOR', 'activity cursors are nonnegative event ids; remove the damaged local inbox cursor and read inbox again');+ }+ // Freeze a high-water mark before any Git seam or other query; later events must remain pending.+ const cursor = board.db.prepare('SELECT COALESCE(MAX(event_id),0) AS id FROM event').get().id;+ const items = listItems(board, { all: true });+ const builds = items.filter(item => item.item_status === 'claimed' && item.item_owner === agentId);+ const observed = typeof workingFiles === 'function' ? workingFiles(builds) : workingFiles;+ const observedFiles = Array.isArray(observed) ? observed : observed.files;+ const interests = activityInterests(agent, items, { workingFiles: observedFiles, at: now(board) });+ interests.unknownWorkingFiles = !Array.isArray(observed) && observed.unknown === true;+ const wanted = [...new Set([...interests.related, ...[...interests.byId.values()]+ .filter(item => item.item_lane === agent.agent_lane).map(item => item.item_id)])];+ const rows = new Map();+ for (let offset = 0; offset < wanted.length; offset += 500) {+ const ids = wanted.slice(offset, offset + 500);+ for (const event of board.db.prepare(`SELECT * FROM event WHERE event_id>? AND event_id<=? AND item_id IN (${ids.map(() => '?').join(',')}) ORDER BY event_id`).all(after, cursor, ...ids)) rows.set(event.event_id, event);+ }+ for (const event of board.db.prepare(`SELECT * FROM event WHERE event_id>? AND event_id<=?+ AND event_kind IN ('main-moved','row_decision','row_apply','row_draft','shout','pass','answer') ORDER BY event_id`).all(after, cursor)) rows.set(event.event_id, event);+ if (sessionStart) for (const event of board.db.prepare(`SELECT * FROM event WHERE event_id>? AND event_id<=? AND event_kind='shout'+ AND json_valid(event_detail) AND json_extract(event_detail,'$.news')=1+ AND json_extract(event_detail,'$.newsFormat')=1 ORDER BY event_id`).all(newsAfter, cursor)) rows.set(event.event_id, event);+ const shoutCursor = Math.max(0, ...['shout', 'answer', 'pass'].map(kind => board.db.prepare(+ `SELECT json_extract(event_detail,'$.shout') AS id FROM event WHERE event_kind=? AND event_id<=? ORDER BY event_id DESC LIMIT 1`)+ .get(kind, cursor)?.id ?? 0));+ const messages = board.db.prepare(`SELECT * ${UNREAD_SQL} AND shout_id<=? ORDER BY shout_id`)+ .all(...unreadShoutBindings(agent.agent_last_shout_id, agentId, agent.agent_lane), shoutCursor);+ // News delivery uses its own cursor so ordinary inbox reads cannot consume a future session's digest.+ const newsIds = [...rows.values()].filter(event => event.event_kind === 'shout'+ && activityEventDetail(event)?.news === true && activityEventDetail(event)?.newsFormat === 1)+ .map(event => activityEventDetail(event).shout);+ for (let offset = 0; offset < newsIds.length; offset += 500) {+ const ids = newsIds.slice(offset, offset + 500);+ messages.push(...board.db.prepare(`SELECT * FROM shout WHERE shout_id IN (${ids.map(() => '?').join(',')}) AND shout_to='all'`).all(...ids));+ }+ for (const event of rows.values()) if (event.event_kind === 'main-moved') event.activityBase = activityBatchBase(board, event);+ for (const event of rows.values()) if (event.event_kind === 'row_apply') {+ const ids = activityEventDetail(event)?.events;+ event.activityRows = [];+ if (!Array.isArray(ids)) continue;+ for (let offset = 0; offset < ids.length; offset += 500) {+ const chunk = ids.slice(offset, offset + 500).filter(id => Number.isSafeInteger(id) && id > 0 && id < event.event_id);+ if (chunk.length) for (const row of board.db.prepare(`SELECT * FROM event WHERE event_kind='row_decision'+ AND event_id IN (${chunk.map(() => '?').join(',')})`).all(...chunk)) {+ const id = activityEventDetail(row)?.record?.id;+ if (typeof id === 'string') event.activityRows.push(id);+ }+ }+ }+ return { ...projectAgentActivity({ agent, interests, events: [...rows.values()].toSorted((a, b) => a.event_id - b.event_id),+ shouts: messages, changesForMain, sessionStart, after, newsAfter, cursor }), shoutCursor, newsShouts: newsIds };+}diff --git a/src/board.js b/src/board.jsindex d1d63bf1..0fd1eee7 100644--- a/src/board.js+++ b/src/board.js@@ -1,3 +1,4 @@+import { activityNewsDetail } from './activity-news.js';import {focusOrder,focusReasons,@@ -1649,11 +1650,12 @@ export { getItem } from './board-query.js';* Insert a shout within the caller's transaction.** @param {any} board- * @param {{ from: string, to: string, text: string, lanes: string[], item?: number, decision?: boolean, answers?: number | null, evidence?: any, request?: boolean, channel?: 'terminal' | 'view', detail?: object }} message - detail: extra event fields+ * @param {{ from: string, to: string, text: string, lanes: string[], item?: number, decision?: boolean, answers?: number | null, evidence?: any, request?: boolean, news?: boolean, channel?: 'terminal' | 'view', detail?: object }} message - detail: extra event fields* @returns {number}*/-function insertShout(board, { from, to, text, lanes, item, decision = false, answers = null, evidence = null, request = false, channel = 'terminal', detail = {} }) {+function insertShout(board, { from, to, text, lanes, item, decision = false, answers = null, evidence = null, request = false, news, channel = 'terminal', detail = {} }) {const engine = board.executionEngineVersion ?? ENGINE_VERSION;+ detail = { ...detail, ...activityNewsDetail({ news, from, to, item, decision, request, answers, detail }, engine) };if (item !== undefined) {if (engine < ITEM_SHOUT_ENGINE) throw new Refused('ENGINE_VERSION', 'item messages require engine 93; upgrade every linked device before sending one');to = itemShoutTarget(board.db, item);@@ -1718,7 +1720,7 @@ function persistShout(board, { from, to, text, decision = false, answers = null,* Shout to a lane, an agent, `all`, or the person (B7, B25, B26). The caller passes declared lanes.** @param {any} board- * @param {{ from: string, to: string, text: string, lanes: string[], item?: number, decision?: boolean, answers?: number | null, evidence?: any, request?: boolean, channel?: 'terminal' | 'view' }} message+ * @param {{ from: string, to: string, text: string, lanes: string[], item?: number, decision?: boolean, answers?: number | null, evidence?: any, request?: boolean, news?: boolean, channel?: 'terminal' | 'view' }} message* @returns {number}*/export function shout(board, message) {@@ -1849,28 +1851,7 @@ function checkEvidence(board, { kind, outcome, item, commit }) {export { openDecisions } from './board-query.js';-/**- * Unread shouts for an agent, oldest first, then marked read.- *- * @param {any} board- * @param {string} agentId- * @returns {any[]}- */-export function inbox(board, agentId) {- return atomic(board, () => {- const agent = board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(agentId);- if (!agent) throw new Refused('NO_AGENT', `no agent ${agentId}`);- const shouts = board.db- .prepare(`SELECT * ${UNREAD_SQL} ORDER BY shout_id`)- .all(...unreadShoutBindings(agent.agent_last_shout_id, agentId, agent.agent_lane));- const last = shouts.at(-1)?.shout_id ?? agent.agent_last_shout_id;- board.db.prepare('UPDATE agent SET agent_last_shout_id = ? WHERE agent_id = ?').run(last, agentId);- if (agentId !== COORDINATOR) return shouts;- const requests = openRequests(board);- const ids = new Set(requests.map((shout) => shout.shout_id));- return [...requests, ...shouts.filter((shout) => !ids.has(shout.shout_id))];- });-}+export { inbox } from './inbox-store.js';export { unreadCount } from './board-query.js';@@ -2393,3 +2374,6 @@ export function intakeOutside(board, options) { return applyOutsideIntake(board,/** Record the person's exact-commit owner approval. */export function approveOutside(board, id, options) { return applyOutsideApproval(board, id, options, atomic); }++/** Tailored inbox activity is the same canonical read projection as other board queries. */+export { agentActivity } from './board-query.js';diff --git a/src/cli-main.js b/src/cli-main.jsindex 0bad3f05..2e037394 100644--- a/src/cli-main.js+++ b/src/cli-main.js@@ -123,6 +123,7 @@ const OPTIONS = {since: { type: 'string' },window: { type: 'string' },decision: { type: 'boolean' },+ news: { type: 'boolean' },evidence: { type: 'string' },outcome: { type: 'string' },item: { type: 'string' },diff --git a/src/commands/inbox.js b/src/commands/inbox.jsindex faf9b94f..32bfe1c9 100644--- a/src/commands/inbox.js+++ b/src/commands/inbox.js@@ -1,3 +1,9 @@+import {+ activityMainFiles,+ activityWorkingFiles,+ readActivityCursor,+ saveActivityCursor,+} from '../activity-inbox.js';/** The pullboard inbox command, in its own module so an item adding another command never edits these lines. */import * as store from '../board.js';import {@@ -11,12 +17,20 @@ import {/** Run `pullboard inbox` and return its exit code. */export function run(io) {const ctx = context(io);- const { shouts, agents } = withBoard(ctx, (board) => ({- shouts: store.inbox(board, whoAmI(ctx, board).id),- agents: store.listAgents(board),- }));- io.result?.({ shouts });- if (!shouts.length) io.say('no new shouts');+ const { shouts, agents, activity, delivery } = withBoard(ctx, (board) => {+ const me = whoAmI(ctx, board);+ const delivery = readActivityCursor(ctx.info.root, me.id, store.boardId(board));+ const projected = store.agentActivity(board, me.id, { after: delivery.after, newsAfter: delivery.newsAfter,+ sessionStart: delivery.sessionStart,+ workingFiles: builds => activityWorkingFiles(ctx.info.root, builds),+ changesForMain: (commit, detail) => activityMainFiles(ctx.info.root, commit, detail,+ { rowFiles: [ctx.config.spec, ctx.config.practice] }) });+ const { newsShouts, shoutCursor, ...activity } = projected;+ return { shouts: store.inbox(board, me.id, { through: shoutCursor }).filter(shout => !newsShouts.includes(shout.shout_id)),+ agents: store.listAgents(board), activity, delivery };+ });+ io.result?.({ shouts, activity });+ if (!shouts.length && !activity.entries.length && !activity.digests.length) io.say('no new shouts or activity');for (const shout of shouts) {const ask = shout.shout_decision ? `asks for a decision (#${shout.shout_id}; pullboard answer ${shout.shout_id} "..."): ` : '';const reply = shout.shout_answers ? `answers #${shout.shout_answers}: ` : '';@@ -25,5 +39,9 @@ export function run(io) {io.say(`${shout.shout_at.slice(0, 16)} ${from} -> ${to}: ${ask}${reply}${shout.shout_text}`);if (shout.shout_evidence_kind) io.say(` ${evidenceLine(shout)}`);}+ const delivered = new Set(shouts.map(shout => shout.shout_id));+ for (const entry of activity.entries) if (!delivered.has(entry.shout)) io.say(`${entry.at.slice(0, 16)} ${entry.text}`);+ for (const digest of activity.digests) io.say(digest.text);+ if (!saveActivityCursor(delivery, activity.cursor)) io.say('activity cursor could not be saved; activity may repeat when you read inbox again');return 0;}diff --git a/src/commands/shout.js b/src/commands/shout.jsindex e2b07fab..4df95125 100644--- a/src/commands/shout.js+++ b/src/commands/shout.js@@ -25,7 +25,7 @@ export async function run(io, { first, second, rest, values }) {const hasRecipient = first && recipients.includes(first) && (values.item === undefined || second !== undefined);const to = values.item !== undefined ? `item:${values.item}` : hasRecipient ? first : values.decision ? (me.id === COORDINATOR ? 'person' : COORDINATOR) : first ?? '';const text = [hasRecipient ? second : first, ...(hasRecipient ? rest : [second, ...rest])].filter(Boolean).join(' ');- const id = await ordered(ctx, board, 'shout', [{ from: personShout(io, me) ? store.PERSON : me.id, to, text, ...(values.item !== undefined ? { item: Number(values.item) } : {}), lanes: laneNames(ctx.config), decision: Boolean(values.decision), evidence }]);+ const id = await ordered(ctx, board, 'shout', [{ from: personShout(io, me) ? store.PERSON : me.id, to, text, ...(values.item !== undefined ? { item: Number(values.item) } : {}), lanes: laneNames(ctx.config), decision: Boolean(values.decision), ...(values.news ? { news: true } : {}), evidence }]);io.result?.({ id, decision: Boolean(values.decision) });const agents = store.listAgents(board);const recipient = agents.some((agent) => agent.agent_id === to) ? agentDisplayName(agents, ctx.config, to) : to;diff --git a/src/help.js b/src/help.jsindex 752ee9e6..c020af12 100644--- a/src/help.js+++ b/src/help.js@@ -149,6 +149,8 @@ Workpullboard shout <lane|agent|person|all> <text> pullboard inboxpullboard shout --item <id> <text> message the item builder, reviewer and coordinatorA seat shout to all reaches only coordinator and person; their broadcasts reach everyone.+ pullboard shout all <text> --news coordinator/person release or focus news, digested at session start+ Inbox combines direct coordination with item/dependency, file and cited-row activity; other lane activity is summarized.pullboard shout [<to>] <text> --decision ask for a decision; defaults to your coordinator or the personpullboard shout <to> <text> --evidence attempt|receipt --outcome <word> --item <id> --commit <rev>pullboard answer <shout-id> <text> [--as person] [--implies <ids>] [--supersedes <answer-id>]diff --git a/src/inbox-store.js b/src/inbox-store.jsnew file mode 100644index 00000000..ca3aa064--- /dev/null+++ b/src/inbox-store.js@@ -0,0 +1,35 @@+/** Local inbox acknowledgement keeps delivery metadata out of immutable activity history [R2,N26]. */+import { atomic } from './board.js';+import { openRequests } from './board-read-auxiliary.js';+import { COORDINATOR } from './config.js';+import { Refused } from './refused.js';+import {+ UNREAD_SHOUT_SQL as UNREAD_SQL,+ unreadShoutBindings,+} from './shout-audience.js';++/**+ * Unread shouts for an agent, oldest first, then marked read.+ *+ * @param {any} board+ * @param {string} agentId+ * @returns {any[]}+ */+export function inbox(board, agentId, { through } = {}) {+ if (through !== undefined && (!Number.isSafeInteger(through) || through < 0)) {+ throw new Refused('BAD_ACTIVITY_CURSOR', 'the inbox high-water mark is a nonnegative shout id; read inbox again');+ }+ return atomic(board, () => {+ const agent = board.db.prepare('SELECT * FROM agent WHERE agent_id = ?').get(agentId);+ if (!agent) throw new Refused('NO_AGENT', `no agent ${agentId}`);+ const shouts = board.db+ .prepare(`SELECT * ${UNREAD_SQL}${through === undefined ? '' : ' AND shout_id<=?'} ORDER BY shout_id`)+ .all(...unreadShoutBindings(agent.agent_last_shout_id, agentId, agent.agent_lane), ...(through === undefined ? [] : [through]));+ const last = shouts.at(-1)?.shout_id ?? agent.agent_last_shout_id;+ board.db.prepare('UPDATE agent SET agent_last_shout_id = ? WHERE agent_id = ?').run(last, agentId);+ if (agentId !== COORDINATOR) return shouts;+ const requests = openRequests(board);+ const ids = new Set(requests.map((shout) => shout.shout_id));+ return [...requests, ...shouts.filter((shout) => !ids.has(shout.shout_id))];+ });+}diff --git a/src/moves/shout.js b/src/moves/shout.jsindex 52421427..777df28a 100644--- a/src/moves/shout.js+++ b/src/moves/shout.js@@ -1,3 +1,4 @@+import { ACTIVITY_NEWS_ENGINE } from '../activity-news-engine.js';import { RIGOR_AUTO_ENGINE } from '../rigor-auto-engine.js';/** Routing metadata owned by shout, discovered without a shared registry edit [C7,V4,H16]. */import { ITEM_SHOUT_ENGINE } from '../item-shout-engine.js';@@ -5,7 +6,7 @@ import { LANDING_LEASE_ENGINE } from '../landing-lease-engine.js';import { BOARD_SENTINEL_ENGINE } from '../sentinel-engine.js';/** Preserve this operation's historical first-matching engine conditions [H16]. */-function minimumEngine(args, board, at) {+function historicalMinimumEngine(args, board, at) {if (typeof args[1]?.cause === 'string' && args[1].cause.startsWith('conflict:')) return RIGOR_AUTO_ENGINE;if (args[0]?.item !== undefined) return ITEM_SHOUT_ENGINE;if (args[0]?.landingFence !== undefined) return LANDING_LEASE_ENGINE;@@ -13,6 +14,16 @@ function minimumEngine(args, board, at) {return 1;}+/** News combines every applicable floor; old arguments retain their historical replay condition order. */+function minimumEngine(args, board, at) {+ if (args[0]?.news !== true) return historicalMinimumEngine(args, board, at);+ return Math.max(ACTIVITY_NEWS_ENGINE,+ typeof args[1]?.cause === 'string' && args[1].cause.startsWith('conflict:') ? RIGOR_AUTO_ENGINE : 1,+ args[0]?.item !== undefined ? ITEM_SHOUT_ENGINE : 1,+ args[0]?.landingFence !== undefined ? LANDING_LEASE_ENGINE : 1,+ typeof args[1]?.cause === 'string' && args[1].cause.startsWith('sentinel:') ? BOARD_SENTINEL_ENGINE : 1);+}+/** Read precisely the actor argument used by this operation [H2,H16]. */function actor(move) { return move.args[0]?.from ?? null; }@@ -22,6 +33,7 @@ export default Object.freeze({ operation: "shout", order: 23, engine: 1,"B26_PERSON_CHANNEL": "record it as the person through pullboard view or the person's own terminal","B26_PERSON_DECISION": "ask your coordinator: pullboard shout coordinator \"<question>\" --decision","BAD_EVIDENCE": "pass the evidence fields the message names, then retry",+ "BAD_NEWS": "send news from the coordinator or person to all, without item, decision, request or answer","BAD_REQUEST": "send the request body the message names as an application/json object","COORDINATOR_ONLY": "ask the coordinator to do it: pullboard shout coordinator \"<what you need>\"","EMPTY_SHOUT": "give the shout text: pullboard shout <to> \"<text>\"",diff --git a/test/activity-feed.test.js b/test/activity-feed.test.jsindex 229ebc7e..b971dce5 100644--- a/test/activity-feed.test.js+++ b/test/activity-feed.test.js@@ -2,11 +2,18 @@/** Lifecycle activity retains its evidence without turning routine status into messages [B3,R2,N26,H16]. */import assert from 'node:assert/strict';import { join } from 'node:path';+import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';import { after, test } from 'node:test';import * as store from '../src/board.js';import { createE2eHelpers } from './e2e-helpers.js';import { submitFixture } from './board-submit-fixture.js';import { exportBoard } from '../src/exchange.js';+import { applyEngineMove, prepareEngineMove } from '../src/engine.js';+import { ACTIVITY_NEWS_ENGINE } from '../src/activity-news-engine.js';+import { ITEM_SHOUT_ENGINE } from '../src/item-shout-engine.js';+import { LANDING_LEASE_ENGINE } from '../src/landing-lease-engine.js';+import shoutMove from '../src/moves/shout.js';+import { activityMainFiles, activityWorkingFiles, readActivityCursor, saveActivityCursor } from '../src/activity-inbox.js';const e2e = createE2eHelpers();after(e2e.cleanup);@@ -113,10 +120,14 @@ test('an agent feed shows only activity that touches its items files rows and lastore.appendFact(board, id, { agentId: 'coordinator', kind: 'note', text: id === laneOnly? 'Private lane detail must be summarized, not broadcast verbatim.' : `Private observation for #${id}` });}- for (const id of ['G1', 'G2']) store.recordRowDecisions(board, { agentId: 'person', channel: 'terminal', decisions: [{+ const rowRecords = [];+ for (const id of ['G1', 'G2']) rowRecords.push(...store.recordRowDecisions(board, { agentId: 'person', channel: 'terminal', decisions: [{kind: 'spec', id, file: 'SPEC.md', decision: 'approve', source: `- ${id} [draft] Private row ${id}.`,replacement: `- ${id} [approved] Private row ${id}.`, text: `Private row ${id}.`,- }] });+ }] }));+ store.applyRowDecisions(board, { agentId: 'coordinator', events: rowRecords.map(record => record.event) });+ store.draftSpecRow(board, { agentId: 'web-1', row: { id: 'G1', text: 'Private cited-row draft',+ gate: 'private fixture gate', tier: 'should', section: 'Goals' } });const answer = store.answerDecision(board, question, { agentId: 'api-1', text: 'Use the narrow path.', lanes });store.answerDecision(board, otherQuestion, { agentId: 'api-1', text: 'Unrelated answer must stay private.', lanes });const sha = 'a'.repeat(40);@@ -135,6 +146,8 @@ test('an agent feed shows only activity that touches its items files rows and laconst rowChanges = feed.entries.filter(entry => entry.kind === 'row_decision');assert.equal(rowChanges.length, 1);assert.deepEqual(rowChanges[0].rows, ['G1'], 'only rows cited by my active work reach me');+ assert.deepEqual(feed.entries.find(entry => entry.kind === 'row_apply')?.rows, ['G1'], 'application resolves its original decision ids');+ assert.deepEqual(feed.entries.find(entry => entry.kind === 'row_draft')?.rows, ['G1'], 'a cited draft change reaches the same feed');const answers = feed.entries.filter(entry => entry.kind === 'answer');assert.deepEqual(answers.map(entry => entry.shout), [answer]);assert.equal(answers[0].text, 'Use the narrow path.');@@ -160,4 +173,130 @@ test('an agent feed shows only activity that touches its items files rows and laassert.equal(continued.digests.some(entry => entry.kind === 'news'), false, 'news is read at session start, not on every poll');assert.deepEqual(exportBoard(board), snapshot, 'a feed projection does not modify immutable history or native receipts');assert.throws(() => store.agentActivity(board, 'unknown-fixture-agent', options), error => error.code === 'NO_AGENT');+ for (const invalid of [{ from: 'web-1' }, { to: 'web' }, { decision: true }, { request: true },+ { answers: question }, { item: mine }, { detail: { news: true }, news: undefined }]) {+ assert.throws(() => store.shout(board, { from: 'coordinator', to: 'all', text: 'Invalid private announcement',+ lanes, news: true, ...invalid }), error => error.code === 'BAD_NEWS', 'news never creates a new broadcast or decision authority');+ }+ const executable = prepareEngineMove(board, 'shout', [{ from: 'coordinator', to: 'all', text: 'Private replay news', lanes, news: true }]);+ assert.throws(() => applyEngineMove(board, { ...executable, engine: ACTIVITY_NEWS_ENGINE - 1 },+ { sequence: 1, at: new Date().toISOString() }), error => error.code === 'RELAY_MOVE', 'old engines cannot silently reinterpret explicitly marked news');+ assert.equal(shoutMove.minimumEngine([{ item: mine }]), ITEM_SHOUT_ENGINE, 'ordinary historical arguments keep their old engine floor');+ assert.equal(shoutMove.minimumEngine([{ news: true, item: mine, landingFence: {} }]),+ Math.max(ACTIVITY_NEWS_ENGINE, ITEM_SHOUT_ENGINE, LANDING_LEASE_ENGINE), 'news combines every applicable feature floor');+ assert.deepEqual(exportBoard(board), snapshot, 'refused news and old replay leave all native rows and receipts unchanged');+});+++test('activity cursors leave events arriving during an observation pending [N26]', (t) => {+ const board = store.openBoard(':memory:');+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: '/feed-cursor-fixture' });+ store.register(board, { lane: 'web', path: '/feed-cursor-fixture/web-1' });+ const item = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Private cursor item' });+ store.claim(board, item, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, freeze });+ const before = board.db.prepare('SELECT MAX(event_id) AS id FROM event').get().id;+ const observed = store.agentActivity(board, 'web-1', { after: before, workingFiles: () => {+ store.appendFact(board, item, { agentId: 'coordinator', kind: 'note', text: 'Arrived after the observed high-water mark' });+ store.shout(board, { from: 'coordinator', to: 'all', text: 'A later governing message', lanes: ['web'] });+ return [];+ } });+ assert.equal(observed.cursor, before);+ assert.deepEqual(observed.entries, [], 'later events are not falsely covered by the earlier cursor');+ assert.deepEqual(store.inbox(board, 'web-1', { through: observed.shoutCursor }), [], 'acknowledging this snapshot does not consume the later message');+ const next = store.agentActivity(board, 'web-1', { after: observed.cursor });+ assert.equal(next.entries.some(entry => entry.kind === 'fact' && entry.item === item), true);+ assert.equal(next.entries.some(entry => entry.text === 'A later governing message'), true);+ // Legacy corruption is a private fixture, not a native writer or a repair to its stored bytes.+ board.db.prepare('INSERT INTO event(event_at,event_by,event_kind,item_id,event_detail) VALUES (?,?,?,?,?)')+ .run(new Date().toISOString(), 'coordinator', 'fact', item, '{broken legacy fact');+ store.shout(board, { from: 'coordinator', to: 'all', text: 'Governing messages survive unknown old detail', lanes: ['web'] });+ const intact = exportBoard(board);+ const unknown = store.agentActivity(board, 'web-1', { after: next.cursor });+ assert.equal(unknown.entries.some(entry => entry.item === item && entry.unknown === true), true);+ assert.equal(unknown.entries.some(entry => entry.text === 'Governing messages survive unknown old detail'), true);+ assert.deepEqual(exportBoard(board), intact, 'unknown legacy detail is reported without rewriting it');+ assert.throws(() => store.inbox(board, 'web-1', { through: -1 }), error => error.code === 'BAD_ACTIVITY_CURSOR');+});++test('inbox delivery uses real Git paths and board-bound cursors without consuming later news [R2,N26,H16]', () => {+ const box = e2e.project();+ const base = box.git(box.web, 'rev-parse', 'HEAD');+ const rowFile = 'web/feed-rows.md';+ const first = '## Goals\n- G1 [draft, should] First row.\n- G2 [draft, should] Other row.\n';+ assert.equal(e2e.commitFile(box, box.web, rowFile, first, 'feat(web): private row file [G1]').status, 0);+ const introduced = box.git(box.web, 'rev-parse', 'HEAD');+ assert.deepEqual(activityMainFiles(box.web, introduced, { base }, { rowFiles: [rowFile] }).rows.toSorted(), ['G1', 'G2']);+ assert.equal(e2e.commitFile(box, box.web, rowFile, first.replace('First row.', 'Changed row.'), 'feat(web): change one private row [G1]').status, 0);+ const changed = box.git(box.web, 'rev-parse', 'HEAD');+ assert.deepEqual(activityMainFiles(box.web, changed, { base: introduced }, { rowFiles: [rowFile] }).rows, ['G1']);+ assert.equal(activityMainFiles(box.web, changed, { base: 'f'.repeat(40) }), null, 'missing Git ancestry stays unknown');+ writeFileSync(join(box.web, 'web', 'untracked\nname.js'), 'private current diff\n');+ const observed = activityWorkingFiles(box.web, [{ item_claim_head: base }]);+ assert.equal(observed.unknown, false);+ assert.ok(observed.files.includes(rowFile));+ assert.ok(observed.files.includes('web/untracked\nname.js'), 'real NUL-delimited Git output preserves newline names');+ assert.equal(activityWorkingFiles(box.web, [{ item_claim_head: 'missing' }]).unknown, true);++ const board = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));+ const id = store.addItem(board, { by: 'coordinator', lane: 'web', title: 'Private CLI feed item',+ specIds: ['G1'], brief: 'Files: web/feed-rows.md\nTest: private fixture\n' });+ store.claim(board, id, { agentId: 'web-1', lane: 'web', leaseMs: 3_600_000, head: base, freeze });+ store.appendFact(board, id, { agentId: 'web-1', kind: 'note', text: 'Private meaningful activity' });+ // Synthetic native batch receipts exercise the read path, not a claim that a landing gate ran.+ store.recordLandingBatch(board, { agentId: 'coordinator', batch: { version: 1, id: 'private-feed-git',+ state: 'pushed', base, tip: changed, root: box.web, branch: 'refs/heads/main', owner: 'private-fixture',+ logPath: join(box.dir, 'private-feed-git.log'), items: [] } });+ store.finishLandingBatch(board, { agentId: 'coordinator', id: 'private-feed-git', tip: changed });+ const lanes = ['web', 'api'];+ store.shout(board, { from: 'coordinator', to: 'all', text: 'A governing instruction stays direct.', lanes });+ const firstNews = store.shout(board, { from: 'coordinator', to: 'all', text: 'First private release.', lanes, news: true });+ const boardId = store.boardId(board);+ store.closeBoard(board);+ const one = box.run(box.web, 'inbox', '--json');+ assert.equal(one.code, 0, one.err);+ const feed = JSON.parse(one.out);+ assert.ok(feed.shouts.some(shout => shout.shout_text === 'A governing instruction stays direct.'));+ assert.equal(feed.shouts.some(shout => shout.shout_id === firstNews), false);+ assert.ok(feed.activity.entries.some(entry => entry.kind === 'fact' && entry.item === id));+ assert.deepEqual(feed.activity.entries.find(entry => entry.kind === 'main-moved')?.files, [rowFile],+ 'the real CLI compares the exact recorded Git base and tip against the active file plan');+ assert.deepEqual(feed.activity.digests.find(digest => digest.kind === 'news')?.shouts, [firstNews]);+ const continued = box.run(box.web, 'inbox', '--json');+ assert.equal(continued.code, 0, continued.err);+ assert.deepEqual(JSON.parse(continued.out).activity.entries, []);+ assert.deepEqual(JSON.parse(continued.out).activity.digests, []);+ const again = store.openBoard(join(box.repo, '.git', 'pullboard', 'board.sqlite'));+ const secondNews = store.shout(again, { from: 'coordinator', to: 'all', text: 'Next private release.', lanes, news: true });+ store.closeBoard(again);+ const sameSession = box.run(box.web, 'inbox', '--json');+ assert.equal(sameSession.code, 0, sameSession.err);+ assert.deepEqual(JSON.parse(sameSession.out).activity.digests, [], 'later news waits for the next session');+ const delivery = readActivityCursor(box.web, 'web-1', boardId);+ const saved = JSON.parse(readFileSync(delivery.file, 'utf8'));+ // Explicit synthetic local delivery state models a restart; no native board identity is changed.+ writeFileSync(delivery.file, JSON.stringify({ ...saved, session: 'older-private-fixture-session' }));+ const restarted = box.run(box.web, 'inbox', '--json');+ assert.equal(restarted.code, 0, restarted.err);+ assert.deepEqual(JSON.parse(restarted.out).activity.digests.find(digest => digest.kind === 'news')?.shouts, [secondNews]);+ assert.equal(readActivityCursor(box.web, 'web-1', 'different-private-board').after, 0, 'another board cannot borrow a cursor');+ writeFileSync(delivery.file, '{damaged cursor');+ assert.equal(readActivityCursor(box.web, 'web-1', boardId).after, 0, 'damaged local state replays instead of dropping history');+ rmSync(delivery.file);+ mkdirSync(delivery.file);+ assert.equal(saveActivityCursor(delivery, 1), false, 'a refused cursor save reports failure without hiding it');+ rmSync(delivery.file, { recursive: true });+});++test('old ordinary shout replay does not become newly typed news [H16,N26]', (t) => {+ const board = store.openBoard(':memory:');+ t.after(() => store.closeBoard(board));+ store.register(board, { lane: 'coordinator', path: '/private-legacy-feed' });+ store.register(board, { lane: 'web', path: '/private-legacy-feed/web-1' });+ const move = prepareEngineMove(board, 'shout', [{ from: 'coordinator', to: 'all', lanes: ['web'],+ text: 'Historical metadata is not a new delivery instruction.', detail: { news: true } }]);+ applyEngineMove(board, { ...move, engine: 1 }, { sequence: 1, at: new Date().toISOString() });+ const feed = store.agentActivity(board, 'web-1', { sessionStart: true });+ assert.ok(feed.entries.some(entry => entry.text === 'Historical metadata is not a new delivery instruction.'));+ assert.deepEqual(feed.digests, [], 'only the new versioned explicit representation is digested');});