Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): schema packs declare relation semantics with link_types[].temporal (GBRA-49 P1)

garrytanefd7c258ae03
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 0cc09769ea..0b6eabb6d3 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -107,6 +107,6 @@ rejection of serve-only flags before a brain opens.
- `src/core/trajectory-format.ts` — shared `formatTrajectoryBlock(points, entitySlug, opts)` consumed by both `gbrain think` (production) and the LongMemEval harness (benchmark). Groups by `(metric ?? event_type)`, per-metric cap 20, total cap 100, knowledge_update intent annotates value-change rows with `(superseded prior)`. Emits a `<trajectory entity="...">` XML envelope — `INJECTION_PATTERNS` in `src/core/think/sanitize.ts` escapes `</trajectory>`, `<trajectory ...>` open tags, and attribute injection so adversarial fact text can't break out. Pinned by `test/trajectory-format.test.ts`.
-- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.
+- `src/core/link-validity.ts` + `src/core/link-relationships.ts` + `src/core/link-temporal-evidence.ts` + `src/core/link-temporal-apply.ts` + `src/core/ops/edge-temporal.ts` — temporal typed edges ([guide](../../guides/temporal-edges.md)). Relation semantics (state / event / reference), `buildRelationshipState` (order-invariant stints from `links` assertions with `assertion_tense` plus dated `link_transitions`; dated beats undated, same-page present beats past), `closeContradiction` (pure date arithmetic, relationship-specific starts only), and `relationshipFilterSql` / `annotateTemporalRow` / `edgeMatchesTemporal` (one liveness rule: a relationship with no `link_relationships` row reads live). `refreshRelationships` recomputes per-scope state (`all`, `world` ignores private-origin evidence) inside the writer's transaction; `replaceDerivedLinks` calls `applyTemporalEvidence`, and the engine link writers refresh touched temporal keys; the extract phase sweeps lagging or orphaned state. Graph ops read live relationships by default; default reads keep the established row shape, history reads (`status`, `as_of`, `during`) return `status`/`stints`/`recorded_at`/`retired_at`; hidden rows emit `former_relationships_hidden` + `gbrain.temporal` meta. `graph.edge_validity off` is a read policy only. `src/core/link-semantics-pack.ts` installs pack-declared `link_types[].temporal` semantics (union of the active and per-source packs, `state` wins) over the built-in table; `replaceDerivedLinks`, `add_link`/`remove_link` and the extract sweep prime it before deriving or refreshing state (lint rule `link_types_temporal`; `test/link-semantics-pack.test.ts`). `src/core/link-relationship-notes.ts` renders the shared relationship note (`now: … ; ended: … ; summary may be stale`) with one batched read for entity cards, `context_pack`, ambient turn-context synopses and compiled context entries. Pinned by `test/link-validity.test.ts`, `test/link-temporal-evidence.test.ts`, `test/link-relationships.test.ts` (+ Postgres twin), `test/link-temporal-put-page.test.ts`, `test/link-temporal-reads.test.ts`.
- `src/core/cycle/edge-contradictions.ts` + `src/commands/edge-proposals.ts` — the `edge_contradictions` dream phase and `gbrain edge-proposals`. Candidates are subjects with ≥2 live same-type state relationships whose pair evidence hash has no proposal; one judge call per subject returns only conflict flags; `closeContradiction` picks the ending relationship and date (undated → `undated_unresolved`). Modes propose (default) / apply (certified models in `CERTIFIED_APPLY_MODELS`) / off; applying appends a `gbrain-dream (inferred)` "Ended <type> [[target]]" timeline line through the coordinated `add_timeline_entry` path and re-derives the page; a hand-deleted line becomes `reverted_by_user`. Budget through the cycle `BudgetMeter`. Pinned by `test/cycle-edge-contradictions.test.ts` and the managed phase matrix.
diff --git a/docs/architecture/schema-packs.md b/docs/architecture/schema-packs.md
index 111895c159..fde411da22 100644
--- a/docs/architecture/schema-packs.md
+++ b/docs/architecture/schema-packs.md
@@ -270,6 +270,7 @@ This section is the single home for the merge rules (other docs link here).
`borrow_from` targets) into the `resolved.manifest` every consumer reads.
The rules:
+- **`link_types[].temporal`** (`state` | `event`, optional) declares whether a relation can end or happened on a date; graph reads then treat it as a temporal typed edge ([temporal edges](../guides/temporal-edges.md)).
- **Six fields inherit, child-wins:** `page_types`, `link_types`,
`frontmatter_links`, `enrichable_types`, `filing_rules`, and `takes_kinds`.
A child value with the same key (type name, link name, etc.) overrides the
diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.md
index af25aea735..497d61de7f 100644
--- a/docs/guides/temporal-edges.md
+++ b/docs/guides/temporal-edges.md
@@ -24,6 +24,27 @@ Relationship types fall into three groups:
Open-loop edges (`owes_to`, `awaiting_reply_from`) keep their own lifecycle in
open loops.
+A schema pack adds its own relations to the first two groups with
+`link_types[].temporal`:
+
+```yaml
+link_types:
+ - name: reports_to
+ inverse: manages
+ temporal: state # can end: reads return the manager true today
+ - name: promoted
+ temporal: event
+```
+
+The table above is the default; a pack declaration wins for its relation. The brain
+uses the union of its active pack and every per-source pack, and `state` wins if two
+packs disagree. `mentions` never carries a date. `gbrain schema lint` reports a
+`temporal` on `mentions` (error), a built-in relation redeclared with different
+semantics, and an inverse pair that disagrees (warnings). Natural-language cues
+("left", "joined") date the built-in relations only; a pack relation takes its dates
+from the explicit grammar (`Ended reports_to [[people/x]]`), frontmatter
+`since`/`until`, and `add_link valid_from` / `valid_until`.
+
## How dates get recorded (no model calls)
Every write re-reads the page and records dated evidence for the relationships
diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.ts
index 5a23bce821..d15dee02d6 100644
--- a/src/core/cycle/edge-contradictions.ts
+++ b/src/core/cycle/edge-contradictions.ts
@@ -26,7 +26,7 @@ import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.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';
+import { closeContradiction, parseMultirange, utcToday, dateKey, type Stint } from '../link-validity.ts';
export interface EdgeContradictionsResult {
name: 'edge_contradictions';
@@ -188,7 +188,6 @@ async function findCandidateGroups(engine: BrainEngine, maxSubjects: number): Pr
[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); }
diff --git a/src/core/derived-links.ts b/src/core/derived-links.ts
index 8a54468066..f2422135c6 100644
--- a/src/core/derived-links.ts
+++ b/src/core/derived-links.ts
@@ -3,6 +3,7 @@ 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';
+import { primeRelationSemantics } from './link-semantics-pack.ts';
export interface DerivedLinkOrigin {
slug: string;
@@ -53,6 +54,7 @@ export async function replaceDerivedLinks(
links: LinkBatchInput[],
opts: DerivedLinkReplacementOptions = {},
): Promise<{ created: number; removed: number }> {
+ await primeRelationSemantics(engine as Partial<Pick<BrainEngine, 'getConfig' | 'listConfigKeys'>>);
const producers = ['markdown', 'wikilink-resolved', ...(opts.includeFrontmatter === false ? [] : ['frontmatter'])];
const unique = new Map<string, LinkBatchInput>();
for (const link of links) {
diff --git a/src/core/link-relationship-notes.ts b/src/core/link-relationship-notes.ts
index 868369efc6..c5d1f28150 100644
--- a/src/core/link-relationship-notes.ts
+++ b/src/core/link-relationship-notes.ts
@@ -11,8 +11,7 @@
*/
import {
- annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, TEMPORAL_LINK_TYPES, relationSemantics,
- type RelationshipStatus,
+ annotateTemporalRow, temporalLinkJoinSql, TEMPORAL_LINK_SELECT_SQL, type RelationshipStatus,
} from './link-validity.ts';
import { privateLinkOriginFilterFragment, privatePagesFilterFragment } from './search/private-visibility.ts';
@@ -58,7 +57,6 @@ export async function loadRelationshipNotes(
): Promise<Map<string, string>> {
const notes = new Map<string, string>();
if (subjects.length === 0) return notes;
- const stateTypes = TEMPORAL_LINK_TYPES.filter(t => relationSemantics(t) === 'state');
const privacy = opts.excludePrivate ? ` AND ${privatePagesFilterFragment('t')} AND ${privateLinkOriginFilterFragment('l')}` : '';
const rows = await engine.executeRaw<{ from_slug: string; source_id: string; to_slug: string; to_title: string | null; link_type: string }>(
`SELECT f.slug AS from_slug, f.source_id, t.slug AS to_slug, t.title AS to_title, l.link_type${TEMPORAL_LINK_SELECT_SQL}
@@ -67,8 +65,8 @@ export async function loadRelationshipNotes(
JOIN pages t ON t.id = l.to_page_id
${temporalLinkJoinSql('l', opts.excludePrivate)}
WHERE (f.source_id, f.slug) IN (SELECT s.source_id, s.slug FROM unnest($1::text[], $2::text[]) AS s(source_id, slug))
- AND l.link_type = ANY($3::text[]) AND lr_t.semantics = 'state' AND t.deleted_at IS NULL${privacy}`,
- [subjects.map(s => s.source_id), subjects.map(s => s.slug), stateTypes],
+ AND lr_t.semantics = 'state' AND t.deleted_at IS NULL${privacy}`,
+ [subjects.map(s => s.source_id), subjects.map(s => s.slug)],
);
const bySubject = new Map<string, Map<string, NoteEdge>>();
for (const raw of rows) {
diff --git a/src/core/link-relationships.ts b/src/core/link-relationships.ts
index ad8fee393d..9f7f2af97d 100644
--- a/src/core/link-relationships.ts
+++ b/src/core/link-relationships.ts
@@ -21,7 +21,7 @@ import type { BrainEngine } from './engine.ts';
import { executeRawJsonb } from './sql-query.ts';
import { privatePagesFilterFragment } from './search/private-visibility.ts';
import {
- buildRelationshipState, relationSemantics, statusAt, stintsToMultirange, dateKey, TEMPORAL_LINK_TYPES,
+ buildRelationshipState, relationSemantics, statusAt, stintsToMultirange, dateKey, temporalLinkTypes,
type AssertionEvidence, type TransitionEvidence, type RelationshipScope, type TransitionProducer,
} from './link-validity.ts';
@@ -187,7 +187,7 @@ export async function relationshipKeysForPages(exec: RawExec, pageIds: readonly
UNION
SELECT from_page_id, to_page_id, link_type FROM link_relationships
WHERE from_page_id = ANY($1::int[]) OR to_page_id = ANY($1::int[])`,
- [ids, [...TEMPORAL_LINK_TYPES]]);
+ [ids, temporalLinkTypes()]);
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 }));
}
@@ -209,7 +209,7 @@ export async function staleRelationshipKeys(exec: RawExec, limit = 500): Promise
AND lr.to_page_id = e.to_page_id AND lr.link_type = e.link_type AND lr.scope = 'all' AND lr.refreshed_at >= e.newest)
GROUP BY from_page_id, to_page_id, link_type
ORDER BY min(newest) LIMIT $2`,
- [[...TEMPORAL_LINK_TYPES], limit]);
+ [temporalLinkTypes(), limit]);
// Relationships whose evidence-owning page was deleted, restored or edited
// after the last refresh (soft deletes change no evidence row).
const originChanged = rows.length >= limit ? [] : await exec.executeRaw<RelationshipKey>(
@@ -237,6 +237,8 @@ export async function staleRelationshipKeys(exec: RawExec, limit = 500): Promise
*/
export async function sweepStaleRelationships(engine: BrainEngine, limit = 2000): Promise<Record<string, unknown>> {
try {
+ const { primeRelationSemantics } = await import('./link-semantics-pack.ts');
+ await primeRelationSemantics(engine);
const keys = await staleRelationshipKeys(engine, limit);
if (!keys.length) return {};
const { maintenanceTransaction } = await import('./persistence/attribution.ts');
diff --git a/src/core/link-semantics-pack.ts b/src/core/link-semantics-pack.ts
new file mode 100644
index 0000000000..f5f6590fda
--- /dev/null
+++ b/src/core/link-semantics-pack.ts
@@ -0,0 +1,56 @@
+/**
+ * Temporal typed edges: pack-declared relation semantics.
+ *
+ * A schema pack declares `link_types[].temporal: state | event`; the built-in
+ * table in link-validity.ts is the default. Semantics are brain-wide, keyed by
+ * relation name: the union of the brain's active pack and every per-source
+ * pack (`schema_pack.source.<id>`). When two packs disagree, `state` wins, so
+ * a relation that can end is never treated as permanent. `mentions` is never
+ * temporal.
+ *
+ * Write entry points (derived-link replacement, add_link / remove_link, the
+ * extract sweep, the contradiction phase) call `primeRelationSemantics` before
+ * they derive or refresh relationship state, so every writer in the process
+ * agrees with the pack. Reads use the semantics stored on each relationship.
+ */
+
+import type { BrainEngine } from './engine.ts';
+import { setPackRelationSemantics } from './link-validity.ts';
+import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';
+
+const SOURCE_PACK_PREFIX = 'schema_pack.source.';
+
+/** Pure: merge pack declarations; `state` wins a disagreement; `mentions` is ignored. */
+export function packRelationSemantics(manifests: ReadonlyArray<Pick<SchemaPackManifest, 'link_types'> | null | undefined>): Map<string, 'state' | 'event'> {
+ const out = new Map<string, 'state' | 'event'>();
+ for (const m of manifests) {
+ for (const lt of m?.link_types ?? []) {
+ if (!lt.temporal || lt.name === 'mentions') continue;
+ if (out.get(lt.name) !== 'state') out.set(lt.name, lt.temporal);
+ }
+ }
+ return out;
+}
+
+/**
+ * Load the active packs for `engine` and install their semantics. Fail-soft:
+ * an unreadable pack keeps the previous semantics (the built-in table on a
+ * fresh process).
+ */
+export async function primeRelationSemantics(engine: Partial<Pick<BrainEngine, 'getConfig' | 'listConfigKeys'>>): Promise<void> {
+ if (!engine.getConfig || !engine.listConfigKeys) return;
+ const configured = engine as Pick<BrainEngine, 'getConfig' | 'listConfigKeys'>;
+ try {
+ const { loadActivePackForLocalEngine } = await import('./schema-pack/best-effort.ts');
+ const sourceKeys = await configured.listConfigKeys(SOURCE_PACK_PREFIX).catch(() => [] as string[]);
+ const sourceIds = [...new Set(sourceKeys.map(k => k.slice(SOURCE_PACK_PREFIX.length)).filter(Boolean))];
+ const packs = await Promise.all([
+ loadActivePackForLocalEngine(configured),
+ ...sourceIds.map(sourceId => loadActivePackForLocalEngine(configured, { sourceId })),
+ ]);
+ if (packs.every(p => p === null)) return;
+ setPackRelationSemantics(packRelationSemantics(packs.map(p => p?.manifest)));
+ } catch {
+ // keep the semantics already installed
+ }
+}
diff --git a/src/core/link-temporal-apply.ts b/src/core/link-temporal-apply.ts
index bb3b0cbffa..97f7c304a9 100644
--- a/src/core/link-temporal-apply.ts
+++ b/src/core/link-temporal-apply.ts
@@ -16,7 +16,7 @@ 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 './link-relationships.ts';
-import { TEMPORAL_LINK_TYPES } from './link-validity.ts';
+import { temporalLinkTypes } from './link-validity.ts';
type Tx = Pick<BrainEngine, 'executeRaw'>;
@@ -37,7 +37,7 @@ export async function relationshipKeysForOrigin(tx: Tx, pageId: number): Promise
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]]);
+ [pageId, temporalLinkTypes()]);
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 }));
}
diff --git a/src/core/link-validity.ts b/src/core/link-validity.ts
index 3a5016f336..cb120e4a93 100644
--- a/src/core/link-validity.ts
+++ b/src/core/link-validity.ts
@@ -46,15 +46,30 @@ export const RELATION_SEMANTICS: Readonly<Record<string, RelationSemantics>> = {
cited: 'event',
};
+/**
+ * Pack-declared semantics (`link_types[].temporal`) layered over the built-in
+ * table; a pack declaration wins for its type. Set by
+ * `primeRelationSemantics` (link-semantics-pack.ts) at write entry points.
+ */
+let packSemantics: ReadonlyMap<string, 'state' | 'event'> = new Map();
+
+export function setPackRelationSemantics(semantics: ReadonlyMap<string, 'state' | 'event'>): void {
+ packSemantics = semantics;
+}
+
export function relationSemantics(linkType: string | null | undefined): RelationSemantics {
- return (linkType && RELATION_SEMANTICS[linkType]) || 'reference';
+ if (!linkType) return 'reference';
+ return packSemantics.get(linkType) ?? RELATION_SEMANTICS[linkType] ?? 'reference';
}
export function isTemporalLinkType(linkType: string | null | undefined): boolean {
return relationSemantics(linkType) !== 'reference';
}
-export const TEMPORAL_LINK_TYPES: readonly string[] = Object.keys(RELATION_SEMANTICS);
+/** Every relation type with temporal state: the built-in table plus pack declarations. */
+export function temporalLinkTypes(): string[] {
+ return [...new Set([...Object.keys(RELATION_SEMANTICS), ...packSemantics.keys()])].filter(isTemporalLinkType).sort();
+}
// ─── Dates ───────────────────────────────────────────────────────────────
@@ -457,8 +472,9 @@ export function annotateTemporalRow<T extends { link_type: string }>(row: T, asO
const semantics = r.temporal_semantics as 'state' | 'event' | null | undefined;
const out = { ...row } as T & TemporalAnnotation & { first_start?: string | null };
for (const c of TEMPORAL_COLUMNS) delete (out as unknown as Record<string, unknown>)[c];
- if (relationSemantics(row.link_type) === 'reference') return Object.assign(out, { status: 'reference' as const });
- if (ranges == null || !semantics) return Object.assign(out, { status: 'live' as const });
+ if (ranges == null || !semantics) {
+ return Object.assign(out, { status: relationSemantics(row.link_type) === 'reference' ? 'reference' as const : 'live' as const });
+ }
const stints = parseMultirange(ranges);
const status = statusAt({ semantics, stints, disputed: r.temporal_disputed === true, undatedPast: Number(r.temporal_undated_past ?? 0) }, asOf);
return Object.assign(out, {
diff --git a/src/core/ops/links.ts b/src/core/ops/links.ts
index c8454c129a..0e001b5a80 100644
--- a/src/core/ops/links.ts
+++ b/src/core/ops/links.ts
@@ -29,9 +29,10 @@ 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, 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 { isCalendarDate, relationSemantics, temporalLinkTypes } from '../link-validity.ts';
import { writeManualTransitions, removeManualTransitions } from '../link-temporal-apply.ts';
import { maintenanceTransaction } from '../persistence/attribution.ts';
+import { primeRelationSemantics } from '../link-semantics-pack.ts';
// #4655: write-time pack vocabulary enforcement for explicit link verbs.
import {
loadActivePackForWriteVocabulary,
@@ -68,7 +69,7 @@ function validateLinkDates(ctx: OperationContext, p: Record<string, unknown>, li
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(', ')})`,
+ throw opError('invalid_params', `add_link: link_type '${linkType || '(none)'}' has no dates; valid_from/valid_until apply to dated relations (${temporalLinkTypes().join(', ')})`,
`Pass link_type such as works_at with the dates, or drop valid_from/valid_until.`);
}
if (relationSemantics(linkType) === 'event' && validUntil !== undefined) {
@@ -113,6 +114,7 @@ const add_link: Operation = {
);
}
}
+ await primeRelationSemantics(ctx.engine);
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
@@ -184,6 +186,7 @@ const remove_link: Operation = {
handler: async (ctx, p) => {
enforceClientSlugFence(ctx, p.from as string, 'remove_link');
if (ctx.dryRun) return { dry_run: true, action: 'remove_link', from: p.from, to: p.to };
+ await primeRelationSemantics(ctx.engine);
const linkOpts = ctx.sourceId
? { fromSourceId: ctx.sourceId, toSourceId: ctx.sourceId }
: undefined;
diff --git a/src/core/schema-pack/lint-rules.ts b/src/core/schema-pack/lint-rules.ts
index 0aad49cde8..b97bbe3588 100644
--- a/src/core/schema-pack/lint-rules.ts
+++ b/src/core/schema-pack/lint-rules.ts
@@ -12,6 +12,7 @@
// Issue shape mirrors the StructuredAgentError envelope from
// src/core/errors.ts so JSON output is consistent across CLI + MCP.
+import { RELATION_SEMANTICS } from '../link-validity.ts';
import type { SchemaPackManifest } from './manifest-v1.ts';
import type { BrainEngine } from '../engine.ts';
import { readRecentMutations } from './mutate-audit.ts';
@@ -169,6 +170,35 @@ export const linkTypesUndeclared: LintRule = (manifest) => {
return issues;
};
+/**
+ * `link_types[].temporal`: `mentions` never carries temporal state (error);
+ * redeclaring a built-in relation with different semantics, or an inverse
+ * pair that disagrees, is flagged (warning).
+ */
+export const linkTypesTemporal: LintRule = (manifest) => {
+ const issues: LintIssue[] = [];
+ const declared = new Map(manifest.link_types.filter((lt) => lt.temporal).map((lt) => [lt.name, lt.temporal!]));
+ for (const lt of manifest.link_types) {
+ if (!lt.temporal) continue;
+ if (lt.name === 'mentions') {
+ issues.push({ rule: 'link_types_temporal_mentions', severity: 'error', pack: manifest.name, link: lt.name,
+ message: "link_type 'mentions' cannot be temporal: mentions are references, and every mention would get relationship state. Remove temporal from 'mentions'." });
+ continue;
+ }
+ const builtin = RELATION_SEMANTICS[lt.name];
+ if (builtin && builtin !== lt.temporal) {
+ issues.push({ rule: 'link_types_temporal_overrides_builtin', severity: 'warning', pack: manifest.name, link: lt.name,
+ message: `link_type '${lt.name}' is built in as '${builtin}'; this pack makes it '${lt.temporal}' for every brain using the pack. Drop temporal from '${lt.name}' to keep '${builtin}'.` });
+ }
+ const inverse = lt.inverse ? declared.get(lt.inverse) : undefined;
+ if (inverse && inverse !== lt.temporal) {
+ issues.push({ rule: 'link_types_temporal_inverse_mismatch', severity: 'warning', pack: manifest.name, link: lt.name,
+ message: `link_type '${lt.name}' is '${lt.temporal}' but its inverse '${lt.inverse}' is '${inverse}'. Declare the same temporal value on both.` });
+ }
+ }
+ return issues;
+};
+
export const frontmatterLinksUndeclared: LintRule = (manifest) => {
const issues: LintIssue[] = [];
const typeNames = new Set(manifest.page_types.map((t) => t.name));
@@ -427,6 +457,7 @@ export const ALL_LINT_RULES: ReadonlyArray<{ name: string; rule: LintRule; plane
{ name: 'alias_references_undeclared_type', rule: aliasReferencesUndeclaredType, planeAware: false },
{ name: 'enrichable_types_undeclared', rule: enrichableTypesUndeclared, planeAware: false },
{ name: 'link_types_undeclared', rule: linkTypesUndeclared, planeAware: false },
+ { name: 'link_types_temporal', rule: linkTypesTemporal, planeAware: false },
{ name: 'frontmatter_links_undeclared', rule: frontmatterLinksUndeclared, planeAware: false },
{ name: 'expert_routing_without_prefix', rule: expertRoutingWithoutPrefix, planeAware: false },
{ name: 'prefix_collision', rule: prefixCollision, planeAware: false },
diff --git a/src/core/schema-pack/manifest-v1.ts b/src/core/schema-pack/manifest-v1.ts
index 7f3dd723ed..e28c38bb5f 100644
--- a/src/core/schema-pack/manifest-v1.ts
+++ b/src/core/schema-pack/manifest-v1.ts
@@ -43,6 +43,13 @@ const LinkTypeSchema = z.object({
name: z.string().min(1),
inverse: z.string().optional(),
inference: LinkInferenceSchema.optional(),
+ /**
+ * Temporal typed edges: `state` relations can end (works_at, reports_to) and
+ * graph reads return the ones true today; `event` relations happened on a
+ * date and stay true. Omitted: the built-in table decides, else a plain
+ * reference. See docs/guides/temporal-edges.md.
+ */
+ temporal: z.enum(['state', 'event']).optional(),
}).strict();
/**
diff --git a/test/link-semantics-pack.test.ts b/test/link-semantics-pack.test.ts
new file mode 100644
index 0000000000..1c342481f9
--- /dev/null
+++ b/test/link-semantics-pack.test.ts
@@ -0,0 +1,115 @@
+/**
+ * Temporal typed edges — pack-declared relation semantics
+ * (`link_types[].temporal`): manifest validation, lint, the merge rule, and a
+ * pack relation (`reports_to`) that gains validity dates through add_link and
+ * the explicit timeline grammar.
+ */
+import { afterAll, beforeAll, describe, expect, setDefaultTimeout, test } from 'bun:test';
+import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { operations, type OperationContext } from '../src/core/operations.ts';
+import { parseSchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';
+import { linkTypesTemporal } from '../src/core/schema-pack/lint-rules.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests, _resetPackCacheForTests } from '../src/core/schema-pack/index.ts';
+import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';
+import { packRelationSemantics, primeRelationSemantics } from '../src/core/link-semantics-pack.ts';
+import { relationSemantics, setPackRelationSemantics, temporalLinkTypes } from '../src/core/link-validity.ts';
+
+setDefaultTimeout(60_000);
+
+const base = { api_version: 'gbrain-schema-pack-v1', name: 'org-fixture', version: '1.0.0', extends: null, page_types: [], frontmatter_links: [] };
+const orgPack = { ...base, link_types: [{ name: 'reports_to', inverse: 'manages', temporal: 'state' }, { name: 'manages', inverse: 'reports_to', temporal: 'state' }, { name: 'promoted', temporal: 'event' }] };
+
+describe('manifest and lint', () => {
+ test('temporal accepts state and event, rejects anything else', () => {
+ expect(parseSchemaPackManifest(orgPack).link_types.map(l => l.temporal)).toEqual(['state', 'state', 'event']);
+ expect(() => parseSchemaPackManifest({ ...base, link_types: [{ name: 'reports_to', temporal: 'forever' }] })).toThrow();
+ });
+
+ test("lint: mentions is an error; a built-in override and an inverse mismatch warn", async () => {
+ const issues = await linkTypesTemporal(parseSchemaPackManifest({ ...base, link_types: [
+ { name: 'mentions', temporal: 'state' },
+ { name: 'works_at', temporal: 'event' },
+ { name: 'reports_to', inverse: 'manages', temporal: 'state' },
+ { name: 'manages', inverse: 'reports_to', temporal: 'event' },
+ ] }), {});
+ expect(issues.map(i => [i.rule, i.severity, i.link])).toEqual([
+ ['link_types_temporal_mentions', 'error', 'mentions'],
+ ['link_types_temporal_overrides_builtin', 'warning', 'works_at'],
+ ['link_types_temporal_inverse_mismatch', 'warning', 'reports_to'],
+ ['link_types_temporal_inverse_mismatch', 'warning', 'manages'],
+ ]);
+ expect(await linkTypesTemporal(parseSchemaPackManifest(orgPack), {})).toEqual([]);
+ });
+
+ test('merge: state wins a disagreement between packs; mentions is ignored', () => {
+ const merged = packRelationSemantics([
+ { link_types: [{ name: 'owned_by', temporal: 'event' }, { name: 'mentions', temporal: 'state' }] },
+ { link_types: [{ name: 'owned_by', temporal: 'state' }] },
+ null,
+ ] as never);
+ expect([...merged]).toEqual([['owned_by', 'state']]);
+ });
+});
+
+describe('a pack relation through the write and read paths', () => {
+ let engine: PGLiteEngine;
+ let root: string;
+ const ctx = (): OperationContext => ({ engine, config: { engine: 'pglite' as const }, logger: { info() {}, warn() {}, error() {} }, dryRun: false, remote: false, sourceId: 'default' } as OperationContext);
+ const op = (name: string) => operations.find(o => o.name === name)!;
+ const put = async (slug: string, content: string) => {
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op('put_page').handler(ctx(), { slug, content, ...(snapshot ? { expected_revision: snapshot.revision } : {}) });
+ };
+ const reports = async (params: Record<string, unknown> = {}) =>
+ (await op('get_links').handler(ctx(), { slug: 'people/alice-example', link_type: 'reports_to', ...params }) as Array<Record<string, unknown>>);
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-semantics-pack-'));
+ writeFileSync(join(root, 'pack.json'), JSON.stringify(orgPack));
+ __setPackLocatorForTests(name => name === orgPack.name ? join(root, 'pack.json') : bundledPackPath(name));
+ _resetPackCacheForTests();
+ engine = new PGLiteEngine(); await engine.connect({}); await engine.initSchema();
+ await engine.setConfig('schema_pack', orgPack.name);
+ for (const slug of ['people/alice-example', 'people/bob-example', 'people/carol-example']) await put(slug, `---\ntype: person\ntitle: ${slug}\n---\n\nA person.\n`);
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ setPackRelationSemantics(new Map());
+ _resetPackLocatorForTests(); _resetPackCacheForTests();
+ rmSync(root, { recursive: true, force: true });
+ });
+
+ test('priming installs the pack semantics over the built-in table (page writes already primed)', async () => {
+ expect(relationSemantics('reports_to')).toBe('state');
+ setPackRelationSemantics(new Map());
+ expect(relationSemantics('reports_to')).toBe('reference');
+ await primeRelationSemantics(engine);
+ expect(relationSemantics('reports_to')).toBe('state');
+ expect(relationSemantics('promoted')).toBe('event');
+ expect(relationSemantics('works_at')).toBe('state');
+ expect(temporalLinkTypes()).toContain('reports_to');
+ });
+
+ test('add_link valid_until ends a pack state relation; default reads hide it, history keeps it', async () => {
+ await op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'people/bob-example', link_type: 'reports_to', valid_from: '2020-01-01', valid_until: '2023-06-01' });
+ await op('add_link').handler(ctx(), { from: 'people/alice-example', to: 'people/carol-example', link_type: 'reports_to', valid_from: '2023-06-01' });
+ expect((await reports()).map(r => r.to_slug)).toEqual(['people/carol-example']);
+ const history = await reports({ status: 'all' });
+ expect(history.map(r => [r.to_slug, r.status]).sort()).toEqual([['people/bob-example', 'ended'], ['people/carol-example', 'live']]);
+ expect((await reports({ as_of: '2021-01-01' })).map(r => r.to_slug)).toEqual(['people/bob-example']);
+ });
+
+ test('the explicit timeline grammar ends a pack relation on the page that states it', async () => {
+ await put('people/alice-example', [
+ '---', 'type: person', 'title: Alice', '---', '', 'Alice is on the platform team.', '', '## Timeline', '',
+ '- **2026-01-15** | note — Ended reports_to [[people/carol-example]]',
+ ].join('\n'));
+ expect(await reports()).toEqual([]);
+ const carol = (await reports({ status: 'all' })).find(r => r.to_slug === 'people/carol-example')!;
+ expect(carol.status).toBe('ended');
+ expect(carol.stints).toEqual([{ from: '2023-06-01', until: '2026-01-15' }]);
+ });
+});
diff --git a/test/schema-pack-lint-rules.test.ts b/test/schema-pack-lint-rules.test.ts
index 8ac978221a..d545df3abc 100644
--- a/test/schema-pack-lint-rules.test.ts
+++ b/test/schema-pack-lint-rules.test.ts
@@ -332,15 +332,16 @@ describe('runAllLintRules — composition', () => {
});
describe('rule registry shape', () => {
- it('ALL_LINT_RULES contains 14 rules', () => {
+ it('ALL_LINT_RULES contains 15 rules', () => {
// v0.41.37.0 #1569 added link_regex_catastrophic_backtrack (file-plane).
// Five-issue fix wave added stored_type_is_alias + stored_type_undeclared
// (both data-plane — they audit the pages corpus against the pack).
- expect(ALL_LINT_RULES.length).toBe(14);
+ // Temporal typed edges added link_types_temporal (file-plane).
+ expect(ALL_LINT_RULES.length).toBe(15);
});
it('FILE_PLANE_LINT_RULES excludes the 4 DB-aware rules', () => {
- expect(FILE_PLANE_LINT_RULES.length).toBe(10);
+ expect(FILE_PLANE_LINT_RULES.length).toBe(11);
expect(FILE_PLANE_LINT_RULES.every((r) => !r.planeAware)).toBe(true);
});