Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

feat(graph): declared single-value relations close by the chain rule without a model (schema pack cardinality one_per_from)

garrytan60655971a03e
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 5d6ca00a5a..7e2e38865e 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -111,3 +111,4 @@ rejection of serve-only flags before a brain opens.
- `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.
+- `src/core/link-single-value.ts` — declared single-value relations ([guide](../../guides/temporal-edges.md#declared-single-value-relations)). A pack's `cardinality: one_per_from` on a state relation, built in or declared `temporal: state` (manifest-v1 `LinkTypeSchema`; lint rule `link_types_cardinality` rejects it elsewhere) makes `edge_contradictions` close that type's competing live relationships without a model: `planSingleValueClosures` orders members by latest dated start and applies `closeContradiction` to each consecutive pair (undated and same-date members stay open as proposals). `declaredSingleValueTypes` reads the source's resolved pack; `previewSingleValue` backs the read-only `gbrain schema cardinality-preview`. `dream.single_value.mode` apply (default) / propose / off. Pinned by `test/link-single-value.test.ts`.
diff --git a/docs/guides/temporal-edges.md b/docs/guides/temporal-edges.md
index 4466c9f426..09adc9905a 100644
--- a/docs/guides/temporal-edges.md
+++ b/docs/guides/temporal-edges.md
@@ -169,11 +169,49 @@ An applied proposal is one timeline line on the subject page:
Delete the line to reopen the relationship; the check records that and does not
propose it again until the evidence changes.
+## Declared single-value relations
+
+A schema pack can declare that a state relation has one current value per page, for
+example a company brain where `works_at` means the one current employer:
+
+```yaml
+link_types:
+ - name: works_at
+ cardinality: one_per_from # default: many
+```
+
+For a declared type the nightly check asks no model: the declaration already says two
+live relationships cannot both hold. The chain rule orders the page's live
+relationships by their latest dated start and ends each one on the date the next one
+started, so an out-of-order import (Acme from January, Widget from March, then Gadget
+from February) ends Acme in February and Gadget in March. Relationships without a dated
+start, and two that start on the same date, stay open and appear in
+`gbrain edge-proposals list`. Closures land as the same reversible timeline lines,
+recorded with model `schema-pack:cardinality`.
+
+- Only state relations take `cardinality`: the built-in ones (`works_at`, `advises`, `yc_partner`) and any type the
+ pack declares `temporal: state`. `gbrain schema lint` rejects it elsewhere, because only state relations end.
+- The declaration comes from the source's resolved pack. A child pack that redeclares
+ the type replaces the whole entry, so it must restate `cardinality`.
+- `gbrain schema cardinality-preview [--source <id>] [--json]` lists every page with
+ more than one live relationship of a declared type and what the next dream cycle
+ closes or leaves open. It writes nothing; run it before activating a pack that adds a
+ declaration.
+- `gbrain config set dream.single_value.mode propose` records closures for review
+ instead of applying them; `off` hands declared types back to the model judge. The
+ default is `apply`.
+- To stop further closures, remove the declaration. `gbrain edge-proposals undo <id>`
+ (or deleting the line) reopens a relationship it closed.
+
+Older gbrain releases reject a pack that uses `cardinality`, so set the pack's
+`gbrain_min_version` to the release that adds it.
+
## Turning it off
- `gbrain config set graph.edge_validity off`: graph reads return every edge, as
before. Dated evidence keeps being recorded, so turning it back on loses nothing.
-- `gbrain config set dream.edge_contradictions.mode off`: no relationship checks.
+- `gbrain config set dream.edge_contradictions.mode off`: no model-judged relationship checks
+ (declared single-value relations follow `dream.single_value.mode`).
Lines it already wrote stay until `gbrain edge-proposals undo --all-applied`.
## Health
diff --git a/src/commands/schema.ts b/src/commands/schema.ts
index a1757bce66..1f5be37a28 100644
--- a/src/commands/schema.ts
+++ b/src/commands/schema.ts
@@ -81,6 +81,7 @@ export async function runSchema(args: string[]): Promise<void> {
case 'downgrade': return runDowngradeCmd(args.slice(1));
case 'usage': return runUsageCmd(args.slice(1));
case 'stats': return runStatsCmd(args.slice(1));
+ case 'cardinality-preview': return runCardinalityPreviewCmd(args.slice(1));
case 'sync': return runSyncCmd(args.slice(1));
case 'reload': return runReloadCmd(args.slice(1));
case 'add-type': return runAddTypeCmd(args.slice(1));
@@ -117,6 +118,8 @@ Inspection:
graph Show type/primitive graph with link-verb edges
lint [<pack>] Lint a pack for duplicates, dangling refs, etc.
stats [--source <id>] Per-type page counts + typed-coverage from the DB
+ cardinality-preview [--source <id>]
+ Pages with several live relationships of a declared single-value type, and what the dream cycle closes (read-only)
explain <type> Print resolved settings for a single type
usage [--since N(d|w|m)] CLI invocation telemetry summary
@@ -1045,6 +1048,28 @@ async function runStatsCmd(args: string[]): Promise<void> {
});
}
+async function runCardinalityPreviewCmd(args: string[]): Promise<void> {
+ const { json, source } = parseFlags(args);
+ await withConnectedEngine(async (engine) => {
+ const { previewSingleValue } = await import('../core/link-single-value.ts');
+ const result = await previewSingleValue(engine, source);
+ if (json) { console.log(JSON.stringify(result, null, 2)); return; }
+ if (Object.keys(result.declared).length === 0) {
+ console.log('No single-value relations declared. A pack declares one with `cardinality: one_per_from` on a state relation (docs/guides/temporal-edges.md#declared-single-value-relations).');
+ return;
+ }
+ for (const [src, types] of Object.entries(result.declared)) console.log(`Source ${src}: single-value ${types.join(', ')}`);
+ if (result.groups.length === 0) { console.log('No page holds more than one live relationship of a declared type.'); return; }
+ for (const g of result.groups) {
+ console.log(`\n${g.subject} ${g.link_type} (${g.source_id}): ${g.live.map(l => `${l.target}${l.since ? ` since ${l.since}` : ' (undated)'}`).join(', ')}`);
+ for (const c of g.would_close) console.log(` closes ${c.target} on ${c.close_date} (superseded by ${c.superseded_by})`);
+ for (const u of g.undated) console.log(` leaves ${u} open: no dated start; add one to the page timeline`);
+ for (const [a, b] of g.same_date) console.log(` leaves ${a} and ${b} open: both start on the same date`);
+ }
+ console.log('\nThe dream cycle (edge_contradictions phase) applies the closures as timeline lines; `gbrain edge-proposals list` shows them, and deleting a line reopens the relationship.');
+ });
+}
+
async function runSyncCmd(args: string[]): Promise<void> {
const apply = args.includes('--apply');
const { json, source } = parseFlags(args);
diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.ts
index be3eef5d0c..fad1b9d481 100644
--- a/src/core/cycle/edge-contradictions.ts
+++ b/src/core/cycle/edge-contradictions.ts
@@ -27,6 +27,7 @@ import type { PhaseResult } from '../cycle.ts';
import { BudgetMeter, loadAllowUnpriced, loadPricingOverrides, parseBudgetUsd } from './budget-meter.ts';
import { resolveModel } from '../model-config.ts';
import { closeContradiction, parseMultirange, utcToday, dateKey, type Stint } from '../link-validity.ts';
+import { declaredSingleValueTypes, planSingleValueClosures } from '../link-single-value.ts';
export interface EdgeContradictionsResult {
name: 'edge_contradictions';
@@ -222,19 +223,29 @@ export async function runPhaseEdgeContradictions(engine: BrainEngine, opts: Edge
const model = await resolveModel(engine, { configKey: 'models.dream.edge_contradictions', tier: 'utility', fallback: 'haiku' });
const config = await loadEdgeContradictionsConfig(engine, model);
- if (config.mode === 'off') return done('skipped', 'mode off (dream.edge_contradictions.mode)');
+ const declaredMode = await loadSingleValueMode(engine);
+ if (config.mode === 'off' && declaredMode === 'off') return done('skipped', 'mode off (dream.edge_contradictions.mode, dream.single_value.mode)');
+
+ const reverted = await markRevertedProposals(engine);
+ const allGroups = await findCandidateGroups(engine, config.maxSubjects);
+ if (allGroups.length === 0) return done('complete', `no subjects with competing live relationships${reverted ? `; ${reverted} reverted by user` : ''}`, { subjects: 0, reverted });
+ if (opts.dryRun) return done('skipped', `dry-run: ${allGroups.length} subject(s) would be judged`, { subjects: allGroups.length });
+
+ const declared = await runDeclaredSingleValue(engine, allGroups, declaredMode, opts);
+ const groups = allGroups.filter(g => !declared.handled.has(g));
+ const declaredDetail = declared.handled.size
+ ? `; declared single-value: ${declared.totals.proposed} closure(s), ${declared.totals.applied} applied, ${declared.totals.undated_unresolved} undated, ${declared.totals.ambiguous_same_date} same-date`
+ : '';
+ const withDeclared = (t: Record<string, number>) => ({ ...t, ...Object.fromEntries(Object.entries(declared.totals).map(([k, v]) => [`declared_${k}`, v])) });
+ if (groups.length === 0) return done('complete', `no subjects left for the judge${declaredDetail}`, withDeclared({ subjects: allGroups.length, reverted }));
+ if (config.mode === 'off') return done(declared.handled.size ? 'complete' : 'skipped', `mode off (dream.edge_contradictions.mode)${declaredDetail}`, withDeclared({ subjects: allGroups.length, reverted }));
if (!opts.judge && !opts.assumeChatAvailable) {
const { isAvailable } = await import('../ai/gateway.ts');
if (!isAvailable('chat', model)) {
- return done('skipped', `no chat model available (${model}); configure one (gbrain models) to have relationship contradictions proposed`);
+ return done(declared.handled.size ? 'complete' : 'skipped', `no chat model available (${model}); configure one (gbrain models) to have relationship contradictions proposed${declaredDetail}`, withDeclared({ subjects: allGroups.length, reverted }));
}
}
- const reverted = await markRevertedProposals(engine);
- const groups = await findCandidateGroups(engine, config.maxSubjects);
- if (groups.length === 0) return done('complete', `no subjects with competing live relationships${reverted ? `; ${reverted} reverted by user` : ''}`, { subjects: 0, reverted });
- if (opts.dryRun) return done('skipped', `dry-run: ${groups.length} subject(s) would be judged`, { subjects: groups.length });
-
const meter = new BudgetMeter({
budgetUsd: config.budgetUsd, allowUnpriced: config.allowUnpriced,
pricingOverrides: await loadPricingOverrides(engine), phase: 'edge_contradictions', auditPath: opts.auditPath,
@@ -310,9 +321,67 @@ export async function runPhaseEdgeContradictions(engine: BrainEngine, opts: Edge
(config.mode === 'apply' ? `, ${totals.applied} applied` : ' (mode propose: review with gbrain edge-proposals list)') +
`, ${totals.compatible} compatible, ${totals.undated_unresolved} undated, ${totals.ambiguous_same_date} same-date` +
(totals.errors ? `, ${totals.errors} judge error(s)` : '') + (budgetExhausted ? ' (budget exhausted)' : '') +
- `. Cost: $${meter.totalSpent.toFixed(4)} / $${config.budgetUsd.toFixed(2)} with ${model}`;
+ `. Cost: $${meter.totalSpent.toFixed(4)} / $${config.budgetUsd.toFixed(2)} with ${model}${declaredDetail}`;
const status = budgetExhausted || totals.errors ? (totals.judged ? 'partial' : 'failed') : 'complete';
- return done(status, detail, totals);
+ return done(status, detail, withDeclared(totals));
+}
+
+export type SingleValueMode = 'apply' | 'propose' | 'off';
+export const SINGLE_VALUE_MODEL = 'schema-pack:cardinality';
+
+async function loadSingleValueMode(engine: BrainEngine): Promise<SingleValueMode> {
+ const raw = (await engine.getConfig('dream.single_value.mode'))?.trim().toLowerCase();
+ return raw === 'propose' || raw === 'off' ? raw : 'apply';
+}
+
+/**
+ * Groups whose relation the source's pack declares `cardinality: one_per_from`
+ * are closed by the chain rule (link-single-value.ts) without a model: each
+ * live relationship ends at the next one's dated start. Undated and same-date
+ * members are recorded as open conflicts. Handled groups never reach the judge.
+ */
+async function runDeclaredSingleValue(
+ engine: BrainEngine, groups: SubjectGroup[], mode: SingleValueMode, opts: EdgeContradictionsOpts,
+): Promise<{ handled: Set<SubjectGroup>; totals: Record<string, number> }> {
+ const totals = { groups: 0, proposed: 0, applied: 0, undated_unresolved: 0, ambiguous_same_date: 0 };
+ const handled = new Set<SubjectGroup>();
+ if (mode === 'off') return { handled, totals };
+ const declaredBySource = new Map<string, Set<string>>();
+ for (const g of groups) {
+ if (!declaredBySource.has(g.sourceId)) declaredBySource.set(g.sourceId, await declaredSingleValueTypes(engine, g.sourceId));
+ if (!declaredBySource.get(g.sourceId)!.has(g.linkType)) continue;
+ handled.add(g);
+ totals.groups++;
+ const byTo = new Map(g.rels.map(r => [Number(r.to_page_id), r]));
+ const plan = planSingleValueClosures(g.rels.map(r => ({
+ to_page_id: Number(r.to_page_id), lastStart: dateKey(r.last_start), stints: parseMultirange(r.valid_ranges) as Stint[],
+ recordedAt: r.recorded_at instanceof Date ? r.recorded_at : r.recorded_at == null ? null : String(r.recorded_at),
+ })));
+ const record = async (a: CandidateRow, b: CandidateRow, p: Parameters<typeof recordProposal>[5]) => {
+ const [x, y] = ordered(a, b);
+ return recordProposal(engine, g, x, y, pairHash(x, y), p);
+ };
+ for (const c of plan.closures) {
+ const ending = byTo.get(c.ending)!, successor = byTo.get(c.successor)!;
+ const id = await record(ending, successor, {
+ status: 'proposed', model: SINGLE_VALUE_MODEL, confidence: 1, endingTo: c.ending, closeDate: c.closeDate,
+ bornClosed: c.bornClosed, line: dreamClosureLine(g.linkType, ending.target_slug, successor.target_slug),
+ });
+ if (id === null) continue;
+ totals.proposed++;
+ if (mode === 'apply' && (await (opts.applier ?? applyEdgeProposal)(engine, id)).status === 'applied') totals.applied++;
+ }
+ const dated = g.rels.filter(r => dateKey(r.last_start));
+ for (const to of plan.undated) {
+ const a = byTo.get(to)!;
+ const b = dated[dated.length - 1] ?? g.rels.find(r => r !== a)!;
+ if (await record(a, b, { status: 'undated_unresolved', model: SINGLE_VALUE_MODEL, detail: 'declared single-value relation without a dated start' }) !== null) totals.undated_unresolved++;
+ }
+ for (const [x, y] of plan.sameDate) {
+ if (await record(byTo.get(x)!, byTo.get(y)!, { status: 'ambiguous_same_date', model: SINGLE_VALUE_MODEL, detail: 'declared single-value relation with two starts on the same date' }) !== null) totals.ambiguous_same_date++;
+ }
+ }
+ return { handled, totals };
}
async function recordProposal(
diff --git a/src/core/link-single-value.ts b/src/core/link-single-value.ts
new file mode 100644
index 0000000000..6f0c222d8a
--- /dev/null
+++ b/src/core/link-single-value.ts
@@ -0,0 +1,123 @@
+/**
+ * Declared single-value relations: a schema pack marks a state relation
+ * `cardinality: one_per_from` (e.g. a pack where `works_at` means the one
+ * current employer). When a page then holds several live relationships of
+ * that type, the declaration itself is the verdict that they cannot all hold,
+ * so no model is asked; `closeContradiction` (link-validity.ts) still supplies
+ * every date. Closures land through the edge_contradictions apply path, as one
+ * reversible timeline line on the subject page.
+ *
+ * The chain rule orders a group's live relationships by their latest dated
+ * start and closes each one at the next one's start, so an out-of-order import
+ * (A from January, B from March, then C from February) ends A in February and
+ * C in March. Undated relationships and equal start dates are left open as
+ * conflicts.
+ */
+import type { BrainEngine } from './engine.ts';
+import { closeContradiction, dateKey, parseMultirange, RELATION_SEMANTICS, type Stint } from './link-validity.ts';
+
+export interface SingleValueMember {
+ to_page_id: number;
+ lastStart: string | null;
+ stints: Stint[];
+ recordedAt: string | Date | null;
+}
+
+export interface SingleValueClosure { ending: number; successor: number; closeDate: string; bornClosed: boolean }
+
+export interface SingleValuePlan {
+ closures: SingleValueClosure[];
+ undated: number[];
+ sameDate: Array<[number, number]>;
+}
+
+export function planSingleValueClosures(members: readonly SingleValueMember[]): SingleValuePlan {
+ const undated = members.filter(m => !dateKey(m.lastStart)).map(m => m.to_page_id);
+ const dated = members.filter(m => dateKey(m.lastStart))
+ .sort((a, b) => dateKey(a.lastStart)!.localeCompare(dateKey(b.lastStart)!) || a.to_page_id - b.to_page_id);
+ const closures: SingleValueClosure[] = [];
+ const sameDate: Array<[number, number]> = [];
+ for (let i = 0; i + 1 < dated.length; i++) {
+ const older = dated[i]!, newer = dated[i + 1]!;
+ const outcome = closeContradiction(older, newer);
+ if (outcome.action === 'close') {
+ closures.push({ ending: older.to_page_id, successor: newer.to_page_id, closeDate: outcome.closeDate, bornClosed: outcome.bornClosed });
+ } else if (outcome.reason === 'ambiguous_same_date') {
+ sameDate.push([older.to_page_id, newer.to_page_id]);
+ }
+ }
+ return { closures, undated, sameDate };
+}
+
+/** State relations the source's resolved schema pack declares single-valued. Fail-open to none. */
+export async function declaredSingleValueTypes(engine: BrainEngine, sourceId: string): Promise<Set<string>> {
+ try {
+ const { loadActivePackForEngine } = await import('./schema-pack/engine-resolution.ts');
+ const pack = await loadActivePackForEngine(engine, { sourceId, remote: false });
+ return new Set(pack.manifest.link_types
+ .filter(lt => lt.cardinality === 'one_per_from' && (lt.temporal ?? RELATION_SEMANTICS[lt.name]) === 'state')
+ .map(lt => lt.name));
+ } catch {
+ return new Set();
+ }
+}
+
+export interface SingleValuePreviewGroup {
+ source_id: string;
+ subject: string;
+ link_type: string;
+ live: Array<{ target: string; since: string | null }>;
+ would_close: Array<{ target: string; close_date: string; superseded_by: string }>;
+ undated: string[];
+ same_date: Array<[string, string]>;
+}
+
+/**
+ * Read-only: per declared single-value relation, every page with more than one
+ * live relationship of that type, and what the chain rule would close or leave
+ * open. `sourceId` narrows to one source.
+ */
+export async function previewSingleValue(engine: BrainEngine, sourceId?: string): Promise<{ declared: Record<string, string[]>; groups: SingleValuePreviewGroup[] }> {
+ const sources = sourceId ? [sourceId]
+ : (await engine.executeRaw<{ id: string }>(`SELECT id FROM sources ORDER BY id`)).map(r => r.id);
+ const declared: Record<string, string[]> = {};
+ const groups: SingleValuePreviewGroup[] = [];
+ for (const source of sources) {
+ const types = [...await declaredSingleValueTypes(engine, source)].sort();
+ if (!types.length) continue;
+ declared[source] = types;
+ const rows = await engine.executeRaw<{ subject: string; link_type: string; to_page_id: number; target: string; last_start: unknown; valid_ranges: string; recorded_at: unknown }>(
+ `WITH live AS (
+ SELECT lr.* FROM link_relationships lr
+ WHERE lr.scope = 'all' AND lr.source_id = $1 AND lr.link_type = ANY($2::text[]) AND lr.valid_ranges @> CURRENT_DATE
+ ), multi AS (
+ SELECT from_page_id, link_type FROM live GROUP BY 1, 2 HAVING count(DISTINCT to_page_id) >= 2
+ )
+ SELECT f.slug AS subject, l.link_type, l.to_page_id, t.slug AS target, l.last_start, l.valid_ranges::text AS valid_ranges, l.recorded_at
+ FROM live l JOIN multi m USING (from_page_id, link_type)
+ JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL
+ JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL
+ ORDER BY f.slug, l.link_type, t.slug`,
+ [source, types]);
+ const bySubject = new Map<string, typeof rows>();
+ for (const r of rows) {
+ const key = `${r.subject}\0${r.link_type}`;
+ bySubject.set(key, [...(bySubject.get(key) ?? []), r]);
+ }
+ for (const members of bySubject.values()) {
+ const slugOf = new Map(members.map(m => [Number(m.to_page_id), m.target]));
+ const plan = planSingleValueClosures(members.map(m => ({
+ to_page_id: Number(m.to_page_id), lastStart: dateKey(m.last_start), stints: parseMultirange(m.valid_ranges),
+ recordedAt: m.recorded_at instanceof Date ? m.recorded_at : m.recorded_at == null ? null : String(m.recorded_at),
+ })));
+ groups.push({
+ source_id: source, subject: members[0]!.subject, link_type: members[0]!.link_type,
+ live: members.map(m => ({ target: m.target, since: dateKey(m.last_start) })),
+ would_close: plan.closures.map(c => ({ target: slugOf.get(c.ending)!, close_date: c.closeDate, superseded_by: slugOf.get(c.successor)! })),
+ undated: plan.undated.map(id => slugOf.get(id)!),
+ same_date: plan.sameDate.map(([a, b]) => [slugOf.get(a)!, slugOf.get(b)!] as [string, string]),
+ });
+ }
+ }
+ return { declared, groups };
+}
diff --git a/src/core/schema-pack/lint-rules.ts b/src/core/schema-pack/lint-rules.ts
index b97bbe3588..044257ebb9 100644
--- a/src/core/schema-pack/lint-rules.ts
+++ b/src/core/schema-pack/lint-rules.ts
@@ -199,6 +199,21 @@ export const linkTypesTemporal: LintRule = (manifest) => {
return issues;
};
+export const linkTypesCardinality: LintRule = (manifest) => {
+ const issues: LintIssue[] = [];
+ for (const lt of manifest.link_types) {
+ if (lt.cardinality !== 'one_per_from' || (lt.temporal ?? RELATION_SEMANTICS[lt.name]) === 'state') continue;
+ issues.push({
+ rule: 'link_types_cardinality_not_state',
+ severity: 'error',
+ message: `link_type '${lt.name}' declares cardinality one_per_from, but only state relations have stints a newer start can close; declare temporal: state on '${lt.name}' or remove its cardinality`,
+ pack: manifest.name,
+ link: lt.name,
+ });
+ }
+ return issues;
+};
+
export const frontmatterLinksUndeclared: LintRule = (manifest) => {
const issues: LintIssue[] = [];
const typeNames = new Set(manifest.page_types.map((t) => t.name));
@@ -458,6 +473,7 @@ export const ALL_LINT_RULES: ReadonlyArray<{ name: string; rule: LintRule; plane
{ 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: 'link_types_cardinality', rule: linkTypesCardinality, 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 e28c38bb5f..d915738728 100644
--- a/src/core/schema-pack/manifest-v1.ts
+++ b/src/core/schema-pack/manifest-v1.ts
@@ -50,6 +50,8 @@ const LinkTypeSchema = z.object({
* reference. See docs/guides/temporal-edges.md.
*/
temporal: z.enum(['state', 'event']).optional(),
+ /** `one_per_from`: a page holds at most one live relationship of this type; a newer dated start closes the older one (docs/guides/temporal-edges.md). */
+ cardinality: z.enum(['many', 'one_per_from']).optional(),
}).strict();
/**
diff --git a/test/link-single-value.test.ts b/test/link-single-value.test.ts
new file mode 100644
index 0000000000..812bac2e07
--- /dev/null
+++ b/test/link-single-value.test.ts
@@ -0,0 +1,180 @@
+/**
+ * Declared single-value relations: a schema pack marks a state relation
+ * `cardinality: one_per_from`, and the edge_contradictions phase closes a
+ * page's competing live relationships of that type by the chain rule, with no
+ * model. Covers the pure planner (out-of-order imports, undated, same-date),
+ * the manifest and lint contract, and the phase on PGLite (apply, idempotent
+ * rerun, hand-deleted closure, mode off, undated conflict).
+ */
+import { afterAll, beforeAll, beforeEach, 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 { resetPgliteState } from './helpers/reset-pglite.ts';
+import { operations } from '../src/core/operations.ts';
+import type { OperationContext } from '../src/core/operations.ts';
+import { runPhaseEdgeContradictions } from '../src/core/cycle/edge-contradictions.ts';
+import { planSingleValueClosures, declaredSingleValueTypes, previewSingleValue } from '../src/core/link-single-value.ts';
+import { relationshipFilterSql } from '../src/core/link-validity.ts';
+import { __setPackLocatorForTests, _resetPackLocatorForTests, _resetPackCacheForTests } from '../src/core/schema-pack/index.ts';
+import { bundledPackPath } from '../src/core/schema-pack/bundled-assets.ts';
+import { parseSchemaPackManifest } from '../src/core/schema-pack/manifest-v1.ts';
+import { linkTypesCardinality } from '../src/core/schema-pack/lint-rules.ts';
+
+setDefaultTimeout(60_000);
+
+const stint = (from: string | null, until: string | null = null) => [{ from, until }];
+
+describe('planSingleValueClosures', () => {
+ test('an out-of-order import closes each relationship at the next dated start', () => {
+ const plan = planSingleValueClosures([
+ { to_page_id: 1, lastStart: '2024-01-10', stints: stint('2024-01-10'), recordedAt: null },
+ { to_page_id: 2, lastStart: '2024-03-01', stints: stint('2024-03-01'), recordedAt: null },
+ { to_page_id: 3, lastStart: '2024-02-01', stints: stint('2024-02-01'), recordedAt: null },
+ ]);
+ expect(plan.closures.map(c => [c.ending, c.successor, c.closeDate])).toEqual([[1, 3, '2024-02-01'], [3, 2, '2024-03-01']]);
+ expect(plan.undated).toEqual([]);
+ });
+
+ test('undated and same-date members stay open as conflicts; an already-ended stint is left alone', () => {
+ const plan = planSingleValueClosures([
+ { to_page_id: 1, lastStart: null, stints: stint(null), recordedAt: null },
+ { to_page_id: 2, lastStart: '2024-03-01', stints: stint('2024-03-01'), recordedAt: null },
+ { to_page_id: 3, lastStart: '2024-03-01', stints: stint('2024-03-01'), recordedAt: null },
+ { to_page_id: 4, lastStart: '2023-01-01', stints: stint('2023-01-01', '2023-06-01'), recordedAt: null },
+ ]);
+ expect(plan.undated).toEqual([1]);
+ expect(plan.sameDate).toEqual([[2, 3]]);
+ expect(plan.closures).toEqual([]);
+ });
+});
+
+describe('cardinality in the pack contract', () => {
+ const base = { api_version: 'gbrain-schema-pack-v1', name: 'sv-lint', version: '1.0.0', extends: null, page_types: [], frontmatter_links: [] };
+ test('one_per_from parses; one_per_to and unknown values are rejected', () => {
+ expect(parseSchemaPackManifest({ ...base, link_types: [{ name: 'works_at', cardinality: 'one_per_from' }] }).link_types[0]!.cardinality).toBe('one_per_from');
+ expect(() => parseSchemaPackManifest({ ...base, link_types: [{ name: 'works_at', cardinality: 'one_per_to' }] })).toThrow();
+ });
+ test('lint rejects a single-value declaration on a relation without stints', async () => {
+ const m = parseSchemaPackManifest({ ...base, link_types: [{ name: 'works_at', cardinality: 'one_per_from' }, { name: 'mentions', cardinality: 'one_per_from' }] });
+ const issues = await linkTypesCardinality(m);
+ expect(issues.map(i => [i.rule, i.link])).toEqual([['link_types_cardinality_not_state', 'mentions']]);
+ const custom = parseSchemaPackManifest({ ...base, link_types: [{ name: 'reports_to', temporal: 'state', cardinality: 'one_per_from' }, { name: 'manages', cardinality: 'one_per_from' }] });
+ expect((await linkTypesCardinality(custom)).map(i => i.link)).toEqual(['manages']);
+ });
+});
+
+describe('declared single-value closures in edge_contradictions', () => {
+ let engine: PGLiteEngine;
+ let root: string;
+ const pack = {
+ api_version: 'gbrain-schema-pack-v1', name: 'single-value-fixture', version: '1.0.0', extends: 'gbrain-base',
+ page_types: [], frontmatter_links: [], link_types: [{ name: 'works_at', cardinality: 'one_per_from' }],
+ };
+ const ctx = (): OperationContext => ({ engine, config: { engine: 'pglite' as const }, logger: { info: () => {}, warn: () => {}, error: () => {} }, dryRun: false, remote: false, sourceId: 'default' });
+ async function put(slug: string, fm: string, body: string) {
+ const op = operations.find(o => o.name === 'put_page')!;
+ const snapshot = await engine.readPageSnapshot(slug, { sourceId: 'default' });
+ await op.handler(ctx(), { slug, ...(snapshot ? { expected_revision: snapshot.revision } : {}), content: `---\n${fm}\n---\n\n${body}` });
+ }
+ const COMPANIES = ['acme-example', 'widget-co', 'gadget-co'];
+ async function seed(timeline: string) {
+ for (const c of COMPANIES) await put(`companies/${c}`, `type: company\ntitle: ${c}`, 'A company.');
+ await put('people/alice-example', 'type: person\ntitle: Alice',
+ `Alice works at ${COMPANIES.map(c => `[${c}](../companies/${c})`).join(', ')}.\n\n## Timeline\n\n${timeline}`);
+ }
+ const OUT_OF_ORDER = [
+ '- **2024-01-10** | test — joined [acme-example](../companies/acme-example)',
+ '- **2024-03-01** | test — joined [widget-co](../companies/widget-co)',
+ '- **2024-02-01** | test — joined [gadget-co](../companies/gadget-co)',
+ ].join('\n');
+ async function liveWorksAt() {
+ const rows = await engine.executeRaw<{ slug: string }>(
+ `SELECT DISTINCT t.slug FROM links l JOIN pages f ON f.id = l.from_page_id JOIN pages t ON t.id = l.to_page_id
+ WHERE f.slug = 'people/alice-example' AND l.link_type = 'works_at' AND ${relationshipFilterSql('l')} ORDER BY 1`);
+ return rows.map(r => r.slug);
+ }
+ const proposals = () => engine.executeRaw<{ status: string; close_date: string | null; model: string }>(
+ `SELECT status, close_date::text AS close_date, model FROM link_edge_proposals ORDER BY close_date NULLS LAST, id`);
+ const noJudge = async () => { throw new Error('the judge must not be called for declared relations'); };
+
+ beforeAll(async () => {
+ root = mkdtempSync(join(tmpdir(), 'gbrain-single-value-'));
+ writeFileSync(join(root, 'pack.json'), JSON.stringify(pack));
+ __setPackLocatorForTests(name => (name === pack.name ? join(root, 'pack.json') : bundledPackPath(name)));
+ _resetPackCacheForTests();
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ });
+ afterAll(async () => {
+ await engine.disconnect();
+ _resetPackLocatorForTests();
+ _resetPackCacheForTests();
+ rmSync(root, { recursive: true, force: true });
+ });
+ beforeEach(async () => {
+ await resetPgliteState(engine);
+ await engine.setConfig('schema_pack', pack.name);
+ });
+
+ test('the source pack declaration is read; the bundled default declares nothing', async () => {
+ expect([...await declaredSingleValueTypes(engine, 'default')]).toEqual(['works_at']);
+ await engine.setConfig('schema_pack', 'gbrain-base');
+ expect([...await declaredSingleValueTypes(engine, 'default')]).toEqual([]);
+ });
+
+ test('the preview lists what the dream cycle would close, without writing', async () => {
+ await seed(OUT_OF_ORDER);
+ const preview = await previewSingleValue(engine);
+ expect(preview.declared).toEqual({ default: ['works_at'] });
+ expect(preview.groups).toHaveLength(1);
+ expect(preview.groups[0]!.would_close).toEqual([
+ { target: 'companies/acme-example', close_date: '2024-02-01', superseded_by: 'companies/gadget-co' },
+ { target: 'companies/gadget-co', close_date: '2024-03-01', superseded_by: 'companies/widget-co' },
+ ]);
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+ });
+
+ test('closes the chain with no model, lands as timeline lines, and a rerun changes nothing', async () => {
+ await seed(OUT_OF_ORDER);
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+ const r = await runPhaseEdgeContradictions(engine, { judge: noJudge });
+ expect(r.totals).toMatchObject({ declared_proposed: 2, declared_applied: 2 });
+ expect(await liveWorksAt()).toEqual(['companies/widget-co']);
+ expect((await proposals()).map(p => [p.status, p.close_date, p.model])).toEqual([
+ ['applied', '2024-02-01', 'schema-pack:cardinality'], ['applied', '2024-03-01', 'schema-pack:cardinality'],
+ ]);
+ const page = await engine.getPage('people/alice-example', { sourceId: 'default' });
+ expect(page?.timeline).toContain('Ended works_at [[companies/acme-example]] (superseded by works_at companies/gadget-co)');
+ expect(page?.timeline).toContain('Ended works_at [[companies/gadget-co]] (superseded by works_at companies/widget-co)');
+ const again = await runPhaseEdgeContradictions(engine, { judge: noJudge });
+ expect(again.totals).toMatchObject({ subjects: 0 });
+ });
+
+ test('a hand-deleted closure line is reverted and never re-applied', async () => {
+ await seed(OUT_OF_ORDER);
+ await runPhaseEdgeContradictions(engine, { judge: noJudge });
+ await seed(OUT_OF_ORDER);
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+ const r = await runPhaseEdgeContradictions(engine, { judge: noJudge });
+ expect(r.totals).toMatchObject({ reverted: 2, declared_proposed: 0 });
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+ });
+
+ test('undated members stay open; dream.single_value.mode off hands the group back to the judge path', async () => {
+ await seed('- **2024-03-01** | test — joined [widget-co](../companies/widget-co)');
+ const r = await runPhaseEdgeContradictions(engine, { judge: noJudge });
+ expect(r.totals).toMatchObject({ declared_undated_unresolved: 2, declared_proposed: 0 });
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+
+ await resetPgliteState(engine);
+ await engine.setConfig('schema_pack', pack.name);
+ await engine.setConfig('dream.single_value.mode', 'off');
+ await engine.setConfig('dream.edge_contradictions.mode', 'off');
+ await seed(OUT_OF_ORDER);
+ expect((await runPhaseEdgeContradictions(engine, { judge: noJudge })).status).toBe('skipped');
+ expect(await liveWorksAt()).toEqual(['companies/acme-example', 'companies/gadget-co', 'companies/widget-co']);
+ });
+});
diff --git a/test/schema-pack-lint-rules.test.ts b/test/schema-pack-lint-rules.test.ts
index d545df3abc..64f6c539c3 100644
--- a/test/schema-pack-lint-rules.test.ts
+++ b/test/schema-pack-lint-rules.test.ts
@@ -332,16 +332,17 @@ describe('runAllLintRules — composition', () => {
});
describe('rule registry shape', () => {
- it('ALL_LINT_RULES contains 15 rules', () => {
+ it('ALL_LINT_RULES contains 16 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).
// Temporal typed edges added link_types_temporal (file-plane).
- expect(ALL_LINT_RULES.length).toBe(15);
+ // Declared single-value relations added link_types_cardinality (file-plane).
+ expect(ALL_LINT_RULES.length).toBe(16);
});
it('FILE_PLANE_LINT_RULES excludes the 4 DB-aware rules', () => {
- expect(FILE_PLANE_LINT_RULES.length).toBe(11);
+ expect(FILE_PLANE_LINT_RULES.length).toBe(12);
expect(FILE_PLANE_LINT_RULES.every((r) => !r.planeAware)).toBe(true);
});