Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

fix(graph): admit only person/employer works_at pairs as contradiction candidates (#6953)

time-attack26adc4dedeee
diff --git a/docs/architecture/key-files/graph-and-facts.md b/docs/architecture/key-files/graph-and-facts.md
index 6cf9a0cf0b..e72016892d 100644
--- a/docs/architecture/key-files/graph-and-facts.md
+++ b/docs/architecture/key-files/graph-and-facts.md
@@ -119,5 +119,5 @@ 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; `LIVENESS_EXEMPT_LINK_TYPES` (`amends`) never hide outside `ended` reads). `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`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`). #6311: a judge failure writes an `error` row whose detail is `attempt N/3; <class>: <message>` (provider keys, connection info and labeled credentials redacted, message ≤ 200 chars); skip-known treats it as known for 24 h (`updated_at`), then the pair is judged again and `recordProposal`'s upsert replaces only an `error` row; after `JUDGE_MAX_ATTEMPTS` (3) the detail reads `held after 3 attempts; …` and the pair is skipped until `gbrain edge-proposals retry <id> | --all-held` deletes the row (or the evidence hash changes). No migration. Pinned by `test/cycle-edge-contradictions.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; #6953 admission: `entity-types.ts`; 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`. `list` reads `--status` and `--limit` as `--flag value` or `--flag=value`; `--limit` is a positive integer (`intFlagValue`, a bad or missing value is `invalid_params` before any query) capped at 1000 (`test/edge-proposals-list-flags.test.ts`). Budget through the cycle `BudgetMeter`. The CLI's `rows()` normalizes proposal ids at the row boundary (Postgres returns `bigint` as BigInt: a safe integer becomes a number, anything larger an exact string) and `--json` output also passes `bigintToStringReplacer`, so `list/show --json` never crash on Postgres (#6193). Pinned by `test/cycle-edge-contradictions.test.ts`, the managed phase matrix, `test/edge-proposals-json-bigint.test.ts` and `test/e2e/edge-proposals-json-postgres.test.ts`. `edge-proposals <sub> --help` prints usage before any engine read (router help, `src/cli/subcommands.ts`). #6311: a judge failure writes an `error` row whose detail is `attempt N/3; <class>: <message>` (provider keys, connection info and labeled credentials redacted, message ≤ 200 chars); skip-known treats it as known for 24 h (`updated_at`), then the pair is judged again and `recordProposal`'s upsert replaces only an `error` row; after `JUDGE_MAX_ATTEMPTS` (3) the detail reads `held after 3 attempts; …` and the pair is skipped until `gbrain edge-proposals retry <id> | --all-held` deletes the row (or the evidence hash changes). No migration. Pinned by `test/cycle-edge-contradictions.test.ts`.
- `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` propose (default) / apply / off. Pinned by `test/link-single-value.test.ts`.
diff --git a/docs/architecture/key-files/schema-mutation.md b/docs/architecture/key-files/schema-mutation.md
index 230f3fc178..860a983688 100644
--- a/docs/architecture/key-files/schema-mutation.md
+++ b/docs/architecture/key-files/schema-mutation.md
@@ -20,7 +20,7 @@ Key files:
- `src/core/schema-pack/query-types.ts` — expands scalar/multiple type filters through the selected engine's active alias graph. Scalar and array filters retain intersection semantics; explicit empty arrays deny before any engine/cache access. Missing packs yield an empty filter that consumers return as no results, never as an unrestricted query; DB lookup failures propagate through keyword, hybrid and image readers. Mixed-pack explicit source scopes refuse rather than arbitrarily choosing a closure. Used by hybrid search and the search/query keyword-only/image bypasses; typed hybrid requests bypass semantic result caching. Tests: `test/schema-engine-isolation.serial.test.ts`, `test/ops-search-types.test.ts`.
-- `src/core/schema-pack/entity-types.ts` — #4772: the one answer to "is this stored type an entity" for the counters. `entityTypesFromPack(manifest)` returns the pack's `primitive: entity` type names (plus undeclared aliases of them) and the legacy names (`entity`, `person`, `company`, `organization`) the pack leaves undeclared; a pack that declares a legacy name under another primitive reclassified it and wins. `resolveEntityTypes(engine, scope)` resolves per source (every requested source id, or brain-wide: the brain's pack plus every registered source with a `schema_pack.source.<id>` override) into an `EntityTypeFilter` (default list + per-source lists that differ), and returns `pack_unavailable` with an empty filter when any pack in scope fails to load (the `best-effort.ts` null contract: empty filter, never hardcoded defaults). `entityTypePredicateSql(alias, filter)` renders it as a parameter-bound `sqlFragment`. Consumers: `engine-sql/health.ts` through `HealthDeps.entityTypes` (both engines delegate), `commands/doctor/checks/graph-health.ts` (`graph_coverage`, `orphan_ratio`), `onboard/checks.ts` (`entity_link_coverage`, `timeline_coverage`, and `visibleEntityCoverageSql` for `onboard/impact-capture.ts`; a pack that does not load warns `entity_types_unavailable`), `onboard/mcp-onboarding.ts` (the three entity counts are `null` with `entityTypesStatus: pack_unavailable`; the timeline result predicate) and `extract-ner.ts` (the target-type map; `pack_unavailable` when a source's pack does not load). `mentions/policy.ts` keeps its own linkable-type union. Pinned by `test/onboard-entity-types-pack-4772.test.ts`. Lazy-imports the pack loader so the engines can import it statically.
+- `src/core/schema-pack/entity-types.ts` — #4772: the one answer to "is this stored type an entity" for the counters. `entityTypesFromPack(manifest)` returns the pack's `primitive: entity` type names (plus undeclared aliases of them) and the legacy names (`entity`, `person`, `company`, `organization`) the pack leaves undeclared; a pack that declares a legacy name under another primitive reclassified it and wins. `resolveEntityTypes(engine, scope)` resolves per source (every requested source id, or brain-wide: the brain's pack plus every registered source with a `schema_pack.source.<id>` override) into an `EntityTypeFilter` (default list + per-source lists that differ), and returns `pack_unavailable` with an empty filter when any pack in scope fails to load (the `best-effort.ts` null contract: empty filter, never hardcoded defaults). `entityTypePredicateSql(alias, filter)` renders it as a parameter-bound `sqlFragment`. #6953: `personTypesFromPack` / `resolvePersonTypes` answer "is this type person-like" the same way (per source, same `pack_unavailable` contract): `person` plus its alias closure (`closure.ts`), never primitive siblings; consumer `cycle/edge-contradictions.ts`: its `works_at` members are admitted before grouping and LIMIT only when the subject is person-like by its source's pack (a pack that does not load admits none) and the target is neither person-like nor a `NON_EMPLOYER_TYPES` type (untyped: `NON_EMPLOYER_PREFIXES`; both lists shared with `link-target-roles.ts`'s `targetTakesVerb`); an open proposal made before that rule is not re-checked when applied (`test/edge-employment-roles.test.ts` + Postgres twin). Consumers: `engine-sql/health.ts` through `HealthDeps.entityTypes` (both engines delegate), `commands/doctor/checks/graph-health.ts` (`graph_coverage`, `orphan_ratio`), `onboard/checks.ts` (`entity_link_coverage`, `timeline_coverage`, and `visibleEntityCoverageSql` for `onboard/impact-capture.ts`; a pack that does not load warns `entity_types_unavailable`), `onboard/mcp-onboarding.ts` (the three entity counts are `null` with `entityTypesStatus: pack_unavailable`; the timeline result predicate) and `extract-ner.ts` (the target-type map; `pack_unavailable` when a source's pack does not load). `mentions/policy.ts` keeps its own linkable-type union. Pinned by `test/onboard-entity-types-pack-4772.test.ts`. Lazy-imports the pack loader so the engines can import it statically.
- `src/core/schema-pack/best-effort.ts` — `loadActivePackBestEffort(ctx)` returns `ResolvedPack | null`. Single source of truth for the pack-aware wiring sites. `null` means EMPTY FILTER (NOT hardcoded defaults, which would silently violate the pack). Threads the tier-4 DB-plane `schema_pack` from `ctx.engine`, so every caller resolves the SAME pack `schema active` / `get_active_schema_pack` report. `readDbSchemaPack(engine?)` is the ONE spelling of that tier-4 read (null-safe, propagates DB read failures, trims missing/empty values to undefined) — shared by both loaders here, the CLI inspection verbs (`schema show/graph/lint/explain`, via `readDbSchemaPackConfig` in `src/commands/schema.ts`, which keeps the cfg-null gate so an unconfigured home never cold-creates a PGLite dir) and the MCP `schema_lint`/`schema_graph`/`schema_explain_type` ops. `loadActivePackForLocalEngine(engine)` is the `remote: false` + FILE-ONLY-config variant for local engine-backed surfaces. Pinned by `test/schema-pack-best-effort.test.ts`, `test/operations-schema-pack.test.ts`, `test/schema-cli-db-config.test.ts`.
- `src/core/schema-pack/type-usage.ts` — stored-type classifier behind the alias-footgun visibility surfaces: `classifyStoredType(type, pack)` → canonical | alias_of (with the canonical type + `path_prefixes[0]` filing directory) | undeclared, over a STRUCTURAL pack shape so import-file's thin `activePack` and the full manifest both satisfy it. `sanitizeTypeForDisplay` strips control chars + caps length (type strings come from frontmatter and get echoed into terminals); `renderTypeWarningSummary` renders the once-per-type-per-run lines. Consumers: `importFromContent` (advisory `ImportResult.type_warning` at the typeExplicit site — the type is still stored literally, zero filing change), sync/import summary aggregation (+ `SyncResult.type_warnings` so worker-driven syncs surface counts in job results), the `stored_type_is_alias`/`stored_type_undeclared` data-plane lint rules, all gated by config `schema.type_warnings` (default on; lint rules always active). `storedTypeMissesPack(type, pack)` (empty type, or undeclared) is the one predicate every pack-conformance surface uses: `findTypeOrphans` (`schema-pack/review.ts`), `schema_stats` coverage, doctor `schema_pack_consistency`, `gbrain lint`'s `type-undeclared` rule. Pinned by `test/schema-type-usage.test.ts` and `test/schema-pack-type-conformance.test.ts`.
- `src/core/schema-pack/lint-rules.ts` — 14 pure rule functions. `withMutation`'s pre-write validation gate composes the 10 file-plane rules; the 4 DB-aware rules (`extractable_empty_corpus`, `mutation_count_anomaly`, `stored_type_is_alias`, `stored_type_undeclared`) need an engine (CLI `--with-db`; the stored-type pair accepts `LintOpts.sourceId` scoping, not yet threaded from the CLI). Single source of truth consumed by CLI lint + MCP `schema_lint` + the pre-write validation gate. File-plane rule `link_regex_catastrophic_backtrack` — advisory ReDoS pre-screen flagging the classic nested-quantifier shapes (`(a+)+`, `(a*)*`, `(a+)*`, `(\w+)+`) in a link_type's `inference.regex` via `NESTED_QUANTIFIER_RE`. WARNING not error: a hard reject would disable the whole pack on upgrade (pages fall back to legacy typing). The runtime input-length cap in `redos-guard.ts` is the actual safety net; this rule tells the pack author to fix the pattern.
diff --git a/src/core/behavior-change-notice.ts b/src/core/behavior-change-notice.ts
index 79702a3e17..f76f2c7702 100644
--- a/src/core/behavior-change-notice.ts
+++ b/src/core/behavior-change-notice.ts
@@ -904,10 +904,11 @@ export const BEHAVIOR_CHANGES: ReadonlyArray<{ since: string; text: ChangeText;
{ since: '0.60.299.0', text: 'Managed sync of a Markdown file over 24 MiB whose origin another page records (a page renamed with its file) now imports it into that page, as for a smaller file, instead of failing it `revision_conflict` ("A different page already owns this file identity") and stopping the source\'s sync at it.' },
{ since: '0.60.299.0', text: '`gbrain repair stuck-recovery` now resolves a page recovery whose file is over 24 MiB, which used to be listed as refused (`recovery_large_file_unsupported`) with no exit while it stopped every write on its source\'s worktree. The preview lists it with both fingerprints and the state of the staged copy of the prior file, backs up both versions, and writes a summary instead of a full diff (both hashes and sizes, the first byte where they differ, and a window of at most 1 KiB); `--apply --expect <hash> --keep prior|disk --yes` resolves it as it does a small file. Every read, hash and copy of the large file is done in pieces of at most a segment. When the staged copy of the prior file is missing or damaged, `--keep prior` refuses with `recovery_prior_stage_unavailable`, whose fix is the `--keep disk` apply, which keeps a damaged copy in the backup directory and removes it from the checkout.' },
{ since: '0.60.307.0', text: 'The remote doctor (`run_doctor`, `gbrain remote doctor`) now confines every check to the sources the caller may read. A source-scoped token no longer sees other sources\' ids, names, lag, embed coverage or failed jobs in `federation_health` and `sync_freshness`, or brain-wide counts in `sync_consolidation`, `links_extraction_lag` (each granted source is graded on its own and the worst is reported), `schema_pack_source_drift`, `graph_signals_coverage`, `hidden_by_search_policy`, `link_resolution_opportunity`, `embedding_migration_state`, the synopsis-failure line of `contextual_retrieval_coverage`, `brainstorm_health`, `abandoned_threads`, `calibration_freshness`, `grade_confidence_drift` and `voice_gate_health`. `federation_health` grades a scoped caller\'s sources even when it is granted only one. The local doctor and unscoped callers are unchanged.' },
- // Wave 20 lane 1 (#6944 #6945 #6940).
+ // Wave 20 lane 1 (#6944 #6945 #6940 #6953).
{ since: '0.60.307.0', text: '`gbrain recall --since <value>` now refuses a value it cannot read (and a `--since` with no value) with `invalid_params` (exit 2), echoing the value and listing the accepted forms, instead of silently recalling every time window. `--session` / `--session-id` with no ID refuses the same way instead of recalling every session. The CLI and the recall operation now share one `--since` parser.' },
{ since: '0.60.307.0', text: '`gbrain recall --since-last-run` (and `--watch`) on a local brain no longer skips facts when more than `--limit` of them arrived since the last run. A run that fills the window now shows the OLDEST `--limit` new facts (newest first within the page) and the next run continues right after the last one shown, until it catches up; before, it showed the newest `--limit` and the rest were never shown. The cursor file keeps `schema_version: 1` and gains two optional fields, so cursor files from earlier versions keep working. A thin client cannot page yet: when its window is full it prints a warning to raise `--limit`.' },
{ since: '0.60.307.0', text: '`get_health` / `gbrain health` `most_connected` no longer counts links to or from soft-deleted pages, so a hub whose neighbours were deleted drops in the ranking instead of keeping their edges (#6940). The islanded scan already applied this liveness rule.' },
+ { since: '0.60.307.0', text: 'The dream cycle\'s `edge_contradictions` phase now judges a `works_at` group only when its subject is a person (the pack\'s `person` type or a type that declares `aliases: [person]`) and its targets can employ someone: links from companies, and links to people, meetings, conversations, emails, sources, notes or inbox pages, no longer become "Ended works_at" proposals, and such malformed groups no longer use up the phase\'s subject limit (#6953). Link extraction no longer types a link to a conversation, email, source, note or inbox page as `works_at` (it stays `mentions`). Open proposals made earlier are not re-checked: reject unwanted ones with `gbrain edge-proposals reject <id>`. The judge prompt is unchanged.' },
];
/** The newest disclosed change's release: the notice id moves only when a release adds rows. */
diff --git a/src/core/cycle/edge-contradictions.ts b/src/core/cycle/edge-contradictions.ts
index 470438d937..f07c5d7eb4 100644
--- a/src/core/cycle/edge-contradictions.ts
+++ b/src/core/cycle/edge-contradictions.ts
@@ -26,6 +26,9 @@ import { redactConnectionInfo } from '../audit/redact-connection-info.ts';
import { applyRedaction, planRedaction } from '../secret-scan.ts';
import { LINK_EXTRACTION_GENERATION_KEY } from '../line-grammar.ts';
import { linkExtractorWatermarkFor } from '../link-extraction-watermark.ts';
+import { NON_EMPLOYER_PREFIXES, NON_EMPLOYER_TYPES } from '../link-target-roles.ts';
+import { entityTypePredicateSql, resolvePersonTypes } from '../schema-pack/entity-types.ts';
+import { renderFragment, sqlFragment } from '../engine-sql/fragment.ts';
import { createHash } from 'node:crypto';
import type { BrainEngine } from '../engine.ts';
import type { PhaseResult } from '../cycle.ts';
@@ -190,24 +193,34 @@ async function findCandidateGroups(engine: BrainEngine, maxSubjects: number): Pr
// decided on a half-reconciled graph. Before any change (generation unset) every subject is eligible, as before.
const generation = await engine.getConfig(LINK_EXTRACTION_GENERATION_KEY);
const pendingCutoff = generation ? linkExtractorWatermarkFor(generation) : null;
- const rows = await engine.executeRaw<CandidateRow>(
- `WITH live AS (
+ // #6953: works_at members are admitted before grouping and LIMIT, so mistyped newer groups cannot starve valid
+ // ones: the subject must be person-like by its source's pack (resolvePersonTypes; a pack that does not load admits
+ // no works_at subject), and the target neither person-like nor a non-employer type (untyped: by slug directory).
+ const personTypes = await resolvePersonTypes(engine, null);
+ const isPerson = (alias: 'f' | 't') => entityTypePredicateSql(alias, personTypes.filter);
+ const sql = renderFragment(sqlFragment`WITH live AS (
SELECT lr.* FROM link_relationships lr
- WHERE lr.scope = 'all' AND lr.semantics = 'state' AND lr.valid_ranges @> $1::date
+ JOIN pages f ON f.id = lr.from_page_id AND f.deleted_at IS NULL
+ JOIN pages t ON t.id = lr.to_page_id AND t.deleted_at IS NULL
+ WHERE lr.scope = 'all' AND lr.semantics = 'state' AND lr.valid_ranges @> ${today}::date
+ AND (lr.link_type <> 'works_at' OR (${isPerson('f')} AND NOT ${isPerson('t')} AND
+ CASE WHEN NULLIF(t.type, '') IS NOT NULL THEN NOT (t.type = ANY(${[...NON_EMPLOYER_TYPES]}::text[]))
+ ELSE NOT EXISTS (SELECT 1 FROM unnest(${[...NON_EMPLOYER_PREFIXES]}::text[]) AS prefix(value)
+ WHERE starts_with(t.slug, prefix.value)) END))
), multi AS (
SELECT source_id, from_page_id, link_type FROM live
GROUP BY 1, 2, 3 HAVING count(DISTINCT to_page_id) >= 2
- ORDER BY max(refreshed_at) DESC LIMIT $2
+ ORDER BY max(refreshed_at) DESC LIMIT ${maxSubjects}
)
SELECT l.source_id, l.from_page_id, l.to_page_id, l.link_type, l.valid_ranges::text AS valid_ranges,
l.last_start, l.recorded_at, l.evidence_hash,
f.slug AS subject_slug, f.title AS subject_title, t.slug AS target_slug, t.title AS target_title
FROM live l JOIN multi m USING (source_id, from_page_id, link_type)
JOIN pages f ON f.id = l.from_page_id AND f.deleted_at IS NULL
- AND ($3::timestamptz IS NULL OR f.links_extracted_at >= $3::timestamptz)
+ AND (${pendingCutoff}::timestamptz IS NULL OR f.links_extracted_at >= ${pendingCutoff}::timestamptz)
JOIN pages t ON t.id = l.to_page_id AND t.deleted_at IS NULL
- ORDER BY l.from_page_id, l.link_type, l.last_start NULLS FIRST, t.slug`,
- [today, maxSubjects, pendingCutoff]);
+ ORDER BY l.from_page_id, l.link_type, l.last_start NULLS FIRST, t.slug`);
+ const rows = await engine.executeRaw<CandidateRow>(sql.text, sql.params);
const groups = new Map<string, SubjectGroup>();
for (const r of rows) {
const key = `${r.from_page_id}\0${r.link_type}`;
diff --git a/src/core/link-target-roles.ts b/src/core/link-target-roles.ts
index a75b647638..062b20e166 100644
--- a/src/core/link-target-roles.ts
+++ b/src/core/link-target-roles.ts
@@ -2,8 +2,9 @@
* #6191: which role verbs a link target can take. A role verb in a link's
* context window ("VP of Sales", "founded … after") only types the edge when
* the target can hold that role:
- * - `works_at` needs an employer: never a person, nor a temporal or media
- * page (meeting, calendar event, media, image, transcript);
+ * - `works_at` needs an employer: never a person, a temporal or media page
+ * (meeting, calendar event, media, image, transcript), nor a document
+ * (conversation, email, source, note, inbox);
* - `founded` / `invested_in` never point at a temporal or media page
* (people found and invest together, so a person target keeps them).
* With no target type, the slug's directory decides (`people/`, `meetings/`,
@@ -13,10 +14,18 @@
const TEMPORAL_OR_MEDIA_TYPES = new Set(['meeting', 'calendar', 'calendar-event', 'media', 'image', 'transcript']);
const TEMPORAL_PREFIXES = ['meetings/', 'calendar/', 'cal/'];
+/** #6953: never employers. Shared with edge_contradictions' stored-edge admission; custom employer types stay allowed. */
+export const NON_EMPLOYER_TYPES: readonly string[] = [
+ ...TEMPORAL_OR_MEDIA_TYPES, 'person', 'conversation', 'email', 'source', 'note', 'inbox',
+];
+export const NON_EMPLOYER_PREFIXES: readonly string[] = [
+ ...TEMPORAL_PREFIXES, 'people/', 'conversations/', 'emails/', 'sources/', 'notes/', 'inbox/',
+];
+
export function targetTakesVerb(verb: string, targetSlug?: string, targetType?: string | null): boolean {
if (verb !== 'works_at' && verb !== 'founded' && verb !== 'invested_in') return true;
const temporal = targetType ? TEMPORAL_OR_MEDIA_TYPES.has(targetType) : TEMPORAL_PREFIXES.some(p => targetSlug?.startsWith(p));
if (temporal) return false;
if (verb !== 'works_at') return true;
- return targetType ? targetType !== 'person' : !targetSlug?.startsWith('people/');
+ return targetType ? !NON_EMPLOYER_TYPES.includes(targetType) : !NON_EMPLOYER_PREFIXES.some(p => targetSlug?.startsWith(p));
}
diff --git a/src/core/schema-pack/entity-types.ts b/src/core/schema-pack/entity-types.ts
index b44714af0b..f80455d12d 100644
--- a/src/core/schema-pack/entity-types.ts
+++ b/src/core/schema-pack/entity-types.ts
@@ -37,6 +37,7 @@
import type { BrainEngine } from '../engine.ts';
import { joinFragments, sqlFragment, trustedSql, type SqlFragment } from '../engine-sql/fragment.ts';
import type { SchemaPackManifest } from './manifest-v1.ts';
+import { buildAliasGraph, expandClosure } from './closure.ts';
/** The pre-pack hardcoded list; still entities while a pack leaves them undeclared. */
export const LEGACY_ENTITY_TYPES: readonly string[] = ['entity', 'person', 'company', 'organization'];
@@ -72,6 +73,15 @@ export function entityTypesFromPack(pack: Pick<SchemaPackManifest, 'page_types'>
return [...out].sort();
}
+/**
+ * #6953: person-like type names under one resolved pack, sorted: `person`
+ * plus every type in its alias closure (a type declaring `aliases: [person]`,
+ * and the types `person` declares). Primitive sharing does not count.
+ */
+export function personTypesFromPack(pack: SchemaPackManifest): string[] {
+ return expandClosure('person', buildAliasGraph(pack));
+}
+
const SOURCE_OVERRIDE_PREFIX = 'schema_pack.source.';
/**
@@ -82,11 +92,27 @@ const SOURCE_OVERRIDE_PREFIX = 'schema_pack.source.';
export async function resolveEntityTypes(
engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>,
scope: readonly string[] | null,
+): Promise<EntityTypeResolution> {
+ return resolveTypeFilter(engine, scope, entityTypesFromPack);
+}
+
+/** The person-like type filter (personTypesFromPack) for a reading, resolved per source like resolveEntityTypes. */
+export async function resolvePersonTypes(
+ engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>,
+ scope: readonly string[] | null,
+): Promise<EntityTypeResolution> {
+ return resolveTypeFilter(engine, scope, personTypesFromPack);
+}
+
+async function resolveTypeFilter(
+ engine: Pick<BrainEngine, 'getConfig' | 'executeRaw'>,
+ scope: readonly string[] | null,
+ fromPack: (pack: SchemaPackManifest) => string[],
): Promise<EntityTypeResolution> {
const { loadActivePackForLocalEngine } = await import('./best-effort.ts');
const typesFor = async (sourceId?: string) => {
const pack = await loadActivePackForLocalEngine(engine, sourceId ? { sourceId } : {});
- return pack ? entityTypesFromPack(pack.manifest) : null;
+ return pack ? fromPack(pack.manifest) : null;
};
const unresolved: string[] = [];
let defaults: string[] | null;
diff --git a/test/e2e/edge-employment-roles-postgres.test.ts b/test/e2e/edge-employment-roles-postgres.test.ts
new file mode 100644
index 0000000000..ae73cd92fa
--- /dev/null
+++ b/test/e2e/edge-employment-roles-postgres.test.ts
@@ -0,0 +1,3 @@
+import { registerPostgresTests } from '../helpers/test-backends.ts';
+
+await registerPostgresTests(() => import('../edge-employment-roles.test.ts'));
diff --git a/test/edge-employment-roles.test.ts b/test/edge-employment-roles.test.ts
new file mode 100644
index 0000000000..b9361c6e4e
--- /dev/null
+++ b/test/edge-employment-roles.test.ts
@@ -0,0 +1,164 @@
+/**
+ * #6953: edge_contradictions' works_at candidates admit only a person-like
+ * subject (the pack's person type and its alias closure, per source) and an
+ * employer target, before grouping and LIMIT. The judge prompt is unchanged
+ * (D7). PGLite here; Postgres through test/e2e/edge-employment-roles-postgres.test.ts.
+ */
+import { afterAll, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
+import { mkdtempSync, rmSync } from 'node:fs';
+import { tmpdir } from 'node:os';
+import { join } from 'node:path';
+import { _resetPackCacheForTests } from '../src/core/schema-pack/registry.ts';
+import { personTypesFromPack } from '../src/core/schema-pack/entity-types.ts';
+import { withEnv } from './helpers/with-env.ts';
+import { PACKS, writeEntityTypePacks } from './helpers/entity-types-pack-fixture.ts';
+import type { BrainEngine } from '../src/core/engine.ts';
+import { PGLiteEngine } from '../src/core/pglite-engine.ts';
+import { resetPgliteState } from './helpers/reset-pglite.ts';
+import { testBackends } from './helpers/test-backends.ts';
+import { runPhaseEdgeContradictions } from '../src/core/cycle/edge-contradictions.ts';
+import { targetTakesVerb } from '../src/core/link-target-roles.ts';
+import { extractPageLinks } from '../src/core/link-extraction.ts';
+import type { EdgeJudgeFn } from '../src/core/cycle/edge-contradictions.ts';
+
+for (const backend of testBackends()) describe(`employment role admission (${backend})`, () => {
+ let engine: BrainEngine;
+ beforeAll(async () => {
+ if (backend === 'postgres') {
+ const { setupDB } = await import('./e2e/helpers.ts');
+ engine = await setupDB();
+ } else {
+ engine = new PGLiteEngine();
+ await engine.connect({});
+ await engine.initSchema();
+ }
+ }, 60_000);
+ afterAll(async () => {
+ if (backend === 'postgres') {
+ const { teardownDB } = await import('./e2e/helpers.ts');
+ await teardownDB();
+ } else await engine.disconnect();
+ });
+ beforeEach(async () => {
+ if (backend === 'pglite') await resetPgliteState(engine as PGLiteEngine);
+ else {
+ await engine.executeRaw('DELETE FROM link_edge_proposals');
+ await engine.executeRaw('DELETE FROM pages');
+ }
+ await engine.setConfig('dream.edge_contradictions.mode', 'propose');
+ await engine.setConfig('dream.edge_contradictions.max_subjects', '1');
+ _resetPackCacheForTests();
+ });
+
+ async function page(slug: string, type: string) {
+ const p = await engine.putPage(slug, { type, title: slug, compiled_truth: 'Synthetic fixture.' });
+ return Number(p.id);
+ }
+ async function edge(from: number, to: number, type = 'works_at', refreshed = '2020-01-01') {
+ await engine.executeRaw(`INSERT INTO link_relationships
+ (from_page_id, to_page_id, link_type, scope, source_id, semantics, valid_ranges, status_now, evidence_hash, refreshed_at)
+ VALUES ($1, $2, $3, 'all', 'default', 'state', '{[2020-01-01,)}'::datemultirange, 'live', $4, $5::timestamptz)`,
+ [from, to, type, `${from}:${to}:${type}`, refreshed]);
+ }
+ async function judged() {
+ const inputs: Array<Parameters<EdgeJudgeFn>[0]> = [];
+ await runPhaseEdgeContradictions(engine, { judge: async input => {
+ inputs.push(input);
+ return [{ a: 1, b: 2, conflict: false, confidence: 0.9 }];
+ } });
+ return inputs;
+ }
+
+ test('mistyped newer groups cannot starve a valid person/employer pair at LIMIT 1', async () => {
+ const person = await page('people/alice-example', 'person');
+ const a = await page('orgs/acme-example', 'company');
+ const b = await page('orgs/widget-example', 'organization');
+ await edge(person, a); await edge(person, b);
+ for (const type of ['meeting', 'conversation', 'email', 'source', 'note', 'inbox', 'person']) {
+ const subject = await page(`people/${type}-example`, 'person');
+ const invalid = await page(`arbitrary/${type}-example`, type);
+ await edge(subject, a, 'works_at', '2099-01-01');
+ await edge(subject, invalid, 'works_at', '2099-01-01');
+ }
+ const inputs = await judged();
+ expect(inputs.map(i => i.subject.slug)).toEqual(['people/alice-example']);
+ expect(inputs[0].relationships.map(r => r.target).sort()).toEqual(['orgs/acme-example', 'orgs/widget-example']);
+ });
+
+ test('inverted company subject never reaches the judge or writes a proposal', async () => {
+ const subject = await page('companies/acme-example', 'company');
+ await edge(subject, await page('people/alice-example', 'person'));
+ await edge(subject, await page('people/bob-example', 'person'));
+ expect(await judged()).toEqual([]);
+ expect(await engine.executeRaw('SELECT id FROM link_edge_proposals')).toEqual([]);
+ });
+
+ test('filters invalid members before the per-subject relationship cap', async () => {
+ const subject = await page('people/alice-example', 'person');
+ for (let i = 0; i < 9; i++) await edge(subject, await page(`aaa/note-${i}`, 'note'));
+ await edge(subject, await page('orgs/acme-example', 'company'));
+ await edge(subject, await page('orgs/widget-example', 'investment-firm'));
+ const inputs = await judged();
+ expect(inputs).toHaveLength(1);
+ expect(inputs[0].relationships.map(r => r.target)).toEqual(['orgs/acme-example', 'orgs/widget-example']);
+ });
+
+ test('a pack type aliasing person is a subject; an entity type without the alias is not', async () => {
+ const home = mkdtempSync(join(tmpdir(), 'gbrain-6953-'));
+ try {
+ writeEntityTypePacks(home);
+ await withEnv({ GBRAIN_HOME: home, GBRAIN_SCHEMA_PACK: undefined }, async () => {
+ await engine.setConfig('schema_pack', PACKS.personAlias);
+ await engine.setConfig('dream.edge_contradictions.max_subjects', '5');
+ const researcher = await page('researchers/alice-example', 'researcher');
+ const lab = await page('labs/acme-lab-example', 'lab');
+ const a = await page('orgs/acme-example', 'company');
+ const b = await page('orgs/widget-example', 'company');
+ await edge(researcher, a); await edge(researcher, b);
+ await edge(lab, a, 'works_at', '2099-01-01'); await edge(lab, b, 'works_at', '2099-01-01');
+ expect((await judged()).map(i => i.subject.slug)).toEqual(['researchers/alice-example']);
+ });
+ } finally {
+ await engine.executeRaw("DELETE FROM config WHERE key = 'schema_pack'");
+ _resetPackCacheForTests();
+ rmSync(home, { recursive: true, force: true });
+ }
+ });
+
+ test('unrelated state relations retain organization subjects and document targets', async () => {
+ const subject = await page('companies/acme-example', 'company');
+ await edge(subject, await page('notes/a-example', 'note'), 'custom_state');
+ await edge(subject, await page('notes/b-example', 'note'), 'custom_state');
+ expect(await judged()).toHaveLength(1);
+ });
+});
+
+describe('employment inference and evidence policy', () => {
+ test('person-like types are person plus its alias closure, not primitive siblings', () => {
+ const pack = { page_types: [
+ { name: 'person', primitive: 'entity', aliases: [] },
+ { name: 'researcher', primitive: 'entity', aliases: ['person'] },
+ { name: 'lab', primitive: 'entity', aliases: [] },
+ ] } as never;
+ expect(personTypesFromPack(pack)).toEqual(['person', 'researcher']);
+ expect(personTypesFromPack({ page_types: [] } as never)).toEqual(['person']);
+ });
+ test('real link extraction keeps document mentions without inventing employment', async () => {
+ for (const type of ['conversation', 'email', 'source', 'note', 'inbox']) {
+ const { candidates } = await extractPageLinks('people/alice-example',
+ 'Alice is the CEO of [Example](arbitrary/example).', {}, 'person',
+ { resolve: async name => name }, { targetType: () => type });
+ expect(candidates.find(c => c.targetSlug === 'arbitrary/example')?.linkType).toBe('mentions');
+ }
+ });
+ test('document and person targets never take works_at, including untyped conventional paths', () => {
+ for (const type of ['conversation', 'email', 'source', 'note', 'inbox', 'person', 'meeting']) {
+ expect(targetTakesVerb('works_at', 'arbitrary/example', type)).toBe(false);
+ }
+ for (const prefix of ['conversations/', 'emails/', 'sources/', 'notes/', 'inbox/', 'people/', 'meetings/']) {
+ expect(targetTakesVerb('works_at', `${prefix}example`)).toBe(false);
+ }
+ expect(targetTakesVerb('works_at', 'orgs/example', 'custom-employer')).toBe(true);
+ expect(targetTakesVerb('invested_in', 'people/example', 'person')).toBe(true);
+ });
+});
diff --git a/test/helpers/entity-types-pack-fixture.ts b/test/helpers/entity-types-pack-fixture.ts
index 84c102f080..c7f1195a18 100644
--- a/test/helpers/entity-types-pack-fixture.ts
+++ b/test/helpers/entity-types-pack-fixture.ts
@@ -32,6 +32,7 @@ export const PACKS = {
widgetConcept: 'widget-concept-4772',
missing: 'missing-4772',
corrupt: 'corrupt-4772',
+ personAlias: 'person-alias-6953',
} as const;
function manifest(name: string, pageTypes: Array<{ name: string; primitive: string; aliases?: string[] }>): string {
@@ -73,6 +74,12 @@ export function writeEntityTypePacks(home: string): void {
{ name: 'widget', primitive: 'concept' },
{ name: 'gadget', primitive: 'entity' },
]));
+ write(PACKS.personAlias, manifest(PACKS.personAlias, [
+ { name: 'person', primitive: 'entity' },
+ { name: 'researcher', primitive: 'entity', aliases: ['person'] },
+ { name: 'lab', primitive: 'entity' },
+ { name: 'company', primitive: 'entity' },
+ ]));
write(PACKS.corrupt, 'api_version: gbrain-schema-pack-v1\nname: [not\n a: valid\npage_types: "nope"\n');
}