Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): validity ranges on typed relation lines date the relationship (line_grammar.effective_ranges, off by default)

garrytan94886ff9fc08
diff --git a/docs/eval/decisions/p5-delta-2026-10-05/preregistration.md b/docs/eval/decisions/p5-delta-2026-10-05/preregistration.md
new file mode 100644
index 0000000000..ea860f59e5
--- /dev/null
+++ b/docs/eval/decisions/p5-delta-2026-10-05/preregistration.md
@@ -0,0 +1,52 @@
+# P5 delta preregistration: pieces landed after the frozen build
+
+Decision id `p5-delta-2026-10-05`. Recorded on 2026-10-05, before any sealed data for these pieces was opened. The
+first sealed run (`../p5-dev-2026-10-04/preregistration.md`) decides wanted pages, the typed line grammar, the
+similar-page hint and per-edge verb attachment at frozen build `21befeb5b`. This run decides only what changed after
+it. Sealed runs are executed by the custodian only; the custodian pins the delta build SHA at confirmation.
+
+## What the delta covers and the default each verdict decides
+
+| Piece | Config key | Default if the bar passes | If it fails |
+|---|---|---|---|
+| Validity ranges on typed relation lines stored as dated edge transitions (producer `inline`, `src/core/link-effective.ts`) | `line_grammar.effective_ranges` | on | off (ships off) |
+| Wanted rows recorded on the remote `put_page` write path (link-effect hook) | added with the hook; ships off | on | off |
+| Link typing changes made when the edge-validity schema merged: the verb is read at the link's own position in the window; links joined only by commas or conjunctions share the verb before the first; a `mentions` edge to a target the page also links with a typed edge is dropped | none (extraction behavior) | kept | reverted to the frozen build's typing before landing |
+
+## Hypotheses, metrics and bars
+
+**H7, validity ranges.** Same delta build, two arms: `line_grammar.effective_ranges` off and on. Corpus: the
+temporal-edges category's held-out stints (custodian mode), written as typed relation lines with
+`@effective[start,end)` ranges instead of dated timeline prose. Questions: current employer/advisor (live reads) and
+"where did X work on date D" (`as_of` reads). Metric: answer accuracy per question, clustered by person.
+Bars: as_of accuracy on − off ≥ +10 points with the 95% CI lower bound > 0; current-state accuracy no lower than off
+by more than 1 point; pages with no ranges produce identical `link_transitions` in both arms (exact).
+
+**H8, remote wanted rows.** H4's sequential-write runner over the HTTP transport (remote `put_page`), seeded shuffled
+write order, withheld-entity variant. Metric: withheld-entity recall in `wanted_pages`, edges recovered once targets
+appear. Bars: recall ≥ 0.95, within 0.02 of the local arm, non-entity noise 0 (exact).
+
+**H9, typing changes.** Frozen build `21befeb5b` extractor vs delta build extractor, the same pages. Corpus: held-out
+world-v1 seeds (not 1–3) and the temporal-edges held-out set. Metrics: `anyTypeMatch` per gold edge and live-
+relationship accuracy. Bars: noninferior at tolerance 0.01 on both.
+
+Guardrails: LongMemEval-S `recall_all@5` noninferior (tolerance 0.01); N4 resolver no new wrong merge (exact).
+
+## Dev disclosures
+
+Dev world-v1 (seeds 1–3 only, never sealed): type accuracy 0.767 at the frozen build, 0.753 at the delta build,
+0.747 on master with the edge-validity schema; strict F1 0.195, 0.217 and 0.188. The 0.014 drop comes from two
+edges on one page ("advisor at [A], [B], and [C]") that the coordination rule types `advises` while world-v1's gold,
+built from the generator's ledger, says `invested_in`. H7 dev: `test/link-effective.test.ts` shows an ended range
+hides the edge from default reads and `as_of` finds it.
+
+## Runner pieces the custodian needs (not built by the implementer)
+
+1. H7: a temporal-edges variant writer that renders held-out stints as relation lines with ranges, and an arm switch
+ for `line_grammar.effective_ranges` on category runners (they take `search.*` pins only today).
+2. H8: H4's sequential-write runner with an HTTP-transport arm.
+3. H9: a type-accuracy runner that imports an overlay build's extractor (`--gbrain`) and writes receipt rows.
+
+## Budget
+
+H7 and H9 are deterministic ($0). H8 is deterministic ($0). Guardrails ≈ $10 in embeddings. Within the P5 cap.
diff --git a/docs/eval/decisions/p5-dev-2026-10-04/preregistration.md b/docs/eval/decisions/p5-dev-2026-10-04/preregistration.md
index fd49ae1286..13548adaef 100644
--- a/docs/eval/decisions/p5-dev-2026-10-04/preregistration.md
+++ b/docs/eval/decisions/p5-dev-2026-10-04/preregistration.md
@@ -16,7 +16,7 @@ P5 is decided in two sealed runs.
wanted-row recording on the remote `put_page` write path (after the link-effect hook in the persistence pipeline
merges) and validity ranges stored on edges (`@effective[start,end)`, after the edge-validity schema merges). Its
baseline is the frozen build above. Those pieces ship off by default and turn on only if the delta run passes; if
- it fails, they stay off.
+ it fails, they stay off. Its preregistration is `../p5-delta-2026-10-05/preregistration.md`.
## Features and the default each verdict decides
@@ -25,7 +25,7 @@ P5 is decided in two sealed runs.
| Wanted pages: unresolved authored links recorded and re-linked when the target appears | `wanted_pages.enabled` | on | off |
| Typed relation lines (`- works_at [[companies/x]]`) | `line_grammar.enabled` | on | off |
| Similar-page hint when a write creates a page | `put_page.similar_pages` | on | off |
-| Validity ranges stored on edges (`@effective[start,end)`) | needs the edge-validity schema | on only if the delta run passes | off |
+| Validity ranges stored on edges (`@effective[start,end)`) | `line_grammar.effective_ranges` | on only if the delta run passes | off |
| Wanted rows from remote `put_page` writes | needs the persistence link-effect hook | on only if the delta run passes | off |
Fact lines (`- [category] claim`) are parsed, linted and reported; they are not projected into `facts`, and no
diff --git a/docs/guides/line-grammar.md b/docs/guides/line-grammar.md
index af5ac0f464..f0d339c307 100644
--- a/docs/guides/line-grammar.md
+++ b/docs/guides/line-grammar.md
@@ -38,7 +38,14 @@ They stay searchable page text; recall's facts come from `remember` and the
`@effective[start,end)` (alias `@valid`) states when a relation or fact holds,
with `YYYY`, `YYYY-MM` or `YYYY-MM-DD` dates in UTC. Square brackets are
inclusive, parentheses exclusive, and an empty side is open. Ranges are parsed
-and validated on write; storing them on edges uses the edge validity columns.
+and validated on write. With `line_grammar.effective_ranges true` (off by
+default), a range on a relation line is stored on that relationship as dated
+start and end evidence, the same evidence a dated timeline line gives
+([temporal edges](temporal-edges.md)): `- works_at @effective[2021-03,2024-06) [[companies/acme-example]]`
+makes the works_at edge live from 2021-03-01 and ended on 2024-06-01, so
+default graph reads hide it and `as_of` reads find it. A range on a type that
+is not a dated relationship, or on a link the page does not store with that
+type, is reported and stores nothing.
## What `put_page` reports
diff --git a/plugin-variants/gbrain-coding/skills/conventions/line-grammar.md b/plugin-variants/gbrain-coding/skills/conventions/line-grammar.md
index 5d188ceb82..5574514afe 100644
--- a/plugin-variants/gbrain-coding/skills/conventions/line-grammar.md
+++ b/plugin-variants/gbrain-coding/skills/conventions/line-grammar.md
@@ -50,6 +50,10 @@ category is known; write prose for everything else.
it holds. Dates are `YYYY`, `YYYY-MM` or `YYYY-MM-DD` (UTC). `[`/`]` are
inclusive, `(`/`)` exclusive, an empty side is open: `@effective[2022,)` means
"since 2022". Natural-language and relative dates (`last spring`) are not read.
+When `line_grammar.effective_ranges` is on, the range on a relation line dates
+that relationship: an ended range hides the edge from default graph reads
+(`get_links` with `status: all` or `as_of` still shows it). To record that a
+job ended, edit the line's range rather than deleting the line.
## Check before writing
diff --git a/plugin-variants/gbrain-daily/skills/conventions/line-grammar.md b/plugin-variants/gbrain-daily/skills/conventions/line-grammar.md
index 5d188ceb82..5574514afe 100644
--- a/plugin-variants/gbrain-daily/skills/conventions/line-grammar.md
+++ b/plugin-variants/gbrain-daily/skills/conventions/line-grammar.md
@@ -50,6 +50,10 @@ category is known; write prose for everything else.
it holds. Dates are `YYYY`, `YYYY-MM` or `YYYY-MM-DD` (UTC). `[`/`]` are
inclusive, `(`/`)` exclusive, an empty side is open: `@effective[2022,)` means
"since 2022". Natural-language and relative dates (`last spring`) are not read.
+When `line_grammar.effective_ranges` is on, the range on a relation line dates
+that relationship: an ended range hides the edge from default graph reads
+(`get_links` with `status: all` or `as_of` still shows it). To record that a
+job ended, edit the line's range rather than deleting the line.
## Check before writing
diff --git a/plugin/skills/conventions/line-grammar.md b/plugin/skills/conventions/line-grammar.md
index 5d188ceb82..5574514afe 100644
--- a/plugin/skills/conventions/line-grammar.md
+++ b/plugin/skills/conventions/line-grammar.md
@@ -50,6 +50,10 @@ category is known; write prose for everything else.
it holds. Dates are `YYYY`, `YYYY-MM` or `YYYY-MM-DD` (UTC). `[`/`]` are
inclusive, `(`/`)` exclusive, an empty side is open: `@effective[2022,)` means
"since 2022". Natural-language and relative dates (`last spring`) are not read.
+When `line_grammar.effective_ranges` is on, the range on a relation line dates
+that relationship: an ended range hides the edge from default graph reads
+(`get_links` with `status: all` or `as_of` still shows it). To record that a
+job ended, edit the line's range rather than deleting the line.
## Check before writing
diff --git a/scripts/e2e-test-map.ts b/scripts/e2e-test-map.ts
index ef55f17e28..233d68655d 100644
--- a/scripts/e2e-test-map.ts
+++ b/scripts/e2e-test-map.ts
@@ -655,6 +655,7 @@ export const E2E_TEST_MAP: Record<string, string[]> = {
"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-effective.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", "test/e2e/wanted-links-postgres.test.ts"],
diff --git a/skills/conventions/line-grammar.md b/skills/conventions/line-grammar.md
index 5d188ceb82..5574514afe 100644
--- a/skills/conventions/line-grammar.md
+++ b/skills/conventions/line-grammar.md
@@ -50,6 +50,10 @@ category is known; write prose for everything else.
it holds. Dates are `YYYY`, `YYYY-MM` or `YYYY-MM-DD` (UTC). `[`/`]` are
inclusive, `(`/`)` exclusive, an empty side is open: `@effective[2022,)` means
"since 2022". Natural-language and relative dates (`last spring`) are not read.
+When `line_grammar.effective_ranges` is on, the range on a relation line dates
+that relationship: an ended range hides the edge from default graph reads
+(`get_links` with `status: all` or `as_of` still shows it). To record that a
+job ended, edit the line's range rather than deleting the line.
## Check before writing
diff --git a/skills/skills.lock.json b/skills/skills.lock.json
index 7894279a21..251b2083b7 100644
--- a/skills/skills.lock.json
+++ b/skills/skills.lock.json
@@ -50,7 +50,7 @@
"conventions/cron-via-minions.md": "badb1cd6cd825d6f1ac0b6b28cc47e5d80facc783a3e59a14146ae901ee0f933",
"conventions/cross-modal.yaml": "c012c3d72614a87b1ee698173dce2a0fb0d057a54df7aab87993c4b07fff6280",
"conventions/exec-output.md": "2bf371ac3ec4987eff7cc13cd3ea8cc97c46bd43f588eec024ff27f3171bc58f",
- "conventions/line-grammar.md": "e08dd3e7da9285d9b41615a70a040b3967bd298a33011fccba2a1c18e730e235",
+ "conventions/line-grammar.md": "2edc5279bc8c7daa0f69a78652e720cad3301ec7317ac9f95ac87acc0e7fc9fd",
"conventions/model-routing.md": "c0d5031e4372c108d7e94346dc2958c21389f3b67544524578bbc9ea32d53c34",
"conventions/path-discipline.md": "8af5415721bd115e6979c96688bcf542a32675809ada9aaedbb6706a40926954",
"conventions/quality.md": "8aa681001114689d34268ccadaf0e2ff07b8f68aa5987c093a8c4a7a744f12a6",
diff --git a/src/core/config.ts b/src/core/config.ts
index 844b0c2e32..5b9f348ab8 100644
--- a/src/core/config.ts
+++ b/src/core/config.ts
@@ -1580,6 +1580,9 @@ export const KNOWN_CONFIG_KEYS: readonly string[] = [
// undeclared relation types fall back to inference unless allowed.
'line_grammar.enabled',
'line_grammar.allow_undeclared_types',
+ // Validity ranges on typed relation lines stored as dated edge transitions
+ // (core/link-effective.ts). Off until its held-out verdict.
+ 'line_grammar.effective_ranges',
// put_page "did you mean an existing page?" advisory on creates (core/similar-pages.ts).
'put_page.similar_pages',
// #5584: skillopt optimizer output cap (default 32000 thinking / 4096 otherwise).
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index 09b2cb263b..f5354cc481 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -5,6 +5,7 @@ import { sanitizeForJsonb } from './batch-rows.ts';
import { replaceWantedLinks, type WantedLinksReplacement } from './wanted-links-store.ts';
import { applyTemporalEvidence, relationshipKeysForOrigin } from './link-temporal-apply.ts';
import { primeRelationSemantics } from './link-semantics-pack.ts';
+import { effectiveRangesEnabled } from './line-grammar.ts';
export interface DerivedLinkOrigin {
slug: string;
@@ -98,7 +99,7 @@ export async function replaceDerivedLinks(
// 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);
+ await applyTemporalEvidence(tx, snapshot.page, rows, temporalKeysBefore, { inlineRanges: await effectiveRangesEnabled(tx) });
return result;
};
if (opts.includeFrontmatter !== false && !opts.preserveExisting) {
diff --git a/src/core/line-grammar.ts b/src/core/line-grammar.ts
index 881b0f26f0..d9c11102a4 100644
--- a/src/core/line-grammar.ts
+++ b/src/core/line-grammar.ts
@@ -332,6 +332,12 @@ export async function lineGrammarOptions(engine: { getConfig(key: string): Promi
allowUndeclaredTypes: allow != null && ['true', '1', 'yes', 'on'].includes(allow.trim().toLowerCase()) };
}
+/** `line_grammar.effective_ranges` (default off; needs the grammar on): store relation-line ranges on edges (core/link-effective.ts). */
+export async function effectiveRangesEnabled(engine: { getConfig(key: string): Promise<string | null> }): Promise<boolean> {
+ const ranges = await engine.getConfig('line_grammar.effective_ranges').catch(() => null);
+ return ranges != null && ['true', '1', 'yes', 'on'].includes(ranges.trim().toLowerCase()) && (await lineGrammarOptions(engine)).enabled;
+}
+
/**
* The stated relation type for a link at `index` in `text`, for link
* extraction. `declaredVerbs` (the active pack's link verbs) gates types
diff --git a/src/core/link-effective.ts b/src/core/link-effective.ts
new file mode 100644
index 0000000000..499d839eba
--- /dev/null
+++ b/src/core/link-effective.ts
@@ -0,0 +1,44 @@
+/**
+ * Validity ranges written on typed relation lines become dated transitions.
+ *
+ * - works_at @effective[2021-03,2024-06) [[companies/acme-example]]
+ *
+ * reads as "started 2021-03-01, ended 2024-06-01" on the works_at
+ * relationship this page states with that line (producer 'inline', owned by
+ * the page and replaced with its derived links). Only a relationship the
+ * page's derived links assert with the line's type gets a range, so a
+ * missing target, a gated type or a disabled grammar dates nothing. Bounds
+ * are already exact days (line-grammar.ts resolves `[ ]` / `( )`), so the
+ * precision is 'day'. Grammar: docs/guides/line-grammar.md.
+ */
+import { parseLineGrammar } from './line-grammar.ts';
+import { lineHash, normalizeLinkTarget, refersTo, type DerivedTransition, type OwnedRow, type TemporalEvidence } from './link-temporal-evidence.ts';
+import { relationSemantics } from './link-validity.ts';
+
+export type InlineTransition = Omit<DerivedTransition, 'producer'> & { producer: 'inline' };
+
+const LINK_RE = /\[\[([^\]|\n]+)(?:\|[^\]\n]*)?\]\]|\[[^\]\n]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/;
+
+export function inlineTransitions(slug: string, content: string, rows: readonly OwnedRow[]): {
+ transitions: InlineTransition[]; unmatched: TemporalEvidence['unmatched'];
+} {
+ const transitions: InlineTransition[] = [];
+ const unmatched: TemporalEvidence['unmatched'] = [];
+ for (const relation of parseLineGrammar(content).relations) {
+ if (!relation.effective) continue;
+ const line = content.slice(relation.start, relation.end).trim();
+ const semantics = relationSemantics(relation.type);
+ if (semantics === 'reference') { unmatched.push({ line, reason: 'not_temporal' }); continue; }
+ const link = LINK_RE.exec(line);
+ const target = link ? normalizeLinkTarget(link[1] ?? link[2]) : '';
+ const row = target ? rows.find(r => r.from_slug === slug && r.link_type === relation.type && refersTo(target, r.to_slug)) : undefined;
+ if (!row) { unmatched.push({ line, reason: 'no_target' }); continue; }
+ const base = { from_slug: row.from_slug, to_slug: row.to_slug, link_type: relation.type, date_precision: 'day' as const,
+ producer: 'inline' as const, line_hash: lineHash(line) };
+ const { from, until } = relation.effective;
+ if (from) transitions.push({ ...base, kind: 'start', occurred_on: from });
+ if (until && semantics === 'event') unmatched.push({ line, reason: 'event_cannot_end' });
+ else if (until) transitions.push({ ...base, kind: 'end', occurred_on: until });
+ }
+ return { transitions, unmatched };
+}
diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.ts
index 97f7c304a9..1f2980663b 100644
--- a/src/core/link-temporal-apply.ts
+++ b/src/core/link-temporal-apply.ts
@@ -4,7 +4,9 @@
*
* 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);
+ * explicit, frontmatter, dream, and inline when `inlineRanges` is on:
+ * validity ranges on typed relation lines, core/link-effective.ts; manual
+ * rows are left alone);
* 3. refresh `link_relationships` for every relationship the page touched
* before or after the change.
*
@@ -17,10 +19,11 @@ import { executeRawJsonb } from './sql-query.ts';
import { deriveTemporalEvidence, rowKey, type TemporalEvidence } from './link-temporal-evidence.ts';
import { refreshRelationships, type RelationshipKey } from './link-relationships.ts';
import { temporalLinkTypes } from './link-validity.ts';
+import { inlineTransitions } from './link-effective.ts';
type Tx = Pick<BrainEngine, 'executeRaw'>;
-const DERIVED_PRODUCERS = ['timeline', 'explicit', 'frontmatter', 'dream'];
+const DERIVED_PRODUCERS = ['timeline', 'explicit', 'frontmatter', 'dream', 'inline'];
export interface TemporalApplyResult {
transitions: number;
@@ -46,6 +49,7 @@ export async function applyTemporalEvidence(
page: Pick<Page, 'id' | 'slug' | 'source_id' | 'compiled_truth' | 'timeline' | 'frontmatter'>,
rows: readonly LinkBatchInput[],
keysBefore: readonly RelationshipKey[],
+ opts: { inlineRanges?: boolean } = {},
): Promise<TemporalApplyResult> {
const pageId = Number(page.id);
const sourceId = page.source_id ?? 'default';
@@ -53,6 +57,10 @@ export async function applyTemporalEvidence(
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 inline = opts.inlineRanges
+ ? inlineTransitions(page.slug, `${page.compiled_truth ?? ''}\n${page.timeline ?? ''}`, rows.filter(r => (r.link_source ?? 'markdown') !== 'frontmatter'))
+ : { transitions: [], unmatched: [] };
+ const transitions = [...evidence.transitions, ...inline.transitions];
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',
@@ -74,7 +82,7 @@ export async function applyTemporalEvidence(
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) {
+ if (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
@@ -84,9 +92,9 @@ export async function applyTemporalEvidence(
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 }]);
+ [pageId, sourceId], [{ rows: transitions }]);
}
- const unmatched = [...evidence.unmatched];
+ const unmatched = [...evidence.unmatched, ...inline.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 }>(
diff --git a/src/core/link-temporal-evidence.ts b/src/core/link-temporal-evidence.ts
index 02bf412222..4029bd42d4 100644
--- a/src/core/link-temporal-evidence.ts
+++ b/src/core/link-temporal-evidence.ts
@@ -135,7 +135,7 @@ function referencesIn(text: string): RefHit[] {
}
/** Does a normalized link target point at `slug` (full path or unique basename form)? */
-function refersTo(target: string, slug: string): boolean {
+export function refersTo(target: string, slug: string): boolean {
if (target === slug) return true;
const base = slug.split('/').pop()!;
return !target.includes('/') && target.toLowerCase() === base.toLowerCase();
@@ -179,7 +179,7 @@ function datedLines(content: string): DatedLine[] {
return out;
}
-const lineHash = (s: string) => createHash('sha256').update(s).digest('hex').slice(0, 16);
+export const lineHash = (s: string) => createHash('sha256').update(s).digest('hex').slice(0, 16);
// ─── Derivation ──────────────────────────────────────────────────────────
diff --git a/test/fixtures/goldens/sql-text/_driver.json b/test/fixtures/goldens/sql-text/_driver.json
index ff5cc72d56..d3fc5815d3 100644
--- a/test/fixtures/goldens/sql-text/_driver.json
+++ b/test/fixtures/goldens/sql-text/_driver.json
@@ -2096,6 +2096,10 @@
},
"via": "unsafe"
},
+ {
+ "paramCount": 1,
+ "via": "tagged"
+ },
{
"paramCount": 2,
"unsafeOptions": {
diff --git a/test/fixtures/goldens/sql-text/links.json b/test/fixtures/goldens/sql-text/links.json
index f0b3bc2402..0dd273a590 100644
--- a/test/fixtures/goldens/sql-text/links.json
+++ b/test/fixtures/goldens/sql-text/links.json
@@ -398,6 +398,14 @@
"event": "savepoint-release",
"lane": "tx>sp"
},
+ {
+ "lane": "tx",
+ "params": [
+ "string"
+ ],
+ "sql": "SELECT value FROM config WHERE key = $1",
+ "textSha256": "32d050605cb95dccb4dcc33a20003cfd10f1fd8e194c317d54e08869acb32e9c"
+ },
{
"lane": "tx",
"params": [
diff --git a/test/link-effective.test.ts b/test/link-effective.test.ts
new file mode 100644
index 0000000000..6d6d31823b
--- /dev/null
+++ b/test/link-effective.test.ts
@@ -0,0 +1,101 @@
+/**
+ * Validity ranges on typed relation lines (`- works_at @effective[a,b) [[x]]`)
+ * stored as dated edge transitions (producer 'inline', core/link-effective.ts)
+ * when `line_grammar.effective_ranges` is on.
+ *
+ * Protects: an ended range hides the edge from default graph reads and shows
+ * it to as_of reads; an open range keeps it live; editing the range replaces
+ * the stored transitions; a range on an event type stores only its start; a
+ * range on a link the page does not store with that type stores nothing; with
+ * the flag off nothing is stored.
+ */
+import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { PGLiteEngine } from '../src/core/pglite-engine.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 { inlineTransitions } from '../src/core/link-effective.ts';
+
+setDefaultTimeout(60_000);
+let engine: PGLiteEngine;
+
+const ctx = (): OperationContext => ({
+ engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} },
+ dryRun: false, remote: false, sourceId: 'default', emitNotice: () => {}, emitResponseMeta: () => {},
+} as OperationContext);
+const op = (name: string) => operations.find(o => o.name === name)!;
+
+async function put(slug: string, fm: string, body: string) {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op('put_page').handler(ctx(), { slug, ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: `---\n${fm}\n---\n\n${body}` });
+}
+const worksAt = async (params: Record<string, unknown> = {}) =>
+ ((await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'works_at', ...params })) as Array<{ to_slug: string }>).map(r => r.to_slug).sort();
+const inline = () => engine.executeRaw<{ kind: string; occurred_on: unknown; link_type: string }>(
+ `SELECT kind, occurred_on::text AS occurred_on, link_type FROM link_transitions WHERE producer = 'inline' ORDER BY link_type, kind`);
+
+beforeAll(async () => {
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema(); resetGateway();
+ await put('companies/acme-example', 'type: company\ntitle: Acme', 'A company.');
+ await put('companies/widget-co', 'type: company\ntitle: Widget', 'Another company.');
+});
+afterAll(async () => { await engine.disconnect(); resetGateway(); });
+
+describe('line_grammar.effective_ranges', () => {
+ test('off by default: a range is parsed but nothing is stored', async () => {
+ await put('people/alice-example', 'type: person\ntitle: Alice',
+ '- works_at @effective[2021-03,2024-06) [[companies/acme-example]]\n- works_at @effective[2024-06,) [[companies/widget-co]]');
+ expect(await inline()).toEqual([]);
+ expect(await worksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);
+ });
+
+ test('on: an ended range hides the edge from default reads; as_of finds it', async () => {
+ await engine.setConfig('line_grammar.effective_ranges', 'true');
+ await put('people/alice-example', 'type: person\ntitle: Alice',
+ 'Alice.\n\n- works_at @effective[2021-03,2024-06) [[companies/acme-example]]\n- works_at @effective[2024-06,) [[companies/widget-co]]');
+ expect(await inline()).toEqual([
+ { kind: 'end', occurred_on: '2024-06-01', link_type: 'works_at' },
+ { kind: 'start', occurred_on: '2021-03-01', link_type: 'works_at' },
+ { kind: 'start', occurred_on: '2024-06-01', link_type: 'works_at' },
+ ]);
+ expect(await worksAt()).toEqual(['companies/widget-co']);
+ expect(await worksAt({ as_of: '2022-01-01' })).toEqual(['companies/acme-example']);
+ expect(await worksAt({ status: 'all' })).toEqual(['companies/acme-example', 'companies/widget-co']);
+ });
+
+ test('editing the range replaces the stored transitions', async () => {
+ await put('people/alice-example', 'type: person\ntitle: Alice',
+ '- works_at @effective[2021-03,) [[companies/acme-example]]\n- works_at @effective[2024-06,) [[companies/widget-co]]');
+ expect((await inline()).filter(r => r.kind === 'end')).toEqual([]);
+ expect(await worksAt()).toEqual(['companies/acme-example', 'companies/widget-co']);
+ await put('people/alice-example', 'type: person\ntitle: Alice', '- works_at [[companies/widget-co]]');
+ expect(await inline()).toEqual([]);
+ });
+
+ test('turning the flag off drops the stored ranges on the next extraction', async () => {
+ await put('people/alice-example', 'type: person\ntitle: Alice', '- works_at @effective[2021-03,2024-06) [[companies/acme-example]]');
+ expect((await inline()).length).toBe(2);
+ await engine.setConfig('line_grammar.effective_ranges', 'false');
+ await put('people/alice-example', 'type: person\ntitle: Alice', '- works_at @effective[2021-03,2024-06) [[companies/acme-example]]\n\nEdited.');
+ expect(await inline()).toEqual([]);
+ expect(await worksAt()).toEqual(['companies/acme-example']);
+ });
+});
+
+describe('inlineTransitions', () => {
+ const rows = [{ from_slug: 'people/alice-example', to_slug: 'companies/acme-example', link_type: 'works_at', link_source: 'markdown' },
+ { from_slug: 'people/alice-example', to_slug: 'companies/widget-co', link_type: 'invested_in', link_source: 'markdown' }];
+
+ test('an event type stores its start and reports the end', () => {
+ const r = inlineTransitions('people/alice-example', '- invested_in @effective[2021,2023) [[companies/widget-co]]', rows);
+ expect(r.transitions.map(t => [t.kind, t.occurred_on, t.producer])).toEqual([['start', '2021-01-01', 'inline']]);
+ expect(r.unmatched.map(u => u.reason)).toEqual(['event_cannot_end']);
+ });
+
+ test('a link the page does not store with the line type, or a reference type, stores nothing', () => {
+ const r = inlineTransitions('people/alice-example',
+ '- advises @effective[2021,) [[companies/acme-example]]\n- mentions @effective[2021,) [[companies/acme-example]]', rows);
+ expect(r.transitions).toEqual([]);
+ expect(r.unmatched.map(u => u.reason).sort()).toEqual(['no_target', 'not_temporal']);
+ });
+});