Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(questions): pinned questions core, ops, CLI, standing_questions phase, auto_think migration, B5 safety suite (WIP)
garrytandc6f9569d11b
diff --git a/scripts/build-schema.ts b/scripts/build-schema.tsindex d691873941..c49115eec4 100644--- a/scripts/build-schema.ts+++ b/scripts/build-schema.ts@@ -40,6 +40,7 @@ import { WORKTREE_REFRESH_SCHEMA_SQL } from '../src/core/persistence/worktree-reimport { SHARED_SKILLS_SCHEMA_SQL } from '../src/core/shared-skills/schema-all.ts';import { DECIDE_SCHEMA_SQL } from '../src/core/ai/decide/schema.ts';import { FACT_RELINK_SCHEMA_SQL } from '../src/core/facts/relink-schema.ts';+import { PINNED_QUESTIONS_SCHEMA_SQL } from '../src/core/questions/schema.ts';const REPO = resolve(import.meta.dir, '..');export const SCHEMA_SQL_PATH = 'src/schema.sql';@@ -97,6 +98,7 @@ export const FRAGMENTS: readonly Fragment[] = [{ source: 'src/core/ai/decide/schema.ts', expr: 'DECIDE_SCHEMA_SQL', postgres: DECIDE_SCHEMA_SQL, pglite: DECIDE_SCHEMA_SQL },{ source: 'src/core/facts/relink-schema.ts', expr: 'FACT_RELINK_SCHEMA_SQL', postgres: FACT_RELINK_SCHEMA_SQL, pglite: FACT_RELINK_SCHEMA_SQL },{ source: 'src/core/link-temporal-schema.ts', expr: 'LINK_TEMPORAL_SCHEMA_SQL', postgres: LINK_TEMPORAL_SCHEMA_SQL, pglite: LINK_TEMPORAL_SCHEMA_SQL },+ { source: 'src/core/questions/schema.ts', expr: 'PINNED_QUESTIONS_SCHEMA_SQL', postgres: PINNED_QUESTIONS_SCHEMA_SQL, pglite: PINNED_QUESTIONS_SCHEMA_SQL },];const fragmentLabel = (f: Fragment) => `${f.source} (${f.expr})`;diff --git a/src/cli.ts b/src/cli.tsindex abb5b1f52e..4b0bed1098 100755--- a/src/cli.ts+++ b/src/cli.ts@@ -139,6 +139,8 @@ const SELF_HELP_WITHOUT_ENGINE: Record<string, true | (() => Promise<(engine: ne// runLoops / runWaiting answer --help before touching the engine.loops: async () => (await import('./commands/loops.ts')).runLoops as never,'edge-proposals': async () => (await import('./commands/edge-proposals.ts')).runEdgeProposals as never,+ // runQuestions answers --help before touching the engine.+ questions: async () => (await import('./commands/questions.ts')).runQuestions as never,waiting: async () => (await import('./commands/loops.ts')).runWaiting as never,// runSources's `--help`/`-h`/undefined-subcommand branch calls printHelp()// without ever touching `engine` — safe to dispatch with no brain@@ -3062,6 +3064,7 @@ TOOLSfacts relink [--dry-run] Link facts saved without an entity to the entity they namecheck-resolvable [--json] [--fix] Validate skill tree (reachability/MECE/DRY)report --type <name> --content ... Save timestamped report to brain/reports/+ questions pin|list|status|refresh|unpin Pinned questions: cited answers kept current (owner-private)OPEN LOOPS (Gmail/Calendar/Contacts connector — v0.47)google setup [--account <email>] One command: BYO OAuth → source → first sync → first digestdiff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 92ce15a43c..46ecf9781c 100644--- a/src/cli/command-table.ts+++ b/src/cli/command-table.ts@@ -362,6 +362,8 @@ export const CLI_COMMANDS: readonly CliCommandRecord[] = [ // Pre-connect: disp// CLI_ONLY: Open-loop engine CLI (engine-bound; trusted-local op dispatch).{ name: 'waiting', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/waiting.ts') },{ name: 'loops', phase: 'post-connect', thinClient: 'none', selfHelp: true, routes_source: true, load: () => import('./commands/loops.ts') },+ // CLI_ONLY: pinned questions (C4); trusted-local op dispatch of the questions_* ops.+ { name: 'questions', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, routes_source: true, load: () => import('./commands/questions.ts') },// CLI_ONLY: relationship-contradiction proposals (temporal typed edges); host-local, writes canonical timeline lines.{ name: 'edge-proposals', phase: 'post-connect', thinClient: 'refuse', selfHelp: true, load: () => import('./commands/edge-proposals.ts') },// selfHelp: connectors ships its own printHelp (commands/connectors/index.ts) with thediff --git a/src/cli/commands/questions.ts b/src/cli/commands/questions.tsnew file mode 100644index 0000000000..7c68bb089e--- /dev/null+++ b/src/cli/commands/questions.ts@@ -0,0 +1,10 @@+/**+ * `gbrain questions`: post-connect dispatch, run by handleCliOnly with the+ * engine connectEngine() opened; the record lives in src/cli/command-table.ts.+ */+import type { BrainEngine } from '../../core/engine.ts';++export async function run(engine: BrainEngine, args: string[]): Promise<void> {+ const { runQuestions } = await import('../../commands/questions.ts');+ await runQuestions(engine, args);+}diff --git a/src/commands/config.ts b/src/commands/config.tsindex 9da71f6759..3b94bb0c6a 100644--- a/src/commands/config.ts+++ b/src/commands/config.ts@@ -746,6 +746,12 @@ export async function runConfig(engine: BrainEngine, args: string[]) {const positionals = args.filter((a) => a !== '--raw');const key = positionals[1];const value = positionals[2];+ if ((action === 'get' || action === 'set') && key) {+ // C4: dream.auto_think.* keys were migrated to pinned questions (v205); name the replacement.+ const { autoThinkReplacement } = await import('../core/questions/auto-think-migration.ts');+ const replacement = autoThinkReplacement(key);+ if (replacement) console.error(`[config] ${key} is replaced by pinned questions (docs/guides/pinned-questions.md): ${replacement}`);+ }if (action === 'get' && key) {// #2120: `get` used to read only the DB plane, so a runtime-effective keydiff --git a/src/commands/dream.ts b/src/commands/dream.tsindex f938da986b..dd4784098d 100644--- a/src/commands/dream.ts+++ b/src/commands/dream.ts@@ -158,6 +158,10 @@ function parseArgs(args: string[]): DreamArgs {const phaseWasExplicit = phaseValues.length > 0;let phases: CyclePhase[] = [];for (const rawPhase of phaseValues) {+ if (rawPhase === 'auto_think') {+ dreamExit(usageError('The auto_think phase is replaced by pinned questions: dream.auto_think.questions became pins (inactive when auto_think was off).',+ 'Run: gbrain questions list (refresh one with gbrain questions refresh <id>, or run gbrain dream --phase standing_questions)'), json);+ }if (!(ALL_PHASES as string[]).includes(rawPhase)) {dreamExit(usageError(`Unknown phase "${rawPhase}". Valid: ${ALL_PHASES.join(', ')}`, 'Example: gbrain dream --phase lint'), json);}diff --git a/src/commands/models.ts b/src/commands/models.tsindex 9aa8ef2a56..7bd0861ef3 100644--- a/src/commands/models.ts+++ b/src/commands/models.ts@@ -92,7 +92,7 @@ const PER_TASK_KEYS: PerTaskModelRoute[] = [narrowResolver: resolveExtractAtomsModelWithSource,},{ key: 'models.drift', tier: 'reasoning', description: 'Drift LLM judge (v0.29 scaffold)' },- { key: 'models.auto_think', tier: 'deep', description: 'Auto-think question answering' },+ { key: 'models.standing_questions', tier: 'deep', description: 'Pinned-question answers (standing_questions phase, questions_pin/refresh)' },{ key: 'models.think', tier: 'deep', description: '`gbrain think` synthesis op' },{ key: 'models.subagent', tier: 'subagent', description: '`gbrain agent run` subagent loop' },{ key: 'facts.extraction_model', tier: 'reasoning', description: 'Real-time facts extraction during sync' },diff --git a/src/commands/questions.ts b/src/commands/questions.tsnew file mode 100644index 0000000000..ac8f7741c5--- /dev/null+++ b/src/commands/questions.ts@@ -0,0 +1,151 @@+/**+ * gbrain questions — pinned questions (standing answers kept current from+ * evidence). Every path dispatches through the trusted-local op layer+ * (handleToolCall, remote:false) so the CLI and the questions_* MCP tools+ * share one behavior.+ *+ * gbrain questions pin "<question>" [--source <id>] [--prefix <slug-prefix>] [--entity <slug>] [--defer] [--wait-ms N]+ * gbrain questions pin --id <id> [--publish] activate (or re-pin) an existing pin+ * gbrain questions list [--source <id>] [--include-archived]+ * gbrain questions status <id>+ * gbrain questions refresh <id> [--full] [--wait-ms N]+ * gbrain questions unpin <id>+ * Every subcommand takes --json (the receipt). Exit 1 when the answer is+ * blocked (no key, budget, failed refresh, awaiting consent) or a refresh did+ * not publish.+ */+import type { BrainEngine } from '../core/engine.ts';+import { handleToolCall } from '../mcp/server.ts';+import { setCliExitVerdict } from '../core/cli-force-exit.ts';+import { shellQuote } from '../core/agent-output.ts';+import type { QuestionReceipt } from '../core/questions/receipt.ts';++const HELP = [+ 'gbrain questions — pinned questions: cited answers kept current from your notes',+ '',+ ' pin "<question>" pin a question and get its first answer (paid model call)',+ ' --source <id> evidence source (default: current source)',+ ' --prefix <p> only pages under this slug prefix, e.g. projects/',+ ' --entity <slug> the entity page the question is about (context_pack shows its answer)',+ ' --defer pin without the first answer',+ ' --wait-ms N max wait for the first answer (default 30000)',+ ' pin --id <id> activate an inactive pin (made over MCP, or imported from dream.auto_think)',+ ' --publish publish a draft-only pin',+ ' list pins with freshness and blocked reason (--include-archived, --source <id>)',+ ' status <id> the answer with per-sentence stale flags and the next action',+ ' refresh <id> refresh now (--full recomputes; --wait-ms N)',+ ' unpin <id> stop refreshing and archive the page',+ '',+ 'Every subcommand takes --json. Docs: docs/guides/pinned-questions.md',+].join('\n');++function flag(args: string[], name: string): string | undefined {+ const i = args.indexOf(name);+ return i !== -1 ? args[i + 1] : undefined;+}++function positional(args: string[]): string | undefined {+ const valueFlags = new Set(['--source', '--prefix', '--entity', '--wait-ms', '--id', '--brain']);+ for (let i = 0; i < args.length; i++) {+ if (valueFlags.has(args[i])) { i++; continue; }+ if (args[i] === '--') return args[i + 1];+ if (!args[i].startsWith('--')) return args[i];+ }+ return undefined;+}++function waitMs(args: string[]): number | undefined {+ const raw = flag(args, '--wait-ms');+ return raw !== undefined && Number.isFinite(Number(raw)) ? Number(raw) : undefined;+}++function blocked(r: QuestionReceipt): boolean {+ return r.blocked_reason !== null || (r.refresh !== undefined && !['published', 'skipped'].includes(r.refresh.status));+}++function renderReceipt(r: QuestionReceipt, withAnswer: boolean): string {+ const lines = [`${r.id} [${r.freshness}${r.state !== 'active' ? `, ${r.state}` : ''}${r.publish_mode === 'draft' ? ', draft' : ''}]`, ` Q: ${r.question}`];+ if (r.refresh) lines.push(` refresh: ${r.refresh.status}${'blocked_reason' in r.refresh ? ` (${r.refresh.blocked_reason})` : ''}${'detail' in r.refresh ? ` — ${r.refresh.detail}` : ''}`);+ if (withAnswer && r.answer?.length) {+ for (const s of r.answer) lines.push(` ${s.stale ? '[stale] ' : ''}${s.origin === 'owner' ? '(you) ' : ''}${s.text}`);+ } else if (withAnswer && r.answer_revision > 0) {+ lines.push(' (no answer sentences: the evidence did not answer it)');+ }+ lines.push(` sentences: ${r.sentences.fresh} fresh, ${r.sentences.stale} stale${r.sentences.withheld ? `, ${r.sentences.withheld} withheld` : ''}; last refresh: ${r.last_refresh_at ?? 'never'}`);+ if (r.blocked_reason) lines.push(` blocked: ${r.blocked_reason}`);+ if (r.next_action) {+ const cmd = r.next_action.argv ? shellQuote(r.next_action.argv) : r.next_action.mcp?.tool;+ lines.push(` next: ${cmd}`, ` ${r.next_action.why}`);+ }+ return lines.join('\n');+}++export async function runQuestions(engine: BrainEngine, args: string[]): Promise<void> {+ const sub = args[0];+ const rest = args.slice(1);+ if (!sub || sub === '--help' || sub === '-h' || rest.includes('--help') || rest.includes('-h')) {+ process.stdout.write(HELP + '\n');+ return;+ }+ const json = rest.includes('--json');+ const source = flag(rest, '--source');+ const out = (doc: unknown, text: string) => process.stdout.write((json ? JSON.stringify(doc, null, 2) : text) + '\n');++ if (sub === 'pin') {+ const id = flag(rest, '--id');+ const question = id ? undefined : positional(rest);+ if (!id && !question) {+ console.error('Usage: gbrain questions pin "<question>" [--source <id>] [--prefix <p>] [--entity <slug>] | gbrain questions pin --id <id>');+ process.exit(2);+ }+ const prefix = flag(rest, '--prefix');+ const entity = flag(rest, '--entity');+ const params: Record<string, unknown> = id ? { id } : {+ question,+ ...(source || prefix || entity ? { scope: { ...(source ? { source } : {}), ...(prefix ? { slug_prefix: prefix } : {}), ...(entity ? { entity } : {}) } } : {}),+ };+ if (rest.includes('--defer')) params.defer = true;+ if (rest.includes('--publish')) params.publish = true;+ const wait = waitMs(rest);+ if (wait !== undefined) params.wait_ms = wait;+ const result = await handleToolCall(engine, 'questions_pin', params) as { created: boolean; activated: boolean; receipt: QuestionReceipt };+ out({ ok: !blocked(result.receipt), ...result }, `${result.created ? 'Pinned' : result.activated ? 'Activated' : 'Already pinned'}: ${renderReceipt(result.receipt, true)}`);+ if (blocked(result.receipt)) setCliExitVerdict(1);+ return;+ }+ if (sub === 'list') {+ const result = await handleToolCall(engine, 'questions_list', { ...(source ? { source } : {}), ...(rest.includes('--include-archived') ? { include_archived: true } : {}) }) as {+ questions: QuestionReceipt[]; counts: Record<string, number>;+ };+ const c = result.counts;+ out({ ok: true, ...result }, result.questions.length === 0+ ? 'No pinned questions. Pin one: gbrain questions pin "<question>"'+ : [...result.questions.map(r => renderReceipt(r, false)), '', `${c.total} pinned: ${c.fresh} fresh, ${c.stale} stale, ${c.awaiting_refresh} awaiting refresh, ${c.blocked} blocked`].join('\n'));+ return;+ }+ if (sub === 'status' || sub === 'refresh' || sub === 'unpin') {+ const id = positional(rest);+ if (!id) {+ console.error(`Usage: gbrain questions ${sub} <id> (ids: gbrain questions list)`);+ process.exit(2);+ }+ if (sub === 'status') {+ const r = await handleToolCall(engine, 'questions_status', { id }) as QuestionReceipt;+ out({ ok: !blocked(r), ...r }, renderReceipt(r, true));+ if (blocked(r)) setCliExitVerdict(1);+ return;+ }+ if (sub === 'refresh') {+ const wait = waitMs(rest);+ const r = await handleToolCall(engine, 'questions_refresh', { id, ...(rest.includes('--full') ? { full: true } : {}), ...(wait !== undefined ? { wait_ms: wait } : {}) }) as QuestionReceipt;+ out({ ok: !blocked(r), ...r }, renderReceipt(r, true));+ if (blocked(r)) setCliExitVerdict(1);+ return;+ }+ const result = await handleToolCall(engine, 'questions_unpin', { id }) as { unpinned: boolean; receipt: QuestionReceipt };+ out({ ok: true, ...result }, result.unpinned ? `Unpinned ${result.receipt.id}: refreshes stopped and its page is archived.` : `${result.receipt.id} was already unpinned.`);+ return;+ }+ console.error(`Unknown subcommand: ${sub} (try: gbrain questions --help)`);+ process.exit(2);+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 9dc9ebb241..f192cf0278 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -95,6 +95,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'providers': ['--brain', '--embedding-dimensions', '--embedding-model', '--help', '--json', '--model', '--source', '--status', '--touchpoint'],'publish': ['--accent', '--bg', '--border', '--brain', '--card-bg', '--code-bg', '--error', '--fg', '--help', '--json', '--link', '--muted', '--out', '--password', '--source', '--title'],'quarantine': ['--apply', '--brain', '--force', '--force-rechunk', '--help', '--include-flagged', '--json', '--limit', '--no-embed', '--source', '--source-id', '--stale'],+ 'questions': ['--brain', '--defer', '--entity', '--fail-fast', '--full', '--help', '--id', '--include-archived', '--json', '--prefix', '--probe', '--publish', '--source', '--tools-json', '--wait-ms', '--yes'],'recall': ['--accept-pending', '--access', '--add', '--allowed-operations', '--as-context', '--asof', '--background', '--bound-slug-prefixes', '--brain', '--budget-policy', '--budget-tokens', '--client', '--date', '--dated-since', '--days', '--entities', '--explain', '--federated-read', '--follow', '--full', '--fuzzy', '--grep', '--help', '--http', '--id', '--include-deleted', '--include-expired', '--json', '--kind', '--limit', '--mcp-only', '--model', '--multimodal', '--no-accept-pending', '--no-autopilot-install', '--page', '--params', '--path', '--pending', '--phase', '--progress-interval', '--progress-json', '--query', '--quiet', '--reason', '--recent', '--refresh-operations', '--request-id', '--rollup', '--scopes', '--session', '--session-id', '--since', '--since-last-run', '--slugs', '--source', '--source-id', '--sources', '--stale', '--supersessions', '--surface', '--timeout', '--to', '--today', '--url', '--wait', '--watch', '--yes'],'reconcile-links': ['--accept-pending', '--background', '--brain', '--dry-run', '--explain', '--follow', '--help', '--json', '--no-accept-pending', '--progress-interval', '--progress-json', '--quiet', '--source', '--timeout', '--wait'],'reindex': ['--accept-pending', '--aliases', '--background', '--brain', '--concurrency', '--cost-estimate', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--force-rechunk', '--help', '--json', '--limit', '--markdown', '--multimodal', '--no-accept-pending', '--no-embed', '--no-embedding', '--path', '--progress-interval', '--progress-json', '--quiet', '--repo', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--type', '--vectors', '--wait', '--workers', '--yes'],@@ -192,6 +193,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'pricing': ['--brain'],'projections': ['--brain'],'quarantine': ['--brain'],+ 'questions': ['--brain', '--source'],'recall': ['--brain', '--source'],'reconcile-links': ['--brain'],'reindex': ['--brain'],diff --git a/src/core/config.ts b/src/core/config.tsindex 9adde4eba6..acd3030c5d 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1389,6 +1389,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = ['models.dream.triage','models.drift','models.auto_think',+ 'models.standing_questions','models.think','models.subagent','models.expansion',diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex dc128b88fe..84ab68c799 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -81,6 +81,8 @@ export type CyclePhase =// soft-band takes against recent timeline evidence; report-only in v1// (writes reports/drift-<date>; auto_update mutates nothing).| 'drift'+ // C4 — pinned questions: refresh active pins under one BudgetMeter (src/core/questions/phase.ts).+ | 'standing_questions'// #5876 — Life Chronicle events from meeting/conversation/calendar pages (default ON).| 'chronicle'// Lane D — runs queued facts-absorb jobs on PGLite (no job worker there); bounded per run and per day.@@ -175,6 +177,8 @@ export const ALL_PHASES: CyclePhase[] = [// the calibration trio (fresh take resolutions) and BEFORE embed so the// drift report page gets embedded same-cycle. Report-only in v1.'drift',+ // C4 — pinned questions (global). Refreshes active pins; question pages publish through the coordinator.+ 'standing_questions',// #5876 — Life Chronicle events (global). BEFORE embed so event pages embed same-cycle.'chronicle',// Lane D — automatic facts drain (PGLite). BEFORE embed so new facts embed same-cycle.@@ -337,6 +341,8 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['calibration_profile',// #2653 — writes the reports/drift-<date> page.'drift',+ // C4 — writes pinned answers and question pages.+ 'standing_questions','edge_contradictions', // writes proposals and (apply mode) closure lines// #5876 — writes event pages, projections and the chronicle ledger.'chronicle',@@ -2760,6 +2766,19 @@ export async function runCycle(await safeYield(opts.yieldBetweenPhases);}+ // C4 pinned questions: refresh active pins under one BudgetMeter and max_per_cycle (src/core/questions/phase.ts).+ if (phases.includes('standing_questions')) {+ checkAborted(cycleSignal);+ if (!engine) phaseResults.push({ phase: 'standing_questions', status: 'skipped', duration_ms: 0, summary: 'no database connected', details: { reason: 'no_database' } });+ else {+ progress.start('cycle.standing_questions');+ const { runPhaseStandingQuestions } = await import('./questions/phase.ts');+ const { result, duration_ms } = await timePhase(() => runPhaseStandingQuestions(engine, { dryRun, signal: cycleSignal }), 'standing_questions');+ result.duration_ms = duration_ms; phaseResults.push(result); progress.finish();+ }+ await safeYield(opts.yieldBetweenPhases);+ }+// #5876 Life Chronicle (default ON): executes write-time ledger decisions and backfill rows, bounded per run.if (phases.includes('chronicle')) {checkAborted(cycleSignal);diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 46712ce6f6..80765230f4 100644--- a/src/core/cycle/phase-scope.ts+++ b/src/core/cycle/phase-scope.ts@@ -27,6 +27,7 @@ export const PHASE_SCOPE: Record<CyclePhase, PhaseScope> = {grade_takes: 'global',calibration_profile: 'global',drift: 'global',+ standing_questions: 'global',edge_contradictions: 'global',chronicle: 'global',facts_drain: 'global',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex da4e1d3db5..4918f21526 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -37,6 +37,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>calibration_profile: { class: 'no_coordinated_write', reason: 'Writes the calibration_profiles side table only.' },edge_contradictions: { class: 'writes', reason: 'Applied closures append a timeline line through the coordinated add_timeline_entry mutation; proposals live in the link_edge_proposals side table.' },drift: { class: 'writes', reason: 'The drift report page publishes through the maintenance coordinator.' },+ standing_questions: { class: 'writes', reason: 'Question pages publish through coordinated put_page mutations; answers and evidence pointers live in the pinned_questions side tables.' },chronicle: { class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },facts_drain: { class: 'writes', reason: 'Queued facts-absorb jobs publish facts through the same coordinated write path as the job worker.' },conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },diff --git a/src/core/error-registry.ts b/src/core/error-registry.tsindex 7382207ed5..c5a3da8eb1 100644--- a/src/core/error-registry.ts+++ b/src/core/error-registry.ts@@ -225,6 +225,8 @@ export const CODES = {projection_pending: { class: 'retryable', summary: "The current text projection is not ready." },provenance_required: { class: 'caller', summary: "provenance is required and must be non-empty." },publication_pending: { class: 'retryable', summary: "The catalog adoption is accepted but not fully committed." },+ question_not_found: { class: 'caller', summary: "No pinned question has this id in the caller's scope; ids are source-qualified (default:questions/<slug>).", docs: 'docs/guides/pinned-questions.md#ids-and-scope' },+ question_owner_only: { class: 'host_only', summary: "Pinned questions are owner-private: this connection cannot read private pages (or is slug-fenced or delegated), so the owner runs the command on the brain host.", docs: 'docs/guides/pinned-questions.md#who-can-see-pinned-questions' },queue_capacity: { class: 'retryable', summary: "The bounded queue is full; existing requests keep their place." },rate_limited: { class: 'retryable', summary: "The request was rate-limited; retry after the stated delay." },recovery_required: { class: 'host_only', summary: "An earlier write left state that must be inspected and recovered before new writes." },@@ -349,6 +351,7 @@ export const NOTICE_CODES = {post_upgrade: { kind: 'safety', summary: 'gbrain was upgraded; behavior for scripts and agents changed — read the behavior table once.' },facts_drain_first_run: { kind: 'info', summary: 'The automatic facts drain is about to process its first backlog on this brain: the queued page count, the estimated spend, the caps and the opt-out.' },facts_drain_deferred: { kind: 'degraded', summary: 'The automatic facts drain left queued pages waiting (no key, a spend cap, an unpriced model under a user cap); the fix is the next step.' },+ pinned_answer_stale: { kind: 'degraded', summary: 'A pinned answer has stale sentences (their evidence changed or was removed) or its refresh is blocked; stale sentences are flagged and withheld from context_pack, and the fix is the next step.' },held_files: { kind: 'degraded', summary: 'Sync holds files in the read scope it cannot import: held new files are missing and pages whose newer file is held are stale; the fix is the repair preview on the brain host.' },recovered_frontmatter: { kind: 'coaching', summary: 'Files imported only after quoting unquoted frontmatter values; the generator writing them should quote values (the fix is the repair preview).' },} as const satisfies Record<string, NoticeEntry>;diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.tsindex 2a7619c02b..e3b5138751 100644--- a/src/core/minions/protected-names.ts+++ b/src/core/minions/protected-names.ts@@ -33,6 +33,8 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set(['consolidate',// Temporal typed edges: the contradiction phase calls the chat model.'edge_contradictions',+ // C4 pinned questions: each refresh is a paid chat call.+ 'standing_questions',// v0.40.3.0 — per-chunk Haiku contextual retrieval backfill. Each job// potentially calls Haiku 1-50 times per page; an MCP/OAuth-scoped// caller submitting this in bulk could drain the user's Anthropicdiff --git a/src/core/operations.ts b/src/core/operations.tsindex 183da64120..a5a10daaa5 100644--- a/src/core/operations.ts+++ b/src/core/operations.ts@@ -113,6 +113,7 @@ import { imageOperations } from './ops/image.ts';import { schemaPacksOperations } from './ops/schema-packs.ts';import { skilloptOperations } from './ops/skillopt.ts';import { loopsOperations } from './ops/loops.ts';+import { questionsOperations } from './ops/questions.ts';import { chronicleOperations } from './ops/chronicle.ts';import { extractionOperations } from './ops/extraction.ts';import { entityIdentityOperations } from './ops/entity-identity.ts';@@ -221,7 +222,7 @@ export const operations: Operation[] = [// v0.41.18.0 run_onboard + v0.41.20.0 run_skillopt — ops/skillopt.ts...skilloptOperations,// v0.47: open-loop engine (who is waiting on you) — ops/loops.ts- ...loopsOperations, ...noticesOperations, // + agent contract v1 A6 mute_notice — ops/notices.ts+ ...loopsOperations, ...questionsOperations, ...noticesOperations, // + agent contract v1 A6 mute_notice — ops/notices.ts];// ---------------------------------------------------------------------------@@ -307,6 +308,9 @@ const OP_AREAS: Record<string, string> = {entity_identity_list: 'entities',// v0.47 open-loop engine (google source kind)open_loops: 'loops', loops_close: 'loops', loops_mute: 'loops', loops_unmute: 'loops',+ // C4 pinned questions (owner-private, full surface only)+ questions_pin: 'questions', questions_list: 'questions', questions_status: 'questions',+ questions_refresh: 'questions', questions_unpin: 'questions',// insight / signal readsget_recent_salience: 'insights', find_anomalies: 'insights',find_contradictions: 'insights', find_experts: 'insights',diff --git a/src/core/ops/cli-equivalent.ts b/src/core/ops/cli-equivalent.tsindex c51709f2bc..c05935c29b 100644--- a/src/core/ops/cli-equivalent.ts+++ b/src/core/ops/cli-equivalent.ts@@ -16,6 +16,11 @@ const OVERRIDES: Readonly<Record<string, readonly string[]>> = {open_loops: ['gbrain', 'loops', 'list'],loops_close: ['gbrain', 'loops', 'done'],loops_mute: ['gbrain', 'loops', 'mute'],+ questions_pin: ['gbrain', 'questions', 'pin'],+ questions_list: ['gbrain', 'questions', 'list'],+ questions_status: ['gbrain', 'questions', 'status'],+ questions_refresh: ['gbrain', 'questions', 'refresh'],+ questions_unpin: ['gbrain', 'questions', 'unpin'],get_active_schema_pack: ['gbrain', 'schema', 'active'],list_schema_packs: ['gbrain', 'schema', 'list'],schema_stats: ['gbrain', 'schema', 'stats'],diff --git a/src/core/ops/contract.ts b/src/core/ops/contract.tsindex 547a12f24a..68dfa9b008 100644--- a/src/core/ops/contract.ts+++ b/src/core/ops/contract.ts@@ -6,6 +6,7 @@* this entire surface, so existing importers are unchanged.*/+import type { WriteInference } from './write-inference.ts';import type { BrainEngine } from '../engine.ts';import type { GBrainConfig } from '../config.ts';import { MEMORY_VERBS_VERSION } from '../verbs.ts';@@ -652,6 +653,11 @@ export interface Operation {handler: (ctx: OperationContext, params: Record<string, unknown>) => Promise<unknown>;outputRedaction: OutputRedactionPolicy;mutating?: boolean;+ /**+ * What model work this write may do and when (`src/core/ops/write-inference.ts`).+ * Unset resolves through OP_WRITE_INFERENCE, then to `'none'`.+ */+ writeInference?: WriteInference;/*** Agent contract v1 (A2): repeating the call with the same arguments (and,* for journaled writes, the same request identity) has the same effect asdiff --git a/src/core/ops/facts.ts b/src/core/ops/facts.tsindex d95c8fff62..b90f10b2cb 100644--- a/src/core/ops/facts.ts+++ b/src/core/ops/facts.ts@@ -720,6 +720,9 @@ const context_pack: Operation = {...(budgetTokens !== null? { budget_tokens: budgetTokens, budget_used: budgetUsed, dropped_count: droppedCount }: {}),+ // C4: optional pinned answers (fresh sentences) and the withheld count (src/core/questions/service.ts).+ ...(await (await import('../questions/service.ts')).pinnedAnswersForPack(ctx, [...new Set([...(res.cards ?? []).map((c) => c.entity.slug), ...entities])])+ .catch(() => null)),};},};diff --git a/src/core/ops/questions.ts b/src/core/ops/questions.tsnew file mode 100644index 0000000000..ecb12cbb36--- /dev/null+++ b/src/core/ops/questions.ts@@ -0,0 +1,100 @@+/**+ * questions_* ops: pinned questions (standing answers kept current from+ * evidence). Owner-private in v1: every op refuses callers that cannot read+ * private pages (src/core/questions/service.ts). Full MCP surface only (not+ * in STARTER_OPS); `gbrain questions <verb>` is the CLI.+ */+import type { Operation, ParamDef } from './contract.ts';++const EXEMPT = { exempt: 'owner-private pinned-question receipts: every questions_* op refuses callers that cannot read private pages' };+const ID: ParamDef = { type: 'string', required: true, description: 'Source-qualified id from questions_list, e.g. default:questions/<slug>.' };+const WAIT: ParamDef = { type: 'number', description: 'Max ms to wait for the answer (pin default 30000, refresh 120000; max 300000).' };++const questions_pin: Operation = {+ name: 'questions_pin',+ description: 'Pin a question: gbrain keeps a cited answer current from your notes and flags sentences whose evidence changed. Idempotent. Pins made over MCP stay inactive (paid refresh) until the owner activates them; returns the first answer when a key and consent exist, else awaiting_refresh with next_action.',+ params: {+ question: { type: 'string', description: 'The question (omit when passing id).' },+ scope: {+ type: 'object', description: 'Evidence scope; default: the current source.',+ properties: {+ source: { type: 'string', description: 'Source id.' },+ slug_prefix: { type: 'string', description: 'Only pages under this prefix, e.g. projects/.' },+ entity: { type: 'string', description: 'Entity page slug the question is about.' },+ },+ },+ id: { type: 'string', description: 'Existing pin id: re-pin or (owner, on the host) activate it.' },+ defer: { type: 'boolean', description: 'Skip the first answer.' },+ wait_ms: WAIT,+ publish: { type: 'boolean', description: 'Owner only: publish a draft-only pin.' },+ },+ mutating: true,+ writeInference: 'explicit_llm',+ idempotent: true,+ scope: 'write',+ outputRedaction: EXEMPT,+ annotations: { title: 'questions_pin', idempotentHint: true },+ handler: async (ctx, p) => (await import('../questions/service.ts')).pinQuestion(ctx, p),+};++const questions_list: Operation = {+ name: 'questions_list',+ description: 'List pinned questions with freshness, blocked reason and next action, plus fresh/stale/pending counts. Owner-capable connections only.',+ params: {+ source: { type: 'string', description: 'Only this source.' },+ include_archived: { type: 'boolean', description: 'Include unpinned (archived) questions.' },+ },+ mutating: false,+ idempotent: true,+ scope: 'read',+ outputRedaction: EXEMPT,+ annotations: { title: 'questions_list', readOnlyHint: true },+ handler: async (ctx, p) => (await import('../questions/service.ts')).listQuestions(ctx, p),+};++const questions_status: Operation = {+ name: 'questions_status',+ description: 'One pinned question: the answer with per-sentence stale flags, evidence watermark, last refresh, blocked reason, next action and verify step. Owner-capable connections only.',+ params: {+ id: ID,+ include_answer: { type: 'boolean', description: 'Include answer sentences (default true).' },+ },+ mutating: false,+ idempotent: true,+ scope: 'read',+ outputRedaction: EXEMPT,+ annotations: { title: 'questions_status', readOnlyHint: true },+ handler: async (ctx, p) => (await import('../questions/service.ts')).questionStatus(ctx, p),+};++const questions_refresh: Operation = {+ name: 'questions_refresh',+ description: 'Refresh a pinned answer now (a paid model call): re-retrieves current evidence and edits the answer, or recomputes with full or after deletions. A failed refresh keeps the previous answer with its stale flags.',+ params: {+ id: ID,+ full: { type: 'boolean', description: 'Recompute from scratch.' },+ wait_ms: WAIT,+ },+ mutating: true,+ writeInference: 'explicit_llm',+ idempotent: false,+ scope: 'write',+ outputRedaction: EXEMPT,+ annotations: { title: 'questions_refresh' },+ handler: async (ctx, p) => (await import('../questions/service.ts')).refreshQuestion(ctx, p),+};++const questions_unpin: Operation = {+ name: 'questions_unpin',+ description: 'Unpin a question: refreshes stop and its page is archived (your notes on it are kept). Idempotent.',+ params: { id: ID },+ mutating: true,+ writeInference: 'none',+ idempotent: true,+ scope: 'write',+ outputRedaction: EXEMPT,+ annotations: { title: 'questions_unpin', idempotentHint: true },+ handler: async (ctx, p) => (await import('../questions/service.ts')).unpinQuestion(ctx, p),+};++export const questionsOperations: Operation[] = [questions_pin, questions_list, questions_status, questions_refresh, questions_unpin];diff --git a/src/core/ops/write-inference.ts b/src/core/ops/write-inference.tsnew file mode 100644index 0000000000..2ed662fdb6--- /dev/null+++ b/src/core/ops/write-inference.ts@@ -0,0 +1,87 @@+/**+ * Write-inference classes: what model work a write may do and when.+ *+ * The contract every write path keeps: saving text or a fact never waits on a+ * generative model. A write is acknowledged and keyword-queryable without one.+ * Embeddings are the configured feature. Generative work a write triggers runs+ * after the save, attributed and switchable. Opt-in media preprocessing (image+ * OCR) is the one exception that runs before the save, and only when enabled.+ *+ * Resolution order for an operation: its inline `writeInference` field, then+ * this map, then `'none'` (the strictest promise), so an operation added+ * without a class is held to the zero-model rule rather than exempted.+ * `test/write-path-zero-llm.serial.test.ts` checks the promise at runtime.+ */+import type { Operation } from './contract.ts';++export type WriteInference =+ /** No model call of any kind before the write commits (post-commit embedding effects are fine). */+ | 'none'+ /** May embed before commit (e.g. `remember` dedup); never calls a generative model. */+ | 'embedding'+ /** `none`/`embedding` before commit; may queue generative work that runs after commit (facts extraction). */+ | 'async_derived'+ /** May call a generative model before commit only when a user opt-in is on (image OCR). */+ | 'opt_in_media'+ /** The operation is itself an explicit model call (think, extract_facts, submit_agent, …). */+ | 'explicit_llm'+ /** Administrative state (jobs, sources, skills, notices); writes no memory content. */+ | 'non_content';++export const WRITE_INFERENCE_CLASSES: readonly WriteInference[] = [+ 'none', 'embedding', 'async_derived', 'opt_in_media', 'explicit_llm', 'non_content',+];++/** Classes that promise no generative model call before the write commits. */+export const ZERO_GENERATIVE_BEFORE_COMMIT: ReadonlySet<WriteInference> = new Set<WriteInference>([+ 'none', 'embedding', 'async_derived',+]);++export const OP_WRITE_INFERENCE: Readonly<Record<string, WriteInference>> = {+ // memory verbs and facts+ remember: 'embedding', forget: 'none', forget_fact: 'none', extract_facts: 'explicit_llm',+ // pages+ put_page: 'async_derived', capture: 'async_derived', edit_page: 'async_derived',+ revert_version: 'async_derived', delete_page: 'none', restore_page: 'none',+ purge_deleted_pages: 'none', cancel_write_request: 'none',+ put_raw_data: 'none', log_ingest: 'none', file_upload: 'opt_in_media',+ // graph, tags, timeline, takes+ add_tag: 'none', remove_tag: 'none', add_link: 'none', remove_link: 'none',+ add_timeline_entry: 'none', takes_add: 'none', takes_update: 'none',+ takes_resolve: 'none', takes_supersede: 'none', ontology_propose: 'none',+ // entities and loops+ extract_entities: 'embedding', extraction_review: 'none',+ entity_identity_link: 'none', entity_identity_unlink: 'none',+ loops_close: 'none', loops_mute: 'none', loops_unmute: 'none',+ // sync and connectors+ sync_brain: 'async_derived', connector_sync: 'async_derived',+ // explicit model work+ think: 'explicit_llm', submit_agent: 'explicit_llm', run_skillopt: 'explicit_llm',+ run_onboard: 'explicit_llm', chronicle_backfill: 'explicit_llm',+ // administrative state+ put_skill: 'non_content', delete_skill: 'non_content', set_skill_policy: 'non_content',+ prune_skill_revisions: 'non_content', retain_skill_revision: 'non_content',+ import_skill_proposal: 'non_content', join_brain: 'non_content',+ sync_brain_skills: 'non_content', leave_brain: 'non_content',+ submit_job: 'non_content', cancel_job: 'non_content', retry_job: 'non_content',+ pause_job: 'non_content', resume_job: 'non_content', replay_job: 'non_content',+ send_job_message: 'non_content', sources_add: 'non_content', sources_remove: 'non_content',+ request_tools: 'non_content', code_traversal_cache_clear: 'non_content',+ migrate_embeddings: 'non_content', schema_apply_mutations: 'non_content',+ mute_notice: 'non_content',+};++/** CLI writers that are not operations, with the class they keep. */+export const CLI_WRITE_INFERENCE: Readonly<Record<string, WriteInference>> = {+ import: 'embedding',+ sync: 'async_derived',+ 'transcripts ingest': 'async_derived',+ 'connectors sync': 'async_derived',+ 'hook ipc banking': 'none',+ // P1: accept/undo/date append or remove a timeline line and re-derive links; reject records a verdict.+ 'edge-proposals': 'none',+};++export function writeInferenceOf(op: Pick<Operation, 'name' | 'writeInference'>): WriteInference {+ return op.writeInference ?? OP_WRITE_INFERENCE[op.name] ?? 'none';+}diff --git a/src/core/pglite-schema.generated.ts b/src/core/pglite-schema.generated.tsindex 0783d2ea7b..557ff83260 100644--- a/src/core/pglite-schema.generated.ts+++ b/src/core/pglite-schema.generated.ts@@ -1911,6 +1911,68 @@ END \$rls\$;CREATE SEQUENCE IF NOT EXISTS graph_generation_seq;+-- Pinned questions (C4): answers and their evidence pointers live outside pages.+CREATE TABLE IF NOT EXISTS pinned_questions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ question TEXT NOT NULL,+ scope_slug_prefix TEXT,+ scope_entity TEXT,+ state TEXT NOT NULL DEFAULT 'active',+ inactive_reason TEXT,+ publish_mode TEXT NOT NULL DEFAULT 'publish',+ model TEXT,+ cooldown_days REAL,+ origin TEXT NOT NULL DEFAULT 'pin',+ created_by TEXT NOT NULL,+ revision BIGINT NOT NULL DEFAULT 1,+ answer_revision INTEGER NOT NULL DEFAULT 0,+ answer TEXT,+ answer_model TEXT,+ last_refresh_at TIMESTAMPTZ,+ last_attempt_at TIMESTAMPTZ,+ last_error TEXT,+ watermark_generation BIGINT,+ watermark_fact_id BIGINT,+ watermark_at TIMESTAMPTZ,+ lease_token TEXT,+ lease_owner TEXT,+ lease_expires_at TIMESTAMPTZ,+ refresh_attempts INTEGER NOT NULL DEFAULT 0,+ spend_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ archived_at TIMESTAMPTZ,+ CONSTRAINT pinned_questions_source_slug_key UNIQUE (source_id, slug)+);+CREATE INDEX IF NOT EXISTS pinned_questions_state_idx ON pinned_questions (state, source_id);+CREATE TABLE IF NOT EXISTS question_evidence (+ id BIGSERIAL PRIMARY KEY,+ question_id BIGINT NOT NULL,+ answer_revision INTEGER NOT NULL,+ sentence_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ source_id TEXT NOT NULL,+ page_id INTEGER,+ page_slug TEXT,+ page_generation BIGINT,+ page_revision TEXT,+ item_id BIGINT,+ content_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS question_evidence_question_idx ON question_evidence (question_id, answer_revision);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE pinned_questions ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE question_evidence ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;`;diff --git a/src/core/questions/auto-think-migration.ts b/src/core/questions/auto-think-migration.tsnew file mode 100644index 0000000000..e75652e58f--- /dev/null+++ b/src/core/questions/auto-think-migration.ts@@ -0,0 +1,120 @@+/**+ * dream.auto_think -> pinned questions (C4 migration). Maps all seven legacy+ * keys without creating consent the owner never gave:+ *+ * dream.auto_think.questions one pin per question (source `default`, no scope)+ * dream.auto_think.enabled=false pins import inactive (`migrated_disabled`)+ * dream.auto_think.budget = 0 pins import inactive (`migrated_zero_budget`);+ * a positive budget seeds cycle.standing_questions.budget_usd+ * dream.auto_think.auto_commit false (the default) keeps draft-only publishing+ * dream.auto_think.cooldown_days per-pin cooldown (default 30, as before)+ * dream.auto_think.max_per_cycle seeds cycle.standing_questions.max_per_cycle+ * models.auto_think / dream.auto_think.model+ * per-pin model+ * plus dream.auto_think.allow_unpriced -> cycle.standing_questions.allow_unpriced+ * and last_completion_ts as each pin's cooldown anchor.+ *+ * Reads config and inserts rows only: no provider call, no page write (the+ * owner's next local `gbrain questions` call or cycle materializes the+ * question pages). Re-running inserts nothing new (ON CONFLICT DO NOTHING on+ * the deterministic slug) and never overwrites a key the owner already set.+ */+import type { BrainEngine } from '../engine.ts';+import { MAX_QUESTION_CHARS, normalizeQuestion, questionSlug } from './identity.ts';++export const AUTO_THINK_KEYS = [+ 'dream.auto_think.enabled', 'dream.auto_think.questions', 'dream.auto_think.max_per_cycle',+ 'dream.auto_think.auto_commit', 'dream.auto_think.budget', 'dream.auto_think.cooldown_days',+ 'dream.auto_think.model',+] as const;++/** Where each legacy key went; `gbrain config set|get` prints it for the old key. */+export const AUTO_THINK_REPLACEMENTS: Readonly<Record<string, string>> = {+ 'dream.auto_think.enabled': 'gbrain questions pin "<question>" (CLI pins refresh; gbrain questions unpin <id> stops one)',+ 'dream.auto_think.questions': 'gbrain questions pin "<question>" / gbrain questions list',+ 'dream.auto_think.max_per_cycle': 'gbrain config set cycle.standing_questions.max_per_cycle <n>',+ 'dream.auto_think.auto_commit': 'gbrain questions pin --id <id> --publish',+ 'dream.auto_think.budget': 'gbrain config set cycle.standing_questions.budget_usd <usd>',+ 'dream.auto_think.cooldown_days': 'gbrain config set cycle.standing_questions.cooldown_days <days>',+ 'dream.auto_think.model': 'gbrain config set models.standing_questions <model>',+ 'dream.auto_think.allow_unpriced': 'gbrain config set cycle.standing_questions.allow_unpriced true',+ 'dream.auto_think.last_completion_ts': 'gbrain questions status <id> (last_refresh_at)',+ 'models.auto_think': 'gbrain config set models.standing_questions <model>',+};++export function autoThinkReplacement(key: string): string | null {+ return AUTO_THINK_REPLACEMENTS[key] ?? null;+}++export interface AutoThinkMigrationReport {+ questions: number;+ inserted: number;+ state: 'active' | 'inactive' | null;+ publish_mode: 'publish' | 'draft' | null;+ config_set: string[];+}++function finiteNumber(raw: string | null | undefined): number | null {+ if (raw === null || raw === undefined || raw.trim() === '') return null;+ const n = Number(raw);+ return Number.isFinite(n) ? n : null;+}++async function setIfUnset(engine: BrainEngine, key: string, value: string, set: string[]): Promise<void> {+ const current = await engine.getConfig(key);+ if (current !== null && current !== undefined && current !== '') return;+ await engine.setConfig(key, value);+ set.push(key);+}++export async function migrateAutoThinkToPins(engine: BrainEngine): Promise<AutoThinkMigrationReport> {+ const read = (key: string) => engine.getConfig(key).catch(() => null);+ const report: AutoThinkMigrationReport = { questions: 0, inserted: 0, state: null, publish_mode: null, config_set: [] };+ let questions: string[] = [];+ const rawQuestions = await read('dream.auto_think.questions');+ if (rawQuestions) {+ try {+ const parsed = JSON.parse(rawQuestions);+ if (Array.isArray(parsed)) questions = parsed.filter((q): q is string => typeof q === 'string');+ } catch { /* malformed list: nothing to import */ }+ }+ const bySlug = new Map<string, string>();+ for (const q of questions.map(normalizeQuestion)) {+ if (q.length === 0 || q.length > MAX_QUESTION_CHARS) continue;+ const slug = questionSlug(q, { source: 'default' });+ if (!bySlug.has(slug)) bySlug.set(slug, q);+ }+ questions = [...bySlug.values()];+ report.questions = questions.length;+ if (questions.length === 0) return report;++ const enabled = (await read('dream.auto_think.enabled')) === 'true';+ const budget = finiteNumber(await read('dream.auto_think.budget')) ?? 2.0;+ const autoCommit = (await read('dream.auto_think.auto_commit')) === 'true';+ const cooldown = Math.max(0, finiteNumber(await read('dream.auto_think.cooldown_days')) ?? 30);+ const model = (await read('models.auto_think')) || (await read('dream.auto_think.model')) || null;+ const lastCompletion = await read('dream.auto_think.last_completion_ts');+ const anchor = lastCompletion && Number.isFinite(Date.parse(lastCompletion)) ? new Date(Date.parse(lastCompletion)).toISOString() : null;+ const inactiveReason = !enabled ? 'migrated_disabled' : budget <= 0 ? 'migrated_zero_budget' : null;+ report.state = inactiveReason ? 'inactive' : 'active';+ report.publish_mode = autoCommit ? 'publish' : 'draft';++ for (const question of questions) {+ const slug = questionSlug(question, { source: 'default' });+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO pinned_questions (source_id, slug, question, state, inactive_reason, publish_mode, model, cooldown_days,+ origin, created_by, last_attempt_at)+ VALUES ('default', $1, $2, $3, $4, $5, $6, $7, 'auto_think', 'migration:auto_think', $8::timestamptz)+ ON CONFLICT (source_id, slug) DO NOTHING RETURNING id`,+ [slug, question, report.state, inactiveReason, report.publish_mode, model, cooldown, anchor]);+ report.inserted += rows.length;+ }++ const maxPerCycle = finiteNumber(await read('dream.auto_think.max_per_cycle'));+ if (maxPerCycle !== null && maxPerCycle >= 1) await setIfUnset(engine, 'cycle.standing_questions.max_per_cycle', String(Math.floor(maxPerCycle)), report.config_set);+ if (budget > 0) await setIfUnset(engine, 'cycle.standing_questions.budget_usd', String(budget), report.config_set);+ if ((await read('dream.auto_think.allow_unpriced')) === 'true') {+ await setIfUnset(engine, 'cycle.standing_questions.allow_unpriced', 'true', report.config_set);+ }+ return report;+}diff --git a/src/core/questions/freshness.ts b/src/core/questions/freshness.tsnew file mode 100644index 0000000000..c542351959--- /dev/null+++ b/src/core/questions/freshness.ts@@ -0,0 +1,178 @@+/**+ * Read-time staleness for pinned answers. Nothing here trusts a write hook:+ * every read joins the answer's evidence pointers against the current rows,+ * so hard deletes, purges, cascades, `forget`, expiry by the clock alone,+ * supersession and visibility changes all surface on the next read with no+ * cycle run. A pointer that no longer resolves, or a sentence with no pointer+ * at all, is stale (fail closed).+ */+import type { BrainEngine } from '../engine.ts';+import type { AnswerSentence, PinRow } from './store.ts';++export type StaleReason =+ | 'page_missing' | 'page_deleted' | 'page_changed' | 'source_archived'+ | 'fact_missing' | 'fact_withdrawn' | 'fact_expired' | 'fact_superseded' | 'fact_changed'+ | 'timeline_missing' | 'timeline_changed' | 'take_missing' | 'take_inactive' | 'take_changed'+ | 'owner_edited' | 'unverifiable';++/** Reasons that remove or contradict evidence: an incremental edit can't recover from them, so refresh recomputes. */+const FULL_RECOMPUTE_REASONS: ReadonlySet<StaleReason> = new Set([+ 'page_missing', 'page_deleted', 'source_archived', 'fact_missing', 'fact_withdrawn', 'fact_expired',+ 'fact_superseded', 'fact_changed', 'timeline_missing', 'take_missing', 'take_inactive', 'take_changed', 'unverifiable',+]);++export type EvidenceKind = 'page' | 'fact' | 'timeline' | 'take' | 'owner';++/** Content hashes computed in SQL, identically at capture and at read. */+export const FACT_HASH_SQL = (a: string) => `md5(${a}.fact || '|' || ${a}.visibility || '|' || COALESCE(${a}.entity_slug, '') || '|' || ${a}.kind)`;+export const TIMELINE_HASH_SQL = (a: string) => `md5(${a}.date::text || '|' || ${a}.summary || '|' || ${a}.detail)`;+export const TAKE_HASH_SQL = (a: string) => `md5(${a}.claim || '|' || ${a}.holder || '|' || COALESCE(${a}.weight::text, '') || '|' || COALESCE(${a}.resolved_outcome::text, ''))`;++export interface EvaluatedSentence extends AnswerSentence {+ stale: boolean;+ /** Not readable by this caller (evidence outside its source grant): never returned as text. */+ hidden: boolean;+ reasons: StaleReason[];+}++export interface AnswerEvaluation {+ sentences: EvaluatedSentence[];+ fresh: number;+ stale: number;+ hidden: number;+ /** A stale reason an incremental edit cannot repair (deletion, withdrawal, conflicting correction). */+ needsFull: boolean;+}++interface EvidenceJoinRow {+ sentence_id: string;+ kind: string;+ source_id: string;+ page_id: number | null;+ page_generation: string | number | null;+ page_revision: string | null;+ content_hash: string | null;+ p_id: number | null;+ p_generation: string | number | null;+ p_revision: string | null;+ p_deleted: unknown;+ p_source_archived: boolean | null;+ p_body_hash: string | null;+ f_id: string | number | null;+ f_expired: unknown;+ f_valid_until_passed: boolean | null;+ f_superseded: string | number | null;+ f_hash: string | null;+ t_id: number | null;+ t_hash: string | null;+ k_id: string | number | null;+ k_active: boolean | null;+ k_superseded: number | null;+ k_hash: string | null;+}++function pageReasons(r: EvidenceJoinRow, changed: StaleReason): StaleReason[] {+ if (r.page_id === null) return [];+ if (r.p_id === null) return ['page_missing'];+ if (r.p_deleted !== null && r.p_deleted !== undefined) return ['page_deleted'];+ if (r.p_source_archived) return ['source_archived'];+ if (String(r.p_generation) !== String(r.page_generation) || (r.page_revision ?? null) !== (r.p_revision ?? null)) return [changed];+ return [];+}++export function evidenceReasons(r: EvidenceJoinRow): StaleReason[] {+ switch (r.kind as EvidenceKind) {+ case 'page': return r.page_id === null ? ['unverifiable'] : pageReasons(r, 'page_changed');+ case 'owner': {+ if (r.page_id === null) return ['unverifiable'];+ if (r.p_id === null) return ['page_missing'];+ if (r.p_deleted !== null && r.p_deleted !== undefined) return ['page_deleted'];+ return r.p_body_hash === r.content_hash ? [] : ['owner_edited'];+ }+ case 'fact': {+ if (r.f_id === null) return ['fact_missing'];+ if (r.f_expired !== null && r.f_expired !== undefined) return ['fact_withdrawn'];+ if (r.f_superseded !== null && r.f_superseded !== undefined) return ['fact_superseded'];+ if (r.f_valid_until_passed) return ['fact_expired'];+ if (r.f_hash !== r.content_hash) return ['fact_changed'];+ return [];+ }+ case 'timeline': {+ if (r.t_id === null) return ['timeline_missing'];+ if (r.t_hash !== r.content_hash) return ['timeline_changed'];+ return pageReasons(r, 'page_changed');+ }+ case 'take': {+ if (r.k_id === null) return ['take_missing'];+ if (r.k_active === false || (r.k_superseded !== null && r.k_superseded !== undefined)) return ['take_inactive'];+ if (r.k_hash !== r.content_hash) return ['take_changed'];+ return pageReasons(r, 'page_changed');+ }+ default: return ['unverifiable'];+ }+}++/**+ * Evaluate the current answer for one reader. `readableSources` null means the+ * trusted local view (every source); otherwise a sentence citing evidence in a+ * source outside the list is hidden, never returned.+ */+export async function evaluateAnswer(+ engine: BrainEngine,+ pin: Pick<PinRow, 'id' | 'answer' | 'answer_revision'>,+ opts: { readableSources: string[] | null },+): Promise<AnswerEvaluation> {+ const rows = pin.answer.length === 0 ? [] : await engine.executeRaw<EvidenceJoinRow>(+ `SELECT e.sentence_id, e.kind, e.source_id, e.page_id, e.page_generation, e.page_revision, e.content_hash,+ p.id AS p_id, p.generation AS p_generation, p.knowledge_revision::text AS p_revision, p.deleted_at AS p_deleted,+ s.archived AS p_source_archived, md5(p.compiled_truth) AS p_body_hash,+ f.id AS f_id, f.expired_at AS f_expired, (f.valid_until IS NOT NULL AND f.valid_until <= now()) AS f_valid_until_passed,+ f.superseded_by AS f_superseded, ${FACT_HASH_SQL('f')} AS f_hash,+ t.id AS t_id, ${TIMELINE_HASH_SQL('t')} AS t_hash,+ k.id AS k_id, k.active AS k_active, k.superseded_by AS k_superseded, ${TAKE_HASH_SQL('k')} AS k_hash+ FROM question_evidence e+ LEFT JOIN pages p ON p.id = e.page_id+ LEFT JOIN sources s ON s.id = p.source_id+ LEFT JOIN facts f ON e.kind = 'fact' AND f.id = e.item_id AND f.source_id = e.source_id+ LEFT JOIN timeline_entries t ON e.kind = 'timeline' AND t.id = e.item_id+ LEFT JOIN takes k ON e.kind = 'take' AND k.id = e.item_id+ WHERE e.question_id = $1 AND e.answer_revision = $2`,+ [pin.id, pin.answer_revision]);+ const bySentence = new Map<string, EvidenceJoinRow[]>();+ for (const r of rows) bySentence.set(r.sentence_id, [...(bySentence.get(r.sentence_id) ?? []), r]);+ const sentences = pin.answer.map((s): EvaluatedSentence => {+ const evidence = bySentence.get(s.id) ?? [];+ const reasons = evidence.length === 0 ? ['unverifiable' as const] : [...new Set(evidence.flatMap(evidenceReasons))];+ const hidden = opts.readableSources !== null && evidence.some(e => !opts.readableSources!.includes(e.source_id));+ return { ...s, stale: reasons.length > 0, hidden, reasons };+ });+ return {+ sentences,+ fresh: sentences.filter(s => !s.stale && !s.hidden).length,+ stale: sentences.filter(s => s.stale && !s.hidden).length,+ hidden: sentences.filter(s => s.hidden).length,+ needsFull: sentences.some(s => s.reasons.some(r => FULL_RECOMPUTE_REASONS.has(r))),+ };+}++/**+ * Evidence written in the pin's scope after its watermark (new pages or+ * edits by the global page-generation clock, new fact rows). Informational:+ * it schedules a refresh but never marks a cited sentence stale.+ */+export async function newEvidenceSinceWatermark(engine: BrainEngine, pin: PinRow): Promise<boolean> {+ if (pin.answer_revision === 0 || pin.watermark_generation === null) return false;+ const params: unknown[] = [pin.source_id, pin.watermark_generation];+ let prefix = '';+ if (pin.scope_slug_prefix) { params.push(`${pin.scope_slug_prefix.replace(/[\\%_]/g, '\\$&')}%`); prefix = `AND p.slug LIKE $${params.length}`; }+ const [pageHit] = await engine.executeRaw<{ hit: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM pages p WHERE p.source_id = $1 AND p.generation > $2 AND p.deleted_at IS NULL+ AND p.type NOT IN ('question', 'synthesis') AND NOT (p.frontmatter ? 'pinned_question') ${prefix}) AS hit`, params);+ if (pageHit?.hit) return true;+ if (pin.watermark_fact_id === null) return false;+ const [factHit] = await engine.executeRaw<{ hit: boolean }>(+ `SELECT EXISTS (SELECT 1 FROM facts f WHERE f.source_id = $1 AND f.id > $2 AND f.expired_at IS NULL+ ${pin.scope_entity ? 'AND f.entity_slug = $3' : ''}) AS hit`,+ pin.scope_entity ? [pin.source_id, pin.watermark_fact_id, pin.scope_entity] : [pin.source_id, pin.watermark_fact_id]);+ return factHit?.hit === true;+}diff --git a/src/core/questions/identity.ts b/src/core/questions/identity.tsnew file mode 100644index 0000000000..f216271f7d--- /dev/null+++ b/src/core/questions/identity.ts@@ -0,0 +1,56 @@+/**+ * Pinned-question identity: source-qualified ids (`<source_id>:<slug>`) and+ * deterministic slugs, so pinning the same question with the same scope twice+ * lands on the same row. Pure; no engine or runtime imports (the v205+ * migration handler imports it).+ */+import { createHash } from 'node:crypto';++export const QUESTION_SLUG_PREFIX = 'questions/';+export const QUESTION_PAGE_TYPE = 'question';+/** Frontmatter key that marks a page as a pinned question's page; forces it private for remote readers. */+export const PINNED_QUESTION_MARKER = 'pinned_question';+export const MAX_QUESTION_CHARS = 500;++export interface QuestionScope {+ source: string;+ slug_prefix?: string;+ entity?: string;+}++export function normalizeQuestion(question: string): string {+ return question.replace(/\s+/g, ' ').trim();+}++export function questionSlug(question: string, scope: QuestionScope): string {+ const norm = normalizeQuestion(question);+ const kebab = norm.toLowerCase().replace(/[^a-z0-9\s-]+/g, '').trim().replace(/[\s-]+/g, '-').slice(0, 60).replace(/-+$/, '') || 'question';+ const digest = createHash('sha256')+ .update([norm.toLowerCase(), scope.slug_prefix ?? '', scope.entity ?? ''].join('\n'))+ .digest('hex').slice(0, 8);+ return `${QUESTION_SLUG_PREFIX}${kebab}-${digest}`;+}++export function formatQuestionId(sourceId: string, slug: string): string {+ return `${sourceId}:${slug}`;+}++/** Parses `<source_id>:<slug>`; a bare slug resolves in `defaultSource`. Null when malformed. */+export function parseQuestionId(id: string, defaultSource: string): { sourceId: string; slug: string } | null {+ const raw = id.trim();+ const colon = raw.indexOf(':');+ const sourceId = colon > 0 ? raw.slice(0, colon) : defaultSource;+ const slug = colon > 0 ? raw.slice(colon + 1) : raw;+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(sourceId)) return null;+ if (!slug.startsWith(QUESTION_SLUG_PREFIX) || !/^questions\/[a-z0-9][a-z0-9-]{0,80}$/.test(slug)) return null;+ return { sourceId, slug };+}++export function sha256Hex(text: string): string {+ return createHash('sha256').update(text).digest('hex');+}++/** Stable sentence id from its text: keeps citations attached across rewrites that leave a sentence unchanged. */+export function sentenceId(text: string): string {+ return `s_${sha256Hex(normalizeQuestion(text).toLowerCase()).slice(0, 12)}`;+}diff --git a/src/core/questions/pages.ts b/src/core/questions/pages.tsnew file mode 100644index 0000000000..a4d99325c6--- /dev/null+++ b/src/core/questions/pages.ts@@ -0,0 +1,106 @@+/**+ * The question page (`questions/<slug>`): the question, its scope and the+ * owner's own notes. It never holds the generated answer (that lives in+ * pinned_questions, read through freshness.ts), so its chunks, versions, the+ * exported file and git history carry no derived text. Frontmatter+ * `visibility: private` plus the `pinned_question` marker keep it out of+ * every remote read, whatever the owner later edits.+ *+ * Only trusted local callers materialize or archive the page, through the+ * persistence coordinator; a remote pin waits for the owner's next local+ * `gbrain questions` call or cycle.+ */+import type { BrainEngine } from '../engine.ts';+import type { OperationContext } from '../ops/contract.ts';+import type { Page } from '../types.ts';+import { serializePageToMarkdown } from '../markdown.ts';+import { submitPageMutation } from '../persistence/page-mutations.ts';+import { PINNED_QUESTION_MARKER, QUESTION_PAGE_TYPE, normalizeQuestion } from './identity.ts';+import { pinId, pinScope, type PinRow } from './store.ts';++const OWNER_NOTE_MARKER = '<!-- gbrain:pinned-question v1 -->';+export const MAX_OWNER_SENTENCES = 20;+const MAX_OWNER_SENTENCE_CHARS = 500;++export interface QuestionPageState {+ page_id: number;+ generation: number;+ revision: string;+ compiled_truth: string;+ archived: boolean;+}++export async function readQuestionPage(engine: BrainEngine, pin: Pick<PinRow, 'source_id' | 'slug'>): Promise<QuestionPageState | null> {+ const [row] = await engine.executeRaw<{ id: number; generation: string | number; revision: string | null; compiled_truth: string; archived: boolean }>(+ `SELECT id, generation, knowledge_revision::text AS revision, compiled_truth,+ COALESCE(frontmatter->>'status', '') = 'archived' AS archived+ FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL`, [pin.source_id, pin.slug]);+ return row ? { page_id: row.id, generation: Number(row.generation), revision: row.revision ?? '', compiled_truth: row.compiled_truth ?? '', archived: row.archived } : null;+}++/** The owner's claims: every sentence of the page body except the heading and gbrain's comments. */+export function ownerClaims(compiledTruth: string): string[] {+ const body = compiledTruth+ .replace(/<!--[\s\S]*?-->/g, ' ')+ .split('\n')+ .filter(line => !/^\s*#\s/.test(line))+ .join('\n');+ return body+ .split(/(?<=[.!?])\s+|\n+/)+ .map(s => normalizeQuestion(s.replace(/^[-*]\s+/, '')))+ .filter(s => s.length > 0)+ .slice(0, MAX_OWNER_SENTENCES)+ .map(s => s.slice(0, MAX_OWNER_SENTENCE_CHARS));+}++function renderPage(pin: PinRow, status: 'pinned' | 'archived', ownerBody: string | null): string {+ const id = pinId(pin);+ const scope = pinScope(pin);+ const page = {+ title: pin.question.slice(0, 200),+ type: QUESTION_PAGE_TYPE,+ compiled_truth: ownerBody ?? [+ `# ${pin.question}`,+ '',+ OWNER_NOTE_MARKER,+ `<!-- Write your own claims about this question below; each sentence is kept in the answer as your claim and goes stale when you edit it until the next refresh. The generated answer is not stored in this file: gbrain questions status ${id} -->`,+ '',+ ].join('\n'),+ timeline: '',+ frontmatter: {+ visibility: 'private',+ [PINNED_QUESTION_MARKER]: id,+ question: pin.question,+ status,+ ...(scope.slug_prefix ? { scope_slug_prefix: scope.slug_prefix } : {}),+ ...(scope.entity ? { scope_entity: scope.entity } : {}),+ },+ } as unknown as Page;+ return serializePageToMarkdown(page, []);+}++function localCtx(ctx: Pick<OperationContext, 'engine' | 'config'>, sourceId: string): OperationContext {+ return { engine: ctx.engine, config: ctx.config, remote: false, sourceId, dryRun: false, logger: { info() {}, warn() {}, error() {} } };+}++/** Brings the page in line with the pin: created when missing, archived or restored with the pin. Trusted local callers only. */+export async function syncQuestionPage(ctx: Pick<OperationContext, 'engine' | 'config' | 'remote'>, pin: PinRow): Promise<'created' | 'archived' | 'restored' | 'unchanged' | 'skipped'> {+ if (ctx.remote !== false) return 'skipped';+ const existing = await readQuestionPage(ctx.engine, pin);+ const wantArchived = pin.state === 'archived';+ if (!existing) {+ if (wantArchived) return 'unchanged';+ await submitPageMutation(localCtx(ctx, pin.source_id), { operation: 'put_page', params: {+ slug: pin.slug, source_id: pin.source_id, content: renderPage(pin, 'pinned', null),+ } });+ return 'created';+ }+ if (existing.archived === wantArchived) return 'unchanged';+ const snapshot = await ctx.engine.readPageSnapshot(pin.slug, { sourceId: pin.source_id });+ if (!snapshot) return 'unchanged';+ await submitPageMutation(localCtx(ctx, pin.source_id), { operation: 'put_page', params: {+ slug: pin.slug, source_id: pin.source_id, expected_revision: snapshot.revision,+ content: renderPage(pin, wantArchived ? 'archived' : 'pinned', snapshot.page.compiled_truth ?? existing.compiled_truth),+ } });+ return wantArchived ? 'archived' : 'restored';+}diff --git a/src/core/questions/phase.ts b/src/core/questions/phase.tsnew file mode 100644index 0000000000..7b3795d21b--- /dev/null+++ b/src/core/questions/phase.ts@@ -0,0 +1,99 @@+/**+ * Cycle phase `standing_questions`: refreshes active pinned questions under one+ * BudgetMeter (`cycle.standing_questions.budget_usd`, default $1.00 per run)+ * and `cycle.standing_questions.max_per_cycle` (default 5). Order: never+ * 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+ * (inactive: never refreshed; draft: refreshed, not served by context_pack).+ *+ * The phase also brings question pages in line with their pins (materializes+ * pages for pins made over MCP or imported from dream.auto_think, archives+ * unpinned ones) and stamps `cycle.standing_questions.last_run_at`, which is+ * how receipts know a scheduler exists. Kill switch:+ * `cycle.standing_questions.enabled=false`.+ */+import type { BrainEngine } from '../engine.ts';+import type { PhaseResult } from '../cycle.ts';+import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd } from '../cycle/budget-meter.ts';+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 { listPins, pinId, type PinRow } from './store.ts';+import { DEFAULT_BUDGET_USD } from './service.ts';++export interface StandingQuestionsPhaseOpts {+ dryRun: boolean;+ signal?: AbortSignal;+ /** Test seams. */+ chat?: QuestionChatFn;+ hooks?: RefreshHooks;+}++async function numberConfig(engine: BrainEngine, key: string, fallback: number): Promise<number> {+ const raw = await engine.getConfig(key).catch(() => null);+ const n = raw === null || raw === undefined || raw === '' ? NaN : Number(raw);+ return Number.isFinite(n) ? n : fallback;+}++export async function runPhaseStandingQuestions(engine: BrainEngine, opts: StandingQuestionsPhaseOpts): Promise<PhaseResult> {+ const enabled = await engine.getConfig('cycle.standing_questions.enabled').catch(() => null);+ if (enabled === 'false') {+ return { phase: 'standing_questions', status: 'skipped', duration_ms: 0, summary: 'cycle.standing_questions.enabled is false', details: { reason: 'disabled' } };+ }+ const maxPerCycle = Math.max(1, Math.floor(await numberConfig(engine, 'cycle.standing_questions.max_per_cycle', 5)));+ const defaultCooldownDays = Math.max(0, await numberConfig(engine, 'cycle.standing_questions.cooldown_days', 1));+ const budgetUsd = parseBudgetUsd(await engine.getConfig('cycle.standing_questions.budget_usd'), DEFAULT_BUDGET_USD);+ const meter = new BudgetMeter({+ budgetUsd, phase: 'standing_questions', pricingOverrides: await loadPricingOverrides(engine),+ allowUnpriced: (await engine.getConfig('cycle.standing_questions.allow_unpriced')) === 'true' || await loadAllowUnpriced(engine),+ });+ const ctx = { engine, config: { engine: engine.kind } as never, remote: false as const };+ const pins = await listPins(engine, { includeArchived: true });+ let pagesSynced = 0;+ for (const pin of pins) {+ if (opts.dryRun) break;+ try { if ((await syncQuestionPage(ctx, pin)) !== 'unchanged') pagesSynced++; }+ catch (e) { process.stderr.write(`[questions] page sync for ${pinId(pin)} failed: ${(e as Error).message}\n`); }+ }+ const now = Date.now();+ const candidates: Array<{ pin: PinRow; rank: number }> = [];+ for (const pin of pins.filter(p => p.state === 'active')) {+ 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;+ if (pin.answer_revision === 0) { candidates.push({ pin, rank: 0 }); continue; }+ const evaluation = await evaluateAnswer(engine, pin, { readableSources: null });+ if (evaluation.stale > 0) { candidates.push({ pin, rank: 1 }); continue; }+ 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 }> = [];+ for (const { pin } of candidates.slice(0, maxPerCycle)) {+ opts.signal?.throwIfAborted();+ if (opts.dryRun) { outcomes.push({ id: pinId(pin), status: 'dry_run' }); continue; }+ const outcome = await refreshPin(engine, pin.source_id, pin.slug, {+ trigger: 'cycle', meter, leaseOwner: 'cycle', ...(opts.signal ? { signal: opts.signal } : {}),+ ...(opts.chat ? { chat: opts.chat } : {}), ...(opts.hooks ? { hooks: opts.hooks } : {}),+ });+ outcomes.push({ id: pinId(pin), status: outcome.status === 'blocked' ? `blocked:${outcome.blocked_reason}` : outcome.status });+ if (outcome.status === 'published') tally.refreshed++;+ else if (outcome.status === 'blocked') {+ tally.blocked++;+ if (outcome.blocked_reason === 'budget_exhausted' || outcome.blocked_reason === 'no_model_key') break;+ } else if (outcome.status === 'failed') tally.failed++;+ else if (outcome.status === 'conflict') tally.conflicts++;+ else if (outcome.status === 'in_progress') tally.in_progress++;+ }+ if (!opts.dryRun) await engine.setConfig(LAST_PHASE_RUN_KEY, new Date().toISOString());+ const status = tally.failed > 0 || tally.blocked > 0 ? 'warn' : candidates.length === 0 && pagesSynced === 0 ? 'skipped' : 'ok';+ return {+ 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 },+ };+}diff --git a/src/core/questions/receipt.ts b/src/core/questions/receipt.tsnew file mode 100644index 0000000000..93de479c21--- /dev/null+++ b/src/core/questions/receipt.ts@@ -0,0 +1,152 @@+/**+ * Pinned-question receipts: the agent operator envelope for every pin, list,+ * status and refresh. Each carries the freshness state, the evidence+ * watermark, the last successful refresh, the blocked reason with its next+ * action (an `Action`, rendered by the transport) and a read-only verify+ * step. Answer text appears only for owner-capable readers (access.ts).+ */+import { existsSync } from 'node:fs';+import type { BrainEngine } from '../engine.ts';+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 { pinId, pinScope, type PinRow } from './store.ts';+import type { QuestionScope } from './identity.ts';++export type Freshness = 'fresh' | 'stale' | 'awaiting_refresh' | 'refreshing' | 'archived';++export const LAST_PHASE_RUN_KEY = 'cycle.standing_questions.last_run_at';+const WORKER_WINDOW_MS = 2 * 86_400_000;++export interface QuestionReceipt {+ id: string;+ source_id: string;+ slug: string;+ question: string;+ scope: QuestionScope;+ state: PinRow['state'];+ inactive_reason: PinRow['inactive_reason'];+ publish_mode: PinRow['publish_mode'];+ origin: string;+ page_materialized: boolean;+ freshness: Freshness;+ answer_revision: number;+ sentences: { total: number; fresh: number; stale: number; withheld: number };+ answer?: Array<Pick<EvaluatedSentence, 'id' | 'text' | 'origin' | 'stale' | 'reasons'>>;+ evidence_watermark: { page_generation: number; fact_id: number | null; at: string } | null;+ new_evidence_since_watermark: boolean;+ last_refresh_at: string | null;+ last_attempt_at: string | null;+ last_error: string | null;+ blocked_reason: BlockedReason | null;+ next_action: Action | null;+ verify: { argv: string[]; mcp: McpCall };+ spend_usd: number;+ refresh_attempts: number;+ refresh?: RefreshOutcome;+}++/** Is anything going to run the standing_questions phase on its own: a recent phase run, or installed, unpaused autopilot. */+export async function scheduledRefreshAvailable(engine: BrainEngine): Promise<boolean> {+ const last = await engine.getConfig(LAST_PHASE_RUN_KEY).catch(() => null);+ const at = last ? Date.parse(last) : NaN;+ if (Number.isFinite(at) && Date.now() - at < WORKER_WINDOW_MS) return true;+ try { return existsSync(autopilotInstallIdPath()) && !autopilotPaused(); } catch { return false; }+}++export function statusArgv(id: string): string[] { return ['gbrain', 'questions', 'status', id, '--json']; }++function verifyStep(id: string): { argv: string[]; mcp: McpCall } {+ return { argv: statusArgv(id), mcp: { tool: 'questions_status', arguments: { id } } };+}++function refreshAction(id: string, why: string, full = false): Action {+ return {+ argv: ['gbrain', 'questions', 'refresh', id, ...(full ? ['--full'] : [])],+ mcp: { tool: 'questions_refresh', arguments: { id, ...(full ? { full: true } : {}) } },+ consent: [], actor: 'agent', why, verify: verifyStep(id), requires_exclusive: false,+ };+}++function lastAttemptFailed(pin: PinRow, prefix: string): boolean {+ if (!pin.last_error?.startsWith(prefix) || !pin.last_attempt_at) return false;+ return !pin.last_refresh_at || pin.last_attempt_at.getTime() >= pin.last_refresh_at.getTime();+}++export function nextActionFor(pin: PinRow, blocked: BlockedReason | null, freshness: Freshness, remote: boolean): Action | null {+ const id = pinId(pin);+ switch (blocked) {+ case 'awaiting_consent':+ return {+ argv: ['gbrain', 'questions', 'pin', '--id', id], consent: ['paid'], actor: remote ? 'user' : 'agent',+ why: pin.inactive_reason === 'migrated_disabled' || pin.inactive_reason === 'migrated_zero_budget'+ ? 'This pin was imported from dream.auto_think, which was off (or had a zero budget), so it stays inactive until the owner turns it on. Activating it allows paid model refreshes under cycle.standing_questions.budget_usd.'+ : 'A pin created over MCP stays inactive until the owner activates paid refresh on the brain host (or has set consent.preapprove.paid.max_usd_per_run). Activating it allows paid model refreshes under cycle.standing_questions.budget_usd.',+ user_message: `The pinned question "${pin.question.slice(0, 120)}" needs a paid model call to answer and to keep its answer current. Activate it with: gbrain questions pin --id ${id}`,+ verify: verifyStep(id), requires_exclusive: false,+ };+ case 'no_model_key':+ return { ...chatKeyFix(), verify: verifyStep(id) };+ case 'budget_exhausted':+ return {+ argv: ['gbrain', 'config', 'set', 'cycle.standing_questions.budget_usd', '<usd>'], consent: ['paid'], actor: 'user',+ inputs: [{ name: 'usd', how: 'Ask the user for the per-run cap in USD they want for pinned-question refreshes.' }],+ why: 'The pinned-question refresh budget for this run is spent, so the refresh was not attempted. The answer keeps its stale flags until the next run with budget; raising the cap is the owner\'s call.',+ 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 'refresh_failed':+ 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.');+ default:+ if (freshness === 'stale' || freshness === 'awaiting_refresh') {+ return refreshAction(id, 'The answer needs a refresh; the next standing_questions cycle phase does it, or refresh it now.');+ }+ return null;+ }+}++export async function buildReceipt(engine: BrainEngine, pin: PinRow, view: {+ readableSources: string[] | null; includeAnswer: boolean; remote: boolean; refresh?: RefreshOutcome;+}): Promise<QuestionReceipt> {+ const evaluation = await evaluateAnswer(engine, pin, { readableSources: view.readableSources });+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2 AND deleted_at IS NULL', [pin.source_id, pin.slug]);+ const leaseLive = pin.lease_token !== null && pin.lease_expires_at !== null && pin.lease_expires_at.getTime() > Date.now();+ const freshness: Freshness = pin.state === 'archived' ? 'archived'+ : leaseLive ? 'refreshing'+ : pin.answer_revision === 0 ? 'awaiting_refresh'+ : evaluation.stale > 0 || evaluation.hidden > 0 ? 'stale' : 'fresh';+ const newEvidence = pin.state === 'active' ? await newEvidenceSinceWatermark(engine, pin) : false;+ let blocked: BlockedReason | null = null;+ if (pin.state === 'inactive') blocked = 'awaiting_consent';+ else if (pin.state === 'active' && freshness !== 'refreshing') {+ 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, 'refresh_failed')) blocked = 'refresh_failed';+ else if ((needsRefresh || newEvidence) && !(await scheduledRefreshAvailable(engine))) blocked = 'no_worker';+ }+ const id = pinId(pin);+ return {+ id, source_id: pin.source_id, slug: pin.slug, question: pin.question, scope: pinScope(pin), state: pin.state,+ inactive_reason: pin.inactive_reason, publish_mode: pin.publish_mode, origin: pin.origin, page_materialized: !!page,+ freshness, answer_revision: pin.answer_revision,+ sentences: { total: pin.answer.length, fresh: evaluation.fresh, stale: evaluation.stale, withheld: evaluation.hidden },+ ...(view.includeAnswer ? { answer: evaluation.sentences.filter(s => !s.hidden).map(s => ({ id: s.id, text: s.text, origin: s.origin, stale: s.stale, reasons: s.reasons })) } : {}),+ evidence_watermark: pin.watermark_generation === null ? null+ : { page_generation: pin.watermark_generation, fact_id: pin.watermark_fact_id, at: pin.watermark_at?.toISOString() ?? '' },+ new_evidence_since_watermark: newEvidence,+ last_refresh_at: pin.last_refresh_at?.toISOString() ?? null,+ last_attempt_at: pin.last_attempt_at?.toISOString() ?? null,+ last_error: pin.last_error,+ blocked_reason: blocked,+ next_action: nextActionFor(pin, blocked, freshness, view.remote),+ verify: verifyStep(id),+ spend_usd: Number(pin.spend_usd.toFixed(6)),+ refresh_attempts: pin.refresh_attempts,+ ...(view.refresh ? { refresh: view.refresh } : {}),+ };+}diff --git a/src/core/questions/refresh.ts b/src/core/questions/refresh.tsnew file mode 100644index 0000000000..9727378623--- /dev/null+++ b/src/core/questions/refresh.ts@@ -0,0 +1,385 @@+/**+ * Refreshing a pinned answer.+ *+ * 1. Pre-checks with no spend: inactive pins report `awaiting_consent`, a+ * missing chat key `no_model_key`, a refused budget check `budget_exhausted`.+ * 2. A durable lease on the pin row (a duplicate worker gets `in_progress`; a+ * crashed worker's expired lease is taken over).+ * 3. Capture: the pin revision, the question page (owner claims), and the+ * evidence watermark (global page-generation clock, newest fact id).+ * 4. Re-retrieve over current evidence in scope. Question and synthesis pages,+ * and pages that repeat a stored answer sentence, are never evidence.+ * 5. One model call. With a previous answer and nothing removed or+ * contradicted it edits that answer; after deletions, withdrawals,+ * conflicting corrections, non-monotonic questions or `full` it recomputes.+ * 6. Publish in one transaction that first revalidates (memory-prepare.ts+ * pattern: observe, prepare, then repeat the checks under row locks): the+ * 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.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import type { BudgetMeter } from '../cycle/budget-meter.ts';+import { resolveModel } from '../model-config.ts';+import { normalizeModelId } from '../model-id.ts';+import { canonicalLookup } from '../model-pricing.ts';+import { chat as gatewayChat, probeChatModel } from '../ai/gateway.ts';+import { classifyLlmCallFailure } from '../think/index.ts';+import { PINNED_QUESTION_MARKER, normalizeQuestion, sentenceId } from './identity.ts';+import { FACT_HASH_SQL, TAKE_HASH_SQL, TIMELINE_HASH_SQL, evaluateAnswer, type EvidenceKind } from './freshness.ts';+import { ownerClaims, readQuestionPage } from './pages.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 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 }+export type QuestionChatFn = (req: QuestionChatRequest) => Promise<QuestionChatResponse>;++/** Test-only crash and race injection points around publication. */+export interface RefreshHooks {+ afterRetrieve?: () => Promise<void> | void;+ beforeCommit?: () => Promise<void> | void;+ betweenPublicationStages?: () => Promise<void> | void;+}++export interface RefreshOpts {+ trigger: 'pin' | 'manual' | 'cycle';+ full?: boolean;+ chat?: QuestionChatFn;+ meter?: BudgetMeter;+ signal?: AbortSignal;+ leaseOwner: string;+ leaseTtlMs?: number;+ hooks?: RefreshHooks;+}++export type RefreshOutcome =+ | { status: 'published'; mode: 'full' | 'incremental'; cost_usd: number; sentences: number; dropped_uncited: number; gaps: string[] }+ | { status: 'blocked'; blocked_reason: BlockedReason; detail: string }+ | { status: 'in_progress' }+ | { status: 'conflict'; detail: string; cost_usd: number }+ | { status: 'failed'; error: string; cost_usd: number }+ | { status: 'timeout'; cost_usd: number }+ | { status: 'skipped'; reason: 'archived' };++export const EST_INPUT_TOKENS = 8_000;+export const MAX_OUTPUT_TOKENS = 2_000;+const MAX_PAGES = 12;+const MAX_FACTS = 30;+const MAX_TIMELINE = 20;+const MAX_TAKES = 20;+const PAGE_EXCERPT_CHARS = 1_500;+const MAX_SENTENCES = 12;+const NON_MONOTONIC = /\b(latest|current(ly)?|now|today|most recent|newest|recent(ly)?|cheapest|best|worst|top|highest|lowest|largest|smallest|only|still|last)\b/i;++export interface EvidenceItem {+ ref: string;+ kind: Exclude<EvidenceKind, 'owner'>;+ source_id: string;+ page_id: number | null;+ page_slug: string | null;+ page_generation: number | null;+ page_revision: string | null;+ item_id: number | null;+ content_hash: string | null;+ text: string;+}++export async function resolveQuestionModel(engine: BrainEngine, pin: Pick<PinRow, 'model'>): Promise<string> {+ return resolveModel(engine, {+ cliFlag: pin.model ?? undefined, configKey: 'models.standing_questions', deprecatedConfigKey: 'models.auto_think',+ tier: 'deep', fallback: 'opus',+ });+}++/** True when a chat call for this pin's model can run (a key is configured). */+export function chatKeyAvailable(model: string): boolean {+ return probeChatModel(normalizeModelId(model)).ok;+}++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 };+};++function costUsd(model: string, usage: QuestionChatResponse['usage']): number {+ const p = canonicalLookup(normalizeModelId(model)) ?? canonicalLookup(model);+ if (!p || !usage) return 0;+ return (usage.input_tokens / 1_000_000) * p.input + (usage.output_tokens / 1_000_000) * p.output;+}++async function recordBlocked(engine: BrainEngine, id: number, code: string): Promise<void> {+ await engine.executeRaw(+ `UPDATE pinned_questions SET last_attempt_at = now(), last_error = $2, updated_at = now()+ WHERE id = $1 AND (lease_token IS NULL OR lease_expires_at < now())`, [id, code]);+}++function normalizedSentenceSet(pins: Array<{ answer: string | null }>): Set<string> {+ const out = new Set<string>();+ for (const p of pins) {+ if (!p.answer) continue;+ try {+ for (const s of JSON.parse(p.answer) as Array<{ text?: unknown }>) {+ const t = typeof s.text === 'string' ? normalizeQuestion(s.text).toLowerCase() : '';+ if (t.length >= 24) out.add(t);+ }+ } catch { /* unreadable stored answer contributes nothing */ }+ }+ return out;+}++interface CandidatePage { id: number; slug: string; source_id: string; generation: string | number; revision: string | null; type: string; compiled_truth: string; marker: boolean }++/** Pages first (hybrid retrieval, keyword fallback), then facts, timeline and takes anchored to them. */+export async function retrieveEvidence(engine: BrainEngine, pin: PinRow): Promise<EvidenceItem[]> {+ const slugs = new Set<string>();+ try {+ const { hybridSearch } = await import('../search/hybrid.ts');+ for (const r of await hybridSearch(engine, pin.question, { sourceId: pin.source_id, limit: MAX_PAGES * 2, exclude_slug_prefixes: ['questions/'] })) slugs.add(r.slug);+ } catch {+ for (const r of await engine.searchKeyword(pin.question, { sourceId: pin.source_id, limit: MAX_PAGES * 2 }).catch(() => [])) slugs.add(r.slug);+ }+ if (pin.scope_entity) slugs.add(pin.scope_entity);+ const candidates = slugs.size === 0 ? [] : await engine.executeRaw<CandidatePage>(+ `SELECT id, slug, source_id, generation, knowledge_revision::text AS revision, type, compiled_truth,+ (frontmatter ? '${PINNED_QUESTION_MARKER}') AS marker+ FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [pin.source_id, [...slugs]]);+ const laundered = normalizedSentenceSet(await engine.executeRaw<{ answer: string | null }>(+ `SELECT answer FROM pinned_questions WHERE source_id = $1 AND answer IS NOT NULL`, [pin.source_id]));+ const order = [...slugs];+ const pages = candidates+ .filter(p => p.type !== 'question' && p.type !== 'synthesis' && !p.marker)+ .filter(p => !pin.scope_slug_prefix || p.slug.startsWith(pin.scope_slug_prefix) || p.slug === pin.scope_entity)+ .filter(p => {+ const body = normalizeQuestion(p.compiled_truth ?? '').toLowerCase();+ for (const s of laundered) if (body.includes(s)) return false;+ return true;+ })+ .sort((a, b) => order.indexOf(a.slug) - order.indexOf(b.slug))+ .slice(0, MAX_PAGES);+ const items: EvidenceItem[] = [];+ const push = (item: Omit<EvidenceItem, 'ref'>) => items.push({ ...item, ref: `E${items.length + 1}` });+ for (const p of pages) {+ push({ kind: 'page', source_id: p.source_id, page_id: p.id, page_slug: p.slug, page_generation: Number(p.generation),+ page_revision: p.revision, item_id: null, content_hash: null, text: `[page ${p.slug}] ${(p.compiled_truth ?? '').slice(0, PAGE_EXCERPT_CHARS)}` });+ }+ const pageIds = pages.map(p => p.id);+ const entitySlugs = [...new Set([...pages.map(p => p.slug), ...(pin.scope_entity ? [pin.scope_entity] : [])])];+ if (entitySlugs.length > 0) {+ const facts = await engine.executeRaw<{ id: string | number; fact: string; entity_slug: string | null; valid_from: unknown; hash: string }>(+ `SELECT f.id, f.fact, f.entity_slug, f.valid_from, ${FACT_HASH_SQL('f')} AS hash FROM facts f+ WHERE f.source_id = $1 AND f.entity_slug = ANY($2::text[]) AND f.expired_at IS NULL AND f.superseded_by IS NULL+ AND (f.valid_until IS NULL OR f.valid_until > now())+ AND NOT EXISTS (SELECT 1 FROM pages fp WHERE fp.source_id = f.source_id AND fp.slug = f.source_markdown_slug+ AND (fp.type IN ('question', 'synthesis') OR fp.frontmatter ? '${PINNED_QUESTION_MARKER}'))+ ORDER BY f.valid_from DESC, f.id DESC LIMIT ${MAX_FACTS}`, [pin.source_id, entitySlugs]);+ for (const f of facts) {+ push({ kind: 'fact', source_id: pin.source_id, page_id: null, page_slug: f.entity_slug, page_generation: null, page_revision: null,+ item_id: Number(f.id), content_hash: f.hash, text: `[fact about ${f.entity_slug ?? 'unknown'}, from ${String(f.valid_from).slice(0, 10)}] ${f.fact}` });+ }+ }+ if (pageIds.length > 0) {+ const timeline = await engine.executeRaw<{ id: number; date: unknown; summary: string; detail: string; page_id: number; slug: string; generation: string | number; revision: string | null; hash: string }>(+ `SELECT t.id, t.date, t.summary, t.detail, p.id AS page_id, p.slug, p.generation, p.knowledge_revision::text AS revision, ${TIMELINE_HASH_SQL('t')} AS hash+ FROM timeline_entries t JOIN pages p ON p.id = t.page_id WHERE p.id = ANY($1::integer[]) ORDER BY t.date DESC, t.id DESC LIMIT ${MAX_TIMELINE}`, [pageIds]);+ for (const t of timeline) {+ push({ kind: 'timeline', source_id: pin.source_id, page_id: t.page_id, page_slug: t.slug, page_generation: Number(t.generation),+ page_revision: t.revision, item_id: t.id, content_hash: t.hash, text: `[timeline ${t.slug} ${String(t.date).slice(0, 10)}] ${t.summary}${t.detail ? ` — ${t.detail.slice(0, 300)}` : ''}` });+ }+ const takes = await engine.executeRaw<{ id: string | number; claim: string; holder: string; weight: number | null; page_id: number; slug: string; generation: string | number; revision: string | null; hash: string }>(+ `SELECT k.id, k.claim, k.holder, k.weight, p.id AS page_id, p.slug, p.generation, p.knowledge_revision::text AS revision, ${TAKE_HASH_SQL('k')} AS hash+ FROM takes k JOIN pages p ON p.id = k.page_id WHERE p.id = ANY($1::integer[]) AND k.active AND k.superseded_by IS NULL+ ORDER BY k.id DESC LIMIT ${MAX_TAKES}`, [pageIds]);+ for (const k of takes) {+ push({ kind: 'take', source_id: pin.source_id, page_id: k.page_id, page_slug: k.slug, page_generation: Number(k.generation),+ page_revision: k.revision, item_id: Number(k.id), content_hash: k.hash, text: `[take on ${k.slug}, held by ${k.holder}${k.weight !== null ? `, weight ${k.weight}` : ''}] ${k.claim}` });+ }+ }+ return items;+}++const SYSTEM_PROMPT = [+ 'You maintain a standing answer to one question from a personal knowledge base.',+ 'Use only the numbered evidence. Every sentence must cite at least one evidence id; a sentence you cannot cite is not allowed.',+ 'Owner claims are the owner\'s own statements: they are shown for context, are kept verbatim by the system, and must not be repeated or contradicted.',+ 'Return only JSON: {"sentences":[{"text":"...","cite":["E1"]}],"gaps":["what the evidence does not answer"]}.',+ 'If the evidence does not answer the question, return no sentences and name the gap.',+].join('\n');++export function buildPrompt(pin: PinRow, items: EvidenceItem[], owner: string[], previous: AnswerSentence[] | null): string {+ const lines = [`Question: ${pin.question}`];+ if (pin.scope_slug_prefix || pin.scope_entity) {+ lines.push(`Scope: ${[pin.scope_slug_prefix ? `pages under ${pin.scope_slug_prefix}` : '', pin.scope_entity ? `about ${pin.scope_entity}` : ''].filter(Boolean).join(', ')}`);+ }+ if (owner.length) lines.push('', 'Owner claims:', ...owner.map(s => `- ${s}`));+ if (previous && previous.length) {+ lines.push('', 'Previous answer (edit it: keep sentences the evidence still supports, revise or drop the rest, add sentences for new evidence):',+ ...previous.map(s => `- ${s.text}`));+ }+ lines.push('', 'Evidence:', ...(items.length ? items.map(i => `${i.ref}: ${i.text.replace(/\s+/g, ' ')}`) : ['(none)']));+ return lines.join('\n');+}++export function parseModelAnswer(text: string, items: EvidenceItem[]): { sentences: Array<{ text: string; cites: EvidenceItem[] }>; dropped: number; gaps: string[] } {+ const start = text.indexOf('{');+ const end = text.lastIndexOf('}');+ if (start < 0 || end <= start) throw new Error('model_output_not_json');+ let parsed: { sentences?: unknown; gaps?: unknown };+ try { parsed = JSON.parse(text.slice(start, end + 1)); } catch { throw new Error('model_output_not_json'); }+ const byRef = new Map(items.map(i => [i.ref, i]));+ const out: Array<{ text: string; cites: EvidenceItem[] }> = [];+ const seen = new Set<string>();+ let dropped = 0;+ for (const raw of Array.isArray(parsed.sentences) ? parsed.sentences : []) {+ const s = raw as { text?: unknown; cite?: unknown };+ const body = typeof s.text === 'string' ? normalizeQuestion(s.text).slice(0, 600) : '';+ const cites = (Array.isArray(s.cite) ? s.cite : []).map(c => byRef.get(String(c).trim())).filter((c): c is EvidenceItem => !!c);+ if (!body || cites.length === 0 || seen.has(sentenceId(body))) { if (body) dropped++; continue; }+ seen.add(sentenceId(body));+ out.push({ text: body, cites: [...new Set(cites)] });+ if (out.length >= MAX_SENTENCES) break;+ }+ const gaps = (Array.isArray(parsed.gaps) ? parsed.gaps : []).filter((g): g is string => typeof g === 'string').map(g => g.slice(0, 300)).slice(0, 5);+ return { sentences: out, dropped, gaps };+}++interface EvidenceRow {+ sentence_id: string; kind: EvidenceKind; source_id: string; page_id: number | null; page_slug: string | null;+ page_generation: number | null; page_revision: string | null; item_id: number | null; content_hash: string | null;+}++/** Repeats every dependency check under row locks; returns the first mismatch, or null when all still hold. */+async function revalidate(tx: BrainEngine, rows: EvidenceRow[]): Promise<string | null> {+ const pageRows = rows.filter(r => r.page_id !== null && r.kind !== 'fact');+ const pageIds = [...new Set(pageRows.map(r => r.page_id!))];+ if (pageIds.length) {+ const current = new Map((await tx.executeRaw<{ id: number; generation: string | number; revision: string | null; deleted: boolean; body: string }>(+ `SELECT id, generation, knowledge_revision::text AS revision, deleted_at IS NOT NULL AS deleted, md5(compiled_truth) AS body+ FROM pages WHERE id = ANY($1::integer[]) FOR SHARE`, [pageIds])).map(r => [r.id, r]));+ for (const r of pageRows) {+ const c = current.get(r.page_id!);+ if (!c || c.deleted) return `page ${r.page_slug ?? r.page_id} was removed`;+ if (r.kind === 'owner') { if (c.body !== r.content_hash) return 'the owner edited the question page'; continue; }+ if (String(c.generation) !== String(r.page_generation) || (c.revision ?? null) !== (r.page_revision ?? null)) return `page ${r.page_slug ?? r.page_id} changed`;+ }+ }+ const check = async (kind: EvidenceKind, sql: string) => {+ const want = rows.filter(r => r.kind === kind);+ if (!want.length) return null;+ const current = new Map((await tx.executeRaw<{ id: string | number; ok: boolean; hash: string }>(sql, [[...new Set(want.map(r => r.item_id!))]]))+ .map(r => [Number(r.id), r]));+ for (const r of want) {+ const c = current.get(Number(r.item_id));+ if (!c || !c.ok || c.hash !== r.content_hash) return `${kind} ${r.item_id} changed`;+ }+ return null;+ };+ return (await check('fact', `SELECT id, (expired_at IS NULL AND superseded_by IS NULL AND (valid_until IS NULL OR valid_until > now())) AS ok,+ ${FACT_HASH_SQL('facts')} AS hash FROM facts WHERE id = ANY($1::bigint[]) FOR SHARE`))+ ?? (await check('timeline', `SELECT id, true AS ok, ${TIMELINE_HASH_SQL('timeline_entries')} AS hash FROM timeline_entries WHERE id = ANY($1::integer[]) FOR SHARE`))+ ?? (await check('take', `SELECT id, (active AND superseded_by IS NULL) AS ok, ${TAKE_HASH_SQL('takes')} AS hash FROM takes WHERE id = ANY($1::bigint[]) FOR SHARE`));+}++export async function refreshPin(engine: BrainEngine, sourceId: string, slug: string, opts: RefreshOpts): Promise<RefreshOutcome> {+ const pin = await getPin(engine, sourceId, slug);+ if (!pin) throw new Error(`pinned question ${sourceId}:${slug} not found`);+ if (pin.state === 'archived') return { status: 'skipped', reason: 'archived' };+ if (pin.state === 'inactive') return { status: 'blocked', blocked_reason: 'awaiting_consent', detail: `pin is inactive (${pin.inactive_reason ?? 'awaiting_consent'})` };+ const model = await resolveQuestionModel(engine, pin);+ if (!opts.chat && !chatKeyAvailable(model)) {+ await recordBlocked(engine, pin.id, 'no_model_key');+ return { status: 'blocked', blocked_reason: 'no_model_key', detail: `no usable chat key for ${model}` };+ }+ if (opts.meter) {+ const check = opts.meter.check({ modelId: model, estimatedInputTokens: EST_INPUT_TOKENS, maxOutputTokens: MAX_OUTPUT_TOKENS, 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' };+ }+ }+ const token = randomUUID();+ const leased = await acquireLease(engine, pin.id, token, opts.leaseOwner, opts.leaseTtlMs ?? 10 * 60_000);+ if (!leased) return { status: 'in_progress' };+ let spend = 0;+ let stage: 'retrieve' | 'model' | 'parse' | 'publish' = 'retrieve';+ try {+ const [clock] = await engine.executeRaw<{ generation: string | number; fact_id: string | number }>(+ `SELECT (SELECT COALESCE(MAX(generation), 0) FROM pages) AS generation,+ (SELECT COALESCE(MAX(id), 0) FROM facts WHERE source_id = $1) AS fact_id`, [pin.source_id]);+ const page = await readQuestionPage(engine, pin);+ const owner = page ? ownerClaims(page.compiled_truth) : [];+ const items = await retrieveEvidence(engine, leased);+ await opts.hooks?.afterRetrieve?.();+ const evaluation = await evaluateAnswer(engine, leased, { readableSources: null });+ const previous = leased.answer.filter(s => s.origin === 'model');+ const full = opts.full === true || previous.length === 0 || evaluation.needsFull || NON_MONOTONIC.test(leased.question);+ opts.signal?.throwIfAborted();+ stage = 'model';+ const response = await (opts.chat ?? gatewayQuestionChat)({+ model, system: SYSTEM_PROMPT, user: buildPrompt(leased, items, owner, full ? null : previous), maxTokens: MAX_OUTPUT_TOKENS, signal: opts.signal,+ });+ spend = costUsd(response.model || model, response.usage);+ stage = 'parse';+ const parsed = parseModelAnswer(response.text, items);+ const ownerSentences: AnswerSentence[] = owner.map(text => ({ id: sentenceId(`owner:${text}`), text, origin: 'owner' }));+ const modelSentences: AnswerSentence[] = parsed.sentences.map(s => ({ id: sentenceId(s.text), text: s.text, origin: 'model' }));+ const evidence: EvidenceRow[] = [+ ...(page ? ownerSentences.map(s => ({ sentence_id: s.id, kind: 'owner' as const, source_id: pin.source_id, page_id: page.page_id,+ page_slug: pin.slug, page_generation: page.generation, page_revision: page.revision, item_id: null,+ content_hash: null })) : []),+ ...parsed.sentences.flatMap(s => s.cites.map(c => ({ sentence_id: sentenceId(s.text), kind: c.kind, source_id: c.source_id, page_id: c.page_id,+ page_slug: c.page_slug, page_generation: c.page_generation, page_revision: c.page_revision, item_id: c.item_id, content_hash: c.content_hash }))),+ ];+ if (page && ownerSentences.length) {+ const [h] = await engine.executeRaw<{ body: string }>('SELECT md5($1::text) AS body', [page.compiled_truth]);+ for (const e of evidence) if (e.kind === 'owner') e.content_hash = h!.body;+ }+ stage = 'publish';+ await opts.hooks?.beforeCommit?.();+ opts.signal?.throwIfAborted();+ const conflict = await engine.transaction(async (tx) => {+ const [row] = await tx.executeRaw<{ revision: string | number; lease_token: string | null; state: string }>(+ 'SELECT revision, lease_token, state FROM pinned_questions WHERE id = $1 FOR UPDATE', [pin.id]);+ if (!row || row.lease_token !== token) return 'the refresh lease was lost';+ if (Number(row.revision) !== leased.revision || row.state !== 'active') return 'the pin changed during refresh';+ const mismatch = await revalidate(tx, evidence);+ if (mismatch) return mismatch;+ await tx.executeRaw(+ `UPDATE pinned_questions SET answer = $2, answer_revision = answer_revision + 1, revision = revision + 1, answer_model = $3,+ last_refresh_at = now(), last_error = NULL, watermark_generation = $4, watermark_fact_id = $5, watermark_at = now(),+ lease_token = NULL, lease_owner = NULL, lease_expires_at = NULL, spend_usd = spend_usd + $6, updated_at = now()+ WHERE id = $1`,+ [pin.id, JSON.stringify([...ownerSentences, ...modelSentences]), response.model || model, Number(clock!.generation), Number(clock!.fact_id), spend]);+ await opts.hooks?.betweenPublicationStages?.();+ await tx.executeRaw('DELETE FROM question_evidence WHERE question_id = $1', [pin.id]);+ const revision = leased.answer_revision + 1;+ for (const e of evidence) {+ await tx.executeRaw(+ `INSERT INTO question_evidence (question_id, answer_revision, sentence_id, kind, source_id, page_id, page_slug, page_generation, page_revision, item_id, content_hash)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11)`,+ [pin.id, revision, e.sentence_id, e.kind, e.source_id, e.page_id, e.page_slug, e.page_generation, e.page_revision, e.item_id, e.content_hash]);+ }+ return null;+ });+ if (conflict) {+ await releaseLease(engine, pin.id, token, { error: 'concurrent_change', spendUsd: spend });+ return { status: 'conflict', detail: conflict, cost_usd: spend };+ }+ return { status: 'published', mode: full ? 'full' : 'incremental', cost_usd: spend, sentences: ownerSentences.length + modelSentences.length,+ dropped_uncited: parsed.dropped, gaps: parsed.gaps };+ } catch (e) {+ if (opts.signal?.aborted) {+ await releaseLease(engine, pin.id, token, { error: leased.last_error, spendUsd: spend });+ 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'+ : `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 });+ return { status: 'failed', error: code, cost_usd: spend };+ }+}diff --git a/src/core/questions/schema.ts b/src/core/questions/schema.tsnew file mode 100644index 0000000000..6b00cd827c--- /dev/null+++ b/src/core/questions/schema.ts@@ -0,0 +1,73 @@+/**+ * Pinned questions storage DDL: one canonical copy used by migration v205 and,+ * through scripts/build-schema.ts FRAGMENTS, by fresh-install DDL.+ *+ * The answer lives here, never in `pages`: question pages hold the question+ * and the owner's notes only, so search, chunks, page history, export and git+ * sync never carry answer text. `question_evidence` stores pointers (kind, id,+ * page generation and knowledge revision, content hash) with no foreign key,+ * so a hard delete or cascade leaves a dangling pointer that reads as stale+ * instead of erasing the dependency.+ */++const rls = (table: string) => `DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE ${table} ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;`;++export const PINNED_QUESTIONS_SCHEMA_SQL = `+CREATE TABLE IF NOT EXISTS pinned_questions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ question TEXT NOT NULL,+ scope_slug_prefix TEXT,+ scope_entity TEXT,+ state TEXT NOT NULL DEFAULT 'active',+ inactive_reason TEXT,+ publish_mode TEXT NOT NULL DEFAULT 'publish',+ model TEXT,+ cooldown_days REAL,+ origin TEXT NOT NULL DEFAULT 'pin',+ created_by TEXT NOT NULL,+ revision BIGINT NOT NULL DEFAULT 1,+ answer_revision INTEGER NOT NULL DEFAULT 0,+ answer TEXT,+ answer_model TEXT,+ last_refresh_at TIMESTAMPTZ,+ last_attempt_at TIMESTAMPTZ,+ last_error TEXT,+ watermark_generation BIGINT,+ watermark_fact_id BIGINT,+ watermark_at TIMESTAMPTZ,+ lease_token TEXT,+ lease_owner TEXT,+ lease_expires_at TIMESTAMPTZ,+ refresh_attempts INTEGER NOT NULL DEFAULT 0,+ spend_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ archived_at TIMESTAMPTZ,+ CONSTRAINT pinned_questions_source_slug_key UNIQUE (source_id, slug)+);+CREATE INDEX IF NOT EXISTS pinned_questions_state_idx ON pinned_questions (state, source_id);+CREATE TABLE IF NOT EXISTS question_evidence (+ id BIGSERIAL PRIMARY KEY,+ question_id BIGINT NOT NULL,+ answer_revision INTEGER NOT NULL,+ sentence_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ source_id TEXT NOT NULL,+ page_id INTEGER,+ page_slug TEXT,+ page_generation BIGINT,+ page_revision TEXT,+ item_id BIGINT,+ content_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS question_evidence_question_idx ON question_evidence (question_id, answer_revision);+${rls('pinned_questions')}+${rls('question_evidence')}+`;diff --git a/src/core/questions/service.ts b/src/core/questions/service.tsnew file mode 100644index 0000000000..970289e707--- /dev/null+++ b/src/core/questions/service.ts@@ -0,0 +1,281 @@+/**+ * Pinned questions behind the questions_* operations and `gbrain questions`.+ *+ * Version 1 is owner-private: every operation requires an owner-capable+ * caller (access below), question pages are private, and answers are read+ * only through these receipts and context_pack's optional pinned field.+ * Consent: a CLI pin is active; a pin created over MCP stays inactive+ * (`awaiting_consent`) until the owner activates it on the brain host or a+ * paid preapproval (consent.preapprove.paid.max_usd_per_run) covers it. A pin+ * never installs a scheduler.+ */+import type { OperationContext } from '../ops/contract.ts';+import { opError } from '../ops/contract.ts';+import { hostOnlyError, invalidParam, readFix } from '../ops/op-fix.ts';+import { assertSourceInCallerScope, assertSourceInCallerWriteScope, enforceClientSlugFence, sourceScopeOpts } from '../ops/context.ts';+import { resolveExcludePrivatePages } from '../search/private-visibility.ts';+import { readConsentPreapprovals } from '../consent-preapproval.ts';+import { ALL_SOURCES } from '../source-id.ts';+import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd } from '../cycle/budget-meter.ts';+import { MAX_QUESTION_CHARS, normalizeQuestion, parseQuestionId, questionSlug, type QuestionScope } from './identity.ts';+import { syncQuestionPage } from './pages.ts';+import { buildReceipt, type QuestionReceipt } from './receipt.ts';+import { refreshPin, type QuestionChatFn, type RefreshHooks, type RefreshOutcome } from './refresh.ts';+import { getPin, insertPin, listPins, pinId, updatePinState, type PinRow } from './store.ts';+import { evaluateAnswer } from './freshness.ts';++export const DEFAULT_BUDGET_USD = 1.0;+export const DEFAULT_PIN_WAIT_MS = 30_000;+export const DEFAULT_REFRESH_WAIT_MS = 120_000;+const MAX_WAIT_MS = 300_000;++/** Test seams: an injected chat function and publication hooks (production callers pass none). */+export interface QuestionsDeps { chat?: QuestionChatFn; hooks?: RefreshHooks }++export interface CallerAccess { readableSources: string[] | null; remote: boolean }++/**+ * Owner-capable callers: the trusted local CLI, or a remote grant that reads+ * private pages (the operator opted remote readers into private pages) and is+ * not slug-fenced or a delegated subagent. Everyone else is refused with the+ * CLI equivalent, so restricted grants never learn a question or answer.+ */+export async function requireOwnerCapable(ctx: OperationContext, op: string, cli: string[]): Promise<CallerAccess> {+ if (ctx.remote === false) {+ const scope = sourceScopeOpts(ctx);+ return { readableSources: scope.sourceIds ?? null, remote: false };+ }+ const excludePrivate = await resolveExcludePrivatePages(ctx.engine, ctx.remote);+ const restricted = ctx.viaSubagent === true || (ctx.auth?.boundSlugPrefixes?.length ?? 0) > 0+ || ctx.auth?.fenceProjectionDegraded === true || ctx.auth?.grantProjectionDegraded === true;+ if (excludePrivate || restricted) {+ throw hostOnlyError(ctx, 'question_owner_only', `${op}: pinned questions are owner-private, and this connection cannot read private pages.`, cli,+ 'Pinned questions and their answers are private to the brain owner in this version. This connection is a restricted grant (it cannot read private pages' ++ `${restricted ? ', or it is slug-fenced or delegated' : ''}), so the owner runs the command on the brain host. An operator who wants this MCP connection to manage pins sets search.remote_private_pages=visible, which also shows it every private page.`);+ }+ const scope = sourceScopeOpts(ctx);+ const readable = scope.sourceIds ?? (scope.sourceId !== undefined ? [scope.sourceId] : null);+ return { readableSources: readable, remote: true };+}++function defaultSource(ctx: OperationContext): string {+ if (ctx.sourceId && ctx.sourceId !== ALL_SOURCES) return ctx.sourceId;+ return ctx.auth?.sourceId && ctx.auth.sourceId !== ALL_SOURCES ? ctx.auth.sourceId : 'default';+}++function waitMs(raw: unknown, fallback: number): number {+ return typeof raw === 'number' && Number.isFinite(raw) && raw >= 0 ? Math.min(Math.floor(raw), MAX_WAIT_MS) : fallback;+}++async function parseScope(ctx: OperationContext, raw: unknown, op: string): Promise<QuestionScope> {+ if (raw !== undefined && (raw === null || typeof raw !== 'object' || Array.isArray(raw))) {+ throw invalidParam(ctx, op, 'scope', `${op}: scope must be an object {source, slug_prefix?, entity?}.`, { example: { source: 'default' } });+ }+ const s = (raw ?? {}) as Record<string, unknown>;+ const source = typeof s.source === 'string' && s.source.trim() ? s.source.trim() : defaultSource(ctx);+ if (!/^[a-z0-9][a-z0-9_-]{0,63}$/i.test(source)) throw invalidParam(ctx, op, 'scope', `${op}: scope.source is not a valid source id.`, { example: { source: 'default' } });+ assertSourceInCallerScope(ctx, source);+ const [live] = await ctx.engine.executeRaw<{ id: string }>('SELECT id FROM sources WHERE id = $1 AND NOT archived', [source]);+ if (!live) {+ throw opError('not_found', `Unknown source: ${source}`, 'Pass a source id from sources_list.',+ { fix: readFix('Lists the sources this connection can read.', { argv: ['gbrain', 'sources', 'list'], mcp: { tool: 'sources_list', arguments: {} } }) });+ }+ let slugPrefix: string | undefined;+ if (s.slug_prefix !== undefined && s.slug_prefix !== null && s.slug_prefix !== '') {+ if (typeof s.slug_prefix !== 'string' || !/^[a-z0-9][a-z0-9/_.-]{0,200}$/i.test(s.slug_prefix) || s.slug_prefix.includes('..')) {+ throw invalidParam(ctx, op, 'scope', `${op}: scope.slug_prefix must be a slug prefix such as "projects/".`, { example: { source, slug_prefix: 'projects/' } });+ }+ slugPrefix = s.slug_prefix.toLowerCase().endsWith('/') ? s.slug_prefix.toLowerCase() : `${s.slug_prefix.toLowerCase()}/`;+ }+ let entity: string | undefined;+ if (s.entity !== undefined && s.entity !== null && s.entity !== '') {+ if (typeof s.entity !== 'string' || !/^[a-z0-9][a-z0-9/_.-]{0,200}$/i.test(s.entity) || s.entity.includes('..')) {+ throw invalidParam(ctx, op, 'scope', `${op}: scope.entity must be an entity page slug such as "companies/acme-example".`, { example: { source, entity: 'companies/acme-example' } });+ }+ entity = s.entity.toLowerCase();+ }+ return { source, ...(slugPrefix ? { slug_prefix: slugPrefix } : {}), ...(entity ? { entity } : {}) };+}++async function resolvePin(ctx: OperationContext, access: CallerAccess, rawId: unknown, op: string): Promise<PinRow> {+ if (typeof rawId !== 'string' || !rawId.trim()) throw invalidParam(ctx, op, 'id', `${op}: id is required.`, { example: 'default:questions/who-leads-acme-example-1a2b3c4d' });+ const parsed = parseQuestionId(rawId, defaultSource(ctx));+ const notFound = () => opError('question_not_found', `${op}: no pinned question ${rawId} in this connection's scope.`,+ 'Pass an id from questions_list (source-qualified, e.g. default:questions/<slug>).',+ { fix: readFix('Lists the pinned questions this connection can read, with their ids.', { argv: ['gbrain', 'questions', 'list', '--json'], mcp: { tool: 'questions_list', arguments: {} } }) });+ if (!parsed) throw notFound();+ if (access.readableSources && !access.readableSources.includes(parsed.sourceId)) throw notFound();+ const pin = await getPin(ctx.engine, parsed.sourceId, parsed.slug);+ if (!pin) throw notFound();+ return pin;+}++async function meterFor(ctx: OperationContext): Promise<BudgetMeter> {+ let budget = parseBudgetUsd(await ctx.engine.getConfig('cycle.standing_questions.budget_usd'), DEFAULT_BUDGET_USD);+ if (ctx.remote !== false) {+ const pre = readConsentPreapprovals().paid?.max_usd_per_run;+ if (pre !== undefined) budget = Math.min(budget, pre);+ }+ const allowUnpriced = (await ctx.engine.getConfig('cycle.standing_questions.allow_unpriced')) === 'true' || await loadAllowUnpriced(ctx.engine);+ return new BudgetMeter({ budgetUsd: budget, allowUnpriced, pricingOverrides: await loadPricingOverrides(ctx.engine), phase: 'standing_questions' });+}++async function boundedRefresh(ctx: OperationContext, pin: PinRow, opts: { full: boolean; waitMs: number; trigger: 'pin' | 'manual' }, deps: QuestionsDeps): Promise<RefreshOutcome> {+ const controller = new AbortController();+ const timer = setTimeout(() => controller.abort(new Error('wait_ms elapsed')), opts.waitMs);+ try {+ return await refreshPin(ctx.engine, pin.source_id, pin.slug, {+ trigger: opts.trigger, full: opts.full, signal: controller.signal, meter: await meterFor(ctx),+ leaseOwner: ctx.remote === false ? 'cli' : `mcp:${ctx.auth?.clientId ?? ctx.transport ?? 'stdio'}`,+ leaseTtlMs: opts.waitMs + 60_000, ...(deps.chat ? { chat: deps.chat } : {}), ...(deps.hooks ? { hooks: deps.hooks } : {}),+ });+ } finally {+ clearTimeout(timer);+ }+}++async function receiptFor(ctx: OperationContext, access: CallerAccess, sourceId: string, slug: string, includeAnswer: boolean, refresh?: RefreshOutcome): Promise<QuestionReceipt> {+ const pin = (await getPin(ctx.engine, sourceId, slug))!;+ const receipt = await buildReceipt(ctx.engine, pin, { readableSources: access.readableSources, includeAnswer, remote: access.remote, refresh });+ if (receipt.blocked_reason || receipt.freshness === 'stale') {+ ctx.emitNotice?.({+ code: 'pinned_answer_stale', kind: 'degraded',+ why: receipt.blocked_reason+ ? `Pinned question ${receipt.id} is ${receipt.freshness} and blocked (${receipt.blocked_reason}); its stale sentences are flagged here and withheld from context_pack.`+ : `Pinned question ${receipt.id} has ${receipt.sentences.stale} stale sentence(s): their evidence changed or was removed. They are flagged here and withheld from context_pack until a refresh.`,+ ...(receipt.next_action ? { fix: receipt.next_action } : {}),+ });+ }+ return receipt;+}++export async function pinQuestion(ctx: OperationContext, p: Record<string, unknown>, deps: QuestionsDeps = {}): Promise<{ created: boolean; activated: boolean; receipt: QuestionReceipt }> {+ const access = await requireOwnerCapable(ctx, 'questions_pin', ['gbrain', 'questions', 'pin', typeof p.question === 'string' ? p.question : '<question>']);+ const local = ctx.remote === false;+ if (p.publish !== undefined && !local) {+ throw hostOnlyError(ctx, 'question_owner_only', 'questions_pin: publish (draft -> published answers) is set by the owner on the brain host.',+ ['gbrain', 'questions', 'pin', '--id', typeof p.id === 'string' ? p.id : '<id>', '--publish'], 'Publishing a draft-only pin changes what context_pack serves, so only the owner decides it.');+ }+ const preapproved = readConsentPreapprovals().paid !== undefined;+ const desired = local || preapproved ? { state: 'active' as const, inactiveReason: null } : { state: 'inactive' as const, inactiveReason: 'awaiting_consent' as const };+ let pin: PinRow;+ let created = false;+ if (p.id !== undefined) {+ pin = await resolvePin(ctx, access, p.id, 'questions_pin');+ if (!local) assertSourceInCallerWriteScope(ctx, pin.source_id);+ } else {+ const question = typeof p.question === 'string' ? normalizeQuestion(p.question) : '';+ if (!question || question.length > MAX_QUESTION_CHARS) {+ throw invalidParam(ctx, 'questions_pin', 'question', `questions_pin: question is required (1-${MAX_QUESTION_CHARS} characters), or pass id to activate an existing pin.`, { example: 'Who leads acme-example now?' });+ }+ const scope = await parseScope(ctx, p.scope, 'questions_pin');+ if (!local) assertSourceInCallerWriteScope(ctx, scope.source);+ const slug = questionSlug(question, scope);+ if (!local) enforceClientSlugFence(ctx, slug, 'questions_pin');+ ({ row: pin, created } = await insertPin(ctx.engine, {+ sourceId: scope.source, slug, question, scope, state: desired.state, inactiveReason: desired.inactiveReason,+ publishMode: 'publish', createdBy: local ? 'cli' : `mcp:${ctx.auth?.clientId ?? ctx.transport ?? 'stdio'}`,+ }));+ }+ let activated = created && pin.state === 'active';+ const reactivate = pin.state === 'archived' || (pin.state === 'inactive' && desired.state === 'active');+ if (!created && (reactivate || (p.publish === true && pin.publish_mode === 'draft'))) {+ const next = reactivate ? desired : { state: pin.state, inactiveReason: pin.inactive_reason };+ pin = await updatePinState(ctx.engine, pin.id, { state: next.state, inactiveReason: next.inactiveReason, ...(p.publish === true ? { publishMode: 'publish' as const } : {}) });+ activated = reactivate && pin.state === 'active';+ }+ await syncQuestionPage(ctx, pin);+ let refresh: RefreshOutcome | undefined;+ if (p.defer !== true && pin.state === 'active' && pin.answer_revision === 0) {+ refresh = await boundedRefresh(ctx, pin, { full: true, waitMs: waitMs(p.wait_ms, DEFAULT_PIN_WAIT_MS), trigger: 'pin' }, deps);+ }+ return { created, activated, receipt: await receiptFor(ctx, access, pin.source_id, pin.slug, true, refresh) };+}++export async function listQuestions(ctx: OperationContext, p: Record<string, unknown>): Promise<{+ questions: QuestionReceipt[]; counts: Record<'total' | 'fresh' | 'stale' | 'awaiting_refresh' | 'refreshing' | 'archived' | 'blocked', number>;+}> {+ const access = await requireOwnerCapable(ctx, 'questions_list', ['gbrain', 'questions', 'list']);+ let sources = access.readableSources ?? undefined;+ if (typeof p.source === 'string' && p.source.trim()) {+ assertSourceInCallerScope(ctx, p.source.trim());+ sources = [p.source.trim()];+ } else if (access.remote && !sources) {+ sources = [defaultSource(ctx)];+ }+ const pins = await listPins(ctx.engine, { ...(sources ? { sourceIds: sources } : {}), includeArchived: p.include_archived === true });+ const questions: QuestionReceipt[] = [];+ for (const pin of pins) questions.push(await buildReceipt(ctx.engine, pin, { readableSources: access.readableSources, includeAnswer: false, remote: access.remote }));+ const count = (f: (r: QuestionReceipt) => boolean) => questions.filter(f).length;+ return {+ questions,+ counts: {+ total: questions.length, fresh: count(r => r.freshness === 'fresh'), stale: count(r => r.freshness === 'stale'),+ awaiting_refresh: count(r => r.freshness === 'awaiting_refresh'), refreshing: count(r => r.freshness === 'refreshing'),+ archived: count(r => r.freshness === 'archived'), blocked: count(r => r.blocked_reason !== null),+ },+ };+}++export async function questionStatus(ctx: OperationContext, p: Record<string, unknown>): Promise<QuestionReceipt> {+ const access = await requireOwnerCapable(ctx, 'questions_status', ['gbrain', 'questions', 'status', typeof p.id === 'string' ? p.id : '<id>']);+ const pin = await resolvePin(ctx, access, p.id, 'questions_status');+ return receiptFor(ctx, access, pin.source_id, pin.slug, p.include_answer !== false);+}++export async function refreshQuestion(ctx: OperationContext, p: Record<string, unknown>, deps: QuestionsDeps = {}): Promise<QuestionReceipt> {+ const access = await requireOwnerCapable(ctx, 'questions_refresh', ['gbrain', 'questions', 'refresh', typeof p.id === 'string' ? p.id : '<id>']);+ let pin = await resolvePin(ctx, access, p.id, 'questions_refresh');+ if (ctx.remote !== false) assertSourceInCallerWriteScope(ctx, pin.source_id);+ if (pin.state !== 'archived') await syncQuestionPage(ctx, pin);+ pin = (await getPin(ctx.engine, pin.source_id, pin.slug))!;+ const refresh: RefreshOutcome = pin.state === 'archived' ? { status: 'skipped', reason: 'archived' }+ : pin.state === 'inactive' ? { status: 'blocked', blocked_reason: 'awaiting_consent', detail: `pin is inactive (${pin.inactive_reason ?? 'awaiting_consent'})` }+ : await boundedRefresh(ctx, pin, { full: p.full === true, waitMs: waitMs(p.wait_ms, DEFAULT_REFRESH_WAIT_MS), trigger: 'manual' }, deps);+ return receiptFor(ctx, access, pin.source_id, pin.slug, true, refresh);+}++export async function unpinQuestion(ctx: OperationContext, p: Record<string, unknown>): Promise<{ unpinned: boolean; receipt: QuestionReceipt }> {+ const access = await requireOwnerCapable(ctx, 'questions_unpin', ['gbrain', 'questions', 'unpin', typeof p.id === 'string' ? p.id : '<id>']);+ let pin = await resolvePin(ctx, access, p.id, 'questions_unpin');+ if (ctx.remote !== false) assertSourceInCallerWriteScope(ctx, pin.source_id);+ const unpinned = pin.state !== 'archived';+ if (unpinned) pin = await updatePinState(ctx.engine, pin.id, { state: 'archived' });+ await syncQuestionPage(ctx, pin);+ return { unpinned, receipt: await receiptFor(ctx, access, pin.source_id, pin.slug, false) };+}++export interface PinnedForPack {+ pinned_questions?: Array<{ id: string; question: string; answer: string[]; freshness: 'fresh' | 'stale' }>;+ withheld?: { stale_sentences: number; question_ids: string[]; refresh_command: string };+}++/**+ * context_pack's optional pinned fields: published, active pins scoped to one+ * of the packed entities, fresh sentences only. Stale (and unreadable)+ * sentences are withheld and counted. Owner-capable callers only; anyone else+ * gets nothing (and no hint that pins exist).+ */+export async function pinnedAnswersForPack(ctx: OperationContext, entitySlugs: string[]): Promise<PinnedForPack | null> {+ if (entitySlugs.length === 0) return null;+ let access: CallerAccess;+ try { access = await requireOwnerCapable(ctx, 'context_pack', ['gbrain', 'questions', 'list']); } catch { return null; }+ const sources = access.readableSources ?? [defaultSource(ctx)];+ const pins = (await listPins(ctx.engine, { sourceIds: sources, states: ['active'] }))+ .filter(pin => pin.publish_mode === 'publish' && pin.answer_revision > 0 && pin.scope_entity && entitySlugs.includes(pin.scope_entity));+ if (pins.length === 0) return null;+ const pinned: NonNullable<PinnedForPack['pinned_questions']> = [];+ let withheld = 0;+ const withheldIds: string[] = [];+ for (const pin of pins) {+ const evaluation = await evaluateAnswer(ctx.engine, pin, { readableSources: access.readableSources });+ const fresh = evaluation.sentences.filter(s => !s.stale && !s.hidden).map(s => s.text);+ const held = evaluation.stale + evaluation.hidden;+ if (held > 0) { withheld += held; withheldIds.push(pinId(pin)); }+ if (fresh.length > 0) pinned.push({ id: pinId(pin), question: pin.question, answer: fresh, freshness: held > 0 ? 'stale' : 'fresh' });+ }+ return {+ ...(pinned.length ? { pinned_questions: pinned } : {}),+ ...(withheld > 0 ? { withheld: { stale_sentences: withheld, question_ids: withheldIds, refresh_command: `gbrain questions refresh ${withheldIds[0]}` } } : {}),+ };+}diff --git a/src/core/questions/store.ts b/src/core/questions/store.tsnew file mode 100644index 0000000000..d99ea9f186--- /dev/null+++ b/src/core/questions/store.ts@@ -0,0 +1,184 @@+/**+ * Pinned-question rows: reads, idempotent pin, state changes and the durable+ * refresh lease. SQL runs through `engine.executeRaw` on the pinned_questions+ * table (not a canonical-writer table, so no coordinator capability is needed);+ * the question page itself is written by ./pages.ts through the coordinator.+ */+import type { BrainEngine } from '../engine.ts';+import { formatQuestionId, type QuestionScope } from './identity.ts';++export type PinState = 'active' | 'inactive' | 'archived';+export type InactiveReason = 'awaiting_consent' | 'migrated_disabled' | 'migrated_zero_budget';+export type PublishMode = 'publish' | 'draft';+export type SentenceOrigin = 'model' | 'owner';++export interface AnswerSentence {+ id: string;+ text: string;+ origin: SentenceOrigin;+}++export interface PinRow {+ id: number;+ source_id: string;+ slug: string;+ question: string;+ scope_slug_prefix: string | null;+ scope_entity: string | null;+ state: PinState;+ inactive_reason: InactiveReason | null;+ publish_mode: PublishMode;+ model: string | null;+ cooldown_days: number | null;+ origin: string;+ created_by: string;+ revision: number;+ answer_revision: number;+ answer: AnswerSentence[];+ answer_model: string | null;+ last_refresh_at: Date | null;+ last_attempt_at: Date | null;+ last_error: string | null;+ watermark_generation: number | null;+ watermark_fact_id: number | null;+ watermark_at: Date | null;+ lease_token: string | null;+ lease_owner: string | null;+ lease_expires_at: Date | null;+ refresh_attempts: number;+ spend_usd: number;+ created_at: Date;+ archived_at: Date | null;+}++const COLUMNS = `id, source_id, slug, question, scope_slug_prefix, scope_entity, state, inactive_reason, publish_mode, model,+ cooldown_days, origin, created_by, revision, answer_revision, answer, answer_model, last_refresh_at, last_attempt_at,+ last_error, watermark_generation, watermark_fact_id, watermark_at, lease_token, lease_owner, lease_expires_at,+ refresh_attempts, spend_usd, created_at, archived_at`;++const date = (v: unknown): Date | null => v === null || v === undefined ? null : v instanceof Date ? v : new Date(String(v));+const num = (v: unknown): number | null => v === null || v === undefined ? null : Number(v);++export function parseAnswer(raw: unknown): AnswerSentence[] {+ if (typeof raw !== 'string' || raw === '') return [];+ try {+ const parsed = JSON.parse(raw);+ if (!Array.isArray(parsed)) return [];+ return parsed.filter((s): s is AnswerSentence => s && typeof s.id === 'string' && typeof s.text === 'string'+ && (s.origin === 'model' || s.origin === 'owner'));+ } catch {+ return [];+ }+}++export function toPinRow(r: Record<string, unknown>): PinRow {+ return {+ id: Number(r.id), source_id: String(r.source_id), slug: String(r.slug), question: String(r.question),+ scope_slug_prefix: (r.scope_slug_prefix as string | null) ?? null, scope_entity: (r.scope_entity as string | null) ?? null,+ state: r.state as PinState, inactive_reason: (r.inactive_reason as InactiveReason | null) ?? null,+ publish_mode: r.publish_mode === 'draft' ? 'draft' : 'publish', model: (r.model as string | null) ?? null,+ cooldown_days: num(r.cooldown_days), origin: String(r.origin), created_by: String(r.created_by),+ revision: Number(r.revision), answer_revision: Number(r.answer_revision), answer: parseAnswer(r.answer),+ answer_model: (r.answer_model as string | null) ?? null, last_refresh_at: date(r.last_refresh_at),+ last_attempt_at: date(r.last_attempt_at), last_error: (r.last_error as string | null) ?? null,+ watermark_generation: num(r.watermark_generation), watermark_fact_id: num(r.watermark_fact_id), watermark_at: date(r.watermark_at),+ lease_token: (r.lease_token as string | null) ?? null, lease_owner: (r.lease_owner as string | null) ?? null,+ lease_expires_at: date(r.lease_expires_at), refresh_attempts: Number(r.refresh_attempts ?? 0),+ spend_usd: Number(r.spend_usd ?? 0), created_at: date(r.created_at)!, archived_at: date(r.archived_at),+ };+}++export function pinId(row: Pick<PinRow, 'source_id' | 'slug'>): string {+ return formatQuestionId(row.source_id, row.slug);+}++export function pinScope(row: Pick<PinRow, 'source_id' | 'scope_slug_prefix' | 'scope_entity'>): QuestionScope {+ return {+ source: row.source_id,+ ...(row.scope_slug_prefix ? { slug_prefix: row.scope_slug_prefix } : {}),+ ...(row.scope_entity ? { entity: row.scope_entity } : {}),+ };+}++export async function getPin(engine: BrainEngine, sourceId: string, slug: string, opts: { forUpdate?: boolean } = {}): Promise<PinRow | null> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT ${COLUMNS} FROM pinned_questions WHERE source_id = $1 AND slug = $2${opts.forUpdate ? ' FOR UPDATE' : ''}`, [sourceId, slug]);+ return rows[0] ? toPinRow(rows[0]) : null;+}++export async function listPins(engine: BrainEngine, opts: { sourceIds?: string[]; includeArchived?: boolean; states?: PinState[] } = {}): Promise<PinRow[]> {+ const params: unknown[] = [];+ const where: string[] = [];+ if (opts.sourceIds) { params.push(opts.sourceIds); where.push(`source_id = ANY($${params.length}::text[])`); }+ if (opts.states) { params.push(opts.states); where.push(`state = ANY($${params.length}::text[])`); }+ else if (!opts.includeArchived) where.push(`state <> 'archived'`);+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `SELECT ${COLUMNS} FROM pinned_questions ${where.length ? `WHERE ${where.join(' AND ')}` : ''} ORDER BY source_id, created_at, id`, params);+ return rows.map(toPinRow);+}++export interface PinInsert {+ sourceId: string;+ slug: string;+ question: string;+ scope: QuestionScope;+ state: PinState;+ inactiveReason: InactiveReason | null;+ publishMode: PublishMode;+ createdBy: string;+}++/** Idempotent insert keyed on (source_id, slug). Returns the row and whether it was created. */+export async function insertPin(engine: BrainEngine, p: PinInsert): Promise<{ row: PinRow; created: boolean }> {+ const inserted = await engine.executeRaw<Record<string, unknown>>(+ `INSERT INTO pinned_questions (source_id, slug, question, scope_slug_prefix, scope_entity, state, inactive_reason, publish_mode, created_by)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)+ ON CONFLICT (source_id, slug) DO NOTHING RETURNING ${COLUMNS}`,+ [p.sourceId, p.slug, p.question, p.scope.slug_prefix ?? null, p.scope.entity ?? null, p.state, p.inactiveReason, p.publishMode, p.createdBy]);+ if (inserted[0]) return { row: toPinRow(inserted[0]), created: true };+ return { row: (await getPin(engine, p.sourceId, p.slug))!, created: false };+}++/** State change that bumps the pin revision, so an in-flight refresh revalidating at commit sees it. */+export async function updatePinState(engine: BrainEngine, id: number, patch: {+ state?: PinState; inactiveReason?: InactiveReason | null; publishMode?: PublishMode;+}): Promise<PinRow> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `UPDATE pinned_questions SET+ state = COALESCE($2, state),+ inactive_reason = CASE WHEN $3::boolean THEN $4 ELSE inactive_reason END,+ publish_mode = COALESCE($5, publish_mode),+ archived_at = CASE WHEN COALESCE($2, state) = 'archived' THEN COALESCE(archived_at, now()) ELSE NULL END,+ lease_token = CASE WHEN COALESCE($2, state) = 'archived' THEN NULL ELSE lease_token END,+ lease_expires_at = CASE WHEN COALESCE($2, state) = 'archived' THEN NULL ELSE lease_expires_at END,+ revision = revision + 1, updated_at = now()+ WHERE id = $1 RETURNING ${COLUMNS}`,+ [id, patch.state ?? null, patch.inactiveReason !== undefined, patch.inactiveReason ?? null, patch.publishMode ?? null]);+ return toPinRow(rows[0]!);+}++/**+ * Durable refresh lease. A second worker (or a duplicate cycle) gets null+ * while a live lease exists; an expired lease (a crashed worker) is taken over.+ */+export async function acquireLease(engine: BrainEngine, id: number, token: string, owner: string, ttlMs: number): Promise<PinRow | null> {+ const rows = await engine.executeRaw<Record<string, unknown>>(+ `UPDATE pinned_questions SET lease_token = $2, lease_owner = $3,+ lease_expires_at = now() + ($4::double precision * interval '1 millisecond'),+ last_attempt_at = now(), refresh_attempts = refresh_attempts + 1+ WHERE id = $1 AND state <> 'archived' AND (lease_token IS NULL OR lease_expires_at IS NULL OR lease_expires_at < now())+ RETURNING ${COLUMNS}`, [id, token, owner, ttlMs]);+ return rows[0] ? toPinRow(rows[0]) : null;+}++/** Ends a refresh attempt without publishing: keeps the previous answer, records the cause and spend. */+export async function releaseLease(engine: BrainEngine, id: number, token: string, outcome: { error: string | null; spendUsd: number }): Promise<void> {+ await engine.executeRaw(+ `UPDATE pinned_questions SET lease_token = NULL, lease_owner = NULL, lease_expires_at = NULL,+ last_error = $3, spend_usd = spend_usd + $4, updated_at = now()+ WHERE id = $1 AND lease_token = $2`, [id, token, outcome.error, outcome.spendUsd]);+}++export async function addSpend(engine: BrainEngine, id: number, usd: number): Promise<void> {+ if (usd > 0) await engine.executeRaw('UPDATE pinned_questions SET spend_usd = spend_usd + $2 WHERE id = $1', [id, usd]);+}diff --git a/src/core/schema-embedded.generated.ts b/src/core/schema-embedded.generated.tsindex 5fc1b811b6..6f28042a70 100644--- a/src/core/schema-embedded.generated.ts+++ b/src/core/schema-embedded.generated.ts@@ -2646,4 +2646,68 @@ ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_checked_at TIMESTAMPTZ;ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_commit TEXT;ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_behind INTEGER;+-- Pinned questions (C4): answers and their evidence pointers live outside pages.+-- BEGIN GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS pinned_questions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ question TEXT NOT NULL,+ scope_slug_prefix TEXT,+ scope_entity TEXT,+ state TEXT NOT NULL DEFAULT 'active',+ inactive_reason TEXT,+ publish_mode TEXT NOT NULL DEFAULT 'publish',+ model TEXT,+ cooldown_days REAL,+ origin TEXT NOT NULL DEFAULT 'pin',+ created_by TEXT NOT NULL,+ revision BIGINT NOT NULL DEFAULT 1,+ answer_revision INTEGER NOT NULL DEFAULT 0,+ answer TEXT,+ answer_model TEXT,+ last_refresh_at TIMESTAMPTZ,+ last_attempt_at TIMESTAMPTZ,+ last_error TEXT,+ watermark_generation BIGINT,+ watermark_fact_id BIGINT,+ watermark_at TIMESTAMPTZ,+ lease_token TEXT,+ lease_owner TEXT,+ lease_expires_at TIMESTAMPTZ,+ refresh_attempts INTEGER NOT NULL DEFAULT 0,+ spend_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ archived_at TIMESTAMPTZ,+ CONSTRAINT pinned_questions_source_slug_key UNIQUE (source_id, slug)+);+CREATE INDEX IF NOT EXISTS pinned_questions_state_idx ON pinned_questions (state, source_id);+CREATE TABLE IF NOT EXISTS question_evidence (+ id BIGSERIAL PRIMARY KEY,+ question_id BIGINT NOT NULL,+ answer_revision INTEGER NOT NULL,+ sentence_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ source_id TEXT NOT NULL,+ page_id INTEGER,+ page_slug TEXT,+ page_generation BIGINT,+ page_revision TEXT,+ item_id BIGINT,+ content_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS question_evidence_question_idx ON question_evidence (question_id, answer_revision);+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE pinned_questions ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+DO \$rls\$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE question_evidence ENABLE ROW LEVEL SECURITY;+ END IF;+END \$rls\$;+-- END GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL)`;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex c818627717..0cc16da960 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -205,6 +205,7 @@ import { v201 } from './v201-persistence-graduation.ts';import { v202 } from './v202-legacy-token-grant-conversion.ts';import { v203 } from './v203-oauth-client-grant-axes.ts';import { v204 } from './v204-links-temporal-state.ts';+import { v205 } from './v205-pinned-questions.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -408,4 +409,5 @@ export const MIGRATIONS: Migration[] = [v202,v203,v204,+ v205,];diff --git a/src/core/schema-migrations/v205-pinned-questions.ts b/src/core/schema-migrations/v205-pinned-questions.tsnew file mode 100644index 0000000000..ca91549eea--- /dev/null+++ b/src/core/schema-migrations/v205-pinned-questions.ts@@ -0,0 +1,15 @@+import type { Migration } from './types.ts';+import { PINNED_QUESTIONS_SCHEMA_SQL } from '../questions/schema.ts';+import { migrateAutoThinkToPins } from '../questions/auto-think-migration.ts';++// Pinned questions (C4): the pinned_questions and question_evidence tables+// (DDL in src/core/questions/schema.ts), then the dream.auto_think config+// keys become pins. The handler reads config only: no provider call, no page+// write, and a second run changes nothing.+export const v205: Migration = {+ version: 205,+ name: 'pinned_questions',+ idempotent: true,+ sql: PINNED_QUESTIONS_SCHEMA_SQL,+ handler: async (engine) => { await migrateAutoThinkToPins(engine); },+};diff --git a/src/core/schema-pack/base/gbrain-base.yaml b/src/core/schema-pack/base/gbrain-base.yamlindex 9a14e88949..3d0d26bf8d 100644--- a/src/core/schema-pack/base/gbrain-base.yaml+++ b/src/core/schema-pack/base/gbrain-base.yaml@@ -305,6 +305,16 @@ page_types:extractable: falseexpert_routing: false+ # Pinned question page (C4): the question and the owner's notes; the answer+ # lives in pinned_questions. Owner-private and never evidence. Set via+ # frontmatter only, so an existing questions/ folder keeps its own types.+ - name: question+ primitive: annotation+ path_prefixes: []+ aliases: []+ extractable: false+ expert_routing: false+# Receipt page written by the v0.41.23 extract framework after every# extractor run. Demoted in search via the 0.3x source-boost on the# `extracts/` prefix (see src/core/search/source-boost.ts). Alwaysdiff --git a/src/core/search/private-visibility.ts b/src/core/search/private-visibility.tsindex f581bf28cd..af06aba9b9 100644--- a/src/core/search/private-visibility.ts+++ b/src/core/search/private-visibility.ts@@ -27,11 +27,12 @@ export const REMOTE_PRIVATE_PAGES_KEY = 'search.remote_private_pages';/*** #5525 — extracted atoms and synthesized concept pages are derived from* other pages or from private transcripts, so a missing `visibility` field on- * them means "origin unknown", not "world". They fail closed; every other page- * keeps the documented default (absent visibility is world).+ * them means "origin unknown", not "world". Pinned-question pages (`type:+ * question`) are owner-private. They fail closed; every other page keeps the+ * documented default (absent visibility is world).*/function derivedPageSql(pageAlias: string): string {- return `(${pageAlias}.type = 'atom' OR (${pageAlias}.type = 'concept' AND ${pageAlias}.frontmatter->>'synthesized_by' IS NOT NULL))`;+ return `(${pageAlias}.type IN ('atom', 'question') OR (${pageAlias}.type = 'concept' AND ${pageAlias}.frontmatter->>'synthesized_by' IS NOT NULL))`;}/**@@ -70,10 +71,13 @@ function declaredLineagePrivateSql(p: string): string {/*** The same rule on a row's own `type`/`frontmatter` only, for snapshots such* as `page_versions` that have no page identity to follow to an origin. Callers- * pair it with privatePagesFilterFragment on the live page.+ * pair it with privatePagesFilterFragment on the live page. A page carrying the+ * `pinned_question` marker is private whatever its `visibility` says (pinned+ * questions are owner-private, src/core/questions/pages.ts).*/export function privateSnapshotFilterFragment(alias: string): string {- return `COALESCE(${alias}.frontmatter->>'visibility', CASE WHEN ${derivedPageSql(alias)} THEN 'private' ELSE 'world' END) <> 'private'`;+ return `(COALESCE(${alias}.frontmatter->>'visibility', CASE WHEN ${derivedPageSql(alias)} THEN 'private' ELSE 'world' END) <> 'private'+ AND NOT COALESCE(${alias}.frontmatter ? 'pinned_question', false))`;}/**@@ -170,7 +174,8 @@ export function privateProvenanceFilterFragment(factAlias: string): string {export function isPrivatePage(page: { type?: string | null; frontmatter?: unknown }): boolean {const frontmatter = typeof page.frontmatter === 'object' && page.frontmatter !== null? page.frontmatter as Record<string, unknown> : {};- const derived = page.type === 'atom' || (page.type === 'concept' && frontmatter.synthesized_by != null);+ if (frontmatter.pinned_question != null) return true;+ const derived = page.type === 'atom' || page.type === 'question' || (page.type === 'concept' && frontmatter.synthesized_by != null);return (frontmatter.visibility ?? (derived ? 'private' : 'world')) === 'private';}diff --git a/src/core/types.ts b/src/core/types.tsindex a944875090..4aecb2cf48 100644--- a/src/core/types.ts+++ b/src/core/types.ts@@ -64,6 +64,10 @@ export const ALL_PAGE_TYPES: readonly string[] = [// extractable:false (events are one-line atoms; diary is private interiority// never mined into the facts table). Pack entries in gbrain-base.yaml.'event', 'diary',+ // C4 — `question` = a pinned question's page (question + owner notes; the+ // answer lives in pinned_questions). Owner-private, never evidence, set+ // explicitly via frontmatter (no path prefix). Pack entry in gbrain-base.yaml.+ 'question',] as const;/**diff --git a/src/core/verbs.ts b/src/core/verbs.tsindex f3c09c5c0c..0aa9ed7d87 100644--- a/src/core/verbs.ts+++ b/src/core/verbs.ts@@ -706,6 +706,31 @@ export const RESPONSE_SCHEMAS: Record<VerbName, Record<string, unknown>> = {budget_tokens: { type: 'integer', description: 'Present when budget_tokens was passed.' },budget_used: { type: 'integer' },dropped_count: { type: 'integer' },+ // C4 pinned questions — additive optional, owner-capable callers only; outside `text` and the budget.+ pinned_questions: {+ type: 'array',+ description: 'Fresh sentences of pinned answers scoped to a packed entity (owner-capable callers only).',+ items: {+ type: 'object',+ required: ['id', 'question', 'answer', 'freshness'],+ properties: {+ id: { type: 'string' },+ question: { type: 'string' },+ answer: { type: 'array', items: { type: 'string' } },+ freshness: { type: 'string', enum: ['fresh', 'stale'] },+ },+ },+ },+ withheld: {+ type: 'object',+ required: ['stale_sentences', 'question_ids', 'refresh_command'],+ description: 'Pinned-answer sentences left out because their evidence changed or is unreadable.',+ properties: {+ stale_sentences: { type: 'integer' },+ question_ids: { type: 'array', items: { type: 'string' } },+ refresh_command: { type: 'string' },+ },+ },},},delta: {diff --git a/src/schema.sql b/src/schema.sqlindex 0d4ae41efd..7396a1e869 100644--- a/src/schema.sql+++ b/src/schema.sql@@ -2642,3 +2642,67 @@ ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_checked_at TIMESTAMPTZ;ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_commit TEXT;ALTER TABLE sources ADD COLUMN IF NOT EXISTS upstream_behind INTEGER;+-- Pinned questions (C4): answers and their evidence pointers live outside pages.+-- BEGIN GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL). Edit that file, then run: bun run build:schema+CREATE TABLE IF NOT EXISTS pinned_questions (+ id BIGSERIAL PRIMARY KEY,+ source_id TEXT NOT NULL,+ slug TEXT NOT NULL,+ question TEXT NOT NULL,+ scope_slug_prefix TEXT,+ scope_entity TEXT,+ state TEXT NOT NULL DEFAULT 'active',+ inactive_reason TEXT,+ publish_mode TEXT NOT NULL DEFAULT 'publish',+ model TEXT,+ cooldown_days REAL,+ origin TEXT NOT NULL DEFAULT 'pin',+ created_by TEXT NOT NULL,+ revision BIGINT NOT NULL DEFAULT 1,+ answer_revision INTEGER NOT NULL DEFAULT 0,+ answer TEXT,+ answer_model TEXT,+ last_refresh_at TIMESTAMPTZ,+ last_attempt_at TIMESTAMPTZ,+ last_error TEXT,+ watermark_generation BIGINT,+ watermark_fact_id BIGINT,+ watermark_at TIMESTAMPTZ,+ lease_token TEXT,+ lease_owner TEXT,+ lease_expires_at TIMESTAMPTZ,+ refresh_attempts INTEGER NOT NULL DEFAULT 0,+ spend_usd DOUBLE PRECISION NOT NULL DEFAULT 0,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),+ archived_at TIMESTAMPTZ,+ CONSTRAINT pinned_questions_source_slug_key UNIQUE (source_id, slug)+);+CREATE INDEX IF NOT EXISTS pinned_questions_state_idx ON pinned_questions (state, source_id);+CREATE TABLE IF NOT EXISTS question_evidence (+ id BIGSERIAL PRIMARY KEY,+ question_id BIGINT NOT NULL,+ answer_revision INTEGER NOT NULL,+ sentence_id TEXT NOT NULL,+ kind TEXT NOT NULL,+ source_id TEXT NOT NULL,+ page_id INTEGER,+ page_slug TEXT,+ page_generation BIGINT,+ page_revision TEXT,+ item_id BIGINT,+ content_hash TEXT,+ created_at TIMESTAMPTZ NOT NULL DEFAULT now()+);+CREATE INDEX IF NOT EXISTS question_evidence_question_idx ON question_evidence (question_id, answer_revision);+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE pinned_questions ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+DO $rls$ BEGIN+ IF EXISTS (SELECT 1 FROM pg_roles r WHERE pg_has_role(current_user, r.oid, 'USAGE') AND (r.rolbypassrls OR r.rolsuper)) THEN+ ALTER TABLE question_evidence ENABLE ROW LEVEL SECURITY;+ END IF;+END $rls$;+-- END GENERATED from src/core/questions/schema.ts (PINNED_QUESTIONS_SCHEMA_SQL)diff --git a/test/helpers/pinned-questions-fixture.ts b/test/helpers/pinned-questions-fixture.tsnew file mode 100644index 0000000000..5e988bd7be--- /dev/null+++ b/test/helpers/pinned-questions-fixture.ts@@ -0,0 +1,118 @@+/**+ * Shared fixture for the pinned-question (C4) suites: the B5 offline safety+ * gate and operator journeys run the same scenarios on PGLite+ * (test/pinned-questions-safety.test.ts) and live Postgres+ * (test/e2e/pinned-questions-postgres.test.ts).+ *+ * The stub model answers one sentence per evidence item, each starting with+ * the canary `QZ7`, so any surface that leaks answer text is caught by a+ * substring search. Each scenario gets its own source.+ */+import { randomUUID } from 'node:crypto';+import type { BrainEngine } from '../../src/core/engine.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { dispatchToolCall, type ToolResult } from '../../src/mcp/dispatch.ts';+import type { ChatOpts, ChatResult } from '../../src/core/ai/gateway.ts';+import type { QuestionChatFn } from '../../src/core/questions/refresh.ts';++export const CANARY = 'QZ7';+export const QUESTION = 'Where does acme-example build widgets and who leads it?';+export const ENTITY = 'companies/acme-example';+export const MODEL = 'anthropic:claude-sonnet-4-6';++export const logger = { info() {}, warn() {}, error() {} };++export function localCtx(engine: BrainEngine, sourceId: string): OperationContext {+ return { engine, config: { engine: engine.kind, embedding_disabled: true } as never, remote: false, sourceId, dryRun: false, logger };+}++export async function newSource(engine: BrainEngine): Promise<string> {+ const id = `pq-${randomUUID().slice(0, 8)}`;+ await engine.executeRaw('INSERT INTO sources (id, name) VALUES ($1, $1)', [id]);+ return id;+}++export async function putPage(engine: BrainEngine, sourceId: string, slug: string, content: string, expectedRevision?: string): Promise<void> {+ await submitPageMutation(localCtx(engine, sourceId), { operation: 'put_page', params: {+ slug, content, source_id: sourceId, ...(expectedRevision ? { expected_revision: expectedRevision } : {}),+ } });+}++export const page = (type: string, title: string, body: string, extra = '') => `---\ntype: ${type}\ntitle: ${title}\n${extra}---\n${body}\n`;++export interface Seeded { sourceId: string; factId: number; expiringFactId: number; timelineId: number; takeId: number }++/** A small brain: an entity page, two related pages, facts (one expiring by the clock), a timeline row and a take. */+export async function seedBrain(engine: BrainEngine, opts: { expiringInMs?: number } = {}): Promise<Seeded> {+ const sourceId = await newSource(engine);+ await putPage(engine, sourceId, ENTITY, page('company', 'Acme example', 'Acme example builds widgets in Lisbon.'));+ await putPage(engine, sourceId, 'people/alice-example', page('person', 'Alice example', 'Alice example leads acme-example engineering.'));+ await putPage(engine, sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan for acme-example ships in March.'));+ const fact = await engine.executeRaw<{ id: string }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from)+ VALUES ($1, $2, 'Acme example has 40 employees', 'fact', 'test', 'world', 1, now() - interval '1 day') RETURNING id`, [sourceId, ENTITY]);+ const expiring = await engine.executeRaw<{ id: string }>(+ `INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from, valid_until)+ VALUES ($1, $2, 'Acme example runs a widget sale', 'fact', 'test', 'world', 1, now() - interval '1 day',+ now() + ($3::double precision * interval '1 millisecond')) RETURNING id`, [sourceId, ENTITY, opts.expiringInMs ?? 3_600_000]);+ const [alice] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE source_id = $1 AND slug = $2', [sourceId, 'people/alice-example']);+ const timeline = await engine.executeRaw<{ id: number }>(+ `INSERT INTO timeline_entries (page_id, date, source, summary, detail) VALUES ($1, '2026-02-01', 'test', 'Alice example promoted to engineering lead', '') RETURNING id`, [alice!.id]);+ const take = await engine.executeRaw<{ id: string }>(+ `INSERT INTO takes (page_id, row_num, claim, kind, holder, weight, source, active) VALUES ($1, 1, 'Alice example will ship widgets on time', 'take', 'brain', 0.7, 'test', true) RETURNING id`, [alice!.id]);+ return { sourceId, factId: Number(fact[0]!.id), expiringFactId: Number(expiring[0]!.id), timelineId: timeline[0]!.id, takeId: Number(take[0]!.id) };+}++/** Deterministic answer: one canary sentence per evidence line, citing it. */+export function stubAnswer(user: string, opts: { limit?: number; prefix?: string } = {}): string {+ const lines = user.split('\n').filter(l => /^E\d+: /.test(l)).slice(0, opts.limit ?? 12);+ return JSON.stringify({+ sentences: lines.map(l => {+ const ref = l.slice(0, l.indexOf(':'));+ const body = l.slice(l.indexOf(':') + 2).replace(/\s+/g, ' ').slice(0, 90);+ return { text: `${CANARY}${opts.prefix ?? ''} answer citing ${body}.`, cite: [ref] };+ }),+ gaps: [],+ });+}++export interface StubChat { fn: QuestionChatFn; calls: string[]; fail: boolean; gate?: Promise<void> }++export function stubChat(): StubChat {+ const s: StubChat = { calls: [], fail: false, fn: async () => ({ text: '', usage: null, model: MODEL }) };+ s.fn = async (req) => {+ s.calls.push(req.user);+ if (s.gate) await s.gate;+ if (s.fail) throw new Error('503 provider_error from stub');+ return { text: stubAnswer(req.user), usage: { input_tokens: 1000, output_tokens: 200 }, model: MODEL };+ };+ return s;+}++/** Gateway-level transport for op journeys (the ops call gateway chat like production). */+export function stubTransport(state: { calls: number; fail: boolean }): (opts: ChatOpts) => Promise<ChatResult> {+ return async (opts) => {+ state.calls++;+ if (state.fail) throw new Error('503 provider_error from stub');+ const user = String(opts.messages[opts.messages.length - 1]?.content ?? '');+ const text = stubAnswer(user);+ return { text, blocks: [{ type: 'text', text }], stopReason: 'end', model: opts.model ?? MODEL, providerId: 'anthropic',+ usage: { input_tokens: 1000, output_tokens: 200, cache_read_tokens: 0, cache_creation_tokens: 0 } };+ };+}++export interface RemoteAuth { scopes: string[]; sourceId: string; boundSlugPrefixes?: string[] }++/** An MCP call as a remote agent (stdio transport with an explicit grant). */+export async function mcp(engine: BrainEngine, tool: string, params: Record<string, unknown>, auth: RemoteAuth): Promise<{ result: ToolResult; body: Record<string, unknown>; text: string }> {+ const result = await dispatchToolCall(engine, tool, params, {+ remote: true, transport: 'stdio', sourceId: auth.sourceId, config: { engine: engine.kind, embedding_disabled: true } as never, logger,+ auth: { token: 't', clientId: 'pq-agent', scopes: auth.scopes, sourceId: auth.sourceId, allowedSources: [auth.sourceId],+ ...(auth.boundSlugPrefixes ? { boundSlugPrefixes: auth.boundSlugPrefixes } : {}) },+ });+ const text = result.content.map(c => (c as { text?: string }).text ?? '').join('\n');+ let body: Record<string, unknown> = {};+ try { body = JSON.parse((result.content[0] as { text: string }).text); } catch { /* non-JSON */ }+ return { result, body, text };+}diff --git a/test/helpers/pinned-questions-scenarios.ts b/test/helpers/pinned-questions-scenarios.tsnew file mode 100644index 0000000000..d0b21dc524--- /dev/null+++ b/test/helpers/pinned-questions-scenarios.ts@@ -0,0 +1,580 @@+/**+ * B5 offline safety gate and operator journeys for pinned questions (C4),+ * registered once per engine: test/pinned-questions-safety.test.ts (PGLite)+ * and test/e2e/pinned-questions-postgres.test.ts (live Postgres). Stub model+ * only; no network.+ *+ * Protects: restricted grants never see a question page or answer on any+ * read surface; answer text never enters pages, chunks, versions or export;+ * every evidence change (edit, soft and hard delete, forget, clock expiry,+ * supersession, visibility, take, timeline, owner edit) marks the dependent+ * sentence stale on the next read with no cycle; refresh never publishes over+ * a concurrent change, a duplicate worker, a crash between publication+ * stages, or a failure; consent, keyless, budget and worker states carry an+ * actionable next step; the dream.auto_think migration keeps every opt-out.+ */+import { describe, expect, test } from 'bun:test';+import { mkdtempSync, readdirSync, readFileSync, rmSync, statSync, writeFileSync, mkdirSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import type { BrainEngine } from '../../src/core/engine.ts';+import { submitPageMutation } from '../../src/core/persistence/page-mutations.ts';+import { recordFactWithdrawal } from '../../src/core/facts/withdrawal.ts';+import { __resetPrivateVisibilityCacheForTests } from '../../src/core/search/private-visibility.ts';+import { __setChatTransportForTests } from '../../src/core/ai/gateway.ts';+import { operationScopesAllowed } from '../../src/core/scope.ts';+import { operationsByName } from '../../src/core/operations.ts';+import { runExport } from '../../src/commands/export.ts';+import { pinQuestion, questionStatus, refreshQuestion, unpinQuestion, listQuestions } from '../../src/core/questions/service.ts';+import { refreshPin } from '../../src/core/questions/refresh.ts';+import { getPin } from '../../src/core/questions/store.ts';+import { parseQuestionId, questionSlug } from '../../src/core/questions/identity.ts';+import { migrateAutoThinkToPins } from '../../src/core/questions/auto-think-migration.ts';+import { runPhaseStandingQuestions } from '../../src/core/questions/phase.ts';+import type { QuestionReceipt } from '../../src/core/questions/receipt.ts';+import { withEnv } from './with-env.ts';+import { CANARY, ENTITY, MODEL, QUESTION, localCtx, mcp, page, putPage, seedBrain, stubChat, stubTransport, type Seeded } from './pinned-questions-fixture.ts';++type Pinned = { created: boolean; activated: boolean; receipt: QuestionReceipt };++async function pin(engine: BrainEngine, s: Seeded, chat = stubChat(), extra: Record<string, unknown> = {}): Promise<Pinned> {+ return pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY }, ...extra }, { chat: chat.fn });+}++const status = (engine: BrainEngine, s: Seeded, id: string) => questionStatus(localCtx(engine, s.sourceId), { id });+const sentence = (r: QuestionReceipt, needle: string) => r.answer!.find(x => x.text.includes(needle));++async function revisionOf(engine: BrainEngine, sourceId: string, slug: string): Promise<string> {+ return (await engine.readPageSnapshot(slug, { sourceId }))!.revision;+}++async function setRemotePrivate(engine: BrainEngine, visible: boolean): Promise<void> {+ if (visible) await engine.setConfig('search.remote_private_pages', 'visible');+ else await engine.executeRaw("DELETE FROM config WHERE key = 'search.remote_private_pages'");+ __resetPrivateVisibilityCacheForTests();+}++function walk(dir: string): string[] {+ return readdirSync(dir).flatMap(name => {+ const p = join(dir, name);+ return statSync(p).isDirectory() ? walk(p) : [p];+ });+}++export function registerPinnedQuestionSuite(label: string, getEngine: () => BrainEngine): void {+ const env = { ANTHROPIC_API_KEY: 'sk-test-pinned-questions' };+ const run = (name: string, fn: (engine: BrainEngine) => Promise<void>, timeout = 60_000) =>+ test(name, async () => {+ const engine = getEngine();+ await engine.setConfig('models.standing_questions', MODEL);+ await withEnv(env, () => fn(engine));+ }, timeout);++ describe(`${label}: lifecycle and consent`, () => {+ run('a CLI pin is active, answers first, is idempotent and keeps the answer out of its page', async (engine) => {+ const s = await seedBrain(engine);+ const chat = stubChat();+ const first = await pin(engine, s, chat);+ expect(first.created).toBe(true);+ expect(first.receipt).toMatchObject({ state: 'active', freshness: 'fresh', blocked_reason: null, page_materialized: true, answer_revision: 1 });+ expect(first.receipt.answer!.length).toBeGreaterThan(3);+ expect(first.receipt.answer!.every(x => x.text.startsWith(CANARY) && !x.stale)).toBe(true);+ expect(first.receipt.verify.mcp).toEqual({ tool: 'questions_status', arguments: { id: first.receipt.id } });+ expect(first.receipt.evidence_watermark?.page_generation).toBeGreaterThan(0);+ const again = await pin(engine, s, chat);+ expect(again).toMatchObject({ created: false, receipt: { id: first.receipt.id, answer_revision: 1 } });+ expect(chat.calls).toHaveLength(1);+ const parsed = parseQuestionId(first.receipt.id, 'default')!;+ const [row] = await engine.executeRaw<{ type: string; vis: string; marker: string; body: string }>(+ `SELECT type, frontmatter->>'visibility' AS vis, frontmatter->>'pinned_question' AS marker, compiled_truth AS body FROM pages WHERE source_id = $1 AND slug = $2`,+ [parsed.sourceId, parsed.slug]);+ expect(row).toMatchObject({ type: 'question', vis: 'private', marker: first.receipt.id });+ expect(row!.body).not.toContain(CANARY);+ });++ run('the same question in two sources has two source-qualified ids', async (engine) => {+ const a = await seedBrain(engine);+ const b = await seedBrain(engine);+ const pa = await pin(engine, a);+ const pb = await pin(engine, b);+ expect(pa.receipt.id).not.toBe(pb.receipt.id);+ expect(pa.receipt.id.startsWith(`${a.sourceId}:questions/`)).toBe(true);+ expect(pb.receipt.slug).toBe(pa.receipt.slug);+ const listed = await listQuestions(localCtx(engine, a.sourceId), { source: a.sourceId });+ expect(listed.questions.map(q => q.id)).toEqual([pa.receipt.id]);+ });++ run('an MCP pin stays inactive with no model call until the owner activates it', async (engine) => {+ const s = await seedBrain(engine);+ await setRemotePrivate(engine, true);+ const calls = { calls: 0, fail: false };+ __setChatTransportForTests(stubTransport(calls));+ try {+ const { body } = await mcp(engine, 'questions_pin', { question: QUESTION, scope: { entity: ENTITY } }, { scopes: ['read', 'write'], sourceId: s.sourceId });+ const receipt = (body as unknown as Pinned).receipt;+ expect(receipt).toMatchObject({ state: 'inactive', inactive_reason: 'awaiting_consent', freshness: 'awaiting_refresh', blocked_reason: 'awaiting_consent', page_materialized: false });+ expect(receipt.next_action).toMatchObject({ argv: ['gbrain', 'questions', 'pin', '--id', receipt.id], consent: ['paid'], actor: 'user' });+ const refreshed = await mcp(engine, 'questions_refresh', { id: receipt.id }, { scopes: ['read', 'write'], sourceId: s.sourceId });+ expect(refreshed.body).toMatchObject({ blocked_reason: 'awaiting_consent', refresh: { status: 'blocked', blocked_reason: 'awaiting_consent' } });+ expect(calls.calls).toBe(0);+ const activated = await pinQuestion(localCtx(engine, s.sourceId), { id: receipt.id }, { chat: stubChat().fn });+ expect(activated).toMatchObject({ created: false, activated: true, receipt: { state: 'active', freshness: 'fresh', page_materialized: true } });+ } finally {+ __setChatTransportForTests(null);+ await setRemotePrivate(engine, false);+ }+ });++ run('unpin stops refreshes and archives the page, keeping the owner notes', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const snap = await engine.readPageSnapshot(slug, { sourceId: s.sourceId });+ await putPage(engine, s.sourceId, slug, `---\n${Object.entries(snap!.page.frontmatter as Record<string, unknown>).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n')}\ntitle: ${JSON.stringify(snap!.page.title)}\ntype: question\n---\n${snap!.page.compiled_truth}\nMy own note about acme.\n`, snap!.revision);+ const out = await unpinQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id });+ expect(out).toMatchObject({ unpinned: true, receipt: { state: 'archived', freshness: 'archived', blocked_reason: null, next_action: null } });+ const [row] = await engine.executeRaw<{ status: string; body: string }>(`SELECT frontmatter->>'status' AS status, compiled_truth AS body FROM pages WHERE source_id = $1 AND slug = $2`, [s.sourceId, slug]);+ expect(row).toMatchObject({ status: 'archived' });+ expect(row!.body).toContain('My own note about acme.');+ const chat = stubChat();+ expect((await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: chat.fn, leaseOwner: 't' })).status).toBe('skipped');+ expect((await unpinQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id })).unpinned).toBe(false);+ const phase = await runPhaseStandingQuestions(engine, { dryRun: false, chat: chat.fn });+ expect(JSON.stringify(phase.details)).not.toContain(pinned.receipt.id.split(':')[1]!);+ expect(chat.calls).toHaveLength(0);+ });+ });++ describe(`${label}: zero leakage to restricted grants`, () => {+ run('restricted grants never see question pages or answers on any read surface', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const grants = [+ { scopes: ['read', 'write'], sourceId: s.sourceId },+ { scopes: ['read'], sourceId: s.sourceId },+ ];+ for (const g of grants) {+ for (const [tool, params] of [+ ['search', { query: 'acme-example widgets leads' }],+ ['query', { query: QUESTION }],+ ['list_pages', { type: 'question' }],+ ['list_pages', {}],+ ['get_page', { slug }],+ ['get_page', { slug, fuzzy: true }],+ ['get_versions', { slug }],+ ['context_pack', { entities: ENTITY }],+ ['recall', { query: QUESTION }],+ ] as Array<[string, Record<string, unknown>]>) {+ const { text, result } = await mcp(engine, tool, params, g);+ const echoed = params.slug === slug;+ expect({ tool, leaked: text.includes(CANARY) || (!echoed && text.includes(slug)) || text.includes(QUESTION) || text.includes('pinned_questions') })+ .toEqual({ tool, leaked: false });+ if (tool === 'get_page') expect(result.isError).toBe(true);+ }+ for (const tool of ['questions_list', 'questions_status', 'questions_refresh', 'questions_unpin', 'questions_pin']) {+ const { result, body } = await mcp(engine, tool, { id: pinned.receipt.id, question: QUESTION }, g);+ expect({ tool, isError: result.isError, code: body.code }).toEqual({ tool, isError: true, code: 'question_owner_only' });+ expect(JSON.stringify(body)).not.toContain(CANARY);+ }+ }+ await setRemotePrivate(engine, true);+ try {+ const fenced = { scopes: ['read', 'write'], sourceId: s.sourceId, boundSlugPrefixes: ['notes/'] };+ const { body } = await mcp(engine, 'questions_status', { id: pinned.receipt.id }, fenced);+ expect(body.code).toBe('question_owner_only');+ const pack = await mcp(engine, 'context_pack', { entities: ENTITY }, fenced);+ expect(pack.text).not.toContain(CANARY);+ } finally { await setRemotePrivate(engine, false); }+ });++ run('answer text never enters pages, chunks, versions, history or export', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ await refreshQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id, full: true }, { chat: stubChat().fn });+ const like = `%${CANARY}%`;+ const [counts] = await engine.executeRaw<{ pages: number; chunks: number; versions: number }>(+ `SELECT (SELECT count(*)::int FROM pages WHERE compiled_truth LIKE $1 OR timeline LIKE $1 OR frontmatter::text LIKE $1) AS pages,+ (SELECT count(*)::int FROM content_chunks WHERE chunk_text LIKE $1) AS chunks,+ (SELECT count(*)::int FROM page_versions WHERE compiled_truth LIKE $1 OR frontmatter::text LIKE $1) AS versions`, [like]);+ expect(counts).toEqual({ pages: 0, chunks: 0, versions: 0 });+ const dir = mkdtempSync(join(tmpdir(), 'pq-export-'));+ try {+ await runExport(engine, ['--dir', dir, '--source', s.sourceId]);+ const files = walk(dir);+ expect(files.some(f => f.includes('questions'))).toBe(true);+ for (const f of files) expect(readFileSync(f, 'utf8')).not.toContain(CANARY);+ } finally { rmSync(dir, { recursive: true, force: true }); }+ });+ });++ describe(`${label}: read-time staleness (no cycle)`, () => {+ const cases: Array<{ name: string; needle: string; reason: string; mutate: (engine: BrainEngine, s: Seeded, slug: string) => Promise<void>; expiringInMs?: number }> = [+ { name: 'edited page', needle: 'notes/widget-plan', reason: 'page_changed', mutate: async (engine, s) =>+ putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan slipped to June.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan')) },+ { name: 'soft-deleted page', needle: 'notes/widget-plan', reason: 'page_deleted', mutate: async (engine, s) => {+ await submitPageMutation(localCtx(engine, s.sourceId), { operation: 'delete_page', params: { slug: 'notes/widget-plan', source_id: s.sourceId, expected_revision: await revisionOf(engine, s.sourceId, 'notes/widget-plan') } });+ } },+ { name: 'hard-deleted page (cascade)', needle: 'timeline people/alice-example', reason: 'timeline_missing', mutate: async (engine, s) => {+ await engine.executeRaw('DELETE FROM pages WHERE source_id = $1 AND slug = $2', [s.sourceId, 'people/alice-example']);+ } },+ { name: 'forgotten fact', needle: '40 employees', reason: 'fact_withdrawn', mutate: async (engine, s) => { await recordFactWithdrawal(engine, s.factId, s.sourceId); } },+ { name: 'fact expired by the clock alone', needle: 'widget sale', reason: 'fact_expired', expiringInMs: 2_500, mutate: async () => { await new Promise(r => setTimeout(r, 3_000)); } },+ { name: 'superseded fact', needle: '40 employees', reason: 'fact_superseded', mutate: async (engine, s) => {+ const [n] = await engine.executeRaw<{ id: string }>(`INSERT INTO facts (source_id, entity_slug, fact, kind, source, visibility, confidence, valid_from)+ VALUES ($1, $2, 'Acme example has 55 employees', 'fact', 'test', 'world', 1, now()) RETURNING id`, [s.sourceId, ENTITY]);+ await engine.executeRaw('UPDATE facts SET superseded_by = $2 WHERE id = $1', [s.factId, Number(n!.id)]);+ } },+ { name: 'page made private', needle: 'notes/widget-plan', reason: 'page_changed', mutate: async (engine, s) =>+ putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan for acme-example ships in March.', 'visibility: private\n'), await revisionOf(engine, s.sourceId, 'notes/widget-plan')) },+ { name: 'deactivated take', needle: 'take on people/alice-example', reason: 'take_inactive', mutate: async (engine, s) => { await engine.executeRaw('UPDATE takes SET active = false WHERE id = $1', [s.takeId]); } },+ { name: 'removed timeline entry', needle: 'timeline people/alice-example', reason: 'timeline_missing', mutate: async (engine, s) => { await engine.executeRaw('DELETE FROM timeline_entries WHERE id = $1', [s.timelineId]); } },+ ];+ for (const c of cases) {+ run(`${c.name} makes the dependent sentence stale on read, and context_pack withholds it`, async (engine) => {+ const s = await seedBrain(engine, { expiringInMs: c.expiringInMs });+ const pinned = await pin(engine, s);+ const before = sentence(pinned.receipt, c.needle);+ expect(before).toMatchObject({ stale: false });+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ await c.mutate(engine, s, slug);+ const notices: Array<{ code: string; kind: string; fix?: unknown }> = [];+ const after = await questionStatus({ ...localCtx(engine, s.sourceId), emitNotice: (n) => { notices.push(n); } }, { id: pinned.receipt.id });+ expect(after.freshness).toBe('stale');+ expect(notices).toMatchObject([{ code: 'pinned_answer_stale', kind: 'degraded' }]);+ expect(sentence(after, c.needle)).toMatchObject({ stale: true, reasons: [c.reason] });+ expect(after.next_action?.mcp?.tool).toBe('questions_refresh');+ const pack = await (await import('../../src/core/questions/service.ts')).pinnedAnswersForPack(localCtx(engine, s.sourceId), [ENTITY]);+ expect(pack?.withheld?.stale_sentences).toBe(after.sentences.stale);+ expect(JSON.stringify(pack?.pinned_questions ?? [])).not.toContain(before!.text);+ }, 30_000);+ }++ run('an owner edit to the question page becomes an owner claim, stale until the next refresh', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const edit = async (note: string) => {+ const snap = (await engine.readPageSnapshot(slug, { sourceId: s.sourceId }))!;+ const fm = Object.entries(snap.page.frontmatter as Record<string, unknown>).map(([k, v]) => `${k}: ${JSON.stringify(v)}`).join('\n');+ await putPage(engine, s.sourceId, slug, `---\n${fm}\ntitle: ${JSON.stringify(snap.page.title)}\ntype: question\n---\n# ${QUESTION}\n\n${note}\n`, snap.revision);+ };+ await edit('Acme example is moving widget production to Porto.');+ const viaRefresh = await refreshQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id }, { chat: stubChat().fn });+ const owner = viaRefresh.answer!.find(x => x.origin === 'owner');+ expect(owner).toMatchObject({ text: 'Acme example is moving widget production to Porto.', stale: false });+ await edit('Acme example moved widget production to Porto in May.');+ const after = await status(engine, s, pinned.receipt.id);+ expect(after.answer!.find(x => x.origin === 'owner')).toMatchObject({ stale: true, reasons: ['owner_edited'] });+ });+ });++ describe(`${label}: refresh protocol`, () => {+ run('refresh edits the previous answer for new evidence and recomputes after a deletion', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ await putPage(engine, s.sourceId, 'notes/widget-factory', page('note', 'Widget factory', 'acme-example opened a second widget factory led by Alice example.'));+ const chat = stubChat();+ const incremental = await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: chat.fn, leaseOwner: 't' });+ expect(incremental).toMatchObject({ status: 'published', mode: 'incremental' });+ expect(chat.calls[0]).toContain('Previous answer');+ await submitPageMutation(localCtx(engine, s.sourceId), { operation: 'delete_page', params: { slug: 'notes/widget-factory', source_id: s.sourceId, expected_revision: await revisionOf(engine, s.sourceId, 'notes/widget-factory') } });+ const full = await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: chat.fn, leaseOwner: 't' });+ expect(full).toMatchObject({ status: 'published', mode: 'full' });+ expect(chat.calls[1]).not.toContain('Previous answer');+ expect((await status(engine, s, pinned.receipt.id)).freshness).toBe('fresh');+ });++ run('a concurrent owner edit during refresh keeps the previous answer stale (revision revalidated at commit)', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ await putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in April.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan'));+ const outcome = await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: stubChat().fn, leaseOwner: 't', hooks: {+ beforeCommit: async () => putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in May.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan')),+ } });+ expect(outcome).toMatchObject({ status: 'conflict' });+ const after = await status(engine, s, pinned.receipt.id);+ expect(after).toMatchObject({ answer_revision: 1, freshness: 'stale', last_error: 'concurrent_change' });+ expect(sentence(after, 'notes/widget-plan')).toMatchObject({ stale: true });+ expect((await getPin(engine, s.sourceId, slug))!.lease_token).toBeNull();+ });++ run('duplicate workers: one holds the lease, the other reports in_progress, one publication lands', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const chat = stubChat();+ let release!: () => void;+ chat.gate = new Promise(r => { release = r; });+ const first = refreshPin(engine, s.sourceId, slug, { trigger: 'cycle', chat: chat.fn, leaseOwner: 'worker-a' });+ while (chat.calls.length === 0) await new Promise(r => setTimeout(r, 10));+ const second = await refreshPin(engine, s.sourceId, slug, { trigger: 'cycle', chat: stubChat().fn, leaseOwner: 'worker-b' });+ expect(second).toEqual({ status: 'in_progress' });+ expect((await status(engine, s, pinned.receipt.id)).freshness).toBe('refreshing');+ release();+ expect((await first).status).toBe('published');+ expect((await getPin(engine, s.sourceId, slug))!.answer_revision).toBe(2);+ });++ run('a crash between publication stages publishes nothing and keeps the previous answer', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const before = await getPin(engine, s.sourceId, slug);+ const outcome = await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: stubChat().fn, leaseOwner: 't', full: true, hooks: {+ betweenPublicationStages: () => { throw new Error('simulated crash after the answer update'); },+ } });+ expect(outcome).toMatchObject({ status: 'failed', error: 'refresh_failed:publish' });+ const after = (await getPin(engine, s.sourceId, slug))!;+ expect(after).toMatchObject({ answer_revision: before!.answer_revision, lease_token: null });+ expect(after.answer).toEqual(before!.answer);+ const [ev] = await engine.executeRaw<{ n: number; rev: number }>('SELECT count(*)::int AS n, max(answer_revision)::int AS rev FROM question_evidence WHERE question_id = $1', [after.id]);+ expect(ev).toMatchObject({ rev: 1 });+ expect(ev!.n).toBeGreaterThan(0);+ const r = await status(engine, s, pinned.receipt.id);+ expect(r).toMatchObject({ freshness: 'fresh', blocked_reason: 'refresh_failed' });+ expect(r.next_action?.mcp).toEqual({ tool: 'questions_refresh', arguments: { id: pinned.receipt.id, full: true } });+ });++ run("a crashed worker's lease is taken over only after it expires", async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ await engine.executeRaw(`UPDATE pinned_questions SET lease_token = 'dead', lease_owner = 'crashed', lease_expires_at = now() + interval '1 hour' WHERE source_id = $1 AND slug = $2`, [s.sourceId, slug]);+ expect((await refreshPin(engine, s.sourceId, slug, { trigger: 'cycle', chat: stubChat().fn, leaseOwner: 'w' })).status).toBe('in_progress');+ await engine.executeRaw(`UPDATE pinned_questions SET lease_expires_at = now() - interval '1 second' WHERE source_id = $1 AND slug = $2`, [s.sourceId, slug]);+ expect((await refreshPin(engine, s.sourceId, slug, { trigger: 'cycle', chat: stubChat().fn, leaseOwner: 'w' })).status).toBe('published');+ });++ run('a failed refresh keeps the previous answer with its stale flags; the next refresh recovers', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ await putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in July.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan'));+ const chat = stubChat();+ chat.fail = true;+ const failed = await refreshQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id }, { chat: chat.fn });+ expect(failed).toMatchObject({ freshness: 'stale', blocked_reason: 'refresh_failed', answer_revision: 1, refresh: { status: 'failed', error: 'refresh_failed:provider_error' } });+ expect(sentence(failed, 'notes/widget-plan')).toMatchObject({ stale: true });+ chat.fail = false;+ const recovered = await refreshQuestion(localCtx(engine, s.sourceId), { id: pinned.receipt.id, full: true }, { chat: chat.fn });+ expect(recovered).toMatchObject({ freshness: 'fresh', blocked_reason: null, answer_revision: 2, last_error: null });+ });++ run('question pages, synthesis pages and pages repeating a stored answer are never evidence', async (engine) => {+ const s = await seedBrain(engine);+ await putPage(engine, s.sourceId, 'synthesis/acme-widgets', page('synthesis', 'Acme widgets', 'acme-example widgets are built in Lisbon and Alice example leads it.'));+ await putPage(engine, s.sourceId, 'notes/retyped-question', page('question', 'Retyped', 'Where does acme-example build widgets? Alice example leads it.'));+ const pinned = await pin(engine, s);+ await putPage(engine, s.sourceId, 'notes/copied-answer', page('note', 'Copied', `${pinned.receipt.answer![0]!.text} acme-example widgets leads.`));+ const { slug } = parseQuestionId(pinned.receipt.id, 'default')!;+ const chat = stubChat();+ await refreshPin(engine, s.sourceId, slug, { trigger: 'manual', chat: chat.fn, leaseOwner: 't', full: true });+ const cited = (await engine.executeRaw<{ page_slug: string | null }>(+ 'SELECT DISTINCT page_slug FROM question_evidence WHERE question_id = (SELECT id FROM pinned_questions WHERE source_id = $1 AND slug = $2)', [s.sourceId, slug])).map(r => r.page_slug);+ for (const banned of ['synthesis/acme-widgets', 'notes/retyped-question', 'notes/copied-answer', slug]) expect(cited).not.toContain(banned);+ for (const banned of ['synthesis/acme-widgets', 'notes/retyped-question', 'notes/copied-answer']) expect(chat.calls.join('\n')).not.toContain(banned);+ });++ run('the first answer is a bounded wait: a slow model leaves awaiting_refresh and releases the lease', async (engine) => {+ const s = await seedBrain(engine);+ const chat = stubChat();+ chat.gate = new Promise(() => {});+ const slowFn: typeof chat.fn = (req) => Promise.race([chat.fn(req), new Promise<never>((_, rej) => req.signal?.addEventListener('abort', () => rej(new Error('aborted'))))]);+ const out = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY }, wait_ms: 200 }, { chat: slowFn });+ expect(out.receipt).toMatchObject({ freshness: 'awaiting_refresh', refresh: { status: 'timeout' } });+ expect(out.receipt.next_action?.mcp?.tool).toBe('questions_refresh');+ expect((await getPin(engine, s.sourceId, out.receipt.slug))!.lease_token).toBeNull();+ });+ });++ describe(`${label}: blocked states carry the next step`, () => {+ run('keyless: the pin is kept, awaiting_refresh, blocked no_model_key with the key fix', async (engine) => {+ const s = await seedBrain(engine);+ await withEnv({ ANTHROPIC_API_KEY: undefined, GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'pq-keyless-')) }, async () => {+ const out = await pinQuestion(localCtx(engine, s.sourceId), { question: QUESTION, scope: { entity: ENTITY } });+ expect(out.receipt).toMatchObject({ state: 'active', freshness: 'awaiting_refresh', blocked_reason: 'no_model_key', refresh: { status: 'blocked', blocked_reason: 'no_model_key' } });+ expect(out.receipt.next_action).toMatchObject({ argv: ['gbrain', 'providers', 'list'], actor: 'user', consent: ['credentials', 'paid'] });+ expect(out.receipt.next_action?.verify?.mcp).toEqual({ tool: 'questions_status', arguments: { id: out.receipt.id } });+ });+ });++ run('a spent budget blocks the refresh before any model call', async (engine) => {+ const s = await seedBrain(engine);+ await engine.setConfig('cycle.standing_questions.budget_usd', '0.000001');+ try {+ const chat = stubChat();+ const out = await pin(engine, s, chat);+ expect(out.receipt).toMatchObject({ freshness: 'awaiting_refresh', blocked_reason: 'budget_exhausted' });+ expect(out.receipt.next_action?.argv).toEqual(['gbrain', 'config', 'set', 'cycle.standing_questions.budget_usd', '<usd>']);+ expect(chat.calls).toHaveLength(0);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key = 'cycle.standing_questions.budget_usd'"); }+ });++ run('no worker: a stale answer with nothing scheduled says so; the cycle phase refreshes it and clears it', async (engine) => {+ await engine.executeRaw("DELETE FROM config WHERE key = 'cycle.standing_questions.last_run_at'");+ const s = await seedBrain(engine);+ await withEnv({ GBRAIN_HOME: mkdtempSync(join(tmpdir(), 'pq-noworker-')) }, async () => {+ const pinned = await pin(engine, s);+ await putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in August.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan'));+ const stale = await status(engine, s, pinned.receipt.id);+ expect(stale).toMatchObject({ freshness: 'stale', blocked_reason: 'no_worker' });+ expect(stale.next_action?.why).toContain('autopilot');+ await engine.executeRaw("UPDATE pinned_questions SET cooldown_days = 0 WHERE source_id = $1", [s.sourceId]);+ const phase = await runPhaseStandingQuestions(engine, { dryRun: false, chat: stubChat().fn });+ expect((phase.details as { refreshed: number }).refreshed).toBeGreaterThanOrEqual(1);+ expect(await status(engine, s, pinned.receipt.id)).toMatchObject({ freshness: 'fresh', blocked_reason: null });+ });+ });++ run('the cycle phase honors max_per_cycle and never refreshes inactive pins', async (engine) => {+ const s = await seedBrain(engine);+ const ctx = localCtx(engine, s.sourceId);+ for (const q of ['Who leads acme-example?', 'Where are acme-example widgets built?', 'When does the widget plan ship?']) {+ await pinQuestion(ctx, { question: q, defer: true }, { chat: stubChat().fn });+ }+ await engine.executeRaw(`UPDATE pinned_questions SET state = 'inactive', inactive_reason = 'awaiting_consent' WHERE source_id = $1 AND question LIKE 'When%'`, [s.sourceId]);+ await engine.executeRaw(`UPDATE pinned_questions SET state = 'archived' WHERE source_id <> $1`, [s.sourceId]);+ await engine.setConfig('cycle.standing_questions.max_per_cycle', '1');+ try {+ const chat = stubChat();+ const phase = await runPhaseStandingQuestions(engine, { dryRun: false, chat: chat.fn });+ expect(phase.details).toMatchObject({ candidates: 2, refreshed: 1 });+ expect(chat.calls).toHaveLength(1);+ } finally { await engine.executeRaw("DELETE FROM config WHERE key = 'cycle.standing_questions.max_per_cycle'"); }+ });+ });++ describe(`${label}: operator journeys over MCP`, () => {+ const preapprovedHome = () => {+ const home = mkdtempSync(join(tmpdir(), 'pq-home-'));+ mkdirSync(join(home, '.gbrain'), { recursive: true });+ writeFileSync(join(home, '.gbrain', 'config.json'), JSON.stringify({ engine: 'pglite', consent: { preapprove: { paid: { max_usd_per_run: 2 } } } }));+ return home;+ };++ run('MCP-only: pin under a paid preapproval, then refresh, with no shell', async (engine) => {+ const s = await seedBrain(engine);+ await setRemotePrivate(engine, true);+ const calls = { calls: 0, fail: false };+ __setChatTransportForTests(stubTransport(calls));+ try {+ await withEnv({ GBRAIN_HOME: preapprovedHome() }, async () => {+ const grant = { scopes: ['read', 'write'], sourceId: s.sourceId };+ const pinned = (await mcp(engine, 'questions_pin', { question: QUESTION, scope: { entity: ENTITY } }, grant)).body as unknown as Pinned;+ expect(pinned.receipt).toMatchObject({ state: 'active', freshness: 'fresh', page_materialized: false });+ expect(calls.calls).toBe(1);+ await putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in September.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan'));+ const stale = await mcp(engine, 'questions_status', { id: pinned.receipt.id }, grant);+ expect(stale.body).toMatchObject({ freshness: 'stale' });+ const refreshed = await mcp(engine, 'questions_refresh', { id: pinned.receipt.id }, grant);+ expect(refreshed.body).toMatchObject({ freshness: 'fresh', refresh: { status: 'published' } });+ const pack = await mcp(engine, 'context_pack', { entities: ENTITY }, grant);+ expect((pack.body.pinned_questions as Array<{ id: string }>)?.[0]?.id).toBe(pinned.receipt.id);+ });+ } finally {+ __setChatTransportForTests(null);+ await setRemotePrivate(engine, false);+ }+ });++ run('a read-only connection lists and reads but cannot mutate', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ await setRemotePrivate(engine, true);+ try {+ const grant = { scopes: ['read'], sourceId: s.sourceId };+ const listed = await mcp(engine, 'questions_list', {}, grant);+ expect(listed.result.isError).toBeFalsy();+ expect((listed.body.questions as QuestionReceipt[]).map(q => q.id)).toEqual([pinned.receipt.id]);+ expect((listed.body.counts as Record<string, number>).total).toBe(1);+ expect((await mcp(engine, 'questions_status', { id: pinned.receipt.id }, grant)).body).toMatchObject({ freshness: 'fresh' });+ for (const op of ['questions_pin', 'questions_refresh', 'questions_unpin']) expect(operationScopesAllowed(['read'], operationsByName[op]!)).toBe(false);+ for (const op of ['questions_list', 'questions_status']) expect(operationScopesAllowed(['read'], operationsByName[op]!)).toBe(true);+ } finally { await setRemotePrivate(engine, false); }+ });++ run('a failed refresh is recovered over MCP by running its next_action', async (engine) => {+ const s = await seedBrain(engine);+ const pinned = await pin(engine, s);+ await setRemotePrivate(engine, true);+ const calls = { calls: 0, fail: true };+ __setChatTransportForTests(stubTransport(calls));+ try {+ const grant = { scopes: ['read', 'write'], sourceId: s.sourceId };+ await putPage(engine, s.sourceId, 'notes/widget-plan', page('note', 'Widget plan', 'The widget plan ships in October.'), await revisionOf(engine, s.sourceId, 'notes/widget-plan'));+ const failed = (await mcp(engine, 'questions_refresh', { id: pinned.receipt.id }, grant)).body as unknown as QuestionReceipt;+ expect(failed).toMatchObject({ blocked_reason: 'refresh_failed', freshness: 'stale' });+ calls.fail = false;+ const next = failed.next_action!.mcp!;+ const recovered = (await mcp(engine, next.tool, next.arguments, grant)).body as unknown as QuestionReceipt;+ expect(recovered).toMatchObject({ freshness: 'fresh', blocked_reason: null, refresh: { status: 'published', mode: 'full' } });+ } finally {+ __setChatTransportForTests(null);+ await setRemotePrivate(engine, false);+ }+ });+ });++ describe(`${label}: dream.auto_think migration`, () => {+ const keys = ['dream.auto_think.enabled', 'dream.auto_think.questions', 'dream.auto_think.max_per_cycle', 'dream.auto_think.auto_commit',+ 'dream.auto_think.budget', 'dream.auto_think.cooldown_days', 'dream.auto_think.model', 'models.auto_think', 'dream.auto_think.allow_unpriced',+ 'cycle.standing_questions.max_per_cycle', 'cycle.standing_questions.budget_usd', 'cycle.standing_questions.allow_unpriced'];+ const reset = async (engine: BrainEngine) => {+ for (const k of keys) await engine.executeRaw('DELETE FROM config WHERE key = $1', [k]);+ await engine.executeRaw(`DELETE FROM pinned_questions WHERE origin = 'auto_think'`);+ };+ const migrated = (engine: BrainEngine) => engine.executeRaw<{ question: string; state: string; inactive_reason: string | null; publish_mode: string; model: string | null; cooldown_days: number }>(+ `SELECT question, state, inactive_reason, publish_mode, model, cooldown_days FROM pinned_questions WHERE origin = 'auto_think' ORDER BY question`);++ run('maps all seven keys without creating consent, makes no model call, and is idempotent', async (engine) => {+ const calls = { calls: 0, fail: false };+ __setChatTransportForTests(stubTransport(calls));+ try {+ await reset(engine);+ await engine.setConfig('dream.auto_think.questions', JSON.stringify(['Who leads acme-example?', 'who leads acme-example?', 'Who leads acme-example?', 'What changed this week?']));+ await engine.setConfig('dream.auto_think.enabled', 'false');+ await engine.setConfig('dream.auto_think.budget', '3.5');+ await engine.setConfig('dream.auto_think.cooldown_days', '7');+ await engine.setConfig('dream.auto_think.max_per_cycle', '2');+ await engine.setConfig('models.auto_think', 'anthropic:claude-opus-4-7');+ await engine.setConfig('dream.auto_think.allow_unpriced', 'true');+ const report = await migrateAutoThinkToPins(engine);+ expect(report).toMatchObject({ questions: 2, inserted: 2, state: 'inactive', publish_mode: 'draft' });+ const rows = await migrated(engine);+ expect(rows.map(r => r.question)).toEqual(['What changed this week?', 'Who leads acme-example?']);+ expect(rows.every(r => r.state === 'inactive' && r.inactive_reason === 'migrated_disabled' && r.publish_mode === 'draft'+ && r.model === 'anthropic:claude-opus-4-7' && Number(r.cooldown_days) === 7)).toBe(true);+ expect(await engine.getConfig('cycle.standing_questions.max_per_cycle')).toBe('2');+ expect(await engine.getConfig('cycle.standing_questions.budget_usd')).toBe('3.5');+ expect(await engine.getConfig('cycle.standing_questions.allow_unpriced')).toBe('true');+ expect((await migrateAutoThinkToPins(engine)).inserted).toBe(0);+ expect(await migrated(engine)).toHaveLength(2);+ expect(calls.calls).toBe(0);+ const chat = stubChat();+ await runPhaseStandingQuestions(engine, { dryRun: false, chat: chat.fn });+ expect(chat.calls.filter(c => c.includes('What changed this week?'))).toHaveLength(0);+ } finally { __setChatTransportForTests(null); await reset(engine); }+ });++ run('enabled with a zero budget imports inactive; enabled with auto_commit imports active and published', async (engine) => {+ try {+ await reset(engine);+ await engine.setConfig('dream.auto_think.questions', JSON.stringify(['Who leads acme-example?']));+ await engine.setConfig('dream.auto_think.enabled', 'true');+ await engine.setConfig('dream.auto_think.budget', '0');+ expect(await migrateAutoThinkToPins(engine)).toMatchObject({ state: 'inactive' });+ expect((await migrated(engine))[0]).toMatchObject({ inactive_reason: 'migrated_zero_budget' });+ expect(await engine.getConfig('cycle.standing_questions.budget_usd')).toBeNull();+ await reset(engine);+ await engine.setConfig('dream.auto_think.questions', JSON.stringify(['Who leads acme-example?']));+ await engine.setConfig('dream.auto_think.enabled', 'true');+ await engine.setConfig('dream.auto_think.auto_commit', 'true');+ expect(await migrateAutoThinkToPins(engine)).toMatchObject({ state: 'active', publish_mode: 'publish' });+ expect((await migrated(engine))[0]).toMatchObject({ state: 'active', publish_mode: 'publish', inactive_reason: null, cooldown_days: 30 });+ expect(questionSlug('Who leads acme-example?', { source: 'default' })).toMatch(/^questions\/who-leads-acme-example-[0-9a-f]{8}$/);+ } finally { await reset(engine); }+ });+ });+}diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex 2061aa6796..926973c11c 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -38,6 +38,8 @@ import { disposePersistenceConsumer } from '../src/core/persistence/service.ts';import type { ChatOpts, ChatResult } from '../src/core/ai/gateway.ts';import { configureGateway, resetGateway, __setChatTransportForTests, __setEmbedTransportForTests } from '../src/core/ai/gateway.ts';import { isolatedPersistencePostgres } from './helpers/persistence-postgres.ts';+import { getPin, insertPin } from '../src/core/questions/store.ts';+import { questionSlug } from '../src/core/questions/identity.ts';import { withEnv } from './helpers/with-env.ts';import { testBackends } from './helpers/test-backends.ts';@@ -281,6 +283,22 @@ const MATRIX: Record<CyclePhase, Entry> = {expect((await engine.getPage(slug!, { sourceId: 'default' }))?.compiled_truth).toContain('DRIFTED — notes/drift-example');},},+ standing_questions: {+ config: { 'models.standing_questions': 'anthropic:claude-sonnet-4-6' },+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'companies/acme-example', page('company', 'Acme', 'Acme example builds widgets in Lisbon.'));+ const scope = { source: sourceId, entity: 'companies/acme-example' };+ const question = 'Where does acme-example build widgets?';+ await insertPin(engine, { sourceId, slug: questionSlug(question, scope), question, scope, state: 'active', inactiveReason: null, publishMode: 'publish', createdBy: 'cli' });+ },+ reply: () => JSON.stringify({ sentences: [{ text: 'Acme example builds widgets in Lisbon.', cite: ['E1'] }], gaps: [] }),+ assert: async ({ engine, sourceId, result }) => {+ const slug = questionSlug('Where does acme-example build widgets?', { source: sourceId, entity: 'companies/acme-example' });+ expect(result.details).toMatchObject({ refreshed: 1 });+ expect(await committed(engine, sourceId, slug)).not.toHaveLength(0);+ expect((await getPin(engine, sourceId, slug))?.answer.map(s => s.text)).toEqual(['Acme example builds widgets in Lisbon.']);+ },+ },edge_contradictions: {config: { 'dream.edge_contradictions.mode': 'apply', 'models.dream.edge_contradictions': 'anthropic:claude-sonnet-4-6' },seed: async ({ engine, sourceId }) => {diff --git a/test/pinned-questions-safety.test.ts b/test/pinned-questions-safety.test.tsnew file mode 100644index 0000000000..7fd941edd0--- /dev/null+++ b/test/pinned-questions-safety.test.ts@@ -0,0 +1,31 @@+/**+ * Pinned questions (C4) on PGLite: the B5 offline safety gate, operator+ * journeys and the dream.auto_think migration. Scenarios live in+ * test/helpers/pinned-questions-scenarios.ts and also run on live Postgres+ * (test/e2e/pinned-questions-postgres.test.ts). Stub model; no network.+ */+import { afterAll, beforeAll } from 'bun:test';+import { mkdtempSync, rmSync } from 'node:fs';+import { tmpdir } from 'node:os';+import { join } from 'node:path';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { registerPinnedQuestionSuite } from './helpers/pinned-questions-scenarios.ts';++let engine: PGLiteEngine;+const home = mkdtempSync(join(tmpdir(), 'pq-safety-home-'));+const priorHome = process.env.GBRAIN_HOME;++beforeAll(async () => {+ process.env.GBRAIN_HOME = home;+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+}, 120_000);++afterAll(async () => {+ await engine?.disconnect();+ if (priorHome === undefined) delete process.env.GBRAIN_HOME; else process.env.GBRAIN_HOME = priorHome;+ rmSync(home, { recursive: true, force: true });+}, 60_000);++registerPinnedQuestionSuite('pglite', () => engine);