Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
feat(graph): edge_contradictions dream phase, edge-proposals CLI, dated add_link, phantom type guard (GBRA-49 P1)
garrytan48d96ddcf093
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.tsindex 722f3dd6f3..fa4c785e25 100644--- a/scripts/e2e-test-map.ts+++ b/scripts/e2e-test-map.ts@@ -612,7 +612,11 @@ export const E2E_TEST_MAP: Record<string, string[]> = {"src/core/link-extraction.ts": ["test/e2e/graph-quality.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts"],"src/core/attendance-repair.ts": ["test/e2e/attendance-repair-postgres.test.ts"],"src/core/extract-timeline-from-meetings.ts": ["test/e2e/extract-timeline-attendance-postgres.test.ts"],- "src/core/derived-links.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/attendance-repair-postgres.test.ts"],+ "src/core/derived-links.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/attendance-repair-postgres.test.ts", "test/e2e/link-relationships-postgres.test.ts"],+ "src/core/link-relationships.ts": ["test/e2e/link-relationships-postgres.test.ts"],+ "src/core/link-validity.ts": ["test/e2e/link-relationships-postgres.test.ts"],+ "src/core/link-temporal-apply.ts": ["test/e2e/link-relationships-postgres.test.ts"],+ "src/core/link-temporal-schema.ts": ["test/e2e/link-relationships-postgres.test.ts"],"src/core/link-reconciliation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],"src/core/persistence/links-preparation.ts": ["test/e2e/attendance-retrieval-postgres.test.ts"],"src/core/sweep.ts": ["test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/fix-wave-5-integration.test.ts"],@@ -744,4 +748,4 @@ E2E_TEST_MAP["src/core/engine-sql/dialect-*.ts"] = ENGINE_SQL_EXECUTOR_E2E;E2E_TEST_MAP["src/core/engine-sql/normalize.ts"] = ["test/e2e/engine-sql-normalize-parity.test.ts"];E2E_TEST_MAP["src/core/engine-sql/brands.ts"] = ["test/e2e/engine-sql-rls-scope.test.ts"];E2E_TEST_MAP["src/core/engine-sql/chunks.ts"] = ["test/e2e/evidence-delivery-leak.test.ts", "test/e2e/evidence-delivery-parity.test.ts", "test/e2e/embedding-tombstones-postgres.test.ts"];-E2E_TEST_MAP["src/core/engine-sql/links.ts"] = ["test/e2e/links-read-order.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/federated-link-reads-postgres.test.ts"];+E2E_TEST_MAP["src/core/engine-sql/links.ts"] = ["test/e2e/links-read-order.test.ts", "test/e2e/attendance-retrieval-postgres.test.ts", "test/e2e/federated-link-reads-postgres.test.ts", "test/e2e/link-relationships-postgres.test.ts"];diff --git a/src/cli/command-table.ts b/src/cli/command-table.tsindex 243b738041..92ce15a43c 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: 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 the// per-subcommand usage; keep the generic short-circuit from hiding it.{ name: 'connectors', phase: 'post-connect', thinClient: 'none', selfHelp: true, load: () => import('./commands/connectors.ts') },diff --git a/src/cli/commands/edge-proposals.ts b/src/cli/commands/edge-proposals.tsnew file mode 100644index 0000000000..1b011d2d64--- /dev/null+++ b/src/cli/commands/edge-proposals.ts@@ -0,0 +1,11 @@+/**+ * `gbrain edge-proposals`: post-connect dispatch (relationship-contradiction+ * proposals from the edge_contradictions dream phase). 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 { runEdgeProposals } = await import('../../commands/edge-proposals.ts');+ await runEdgeProposals(engine, args);+}diff --git a/src/commands/edge-proposals.ts b/src/commands/edge-proposals.tsnew file mode 100644index 0000000000..21decd3001--- /dev/null+++ b/src/commands/edge-proposals.ts@@ -0,0 +1,113 @@+/**+ * `gbrain edge-proposals` — review and apply relationship-contradiction+ * proposals from the edge_contradictions dream phase (host-local).+ *+ * gbrain edge-proposals list [--status proposed|applied|...|all] [--limit N] [--json]+ * gbrain edge-proposals show <id> [--json]+ * gbrain edge-proposals accept <id> append the closure line and re-derive+ * gbrain edge-proposals reject <id>+ * gbrain edge-proposals undo <id> | --all-applied+ * gbrain edge-proposals date <id> <YYYY-MM-DD> date an undated pair: writes "Started <type> [[target]]"+ *+ * Every proposal names the subject page, the relationship that ends, the close+ * date (from relationship-specific evidence) and why. gbrain never invents a+ * date: undated pairs wait for `date`.+ */+import type { BrainEngine } from '../core/engine.ts';+import { applyEdgeProposal, rejectEdgeProposal, undoEdgeProposal, DREAM_TIMELINE_SOURCE } from '../core/cycle/edge-contradictions.ts';+import { isCalendarDate, dateKey } from '../core/link-validity.ts';++const STATUSES = ['proposed', 'applied', 'rejected', 'undone', 'stale', 'reverted_by_user', 'undated_unresolved', 'ambiguous_same_date', 'compatible', 'error'];++interface Row {+ id: number; status: string; link_type: string; subject: string; a_target: string; b_target: string; ending: string | null;+ close_date: unknown; born_closed: boolean; model: string | null; confidence: number | null; generated_line: string | null; created_at: unknown;+}++function usage(): string {+ return [+ 'Usage: gbrain edge-proposals <list|show|accept|reject|undo|date> [args]',+ ' list [--status <status|all>] [--limit N] [--json] default status: proposed + undated_unresolved',+ ' show <id> [--json]',+ ' accept <id> write the closure line on the subject page and re-derive its links',+ ' reject <id> keep both relationships',+ ' undo <id> | --all-applied remove the closure line(s) this phase wrote',+ ' date <id> <YYYY-MM-DD> record when the newer relationship started (undated pairs), then re-run the dream cycle',+ ].join('\n');+}++async function rows(engine: BrainEngine, where: string, params: unknown[], limit = 50): Promise<Row[]> {+ return engine.executeRaw<Row>(+ `SELECT p.id, p.status, p.link_type, f.slug AS subject, ta.slug AS a_target, tb.slug AS b_target, te.slug AS ending,+ p.close_date::text AS close_date, p.born_closed, p.model, p.confidence, p.generated_line, p.created_at+ FROM link_edge_proposals p+ JOIN pages f ON f.id = p.from_page_id JOIN pages ta ON ta.id = p.a_to_page_id JOIN pages tb ON tb.id = p.b_to_page_id+ LEFT JOIN pages te ON te.id = p.ending_to_page_id+ WHERE ${where} ORDER BY p.created_at DESC, p.id DESC LIMIT ${Math.max(1, Math.min(1000, limit))}`, params);+}++function describe(r: Row): string {+ const pair = `${r.subject}: ${r.link_type} ${r.a_target} vs ${r.b_target}`;+ if (r.status === 'proposed' || r.status === 'applied') {+ return `#${r.id} [${r.status}] ${pair} → ${r.ending} ended ${dateKey(r.close_date)}${r.born_closed ? ' (recorded out of order)' : ''}`;+ }+ if (r.status === 'undated_unresolved') return `#${r.id} [undated] ${pair} → cannot both hold, but a start date is missing; run: gbrain edge-proposals date ${r.id} <YYYY-MM-DD>`;+ return `#${r.id} [${r.status}] ${pair}`;+}++export async function runEdgeProposals(engine: BrainEngine, args: string[]): Promise<void> {+ const [sub, ...rest] = args;+ const json = rest.includes('--json');+ const flag = (name: string) => { const i = rest.indexOf(name); return i >= 0 ? rest[i + 1] : undefined; };+ const id = Number(rest.find(a => /^\d+$/.test(a)));+ const out = (value: unknown, text: string) => console.log(json ? JSON.stringify(value, null, 2) : text);++ if (!sub || sub === '--help' || sub === 'help') { console.log(usage()); return; }+ if (sub === 'list') {+ const status = flag('--status');+ if (status && status !== 'all' && !STATUSES.includes(status)) { console.error(`Unknown status ${status}. One of: ${STATUSES.join(', ')}, all`); process.exitCode = 2; return; }+ const list = status === 'all' ? await rows(engine, 'TRUE', [], Number(flag('--limit') ?? 50))+ : await rows(engine, 'p.status = ANY($1::text[])', [status ? [status] : ['proposed', 'undated_unresolved']], Number(flag('--limit') ?? 50));+ out(list, list.length ? list.map(describe).join('\n') + '\n\nNext: gbrain edge-proposals accept <id> | reject <id>' : 'No open relationship proposals.');+ return;+ }+ if (!Number.isSafeInteger(id) || id <= 0) { console.error(`${usage()}\n\nA proposal id is required (gbrain edge-proposals list shows them).`); process.exitCode = 2; return; }+ if (sub === 'show') {+ const [r] = await rows(engine, 'p.id = $1', [id]);+ if (!r) { console.error(`No proposal #${id}.`); process.exitCode = 1; return; }+ out(r, `${describe(r)}\nmodel: ${r.model ?? '-'} confidence: ${r.confidence ?? '-'}\n${r.generated_line ? `line: - **${dateKey(r.close_date)}** | ${DREAM_TIMELINE_SOURCE} — ${r.generated_line}` : ''}`);+ return;+ }+ if (sub === 'accept' || sub === 'reject' || sub === 'undo') {+ if (sub === 'undo' && rest.includes('--all-applied')) {+ const applied = await engine.executeRaw<{ id: number }>(`SELECT id FROM link_edge_proposals WHERE status = 'applied' ORDER BY id`);+ const results = [];+ for (const a of applied) results.push({ id: Number(a.id), ...(await undoEdgeProposal(engine, Number(a.id))) });+ out(results, `${results.filter(r => r.status === 'undone').length} applied proposal(s) undone.`);+ return;+ }+ const result = sub === 'accept' ? await applyEdgeProposal(engine, id) : sub === 'reject' ? await rejectEdgeProposal(engine, id) : await undoEdgeProposal(engine, id);+ out({ id, ...result }, `#${id}: ${result.status}${result.reason ? ` — ${result.reason}` : ''}`);+ if (!['applied', 'rejected', 'undone'].includes(result.status)) process.exitCode = 1;+ return;+ }+ if (sub === 'date') {+ const date = rest.find(a => /^\d{4}-\d{2}-\d{2}$/.test(a));+ if (!isCalendarDate(date)) { console.error('date needs a calendar date YYYY-MM-DD: when the newer relationship started.'); process.exitCode = 2; return; }+ const [r] = await rows(engine, `p.id = $1 AND p.status = 'undated_unresolved'`, [id]);+ if (!r) { console.error(`No undated proposal #${id}.`); process.exitCode = 1; return; }+ const target = rest.find(a => a.includes('/')) ?? r.b_target;+ const { operations } = await import('../core/operations.ts');+ const op = operations.find(o => o.name === 'add_timeline_entry')!;+ const sourceId = (await engine.executeRaw<{ source_id: string }>(`SELECT source_id FROM link_edge_proposals WHERE id = $1`, [id]))[0].source_id;+ await op.handler({ engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId, logger: { info() {}, warn() {}, error() {} } } as never,+ { slug: r.subject, date, summary: `Started ${r.link_type} [[${target}]]`, source: 'gbrain edge-proposals' });+ const { autoLinkWrittenPage } = await import('../core/ops/pages.ts');+ await autoLinkWrittenPage(engine, r.subject, { sourceId });+ await engine.executeRaw(`UPDATE link_edge_proposals SET status = 'rejected', detail = 'dated by user', updated_at = now() WHERE id = $1`, [id]);+ out({ id, status: 'dated', target, date }, `#${id}: recorded "Started ${r.link_type} [[${target}]]" on ${date}. The next dream cycle re-judges the pair with this date.`);+ return;+ }+ console.error(usage());+ process.exitCode = 2;+}diff --git a/src/core/cli-flag-registry.generated.ts b/src/core/cli-flag-registry.generated.tsindex 742267af39..0c38e6ea40 100644--- a/src/core/cli-flag-registry.generated.ts+++ b/src/core/cli-flag-registry.generated.ts@@ -48,6 +48,7 @@ export const CLI_FLAG_REGISTRY: Record<string, readonly string[]> = {'decide': ['--all', '--all-from', '--brain', '--call-site', '--dataset', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--from', '--help', '--input', '--json', '--limit', '--min', '--out', '--provider', '--query', '--recommended', '--shadow', '--since', '--slot', '--source', '--status', '--suite', '--target', '--threshold', '--what-if-threshold', '--yes'],'doctor': ['--abandon', '--abbrev-ref', '--abort', '--accept-pending', '--admin-intent', '--adopt-columns', '--adopt-permissions', '--all', '--all-from', '--allow-old-serve', '--allow-shell-jobs', '--allow-unverified-remote', '--apply', '--apply-rewrites', '--auto', '--auto-fix', '--background', '--brain', '--branch', '--break-lock', '--by-mention', '--cached', '--call-site', '--catch-up', '--check', '--client', '--concurrency', '--confidence', '--confirm', '--content-audit', '--count', '--dataset', '--db-url', '--delete-brain', '--detach', '--diff-filter', '--dim', '--dir', '--drain', '--dry-run', '--egress', '--embedding-dimensions', '--embedding-model', '--env', '--exclude', '--exclude-standard', '--exit-code', '--expect', '--expected-epoch', '--expected-state', '--explain', '--facts', '--fast', '--federated-read', '--fetch-timeout-ms', '--ff-only', '--file', '--fix', '--follow', '--force', '--force-rechunk', '--force-retry', '--force-schema', '--format', '--fresh', '--from', '--from-pages', '--full', '--gbrain-bin', '--get', '--get-url', '--git-common-dir', '--git-dir', '--git-path', '--hard', '--harness', '--help', '--home', '--http', '--id', '--ignore-env-override', '--include-ambiguous', '--include-flagged', '--include-gitignored', '--include-hidden', '--include-pseudo', '--include-repairs', '--index-audit', '--init', '--input', '--install', '--is-ancestor', '--is-inside-work-tree', '--job-isolation', '--jq', '--json', '--lang', '--limit', '--link-source', '--link-type', '--local', '--locks', '--log-noop', '--manifest', '--markdown', '--max-cost', '--max-cost-usd', '--max-jobs', '--max-rss', '--max-usd', '--max-waiting', '--mcp-only', '--migrate-legacy', '--migrate-only', '--min', '--mode', '--multimodal', '--name', '--name-only', '--nice', '--no-accept-pending', '--no-autopilot-install', '--no-capture', '--no-cron', '--no-edit', '--no-embed', '--no-embedding', '--no-extract', '--no-hooks', '--no-migrate', '--no-pull', '--no-renames', '--no-schema-pack', '--no-tags', '--no-verify', '--no-write-fetch-head', '--non-interactive', '--older-than', '--once', '--only', '--operations', '--others', '--out', '--output', '--overwrite', '--parallel', '--params', '--pat-file', '--path', '--path-format', '--pglite', '--phase', '--pid-file', '--porcelain', '--port', '--prefer-postgres', '--preset', '--preview', '--probe', '--probe-pglite', '--progress-interval', '--progress-json', '--project', '--provider', '--prune-orphans', '--pure', '--push', '--push-only', '--query', '--queue', '--quiet', '--rate', '--reauth', '--rebase', '--recommended', '--refresh', '--refresh-operations', '--refresh-skills', '--regenerate', '--reissue', '--remediate', '--remediation-plan', '--remove', '--repo', '--request-id', '--reranker', '--reset', '--reset-checkpoint', '--restore-only', '--resume', '--retry-failed', '--review-lower', '--scope', '--scopes', '--select', '--self-transfer', '--session', '--set', '--set-upstream-to', '--shadow', '--short', '--show-current', '--show-token', '--show-toplevel', '--since', '--skills', '--skills-dir', '--skip', '--skip-bare-tweet', '--skip-failed', '--skip-urls', '--skip-verify', '--slot', '--slugs', '--source', '--source-id', '--sources', '--src-subpath', '--staged', '--stale', '--status', '--strategy', '--strict', '--suite', '--supabase', '--surface', '--symbol-kind', '--symbolic-full-name', '--takes-holders', '--target', '--target-score', '--threshold', '--timeout', '--to', '--token', '--token-name', '--token-ttl', '--top-k', '--trust', '--type', '--uninstall', '--unsafe-bypass-dream-guard', '--unset-all', '--untracked-files', '--url', '--user', '--vectors', '--verbose', '--verify', '--version', '--wait', '--wait-drain', '--what-if-threshold', '--window', '--workers', '--working-tree', '--yes'],'dream': ['--audit-rejects', '--brain', '--cancel-unmatched', '--date', '--dir', '--drain', '--dry-run', '--eval-run', '--force', '--force-retry', '--from', '--help', '--input', '--install', '--json', '--limit', '--list', '--max-usd', '--once', '--path', '--phase', '--pull', '--reconcile-queue', '--since', '--source', '--source-id', '--threshold', '--to', '--unsafe-bypass-dream-guard', '--window', '--yes'],+ 'edge-proposals': ['--access', '--add', '--all-applied', '--allowed-operations', '--asof', '--bound-slug-prefixes', '--brain', '--client', '--date', '--dated-since', '--days', '--entities', '--federated-read', '--full', '--fuzzy', '--help', '--http', '--id', '--include-deleted', '--json', '--kind', '--limit', '--model', '--multimodal', '--no-autopilot-install', '--page', '--params', '--path', '--phase', '--recent', '--refresh-operations', '--scopes', '--session', '--since', '--slugs', '--source', '--sources', '--stale', '--status', '--surface', '--to', '--url', '--yes'],'edges-backfill': ['--all-sources', '--brain', '--concurrency', '--help', '--json', '--max-chunks', '--source', '--workers'],'embed': ['--accept-pending', '--all', '--background', '--batch-size', '--brain', '--break-lock', '--budget-ms', '--catch-up', '--db-url', '--dim', '--dry-run', '--embedding-dimensions', '--embedding-model', '--explain', '--facts', '--follow', '--force', '--help', '--http', '--images', '--include-null-signature', '--json', '--max-cost-usd', '--max-facts', '--max-usd', '--no-accept-pending', '--no-embed', '--no-embedding', '--pace', '--pace-max-concurrency', '--path', '--priority', '--progress-interval', '--progress-json', '--quiet', '--show-toplevel', '--slugs', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],'embeddings': ['--accept-pending', '--background', '--brain', '--db-url', '--dim', '--embedding-dimensions', '--embedding-model', '--explain', '--follow', '--force', '--help', '--json', '--no-accept-pending', '--no-embedding', '--path', '--probe', '--progress-interval', '--progress-json', '--quiet', '--source', '--stale', '--status', '--supabase', '--timeout', '--to', '--wait', '--yes'],@@ -161,6 +162,7 @@ export const CLI_ROUTING_FLAGS: Record<string, readonly string[]> = {'decide': ['--brain'],'doctor': ['--brain'],'dream': ['--brain', '--source'],+ 'edge-proposals': ['--brain'],'edges-backfill': ['--brain', '--source'],'embed': ['--brain', '--source'],'embeddings': ['--brain'],diff --git a/src/core/config.ts b/src/core/config.tsindex 60c1fb60d9..12adf94dee 100644--- a/src/core/config.ts+++ b/src/core/config.ts@@ -1658,6 +1658,7 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [*/export const KNOWN_CONFIG_KEY_PREFIXES: readonly string[] = ['search.', // search.* (mode, cache.*, etc.)+ 'graph.', // graph.edge_validity (temporal typed-edge read policy, src/core/link-validity.ts)'models.', // models.* (tier, aliases, per-task)'dream.', // dream.synthesize.*, dream.patterns.*'cycle.', // cycle.<phase>.*diff --git a/src/core/cycle.ts b/src/core/cycle.tsindex 4ae8dad37a..ea676d1d9d 100644--- a/src/core/cycle.ts+++ b/src/core/cycle.ts@@ -76,6 +76,9 @@ export type CyclePhase =// - calibration_profile: aggregates the resolved subset into 2-4// narrative pattern statements + active bias tags. Voice-gated.| 'propose_takes' | 'grade_takes' | 'calibration_profile'+ // Temporal typed edges: an LLM flags live relationships that cannot both+ // hold; date arithmetic decides which ended (proposals by default).+ | 'edge_contradictions'// #2653 — drift detection (default OFF; dream.drift.enabled). LLM-judges// soft-band takes against recent timeline evidence; report-only in v1// (writes reports/drift-<date>; auto_update mutates nothing).@@ -167,6 +170,10 @@ export const ALL_PHASES: CyclePhase[] = ['propose_takes','grade_takes','calibration_profile',+ // Temporal typed edges: proposes (or, for certified models, applies)+ // closures for live relationships that cannot both hold. Runs after+ // extract so it judges freshly derived relationship state.+ 'edge_contradictions',// #2653 — drift detection. Default OFF (dream.drift.enabled). Runs AFTER// the calibration trio (fresh take resolutions) and BEFORE embed so the// drift report page gets embedded same-cycle. Report-only in v1.@@ -331,6 +338,8 @@ const NEEDS_LOCK_PHASES: ReadonlySet<CyclePhase> = new Set(['calibration_profile',// #2653 — writes the reports/drift-<date> page.'drift',+ // Temporal typed edges — writes proposals and (apply mode) closure lines.+ 'edge_contradictions',// #5876 — writes event pages, projections and the chronicle ledger.'chronicle',// v0.41 T9 — extract_atoms writes atom-typed pages via put_page;@@ -607,6 +616,8 @@ export interface CycleOpts {* cap's worth drains incrementally across cycles (staleRemaining reports it).*/export const CYCLE_STALE_DRAIN_BUDGET_MS = 3 * 60 * 1000;+/** Relationship-state rows refreshed per cycle by the extract phase sweep (temporal typed edges). */+const RELATIONSHIP_SWEEP_LIMIT = 2000;const LEGACY_CYCLE_LOCK_ID = 'gbrain-cycle';// v0.41.19.0 (T2 of ops-fix-wave): dropped from 30 min to 5 min so a@@ -1394,6 +1405,20 @@ async function runPhaseExtract(} catch (e) {staleDetails = { stale_drain_error: e instanceof Error ? e.message : String(e) };}+ // Temporal typed edges: relationships whose state is missing or older than+ // their newest evidence (writers that bypass the engine, rows from before+ // the upgrade) converge here, bounded per cycle. Zero LLM.+ try {+ const { staleRelationshipKeys, refreshRelationships } = await import('./link-relationships.ts');+ const { maintenanceTransaction } = await import('./persistence/attribution.ts');+ const keys = await staleRelationshipKeys(engine, RELATIONSHIP_SWEEP_LIMIT);+ if (keys.length) {+ const refreshed = await maintenanceTransaction(engine, tx => refreshRelationships(tx, keys));+ staleDetails = { ...staleDetails, relationships_swept: keys.length, relationships_changed: refreshed };+ }+ } catch (e) {+ staleDetails = { ...staleDetails, relationship_sweep_error: e instanceof Error ? e.message : String(e) };+ }return {phase: 'extract',status: 'ok',@@ -2696,6 +2721,26 @@ export async function runCycle(}}+ // ── Temporal typed edges: contradiction proposals ─────────────+ if (phases.includes('edge_contradictions')) {+ checkAborted(cycleSignal);+ if (!engine) {+ phaseResults.push({ phase: 'edge_contradictions', status: 'skipped', duration_ms: 0, summary: 'no database connected', details: { reason: 'no_database' } });+ } else {+ progress.start('cycle.edge_contradictions');+ const { runPhaseEdgeContradictions } = await import('./cycle/edge-contradictions.ts');+ const { result, duration_ms } = await timePhase(async (): Promise<PhaseResult> => {+ const r = await runPhaseEdgeContradictions(engine, { dryRun });+ const status: PhaseStatus = r.status === 'complete' ? 'ok' : r.status === 'partial' ? 'warn' : r.status === 'failed' ? 'fail' : 'skipped';+ return { phase: 'edge_contradictions', status, duration_ms: 0, summary: r.detail, details: { ...(r.totals ?? {}) } };+ }, 'edge_contradictions');+ result.duration_ms = duration_ms;+ phaseResults.push(result);+ progress.finish();+ }+ await safeYield(opts.yieldBetweenPhases);+ }+// ── #2653: drift detection ──────────────────────────────────// Default OFF (dream.drift.enabled). LLM-judges soft-band takes// against recent timeline evidence; report-only in v1 — writes onediff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.tsnew file mode 100644index 0000000000..afcd913903--- /dev/null+++ b/src/core/cycle/edge-contradictions.ts@@ -0,0 +1,444 @@+/**+ * Dream phase `edge_contradictions`: an LLM flags which live state+ * relationships of one subject cannot both hold now ("works_at acme-example"+ * vs "works_at widget-co"); deterministic date arithmetic (`closeContradiction`+ * in src/core/link-validity.ts) decides which one ended and when. The model+ * never supplies dates.+ *+ * Modes (`dream.edge_contradictions.mode`):+ * propose record a proposal; `gbrain edge-proposals accept <id>` applies it+ * apply apply automatically (default only for certified models)+ * off do nothing+ * Applying writes one timeline line on the subject page through the+ * coordinated add_timeline_entry mutation:+ * - **2025-03-01** | gbrain-dream (inferred) — Ended works_at [[companies/acme-example]] (superseded by works_at companies/widget-co)+ * then re-derives that page's links, so the closure lands through the+ * deterministic extractor (transition producer 'dream'). Deleting the line+ * reopens the relationship; the proposal is then marked reverted_by_user and+ * never re-proposed until the evidence changes.+ *+ * Candidates: subjects with ≥2 live relationships of the same state type to+ * different targets whose combined evidence hash has no proposal yet.+ * Bounded by max_subjects and the cycle budget meter (max_usd).+ */+import { createHash } from 'node:crypto';+import type { BrainEngine } from '../engine.ts';+import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd } from './budget-meter.ts';+import { resolveModel } from '../model-config.ts';+import { closeContradiction, parseMultirange, relationSemantics, utcToday, dateKey, type Stint } from '../link-validity.ts';++export interface EdgeContradictionsResult {+ name: 'edge_contradictions';+ status: 'complete' | 'partial' | 'failed' | 'skipped';+ detail: string;+ totals?: Record<string, number>;+ duration_ms: number;+}++export interface JudgeRelationship {+ index: number;+ link_type: string;+ target: string;+ target_title: string;+ since: string | null;+ contexts: string[];+}++export interface JudgePair { a: number; b: number; conflict: boolean; confidence: number }++export type EdgeJudgeFn = (input: {+ subject: { slug: string; title: string };+ relationships: JudgeRelationship[];+ modelHint?: string;+ maxOutputTokens?: number;+}) => Promise<JudgePair[] | null>;++export type EdgeContradictionsMode = 'propose' | 'apply' | 'off';++export interface EdgeContradictionsConfig {+ mode: EdgeContradictionsMode;+ modeExplicit: boolean;+ maxSubjects: number;+ budgetUsd: number;+ allowUnpriced: boolean;+}++export interface EdgeContradictionsOpts {+ dryRun?: boolean;+ judge?: EdgeJudgeFn;+ /** Apply a proposal (tests inject; default appends the timeline line via the coordinated op path). */+ applier?: (engine: BrainEngine, proposalId: number) => Promise<ApplyOutcome>;+ /** Treat the chat model as available (tests). */+ assumeChatAvailable?: boolean;+ auditPath?: string;+}++/**+ * Models whose sealed held-out run met the certification bar (wrong closures+ * ≤ 1% on every run). With no explicit mode, a certified model defaults to+ * `apply`; every other configured model defaults to `propose`.+ */+export const CERTIFIED_APPLY_MODELS: readonly string[] = [];++const DEFAULT_MAX_SUBJECTS = 200;+const DEFAULT_BUDGET_USD = 1.0;+const MAX_RELATIONSHIPS_PER_SUBJECT = 8;+const JUDGE_MAX_OUTPUT_TOKENS = 600;+export const DREAM_TIMELINE_SOURCE = 'gbrain-dream (inferred)';++export async function loadEdgeContradictionsConfig(engine: BrainEngine, model: string): Promise<EdgeContradictionsConfig> {+ const raw = (await engine.getConfig('dream.edge_contradictions.mode'))?.trim().toLowerCase();+ const explicit = raw === 'propose' || raw === 'apply' || raw === 'off';+ const mode: EdgeContradictionsMode = explicit ? raw as EdgeContradictionsMode+ : CERTIFIED_APPLY_MODELS.includes(model) ? 'apply' : 'propose';+ const subjects = Number.parseInt((await engine.getConfig('dream.edge_contradictions.max_subjects')) ?? '', 10);+ return {+ mode,+ modeExplicit: explicit,+ maxSubjects: Number.isFinite(subjects) && subjects > 0 ? subjects : DEFAULT_MAX_SUBJECTS,+ budgetUsd: parseBudgetUsd(await engine.getConfig('dream.edge_contradictions.max_usd'), DEFAULT_BUDGET_USD),+ allowUnpriced: await loadAllowUnpriced(engine),+ };+}++export const EDGE_JUDGE_PROMPT = `You check a person's or organization's current relationships in a personal knowledge base.+Each numbered relationship below is currently recorded as true. Decide, for each pair of relationships+of the SAME type, whether they can both be true at the same time right now.++Examples: two full-time works_at relationships at different companies usually cannot both hold+(someone moved jobs) unless the evidence says the person holds both roles; advising two companies,+working at a company while advising another, and board seats can all hold at once.++Do not guess dates. Judge only whether both can be true now, from the evidence shown.++Output ONLY one JSON object:+{"pairs": [{"a": <index>, "b": <index>, "conflict": true|false, "confidence": <0..1>}]}+List every same-type pair once.++SUBJECT: {SUBJECT}++RELATIONSHIPS:+{RELATIONSHIPS}+`;++export function buildEdgeJudgePrompt(subject: { slug: string; title: string }, relationships: JudgeRelationship[]): string {+ const clean = (s: string) => s.replace(/[\r\n]+/g, ' ').replace(/[<>]/g, '').slice(0, 240);+ const lines = relationships.map(r => `${r.index}. ${r.link_type} → ${clean(r.target_title || r.target)} (${r.target})` ++ `${r.since ? `, recorded since ${r.since}` : ', start date unknown'}` ++ `${r.contexts.length ? `\n evidence: ${r.contexts.map(c => `"${clean(c)}"`).join(' | ')}` : ''}`);+ return EDGE_JUDGE_PROMPT.replace('{SUBJECT}', `${clean(subject.title)} (${subject.slug})`).replace('{RELATIONSHIPS}', lines.join('\n'));+}++/** Parse the judge's JSON; null on anything malformed (refusals, prose, unknown shapes). */+export function parseEdgeJudgeOutput(text: string, maxIndex: number): JudgePair[] | null {+ const match = /\{[\s\S]*\}/.exec(text ?? '');+ if (!match) return null;+ let parsed: unknown;+ try { parsed = JSON.parse(match[0]); } catch { return null; }+ const pairs = (parsed as { pairs?: unknown })?.pairs;+ if (!Array.isArray(pairs)) return null;+ const out: JudgePair[] = [];+ for (const p of pairs) {+ const a = Number((p as JudgePair).a), b = Number((p as JudgePair).b);+ if (!Number.isInteger(a) || !Number.isInteger(b) || a === b || a < 1 || b < 1 || a > maxIndex || b > maxIndex) return null;+ if (typeof (p as JudgePair).conflict !== 'boolean') return null;+ const confidence = Number((p as JudgePair).confidence);+ out.push({ a, b, conflict: (p as JudgePair).conflict, confidence: Number.isFinite(confidence) ? Math.max(0, Math.min(1, confidence)) : 0.5 });+ }+ return out;+}++export async function defaultEdgeJudge(input: Parameters<EdgeJudgeFn>[0]): Promise<JudgePair[] | null> {+ const { chat } = await import('../ai/gateway.ts');+ const result = await chat({+ messages: [{ role: 'user', content: buildEdgeJudgePrompt(input.subject, input.relationships) }],+ ...(input.modelHint ? { model: input.modelHint } : {}),+ maxTokens: input.maxOutputTokens ?? JUDGE_MAX_OUTPUT_TOKENS,+ });+ return parseEdgeJudgeOutput(result.text, input.relationships.length);+}++interface CandidateRow {+ source_id: string; from_page_id: number; to_page_id: number; link_type: string;+ valid_ranges: string; last_start: unknown; recorded_at: unknown; evidence_hash: string;+ subject_slug: string; subject_title: string | null; target_slug: string; target_title: string | null;+}++interface SubjectGroup { sourceId: string; fromId: number; slug: string; title: string; linkType: string; rels: CandidateRow[] }++async function findCandidateGroups(engine: BrainEngine, maxSubjects: number): Promise<SubjectGroup[]> {+ const today = utcToday();+ const rows = await engine.executeRaw<CandidateRow>(+ `WITH live AS (+ SELECT lr.* FROM link_relationships lr+ WHERE lr.scope = 'all' AND lr.semantics = 'state' AND lr.valid_ranges @> $1::date+ ), multi AS (+ SELECT source_id, from_page_id, link_type FROM live+ GROUP BY 1, 2, 3 HAVING count(DISTINCT to_page_id) >= 2+ ORDER BY max(refreshed_at) DESC LIMIT $2+ )+ SELECT l.source_id, l.from_page_id, l.to_page_id, l.link_type, l.valid_ranges::text AS valid_ranges,+ l.last_start, l.recorded_at, l.evidence_hash,+ f.slug AS subject_slug, f.title AS subject_title, t.slug AS target_slug, t.title AS target_title+ FROM live l JOIN multi m USING (source_id, from_page_id, link_type)+ JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL+ JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL+ ORDER BY l.from_page_id, l.link_type, l.last_start NULLS FIRST, t.slug`,+ [today, maxSubjects]);+ const groups = new Map<string, SubjectGroup>();+ for (const r of rows) {+ if (relationSemantics(r.link_type) !== 'state') continue;+ const key = `${r.from_page_id}\0${r.link_type}`;+ let g = groups.get(key);+ if (!g) { g = { sourceId: r.source_id, fromId: Number(r.from_page_id), slug: r.subject_slug, title: r.subject_title ?? r.subject_slug, linkType: r.link_type, rels: [] }; groups.set(key, g); }+ if (g.rels.length < MAX_RELATIONSHIPS_PER_SUBJECT) g.rels.push(r);+ }+ return [...groups.values()];+}++const pairHash = (a: CandidateRow, b: CandidateRow) =>+ createHash('sha256').update([a.evidence_hash, b.evidence_hash].sort().join(':')).digest('hex').slice(0, 32);+const ordered = (a: CandidateRow, b: CandidateRow): [CandidateRow, CandidateRow] => (Number(a.to_page_id) < Number(b.to_page_id) ? [a, b] : [b, a]);++/** The timeline line an applied proposal writes. */+export function dreamClosureLine(linkType: string, endingSlug: string, otherSlug: string): string {+ return `Ended ${linkType} [[${endingSlug}]] (superseded by ${linkType} ${otherSlug})`;+}++export async function runPhaseEdgeContradictions(engine: BrainEngine, opts: EdgeContradictionsOpts = {}): Promise<EdgeContradictionsResult> {+ const start = Date.now();+ const done = (status: EdgeContradictionsResult['status'], detail: string, totals?: Record<string, number>): EdgeContradictionsResult =>+ ({ name: 'edge_contradictions', status, detail, totals, duration_ms: Date.now() - start });++ const model = await resolveModel(engine, { configKey: 'models.dream.edge_contradictions', tier: 'utility', fallback: 'haiku' });+ const config = await loadEdgeContradictionsConfig(engine, model);+ if (config.mode === 'off') return done('skipped', 'mode off (dream.edge_contradictions.mode)');+ if (!opts.judge && !opts.assumeChatAvailable) {+ const { isAvailable } = await import('../ai/gateway.ts');+ if (!isAvailable('chat', model)) {+ return done('skipped', `no chat model available (${model}); configure one (gbrain models) to have relationship contradictions proposed`);+ }+ }++ const reverted = await markRevertedProposals(engine);+ const groups = await findCandidateGroups(engine, config.maxSubjects);+ if (groups.length === 0) return done('complete', `no subjects with competing live relationships${reverted ? `; ${reverted} reverted by user` : ''}`, { subjects: 0, reverted });+ if (opts.dryRun) return done('skipped', `dry-run: ${groups.length} subject(s) would be judged`, { subjects: groups.length });++ const meter = new BudgetMeter({+ budgetUsd: config.budgetUsd, allowUnpriced: config.allowUnpriced,+ pricingOverrides: await loadPricingOverrides(engine), phase: 'edge_contradictions', auditPath: opts.auditPath,+ });+ const judge = opts.judge ?? defaultEdgeJudge;+ const totals = { subjects: groups.length, judged: 0, proposed: 0, applied: 0, born_closed: 0, undated_unresolved: 0, ambiguous_same_date: 0, compatible: 0, errors: 0, skipped_known: 0, reverted };+ let budgetExhausted = false;++ for (const g of groups) {+ // Skip subjects whose every pair already has a proposal for this evidence.+ const pairs: Array<[CandidateRow, CandidateRow]> = [];+ for (let i = 0; i < g.rels.length; i++) for (let j = i + 1; j < g.rels.length; j++) pairs.push(ordered(g.rels[i], g.rels[j]));+ const known = new Set((await engine.executeRaw<{ a: number; b: number }>(+ `SELECT a_to_page_id AS a, b_to_page_id AS b FROM link_edge_proposals+ WHERE from_page_id = $1 AND link_type = $2 AND evidence_hash = ANY($3::text[])`,+ [g.fromId, g.linkType, pairs.map(([a, b]) => pairHash(a, b))])).map(r => `${r.a}:${r.b}`));+ const fresh = pairs.filter(([a, b]) => !known.has(`${a.to_page_id}:${b.to_page_id}`));+ if (fresh.length === 0) { totals.skipped_known++; continue; }++ const relationships: JudgeRelationship[] = await Promise.all(g.rels.map(async (r, i) => ({+ index: i + 1, link_type: r.link_type, target: r.target_slug, target_title: r.target_title ?? r.target_slug,+ since: dateKey(r.last_start),+ contexts: (await engine.executeRaw<{ context: string }>(+ `SELECT DISTINCT context FROM links WHERE from_page_id = $1 AND to_page_id = $2 AND link_type = $3 AND context <> '' LIMIT 3`,+ [r.from_page_id, r.to_page_id, r.link_type])).map(c => c.context),+ })));+ const prompt = buildEdgeJudgePrompt(g, relationships);+ const check = meter.check({ modelId: model, estimatedInputTokens: Math.ceil(prompt.length / 4), maxOutputTokens: JUDGE_MAX_OUTPUT_TOKENS, label: `edge_contradictions:${g.slug}` });+ if (!check.allowed) { budgetExhausted = true; break; }++ let verdict: JudgePair[] | null = null;+ try { verdict = await judge({ subject: g, relationships, modelHint: model, maxOutputTokens: JUDGE_MAX_OUTPUT_TOKENS }); }+ catch (e) { process.stderr.write(`[edge_contradictions] judge failed for ${g.slug}: ${(e as Error).message}\n`); }+ totals.judged++;+ for (const [a, b] of fresh) {+ const hash = pairHash(a, b);+ const ia = g.rels.indexOf(a) + 1, ib = g.rels.indexOf(b) + 1;+ if (!verdict) {+ await recordProposal(engine, g, a, b, hash, { status: 'error', model, detail: 'judge output missing or malformed' });+ totals.errors++;+ continue;+ }+ const v = verdict.find(p => (p.a === ia && p.b === ib) || (p.a === ib && p.b === ia));+ if (!v || !v.conflict) {+ await recordProposal(engine, g, a, b, hash, { status: 'compatible', model, confidence: v?.confidence ?? null });+ totals.compatible++;+ continue;+ }+ const side = (r: CandidateRow) => ({ lastStart: dateKey(r.last_start), stints: parseMultirange(r.valid_ranges) as Stint[], recordedAt: r.recorded_at instanceof Date ? r.recorded_at : String(r.recorded_at) });+ const outcome = closeContradiction(side(a), side(b));+ if (outcome.action === 'none') {+ const status = outcome.reason === 'already_disjoint' ? 'compatible' : outcome.reason;+ await recordProposal(engine, g, a, b, hash, { status, model, confidence: v.confidence });+ totals[status === 'compatible' ? 'compatible' : status]++;+ continue;+ }+ const ending = outcome.side === 'a' ? a : b;+ const other = outcome.side === 'a' ? b : a;+ const id = await recordProposal(engine, g, a, b, hash, {+ status: 'proposed', model, confidence: v.confidence, endingTo: Number(ending.to_page_id), closeDate: outcome.closeDate,+ bornClosed: outcome.bornClosed, line: dreamClosureLine(g.linkType, ending.target_slug, other.target_slug),+ });+ totals.proposed++;+ if (outcome.bornClosed) totals.born_closed++;+ if (config.mode === 'apply' && id !== null) {+ const applied = await (opts.applier ?? applyEdgeProposal)(engine, id);+ if (applied.status === 'applied') totals.applied++;+ }+ }+ }++ const detail = `judged ${totals.judged}/${groups.length} subject(s): ${totals.proposed} proposal(s)` ++ (config.mode === 'apply' ? `, ${totals.applied} applied` : ' (mode propose: review with gbrain edge-proposals list)') ++ `, ${totals.compatible} compatible, ${totals.undated_unresolved} undated, ${totals.ambiguous_same_date} same-date` ++ (totals.errors ? `, ${totals.errors} judge error(s)` : '') + (budgetExhausted ? ' (budget exhausted)' : '') ++ `. Cost: $${meter.totalSpent.toFixed(4)} / $${config.budgetUsd.toFixed(2)} with ${model}`;+ const status = budgetExhausted || totals.errors ? (totals.judged ? 'partial' : 'failed') : 'complete';+ return done(status, detail, totals);+}++async function recordProposal(+ engine: BrainEngine, g: SubjectGroup, a: CandidateRow, b: CandidateRow, hash: string,+ p: { status: string; model: string; confidence?: number | null; endingTo?: number; closeDate?: string; bornClosed?: boolean; line?: string; detail?: string },+): Promise<number | null> {+ const rows = await engine.executeRaw<{ id: number }>(+ `INSERT INTO link_edge_proposals (source_id, from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash, status,+ ending_to_page_id, close_date, born_closed, model, confidence, generated_line, detail)+ VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9::date, $10, $11, $12, $13, $14)+ ON CONFLICT (from_page_id, a_to_page_id, b_to_page_id, link_type, evidence_hash) DO NOTHING+ RETURNING id`,+ [g.sourceId, g.fromId, Number(a.to_page_id), Number(b.to_page_id), g.linkType, hash, p.status,+ p.endingTo ?? null, p.closeDate ?? null, p.bornClosed ?? false, p.model, p.confidence ?? null, p.line ?? null, p.detail ?? null]);+ return rows[0] ? Number(rows[0].id) : null;+}++// ─── Apply / undo / revert detection ─────────────────────────────────────++export type ApplyOutcome = { status: 'applied' | 'stale' | 'not_found' | 'refused' | 'undone' | 'rejected'; reason?: string };++interface ProposalRow {+ id: number; source_id: string; status: string; from_page_id: number; ending_to_page_id: number | null;+ link_type: string; close_date: unknown; generated_line: string | null; subject_slug: string; ending_slug: string | null;+}++async function loadProposal(engine: BrainEngine, id: number): Promise<ProposalRow | null> {+ const [row] = await engine.executeRaw<ProposalRow>(+ `SELECT p.id, p.source_id, p.status, p.from_page_id, p.ending_to_page_id, p.link_type, p.close_date::text AS close_date,+ p.generated_line, f.slug AS subject_slug, t.slug AS ending_slug+ FROM link_edge_proposals p JOIN pages f ON f.id = p.from_page_id LEFT JOIN pages t ON t.id = p.ending_to_page_id+ WHERE p.id = $1`, [id]);+ return row ?? null;+}++/** Does the subject page carry this proposal's closure (a dream transition on the ending relationship at the close date)? */+async function closureLanded(engine: BrainEngine, p: ProposalRow): Promise<boolean> {+ const rows = await engine.executeRaw(+ `SELECT 1 FROM link_transitions WHERE origin_page_id = $1 AND from_page_id = $1 AND to_page_id = $2 AND link_type = $3+ AND kind = 'end' AND producer = 'dream' AND occurred_on = $4::date LIMIT 1`,+ [p.from_page_id, p.ending_to_page_id, p.link_type, dateKey(p.close_date)]);+ return rows.length > 0;+}++/**+ * Apply one proposal: append the closure line to the subject page through the+ * coordinated add_timeline_entry mutation, re-derive that page's links (so the+ * closure lands as a 'dream' transition), then mark the proposal applied.+ * Refuses when the relationships changed since the judgment (stale).+ * Idempotent: replaying an applied proposal changes nothing.+ */+export async function applyEdgeProposal(engine: BrainEngine, id: number): Promise<ApplyOutcome> {+ const p = await loadProposal(engine, id);+ if (!p) return { status: 'not_found' };+ if (p.status === 'applied') return { status: 'applied', reason: 'already applied' };+ if (p.status !== 'proposed') return { status: 'refused', reason: `proposal is ${p.status}` };+ if (!p.ending_slug || !p.generated_line) return { status: 'refused', reason: 'proposal has no closure to apply' };+ const [current] = await engine.executeRaw<{ a: string; b: string }>(+ `SELECT la.evidence_hash AS a, lb.evidence_hash AS b FROM link_edge_proposals pr+ JOIN link_relationships la ON la.from_page_id = pr.from_page_id AND la.to_page_id = pr.a_to_page_id AND la.link_type = pr.link_type AND la.scope = 'all'+ JOIN link_relationships lb ON lb.from_page_id = pr.from_page_id AND lb.to_page_id = pr.b_to_page_id AND lb.link_type = pr.link_type AND lb.scope = 'all'+ WHERE pr.id = $1`, [id]);+ const [stored] = await engine.executeRaw<{ evidence_hash: string }>(`SELECT evidence_hash FROM link_edge_proposals WHERE id = $1`, [id]);+ const hashNow = current ? createHash('sha256').update([current.a, current.b].sort().join(':')).digest('hex').slice(0, 32) : null;+ if (hashNow !== stored?.evidence_hash) {+ await engine.executeRaw(`UPDATE link_edge_proposals SET status = 'stale', updated_at = now() WHERE id = $1`, [id]);+ return { status: 'stale', reason: 'the relationships changed since the judgment; the next dream cycle re-judges them' };+ }+ await appendTimelineLine(engine, p.source_id, p.subject_slug, String(dateKey(p.close_date)), p.generated_line);+ await rederivePage(engine, p.source_id, p.subject_slug);+ const landed = await closureLanded(engine, p);+ await engine.executeRaw(`UPDATE link_edge_proposals SET status = $2, updated_at = now() WHERE id = $1`, [id, landed ? 'applied' : 'proposed']);+ return landed ? { status: 'applied' } : { status: 'refused', reason: 'the closure line was written but did not re-derive; run gbrain extract --stale and re-check' };+}++/** Reject a proposal (it will not be applied; a later evidence change re-judges the pair). */+export async function rejectEdgeProposal(engine: BrainEngine, id: number): Promise<ApplyOutcome> {+ const rows = await engine.executeRaw(`UPDATE link_edge_proposals SET status = 'rejected', updated_at = now() WHERE id = $1 AND status IN ('proposed','undated_unresolved','ambiguous_same_date') RETURNING 1`, [id]);+ return rows.length ? { status: 'rejected' } : { status: 'refused', reason: 'only open proposals can be rejected' };+}++/** Undo an applied proposal: remove its exact closure line, re-derive, mark undone. */+export async function undoEdgeProposal(engine: BrainEngine, id: number): Promise<ApplyOutcome> {+ const p = await loadProposal(engine, id);+ if (!p) return { status: 'not_found' };+ if (p.status !== 'applied' || !p.generated_line) return { status: 'refused', reason: `proposal is ${p.status}` };+ const removed = await removeTimelineLine(engine, p.source_id, p.subject_slug, String(dateKey(p.close_date)), p.generated_line);+ await rederivePage(engine, p.source_id, p.subject_slug);+ await engine.executeRaw(`UPDATE link_edge_proposals SET status = 'undone', updated_at = now() WHERE id = $1`, [id]);+ return { status: 'undone', ...(removed ? {} : { reason: 'the closure line was already gone' }) };+}++/** Applied proposals whose closure line the user deleted become reverted_by_user (never re-proposed for that evidence). */+async function markRevertedProposals(engine: BrainEngine): Promise<number> {+ const rows = await engine.executeRaw<{ id: number }>(+ `UPDATE link_edge_proposals p SET status = 'reverted_by_user', updated_at = now()+ WHERE p.status = 'applied' AND p.updated_at < now() AND NOT EXISTS (+ SELECT 1 FROM link_transitions t WHERE t.origin_page_id = p.from_page_id AND t.from_page_id = p.from_page_id+ AND t.to_page_id = p.ending_to_page_id AND t.link_type = p.link_type AND t.kind = 'end' AND t.producer = 'dream'+ AND t.occurred_on = p.close_date)+ RETURNING p.id`);+ return rows.length;+}++async function trustedCtx(engine: BrainEngine, sourceId: string) {+ return {+ engine, config: { engine: engine.kind }, remote: false, dryRun: false, sourceId,+ logger: { info: () => {}, warn: () => {}, error: () => {} },+ } as unknown as import('../operations.ts').OperationContext;+}++async function appendTimelineLine(engine: BrainEngine, sourceId: string, slug: string, date: string, summary: string): Promise<void> {+ const { operations } = await import('../operations.ts');+ const op = operations.find(o => o.name === 'add_timeline_entry')!;+ await op.handler(await trustedCtx(engine, sourceId), { slug, date, summary, source: DREAM_TIMELINE_SOURCE });+}++async function removeTimelineLine(engine: BrainEngine, sourceId: string, slug: string, date: string, summary: string): Promise<boolean> {+ const snapshot = await engine.readPageSnapshot(slug, { sourceId });+ if (!snapshot) return false;+ const needle = `- **${date}** | ${DREAM_TIMELINE_SOURCE} — ${summary}`;+ const strip = (text: string) => text.split('\n').filter(l => l.trim() !== needle).join('\n');+ const page = snapshot.page;+ const compiled = strip(page.compiled_truth ?? ''), timeline = strip(page.timeline ?? '');+ if (compiled === (page.compiled_truth ?? '') && timeline === (page.timeline ?? '')) return false;+ const { serializeMarkdown } = await import('../markdown.ts');+ const { operations } = await import('../operations.ts');+ const put = operations.find(o => o.name === 'put_page')!;+ const content = serializeMarkdown((page.frontmatter ?? {}) as Record<string, unknown>, compiled, timeline,+ { type: page.type, title: page.title, tags: snapshot.tags });+ await put.handler(await trustedCtx(engine, sourceId), { slug, content, expected_revision: snapshot.revision });+ return true;+}++/** Re-derive one page's links + temporal evidence from its current content (zero LLM). */+async function rederivePage(engine: BrainEngine, sourceId: string, slug: string): Promise<void> {+ const { autoLinkWrittenPage } = await import('../ops/pages.ts');+ await autoLinkWrittenPage(engine, slug, { sourceId });+}diff --git a/src/core/cycle/phantom-redirect.ts b/src/core/cycle/phantom-redirect.tsindex 893b8f2c35..31d09bc52b 100644--- a/src/core/cycle/phantom-redirect.ts+++ b/src/core/cycle/phantom-redirect.ts@@ -492,7 +492,7 @@ export async function tryRedirectPhantom(}// Codex #1: phantom-specific resolver bypasses exact-self-match.- const canonical = await resolvePhantomCanonical(engine, sourceId, page.slug);+ const canonical = await resolvePhantomCanonical(engine, sourceId, page.slug, { type: page.type });if (!canonical) {logPhantomEvent({phantom_slug: page.slug,diff --git a/src/core/cycle/phase-scope.ts b/src/core/cycle/phase-scope.tsindex 5728acd454..0774409622 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',+ edge_contradictions: 'global',chronicle: 'global',embed: 'global',orphans: 'global',diff --git a/src/core/cycle/phase-table.ts b/src/core/cycle/phase-table.tsindex 65ed1f87b6..94c07985e0 100644--- a/src/core/cycle/phase-table.ts+++ b/src/core/cycle/phase-table.ts@@ -35,6 +35,7 @@ export const MANAGED_PHASE_TABLE: Readonly<Record<CyclePhase, ManagedPhaseEntry>propose_takes: { class: 'no_coordinated_write', reason: 'Writes the take_proposals review queue; managed brains skip the legacy receipt page.' },grade_takes: { class: 'no_coordinated_write', reason: 'The cycle runs it with auto-resolve off, so it only caches verdicts in take_grade_cache; opt-in auto-applied resolutions go through the coordinated takes_resolve mutation.' },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.' },chronicle: { class: 'writes', reason: 'Life Chronicle event pages and their projections publish through the maintenance coordinator, re-validated against the judged depth revision.' },conversation_facts_backfill: { class: 'writes', reason: 'Backfilled conversation facts publish through coordinated writes.' },diff --git a/src/core/entities/resolve.ts b/src/core/entities/resolve.tsindex a1db9cf0df..7e2cec5e2b 100644--- a/src/core/entities/resolve.ts+++ b/src/core/entities/resolve.ts@@ -401,22 +401,55 @@ export async function resolvePhantomCanonical(engine: BrainEngine,source_id: string,phantomSlug: string,+ opts: { type?: string | null } = {},): Promise<string | null> {if (!phantomSlug) return null;const trimmed = phantomSlug.trim();if (!trimmed) return null;+ // Type guard: a phantom that declares an entity type only merges into a page+ // of that type's directory (a company phantom never lands on people/…).+ const allowedDirs = opts.type ? PHANTOM_TYPE_DIRS[opts.type] : undefined;+ const typeOk = (slug: string) => !allowedDirs || allowedDirs.some(dir => slug.startsWith(`${dir}/`));// The phantom slug is the input; we treat it as the search term too,// because phantom slugs ARE the lowercased bare name a fuzzy / prefix- // lookup would naturally target.- const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed, false);- if (fuzzy && fuzzy !== phantomSlug && fuzzy.includes('/')) return fuzzy;+ // lookup would naturally target. Short or repetitive names carry too little+ // signal for a trigram match, so they skip the fuzzy tier.+ if (hasNameSignal(trimmed.replace(/-/g, ' '))) {+ const fuzzy = await tryFuzzyMatch(engine, source_id, trimmed, false);+ if (fuzzy && fuzzy !== phantomSlug && fuzzy.includes('/') && typeOk(fuzzy)) return fuzzy;+ }const expanded = await tryPrefixExpansion(engine, source_id, slugify(trimmed));- if (expanded && expanded !== phantomSlug && expanded.includes('/')) return expanded;+ if (expanded && expanded !== phantomSlug && expanded.includes('/') && typeOk(expanded)) return expanded;return null;}+/** Entity types whose phantoms may only merge into their own directories. */+const PHANTOM_TYPE_DIRS: Readonly<Record<string, readonly string[]>> = {+ person: ['people'],+ company: ['companies'],+ project: ['projects'],+ host: ['hosts'],+};++/**+ * Name-specificity gate for fuzzy phantom merges: at least 6 characters or two+ * tokens, and Shannon character entropy of at least 1.5 bits. Short or+ * repetitive names ("ai", "aaaa") defer to the stricter prefix tier.+ */+export function hasNameSignal(name: string): boolean {+ const normalized = name.trim().toLowerCase().replace(/\s+/g, ' ');+ if (normalized.length < 6 && normalized.split(' ').length < 2) return false;+ const chars = normalized.replace(/ /g, '');+ if (!chars) return false;+ const counts = new Map<string, number>();+ for (const c of chars) counts.set(c, (counts.get(c) ?? 0) + 1);+ let entropy = 0;+ for (const n of counts.values()) { const p = n / chars.length; entropy -= p * Math.log2(p); }+ return entropy >= 1.5;+}+/*** v0.35.5 — standalone candidate query for ambiguity detection (codex #11).*diff --git a/src/core/link-relationships.ts b/src/core/link-relationships.tsindex 963fb8c968..b348538ae7 100644--- a/src/core/link-relationships.ts+++ b/src/core/link-relationships.ts@@ -209,6 +209,13 @@ export async function staleRelationshipKeys(exec: RawExec, limit = 500): PromiseGROUP BY from_page_id, to_page_id, link_typeORDER BY min(newest) LIMIT $2`,[[...TEMPORAL_LINK_TYPES], limit]);- return rows.map(r => ({ from_page_id: Number(r.from_page_id), to_page_id: Number(r.to_page_id), link_type: r.link_type }));+ // State rows whose evidence is gone entirely (raw deletes) are refreshed away too.+ const orphans = rows.length >= limit ? [] : await exec.executeRaw<RelationshipKey>(+ `SELECT lr.from_page_id, lr.to_page_id, lr.link_type FROM link_relationships lr+ WHERE lr.scope = 'all'+ AND NOT EXISTS (SELECT 1 FROM links l WHERE l.from_page_id = lr.from_page_id AND l.to_page_id = lr.to_page_id AND l.link_type = lr.link_type)+ AND NOT EXISTS (SELECT 1 FROM link_transitions t WHERE t.from_page_id = lr.from_page_id AND t.to_page_id = lr.to_page_id AND t.link_type = lr.link_type)+ LIMIT $1`, [limit - rows.length]);+ return [...rows, ...orphans].map(r => ({ from_page_id: Number(r.from_page_id), to_page_id: Number(r.to_page_id), link_type: r.link_type }));}diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.tsindex 06b6549436..bb3b0cbffa 100644--- a/src/core/link-temporal-apply.ts+++ b/src/core/link-temporal-apply.ts@@ -101,3 +101,45 @@ export async function applyTemporalEvidence(const refreshed = await refreshRelationships(tx, [...keysBefore, ...keysAfter]);return { transitions: inserted.length, refreshed, unmatched };}++/**+ * Manual (database-only) dated statements for one relationship, from add_link+ * valid_from / valid_until. Runs in the caller's transaction (coordinated or+ * maintenance). Returns the number of transitions written.+ */+export async function writeManualTransitions(+ tx: Tx,+ rel: { from: string; to: string; linkType: string; sourceId: string },+ dates: { validFrom?: string; validUntil?: string },+): Promise<number> {+ const rows = [+ ...(dates.validFrom ? [{ kind: 'start', occurred_on: dates.validFrom }] : []),+ ...(dates.validUntil ? [{ kind: 'end', occurred_on: dates.validUntil }] : []),+ ];+ if (!rows.length) return 0;+ const inserted = await executeRawJsonb<RelationshipKey>(tx,+ `INSERT INTO link_transitions (source_id, from_page_id, to_page_id, link_type, kind, occurred_on, producer, origin_page_id)+ SELECT $1, f.id, t.id, $4, v.kind, v.occurred_on::date, 'manual', NULL+ FROM jsonb_to_recordset(($5::jsonb)->'rows') AS v(kind text, occurred_on text)+ JOIN pages f ON f.slug = $2 AND f.source_id = $1 AND f.deleted_at IS NULL+ JOIN pages t ON t.slug = $3 AND t.source_id = $1 AND t.deleted_at IS NULL+ ON CONFLICT DO NOTHING+ RETURNING from_page_id, to_page_id, link_type`,+ [rel.sourceId, rel.from, rel.to, rel.linkType], [{ rows }]);+ const [key] = await tx.executeRaw<RelationshipKey>(+ `SELECT f.id AS from_page_id, t.id AS to_page_id, $4::text AS link_type FROM pages f, pages t+ WHERE f.slug = $2 AND f.source_id = $1 AND t.slug = $3 AND t.source_id = $1`, [rel.sourceId, rel.from, rel.to, rel.linkType]);+ if (key) await refreshRelationships(tx, [key]);+ return inserted.length;+}++/** remove_link companion: drop manual dated statements for the removed relationship(s). */+export async function removeManualTransitions(tx: Tx, rel: { from: string; to: string; linkType?: string; sourceId: string }): Promise<void> {+ const keys = await tx.executeRaw<RelationshipKey>(+ `DELETE FROM link_transitions lt USING pages f, pages t+ WHERE f.id = lt.from_page_id AND t.id = lt.to_page_id AND f.slug = $1 AND t.slug = $2+ AND f.source_id = $3 AND t.source_id = $3 AND lt.producer = 'manual'+ AND ($4::text IS NULL OR lt.link_type = $4)+ RETURNING lt.from_page_id, lt.to_page_id, lt.link_type`, [rel.from, rel.to, rel.sourceId, rel.linkType ?? null]);+ if (keys.length) await refreshRelationships(tx, keys);+}diff --git a/src/core/minions/protected-names.ts b/src/core/minions/protected-names.tsindex 82e62aeb5d..2a7619c02b 100644--- a/src/core/minions/protected-names.ts+++ b/src/core/minions/protected-names.ts@@ -31,6 +31,8 @@ export const PROTECTED_JOB_NAMES: ReadonlySet<string> = new Set(['synthesize','patterns','consolidate',+ // Temporal typed edges: the contradiction phase calls the chat model.+ 'edge_contradictions',// 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/ops/edge-temporal.ts b/src/core/ops/edge-temporal.tsindex 0b9abb501c..3980e82a7d 100644--- a/src/core/ops/edge-temporal.ts+++ b/src/core/ops/edge-temporal.ts@@ -15,12 +15,16 @@ import type { Link } from '../types.ts';import { edgeMatchesTemporal, edgeValidityEnabled, parseTemporalParams, utcToday, type EdgeTemporalOpts, type TemporalAnnotation } from '../link-validity.ts';export const TEMPORAL_EDGE_PARAMS: Record<'status' | 'as_of' | 'during', ParamDef> = {- status: { type: 'string', enum: ['live', 'ended', 'all'], description: "Relationship status: live (default: what is true now, or at as_of), ended (former only), all (history)." },- as_of: { type: 'string', description: 'Answer as of this date (YYYY-MM-DD) instead of today.' },- during: { type: 'string', description: 'Relationships true at any point in a period: YYYY, YYYY-MM, YYYY-MM-DD or FROM..UNTIL (e.g. 2022, 2021..2023-06).' },+ status: { type: 'string', enum: ['live', 'ended', 'all'], description: 'Default live (true now).' },+ as_of: { type: 'string', description: 'YYYY-MM-DD.' },+ during: { type: 'string', description: 'Period: 2022, 2022-03 or 2021..2023.' },};+/** Starter-surface (budgeted) forms: live is the default; `all` = history. */+export const STARTER_STATUS_PARAM: ParamDef = { type: 'string', enum: ['live', 'all'], description: 'Default live.' };+export const STARTER_AS_OF_PARAM: ParamDef = { type: 'string', description: 'YYYY-MM-DD' };+/** Validate the temporal params and resolve the effective policy for this call. */export async function resolveEdgeTemporal(ctx: OperationContext, p: Record<string, unknown>, opName: string): Promise<EdgeTemporalOpts> {const parsed = parseTemporalParams({ status: p.status, as_of: p.as_of, during: p.during });@@ -36,7 +40,17 @@ export async function resolveEdgeTemporal(ctx: OperationContext, p: Record<strinexport function filterTemporalLinks(links: Link[], temporal: EdgeTemporalOpts): { kept: Link[]; hidden: number } {if (temporal.disabled) return { kept: links, hidden: 0 };const kept = links.filter(l => edgeMatchesTemporal(l as Link & TemporalAnnotation, temporal));- return { kept, hidden: links.length - kept.length };+ // A default (live, today) read keeps the established row shape: every kept+ // row is live, so the annotation adds nothing. History reads (status, as_of,+ // during) return each row's status, stints, recorded_at and retired_at.+ const historyRead = (temporal.status ?? 'live') !== 'live' || !!temporal.asOf || !!temporal.during;+ const shaped = kept.map(l => {+ const { first_start: _first, ...rest } = l as Link & { first_start?: unknown };+ if (historyRead) return rest as Link;+ const { status: _s, stints: _st, recorded_at: _r, retired_at: _rt, ...plain } = rest as Link & TemporalAnnotation;+ return plain as Link;+ });+ return { kept: shaped, hidden: links.length - kept.length };}/**diff --git a/src/core/ops/links.ts b/src/core/ops/links.tsindex 243746bf20..c8454c129a 100644--- a/src/core/ops/links.ts+++ b/src/core/ops/links.ts@@ -28,7 +28,10 @@ import { PageMissingError } from '../engine-errors.ts';import { TRAVERSE_PATH_ROW_CAP } from '../engine-constants.ts';// #4224: flag-gated cross-source identity union for the link read ops.import { unionLinksAcrossIdentity } from '../entity-identity.ts';-import { TEMPORAL_EDGE_PARAMS, resolveEdgeTemporal, filterTemporalLinks, reportTemporal } from './edge-temporal.ts';+import { TEMPORAL_EDGE_PARAMS, STARTER_STATUS_PARAM, STARTER_AS_OF_PARAM, resolveEdgeTemporal, filterTemporalLinks, reportTemporal } from './edge-temporal.ts';+import { isCalendarDate, relationSemantics, TEMPORAL_LINK_TYPES } from '../link-validity.ts';+import { writeManualTransitions, removeManualTransitions } from '../link-temporal-apply.ts';+import { maintenanceTransaction } from '../persistence/attribution.ts';// #4655: write-time pack vocabulary enforcement for explicit link verbs.import {loadActivePackForWriteVocabulary,@@ -51,6 +54,29 @@ import {*/export const MANAGED_LINK_SOURCES = ['markdown', 'frontmatter', 'mentions', 'wikilink-resolved'];+/** add_link valid_from / valid_until: calendar dates on a dated relation type. Null when neither is given. */+function validateLinkDates(ctx: OperationContext, p: Record<string, unknown>, linkType: string): { validFrom?: string; validUntil?: string } | null {+ const validFrom = p.valid_from, validUntil = p.valid_until;+ if (validFrom === undefined && validUntil === undefined) return null;+ for (const [name, value] of [['valid_from', validFrom], ['valid_until', validUntil]] as const) {+ if (value !== undefined && !isCalendarDate(value)) {+ throw opError('invalid_params', `add_link: ${name} must be a calendar date YYYY-MM-DD (got ${JSON.stringify(value)})`,+ `Pass ${paramUse(ctx, name, '2025-03-01')}; omit it when the date is unknown.`);+ }+ }+ if (typeof validFrom === 'string' && typeof validUntil === 'string' && validUntil < validFrom) {+ throw opError('invalid_params', 'add_link: valid_until is before valid_from', `Swap them, or pass only ${paramUse(ctx, 'valid_until')} to record when the relationship ended.`);+ }+ if (relationSemantics(linkType) === 'reference') {+ throw opError('invalid_params', `add_link: link_type '${linkType || '(none)'}' has no dates; valid_from/valid_until apply to dated relations (${TEMPORAL_LINK_TYPES.join(', ')})`,+ `Pass link_type such as works_at with the dates, or drop valid_from/valid_until.`);+ }+ if (relationSemantics(linkType) === 'event' && validUntil !== undefined) {+ throw opError('invalid_params', `add_link: ${linkType} is an event and does not end; pass only valid_from (when it happened)`, `Drop ${paramUse(ctx, 'valid_until')}.`);+ }+ return { ...(typeof validFrom === 'string' ? { validFrom } : {}), ...(typeof validUntil === 'string' ? { validUntil } : {}) };+}+const add_link: Operation = {name: 'add_link',idempotent: false,@@ -62,6 +88,8 @@ const add_link: Operation = {link_type: { type: 'string', description: 'Link type (e.g., invested_in, works_at). When the active schema pack declares a link vocabulary, an explicit link_type must be one of its declared verbs (undeclared verbs are rejected, also under dry_run). Omitted = untyped edge.' },context: { type: 'string', description: 'Context for the link' },link_source: { type: 'string', description: "Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected." },+ valid_from: { type: 'string', description: 'When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in.' },+ valid_until: { type: 'string', description: 'When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended.' },},mutating: true,scope: 'write',@@ -85,6 +113,7 @@ const add_link: Operation = {);}}+ const dates = validateLinkDates(ctx, p, linkType);if (ctx.dryRun) return { dry_run: true, action: 'add_link', from: p.from, to: p.to };// v114 (#1941): default omitted provenance to 'manual' (NOT the engine's// 'markdown' default) so hand/tool-created CLI edges are honestly manual,@@ -107,15 +136,25 @@ const add_link: Operation = {await requireWritablePage(ctx, p.to as string, 'add_link', 'to');try {// #5280: a managed brain takes the coordinated database-only path.- const managed = await coordinatedManualLinkWrite(ctx, 'add_link', p.from as string, p.to as string, (engine, sourceId) =>- engine.addLink(p.from as string, p.to as string, (p.context as string) || '', linkType, linkSource, undefined, undefined, // gbrain-allow-direct-insert: coordinated manual link inside withCoordinatedWrite- { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId }));- if (!managed) await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hook+ const managed = await coordinatedManualLinkWrite(ctx, 'add_link', p.from as string, p.to as string, async (engine, sourceId) => {+ await engine.addLink(p.from as string, p.to as string, (p.context as string) || '', linkType, linkSource, undefined, undefined, // gbrain-allow-direct-insert: coordinated manual link inside withCoordinatedWrite+ { fromSourceId: sourceId, toSourceId: sourceId, originSourceId: sourceId });+ if (dates) await writeManualTransitions(engine, { from: p.from as string, to: p.to as string, linkType, sourceId }, dates);+ });+ if (!managed && !dates) await ctx.engine.addLink( // gbrain-allow-direct-insert: add_link MCP op is the explicit canonical surface for manual link creation; auto-link reconciliation runs separately via auto_link post-hookp.from as string, p.to as string,(p.context as string) || '', linkType,linkSource, undefined, undefined,linkOpts,);+ if (!managed && dates) {+ const sourceId = ctx.sourceId ?? 'default';+ await maintenanceTransaction(ctx.engine, async tx => {+ await tx.addLink(p.from as string, p.to as string, (p.context as string) || '', linkType, linkSource, undefined, undefined, // gbrain-allow-direct-insert: add_link with dated manual evidence, one maintenance transaction+ linkOpts);+ await writeManualTransitions(tx, { from: p.from as string, to: p.to as string, linkType, sourceId }, dates);+ });+ }} catch (error) {// An endpoint hard-deleted between preflight and mutation: reclassify// the typed engine miss instead of surfacing it as internal_error.@@ -148,12 +187,19 @@ const remove_link: Operation = {const linkOpts = ctx.sourceId? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }: undefined;- const remove = (engine: typeof ctx.engine, opts: typeof linkOpts) => engine.removeLink(- p.from as string, p.to as string,- (p.link_type as string) || undefined,- (p.link_source as string) || undefined,- opts,- );+ const remove = async (engine: typeof ctx.engine, opts: typeof linkOpts) => {+ const removed = await engine.removeLink(+ p.from as string, p.to as string,+ (p.link_type as string) || undefined,+ (p.link_source as string) || undefined,+ opts,+ );+ // Manual dated statements belong to manual edges; drop them with the edge.+ if (removed > 0 && (!p.link_source || p.link_source === 'manual')) {+ await removeManualTransitions(engine, { from: p.from as string, to: p.to as string, linkType: (p.link_type as string) || undefined, sourceId: opts?.fromSourceId ?? 'default' });+ }+ return removed;+ };// #4527: report how many edges actually died — an unconditional// `{ status: 'ok' }` made a zero-match delete (typo'd slug, wrong// link_type, already removed) indistinguishable from a real removal.@@ -324,10 +370,10 @@ const get_links: Operation = {mutating: false,idempotent: true,outputRedaction: 'retrieval',- description: 'List a page\'s outgoing links (typed edges to other pages). Returns relationships that are true today, each with status and dates; pass status: "all" for history, as_of for a past date, during for a period (e.g. where someone worked in 2022). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.',+ description: 'List a page\'s outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: "all" for history, during: "2022" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.',params: {slug: { type: 'string', required: true, description: 'Slug of the page whose outgoing links to list.' },- link_type: { type: 'string', description: 'Only this link type (e.g. works_at).' },+ link_type: { type: 'string', description: 'Only this type.' },...TEMPORAL_EDGE_PARAMS,source_id: LINK_SOURCE_ID_PARAM,all_sources: LINK_ALL_SOURCES_PARAM,@@ -342,11 +388,11 @@ const get_backlinks: Operation = {mutating: false,idempotent: true,outputRedaction: 'retrieval',- description: 'List links pointing to a page, such as who works at a company. Returns relationships true today; status: "ended" lists former ones, status: "all" history, as_of / during a past date or period.',+ description: 'List links pointing to a page. Use when finding what mentions an entity.',params: {slug: { type: 'string', description: 'Page slug.', required: true },- link_type: { type: 'string', description: 'Only this link type (e.g. works_at).' },- ...TEMPORAL_EDGE_PARAMS,+ status: STARTER_STATUS_PARAM,+ as_of: STARTER_AS_OF_PARAM,source_id: LINK_SOURCE_ID_PARAM,all_sources: LINK_ALL_SOURCES_PARAM,},@@ -401,14 +447,14 @@ const traverse_graph: Operation = {mutating: false,idempotent: true,outputRedaction: 'retrieval',- description: `Walk the link graph from a page along relationships that are true today (status: "all" walks history, as_of a past date). Remote callers get bidirectional paths at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} by default.`,+ description: `Walk the link graph from a page. Remote callers get bidirectional paths at depth ${REMOTE_BIDIRECTIONAL_DEFAULT_DEPTH} by default.`,params: {slug: { type: 'string', description: 'Start page slug.', required: true },depth: { type: 'number', description: `Max depth (cap ${TRAVERSE_DEPTH_CAP}).` },link_type: { type: 'string', description: 'Follow only this link type.' },direction: { type: 'string', description: 'Remote default both.', enum: ['in', 'out', 'both'] },- status: TEMPORAL_EDGE_PARAMS.status,- as_of: TEMPORAL_EDGE_PARAMS.as_of,+ status: STARTER_STATUS_PARAM,+ as_of: STARTER_AS_OF_PARAM,source_id: LINK_SOURCE_ID_PARAM,all_sources: LINK_ALL_SOURCES_PARAM,},diff --git a/test/cycle-edge-contradictions.test.ts b/test/cycle-edge-contradictions.test.tsnew file mode 100644index 0000000000..e322bee0a9--- /dev/null+++ b/test/cycle-edge-contradictions.test.ts@@ -0,0 +1,133 @@+/**+ * Dream phase edge_contradictions (temporal typed edges): the judge only flags+ * conflicts; date arithmetic picks the ending relationship and date. Covers+ * propose vs apply, accept/undo/reject, reverted-by-user, undated pairs,+ * malformed judge output, compatible caching and the budget cap.+ */+import { afterAll, beforeAll, beforeEach, describe, expect, setDefaultTimeout, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { resetPgliteState } from './helpers/reset-pglite.ts';+import { operations } from '../src/core/operations.ts';+import type { OperationContext } from '../src/core/operations.ts';+import { resetGateway } from '../src/core/ai/gateway.ts';+import {+ runPhaseEdgeContradictions, applyEdgeProposal, undoEdgeProposal, rejectEdgeProposal, parseEdgeJudgeOutput, type EdgeJudgeFn,+} from '../src/core/cycle/edge-contradictions.ts';+import { relationshipFilterSql } from '../src/core/link-validity.ts';++setDefaultTimeout(60_000);+let engine: PGLiteEngine;+beforeAll(async () => { engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); });+afterAll(async () => { await engine.disconnect(); resetGateway(); });+beforeEach(async () => { await resetPgliteState(engine); resetGateway(); });++const ctx = (): OperationContext => ({ engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: false, sourceId: 'default' });+async function put(slug: string, fm: string, body: string) {+ const op = operations.find(o => o.name === 'put_page')!;+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });+ await op.handler(ctx(), { slug, ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: `---\n${fm}\n---\n\n${body}` });+}+async function seed(timeline: string) {+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');+ await put('companies/widget-co', 'type: company\ntitle: Widget', 'A company.');+ await put('people/alice-example', 'type: person\ntitle: Alice', `Alice works at [Acme](../companies/acme-example) and at [Widget](../companies/widget-co).\n\n## Timeline\n\n${timeline}`);+}+const DATED = '- **2019-02-01** | test — joined [Acme](../companies/acme-example)\n- **2024-05-01** | test — joined [Widget](../companies/widget-co)';+const conflict: EdgeJudgeFn = async () => [{ a: 1, b: 2, conflict: true, confidence: 0.9 }];+let calls = 0;+const counting = (fn: EdgeJudgeFn): EdgeJudgeFn => async (input) => { calls++; return fn(input); };+async function liveWorksAt() {+ const rows = await engine.executeRaw<{ slug: string }>(+ `SELECT DISTINCT t.slug FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id+ WHERE f.slug = 'people/alice-example' AND l.link_type = 'works_at' AND ${relationshipFilterSql('l')} ORDER BY 1`);+ return rows.map(r => r.slug);+}+const proposals = () => engine.executeRaw<{ id: number; status: string; close_date: string | null; born_closed: boolean }>(`SELECT id, status, close_date::text AS close_date, born_closed FROM link_edge_proposals ORDER BY id`);++describe('edge_contradictions', () => {+ test('propose mode records a proposal and writes nothing canonical; accept applies; undo reopens', async () => {+ await seed(DATED);+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);+ const r = await runPhaseEdgeContradictions(engine, { judge: conflict });+ expect(r.totals).toMatchObject({ judged: 1, proposed: 1, applied: 0 });+ const [p] = await proposals();+ expect(p).toMatchObject({ status: 'proposed', close_date: '2024-05-01', born_closed: false });+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);++ expect(await applyEdgeProposal(engine, p.id)).toEqual({ status: 'applied' });+ expect(await liveWorksAt()).toEqual(['companies/widget-co']);+ const page = await engine.getPage('people/alice-example', { sourceId: 'default' });+ expect(page?.timeline).toContain('gbrain-dream (inferred) — Ended works_at [[companies/acme-example]] (superseded by works_at companies/widget-co)');+ expect(await applyEdgeProposal(engine, p.id)).toEqual({ status: 'applied', reason: 'already applied' });++ expect((await undoEdgeProposal(engine, p.id)).status).toBe('undone');+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);+ });++ test('apply mode applies; a hand-deleted closure line becomes reverted_by_user and is never re-proposed', async () => {+ await seed(DATED);+ await engine.setConfig('dream.edge_contradictions.mode', 'apply');+ try {+ const r = await runPhaseEdgeContradictions(engine, { judge: conflict });+ expect(r.totals).toMatchObject({ proposed: 1, applied: 1 });+ expect(await liveWorksAt()).toEqual(['companies/widget-co']);+ // The user deletes the line by rewriting the page without it.+ await seed(DATED);+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);+ calls = 0;+ const again = await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(again.totals).toMatchObject({ reverted: 1 });+ expect(calls).toBe(0);+ expect((await proposals()).map(p => p.status)).toEqual(['reverted_by_user']);+ } finally { await engine.setConfig('dream.edge_contradictions.mode', 'propose'); }+ });++ test('undated relationships are never closed; the proposal asks for a date', async () => {+ await seed('- **2024-05-01** | test — joined [Widget](../companies/widget-co)');+ const r = await runPhaseEdgeContradictions(engine, { judge: conflict });+ expect(r.totals).toMatchObject({ undated_unresolved: 1, proposed: 0 });+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);+ });++ test('compatible verdicts are cached: the same evidence is not judged twice', async () => {+ await seed(DATED);+ calls = 0;+ const compatible = counting(async () => [{ a: 1, b: 2, conflict: false, confidence: 0.8 }]);+ await runPhaseEdgeContradictions(engine, { judge: compatible });+ await runPhaseEdgeContradictions(engine, { judge: compatible });+ expect(calls).toBe(1);+ expect((await proposals()).map(p => p.status)).toEqual(['compatible']);+ });++ test('malformed judge output is an error row, never a closure', async () => {+ await seed(DATED);+ const r = await runPhaseEdgeContradictions(engine, { judge: async () => null });+ expect(r.totals).toMatchObject({ errors: 1, proposed: 0 });+ expect(r.status).toBe('partial');+ expect(parseEdgeJudgeOutput('I cannot help with that.', 2)).toBeNull();+ expect(parseEdgeJudgeOutput('{"pairs":[{"a":1,"b":9,"conflict":true}]}', 2)).toBeNull();+ expect(parseEdgeJudgeOutput('{"pairs":[{"a":1,"b":2,"conflict":true,"confidence":2}]}', 2)).toEqual([{ a: 1, b: 2, conflict: true, confidence: 1 }]);+ });++ test('zero budget spends nothing', async () => {+ await seed(DATED);+ await engine.setConfig('dream.edge_contradictions.max_usd', '0');+ try {+ calls = 0;+ const r = await runPhaseEdgeContradictions(engine, { judge: counting(conflict) });+ expect(calls).toBe(0);+ expect(r.detail).toContain('budget exhausted');+ } finally { await engine.setConfig('dream.edge_contradictions.max_usd', '1'); }+ });++ test('reject keeps both relationships; mode off skips', async () => {+ await seed(DATED);+ await runPhaseEdgeContradictions(engine, { judge: conflict });+ const [p] = await proposals();+ expect((await rejectEdgeProposal(engine, p.id)).status).toBe('rejected');+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);+ await engine.setConfig('dream.edge_contradictions.mode', 'off');+ try { expect((await runPhaseEdgeContradictions(engine, { judge: conflict })).status).toBe('skipped'); }+ finally { await engine.setConfig('dream.edge_contradictions.mode', 'propose'); }+ });+});diff --git a/test/fixtures/goldens/cli/help-and-errors.json b/test/fixtures/goldens/cli/help-and-errors.jsonindex 2dd82bd490..ba46b18f42 100644--- a/test/fixtures/goldens/cli/help-and-errors.json+++ b/test/fixtures/goldens/cli/help-and-errors.json@@ -720,7 +720,9 @@" <to> Slug of the page the link points to, e.g. 'companies/acme-example'. (required)"," --link-type Link type (e.g., invested_in, works_at). When the active schema pack declares a link vocabulary, an explicit link_type must be one of its declared verbs (undeclared verbs are rejected, also under dry_run). Omitted = untyped edge."," --context Context for the link",- " --link-source Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected."+ " --link-source Provenance tag (kebab-case, e.g. 'citation-graph'). Defaults to 'manual'. Reconciliation-managed built-ins (markdown/frontmatter/mentions/wikilink-resolved) are rejected.",+ " --valid-from When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in.",+ " --valid-until When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended."]},{diff --git a/test/fixtures/goldens/cli/tools-json.json b/test/fixtures/goldens/cli/tools-json.jsonindex 8c613f7b27..c4950f0dcf 100644--- a/test/fixtures/goldens/cli/tools-json.json+++ b/test/fixtures/goldens/cli/tools-json.json@@ -2,8 +2,8 @@"golden": {"exitCode": 0,"stderr": "",- "stdoutBytes": 196835,- "stdoutSha256": "7c6a8f58d1ecf9152a0bef45fe6b85d84ea6bc81c4610fc65b2a65eeec68370a",+ "stdoutBytes": 198727,+ "stdoutSha256": "1bd62e59ff08b005f7796f8bb9ad92de5526d41a67a00f95811b3e7a4ec2d8c8","toolNames": ["remember","entity",@@ -1479,7 +1479,9 @@"from": "string","link_source": "string?","link_type": "string?",- "to": "string"+ "to": "string",+ "valid_from": "string?",+ "valid_until": "string?"},"required_scopes": [],"schema": {@@ -1503,6 +1505,14 @@"to": {"description": "Slug of the page the link points to, e.g. 'companies/acme-example'.","type": "string"+ },+ "valid_from": {+ "description": "When the relationship started (YYYY-MM-DD), for dated relations such as works_at or invested_in.",+ "type": "string"+ },+ "valid_until": {+ "description": "When it ended (YYYY-MM-DD, exclusive). Re-run add_link with valid_until to record that a relationship ended.",+ "type": "string"}},"required": [@@ -1554,15 +1564,19 @@"scope": "write"},{- "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.",+ "description": "List a page's outgoing links (typed edges to other pages). Use when exploring what a page points at; rows carry status and dates, live relationships by default (status: \"all\" for history, during: \"2022\" for a period). Pass source_id or all_sources to widen. Needs read scope. On page_not_found: resolve the slug with resolve_slugs.","idempotent": true,"local_only": false,"mutating": false,"name": "get_links","parameters": {"all_sources": "boolean?",+ "as_of": "string?",+ "during": "string?",+ "link_type": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1571,6 +1585,18 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD.",+ "type": "string"+ },+ "during": {+ "description": "Period: 2022, 2022-03 or 2021..2023.",+ "type": "string"+ },+ "link_type": {+ "description": "Only this type.",+ "type": "string"+ },"slug": {"description": "Slug of the page whose outgoing links to list.","type": "string"@@ -1578,6 +1604,15 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live (true now).",+ "enum": [+ "live",+ "ended",+ "all"+ ],+ "type": "string"}},"required": [@@ -1595,8 +1630,10 @@"name": "get_backlinks","parameters": {"all_sources": "boolean?",+ "as_of": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1605,6 +1642,10 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD",+ "type": "string"+ },"slug": {"description": "Page slug.","type": "string"@@ -1612,6 +1653,14 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live.",+ "enum": [+ "live",+ "all"+ ],+ "type": "string"}},"required": [@@ -1644,11 +1693,13 @@"name": "traverse_graph","parameters": {"all_sources": "boolean?",+ "as_of": "string?","depth": "number?","direction": "string?","link_type": "string?","slug": "string",- "source_id": "string?"+ "source_id": "string?",+ "status": "string?"},"required_scopes": [],"schema": {@@ -1657,6 +1708,10 @@"description": "Same as source_id __all__.","type": "boolean"},+ "as_of": {+ "description": "YYYY-MM-DD",+ "type": "string"+ },"depth": {"description": "Max depth (cap 10).","type": "number"@@ -1681,6 +1736,14 @@"source_id": {"description": "One source, or '__all__'.","type": "string"+ },+ "status": {+ "description": "Default live.",+ "enum": [+ "live",+ "all"+ ],+ "type": "string"}},"required": [@@ -6268,6 +6331,7 @@"degraded_dedup","empty_retrieval","features_auto_fix",+ "former_relationships_hidden","listing_truncated","local_transcripts","onboard_opportunities",diff --git a/test/fixtures/goldens/doctor/json-pglite-degraded.json b/test/fixtures/goldens/doctor/json-pglite-degraded.jsonindex 22c4a12451..b72f8fcec2 100644--- a/test/fixtures/goldens/doctor/json-pglite-degraded.json+++ b/test/fixtures/goldens/doctor/json-pglite-degraded.json@@ -507,13 +507,13 @@},{"category": "meta",- "message": "Version 200 (latest: 200)",+ "message": "Version 201 (latest: 201)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "853 column(s) verified against live schema",+ "message": "901 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1653,7 +1653,7 @@"category": "meta","details": {"counts": {- "global": 10,+ "global": 11,"mixed": 2,"source": 12},@@ -1664,6 +1664,7 @@"consolidate": "source","conversation_facts_backfill": "source","drift": "global",+ "edge_contradictions": "global","embed": "global","enrich_thin": "source","extract": "source",@@ -1684,7 +1685,7 @@"synthesize_concepts": "global"}},- "message": "Phase taxonomy: 12 source-scoped, 10 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, drift, chronicle, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 11 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/doctor/json-pglite-fresh.json b/test/fixtures/goldens/doctor/json-pglite-fresh.jsonindex 153d996111..d7feca2855 100644--- a/test/fixtures/goldens/doctor/json-pglite-fresh.json+++ b/test/fixtures/goldens/doctor/json-pglite-fresh.json@@ -510,13 +510,13 @@},{"category": "meta",- "message": "Version 200 (latest: 200)",+ "message": "Version 201 (latest: 201)","name": "schema_version","status": "ok"},{"category": "meta",- "message": "853 column(s) verified against live schema",+ "message": "901 column(s) verified against live schema","name": "schema_columns","status": "ok"},@@ -1729,7 +1729,7 @@"category": "meta","details": {"counts": {- "global": 10,+ "global": 11,"mixed": 2,"source": 12},@@ -1740,6 +1740,7 @@"consolidate": "source","conversation_facts_backfill": "source","drift": "global",+ "edge_contradictions": "global","embed": "global","enrich_thin": "source","extract": "source",@@ -1760,7 +1761,7 @@"synthesize_concepts": "global"}},- "message": "Phase taxonomy: 12 source-scoped, 10 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, drift, chronicle, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].",+ "message": "Phase taxonomy: 12 source-scoped, 11 brain-global, 2 mixed. Source-safe: [lint, backlinks, sync, extract, extract_facts, extract_atoms, recompute_emotional_weight, consolidate, propose_takes, conversation_facts_backfill, enrich_thin, schema-suggest]. Brain-global: [resolve_symbol_edges, synthesize_concepts, grade_takes, calibration_profile, edge_contradictions, drift, chronicle, skillopt, embed, orphans, purge]. Mixed: [synthesize, patterns].","name": "cycle_phase_scope","status": "ok"},diff --git a/test/fixtures/goldens/exports/types.json b/test/fixtures/goldens/exports/types.jsonindex fb4aa5732c..5bd82cb118 100644--- a/test/fixtures/goldens/exports/types.json+++ b/test/fixtures/goldens/exports/types.json@@ -91,7 +91,7 @@"getAllConfig: () => Promise<Record<string, string>>","getAllSlugs: (opts?: { sourceId?: string; }) => Promise<Set<string>>","getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",- "getBacklinks: (slug: string, opts?: PageReadScope) => Promise<Link[]>",+ "getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",@@ -110,7 +110,7 @@"getHealth: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<BrainHealth>","getIngestLog: (opts?: { limit?: number; sourceIds?: string[]; }) => Promise<IngestLogEntry[]>","getLastSeen: (entitySlug: string, opts?: PageReadScope & { asof?: string; }) => Promise<LastSeenResult>",- "getLinks: (slug: string, opts?: PageReadScope) => Promise<Link[]>",+ "getLinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getOnThisDay: (opts?: PageReadScope & { date?: string; limit?: number; }) => Promise<ChronicleTimelineRow[]>","getOntology: (entitySlug: string, opts?: OntologyReadOpts) => Promise<OntologyValue[]>","getPage: (slug: string, opts?: GetPageOpts) => Promise<Page | null>",@@ -207,7 +207,7 @@"transactionDirect: <T>(fn: (engine: BrainEngine) => Promise<T>) => Promise<T>","traverseGraph: (slug: string, depth?: number, opts?: TraverseGraphOpts) => Promise<GraphNode[]>","traversePaths: (slug: string, opts?: PageReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<GraphPath[]>",- "traversePathsDetailed: (slug: string, opts?: PageReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<{ paths: GraphPath[]; truncated: boolean; }>",+ "traversePathsDetailed: (slug: string, opts?: LinkReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<{ paths: GraphPath[]; truncated: boolean; }>","unsetConfig: (key: string) => Promise<number>","updatePageContextualRetrievalState: (slug: string, sourceId: string, mode: string, corpusGeneration: string | null) => Promise<void>","updateSlug: (oldSlug: string, newSlug: string, opts?: { sourceId?: string; }) => Promise<number>",@@ -995,7 +995,7 @@"getAllConfig: () => Promise<Record<string, string>>","getAllSlugs: (opts?: { sourceId?: string; }) => Promise<Set<string>>","getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",- "getBacklinks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<Link[]>",+ "getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",@@ -1014,7 +1014,7 @@"getHealth: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<BrainHealth>","getIngestLog: (opts?: { limit?: number; sourceIds?: string[]; }) => Promise<IngestLogEntry[]>","getLastSeen: (entitySlug: string, opts?: PageReadScope & { asof?: string; }) => Promise<LastSeenResult>",- "getLinks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<Link[]>",+ "getLinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getOnThisDay: (opts?: PageReadScope & { date?: string; limit?: number; }) => Promise<ChronicleTimelineRow[]>","getOntology: (entitySlug: string, opts?: OntologyReadOpts) => Promise<OntologyValue[]>","getPage: (slug: string, opts?: PageSnapshotOptions) => Promise<Page | null>",@@ -1195,7 +1195,8 @@"seedRefs?: { source_id: string; slug: string; }[] | undefined","sourceId?: string | undefined","sourceIds?: string[] | undefined",- "takesHoldersAllowList?: string[] | undefined"+ "takesHoldersAllowList?: string[] | undefined",+ "temporal?: EdgeTemporalOpts | undefined"],"name": "RelationalFanoutOpts"},@@ -3076,7 +3077,7 @@"getAllConfig: () => Promise<Record<string, string>>","getAllSlugs: (opts?: { sourceId?: string; }) => Promise<Set<string>>","getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",- "getBacklinks: (slug: string, opts?: PageReadScope) => Promise<Link[]>",+ "getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",@@ -3095,7 +3096,7 @@"getHealth: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<BrainHealth>","getIngestLog: (opts?: { limit?: number; sourceIds?: string[]; }) => Promise<IngestLogEntry[]>","getLastSeen: (entitySlug: string, opts?: PageReadScope & { asof?: string; }) => Promise<LastSeenResult>",- "getLinks: (slug: string, opts?: PageReadScope) => Promise<Link[]>",+ "getLinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getOnThisDay: (opts?: PageReadScope & { date?: string; limit?: number; }) => Promise<ChronicleTimelineRow[]>","getOntology: (entitySlug: string, opts?: OntologyReadOpts) => Promise<OntologyValue[]>","getPage: (slug: string, opts?: GetPageOpts) => Promise<Page | null>",@@ -3192,7 +3193,7 @@"transactionDirect: <T>(fn: (engine: BrainEngine) => Promise<T>) => Promise<T>","traverseGraph: (slug: string, depth?: number, opts?: TraverseGraphOpts) => Promise<GraphNode[]>","traversePaths: (slug: string, opts?: PageReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<GraphPath[]>",- "traversePathsDetailed: (slug: string, opts?: PageReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<{ paths: GraphPath[]; truncated: boolean; }>",+ "traversePathsDetailed: (slug: string, opts?: LinkReadScope & { depth?: number; linkType?: string; direction?: \"in\" | \"out\" | \"both\"; }) => Promise<{ paths: GraphPath[]; truncated: boolean; }>","unsetConfig: (key: string) => Promise<number>","updatePageContextualRetrievalState: (slug: string, sourceId: string, mode: string, corpusGeneration: string | null) => Promise<void>","updateSlug: (oldSlug: string, newSlug: string, opts?: { sourceId?: string; }) => Promise<number>",@@ -3735,7 +3736,8 @@"frontierCap?: number | undefined","requireSafeChunks?: boolean | undefined","sourceId?: string | undefined",- "sourceIds?: string[] | undefined"+ "sourceIds?: string[] | undefined",+ "temporal?: EdgeTemporalOpts | undefined"],"name": "TraverseGraphOpts"},@@ -5864,7 +5866,7 @@"getAllConfig: () => Promise<Record<string, string>>","getAllSlugs: (opts?: { sourceId?: string; }) => Promise<Set<string>>","getBacklinkCounts: (pageIds: number[], opts?: PageReadScope) => Promise<Map<number, number>>",- "getBacklinks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<Link[]>",+ "getBacklinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getCalibrationCurve: (opts: CalibrationCurveOpts, allowList: string[] | undefined) => Promise<CalibrationBucket[]>","getCalleesOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; bareFallback?: boolean; }) => Promise<CodeEdgeResult[]>","getCallersOf: (qualifiedName: string, opts?: { sourceId?: string; allSources?: boolean; limit?: number; }) => Promise<CodeEdgeResult[]>",@@ -5883,7 +5885,7 @@"getHealth: (opts?: { sourceId?: string; sourceIds?: string[]; }) => Promise<BrainHealth>","getIngestLog: (opts?: { limit?: number; sourceIds?: string[]; }) => Promise<IngestLogEntry[]>","getLastSeen: (entitySlug: string, opts?: PageReadScope & { asof?: string; }) => Promise<LastSeenResult>",- "getLinks: (slug: string, opts?: { sourceId?: string; sourceIds?: string[]; excludePrivate?: boolean; }) => Promise<Link[]>",+ "getLinks: (slug: string, opts?: LinkReadScope) => Promise<Link[]>","getOnThisDay: (opts?: PageReadScope & { date?: string; limit?: number; }) => Promise<ChronicleTimelineRow[]>","getOntology: (entitySlug: string, opts?: OntologyReadOpts) => Promise<OntologyValue[]>","getPage: (slug: string, opts?: PageSnapshotOptions) => Promise<Page | null>",@@ -8078,7 +8080,8 @@"seedRefs?: { source_id: string; slug: string; }[] | undefined","sourceId?: string | undefined","sourceIds?: string[] | undefined",- "takesHoldersAllowList?: string[] | undefined"+ "takesHoldersAllowList?: string[] | undefined",+ "temporal?: EdgeTemporalOpts | undefined"],"name": "RelationalFanoutOpts"},diff --git a/test/fixtures/goldens/migrations/records.json b/test/fixtures/goldens/migrations/records.jsonindex 190c942fa0..cc603db989 100644--- a/test/fixtures/goldens/migrations/records.json+++ b/test/fixtures/goldens/migrations/records.json@@ -1,6 +1,6 @@{"golden": {- "count": 195,+ "count": 196,"gaps": [17,18,@@ -28,7 +28,7 @@"slugifyPath": "401dbca23580865d8b168dd8d84db4a6c708c6610d7cb61abafc7d0ee9809063","verifyProjectionStatistics": "59d9ccfea1c53384d8607874a51209a9c2dfd51b2b85a2cb6269fa4120faf1f3"},- "latest": 200,+ "latest": 201,"records": [{"handler": {@@ -2968,6 +2968,19 @@"transaction": "absent","verify": "absent","version": 200+ },+ {+ "handler": "absent",+ "idempotent": true,+ "name": "links_temporal_state",+ "sql": {+ "length": 4732,+ "sha256": "75dbc393feb6485b2a00d9c5a1c67ae3d61382845d00c67a367501d1940dadec"+ },+ "sqlFor": "absent",+ "transaction": "absent",+ "verify": "absent",+ "version": 201}],"versions": [@@ -3165,7 +3178,8 @@197,198,199,- 200+ 200,+ 201]},"normalizer": "migrations-record-v1"diff --git a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.jsonindex 6448c96bb8..b6053f59cd 100644--- a/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json+++ b/test/fixtures/goldens/postgres-engine-gauge/acquires-by-case.json@@ -282,7 +282,7 @@"tx": 1},"replaceDerivedLinks#default": {- "raw": 8,+ "raw": 12,"tx": 1},"resolveSlugWithAlias#default": {},diff --git a/test/fixtures/goldens/rls-scope-inventory.json b/test/fixtures/goldens/rls-scope-inventory.jsonindex 4cfa6a5b1c..6f052f595c 100644--- a/test/fixtures/goldens/rls-scope-inventory.json+++ b/test/fixtures/goldens/rls-scope-inventory.json@@ -25,12 +25,12 @@},"addLinksBatch#default": {"flagOffLanes": [- "pool"+ "tx"],- "flagOffOpensTransaction": false,+ "flagOffOpensTransaction": true,"flagOn": "unscoped","flagOnLanes": [- "pool"+ "tx"],"flagOnScopes": []},@@ -2483,7 +2483,8 @@},"replaceDerivedLinks#default": {"flagOffLanes": [- "tx"+ "tx",+ "tx>sp"],"flagOffOpensTransaction": true,"flagOn": "scoped",diff --git a/test/link-temporal-reads.test.ts b/test/link-temporal-reads.test.tsindex e1b706275e..68b6f0073f 100644--- a/test/link-temporal-reads.test.ts+++ b/test/link-temporal-reads.test.ts@@ -56,8 +56,10 @@ describe('get_links / get_backlinks', () => {notices.length = 0;const rows = await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at' }) as Array<Record<string, unknown>>;expect(targets(rows)).toEqual(['companies/widget-co']);- expect(rows[0].status).toBe('live');- expect(rows[0].stints).toEqual([{ from: '2025-03-01', until: null }]);+ expect(rows[0].status).toBeUndefined(); // default reads keep the established row shape+ const history = await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', status: 'live', as_of: '2026-01-01' }) as Array<Record<string, unknown>>;+ expect(history[0].status).toBe('live');+ expect(history[0].stints).toEqual([{ from: '2025-03-01', until: null }]);const notice = notices.find(n => n.code === 'former_relationships_hidden')!;expect(notice.why).toContain('1 relationship');expect(notice.fix?.mcp).toEqual({ tool: 'get_links', arguments: { slug: 'people/alice-example', link_type: 'works_at', status: 'all' } });@@ -119,3 +121,21 @@ describe('relational search arm', () => {expect([...former, ...worked].map(r => r.slug)).toContain('people/alice-example');});});++describe('add_link valid_from / valid_until', () => {+ test('dated manual edges close and reopen; invalid dates are rejected', async () => {+ await put('companies/fund-b', 'type: company\ntitle: Fund B', 'A fund.');+ await op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'advises', valid_from: '2020-01-01' });+ const live = async () => targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'advises' }));+ expect(await live()).toEqual(['companies/fund-b']);+ await op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'advises', valid_until: '2024-01-01' });+ expect(await live()).toEqual([]);+ expect(targets(await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'advises', as_of: '2022-01-01' }))).toEqual(['companies/fund-b']);+ await expect(op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'advises', valid_until: '2024-13-01' })).rejects.toThrow(/valid_until/);+ await expect(op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'mentions', valid_from: '2024-01-01' })).rejects.toThrow(/no dates/);+ await expect(op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'invested_in', valid_until: '2024-01-01' })).rejects.toThrow(/does not end/);+ await op('remove_link').handler(ctx(), { from: 'people/alice-example', to: 'companies/fund-b', link_type: 'advises' });+ const left = await engine.executeRaw(`SELECT 1 FROM link_transitions WHERE producer = 'manual'`);+ expect(left.length).toBe(0);+ });+});diff --git a/test/managed-phase-matrix.test.ts b/test/managed-phase-matrix.test.tsindex c5f0b9ec8b..6fe6bd4f27 100644--- a/test/managed-phase-matrix.test.ts+++ b/test/managed-phase-matrix.test.ts@@ -272,6 +272,23 @@ const MATRIX: Record<CyclePhase, Entry> = {expect((await engine.getPage(slug!, { sourceId: 'default' }))?.compiled_truth).toContain('DRIFTED — notes/drift-example');},},+ edge_contradictions: {+ config: { 'dream.edge_contradictions.mode': 'apply', 'models.dream.edge_contradictions': 'anthropic:claude-sonnet-4-6' },+ seed: async ({ engine, sourceId }) => {+ await put(engine, sourceId, 'companies/acme-example', page('company', 'Acme', 'A company.'));+ await put(engine, sourceId, 'companies/widget-co', page('company', 'Widget', 'A company.'));+ await put(engine, sourceId, 'people/edge-example', page('person', 'Edge Example',+ 'Works at [Acme](../companies/acme-example) and at [Widget](../companies/widget-co).\n\n## Timeline\n\n' ++ '- **2019-02-01** | test — joined [Acme](../companies/acme-example)\n- **2024-05-01** | test — joined [Widget](../companies/widget-co)'));+ },+ reply: () => JSON.stringify({ pairs: [{ a: 1, b: 2, conflict: true, confidence: 0.9 }] }),+ assert: async ({ engine, sourceId, result }) => {+ expect(result.details).toMatchObject({ proposed: 1, applied: 1 });+ const ops = await committed(engine, sourceId, 'people/edge-example');+ expect(ops.some(o => (o as { operation: string }).operation === 'add_timeline_entry')).toBe(true);+ expect((await engine.getPage('people/edge-example', { sourceId }))?.timeline).toContain('Ended works_at [[companies/acme-example]]');+ },+ },chronicle: {seed: async ({ engine, sourceId }) => {await put(engine, sourceId, 'meetings/chronicle-example', page('meeting', 'Weekly sync',diff --git a/test/mcp-schema-budget.test.ts b/test/mcp-schema-budget.test.tsindex 4a7eff8069..4503834462 100644--- a/test/mcp-schema-budget.test.ts+++ b/test/mcp-schema-budget.test.ts@@ -47,15 +47,15 @@ const INSTRUCTIONS_MAX_CHARS = 4_628;const DESCRIPTION_HARD_CAP = 1_200;const PARAM_DESCRIPTION_HARD_CAP = 200;-/** Per-tool budget: JSON.stringify of the served tool definition. */+/** Per-tool budget: JSON.stringify of the served tool definition. get_backlinks / traverse_graph carry the temporal status + as_of params (live relationships by default). */const TOOL_BUDGETS: Record<string, number> = {add_timeline_entry: 640, cancel_job: 270, cancel_write_request: 350, capture: 1250, context_pack: 760,delete_skill: 810, delta: 830, edit_page: 1090, entity: 460, find_anomalies: 520, forget: 560, get_agent_job: 270,- get_backlinks: 430, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,+ get_backlinks: 550, get_ingest_log: 280, get_page: 810, get_recent_salience: 660, get_skill: 910,get_skill_asset: 790, get_write_request: 330, join_brain: 560, leave_brain: 540, list_brain_skillpack: 230,list_link_sources: 220, list_pages: 1090, list_skills: 670, list_write_requests: 450, put_page: 1320,put_skill: 1420, query: 3250, recall: 1590, remember: 1370, request_tools: 560, resolve_slugs: 410, search: 1760,- submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 680, whoami: 230,+ submit_agent: 750, sync_brain_skills: 770, synthesize: 550, traverse_graph: 810, whoami: 230,};/** DX-14: phrases each tool's description must keep. */diff --git a/test/phantom-type-guard.test.ts b/test/phantom-type-guard.test.tsnew file mode 100644index 0000000000..a9fb888139--- /dev/null+++ b/test/phantom-type-guard.test.ts@@ -0,0 +1,34 @@+/**+ * Phantom redirect hardening: a phantom that declares an entity type only+ * merges into that type's directory, and short / repetitive names skip the+ * fuzzy tier (name-entropy gate).+ */+import { afterAll, beforeAll, describe, expect, test } from 'bun:test';+import { PGLiteEngine } from '../src/core/pglite-engine.ts';+import { hasNameSignal, resolvePhantomCanonical } from '../src/core/entities/resolve.ts';++let engine: PGLiteEngine;+beforeAll(async () => {+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();+ await engine.putPage('people/mercury-example', { type: 'person' as never, title: 'Mercury Example', compiled_truth: 'A person.', timeline: '' });+ await engine.putPage('companies/acme-example', { type: 'company' as never, title: 'Acme Example', compiled_truth: 'A company.', timeline: '' });+});+afterAll(async () => { await engine.disconnect(); });++describe('resolvePhantomCanonical hardening', () => {+ test('a company phantom never merges into a person page', async () => {+ expect(await resolvePhantomCanonical(engine, 'default', 'mercury', { type: 'company' })).toBeNull();+ expect(await resolvePhantomCanonical(engine, 'default', 'mercury', { type: 'person' })).toBe('people/mercury-example');+ expect(await resolvePhantomCanonical(engine, 'default', 'mercury')).toBe('people/mercury-example');+ });+ test('a person phantom never merges into a company page', async () => {+ expect(await resolvePhantomCanonical(engine, 'default', 'acme', { type: 'person' })).toBeNull();+ expect(await resolvePhantomCanonical(engine, 'default', 'acme', { type: 'company' })).toBe('companies/acme-example');+ });+ test('name-entropy gate', () => {+ expect(hasNameSignal('ai')).toBe(false);+ expect(hasNameSignal('aaaaaaa')).toBe(false);+ expect(hasNameSignal('acme example')).toBe(true);+ expect(hasNameSignal('mercury')).toBe(true);+ });+});