Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
chronicle: one eligibility function, shared confinement predicate, default-on config (#5876)
garrytanc3422cb38d8f
diff --git a/src/core/chronicle/backstop.ts b/src/core/chronicle/backstop.tsdeleted file mode 100644index 2a739ca1a7..0000000000--- a/src/core/chronicle/backstop.ts+++ /dev/null@@ -1,38 +0,0 @@-// v0.42.x — Life Chronicle (#2390) put_page chronicle backstop (Phase A.3).-// Deterministic + fire-and-forget: it ONLY checks eligibility + the auto_chronicle-// flag and enqueues a `chronicle_extract` minion job. The LLM judgment runs off-// the write path in the job handler. Mirrors facts/backstop.ts (queue mode).-import type { BrainEngine } from '../engine.ts';-import { isChronicleEligible } from './eligibility.ts';-import { isAutoChronicleEnabled } from './config.ts';--export interface ChronicleBackstopResult {- enqueued: boolean;- skipped?: string;-}--/**- * Eligibility + enqueue. The CALLER is responsible for the trust gate and for- * only invoking on a real import (status==='imported') — see the put_page hook,- * which skips on remote/untrusted and on skipped/unchanged rewrites so an edit- * that changes nothing never re-enqueues.- */-export async function runChronicleBackstop(- page: { slug: string; type: string; compiled_truth?: string; frontmatter?: Record<string, unknown> },- ctx: { engine: BrainEngine; sourceId: string },-): Promise<ChronicleBackstopResult> {- const dreamGenerated = page.frontmatter?.dream_generated === true;- const elig = isChronicleEligible({- type: page.type, slug: page.slug, body: page.compiled_truth, dreamGenerated,- });- if (!elig.ok) return { enqueued: false, skipped: elig.reason };- if (!(await isAutoChronicleEnabled(ctx.engine))) return { enqueued: false, skipped: 'auto_chronicle_off' };- try {- const { MinionQueue } = await import('../minions/queue.ts');- const queue = new MinionQueue(ctx.engine);- await queue.add('chronicle_extract', { slug: page.slug, sourceId: ctx.sourceId });- return { enqueued: true };- } catch {- return { enqueued: false, skipped: 'enqueue_error' };- }-}diff --git a/src/core/chronicle/config.ts b/src/core/chronicle/config.tsindex 1df538efa7..98f66d61b3 100644--- a/src/core/chronicle/config.ts+++ b/src/core/chronicle/config.ts@@ -1,15 +1,65 @@// v0.42.x — Life Chronicle (#2390) config flags.import type { BrainEngine } from '../engine.ts';+import { CHRONICLE_CONFIG, CHRONICLE_DEFAULTS } from './contract.ts';++const TRUE_WORDS = ['true', '1', 'yes', 'on'];+const FALSE_WORDS = ['false', '0', 'no', 'off'];/**- * Auto-emit is OFF by default (plan D5.5: spend posture — extraction spends LLM- * tokens per eligible write). The only caller is the unwired backstop, so the- * setting currently has no effect; advisor and doctor `auto_chronicle` say so (#5876).+ * Automatic extraction is ON by default (#5876, the standing default-on rule):+ * one paid judge call per new or changed meeting, conversation or calendar+ * page, bounded by the daily limit, the recency window and the per-page cap.+ * Opt out with `gbrain config set auto_chronicle false`. A value outside the+ * known true/false words reads as off (doctor warns `auto_chronicle_invalid`).*/export async function isAutoChronicleEnabled(engine: BrainEngine): Promise<boolean> {- const val = await engine.getConfig('auto_chronicle');- if (val == null) return false; // default OFF- return ['true', '1', 'yes', 'on'].includes(val.trim().toLowerCase());+ return autoChronicleSetting(await engine.getConfig(CHRONICLE_CONFIG.enabled)) === 'on';+}++/** How a stored `auto_chronicle` value reads: unset is on; an unknown word is off and invalid. */+export function autoChronicleSetting(raw: string | null | undefined): 'on' | 'off' | 'invalid' {+ if (raw == null) return 'on';+ const v = raw.trim().toLowerCase();+ if (TRUE_WORDS.includes(v)) return 'on';+ if (FALSE_WORDS.includes(v)) return 'off';+ return 'invalid';+}++export interface ChronicleSettings {+ jobBudgetUsd: number;+ /** The operator set chronicle.job_budget_usd (an unpriced model then refuses instead of running uncapped). */+ explicitBudget: boolean;+ dailyLimit: number;+ recentDays: number;+ settleSeconds: number;+ /** When the automatic path activated on this brain; revisions decided earlier are history. */+ activatedAt: Date | null;+}++function positiveNumber(raw: string | null, fallback: number, integer: boolean): number {+ if (raw == null) return fallback;+ const n = Number(raw.trim());+ if (!Number.isFinite(n) || n <= 0 || (integer && !Number.isInteger(n))) return fallback;+ return n;+}++/** Numeric knobs; a malformed stored value falls back to its default (doctor warns). */+export async function chronicleSettings(engine: BrainEngine): Promise<ChronicleSettings> {+ const get = (key: string) => engine.getConfig(key).catch(() => null);+ const [budget, limit, recent, settle, activated] = await Promise.all([+ get(CHRONICLE_CONFIG.jobBudgetUsd), get(CHRONICLE_CONFIG.dailyLimit), get(CHRONICLE_CONFIG.recentDays),+ get(CHRONICLE_CONFIG.settleSeconds), get(CHRONICLE_CONFIG.activatedAt),+ ]);+ const jobBudgetUsd = positiveNumber(budget, CHRONICLE_DEFAULTS.jobBudgetUsd, false);+ const activatedAt = activated ? new Date(activated) : null;+ return {+ jobBudgetUsd,+ explicitBudget: budget != null && jobBudgetUsd === Number(budget.trim()),+ dailyLimit: positiveNumber(limit, CHRONICLE_DEFAULTS.dailyLimit, true),+ recentDays: positiveNumber(recent, CHRONICLE_DEFAULTS.recentDays, true),+ settleSeconds: settle != null && settle.trim() === '0' ? 0 : positiveNumber(settle, CHRONICLE_DEFAULTS.settleSeconds, true),+ activatedAt: activatedAt && !Number.isNaN(activatedAt.getTime()) ? activatedAt : null,+ };}/** Pinned timezone for the when→date projection cast (plan: default UTC). */diff --git a/src/core/chronicle/eligibility.ts b/src/core/chronicle/eligibility.tsindex fdf06292a9..c578c3b76d 100644--- a/src/core/chronicle/eligibility.ts+++ b/src/core/chronicle/eligibility.ts@@ -3,22 +3,81 @@// emits timeline events) when it is conversation-shape, NOT dream-generated,// and NOT a diary/event page. Diary interiority is NEVER mined into events// (privacy/consent — plan D5.4); event pages are already the output (anti-loop).+//+// #5876: the one eligibility function. The write decision, the `chronicle`+// phase and `chronicle-backfill` all call it; time rules (recency, invite+// end, settle window) apply only when the caller passes the policy for them.import type { PageType } from '../types.ts';-export type ChronicleEligibility = { ok: true } | { ok: false; reason: string };+export type ChronicleEligibility =+ | { ok: true }+ | { ok: false; reason: string }+ /** Transient: the same content becomes eligible at `until` without an edit. */+ | { ok: false; reason: 'not_yet_happened' | 'settling'; wait: true; until: Date };const ELIGIBLE_TYPES: PageType[] = ['meeting', 'conversation', 'calendar-event'];// Directory rescue: a meetings/… page that frontmatter-typed itself 'note' is// still conversation-shape. life/diary excluded explicitly below.-const RESCUE_SLUG_PREFIXES = ['meetings/', 'conversations/', 'cal/', 'calendar/'] as const;+export const RESCUE_SLUG_PREFIXES = ['meetings/', 'conversations/', 'cal/', 'calendar/'] as const;+export const CHRONICLE_TYPES: readonly PageType[] = ELIGIBLE_TYPES;const MIN_BODY_CHARS = 80;+/** Effective-date sources that are not authored: an undated import's stable anchor. */+const UNAUTHORED_DATE_SOURCES = new Set(['fallback']);-export function isChronicleEligible(input: {+export interface ChronicleEligibilityInput {type: PageType;slug: string;body?: string;dreamGenerated?: boolean;-}): ChronicleEligibility {+ /** pages.effective_date and pages.effective_date_source (E11: only an authored source dates the page). */+ effectiveDate?: Date | string | null;+ effectiveDateSource?: string | null;+ /** Page frontmatter: `date`, `start` and `end` date the page when effective_date does not. */+ frontmatter?: Record<string, unknown> | null;+ /** When the content was decided or last changed (settle window). */+ changedAt?: Date | string | null;+}++export interface ChronicleTimePolicy {+ now: Date;+ /** C14: pages dated before now - recentDays skip `history`. null = no recency rule (backfill). */+ recentDays: number | null;+ /** D4: content changed less than this many seconds ago waits. null = no settle rule. */+ settleSeconds?: number | null;+}++/** A meeting, conversation or calendar page by type or directory; the only pages a receipt or ledger row mentions. */+export function isChronicleShaped(type: string, slug: string): boolean {+ if (type === 'diary' || slug.startsWith('life/diary/') || type === 'event' || slug.startsWith('life/events/')+ || slug.startsWith('wiki/agents/')) return false;+ return (ELIGIBLE_TYPES as string[]).includes(type) || RESCUE_SLUG_PREFIXES.some((p) => slug.startsWith(p));+}++function toDate(value: unknown): Date | null {+ if (value instanceof Date) return Number.isNaN(value.getTime()) ? null : value;+ if (typeof value !== 'string' || !value.trim()) return null;+ const d = new Date(value);+ return Number.isNaN(d.getTime()) ? null : d;+}++/** The page's own date: an authored effective_date, else frontmatter `date`/`start`. null = undated. */+export function chroniclePageDate(input: Pick<ChronicleEligibilityInput, 'effectiveDate' | 'effectiveDateSource' | 'frontmatter'>): Date | null {+ const authored = input.effectiveDateSource != null && !UNAUTHORED_DATE_SOURCES.has(input.effectiveDateSource);+ if (authored) {+ const d = toDate(input.effectiveDate);+ if (d) return d;+ }+ const fm = input.frontmatter ?? {};+ return toDate(fm.date) ?? toDate(fm.start);+}++/** C13: the meeting's end (else start) when the page declares one. */+function meetingEnd(fm: Record<string, unknown> | null | undefined): Date | null {+ if (!fm) return null;+ return toDate(fm.end) ?? toDate(fm.start);+}++export function isChronicleEligible(input: ChronicleEligibilityInput, policy?: ChronicleTimePolicy): ChronicleEligibility {const { type, slug } = input;if (input.dreamGenerated === true) return { ok: false, reason: 'dream_generated' };// Diary: never extract events from private interiority. Event: anti-loop.@@ -30,5 +89,18 @@ export function isChronicleEligible(input: {const typeOk = ELIGIBLE_TYPES.includes(type);const slugOk = RESCUE_SLUG_PREFIXES.some((p) => slug.startsWith(p));if (!typeOk && !slugOk) return { ok: false, reason: `kind:${type}` };+ if (!policy) return { ok: true };+ const end = meetingEnd(input.frontmatter);+ if (end && end.getTime() > policy.now.getTime()) return { ok: false, reason: 'not_yet_happened', wait: true, until: end };+ if (policy.recentDays !== null) {+ const dated = chroniclePageDate(input);+ if (dated && dated.getTime() < policy.now.getTime() - policy.recentDays * 86_400_000) return { ok: false, reason: 'history' };+ }+ if (policy.settleSeconds != null && policy.settleSeconds > 0) {+ const changed = toDate(input.changedAt);+ if (changed && policy.now.getTime() - changed.getTime() < policy.settleSeconds * 1000) {+ return { ok: false, reason: 'settling', wait: true, until: new Date(changed.getTime() + policy.settleSeconds * 1000) };+ }+ }return { ok: true };}diff --git a/src/core/persistence/derived-extraction-gate.ts b/src/core/persistence/derived-extraction-gate.tsnew file mode 100644index 0000000000..c7e11c0a29--- /dev/null+++ b/src/core/persistence/derived-extraction-gate.ts@@ -0,0 +1,15 @@+import type { WriteAuthority } from './model.ts';++/**+ * The writer confinement rule for paid derived extraction (facts backstop and+ * Life Chronicle events), shared so the two can never drift: a confined writer+ * (slug-bound, delegated or restricted namespace) never triggers it, and an+ * operation-bound grant needs `extract_facts`, the existing derived-extraction+ * permission. null = the writer may trigger extraction.+ */+export function derivedExtractionSkip(authority: Pick<WriteAuthority, 'restrictedNamespace' | 'delegated' | 'slugPrefixes' | 'operations'>):+ 'slug_bound_client' | 'operation_bound_client' | null {+ if (authority.restrictedNamespace || authority.delegated || authority.slugPrefixes != null) return 'slug_bound_client';+ if (authority.operations != null && !authority.operations.includes('extract_facts')) return 'operation_bound_client';+ return null;+}diff --git a/src/core/persistence/effect-facts.ts b/src/core/persistence/effect-facts.tsindex 310497c54a..ecd93bdc44 100644--- a/src/core/persistence/effect-facts.ts+++ b/src/core/persistence/effect-facts.ts@@ -7,13 +7,14 @@ import { OperationError } from '../ops/contract.ts';import { authorizeStoredRequest, authorizeWrite } from './authority.ts';import { completeEffect } from './effect-journal.ts';import { guardEffectSource } from './effect-recovery.ts';+import { derivedExtractionSkip } from './derived-extraction-gate.ts';import type { PersistenceEffect } from './effect-model.ts';import type { WriteRequest } from './model.ts';export type FactsBackstopStatus = { queued: true } | { skipped: string };export async function authorizeFactsBackstop(engine: BrainEngine, row: WriteRequest, lock = false): Promise<void> {- if (row.authority.restrictedNamespace || row.authority.delegated || row.authority.slugPrefixes != null) {+ if (derivedExtractionSkip(row.authority) === 'slug_bound_client') {throw new OperationError('permission_denied', 'A confined writer cannot extract into unnamed entity pages.');}await authorizeStoredRequest(engine, row, lock);@@ -30,8 +31,8 @@ export async function authorizeFactsBackstop(engine: BrainEngine, row: WriteRequ/** Provider availability belongs to the durable job's execution process. */export async function prepareFactsBackstop(engine: BrainEngine, row: WriteRequest, page: ParsedPage): Promise<FactsBackstopStatus> {- if (row.authority.restrictedNamespace || row.authority.delegated || row.authority.slugPrefixes != null) return { skipped: 'slug_bound_client' };- if (row.authority.operations != null && !row.authority.operations.includes('extract_facts')) return { skipped: 'operation_bound_client' };+ const confined = derivedExtractionSkip(row.authority);+ if (confined) return { skipped: confined };if (!(await isFactsExtractionEnabled(engine))) return { skipped: 'extraction_disabled' };const eligible = isFactsBackstopEligible(row.slug, page);if (!eligible.ok) return { skipped: eligible.reason };