Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(questions): answer_too_long reason, configurable refresh output cap, no scheduled retry at the same cap (#7306)

garrytan468ae9671337
diff --git a/docs/architecture/key-files/core-questions.md b/docs/architecture/key-files/core-questions.md
index 60b6edb11b..19a18226f2 100644
--- a/docs/architecture/key-files/core-questions.md
+++ b/docs/architecture/key-files/core-questions.md
@@ -12,15 +12,15 @@ User guide: [docs/guides/pinned-questions.md](../../guides/pinned-questions.md).
- `src/core/questions/freshness.ts` — Read-time staleness. `evaluateAnswer` joins the current answer's evidence pointers against `pages`, `sources`, `facts`, `timeline_entries` and `takes` on every read: missing row, soft delete, archived source, generation or knowledge-revision change, fact expiry by `valid_until` with no write, withdrawal (`expired_at`), supersession, content-hash change, inactive take and owner edits each mark the sentence stale; a sentence with no pointer or an unknown kind is stale (fail closed); a pointer outside the reader's sources hides the sentence. `needsFull` flags reasons an incremental edit cannot repair. Hash expressions (`FACT_HASH_SQL` etc.) are shared with capture and commit.
-- `src/core/questions/refresh.ts` — `refreshPin`: no-spend pre-checks (inactive, `no_model_key` via `probeChatModel`, `budget_exhausted` via the caller's `BudgetMeter`), lease, capture (pin revision, question page, global page-generation clock and newest fact id as the watermark), `retrieveEvidence` (hybrid retrieval with keyword fallback, plus facts, timeline rows and takes anchored to the retrieved pages; question and synthesis pages, marker pages and pages that repeat a published answer sentence after it was published are never evidence), one model call (incremental edit of the previous answer, or full recompute after deletions, withdrawals, conflicting corrections, non-monotonic questions or `full`), then one transaction that locks the pin and every cited row (`FOR UPDATE`/`FOR SHARE`), revalidates lease, revision and dependency revisions, writes the answer and replaces the evidence rows. A mismatch publishes nothing (`conflict`); any failure keeps the previous answer and records `refresh_failed:<stage>`. `RefreshHooks` are test-only injection points.
+- `src/core/questions/refresh.ts` — `refreshPin`: no-spend pre-checks (inactive, `no_model_key` via `probeChatModel`, `budget_exhausted` via the caller's `BudgetMeter`), lease, capture (pin revision, question page, global page-generation clock and newest fact id as the watermark), `retrieveEvidence` (hybrid retrieval with keyword fallback, plus facts, timeline rows and takes anchored to the retrieved pages; question and synthesis pages, marker pages and pages that repeat a published answer sentence after it was published are never evidence), one model call (incremental edit of the previous answer, or full recompute after deletions, withdrawals, conflicting corrections, non-monotonic questions or `full`), then one transaction that locks the pin and every cited row (`FOR UPDATE`/`FOR SHARE`), revalidates lease, revision and dependency revisions, writes the answer and replaces the evidence rows. A mismatch publishes nothing (`conflict`); any failure keeps the previous answer and records `refresh_failed:<stage>`. The output cap is `cycle.standing_questions.max_output_tokens` (default 2,000); a reply cut off at it (a `length` stop or claude-cli's output-token-maximum error) records `refresh_failed:answer_too_long:<cap>` with no JSON retry (#7306). `RefreshHooks` are test-only injection points.
- `src/core/questions/pages.ts` — The question page: question, scope and the owner's notes, never the answer. `syncQuestionPage` creates, archives or restores it through coordinated `put_page` (trusted local callers only). `ownerClaims` turns the body (minus heading and comments) into owner-attributed sentences, pinned to the body's hash.
-- `src/core/questions/receipt.ts` — `buildReceipt`: freshness (`fresh|stale|awaiting_refresh|refreshing|archived`), sentence counts, evidence watermark, last refresh, blocked reason (`awaiting_consent`, `no_model_key`, `budget_exhausted`, `refresh_failed`, `no_worker`), `fix` (an agent-operator `Action` with a read-only `verify`) and the answer for owner-capable readers. `scheduledRefreshAvailable` (a `standing_questions` run in the last two days, or installed unpaused autopilot) decides `no_worker`.
+- `src/core/questions/receipt.ts` — `buildReceipt`: freshness (`fresh|stale|awaiting_refresh|refreshing|archived`), sentence counts, evidence watermark, last refresh, blocked reason (`awaiting_consent`, `no_model_key`, `budget_exhausted`, `answer_too_long` (fix: raise `cycle.standing_questions.max_output_tokens`), `refresh_failed`, `no_worker`), `fix` (an agent-operator `Action` with a read-only `verify`) and the answer for owner-capable readers. `scheduledRefreshAvailable` (a `standing_questions` run in the last two days, or installed unpaused autopilot) decides `no_worker`.
- `src/core/questions/service.ts` — The operations' behavior. `requireOwnerCapable` admits the trusted local CLI and remote grants that read private pages and are neither slug-fenced nor delegated; everyone else gets `question_owner_only` with the CLI equivalent. Consent: CLI pins are active; MCP pins are inactive (`awaiting_consent`) unless a paid preapproval exists; `pin --id` on the host activates. First answer is a bounded wait (`wait_ms`, abort releases the lease). `pinnedAnswersForPack` feeds context_pack's optional `pinned_questions` / `withheld` fields (published, active, entity-scoped pins whose `(source_id, scope_entity)` is one of the pack's accepted cards; fresh sentences only). Emits the `pinned_answer_stale` notice.
-- `src/core/questions/phase.ts` — Cycle phase `standing_questions` (global, writes): syncs question pages, refreshes due active pins (never answered, then stale, then new evidence since the watermark; cooldown per pin or `cycle.standing_questions.cooldown_days`) under one `BudgetMeter` (`cycle.standing_questions.budget_usd`) and `max_per_cycle`, stops on `budget_exhausted` or `no_model_key`, and stamps `cycle.standing_questions.last_run_at`. Kill switch `cycle.standing_questions.enabled=false`.
+- `src/core/questions/phase.ts` — Cycle phase `standing_questions` (global, writes): syncs question pages, refreshes due active pins (never answered, then stale, then new evidence since the watermark; cooldown per pin or `cycle.standing_questions.cooldown_days`) under one `BudgetMeter` (`cycle.standing_questions.budget_usd`) and `max_per_cycle`, stops on `budget_exhausted` or `no_model_key`, skips (reported `blocked:answer_too_long`) a pin whose last refresh did not fit the current output cap until the cap is raised, and stamps `cycle.standing_questions.last_run_at`. Kill switch `cycle.standing_questions.enabled=false`.
- `src/core/questions/auto-think-migration.ts` — Maps the seven `dream.auto_think` keys onto pins without creating consent (every pin imports inactive: `migrated_disabled`, `migrated_zero_budget` or `migrated_enabled`; `auto_commit=false` → draft; cooldown and model per pin; budget, max and allow_unpriced seed `cycle.standing_questions.*` only when unset). Config reads and inserts only; idempotent. `autoThinkReplacement` is what `gbrain config get|set` prints for an old key.
@@ -30,4 +30,4 @@ User guide: [docs/guides/pinned-questions.md](../../guides/pinned-questions.md).
- Privacy and retrieval seams: `src/core/search/private-visibility.ts` treats `type: question` without a visibility as private and any page with the `pinned_question` marker as private whatever its `visibility`; `buildVisibilityClause` (`src/core/search/sql-ranking.ts`) keeps marker pages out of every search arm for every caller.
-- Tests: `test/helpers/pinned-questions-scenarios.ts` (B5 safety gate, operator journeys, migration) runs on PGLite (`test/pinned-questions-safety.test.ts`) and Postgres (`test/e2e/pinned-questions-postgres.test.ts`); `test/questions-cli.test.ts`; `test/pinned-questions-benefit-gate.test.ts` (offline harness plumbing); the `standing_questions` row of `test/managed-phase-matrix.test.ts`.
+- Tests: `test/helpers/pinned-questions-scenarios.ts` (B5 safety gate, operator journeys, migration) runs on PGLite (`test/pinned-questions-safety.test.ts`) and Postgres (`test/e2e/pinned-questions-postgres.test.ts`); `test/questions-cli.test.ts`; `test/pinned-questions-answer-too-long.test.ts` (output cap, #7306); `test/pinned-questions-benefit-gate.test.ts` (offline harness plumbing); the `standing_questions` row of `test/managed-phase-matrix.test.ts`.
diff --git a/docs/guides/pinned-questions.md b/docs/guides/pinned-questions.md
index 1dca16206c..24c0c9f506 100644
--- a/docs/guides/pinned-questions.md
+++ b/docs/guides/pinned-questions.md
@@ -77,6 +77,7 @@ Every pin, list, status and refresh returns the same fields:
| `awaiting_consent` | The pin was made over MCP (or imported from `dream.auto_think`) and is not active | The owner runs `gbrain questions pin --id <id>` |
| `no_model_key` | No chat-model key is configured | The user adds an Anthropic or OpenAI key (`gbrain providers list` shows how) |
| `budget_exhausted` | This run's refresh budget is spent | Raise `cycle.standing_questions.budget_usd`, or wait for the next run |
+| `answer_too_long` | The answer did not fit the refresh output cap, so the last refresh failed (a full refresh fails the same way); scheduled refreshes skip the pin until the cap is raised | The owner raises `cycle.standing_questions.max_output_tokens`, or narrows the question |
| `refresh_failed` | The last refresh failed; the previous answer is kept with its stale flags | `questions_refresh {id, full: true}` |
| `no_worker` | Nothing runs scheduled refreshes (no `standing_questions` phase in two days, no autopilot) | `questions_refresh {id}`; recurring refreshes need autopilot, which a pin never installs |
@@ -113,8 +114,11 @@ from scratch. A refresh publishes only if nothing it cited changed while it
ran; otherwise the previous answer stays, still flagged, and the next refresh
tries again. A model reply with no parseable answer is retried once with a
JSON-only reminder (both calls count toward spend); if that also fails, the
-refresh fails with `refresh_failed:model_output_not_json`. A failed refresh
-never removes the previous answer.
+refresh fails with `refresh_failed:model_output_not_json`. A reply cut off at
+the output cap is not retried: the refresh fails with
+`refresh_failed:answer_too_long:<cap>`, and the cycle does not try that pin
+again until `cycle.standing_questions.max_output_tokens` is raised. A failed
+refresh never removes the previous answer.
Question pages, synthesis pages, pages that copy a published answer, and
quarantined pages (with the facts extracted from them) are never used as
@@ -159,6 +163,7 @@ Scheduled refreshes run in the `standing_questions` cycle phase (part of
| `cycle.standing_questions.budget_usd` | `1.00` | Spend cap per run (`0` spends nothing) |
| `cycle.standing_questions.max_per_cycle` | `5` | Refreshes per run |
| `cycle.standing_questions.cooldown_days` | `1` | Minimum days between scheduled refreshes of one pin |
+| `cycle.standing_questions.max_output_tokens` | `2000` | Output cap of one refresh call; an answer longer than this fails `answer_too_long` |
| `cycle.standing_questions.allow_unpriced` | `false` | Let a model with no known price run uncapped |
| `cycle.standing_questions.enabled` | `true` | `false` stops the phase |
| `models.standing_questions` | deep tier | The answer model |
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 39ac344787..6d304f9ce8 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -1097,6 +1097,7 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.359.0', text: 'A `gbrain repair <kind> --apply` that the database refuses mid-run (deadlock 40P01, serialization failure 40001, a lost connection) now stops with a result (`stopped.reason` `database_contention` or `connection_lost`, the SQLSTATE in its message, what it applied, and the command that resumes from the refused item) instead of ending with an error and, under `--json`, no record of what it applied. A SIGTERM or SIGHUP (an outer timeout, a closed terminal) stops the apply before its next item with `stopped.reason: interrupted` and the same result; a second signal exits at once.' },
// #7190 (GBRA-150): per-source applied-through watermark. `since` is stamped at the merge slot.
{ since: '0.60.361.0', id: 'applied_watermark_7190', text: '`get_write_request` with `applied: true` (`gbrain write-request <id> --applied`) now returns `applied`, read live: whether the write is searchable yet (`searchable_yet`, `searchable`, `state`), the gap (`requests_ahead`, `unembedded_chunks`), the request `sequence` and the source\'s write watermark (`indexed_through`, `committed_through_request`, `requests_pending`), and a pending write\'s hint names that read; a write\'s own reply is otherwise unchanged. `gbrain sources status --json`, MCP `sources_status` and `gbrain sync --json` add a `watermark` per source: `indexed_through` (the last commit a finished sync pass reached; a deadline-stopped or partial pass never moves it), `embedded_through` (held pages count as not embedded), `committed_through_request`, `pending` (requests, commits and files behind HEAD, held files, withheld deletes) and `writer_heartbeat` (the drain-lease holder and its last progress).' },
+ { since: 'TBD', text: 'A pinned-question refresh whose answer does not fit the output cap no longer fails as `refresh_failed:provider_error` (or `model_output_not_json` after a second metered call): it fails `refresh_failed:answer_too_long:<cap>` after one call, the receipt\'s `blocked_reason` is `answer_too_long` with a fix naming the new key `cycle.standing_questions.max_output_tokens` (default 2000, the old fixed cap), and the `standing_questions` cycle phase skips that pin (reported `blocked:answer_too_long`) until the cap is raised instead of spending on it every cooldown. `gbrain questions refresh <id>` still runs when asked.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/questions/phase.ts b/src/core/questions/phase.ts
index 7b3795d21b..5095b53458 100644
--- a/src/core/questions/phase.ts
+++ b/src/core/questions/phase.ts
@@ -5,7 +5,9 @@
* answered, then stale, then new evidence in scope since the watermark. A pin
* refreshed (or attempted) within its cooldown (`cooldown_days` on the pin, or
* `cycle.standing_questions.cooldown_days`, default 1) waits, except a pin that
- * was never attempted. Inactive and draft-only pins follow their own rules
+ * was never attempted. A pin whose last refresh failed `answer_too_long` at
+ * the current `cycle.standing_questions.max_output_tokens` (#7306) is skipped
+ * and reported blocked until the cap is raised. Inactive and draft-only pins follow their own rules
* (inactive: never refreshed; draft: refreshed, not served by context_pack).
*
* The phase also brings question pages in line with their pins (materializes
@@ -20,7 +22,7 @@ import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd }
import { evaluateAnswer, newEvidenceSinceWatermark } from './freshness.ts';
import { syncQuestionPage } from './pages.ts';
import { LAST_PHASE_RUN_KEY } from './receipt.ts';
-import { refreshPin, type QuestionChatFn, type RefreshHooks } from './refresh.ts';
+import { answerTooLongCap, refreshPin, resolveMaxOutputTokens, type QuestionChatFn, type RefreshHooks } from './refresh.ts';
import { listPins, pinId, type PinRow } from './store.ts';
import { DEFAULT_BUDGET_USD } from './service.ts';
@@ -59,8 +61,13 @@ export async function runPhaseStandingQuestions(engine: BrainEngine, opts: Stand
catch (e) { process.stderr.write(`[questions] page sync for ${pinId(pin)} failed: ${(e as Error).message}\n`); }
}
const now = Date.now();
+ const maxTokens = await resolveMaxOutputTokens(engine);
const candidates: Array<{ pin: PinRow; rank: number }> = [];
+ const tooLong: string[] = [];
for (const pin of pins.filter(p => p.state === 'active')) {
+ // #7306: an answer that did not fit the output cap fails the same way at that cap; it waits for the cap to be raised.
+ const failedCap = answerTooLongCap(pin.last_error);
+ if (failedCap !== null && failedCap >= maxTokens) { tooLong.push(pinId(pin)); continue; }
const neverAttempted = pin.last_attempt_at === null;
const cooldownMs = (pin.cooldown_days ?? defaultCooldownDays) * 86_400_000;
if (!neverAttempted && pin.last_attempt_at && now - pin.last_attempt_at.getTime() < cooldownMs) continue;
@@ -70,8 +77,8 @@ export async function runPhaseStandingQuestions(engine: BrainEngine, opts: Stand
if (await newEvidenceSinceWatermark(engine, pin)) candidates.push({ pin, rank: 2 });
}
candidates.sort((a, b) => a.rank - b.rank || (a.pin.last_attempt_at?.getTime() ?? 0) - (b.pin.last_attempt_at?.getTime() ?? 0));
- const tally = { candidates: candidates.length, refreshed: 0, blocked: 0, failed: 0, conflicts: 0, in_progress: 0, pages_synced: pagesSynced };
- const outcomes: Array<{ id: string; status: string }> = [];
+ const tally = { candidates: candidates.length, refreshed: 0, blocked: tooLong.length, failed: 0, conflicts: 0, in_progress: 0, pages_synced: pagesSynced };
+ const outcomes: Array<{ id: string; status: string }> = tooLong.map(id => ({ id, status: 'blocked:answer_too_long' }));
for (const { pin } of candidates.slice(0, maxPerCycle)) {
opts.signal?.throwIfAborted();
if (opts.dryRun) { outcomes.push({ id: pinId(pin), status: 'dry_run' }); continue; }
@@ -94,6 +101,6 @@ export async function runPhaseStandingQuestions(engine: BrainEngine, opts: Stand
phase: 'standing_questions', status, duration_ms: 0,
summary: `${tally.refreshed} refreshed, ${tally.blocked} blocked, ${tally.failed} failed, ${tally.conflicts} conflicts of ${candidates.length} due; ` +
`$${meter.totalSpent.toFixed(4)} / $${budgetUsd.toFixed(2)}`,
- details: { ...tally, spend_usd: meter.totalSpent, budget_usd: budgetUsd, max_per_cycle: maxPerCycle, outcomes },
+ details: { ...tally, spend_usd: meter.totalSpent, budget_usd: budgetUsd, max_per_cycle: maxPerCycle, max_output_tokens: maxTokens, outcomes },
};
}
diff --git a/src/core/questions/receipt.ts b/src/core/questions/receipt.ts
index f24e1f20e2..99fcb900ae 100644
--- a/src/core/questions/receipt.ts
+++ b/src/core/questions/receipt.ts
@@ -11,7 +11,7 @@ import type { Action, McpCall } from '../agent-output.ts';
import { autopilotInstallIdPath, autopilotPaused } from '../autopilot-paths.ts';
import { chatKeyFix } from '../interop-notices.ts';
import { evaluateAnswer, newEvidenceSinceWatermark, type EvaluatedSentence } from './freshness.ts';
-import { chatKeyAvailable, resolveQuestionModel, type BlockedReason, type RefreshOutcome } from './refresh.ts';
+import { ANSWER_TOO_LONG_ERROR, MAX_OUTPUT_TOKENS_KEY, answerTooLongCap, chatKeyAvailable, resolveMaxOutputTokens, resolveQuestionModel, type BlockedReason, type RefreshOutcome } from './refresh.ts';
import { pinId, pinScope, type PinRow } from './store.ts';
import type { QuestionScope } from './identity.ts';
@@ -97,7 +97,16 @@ export function fixFor(pin: PinRow, blocked: BlockedReason | null, freshness: Fr
user_message: 'Pinned-question refreshes hit their spending cap. Raise cycle.standing_questions.budget_usd, or wait for the next run?',
verify: verifyStep(id), requires_exclusive: false,
};
+ case 'answer_too_long':
+ return {
+ argv: ['gbrain', 'config', 'set', MAX_OUTPUT_TOKENS_KEY, '<tokens>'], consent: ['paid'], actor: 'user',
+ inputs: [{ name: 'tokens', how: `Ask the user for a larger output cap than the ${answerTooLongCap(pin.last_error) ?? 'current'} tokens the last refresh hit (each refresh may then spend up to that many output tokens).` }],
+ why: `The answer did not fit the refresh output cap of ${answerTooLongCap(pin.last_error) ?? 'the configured'} tokens, so the refresh failed and the previous answer is kept with its stale flags. The same cap fails the same way (a full refresh too), so scheduled refreshes skip this pin until ${MAX_OUTPUT_TOKENS_KEY} is raised; raising it is the owner's call.`,
+ user_message: `The answer to the pinned question "${pin.question.slice(0, 120)}" is longer than the refresh output cap. Raise ${MAX_OUTPUT_TOKENS_KEY}, or narrow the question?`,
+ verify: verifyStep(id), requires_exclusive: false,
+ };
case 'refresh_failed':
+ if (answerTooLongCap(pin.last_error) !== null) return refreshAction(id, `The last refresh hit the old output cap; ${MAX_OUTPUT_TOKENS_KEY} has been raised since, so the next scheduled run retries it, or refresh it now.`);
return refreshAction(id, `The last refresh failed (${pin.last_error}); the previous answer is kept with its stale flags. A full refresh recomputes it from current evidence.`, true);
case 'no_worker':
return refreshAction(id, 'Nothing runs scheduled refreshes on this brain (no standing_questions cycle phase in the last 2 days and no autopilot), so the answer stays as it is until something refreshes it. Refresh it now; a recurring cycle needs the owner to install autopilot (gbrain autopilot --install), which a pin never does.');
@@ -126,6 +135,7 @@ export async function buildReceipt(engine: BrainEngine, pin: PinRow, view: {
const needsRefresh = freshness === 'stale' || freshness === 'awaiting_refresh';
if (!chatKeyAvailable(await resolveQuestionModel(engine, pin))) blocked = needsRefresh || lastAttemptFailed(pin, 'no_model_key') ? 'no_model_key' : null;
else if (lastAttemptFailed(pin, 'budget_exhausted')) blocked = 'budget_exhausted';
+ else if (lastAttemptFailed(pin, ANSWER_TOO_LONG_ERROR) && (answerTooLongCap(pin.last_error) ?? 0) >= await resolveMaxOutputTokens(engine)) blocked = 'answer_too_long';
else if (lastAttemptFailed(pin, 'refresh_failed')) blocked = 'refresh_failed';
else if ((needsRefresh || newEvidence) && !(await scheduledRefreshAvailable(engine))) blocked = 'no_worker';
}
diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.ts
index 942be046b2..a8642f6067 100644
--- a/src/core/questions/refresh.ts
+++ b/src/core/questions/refresh.ts
@@ -17,6 +17,8 @@
* lease, the pin revision and every cited dependency revision. Any change
* rejects publication, so the previous answer keeps its stale flags.
* A failure anywhere keeps the previous answer; the error is recorded.
+ * #7306: a reply cut off at the output cap fails `refresh_failed:answer_too_long:<cap>` without the JSON retry;
+ * the cycle phase does not retry that pin until the cap is raised.
*/
import { randomUUID } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
@@ -34,10 +36,11 @@ import { ownerClaims, readQuestionPage } from './pages.ts';
import { neutralizeForPrompt } from '../think/sanitize.ts';
import { acquireLease, getPin, pinId, releaseLease, type AnswerSentence, type PinRow } from './store.ts';
-export type BlockedReason = 'no_model_key' | 'budget_exhausted' | 'no_worker' | 'refresh_failed' | 'awaiting_consent';
+export type BlockedReason = 'no_model_key' | 'budget_exhausted' | 'no_worker' | 'refresh_failed' | 'answer_too_long' | 'awaiting_consent';
export interface QuestionChatRequest { model: string; system: string; user: string; maxTokens: number; signal?: AbortSignal }
-export interface QuestionChatResponse { text: string; usage: { input_tokens: number; output_tokens: number } | null; model: string }
+/** `truncated`: the reply stopped at the output cap (`maxTokens`), so its text is cut off. */
+export interface QuestionChatResponse { text: string; usage: { input_tokens: number; output_tokens: number } | null; model: string; truncated?: boolean }
export type QuestionChatFn = (req: QuestionChatRequest) => Promise<QuestionChatResponse>;
/** Test-only crash and race injection points around publication. */
@@ -68,7 +71,12 @@ export type RefreshOutcome =
| { status: 'skipped'; reason: 'archived' };
export const EST_INPUT_TOKENS = 8_000;
-export const MAX_OUTPUT_TOKENS = 2_000;
+/** The output cap of one refresh call; `cycle.standing_questions.max_output_tokens` overrides it. */
+export const DEFAULT_MAX_OUTPUT_TOKENS = 2_000;
+export const MAX_OUTPUT_TOKENS_KEY = 'cycle.standing_questions.max_output_tokens';
+/** #7306: `refresh_failed:answer_too_long:<cap>` records an answer that did not fit the cap; the same cap fails the same way. */
+export const ANSWER_TOO_LONG_ERROR = 'refresh_failed:answer_too_long';
+const OUTPUT_CAP_ERROR = /exceeded the \d+ output token maximum/i;
const MAX_PAGES = 16;
const MAX_FACTS = 30;
const MAX_TIMELINE = 20;
@@ -105,9 +113,23 @@ export function chatKeyAvailable(model: string): boolean {
const gatewayQuestionChat: QuestionChatFn = async (req) => {
const r = await gatewayChat({ model: normalizeModelId(req.model), system: req.system, messages: [{ role: 'user', content: req.user }],
maxTokens: req.maxTokens, allowFallback: false, ...(req.signal ? { abortSignal: req.signal } : {}) });
- return { text: r.text, usage: { input_tokens: r.usage.input_tokens, output_tokens: r.usage.output_tokens }, model: r.model };
+ return { text: r.text, usage: { input_tokens: r.usage.input_tokens, output_tokens: r.usage.output_tokens }, model: r.model, truncated: r.stopReason === 'length' };
};
+export async function resolveMaxOutputTokens(engine: BrainEngine): Promise<number> {
+ const n = Number((await engine.getConfig(MAX_OUTPUT_TOKENS_KEY).catch(() => null)) ?? NaN);
+ return Number.isInteger(n) && n > 0 ? n : DEFAULT_MAX_OUTPUT_TOKENS;
+}
+
+/** The cap an `answer_too_long` failure recorded, or null when the error is another one. */
+export function answerTooLongCap(lastError: string | null): number | null {
+ if (!lastError?.startsWith(`${ANSWER_TOO_LONG_ERROR}:`)) return null;
+ const cap = Number(lastError.slice(ANSWER_TOO_LONG_ERROR.length + 1));
+ return Number.isInteger(cap) && cap > 0 ? cap : null;
+}
+
+class AnswerTooLong extends Error {}
+
function costUsd(model: string, usage: QuestionChatResponse['usage']): number {
const p = canonicalLookup(normalizeModelId(model)) ?? canonicalLookup(model);
if (!p || !usage) return 0;
@@ -359,8 +381,9 @@ export async function refreshPin(engine: BrainEngine, sourceId: string, slug: st
await recordBlocked(engine, pin.id, 'no_model_key');
return { status: 'blocked', blocked_reason: 'no_model_key', detail: `no usable chat key for ${model}` };
}
+ const maxTokens = await resolveMaxOutputTokens(engine);
if (opts.meter) {
- const check = opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: MAX_OUTPUT_TOKENS, label: `standing_questions:${pinId(pin)}` });
+ const check = opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: maxTokens, label: `standing_questions:${pinId(pin)}` });
if (!check.allowed) {
await recordBlocked(engine, pin.id, 'budget_exhausted');
return { status: 'blocked', blocked_reason: 'budget_exhausted', detail: check.reason ?? 'budget exhausted' };
@@ -385,20 +408,22 @@ export async function refreshPin(engine: BrainEngine, sourceId: string, slug: st
opts.signal?.throwIfAborted();
stage = 'model';
const chat = opts.chat ?? gatewayQuestionChat;
- const request = { model, system: SYSTEM_PROMPT, user: buildPrompt(leased, items, owner, full ? null : previous), maxTokens: MAX_OUTPUT_TOKENS, signal: opts.signal };
+ const request = { model, system: SYSTEM_PROMPT, user: buildPrompt(leased, items, owner, full ? null : previous), maxTokens, signal: opts.signal };
let response = await chat(request);
spend = costUsd(response.model || model, response.usage);
+ if (response.truncated) throw new AnswerTooLong(`the answer did not fit the ${maxTokens}-token output cap (${MAX_OUTPUT_TOKENS_KEY})`);
stage = 'parse';
let parsed: ReturnType<typeof parseModelAnswer>;
try {
parsed = parseModelAnswer(response.text, items);
} catch (e) {
if (!(e instanceof Error && e.message === 'model_output_not_json')) throw e;
- if (opts.meter && !opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: MAX_OUTPUT_TOKENS, label: `standing_questions:${pinId(pin)}:retry` }).allowed) throw e;
+ if (opts.meter && !opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: maxTokens, label: `standing_questions:${pinId(pin)}:retry` }).allowed) throw e;
opts.signal?.throwIfAborted();
stage = 'model';
response = await chat({ ...request, user: `${request.user}\n\n${JSON_RETRY_NOTE}` });
spend += costUsd(response.model || model, response.usage);
+ if (response.truncated) throw new AnswerTooLong(`the answer did not fit the ${maxTokens}-token output cap (${MAX_OUTPUT_TOKENS_KEY})`);
stage = 'parse';
parsed = parseModelAnswer(response.text, items);
}
@@ -454,7 +479,8 @@ export async function refreshPin(engine: BrainEngine, sourceId: string, slug: st
return { status: 'timeout', cost_usd: spend };
}
const message = e instanceof Error ? e.message : String(e);
- const code = message === 'model_output_not_json' ? 'refresh_failed:model_output_not_json'
+ const code = e instanceof AnswerTooLong || (stage === 'model' && OUTPUT_CAP_ERROR.test(message)) ? `${ANSWER_TOO_LONG_ERROR}:${maxTokens}`
+ : message === 'model_output_not_json' ? 'refresh_failed:model_output_not_json'
: `refresh_failed:${stage === 'model' ? classifyLlmCallFailure(e) : stage}`;
process.stderr.write(`[questions] refresh of ${pinId(pin)} failed: ${message}\n`);
await releaseLease(engine, pin.id, token, { error: code, spendUsd: spend });
diff --git a/test/pinned-questions-answer-too-long.test.ts b/test/pinned-questions-answer-too-long.test.ts
new file mode 100644
index 0000000000..2fd4095f85
--- /dev/null
+++ b/test/pinned-questions-answer-too-long.test.ts
@@ -0,0 +1,132 @@
+/**
+ * #7306: a pinned answer longer than the refresh output cap. The cap is
+ * `cycle.standing_questions.max_output_tokens` (default 2,000); a reply cut off
+ * at it (a `length` stop, or claude-cli's "exceeded the N output token maximum"
+ * error) fails `refresh_failed:answer_too_long:<cap>` after one call, the receipt
+ * names the key instead of a --full refresh that fails the same way, and the
+ * cycle phase stops spending on the pin until the cap is raised. Stub model; no network.
+ */
+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { __setChatTransportForTests, type ChatOpts, type ChatResult } from '../src/core/ai/gateway.ts';
+import { pinQuestion, questionStatus } from '../src/core/questions/service.ts';
+import { refreshPin, type QuestionChatFn, type QuestionChatRequest } from '../src/core/questions/refresh.ts';
+import { runPhaseStandingQuestions } from '../src/core/questions/phase.ts';
+import { getPin } from '../src/core/questions/store.ts';
+import { parseQuestionId } from '../src/core/questions/identity.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { ENTITY, MODEL, QUESTION, localCtx, seedBrain, stubAnswer, stubChat } from './helpers/pinned-questions-fixture.ts';
+
+const MAX_OUTPUT_TOKENS_KEY = 'cycle.standing_questions.max_output_tokens';
+const DEFAULT_MAX_OUTPUT_TOKENS = 2000;
+
+describe('pinned-question refresh output cap (#7306)', () => {
+ let engine: PGLiteEngine;
+ beforeAll(async () => {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }, 120_000);
+ afterAll(async () => { await engine?.disconnect(); }, 60_000);
+
+ const run = (name: string, fn: () => Promise<void>) => test(name, async () => {
+ await engine.setConfig('models.standing_questions', MODEL);
+ await withEnv({ ANTHROPIC_API_KEY: 'sk-test-pinned-questions' }, fn);
+ }, 60_000);
+
+ async function pinned() {
+ const s = await seedBrain(engine);
+ const r = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY } }, { chat: stubChat().fn });
+ const { slug } = parseQuestionId(r.receipt.id, s.sourceId)!;
+ return { sourceId: s.sourceId, slug, id: r.receipt.id, pin: (await getPin(engine, s.sourceId, slug))! };
+ }
+
+ function recording(reply: (req: QuestionChatRequest) => ReturnType<QuestionChatFn>): { fn: QuestionChatFn; requests: QuestionChatRequest[] } {
+ const requests: QuestionChatRequest[] = [];
+ return { requests, fn: async (req) => { requests.push(req); return reply(req); } };
+ }
+ const cutOff = (req: QuestionChatRequest) => Promise.resolve({ text: stubAnswer(req.user).slice(0, 60), usage: { input_tokens: 1000, output_tokens: req.maxTokens }, model: MODEL, truncated: true });
+ const cliCapError = () => Promise.reject(new Error("claude-cli reported error: API Error: Claude's response exceeded the 2000 output token maximum. To configure this behavior, set the CLAUDE_CODE_MAX_OUTPUT_TOKENS environment variable."));
+
+ run('a reply cut off at the cap fails answer_too_long after one call, with no JSON retry, keeping the answer', async () => {
+ const { sourceId, slug, pin } = await pinned();
+ const chat = recording(cutOff);
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: chat.fn, leaseOwner: 't' });
+ expect(outcome).toMatchObject({ status: 'failed', error: `refresh_failed:answer_too_long:${DEFAULT_MAX_OUTPUT_TOKENS}` });
+ expect(chat.requests).toHaveLength(1);
+ const after = (await getPin(engine, sourceId, slug))!;
+ expect(after.answer).toEqual(pin.answer);
+ expect(after.last_error).toBe(`refresh_failed:answer_too_long:${DEFAULT_MAX_OUTPUT_TOKENS}`);
+ });
+
+ run("claude-cli's output-token-maximum error is answer_too_long, not provider_error", async () => {
+ const { sourceId, slug } = await pinned();
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: cliCapError, leaseOwner: 't' });
+ expect(outcome).toMatchObject({ status: 'failed', error: 'refresh_failed:answer_too_long:2000' });
+ });
+
+ run('a length stop from the gateway is answer_too_long', async () => {
+ const { sourceId, slug } = await pinned();
+ let calls = 0;
+ __setChatTransportForTests(async (opts: ChatOpts): Promise<ChatResult> => {
+ calls++;
+ const text = stubAnswer(String(opts.messages[opts.messages.length - 1]?.content ?? '')).slice(0, 40);
+ return { text, blocks: [{ type: 'text', text }], stopReason: 'length', model: opts.model ?? MODEL, providerId: 'anthropic',
+ usage: { input_tokens: 1000, output_tokens: 2000, cache_read_tokens: 0, cache_creation_tokens: 0 } };
+ });
+ try {
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, leaseOwner: 't' });
+ expect(outcome).toMatchObject({ status: 'failed', error: 'refresh_failed:answer_too_long:2000' });
+ expect(calls).toBe(1);
+ } finally { __setChatTransportForTests(null); }
+ });
+
+ run('the receipt names the cap key, not a --full refresh', async () => {
+ const { sourceId, slug, id } = await pinned();
+ await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: cliCapError, leaseOwner: 't' });
+ const receipt = await questionStatus(localCtx(engine, sourceId), { id });
+ expect(receipt.blocked_reason).toBe('answer_too_long');
+ expect(receipt.fix).toMatchObject({ argv: ['gbrain', 'config', 'set', MAX_OUTPUT_TOKENS_KEY, '<tokens>'], actor: 'user', consent: ['paid'] });
+ expect(receipt.fix!.argv).not.toContain('--full');
+ });
+
+ run('the configured cap reaches the model call', async () => {
+ const { sourceId, slug } = await pinned();
+ await engine.setConfig(MAX_OUTPUT_TOKENS_KEY, '6000');
+ try {
+ const chat = recording(req => Promise.resolve({ text: stubAnswer(req.user), usage: { input_tokens: 1000, output_tokens: 200 }, model: MODEL }));
+ const outcome = await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: chat.fn, leaseOwner: 't' });
+ expect(outcome.status).toBe('published');
+ expect(chat.requests[0]!.maxTokens).toBe(6000);
+ } finally { await engine.setConfig(MAX_OUTPUT_TOKENS_KEY, ''); }
+ });
+
+ run('the cycle phase does not spend on a pin that failed answer_too_long at the current cap, and retries once it is raised', async () => {
+ const { sourceId, slug, id } = await pinned();
+ await refreshPin(engine, sourceId, slug, { trigger: 'manual', full: true, chat: cliCapError, leaseOwner: 't' });
+ await engine.executeRaw("UPDATE pinned_questions SET last_attempt_at = now() - interval '3 days' WHERE source_id = $1 AND slug = $2", [sourceId, slug]);
+ await engine.executeRaw(`INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from)
+ VALUES ($1, $2, 'Acme example opened a widget plant in Porto', 'fact', 'test', 'world', 1, now())`, [sourceId, ENTITY]);
+ await engine.setConfig('cycle.standing_questions.cooldown_days', '0');
+ try {
+ const held = recording(cutOff);
+ const first = await runPhaseStandingQuestions(engine, { dryRun: false, chat: held.fn });
+ expect(held.requests.filter(r => r.user.includes(QUESTION))).toHaveLength(0);
+ expect(first.status).toBe('warn');
+ expect((first.details.outcomes as Array<{ id: string; status: string }>).find(o => o.id === id)?.status).toBe('blocked:answer_too_long');
+
+ await engine.setConfig(MAX_OUTPUT_TOKENS_KEY, '4000');
+ const raised = recording(req => Promise.resolve({ text: stubAnswer(req.user), usage: { input_tokens: 1000, output_tokens: 200 }, model: MODEL }));
+ const receipt = await questionStatus(localCtx(engine, sourceId), { id });
+ expect(receipt.blocked_reason).not.toBe('answer_too_long');
+ await runPhaseStandingQuestions(engine, { dryRun: false, chat: raised.fn });
+ const own = raised.requests.filter(r => r.user.includes(QUESTION));
+ expect(own.length).toBeGreaterThanOrEqual(1);
+ expect(own[0]!.maxTokens).toBe(4000);
+ expect((await getPin(engine, sourceId, slug))!.last_error).toBeNull();
+ } finally {
+ await engine.setConfig(MAX_OUTPUT_TOKENS_KEY, '');
+ await engine.setConfig('cycle.standing_questions.cooldown_days', '');
+ }
+ });
+});