From fd507e5efedb843628ba447159af1592b9da2aac Mon Sep 17 00:00:00 2001 From: caelum0x Date: Tue, 25 Aug 2026 12:29:47 +0300 Subject: [PATCH] feat(graph): typed talent-graph ontology + edge validation & extraction MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Promote the talent graph's implicit structure to an explicit schema and add the single guardrail that removes hallucinated structure: validate every candidate edge against its edge type's domain/range and reject type-incompatible ones. - talentGraphOntology.ts: node types (developer, repo, org, skill, contribution) and edge types (contributed_to, member_of, has_skill, collaborated_with) with domain/range, symmetry and reflexivity rules. validateEdge / validateEdges vet untrusted edges, require provenance (source, observedAt, confidence) on every fact, dedup symmetric edges, and return typed rejection reasons. Pure, no I/O. - talentGraphEdges.ts: extraction step — turns getTalentGraph's view into provenanced candidate edges, reusing canonicalizeSkill and the evidence source union aligned with TalentEvidence.kind. - tests: 15 unit tests covering domain/range rejection, provenance validation, symmetric dedup, and extract-then-validate soundness. --- .../backend/src/services/talentGraphEdges.ts | 133 ++++++++ .../src/services/talentGraphOntology.ts | 291 ++++++++++++++++++ .../tests/unit/talentGraphOntology.test.ts | 227 ++++++++++++++ 3 files changed, 651 insertions(+) create mode 100644 gitgram/backend/src/services/talentGraphEdges.ts create mode 100644 gitgram/backend/src/services/talentGraphOntology.ts create mode 100644 gitgram/backend/tests/unit/talentGraphOntology.test.ts diff --git a/gitgram/backend/src/services/talentGraphEdges.ts b/gitgram/backend/src/services/talentGraphEdges.ts new file mode 100644 index 00000000..0dbb029b --- /dev/null +++ b/gitgram/backend/src/services/talentGraphEdges.ts @@ -0,0 +1,133 @@ +/** + * Edge extraction from the assembled talent graph. + * + * `getTalentGraph` (talentGraphService.ts) already assembles a developer's + * projects, collaborators and evidence on read, but returns them as nested view + * objects — not as typed, provenanced edges. This module is the extraction step + * of the graph pipeline: it turns that view into flat candidate edges + * (`TalentEdgeInput`) which the ontology's `validateEdges` then vets against + * domain/range before anything is persisted. Extract → validate → serve. + * + * It REUSES rather than rebuilds: + * - the shapes produced by `getTalentGraph` (structural subset below), + * - `canonicalizeSkill` from skillTaxonomyService for skill-node identity, + * - the ontology's `EvidenceSource` union, aligned with `TalentEvidence.kind`. + * + * Pure and dependency-light: takes an already-fetched graph view, does no I/O. + */ +import { canonicalizeSkill } from './skillTaxonomyService'; +import { EVIDENCE_SOURCES, type EvidenceSource, type TalentEdgeInput } from './talentGraphOntology'; + +type EvidenceLevel = 'verified' | 'linked' | 'recorded'; + +/** Confidence for an edge derived from a project at a given verification tier. */ +const CONFIDENCE_BY_LEVEL: Readonly> = { + verified: 1, + linked: 0.75, + recorded: 0.5, +}; + +const SOURCE_SET: ReadonlySet = new Set(EVIDENCE_SOURCES); + +/** Structural subset of one project as returned by `getTalentGraph`. */ +export interface GraphProjectView { + readonly id: string; + readonly url: string | null; + readonly topics: readonly string[]; + readonly verificationLevel: EvidenceLevel; + readonly lastVerifiedAt: Date; + readonly evidence: readonly { readonly kind: string; readonly sourceUrl: string | null }[]; +} + +/** Structural subset of one collaborator as returned by `getTalentGraph`. */ +export interface GraphCollaboratorView { + readonly id: string; + readonly sharedProjects: readonly { readonly id: string; readonly url: string }[]; +} + +/** Structural subset of the whole graph view `deriveTalentEdges` consumes. */ +export interface TalentGraphView { + readonly profile: { readonly id: string }; + readonly projects: readonly GraphProjectView[]; + readonly collaborators: readonly GraphCollaboratorView[]; +} + +/** + * Pick the provenance source for a project-derived edge from its strongest + * evidence record, falling back to `project_record` when the evidence carries no + * recognized kind. Keeps edge provenance traceable to the same evidence the + * dossier shows the user. + */ +function projectSource(project: GraphProjectView): EvidenceSource { + const known = project.evidence.find((item) => SOURCE_SET.has(item.kind)); + return (known?.kind as EvidenceSource) ?? 'project_record'; +} + +/** + * Extract candidate edges from a talent graph view. The output is intentionally + * untrusted `TalentEdgeInput[]`: run it through `validateEdges` to get the vetted, + * de-duplicated edge set. Emits three relation families: + * - developer —contributed_to→ repo (one per project) + * - developer —has_skill→ skill (one per canonicalized project topic) + * - developer —collaborated_with→ developer (one per collaborator, symmetric) + */ +export function deriveTalentEdges(graph: TalentGraphView): TalentEdgeInput[] { + const developerId = graph.profile.id; + const edges: TalentEdgeInput[] = []; + if (!developerId) return edges; + + for (const project of graph.projects) { + const source = projectSource(project); + const confidence = CONFIDENCE_BY_LEVEL[project.verificationLevel]; + + edges.push({ + type: 'contributed_to', + from: { id: developerId, type: 'developer' }, + to: { id: project.id, type: 'repo' }, + provenance: { + source, + observedAt: project.lastVerifiedAt, + confidence, + sourceUrl: project.url, + }, + }); + + const seenSkills = new Set(); + for (const topic of project.topics) { + const skill = canonicalizeSkill(topic); + if (!skill || seenSkills.has(skill)) continue; + seenSkills.add(skill); + edges.push({ + type: 'has_skill', + from: { id: developerId, type: 'developer' }, + to: { id: skill, type: 'skill' }, + provenance: { + source, + observedAt: project.lastVerifiedAt, + // A skill inferred from a repo topic is weaker than the contribution + // itself; cap it at the "recorded" tier. + confidence: Math.min(confidence, CONFIDENCE_BY_LEVEL.recorded), + sourceUrl: project.url, + }, + }); + } + } + + for (const collaborator of graph.collaborators) { + if (!collaborator.id || collaborator.id === developerId) continue; + const shared = collaborator.sharedProjects[0]; + edges.push({ + type: 'collaborated_with', + from: { id: developerId, type: 'developer' }, + to: { id: collaborator.id, type: 'developer' }, + provenance: { + source: 'github_sync', + observedAt: new Date(), + confidence: CONFIDENCE_BY_LEVEL.recorded, + sourceUrl: shared?.url ?? null, + }, + }); + } + + return edges; +} diff --git a/gitgram/backend/src/services/talentGraphOntology.ts b/gitgram/backend/src/services/talentGraphOntology.ts new file mode 100644 index 00000000..a2a82b7f --- /dev/null +++ b/gitgram/backend/src/services/talentGraphOntology.ts @@ -0,0 +1,291 @@ +/** + * Talent-graph ontology + edge validation. + * + * A graph is a PRODUCT WITH A SCHEMA, not a pile of triples. Before this rung the + * talent graph was assembled implicitly inside `getTalentGraph` — projects, + * collaborators and skills were derived on read, but no typed contract said which + * relationships are *legal*. This module promotes that implicit structure to an + * explicit ontology and adds the single guardrail that removes hallucinated + * structure: every candidate edge is validated against its edge type's + * domain/range, and type-incompatible edges are rejected with a reason. + * + * Entities (node types): developer, repo, org, skill, contribution. + * Relations (edge types): contributed_to, member_of, has_skill, collaborated_with. + * + * Discipline applied here (not recited): + * - Model types BEFORE writing edges (TALENT_ONTOLOGY below). + * - Provenance on EVERY fact: source, observedAt, confidence, sourceUrl. + * - Validate edges against domain/range; reject type-incompatible ones. + * - Incremental & pure: no Prisma, no I/O — unit-testable in isolation, mirroring + * skillTaxonomyService / talentGapAnalysisService. + * + * The evidence `source` union is deliberately aligned with the `kind` field of + * `TalentEvidence` in talentGraphService.ts (plus `profile_interest`) so edges + * derived from that service carry provenance the rest of the graph already speaks. + */ + +export const TALENT_NODE_TYPES = ['developer', 'repo', 'org', 'skill', 'contribution'] as const; +export type TalentNodeType = (typeof TALENT_NODE_TYPES)[number]; + +export const TALENT_EDGE_TYPES = ['contributed_to', 'member_of', 'has_skill', 'collaborated_with'] as const; +export type TalentEdgeType = (typeof TALENT_EDGE_TYPES)[number]; + +/** + * Provenance sources. Kept in lock-step with `TalentEvidence['kind']` in + * talentGraphService.ts, extended with `profile_interest` for the weakest signal + * (a self-declared interest with no repository/pilot evidence behind it). + */ +export const EVIDENCE_SOURCES = [ + 'repository_claim', + 'github_sync', + 'github_activity', + 'project_record', + 'institutional_pilot', + 'profile_interest', +] as const; +export type EvidenceSource = (typeof EVIDENCE_SOURCES)[number]; + +/** + * Domain/range contract for one edge type. `domain` is the set of legal source + * node types, `range` the set of legal target node types. `symmetric` marks + * undirected relations (collaborated_with) so A→B and B→A collapse to one edge. + * `reflexiveAllowed` guards self-loops (a developer cannot collaborate with self). + */ +export interface EdgeTypeDefinition { + readonly type: TalentEdgeType; + readonly domain: readonly TalentNodeType[]; + readonly range: readonly TalentNodeType[]; + readonly symmetric: boolean; + readonly reflexiveAllowed: boolean; +} + +export const TALENT_ONTOLOGY: Readonly> = { + contributed_to: { + type: 'contributed_to', + domain: ['developer'], + range: ['repo'], + symmetric: false, + reflexiveAllowed: false, + }, + member_of: { + type: 'member_of', + domain: ['developer'], + range: ['org'], + symmetric: false, + reflexiveAllowed: false, + }, + has_skill: { + type: 'has_skill', + domain: ['developer'], + range: ['skill'], + symmetric: false, + reflexiveAllowed: false, + }, + collaborated_with: { + type: 'collaborated_with', + domain: ['developer'], + range: ['developer'], + symmetric: true, + reflexiveAllowed: false, + }, +}; + +export interface NodeRef { + readonly id: string; + readonly type: TalentNodeType; +} + +export interface EdgeProvenance { + readonly source: EvidenceSource; + readonly observedAt: Date; + /** Confidence in (0, 1]. Verified evidence is 1; weaker signals score lower. */ + readonly confidence: number; + readonly sourceUrl: string | null; +} + +/** An accepted, well-typed edge. `key` is its canonical dedup identity. */ +export interface TalentEdge { + readonly type: TalentEdgeType; + readonly from: NodeRef; + readonly to: NodeRef; + readonly provenance: EdgeProvenance; + readonly key: string; +} + +/** + * Untrusted edge input, exactly as it might arrive from an extractor, a GitHub + * sync, or an LLM. Every field is loosely typed on purpose — validation is what + * narrows it. Never trust external data. + */ +export interface TalentEdgeInput { + readonly type: string; + readonly from: { readonly id: string; readonly type: string }; + readonly to: { readonly id: string; readonly type: string }; + readonly provenance: { + readonly source: string; + readonly observedAt: Date | string | number; + readonly confidence: number; + readonly sourceUrl?: string | null; + }; +} + +export type EdgeRejectionCode = + | 'unknown_edge_type' + | 'missing_from_id' + | 'missing_to_id' + | 'unknown_from_type' + | 'unknown_to_type' + | 'domain_violation' + | 'range_violation' + | 'self_reference' + | 'unknown_source' + | 'invalid_confidence' + | 'invalid_observed_at'; + +export interface EdgeRejection { + readonly code: EdgeRejectionCode; + readonly message: string; +} + +export type EdgeValidation = + | { readonly valid: true; readonly edge: TalentEdge } + | { readonly valid: false; readonly rejections: readonly EdgeRejection[] }; + +export interface EdgeBatchResult { + readonly accepted: readonly TalentEdge[]; + readonly rejected: readonly { readonly input: TalentEdgeInput; readonly rejections: readonly EdgeRejection[] }[]; +} + +const NODE_TYPE_SET: ReadonlySet = new Set(TALENT_NODE_TYPES); +const SOURCE_SET: ReadonlySet = new Set(EVIDENCE_SOURCES); + +function isTalentEdgeType(value: string): value is TalentEdgeType { + return Object.prototype.hasOwnProperty.call(TALENT_ONTOLOGY, value); +} + +function coerceDate(value: Date | string | number): Date | null { + const date = value instanceof Date ? value : new Date(value); + return Number.isNaN(date.getTime()) ? null : date; +} + +/** + * Canonical identity of an edge. For symmetric edge types the two endpoints are + * sorted so that A—B and B—A share one key; for directed edges the order is kept. + */ +export function edgeKey(type: TalentEdgeType, from: NodeRef, to: NodeRef): string { + const left = `${from.type}:${from.id}`; + const right = `${to.type}:${to.id}`; + const [a, b] = TALENT_ONTOLOGY[type].symmetric && right < left ? [right, left] : [left, right]; + return `${type}|${a}|${b}`; +} + +/** + * Validate a single untrusted edge against the ontology. Returns the normalized, + * accepted edge, or ALL the reasons it was rejected (validation is comprehensive + * rather than fail-fast so callers can surface every problem at once). + */ +export function validateEdge(input: TalentEdgeInput): EdgeValidation { + const rejections: EdgeRejection[] = []; + + const type = typeof input.type === 'string' ? input.type.trim() : ''; + const fromId = typeof input.from?.id === 'string' ? input.from.id.trim() : ''; + const toId = typeof input.to?.id === 'string' ? input.to.id.trim() : ''; + const fromType = typeof input.from?.type === 'string' ? input.from.type.trim() : ''; + const toType = typeof input.to?.type === 'string' ? input.to.type.trim() : ''; + + if (!isTalentEdgeType(type)) { + rejections.push({ code: 'unknown_edge_type', message: `Unknown edge type "${input.type}"` }); + } + if (!fromId) rejections.push({ code: 'missing_from_id', message: 'Edge is missing a source node id' }); + if (!toId) rejections.push({ code: 'missing_to_id', message: 'Edge is missing a target node id' }); + if (!NODE_TYPE_SET.has(fromType)) { + rejections.push({ code: 'unknown_from_type', message: `Unknown source node type "${fromType}"` }); + } + if (!NODE_TYPE_SET.has(toType)) { + rejections.push({ code: 'unknown_to_type', message: `Unknown target node type "${toType}"` }); + } + + // Domain/range only make sense once the edge type is known. + if (isTalentEdgeType(type)) { + const def = TALENT_ONTOLOGY[type]; + if (NODE_TYPE_SET.has(fromType) && !def.domain.includes(fromType as TalentNodeType)) { + rejections.push({ + code: 'domain_violation', + message: `${type} requires a source of type [${def.domain.join(', ')}], got "${fromType}"`, + }); + } + if (NODE_TYPE_SET.has(toType) && !def.range.includes(toType as TalentNodeType)) { + rejections.push({ + code: 'range_violation', + message: `${type} requires a target of type [${def.range.join(', ')}], got "${toType}"`, + }); + } + if (!def.reflexiveAllowed && fromId && toId && fromType === toType && fromId === toId) { + rejections.push({ + code: 'self_reference', + message: `${type} cannot connect a node to itself (${fromType}:${fromId})`, + }); + } + } + + const source = typeof input.provenance?.source === 'string' ? input.provenance.source.trim() : ''; + if (!SOURCE_SET.has(source)) { + rejections.push({ code: 'unknown_source', message: `Unknown provenance source "${source}"` }); + } + const confidence = input.provenance?.confidence; + if (typeof confidence !== 'number' || !Number.isFinite(confidence) || confidence <= 0 || confidence > 1) { + rejections.push({ code: 'invalid_confidence', message: 'Provenance confidence must be a number in (0, 1]' }); + } + const observedAt = input.provenance?.observedAt === undefined ? null : coerceDate(input.provenance.observedAt); + if (!observedAt) { + rejections.push({ code: 'invalid_observed_at', message: 'Provenance observedAt must be a valid date' }); + } + + if (rejections.length > 0) return { valid: false, rejections }; + + const edgeType = type as TalentEdgeType; + const from: NodeRef = { id: fromId, type: fromType as TalentNodeType }; + const to: NodeRef = { id: toId, type: toType as TalentNodeType }; + const provenance: EdgeProvenance = { + source: source as EvidenceSource, + observedAt: observedAt as Date, + confidence: confidence as number, + sourceUrl: input.provenance.sourceUrl ?? null, + }; + + return { + valid: true, + edge: { type: edgeType, from, to, provenance, key: edgeKey(edgeType, from, to) }, + }; +} + +/** + * Validate a batch of untrusted edges, partitioning into accepted and rejected. + * Accepted edges are de-duplicated by canonical `key` (first writer wins); when a + * duplicate carries higher confidence the stronger provenance is kept. + * + * This is the "single validation step that removes hallucinated structure": feed + * it raw extraction output, persist only `accepted`, and inspect `rejected` to + * see exactly which type-incompatible triples were dropped and why. + */ +export function validateEdges(inputs: readonly TalentEdgeInput[]): EdgeBatchResult { + const acceptedByKey = new Map(); + const rejected: EdgeBatchResult['rejected'] = []; + + for (const input of inputs) { + const result = validateEdge(input); + if (!result.valid) { + (rejected as { input: TalentEdgeInput; rejections: readonly EdgeRejection[] }[]).push({ + input, + rejections: result.rejections, + }); + continue; + } + const existing = acceptedByKey.get(result.edge.key); + if (!existing || result.edge.provenance.confidence > existing.provenance.confidence) { + acceptedByKey.set(result.edge.key, result.edge); + } + } + + return { accepted: Array.from(acceptedByKey.values()), rejected }; +} diff --git a/gitgram/backend/tests/unit/talentGraphOntology.test.ts b/gitgram/backend/tests/unit/talentGraphOntology.test.ts new file mode 100644 index 00000000..874c14bf --- /dev/null +++ b/gitgram/backend/tests/unit/talentGraphOntology.test.ts @@ -0,0 +1,227 @@ +/** + * Unit tests for the talent-graph ontology + edge validation and extraction. + * + * These are pure (no Prisma, no I/O), mirroring skillTaxonomyService / + * talentGapAnalysisService tests. They pin the load-bearing behavior of this + * rung: edges are validated against the ontology's domain/range so + * type-incompatible ("hallucinated") structure is rejected, provenance is + * required on every fact, symmetric edges de-duplicate, and edges extracted from + * a graph view all pass validation. + */ +import { + validateEdge, + validateEdges, + edgeKey, + TALENT_ONTOLOGY, + type TalentEdgeInput, +} from '../../src/services/talentGraphOntology'; +import { deriveTalentEdges, type TalentGraphView } from '../../src/services/talentGraphEdges'; + +function makeInput(overrides: Partial = {}): TalentEdgeInput { + return { + type: 'contributed_to', + from: { id: 'dev-1', type: 'developer' }, + to: { id: 'repo-1', type: 'repo' }, + provenance: { + source: 'repository_claim', + observedAt: new Date('2026-01-01T00:00:00Z'), + confidence: 1, + sourceUrl: 'https://github.com/acme/repo-1', + }, + ...overrides, + }; +} + +describe('validateEdge', () => { + it('accepts a well-typed developer→repo contribution and normalizes it', () => { + const result = validateEdge(makeInput()); + expect(result.valid).toBe(true); + if (!result.valid) return; + expect(result.edge.type).toBe('contributed_to'); + expect(result.edge.from).toEqual({ id: 'dev-1', type: 'developer' }); + expect(result.edge.to).toEqual({ id: 'repo-1', type: 'repo' }); + expect(result.edge.provenance.confidence).toBe(1); + expect(result.edge.provenance.observedAt).toBeInstanceOf(Date); + expect(result.edge.key).toBe('contributed_to|developer:dev-1|repo:repo-1'); + }); + + it('rejects an unknown edge type', () => { + const result = validateEdge(makeInput({ type: 'founded' })); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('unknown_edge_type'); + }); + + it('rejects a domain violation (repo cannot be the source of contributed_to)', () => { + const result = validateEdge( + makeInput({ from: { id: 'repo-1', type: 'repo' }, to: { id: 'repo-2', type: 'repo' } }), + ); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('domain_violation'); + }); + + it('rejects a range violation (has_skill must target a skill, not a repo)', () => { + const result = validateEdge( + makeInput({ type: 'has_skill', to: { id: 'repo-1', type: 'repo' } }), + ); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('range_violation'); + }); + + it('rejects an unknown node type', () => { + const result = validateEdge( + makeInput({ type: 'member_of', to: { id: 'x', type: 'company' } }), + ); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('unknown_to_type'); + }); + + it('rejects a self-referential collaborated_with edge', () => { + const result = validateEdge( + makeInput({ + type: 'collaborated_with', + from: { id: 'dev-1', type: 'developer' }, + to: { id: 'dev-1', type: 'developer' }, + }), + ); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('self_reference'); + }); + + it('rejects missing endpoint ids', () => { + const result = validateEdge(makeInput({ from: { id: ' ', type: 'developer' } })); + expect(result.valid).toBe(false); + if (result.valid) return; + expect(result.rejections.map((r) => r.code)).toContain('missing_from_id'); + }); + + it('rejects out-of-range and non-finite confidence', () => { + for (const confidence of [0, 1.5, -0.2, Number.NaN]) { + const result = validateEdge( + makeInput({ provenance: { source: 'github_sync', observedAt: new Date(), confidence, sourceUrl: null } }), + ); + expect(result.valid).toBe(false); + if (result.valid) continue; + expect(result.rejections.map((r) => r.code)).toContain('invalid_confidence'); + } + }); + + it('rejects an unknown provenance source and an invalid date together', () => { + const result = validateEdge( + makeInput({ provenance: { source: 'psychic_intuition', observedAt: 'not-a-date', confidence: 0.5 } }), + ); + expect(result.valid).toBe(false); + if (result.valid) return; + const codes = result.rejections.map((r) => r.code); + expect(codes).toContain('unknown_source'); + expect(codes).toContain('invalid_observed_at'); + }); + + it('coerces an ISO-string observedAt into a Date', () => { + const result = validateEdge( + makeInput({ provenance: { source: 'github_activity', observedAt: '2026-02-01T12:00:00Z', confidence: 0.75, sourceUrl: null } }), + ); + expect(result.valid).toBe(true); + if (!result.valid) return; + expect(result.edge.provenance.observedAt.toISOString()).toBe('2026-02-01T12:00:00.000Z'); + }); +}); + +describe('edgeKey', () => { + it('is order-independent for symmetric edges and directed for others', () => { + const a = { id: 'dev-a', type: 'developer' as const }; + const b = { id: 'dev-b', type: 'developer' as const }; + expect(edgeKey('collaborated_with', a, b)).toBe(edgeKey('collaborated_with', b, a)); + + const dev = { id: 'dev-a', type: 'developer' as const }; + const repo = { id: 'repo-1', type: 'repo' as const }; + expect(edgeKey('contributed_to', dev, repo)).not.toBe(edgeKey('contributed_to', repo as never, dev as never)); + }); + + it('every ontology edge type has a coherent domain/range', () => { + for (const def of Object.values(TALENT_ONTOLOGY)) { + expect(def.domain.length).toBeGreaterThan(0); + expect(def.range.length).toBeGreaterThan(0); + } + }); +}); + +describe('validateEdges (batch)', () => { + it('partitions accepted from rejected and dedups symmetric edges keeping strongest confidence', () => { + const inputs: TalentEdgeInput[] = [ + makeInput(), + // duplicate symmetric collaboration in both directions, second stronger + makeInput({ + type: 'collaborated_with', + from: { id: 'dev-1', type: 'developer' }, + to: { id: 'dev-2', type: 'developer' }, + provenance: { source: 'github_sync', observedAt: new Date(), confidence: 0.5, sourceUrl: null }, + }), + makeInput({ + type: 'collaborated_with', + from: { id: 'dev-2', type: 'developer' }, + to: { id: 'dev-1', type: 'developer' }, + provenance: { source: 'github_sync', observedAt: new Date(), confidence: 0.9, sourceUrl: null }, + }), + // hallucinated / type-incompatible: a skill cannot contribute to a repo + makeInput({ from: { id: 'skill-x', type: 'skill' } }), + ]; + + const { accepted, rejected } = validateEdges(inputs); + + // one contribution + one deduped collaboration + expect(accepted).toHaveLength(2); + const collab = accepted.find((e) => e.type === 'collaborated_with'); + expect(collab?.provenance.confidence).toBe(0.9); + + expect(rejected).toHaveLength(1); + expect(rejected[0].rejections.map((r) => r.code)).toContain('domain_violation'); + }); +}); + +describe('deriveTalentEdges', () => { + const view: TalentGraphView = { + profile: { id: 'dev-1' }, + projects: [ + { + id: 'repo-1', + url: 'https://github.com/acme/repo-1', + topics: ['reactjs', 'k8s', 'reactjs'], // alias + duplicate → one skill + verificationLevel: 'verified', + lastVerifiedAt: new Date('2026-01-01T00:00:00Z'), + evidence: [{ kind: 'repository_claim', sourceUrl: 'https://github.com/acme/repo-1' }], + }, + ], + collaborators: [ + { id: 'dev-2', sharedProjects: [{ id: 'repo-1', url: 'https://github.com/acme/repo-1' }] }, + { id: 'dev-1', sharedProjects: [] }, // self — must be skipped + ], + }; + + it('emits contributed_to, canonicalized+deduped has_skill, and collaborated_with edges', () => { + const edges = deriveTalentEdges(view); + const byType = edges.reduce>((acc, e) => { + (acc[e.type] ??= []).push(e); + return acc; + }, {}); + + expect(byType.contributed_to).toHaveLength(1); + expect(byType.has_skill.map((e) => e.to.id).sort()).toEqual(['kubernetes', 'react']); + // self-collaborator dev-1 skipped, only dev-2 remains + expect(byType.collaborated_with).toHaveLength(1); + expect(byType.collaborated_with[0].to.id).toBe('dev-2'); + }); + + it('produces edges that all pass ontology validation', () => { + const { accepted, rejected } = validateEdges(deriveTalentEdges(view)); + expect(rejected).toHaveLength(0); + expect(accepted.length).toBeGreaterThan(0); + // skill edges are capped at the recorded tier even for a verified project + const skillEdge = accepted.find((e) => e.type === 'has_skill'); + expect(skillEdge?.provenance.confidence).toBe(0.5); + }); +});