Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): derive temporal edge evidence on the write path (GBRA-49 P1)

garrytan51fb46020490
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index f74a019762..8a54468066 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -2,6 +2,7 @@ import type { BrainEngine, LinkBatchInput } from './engine.ts';
import { assertPageRevision } from './page-state/types.ts';
import { executeRawJsonb } from './sql-query.ts';
import { sanitizeForJsonb } from './batch-rows.ts';
+import { applyTemporalEvidence, relationshipKeysForOrigin } from './link-temporal-apply.ts';
export interface DerivedLinkOrigin {
slug: string;
@@ -87,6 +88,13 @@ export async function replaceDerivedLinks(
throw new Error('Derived link origin changed or was deleted');
}
const id = snapshot.page.id;
+ // Temporal evidence (tense, dated transitions, relationship state) is part
+ // of the same derived projection: captured before, replaced after.
+ const temporalKeysBefore = await relationshipKeysForOrigin(tx, Number(id));
+ const withTemporal = async (result: { created: number; removed: number }) => {
+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore);
+ return result;
+ };
if (opts.includeFrontmatter !== false && !opts.preserveExisting) {
const ambiguous = await tx.executeRaw(`SELECT 1 FROM links WHERE link_source='frontmatter'
AND origin_page_id IS NULL AND (from_page_id=$1 OR to_page_id=$1) LIMIT 1`, [id]);
@@ -151,13 +159,13 @@ export async function replaceDerivedLinks(
const additions = rows.filter(row => !retained.has(identity(row)));
const created = additions.length ? await tx.addLinksBatch(additions, { auditSite: 'addLinksBatch' }) : 0;
if (created !== additions.length) throw new Error('Derived link replacement did not persist every candidate');
- return { created, removed: obsolete.length };
+ return withTemporal({ created, removed: obsolete.length });
}
const removed = await tx.executeRaw(`DELETE FROM links WHERE link_source=ANY($2::text[])
AND (origin_page_id=$1 OR (origin_page_id IS NULL AND from_page_id=$1
AND link_source IN ('markdown','wikilink-resolved'))) RETURNING id`, [id, producers]);
const created = await tx.addLinksBatch(rows, { auditSite: 'addLinksBatch' });
if (created !== rows.length) throw new Error('Derived link replacement did not persist every candidate');
- return { created, removed: removed.length };
+ return withTemporal({ created, removed: removed.length });
});
}
diff --git a/src/core/engine-sql/links.ts b/src/core/engine-sql/links.ts
index bb8c20e35f..3ca0f45f6b 100644
--- a/src/core/engine-sql/links.ts
+++ b/src/core/engine-sql/links.ts
@@ -22,6 +22,8 @@ import { QUARANTINE_FILTER_FRAGMENT } from '../quarantine.ts';
import type { SqlExecutor } from './executor.ts';
import type { LegacyUnscopedRead, ScopedRead } from './brands.ts';
import { sqlFragment, trustedSql } from './fragment.ts';
+import { refreshRelationships, type RelationshipKey } from './link-relationships.ts';
+import { isTemporalLinkType } from '../link-validity.ts';
export async function addLink(
exec: SqlExecutor,
@@ -68,11 +70,15 @@ export async function addLink(
)
SELECT
endpoint_state.from_id IS NOT NULL AS from_exists,
- endpoint_state.to_id IS NOT NULL AS to_exists
+ endpoint_state.to_id IS NOT NULL AS to_exists,
+ endpoint_state.from_id, endpoint_state.to_id
FROM endpoint_state
- `)).rows;
+ `)).rows as Array<{ from_exists: boolean; to_exists: boolean; from_id: number | null; to_id: number | null }>;
if (!result?.from_exists) throw new PageMissingError('addLink', 'from', from, fromSrc);
if (!result.to_exists) throw new PageMissingError('addLink', 'to', to, toSrc);
+ if (isTemporalLinkType(linkType)) {
+ await refreshRelationships(exec, [{ from_page_id: Number(result.from_id), to_page_id: Number(result.to_id), link_type: linkType! }]);
+ }
}
@@ -87,8 +93,8 @@ export async function addLinksBatch(exec: SqlExecutor, links: LinkBatchInput[]):
// the same array serializer this fix exists to avoid. Row construction +
// NUL-stripping + exact defaulting live in buildLinkRows (shared with PGLite).
const rows = buildLinkRows(links);
- const result = await executeRawJsonb(
- exec,
+ const insert = (target: SqlExecutor) => executeRawJsonb<RelationshipKey>(
+ target,
`INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field)
SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field
FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(
@@ -100,11 +106,18 @@ export async function addLinksBatch(exec: SqlExecutor, links: LinkBatchInput[]):
JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id
LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id
ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING
- RETURNING 1`,
+ RETURNING from_page_id, to_page_id, link_type`,
[],
[{ rows }],
);
- return result.length;
+ // Temporal relation types also refresh their relationship state in the
+ // same transaction; batches of plain references skip it entirely.
+ if (!rows.some(r => isTemporalLinkType(r.link_type))) return (await insert(exec)).length;
+ return exec.transaction(async tx => {
+ const inserted = await insert(tx);
+ await refreshRelationships(tx, inserted);
+ return inserted.length;
+ });
}
@@ -150,10 +163,11 @@ export async function removeLinksByPagesAndSource(
WHERE k.from_id = l.from_page_id AND k.to_id = l.to_page_id
)
)
- RETURNING 1`,
+ RETURNING l.from_page_id, l.to_page_id, l.link_type`,
[opts.linkSource],
[payload],
- );
+ ) as RelationshipKey[];
+ await refreshRelationships(exec, rows);
return rows.length;
}
@@ -181,8 +195,9 @@ export async function removeLink(
AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})
AND link_type = ${linkType}
AND link_source IS NOT DISTINCT FROM ${linkSource}
- RETURNING 1
- `)).rows;
+ RETURNING from_page_id, to_page_id, link_type
+ `)).rows as unknown as RelationshipKey[];
+ await refreshRelationships(exec, rows);
return rows.length;
} else if (linkType !== undefined) {
const rows = (await exec.run(sqlFragment`
@@ -190,8 +205,9 @@ export async function removeLink(
WHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})
AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})
AND link_type = ${linkType}
- RETURNING 1
- `)).rows;
+ RETURNING from_page_id, to_page_id, link_type
+ `)).rows as unknown as RelationshipKey[];
+ await refreshRelationships(exec, rows);
return rows.length;
} else if (linkSource !== undefined) {
const rows = (await exec.run(sqlFragment`
@@ -199,16 +215,18 @@ export async function removeLink(
WHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})
AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})
AND link_source IS NOT DISTINCT FROM ${linkSource}
- RETURNING 1
- `)).rows;
+ RETURNING from_page_id, to_page_id, link_type
+ `)).rows as unknown as RelationshipKey[];
+ await refreshRelationships(exec, rows);
return rows.length;
} else {
const rows = (await exec.run(sqlFragment`
DELETE FROM links
WHERE from_page_id = (SELECT id FROM pages WHERE slug = ${from} AND source_id = ${fromSrc})
AND to_page_id = (SELECT id FROM pages WHERE slug = ${to} AND source_id = ${toSrc})
- RETURNING 1
- `)).rows;
+ RETURNING from_page_id, to_page_id, link_type
+ `)).rows as unknown as RelationshipKey[];
+ await refreshRelationships(exec, rows);
return rows.length;
}
}
diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.ts
new file mode 100644
index 0000000000..2b853062a2
--- /dev/null
+++ b/src/core/link-temporal-apply.ts
@@ -0,0 +1,103 @@
+/**
+ * Temporal typed edges — persist one origin page's temporal evidence inside
+ * the transaction that replaces its derived links (src/core/derived-links.ts):
+ *
+ * 1. stamp `assertion_tense` on the links rows this page owns;
+ * 2. replace the page's derived `link_transitions` (producers timeline,
+ * explicit, frontmatter, dream; manual and inline rows are left alone);
+ * 3. refresh `link_relationships` for every relationship the page touched
+ * before or after the change.
+ *
+ * Zero LLM. Explicit-grammar targets must be live pages in the same source;
+ * unusable lines are returned so callers can report them.
+ */
+import type { BrainEngine, LinkBatchInput } from './engine.ts';
+import type { Page } from './types.ts';
+import { executeRawJsonb } from './sql-query.ts';
+import { deriveTemporalEvidence, rowKey, type TemporalEvidence } from './link-temporal-evidence.ts';
+import { refreshRelationships, type RelationshipKey } from './engine-sql/link-relationships.ts';
+import { TEMPORAL_LINK_TYPES } from './link-validity.ts';
+
+type Tx = Pick<BrainEngine, 'executeRaw'>;
+
+const DERIVED_PRODUCERS = ['timeline', 'explicit', 'frontmatter', 'dream'];
+
+export interface TemporalApplyResult {
+ transitions: number;
+ refreshed: number;
+ unmatched: TemporalEvidence['unmatched'];
+}
+
+/** Relationship keys whose evidence this origin page owns (links rows + derived transitions + state rows it starts). */
+export async function relationshipKeysForOrigin(tx: Tx, pageId: number): Promise<RelationshipKey[]> {
+ const rows = await tx.executeRaw<RelationshipKey>(
+ `SELECT from_page_id, to_page_id, link_type FROM links
+ WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $1)) AND link_type = ANY($2::text[])
+ UNION
+ SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $1
+ UNION
+ SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $1 AND scope = 'all'`,
+ [pageId, [...TEMPORAL_LINK_TYPES]]);
+ 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 }));
+}
+
+export async function applyTemporalEvidence(
+ tx: Tx,
+ page: Pick<Page, 'id' | 'slug' | 'source_id' | 'compiled_truth' | 'timeline' | 'frontmatter'>,
+ rows: readonly LinkBatchInput[],
+ keysBefore: readonly RelationshipKey[],
+): Promise<TemporalApplyResult> {
+ const pageId = Number(page.id);
+ const sourceId = page.source_id ?? 'default';
+ const evidence = deriveTemporalEvidence({
+ slug: page.slug, compiled_truth: page.compiled_truth ?? '', timeline: page.timeline ?? '',
+ frontmatter: (page.frontmatter ?? {}) as Record<string, unknown>,
+ }, rows.map(r => ({ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type, link_source: r.link_source ?? 'markdown', origin_field: r.origin_field ?? null })));
+
+ const tenseRows = rows.filter(r => evidence.tense.has(rowKey(r))).map(r => ({
+ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type ?? '', link_source: r.link_source ?? 'markdown',
+ from_source_id: r.from_source_id ?? sourceId, to_source_id: r.to_source_id ?? sourceId,
+ tense: evidence.tense.get(rowKey(r)) === 'past' ? 'past' : null,
+ }));
+ if (tenseRows.length) {
+ await executeRawJsonb(tx,
+ `UPDATE links l SET assertion_tense = v.tense
+ FROM jsonb_to_recordset(($2::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, link_source text,
+ from_source_id text, to_source_id text, tense text)
+ JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id
+ JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id
+ WHERE l.from_page_id = f.id AND l.to_page_id = t.id AND l.link_type = v.link_type AND l.link_source = v.link_source
+ AND (l.origin_page_id = $1 OR (l.origin_page_id IS NULL AND l.from_page_id = $1))
+ AND l.assertion_tense IS DISTINCT FROM v.tense`,
+ [pageId], [{ rows: tenseRows }]);
+ }
+
+ await tx.executeRaw(`DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])`, [pageId, DERIVED_PRODUCERS]);
+ let inserted: RelationshipKey[] = [];
+ if (evidence.transitions.length) {
+ inserted = await executeRawJsonb<RelationshipKey>(tx,
+ `INSERT INTO link_transitions (source_id, from_page_id, to_page_id, link_type, kind, occurred_on, date_precision, producer, origin_page_id, line_hash)
+ SELECT $2, f.id, t.id, v.link_type, v.kind, v.occurred_on::date, v.date_precision, v.producer, $1, v.line_hash
+ FROM jsonb_to_recordset(($3::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, kind text,
+ occurred_on text, date_precision text, producer text, line_hash text)
+ JOIN pages f ON f.slug = v.from_slug AND f.source_id = $2 AND f.deleted_at IS NULL
+ JOIN pages t ON t.slug = v.to_slug AND t.source_id = $2 AND t.deleted_at IS NULL
+ ON CONFLICT DO NOTHING
+ RETURNING from_page_id, to_page_id, link_type`,
+ [pageId, sourceId], [{ rows: evidence.transitions }]);
+ }
+ const unmatched = [...evidence.unmatched];
+ const explicitTargets = [...new Set(evidence.transitions.filter(t => t.producer === 'explicit' || t.producer === 'dream').map(t => t.to_slug))];
+ if (explicitTargets.length) {
+ const live = new Set((await tx.executeRaw<{ slug: string }>(
+ `SELECT slug FROM pages WHERE source_id = $1 AND slug = ANY($2::text[]) AND deleted_at IS NULL`, [sourceId, explicitTargets])).map(r => r.slug));
+ for (const t of evidence.transitions) {
+ if ((t.producer === 'explicit' || t.producer === 'dream') && !live.has(t.to_slug)) {
+ unmatched.push({ line: `${t.kind === 'start' ? 'Started' : 'Ended'} ${t.link_type} [[${t.to_slug}]]`, reason: 'no_target' });
+ }
+ }
+ }
+ const keysAfter = await relationshipKeysForOrigin(tx, pageId);
+ const refreshed = await refreshRelationships(tx, [...keysBefore, ...keysAfter]);
+ return { transitions: inserted.length, refreshed, unmatched };
+}
diff --git a/src/core/link-temporal-evidence.ts b/src/core/link-temporal-evidence.ts
new file mode 100644
index 0000000000..b33e957713
--- /dev/null
+++ b/src/core/link-temporal-evidence.ts
@@ -0,0 +1,270 @@
+/**
+ * Temporal typed edges — deterministic evidence derivation (zero LLM).
+ *
+ * Given one page's content and the derived link rows it owns, produce:
+ * - the tense of each owned assertion row ('past' when every compiled-truth
+ * mention of the other endpoint carries a past-tense cue such as
+ * "previously at", "former CTO of"; otherwise 'present');
+ * - dated transitions: cue-bearing timeline lines ("- **2025-03-01** | left
+ * [Acme](...)"), the explicit grammar ("Ended works_at [[companies/acme]]",
+ * "Started advises [[companies/acme]]") inside a dated timeline entry, and
+ * `since:` / `until:` keys on relationship frontmatter objects.
+ *
+ * Natural cues only date relationships the page already asserts (an owned
+ * row of a matching state/event type); they never create a relationship.
+ * The explicit grammar is a full statement on its own: it names the relation
+ * and the target, so a closure survives even after the stale positive
+ * sentence is deleted. Lines whose timeline source label starts with
+ * `gbrain-dream` carry producer 'dream' (an applied contradiction proposal).
+ *
+ * Contract and examples: docs/guides/temporal-edges.md.
+ */
+import { createHash } from 'node:crypto';
+import {
+ relationSemantics, normalizePartialDate, type AssertionTense, type DatePrecision,
+ type TransitionKind, type TransitionProducer,
+} from './link-validity.ts';
+
+export interface OwnedRow {
+ from_slug: string;
+ to_slug: string;
+ link_type?: string;
+ link_source?: string | null;
+ origin_field?: string | null;
+}
+
+export interface DerivedTransition {
+ from_slug: string;
+ to_slug: string;
+ link_type: string;
+ kind: TransitionKind;
+ occurred_on: string;
+ date_precision: DatePrecision;
+ producer: Extract<TransitionProducer, 'timeline' | 'explicit' | 'frontmatter' | 'dream'>;
+ line_hash: string;
+}
+
+export interface TemporalEvidence {
+ /** Tense per owned row, keyed by rowKey(). */
+ tense: Map<string, AssertionTense>;
+ transitions: DerivedTransition[];
+ /** Explicit-grammar lines whose relation or target could not be used. */
+ unmatched: Array<{ line: string; reason: 'not_temporal' | 'event_cannot_end' | 'no_target' }>;
+}
+
+export const rowKey = (r: Pick<OwnedRow, 'from_slug' | 'to_slug' | 'link_type'>) => `${r.from_slug}\0${r.to_slug}\0${r.link_type ?? ''}`;
+
+// ─── Cue lexicon ─────────────────────────────────────────────────────────
+// Each pattern is anchored at the END of the text just before a reference to
+// the other endpoint, so the nearest phrase decides ("Left [Wisp] to join
+// [Helix]": end for Wisp, start for Helix).
+
+const ROLE = String.raw`(?:[\w&./-]+\s+){0,4}?`;
+
+const EMPLOYMENT = {
+ end: new RegExp(String.raw`\b(?:left|departed(?:\s+from)?|quit|resigned(?:\s+as\s+${ROLE})?(?:\s+from|\s+at)?|stepped\s+down(?:\s+as\s+${ROLE})?(?:\s+from|\s+at)?|(?:was\s+)?laid\s+off\s+(?:from|by|at)|(?:was\s+)?let\s+go\s+(?:from|by)|(?:was\s+)?fired\s+(?:from|by)|no\s+longer\s+(?:at|with|works\s+at|working\s+at)|exited|parted\s+ways\s+with)\s*$`, 'i'),
+ start: new RegExp(String.raw`\b(?:join(?:ed|s)?(?:\s+${ROLE}(?:at|as))?|hired\s+(?:by|at|as\s+${ROLE}at)|started\s+(?:at|with|working\s+at)|became\s+${ROLE}(?:at|of)|promoted\s+to\s+${ROLE}(?:at|of)|signed\s+on\s+(?:at|with)|named\s+${ROLE}(?:at|of))\s*$`, 'i'),
+ past: new RegExp(String.raw`\b(?:previously(?:\s+worked)?\s+(?:at|with|for)|formerly(?:\s+${ROLE})?\s*(?:at|of|with)|former\s+${ROLE}(?:at|of|with)|ex-[\w-]+\s+(?:at|of)|used\s+to\s+work\s+(?:at|for)|worked\s+(?:at|for|with)|spent\s+(?:[\w-]+\s+){1,4}?(?:at|with)|(?:his|her|their|my)\s+(?:time|stint|tenure)\s+at|stint\s+at|was\s+${ROLE}(?:at|of)|alum(?:nus|na|ni)?\s+of)\s*$`, 'i'),
+};
+
+const ADVISORY = {
+ end: /\b(?:stepped\s+down\s+as\s+(?:an?\s+)?(?:\w+\s+)?advisor\s+(?:to|at|of|for)|left\s+(?:the\s+)?advisory\s+board\s+(?:of|at)|no\s+longer\s+advis(?:es|ing)|stopped\s+advising|ended\s+(?:the\s+|(?:his|her|their)\s+)?advisory\s+(?:role|work)\s+(?:with|at|for))\s*$/i,
+ start: /\b(?:joined\s+(?:the\s+)?advisory\s+board\s+(?:of|at)|became\s+(?:an?\s+)?(?:\w+\s+)?advisor\s+(?:to|at|of|for)|started\s+advising|began\s+advising)\s*$/i,
+ past: /\b(?:former\s+(?:\w+\s+)?advisor\s+(?:to|at|of|for)|previously\s+advised|used\s+to\s+advise|advised)\s*$/i,
+};
+
+const PARTNER = {
+ end: /\b(?:left|stepped\s+down\s+(?:as\s+(?:a\s+)?partner\s+)?(?:from|at))\s*$/i,
+ start: /\b(?:joined(?:\s+as\s+(?:a\s+)?(?:\w+\s+)?partner\s+at)?|became\s+(?:a\s+)?(?:\w+\s+)?partner\s+at)\s*$/i,
+ past: /\b(?:former\s+(?:\w+\s+)?partner\s+(?:at|of)|was\s+(?:a\s+)?(?:\w+\s+)?partner\s+at)\s*$/i,
+};
+
+const EVENT_START: Record<string, RegExp> = {
+ invested_in: /\b(?:invested\s+in|invests\s+in|backed|led\s+(?:the\s+)?(?:\w+\s+){0,3}?(?:round|investment|seed)\s+(?:in|for|of)|participated\s+in\s+(?:\w+\s+){0,3}?(?:round|seed)\s+(?:of|in|for)|wrote\s+(?:a|the|an)\s+(?:\w+\s+){0,2}?check\s+(?:to|for|into))\s*$/i,
+ led_round: /\b(?:led(?:\s+the)?(?:\s+\w+){0,3}?)\s*$/i,
+ founded: /\b(?:founded|co-?founded|started)\s*$/i,
+};
+
+type CueSet = { end: RegExp; start: RegExp; past: RegExp };
+function cuesFor(linkType: string): CueSet | null {
+ if (linkType === 'works_at') return EMPLOYMENT;
+ if (linkType === 'advises') return ADVISORY;
+ if (linkType === 'yc_partner') return PARTNER;
+ return null;
+}
+
+// ─── References ──────────────────────────────────────────────────────────
+
+/** Normalize a link target to a slug: strip ./ ../ prefixes, a .md suffix and an #anchor. */
+export function normalizeLinkTarget(raw: string): string {
+ let s = raw.trim().replace(/[#?].*$/, '').replace(/\.md$/i, '');
+ while (s.startsWith('../') || s.startsWith('./')) s = s.replace(/^\.\.?\//, '');
+ return s.replace(/^\/+/, '');
+}
+
+interface RefHit { index: number; target: string }
+
+const MD_LINK_RE = /\[[^\]\n]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g;
+const WIKI_LINK_RE = /\[\[([^\]|\n]+)(?:\|[^\]\n]*)?\]\]/g;
+
+function referencesIn(text: string): RefHit[] {
+ const hits: RefHit[] = [];
+ for (const m of text.matchAll(MD_LINK_RE)) hits.push({ index: m.index!, target: normalizeLinkTarget(m[1]) });
+ for (const m of text.matchAll(WIKI_LINK_RE)) hits.push({ index: m.index!, target: normalizeLinkTarget(m[1].replace(/^[a-z0-9-]+:(?=[a-z])/i, '')) });
+ return hits.sort((a, b) => a.index - b.index);
+}
+
+/** Does a normalized link target point at `slug` (full path or unique basename form)? */
+function refersTo(target: string, slug: string): boolean {
+ if (target === slug) return true;
+ const base = slug.split('/').pop()!;
+ return !target.includes('/') && target.toLowerCase() === base.toLowerCase();
+}
+
+/** The clause right before a reference: back to the previous sentence/clause break or reference, max 90 chars. */
+function windowBefore(text: string, index: number, prevRefEnd: number): string {
+ const start = Math.max(0, index - 90, prevRefEnd);
+ let w = text.slice(start, index);
+ const cut = Math.max(w.lastIndexOf('. '), w.lastIndexOf('; '), w.lastIndexOf('\n'), w.lastIndexOf(', and '));
+ if (cut >= 0) w = w.slice(cut + 1);
+ return w.replace(/\*\*|__|[*_`]/g, '');
+}
+
+// ─── Timeline lines ──────────────────────────────────────────────────────
+
+const DATED_LINE_RE = /^\s*(?:[-*]\s*)?\*\*(\d{4}-\d{2}-\d{2})\*\*\s*[|\-–—]+\s*(.+?)\s*$/;
+const DATED_HEADING_RE = /^\s*###\s+(\d{4}-\d{2}-\d{2})\s*[-–—]+\s*(.+?)\s*$/;
+const EXPLICIT_RE = /\b(Started|Ended)\s+([a-z][a-z0-9_]*)\s+(?:\[\[([^\]|\n]+)(?:\|[^\]\n]*)?\]\]|\[[^\]\n]*\]\(([^)\s]+)\))/g;
+
+const EXPLICIT_TEST = new RegExp(EXPLICIT_RE.source);
+
+interface DatedLine { date: string; text: string; dream: boolean }
+
+function datedLines(content: string): DatedLine[] {
+ const out: DatedLine[] = [];
+ let fence = false;
+ for (const line of content.split('\n')) {
+ if (/^\s*(```|~~~)/.test(line)) { fence = !fence; continue; }
+ if (fence) continue;
+ const m = DATED_LINE_RE.exec(line) ?? DATED_HEADING_RE.exec(line);
+ if (!m || !normalizePartialDate(m[1])) continue;
+ out.push({ date: m[1], text: m[2], dream: /^gbrain-dream\b/i.test(m[2].trim()) });
+ }
+ return out;
+}
+
+const lineHash = (s: string) => createHash('sha256').update(s).digest('hex').slice(0, 16);
+
+// ─── Derivation ──────────────────────────────────────────────────────────
+
+export interface PageForEvidence {
+ slug: string;
+ compiled_truth: string;
+ timeline: string;
+ frontmatter: Record<string, unknown> | null | undefined;
+}
+
+export function deriveTemporalEvidence(page: PageForEvidence, rows: readonly OwnedRow[]): TemporalEvidence {
+ const tense = new Map<string, AssertionTense>();
+ const transitions: DerivedTransition[] = [];
+ const unmatched: TemporalEvidence['unmatched'] = [];
+ const content = `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`;
+ const lines = datedLines(content);
+ const temporalRows = rows.filter(r => relationSemantics(r.link_type) !== 'reference');
+ const other = (r: OwnedRow) => (r.from_slug === page.slug ? r.to_slug : r.from_slug);
+ const seen = new Set<string>();
+ const push = (t: DerivedTransition) => {
+ const k = `${t.from_slug}\0${t.to_slug}\0${t.link_type}\0${t.kind}\0${t.occurred_on}\0${t.producer}`;
+ if (!seen.has(k)) { seen.add(k); transitions.push(t); }
+ };
+
+ // 1. Explicit grammar inside dated timeline entries.
+ for (const line of lines) {
+ for (const m of line.text.matchAll(EXPLICIT_RE)) {
+ const linkType = m[2];
+ const target = normalizeLinkTarget(m[3] ?? m[4] ?? '');
+ const semantics = relationSemantics(linkType);
+ if (!target) { unmatched.push({ line: line.text, reason: 'no_target' }); continue; }
+ if (semantics === 'reference') { unmatched.push({ line: line.text, reason: 'not_temporal' }); continue; }
+ if (semantics === 'event' && m[1] === 'Ended') { unmatched.push({ line: line.text, reason: 'event_cannot_end' }); continue; }
+ const resolved = target.includes('/') ? target : temporalRows.map(other).find(slug => refersTo(target, slug)) ?? null;
+ if (!resolved) { unmatched.push({ line: line.text, reason: 'no_target' }); continue; }
+ push({ from_slug: page.slug, to_slug: resolved, link_type: linkType, kind: m[1] === 'Started' ? 'start' : 'end',
+ occurred_on: line.date, date_precision: 'day', producer: line.dream ? 'dream' : 'explicit', line_hash: lineHash(line.text) });
+ }
+ }
+
+ // 2. Natural cues on dated lines, for relationships this page asserts.
+ for (const line of lines) {
+ if (EXPLICIT_TEST.test(line.text)) continue;
+ const refs = referencesIn(line.text);
+ let prevEnd = 0;
+ for (const ref of refs) {
+ const window = windowBefore(line.text, ref.index, prevEnd);
+ prevEnd = ref.index + 2;
+ for (const r of temporalRows) {
+ if (!refersTo(ref.target, other(r)) || !r.link_type) continue;
+ const cues = cuesFor(r.link_type);
+ let kind: TransitionKind | null = null;
+ if (cues) kind = cues.end.test(window) ? 'end' : cues.start.test(window) ? 'start' : null;
+ else if (EVENT_START[r.link_type]?.test(window)) kind = 'start';
+ if (!kind) continue;
+ push({ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type, kind, occurred_on: line.date,
+ date_precision: 'day', producer: line.dream ? 'dream' : 'timeline', line_hash: lineHash(line.text) });
+ }
+ }
+ }
+
+ // 3. Frontmatter since/until on relationship objects ({name, since, until}).
+ const fm = page.frontmatter ?? {};
+ for (const r of temporalRows) {
+ if (r.link_source !== 'frontmatter' || !r.origin_field) continue;
+ const field = fm[r.origin_field];
+ const items = Array.isArray(field) ? field : [field];
+ for (const item of items) {
+ if (!item || typeof item !== 'object') continue;
+ const obj = item as Record<string, unknown>;
+ const name = typeof obj.name === 'string' ? obj.name : typeof obj.slug === 'string' ? obj.slug : null;
+ if (!name || !nameMatches(name, other(r))) continue;
+ for (const [key, kind] of [['since', 'start'], ['until', 'end']] as const) {
+ const d = normalizePartialDate(stringish(obj[key]));
+ if (!d) continue;
+ push({ from_slug: r.from_slug, to_slug: r.to_slug, link_type: r.link_type!, kind, occurred_on: d.date,
+ date_precision: d.precision, producer: 'frontmatter', line_hash: lineHash(`${r.origin_field}:${name}:${key}`) });
+ }
+ }
+ }
+
+ // 4. Tense of each owned assertion row, from compiled-truth mentions only.
+ const narrative = stripDatedLines(page.compiled_truth ?? '');
+ const narrativeRefs = referencesIn(narrative);
+ for (const r of temporalRows) {
+ if (relationSemantics(r.link_type) !== 'state') continue;
+ const cues = cuesFor(r.link_type!)!;
+ let past = 0, present = 0, prevEnd = 0;
+ for (const ref of narrativeRefs) {
+ const window = windowBefore(narrative, ref.index, prevEnd);
+ prevEnd = ref.index + 2;
+ if (!refersTo(ref.target, other(r))) continue;
+ if (cues.past.test(window) || cues.end.test(window)) past++; else present++;
+ }
+ tense.set(rowKey(r), past > 0 && present === 0 && r.link_source !== 'frontmatter' ? 'past' : 'present');
+ }
+ return { tense, transitions, unmatched };
+}
+
+function stripDatedLines(text: string): string {
+ return text.split('\n').map(l => (DATED_LINE_RE.test(l) || DATED_HEADING_RE.test(l) ? '' : l)).join('\n');
+}
+
+function stringish(v: unknown): string | null {
+ if (v instanceof Date) return v.toISOString().slice(0, 10);
+ if (typeof v === 'number') return String(v);
+ return typeof v === 'string' ? v : null;
+}
+
+function nameMatches(name: string, slug: string): boolean {
+ const base = slug.split('/').pop()!.toLowerCase();
+ const norm = name.toLowerCase().trim().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '');
+ return norm === base || base.startsWith(`${norm}-`) || normalizeLinkTarget(name).toLowerCase() === slug.toLowerCase();
+}
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index 441a8aaffb..9fd31549ed 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2043,6 +2043,15 @@
},
"via": "unsafe"
},
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
{
"paramCount": 1,
"unsafeOptions": {
@@ -2078,6 +2087,33 @@
"simple": false
},
"via": "unsafe"
+ },
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
+ },
+ {
+ "paramCount": 2,
+ "unsafeOptions": {
+ "cancelFence": false,
+ "prepare": true,
+ "simple": false
+ },
+ "via": "unsafe"
}
]
},
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index f15cd4c671..62a5a4fe36 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -18,20 +18,28 @@
"string",
"null"
],
- "sql": "WITH endpoint_state AS ( SELECT (SELECT id FROM pages WHERE slug = $1 AND source_id = $2 FOR KEY SHARE) AS from_id, (SELECT id FROM pages WHERE slug = $3 AND source_id = $4 FOR KEY SHARE) AS to_id, (SELECT id FROM pages WHERE slug = $5 AND source_id = $6 FOR KEY SHARE) AS origin_id ), upserted AS ( INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) SELECT s.from_id, s.to_id, $7, $8, $9, s.origin_id, $10 FROM endpoint_state s WHERE s.from_id IS NOT NULL AND s.to_id IS NOT NULL ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET context = EXCLUDED.context, origin_field = EXCLUDED.origin_field RETURNING 1 ) SELECT endpoint_state.from_id IS NOT NULL AS from_exists, endpoint_state.to_id IS NOT NULL AS to_exists FROM endpoint_state",
- "textSha256": "985d6920b2f20b54cc394a8c37a0a46e3b998d8707e01ea2c43b5397715eb7d7"
+ "sql": "WITH endpoint_state AS ( SELECT (SELECT id FROM pages WHERE slug = $1 AND source_id = $2 FOR KEY SHARE) AS from_id, (SELECT id FROM pages WHERE slug = $3 AND source_id = $4 FOR KEY SHARE) AS to_id, (SELECT id FROM pages WHERE slug = $5 AND source_id = $6 FOR KEY SHARE) AS origin_id ), upserted AS ( INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, origin_page_id, origin_field) SELECT s.from_id, s.to_id, $7, $8, $9, s.origin_id, $10 FROM endpoint_state s WHERE s.from_id IS NOT NULL AND s.to_id IS NOT NULL ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO UPDATE SET context = EXCLUDED.context, origin_field = EXCLUDED.origin_field RETURNING 1 ) SELECT endpoint_state.from_id IS NOT NULL AS from_exists, endpoint_state.to_id IS NOT NULL AS to_exists, endpoint_state.from_id, endpoint_state.to_id FROM endpoint_state",
+ "textSha256": "8e5589de060b631c137dd92cafdb25e7a180d5a409f46a0d60d5d5ebc2b4c1fa"
}
]
},
"addLinksBatch": {
"default": [
{
- "lane": "pool",
+ "event": "begin",
+ "lane": "tx"
+ },
+ {
+ "lane": "tx",
"params": [
"object"
],
- "sql": "INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field) SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( from_slug text, to_slug text, link_type text, context text, link_source text, origin_slug text, origin_field text, from_source_id text, to_source_id text, origin_source_id text, link_kind text ) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING RETURNING 1",
- "textSha256": "0da50d169284c0223f331dcf1e03b36c9e691aedcd0b2ecd9106e2efaee9438c"
+ "sql": "INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field) SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( from_slug text, to_slug text, link_type text, context text, link_source text, origin_slug text, origin_field text, from_source_id text, to_source_id text, origin_source_id text, link_kind text ) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "feee32f8e94cf3aafc82c8d95828ed2d63babe9d9caf645435bc20050158e1b8"
+ },
+ {
+ "event": "commit",
+ "lane": "tx"
}
]
},
@@ -205,8 +213,8 @@
"string",
"string"
],
- "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) RETURNING 1",
- "textSha256": "a6ae5888d264954339318394dd84154c444a09597536f5cc599f8ae3f28455fc"
+ "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "a798fbeab2e051fdd6705d7a7056fb3336dd854f7890f9b33b005b666e56080d"
}
],
"linkSource": [
@@ -219,8 +227,8 @@
"string",
"string"
],
- "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_source IS NOT DISTINCT FROM $5 RETURNING 1",
- "textSha256": "f0b5dc57f103514ab2a2608fdf069e16df0e1d5ea2792e709d7fb1968505c247"
+ "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_source IS NOT DISTINCT FROM $5 RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "f57ad7d10b814ee50c4c863d765c745253b87c8b7387eaf53d718bc870a983bc"
}
],
"linkType": [
@@ -233,8 +241,8 @@
"string",
"string"
],
- "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_type = $5 RETURNING 1",
- "textSha256": "cf1f3918ea0c9492bd31c29c80aa3e48f559c922e0b2a0eb6ab2bd8dc2d87605"
+ "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_type = $5 RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "578b22148c0baa8a801dd964944ad18a1a5e751ccde3f089328fb922f9ebc7cd"
}
],
"linkType+linkSource": [
@@ -248,8 +256,8 @@
"string",
"string"
],
- "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_type = $5 AND link_source IS NOT DISTINCT FROM $6 RETURNING 1",
- "textSha256": "d100361cb1fd828894d60ef36833fbefc75f35944416faf68bb797dd083e32bc"
+ "sql": "DELETE FROM links WHERE from_page_id = (SELECT id FROM pages WHERE slug = $1 AND source_id = $2) AND to_page_id = (SELECT id FROM pages WHERE slug = $3 AND source_id = $4) AND link_type = $5 AND link_source IS NOT DISTINCT FROM $6 RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "a025a7a98f5d91965c3bb0af96554dd0e9e8d929ea21c2531fa53aae505b0c50"
}
]
},
@@ -262,8 +270,8 @@
"object",
"string"
],
- "sql": "WITH scope AS ( SELECT f.id AS from_id FROM jsonb_to_recordset(($1::jsonb)->'pages') AS p(slug text, source_id text) JOIN pages f ON f.slug = p.slug AND f.source_id = p.source_id ), keep AS ( SELECT f.id AS from_id, t.id AS to_id FROM jsonb_to_recordset(($2::jsonb)->'keep') AS k( from_slug text, from_source_id text, to_slug text, to_source_id text ) JOIN pages f ON f.slug = k.from_slug AND f.source_id = k.from_source_id JOIN pages t ON t.slug = k.to_slug AND t.source_id = k.to_source_id ) DELETE FROM links l USING scope s WHERE l.from_page_id = s.from_id AND l.link_source = $3 AND NOT ( COALESCE(l.link_kind, '') = 'typed_ner' AND EXISTS ( SELECT 1 FROM keep k WHERE k.from_id = l.from_page_id AND k.to_id = l.to_page_id ) ) RETURNING 1",
- "textSha256": "bfc601f3da1859c53caae43011e542fc1ce996000423f410838cdb5091dd6e88"
+ "sql": "WITH scope AS ( SELECT f.id AS from_id FROM jsonb_to_recordset(($1::jsonb)->'pages') AS p(slug text, source_id text) JOIN pages f ON f.slug = p.slug AND f.source_id = p.source_id ), keep AS ( SELECT f.id AS from_id, t.id AS to_id FROM jsonb_to_recordset(($2::jsonb)->'keep') AS k( from_slug text, from_source_id text, to_slug text, to_source_id text ) JOIN pages f ON f.slug = k.from_slug AND f.source_id = k.from_source_id JOIN pages t ON t.slug = k.to_slug AND t.source_id = k.to_source_id ) DELETE FROM links l USING scope s WHERE l.from_page_id = s.from_id AND l.link_source = $3 AND NOT ( COALESCE(l.link_kind, '') = 'typed_ner' AND EXISTS ( SELECT 1 FROM keep k WHERE k.from_id = l.from_page_id AND k.to_id = l.to_page_id ) ) RETURNING l.from_page_id, l.to_page_id, l.link_type",
+ "textSha256": "d9ecaf7da4c58e550ce837ba4cf33eb3180bce93f74145476ccce55252355b94"
}
]
},
@@ -319,6 +327,18 @@
"sql": "WITH chosen AS ( SELECT p.* FROM pages p WHERE p.slug=$1 AND p.source_id=$2 AND p.deleted_at IS NULL ORDER BY (p.slug=$3) DESC, (p.source_id=$4) DESC, p.source_id ASC LIMIT 1 ) SELECT p.*, (SELECT s.incarnation FROM sources s WHERE s.id=p.source_id) AS source_incarnation, COALESCE((SELECT jsonb_agg(t.tag ORDER BY t.tag) FROM tags t WHERE t.page_id=p.id), '[]'::jsonb) AS snapshot_tags, COALESCE((SELECT jsonb_agg(jsonb_build_object('visibility',w.visibility,'fact_hash',w.fact_hash,'withdrawn_at',w.withdrawn_at) ORDER BY w.visibility,w.fact_hash) FROM (SELECT visibility,fact_hash,min(withdrawn_at) AS withdrawn_at FROM fact_withdrawals WHERE source_id=p.source_id AND (subject='*' OR subject=p.slug) GROUP BY visibility,fact_hash) w), '[]'::jsonb) AS snapshot_withdrawals, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.compiled_truth,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_body, (SELECT string_agg(regexp_replace(lower(line), '[[:space:]]+', ' ', 'g'), chr(10) ORDER BY ord) FROM unnest(string_to_array(p.timeline,chr(10))) WITH ORDINALITY AS lines(line,ord)) AS fingerprint_timeline FROM chosen p",
"textSha256": "22ce659b8fb6104bf08b6ee101bd0e0bafb2769bb7c399380a38e9a4a26c693e"
},
+ {
+ "lane": "tx",
+ "params": [
+ "number",
+ "number",
+ "array<string>",
+ "number",
+ "number"
+ ],
+ "sql": "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $2)) AND link_type = ANY($3::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $4 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $5 AND scope = 'all'",
+ "textSha256": "205ec70125f3e9182b0e9a6bb8865f923305e5652e69c750bca14d3568aecdb3"
+ },
{
"lane": "tx",
"params": [
@@ -347,12 +367,51 @@
"textSha256": "139b6f1adbab926678851d9ab9aa31c10522ad78488ed0ce1daca8c5b2952cac"
},
{
- "lane": "tx",
+ "event": "savepoint",
+ "lane": "tx>sp"
+ },
+ {
+ "lane": "tx>sp",
"params": [
"object"
],
- "sql": "INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field) SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( from_slug text, to_slug text, link_type text, context text, link_source text, origin_slug text, origin_field text, from_source_id text, to_source_id text, origin_source_id text, link_kind text ) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING RETURNING 1",
- "textSha256": "0da50d169284c0223f331dcf1e03b36c9e691aedcd0b2ecd9106e2efaee9438c"
+ "sql": "INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source, link_kind, origin_page_id, origin_field) SELECT f.id, t.id, v.link_type, v.context, v.link_source, v.link_kind, o.id, v.origin_field FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v( from_slug text, to_slug text, link_type text, context text, link_source text, origin_slug text, origin_field text, from_source_id text, to_source_id text, origin_source_id text, link_kind text ) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id LEFT JOIN pages o ON o.slug = v.origin_slug AND o.source_id = v.origin_source_id ON CONFLICT (from_page_id, to_page_id, link_type, link_source, origin_page_id) DO NOTHING RETURNING from_page_id, to_page_id, link_type",
+ "textSha256": "feee32f8e94cf3aafc82c8d95828ed2d63babe9d9caf645435bc20050158e1b8"
+ },
+ {
+ "event": "savepoint-release",
+ "lane": "tx>sp"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "object",
+ "number",
+ "number"
+ ],
+ "sql": "UPDATE links l SET assertion_tense = v.tense FROM jsonb_to_recordset(($1::jsonb)->'rows') AS v(from_slug text, to_slug text, link_type text, link_source text, from_source_id text, to_source_id text, tense text) JOIN pages f ON f.slug = v.from_slug AND f.source_id = v.from_source_id JOIN pages t ON t.slug = v.to_slug AND t.source_id = v.to_source_id WHERE l.from_page_id = f.id AND l.to_page_id = t.id AND l.link_type = v.link_type AND l.link_source = v.link_source AND (l.origin_page_id = $2 OR (l.origin_page_id IS NULL AND l.from_page_id = $3)) AND l.assertion_tense IS DISTINCT FROM v.tense",
+ "textSha256": "3e981a0e85ebda344f510e8c26068decb62c8c54a85f1e3bcfc2cae0963ef3aa"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number",
+ "array<string>"
+ ],
+ "sql": "DELETE FROM link_transitions WHERE origin_page_id = $1 AND producer = ANY($2::text[])",
+ "textSha256": "968b36242f79a4ab122e45782864f2b3d0a9a7fb0f415c42b01a84985d19e7c3"
+ },
+ {
+ "lane": "tx",
+ "params": [
+ "number",
+ "number",
+ "array<string>",
+ "number",
+ "number"
+ ],
+ "sql": "SELECT from_page_id, to_page_id, link_type FROM links WHERE (origin_page_id = $1 OR (origin_page_id IS NULL AND from_page_id = $2)) AND link_type = ANY($3::text[]) UNION SELECT from_page_id, to_page_id, link_type FROM link_transitions WHERE origin_page_id = $4 UNION SELECT from_page_id, to_page_id, link_type FROM link_relationships WHERE from_page_id = $5 AND scope = 'all'",
+ "textSha256": "205ec70125f3e9182b0e9a6bb8865f923305e5652e69c750bca14d3568aecdb3"
},
{
"event": "commit",
diff --git a/test/helpers/link-temporal-scenario.ts b/test/helpers/link-temporal-scenario.ts
index 3e156c9478..63a76841a9 100644
--- a/test/helpers/link-temporal-scenario.ts
+++ b/test/helpers/link-temporal-scenario.ts
@@ -100,7 +100,8 @@ export function defineLinkRelationshipTests(label: string, open: () => Promise<B
test('a relationship without a state row reads as live; the stale sweep finds it', async () => {
await page(newco, 'company');
- await eng.addLink(alice, newco, 'advisor to New Co', 'advises', 'markdown');
+ // A writer from before temporal state (raw insert, no refresh).
+ await eng.executeRaw(`INSERT INTO links (from_page_id, to_page_id, link_type, context, link_source) VALUES ($1, $2, 'advises', 'advisor to New Co', 'markdown')`, [ids[alice], ids[newco]]);
expect(await liveTargets(alice)).toContain('companies/new-co:advises');
const stale = await staleRelationshipKeys(eng, 5000);
expect(stale.some(k => k.to_page_id === ids[newco])).toBe(true);
diff --git a/test/link-temporal-evidence.test.ts b/test/link-temporal-evidence.test.ts
new file mode 100644
index 0000000000..ea7b3a86d5
--- /dev/null
+++ b/test/link-temporal-evidence.test.ts
@@ -0,0 +1,105 @@
+/**
+ * Temporal typed edges — deterministic evidence derivation from page content
+ * (src/core/link-temporal-evidence.ts): cue-dated timeline lines, the explicit
+ * Started/Ended grammar, frontmatter since/until and assertion tense.
+ */
+import { describe, test, expect } from 'bun:test';
+import { deriveTemporalEvidence, rowKey, normalizeLinkTarget, type OwnedRow } from '../src/core/link-temporal-evidence.ts';
+
+const alice = 'people/alice-example';
+const row = (to: string, link_type: string, extra: Partial<OwnedRow> = {}): OwnedRow => ({ from_slug: alice, to_slug: to, link_type, link_source: 'markdown', ...extra });
+const derive = (compiled: string, timeline: string, rows: OwnedRow[], frontmatter: Record<string, unknown> = {}) =>
+ deriveTemporalEvidence({ slug: alice, compiled_truth: compiled, timeline, frontmatter }, rows);
+const brief = (t: ReturnType<typeof derive>['transitions']) => t.map(x => `${x.to_slug.split('/').pop()}:${x.link_type}:${x.kind}:${x.occurred_on}:${x.producer}`);
+
+describe('dated timeline cues', () => {
+ test('left X to join Y dates both relationships', () => {
+ const ev = derive('', '- **2025-03-01** | linkedin — Left [Acme](../companies/acme-example) to join [Widget](../companies/widget-co) as CTO',
+ [row('companies/acme-example', 'works_at'), row('companies/widget-co', 'works_at')]);
+ expect(brief(ev.transitions)).toEqual(['acme-example:works_at:end:2025-03-01:timeline', 'widget-co:works_at:start:2025-03-01:timeline']);
+ });
+
+ test('a cue never creates a relationship the page does not assert', () => {
+ const ev = derive('', '- **2025-03-01** | note — Joined [Widget](companies/widget-co)', [row('companies/acme-example', 'works_at')]);
+ expect(ev.transitions).toEqual([]);
+ });
+
+ test('leaving employment does not end an advisory relationship', () => {
+ const ev = derive('', '- **2024-06-01** | note — left [Acme](companies/acme-example)', [row('companies/acme-example', 'advises')]);
+ expect(ev.transitions).toEqual([]);
+ });
+
+ test('advisory cues date advises', () => {
+ const ev = derive('', '- **2024-06-01** | note — stepped down as advisor to [Acme](companies/acme-example)', [row('companies/acme-example', 'advises')]);
+ expect(brief(ev.transitions)).toEqual(['acme-example:advises:end:2024-06-01:timeline']);
+ });
+
+ test('a meeting with a former employer is not a start', () => {
+ const ev = derive('', '- **2026-01-10** | cal — Coffee with the [Acme](companies/acme-example) team', [row('companies/acme-example', 'works_at')]);
+ expect(ev.transitions).toEqual([]);
+ });
+
+ test('bare wikilinks resolve against asserted targets', () => {
+ const ev = derive('', '- **2023-02-01** | me — joined [[acme-example]]', [row('companies/acme-example', 'works_at')]);
+ expect(brief(ev.transitions)).toEqual(['acme-example:works_at:start:2023-02-01:timeline']);
+ });
+
+ test('event relations get their dated occurrence', () => {
+ const ev = derive('', '- **2021-05-01** | deal — invested in [Fund A](companies/fund-a)', [row('companies/fund-a', 'invested_in')]);
+ expect(brief(ev.transitions)).toEqual(['fund-a:invested_in:start:2021-05-01:timeline']);
+ });
+
+ test('fenced code is ignored', () => {
+ const ev = derive('', '```\n- **2025-03-01** | x — left [Acme](companies/acme-example)\n```', [row('companies/acme-example', 'works_at')]);
+ expect(ev.transitions).toEqual([]);
+ });
+});
+
+describe('explicit grammar', () => {
+ test('Ended works_at needs no positive assertion on the page', () => {
+ const ev = derive('', '- **2025-03-01** | me — Ended works_at [[companies/acme-example]]', []);
+ expect(brief(ev.transitions)).toEqual(['acme-example:works_at:end:2025-03-01:explicit']);
+ });
+
+ test('dream-labelled lines carry producer dream', () => {
+ const ev = derive('', '- **2025-03-01** | gbrain-dream (inferred) — Ended works_at [[companies/acme-example]] (superseded by works_at companies/widget-co)', []);
+ expect(brief(ev.transitions)).toEqual(['acme-example:works_at:end:2025-03-01:dream']);
+ });
+
+ test('unusable explicit lines are reported, not silent', () => {
+ const ev = derive('', '- **2025-03-01** | me — Ended mentions [[companies/acme-example]]\n- **2025-03-02** | me — Ended founded [[companies/acme-example]]', []);
+ expect(ev.transitions).toEqual([]);
+ expect(ev.unmatched.map(u => u.reason)).toEqual(['not_temporal', 'event_cannot_end']);
+ });
+});
+
+describe('frontmatter since/until', () => {
+ test('relationship objects with since and until', () => {
+ const r = row('companies/acme-example', 'works_at', { link_source: 'frontmatter', origin_field: 'company' });
+ const ev = derive('', '', [r], { company: [{ name: 'Acme', since: '2021-04', until: '2024-02-15' }] });
+ expect(ev.transitions.map(t => `${t.kind}:${t.occurred_on}:${t.date_precision}:${t.producer}`)).toEqual(['start:2021-04-01:month:frontmatter', 'end:2024-02-15:day:frontmatter']);
+ });
+});
+
+describe('assertion tense', () => {
+ const acme = row('companies/acme-example', 'works_at');
+ test('past-tense mention only → past', () => {
+ expect(derive('Alice was previously at [Acme](companies/acme-example).', '', [acme]).tense.get(rowKey(acme))).toBe('past');
+ expect(derive('She is a former CTO of [Acme](companies/acme-example).', '', [acme]).tense.get(rowKey(acme))).toBe('past');
+ });
+ test('present beats past on the same page', () => {
+ const text = 'Alice was previously at [Acme](companies/acme-example). Now she runs the EU team at [Acme](companies/acme-example).';
+ expect(derive(text, '', [acme]).tense.get(rowKey(acme))).toBe('present');
+ });
+ test('plain present mention → present', () => {
+ expect(derive('Alice is CTO of [Acme](companies/acme-example).', '', [acme]).tense.get(rowKey(acme))).toBe('present');
+ });
+ test('timeline lines do not set tense', () => {
+ expect(derive('Alice is CTO of [Acme](companies/acme-example).\n- **2025-03-01** | x — worked at [Acme](companies/acme-example)', '', [acme]).tense.get(rowKey(acme))).toBe('present');
+ });
+});
+
+test('normalizeLinkTarget', () => {
+ expect(normalizeLinkTarget('../companies/acme-example.md#team')).toBe('companies/acme-example');
+ expect(normalizeLinkTarget('./people/a')).toBe('people/a');
+});
diff --git a/test/link-temporal-put-page.test.ts b/test/link-temporal-put-page.test.ts
new file mode 100644
index 0000000000..80fc87f3c2
--- /dev/null
+++ b/test/link-temporal-put-page.test.ts
@@ -0,0 +1,94 @@
+/**
+ * Temporal typed edges through put_page: the write path derives tense and
+ * dated transitions from the page and refreshes relationship state in the
+ * same transaction as derived-link replacement (zero LLM).
+ */
+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 { relationshipFilterSql, parseMultirange } from '../src/core/link-validity.ts';
+
+setDefaultTimeout(30_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',
+});
+const putPage = operations.find(o => o.name === 'put_page')!;
+
+async function put(slug: string, frontmatter: string, body: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ return putPage.handler(ctx(), { slug, ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: `---\n${frontmatter}\n---\n\n${body}` });
+}
+
+async function liveWorksAt(slug: string, opts: Parameters<typeof relationshipFilterSql>[1] = {}) {
+ 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 = $1 AND l.link_type = 'works_at' AND ${relationshipFilterSql('l', opts)} ORDER BY t.slug`, [slug]);
+ return rows.map(r => r.slug);
+}
+
+describe('put_page derives temporal evidence', () => {
+ test('timeline cues close the old employer and open the new one', async () => {
+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');
+ await put('companies/widget-co', 'type: company\ntitle: Widget', 'Another company.');
+ await put('people/alice-example', 'type: person\ntitle: Alice', [
+ 'Alice is CTO of [Acme](../companies/acme-example). She works at [Widget](../companies/widget-co).',
+ '',
+ '## Timeline',
+ '',
+ '- **2019-02-01** | linkedin — Joined [Acme](../companies/acme-example) as CTO',
+ '- **2025-03-01** | linkedin — Left [Acme](../companies/acme-example) to join [Widget](../companies/widget-co)',
+ ].join('\n'));
+
+ const links = await engine.executeRaw<{ slug: string; link_type: string }>(
+ `SELECT t.slug, l.link_type 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' ORDER BY 1, 2`);
+ expect(links.filter(l => l.link_type === 'works_at').map(l => l.slug)).toEqual(['companies/acme-example', 'companies/widget-co']);
+
+ const transitions = await engine.executeRaw<{ slug: string; kind: string; occurred_on: string; producer: string }>(
+ `SELECT t.slug, lt.kind, lt.occurred_on::text AS occurred_on, lt.producer FROM link_transitions lt JOIN pages t ON t.id = lt.to_page_id ORDER BY lt.occurred_on, t.slug`);
+ expect(transitions).toEqual([
+ { slug: 'companies/acme-example', kind: 'start', occurred_on: '2019-02-01', producer: 'timeline' },
+ { slug: 'companies/acme-example', kind: 'end', occurred_on: '2025-03-01', producer: 'timeline' },
+ { slug: 'companies/widget-co', kind: 'start', occurred_on: '2025-03-01', producer: 'timeline' },
+ ]);
+
+ expect(await liveWorksAt('people/alice-example')).toEqual(['companies/widget-co']);
+ expect(await liveWorksAt('people/alice-example', { asOf: '2022-01-01' })).toEqual(['companies/acme-example']);
+ const [state] = await engine.executeRaw<{ valid_ranges: string; status_now: string }>(
+ `SELECT lr.valid_ranges::text AS valid_ranges, lr.status_now FROM link_relationships lr JOIN pages t ON t.id = lr.to_page_id
+ WHERE t.slug = 'companies/acme-example' AND lr.scope = 'all'`);
+ expect(parseMultirange(state.valid_ranges)).toEqual([{ from: '2019-02-01', until: '2025-03-01' }]);
+ expect(state.status_now).toBe('ended');
+ });
+
+ test('past-tense prose marks the assertion past and the relationship ended (date unknown)', async () => {
+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');
+ await put('people/bob-example', 'type: person\ntitle: Bob', 'Bob previously worked at [Acme](../companies/acme-example) before going independent.');
+ const [row] = await engine.executeRaw<{ assertion_tense: string | null; link_type: string }>(
+ `SELECT l.assertion_tense, l.link_type FROM links l JOIN pages f ON f.id = l.from_page_id WHERE f.slug = 'people/bob-example'`);
+ expect(row).toEqual({ assertion_tense: 'past', link_type: 'works_at' });
+ expect(await liveWorksAt('people/bob-example')).toEqual([]);
+ expect(await liveWorksAt('people/bob-example', { status: 'ended' })).toEqual(['companies/acme-example']);
+ });
+
+ test('an explicit closure line survives deleting the stale sentence, and editing it away reopens', async () => {
+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');
+ await put('people/carol-example', 'type: person\ntitle: Carol', 'Carol is an engineer at [Acme](../companies/acme-example).\n\n- **2024-06-01** | me — Ended works_at [[companies/acme-example]]');
+ expect(await liveWorksAt('people/carol-example')).toEqual([]);
+ expect(await liveWorksAt('people/carol-example', { asOf: '2024-01-01' })).toEqual(['companies/acme-example']);
+
+ await put('people/carol-example', 'type: person\ntitle: Carol', 'Carol is an engineer at [Acme](../companies/acme-example).');
+ expect(await liveWorksAt('people/carol-example')).toEqual(['companies/acme-example']);
+ const transitions = await engine.executeRaw(`SELECT 1 FROM link_transitions`);
+ expect(transitions.length).toBe(0);
+ });
+});