Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
import { describe, expect, it } from 'bun:test';
import { Database } from 'bun:sqlite';
import { createHash } from 'node:crypto';
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { AGENT_WRITTEN_PROMPTS_FILE, appendReading, applyGroupDecisions, groupIdFor, hasPlaceholderTitle, ledgerSignature, linkBackwards, MAX_READINGS, placeholderTitleFromAsk, readCandidates, readGoals, readLedger, refreshNeeds, runCli, shownGroupIds, storyChaptersToMerge, storyParts, textTarget, trimStoryPreferences, validateProgress, validateStory, validateSubFocusAnswer, validateTitleAnswer } from '../../src/services/work-view/request-groups.mjs';
import { readFocus, readFocusAreas } from '../../src/services/work-view/data-source.mjs';
import { focusAreaRowFields, placementRowFields, routerFocusRows, subFocusPlacementRowFields, type RouterFocusBody } from '../../src/services/work-view/my-focus.mjs';
import { buildHumanRequests } from '../../src/services/work-view/request-projection.mjs';
import { MY_RULES_LIST, restoredSuggestionRowFields, ruleRowFields, type SavedRule } from '../../src/services/work-view/my-rules.mjs';
import { applySharedProjection } from '../../src/services/work-view/shared-projection.mjs';
import { scratchDir } from '../helpers/scratch-dir.js';
const ledgerDir = () => scratchDir('request-groups-test');
const key = (session: string) => JSON.stringify(['conversation', 'claude', session]);
const DAY = 86400000, NOW = 100 * DAY;
function fixtureDatabase() {
const db = new Database(':memory:');
db.exec(`CREATE TABLE sdk_sessions (id INTEGER PRIMARY KEY, platform_source TEXT, content_session_id TEXT, memory_session_id TEXT, project TEXT, user_prompt TEXT, started_at_epoch INTEGER);
CREATE TABLE user_prompts (id INTEGER PRIMARY KEY, session_db_id INTEGER, prompt_number INTEGER, prompt_text TEXT, created_at_epoch INTEGER);
CREATE TABLE tool_uses (id INTEGER PRIMARY KEY, session_db_id INTEGER, tool_name TEXT, tool_input TEXT, created_at_epoch INTEGER);
CREATE TABLE observations (id INTEGER PRIMARY KEY, memory_session_id TEXT, type TEXT, title TEXT, subtitle TEXT, created_at_epoch INTEGER);
CREATE TABLE work_state_entries (id INTEGER PRIMARY KEY, project TEXT, list_name TEXT, fields TEXT, created_at_epoch INTEGER);`);
const session = db.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)');
const prompt = db.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)');
const write = db.prepare('INSERT INTO tool_uses (session_db_id, tool_name, tool_input, created_at_epoch) VALUES (?, ?, ?, ?)');
// Two conversations (one after /clear) record into the same work list; a third is unrelated.
session.run(1, 'claude', 'a', 'm1', 'repo/tree', 'Build the release cards', NOW - 3 * DAY);
session.run(2, 'claude', 'b', 'm2', 'repo/tree', 'Fix the card spacing', NOW - 2 * DAY);
session.run(3, 'claude', 'c', 'm3', 'repo/other', 'Write the pricing page', NOW - DAY);
prompt.run(1, 1, 'Build the release cards', NOW - 3 * DAY);
prompt.run(2, 1, 'Fix the card spacing', NOW - 2 * DAY);
prompt.run(3, 1, 'Write the pricing page', NOW - DAY);
write.run(1, 'mcp__work_state_write', JSON.stringify({ list: 'release-cards', fields: { task: 'cards' } }), NOW - 3 * DAY);
write.run(2, 'mcp__work_state_write', JSON.stringify({ list: 'release-cards', fields: { task: 'spacing' } }), NOW - 2 * DAY);
db.prepare('INSERT INTO observations (memory_session_id, created_at_epoch) VALUES (?, ?)').run('m2', NOW - DAY);
return db;
}
describe('overall requests and progress reviews', () => {
it('work backwards: a shared work list links conversations into one overall request', () => {
const candidates = readCandidates(fixtureDatabase(), { sinceEpoch: NOW - 14 * DAY });
expect(candidates.map((candidate) => candidate.conversationKey)).toEqual([key('a'), key('b'), key('c')]);
expect(candidates[1].lastActivityEpoch).toBe(NOW - DAY);
const { proposedGroups } = linkBackwards(candidates);
const linked = proposedGroups.find((group) => group.conversations.length === 2);
expect(linked.conversations).toEqual([key('a'), key('b')]);
expect(linked.links[0].evidence).toBe('work list "release-cards" in repo/tree');
expect(proposedGroups.length).toBe(2);
});
it('group decisions need evidence and keep a stable anchor id', () => {
expect(() => applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a'), key('b')] }] })).toThrow(/without a recorded link/);
expect(() => applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a'), key('b')], links: [{ kind: 'agent-judgment', evidence: '' }] }] })).toThrow(/without evidence/);
const first = applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a')] }, { title: 'Spacing', conversations: [key('b')] }] }, NOW);
const merged = applyGroupDecisions(first, { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'agent-judgment', conversations: [key('a'), key('b')], evidence: '"this is excellent work, can you now…" continues the card work' }] }] }, NOW);
expect(merged.conversations[key('b')]).toBe(groupIdFor(key('a')));
expect(Object.keys(merged.groups)).toEqual([groupIdFor(key('a'))]);
const ignored = applyGroupDecisions(merged, { groups: [], ignored: [{ conversation: key('c'), reason: 'Automated workspace naming prompt' }] }, NOW);
expect(ignored.ignored[key('c')]).toBe('Automated workspace naming prompt');
const corrected = applyGroupDecisions(ignored, { groups: [{ title: 'Pricing page', conversations: [key('c')] }] }, NOW);
expect(corrected.conversations[key('c')]).toBe(groupIdFor(key('c')));
expect(corrected.ignored[key('c')]).toBeUndefined();
});
it('a commit or push after a review counts as new activity, with no new prompt or observation', () => {
const db = fixtureDatabase();
db.prepare('INSERT INTO tool_uses (session_db_id, tool_name, tool_input, created_at_epoch) VALUES (?, ?, ?, ?)').run(3, 'Bash', JSON.stringify({ command: 'git push' }), NOW - 1000);
const byKey = new Map(readCandidates(db, { sinceEpoch: NOW - 14 * DAY }).map((candidate) => [candidate.conversationKey, candidate]));
expect(byKey.get(key('c')).lastActivityEpoch).toBe(NOW - 1000);
// Inside a window that only the push falls in, the conversation is still found.
const recent = readCandidates(db, { sinceEpoch: NOW - 2000 });
expect(recent.map((candidate) => candidate.conversationKey)).toEqual([key('c')]);
});
it('progress reviews are validated: shipped needs a date and 100%', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'shipped', percent: 100, startedAt: '2026-10-01T00:00:00Z', shippedAt: '2026-10-03T00:00:00Z', summary: 'Cards merged and released.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
expect(validateProgress(base, groups).state).toBe('shipped');
expect(() => validateProgress({ ...base, percent: 90 }, groups)).toThrow(/percent 100/);
expect(() => validateProgress({ ...base, state: 'in-progress', percent: 50 }, groups)).toThrow(/Only a shipped/);
expect(() => validateProgress({ ...base, groupId: 'g_ffffffffffff' }, groups)).toThrow(/Unknown group/);
expect(() => validateProgress({ ...base, preferences: [{ kind: 'vibe', preference: 'x', quote: 'y' }] }, groups)).toThrow(/kind/);
expect(() => validateProgress({ ...base, reviewBasis: undefined }, groups)).toThrow(/reviewBasis/);
});
it('a review records the owner\'s move while the next action is theirs, and never on a finished request', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'in-progress', percent: 90, summary: 'The card PR is open and waits on a merge.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const ownerMove = { what: 'Merge PR #4845 once the card spacing looks right to you.', since: '2026-10-03T00:00:00Z' };
expect(validateProgress({ ...base, ownerMove }, groups).ownerMove).toEqual(ownerMove);
expect(validateProgress({ ...base, state: 'stalled', ownerMove: { what: 'Reply to the agent\'s question about the layout.' } }, groups).ownerMove)
.toEqual({ what: 'Reply to the agent\'s question about the layout.', since: null });
// Absent when the next action is not the owner's.
expect(Object.hasOwn(validateProgress(base, groups), 'ownerMove')).toBe(false);
expect(Object.hasOwn(validateProgress({ ...base, ownerMove: null }, groups), 'ownerMove')).toBe(false);
// The milestones' 200-character cap, with the same target in the refusal.
expect(validateProgress({ ...base, ownerMove: { what: 'x'.repeat(200), since: null } }, groups).ownerMove.what).toHaveLength(200);
expect(() => validateProgress({ ...base, ownerMove: { what: 'x'.repeat(201), since: null } }, groups))
.toThrow('ownerMove.what is 201 characters; it must be 1–200. Bring it to about 150 characters (cut at least 51).');
expect(() => validateProgress({ ...base, ownerMove: { what: ' ', since: null } }, groups)).toThrow(/ownerMove\.what/);
expect(() => validateProgress({ ...base, ownerMove: { what: 'Reply.', since: 'last week' } }, groups)).toThrow('ownerMove.since must be an ISO date or null.');
expect(() => validateProgress({ ...base, ownerMove: 'Reply.' }, groups)).toThrow('ownerMove must be an object with what and since, or left out.');
const shipped = { ...base, state: 'shipped', percent: 100, shippedAt: '2026-10-03T00:00:00Z' };
expect(() => validateProgress({ ...shipped, ownerMove }, groups)).toThrow('A request reviewed as shipped waits on no one; leave ownerMove out.');
expect(() => validateProgress({ ...base, state: 'abandoned', ownerMove }, groups)).toThrow('A request reviewed as abandoned waits on no one; leave ownerMove out.');
// On the retry, an over-long sentence is cut like any other review text and named in coercedFields.
const coercedFields = new Set<string>();
const coerced = validateProgress({ ...base, ownerMove: { what: 'Merge it. '.repeat(30), since: null } }, groups, { coerce: true, coercedFields }) as any;
expect(coerced.ownerMove.what.length).toBeLessThanOrEqual(200);
expect([...coercedFields]).toEqual(['ownerMove.what']);
});
it('record-progress saves the owner\'s move, and a later review without one clears it', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const decisions = join(dir, 'decisions.json');
writeFileSync(decisions, JSON.stringify({ groups: [{ title: 'Pricing page', conversations: [key('c')] }] }));
run(['apply', decisions]);
const groupId = groupIdFor(key('c'));
const review = join(dir, 'review.json');
const ownerMove = { what: 'Confirm the pricing page copy reads right before it goes live.', since: new Date(NOW - DAY).toISOString() };
writeFileSync(review, JSON.stringify({ groupId, state: 'in-progress', percent: 90, summary: 'The pricing page is written and waits on your read.', ownerMove, reviewBasis: run(['show', groupId]).reviewBasis }));
run(['record-progress', review]);
expect(JSON.parse(readFileSync(join(dir, 'progress', `${groupId}.json`), 'utf8')).ownerMove).toEqual(ownerMove);
expect(readLedger(dir).progress[groupId].ownerMove).toEqual(ownerMove);
// The next review is open work again, now without a move for the owner: it replaces the saved one.
writeFileSync(review, JSON.stringify({ groupId, state: 'in-progress', percent: 95, summary: 'The copy was confirmed; the page is being published.', reviewBasis: run(['show', groupId], NOW + 1000).reviewBasis }));
expect(run(['record-progress', review], NOW + 1000).state).toBe('in-progress');
expect(Object.hasOwn(readLedger(dir).progress[groupId], 'ownerMove')).toBe(false);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a review over a cap is refused with a target well under it, so the retry does not miss again (Oct 31)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'in-progress', percent: 50, summary: 'Under way.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
expect(() => validateProgress({ ...base, summary: 'x'.repeat(292) }, groups))
.toThrow('summary is 292 characters; it must be 1–280. Bring it to about 210 characters (cut at least 82).');
expect(() => validateProgress({ ...base, narrative: 'x'.repeat(1347) }, groups)).toThrow(/about 900 characters \(cut at least 447\)/);
const milestones = Array.from({ length: 13 }, (_, index) => ({ at: null, text: `Step ${index}` }));
expect(() => validateProgress({ ...base, milestones }, groups))
.toThrow('milestones has 13 items; it must have at most 12. Keep the 12 that matter most.');
expect(() => validateProgress({ ...base, milestones: 'none' }, groups)).toThrow('milestones must be an array of at most 12.');
// A verbatim quote is shortened by quoting less, so its refusal never asks for a rewrite.
const preferences = [{ kind: 'directive', preference: 'Short replies.', quote: 'x'.repeat(301), at: null }];
expect(() => validateProgress({ ...base, preferences }, groups)).toThrow('Quote a shorter part of it word for word, about 220 characters; never reword a quote.');
});
it('an over-cap list on the retry keeps its newest entries and reports the cut (#5274)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'in-progress', percent: 50, summary: 'Under way.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const coerce = (fields: Record<string, unknown>) => {
const coercedFields = new Set<string>();
return { review: validateProgress({ ...base, ...fields }, groups, { coerce: true, coercedFields }) as any, coercedFields: [...coercedFields] };
};
// Dates decide, whatever order the model answered in: the newest entry comes first here and the oldest is at index 1.
const dayOf = (index: number) => `2026-10-${String(index + 1).padStart(2, '0')}T00:00:00Z`;
const datesNewestFirst = (length: number) => Array.from({ length }, (_, index) => dayOf(index === 0 ? length : index - 1));
const milestones = datesNewestFirst(13).map(at => ({ at, text: `Done ${at}` }));
const keptMilestones = coerce({ milestones });
expect(keptMilestones.review.milestones.map((milestone: any) => milestone.at)).toEqual(milestones.filter((_, index) => index !== 1).map(milestone => milestone.at));
expect(keptMilestones.review.milestones[0].at).toBe(dayOf(13));
expect(keptMilestones.coercedFields).toEqual(['milestones']);
const preferences = datesNewestFirst(11).map(at => ({ kind: 'directive', preference: `Said ${at}`, quote: 'Short replies.', at }));
const keptPreferences = coerce({ preferences });
expect(keptPreferences.review.preferences[0].at).toBe(dayOf(11));
expect(keptPreferences.review.preferences).toHaveLength(10);
expect(keptPreferences.review.preferences.map((preference: any) => preference.at)).not.toContain(dayOf(0));
expect(keptPreferences.coercedFields).toEqual(['preferences']);
const regressions = datesNewestFirst(11).map(at => ({ text: `Broke ${at}`, at, fixedBy: null, evidence: [] }));
const changes = datesNewestFirst(13).map(at => ({ what: `Changed ${at}`, why: 'The owner asked.', at, evidence: [] }));
const keptOutcome = coerce({ outcome: { regressions, changes } });
expect(keptOutcome.review.outcome.regressions[0].at).toBe(dayOf(11));
expect(keptOutcome.review.outcome.changes[0].at).toBe(dayOf(13));
expect(keptOutcome.review.outcome.regressions.map((regression: any) => regression.at)).not.toContain(dayOf(0));
expect(keptOutcome.review.outcome.changes.map((change: any) => change.at)).not.toContain(dayOf(0));
expect(keptOutcome.coercedFields).toEqual(['outcome.regressions', 'outcome.changes']);
// Without a date on every entry, the last ones are the newest the model wrote.
const undated = Array.from({ length: 13 }, (_, index) => ({ at: index === 0 ? dayOf(0) : null, text: `Step ${index}` }));
expect(coerce({ milestones: undated }).review.milestones.map((milestone: any) => milestone.text)).toEqual(undated.slice(1).map(milestone => milestone.text));
});
it('a preference without its words or the owner\'s quote on the retry is dropped, and the review is saved without it', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'in-progress', percent: 50, summary: 'Under way.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const quoted = { kind: 'directive', preference: 'Short replies.', quote: 'keep it short', at: null };
const preferences = [quoted, { kind: 'directive', preference: 'Tests first.', quote: '', at: null }, { kind: 'directive', preference: 'Small commits.', at: null }, { kind: 'directive', preference: ' ', quote: 'something', at: null }];
expect(() => validateProgress({ ...base, preferences }, groups)).toThrow('preferences[1].quote must be 1–300 characters.');
const coercedFields = new Set<string>(), droppedPreferences = new Set<string>();
const review = validateProgress({ ...base, preferences }, groups, { coerce: true, coercedFields, droppedPreferences }) as any;
expect(review.preferences).toEqual([quoted]);
// A drop is not a trim: nothing was shortened.
expect([...droppedPreferences]).toEqual(['preferences[1]', 'preferences[2]', 'preferences[3]']);
expect([...coercedFields]).toEqual([]);
});
it('every length the skill asks for is the target a refusal names', () => {
const skill = readFileSync(join(import.meta.dir, '../../plugin/skills/request-progress/SKILL.md'), 'utf8');
// The story keeps its own target (STORY_NARRATIVE_TARGET), which its refusal names.
const pairs = [...skill.matchAll(/about (\d+) chars and never over (\d+)/g)].map(([, about, cap]) => [Number(about), Number(cap)]).filter(([, cap]) => cap !== 12000);
expect(pairs.length).toBeGreaterThan(10);
for (const [about, cap] of pairs) expect([about, cap]).toEqual([textTarget(cap), cap]);
});
it('a review records how released work landed, with evidence and the why of each change', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'shipped', percent: 100, shippedAt: '2026-10-03T00:00:00Z', summary: 'Cards merged and released.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const outcome = {
landed: { text: 'Released in v14.0.0 on Oct 3.', at: '2026-10-03T00:00:00Z', evidence: ['PR #4845'] },
usage: { level: 'in-use', text: 'Owner opened My Work daily since.', evidence: ['obs 101'] },
value: { level: 'high', text: 'Replaced the manual standup.', evidence: ['Oct 5 ask: "this is excellent work"'] },
regressions: [{ text: 'Cards lost summaries after a refresh.', at: '2026-10-04T00:00:00Z', fixedBy: 'PR #4850', evidence: ['obs 120'] }],
changes: [{ what: 'Restored the approved cards', why: 'Owner: "restore the approved My Work cards"', evidence: ['ce3636c05'] }],
};
const recorded = validateProgress({ ...base, outcome }, groups).outcome;
expect(recorded.usage.level).toBe('in-use');
expect(recorded.regressions[0].fixedBy).toBe('PR #4850');
expect(recorded.changes[0].at).toBeNull();
expect(validateProgress(base, groups).outcome).toBeNull();
expect(() => validateProgress({ ...base, outcome: { usage: { level: 'popular', text: 'x' } } }, groups)).toThrow(/usage.level/);
expect(() => validateProgress({ ...base, outcome: { changes: [{ what: 'x' }] } }, groups)).toThrow(/why/);
});
it('a landed entry with no text in it is refused once, then read as no landed entry on the retry (#6568)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'shipped', percent: 100, shippedAt: '2026-10-03T00:00:00Z', summary: 'Cards merged and released.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
// Every shape that carries no text refuses with the same words on the first ask, so the model can fix it.
for (const landed of [{ text: '' }, { text: ' ' }, { text: 42 }, { at: '2026-10-03T00:00:00Z', evidence: [] }, '']) {
expect(() => validateProgress({ ...base, outcome: { landed } }, groups)).toThrow('outcome.landed.text must be 1–400 characters.');
// On the retry none of them can be corrected into text, so the review is saved with no landed entry
// instead of refused again: refused on both tries, the group failed every refresh (five runs, #6568).
const coercedFields = new Set<string>(), droppedPreferences = new Set<string>();
const review = validateProgress({ ...base, outcome: { landed } }, groups, { coerce: true, coercedFields, droppedPreferences }) as any;
expect(review.outcome.landed).toBeNull();
// The drop is reported, never silent: the refresh counts it with the other retry coercions.
expect([...coercedFields]).toEqual(['outcome.landed (no text) dropped']);
}
// No landed entry at all is not a drop, so nothing is reported.
for (const landed of [null, undefined]) {
const coercedFields = new Set<string>();
expect((validateProgress({ ...base, outcome: { landed } }, groups, { coerce: true, coercedFields, droppedPreferences: new Set() }) as any).outcome.landed).toBeNull();
expect([...coercedFields]).toEqual([]);
}
// A bare string in the entry's place is refused on the first ask and kept as the text on the retry,
// the shape a single evidence string already gets.
expect(() => validateProgress({ ...base, outcome: { landed: 'Released in v14.0.0.' } }, groups)).toThrow('outcome.landed.text must be 1–400 characters.');
const fromStringFields = new Set<string>();
const fromString = validateProgress({ ...base, outcome: { landed: 'Released in v14.0.0.' } }, groups, { coerce: true, coercedFields: fromStringFields, droppedPreferences: new Set() }) as any;
expect(fromString.outcome.landed).toEqual({ text: 'Released in v14.0.0.', at: null, evidence: [] });
expect([...fromStringFields]).toEqual([]);
// A landed entry with text is untouched on both asks, its date and evidence kept.
const landed = { text: 'Released in v14.0.0 on Oct 3.', at: '2026-10-03T00:00:00Z', evidence: ['PR #4845'] };
expect((validateProgress({ ...base, outcome: { landed } }, groups) as any).outcome.landed).toEqual(landed);
expect((validateProgress({ ...base, outcome: { landed } }, groups, { coerce: true, coercedFields: new Set(), droppedPreferences: new Set() }) as any).outcome.landed).toEqual(landed);
});
it('a bad usage or value level, a non-list outcome list and ownerMove on a closed request are refused once, then dropped on the retry (#6645)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'shipped', percent: 100, shippedAt: '2026-10-03T00:00:00Z', summary: 'Cards merged and released.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const retry = (fields: Record<string, unknown>) => {
const coercedFields = new Set<string>();
return { review: validateProgress({ ...base, ...fields }, groups, { coerce: true, coercedFields, droppedPreferences: new Set() }) as any, coercedFields: [...coercedFields] };
};
// An out-of-list level: the first ask keeps its refusal so the model can pick a listed level; the retry saves the
// review without that entry instead of failing the whole refresh on one optional field.
const usage = { level: 'heavy', text: 'Opened daily.', evidence: ['obs 1'] };
expect(() => validateProgress({ ...base, outcome: { usage } }, groups)).toThrow('outcome.usage.level must be one of in-use, some-use, no-evidence, unknown.');
expect(retry({ outcome: { usage } })).toMatchObject({ review: { outcome: { usage: null } }, coercedFields: ['outcome.usage (invalid level) dropped'] });
const value = { level: 'huge', text: 'Worth it.', evidence: [] };
expect(() => validateProgress({ ...base, outcome: { value } }, groups)).toThrow('outcome.value.level must be one of high, medium, low, unclear.');
expect(retry({ outcome: { value } })).toMatchObject({ review: { outcome: { value: null } }, coercedFields: ['outcome.value (invalid level) dropped'] });
// A listed level is kept on the retry, and nothing is reported.
expect(retry({ outcome: { usage: { ...usage, level: 'in-use' } } })).toMatchObject({ review: { outcome: { usage: { level: 'in-use', text: 'Opened daily.' } } }, coercedFields: [] });
// A list given as a string or an object: refused first, read as no entries on the retry.
for (const regressions of ['none', { text: 'Broke the grid.' }]) {
expect(() => validateProgress({ ...base, outcome: { regressions } }, groups)).toThrow('outcome.regressions must be an array of at most 10.');
expect(retry({ outcome: { regressions } })).toMatchObject({ review: { outcome: { regressions: [] } }, coercedFields: ['outcome.regressions (not a list) dropped'] });
}
expect(retry({ milestones: 'Merged.' })).toMatchObject({ review: { milestones: [] }, coercedFields: ['milestones (not a list) dropped'] });
// A missing list is not a drop.
expect(retry({ outcome: { regressions: null } }).coercedFields).toEqual([]);
// ownerMove on a closed request: refused first, dropped on the retry with the state kept.
const ownerMove = { what: 'Merge it.', since: 'not a date' };
expect(() => validateProgress({ ...base, ownerMove }, groups)).toThrow('A request reviewed as shipped waits on no one; leave ownerMove out.');
const shipped = retry({ ownerMove });
expect(shipped.review.state).toBe('shipped');
expect(Object.hasOwn(shipped.review, 'ownerMove')).toBe(false);
expect(shipped.coercedFields).toEqual(['ownerMove (shipped) dropped']);
const abandoned = retry({ state: 'abandoned', percent: 30, shippedAt: null, ownerMove });
expect(Object.hasOwn(abandoned.review, 'ownerMove')).toBe(false);
expect(abandoned.coercedFields).toEqual(['ownerMove (abandoned) dropped']);
// An ownerMove that is not an object is still refused on the retry, and an open request keeps its move.
expect(() => retry({ ownerMove: 'Merge it.' })).toThrow('ownerMove must be an object with what and since, or left out.');
expect(retry({ state: 'in-progress', percent: 50, shippedAt: null, ownerMove: { what: 'Merge it.', since: null } }).review.ownerMove).toEqual({ what: 'Merge it.', since: null });
});
it('on the retry a bad since on an open request still refuses, and a missing list is not a drop (#6645)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const reviewBasis = { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] };
const retryOptions = () => ({ coerce: true, coercedFields: new Set<string>(), droppedPreferences: new Set<string>() });
// The move itself is legitimate on an open request, so a bad since there is still the model's to fix.
expect(() => validateProgress({ groupId: 'g_000000000001', state: 'in-progress', percent: 90, summary: 'Under way.', ownerMove: { what: 'Reply.', since: 'last week' }, reviewBasis }, groups, retryOptions())).toThrow('ownerMove.since must be an ISO date or null.');
// An undefined list already reads as no list, so nothing is reported as dropped.
const options = retryOptions();
const review = validateProgress({ groupId: 'g_000000000001', state: 'shipped', percent: 100, shippedAt: '2026-10-03T00:00:00Z', summary: 'Cards merged and released.', reviewBasis, outcome: { regressions: undefined } }, groups, options) as any;
expect(review.outcome.regressions).toEqual([]);
expect([...options.coercedFields]).toEqual([]);
});
it('a review citing one piece of evidence as a plain string is kept, not thrown (Oct 25)', () => {
const groups = { g_000000000001: { title: 'Cards' } };
const base = { groupId: 'g_000000000001', state: 'in-progress', percent: 40, summary: 'Cards under way.', reviewBasis: { checkedThrough: '2026-10-04T00:00:00Z', conversations: [key('a')] } };
const recorded = validateProgress({ ...base, evidence: 'obs 101', milestones: [{ at: null, text: 'First card', evidence: 'PR #4845' }], outcome: { usage: { level: 'in-use', text: 'Opened daily.', evidence: 'obs 120' } } }, groups);
expect(recorded.evidence).toEqual(['obs 101']);
expect(recorded.milestones[0].evidence).toEqual(['PR #4845']);
expect(recorded.outcome.usage.evidence).toEqual(['obs 120']);
expect(validateProgress({ ...base, evidence: ' ' }, groups).evidence).toEqual([]);
expect(validateProgress(base, groups).evidence).toEqual([]);
});
it('CLI round trip: apply groups, see them due, record a review, then nothing is due', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const { proposedGroups } = run(['candidates', '--days', '14']);
const decisions = join(dir, 'decisions.json');
writeFileSync(decisions, JSON.stringify({ groups: [{ title: 'Release cards', ...proposedGroups[0] }, { title: 'Pricing page', conversations: [key('c')] }] }));
expect(run(['apply', decisions])).toEqual({ groups: 2, conversations: 3 });
const pending = run(['pending', '--days', '14']);
expect(pending.due).toBe(2);
expect(pending.ungroupedConversations).toBe(0);
const groupId = groupIdFor(key('a'));
const review = join(dir, 'review.json');
const { reviewBasis } = run(['show', groupId]);
writeFileSync(review, JSON.stringify({ groupId, state: 'in-progress', percent: 70, startedAt: new Date(NOW - 3 * DAY).toISOString(), summary: 'Cards built; spacing fix in review.', preferences: [{ kind: 'directive', preference: 'Execute clear asks without asking.', quote: 'just do it', at: null }], reviewBasis }));
expect(run(['record-progress', review]).percent).toBe(70);
expect(readLedger(dir).progress[groupId].title).toBe('Release cards');
expect(run(['pending', '--days', '14']).groups.map((group) => group.title)).toEqual(['Pricing page']);
expect(run(['show', groupId]).conversations.length).toBe(2);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('projection merges conversations in a group and starts at the earliest ask', () => {
const groupId = groupIdFor(key('a'));
const ledger = { groups: { conversations: { [key('a')]: groupId, [key('b')]: groupId }, groups: { [groupId]: { title: 'Release cards' } } }, progress: { [groupId]: { groupId, state: 'in-progress', percent: 60 } } };
const sessions = [
{ id: 2, platform_source: 'claude', content_session_id: 'b', user_prompt: 'Fix the card spacing', started_at_epoch: 20 },
{ id: 1, platform_source: 'claude', content_session_id: 'a', user_prompt: 'Build the release cards', started_at_epoch: 10 },
];
const prompts = [
{ id: 21, session_db_id: 2, prompt_number: 1, prompt_text: 'Fix the card spacing', created_at_epoch: 20 },
{ id: 11, session_db_id: 1, prompt_number: 1, prompt_text: 'Build the release cards', created_at_epoch: 10 },
];
const item = (id: number) => ({ id, title: `work ${id}`, kind: 'work-state', listId: 'cards', listName: 'release-cards', project: 'repo/tree', lastUpdateEpoch: id });
const view = { agents: [{ id: 'later', label: 'Claude Code', sessionId: 2, work: [item(2)] }, { id: 'earlier', label: 'Claude Code', sessionId: 1, work: [item(1)] }] };
const { humanRequests } = buildHumanRequests(view, { sessions, prompts }, { ledger });
expect(humanRequests.length).toBe(1);
expect(humanRequests[0].id).toBe(JSON.stringify(['overall-request', groupId]));
expect(humanRequests[0].original.sourceId).toBe(11);
expect(humanRequests[0].progress.percent).toBe(60);
expect(humanRequests[0].title).toBe('Release cards');
expect(new Set(humanRequests[0].conversationKeys)).toEqual(new Set([key('a'), key('b')]));
const ungrouped = buildHumanRequests(view, { sessions, prompts });
expect(ungrouped.humanRequests.length).toBe(2);
});
it('a work list name links conversations only within one project', () => {
const candidate = (id: string, project: string) => ({ conversationKey: key(id), project, workLists: ['release'], requestIds: [] });
const { proposedGroups } = linkBackwards([candidate('a', 'repo-one'), candidate('b', 'repo-two'), candidate('c', 'repo-one')]);
expect(proposedGroups.map((group) => group.conversations)).toEqual([[key('a'), key('c')], [key('b')]]);
});
it('every joined conversation needs a link back to the anchor', () => {
const link = (conversations: string[]) => ({ kind: 'agent-judgment', conversations, evidence: 'continues the card work' });
expect(() => applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a'), key('b'), key('c')], links: [link([key('a'), key('b')])] }] })).toThrow(/without evidence linking/);
expect(() => applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a'), key('b')], links: [link([key('a'), key('z')])] }] })).toThrow(/group's own conversations/);
expect(() => applyGroupDecisions(null, { groups: [{ title: 'Cards', conversations: [key('a'), key('b'), key('c')], links: [link([key('a'), key('b')]), link([key('b'), key('c')])] }] })).not.toThrow();
});
it('a review goes stale when membership changes or unseen activity exists', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const decisions = join(dir, 'decisions.json');
writeFileSync(decisions, JSON.stringify({ groups: [{ title: 'Release cards', conversations: [key('a')] }, { title: 'Spacing', conversations: [key('b')] }, { title: 'Pricing page', conversations: [key('c')] }] }));
run(['apply', decisions]);
const groupId = groupIdFor(key('a'));
// The reviewer read `show` before the latest activity (NOW - DAY) and saves later.
const { reviewBasis, conversations } = run(['show', groupId], NOW - 2 * DAY);
expect(conversations[0].asks[0].text).toBe('Build the release cards');
const review = join(dir, 'review.json');
writeFileSync(review, JSON.stringify({ groupId, state: 'in-progress', percent: 50, summary: 'Cards started.', reviewBasis }));
run(['record-progress', review]);
const due = () => run(['pending', '--days', '14']).groups.map((group: { groupId: string }) => group.groupId);
// Nothing happened in that conversation after show.
expect(due()).not.toContain(groupId);
// Merge spacing in: old activity, new membership, so it is due again.
writeFileSync(decisions, JSON.stringify({ groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }] }));
run(['apply', decisions]);
expect(due()).toContain(groupId);
// Reviewed with the new membership, but the observation at NOW - DAY came after the reviewer's show.
writeFileSync(review, JSON.stringify({ groupId, state: 'in-progress', percent: 60, summary: 'Cards and spacing.', reviewBasis: run(['show', groupId], NOW - 1.5 * DAY).reviewBasis }));
run(['record-progress', review]);
// Activity after checkedThrough stays due even though the save came later.
expect(due()).toContain(groupId);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('recent observations and work-state writes bring older conversations into the window', () => {
const database = fixtureDatabase();
database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)').run(4, 'claude', 'd', 'm4', 'repo/tree', 'Build the old dashboard', NOW - 40 * DAY);
database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)').run(4, 1, 'Build the old dashboard', NOW - 40 * DAY);
const inWindow = () => readCandidates(database, { sinceEpoch: NOW - 14 * DAY }).some((candidate) => candidate.conversationKey === key('d'));
expect(inWindow()).toBe(false);
database.prepare('INSERT INTO observations (memory_session_id, created_at_epoch) VALUES (?, ?)').run('m4', NOW - DAY);
expect(inWindow()).toBe(true);
});
it('show returns every ask in full', () => {
const database = fixtureDatabase();
const prompt = database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)');
for (let number = 2; number <= 13; number += 1) prompt.run(1, number, `Fix card detail ${number} ${'x'.repeat(400)}`, NOW - 3 * DAY + number);
const [listed] = readCandidates(database, { conversationKeys: [key('a')] });
const [full] = readCandidates(database, { conversationKeys: [key('a')], fullAsks: true });
expect(listed.asks.length).toBe(10);
expect(full.asks.length).toBe(13);
expect(full.asks.at(-1).text.length).toBeGreaterThan(400);
});
it('projection hides ignored conversations and keeps the stored anchor ask as the start', () => {
const groupId = groupIdFor(key('a'));
const anchorAsk = { text: 'Build the release cards', source: 'user-prompt', sourceId: 11, url: '/api/work-view/evidence/prompt/11', promptNumber: 1, atEpoch: 10 };
const ledger = { groups: { conversations: { [key('a')]: groupId, [key('b')]: groupId }, groups: { [groupId]: { title: 'Release cards', anchorAsk } }, ignored: { [key('c')]: 'Automated naming prompt' } }, progress: {} };
// Only the later conversation and an ignored one are loaded; the anchor aged out.
const sessions = [
{ id: 2, platform_source: 'claude', content_session_id: 'b', user_prompt: 'Fix the card spacing', started_at_epoch: 20 },
{ id: 3, platform_source: 'claude', content_session_id: 'c', user_prompt: 'Generate a short name for this workspace', started_at_epoch: 30 },
];
const prompts = [{ id: 21, session_db_id: 2, prompt_number: 1, prompt_text: 'Fix the card spacing', created_at_epoch: 20 }];
const item = (id: number) => ({ id, title: `work ${id}`, kind: 'work-state', listId: 'cards', project: 'repo/tree', lastUpdateEpoch: id });
const view = { agents: [{ id: 'later', label: 'Claude Code', sessionId: 2, work: [item(2)] }, { id: 'bot', label: 'Codex', sessionId: 3, work: [item(3)] }] };
const { humanRequests, unlinkedWork } = buildHumanRequests(view, { sessions, prompts }, { ledger });
expect(humanRequests.length).toBe(1);
expect(humanRequests[0].original.sourceId).toBe(11);
expect(humanRequests[0].startedAtEpoch).toBe(10);
expect(unlinkedWork.find((work: { agentId: string }) => work.agentId === 'bot').reason).toBe('ignored-by-request-grouping');
});
it('goals fold the current owner-goals list and drop closed items and history', () => {
const database = fixtureDatabase();
saveGoals(database, '2026-10-01T10:00:00Z');
const goals = readGoals(database);
expect(goals.summary).toBe('Ship the cards.');
expect(goals.goals.map((goal) => [goal.taskKey, goal.kind, goal.rank, goal.legacy])).toEqual([['Focus area: Ship cards', 'focus-area', 1, false]]);
expect(goals.goals[0].evidence).toEqual([{ at: '2026-10-01 10:00', quote: 'ship the cards | today' }]);
});
it('goals saved before the three tests read as the nearest new kind, marked legacy; an unknown kind is refused', () => {
const database = fixtureDatabase();
const write = database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch) VALUES (?, ?, ?, ?)');
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Priority: Ship cards', status: 'todo', goal_kind: 'priority', rank: 1, title: 'Ship cards' }), 1);
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Open ask: Docs', status: 'todo', goal_kind: 'open-ask', rank: 1, title: 'Docs' }), 2);
expect(readGoals(database).goals.map((goal) => [goal.taskKey, goal.kind, goal.legacy])).toEqual([['Priority: Ship cards', 'focus-area', true], ['Open ask: Docs', 'ask', true]]);
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Rule: Tests', status: 'todo', goal_kind: 'rule', title: 'Tests' }), 3);
expect(() => readGoals(database)).toThrow(/unknown goal_kind: "rule"/);
});
it('focus round trip: focus-input lists areas and one batch of requests with every conversation\'s ask; record-focus writes router rows through the worker', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
focus.area('fa_cards', 'Cards', 'kept');
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
const input = run(['focus-input']);
expect(input.areas).toEqual([{ focusAreaId: 'fa_cards', name: 'Cards', goal: 'Make Cards good.', about: 'Everything about Cards.', status: 'kept' }]);
expect(input.requests.map((request: any) => [request.anchor, request.title, request.firstAsk, request.repo, request.conversations, request.conversationAsks]))
.toEqual([[key('a'), 'Release cards', 'Build the release cards', 'repo', 2, ['Build the release cards', 'Fix the card spacing']], [key('c'), 'Pricing page', 'Write the pricing page', 'repo', 1, ['Write the pricing page']]]);
expect(input.remaining).toBe(0);
// Batches: --limit 1 lists the first request and counts the rest.
expect(run(['focus-input', '--limit', '1'])).toMatchObject({ requests: [{ anchor: key('a') }], remaining: 1 });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).unplaced).toBe(2);
// An unknown area id is refused, never mapped to Other, and nothing is written.
const rowsBefore = focus.rows();
await expect(run(['record-focus', write('f0.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_nope', evidence: 'x' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'y' }], proposals: [] })])).rejects.toThrow(/"fa_nope", which is not a listed focus area/);
await expect(run(['record-focus', write('f1.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'x' }], proposals: [] })])).rejects.toThrow(/Place every request asked about; missing/);
expect(focus.rows()).toBe(rowsBefore);
// A batch answer is checked against that batch: the second request is not part of the --limit 1 question.
await expect(run(['record-focus', '--limit', '1', write('f1b.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'x' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'y' }], proposals: [] })])).rejects.toThrow(/was not asked about/);
expect(await run(['record-focus', write('f2.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'Release cards are cards.' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'Pricing fits no area.' }], proposals: [] })]))
.toEqual({ placed: 2, proposed: 0, focusAreaIds: [] });
const placed = readFocus(database, { localDeviceId: '' });
expect(placed.focusAreaIdByAnchor.get(key('a'))).toBe('fa_cards');
expect(placed.focusAreaIdByAnchor.get(key('c'))).toBe('other');
expect(placed.placementsByAnchor.get(key('a'))?.router?.basis).toMatch(/^[0-9a-f]{16}$/);
expect(run(['focus-input']).requests).toEqual([]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).unplaced).toBe(0);
// Without the worker's write, or without the worker's device id, the command refuses instead of guessing.
expect(() => runCli(['record-focus', write('f3.json', { placements: [], proposals: [] })], { dir, database, now: NOW, print: () => {}, localDeviceId: '' })).toThrow(/saves through the claude-mem worker/);
expect(() => runCli(['focus-input'], { dir, database, now: NOW, print: () => {} })).toThrow(/sync device id/);
expect(() => refreshNeeds({ dir, database, now: NOW } as any)).toThrow(/sync device id/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('focus: a request the model cannot decide goes in "ignored" and is recorded in Other with its reason', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
focus.area('fa_cards', 'Cards', 'kept');
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a'), key('c')]);
// Ignoring a request that was not asked about is refused; so is ignoring in the Other pass, which places nothing.
await expect(run(['record-focus', write('f0.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'x' }], proposals: [], ignored: [{ anchor: key('z'), reason: 'Not a request.' }] })])).rejects.toThrow(/ignored\[0\] names .+, which was not asked about/);
await expect(run(['record-focus', '--other', write('f0b.json', { placements: [], proposals: [], ignored: [{ anchor: key('c'), reason: 'Not a request.' }] })])).rejects.toThrow(/places nothing/);
// One placed, one explicitly skipped: the batch completes instead of failing on the missing one (#6432).
expect(await run(['record-focus', write('f1.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'Release cards are cards.' }], proposals: [], ignored: [{ anchor: key('c'), reason: 'A pricing page draft, not a piece of work yet.' }] })]))
.toEqual({ placed: 2, proposed: 0, focusAreaIds: [] });
const placed = readFocus(database, { localDeviceId: '' });
expect(placed.focusAreaIdByAnchor.get(key('a'))).toBe('fa_cards');
expect(placed.focusAreaIdByAnchor.get(key('c'))).toBe('other');
expect(placed.placementsByAnchor.get(key('c'))?.router?.evidence).toBe('A pricing page draft, not a piece of work yet.');
expect(run(['focus-input']).requests).toEqual([]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a request is placed again when its asks or conversations change, never for a new review; another device\'s placement is not compared', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
focus.area('fa_cards', 'Cards', 'kept');
focus.area('fa_done', 'Launch', 'kept');
const { run, write } = cliRunner(dir, database, focus.save);
const group = groupIdFor(key('a'));
run(['apply', write('d1.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
await run(['record-focus', write('f1.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'The cards.' }, { anchor: key('c'), focusAreaId: 'fa_done', evidence: 'Pricing for the launch.' }], proposals: [] })]);
expect(run(['focus-input']).requests).toEqual([]);
// The owner finishes the Launch area; its requests stay there.
focus.area('fa_done', 'Launch', 'done');
// A new review (state, percent, summary) does not decide the area: nothing is queued, in a live or a done area.
for (const groupId of [group, groupIdFor(key('c'))]) {
run(['record-progress', write('r.json', { groupId, state: 'shipped', percent: 100, shippedAt: new Date(NOW).toISOString(), summary: 'Now something else entirely.', reviewBasis: run(['show', groupId]).reviewBasis })]);
}
expect(run(['focus-input']).requests).toEqual([]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).unplaced).toBe(0);
// A merged-in conversation changes the request: it is placed again.
run(['apply', write('d2.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }] })]);
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a')]);
// The same request placed by another computer, decided on that computer's copy: not re-placed here.
focus.insert(placementRowFields({ anchorConversationKey: key('a'), focusAreaId: 'fa_cards', placedBy: 'router', basis: 'ffffffffffffffff', evidence: 'Placed elsewhere.' }), 'other-device');
expect(run(['focus-input']).requests).toEqual([]);
// A seed placement written without a basis counts as current.
focus.insert(placementRowFields({ anchorConversationKey: key('c'), focusAreaId: 'fa_cards', placedBy: 'router', evidence: 'Seeded.' }));
run(['apply', write('d3.json', { groups: [{ title: 'Pricing and plans', conversations: [key('c')] }] })]);
expect(run(['focus-input']).requests).toEqual([]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('an owner placement is never queued while its area is live; once the owner dismisses that area it no longer binds', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
focus.area('fa_cards', 'Cards', 'kept');
focus.area('fa_pricing', 'Pricing', 'suggested');
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
focus.insert(placementRowFields({ anchorConversationKey: key('c'), focusAreaId: 'fa_pricing', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a')]);
run(['apply', write('d2.json', { groups: [{ title: 'Pricing and plans', conversations: [key('c')] }] })]);
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a')]);
await expect(run(['record-focus', write('f.json', { placements: [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'x' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'y' }], proposals: [] })])).rejects.toThrow(/was not asked about/);
focus.area('fa_pricing', 'Pricing', 'dismissed', 'owner');
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a'), key('c')]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('placing promotes any request that holds several asks; sameAs on a listed area places there; a dismissed area is never placed in or proposed again', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
focus.area('fa_cards', 'Cards', 'kept');
focus.area('fa_old', 'Billing', 'dismissed', 'owner');
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
const input = run(['focus-input']);
expect(input.areas.map((area: any) => area.focusAreaId)).toEqual(['fa_cards']);
expect(input.dismissed.map((area: any) => [area.focusAreaId, area.name])).toEqual([['fa_old', 'Billing']]);
const placements = [{ anchor: key('a'), focusAreaId: 'fa_cards', evidence: 'Cards.' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'Pricing.' }];
const promote = { kind: 'promote', name: 'Release', goal: 'Releases ship.', about: 'Cards, spacing and release work.', anchors: [key('a')], sameAs: null, evidence: 'Two separate asks: build cards, fix spacing.' };
const refused = async (answer: unknown, pattern: RegExp, flags: string[] = []) => {
const before = focus.rows();
await expect(run(['record-focus', ...flags, write('f.json', answer)])).rejects.toThrow(pattern);
expect(focus.rows()).toBe(before);
};
await refused({ placements: [{ ...placements[0], focusAreaId: 'fa_old' }, placements[1]], proposals: [] }, /fa_old \("Billing"\), which the owner dismissed/);
await refused({ placements, proposals: [{ ...promote, sameAs: 'fa_old' }] }, /the area the owner dismissed .*never propose it again/);
await refused({ placements, proposals: [{ ...promote, sameAs: 'fa_nope' }] }, /not a listed area/);
await refused({ placements, proposals: [{ ...promote, kind: 'new', anchors: [key('a'), key('c')] }] }, /new areas are proposed from Other in their own question/);
await refused({ placements, proposals: [{ ...promote, anchors: [key('a'), key('c')] }] }, /promotes one request/);
// A request placed in a kept area can still be promoted: it holds several separate asks.
const saved = await run(['record-focus', write('f.json', { placements, proposals: [promote] })]);
expect(saved).toMatchObject({ placed: 2, proposed: 1 });
expect(saved.focusAreaIds[0]).toMatch(/^fa_[0-9a-f]{12}$/);
let after = readFocus(database, { localDeviceId: '' });
expect(after.focusAreas.find((area) => area.focusAreaId === saved.focusAreaIds[0])).toMatchObject({ name: 'Release', status: 'suggested', source: 'promotion', decidedBy: 'system' });
expect(after.focusAreaIdByAnchor.get(key('a'))).toBe(saved.focusAreaIds[0]);
// sameAs naming a listed area: its requests go there and no area is added.
run(['apply', write('d2.json', { groups: [{ title: 'Pricing and plans', conversations: [key('c')] }] })]);
const areasBefore = after.focusAreas.length;
expect(await run(['record-focus', write('f2.json', { placements: [{ anchor: key('c'), focusAreaId: 'other', evidence: 'x' }], proposals: [{ ...promote, name: 'Cards again', anchors: [key('c')], sameAs: 'fa_cards' }] })])).toMatchObject({ placed: 1, proposed: 0 });
after = readFocus(database, { localDeviceId: '' });
expect(after.focusAreas).toHaveLength(areasBefore);
expect(after.focusAreaIdByAnchor.get(key('c'))).toBe('fa_cards');
expect(after.focusAreas.find((area) => area.focusAreaId === 'fa_old')?.status).toBe('dismissed');
// The worker refuses a placement or a sameAs into a dismissed area on its own, whatever the CLI checked.
expect(() => routerFocusRows({ placements: [{ anchorConversationKey: key('a'), focusAreaId: 'fa_old', basis: '0123456789abcdef', evidence: 'x' }], proposals: [] }, readFocusAreas(database, { localDeviceId: '' }))).toThrow(/fa_old, which no longer takes requests/);
expect(() => routerFocusRows({ placements: [], proposals: [{ kind: 'new', name: 'Billing', goal: 'g', about: 'a', evidence: 'e', sameAs: 'fa_old', requests: [{ anchorConversationKey: key('a'), basis: '0123456789abcdef' }] }] }, readFocusAreas(database, { localDeviceId: '' }))).toThrow(/owner dismissed; it is never proposed again/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('the Other pass clusters router-placed Other requests, leaves the owner\'s Other alone, and runs again only when that set changes', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)').run(4, 'claude', 'd', 'm4', 'repo/tree', 'Tidy the card copy', NOW - DAY);
database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)').run(4, 1, 'Tidy the card copy', NOW - DAY);
const focus = focusFixture(database);
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: ['a', 'b', 'c', 'd'].map((session) => ({ title: `Request ${session}`, conversations: [key(session)] })) })]);
// The owner put d in Other themselves; the router put a, b and c there.
focus.insert(placementRowFields({ anchorConversationKey: key('d'), focusAreaId: 'other', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
await run(['record-focus', write('f.json', { placements: ['a', 'b', 'c'].map((session) => ({ anchor: key(session), focusAreaId: 'other', evidence: 'Fits no area.' })), proposals: [] })]);
const needs = refreshNeeds({ dir, database, now: NOW, localDeviceId: '' });
expect([needs.unplaced, needs.otherChanged]).toEqual([0, true]);
const other = run(['focus-input', '--other']);
expect(other.due).toBe(true);
expect(other.other.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c')]);
const cluster = { kind: 'new', name: 'Polish', goal: 'The release looks finished.', about: 'Spacing and copy fixes.', anchors: [key('b'), key('c')], sameAs: null, evidence: 'Both are steps of finishing the release.' };
await expect(run(['record-focus', '--other', write('o0.json', { placements: [{ anchor: key('a'), focusAreaId: 'other', evidence: 'x' }], proposals: [] })])).rejects.toThrow(/places nothing/);
await expect(run(['record-focus', '--other', write('o1.json', { placements: [], proposals: [{ ...cluster, anchors: [key('b'), key('d')] }] })])).rejects.toThrow(/not a listed Other request/);
await expect(run(['record-focus', '--other', write('o2.json', { placements: [], proposals: [{ ...cluster, anchors: [key('b')] }] })])).rejects.toThrow(/clusters one request/);
const saved = await run(['record-focus', '--other', write('o3.json', { placements: [], proposals: [cluster] })]);
expect(saved).toMatchObject({ placed: 2, proposed: 1 });
const after = readFocus(database, { localDeviceId: '' });
expect(after.focusAreas[0]).toMatchObject({ name: 'Polish', status: 'suggested', source: 'clustering' });
expect([key('b'), key('c'), key('d')].map((anchor) => after.focusAreaIdByAnchor.get(anchor))).toEqual([saved.focusAreaIds[0], saved.focusAreaIds[0], 'other']);
// The pass looked at what is left in Other (a): a quiet refresh does not ask again.
expect(run(['focus-input', '--other']).due).toBe(false);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).otherChanged).toBe(false);
// An empty answer still records the pass.
focus.insert(placementRowFields({ anchorConversationKey: key('b'), focusAreaId: 'other', placedBy: 'router', basis: null as any, evidence: 'Back to Other.' }));
expect(run(['focus-input', '--other']).due).toBe(true);
await run(['record-focus', '--other', write('o4.json', { placements: [], proposals: [] })]);
expect(run(['focus-input', '--other']).due).toBe(false);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('the Other pass runs again when a request in Other changes and is placed back in Other', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: ['a', 'b'].map((session) => ({ title: `Request ${session}`, conversations: [key(session)] })) })]);
await run(['record-focus', write('f.json', { placements: ['a', 'b'].map((session) => ({ anchor: key(session), focusAreaId: 'other', evidence: 'Fits no area.' })), proposals: [] })]);
await run(['record-focus', '--other', write('o.json', { placements: [], proposals: [] })]);
expect(run(['focus-input', '--other']).due).toBe(false);
// Another computer's pass record syncs in, newer, over its own local titles: it is not this computer's pass.
focus.insert({ other_pass_hash: 'another-computers-basis' }, 'other-computer');
expect(run(['focus-input', '--other']).due).toBe(false);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).otherChanged).toBe(false);
// Request a changes: the placing step looks at it again and leaves it in Other. The same two requests are in
// Other, but a holds something the last proposal pass never saw.
run(['apply', write('d2.json', { groups: [{ title: 'Request a, now with pricing', conversations: [key('a')] }] })]);
expect(run(['focus-input']).requests.map((request: any) => request.anchor)).toEqual([key('a')]);
await run(['record-focus', write('f2.json', { placements: [{ anchor: key('a'), focusAreaId: 'other', evidence: 'Still fits no area.' }], proposals: [] })]);
expect(run(['focus-input', '--other']).due).toBe(true);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).otherChanged).toBe(true);
await run(['record-focus', '--other', write('o2.json', { placements: [], proposals: [] })]);
expect(run(['focus-input', '--other']).due).toBe(false);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a re-review that adds an owner preference, a ship date fix or a regression reaches the story, at the same state and percent', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
const group = groupIdFor(key('a'));
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }] })]);
const review = (now: number, extra: object) => run(['record-progress', write('r.json', { groupId: group, state: 'in-progress', percent: 40, summary: 'Under way.', reviewBasis: run(['show', group], now).reviewBasis, ...extra })], now);
review(NOW, {});
run(['record-story', write('s.json', { narrative: 'One request under way.' })], NOW + 1000);
// Reworded prose alone is not new story content.
review(NOW + 2000, { summary: 'Still under way.' });
expect(run(['story-input']).reviews).toEqual([]);
review(NOW + 3000, { preferences: [{ kind: 'directive', preference: 'Fail loudly at limits', quote: 'fail loudly', at: null }] });
expect(run(['story-input']).reviews.map((entry: { groupId: string }) => entry.groupId)).toEqual([group]);
run(['record-story', write('s2.json', { narrative: 'One request under way.' })], NOW + 4000);
review(NOW + 5000, { preferences: [{ kind: 'directive', preference: 'Fail loudly at limits', quote: 'fail loudly', at: null }], outcome: { regressions: [{ text: 'Cards lost their dates', at: null }] } });
expect(run(['story-input']).reviews.map((entry: { groupId: string }) => entry.groupId)).toEqual([group]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('show: a re-review with the same conversations amends the previous review from the new asks only', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
const group = groupIdFor(key('a'));
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }] })]);
const first = run(['show', group]);
expect(first).toMatchObject({ mode: 'full', amendSince: null });
run(['record-progress', write('r.json', { groupId: group, state: 'in-progress', percent: 40, summary: 'Under way.', reviewBasis: first.reviewBasis })]);
database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)').run(1, 2, 'Now add the release date to each card', NOW + DAY);
database.prepare('INSERT INTO observations (memory_session_id, type, title, subtitle, created_at_epoch) VALUES (?, ?, ?, ?, ?)').run('m1', 'feature', 'Release dates on cards', 'Each card shows its date', NOW + DAY);
database.prepare('INSERT INTO observations (memory_session_id, type, title, subtitle, created_at_epoch) VALUES (?, ?, ?, ?, ?)').run('m1', 'feature', 'Cards built', 'Before the review', NOW - DAY);
expect(run(['show', group], NOW + 2 * DAY).conversations[0].observations).toMatchObject([{ title: 'Release dates on cards', type: 'feature', at: new Date(NOW + DAY).toISOString() }]);
const amend = run(['show', group], NOW + 2 * DAY);
expect(amend).toMatchObject({ mode: 'amend', amendSince: new Date(NOW).toISOString(), previousReview: { percent: 40 } });
expect(amend.conversations[0].asks.map((ask: { text: string }) => ask.text)).toEqual(['Now add the release date to each card']);
// A merged-in conversation changes what was reviewed: a full review again.
run(['apply', write('d2.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }] })]);
const full = run(['show', group], NOW + 2 * DAY);
expect(full.mode).toBe('full');
expect(full.conversations.find((conversation: { conversationKey: string }) => conversation.conversationKey === key('a')).asks).toHaveLength(2);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('story-input lists every review without a story, then only reviews whose facts changed', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
const review = (session: string, percent: number, now: number) => run(['record-progress', write('r.json', { groupId: groupIdFor(key(session)), state: 'in-progress', percent, summary: 'Under way.', reviewBasis: run(['show', groupIdFor(key(session))], now).reviewBasis })], now);
review('a', 40, NOW); review('c', 40, NOW);
expect(run(['story-input'])).toMatchObject({ update: false, reviews: [{ percent: 40 }, { percent: 40 }] });
run(['record-story', write('s.json', { narrative: 'Two requests under way.' })], NOW + 1000);
// Re-reviewed with the same state and percent: the story still holds.
review('a', 40, NOW + 2000);
expect(run(['story-input'])).toMatchObject({ update: true, reviews: [] });
review('c', 60, NOW + 3000);
const input = run(['story-input']);
expect(input.reviews.map((entry: { groupId: string }) => entry.groupId)).toEqual([groupIdFor(key('c'))]);
expect(input.previousStory.narrative).toBe('Two requests under way.');
// Rules owner-goals put in the story are carried by record-story but never shown to the story model, so it
// cannot echo copies of them back without their source.
const ownerGoalsRule = { preference: 'Ship daily.', when: '', kind: 'directive', supportCount: 1, quotes: [], source: 'owner-goals' };
writeFileSync(join(dir, 'story.json'), JSON.stringify({ ...readLedger(dir).story, preferences: [{ preference: 'Keep the design.', quotes: [] }, ownerGoalsRule] }));
expect(run(['story-input']).previousStory.preferences.map((preference: { preference: string }) => preference.preference)).toEqual(['Keep the design.']);
run(['record-story', write('s3.json', { narrative: 'Two requests under way.', preferences: [{ preference: 'Keep the design.' }] })], NOW + 4000);
expect(readLedger(dir).story.preferences.map((preference: { preference: string; source?: string }) => [preference.preference, preference.source ?? null]))
.toEqual([['Keep the design.', null], ['Ship daily.', 'owner-goals']]);
// The agent gets its budget up front, counted to the target, and an over-long story is refused with its length,
// the target and the parts furthest over budget. A story without chapters keeps the whole target.
expect(input).toMatchObject({ narrativeTarget: 8000, narrativeLimit: 12000, previousNarrativeChars: 'Two requests under way.'.length, roomChars: 8000 - 'Two requests under way.'.length, condenseChars: 0,
previousParts: [{ part: 'recap', chars: 'Two requests under way.'.length, budgetChars: 8000, overBudgetChars: 0 }] });
const overCap = `${'word '.repeat(200)}\n\n## Oct 26: shipped\n${'word '.repeat(996)}\n\n## Oct 27: in progress\n${'word '.repeat(1200)}`;
expect(() => run(['record-story', write('s.json', { narrative: overCap })])).toThrow(`narrative is 12026 characters; it must be 1–12000. Bring it to about 8000 characters: rewrite the parts furthest over their budgets: "Oct 27: in progress" 6023 → 3600 characters (about 720 words); "Oct 26: shipped" 5001 → 3600 characters (about 719 words); the recap 1002 → 800 characters (about 159 words).`);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('storyParts budgets the recap and splits the rest of the target across the chapters', () => {
const story = `${'word '.repeat(230)}\n## Oct 26: agy\n${'word '.repeat(280)}\n## Oct 27: search\n${'word '.repeat(440)}\n## Oct 27: Chrome\n${'word '.repeat(60)}`;
// Budgets also go in words, at each part's own characters per word, which a writer keeps to; character
// budgets alone were missed.
expect(storyParts(story)).toEqual([
{ part: 'recap', chars: 1151, words: 230, budgetChars: 800, budgetWords: 159, overBudgetChars: 351 },
{ part: 'Oct 26: agy', chars: 1416, words: 284, budgetChars: 2400, budgetWords: 481, overBudgetChars: 0 },
{ part: 'Oct 27: search', chars: 2219, words: 444, budgetChars: 2400, budgetWords: 480, overBudgetChars: 0 },
{ part: 'Oct 27: Chrome', chars: 318, words: 64, budgetChars: 2400, budgetWords: 483, overBudgetChars: 0 },
]);
// Lengths add up to the story, so the parts account for every character the writer has to fit.
expect(storyParts(story).reduce((sum, part) => sum + part.chars, 0)).toBe(story.length);
// A story that opens with a chapter has an empty recap, not a chapter counted as the recap.
expect(storyParts('## Only chapter\nText.')).toEqual([
{ part: 'recap', chars: 0, words: 0, budgetChars: 800, budgetWords: 133, overBudgetChars: 0 },
{ part: 'Only chapter', chars: 21, words: 4, budgetChars: 7200, budgetWords: 1371, overBudgetChars: 0 },
]);
});
it('storyParts keeps code-fenced headings, chapterless stories and many chapters workable', () => {
// A `## ` line inside a code fence belongs to its chapter.
expect(storyParts('Recap.\n## Real\nText\n```\n## not a chapter\n```\nMore.\n').map((part) => part.part)).toEqual(['recap', 'Real']);
// Without chapters the recap is the whole story, so it gets the whole target, not the recap's share.
expect(storyParts('word '.repeat(1800))).toEqual([{ part: 'recap', chars: 9000, words: 1800, budgetChars: 8000, budgetWords: 1600, overBudgetChars: 1000 }]);
// Many chapters never push a chapter's budget below the floor.
const many = Array.from({ length: 30 }, (_, index) => `## Day ${index}\nShipped.\n`).join('');
expect(new Set(storyParts(many).slice(1).map((part) => part.budgetChars))).toEqual(new Set([300]));
});
it('storyParts closes a code fence only on a matching fence, as CommonMark does', () => {
// A ```` fence holding a ``` example: the inner ``` lines neither close it nor reopen it, so its `## ` line stays inside.
const story = 'Recap.\n## Real\n````md\n```\n## not a chapter\n```\n````\n## Next\nText.\n';
expect(storyParts(story).map((part) => part.part)).toEqual(['recap', 'Real', 'Next']);
// An indented fence (up to 3 spaces) and a tilde fence count too, and a ``` line does not close a ~~~ fence.
expect(storyParts('Recap.\n## Real\n ```\n## inside\n ```\n~~~\n```\n## still inside\n~~~\n## Next\n').map((part) => part.part)).toEqual(['recap', 'Real', 'Next']);
// Four spaces is code, not a fence, so the heading after it is a chapter.
expect(storyParts('Recap.\n ```\n## Chapter\n').map((part) => part.part)).toEqual(['recap', 'Chapter']);
expect(storyParts(story).reduce((sum, part) => sum + part.chars, 0)).toBe(story.length);
});
it('a story with more chapters than the budgets fit is told to merge its oldest chapters', () => {
// 41 chapters at the 300-character floor add up to more than the target, so an over-cap story with every chapter
// within its budget has nothing over budget to rewrite. The refusal and story-input name the oldest chapters to merge.
const chapter = (index: number) => `## Day ${index}\n${'w'.repeat(290 - String(index).length)}\n`;
const story = `Recap.\n\n${Array.from({ length: 41 }, (_, index) => chapter(index)).join('')}`;
expect(story.length).toBeGreaterThan(12000);
expect(storyParts(story).filter((part) => part.overBudgetChars > 0)).toEqual([]);
expect(storyChaptersToMerge(story)).toBe(18);
let message = '';
try { validateStory({ narrative: story }); } catch (error) { message = (error as Error).message; }
expect(message).toBe(`narrative is ${story.length} characters; it must be 1–12000. Bring it to about 8000 characters: merge the 18 oldest chapters ("Day 0" through "Day 17") into one chapter of at most 300 characters.`);
// Merging them leaves 24 chapters, whose budgets fit the target again.
expect(storyChaptersToMerge(`Recap.\n${Array.from({ length: 24 }, (_, index) => chapter(index)).join('')}`)).toBe(0);
expect(storyChaptersToMerge(`Recap.\n${Array.from({ length: 25 }, (_, index) => chapter(index)).join('')}`)).toBe(2);
});
it('a preference one character over its cap is refused, then trimmed on the retry without losing the others', () => {
const words = 'Show honest empty states and never fabricate fallback data. '.repeat(4).slice(0, 201);
const story = { narrative: 'Recap.', preferences: [{ preference: 'Keep me.', kind: 'directive', supportCount: 2, quotes: [] }, { preference: words, kind: 'directive', supportCount: 1, quotes: [] }] };
expect(() => validateStory(story)).toThrow('preferences[1].preference is 201 characters; it must be 1–200.');
const trimmed = validateStory(trimStoryPreferences(story));
expect(trimmed.preferences).toHaveLength(2);
expect(trimmed.preferences[0].preference).toBe('Keep me.');
expect(trimmed.preferences[1].preference.length).toBeLessThanOrEqual(200);
expect(trimmed.preferences[1].preference.endsWith('…')).toBe(true);
});
it('a story over its 30 preferences is refused, then keeps the 30 most supported on the retry, in the model order (#6568)', () => {
const preferences = Array.from({ length: 32 }, (_, index) => ({ preference: `Preference ${index}.`, kind: 'directive', supportCount: index < 2 ? 1 : 3, quotes: [] }));
// Three preferences seen once, room for one of them: the earliest listed is kept.
preferences[31].supportCount = 1;
const story = { narrative: 'Recap.', preferences };
expect(() => validateStory(story)).toThrow('preferences has 32 items; it must have at most 30.');
const trimmed = new Set<string>(), dropped = new Set<string>();
const saved = validateStory(trimStoryPreferences(story, trimmed, dropped));
expect(saved.preferences.map(preference => preference.preference)).toEqual(['Preference 0.', ...preferences.slice(2, 31).map(preference => preference.preference)]);
expect([...dropped]).toEqual(['preferences[1]', 'preferences[31]']);
expect(trimmed.size).toBe(0);
});
it('an over-cap story is refused with only the parts furthest over budget named', () => {
const story = `Recap.\n\n${Array.from({ length: 10 }, (_, index) => `## Day ${index}\n${'word '.repeat(260)}\n`).join('')}`;
expect(story.length).toBeGreaterThan(12000);
let message = '';
try { validateStory({ narrative: story }); } catch (error) { message = (error as Error).message; }
expect(message).toContain('Bring it to about 8000 characters: rewrite the parts furthest over their budgets: "Day');
expect(message).toContain('; 4 more parts are over their budgets too.');
expect(message.match(/"Day \d"/g)).toHaveLength(6);
expect(message.length).toBeLessThan(1000);
});
// A suggestion's id is a hash of its exact words (my-rules.mjs), so a rejected rule reworded came back as a new
// suggestion (design pass Phase 10): the story step is told what the owner rejected, and owner-goals reads the same
// words through dismissed-rules.
it('story-input and dismissed-rules give the words of every rule the owner rejected in My Rules, and nothing else from the my-rules rows', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const saveRule = (ruleId: string, then: string, setBy: SavedRule['setBy'], status: SavedRule['status'], at: number) =>
database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch) VALUES (?, ?, ?, ?)').run('home', MY_RULES_LIST, JSON.stringify(ruleRowFields({
ruleId, scopeTier: 'everywhere', scopeName: 'Everywhere', when: '', then, setBy, status, source: setBy === 'owner' ? 'you' : 'request-progress',
replacedBy: null, replacedAt: null, quotes: [], timesSeen: 1, latestAt: null, kind: 'directive',
})), at);
expect(run(['story-input']).dismissedRules).toEqual([]);
expect(run(['dismissed-rules'])).toEqual({ dismissedRules: [] });
saveRule('pref_00000000000a', 'Explain findings as slide decks.', 'learned', 'dismissed', NOW - 3 * DAY);
saveRule('pref_00000000000b', 'Use decks to explain plans.', 'approved', 'on', NOW - 3 * DAY);
// An owner's own rule taken back is gone, not rejected.
saveRule('own_00000000000c', 'Never ask twice.', 'owner', 'dismissed', NOW - 3 * DAY);
// Rejected, then put back in Suggestions with its words (WorkViewRoutes restore-suggestion).
saveRule('pref_00000000000d', 'Ship on Fridays.', 'learned', 'dismissed', NOW - 3 * DAY);
database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch) VALUES (?, ?, ?, ?)').run('home', MY_RULES_LIST, JSON.stringify(restoredSuggestionRowFields({
ruleId: 'pref_00000000000d', scopeTier: 'everywhere', scopeName: 'Everywhere', when: '', then: 'Ship on Fridays.', source: 'request-progress', replacedBy: null, replacedAt: null,
})), NOW - 2 * DAY);
// Another list's row naming a dismissed status is no rule.
database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch) VALUES (?, ?, ?, ?)').run('home', 'release-cards', JSON.stringify({ task: 'Rule: x', then: 'Not a rule.', status: 'dismissed', set_by: 'learned' }), NOW - DAY);
expect(run(['story-input']).dismissedRules).toEqual(['Explain findings as slide decks.']);
expect(run(['dismissed-rules'])).toEqual({ dismissedRules: ['Explain findings as slide decks.'] });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('story-input aims an update at the target and asks to condense a previous story past it', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; } }); return output; };
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
run(['apply', write('d.json', { groups: [{ title: 'Release cards', conversations: [key('a')] }] })]);
const review = (percent: number, now: number) => run(['record-progress', write('r.json', { groupId: groupIdFor(key('a')), state: 'in-progress', percent, summary: 'Under way.', reviewBasis: run(['show', groupIdFor(key('a'))], now).reviewBasis })], now);
review(40, NOW);
expect(run(['story-input'])).toMatchObject({ update: false, narrativeTarget: 8000, roomChars: 8000, condenseChars: 0 });
// The target is an aim, not a cap: a story between it and the cap is recorded.
const story = `${'r'.repeat(1199)}\n\n## Oct 26: shipped\n${'a'.repeat(3980)}\n\n## Oct 27: in progress\n${'b'.repeat(4800)}`;
run(['record-story', write('s.json', { narrative: story })], NOW + 1000);
review(60, NOW + 2000);
// Past the target, there is no room to add, and every part over its budget is named, the recap and the
// chapter still in progress included.
expect(run(['story-input'])).toMatchObject({ update: true, previousNarrativeChars: story.length, roomChars: 0, condenseChars: story.length - 8000, mergeOldestChapters: 0,
previousParts: [
{ part: 'recap', chars: 1201, budgetChars: 800, overBudgetChars: 401 },
{ part: 'Oct 26: shipped', chars: 4001, budgetChars: 3600, overBudgetChars: 401 },
{ part: 'Oct 27: in progress', chars: 4823, budgetChars: 3600, overBudgetChars: 1223 },
] });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a refresh is needed for due reviews, stale goals or unplaced requests, and not otherwise', async () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
const focus = focusFixture(database);
const { run, write } = cliRunner(dir, database, focus.save);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toEqual({ due: 0, ungrouped: 3, goalsStale: true, unplaced: 0, otherChanged: false, subFocusDue: 0, subFocusFailed: 0, needed: true });
saveGoals(database, new Date(NOW - 2 * DAY).toISOString());
run(['apply', write('decisions.json', { groups: [{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards" in repo/tree' }] }, { title: 'Pricing page', conversations: [key('c')] }] })]);
// With no focus areas at all, every request still needs a place (Other, or an area the step proposes).
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toEqual({ due: 2, ungrouped: 0, goalsStale: true, unplaced: 2, otherChanged: false, subFocusDue: 0, subFocusFailed: 0, needed: true });
for (const groupId of [groupIdFor(key('a')), groupIdFor(key('c'))]) {
run(['record-progress', write('review.json', { groupId, state: 'in-progress', percent: 50, summary: 'Under way.', reviewBasis: run(['show', groupId]).reviewBasis })]);
}
await run(['record-focus', write('focus.json', { placements: [{ anchor: key('a'), focusAreaId: 'other', evidence: 'Cards.' }, { anchor: key('c'), focusAreaId: 'other', evidence: 'Pricing.' }], proposals: [] })]);
// Two requests newly in Other: the proposal pass is due until it has looked at them.
expect(refreshNeeds({ dir, database, now: NOW - 2 * DAY + 1000, localDeviceId: '' })).toMatchObject({ otherChanged: true, needed: true });
await run(['record-focus', '--other', write('other.json', { placements: [], proposals: [] })]);
expect(refreshNeeds({ dir, database, now: NOW - 2 * DAY + 1000, localDeviceId: '' })).toEqual({ due: 0, ungrouped: 0, goalsStale: false, unplaced: 0, otherChanged: false, subFocusDue: 0, subFocusFailed: 0, needed: false });
expect(run(['refresh-needs'], NOW - 2 * DAY + 1000).needed).toBe(false);
const before = ledgerSignature(dir);
writeFileSync(join(dir, 'refresh.json'), JSON.stringify({ state: 'running' }));
expect(ledgerSignature(dir)).not.toBe(before);
expect(readLedger(dir).refresh).toEqual({ state: 'running' });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('readings: each review adds one dated percent, deduplicated by time and capped', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[], now = NOW) => { runCli(argv, { dir, database, now, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const decisions = join(dir, 'decisions.json');
writeFileSync(decisions, JSON.stringify({ groups: [{ title: 'Pricing page', conversations: [key('c')] }] }));
run(['apply', decisions]);
const groupId = groupIdFor(key('c'));
const review = (percent: number, now: number) => {
const file = join(dir, 'review.json');
writeFileSync(file, JSON.stringify({ groupId, state: 'in-progress', percent, summary: 'Under way.', reviewBasis: run(['show', groupId], now).reviewBasis }));
return run(['record-progress', file], now);
};
expect(review(30, NOW).readings).toBe(1);
expect(review(55, NOW + DAY).readings).toBe(2);
expect(review(60, NOW + DAY).readings).toBe(2);
expect(readLedger(dir).progress[groupId].readings).toEqual([{ at: new Date(NOW).toISOString(), percent: 30 }, { at: new Date(NOW + DAY).toISOString(), percent: 60 }]);
let readings = readLedger(dir).progress[groupId];
for (let index = 0; index < MAX_READINGS + 5; index++) readings = { readings: appendReading(readings, { at: new Date(NOW + (index + 2) * DAY).toISOString(), percent: index }) };
expect(readings.readings.length).toBe(MAX_READINGS);
expect(readings.readings.at(-1).percent).toBe(MAX_READINGS + 4);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
});
describe('sub focuses', () => {
const RELEASES = ['a', 'b', 'c', 'd', 'e'];
/** Five one-conversation requests a–e, all placed by the router in the kept area Releases. */
async function releases(dir: string, sessions = RELEASES) {
const database = fixtureDatabase();
const session = database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)');
const prompt = database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)');
for (const [id, name, ask] of [[4, 'd', 'Create the v16.0.0 announcement image'], [5, 'e', 'Create the v15.18.3 announcement image'], [6, 'f', 'Create the v15.18.2 announcement image']] as const) {
session.run(id, 'claude', name, `m${id}`, 'repo/tree', ask, NOW - DAY);
prompt.run(id, 1, ask, NOW - DAY);
}
const focus = focusFixture(database);
focus.area('fa_releases', 'Releases', 'kept');
const { run, write } = cliRunner(dir, database, focus.save);
run(['apply', write('d.json', { groups: [...sessions, 'f'].map((name) => ({ title: `Request ${name}`, conversations: [key(name)] })) })]);
await run(['record-focus', write('f.json', { placements: [...sessions, 'f'].map((name) => ({ anchor: key(name), focusAreaId: name === 'f' ? 'other' : 'fa_releases', evidence: 'A release task.' })), proposals: [] })]);
return { database, focus, run, write };
}
/** The ledger requests My Work serves, built the way the read worker builds them: the agent-written exclusions applied
* (applySharedProjection), then buildHumanRequests over the given agents' work. */
function servedGroupIds(database: Database, dir: string, agents: any[] = []) {
const records = {
sessions: database.prepare('SELECT id, project, platform_source, content_session_id, memory_session_id, user_prompt, started_at_epoch FROM sdk_sessions').all(),
prompts: database.prepare('SELECT id, session_db_id, prompt_number, prompt_text, created_at_epoch FROM user_prompts').all(),
};
const projected = applySharedProjection(database, null, { ledger: readLedger(dir), records });
return new Set(buildHumanRequests({ agents, recentActivity: [] }, projected.records, { ledger: projected.ledger, localFiles: false }).humanRequests.map((request: any) => request.groupId).filter(Boolean));
}
/** The setup scan judges these conversations' prompts agent-written (the whole list, replacing any earlier one). */
function excludeAsAgentWritten(database: Database, dir: string, ...sessions: string[]) {
const promptOf = (session: string) => (database.prepare('SELECT p.id FROM user_prompts p JOIN sdk_sessions s ON s.id = p.session_db_id WHERE s.content_session_id = ?').get(session) as { id: number }).id;
writeFileSync(join(dir, AGENT_WRITTEN_PROMPTS_FILE), JSON.stringify({ promptIds: sessions.map(promptOf) }));
}
/** A pass hash as it was recorded before passes counted only shown requests: over every request placed in the area. */
const hashOverPlaced = (sessions: string[]) => createHash('sha256').update(JSON.stringify(sessions.map(key).sort())).digest('hex').slice(0, 16);
it('the validator refuses unknown ids and double membership, and ungroups a group of one', async () => {
const dir = ledgerDir();
try {
const { run } = await releases(dir);
const input = run(['sub-focus-input', '--area', 'fa_releases']);
expect(input).toMatchObject({ area: { focusAreaId: 'fa_releases', name: 'Releases', goal: 'Make Releases good.' }, subFocuses: [], passHash: expect.stringMatching(/^[0-9a-f]{16}$/) });
expect(input.requests.map((request: any) => [request.anchor, request.title, request.summary])).toEqual(RELEASES.map((name) => [key(name), `Request ${name}`, null]));
const images = { name: 'Announcement images', anchors: [key('d'), key('e')] };
const answer = (change: Record<string, unknown>) => ({ groups: [], newGroups: [images], ungrouped: [key('a'), key('b'), key('c')], ...change });
expect(() => validateSubFocusAnswer(answer({ ungrouped: [key('a'), key('b'), key('c'), key('zzz')] }), input)).toThrow(/ungrouped\[3\] names .+, which was not asked about/);
expect(() => validateSubFocusAnswer(answer({ groups: [{ subFocusId: 'sf_nope', anchors: [key('a')] }], ungrouped: [key('b'), key('c')] }), input)).toThrow(/"sf_nope", which is not a listed sub focus/);
expect(() => validateSubFocusAnswer(answer({ ungrouped: [key('a'), key('b'), key('c'), key('d')] }), input)).toThrow(/places .+ a second time; a request sits in one sub focus/);
expect(() => validateSubFocusAnswer(answer({ ungrouped: [key('a'), key('b')] }), input)).toThrow(/Decide every request asked about.+missing/);
expect(() => validateSubFocusAnswer({ groups: [], newGroups: [] }, input)).toThrow(/needs a ungrouped array/);
// A group of one is not a group: that request is left ungrouped, and the rest of the answer stands.
const body = validateSubFocusAnswer(answer({ newGroups: [{ name: 'Lonely', anchors: [key('a')] }, images], ungrouped: [key('b'), key('c')] }), input);
expect(body.subFocus.newSubFocuses).toEqual([{ name: 'Announcement images', anchorConversationKeys: [key('d'), key('e')] }]);
expect(body.subFocus.placements).toEqual([key('a'), key('b'), key('c')].map((anchor) => ({ anchorConversationKey: anchor, subFocusId: null })));
expect(body.subFocus.passHash).toBe(input.passHash);
expect(validateSubFocusAnswer(answer({}), input, { recordPass: false }).subFocus.passHash).toBeNull();
// The retry keeps what it can: an unknown request and a second mention are dropped, and a left-out request is ungrouped.
const coerced = validateSubFocusAnswer(answer({ groups: [{ subFocusId: 'sf_nope', anchors: [key('a')] }], ungrouped: [key('zzz'), key('b'), key('d')] }), input, { coerce: true });
expect(coerced.subFocus.newSubFocuses).toEqual([{ name: 'Announcement images', anchorConversationKeys: [key('d'), key('e')] }]);
expect(coerced.subFocus.placements.map((placement) => placement.anchorConversationKey).sort()).toEqual([key('a'), key('b'), key('c')].sort());
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('record-sub-focus saves through the worker; an area is due again only when its set of requests changes, and an area of 3 never', async () => {
const dir = ledgerDir();
try {
const { database, focus, run, write } = await releases(dir);
expect(run(['sub-focus-input'])).toEqual({ due: [{ focusAreaId: 'fa_releases', name: 'Releases', requests: 5 }], failed: [] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 1, needed: true });
const rowsBefore = focus.rows();
await expect(run(['record-sub-focus', '--area', 'fa_releases', write('s0.json', { groups: [], newGroups: [], ungrouped: [key('a')] })])).rejects.toThrow(/Decide every request/);
expect(() => runCli(['record-sub-focus', write('s0b.json', {})], { dir, database, now: NOW, print: () => {}, localDeviceId: '', saveFocus: focus.save })).toThrow(/needs --area/);
expect(focus.rows()).toBe(rowsBefore);
expect(await run(['record-sub-focus', '--area', 'fa_releases', write('s1.json', { groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] })]))
.toEqual({ grouped: 2, ungrouped: 3, newSubFocuses: 1 });
const saved = readFocus(database, { localDeviceId: '' });
const subFocusId = saved.focusAreas[0].subFocuses[0].subFocusId;
expect(saved.focusAreas[0].subFocuses).toEqual([{ subFocusId, name: 'Announcement images', decidedBy: 'system' }]);
expect(subFocusId).toMatch(/^sf_[0-9a-f]{12}$/);
expect([key('d'), key('e')].map((anchor) => saved.subFocusIdByAnchor.get(anchor))).toEqual([subFocusId, subFocusId]);
// The pass is recorded: a quiet refresh asks nothing, and a new review does not change the set.
expect(run(['sub-focus-input']).due).toEqual([]);
run(['record-progress', write('r.json', { groupId: groupIdFor(key('a')), state: 'in-progress', percent: 40, summary: 'Under way.', reviewBasis: run(['show', groupIdFor(key('a'))]).reviewBasis })]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 0 });
// The next pass keeps the group with its members, and lists the requests left ungrouped to decide again.
const next = run(['sub-focus-input', '--area', 'fa_releases']);
expect(next.subFocuses).toEqual([{ subFocusId, name: 'Announcement images', members: [key('d'), key('e')].map((anchor, index) => ({ anchor, title: `Request ${['d', 'e'][index]}`, summary: null })) }]);
expect(next.requests.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c')]);
expect(next.requests[0].summary).toBe('Under way.');
// A request the owner placed is the owner's: never listed to decide, wherever they put it.
focus.insert(subFocusPlacementRowFields({ anchorConversationKey: key('a'), subFocusId, focusAreaId: 'fa_releases', placedBy: 'owner' }));
focus.insert(subFocusPlacementRowFields({ anchorConversationKey: key('b'), subFocusId: null, focusAreaId: 'fa_releases', placedBy: 'owner' }));
const owned = run(['sub-focus-input', '--area', 'fa_releases']);
expect(owned.requests.map((request: any) => request.anchor)).toEqual([key('c')]);
expect(owned.subFocuses[0].members.map((member: any) => member.anchor)).toEqual([key('a'), key('d'), key('e')]);
// A request moves into the area: its set changed, so it is due again.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input']).due).toEqual([{ focusAreaId: 'fa_releases', name: 'Releases', requests: 6 }]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).subFocusDue).toBe(1);
expect(() => run(['sub-focus-input', '--area', 'fa_nope'])).toThrow(/not a kept focus area/);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('the step counts only the requests My Work shows: one whose every ask is agent-written is never asked about', async () => {
const dir = ledgerDir();
try {
const { database, run } = await releases(dir);
const served = () => servedGroupIds(database, dir);
const exclude = (...sessions: string[]) => excludeAsAgentWritten(database, dir, ...sessions);
expect(shownGroupIds(readLedger(dir), database)).toEqual(served());
const before = run(['sub-focus-input', '--area', 'fa_releases']);
// The setup scan judged e's only ask agent-written after e was grouped: My Work shows no card for it.
exclude('e');
expect(served().has(groupIdFor(key('e')))).toBe(false);
expect(shownGroupIds(readLedger(dir), database)).toEqual(served());
expect(run(['sub-focus-input'])).toEqual({ due: [{ focusAreaId: 'fa_releases', name: 'Releases', requests: 4 }], failed: [] });
const after = run(['sub-focus-input', '--area', 'fa_releases']);
expect(after.requests.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c'), key('d')]);
// The pass looks at a different set, so it records a different hash.
expect(after.passHash).not.toBe(before.passHash);
// An answer naming the hidden request is refused: it was not asked about.
expect(() => validateSubFocusAnswer({ groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] }, after)).toThrow(/not asked about/);
// A request whose conversation is not recorded on this computer still shows, from the first ask the ledger stored.
database.prepare("DELETE FROM user_prompts WHERE session_db_id = (SELECT id FROM sdk_sessions WHERE content_session_id = 'c')").run();
database.prepare("DELETE FROM sdk_sessions WHERE content_session_id = 'c'").run();
expect(served().has(groupIdFor(key('c')))).toBe(true);
expect(shownGroupIds(readLedger(dir), database)).toEqual(served());
// Three shown requests cannot make two groups of two: the area is not asked, though the ledger places five in it.
exclude('d', 'e');
expect(shownGroupIds(readLedger(dir), database)).toEqual(served());
expect(run(['sub-focus-input']).due).toEqual([]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).subFocusDue).toBe(0);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('shownGroupIds counts two kinds of request My Work shows no card for: asks carrying explicit request ids, and another root\'s only ask', async () => {
const dir = ledgerDir();
try {
const { database } = await releases(dir);
expect(shownGroupIds(readLedger(dir), database)).toEqual(servedGroupIds(database, dir));
// Explicit request ids: an agent recorded a's work with a request_id. My Work files it under an explicit-request
// card and makes no card for the request a anchors; shownGroupIds reads no work-state, so it counts that request.
const agents = [{ id: 'agent-a', label: 'Agent', sessionId: 1, work: [{ id: 'work-a', requestId: 'release-cards', requestText: 'Build the release cards', lastUpdateEpoch: NOW, sourceRefs: [] }], activity: [] }];
expect(servedGroupIds(database, dir, agents).has(groupIdFor(key('a')))).toBe(false);
expect(shownGroupIds(readLedger(dir), database).has(groupIdFor(key('a')))).toBe(true);
// Another root: a request with no stored root, whose anchor x (repo/tree) has no ask left and whose only asking
// member y is in another root. My Work turns y away from the request and gives y a card of its own.
database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)').run(7, 'claude', 'x', 'm7', 'repo/tree', 'Plan the docs site', NOW - DAY);
database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)').run(8, 'claude', 'y', 'm8', 'other/site', 'Write the docs landing page', NOW - DAY);
for (const [id, ask] of [[7, 'Plan the docs site'], [8, 'Write the docs landing page']] as const) database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)').run(id, 1, ask, NOW - DAY);
const ledger = JSON.parse(readFileSync(join(dir, 'request-groups.json'), 'utf8'));
const docs = groupIdFor(key('x'));
ledger.groups[docs] = { title: 'Docs site', anchor: key('x'), links: [] };
ledger.conversations[key('x')] = docs;
ledger.conversations[key('y')] = docs;
writeFileSync(join(dir, 'request-groups.json'), JSON.stringify(ledger));
excludeAsAgentWritten(database, dir, 'x');
expect(servedGroupIds(database, dir).has(docs)).toBe(false);
expect(shownGroupIds(readLedger(dir), database).has(docs)).toBe(true);
// Every other request is counted alike.
const shown = shownGroupIds(readLedger(dir), database);
shown.delete(docs);
expect(shown).toEqual(servedGroupIds(database, dir));
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('an upgrade alone never asks an area again: a hash recorded over every placed request still names an answered set', async () => {
const dir = ledgerDir();
try {
const { database, focus, run, write } = await releases(dir);
// Answered while all five requests showed: the pass hash then covers every placed request, as before passes
// counted only shown ones.
expect(run(['sub-focus-input', '--area', 'fa_releases']).passHash).toBe(hashOverPlaced(RELEASES));
await run(['record-sub-focus', '--area', 'fa_releases', write('s.json', { groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] })]);
// e has no card any more, so the pass would now count four requests and name another hash. Nothing was placed in
// the area or moved out, so it is not asked again: no paid question for an upgrade or a rescan alone.
excludeAsAgentWritten(database, dir, 'e');
expect(run(['sub-focus-input', '--area', 'fa_releases']).passHash).not.toBe(hashOverPlaced(RELEASES));
expect(run(['sub-focus-input'])).toEqual({ due: [], failed: [] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 0, subFocusFailed: 0 });
// A request moved into the area changes its set: it is asked, about the requests that show.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input'])).toEqual({ due: [{ focusAreaId: 'fa_releases', name: 'Releases', requests: 5 }], failed: [] });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('an upgrade alone never turns a failed pass into a due one: a failed hash over every placed request still names its set', async () => {
const dir = ledgerDir();
try {
const { database, focus, run } = await releases(dir);
const releasesArea = { focusAreaId: 'fa_releases', name: 'Releases', requests: 4 };
// The last pass failed while all five showed (refresh-task.ts records the hash it asked about).
await focus.save({ placements: [], proposals: [], subFocus: { focusAreaId: 'fa_releases', newSubFocuses: [], placements: [], passHash: null, failedPassHash: hashOverPlaced(RELEASES) } });
excludeAsAgentWritten(database, dir, 'e');
// Still the failed set: no scheduled refresh pays for the same question again; the owner's Refresh asks it.
expect(run(['sub-focus-input'])).toEqual({ due: [], failed: [releasesArea] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 0, subFocusFailed: 1 });
// A request moved into the area is a new set: due again.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input'])).toEqual({ due: [{ ...releasesArea, requests: 5 }], failed: [] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 1, subFocusFailed: 0 });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a sub focus left with one request is no group: the router\'s member is decided again, and the owner\'s stays', async () => {
const dir = ledgerDir();
try {
const { focus, run, write } = await releases(dir);
await run(['record-sub-focus', '--area', 'fa_releases', write('s1.json', { groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] })]);
const { subFocusId } = run(['sub-focus-input', '--area', 'fa_releases']).subFocuses[0];
// The owner moves d out of the sub focus: e is left alone in it, which is not a group.
focus.insert(subFocusPlacementRowFields({ anchorConversationKey: key('d'), subFocusId: null, focusAreaId: 'fa_releases', placedBy: 'owner' }));
const alone = run(['sub-focus-input', '--area', 'fa_releases']);
expect(alone.subFocuses).toEqual([{ subFocusId, name: 'Announcement images', members: [] }]);
expect(alone.requests.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c'), key('e')]);
expect(alone.alreadyUngrouped).toEqual([key('a'), key('b'), key('c')]);
// Put back alone it stays ungrouped (a group of one); with another request it holds again.
const back = (anchors: string[]) => validateSubFocusAnswer({ groups: [{ subFocusId, anchors }], newGroups: [], ungrouped: [key('a'), key('b'), key('c'), key('e')].filter((anchor) => !anchors.includes(anchor)) }, alone).subFocus.placements;
expect(back([key('e')])).toEqual([{ anchorConversationKey: key('e'), subFocusId: null }]);
expect(back([key('e'), key('a')])).toEqual([{ anchorConversationKey: key('e'), subFocusId }, { anchorConversationKey: key('a'), subFocusId }]);
// A member the owner placed stays where the owner put it, even alone.
focus.insert(subFocusPlacementRowFields({ anchorConversationKey: key('e'), subFocusId, focusAreaId: 'fa_releases', placedBy: 'owner' }));
const owned = run(['sub-focus-input', '--area', 'fa_releases']);
expect(owned.subFocuses[0].members.map((member: any) => member.anchor)).toEqual([key('e')]);
expect(owned.requests.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c')]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('leaving an already ungrouped request ungrouped writes no row; only a changed decision and the pass are saved', async () => {
const dir = ledgerDir();
try {
const { database, focus, run, write } = await releases(dir);
await run(['record-sub-focus', '--area', 'fa_releases', write('s1.json', { groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] })]);
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
const input = run(['sub-focus-input', '--area', 'fa_releases']);
expect(input.requests.map((request: any) => request.anchor)).toEqual([key('a'), key('b'), key('c'), key('f')]);
expect(input.alreadyUngrouped).toEqual([key('a'), key('b'), key('c')]);
const answer = { groups: [], newGroups: [], ungrouped: [key('a'), key('b'), key('c'), key('f')] };
expect(validateSubFocusAnswer(answer, input).subFocus.placements).toEqual([{ anchorConversationKey: key('f'), subFocusId: null }]);
const rowsBefore = focus.rows();
await run(['record-sub-focus', '--area', 'fa_releases', write('s2.json', answer)]);
// f's placement and the pass row.
expect(focus.rows() - rowsBefore).toBe(2);
expect(run(['sub-focus-input']).due).toEqual([]);
expect(readFocus(database, { localDeviceId: '' }).subFocusPlacementFor(key('a'), 'fa_releases')).toEqual({ placedBy: 'router', subFocusId: null });
// Grouping one of them now is a change, and is saved.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'other', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
const next = run(['sub-focus-input', '--area', 'fa_releases']);
const regrouped = validateSubFocusAnswer({ groups: [], newGroups: [{ name: 'Docs', anchors: [key('a'), key('b')] }], ungrouped: [key('c')] }, next).subFocus;
expect(regrouped.newSubFocuses).toEqual([{ name: 'Docs', anchorConversationKeys: [key('a'), key('b')] }]);
expect(regrouped.placements).toEqual([]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('refuses a new group named like a listed sub focus, and the retry puts its requests in that sub focus', async () => {
const dir = ledgerDir();
try {
const { focus, run, write } = await releases(dir);
await run(['record-sub-focus', '--area', 'fa_releases', write('s1.json', { groups: [], newGroups: [{ name: 'Announcement images', anchors: [key('d'), key('e')] }], ungrouped: [key('a'), key('b'), key('c')] })]);
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
const input = run(['sub-focus-input', '--area', 'fa_releases']);
const { subFocusId } = input.subFocuses[0];
const answer = { groups: [], newGroups: [{ name: ' announcement IMAGES ', anchors: [key('f')] }], ungrouped: [key('a'), key('b'), key('c')] };
expect(() => validateSubFocusAnswer(answer, input)).toThrow(`newGroups[0] is named "announcement IMAGES", like the listed sub focus ${subFocusId}. Put its requests in "groups" with "subFocusId": "${subFocusId}" instead of making a second one.`);
const coerced = validateSubFocusAnswer(answer, input, { coerce: true });
expect(coerced.subFocus.newSubFocuses).toEqual([]);
expect(coerced.subFocus.placements).toEqual([{ anchorConversationKey: key('f'), subFocusId }]);
// A different name is a new sub focus as before.
expect(validateSubFocusAnswer({ ...answer, newGroups: [{ name: 'Announcement copy', anchors: [key('f'), key('a')] }], ungrouped: [key('b'), key('c')] }, input).subFocus.newSubFocuses).toEqual([{ name: 'Announcement copy', anchorConversationKeys: [key('f'), key('a')] }]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('the retry names each new group it dropped, so the refresh can report it; a group of one the model wrote is not a drop', async () => {
const dir = ledgerDir();
try {
const { run } = await releases(dir);
const input = run(['sub-focus-input', '--area', 'fa_releases']);
const answer = { groups: [], ungrouped: [], newGroups: [
{ name: 'x'.repeat(81), anchors: [key('a'), key('b')] },
{ name: 'Announcement images', anchors: [key('d'), key('zzz')] },
{ name: 'Lonely', anchors: [key('c')] },
] };
expect(() => validateSubFocusAnswer(answer, input)).toThrow(/newGroups\[0\]\.name/);
const dropped = new Set<string>();
const body = validateSubFocusAnswer(answer, input, { coerce: true, droppedNewGroups: dropped });
expect([...dropped]).toEqual(['newGroups[0]', 'newGroups[1]']);
expect(body.subFocus.newSubFocuses).toEqual([]);
// Nothing is lost: every listed request is recorded ungrouped.
expect(body.subFocus.placements.map((placement) => placement.anchorConversationKey).sort()).toEqual(RELEASES.map(key).sort());
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a failed pass keeps its area from being due until its set of requests changes, and an answered pass clears it', async () => {
const dir = ledgerDir();
try {
const { database, focus, run, write } = await releases(dir);
const releasesArea = { focusAreaId: 'fa_releases', name: 'Releases', requests: 5 };
const { passHash } = run(['sub-focus-input', '--area', 'fa_releases']);
// The refresh records a failed pass on the requests it looked at (refresh-task.ts).
await focus.save({ placements: [], proposals: [], subFocus: { focusAreaId: 'fa_releases', newSubFocuses: [], placements: [], passHash: null, failedPassHash: passHash } });
expect(run(['sub-focus-input'])).toEqual({ due: [], failed: [releasesArea] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 0, subFocusFailed: 1 });
// Not an answered pass: nothing was grouped, and the pass record names no set.
expect(readFocus(database, { localDeviceId: '' }).subFocusPassHashes.has('fa_releases')).toBe(false);
// A request joins the area: a new set, so it is due again.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input'])).toEqual({ due: [{ ...releasesArea, requests: 6 }], failed: [] });
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' })).toMatchObject({ subFocusDue: 1, subFocusFailed: 0 });
// That pass is answered, which clears the failure: moving the request out again is a change, so the area is due.
await run(['record-sub-focus', '--area', 'fa_releases', write('s.json', { groups: [], newGroups: [], ungrouped: [...RELEASES, 'f'].map(key) })]);
expect(run(['sub-focus-input'])).toEqual({ due: [], failed: [] });
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'other', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input'])).toEqual({ due: [releasesArea], failed: [] });
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('an area with fewer than four placed requests is never due, and a suggested area is never grouped', async () => {
const dir = ledgerDir();
try {
const { database, run, focus } = await releases(dir, ['a', 'b', 'c']);
expect(run(['sub-focus-input']).due).toEqual([]);
expect(refreshNeeds({ dir, database, now: NOW, localDeviceId: '' }).subFocusDue).toBe(0);
// A fourth request makes two groups of two possible.
focus.insert(placementRowFields({ anchorConversationKey: key('f'), focusAreaId: 'fa_releases', placedBy: 'owner', evidence: 'Moved by you in My Work.' }));
expect(run(['sub-focus-input']).due.map((area: any) => area.requests)).toEqual([4]);
// The same area back among suggestions: not kept, so not grouped.
focus.area('fa_releases', 'Releases', 'suggested', 'owner');
expect(run(['sub-focus-input']).due).toEqual([]);
} finally { rmSync(dir, { recursive: true, force: true }); }
});
});
describe('request titles', () => {
it('a title is still the placeholder when it is the opening ask copied, in any case or with a closing period', () => {
expect(placeholderTitleFromAsk('figure it out')).toBe('figure it out');
expect(placeholderTitleFromAsk(null)).toBe('Untitled request');
expect(hasPlaceholderTitle({ title: 'Figure it out.', anchorAsk: { text: 'figure it out' } })).toBe(true);
expect(hasPlaceholderTitle({ title: 'Fix the checkout page loading error', anchorAsk: { text: 'figure it out' } })).toBe(false);
// Words the ask starts with are a copy too, wherever a grouping answer ended its first sentence, with or without markdown.
expect(hasPlaceholderTitle({ title: 'check the status; the deploy looked stuck', anchorAsk: { text: 'check the status; the deploy looked stuck since noon' } })).toBe(true);
expect(hasPlaceholderTitle({ title: 'look at `refresh-task.ts` and figure it out', anchorAsk: { text: 'look at `refresh-task.ts` and figure it out' } })).toBe(true);
expect(hasPlaceholderTitle({ title: 'hmm let us look at the refresh', anchorAsk: { text: 'hmm\nlet us look at the refresh task' } })).toBe(true);
expect(hasPlaceholderTitle({ title: 'Release cards for the launch page', anchorAsk: { text: 'Build the release cards' } })).toBe(false);
// The judge titles from the ask as grouping-input shows it (400 characters), so a GOAL line past that is not the placeholder.
const longAsk = `${'Context about the release. '.repeat(16)}\nGOAL: ship the release cards`;
expect(placeholderTitleFromAsk(longAsk)).toBe('Context about the release.');
expect(hasPlaceholderTitle({ title: 'Context about the release.', anchorAsk: { text: longAsk } })).toBe(true);
});
it('naming round trip: only requests still titled with their ask are listed, with their review, and each is named once', () => {
const dir = ledgerDir();
try {
const database = fixtureDatabase();
let output: any;
const run = (argv: string[]) => { runCli(argv, { dir, database, now: NOW, print: (value: unknown) => { output = value; }, localDeviceId: '' }); return output; };
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
// The card request has a written title; the pricing request still shows its ask, as the judge leaves it.
run(['apply', write('decisions.json', { groups: [
{ title: 'Release cards', conversations: [key('a'), key('b')], links: [{ kind: 'shared-work-list', conversations: [key('a'), key('b')], evidence: 'work list "release-cards"' }] },
{ title: placeholderTitleFromAsk('Write the pricing page'), conversations: [key('c')] },
] })]);
const pricing = groupIdFor(key('c'));
run(['record-progress', write('review.json', { groupId: pricing, state: 'in-progress', percent: 40, summary: 'Pricing page drafted with three plans.', reviewBasis: run(['show', pricing]).reviewBasis })]);
const input = run(['title-input']);
expect(input).toMatchObject({ remaining: 0, requests: [{ groupId: pricing, title: 'Write the pricing page', summary: 'Pricing page drafted with three plans.', conversationAsks: ['Write the pricing page'] }] });
expect(input.requests).toHaveLength(1);
// The ask copied again, or a request the ledger does not hold, is refused before anything is written.
const before = readFileSync(join(dir, 'request-groups.json'), 'utf8');
expect(() => run(['record-titles', write('titles.json', { titles: [{ groupId: pricing, title: 'write the pricing page.' }] })])).toThrow(/repeats the owner's ask/);
expect(() => run(['record-titles', write('titles.json', { titles: [{ groupId: pricing, title: 'Write the pricing' }] })])).toThrow(/repeats the owner's ask/);
expect(() => run(['record-titles', write('titles.json', { titles: [{ groupId: 'g_000000000000', title: 'Pricing page with three plans' }] })])).toThrow(/unknown group/);
expect(readFileSync(join(dir, 'request-groups.json'), 'utf8')).toBe(before);
expect(run(['record-titles', write('titles.json', { titles: [{ groupId: pricing, title: 'Pricing page with three plans' }] })])).toEqual({ titled: 1, kept: 0 });
expect(readLedger(dir).groups.groups[pricing].title).toBe('Pricing page with three plans');
expect(run(['title-input']).requests).toEqual([]);
// A late answer for a request named meanwhile (another device, a second run) keeps the written title.
expect(run(['record-titles', write('titles.json', { titles: [{ groupId: pricing, title: 'Three-plan pricing page' }] })])).toEqual({ titled: 0, kept: 1 });
expect(readLedger(dir).groups.groups[pricing].title).toBe('Pricing page with three plans');
expect(readLedger(dir).groups.groups[groupIdFor(key('a'))].title).toBe('Release cards');
} finally { rmSync(dir, { recursive: true, force: true }); }
});
it('a naming answer names every listed request once; the refresh\'s retry drops what it would refuse', () => {
const input = { requests: [{ groupId: 'g_000000000001', title: 'figure it out', firstAsk: 'figure it out' }, { groupId: 'g_000000000002', title: 'check the status', firstAsk: 'check the status' }] };
const named = (title1: string, title2: string) => ({ titles: [{ groupId: 'g_000000000001', title: title1 }, { groupId: 'g_000000000002', title: title2 }] });
expect(validateTitleAnswer(named('Fix the checkout page loading error', 'Status of the v16 release'), input).titles.map((entry) => entry.title))
.toEqual(['Fix the checkout page loading error', 'Status of the v16 release']);
expect(() => validateTitleAnswer({ titles: [{ groupId: 'g_000000000001', title: 'Fix the checkout page loading error' }] }, input)).toThrow(/missing g_000000000002/);
expect(() => validateTitleAnswer(named('Figure it out.', 'Status of the v16 release'), input)).toThrow(/titles\[0\]\.title repeats the owner's ask/);
expect(() => validateTitleAnswer(named('Figure it', 'Status of the v16 release'), input)).toThrow(/titles\[0\]\.title repeats the owner's ask/);
expect(() => validateTitleAnswer({ titles: [...named('A', 'B').titles, { groupId: 'g_000000000003', title: 'C' }] }, input)).toThrow(/not asked about/);
expect(() => validateTitleAnswer({ titles: [...named('A', 'B').titles, { groupId: 'g_000000000001', title: 'C' }] }, input)).toThrow(/a second time/);
expect(() => validateTitleAnswer(named('x'.repeat(121), 'B'), input)).toThrow(/must be 1–120/);
// On the retry a refused title is dropped and its request keeps the placeholder until a later run.
expect(validateTitleAnswer(named('figure it out', 'Status of the v16 release'), input, { coerce: true }))
.toEqual({ titles: [{ groupId: 'g_000000000002', title: 'Status of the v16 release' }] });
});
});
function saveGoals(database: Database, generatedAt: string) {
const write = database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch) VALUES (?, ?, ?, ?)');
write.run('owner', 'owner-goals', JSON.stringify({ human_summary: 'Ship the cards.', generated_at: generatedAt }), 1);
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Focus area: Ship cards', status: 'todo', goal_kind: 'focus-area', rank: 1, title: 'Ship cards', evidence: '2026-10-01 10:00 | ship the cards | today' }), 2);
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Ask: Old thing', status: 'todo', goal_kind: 'ask', rank: 1, title: 'Old thing' }), 3);
write.run('owner', 'owner-goals', JSON.stringify({ task: 'Ask: Old thing', status: 'dropped' }), 4);
write.run('owner', 'owner-goals/2026-09-01', JSON.stringify({ task: 'Focus area: History', status: 'done', title: 'History' }), 5);
}
/** My Focus rows in the fixture database, written the way the worker writes them (routerFocusRows for the focus step). */
function focusFixture(database: Database) {
database.exec('ALTER TABLE work_state_entries ADD COLUMN origin_device_id TEXT');
let at = 1000;
const insertRow = database.prepare('INSERT INTO work_state_entries (project, list_name, fields, created_at_epoch, origin_device_id) VALUES (?, ?, ?, ?, ?)');
const insert = (fields: Record<string, unknown>, device: string | null = null) => { insertRow.run('home', 'my-focus', JSON.stringify(fields), at++, device); };
return {
insert,
area(focusAreaId: string, name: string, status: 'suggested' | 'kept' | 'dismissed', decidedBy: 'owner' | 'system' = status === 'suggested' ? 'system' : 'owner') {
insert(focusAreaRowFields({ focusAreaId, name, goal: `Make ${name} good.`, about: `Everything about ${name}.`, status, priorityRank: 1, ownerRank: null, source: 'seed', mergedInto: null, evidence: null, decidedBy }));
},
rows: () => (database.prepare("SELECT COUNT(*) AS count FROM work_state_entries WHERE list_name = 'my-focus'").get() as { count: number }).count,
save(body: RouterFocusBody) {
const planned = routerFocusRows(body, readFocusAreas(database, { localDeviceId: '' }));
for (const fields of planned.rows) insert(fields);
return { placed: planned.placed, focusAreaIds: planned.focusAreaIds };
},
};
}
/** The CLI against the fixture; record-focus resolves its output (a refusal rejects). */
function cliRunner(dir: string, database: Database, saveFocus: (body: RouterFocusBody) => { placed: number; focusAreaIds: string[] }) {
let output: any;
const options = (now: number) => ({ dir, database, now, print: (value: unknown) => { output = value; }, saveFocus, localDeviceId: '' });
const run = (argv: string[], now = NOW): any => argv[0] === 'record-focus' || argv[0] === 'record-sub-focus'
? Promise.resolve().then(() => runCli(argv, options(now))).then(() => output)
: (runCli(argv, options(now)), output);
const write = (name: string, value: unknown) => { const path = join(dir, name); writeFileSync(path, JSON.stringify(value)); return path; };
return { run, write };
}