Garry's Opinionated OpenClaw/Hermes Agent Brain
TypeScript
link typing: unit rule and veto plumbing, frozen-example harness (no behavior change)
garrytan192c087012b4
diff --git a/scripts/module-size-limits.tsv b/scripts/module-size-limits.tsvindex ea54912161..e7300b6eb7 100644--- a/scripts/module-size-limits.tsv+++ b/scripts/module-size-limits.tsv@@ -31,7 +31,7 @@ src/core/minions/handlers/subagent.ts 1925 ratchet merged: master v131 settle resrc/commands/bootstrap.ts 2134 ratchet grandfathered at merge (grew past the 1500 cap on master); raised for #4066 HOME_WORKSPACE_GUARD_EXEMPT (status/uninstall/harness); +5 for the harnessDetect test seam (bulk lives in core/bootstrap/harness.ts); +23 for the contract subcommand dispatcher glue (#4105 absorb — bulk lives in core/bootstrap/contract.ts); +codex hooks-consent gate + mcp+hooks receipt registration + uninstall arm; +42 ambient-writeback WP8: interview-time SURFACE_MULTIUSER audience apply (pre-init ordering) + applyDeclaredAudienceFromInterview; +3 #4897 harness usage clause documenting --source ID semantics; +5 #5878: --refresh-skills dispatch and usage lines (logic in core/bootstrap/harness-skills.ts); +11 #5488: SUBCOMMAND_HELP harness entry (gate on --help / -h / help) — CLI help line, cannot move; +11 #4618 seat: --seat/--no-seat help lines and the runHooks parse (parse + notes live in core/bootstrap/hooks.ts parseSeatFlags)src/core/minions/worker.ts 1774 ratchet grandfathered at merge (grew past the 1500 cap on master, #4170); grown v0.46.11.0 five-issue wave; security: durable queued authority and confined filesystem dispatch; typed readiness, configuration-blocked lifecycle and bounded release; post-validation readiness publication and confirmed isolated-execution stop evidence; latch typed lock-renewal faults before generic retry; +9 Lane D: JobDeferredError routing (deferJob helper); +1 spend authorization: runWithJobSpend import (both handler seams call it in place of the bare handler)src/commands/sources.ts 2042 ratchet +5 #5988: sources status/retry-held help rows describe Git holds (help lines cannot move); +2 #5988: sources status <id> filter and Git held files (view in persistence/connector-status.ts); +5 F0: sources refresh dispatch and help rows (command body in sources-refresh.ts, protocol in persistence/worktree-refresh.ts); +6 fix wave 5 #5409: mirror-readonly/mirror-writable dispatch, help rows and the list --json mirror_read_only field (body in sources-mirror.ts); grown v0.46.22.0 phone wave: github source kind (#4104); +129 v0.47 gmail-loops: google source-kind flags + vault preflight + duplicate-account warn + access-mode validation; +8 set-path dispatch + help rows (#4739 — command body peeled to sources-set-path.ts); +29 #4698 adoption: --calendar-id flag + duplicate-account warn scoped to overlapping services; #5105: trusted writer administration route; company handlers and receipt status wiring; parsing stays in dedicated modules; canonical reconciliation: +5 engine-free sibling-command dispatch and help row, implementation remains in source-reconcile.ts; +4 fix wave 3 lane A: sources status connector recovery state and run counts (view lives in persistence/connector-status.ts); +3 fix wave 4 lane B: sources retry-held dispatch and help row (command body in sources-retry-held.ts) and the connector first-sync note on add; bodies in source-delete.ts and sources-set-path.ts); +4 #5984: sources status shows the managed sync backlog (logic in persistence/sync-drain.ts); v0.60.48.0 merge: #5984 growth re-summed over v0.60.47.0 (2031 measured); +11 W-B4: sources shared-skills dispatch, its --help guard and help rows, and the shared_skills field/lines in sources status (body in sources-shared-skills.ts, view in shared-skills/source-opt-out.ts)-src/core/link-extraction.ts 2320 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts+src/core/link-extraction.ts 2345 ratchet grown v0.46.26.0 megawave: link-aware timeline split + delimiter-outside-links (#3957 #4062 #3737); +37 wave-k #3908 reimpl: isCrossSourceLinksEnabled config ladder; +10 wave #4277: parseTimelineEntries skips generated backlink receipts; +17 #4855: latin-fold in normalizeBasename + dir-hint step tries both slug grammars; +17: #4855 Latin stroke-letter fold; +5: #4873 ./-relative markdown links kept as live references; +34 wave review: `../y.md` sibling links resolve on the DB path + folded bare-wikilink grammar (#4873 class); +62 #4977: role-prior suppression in machine-list sections (rolePriorSuppressedRanges, EntityRef.index); +3 composed with #4985 (variation-selector strip) in the same wave; +4 #4995: markdown-link anchor strip + lowercase-candidate rationale comments; +6 pre-landing review: #4977 suppression on code-stripped content + truthful watermark/section-list comments; T2: source-qualified inference and atomic origin-scoped derived links; canonical attendance evidence, source-qualified orientation, strict attendee resolution, and relocated filesystem link scanner (command export preserved); +4: pack-owned fallback and ambiguous attendee guards Display-label attendance exclusion, indexed evidence membership, and bounded strict resolver caching; attendance-boundary review.; complete attendance resolution and fence-safe evidence traversal; frontmatter discovery, canonical basename admission and code-aware attendance comment masking; exclude inline HTML comment spans from admitted attendance ranges; +17 write-path wave: same-name rule for entity fuzzy matches + rename-alias fallback in makeResolver; +1 #5567: materialized marker ends bullet detail; +30 #5749: unique global-basename step before fuzzy and live keyword resolution (ResolveOptions, watermark note); #5765: bold **Attendees:** label accepted + LINK_EXTRACTOR_VERSION_TS bump note; +10 eval-wave N9-2/N9-3/N12-7: pack frontmatter mappings inherit FRONTMATTER_LINK_MAP direction, page-type-bound pack attended follows canonical attendance, LINK_EXTRACTOR_VERSION_TS bump note; +1 #5623: normalizeBasename collapses hyphen runs like slugifySegment (extractor watermark note); +11 #5562: parseTimelineEntries accepts dated ### headings (FS-extractor parity); +3 eval-wave N12-6: Participants accepted as attendance evidence + LINK_EXTRACTOR_VERSION_TS bump note; +22 P5 wanted pages: AuthoredRef on body link candidates; -33 lowered: P5 moved machine-section ranges to core/machine-sections.ts and stated relation types to core/line-grammar.ts; +7 P5: ExtractPageLinksOptions interface + wikilinkAuthoredRef helper (keeps extractPageLinks under the function-size limit); +32 P5: per-edge verb attachment (attachedVerb, VERB_RULES) + joined-as works_at + extractor watermark note; P5 x temporal-edges merge: verb attachment reads the verb at the link's own position in the window (excerptAnchor) and the within-page dedup (now dedupeCandidates) drops a mention of a target the page also links with a typed edge; links joined only by commas/conjunctions share the verb before the first (coordinated); board roles (BOARD_RE, BOARD_AFTER_RE) resolve to invested_in for an investor page and advises otherwise, never works_at; +109 Q2 Track C: stable verb-rule ids, traceLinkType/explainLinkType (reasons for every typing decision), per-occurrence typer hoisted out of extractPageLinks (makeTypeFor); unit logic lives in core/link-typing-units.ts; +25 Q2 Track C: typing-unit verb rules and vetoes in attachedVerb/traceLinkType, validity stints in explainLinkTypesrc/core/embedding-migration.ts 1569 ratchet new row: crossed 1500 in v0.46.25.0 fix waves (#4305 #4306 chunk-model truth helpers); retired provider integration removed; safety wave: canonical projection readiness and fact-aware completion; file configuration publication retains lease-row locks; +8 transactional retained-vector rebuildability checks before destructive migration boundaries; archived eligibility: source-locked reconciliation and live/current smoke revalidation; +2 #5680: authorization_generation field and its carry-forward on same-target re-apply (settle idempotency); +10 #5226: plan carries chunks_to_restamp beside chunks_to_embed; +9 #5088: schema transition defers HNSW builds into the marker (deferred_ann_indexes), carry-forward on re-apply, verify blocks on pending/INVALID ANN indexes (build phase in embedding-ann-build.ts); +10 #5088: dim-pinned tables (query_cache, facts, and any later entry of TEXT_EMBEDDING_DIM_PINNED_TABLES) defer their HNSW through the same worklist (DEFERRED_ANN_TABLES, recordDeferredAnnIndexes); +25 wave 8 lane D1 #5885: takes in the dim-pinned column list, plan (takes_to_embed), status (takes_pending) and completion verifysrc/core/github-source.ts 1530 ratchet new row: crossed the 1500 unlisted cap in v0.46.23.0 review fix wave (scope-state gating, client hardening, symlink containment); merged reliability/shared-skills source integration; managed sweep lease wrapper; fix wave 3 lane A: config parser peeled to github-source-config.ts (-47), +account pin wiring and pinned-installation refreshsrc/commands/hook.ts 1915 ratchet cathedral-5 heartbeat extraction offsets part of the BrainBench-seam growth; grown v0.46.26.0 megawave hooks-ipc (#4245); +108 monthly backup check: banner + gated session-start note + detached spawn (backup/status-file readers); +28 ship-review egress hardening: per-harness capture dispatch (capture-spec), memorable gate + receipt + relay block, fail-closed unscanned/newest-guess skips; +79 ambient-writeback WP4: hookStop bank step (gate -> bankWritebackTurn -> IPC flush; gate/bank logic live in core/facts + corpus-segments); +41 adversarial fix wave: wide-tail retry when the 128KB window misses the user turn, by-design heartbeat outcome classes, source-in-name banking; +11 #5413 session-end skips claude-cli self-transcripts; +11 #5701: hook lanes pass allowOversize so a long session reaches the bounded tail read; +12 core memory: user-prompt context-pressure notice wiring (logic in core/context/pressure.ts; session-start composition in core/context/session-start-output.ts)diff --git a/src/core/link-extraction.ts b/src/core/link-extraction.tsindex eab021eaa6..840eb2f85f 100644--- a/src/core/link-extraction.ts+++ b/src/core/link-extraction.ts@@ -29,9 +29,9 @@ import { isIdentityEntity, sameEntityName } from './entities/resolve.ts';import type { SchemaPackManifest } from './schema-pack/manifest-v1.ts';import { inferLinkTypeFromPack, frontmatterLinkTypeFromPack, ownsAttendanceInference } from './schema-pack/link-inference.ts';import { PageRegexBudget } from './schema-pack/redos-guard.ts';-import type { TypingUnit } from './link-typing-units.ts';+import { UNIT_VERB_RULES, typingUnitEnabled, unitOfRule, unitVerbVeto, type TypingUnit } from './link-typing-units.ts';import { deriveTemporalEvidence, rowKey, type DerivedTransition } from './link-temporal-evidence.ts';-import type { AssertionTense } from './link-validity.ts';+import { buildRelationshipState, relationSemantics, type AssertionTense, type Stint } from './link-validity.ts';/*** #3190: the slice of a schema-pack manifest link extraction consumes.@@ -1274,8 +1274,8 @@ const EMPLOYEE_ROLE_RE = /\b(?:is an? (?:senior|staff|principal|lead|backend|fro/** A per-edge verb rule. `id` is stable: tests, explainLinkType and development reports name rules by it. */-interface VerbRule { id: string; re: RegExp; verb: string }-const VERB_RULES: ReadonlyArray<VerbRule> = [+interface VerbRule { id: string; re: RegExp; verb: string; unit?: TypingUnit }+const CORE_VERB_RULES: ReadonlyArray<VerbRule> = [{ id: 'verb.founded', re: FOUNDED_RE, verb: 'founded' },{ id: 'verb.invested_in', re: INVESTED_RE, verb: 'invested_in' },{ id: 'verb.advises', re: ADVISES_RE, verb: 'advises' },@@ -1286,6 +1286,9 @@ const VERB_RULES: ReadonlyArray<VerbRule> = [{ id: 'verb.zh.works_at', re: ZH_WORKS_AT_RE, verb: 'works_at' },{ id: 'verb.zh.cited', re: ZH_CITED_RE, verb: 'cited' },];+/** Core rules with each typing unit's rules right after the core rule they extend (skipped unless the unit is on). */+const VERB_RULES: ReadonlyArray<VerbRule> = CORE_VERB_RULES.flatMap(r => [r, ...UNIT_VERB_RULES.filter(u => u.after === r.id)]);+const ruleOn = (r: VerbRule) => !r.unit || typingUnitEnabled(r.unit);/*** The per-edge verb for one link when its context window holds several links.@@ -1317,6 +1320,7 @@ function attachedVerb(context: string, targetSlug?: string, anchor?: number, explet rule: VerbRule | null = null;let otherLink = false;for (const r of GLOBAL_VERB_RULES) {+ if (!ruleOn(r)) continue;for (const m of context.matchAll(r.re)) {const start = m.index ?? 0; const end = start + m[0].length;if ((end <= linkStart && LINK_MARK_RE.test(context.slice(end, linkStart)) && !coordinated(context.slice(end, linkStart)))@@ -1325,6 +1329,8 @@ function attachedVerb(context: string, targetSlug?: string, anchor?: number, expif (explain) suppressed.push(`${r.id}:other-link`);continue;}+ const veto = unitVerbVeto({ rule: r, context, start, end });+ if (veto) { suppressed.push(veto); continue; }if (rule) { suppressed.push(`${r.id}:outranked`); break; }rule = r;if (!explain) return { rule, suppressed, otherLink };@@ -1373,7 +1379,7 @@ export function inferLinkType(pageType: PageType, context: string, globalContext/** inferLinkType with its reasons. `pageText` is the whole page (role priors read `globalContext`, which timeline links do not get). */export function traceLinkType(pageType: PageType, context: string, globalContext?: string, targetSlug?: string, targetType?: string | null, anchor?: number, pageText?: string, explain = false): LinkTypeTrace {const out = (type: string, rule: string | null, attachment: LinkTypeTrace['attachment'] = 'none', suppressed: string[] = [], prior: string | null = null): LinkTypeTrace =>- ({ type, rule, attachment, suppressed, prior, unit: null });+ ({ type, rule, attachment, suppressed, prior, unit: unitOfRule(rule) ?? unitOfRule(suppressed.find(id => id.startsWith('unit.'))) });if (pageType === 'media') {return out('mentions', 'page.media');}@@ -1391,9 +1397,18 @@ export function traceLinkType(pageType: PageType, context: string, globalContext// "works at [A] and also advises [B]", A is works_at and B advises.const attached = attachedVerb(context, targetSlug, anchor, explain);if (attached?.rule) return out(attached.rule.verb, attached.rule.id, 'attached', attached.suppressed);- if (attached === undefined) for (const r of VERB_RULES) if (r.re.test(context)) return out(r.verb, r.id, 'window');- const attachment = attached?.otherLink ? 'other-links' : 'none';const suppressed = attached?.suppressed ?? [];+ if (attached === undefined) {+ for (const r of GLOBAL_VERB_RULES) {+ if (!ruleOn(r)) continue;+ for (const m of context.matchAll(r.re)) {+ const veto = unitVerbVeto({ rule: r, context, start: m.index ?? 0, end: (m.index ?? 0) + m[0].length });+ if (!veto) return out(r.verb, r.id, 'window', suppressed);+ suppressed.push(veto);+ }+ }+ }+ const attachment = attached?.otherLink ? 'other-links' : 'none';// Page-role prior: only fires for person -> company links. Concept pages// about VC topics naturally contain "venture capital" in their text, but// their company refs are mentions, not investments. Partner pages mentioning@@ -1421,6 +1436,8 @@ export interface LinkExplanation {tense: Record<string, AssertionTense>;/** Dated transitions for the kept types, each with the id of the cue that produced it. */transitions: Array<DerivedTransition & { rule: string }>;+ /** Validity stints per temporal type, from this page's tense and transitions alone (link-validity.ts buildRelationshipState). */+ stints: Record<string, Stint[]>;}/**@@ -1444,8 +1461,16 @@ export async function explainLinkType(input: {candidates.map(c => ({ from_slug: c.fromSlug ?? input.slug, to_slug: c.targetSlug, link_type: c.linkType, link_source: c.linkSource ?? 'markdown', origin_field: c.originField ?? null })),(t, rule) => { if (t.to_slug === input.target || t.from_slug === input.target) transitions.push({ ...t, rule }); });const tense: Record<string, AssertionTense> = {};- for (const t of types) { const v = evidence.tense.get(rowKey({ from_slug: input.slug, to_slug: input.target, link_type: t })); if (v) tense[t] = v; }- return { target: input.target, occurrences, types, tense, transitions };+ const stints: Record<string, Stint[]> = {};+ for (const t of types) {+ const v = evidence.tense.get(rowKey({ from_slug: input.slug, to_slug: input.target, link_type: t }));+ if (v) tense[t] = v;+ const semantics = relationSemantics(t);+ if (semantics === 'reference') continue;+ stints[t] = buildRelationshipState(semantics, v ? [{ tense: v, originPageId: 1 }] : [],+ transitions.filter(x => x.link_type === t).map(x => ({ kind: x.kind, occurredOn: x.occurred_on, producer: x.producer, originPageId: 1 }))).stints;+ }+ return { target: input.target, occurrences, types, tense, transitions, stints };}// ─── Frontmatter link extraction (v0.13) ────────────────────────diff --git a/src/core/link-typing-units.ts b/src/core/link-typing-units.tsindex 69854e8fa8..c909a42ace 100644--- a/src/core/link-typing-units.ts+++ b/src/core/link-typing-units.ts@@ -55,3 +55,44 @@ export async function withTypingUnits<T>(units: Iterable<string>, fn: () => T |override = previous;}}++// ─── Typing hooks (link-extraction.ts) ──────────────────────────────────++/** A verb rule a unit adds. `id` is stable (`unit.u<N>.*`); it sits right after the core rule for the same verb. */+export interface UnitVerbRule { id: string; re: RegExp; verb: string; unit: TypingUnit; after: string }++export const UNIT_VERB_RULES: readonly UnitVerbRule[] = [+];++/** The clause before `index`: back to a sentence, clause or timeline-entry break (at most 100 chars). */+export function clauseBefore(text: string, index: number): string {+ const w = text.slice(Math.max(0, index - 100), index);+ const cut = Math.max(...['. ', '; ', '! ', '? ', '\n', ' | ', ' — ', ' - **'].map(b => { const i = w.lastIndexOf(b); return i < 0 ? -1 : i + b.length; }));+ return cut >= 0 ? w.slice(cut) : w;+}++/** Someone other than the page's subject holds the role ("her husband is …", "a friend who …"). */+const THIRD_PARTY = /\b(?:husband|wife|spouse|boyfriend|girlfriend|fianc[eé]e?|brother|sister|mother|father|mom|dad|son|daughter|parent|friend|colleague|co-?worker|manager|boss|mentor|mentee|roommate|neighbou?r|cousin|uncle|aunt|classmate|former\s+colleague|whose|who|someone|somebody)\b/i;+export const thirdPartyBefore = (text: string, index: number) => THIRD_PARTY.test(clauseBefore(text, index));++export interface VetoInput {+ rule: { id: string; verb: string };+ context: string;+ /** Match offsets in `context`. */+ start: number;+ end: number;+}++/**+ * A unit's veto of one verb match, or null. A vetoed match does not decide the type; inference moves on to the next+ * match or rule. Returns the stable id of the veto (`unit.u<N>.*`).+ */+export function unitVerbVeto(v: VetoInput): string | null {+ return null;+}++/** The unit a rule or veto id belongs to (`unit.u3.board_wording` → U3). */+export function unitOfRule(id: string | null | undefined): TypingUnit | null {+ const m = /^unit\.u(\d)\./.exec(id ?? '');+ return m ? (`U${m[1]}` as TypingUnit) : null;+}diff --git a/test/helpers/typing-unit-examples.ts b/test/helpers/typing-unit-examples.tsnew file mode 100644index 0000000000..1503c201f7--- /dev/null+++ b/test/helpers/typing-unit-examples.ts@@ -0,0 +1,62 @@+/**+ * Frozen per-example expectations for the relationship-phrasing typing units (src/core/link-typing-units.ts).+ *+ * Each example states the type set, tense, dated transitions and live/as-of result explainLinkType must give with+ * its unit off (`off`, master behavior) and on (`on`). `on` may depend on the other units in the set (joint effects).+ * Controls (negation, third party, concurrent roles, rejoins, repeated targets, window truncation, event look-alikes)+ * are examples whose `on` equals `off` or whose unit is null. Development text only; names are placeholders.+ */+import { explainLinkType } from '../../src/core/link-extraction.ts';+import { stintCovers } from '../../src/core/link-validity.ts';+import type { TypingUnit } from '../../src/core/link-typing-units.ts';++export interface Expectation {+ /** Distinct types the page emits for the target (sorted; `mentions` rows included). */+ types: string[];+ /** Tense per temporal type, when asserted. */+ tense?: Record<string, 'past' | 'present'>;+ /** Dated transitions for the target: `${type} ${kind} ${date}`, in order. */+ transitions?: string[];+ /** Whether `type` is valid on each date (as-of), with 'today' = 2026-10-06. */+ live?: { type: string; at: Record<string, boolean> };+}++export interface TypingExample {+ id: string;+ /** The unit this example measures, or null for a control that no unit may change. */+ unit: TypingUnit | null;+ target: string;+ content: string;+ pageType?: 'person' | 'company' | 'concept';+ off: Expectation;+ on?: Expectation | ((units: ReadonlySet<TypingUnit>) => Expectation);+}++export const ACME = 'companies/acme-example';+export const BETA = 'companies/beta-example';+export const GLOBEX = 'companies/globex-example';+export const SLUG = 'people/alice-example';+export const L = (slug: string) => `[${slug.split('/')[1]!.replace(/-example$/, '').replace(/^\w/, c => c.toUpperCase())}](../${slug}.md)`;+export const page = (prose: string, timeline: string[] = []) =>+ timeline.length ? `${prose}\n\n## Timeline\n\n${timeline.map(l => `- ${l}`).join('\n')}\n` : `${prose}\n`;++export function expected(ex: TypingExample, units: ReadonlySet<TypingUnit>): Expectation {+ if (!ex.unit || !ex.on || !units.has(ex.unit)) return ex.off;+ return typeof ex.on === 'function' ? ex.on(units) : ex.on;+}++/** What explainLinkType actually gives, in the Expectation shape (only the fields `want` asks for). */+export async function observe(ex: TypingExample, want: Expectation): Promise<Expectation> {+ const e = await explainLinkType({ slug: SLUG, content: ex.content, pageType: ex.pageType ?? 'person', target: ex.target });+ const got: Expectation = { types: e.types };+ if (want.tense) got.tense = e.tense;+ if (want.transitions) got.transitions = e.transitions.map(t => `${t.link_type} ${t.kind} ${t.occurred_on}`);+ if (want.live) {+ const stints = e.stints[want.live.type] ?? [];+ got.live = { type: want.live.type, at: Object.fromEntries(Object.keys(want.live.at).map(d =>+ [d, stints.some(s => stintCovers(s, d === 'today' ? '2026-10-06' : d))])) };+ }+ return got;+}++export const EXAMPLES: TypingExample[] = [];diff --git a/test/link-typing-units.test.ts b/test/link-typing-units.test.tsnew file mode 100644index 0000000000..f3ede5227a--- /dev/null+++ b/test/link-typing-units.test.ts@@ -0,0 +1,37 @@+/**+ * Typing units (src/core/link-typing-units.ts): each example's frozen type, tense, transitions and as-of result with+ * no unit, with only its own unit, and with every unit (test/helpers/typing-unit-examples.ts).+ */+import { describe, expect, test } from 'bun:test';+import { TYPING_UNITS, ENABLED_TYPING_UNITS, activeTypingUnits, parseTypingUnits, withTypingUnits, type TypingUnit } from '../src/core/link-typing-units.ts';+import { EXAMPLES, expected, observe } from './helpers/typing-unit-examples.ts';++const sets: Array<[string, TypingUnit[]]> = [['none', []], ...TYPING_UNITS.map(u => [u, [u]] as [string, TypingUnit[]]), ['all', [...TYPING_UNITS]]];++describe('typing units: frozen examples', () => {+ for (const [label, units] of sets) {+ test(`unit set ${label}`, async () => {+ await withTypingUnits(units, async () => {+ for (const ex of EXAMPLES) {+ const want = expected(ex, new Set(units));+ expect({ id: ex.id, ...(await observe(ex, want)) }).toEqual({ id: ex.id, ...want });+ }+ });+ });+ }+});++describe('typing unit switch', () => {+ test('the build ships with no unit enabled until the verdict', () => {+ expect([...ENABLED_TYPING_UNITS]).toEqual([]);+ expect(activeTypingUnits()).toEqual([]);+ });+ test('withTypingUnits restores the previous set', async () => {+ await withTypingUnits(['U2', 'U1'], () => expect(activeTypingUnits()).toEqual(['U1', 'U2']));+ expect(activeTypingUnits()).toEqual([]);+ });+ test('unknown unit ids are refused with the list of units', () => {+ expect(() => parseTypingUnits(['U7'])).toThrow(/Unknown typing unit "U7". The units are U1, U2, U3, U4, U5, U6/);+ expect(parseTypingUnits(['u2', ' U1 ', 'U2'])).toEqual(['U2', 'U1']);+ });+});