Skip to content

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

117 KB
Raw Blame
// Overall-request ledger. Works backwards from recorded work to the human
// conversations behind it, then stores evidence-backed groups, per-group
// progress reviews and the build story beside My Work's other caches.
// The request-progress skill runs the bundled CLI (request-groups-cli.mjs) with bun:
//
//   bun request-groups.mjs candidates [--days 14] [--project root] [--brief]
//                                                   conversations + deterministic links
//   bun request-groups.mjs grouping-input [--days 14] [--limit 20]
//                                                   undecided conversations of one root + its open requests
//   bun request-groups.mjs judge [--days 14] [--apply]  route every undecided conversation with the judge
//                                                   (code links, then Jev when the install has it); plan only without --apply
//   bun request-groups.mjs apply <file|->            persist group decisions
//   bun request-groups.mjs pending [--days 14] [--limit 48]   groups needing a progress review
//   bun request-groups.mjs show <groupId>           one group's asks, work lists and dates (only new asks when amending)
//   bun request-groups.mjs record-progress <file|-> persist one progress review
//   bun request-groups.mjs title-input [--limit 20]  requests still titled with a copy of their opening ask
//   bun request-groups.mjs record-titles <file|->   persist written titles for those requests
//   bun request-groups.mjs story-input              reviews whose facts changed since the last story (all without one)
//   bun request-groups.mjs record-story <file|->    persist the build story and preferences
//   bun request-groups.mjs dismissed-rules          the words of each rule the owner rejected in My Rules (owner-goals)
//   bun request-groups.mjs focus-input [--limit 20]  focus areas + one batch of requests still to place
//   bun request-groups.mjs focus-input --other       focus areas + the requests in Other, to propose areas from
//   bun request-groups.mjs record-focus [--limit 20 | --other] <file|->
//                                                   place requests and propose areas (saved through the worker)
//   bun request-groups.mjs sub-focus-input           kept areas whose sub focuses are due, and those whose last pass
//                                                   failed on the same requests (asked again only by the owner's Refresh)
//   bun request-groups.mjs sub-focus-input --area <focusAreaId>
//                                                   one area's sub focuses, members and requests to group
//   bun request-groups.mjs record-sub-focus --area <focusAreaId> <file|->
//                                                   group that area's requests into sub focuses (saved through the worker)
//   bun request-groups.mjs refresh-needs [--days 14]  what the automatic refresh would do now
import { createRequire } from 'node:module';
import { createHash } from 'node:crypto';
import { readFileSync, readdirSync, statSync } from 'node:fs';
import { homedir } from 'node:os';
import { join } from 'node:path';
import { conversationKey, copiesOpeningAsk, FOCUS_ASK_CHARS, isConversationKey, isHumanActionRequest, originalFor, placeholderTitleFromAsk, requestText } from './request-projection.mjs';
import { GOAL_KINDS, goalKindOf, OWNER_GOALS_LIST } from './owner-goals.mjs';
import { NO_PROJECT, projectRoot, upgradedGroupRoot, withDerivedProjects } from './session-project.mjs';
import { isOwnerDismissedArea, isPlaceableArea, OTHER_FOCUS_AREA_ID, PROPOSAL_KINDS, readFocus, SUB_FOCUS_MIN_REQUESTS } from './my-focus.mjs';
import { SUB_FOCUS_MIN_CARDS } from './sub-focus-rules.mjs';
import { beforeSharedFileWrite } from './shared-file-hooks.mjs';
import { isClosedWorkStateStatus } from './work-state-status.mjs';
import { readWorkStateRows, reduceWorkState } from './work-state-reduce.mjs';
import { buildRules, MY_RULES_LIST } from './my-rules.mjs';
import { PROGRESS_STATES } from './progress-states.mjs';
import { writeJsonFileAtomic } from '../../shared/atomic-json.js';

const DATA_DIR = process.env.CLAUDE_MEM_DATA_DIR || join(homedir(), '.claude-mem');
export const LEDGER_DIR = join(DATA_DIR, 'work-view');
/** Hook-recorded prompts the setup scan judged agent-written; they never become asks. */
export const AGENT_WRITTEN_PROMPTS_FILE = 'agent-written-prompts.json';
const DAY_MS = 86400000;
/** Goals older than this make the automatic refresh run owner-goals again. */
export const GOALS_STALE_MS = DAY_MS;
// A list touched by many conversations is a shared bucket, not proof of one goal.
const MAX_CONVERSATIONS_PER_LINKING_LIST = 8;
// Finished reviews: grouping lists no request in these states as open, and none of them waits on the owner.
const CLOSED_STATES = new Set(['shipped', 'abandoned']);
export const PREFERENCE_KINDS = ['directive', 'correction', 'praise', 'frustration'];
export const USAGE_LEVELS = ['in-use', 'some-use', 'no-evidence', 'unknown'];
export const VALUE_LEVELS = ['high', 'medium', 'low', 'unclear'];
// `judge` links are written by code (request-judge.mjs): their evidence names the judge and its score.
const LINK_KINDS = ['shared-work-list', 'shared-request-id', 'agent-judgment', 'judge'];
// Each review adds one dated percent; the measured ETA reads the last two.
export const MAX_READINGS = 20;

const iso = (epoch) => Number.isFinite(epoch) && epoch > 0 ? new Date(epoch).toISOString() : null;
export const groupIdFor = (anchorConversationKey) => `g_${createHash('sha256').update(anchorConversationKey).digest('hex').slice(0, 12)}`;

function placeholders(values) { return values.map(() => '?').join(','); }

// Keep bound parameters below SQLite limits even for large history scans.
function queryInChunks(database, values, sqlFor, parametersFor = (chunk) => chunk, chunkSize = 500) {
  const rows = [];
  for (let index = 0; index < values.length; index += chunkSize) {
    const chunk = values.slice(index, index + chunkSize);
    const statement = database.prepare(sqlFor(chunk));
    try {
      for (const row of statement.all(...parametersFor(chunk))) rows.push(row);
    } finally {
      statement.finalize();
    }
  }
  return rows;
}

const SESSION_COLUMNS = 'SELECT id, platform_source, content_session_id, project, user_prompt, started_at_epoch FROM sdk_sessions';

/** The recorded sessions of these conversations. 250 pairs (500 parameters) per query, under SQLite's 999-parameter
 * limit before 3.32. */
function sessionsOf(database, conversationKeys) {
  const pairs = conversationKeys.map((key) => JSON.parse(key).slice(1));
  return queryInChunks(database, pairs, (chunk) => `${SESSION_COLUMNS} WHERE (platform_source, content_session_id) IN (VALUES ${chunk.map(() => '(?, ?)').join(',')})`, (chunk) => chunk.flat(), 250);
}

/** The prompts of these sessions, each as a list by session id. */
function promptsOf(database, sessionIds, { fullAsks = false } = {}) {
  const prompts = queryInChunks(database, [...new Set(sessionIds)], (chunk) => `SELECT id, session_db_id, prompt_number, ${fullAsks ? 'prompt_text' : 'substr(prompt_text, 1, 1200) AS prompt_text'}, created_at_epoch
    FROM user_prompts WHERE session_db_id IN (${placeholders(chunk)})`);
  const bySession = new Map();
  for (const prompt of prompts) {
    if (!bySession.has(prompt.session_db_id)) bySession.set(prompt.session_db_id, []);
    bySession.get(prompt.session_db_id).push(prompt);
  }
  return bySession;
}

/** A conversation's opening human ask once the setup scan's agent-written prompts are left out, and the prompts that are
 * its own. An excluded prompt is never an ask, and the session's stored opening prompt is a copy of its first prompt row,
 * so a rejected first prompt stays rejected. My Work reads asks the same way (applySharedProjection drops the excluded
 * prompts and the rejected opening before buildHumanRequests looks for an ask), so a conversation with no ask here is one
 * My Work shows no card for. */
function openingAsk(session, prompts, excludedPromptIds) {
  const own = prompts.filter((prompt) => !excludedPromptIds?.has(prompt.id));
  const openingRejected = prompts.some((prompt) => excludedPromptIds?.has(prompt.id) && (prompt.prompt_number === 1 || prompt.prompt_text === session.user_prompt));
  return { own, original: conversationKey(session) ? originalFor(openingRejected ? { ...session, user_prompt: null } : session, own) : null };
}

/**
 * The ledger requests My Work shows as cards (buildHumanRequests), as far as sessions and prompts tell: one with a
 * conversation that holds a human ask (openingAsk), and one whose anchor conversation is not recorded on this computer,
 * which My Work shows from the first ask the ledger stored. A request whose every ask the setup scan judged agent-written
 * after it was grouped has no card (32 of the 251 requests on the owner's Mac on 2026-11-27), so no step that counts an
 * area's requests counts it. All 219 shown requests on that Mac matched My Work's cards. My Work also reads work-state,
 * shared records and its load limits, which this does not, so these requests are counted here and have no card there:
 * - Explicit request ids: every asking conversation carries a work-state request_id. My Work files that work under an
 *   explicit-request card, and the request's own card is not made while its anchor is recorded.
 * - Another root: the request's stored root is unknown (none, or the "no project" root) and its only asking conversation
 *   is from another root than the request's. My Work gives that conversation a card of its own.
 * - Shared state and load limits: My Work also counts sessions known only from shared records and skips openings that
 *   shared exclusions name, reads at most 12,000 prompts (agent-view.mjs) and the first session of each conversation.
 *   This reads only this computer's sessions, every prompt, and agentWrittenPromptIds, so either side can count a
 *   request the other does not.
 * tests/work-view/request-groups.test.ts keeps the first two as fixture cases.
 * Reads sessions and prompts only: readCandidates also reads work lists, observations and tool activity, 22 to 38 s
 * over the 533 ledger conversations on that Mac, against 6 ms for these two reads.
 */
export function shownGroupIds(ledger, database) {
  const keys = Object.keys(ledger.groups.conversations).filter(isConversationKey);
  const sessions = sessionsOf(database, keys);
  const prompts = promptsOf(database, sessions.map((session) => session.id));
  const recorded = new Set(), asking = new Set();
  for (const session of sessions) {
    const key = conversationKey(session);
    recorded.add(key);
    if (openingAsk(session, prompts.get(session.id) ?? [], ledger.agentWrittenPromptIds).original) asking.add(key);
  }
  const shown = new Set();
  for (const [key, groupId] of Object.entries(ledger.groups.conversations)) if (asking.has(key)) shown.add(groupId);
  for (const [groupId, group] of Object.entries(ledger.groups.groups)) {
    if (group.anchorAsk && !recorded.has(group.anchor) && !ledger.groups.ignored?.[group.anchor]) shown.add(groupId);
  }
  return shown;
}

// Pass sinceEpoch for a time window, or conversationKeys for specific conversations.
// fullAsks returns every qualifying ask untruncated (for `show`); listings stay short.
// Grouping needs the recent window; ordinary candidate listings keep the opening one.
// excludedPromptIds: hook-recorded prompts the setup scan found an agent wrote (agent-written-prompts.json).
export function readCandidates(database, { sinceEpoch = 0, conversationKeys = null, fullAsks = false, recentAsks = false, excludedPromptIds = null }) {
  const stored = conversationKeys
    ? sessionsOf(database, conversationKeys)
    // Any recent activity counts: a new start, prompt, observation or recorded tool use (a commit, a push, a work-state write).
    : database.prepare(`${SESSION_COLUMNS} WHERE started_at_epoch >= ?
        OR id IN (SELECT DISTINCT session_db_id FROM user_prompts WHERE created_at_epoch >= ?)
        OR id IN (SELECT DISTINCT session_db_id FROM tool_uses WHERE created_at_epoch >= ?)
        OR memory_session_id IN (SELECT DISTINCT memory_session_id FROM observations WHERE created_at_epoch >= ?)`).all(sinceEpoch, sinceEpoch, sinceEpoch, sinceEpoch);
  if (!stored.length) return [];
  // A session started from an agent scratch folder takes the repo its tool calls touched.
  const sessions = withDerivedProjects(database, stored);
  const ids = [...new Set(sessions.map((session) => session.id))];
  const promptsBySession = promptsOf(database, ids, { fullAsks });
  const writes = queryInChunks(database, ids, (chunk) => `SELECT session_db_id, tool_input, created_at_epoch FROM tool_uses
    WHERE tool_name LIKE '%work_state_write%' AND session_db_id IN (${placeholders(chunk)})`);
  const observations = queryInChunks(database, ids, (chunk) => `SELECT s.id AS session_db_id, COUNT(*) AS count, MAX(o.created_at_epoch) AS last_epoch
    FROM observations o JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
    WHERE s.id IN (${placeholders(chunk)}) GROUP BY s.id`);
  const observationsBySession = new Map(observations.map((row) => [row.session_db_id, row]));
  // Work after a review without a new prompt or observation (a commit, a push) still makes the review due again.
  const toolActivity = queryInChunks(database, ids, (chunk) => `SELECT session_db_id, MAX(created_at_epoch) AS last_epoch FROM tool_uses
    WHERE session_db_id IN (${placeholders(chunk)}) GROUP BY session_db_id`);
  const lastToolUseBySession = new Map(toolActivity.map((row) => [row.session_db_id, row.last_epoch ?? 0]));
  const candidates = new Map();
  for (const session of sessions) {
    const key = conversationKey(session);
    const { own, original } = openingAsk(session, promptsBySession.get(session.id) ?? [], excludedPromptIds);
    if (!original) continue;
    own.sort((a, b) => a.created_at_epoch - b.created_at_epoch || a.id - b.id);
    const lastPrompt = own.at(-1)?.created_at_epoch ?? 0;
    const asks = own.filter((prompt) => isHumanActionRequest(prompt.prompt_text))
      .map((prompt) => ({ promptId: prompt.id, at: iso(prompt.created_at_epoch), text: requestText(prompt.prompt_text, fullAsks ? Infinity : 280) }));
    candidates.set(key, {
      conversationKey: key, platform: session.platform_source, project: session.project,
      startedAt: iso(original.atEpoch ?? session.started_at_epoch), startedAtEpoch: original.atEpoch ?? session.started_at_epoch,
      lastActivityEpoch: Math.max(lastPrompt, observationsBySession.get(session.id)?.last_epoch ?? 0, lastToolUseBySession.get(session.id) ?? 0, session.started_at_epoch ?? 0),
      firstAsk: requestText(original.text, 600), asks: fullAsks ? asks : recentAsks ? asks.slice(-10) : asks.slice(0, 10), askCount: asks.length, original,
      workLists: [], requestIds: [], observationCount: observationsBySession.get(session.id)?.count ?? 0,
      sessionDbId: session.id,
    });
  }
  const bySession = new Map([...candidates.values()].map((candidate) => [candidate.sessionDbId, candidate]));
  for (const write of writes) {
    const candidate = bySession.get(write.session_db_id);
    if (!candidate) continue;
    let input;
    try { input = JSON.parse(write.tool_input); } catch { continue; }
    if (typeof input?.list === 'string' && !candidate.workLists.includes(input.list)) candidate.workLists.push(input.list);
    const requestId = input?.fields?.request_id;
    if (['string', 'number'].includes(typeof requestId) && String(requestId).trim() && !candidate.requestIds.includes(String(requestId).trim())) candidate.requestIds.push(String(requestId).trim());
    candidate.lastActivityEpoch = Math.max(candidate.lastActivityEpoch, write.created_at_epoch ?? 0);
  }
  return [...candidates.values()].sort((a, b) => a.startedAtEpoch - b.startedAtEpoch)
    .map(({ sessionDbId, lastActivityEpoch, ...candidate }) => ({ ...candidate, lastActivityAt: iso(lastActivityEpoch), lastActivityEpoch }));
}

/** Union conversations that recorded into the same work list or request id.
 * A list name or request id links only within one project root, so worktrees
 * of one repo link and different repos never do. */
export function linkBackwards(candidates) {
  const parent = new Map(candidates.map((candidate) => [candidate.conversationKey, candidate.conversationKey]));
  const find = (key) => { while (parent.get(key) !== key) { parent.set(key, parent.get(parent.get(key))); key = parent.get(key); } return key; };
  const links = [];
  const skippedLists = [];
  const shared = (kind, field) => {
    const owners = new Map();
    for (const candidate of candidates) for (const value of candidate[field]) {
      const scope = JSON.stringify([projectRoot(candidate.project), value]);
      if (!owners.has(scope)) owners.set(scope, { value, project: candidate.project, keys: [] });
      owners.get(scope).keys.push(candidate.conversationKey);
    }
    for (const { value, project, keys } of owners.values()) {
      if (keys.length < 2) continue;
      if (kind === 'shared-work-list' && keys.length > MAX_CONVERSATIONS_PER_LINKING_LIST) { skippedLists.push({ list: value, project, conversations: keys.length }); continue; }
      for (const key of keys.slice(1)) parent.set(find(key), find(keys[0]));
      links.push({ kind, conversations: keys, evidence: kind === 'shared-work-list' ? `work list "${value}" in ${project}` : `request_id "${value}"` });
    }
  };
  shared('shared-request-id', 'requestIds');
  shared('shared-work-list', 'workLists');
  const groups = new Map();
  for (const candidate of candidates) {
    const root = find(candidate.conversationKey);
    if (!groups.has(root)) groups.set(root, { conversations: [], links: [] });
    groups.get(root).conversations.push(candidate.conversationKey);
  }
  for (const link of links) groups.get(find(link.conversations[0])).links.push(link);
  return { proposedGroups: [...groups.values()], skippedLists };
}

/** Fold the owner-goals list (patch entries) into its open focus areas and asks, areas first. */
export function readGoals(database) {
  const rows = database.prepare('SELECT fields FROM work_state_entries WHERE list_name = ? ORDER BY created_at_epoch, id').all(OWNER_GOALS_LIST);
  const listState = {}, items = new Map();
  for (const row of rows) {
    const fields = JSON.parse(row.fields);
    const target = fields.task ? items.get(fields.task) ?? items.set(fields.task, {}).get(fields.task) : listState;
    for (const [key, value] of Object.entries(fields)) { if (value === null) delete target[key]; else target[key] = value; }
  }
  const goals = [...items.values()].filter((item) => !isClosedWorkStateStatus(item.status)).map((item) => ({
    // taskKey is the item's work-state task; goal is only ever a focus area's sentence.
    taskKey: item.task, ...goalKindOf(item), rank: Number(item.rank) || null,
    title: item.title ?? item.task, goal: item.goal ?? null, focusArea: item.focus_area ?? null, focusAreaId: item.focus_area_id ?? null,
    latestAt: item.latest_at ?? null, timesAsked: Number(item.times_asked) || null,
    // A later local refresh changes snapshot, so it cannot reuse an older hosted JSON evidence field.
    evidence: item.source === 'hosted-intent' && item.hosted_snapshot === item.snapshot
      ? JSON.parse(item.evidence_json)
      : String(item.evidence ?? '').split('\n').filter(Boolean).map((line) => { const [at, ...quote] = line.split(' | '); return { at, quote: quote.join(' | ') }; }),
  })).sort((a, b) => GOAL_KINDS.indexOf(a.kind) - GOAL_KINDS.indexOf(b.kind) || (a.rank ?? Infinity) - (b.rank ?? Infinity));
  return { summary: listState.human_summary ?? null, generatedAt: listState.generated_at ?? null, mapPath: listState.map_path ?? null, goals };
}

/** A ledger file's bytes, or null when it does not exist. */
function readBytes(path) {
  try { return readFileSync(path); }
  catch (error) { if (error.code === 'ENOENT') return null; throw error; }
}

/** The sha256 of a file's bytes as read, or 'missing'. A shared write compares it under its write lock with the file's
 * hash then (SharedLedgerAdapter.stageFile readHash), so a value built from an older read is refused. Raw bytes, so the
 * hash is of exactly what the reader parsed. */
const bytesHash = (bytes) => bytes === null ? 'missing' : createHash('sha256').update(bytes).digest('hex');
export const ledgerFileHash = (path) => bytesHash(readBytes(path));

/** readHashes: when given, the read's hash (bytesHash) is recorded under `name`. */
function readJson(path, fallback, readHashes = null, name = null) {
  const bytes = readBytes(path);
  if (readHashes) readHashes[name] = bytesHash(bytes);
  return bytes === null ? fallback : JSON.parse(bytes.toString('utf8'));
}

/**
 * Write one ledger file. With a shared writer registered (shared state on), that writer commits the shared records first
 * and then puts the file in place itself, under its database write lock (SharedLedgerAdapter.finishWrite): a rename made
 * after the lock was released could land after a newer write's and leave the older value in the file. readHash: the hash
 * of the file this value was built from (readLedger's readHashes); the shared write refuses the value when another writer
 * replaced that file since, instead of saving it over the newer decision.
 */
export function writeJsonAtomic(path, value, { readHash } = {}) {
  const finish = beforeSharedFileWrite(path, value, readHash === undefined ? undefined : { readHash });
  if (finish) finish();
  else writeJsonFileAtomic(path, value, { mode: 0o600 });
}

const emptyGroups = () => ({ version: 1, updatedAt: null, conversations: {}, groups: {}, ignored: {} });

/** Merge decisions into the stored ledger. Conversations listed in a decision
 * move to that group; others keep their previous group. `projectOf` maps a
 * conversation key to its project: a group holds one project root only, unless
 * the decision names the request's `projectRoot` itself. */
export function applyGroupDecisions(stored, decisions, now = Date.now(), { projectOf = new Map(), getProjectRoot = projectRoot } = {}) {
  if (!Array.isArray(decisions?.groups)) throw new TypeError('Decisions need a groups array.');
  const next = structuredClone(stored ?? emptyGroups());
  for (const [index, decision] of decisions.groups.entries()) {
    const label = `groups[${index}]`;
    if (typeof decision.title !== 'string' || !decision.title.trim() || decision.title.length > 120) throw new TypeError(`${label}.title must be 1–120 characters.`);
    if (!Array.isArray(decision.conversations) || !decision.conversations.length || !decision.conversations.every(isConversationKey)) throw new TypeError(`${label}.conversations must list conversation keys, earliest first.`);
    const links = decision.links ?? [];
    const members = new Set(decision.conversations);
    const parent = new Map(decision.conversations.map((key) => [key, key]));
    const find = (key) => { while (parent.get(key) !== key) key = parent.get(key); return key; };
    for (const link of links) {
      if (!LINK_KINDS.includes(link.kind)) throw new TypeError(`${label} has unknown link kind ${link.kind}.`);
      if (typeof link.evidence !== 'string' || !link.evidence.trim()) throw new TypeError(`${label} has a link without evidence.`);
      if (!Array.isArray(link.conversations) || link.conversations.length < 2 || !link.conversations.every((key) => members.has(key))) throw new TypeError(`${label} has a link that must name 2+ of the group's own conversations.`);
      for (const key of link.conversations.slice(1)) parent.set(find(key), find(link.conversations[0]));
    }
    if (decision.conversations.length > 1 && !links.length) throw new TypeError(`${label} joins conversations without a recorded link.`);
    const unsupported = decision.conversations.filter((key) => find(key) !== find(decision.conversations[0]));
    if (unsupported.length) throw new TypeError(`${label} joins ${unsupported.join(', ')} without evidence linking it to the anchor.`);
    const id = groupIdFor(decision.conversations[0]);
    // A decision may name the request's root itself: conversations from other roots may then join it, and
    // the group records that root. Without one, a request stays in one project root, members it already
    // has included. A group saved with a named root keeps that allowance when a later decision (a refresh
    // answer, whose schema has no projectRoot) extends it.
    if (decision.projectRoot != null && (typeof decision.projectRoot !== 'string' || !decision.projectRoot.trim())) throw new TypeError(`${label}.projectRoot must be a non-empty string when given.`);
    const explicitRoot = decision.projectRoot ?? (next.groups[id]?.rootNamed ? next.groups[id].projectRoot : null);
    const allMembers = [...new Set([...decision.conversations, ...Object.entries(next.conversations).filter(([key, groupId]) => groupId === id && !decision.conversations.includes(key)).map(([key]) => key)])];
    const storedRoot = upgradedGroupRoot(next.groups[id]?.projectRoot, getProjectRoot(projectOf.get(next.groups[id]?.anchor)),
      allMembers.map((key) => getProjectRoot(projectOf.get(key))));
    // A group decided before its project was known (the "no project" root) takes the root its members show now:
    // its earlier members may still show none, and that does not split it.
    const rootWasUnknown = storedRoot === NO_PROJECT;
    const roots = new Map();
    for (const key of allMembers) {
      const root = getProjectRoot(projectOf.get(key));
      if (root == null || (rootWasUnknown && root === NO_PROJECT && !decision.conversations.includes(key))) continue;
      roots.set(root, [...(roots.get(root) ?? []), key]);
    }
    if (typeof storedRoot === 'string' && !rootWasUnknown && !roots.has(storedRoot)) roots.set(storedRoot, []);
    if (explicitRoot == null && roots.size > 1) throw new TypeError(`${label} joins conversations from different projects (${[...roots.keys()].map((root) => root || 'no project').join(', ')}); a request stays inside one project root.`);
    const projectRootOfGroup = explicitRoot != null ? explicitRoot.trim() : roots.size ? [...roots.keys()][0] : storedRoot ?? null;
    for (const key of decision.conversations) {
      next.conversations[key] = id;
      // A later decision can correct an earlier ignore; the viewer checks ignored first.
      if (next.ignored) delete next.ignored[key];
    }
    // A decision adds its evidence to the request's: a conversation joined one at a time (the judge, the
    // owner's Join) names only its own link, and the links of members that stay must survive it. Links
    // naming a conversation that left the group go with it.
    const memberSet = new Set(allMembers);
    const keptLinks = (next.groups[id]?.links ?? []).filter((link) => link.conversations.every((key) => memberSet.has(key)));
    const known = new Set(keptLinks.map((link) => JSON.stringify(link)));
    const mergedLinks = [...keptLinks, ...links.filter((link) => !known.has(JSON.stringify(link)))];
    next.groups[id] = { title: decision.title.trim(), anchor: decision.conversations[0], projectRoot: projectRootOfGroup, ...(explicitRoot != null ? { rootNamed: true } : {}), links: mergedLinks, decidedAt: iso(now), anchorAsk: stored?.groups?.[id]?.anchor === decision.conversations[0] ? stored.groups[id].anchorAsk ?? null : null };
  }
  next.ignored ??= {};
  for (const [index, ignored] of (decisions.ignored ?? []).entries()) {
    if (!isConversationKey(ignored.conversation)) throw new TypeError(`ignored[${index}].conversation must be a conversation key.`);
    next.ignored[ignored.conversation] = boundedText(ignored.reason, 200, `ignored[${index}].reason`);
    delete next.conversations[ignored.conversation];
  }
  const used = new Set(Object.values(next.conversations));
  for (const [id, group] of Object.entries(next.groups)) {
    if (!used.has(id)) delete next.groups[id];
    else group.links = (group.links ?? []).filter((link) => link.conversations.every((key) => next.conversations[key] === id));
  }
  next.updatedAt = iso(now);
  return next;
}

const isIsoOrNull = (value) => value === null || (typeof value === 'string' && Number.isFinite(Date.parse(value)));
function boundedText(value, max, label, optional = false) {
  if (optional && (value == null || value === '')) return '';
  if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${label} must be 1–${max} characters.`);
  // The length goes in the refusal: an agent asked to fix "must be 1–12000" without it rewrote a 22K story at 22K (Oct 24).
  // So does a target well under the cap: asked to "cut at least 12 characters", reviewers cut about that, miscounted and
  // were refused again, which failed the whole refresh (Oct 31: eight runs in a row, each 2–147 characters over).
  if (value.length > max) {
    const target = textTarget(max);
    throw new TypeError(`${label} is ${value.length} characters; it must be 1–${max}. Bring it to about ${target} characters (cut at least ${value.length - target}).`);
  }
  return value.trim();
}

/** About three quarters of a cap: the length the skill asks for, so a reviewer's miscount still lands under the cap. */
export const textTarget = (max) => Math.floor((max * 0.75) / 10) * 10;

/** A verbatim quote is shortened by quoting less of it, never by rewording, so its refusal says so. */
function boundedQuote(value, max, label) {
  if (typeof value === 'string' && value.length > max) {
    throw new TypeError(`${label} is ${value.length} characters; it must be 1–${max}. Quote a shorter part of it word for word, about ${textTarget(max)} characters; never reword a quote.`);
  }
  return boundedText(value, max, label);
}

/** A list of at most `max`, with the count in the refusal and what to drop, like boundedText's lengths. */
function boundedList(value, max, label) {
  const list = value ?? [];
  if (!Array.isArray(list)) throw new TypeError(`${label} must be an array of at most ${max}.`);
  if (list.length > max) throw new TypeError(`${label} has ${list.length} items; it must have at most ${max}. Keep the ${max} that matter most.`);
  return list;
}

function reviewText(value, max, label, options) {
  if (!options.coerce) return boundedText(value, max, label, options.optional);
  if (options.optional && (value == null || value === '')) return '';
  if (typeof value !== 'string' || !value.trim()) throw new TypeError(`${label} must be 1–${max} characters.`);
  const text = value.trim();
  if (text.length <= max) return text;
  options.coercedFields.add(label);
  const suffix = '…';
  let prefix = text.slice(0, max - suffix.length);
  if (/[\uD800-\uDBFF]$/.test(prefix)) prefix = prefix.slice(0, -1);
  const boundary = prefix.lastIndexOf(' ');
  if (boundary >= prefix.length - 40) prefix = prefix.slice(0, boundary);
  return `${prefix.trimEnd()}${suffix}`;
}

function reviewQuote(value, max, label, options) {
  if (!options.coerce || typeof value !== 'string' || !value.trim()) return boundedQuote(value, max, label);
  const text = value.trim();
  if (text.length <= max) return text;
  options.coercedFields.add(label);
  // Keep the quote verbatim by shortening at a word boundary without adding punctuation.
  let quote = text.slice(0, max);
  if (/[\uD800-\uDBFF]$/.test(quote)) quote = quote.slice(0, -1);
  const boundary = quote.lastIndexOf(' ');
  if (boundary >= quote.length - 40) quote = quote.slice(0, boundary);
  return quote.trimEnd();
}

function reviewList(value, max, label, options) {
  const list = value ?? [];
  // On the retry, a list given as something else (a string, an object) is read as no entries (#6645): refused on
  // both tries, that one optional field failed the whole refresh. The drop is named in `coercedFields`.
  if (!Array.isArray(list) && options.coerce) { options.coercedFields.add(`${label} (not a list) dropped`); return []; }
  if (!Array.isArray(list)) throw new TypeError(`${label} must be an array of at most ${max}.`);
  if (list.length <= max) return list;
  if (!options.coerce) throw new TypeError(`${label} has ${list.length} items; it must have at most ${max}. Keep the ${max} that matter most.`);
  options.coercedFields.add(label);
  // Amend mode starts from the previous review and adds new entries, so a list at its cap must lose its oldest
  // entries, not the new one. Dates decide when every entry has one; otherwise the model's order does.
  const times = list.map(entry => Date.parse(entry?.at));
  if (times.some(Number.isNaN)) return list.slice(-max);
  const newestIndexes = new Set(list.map((_, index) => index).sort((a, b) => times[a] - times[b] || a - b).slice(-max));
  return list.filter((_, index) => newestIndexes.has(index));
}

/** On the retry, a preference missing its words or the owner's quote is dropped: neither can be shortened into being,
 * and the review's state and summary are saved without it. Each drop is named in `droppedPreferences`, apart from the
 * trimmed fields. */
function quotedPreferences(list, options) {
  if (!options.coerce || !Array.isArray(list)) return list;
  const said = (value) => typeof value === 'string' && value.trim() !== '';
  return list.filter((preference, index) => {
    if (said(preference?.preference) && said(preference?.quote)) return true;
    options.droppedPreferences.add(`preferences[${index}]`);
    return false;
  });
}

// Models sometimes answer one citation as a plain string instead of a list (Oct 25: a review's
// `evidence: "obs 101"` threw `.map is not a function` and failed the whole refresh run).
const evidenceList = (value, limit = 8) => (Array.isArray(value) ? value : typeof value === 'string' && value.trim() ? [value] : []).map(String).slice(0, limit);

// How released work landed: where it shipped, whether anyone uses it, whether
// it was worth it, what it broke, and why each change was made. Every judgment
// cites evidence; "no-evidence" / "unclear" are answers, not gaps to fill.
export function validateOutcome(outcome, options = {}) {
  if (outcome == null) return null;
  if (typeof outcome !== 'object' || Array.isArray(outcome)) throw new TypeError('outcome must be an object.');
  options = { coerce: false, coercedFields: new Set(), ...options };
  const text = (value, max, label, optional = false) => reviewText(value, max, label, { ...options, optional });
  const leveled = (entry, levels, label) => {
    if (entry == null) return null;
    // On the retry, an entry whose level is outside the list is read as no entry (#6645), the way a landed entry with
    // no text is: its text was written for a level that can't be saved, so none of it is kept. The drop is reported.
    if (!levels.includes(entry.level) && options.coerce) { options.coercedFields.add(`${label} (invalid level) dropped`); return null; }
    if (!levels.includes(entry.level)) throw new TypeError(`${label}.level must be one of ${levels.join(', ')}.`);
    return { level: entry.level, text: text(entry.text, 400, `${label}.text`), evidence: evidenceList(entry.evidence) };
  };
  const regressions = reviewList(outcome.regressions, 10, 'outcome.regressions', options), changes = reviewList(outcome.changes, 12, 'outcome.changes', options);
  const dated = (value, label) => { if (!isIsoOrNull(value ?? null)) throw new TypeError(`${label} must be an ISO date or null.`); return value ?? null; };
  // On the retry, a landed entry carrying no text is read as no landed entry (#6568): empty or non-string text
  // refuses on both tries, so that review can never be saved and every refresh fails on its group. The text is
  // all the entry says — where and how the work shipped — so without it there is nothing to keep, the way a
  // preference without its words is dropped on the retry. A bare string in the entry's place is kept as its text.
  // The drop is named in `coercedFields`, so the refresh reports it (its date and evidence go with it).
  const landedEntry = outcome.landed !== null && typeof outcome.landed === 'object' ? outcome.landed : null;
  const landedText = landedEntry ? landedEntry.text : options.coerce && typeof outcome.landed === 'string' ? outcome.landed : undefined;
  const landedDropped = options.coerce && outcome.landed != null && (typeof landedText !== 'string' || !landedText.trim());
  if (landedDropped) options.coercedFields.add('outcome.landed (no text) dropped');
  const landed = outcome.landed == null || landedDropped ? null : {
    text: text(landedText, 400, 'outcome.landed.text'), at: dated(landedEntry?.at, 'outcome.landed.at'), evidence: evidenceList(landedEntry?.evidence),
  };
  return {
    landed,
    usage: leveled(outcome.usage, USAGE_LEVELS, 'outcome.usage'),
    value: leveled(outcome.value, VALUE_LEVELS, 'outcome.value'),
    regressions: regressions.map((regression, index) => ({
      text: text(regression.text, 300, `outcome.regressions[${index}].text`), at: dated(regression.at, `outcome.regressions[${index}].at`),
      fixedBy: text(regression.fixedBy, 200, `outcome.regressions[${index}].fixedBy`, true) || null, evidence: evidenceList(regression.evidence),
    })),
    changes: changes.map((change, index) => ({
      what: text(change.what, 200, `outcome.changes[${index}].what`), why: text(change.why, 400, `outcome.changes[${index}].why`),
      at: dated(change.at, `outcome.changes[${index}].at`), evidence: evidenceList(change.evidence),
    })),
  };
}

/** Progress reviews are agent assessments; keep them bounded and dated. */
export function validateProgress(entry, knownGroups, options = {}) {
  if (!entry || typeof entry !== 'object') throw new TypeError('Progress must be an object.');
  options = { coerce: false, coercedFields: new Set(), droppedPreferences: new Set(), ...options };
  const text = (value, max, label, optional = false) => reviewText(value, max, label, { ...options, optional });
  if (!knownGroups[entry.groupId]) throw new TypeError(`Unknown group ${entry.groupId}.`);
  const basis = entry.reviewBasis;
  if (!basis || typeof basis.checkedThrough !== 'string' || !Number.isFinite(Date.parse(basis.checkedThrough)) || !Array.isArray(basis.conversations) || !basis.conversations.length || !basis.conversations.every(isConversationKey)) {
    throw new TypeError('reviewBasis must be copied verbatim from `show` (checkedThrough and conversations).');
  }
  if (!PROGRESS_STATES.includes(entry.state)) throw new TypeError(`state must be one of ${PROGRESS_STATES.join(', ')}.`);
  if (!Number.isInteger(entry.percent) || entry.percent < 0 || entry.percent > 100) throw new TypeError('percent must be an integer 0–100.');
  for (const field of ['startedAt', 'shippedAt', 'lastActivityAt']) if (!isIsoOrNull(entry[field] ?? null)) throw new TypeError(`${field} must be an ISO date or null.`);
  if (entry.state === 'shipped' && (entry.percent !== 100 || !entry.shippedAt)) throw new TypeError('A shipped request needs percent 100 and shippedAt.');
  if (entry.state !== 'shipped' && entry.shippedAt) throw new TypeError('Only a shipped request has shippedAt.');
  const milestones = reviewList(entry.milestones, 12, 'milestones', options), preferences = reviewList(quotedPreferences(entry.preferences, options), 10, 'preferences', options);
  // What the owner has to do next (confirm, reply, review, decide, merge), only while the next action is theirs. Its text
  // cap is the milestones' (200). A finished review waits on no one.
  // On the retry, an owner's move on a shipped or abandoned request is dropped instead of refused again (#6645): the
  // state is the review's answer and the move contradicts it, so the move goes. The drop is named in `coercedFields`.
  const ownerMoveDropped = options.coerce && entry.ownerMove != null && typeof entry.ownerMove === 'object' && !Array.isArray(entry.ownerMove) && CLOSED_STATES.has(entry.state);
  if (ownerMoveDropped) options.coercedFields.add(`ownerMove (${entry.state}) dropped`);
  if (entry.ownerMove != null && !ownerMoveDropped) {
    if (typeof entry.ownerMove !== 'object' || Array.isArray(entry.ownerMove)) throw new TypeError('ownerMove must be an object with what and since, or left out.');
    if (CLOSED_STATES.has(entry.state)) throw new TypeError(`A request reviewed as ${entry.state} waits on no one; leave ownerMove out.`);
    if (!isIsoOrNull(entry.ownerMove.since ?? null)) throw new TypeError('ownerMove.since must be an ISO date or null.');
  }
  const ownerMove = entry.ownerMove == null || ownerMoveDropped ? null : { what: text(entry.ownerMove.what, 200, 'ownerMove.what'), since: entry.ownerMove.since ?? null };
  return {
    groupId: entry.groupId, state: entry.state, percent: entry.percent,
    startedAt: entry.startedAt ?? null, shippedAt: entry.shippedAt ?? null, lastActivityAt: entry.lastActivityAt ?? null,
    summary: text(entry.summary, 280, 'summary'),
    narrative: text(entry.narrative, 1200, 'narrative', true),
    milestones: milestones.map((milestone, index) => {
      if (!isIsoOrNull(milestone.at ?? null)) throw new TypeError(`milestones[${index}].at must be an ISO date or null.`);
      return { at: milestone.at ?? null, text: text(milestone.text, 200, `milestones[${index}].text`), evidence: evidenceList(milestone.evidence, 6) };
    }),
    preferences: preferences.map((preference, index) => {
      if (!PREFERENCE_KINDS.includes(preference.kind)) throw new TypeError(`preferences[${index}].kind must be one of ${PREFERENCE_KINDS.join(', ')}.`);
      if (!isIsoOrNull(preference.at ?? null)) throw new TypeError(`preferences[${index}].at must be an ISO date or null.`);
      return { kind: preference.kind, preference: text(preference.preference, 200, `preferences[${index}].preference`), quote: reviewQuote(preference.quote, 300, `preferences[${index}].quote`, options), at: preference.at ?? null };
    }),
    outcome: validateOutcome(entry.outcome, options),
    ...(ownerMove ? { ownerMove } : {}),
    evidence: evidenceList(entry.evidence, 20),
    // What the reviewer actually saw: later activity or membership changes make it due again.
    reviewedThrough: new Date(Date.parse(basis.checkedThrough)).toISOString(),
    reviewedConversations: [...new Set(basis.conversations)].sort(),
    ...(options.coerce && options.coercedFields.size ? { coercedFields: [...options.coercedFields].sort() } : {}),
  };
}

/** The parts of a review the build story and learned preferences are told from. */
function storyFacts(review) {
  return {
    state: review.state, percent: review.percent, startedAt: review.startedAt ?? null, shippedAt: review.shippedAt ?? null,
    milestones: review.milestones ?? [], preferences: review.preferences ?? [], outcome: review.outcome ?? null,
  };
}

/** Add one reading: deduplicated by `at`, oldest first, the newest MAX_READINGS kept. */
export function appendReading(previous, reading) {
  const byAt = new Map((previous?.readings ?? []).filter((item) => Number.isFinite(Date.parse(item?.at)) && Number.isInteger(item?.percent)).map((item) => [item.at, item]));
  byAt.set(reading.at, { at: reading.at, percent: reading.percent });
  return [...byAt.values()].sort((a, b) => Date.parse(a.at) - Date.parse(b.at)).slice(-MAX_READINGS);
}

/** A review is current only for the membership it covered and the activity it saw. */
export function reviewIsCurrent(review, conversationKeys, lastActivityEpoch) {
  if (!review?.reviewedThrough || !Array.isArray(review.reviewedConversations)) return false;
  const current = [...new Set(conversationKeys)].sort();
  if (current.length !== review.reviewedConversations.length || current.some((key, index) => key !== review.reviewedConversations[index])) return false;
  return Date.parse(review.reviewedThrough) >= lastActivityEpoch;
}

export const STORY_NARRATIVE_MAX = 12000;
const STORY_PREFERENCES_MAX = 30;
// What a story aims for, well under the cap. Aimed at the cap, updates kept landing just over it (Oct 24–26: nine
// answers refused at 12,108–13,614), and one update can add ~3,000 characters (7,026 → 10,030 after 12 groups were
// re-reviewed). 8,000 leaves that much headroom; stories condensed by hand to 6,530–7,351 kept the whole history.
export const STORY_NARRATIVE_TARGET = 8000;
// The recap's share of the target (My Work shows it); the chapters split the rest evenly, down to a floor that
// still holds a dated sentence or two.
export const STORY_RECAP_BUDGET = 800;
const STORY_CHAPTER_MIN_BUDGET = 300;
// Characters per word in a story (11,876 characters / 1,985 words, Oct 27), for a part with no words yet.
const STORY_CHARS_PER_WORD = 6;
// Parts a refusal names, furthest over budget first, so the message stays short.
const STORY_REFUSAL_PARTS = 6;

/** The story split at its `## ` chapter headings: the recap first, then each chapter with its heading. */
function storyPieces(narrative) {
  const pieces = [''];
  // The open code fence, as CommonMark reads one: up to 3 spaces of indent, then 3 or more backticks or tildes.
  // Only a fence of the same character, at least as long and with nothing after it, closes it, so a ``` example
  // inside a ```` fence stays inside, and so does any `## ` line in it.
  let fence = null;
  for (const line of (typeof narrative === 'string' ? narrative : '').split(/(?<=\n)/)) {
    const marker = /^ {0,3}(`{3,}|~{3,})(.*)$/.exec(line.replace(/\r?\n$/, ''));
    if (fence) {
      if (marker && marker[1][0] === fence[0] && marker[1].length >= fence.length && !marker[2].trim()) fence = null;
    } else if (marker && !(marker[1][0] === '`' && marker[2].includes('`'))) fence = marker[1];
    else if (line.startsWith('## ')) pieces.push('');
    pieces[pieces.length - 1] += line;
  }
  return pieces;
}

/**
 * How many of the oldest chapters to merge into one so every chapter's budget fits the target again. Past
 * (target - recap) / floor chapters (24), the floor makes the budgets add up to more than the target, so a story
 * can be over the cap with no part over its budget, and condensing parts alone cannot bring it back. 0 when the
 * budgets fit.
 */
export function storyChaptersToMerge(narrative) {
  const chapters = storyPieces(narrative).length - 1;
  const fit = Math.floor((STORY_NARRATIVE_TARGET - STORY_RECAP_BUDGET) / STORY_CHAPTER_MIN_BUDGET);
  return chapters > fit ? chapters - fit + 1 : 0;
}

/**
 * The story's recap and `## ` chapters with their lengths and budgets, counted here so the writer never has to.
 * Told to cut N characters from "the oldest finished chapters" only, an update cut 1,457 of the 3,876 asked
 * (Oct 27): the recap and the chapters under review held 5,826 of 11,876 characters and were off limits.
 * Budgets go in words as well, at the part's own characters per word: given only character budgets, a writer
 * cut a 2,492-character chapter to 1,891 against a budget of 800. `## ` lines inside code fences are not chapters,
 * and a story without chapters keeps the whole target as its recap budget.
 */
export function storyParts(narrative) {
  const [recap, ...chapters] = storyPieces(narrative);
  const chapterBudget = Math.max(STORY_CHAPTER_MIN_BUDGET, Math.floor((STORY_NARRATIVE_TARGET - STORY_RECAP_BUDGET) / Math.max(1, chapters.length)));
  return [
    { part: 'recap', text: recap, budgetChars: chapters.length ? STORY_RECAP_BUDGET : STORY_NARRATIVE_TARGET },
    ...chapters.map((chapter) => ({ part: chapter.split('\n', 1)[0].replace(/^## /, '').trim(), text: chapter, budgetChars: chapterBudget })),
  ].map(({ part, text, budgetChars }) => {
    const words = text.split(/\s+/).filter(Boolean).length;
    const charsPerWord = words ? text.length / words : STORY_CHARS_PER_WORD;
    return { part, chars: text.length, words, budgetChars, budgetWords: Math.max(1, Math.floor(budgetChars / charsPerWord)), overBudgetChars: Math.max(0, text.length - budgetChars) };
  });
}

/** On the story's one retry, a preference over its 200-character cap is cut to the cap (at a word boundary, with an
 * ellipsis) instead of refused again: one preference a character over otherwise fails the whole story and its other
 * preferences. The narrative keeps its own refusal, which asks for a condensed rewrite. Each trimmed preference's label
 * is added to `coercedFields`, so the refresh can report the trim instead of cutting silently.
 *
 * A list still over its cap of 30 on the retry loses its weakest preferences instead (31 and 32 failed the story on
 * both tries, #6568): the ones the fewest requests showed (`supportCount`), the last listed first among equals. The
 * rest keep the model's order. Each dropped preference's label is added to `droppedPreferences`. */
export function trimStoryPreferences(story, coercedFields = new Set(), droppedPreferences = new Set()) {
  if (!Array.isArray(story?.preferences)) return story;
  const options = { coerce: true, coercedFields };
  const support = (preference) => Number.isInteger(preference?.supportCount) && preference.supportCount > 0 ? preference.supportCount : 1;
  const kept = new Set(story.preferences.map((_, index) => index)
    .sort((a, b) => support(story.preferences[b]) - support(story.preferences[a]) || a - b).slice(0, STORY_PREFERENCES_MAX));
  for (let index = 0; index < story.preferences.length; index++) if (!kept.has(index)) droppedPreferences.add(`preferences[${index}]`);
  return { ...story, preferences: story.preferences.flatMap((preference, index) => !kept.has(index) ? []
    : typeof preference?.preference === 'string' && preference.preference.trim()
      ? [{ ...preference, preference: reviewText(preference.preference, 200, `preferences[${index}].preference`, options) }] : [preference]) };
}

export function validateStory(story) {
  const preferences = boundedList(story?.preferences, STORY_PREFERENCES_MAX, 'preferences');
  // The refusal names the target and the parts furthest over budget, so the retry condenses toward the target
  // instead of landing just under the cap again.
  const narrativeChars = typeof story?.narrative === 'string' ? story.narrative.length : 0;
  if (narrativeChars > STORY_NARRATIVE_MAX) {
    const over = storyParts(story.narrative).filter((part) => part.overBudgetChars > 0).sort((a, b) => b.overBudgetChars - a.overBudgetChars);
    const named = over.slice(0, STORY_REFUSAL_PARTS).map((part) => `${part.part === 'recap' ? 'the recap' : `"${part.part.slice(0, 60)}"`} ${part.chars} → ${part.budgetChars} characters (about ${part.budgetWords} words)`);
    const more = over.length > STORY_REFUSAL_PARTS ? `; ${over.length - STORY_REFUSAL_PARTS} more parts are over their budgets too` : '';
    // Too many chapters: their budgets add up to more than the target, so no part may be over budget at all.
    // Then the oldest chapters are merged first, and the refusal names them.
    const merge = storyChaptersToMerge(story.narrative);
    const chapters = storyParts(story.narrative).slice(1, merge + 1).map((part) => `"${part.part.slice(0, 60)}"`);
    const steps = [
      ...(merge ? [`merge the ${merge} oldest chapters (${chapters[0]} through ${chapters[chapters.length - 1]}) into one chapter of at most ${STORY_CHAPTER_MIN_BUDGET} characters`] : []),
      ...(named.length ? [`rewrite the parts furthest over their budgets: ${named.join('; ')}${more}`] : []),
    ];
    throw new TypeError(`narrative is ${narrativeChars} characters; it must be 1–${STORY_NARRATIVE_MAX}. Bring it to about ${STORY_NARRATIVE_TARGET} characters: ${steps.join(', then ') || 'condense every part'}.`);
  }
  return {
    narrative: boundedText(story?.narrative, STORY_NARRATIVE_MAX, 'narrative'),
    preferences: preferences.map((preference, index) => ({
      preference: boundedText(preference.preference, 200, `preferences[${index}].preference`),
      kind: PREFERENCE_KINDS.includes(preference.kind) ? preference.kind : 'directive',
      supportCount: Number.isInteger(preference.supportCount) && preference.supportCount > 0 ? preference.supportCount : 1,
      quotes: (preference.quotes ?? []).slice(0, 3).map((quote, quoteIndex) => ({ quote: boundedQuote(quote.quote, 300, `preferences[${index}].quotes[${quoteIndex}]`), at: isIsoOrNull(quote.at ?? null) ? quote.at ?? null : null })),
    })),
  };
}

/**
 * What the owner rejected in My Rules: each dismissed learned rule's words, as its saved my-rules row keeps them. A
 * suggestion's id is a hash of its exact words (my-rules.mjs ruleIdForPreference), so a reworded preference would come
 * back as a new suggestion; the story step (story-input) and owner-goals (dismissed-rules) are given these words so
 * they never propose one again in any wording. The row keeps the rule whole, so My Rules can put it back without the
 * story (my-rules.mjs restoredSuggestionRowFields). An owner's own rule taken back is gone, not rejected (buildRules
 * leaves it out). Rows only: the story's own preferences are what is being rewritten.
 */
export function dismissedRuleStatements(database, { localDeviceId = '' } = {}) {
  const state = reduceWorkState(readWorkStateRows(database, { listName: MY_RULES_LIST }), { localDeviceId });
  return buildRules(state, null).rules.filter((rule) => rule.status === 'dismissed').map((rule) => rule.then);
}

/** The story step's input: the reviews to tell, the story they update and its budgets, and the words of the rules the
 * owner rejected (dismissedRuleStatements), never to be proposed again. `story-input` builds it from the saved story; the
 * worker builds each later part of a story written in parts (#6226) from the part before, with the same rejected rules. */
export function storyInput(groups, reviews, story, dismissedRules) {
  const update = Number.isFinite(Date.parse(story?.writtenAt ?? ''));
  // An update only ever added to the story until it reached the cap and every update was refused (Oct 24: 11,958 of 12,000),
  // so the agent is told the budget and the previous story's length up front.
  // With only the limit and length, an update at 11,836 of 12,000 still added ~1,300 characters and condensed nothing (Oct 24),
  // so the room left is spelled out as well.
  // With room counted up to the cap, updates still aimed at the cap and landed over it (Oct 24–26), so the room is
  // counted up to the target, and a previous story past the target is first condensed back to it, part by part.
  const previousNarrativeChars = story?.narrative?.length ?? 0;
  return { groups, update, narrativeTarget: STORY_NARRATIVE_TARGET, narrativeLimit: STORY_NARRATIVE_MAX, previousNarrativeChars,
    roomChars: Math.max(0, STORY_NARRATIVE_TARGET - previousNarrativeChars), condenseChars: Math.max(0, previousNarrativeChars - STORY_NARRATIVE_TARGET),
    previousParts: update ? storyParts(story.narrative) : [], mergeOldestChapters: update ? storyChaptersToMerge(story.narrative) : 0,
    reviews,
    dismissedRules,
    // Rules owner-goals put in the story are its own (record-story carries them over): shown here, the story model
    // would echo them back without their source and when, leaving copies a later owner-goals save cannot replace.
    previousStory: story && { ...story, preferences: (story.preferences ?? []).filter((preference) => preference?.source !== OWNER_GOALS_LIST) } };
}

/** Suggestions still waiting for the owner: the judge's mid-band picks (request-judge.mjs) whose
 * request still exists and whose conversation is not in it yet. */
export function openSuggestions(ledger) {
  const groups = ledger?.groups;
  if (!groups) return [];
  return Object.entries(groups.suggestions ?? {})
    .filter(([key, suggestion]) => suggestion?.status === 'open' && groups.groups[suggestion.requestId] && groups.conversations[key] !== suggestion.requestId)
    .map(([conversationKey, suggestion]) => ({
      conversationKey, requestId: suggestion.requestId, requestTitle: groups.groups[suggestion.requestId].title,
      confidence: suggestion.confidence, evidence: suggestion.evidence, judge: suggestion.judge, at: suggestion.at ?? null,
    }));
}

/** The automatic refresh's status, or null when its bytes are not JSON: the next refresh check writes a new one. */
function readRefreshStatus(dir) {
  try { return readJson(join(dir, 'refresh.json'), null); }
  catch (error) { if (error instanceof SyntaxError) return null; throw error; }
}

/** Everything the monitor needs, read without touching the database. `readHashes` holds the hash of each file a command
 * writes back (request-groups.json, story.json, progress/<groupId>.json) as this read found it; readHashOf names it. */
export function readLedger(dir = LEDGER_DIR) {
  const readHashes = {};
  const groups = readJson(join(dir, 'request-groups.json'), emptyGroups(), readHashes, 'request-groups.json');
  const progress = {};
  let names = [];
  try { names = readdirSync(join(dir, 'progress')).filter((name) => /^g_[0-9a-f]{12}\.json$/.test(name)); }
  catch (error) { if (error.code !== 'ENOENT') throw error; }
  for (const name of names) {
    const entry = readJson(join(dir, 'progress', name), null, readHashes, `progress/${name}`);
    if (entry?.groupId && groups.groups[entry.groupId]) progress[entry.groupId] = { ...entry, title: groups.groups[entry.groupId].title };
  }
  return {
    groups, progress, story: readJson(join(dir, 'story.json'), null, readHashes, 'story.json'), refresh: readRefreshStatus(dir),
    agentWrittenPromptIds: new Set(readJson(join(dir, AGENT_WRITTEN_PROMPTS_FILE), { promptIds: [] }).promptIds ?? []),
    readHashes,
  };
}

/** The hash a write built from `ledger` passes as readHash for the ledger file `name`: a progress file the read did not
 * list did not exist then. */
export const readHashOf = (ledger, name) => ledger.readHashes[name] ?? bytesHash(null);

/** Cheap change detector for the monitor's one-second poll. */
export function ledgerSignature(dir = LEDGER_DIR) {
  return ['request-groups.json', 'progress', 'story.json', 'refresh.json'].map((name) => {
    try { const stat = statSync(join(dir, name)); return `${stat.mtimeMs}:${stat.size}`; }
    catch { return 'missing'; }
  }).join('|');
}

function groupDetails(groupId, ledger, candidatesByKey) {
  const group = ledger.groups.groups[groupId];
  const conversations = Object.entries(ledger.groups.conversations).filter(([, id]) => id === groupId).map(([key]) => candidatesByKey.get(key) ?? { conversationKey: key, outsideWindow: true });
  const loaded = conversations.filter((conversation) => !conversation.outsideWindow);
  return {
    groupId, title: group.title, links: group.links, anchorAsk: group.anchorAsk ?? null,
    startedAt: iso(Math.min(...loaded.map((conversation) => conversation.startedAtEpoch ?? Infinity))),
    lastActivityAt: iso(Math.max(0, ...loaded.map((conversation) => conversation.lastActivityEpoch ?? 0))),
    lastActivityEpoch: Math.max(0, ...loaded.map((conversation) => conversation.lastActivityEpoch ?? 0)),
    projects: [...new Set(loaded.map((conversation) => conversation.project))],
    conversations: conversations.map(({ lastActivityEpoch, startedAtEpoch, original, ...conversation }) => conversation),
    previousReview: ledger.progress[groupId] ?? null,
  };
}

// Re-review only groups with activity after their last review; finished
// groups stay finished unless new work arrives.
function pendingReviews(ledger, database, sinceEpoch) {
  const candidates = new Map(readCandidates(database, { sinceEpoch, excludedPromptIds: ledger.agentWrittenPromptIds }).map((candidate) => [candidate.conversationKey, candidate]));
  const ungrouped = [...candidates.keys()].filter((key) => !ledger.groups.conversations[key] && !ledger.groups.ignored?.[key]).length;
  const ids = [...new Set([...candidates.keys()].map((key) => ledger.groups.conversations[key]).filter(Boolean))];
  const due = ids.map((id) => groupDetails(id, ledger, candidates))
    .filter((group) => !reviewIsCurrent(group.previousReview, group.conversations.map((conversation) => conversation.conversationKey), group.lastActivityEpoch))
    .sort((a, b) => b.lastActivityEpoch - a.lastActivityEpoch);
  return { due, ungrouped };
}

/** An ask as the focus step reads it: the 400 characters grouping-input shows of a conversation's opening ask and an
 * open request's anchor ask (groupingInput), so a request is placed on what it was grouped on. */
export { placeholderTitleFromAsk, copiesOpeningAsk } from './request-projection.mjs';
/** Conversations per readCandidates call: two bound parameters each, and 400 pairs (800 parameters) stays under
 * SQLite's 999-parameter limit before 3.32, the same chunk readConversationProjects uses. */
const CONVERSATIONS_PER_QUERY = 400;

const groupConversations = (ledger, groupId) => Object.entries(ledger.groups.conversations).filter(([, id]) => id === groupId).map(([key]) => key).sort();

/** Each conversation's opening ask, read from the database (the ledger keeps only the anchor's). */
function openingAsks(database, ledger, conversationKeys) {
  const asks = new Map();
  for (let index = 0; index < conversationKeys.length; index += CONVERSATIONS_PER_QUERY) {
    for (const candidate of readCandidates(database, { conversationKeys: conversationKeys.slice(index, index + CONVERSATIONS_PER_QUERY), excludedPromptIds: ledger.agentWrittenPromptIds })) {
      asks.set(candidate.conversationKey, candidate.firstAsk);
    }
  }
  return asks;
}

/** One request as the focus step sees it, keyed by its anchor conversation. Every conversation's opening ask is listed,
 * so a request holding several separate asks (one to promote into an area) can be told from one ask. */
function requestRecord(ledger, groupId, asks, conversations) {
  const group = ledger.groups.groups[groupId], review = ledger.progress[groupId];
  return {
    anchor: group.anchor, groupId, title: group.title, firstAsk: requestText(group.anchorAsk?.text ?? null, FOCUS_ASK_CHARS),
    state: review?.state ?? null, summary: review?.summary ?? null,
    // A tag only, never a grouping: the request's project root.
    repo: group.projectRoot ?? null,
    conversations: conversations.length,
    conversationAsks: conversations.map((key) => requestText(asks.get(key) ?? null, FOCUS_ASK_CHARS)).filter(Boolean),
  };
}

const records = (database, ledger, groupIds, requests) => {
  const asks = openingAsks(database, ledger, groupIds.flatMap(requests.conversations));
  return groupIds.map((groupId) => requestRecord(ledger, groupId, asks, requests.conversations(groupId)));
};

function basisForConversations(ledger, groupId, conversations, title = ledger.groups.groups[groupId].title) {
  const group = ledger.groups.groups[groupId];
  return createHash('sha256').update(JSON.stringify({ title, firstAsk: group.anchorAsk?.text ?? null, conversations })).digest('hex').slice(0, 16);
}

/** What decides a request's area: its title, its first ask and its conversations. Its review (state, percent, summary)
 * is left out, so a request is not placed again every time it is reviewed. */
export function focusBasis(ledger, groupId) {
  return basisForConversations(ledger, groupId, groupConversations(ledger, groupId));
}

/** One synchronous focus operation shares sorted memberships and fingerprints.
 * Build lazily: owner placements and empty batches need no membership scan.
 * Keep this local to the operation so the next read sees ledger edits. */
function focusRequestIndex(ledger) {
  let byGroup;
  const bases = new Map();
  const conversations = (groupId) => {
    if (!byGroup) {
      byGroup = new Map();
      for (const [key, id] of Object.entries(ledger.groups.conversations)) {
        if (!byGroup.has(id)) byGroup.set(id, []);
        byGroup.get(id).push(key);
      }
      for (const keys of byGroup.values()) keys.sort();
    }
    return byGroup.get(groupId) ?? [];
  };
  return {
    conversations,
    basis: (groupId) => {
      if (!bases.has(groupId)) bases.set(groupId, basisForConversations(ledger, groupId, conversations(groupId)));
      return bases.get(groupId);
    },
    /** The basis the request had while it showed the placeholder copied from its ask. Naming (section 3) replaces only
     * that title, so a placement made under the placeholder still stands once the request is named (focusDue). */
    placeholderBasis: (groupId) => basisForConversations(ledger, groupId, conversations(groupId),
      placeholderTitleFromAsk(ledger.groups.groups[groupId].anchorAsk?.text ?? null)),
  };
}

/** Requests the focus step still has to place: no placement, a placement whose area holds no requests any more
 * (dismissed, or merged into a loop), or a router placement whose request changed since. An owner placement into a
 * live area (Other and done areas included) is the owner's and never queued; once its area is dismissed it no longer
 * binds (buildFocusAreas), and the router's placement must stand on its own. A router basis is compared only on the
 * device that wrote it: another device decided on its own copy of the request, and comparing would re-place every
 * request on every device in turn. Placements written without a basis (a seed) count as current, and so does one made
 * while the request showed the placeholder placeholderTitleFromAsk gives (the judge's title): naming it is not a change,
 * and treating it as one placed every named request again (133 of 136 on a copy of a real ledger, Nov 18). A copy
 * worded another way ("Figure it out." for "figure it out") was hashed as written, and once it is named nothing holds
 * those words (a placement keeps only the hash; sync replaces each request with its portable fields), so that request
 * is placed once more after naming. None of the 136 was one. */
function focusDue(ledger, focus, localDeviceId, requests) {
  return Object.keys(ledger.groups.groups).filter((groupId) => {
    const placement = focus.placementsByAnchor.get(ledger.groups.groups[groupId].anchor);
    if (placement?.owner && focus.resolveFocusAreaId(placement.owner.focusAreaId)) return false;
    const router = placement?.router;
    if (!router || !focus.resolveFocusAreaId(router.focusAreaId)) return true;
    return router.device === localDeviceId && router.basis != null && router.basis !== requests.basis(groupId)
      && router.basis !== requests.placeholderBasis(groupId);
  });
}

/** Requests the router put in Other, where new areas come from. A request the owner put in Other is the owner's call,
 * not material for a proposal, and a request still to be placed is left for its placement. */
function routerOther(ledger, focus, queued) {
  return Object.keys(ledger.groups.groups).filter((groupId) => {
    if (queued.has(groupId)) return false;
    const placement = focus.placementsByAnchor.get(ledger.groups.groups[groupId].anchor);
    if (placement?.owner && focus.resolveFocusAreaId(placement.owner.focusAreaId)) return false;
    return !!placement?.router && focus.resolveFocusAreaId(placement.router.focusAreaId) === OTHER_FOCUS_AREA_ID;
  });
}

/** Which Other requests a proposal pass looked at, and what each one held then (its focusBasis), so a request that
 * gained conversations or a new ask and stayed in Other is looked at again; null when Other holds none. */
const otherPassHash = (ledger, groupIds, requests) => groupIds.length
  ? createHash('sha256').update(JSON.stringify(groupIds.map((groupId) => [ledger.groups.groups[groupId].anchor, requests.basis(groupId)]).sort())).digest('hex').slice(0, 16)
  : null;

const focusAreaRecord = (area) => ({ focusAreaId: area.focusAreaId, name: area.name, goal: area.goal, about: area.about, status: area.status });

/** focus-input: the areas a request may go in, the dismissed areas never to propose again, and one batch of requests to
 * place, earliest in the ledger first. `remaining` counts the requests left for later batches. */
export function focusInput(ledger, focus, localDeviceId, database, { limit = FOCUS_BATCH } = {}) {
  const requests = focusRequestIndex(ledger);
  const due = focusDue(ledger, focus, localDeviceId, requests);
  return {
    areas: focus.focusAreas.filter(isPlaceableArea).map(focusAreaRecord),
    dismissed: focus.focusAreas.filter(isOwnerDismissedArea).map(focusAreaRecord),
    requests: records(database, ledger, due.slice(0, limit), requests),
    remaining: Math.max(0, due.length - limit),
  };
}

/** focus-input --other: the requests the router put in Other, for proposing areas. `due` is false when the last pass
 * (on any device: the hash is a synced my-focus row) already looked at exactly these requests. */
export function otherInput(ledger, focus, localDeviceId, database) {
  const requests = focusRequestIndex(ledger);
  const other = routerOther(ledger, focus, new Set(focusDue(ledger, focus, localDeviceId, requests)));
  const hash = otherPassHash(ledger, other, requests);
  return {
    areas: focus.focusAreas.filter(isPlaceableArea).map(focusAreaRecord),
    dismissed: focus.focusAreas.filter(isOwnerDismissedArea).map(focusAreaRecord),
    other: records(database, ledger, other, requests),
    due: hash !== null && hash !== focus.otherPassHash,
  };
}

// Same bounds as the worker's focus routes: a nav label, one sentence, and evidence or an about line of one
// sentence each, so a whole area fits one 2000-character work-state row (MAX_WORK_STATE_FIELDS_JSON_CHARS).
const AREA_NAME_MAX = 80, AREA_SENTENCE_MAX = 300;

/**
 * A focus answer checked against the input it was made from. Two kinds of question share the answer shape:
 * - placing (focus-input): every listed request is placed exactly once, in a listed area by its exact id or in "other";
 *   a request whose conversations hold several separate asks may be promoted into a proposed area. A request the
 *   model cannot decide goes in "ignored" with a reason instead of a placement and is recorded in "other" with
 *   that reason as its evidence — grouping's `ignored` carried to focus (#6432).
 * - Other (focus-input --other): nothing is placed; requests in Other that are steps of something larger cluster into
 *   a "new" proposal (two or more: one request is a request, not a cluster), and one may be promoted.
 * An area id that is not listed is refused, never mapped to Other: guessing would file the request wrongly. A proposal's
 * `sameAs` is the model's judgment of which saved area it already is: a listed area takes its requests (no new area),
 * and a dismissed one is refused, never proposed again under any name. Returns the body POST /api/work-view/focus/router
 * takes; after an Other pass it carries the hash of the Other requests left, so the next pass waits for a change.
 */
export function validateFocusAnswer(answer, input, ledger, { other = false } = {}) {
  if (!Array.isArray(answer?.placements)) throw new TypeError('The answer needs a placements array.');
  if (!Array.isArray(answer?.proposals)) throw new TypeError('The answer needs a proposals array (empty when there is nothing to propose).');
  const listed = new Map((other ? input.other : input.requests).map((request) => [request.anchor, request]));
  const requestIndex = focusRequestIndex(ledger);
  const areaIds = new Set(input.areas.map((area) => area.focusAreaId));
  const dismissed = new Map(input.dismissed.map((area) => [area.focusAreaId, area]));
  const placed = new Map();
  if (other && answer.placements.length) throw new TypeError('This question places nothing: answer "placements": [] and propose areas only.');
  const ignoredEntries = Array.isArray(answer?.ignored) ? answer.ignored : [];
  if (other && ignoredEntries.length) throw new TypeError('This question places nothing: answer "placements": [] and propose areas only; "ignored" belongs to the placing question.');
  const ignored = new Map();
  for (const [index, placement] of answer.placements.entries()) {
    const label = `placements[${index}]`;
    if (!listed.has(placement?.anchor)) throw new TypeError(`${label} names ${placement?.anchor}, which was not asked about.`);
    if (placed.has(placement.anchor)) throw new TypeError(`${label} places ${placement.anchor} a second time; a request sits in one area.`);
    if (placement.focusAreaId !== OTHER_FOCUS_AREA_ID && !areaIds.has(placement.focusAreaId)) {
      if (dismissed.has(placement.focusAreaId)) throw new TypeError(`${label} names ${placement.focusAreaId} ("${dismissed.get(placement.focusAreaId).name}"), which the owner dismissed; it takes no requests. Use a listed area id or "other".`);
      throw new TypeError(`${label} names ${JSON.stringify(placement.focusAreaId)}, which is not a listed focus area. Use an exact focusAreaId from "areas", or "other".`);
    }
    placed.set(placement.anchor, { focusAreaId: placement.focusAreaId, evidence: boundedText(placement.evidence, AREA_SENTENCE_MAX, `${label}.evidence`) });
  }
  for (const [index, entry] of ignoredEntries.entries()) {
    const label = `ignored[${index}]`;
    if (!listed.has(entry?.anchor)) throw new TypeError(`${label} names ${entry?.anchor}, which was not asked about.`);
    if (placed.has(entry.anchor)) throw new TypeError(`${label} names ${entry.anchor}, which a placement already places; a request is placed or skipped, not both.`);
    if (ignored.has(entry.anchor)) throw new TypeError(`${label} names ${entry.anchor} a second time.`);
    ignored.set(entry.anchor, boundedText(entry.reason, 200, `${label}.reason`));
  }
  if (!other) {
    const missing = [...listed.keys()].filter((anchor) => !placed.has(anchor) && !ignored.has(anchor));
    if (missing.length) throw new TypeError(`Place every request asked about; missing ${missing.join(', ')}.`);
  }
  const held = new Set();
  const proposals = answer.proposals.map((proposal, index) => {
    const label = `proposals[${index}]`;
    if (!PROPOSAL_KINDS.includes(proposal?.kind)) throw new TypeError(`${label}.kind must be one of ${PROPOSAL_KINDS.join(', ')}.`);
    if (!other && proposal.kind === 'new') throw new TypeError(`${label}: new areas are proposed from Other in their own question; here only "promote" a request that holds several separate asks.`);
    if (proposal.sameAs != null && !areaIds.has(proposal.sameAs)) {
      if (dismissed.has(proposal.sameAs)) throw new TypeError(`${label} is the area the owner dismissed (${proposal.sameAs}, "${dismissed.get(proposal.sameAs).name}"); never propose it again. Drop this proposal.`);
      throw new TypeError(`${label}.sameAs names ${JSON.stringify(proposal.sameAs)}, which is not a listed area; use an exact focusAreaId from "areas" or null.`);
    }
    if (!Array.isArray(proposal.anchors) || !proposal.anchors.length) throw new TypeError(`${label}.anchors must list the requests it holds.`);
    if (proposal.kind === 'new' && proposal.anchors.length < 2) throw new TypeError(`${label} clusters one request; a "new" area holds two or more steps of something larger (use "promote" for one request that holds several asks).`);
    if (proposal.kind === 'promote' && proposal.anchors.length !== 1) throw new TypeError(`${label} promotes one request; list only that request's anchor.`);
    const requests = proposal.anchors.map((anchor) => {
      if (!listed.has(anchor)) throw new TypeError(`${label} holds ${anchor}, which ${other ? 'is not a listed Other request' : 'was not asked about'}.`);
      if (held.has(anchor)) throw new TypeError(`${label} holds ${anchor}, which another proposal already holds.`);
      held.add(anchor);
      return { anchorConversationKey: anchor, basis: requestIndex.basis(listed.get(anchor).groupId) };
    });
    return {
      kind: proposal.kind, name: boundedText(proposal.name, AREA_NAME_MAX, `${label}.name`), goal: boundedText(proposal.goal, AREA_SENTENCE_MAX, `${label}.goal`),
      about: boundedText(proposal.about, AREA_SENTENCE_MAX, `${label}.about`), evidence: boundedText(proposal.evidence, AREA_SENTENCE_MAX, `${label}.evidence`),
      sameAs: proposal.sameAs ?? null, requests,
    };
  });
  return {
    placements: [
      ...[...placed].filter(([anchor]) => !held.has(anchor)).map(([anchor, { focusAreaId, evidence }]) => ({
        anchorConversationKey: anchor, focusAreaId, basis: requestIndex.basis(listed.get(anchor).groupId), evidence,
      })),
      // A skipped request is recorded in Other with the model's reason as its evidence: the batch is
      // decided, and the owner can move the request whenever they judge it.
      ...[...ignored].filter(([anchor]) => !held.has(anchor)).map(([anchor, reason]) => ({
        anchorConversationKey: anchor, focusAreaId: OTHER_FOCUS_AREA_ID, basis: requestIndex.basis(listed.get(anchor).groupId), evidence: reason,
      })),
    ],
    proposals,
    ...(other ? { otherPassHash: otherPassHash(ledger, [...listed.keys()].filter((anchor) => !held.has(anchor)).map((anchor) => listed.get(anchor).groupId), requestIndex) } : {}),
  };
}

/** An area is grouped into sub focuses only once it holds enough placed requests for the cards: a sub focus holds
 * SUB_FOCUS_MIN_REQUESTS or more, and an area shows sub focus cards only with SUB_FOCUS_MIN_CARDS of them
 * (sub-focus-rules.mjs, docs/design/focus-areas.md), so fewer than that many groups' worth cannot make cards and is never
 * asked about. */
const SUB_FOCUS_AREA_MIN_REQUESTS = SUB_FOCUS_MIN_CARDS * SUB_FOCUS_MIN_REQUESTS;

/** The ledger requests placed in each kept area (not merged) that My Work shows as cards (shownGroupIds): the areas the
 * sub focus step groups. A sub focus card counts the served requests that name it (docs/design/focus-areas.md), so a
 * request with no card is never asked about, never makes a group, and never counts toward an area's four. */
function requestsByKeptArea(ledger, focus, database) {
  const shown = shownGroupIds(ledger, database);
  // placedGroupIds: every placed request, shown or not: the set a pass hash covered before passes counted only shown ones
  // (subFocusAreas).
  const kept = new Map(focus.focusAreas.filter((area) => area.status === 'kept' && !area.mergedInto).map((area) => [area.focusAreaId, { area, groupIds: [], placedGroupIds: [] }]));
  for (const [groupId, group] of Object.entries(ledger.groups.groups)) {
    const entry = kept.get(focus.focusAreaIdByAnchor.get(group.anchor));
    if (!entry) continue;
    entry.placedGroupIds.push(groupId);
    if (shown.has(groupId)) entry.groupIds.push(groupId);
  }
  return [...kept.values()];
}

/** Which requests an area's sub focus pass looked at: the anchors of the requests placed in it, so the area is asked again
 * only when that set changes (a request placed in it or moved out), never for a new review or a regrouping by the owner. */
const subFocusPassHash = (ledger, groupIds) => createHash('sha256').update(JSON.stringify(groupIds.map((groupId) => ledger.groups.groups[groupId].anchor).sort())).digest('hex').slice(0, 16);

/** Kept areas with SUB_FOCUS_AREA_MIN_REQUESTS or more placed requests My Work shows that this computer's last answered
 * pass over the area did not look at. `due`: no pass failed on this set either, so any refresh asks the area. `failed`: this computer's
 * last pass failed on exactly this set (refused twice, the model call failed, or its answer could not be saved). The same
 * question would buy the same paid call again, and a quota reset, a login or a timer does not make it new
 * (docs/architecture/observer-lifecycle.md), so no scheduled refresh asks it; it is due again once its set changes, and the
 * owner's Refresh (OWNER_REFRESH_REASON) asks it.
 * A hash recorded before passes counted only shown requests covers every request placed in the area. It still names the
 * area's set while those placed requests are unchanged: an upgrade alone never asks an area again, neither one answered
 * nor one whose pass failed, and the area is asked again when a request is next placed in it or moved out. */
function subFocusAreas(ledger, focus, database) {
  const due = [], failed = [];
  for (const entry of requestsByKeptArea(ledger, focus, database)) {
    if (entry.groupIds.length < SUB_FOCUS_AREA_MIN_REQUESTS) continue;
    const hashes = [subFocusPassHash(ledger, entry.groupIds), subFocusPassHash(ledger, entry.placedGroupIds)];
    if (hashes.includes(focus.subFocusPassHashes.get(entry.area.focusAreaId))) continue;
    (hashes.includes(focus.subFocusFailedHashes.get(entry.area.focusAreaId)) ? failed : due).push(entry);
  }
  return { due, failed };
}

/**
 * sub-focus-input --area: one kept area's sub focus question. `subFocuses` are its live sub focuses with their members;
 * `requests` are the ones to decide now: not grouped in this area yet, left ungrouped by the router last time, or placed by
 * the router in a sub focus that holds fewer than SUB_FOCUS_MIN_REQUESTS requests now (the owner moved one out, or one
 * left the area), which is no group any more, so the pass groups them anew or leaves them ungrouped. A request the owner
 * placed (in a sub focus or in none) is the owner's and never listed to decide. `alreadyUngrouped` names the listed
 * requests the router left ungrouped last time: leaving one ungrouped again writes nothing. `passHash` names the requests
 * the pass looks at; the answer's last part records it.
 */
export function subFocusInput(ledger, focus, focusAreaId, database) {
  const entry = requestsByKeptArea(ledger, focus, database).find(({ area }) => area.focusAreaId === focusAreaId);
  if (!entry) throw new TypeError(`${focusAreaId} is not a kept focus area.`);
  const { area, groupIds } = entry;
  const anchorOf = (groupId) => ledger.groups.groups[groupId].anchor;
  const record = (groupId) => ({ anchor: anchorOf(groupId), title: ledger.groups.groups[groupId].title, summary: ledger.progress[groupId]?.summary ?? null });
  const decisions = groupIds.map((groupId) => ({ groupId, decided: focus.subFocusPlacementFor(anchorOf(groupId), focusAreaId) }));
  const held = new Map();
  for (const { decided } of decisions) if (decided?.subFocusId) held.set(decided.subFocusId, (held.get(decided.subFocusId) ?? 0) + 1);
  const members = new Map(area.subFocuses.map((subFocus) => [subFocus.subFocusId, []]));
  const requests = [], alreadyUngrouped = [];
  for (const { groupId, decided } of decisions) {
    if (decided?.placedBy === 'owner') { if (decided.subFocusId) members.get(decided.subFocusId).push(record(groupId)); }
    else if (decided?.subFocusId && held.get(decided.subFocusId) >= SUB_FOCUS_MIN_REQUESTS) members.get(decided.subFocusId).push(record(groupId));
    else {
      requests.push(record(groupId));
      if (decided && !decided.subFocusId) alreadyUngrouped.push(anchorOf(groupId));
    }
  }
  return {
    area: { focusAreaId, name: area.name, goal: area.goal },
    subFocuses: area.subFocuses.map((subFocus) => ({ subFocusId: subFocus.subFocusId, name: subFocus.name, members: members.get(subFocus.subFocusId) })),
    requests,
    alreadyUngrouped,
    passHash: subFocusPassHash(ledger, groupIds),
  };
}

/** Two sub focus names that differ only in case or spacing name one sub focus. */
const subFocusNameKey = (name) => name.toLowerCase().replace(/\s+/g, '');

/**
 * A sub focus answer checked against the area input it answers: every listed request decided exactly once, by its anchor,
 * in a listed sub focus by its exact id (`groups`), in a new sub focus (`newGroups`), or in none (`ungrouped`). An unknown
 * request or sub focus id, a request listed twice, and a new group named like a listed sub focus (ignoring case and
 * spaces) are refused. A listed sub focus left with fewer than SUB_FOCUS_MIN_REQUESTS requests, counting its members and
 * every entry that joins it, is not a group, and neither is a new group of one: their listed requests are left ungrouped.
 * A listed request the router left ungrouped last time (`alreadyUngrouped`) and left ungrouped again writes no placement:
 * the decision stands, and repeating it would add a synced row on every pass.
 * coerce (the refresh's one retry): an entry this check refuses is dropped instead, a new group named like a listed sub
 * focus joins that sub focus, and a listed request the answer left out is left ungrouped, so a model that keeps leaving the
 * same request out cannot fail every later refresh (#6432). Each new group the retry dropped, because its name or some of
 * its requests were refused, is named in `droppedNewGroups`, so the refresh reports it.
 * recordPass false (an earlier part of a large area): the pass is recorded only with the last part.
 * Returns the body POST /api/work-view/focus/router takes.
 */
export function validateSubFocusAnswer(answer, input, { coerce = false, recordPass = true, droppedNewGroups = new Set() } = {}) {
  for (const key of ['groups', 'newGroups', 'ungrouped']) if (!Array.isArray(answer?.[key])) throw new TypeError(`The answer needs a ${key} array (empty when it has none).`);
  const listed = new Set(input.requests.map((request) => request.anchor));
  const membersOf = new Map(input.subFocuses.map((subFocus) => [subFocus.subFocusId, subFocus.members.length]));
  const listedByName = new Map(input.subFocuses.map((subFocus) => [subFocusNameKey(subFocus.name), subFocus.subFocusId]));
  const refuse = (message) => { if (!coerce) throw new TypeError(message); };
  const decided = new Set();
  /** The anchors one entry places: listed, and not placed by an earlier entry. */
  const take = (anchors, label) => (Array.isArray(anchors) ? anchors : []).filter((anchor, index) => {
    if (!listed.has(anchor)) { refuse(`${label}[${index}] names ${JSON.stringify(anchor)}, which was not asked about.`); return false; }
    if (decided.has(anchor)) { refuse(`${label}[${index}] places ${anchor} a second time; a request sits in one sub focus.`); return false; }
    decided.add(anchor);
    return true;
  });
  /** The listed requests each listed sub focus takes, decided once every entry is read. */
  const joining = new Map();
  const join = (subFocusId, anchors) => joining.set(subFocusId, [...(joining.get(subFocusId) ?? []), ...anchors]);
  const ungrouped = [], newSubFocuses = [];
  for (const [index, group] of answer.groups.entries()) {
    const label = `groups[${index}]`;
    if (!membersOf.has(group?.subFocusId)) {
      refuse(`${label} names ${JSON.stringify(group?.subFocusId)}, which is not a listed sub focus. Use an exact subFocusId from "subFocuses", or put the requests in "newGroups".`);
      continue;
    }
    join(group.subFocusId, take(group.anchors, `${label}.anchors`));
  }
  for (const [index, group] of answer.newGroups.entries()) {
    const label = `newGroups[${index}]`;
    let name;
    try { name = boundedText(group?.name, AREA_NAME_MAX, `${label}.name`); }
    catch (error) { if (!coerce) throw error; droppedNewGroups.add(label); continue; }
    const same = listedByName.get(subFocusNameKey(name));
    if (same) refuse(`${label} is named "${name}", like the listed sub focus ${same}. Put its requests in "groups" with "subFocusId": "${same}" instead of making a second one.`);
    const asked = Array.isArray(group.anchors) ? group.anchors.length : 0;
    const anchors = take(group.anchors, `${label}.anchors`);
    if (same) { join(same, anchors); continue; }
    // A group of one is not a group: its request stays ungrouped.
    if (anchors.length < SUB_FOCUS_MIN_REQUESTS) {
      if (anchors.length < asked) droppedNewGroups.add(label);
      ungrouped.push(...anchors);
    } else newSubFocuses.push({ name, anchorConversationKeys: anchors });
  }
  const placements = [];
  for (const [subFocusId, anchors] of joining) {
    if (membersOf.get(subFocusId) + anchors.length < SUB_FOCUS_MIN_REQUESTS) ungrouped.push(...anchors);
    else placements.push(...anchors.map((anchor) => ({ anchorConversationKey: anchor, subFocusId })));
  }
  ungrouped.push(...take(answer.ungrouped, 'ungrouped'));
  const missing = [...listed].filter((anchor) => !decided.has(anchor));
  if (missing.length && !coerce) throw new TypeError(`Decide every request asked about, in a sub focus or in "ungrouped"; missing ${missing.join(', ')}.`);
  ungrouped.push(...missing);
  const unchanged = new Set(input.alreadyUngrouped);
  return {
    placements: [], proposals: [],
    subFocus: {
      focusAreaId: input.area.focusAreaId, newSubFocuses,
      placements: [...placements, ...ungrouped.filter((anchor) => !unchanged.has(anchor)).map((anchor) => ({ anchorConversationKey: anchor, subFocusId: null }))],
      passHash: recordPass ? input.passHash : null,
    },
  };
}

/** What a saved sub focus answer did, as record-sub-focus prints it and the refresh counts it. */
export function subFocusAnswerCounts(body) {
  const placements = body.subFocus?.placements ?? [], newSubFocuses = body.subFocus?.newSubFocuses ?? [];
  const inNew = newSubFocuses.reduce((total, group) => total + group.anchorConversationKeys.length, 0);
  return { grouped: inNew + placements.filter((placement) => placement.subFocusId !== null).length, ungrouped: placements.filter((placement) => placement.subFocusId === null).length, newSubFocuses: newSubFocuses.length };
}

/** Whether a request still shows a title copied from its opening ask, whoever copied it. */
export function hasPlaceholderTitle(group) {
  return copiesOpeningAsk(group.title, group.anchorAsk?.text ?? null);
}

/** A written title as the ledger keeps it: 1–120 characters (applyGroupDecisions' title contract) that do not copy the
 * request's opening ask, which would leave the request owed a title on every later run. */
function writtenTitle(value, askText, label) {
  const title = boundedText(value, 120, label);
  if (copiesOpeningAsk(title, askText)) throw new TypeError(`${label} repeats the owner's ask ("${placeholderTitleFromAsk(askText)}"). Name the task in about 5 to 7 words of your own, not words the ask starts with.`);
  return title;
}

/** title-input: one batch of requests still titled with the placeholder copied from their ask, in ledger order, each as
 * the focus step reads it (its asks, and its review's state and summary when it has one), so a vague ask ("figure it
 * out") is named from what the work turned out to be. `remaining` counts the requests left for later batches. */
export function titleInput(ledger, database, { limit = TITLE_BATCH } = {}) {
  const owed = Object.keys(ledger.groups.groups).filter((groupId) => hasPlaceholderTitle(ledger.groups.groups[groupId]));
  return { requests: records(database, ledger, owed.slice(0, limit), focusRequestIndex(ledger)), remaining: Math.max(0, owed.length - limit) };
}

/** A naming answer checked against the batch it answers: every listed request named exactly once, by its groupId.
 * With `coerce` (the refresh's one retry), a title this check refuses and a request left unnamed are dropped instead;
 * such a request keeps its placeholder until a later run asks again. */
export function validateTitleAnswer(answer, input, { coerce = false } = {}) {
  if (!Array.isArray(answer?.titles)) throw new TypeError('The answer needs a titles array.');
  const listed = new Map(input.requests.map((request) => [request.groupId, request]));
  const named = new Map();
  for (const [index, entry] of answer.titles.entries()) {
    const label = `titles[${index}]`;
    try {
      if (!listed.has(entry?.groupId)) throw new TypeError(`${label} names ${JSON.stringify(entry?.groupId)}, which was not asked about.`);
      if (named.has(entry.groupId)) throw new TypeError(`${label} names ${entry.groupId} a second time; give each request one title.`);
      named.set(entry.groupId, writtenTitle(entry.title, listed.get(entry.groupId).firstAsk, `${label}.title`));
    } catch (error) { if (!coerce || !(error instanceof TypeError)) throw error; }
  }
  const missing = [...listed.keys()].filter((groupId) => !named.has(groupId));
  if (missing.length && !coerce) throw new TypeError(`Name every request asked about; missing ${missing.join(', ')}.`);
  return { titles: [...named].map(([groupId, title]) => ({ groupId, title })) };
}

const requireDeviceId = (localDeviceId) => {
  if (typeof localDeviceId !== 'string') throw new TypeError('My Focus needs the worker\'s sync device id ("" when cloud sync never started).');
  return localDeviceId;
};

/** What an automatic refresh would do now; nothing to do means no agent runs.
 * The window is the request-progress skill's own default, so a finished run
 * leaves nothing due. localDeviceId is the worker's sync device id (readFocus), required. */
export function refreshNeeds({ dir = LEDGER_DIR, database, now = Date.now(), days = 14, localDeviceId }) {
  requireDeviceId(localDeviceId);
  const ledger = readLedger(dir);
  const { due, ungrouped } = pendingReviews(ledger, database, now - days * DAY_MS);
  const goals = readGoals(database);
  const generated = Date.parse(goals.generatedAt ?? '');
  const goalsStale = !Number.isFinite(generated) || now - generated > GOALS_STALE_MS;
  const focus = readFocus(database, { localDeviceId });
  const requests = focusRequestIndex(ledger);
  const queued = focusDue(ledger, focus, localDeviceId, requests);
  const otherHash = otherPassHash(ledger, routerOther(ledger, focus, new Set(queued)), requests);
  const otherChanged = otherHash !== null && otherHash !== focus.otherPassHash;
  // Kept areas whose set of placed requests changed since this computer last grouped them into sub focuses. An area whose
  // last pass failed on its current set is counted apart and never makes a scheduled run needed.
  const subFocus = subFocusAreas(ledger, focus, database);
  const subFocusDue = subFocus.due.length;
  return { due: due.length, ungrouped, goalsStale, unplaced: queued.length, otherChanged, subFocusDue, subFocusFailed: subFocus.failed.length,
    needed: Boolean(due.length || ungrouped || goalsStale || queued.length || otherChanged || subFocusDue) };
}

function readInput(source) {
  return JSON.parse(readFileSync(source === '-' ? 0 : source, 'utf8'));
}

function textOption(args, name) {
  const index = args.indexOf(`--${name}`);
  return index === -1 ? null : args[index + 1] ?? null;
}

function option(args, name, fallback) {
  const index = args.indexOf(`--${name}`);
  if (index === -1) return fallback;
  const value = Number(args[index + 1]);
  if (!Number.isInteger(value) || value < 1) throw new TypeError(`--${name} must be a positive integer.`);
  return value;
}

function openDatabase() {
  const path = process.env.CLAUDE_MEM_DB ?? join(DATA_DIR, 'claude-mem.db');
  statSync(path);
  // Portable group reducers can run in Node. Load the native reader only for the local CLI.
  const { Database } = createRequire(typeof __filename === 'string' ? __filename : import.meta.url)('bun:sqlite');
  const database = new Database(path, { readonly: true, create: false });
  database.exec('PRAGMA busy_timeout = 1500');
  return database;
}

/** Conversation key → project (derived for scratch-folder sessions). */
export function readConversationProjects(database, conversationKeys) {
  const pairs = [...new Set(conversationKeys)].filter(isConversationKey).map((key) => JSON.parse(key).slice(1));
  const sessions = [];
  for (let index = 0; index < pairs.length; index += 400) {
    const chunk = pairs.slice(index, index + 400);
    sessions.push(...database.prepare(`SELECT id, platform_source, content_session_id, project FROM sdk_sessions WHERE (platform_source, content_session_id) IN (VALUES ${chunk.map(() => '(?, ?)').join(',')})`).all(...chunk.flat()));
  }
  return new Map(withDerivedProjects(database, sessions).map((session) => [conversationKey(session), session.project]));
}

/** New conversations sent to the grouping agent at once. */
export const GROUPING_BATCH = 20;
/** Requests placed per focus answer: GROUPING_BATCH, the per-answer size the same light model (STEP_MODELS) already
 * decides "every listed item exactly once" for in grouping. Reused, not measured for placement itself. */
export const FOCUS_BATCH = GROUPING_BATCH;
/** Requests named per title answer, measured: on a copy of a real ledger (Nov 18) haiku, the light model (STEP_MODELS),
 * named all 20 requests of a 20-request batch (a 55 KB title-input) in one answer, and validateTitleAnswer accepted
 * every title. It is the size grouping and focus already ask that model to answer for, one item each. */
export const TITLE_BATCH = GROUPING_BATCH;

/** One grouping question: only conversations the ledger has not decided,
 * earliest first and all from one project root, each judged from its opening
 * ask, beside that root's open requests. Decided conversations are never sent
 * again, and neither are the keys in `skip` (conversations the judge could not
 * place in this run). `remaining` counts the new conversations left for later questions. */
export function groupingInput(ledger, database, { sinceEpoch, limit = GROUPING_BATCH, skip = null }) {
  const candidates = readCandidates(database, { sinceEpoch, recentAsks: true, excludedPromptIds: ledger.agentWrittenPromptIds });
  const decided = (key) => Boolean(ledger.groups.conversations[key] || ledger.groups.ignored?.[key] || skip?.has(key));
  const fresh = candidates.filter((candidate) => !decided(candidate.conversationKey));
  if (!fresh.length) return { root: null, conversations: [], openRequests: [], proposedLinks: [], remaining: 0 };
  const root = projectRoot(fresh[0].project);
  const batch = fresh.filter((candidate) => projectRoot(candidate.project) === root).slice(0, limit);
  const inRoot = candidates.filter((candidate) => projectRoot(candidate.project) === root);
  const byKey = new Map(inRoot.map((candidate) => [candidate.conversationKey, candidate]));
  // A group's root is stored at apply time; older groups, and groups decided before their project was
  // known, take it from their anchor.
  const rootIsStored = (group) => typeof group.projectRoot === 'string' && group.projectRoot !== NO_PROJECT;
  // With git-remote keys, a root saved before they were kept whole ("acme") also reads its anchor.
  const mayBeUpgraded = (group) => root.includes('/') && rootIsStored(group) && root.startsWith(`${group.projectRoot}/`);
  const anchorProjects = readConversationProjects(database, Object.values(ledger.groups.groups).filter((group) => !rootIsStored(group) || mayBeUpgraded(group)).map((group) => group.anchor));
  const groupRoot = (group) => rootIsStored(group) ? upgradedGroupRoot(group.projectRoot, projectRoot(anchorProjects.get(group.anchor))) : projectRoot(anchorProjects.get(group.anchor)) ?? group.projectRoot ?? null;
  // Every open request of the root: a new conversation may continue any of them.
  const openRequests = Object.entries(ledger.groups.groups)
    .filter(([groupId, group]) => groupRoot(group) === root && !CLOSED_STATES.has(ledger.progress[groupId]?.state))
    .map(([groupId, group]) => {
      const members = Object.entries(ledger.groups.conversations).filter(([, id]) => id === groupId).map(([key]) => byKey.get(key)).filter(Boolean);
      const asks = members.flatMap((member) => member.asks).sort((a, b) => Date.parse(b.at) - Date.parse(a.at) || b.promptId - a.promptId);
      return {
        groupId, title: group.title, anchor: group.anchor,
        anchorAsk: requestText(group.anchorAsk?.text ?? members[0]?.firstAsk ?? '', 400),
        recentAsks: asks.slice(0, 3).map((ask) => ask.text.slice(0, 200)),
        lastActivityEpoch: Math.max(0, ...members.map((member) => member.lastActivityEpoch ?? 0)),
      };
    })
    .sort((a, b) => b.lastActivityEpoch - a.lastActivityEpoch)
    .map(({ lastActivityEpoch, ...request }) => ({ ...request, lastActivityAt: iso(lastActivityEpoch) }));
  // Code-proven links (a shared work list or request id) between a new conversation and anything in its root.
  const batchKeys = new Set(batch.map((candidate) => candidate.conversationKey));
  const proposedLinks = linkBackwards(inRoot).proposedGroups.filter((group) => group.links.length && group.conversations.some((key) => batchKeys.has(key)))
    .flatMap((group) => group.links).map((link) => ({ ...link, groups: [...new Set(link.conversations.map((key) => ledger.groups.conversations[key]).filter(Boolean))] }));
  return {
    root,
    conversations: batch.map((candidate) => ({ conversationKey: candidate.conversationKey, project: candidate.project, startedAt: candidate.startedAt, openingAsk: requestText(candidate.firstAsk, 400), workLists: candidate.workLists })),
    openRequests, proposedLinks,
    remaining: fresh.length - batch.length,
  };
}

/** The grouping agent decides exactly the conversations it was sent: each
 * one joins an open request (listed after that request's anchor), starts a new
 * one, or is ignored. Nothing already decided may move.
 * With `coerce` (the refresh's one retry, as in validateProgress), what this check and `apply` would refuse is cut
 * from the answer instead, and each changed group or ignore entry is named in `coercedFields`. */
export function validateGroupingAnswer(answer, input, options = {}) {
  options = { coerce: false, coercedFields: new Set(), ...options };
  const asked = new Set(input.conversations.map((conversation) => conversation.conversationKey));
  const anchors = new Set(input.openRequests.map((request) => request.anchor));
  if (options.coerce) answer = coerceGroupingAnswer(answer, asked, anchors, options);
  const decided = new Set();
  for (const [index, group] of (Array.isArray(answer?.groups) ? answer.groups : []).entries()) {
    for (const [position, key] of (Array.isArray(group?.conversations) ? group.conversations : []).entries()) {
      if (asked.has(key)) { decided.add(key); continue; }
      if (position === 0 && anchors.has(key)) continue;
      throw new TypeError(`groups[${index}] lists ${key}, which was not asked about. Continue an open request by listing its anchor first, then only the new conversations.`);
    }
  }
  for (const [index, ignored] of (Array.isArray(answer?.ignored) ? answer.ignored : []).entries()) {
    if (!asked.has(ignored?.conversation)) throw new TypeError(`ignored[${index}] names a conversation that was not asked about.`);
    decided.add(ignored.conversation);
  }
  const missing = [...asked].filter((key) => !decided.has(key));
  if (missing.length) throw new TypeError(`Decide every conversation asked about; missing ${missing.join(', ')}.`);
  return answer;
}

/** A grouping answer without its unsupported parts. A key outside the batch goes (an open request's anchor may only
 * come first); a link keeps only its group's conversations and goes below two; a group is cut into the parts its links
 * connect, so a conversation no link ties to the anchor starts its own request under the same title, and a part
 * holding no asked conversation (an anchor left alone) goes; an ignore reason over 200 characters is shortened.
 * Nothing is joined without a link, and no asked conversation is dropped. */
function coerceGroupingAnswer(answer, asked, anchors, options) {
  const groups = (Array.isArray(answer?.groups) ? answer.groups : []).flatMap((group, index) => {
    if (!Array.isArray(group?.conversations)) return [group];
    const members = group.conversations.filter((key, position) => asked.has(key) || (position === 0 && anchors.has(key)));
    const links = (Array.isArray(group.links) ? group.links : [])
      .map((link) => ({ ...link, conversations: (Array.isArray(link?.conversations) ? link.conversations : []).filter((key) => members.includes(key)) }))
      .filter((link) => link.conversations.length >= 2);
    // The same union of linked conversations applyGroupDecisions checks against the anchor.
    const parent = new Map(members.map((key) => [key, key]));
    const find = (key) => { while (parent.get(key) !== key) key = parent.get(key); return key; };
    for (const link of links) for (const key of link.conversations.slice(1)) parent.set(find(key), find(link.conversations[0]));
    const parts = new Map();
    for (const key of members) parts.set(find(key), [...(parts.get(find(key)) ?? []), key]);
    if (parts.size === 1 && JSON.stringify([members, links]) === JSON.stringify([group.conversations, group.links ?? []])) return [group];
    options.coercedFields.add(`groups[${index}]`);
    return [...parts.values()].filter((part) => part.some((key) => asked.has(key)))
      .map((part) => ({ ...group, conversations: part, links: links.filter((link) => link.conversations.every((key) => part.includes(key))) }));
  });
  const ignored = (Array.isArray(answer?.ignored) ? answer.ignored : []).flatMap((entry, index) => {
    if (!asked.has(entry?.conversation)) { options.coercedFields.add(`ignored[${index}]`); return []; }
    return typeof entry.reason === 'string' && entry.reason.length > 200 ? [{ ...entry, reason: reviewText(entry.reason, 200, `ignored[${index}].reason`, options) }] : [entry];
  });
  return { ...answer, groups, ignored };
}

/** `apply` without the file: the decisions merged into `stored`, with every touched conversation's
 * project read from the database and each new group's first ask kept in the ledger (so a card's start
 * never moves forward when the anchor conversation ages out of My Work's reads). Returns the next
 * ledger without writing it. */
export function applyDecisions(stored, decisions, { database, now = Date.now(), excludedPromptIds = null, enrichGroupIds = null }) {
  // Every conversation the decisions touch, and the members their groups already hold, by project.
  const touched = (decisions?.groups ?? []).flatMap((group) => Array.isArray(group?.conversations) ? group.conversations : []).filter(isConversationKey);
  const touchedGroups = new Set(touched.map((key) => groupIdFor(key)));
  const existing = Object.entries(stored?.conversations ?? {}).filter(([, id]) => touchedGroups.has(id)).map(([key]) => key);
  const next = applyGroupDecisions(stored, decisions, now, { projectOf: readConversationProjects(database, [...touched, ...existing]) });
  const missing = Object.entries(next.groups).filter(([id, group]) => !group.anchorAsk && (enrichGroupIds === null || enrichGroupIds.includes(id))).map(([, group]) => group.anchor);
  const anchors = new Map(readCandidates(database, { conversationKeys: missing, excludedPromptIds }).map((candidate) => [candidate.conversationKey, candidate.original]));
  for (const group of Object.values(next.groups)) if (!group.anchorAsk && anchors.has(group.anchor)) group.anchorAsk = anchors.get(group.anchor);
  return next;
}

/**
 * localDeviceId: the worker's sync device id ("" when cloud sync never started), required by focus-input, record-focus,
 * sub-focus-input, record-sub-focus and refresh-needs so my-focus rows replay in the worker's order.
 * saveFocus(body): writes a checked record-focus or record-sub-focus answer through the worker and resolves
 * {placed, focusAreaIds}; it throws a TypeError when the worker refused the answer before writing anything. record-focus
 * and record-sub-focus return a promise.
 * judge: the Jev judge for the `judge` command: undefined reads it from the install's settings
 * (request-judge.mjs configuredJudge), null routes with code links only. That command returns a promise.
 */
export function runCli(argv, { dir = LEDGER_DIR, database = null, now = Date.now(), print = (value) => console.log(JSON.stringify(value, null, 2)), localDeviceId, saveFocus = null, judge = undefined, coerceProgress = false } = {}) {
  const [command, ...args] = argv;
  const db = () => database ?? openDatabase();
  const since = () => now - option(args, 'days', 14) * DAY_MS;
  if (command === 'candidates') {
    const wantedRoot = textOption(args, 'project');
    const ledger = readLedger(dir);
    const stored = ledger.groups;
    const candidates = readCandidates(db(), { sinceEpoch: since(), excludedPromptIds: ledger.agentWrittenPromptIds })
      .filter((candidate) => !stored.ignored?.[candidate.conversationKey] && (wantedRoot == null || projectRoot(candidate.project) === wantedRoot));
    const { proposedGroups, skippedLists } = linkBackwards(candidates);
    const brief = args.includes('--brief');
    const shown = candidates.map(({ lastActivityEpoch, startedAtEpoch, original, ...candidate }) => {
      const currentGroup = stored.conversations[candidate.conversationKey] ?? null;
      return brief
        ? { conversationKey: candidate.conversationKey, project: candidate.project, startedAt: candidate.startedAt, lastActivityAt: candidate.lastActivityAt, firstAsk: candidate.firstAsk.slice(0, 200), laterAsks: candidate.asks.slice(1, 4).map((ask) => ask.text.slice(0, 120)), workLists: candidate.workLists, currentGroup }
        : { ...candidate, currentGroup };
    });
    return print({ candidates: shown, proposedGroups: proposedGroups.filter((group) => group.links.length), skippedLists, projects: [...new Set(candidates.map((candidate) => projectRoot(candidate.project)))] });
  }
  if (command === 'grouping-input') return print(groupingInput(readLedger(dir), db(), { sinceEpoch: since(), limit: option(args, 'limit', GROUPING_BATCH) }));
  if (command === 'judge') {
    // Imported here, not at the top: the judge module builds on this one.
    return import('./request-judge.mjs')
      .then(({ configuredJudge, routeUndecided }) => routeUndecided({ dir, database: db(), judge: judge === undefined ? configuredJudge() : judge, now, days: option(args, 'days', 14), apply: args.includes('--apply') }))
      .then(print);
  }
  if (command === 'apply') {
    const ledger = readLedger(dir);
    const next = applyDecisions(ledger.groups, readInput(args[0] ?? '-'), { database: db(), now, excludedPromptIds: ledger.agentWrittenPromptIds });
    writeJsonAtomic(join(dir, 'request-groups.json'), next, { readHash: readHashOf(ledger, 'request-groups.json') });
    return print({ groups: Object.keys(next.groups).length, conversations: Object.keys(next.conversations).length });
  }
  if (command === 'pending' || command === 'show') {
    const ledger = readLedger(dir);
    if (command === 'show') {
      if (!ledger.groups.groups[args[0]]) throw new TypeError(`Unknown group ${args[0]}.`);
      const keys = Object.entries(ledger.groups.conversations).filter(([, id]) => id === args[0]).map(([key]) => key);
      const candidates = new Map(readCandidates(db(), { conversationKeys: keys, fullAsks: true, excludedPromptIds: ledger.agentWrittenPromptIds }).map((candidate) => [candidate.conversationKey, candidate]));
      const details = groupDetails(args[0], ledger, candidates);
      // Same conversations as the previous review: the reviewer amends it from what happened since.
      // A membership change (a merge, a split) needs a full review.
      const previous = details.previousReview;
      const amendSince = previous && reviewIsCurrent(previous, keys, 0) ? previous.reviewedThrough : null;
      const since = amendSince ? Date.parse(amendSince) : 0;
      // The conversations' own observations (only the new ones when amending), so a reviewer without memory tools has the evidence.
      const observations = db().prepare(`SELECT o.id, o.type, o.title, o.subtitle, o.created_at_epoch FROM observations o
        JOIN sdk_sessions s ON o.memory_session_id = s.memory_session_id
        WHERE s.platform_source = ? AND s.content_session_id = ? AND o.created_at_epoch > ? ORDER BY o.created_at_epoch, o.id`);
      const conversations = details.conversations.map((conversation) => {
        const [, platform, sessionId] = JSON.parse(conversation.conversationKey);
        return {
          ...conversation,
          ...(conversation.asks && amendSince ? { asks: conversation.asks.filter((ask) => Date.parse(ask.at) > since) } : {}),
          observations: observations.all(platform, sessionId, since).map((row) => ({ id: row.id, at: iso(row.created_at_epoch), type: row.type, title: row.title, subtitle: row.subtitle })),
        };
      });
      // The reviewer passes reviewBasis back to record-progress unchanged.
      return print({ ...details, conversations, mode: amendSince ? 'amend' : 'full', amendSince, reviewBasis: { checkedThrough: iso(now), conversations: keys.sort() } });
    }
    const { due, ungrouped } = pendingReviews(ledger, db(), since());
    const limit = option(args, 'limit', 48);
    return print({ due: due.length, groups: due.slice(0, limit).map((group) => ({ groupId: group.groupId, title: group.title, lastActivityAt: group.lastActivityAt, conversations: group.conversations.length })), deferred: Math.max(0, due.length - limit), ungroupedConversations: ungrouped });
  }
  if (command === 'record-progress') {
    const ledger = readLedger(dir);
    const coercedFields = new Set(), droppedPreferences = new Set();
    const reviewed = validateProgress(readInput(args[0] ?? '-'), ledger.groups.groups, { coerce: coerceProgress, coercedFields, droppedPreferences });
    const checkedAt = iso(now);
    const previous = ledger.progress[reviewed.groupId];
    // The story is retold only from reviews whose facts moved; reworded prose and review timestamps are not news.
    const unchanged = previous && JSON.stringify(storyFacts(previous)) === JSON.stringify(storyFacts(reviewed));
    const entry = { ...reviewed, checkedAt, changedAt: unchanged ? previous.changedAt ?? previous.checkedAt : checkedAt, readings: appendReading(ledger.progress[reviewed.groupId], { at: checkedAt, percent: reviewed.percent }) };
    writeJsonAtomic(join(dir, 'progress', `${entry.groupId}.json`), entry, { readHash: readHashOf(ledger, `progress/${entry.groupId}.json`) });
    return print({ recorded: entry.groupId, state: entry.state, percent: entry.percent, readings: entry.readings.length, ...(coercedFields.size ? { coercedFields: [...coercedFields] } : {}),
      ...(droppedPreferences.size ? { droppedPreferences: [...droppedPreferences] } : {}) });
  }
  if (command === 'title-input') return print(titleInput(readLedger(dir), db(), { limit: option(args, 'limit', TITLE_BATCH) }));
  if (command === 'record-titles') {
    const ledger = readLedger(dir), { groups } = ledger;
    const answer = readInput(args[0] ?? '-');
    if (!Array.isArray(answer?.titles)) throw new TypeError('The answer needs a titles array.');
    let titled = 0;
    // Every title is checked before the ledger is written. Only a placeholder is replaced: a title written meanwhile
    // (a grouping answer, another device) stays.
    for (const [index, entry] of answer.titles.entries()) {
      const group = groups.groups[entry?.groupId];
      if (!group) throw new TypeError(`titles[${index}] names unknown group ${entry?.groupId}.`);
      const title = writtenTitle(entry.title, group.anchorAsk?.text ?? null, `titles[${index}].title`);
      if (hasPlaceholderTitle(group)) { group.title = title; titled++; }
    }
    if (titled) { groups.updatedAt = iso(now); writeJsonAtomic(join(dir, 'request-groups.json'), groups, { readHash: readHashOf(ledger, 'request-groups.json') }); }
    return print({ titled, kept: answer.titles.length - titled });
  }
  if (command === 'story-input') {
    const { groups, progress, story } = readLedger(dir);
    const reviews = Object.values(progress).sort((a, b) => String(a.startedAt).localeCompare(String(b.startedAt)));
    // With a previous story, only reviews whose facts changed after it was written.
    const writtenAt = Date.parse(story?.writtenAt ?? '');
    return print(storyInput(Object.keys(groups.groups).length,
      Number.isFinite(writtenAt) ? reviews.filter((review) => Date.parse(review.changedAt ?? review.checkedAt) > writtenAt) : reviews, story,
      dismissedRuleStatements(db(), { localDeviceId })));
  }
  // The words owner-goals is told never to propose again (plugin/skills/owner-goals/SKILL.md), read as story-input reads them.
  if (command === 'dismissed-rules') return print({ dismissedRules: dismissedRuleStatements(db(), { localDeviceId }) });
  if (command === 'record-story') {
    const validated = validateStory(readInput(args[0] ?? '-'));
    // Rules owner-goals found in the owner's prompts (save_goals.py) are its to replace, not the story's.
    const ledger = readLedger(dir);
    const fromOwnerGoals = (ledger.story?.preferences ?? []).filter((preference) => preference?.source === OWNER_GOALS_LIST);
    const story = { ...validated, preferences: [...validated.preferences, ...fromOwnerGoals], writtenAt: iso(now) };
    writeJsonAtomic(join(dir, 'story.json'), story, { readHash: readHashOf(ledger, 'story.json') });
    return print({ recorded: 'story', preferences: story.preferences.length });
  }
  // focus-input and record-focus take the same flags, so record-focus checks the answer against the input it answers.
  const focusQuestion = () => {
    const ledger = readLedger(dir), focus = readFocus(db(), { localDeviceId: requireDeviceId(localDeviceId) });
    const other = args.includes('--other');
    return { ledger, other, input: other ? otherInput(ledger, focus, localDeviceId, db()) : focusInput(ledger, focus, localDeviceId, db(), { limit: option(args, 'limit', FOCUS_BATCH) }) };
  };
  if (command === 'focus-input') return print(focusQuestion().input);
  if (command === 'record-focus') {
    // My Focus rows sync, so they are written by the worker, never by this read-only CLI: saveFocus posts the
    // checked answer to the worker's system-only route (POST /api/work-view/focus/router), or calls the same
    // write in-process when the worker's own refresh runs this command.
    if (!saveFocus) throw new Error('record-focus saves through the claude-mem worker, and none was given.');
    const { ledger, other, input } = focusQuestion();
    const file = args.filter((arg, index) => !arg.startsWith('--') && args[index - 1] !== '--limit').at(-1) ?? '-';
    const body = validateFocusAnswer(readInput(file), input, ledger, { other });
    return Promise.resolve(saveFocus(body)).then((saved) => print({ placed: saved.placed, proposed: saved.focusAreaIds.length, focusAreaIds: saved.focusAreaIds }));
  }
  if (command === 'sub-focus-input' || command === 'record-sub-focus') {
    const ledger = readLedger(dir), focus = readFocus(db(), { localDeviceId: requireDeviceId(localDeviceId) });
    const focusAreaId = textOption(args, 'area');
    if (command === 'sub-focus-input') {
      if (focusAreaId) return print(subFocusInput(ledger, focus, focusAreaId, db()));
      const listed = ({ area, groupIds }) => ({ focusAreaId: area.focusAreaId, name: area.name, requests: groupIds.length });
      const { due, failed } = subFocusAreas(ledger, focus, db());
      return print({ due: due.map(listed), failed: failed.map(listed) });
    }
    // Saved through the worker, like record-focus: sub focus rows are my-focus rows, which sync.
    if (!saveFocus) throw new Error('record-sub-focus saves through the claude-mem worker, and none was given.');
    if (!focusAreaId) throw new TypeError('record-sub-focus needs --area <focusAreaId>, the area sub-focus-input --area asked about.');
    const file = args.filter((arg, index) => !arg.startsWith('--') && args[index - 1] !== '--area').at(-1) ?? '-';
    const body = validateSubFocusAnswer(readInput(file), subFocusInput(ledger, focus, focusAreaId, db()));
    return Promise.resolve(saveFocus(body)).then(() => print(subFocusAnswerCounts(body)));
  }
  if (command === 'refresh-needs') return print(refreshNeeds({ dir, database: db(), now, days: option(args, 'days', 14), localDeviceId }));
  throw new TypeError('Usage: request-groups.mjs candidates|grouping-input|judge|apply|pending|show|record-progress|title-input|record-titles|story-input|record-story|dismissed-rules|focus-input|record-focus|sub-focus-input|record-sub-focus|refresh-needs (see file header).');
}