Persistent Context Across Sessions for Every Agent – Captures everything your agent does during sessions, compresses it with AI, and injects relevant context back into future sessions. Works with Claude Code, OpenClaw, Codex, Gemini, Hermes, Copilot, OpenCode + More
TypeScript aiai-agentsai-memoryanthropicartificial-intelligencechromadbclaudeclaude-agent-sdkclaude-agentsclaude-codeclaude-code-pluginclaude-skillsembeddingslong-term-memorymem0memory-engineopenmemoryragsqlitesupermemory
fix(work-view): size review questions to fit and fill reviewBasis from show (#6767)
wangshundb3c67464a0b
diff --git a/docs/public/configuration.mdx b/docs/public/configuration.mdxindex 131adc105..f0498e674 100644--- a/docs/public/configuration.mdx+++ b/docs/public/configuration.mdx@@ -260,6 +260,7 @@ The goals step updates a saved snapshot from new owner prompts, including a snap| `CLAUDE_MEM_WORK_VIEW_API_MODEL` | empty | Model for every refresh step on the selected API provider, such as `anthropic/claude-sonnet-4`. Empty keeps the model your provider is configured with. || `CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS` | `600000` | Deadline in milliseconds for one My Work API refresh question, including compatibility retries. Accepts a whole number from 1 to 2147483647. || `CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS` | `16000` | Maximum output tokens per My Work API refresh answer. Accepts a positive whole number. The endpoint receives the same cap when it requires `max_completion_tokens` in place of `max_tokens`. |+| `CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH` | `8` | Most request groups one review question carries, on every agent. Each question is also measured against the refresh's input budget (about 640 KiB, roughly 164k tokens) and split before it would pass it. Lower it, for example to `3`, for a model with a small context window. Accepts a positive whole number; an invalid value uses the default and logs a warning. || `CLAUDE_MEM_API_AGENT_EXTRA_BODY` | empty | JSON object merged into every request of the `api` agent, for refresh steps and for corpus questions with `CLAUDE_MEM_CORPUS_AGENT=api`. A Qwen model on vLLM ignores the `reasoning: { enabled: false }` the agent sends. Set `{"chat_template_kwargs":{"enable_thinking":false}}` to turn its thinking off. Anything but a JSON object is ignored with a warning in the worker log. It cannot set `model`, `models`, `messages`, `stream`, `stream_options`, `max_tokens`, `max_completion_tokens`, `reasoning` or `response_format`, and it is not sent to the cmem.ai gateway. Settings file or environment only. || `CLAUDE_MEM_WORK_VIEW_TEXT_LANGUAGE` | empty | Language for the text the refresh writes (request titles, reviews, focus areas, the story), such as `Turkish`. When set, every step except goals is told to write in it, so separate review batches never pick different languages. Empty uses the language most of your asks are written in, decided once per refresh by the grouping step (which already reads them, so it costs no extra model call) and kept for later refreshes that have nothing to group. |diff --git a/src/services/work-view/refresh-task.ts b/src/services/work-view/refresh-task.tsindex 8387a36e4..87a3ca4ed 100644--- a/src/services/work-view/refresh-task.ts+++ b/src/services/work-view/refresh-task.ts@@ -53,6 +53,14 @@ export function reviewConcurrency(dataDir: string): number {?? parseInt(SettingsDefaultsManager.getAllDefaults().CLAUDE_MEM_MAX_CONCURRENT_AGENTS, 10);}+/** The most groups one review question may carry, from CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH (#6766). Each question is+ * also measured against OWNER_GOALS_QUESTION_BYTES, so this caps the count; it is not the only size control. No upper+ * bound of its own: the measured question is the limit that protects the model's window. */+export function reviewBatchSize(dataDir: string): number {+ const settings = SettingsDefaultsManager.loadFromFile(join(dataDir, 'settings.json'), true, { readOnly: true });+ return workViewLimit('CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH', settings.CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH, Number.MAX_SAFE_INTEGER, REVIEW_BATCH);+}+/** The model each step runs on. Small, fast models match conversations and goals and name requests from their* reviews; stronger ones judge progress, write the story and pick verbatim quotes. Codex's careful steps use its CLI* default model. Ids checked against claude --help (aliases), codex-cli 0.163.0 models_cache.json and gemini 0.49.0 aliases. */@@ -102,16 +110,16 @@ export interface RefreshAgentChoice {const LOCAL_AGENT_IDS: readonly UsableAgentId[] = ['claude-code', 'codex', 'gemini', 'opencode'];-const warnedApiAgentLimits = new Set<string>();+const warnedWorkViewLimits = new Set<string>();-/** One limit setting, or its default. A set but invalid value warns once per value, naming the default used. */-function apiAgentLimit(key: 'CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS' | 'CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS', raw: unknown, max: number, defaultValue: number): number {+/** One positive whole-number limit setting, or its default. A set but invalid value warns once per value, naming the default used. */+function workViewLimit(key: 'CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS' | 'CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS' | 'CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH', raw: unknown, max: number, defaultValue: number): number {const parsed = parseBoundedNumber(raw as string | number | undefined, { min: 1, max, integer: true });if (parsed !== null) return parsed;const text = typeof raw === 'number' ? String(raw) : typeof raw === 'string' ? raw.trim() : '';- if (text && !warnedApiAgentLimits.has(`${key}=${text}`)) {- warnedApiAgentLimits.add(`${key}=${text}`);- logger.warn('WORKER', `Invalid ${key}; the My Work API refresh uses the default`, { value: text, min: 1, max, default: defaultValue });+ if (text && !warnedWorkViewLimits.has(`${key}=${text}`)) {+ warnedWorkViewLimits.add(`${key}=${text}`);+ logger.warn('WORKER', `Invalid ${key}; the My Work refresh uses the default`, { value: text, min: 1, max, default: defaultValue });}return defaultValue;}@@ -120,8 +128,8 @@ function apiAgentLimit(key: 'CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS' | 'CLAUDE_MEM_function resolveApiAgentLimits(settings: SettingsDefaults): ApiAgentLimits {return {// Longer delays overflow a signed 32-bit runtime timer and can expire immediately.- timeoutMs: apiAgentLimit('CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS', settings.CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS, 2_147_483_647, DEFAULT_API_AGENT_LIMITS.timeoutMs),- maxOutputTokens: apiAgentLimit('CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS', settings.CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS, Number.MAX_SAFE_INTEGER, DEFAULT_API_AGENT_LIMITS.maxOutputTokens),+ timeoutMs: workViewLimit('CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS', settings.CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS, 2_147_483_647, DEFAULT_API_AGENT_LIMITS.timeoutMs),+ maxOutputTokens: workViewLimit('CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS', settings.CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS, Number.MAX_SAFE_INTEGER, DEFAULT_API_AGENT_LIMITS.maxOutputTokens),};}@@ -841,8 +849,16 @@ export function buildRefreshTask(options: RefreshTaskOptions): AgentTask & {* and the refresh goes on. A review that was given and could not be saved (the check refused it, or the write* failed) still fails the batch unless its retry is saved: leaving that group out on the retry does not* forgive it, so a write that keeps failing is never reported as a group the model left out. */- const reviewBatch = async (groups: Array<{ groupId: string }>, rule: string) => {- let shows = groups.map(group => cli(['show', group.groupId]));+ /** One review question, exactly as asked. Packing measures it with measuredQuestionBytes, which adds the language+ * line the way the first ask does, so the measured bytes are the bytes sent. */+ const reviewQuestion = (showPath: string, rule = '', retryNote = '') => [+ requestProgress, '---', readOnly,+ `Do only section 2's review for the groups whose \`show\` output is in ${showPath}: decide each one from the evidence as the reviewer task describes (amend the previous review for a group in "amend" mode). Reply with only {"reviews": [<one record-progress input per group>]}. The worker fills reviewBasis from the show output, so you may leave it out.`,+ rule,+ retryNote,+ ].filter(Boolean).join('\n\n');+ const reviewBatch = async (batchShows: any[], firstShowPath: string, rule: string) => {+ let shows = batchShows;let refusals: string[] = [];let rejectedReviews: Array<{ groupId?: string }> = [];/** Why a review that was given could not be saved, by group, from either ask. */@@ -853,12 +869,8 @@ export function buildRefreshTask(options: RefreshTaskOptions): AgentTask & {const retryGroupIds = new Set(shows.map(show => show.groupId));let text: string;try {- text = await ask([- requestProgress, '---', readOnly,- `Do only section 2's review for the groups whose \`show\` output is in ${writeInput('show', shows)}: decide each one from the evidence as the reviewer task describes (amend the previous review for a group in "amend" mode). Reply with only {"reviews": [<one record-progress input per group, with reviewBasis copied verbatim from its show output>]}.`,- rule,- refusals.length ? `Your previous answer was refused for these groups:\n${refusals.join('\n')}\nFix them and answer again for those groups only. Here are the rejected reviews to correct, preserving their evidence and reviewBasis:\n${JSON.stringify(rejectedReviews)}` : '',- ].filter(Boolean).join('\n\n'), stepModels.review);+ text = await ask(reviewQuestion(attempt === 0 ? firstShowPath : writeInput('show', shows), rule,+ refusals.length ? `Your previous answer was refused for these groups:\n${refusals.join('\n')}\nFix them and answer again for those groups only. Here are the rejected reviews to correct, preserving their evidence:\n${JSON.stringify(rejectedReviews)}` : ''), stepModels.review);} catch (error) {// A review answer the provider cut off arrives as an error carrying the raw text, the same// shape askAndSave handles: keep it and fail with its path first, instead of losing the one@@ -874,7 +886,12 @@ export function buildRefreshTask(options: RefreshTaskOptions): AgentTask & {refusals = [];rejectedReviews = [];const recorded = new Set<string>();- for (const review of reviews) {+ const withShownBasis = (review: { groupId?: string }) => {+ const show = batchShows.find(candidate => candidate.groupId === review?.groupId);+ return show ? { ...review, reviewBasis: show.reviewBasis } : review;+ };+ for (const answer of reviews) {+ const review = withShownBasis(answer);if (attempt > 0) firstRefused.delete(String(review.groupId));try {// Keep the first pass strict so the model can correct an oversized answer itself. If that same group@@ -921,17 +938,38 @@ export function buildRefreshTask(options: RefreshTaskOptions): AgentTask & {// Batches are independent, so a few run at once; every batch finishes (and saves) before a failure is reported.// Not all at once: each batch is its own agent process, and a large backlog (Oct 25: ~1,100 due groups,// 138 batches) started every one of them in the same millisecond.- const batches: Array<Array<{ groupId: string }>> = [];- for (let index = 0; index < due.length; index += REVIEW_BATCH) batches.push(due.slice(index, index + REVIEW_BATCH));+ // Each batch is cut when its lane takes it, not up front: groups are added while the question, measured as it will be+ // asked (skill, instructions, shows inline, language line), fits OWNER_GOALS_QUESTION_BYTES and the count stays within+ // CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH (#6766). A show is read just before its question, so only the shows of running+ // batches are held. A group too large for a question of its own is still sent alone, as before.+ const maxBatch = reviewBatchSize(dataDir);+ let nextDue = 0;+ /** A show read for a batch it did not fit; it opens the next batch. */+ let carried: any = null;+ const nextReviewBatch = () => {+ const showPath = writeInput('show', '');+ const batch: any[] = [];+ while (batch.length < maxBatch && (carried || nextDue < due.length)) {+ const show = carried ?? cli(['show', due[nextDue++].groupId]);+ carried = null;+ if (batch.length && measuredQuestionBytes(showPath, JSON.stringify([...batch, show], null, 2), reviewQuestion(showPath)) > OWNER_GOALS_QUESTION_BYTES) { carried = show; break; }+ batch.push(show);+ }+ // The file the first ask names holds exactly this batch.+ const bytes = measuredQuestionBytes(showPath, JSON.stringify(batch, null, 2), reviewQuestion(showPath));+ if (bytes > OWNER_GOALS_QUESTION_BYTES) logger.warn('WORKER', 'A review question for one group exceeds the input budget; it is sent alone', { groupId: batch[0]?.groupId, bytes, budget: OWNER_GOALS_QUESTION_BYTES });+ return { batch, showPath };+ };const outcomes: PromiseSettledResult<void>[] = [];- let next = 0;const lane = async () => {- while (next < batches.length) {- const batch = batches[next++];- outcomes.push(...await Promise.allSettled([timed('review', () => reviewBatch(batch, languageRule()), { groups: batch.length })]));+ while (carried || nextDue < due.length) {+ outcomes.push(...await Promise.allSettled([(async () => {+ const { batch, showPath } = nextReviewBatch();+ await timed('review', () => reviewBatch(batch, showPath, languageRule()), { groups: batch.length });+ })()]));}};- await Promise.all(Array.from({ length: Math.min(reviewConcurrency(dataDir), batches.length) }, lane));+ await Promise.all(Array.from({ length: Math.min(reviewConcurrency(dataDir), due.length) }, lane));const failed = outcomes.filter(outcome => outcome.status === 'rejected');if (failed.length) throw (failed[0] as PromiseRejectedResult).reason;const reviewNotes = [...(coercedReviewFields.size ? [`${coercedReviewFields.size} fields trimmed or dropped after retry`] : []),diff --git a/src/shared/SettingsDefaultsManager.ts b/src/shared/SettingsDefaultsManager.tsindex f6f2a74f1..ec675a4b0 100644--- a/src/shared/SettingsDefaultsManager.ts+++ b/src/shared/SettingsDefaultsManager.ts@@ -481,6 +481,7 @@ export interface SettingsDefaults {CLAUDE_MEM_WORK_VIEW_API_MODEL: string;CLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS: string;CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS: string;+ CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH: string;CLAUDE_MEM_CORPUS_AGENT: string;CLAUDE_MEM_API_AGENT_EXTRA_BODY: string;CLAUDE_MEM_WORK_VIEW_TEXT_LANGUAGE: string;@@ -836,6 +837,7 @@ export class SettingsDefaultsManager {CLAUDE_MEM_WORK_VIEW_API_MODEL: '', // Model for every My Work refresh step on the selected API provider; empty keeps the provider's configured modelCLAUDE_MEM_WORK_VIEW_API_TIMEOUT_MS: String(DEFAULT_API_AGENT_LIMITS.timeoutMs),CLAUDE_MEM_WORK_VIEW_MAX_OUTPUT_TOKENS: String(DEFAULT_API_AGENT_LIMITS.maxOutputTokens),+ CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH: '8', // Most groups one review question carries; each question is also measured against the refresh's input budget and split before it would pass it (#6766). File/env only.CLAUDE_MEM_CORPUS_AGENT: '', // Which agent answers knowledge-corpus prime/query/reprime: '' uses the Claude Agent SDK (the Claude subscription); 'api' answers over chat completions on the selected openrouter/openai-compatible provider and spends that provider's creditCLAUDE_MEM_API_AGENT_EXTRA_BODY: '', // JSON object merged into every api agent request (My Work refresh, corpus), e.g. {"chat_template_kwargs":{"enable_thinking":false}} for vLLM (#6223). Parsed like CLAUDE_MEM_OPENROUTER_EXTRA_BODY; never sets reasoning or response_format. File/env onlyCLAUDE_MEM_WORK_VIEW_TEXT_LANGUAGE: '', // Language for My Work's generated text (titles, reviews, story), such as 'Turkish'. No extra model call; empty uses the language the grouping step finds in the owner's asks, decided once per run (#5660)diff --git a/tests/work-view/auto-refresh.test.ts b/tests/work-view/auto-refresh.test.tsindex 60f70a3ca..05d5e6e7b 100644--- a/tests/work-view/auto-refresh.test.ts+++ b/tests/work-view/auto-refresh.test.ts@@ -514,14 +514,19 @@ describe('refresh task', () => {}, 'gemini');};- it('a review missing reviewBasis is refused once and saved when the retry supplies it', async () => {+ it('a review missing reviewBasis is saved with the show value on its first answer', async () => {const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-basis-'));try {- const review = (show: any) => ({ groupId: show.groupId, state: 'in-progress', percent: 40, summary: 'Cards are being built.' });- const summary = await runRefreshWithReviewAnswers(dir, (show, attempt) => attempt === 0 ? review(show) : { ...review(show), reviewBasis: show.reviewBasis });+ let shown: any;+ let attempts = 0;+ const review = (show: any) => { shown = show; attempts++; return { groupId: show.groupId, state: 'in-progress', percent: 40, summary: 'Cards are being built.' }; };+ const summary = await runRefreshWithReviewAnswers(dir, show => review(show));+ expect(attempts).toBe(1);expect(summary).toBe('1 new conversations grouped, 1 requests reviewed, 1 requests placed, story written.');const [saved] = Object.values(readLedger(dir).progress) as any[];expect(saved.percent).toBe(40);+ expect(saved.reviewedThrough).toBe(shown.reviewBasis.checkedThrough);+ expect(saved.reviewedConversations).toEqual([...shown.reviewBasis.conversations].sort());expect(saved.coercedFields).toBeUndefined();} finally { rmSync(dir, { recursive: true, force: true }); }});@@ -591,17 +596,23 @@ describe('refresh task', () => {} finally { database.close(); rmSync(dir, { recursive: true, force: true }); }});- it('a retry still missing reviewBasis fails the run naming the group and saves no review', async () => {+ it('a review carrying a wrong reviewBasis is saved with the show value, without a retry', async () => {const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-basis-'));try {- let groupId = '';+ let shown: any;+ let attempts = 0;const run = runRefreshWithReviewAnswers(dir, show => {- groupId = show.groupId;- return { groupId: show.groupId, state: 'in-progress', percent: 40, summary: 'x'.repeat(292) };+ shown = show;+ attempts++;+ return { groupId: show.groupId, state: 'in-progress', percent: 40, summary: 'Cards are being built.', reviewBasis: { checkedThrough: 'not-a-date', conversations: [] } };});- const failure: Error = await run.then(() => { throw new Error('the run should have failed'); }, error => error);- expect(failure.message).toContain(`${groupId}: reviewBasis must be copied verbatim`);- expect(readLedger(dir).progress).toEqual({});+ const summary = await run;+ expect(attempts).toBe(1);+ expect(summary).toBe('1 new conversations grouped, 1 requests reviewed, 1 requests placed, story written.');+ const [saved] = Object.values(readLedger(dir).progress) as any[];+ expect(saved.reviewedThrough).toBe(shown.reviewBasis.checkedThrough);+ expect(saved.reviewedConversations).toEqual([...shown.reviewBasis.conversations].sort());+ expect(saved.coercedFields).toBeUndefined();} finally { rmSync(dir, { recursive: true, force: true }); }});@@ -2149,6 +2160,92 @@ describe('My Work text language setting (CLAUDE_MEM_WORK_VIEW_TEXT_LANGUAGE)', (});describe('parallel reviews', () => {+ /** A fixture with one due group for each supplied conversation, all decided and ready for review. */+ function groupedBacklog(dir: string, prompts: Array<{ session: string; text: string }>) {+ const database = fixtureDatabase();+ for (const [index, prompt] of prompts.entries()) {+ const existing = database.prepare('SELECT id FROM sdk_sessions WHERE content_session_id = ?').get(prompt.session) as { id: number } | null;+ if (existing) {+ database.prepare('UPDATE sdk_sessions SET user_prompt = ? WHERE id = ?').run(prompt.text, existing.id);+ database.prepare('UPDATE user_prompts SET prompt_text = ? WHERE session_db_id = ?').run(prompt.text, existing.id);+ } else {+ database.prepare('INSERT INTO sdk_sessions VALUES (?, ?, ?, ?, ?, ?, ?)').run(index + 2, 'claude', prompt.session, `m${index + 2}`, 'repo/tree', prompt.text, NOW - 2 * DAY);+ database.prepare('INSERT INTO user_prompts (session_db_id, prompt_number, prompt_text, created_at_epoch) VALUES (?, ?, ?, ?)').run(index + 2, 1, prompt.text, NOW - 2 * DAY);+ }+ }+ const decisions = join(dir, 'decisions.json');+ writeFileSync(decisions, JSON.stringify({ groups: prompts.map(prompt => ({ title: `Feature ${prompt.session}`, conversations: [key(prompt.session)] })) }));+ runCli(['apply', decisions], { dir, database, now: NOW, print: () => {} });+ return database;+ }++ it('packs a review question by its show output so large groups cannot overflow a small context window (#6766)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-review-bytes-'));+ const long = 'Build the release cards. ' + 'Details about the release. '.repeat(8500);+ const prompts = ['a', 'b', 'c'].map(session => ({ session, text: long }));+ const database = groupedBacklog(dir, prompts);+ try {+ const task = buildRefreshTask({ localDeviceId: () => '', needs: { due: prompts.length, ungrouped: 0, goalsStale: false, unplaced: 0, needed: true }, reason: 'scheduled', dataDir: dir, ledgerDir: dir, pluginRoot: PLUGIN_ROOT, openDatabase: handle(database), now: () => NOW, saveFocus: focusWriter(database).save });+ const batchSizes: number[] = [];+ const ask = async (prompt: string) => {+ if (prompt.includes('Do only section 5')) return JSON.stringify({ narrative: 'Features under way.' });+ if (prompt.includes('Do only section 4')) return everyRequestInOther(prompt);+ const shows = JSON.parse(readFileSync(/is in (.+?\.json)/.exec(prompt)![1], 'utf8'));+ batchSizes.push(shows.length);+ return JSON.stringify({ reviews: shows.map((show: any) => ({ groupId: show.groupId, state: 'in-progress', percent: 30, summary: 'Under way.', reviewBasis: show.reviewBasis })) });+ };+ expect(await task.run(ask, 'claude-code')).toBe('3 requests reviewed, 3 requests placed, story written.');+ // Two large shows fit the show budget under a 160k-token question; the third needs its own question.+ expect(batchSizes).toEqual([2, 1]);+ } finally { database.close(); rmSync(dir, { recursive: true, force: true }); }+ });++ it('measures the whole review question, so shows that fit the budget alone are split when the skill text pushes the question over it (#6766)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-review-question-'));+ // Sized so the two shows together come to about 625 KiB: under the 640 KiB budget on their own, over it once the+ // ~30 KB request-progress skill and the instructions around them are counted.+ const long = 'Build the release cards. ' + 'Details about the release. '.repeat(11750);+ const prompts = ['a', 'b'].map(session => ({ session, text: long }));+ const database = groupedBacklog(dir, prompts);+ try {+ const task = buildRefreshTask({ localDeviceId: () => '', needs: { due: prompts.length, ungrouped: 0, goalsStale: false, unplaced: 0, needed: true }, reason: 'scheduled', dataDir: dir, ledgerDir: dir, pluginRoot: PLUGIN_ROOT, openDatabase: handle(database), now: () => NOW, saveFocus: focusWriter(database).save });+ const reviewQuestions: Array<{ groups: number; bytes: number; showBytes: number }> = [];+ const ask = async (prompt: string) => {+ if (prompt.includes('Do only section 5')) return JSON.stringify({ narrative: 'Features under way.' });+ if (prompt.includes('Do only section 4')) return everyRequestInOther(prompt);+ const contents = readFileSync(/is in (.+?\.json)/.exec(prompt)![1], 'utf8');+ const shows = JSON.parse(contents);+ reviewQuestions.push({ groups: shows.length, bytes: Buffer.byteLength(prompt, 'utf8'), showBytes: Buffer.byteLength(contents, 'utf8') });+ return JSON.stringify({ reviews: shows.map((show: any) => ({ groupId: show.groupId, state: 'in-progress', percent: 30, summary: 'Under way.' })) });+ };+ // Gemini is sent the expanded question (input files inline), so the bytes seen here are the bytes sent.+ expect(await task.run(ask, 'gemini')).toBe('2 requests reviewed, 2 requests placed, story written.');+ expect(reviewQuestions.map(question => question.groups)).toEqual([1, 1]);+ expect(reviewQuestions.reduce((total, question) => total + question.showBytes, 0)).toBeLessThan(OWNER_GOALS_QUESTION_BYTES);+ for (const question of reviewQuestions) expect(question.bytes).toBeLessThanOrEqual(OWNER_GOALS_QUESTION_BYTES);+ } finally { database.close(); rmSync(dir, { recursive: true, force: true }); }+ });++ it('CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH caps the groups in one review question (#6766)', async () => {+ const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-review-count-'));+ const prompts = ['a', 'b', 'c', 'd', 'e', 'f'].map(session => ({ session, text: `Build feature ${session}.` }));+ const database = groupedBacklog(dir, prompts);+ try {+ writeFileSync(join(dir, 'settings.json'), JSON.stringify({ CLAUDE_MEM_WORK_VIEW_REVIEW_BATCH: '2' }));+ const task = buildRefreshTask({ localDeviceId: () => '', needs: { due: prompts.length, ungrouped: 0, goalsStale: false, unplaced: 0, needed: true }, reason: 'scheduled', dataDir: dir, ledgerDir: dir, pluginRoot: PLUGIN_ROOT, openDatabase: handle(database), now: () => NOW, saveFocus: focusWriter(database).save });+ const batchSizes: number[] = [];+ const ask = async (prompt: string) => {+ if (prompt.includes('Do only section 5')) return JSON.stringify({ narrative: 'Features under way.' });+ if (prompt.includes('Do only section 4')) return everyRequestInOther(prompt);+ const shows = JSON.parse(readFileSync(/is in (.+?\.json)/.exec(prompt)![1], 'utf8'));+ batchSizes.push(shows.length);+ return JSON.stringify({ reviews: shows.map((show: any) => ({ groupId: show.groupId, state: 'in-progress', percent: 30, summary: 'Under way.', reviewBasis: show.reviewBasis })) });+ };+ expect(await task.run(ask, 'claude-code')).toBe('6 requests reviewed, 6 requests placed, story written.');+ expect(batchSizes).toEqual([2, 2, 2]);+ } finally { database.close(); rmSync(dir, { recursive: true, force: true }); }+ });+it('review batches run at the same time, and every batch is saved', async () => {const dir = mkdtempSync(join(tmpdir(), 'auto-refresh-parallel-'));try {