Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
W7 slice 1: take_horizons (private horizon per take), stated-horizon scan, gbrain takes horizon
garrytan164feeb11e42
diff --git a/docs/designs/FORECAST_JOURNAL.md b/docs/designs/FORECAST_JOURNAL.mdnew file mode 100644index 0000000000..3c5982543c--- /dev/null+++ b/docs/designs/FORECAST_JOURNAL.md@@ -0,0 +1,64 @@+# Private forecast journal (wave 4b W7)++Status: in progress (draft PR). Plan: gbrain-evals `docs/plans/2026-10-07-10x-memory-advantage/PLAN.md`, wave 4, row W7.++W7 makes each prediction in a brain auditable for its owner: what was predicted, when, by when it had to come true, how it was resolved and on what evidence, and how many predictions are still open. It extends `takes_scorecard` and `gbrain takes scorecard` instead of adding a `track_record` op. Everything new is private, which means trusted local only. `takes_scorecard` keeps returning exactly what it returns today to remote callers. Nothing public about real people ships from this wave.++## Slice 1 (this change): the horizon++The horizon of a take is the last day its claim can come true: `2024-12-31` for "by the end of 2024", `2024-09-30` for "by Q3 2024". Without it, the journal cannot tell a prediction that is overdue from one that is still open.++**Where it lives.** It goes in a table of its own, `take_horizons`, one row per take (migration v250 for now; the number is taken when the merge slot is called). It does not go in either of the two obvious places:++- **The takes fence.** Changing the fence format would make sync hold files. Garry's decision is an additive DB column, not a fence-format change.+- **A column on `takes`.** `takes_list` and `takes_search` return `t.*`, so a new column would reach remote callers. That would break the rule that remote output stays the same, and it would leak a private field.++| Column | Type | Meaning |+|---|---|---|+| `take_id` | `BIGINT PRIMARY KEY REFERENCES takes(id) ON DELETE CASCADE` | The take. The row is deleted when its take is. |+| `claim_sha256` | `TEXT NOT NULL` | The sha256 of the claim the horizon was set for. If the claim is later edited, the row stays as written but reads as not current, so a horizon never carries over to a different proposition. |+| `horizon_date` | `DATE NOT NULL` | The last day the claim can come true. |+| `basis` | `TEXT NOT NULL`, one of `stated`, `stated_relative`, `owner` | How the horizon was set (see below). |+| `set_at` | `TIMESTAMPTZ NOT NULL DEFAULT now()` | When it was set. |++The three bases:++- `stated` is an absolute deadline in the claim's own words: "by the end of 2024", "by the end of Q1 2025", "by Q3 2024", "by March 2025", "before 2025", "by 2026".+- `stated_relative` is "within N months" or "within N years", counted from `since_date`. It is only as certain as `since_date`. On a source without recording, that date is the uncertified one, and the journal labels it `uncertified` (Garry, 2026-10-17).+- `owner` is set by the owner. A scan never overwrites it.++**No page text is stored.** The table holds dates, an enum, a hash and a timestamp. That keeps it outside the purge surface (`text_free_ledger` in the deletion inventory). Graduation copies it as user data. Postgres's RLS event trigger covers it.++**Nothing is written on upgrade.**++- `gbrain takes horizon scan` lists each take's stated horizon. It writes them only with `--apply`.+- `gbrain takes horizon set <slug> --row N --date YYYY-MM-DD` and `clear` are the owner's own edits.+- None of these has an MCP op. A thin client refuses them as host-bound.+- The parser returns nothing in three cases: when a claim states no deadline, when it states two different deadlines, or when it states a relative deadline without a usable `since_date`. It does not guess.++**What stays the same.** `takes_list` and `takes_scorecard` return byte-identical output, locally and to remote callers, whether or not horizons exist. Tests on PGLite and Postgres check this.++## Next slices (same PR, before it leaves draft)++1. **Prediction time.** On sources with recording, the time a take was first recorded comes from the belief ledger (the first `take.asserted` event for its claim) and is certified. Elsewhere it falls back to `since_date`, labelled `uncertified` wherever it shows.+2. **The journal view.** `gbrain takes journal` (trusted local) shows every prediction with:+ - its prediction time and certification;+ - its exact claim;+ - its horizon and basis;+ - its state: open, overdue (past the horizon and unresolved) or resolved;+ - its resolution and provenance: `resolved_by`, `resolved_source`, and the grade verdict when one is cached;+ - the denominator of unresolved predictions.+3. **`takes_scorecard {group_by}`.** `group_by` is `holder` or `source`. The new fields go only to trusted local callers:+ - Beta-shrunk accuracy;+ - Brier skill score against the holder's base rate;+ - recency decay;+ - citations;+ - `min_n` with a `low_n` flag;+ - cohort uncertainty.+ A remote caller gets today's output byte for byte. A remote caller that passes `group_by` gets a typed refusal, so it is never silently ignored. N6-style probes check both.+4. **Gate ($0, synthetic).**+ - Synthetic holders of known skill should give Spearman ρ ≥ 0.8 at n ≥ 10. This is a diagnostic.+ - "Who was right about T" is measured as set-F1.+ - Remote probes should show no access to the journal fields and byte-identical existing output.++The resolution policy for auto-resolve is out of W7's scope. Garry's decision (2026-10-16) is recorded with the take-grading follow-ups in gbrain-evals: a take whose numeric target was missed is never auto-applied, neither as `partial` nor as `incorrect`. It is held for manual review until the real sample settles which.diff --git a/src/commands/takes.ts b/src/commands/takes.tsindex 39661df8c4..9b34ba389b 100644--- a/src/commands/takes.ts+++ b/src/commands/takes.ts@@ -497,6 +497,10 @@ Subcommands:Aggregate calibration scorecard (v0.30.0)takes calibration [<holder>] [--bucket-size 0.1] [--json]Calibration curve binned by stated weight (v0.30.0)+ takes horizon scan [--apply] [--source-id <id>] [--json]+ Preview (or write) each take's stated deadline (W7, private)+ takes horizon set <slug> --row N --date YYYY-MM-DD | clear <slug> --row N+ Set or clear a take's horizon as the ownerCommon flags:--dir <path> Verify the configured canonical directory for mutations@@ -526,6 +530,7 @@ Common flags:// #2411: `takes propose` used to fall through to the slug path and print// "No takes on propose." — the LLM proposal queue had no drain surface.case 'propose': return cmdPropose(engine, rest, await resolveTakesSourceId(engine));+ case 'horizon': return cmdHorizon(engine, rest);case 'scorecard': return cmdScorecard(engine, rest);case 'calibration': return cmdCalibration(engine, rest);case 'revisit': return cmdRevisit(engine, rest);@@ -728,3 +733,55 @@ async function cmdRevisit(_engine: BrainEngine, rest: string[]): Promise<void> {}void execFileSync;}++/**+ * W7: the stated horizon of each take (`scan`, preview-first) and the+ * owner's own horizon (`set`, `clear`), in the private `take_horizons`+ * table (src/core/takes-horizon.ts). Trusted local only: there is no MCP op,+ * so a thin client refuses it.+ */+async function cmdHorizon(engine: BrainEngine, args: string[]): Promise<void> {+ const usage = 'Usage: gbrain takes horizon scan [--apply] [--source-id <id>] [--json]\n' ++ ' gbrain takes horizon set <slug> --row N --date YYYY-MM-DD [--source-id <id>]\n' ++ ' gbrain takes horizon clear <slug> --row N [--source-id <id>]';+ const fail = (message: string): never => { process.stderr.write(`${message}\n`); process.exit(1); };+ const { scanStatedHorizons, setTakeHorizon, clearTakeHorizon } = await import('../core/takes-horizon.ts');+ const [sub, ...rest] = args;+ const json = flagPresent(rest, '--json');++ if (sub === 'scan') {+ const apply = flagPresent(rest, '--apply');+ const sourceId = flagValue(rest, '--source-id');+ const scan = await scanStatedHorizons(engine, { apply, ...(sourceId ? { sourceId } : {}) });+ if (json) {+ console.log(JSON.stringify({ applied: apply, ...scan }, null, 2));+ return;+ }+ for (const p of scan.proposed) console.log(` take ${p.take_id}: ${p.horizon_date} (${p.basis}, "${p.phrase}")${p.replaces ? ` replaces ${p.replaces}` : ''} ${p.claim}`);+ const tail = `${scan.kept_owner} owner horizon(s) kept, ${scan.unparsed} take(s) state no single deadline.`;+ if (apply) console.log(`Wrote ${scan.written} stated horizon(s). ${tail}`);+ else console.log(`${scan.proposed.length} stated horizon(s) to write. ${tail}${scan.proposed.length ? ' Write them with: gbrain takes horizon scan --apply' : ''}`);+ return;+ }++ if (sub !== 'set' && sub !== 'clear') fail(usage);+ const slug = rest[0] && !rest[0].startsWith('-') ? rest[0] : fail(usage);+ const rowRaw = flagValue(rest, '--row');+ const row = rowRaw === undefined ? NaN : Number(rowRaw);+ if (!Number.isSafeInteger(row) || row < 1) fail(`--row requires the take's row number (a positive integer), e.g. --row 1.\n${usage}`);+ const sourceId = await resolveSourceId(engine, flagValue(rest, '--source-id') ?? null);+ const [take] = await engine.executeRaw<{ id: number | string }>(+ `SELECT t.id FROM takes t JOIN pages p ON p.id = t.page_id+ WHERE p.source_id = $1 AND p.slug = $2 AND t.row_num = $3 AND p.deleted_at IS NULL`,+ [sourceId, slug, row]);+ if (!take) fail(`No take ${slug}#${row} on source ${sourceId}. List the page's takes with: gbrain takes ${slug}`);+ const takeId = Number(take!.id);++ if (sub === 'set') {+ const date = flagValue(rest, '--date') ?? fail(`--date YYYY-MM-DD is required.\n${usage}`);+ await setTakeHorizon(engine, takeId, date, 'owner').catch((e: Error) => fail(e.message));+ console.log(`Set the horizon of ${slug}#${row} to ${date} (owner).`);+ return;+ }+ console.log(await clearTakeHorizon(engine, takeId) ? `Cleared the horizon of ${slug}#${row}.` : `${slug}#${row} had no horizon.`);+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 202a749a73..29aa1c2d87 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -130,7 +130,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'storage': ['--brain', '--fix', '--help', '--json', '--plan', '--repo', '--restore-only', '--source', '--to'],'sweep': ['--accept-pending', '--apply', '--assign-corpus', '--background', '--batch-limit', '--brain', '--budget-ms', '--delete-brain', '--explain', '--follow', '--help', '--home', '--json', '--no-accept-pending', '--no-delegate', '--once', '--only', '--progress-interval', '--progress-json', '--quiet', '--retry-failed', '--session', '--source', '--timeout', '--wait'],'sync': ['--abbrev-ref', '--accept-pending', '--account', '--acknowledge-managed', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--allow-empty', '--apply', '--apply-rewrites', '--assign-corpus', '--audit', '--auto', '--background', '--batch-size', '--brain', '--branch', '--break-lock', '--budget-ms', '--by-mention', '--cached', '--catch-up', '--client', '--concurrency', '--confirm-destructive', '--confirm-quiesced', '--confirm-relocated-root', '--conflicts', '--contacts-dir', '--content-audit', '--count', '--db-url', '--delete-brain', '--depth', '--detach', '--detail', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--empty', '--enable', '--exclude', '--exclude-standard', '--expect', '--expected-epoch', '--expected-revision', '--expected-state', '--explain', '--facts', '--fast', '--ff-only', '--filters', '--first-parent', '--fix', '--follow', '--force', '--force-break-lock', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from-meetings', '--full', '--full-history', '--git-dir', '--git-path', '--group-by', '--hard-deadline', '--harness', '--held', '--help', '--home', '--http', '--id', '--images', '--include-ambiguous', '--include-flagged', '--include-frontmatter', '--include-gitignored', '--include-hidden', '--include-null-signature', '--include-repairs', '--index-audit', '--infer-dates', '--install', '--interval', '--is-ancestor', '--is-shallow-repository', '--json', '--kind', '--lanes', '--lang', '--left-right', '--link-source', '--link-type', '--locks', '--log-noop', '--manifest', '--markdown', '--max-age', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-sources', '--max-usd', '--migrate-legacy', '--migrate-only', '--missing-path', '--multimodal', '--name', '--name-only', '--name-status', '--ner', '--no-accept-pending', '--no-auto-embed', '--no-autopilot-install', '--no-bulk', '--no-capture', '--no-delegate', '--no-embed', '--no-extract', '--no-gpg-sign', '--no-hard-deadline', '--no-lanes', '--no-llm', '--no-pull', '--no-renames', '--no-repair', '--no-schema-pack', '--no-verify', '--once', '--only', '--operations', '--others', '--oversized', '--overwrite', '--pace', '--pace-max-concurrency', '--pack', '--page', '--parallel', '--params', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--plan', '--porcelain', '--prefer', '--prefer-postgres', '--preview', '--priority', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--providers', '--prune-orphans', '--query', '--question', '--queue', '--quiet', '--reauth', '--rebuild', '--refresh', '--regenerate', '--remediate', '--remediation-plan', '--remove', '--remove-core', '--replace', '--repo', '--request-id', '--reset', '--reset-checkpoint', '--reset-default', '--restore-only', '--resume', '--retry-failed', '--retry-held', '--reverse', '--scope', '--scopes', '--self-transfer', '--serial', '--short', '--show-current', '--show-toplevel', '--since', '--skills-dir', '--skip', '--skip-failed', '--slot', '--slug', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--stale', '--state', '--status', '--stdin', '--strategy', '--supabase', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--tier', '--timeout', '--to', '--token', '--top-k', '--type', '--url', '--url-env', '--user', '--verbose', '--verify', '--version', '--wait', '--watch', '--window', '--workers', '--working-tree', '--yes'],- 'takes': ['--accept', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],+ 'takes': ['--accept', '--apply', '--batch-size', '--before', '--brain', '--bucket-size', '--by', '--claim', '--date', '--dim', '--dir', '--domain', '--dry-run', '--embedding-dimensions', '--embedding-model', '--evidence', '--expected-revision', '--expired', '--force', '--from-pages', '--help', '--holder', '--include-covered', '--json', '--kind', '--limit', '--max-pages', '--no-embed', '--no-embedding', '--offset', '--outcome', '--path', '--quality', '--reject', '--request-id', '--row', '--semantic', '--since', '--sort', '--source', '--source-id', '--stale', '--status', '--supabase', '--to', '--unit', '--until', '--value', '--weight', '--who', '--yes'],'think': ['--anchor', '--brain', '--calibration-holder', '--help', '--json', '--mcp-only', '--model', '--only', '--reference-date', '--rounds', '--save', '--since', '--source', '--take', '--until', '--with-calibration'],'transcripts': ['--accept-pending', '--all', '--all-discovery', '--apply', '--background', '--brain', '--days', '--dry-run', '--embed', '--explain', '--facts', '--follow', '--format', '--full', '--help', '--include-self', '--json', '--limit', '--max-bytes', '--max-cost-usd', '--no-accept-pending', '--only', '--progress-interval', '--progress-json', '--purge', '--quiet', '--since', '--source', '--source-id', '--timeout', '--wait'],'trust': ['--accept-all', '--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--db-url', '--dry-run', '--expect', '--explain', '--follow', '--from', '--help', '--http', '--json', '--kind', '--no-accept-pending', '--only', '--path', '--progress-interval', '--progress-json', '--quiet', '--reason', '--reason-family', '--relower', '--remove', '--repair-unknown-markers', '--resume', '--since', '--slug', '--source', '--source-id', '--timeout', '--undo', '--uri-prefix', '--version', '--wait', '--yes'],diff --git a/src/core/deletion-inventory.ts b/src/core/deletion-inventory.tsindex f191646755..1eade52ff0 100644--- a/src/core/deletion-inventory.ts+++ b/src/core/deletion-inventory.ts@@ -162,6 +162,7 @@ const ROWS: readonly Row[] = [['subagent_tool_executions', 'out_of_scope', 'probed_reported', 'tool_use_id tool_name input status output error provider_id', 'input output'],['tags', 'out_of_scope', 'no_memory_text', 'tag tag_source'],['take_domain_assignments', 'out_of_scope', 'no_memory_text', 'domain pack source'],+ ['take_horizons', 'out_of_scope', 'text_free_ledger', 'claim_sha256 basis'],['take_grade_cache', 'out_of_scope', 'probed_reported', 'prompt_version judge_model_id evidence_signature wave_version verdict', 'verdict'],['take_nudge_log', 'out_of_scope', 'no_memory_text', 'source_id nudge_pattern channel wave_version'],['take_proposals', 'swept', 'take_proposals', 'source_id page_slug content_hash prompt_version wave_version proposal_run_id status claim_text kind holder domain dedup_against_fence_rows model_id acted_by'],diff --git a/src/core/persistence/graduation-inventory.ts b/src/core/persistence/graduation-inventory.tsindex c0798be5d0..2c044fa3e5 100644--- a/src/core/persistence/graduation-inventory.ts+++ b/src/core/persistence/graduation-inventory.ts@@ -173,6 +173,7 @@ export const GRADUATION_INVENTORY: Inventory = {carry('synthesis_evidence', 'user_data', 'Synthesis citations.'),carry('tags', 'user_data', 'Page tags.'),carry('take_domain_assignments', 'user_data', 'Take domain assignments.'),+ carry('take_horizons', 'user_data', 'Forecast horizons per take, owner-set or from the stated-horizon scan.'),carry('take_grade_cache', 'operational', 'Paid take grading cache; rebuilding spends money.'),carry('take_nudge_log', 'operational', 'Take nudge log.'),carry('take_proposals', 'user_data', 'Take proposals and their status.'),diff --git a/src/core/schema-migrations/latest.generated.ts b/src/core/schema-migrations/latest.generated.tsindex 762ad27cf7..a37b519c57 100644--- a/src/core/schema-migrations/latest.generated.ts+++ b/src/core/schema-migrations/latest.generated.ts@@ -4,4 +4,4 @@// The highest schema migration version (migrate.ts LATEST_VERSION), importable without// loading the migrations themselves.-export const LATEST_SCHEMA_VERSION = 249;+export const LATEST_SCHEMA_VERSION = 250;diff --git a/src/core/schema-migrations/registry.generated.ts b/src/core/schema-migrations/registry.generated.tsindex 36013d21b3..4de8e6dccb 100644--- a/src/core/schema-migrations/registry.generated.ts+++ b/src/core/schema-migrations/registry.generated.ts@@ -250,6 +250,7 @@ import { v246 } from './v246-page-embedding-budget.ts';import { v247 } from './v247-page-extraction-state.ts';import { v248 } from './v248-segmented-page-storage.ts';import { v249 } from './v249-belief-ledger.ts';+import { v250 } from './v250-take-horizons.ts';// Array order is historical (see HISTORICAL_ARRAY_ORDER in the generator); the// runner sorts by version before applying.@@ -498,4 +499,5 @@ export const MIGRATIONS: Migration[] = [v247,v248,v249,+ v250,];diff --git a/src/core/schema-migrations/v250-take-horizons.ts b/src/core/schema-migrations/v250-take-horizons.tsnew file mode 100644index 0000000000..c746d0ed6a--- /dev/null+++ b/src/core/schema-migrations/v250-take-horizons.ts@@ -0,0 +1,29 @@+import type { Migration } from './types.ts';++// Applied by src/core/migrate.ts on the next initSchema(). Migration-only, like+// the other tables that reference takes (takes itself is created by v37).+//+// W7 (wave 4b), the private forecast journal: the horizon of a take (the+// last day its claim can come true), one row per take+// (src/core/takes-horizon.ts). A table of its own rather than a column on+// takes, because takes_list and takes_search return t.*, and a new column+// would reach remote callers. claim_sha256 binds the row to the claim it was+// set for; an edited claim reads the row as not current. Rows go with their+// take (ON DELETE CASCADE). Dates, an enum, a hash and a timestamp only: no+// page text. DDL only, nothing to backfill: horizons come from an explicit,+// preview-first scan or the owner.+export const v250: Migration = {+ version: 250,+ name: 'take_horizons',+ idempotent: true,+ sql: `+ CREATE TABLE IF NOT EXISTS take_horizons (+ take_id BIGINT PRIMARY KEY REFERENCES takes(id) ON DELETE CASCADE,+ claim_sha256 TEXT NOT NULL,+ horizon_date DATE NOT NULL,+ basis TEXT NOT NULL CHECK (basis IN ('stated','stated_relative','owner')),+ set_at TIMESTAMPTZ NOT NULL DEFAULT now()+ );+ CREATE INDEX IF NOT EXISTS take_horizons_date_idx ON take_horizons (horizon_date);+ `,+};diff --git a/src/core/takes-horizon.ts b/src/core/takes-horizon.tsnew file mode 100644index 0000000000..c63191f951--- /dev/null+++ b/src/core/takes-horizon.ts@@ -0,0 +1,150 @@+/**+ * W7 (wave 4b): the forecast horizon of a take, the last day its claim can+ * come true. Stored in `take_horizons`, one row per take, never in the takes+ * fence (a fence-format change would hold files) and never as a column on+ * `takes` (takes_list and takes_search return `t.*`, so a new column would+ * reach remote callers). The journal is private: only trusted local code+ * reads or writes it, and no MCP op exposes it.+ *+ * A row records the sha256 of the claim it was set for. When the claim is+ * edited the row stays as written but reads as not current, so a horizon+ * never silently carries over to a different proposition. Rows go with+ * their take (ON DELETE CASCADE). Nothing is written on upgrade: the stated+ * horizons come from an explicit, preview-first scan.+ *+ * Bases:+ * - `stated`: an absolute deadline in the claim's own words ("by the end of+ * 2024", "by Q3 2024", "by March 2025", "before 2025", "by 2026");+ * - `stated_relative`: "within N months|years", counted from since_date, so it+ * is only as certain as since_date;+ * - `owner`: set by the owner (`gbrain takes horizon set`); a scan never+ * overwrites it.+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from './engine.ts';++export type HorizonBasis = 'stated' | 'stated_relative' | 'owner';+const BASES: ReadonlySet<string> = new Set(['stated', 'stated_relative', 'owner']);++export interface StatedHorizon { date: string; basis: 'stated' | 'stated_relative'; phrase: string }+export interface TakeHorizon { take_id: number; horizon_date: string; basis: HorizonBasis; set_at: string; current: boolean }+export interface HorizonProposal { take_id: number; claim: string; horizon_date: string; basis: 'stated' | 'stated_relative'; phrase: string; replaces: string | null }+export interface HorizonScan { proposed: HorizonProposal[]; written: number; kept_owner: number; unparsed: number }++const MONTHS = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december'];+const ISO_DAY = /^\d{4}-\d{2}-\d{2}$/;+const YEAR = '(20\\d{2})';++const claimSha = (claim: string) => createHash('sha256').update(claim).digest('hex');+const iso = (d: Date) => d.toISOString().slice(0, 10);+const endOfMonth = (year: number, monthIndex: number) => iso(new Date(Date.UTC(year, monthIndex + 1, 0)));++function validDay(s: string): boolean {+ if (!ISO_DAY.test(s)) return false;+ const d = new Date(`${s}T00:00:00Z`);+ return !Number.isNaN(d.getTime()) && iso(d) === s;+}++function addMonths(since: string, n: number): string {+ const d = new Date(`${since}T00:00:00Z`);+ const day = d.getUTCDate();+ const target = new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + n, 1));+ const last = new Date(Date.UTC(target.getUTCFullYear(), target.getUTCMonth() + 1, 0)).getUTCDate();+ target.setUTCDate(Math.min(day, last));+ return iso(target);+}++const PATTERNS: Array<{ re: RegExp; date: (m: RegExpExecArray, since: string | null) => string | null; basis: 'stated' | 'stated_relative' }> = [+ { re: new RegExp(`\\bby (?:the )?end of q([1-4]) ${YEAR}\\b`, 'gi'), date: m => endOfMonth(Number(m[2]), Number(m[1]) * 3 - 1), basis: 'stated' },+ { re: new RegExp(`\\bby (?:the )?end of ${YEAR}\\b`, 'gi'), date: m => `${m[1]}-12-31`, basis: 'stated' },+ { re: new RegExp(`\\bby q([1-4]) ${YEAR}\\b`, 'gi'), date: m => endOfMonth(Number(m[2]), Number(m[1]) * 3 - 1), basis: 'stated' },+ { re: new RegExp(`\\bby (${MONTHS.join('|')}) ${YEAR}\\b`, 'gi'), date: m => endOfMonth(Number(m[2]), MONTHS.indexOf(m[1]!.toLowerCase())), basis: 'stated' },+ { re: new RegExp(`\\bbefore ${YEAR}\\b`, 'gi'), date: m => `${Number(m[1]) - 1}-12-31`, basis: 'stated' },+ { re: new RegExp(`\\bby ${YEAR}\\b(?![,.]?\\d)`, 'gi'), date: m => `${m[1]}-12-31`, basis: 'stated' },+ { re: /\bwithin (\d{1,3}) (months?|years?)\b/gi, date: (m, since) => since && validDay(since) ? addMonths(since, Number(m[1]) * (m[2]!.toLowerCase().startsWith('year') ? 12 : 1)) : null, basis: 'stated_relative' },+];++/**+ * The deadline a claim states in its own words, or null when it states none,+ * states two different ones, or states a relative one without a usable+ * since_date (YYYY-MM-DD).+ */+export function parseStatedHorizon(claim: string, sinceDate: string | null): StatedHorizon | null {+ let text = claim;+ const found: StatedHorizon[] = [];+ let unusable = false;+ for (const p of PATTERNS) {+ p.re.lastIndex = 0;+ for (let m = p.re.exec(text); m; m = p.re.exec(text)) {+ const date = p.date(m, sinceDate);+ if (date === null) unusable = true;+ else found.push({ date, basis: p.basis, phrase: m[0] });+ }+ text = text.replace(p.re, ' '.repeat(1));+ }+ if (unusable || found.length === 0) return null;+ return new Set(found.map(f => f.date)).size === 1 ? found[0]! : null;+}++/** Set (or replace) a take's horizon. Throws on an unknown take, a malformed date or an unknown basis. */+export async function setTakeHorizon(engine: BrainEngine, takeId: number, date: string, basis: HorizonBasis): Promise<void> {+ if (!validDay(date)) throw new Error(`horizon date "${date}" is not a calendar day in YYYY-MM-DD form`);+ if (!BASES.has(basis)) throw new Error(`unknown horizon basis "${basis}" (expected stated, stated_relative or owner)`);+ const [take] = await engine.executeRaw<{ claim: string }>('SELECT claim FROM takes WHERE id = $1', [takeId]);+ if (!take) throw new Error(`take ${takeId} not found`);+ await engine.executeRaw(+ `INSERT INTO take_horizons (take_id, claim_sha256, horizon_date, basis, set_at)+ VALUES ($1, $2, $3::date, $4, now())+ ON CONFLICT (take_id) DO UPDATE SET claim_sha256 = EXCLUDED.claim_sha256, horizon_date = EXCLUDED.horizon_date,+ basis = EXCLUDED.basis, set_at = EXCLUDED.set_at`,+ [takeId, claimSha(take.claim), date, basis]);+}++/** Remove a take's horizon; true when one existed. */+export async function clearTakeHorizon(engine: BrainEngine, takeId: number): Promise<boolean> {+ const rows = await engine.executeRaw<{ take_id: number }>('DELETE FROM take_horizons WHERE take_id = $1 RETURNING take_id', [takeId]);+ return rows.length > 0;+}++/** Horizons by take id (all, or only the given takes); `current` is false when the claim changed since the horizon was set. */+export async function readTakeHorizons(engine: BrainEngine, takeIds?: readonly number[]): Promise<Map<number, TakeHorizon>> {+ const rows = await engine.executeRaw<{ take_id: number | string; horizon_date: string; basis: HorizonBasis; set_at: string | Date; claim_sha256: string; claim: string }>(+ `SELECT h.take_id, h.horizon_date::text AS horizon_date, h.basis, h.set_at, h.claim_sha256, t.claim+ FROM take_horizons h JOIN takes t ON t.id = h.take_id+ WHERE ($1::bigint[] IS NULL OR h.take_id = ANY($1::bigint[]))`,+ [takeIds ? takeIds.map(Number) : null]);+ return new Map(rows.map(r => [Number(r.take_id), {+ take_id: Number(r.take_id), horizon_date: r.horizon_date, basis: r.basis,+ set_at: r.set_at instanceof Date ? r.set_at.toISOString() : String(r.set_at), current: claimSha(r.claim) === r.claim_sha256,+ }]));+}++/**+ * Propose the stated horizon of every take on a live page whose claim states+ * one and that has no current horizon with the same date; with `apply`, write+ * them. Owner-set horizons are kept as they are.+ */+export async function scanStatedHorizons(engine: BrainEngine, opts: { apply: boolean; sourceId?: string }): Promise<HorizonScan> {+ const rows = await engine.executeRaw<{ id: number | string; claim: string; since_date: string | null; basis: HorizonBasis | null; claim_sha256: string | null; horizon_date: string | null }>(+ `SELECT t.id, t.claim, t.since_date, h.basis, h.claim_sha256, h.horizon_date::text AS horizon_date+ FROM takes t JOIN pages p ON p.id = t.page_id LEFT JOIN take_horizons h ON h.take_id = t.id+ WHERE p.deleted_at IS NULL AND ($1::text IS NULL OR p.source_id = $1)+ ORDER BY t.id`,+ [opts.sourceId ?? null]);+ const scan: HorizonScan = { proposed: [], written: 0, kept_owner: 0, unparsed: 0 };+ for (const r of rows) {+ if (r.basis === 'owner') { scan.kept_owner++; continue; }+ const stated = parseStatedHorizon(r.claim, r.since_date);+ if (!stated) { scan.unparsed++; continue; }+ const current = r.claim_sha256 === claimSha(r.claim);+ if (current && r.horizon_date === stated.date && r.basis === stated.basis) continue;+ scan.proposed.push({ take_id: Number(r.id), claim: r.claim, horizon_date: stated.date, basis: stated.basis, phrase: stated.phrase, replaces: r.horizon_date });+ }+ if (opts.apply) {+ for (const p of scan.proposed) {+ await setTakeHorizon(engine, p.take_id, p.horizon_date, p.basis);+ scan.written++;+ }+ }+ return scan;+}diff --git a/test/e2e/takes-horizon-postgres.test.ts b/test/e2e/takes-horizon-postgres.test.tsnew file mode 100644index 0000000000..c0d821abfc--- /dev/null+++ b/test/e2e/takes-horizon-postgres.test.ts@@ -0,0 +1,71 @@+/**+ * W7 on Postgres: the take_horizons store behaves as on PGLite+ * (test/takes-horizon.test.ts). Protects: the DATE round trip as YYYY-MM-DD+ * text, the bigint[] filter, the cascade from takes, the claim-hash staleness+ * check, the preview-first scan, and byte-identical takes_list /+ * takes_scorecard output for local and remote callers with horizons present.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { getEngine, hasDatabase, setupDB, teardownDB } from './helpers.ts';+import type { OperationContext } from '../../src/core/ops/contract.ts';+import { operations } from '../../src/core/operations.ts';+import { clearTakeHorizon, readTakeHorizons, scanStatedHorizons, setTakeHorizon } from '../../src/core/takes-horizon.ts';++const RUN = hasDatabase();+const d = RUN ? describe : describe.skip;+const op = (name: string) => operations.find(o => o.name === name)!;+const ctx = (remote: boolean) => ({ engine: getEngine(), config: { engine: 'postgres' }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote, sourceId: 'default',+ ...(remote ? { auth: { token: 't', clientId: 'c1', scopes: ['read'], sourceId: 'default' } } : {}) }) as unknown as OperationContext;++async function takeOn(slug: string, claim: string, since: string): Promise<number> {+ const engine = getEngine();+ const existing = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);+ if (!existing.length) await engine.putPage(slug, { type: 'company', title: slug, compiled_truth: `${slug} test page.` });+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);+ await engine.addTakesBatch([{ page_id: page!.id, row_num: 1, claim, kind: 'bet', holder: 'world', weight: 0.7, since_date: since }]);+ const [take] = await engine.executeRaw<{ id: number | string }>('SELECT id FROM takes WHERE page_id = $1 AND row_num = 1', [page!.id]);+ return Number(take!.id);+}++beforeAll(async () => { if (RUN) await setupDB(); });+afterAll(async () => { if (RUN) await teardownDB(); });++d('take_horizons on Postgres (W7)', () => {+ test('set, read, stale on claim edit, clear, cascade', async () => {+ const engine = getEngine();+ const a = await takeOn('companies/acme-example', 'Acme-example will reach $5M ARR by the end of 2024', '2023-02-01');+ await setTakeHorizon(engine, a, '2024-12-31', 'owner');+ expect((await readTakeHorizons(engine, [a])).get(a)).toMatchObject({ take_id: a, horizon_date: '2024-12-31', basis: 'owner', current: true });+ await takeOn('companies/acme-example', 'Acme-example will reach $8M ARR by the end of 2025', '2023-02-01');+ expect((await readTakeHorizons(engine, [a])).get(a)).toMatchObject({ horizon_date: '2024-12-31', current: false });+ expect(await clearTakeHorizon(engine, a)).toBe(true);+ expect(await clearTakeHorizon(engine, a)).toBe(false);+ await setTakeHorizon(engine, a, '2025-12-31', 'stated');+ await engine.executeRaw('DELETE FROM takes WHERE id = $1', [a]);+ const [row] = await engine.executeRaw<{ n: number }>('SELECT count(*)::int AS n FROM take_horizons WHERE take_id = $1', [a]);+ expect(row!.n).toBe(0);+ });++ test('scan is preview-first, keeps owner horizons, and the journal stays private', async () => {+ const engine = getEngine();+ const b = await takeOn('companies/bluefin-example', 'Bluefin-example will open a Berlin office within 18 months', '2023-02-10');+ const c = await takeOn('companies/cobalt-example', 'Cobalt-example will ship its API by Q3 2024', '2023-01-15');+ await setTakeHorizon(engine, c, '2024-10-31', 'owner');+ const snapshot = async () => JSON.stringify(await Promise.all([+ op('takes_list').handler(ctx(false), {}), op('takes_list').handler(ctx(true), {}),+ op('takes_scorecard').handler(ctx(false), {}), op('takes_scorecard').handler(ctx(true), {}),+ ]));+ const before = await snapshot();+ const preview = await scanStatedHorizons(engine, { apply: false });+ expect(preview.written).toBe(0);+ expect(preview.proposed.find(p => p.take_id === b)).toMatchObject({ horizon_date: '2024-08-10', basis: 'stated_relative' });+ expect(preview.proposed.some(p => p.take_id === c)).toBe(false);+ expect((await readTakeHorizons(engine, [b])).size).toBe(0);+ const applied = await scanStatedHorizons(engine, { apply: true });+ expect(applied.written).toBe(preview.proposed.length);+ expect((await readTakeHorizons(engine, [b, c])).get(c)).toMatchObject({ horizon_date: '2024-10-31', basis: 'owner' });+ const after = await snapshot();+ expect(after).toBe(before);+ expect(after).not.toContain('horizon');+ });+});diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-default.json b/test/fixtures/goldens/catalog/postgres-engine-init-default.jsonindex 0cff47f751..e37ad7d43e 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-default.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-default.json@@ -418,6 +418,9 @@"take_domain_assignments.take_domain_assignments_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_grade_cache.take_grade_cache_pkey": "p PRIMARY KEY (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache.take_grade_cache_verdict_check": "c CHECK ((verdict = ANY (ARRAY['correct'::text, 'incorrect'::text, 'partial'::text, 'unresolvable'::text])))",+ "take_horizons.take_horizons_basis_check": "c CHECK ((basis = ANY (ARRAY['stated'::text, 'stated_relative'::text, 'owner'::text])))",+ "take_horizons.take_horizons_pkey": "p PRIMARY KEY (take_id)",+ "take_horizons.take_horizons_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_pkey": "p PRIMARY KEY (id)","take_nudge_log.take_nudge_log_proposal_id_fkey": "f FOREIGN KEY (proposal_id) REFERENCES take_proposals(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -919,6 +922,9 @@"take_grade_cache": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "take_horizons": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"take_nudge_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1363,6 +1369,8 @@"take_grade_cache_applied_idx": "CREATE INDEX take_grade_cache_applied_idx ON public.take_grade_cache USING btree (take_id, applied)","take_grade_cache_pkey": "CREATE UNIQUE INDEX take_grade_cache_pkey ON public.take_grade_cache USING btree (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache_wave_idx": "CREATE INDEX take_grade_cache_wave_idx ON public.take_grade_cache USING btree (wave_version, graded_at DESC)",+ "take_horizons_date_idx": "CREATE INDEX take_horizons_date_idx ON public.take_horizons USING btree (horizon_date)",+ "take_horizons_pkey": "CREATE UNIQUE INDEX take_horizons_pkey ON public.take_horizons USING btree (take_id)","take_nudge_log_pkey": "CREATE UNIQUE INDEX take_nudge_log_pkey ON public.take_nudge_log USING btree (id)","take_nudge_log_proposal_cooldown_idx": "CREATE INDEX take_nudge_log_proposal_cooldown_idx ON public.take_nudge_log USING btree (proposal_id, nudge_pattern, fired_at DESC) WHERE (proposal_id IS NOT NULL)","take_nudge_log_take_cooldown_idx": "CREATE INDEX take_nudge_log_take_cooldown_idx ON public.take_nudge_log USING btree (take_id, nudge_pattern, fired_at DESC) WHERE (take_id IS NOT NULL)",@@ -3673,6 +3681,16 @@],"flags": "relkind=r rls=true force_rls=false"},+ "take_horizons": {+ "columns": [+ "1 take_id bigint/int8 NOT NULL",+ "2 claim_sha256 text/text NOT NULL",+ "3 horizon_date date/date NOT NULL",+ "4 basis text/text NOT NULL",+ "5 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"take_nudge_log": {"columns": ["1 id bigint/int8 NOT NULL DEFAULT nextval('take_nudge_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.jsonindex ee7ab297f3..174f2d836f 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-fts-portuguese.json@@ -418,6 +418,9 @@"take_domain_assignments.take_domain_assignments_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_grade_cache.take_grade_cache_pkey": "p PRIMARY KEY (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache.take_grade_cache_verdict_check": "c CHECK ((verdict = ANY (ARRAY['correct'::text, 'incorrect'::text, 'partial'::text, 'unresolvable'::text])))",+ "take_horizons.take_horizons_basis_check": "c CHECK ((basis = ANY (ARRAY['stated'::text, 'stated_relative'::text, 'owner'::text])))",+ "take_horizons.take_horizons_pkey": "p PRIMARY KEY (take_id)",+ "take_horizons.take_horizons_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_pkey": "p PRIMARY KEY (id)","take_nudge_log.take_nudge_log_proposal_id_fkey": "f FOREIGN KEY (proposal_id) REFERENCES take_proposals(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -919,6 +922,9 @@"take_grade_cache": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "take_horizons": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"take_nudge_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1363,6 +1369,8 @@"take_grade_cache_applied_idx": "CREATE INDEX take_grade_cache_applied_idx ON public.take_grade_cache USING btree (take_id, applied)","take_grade_cache_pkey": "CREATE UNIQUE INDEX take_grade_cache_pkey ON public.take_grade_cache USING btree (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache_wave_idx": "CREATE INDEX take_grade_cache_wave_idx ON public.take_grade_cache USING btree (wave_version, graded_at DESC)",+ "take_horizons_date_idx": "CREATE INDEX take_horizons_date_idx ON public.take_horizons USING btree (horizon_date)",+ "take_horizons_pkey": "CREATE UNIQUE INDEX take_horizons_pkey ON public.take_horizons USING btree (take_id)","take_nudge_log_pkey": "CREATE UNIQUE INDEX take_nudge_log_pkey ON public.take_nudge_log USING btree (id)","take_nudge_log_proposal_cooldown_idx": "CREATE INDEX take_nudge_log_proposal_cooldown_idx ON public.take_nudge_log USING btree (proposal_id, nudge_pattern, fired_at DESC) WHERE (proposal_id IS NOT NULL)","take_nudge_log_take_cooldown_idx": "CREATE INDEX take_nudge_log_take_cooldown_idx ON public.take_nudge_log USING btree (take_id, nudge_pattern, fired_at DESC) WHERE (take_id IS NOT NULL)",@@ -3673,6 +3681,16 @@],"flags": "relkind=r rls=true force_rls=false"},+ "take_horizons": {+ "columns": [+ "1 take_id bigint/int8 NOT NULL",+ "2 claim_sha256 text/text NOT NULL",+ "3 horizon_date date/date NOT NULL",+ "4 basis text/text NOT NULL",+ "5 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"take_nudge_log": {"columns": ["1 id bigint/int8 NOT NULL DEFAULT nextval('take_nudge_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.jsonindex a8277151c5..8332bdf261 100644--- a/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json+++ b/test/fixtures/goldens/catalog/postgres-engine-init-high-dims.json@@ -418,6 +418,9 @@"take_domain_assignments.take_domain_assignments_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_grade_cache.take_grade_cache_pkey": "p PRIMARY KEY (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache.take_grade_cache_verdict_check": "c CHECK ((verdict = ANY (ARRAY['correct'::text, 'incorrect'::text, 'partial'::text, 'unresolvable'::text])))",+ "take_horizons.take_horizons_basis_check": "c CHECK ((basis = ANY (ARRAY['stated'::text, 'stated_relative'::text, 'owner'::text])))",+ "take_horizons.take_horizons_pkey": "p PRIMARY KEY (take_id)",+ "take_horizons.take_horizons_take_id_fkey": "f FOREIGN KEY (take_id) REFERENCES takes(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_pkey": "p PRIMARY KEY (id)","take_nudge_log.take_nudge_log_proposal_id_fkey": "f FOREIGN KEY (proposal_id) REFERENCES take_proposals(id) ON DELETE CASCADE","take_nudge_log.take_nudge_log_source_id_fkey": "f FOREIGN KEY (source_id) REFERENCES sources(id) ON DELETE CASCADE",@@ -919,6 +922,9 @@"take_grade_cache": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],+ "take_horizons": [+ "<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"+ ],"take_nudge_log": ["<current_role> -> <current_role> WITH GRANT OPTION: DELETE,INSERT,REFERENCES,SELECT,TRIGGER,TRUNCATE,UPDATE"],@@ -1359,6 +1365,8 @@"take_grade_cache_applied_idx": "CREATE INDEX take_grade_cache_applied_idx ON public.take_grade_cache USING btree (take_id, applied)","take_grade_cache_pkey": "CREATE UNIQUE INDEX take_grade_cache_pkey ON public.take_grade_cache USING btree (take_id, prompt_version, judge_model_id, evidence_signature)","take_grade_cache_wave_idx": "CREATE INDEX take_grade_cache_wave_idx ON public.take_grade_cache USING btree (wave_version, graded_at DESC)",+ "take_horizons_date_idx": "CREATE INDEX take_horizons_date_idx ON public.take_horizons USING btree (horizon_date)",+ "take_horizons_pkey": "CREATE UNIQUE INDEX take_horizons_pkey ON public.take_horizons USING btree (take_id)","take_nudge_log_pkey": "CREATE UNIQUE INDEX take_nudge_log_pkey ON public.take_nudge_log USING btree (id)","take_nudge_log_proposal_cooldown_idx": "CREATE INDEX take_nudge_log_proposal_cooldown_idx ON public.take_nudge_log USING btree (proposal_id, nudge_pattern, fired_at DESC) WHERE (proposal_id IS NOT NULL)","take_nudge_log_take_cooldown_idx": "CREATE INDEX take_nudge_log_take_cooldown_idx ON public.take_nudge_log USING btree (take_id, nudge_pattern, fired_at DESC) WHERE (take_id IS NOT NULL)",@@ -3669,6 +3677,16 @@],"flags": "relkind=r rls=true force_rls=false"},+ "take_horizons": {+ "columns": [+ "1 take_id bigint/int8 NOT NULL",+ "2 claim_sha256 text/text NOT NULL",+ "3 horizon_date date/date NOT NULL",+ "4 basis text/text NOT NULL",+ "5 set_at timestamp with time zone/timestamptz NOT NULL DEFAULT now()"+ ],+ "flags": "relkind=r rls=true force_rls=false"+ },"take_nudge_log": {"columns": ["1 id bigint/int8 NOT NULL DEFAULT nextval('take_nudge_log_id_seq'::regclass)",diff --git a/test/fixtures/goldens/doctor/json-postgres-fresh.json b/test/fixtures/goldens/doctor/json-postgres-fresh.jsonindex d1efba3d5d..fe963ec704 100644--- a/test/fixtures/goldens/doctor/json-postgres-fresh.json+++ b/test/fixtures/goldens/doctor/json-postgres-fresh.json@@ -902,7 +902,7 @@{"category": "ops","elapsed_ms": "<volatile>",- "message": "RLS enabled on 145/145 public tables",+ "message": "RLS enabled on 146/146 public tables","name": "rls","status": "ok"},diff --git a/test/graduation-inventory.test.ts b/test/graduation-inventory.test.tsindex 0977c6000d..39afc8933b 100644--- a/test/graduation-inventory.test.ts+++ b/test/graduation-inventory.test.ts@@ -60,7 +60,7 @@ describe('graduation inventory', () => {expect(new Set(names).size).toBe(names.length);const counts: Record<string, number> = {};for (const e of GRADUATION_INVENTORY.entries) counts[e.class] = (counts[e.class] ?? 0) + 1;- expect(counts).toEqual({ carry: 133, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });+ expect(counts).toEqual({ carry: 134, rebind: 2, rebuild: 2, discard: 7, schema_owned: 4 });for (const e of GRADUATION_INVENTORY.entries) {expect({ relation: e.relation, reason: e.reason.length > 5, present: e.engines.pglite || e.engines.postgres }).toEqual({ relation: e.relation, reason: true, present: true });diff --git a/test/takes-horizon-cli.test.ts b/test/takes-horizon-cli.test.tsnew file mode 100644index 0000000000..fc4a28e476--- /dev/null+++ b/test/takes-horizon-cli.test.ts@@ -0,0 +1,79 @@+/**+ * W7: `gbrain takes horizon` (trusted local; thin clients refuse it, see+ * test/thin-client-routing.test.ts). scan previews by default and writes only+ * with --apply; set and clear address a take by page slug and row.+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { runTakes } from '../src/commands/takes.ts';+import { readTakeHorizons } from '../src/core/takes-horizon.ts';++let engine: PGLiteEngine;+const ids: Record<string, number> = {};++async function capture(fn: () => Promise<void>): Promise<string> {+ const lines: string[] = [];+ const orig = console.log;+ console.log = (...args: unknown[]) => { lines.push(args.join(' ')); };+ try { await fn(); } finally { console.log = orig; }+ return lines.join('\n');+}++async function exitOf(fn: () => Promise<void>): Promise<{ code: number | undefined; stderr: string }> {+ const origExit = process.exit;+ const origErr = process.stderr.write.bind(process.stderr);+ let stderr = '';+ process.stderr.write = ((chunk: unknown) => { stderr += String(chunk); return true; }) as typeof process.stderr.write;+ process.exit = ((code?: number) => { throw Object.assign(new Error('EXIT'), { exitCode: code }); }) as typeof process.exit;+ try { await fn(); return { code: undefined, stderr }; }+ catch (e) { if ((e as Error).message === 'EXIT') return { code: (e as { exitCode?: number }).exitCode, stderr }; throw e; }+ finally { process.exit = origExit; process.stderr.write = origErr; }+}++async function take(slug: string, claim: string, since: string): Promise<number> {+ await engine.putPage(slug, { type: 'company', title: slug, compiled_truth: `${slug} test page.` });+ const [page] = await engine.executeRaw<{ id: number }>('SELECT id FROM pages WHERE slug = $1', [slug]);+ await engine.addTakesBatch([{ page_id: page!.id, row_num: 1, claim, kind: 'bet', holder: 'world', weight: 0.7, since_date: since }]);+ const [row] = await engine.executeRaw<{ id: number }>('SELECT id FROM takes WHERE page_id = $1', [page!.id]);+ return Number(row!.id);+}++beforeAll(async () => {+ engine = new PGLiteEngine();+ await engine.connect({});+ await engine.initSchema();+ ids.acme = await take('companies/acme-example', 'Acme-example will reach $5M ARR by the end of 2024', '2023-02-01');+ ids.cobalt = await take('companies/cobalt-example', 'Cobalt-example has the strongest team in its market', '2023-03-01');+}, 60_000);++afterAll(async () => { await engine.disconnect(); });++describe('gbrain takes horizon', () => {+ test('scan previews without writing, then --apply writes', async () => {+ const preview = JSON.parse(await capture(() => runTakes(engine, ['horizon', 'scan', '--json'])));+ expect(preview).toMatchObject({ applied: false, written: 0, unparsed: 1 });+ expect(preview.proposed).toEqual([expect.objectContaining({ take_id: ids.acme, horizon_date: '2024-12-31', basis: 'stated', phrase: 'by the end of 2024' })]);+ expect((await readTakeHorizons(engine)).size).toBe(0);+ const text = await capture(() => runTakes(engine, ['horizon', 'scan']));+ expect(text).toContain('1 stated horizon(s) to write');+ expect(text).toContain('gbrain takes horizon scan --apply');+ const applied = JSON.parse(await capture(() => runTakes(engine, ['horizon', 'scan', '--apply', '--json'])));+ expect(applied).toMatchObject({ applied: true, written: 1 });+ expect((await readTakeHorizons(engine)).get(ids.acme!)).toMatchObject({ horizon_date: '2024-12-31', basis: 'stated' });+ });++ test('set and clear address a take by slug and row', async () => {+ await capture(() => runTakes(engine, ['horizon', 'set', 'companies/cobalt-example', '--row', '1', '--date', '2025-06-30']));+ expect((await readTakeHorizons(engine)).get(ids.cobalt!)).toMatchObject({ horizon_date: '2025-06-30', basis: 'owner', current: true });+ const out = await capture(() => runTakes(engine, ['horizon', 'clear', 'companies/cobalt-example', '--row', '1']));+ expect(out).toContain('Cleared the horizon of companies/cobalt-example#1');+ expect((await readTakeHorizons(engine)).has(ids.cobalt!)).toBe(false);+ });++ test('refuses a missing take, a malformed date and an unknown subcommand', async () => {+ expect(await exitOf(() => runTakes(engine, ['horizon', 'set', 'companies/none-example', '--row', '1', '--date', '2025-06-30']))).toMatchObject({ code: 1, stderr: expect.stringContaining('No take companies/none-example#1') });+ expect(await exitOf(() => runTakes(engine, ['horizon', 'set', 'companies/cobalt-example', '--row', '1', '--date', '2025-13-01']))).toMatchObject({ code: 1, stderr: expect.stringContaining('YYYY-MM-DD') });+ expect(await exitOf(() => runTakes(engine, ['horizon', 'set', 'companies/cobalt-example', '--date', '2025-06-30']))).toMatchObject({ code: 1, stderr: expect.stringContaining('--row') });+ expect(await exitOf(() => runTakes(engine, ['horizon', 'bogus']))).toMatchObject({ code: 1, stderr: expect.stringContaining('Usage: gbrain takes horizon') });+ });+});diff --git a/test/thin-client-routing.test.ts b/test/thin-client-routing.test.tsindex ae2d1bb9b8..f00c9e6dfc 100644--- a/test/thin-client-routing.test.ts+++ b/test/thin-client-routing.test.ts@@ -240,6 +240,9 @@ describe('routeThinClientCommand — (b) host-bound forms return false', () => {['takes', ['extract']],['beliefs', ['changes', '--source', 'notes']],['beliefs', ['status']],+ ['takes', ['horizon', 'scan']],+ ['takes', ['horizon', 'set', 'companies/acme-example', '--row', '1', '--date', '2025-06-30']],+ ['takes', ['horizon', 'clear', 'companies/acme-example', '--row', '1']],];for (const [command, args] of hostBound) {