@hazeljs/kag 0.0.0-stage → 2.0.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/README.md +122 -2
  2. package/dist/adapters/graphrag.adapter.d.ts +47 -0
  3. package/dist/adapters/graphrag.adapter.d.ts.map +1 -0
  4. package/dist/adapters/graphrag.adapter.js +111 -0
  5. package/dist/confidence.d.ts +7 -0
  6. package/dist/confidence.d.ts.map +1 -0
  7. package/dist/confidence.js +40 -0
  8. package/dist/errors/kag.error.d.ts +42 -0
  9. package/dist/errors/kag.error.d.ts.map +1 -0
  10. package/dist/errors/kag.error.js +80 -0
  11. package/dist/index.d.ts +15 -0
  12. package/dist/index.d.ts.map +1 -0
  13. package/dist/index.js +30 -0
  14. package/dist/ingestion/ingest.d.ts +24 -0
  15. package/dist/ingestion/ingest.d.ts.map +1 -0
  16. package/dist/ingestion/ingest.js +61 -0
  17. package/dist/kag.module.d.ts +29 -0
  18. package/dist/kag.module.d.ts.map +1 -0
  19. package/dist/kag.module.js +58 -0
  20. package/dist/kag.service.d.ts +66 -0
  21. package/dist/kag.service.d.ts.map +1 -0
  22. package/dist/kag.service.js +92 -0
  23. package/dist/knowledge-graph.d.ts +50 -0
  24. package/dist/knowledge-graph.d.ts.map +1 -0
  25. package/dist/knowledge-graph.js +290 -0
  26. package/dist/planner/heuristic-query-planner.d.ts +36 -0
  27. package/dist/planner/heuristic-query-planner.d.ts.map +1 -0
  28. package/dist/planner/heuristic-query-planner.js +67 -0
  29. package/dist/planner/industry-profiles.d.ts +34 -0
  30. package/dist/planner/industry-profiles.d.ts.map +1 -0
  31. package/dist/planner/industry-profiles.js +83 -0
  32. package/dist/resolution/entity-resolver.d.ts +21 -0
  33. package/dist/resolution/entity-resolver.d.ts.map +1 -0
  34. package/dist/resolution/entity-resolver.js +123 -0
  35. package/dist/security/authorizer.d.ts +27 -0
  36. package/dist/security/authorizer.d.ts.map +1 -0
  37. package/dist/security/authorizer.js +57 -0
  38. package/dist/stores/in-memory-knowledge.store.d.ts +22 -0
  39. package/dist/stores/in-memory-knowledge.store.d.ts.map +1 -0
  40. package/dist/stores/in-memory-knowledge.store.js +186 -0
  41. package/dist/temporal.d.ts +7 -0
  42. package/dist/temporal.d.ts.map +1 -0
  43. package/dist/temporal.js +63 -0
  44. package/dist/types.d.ts +207 -0
  45. package/dist/types.d.ts.map +1 -0
  46. package/dist/types.js +15 -0
  47. package/package.json +78 -4
package/README.md CHANGED
@@ -1,3 +1,123 @@
1
- # Temporary Holding Version
1
+ # @hazeljs/kag
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ **Entities, facts, and relationships — with provenance you can audit.**
4
+
5
+ Knowledge-Augmented Generation for HazelJS — typed knowledge graphs, time-scoped facts, contradictions, and explainable multi-hop reasoning. Use when the question is “why did X change?” over structured domain state, not “which PDF page mentions X?”
6
+
7
+ KAG does **not** duplicate GraphRAG internals. Import document-derived graphs via `importGraph()`; community detection and vector search stay in `@hazeljs/rag`.
8
+
9
+ [![npm version](https://img.shields.io/npm/v/@hazeljs/kag.svg)](https://www.npmjs.com/package/@hazeljs/kag)
10
+ [![npm downloads](https://img.shields.io/npm/dm/@hazeljs/kag)](https://www.npmjs.com/package/@hazeljs/kag)
11
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](https://www.apache.org/licenses/LICENSE-2.0)
12
+
13
+ ## KAG vs RAG
14
+
15
+ | | KAG | RAG |
16
+ | -------- | -------------------------------------------------- | --------------------------- |
17
+ | Question | What entities, facts, and relationships do I know? | What passages are relevant? |
18
+ | Unit | Entity / relation / fact | Document chunk |
19
+ | Strength | Multi-hop structured reasoning | Semantic similarity |
20
+
21
+ ## Features
22
+
23
+ - **Typed primitives** — `KnowledgeEntity` / `KnowledgeRelation` / `KnowledgeFact` with confidence + provenance
24
+ - **Tenant-partitioned store** — `InMemoryKnowledgeStore` (Neo4j/Postgres via `KnowledgeStore` ports later)
25
+ - **Entity resolution** — `exact` / `normalized` / `semantic` / `custom`; no auto-merge below threshold
26
+ - **Temporal + contradictions** — `asOf`, ranked conflicts, policy `keep` | `rank` | `reject`
27
+ - **Industry-pluggable planner** — generic by default; opt in with `COMMERCE_INDUSTRY_PROFILE` (or your own)
28
+ - **Explainable answers** — `ask({ explain: true })` returns evidence paths (not model CoT)
29
+ - **Agent OS port** — inject as `AgentRuntimeConfig.kagService`; DNA may declare `context.kag.enabled`
30
+
31
+ ## Installation
32
+
33
+ ```bash
34
+ npm install @hazeljs/kag @hazeljs/core
35
+ ```
36
+
37
+ ## Quick Start
38
+
39
+ ```typescript
40
+ import { KnowledgeGraph, COMMERCE_INDUSTRY_PROFILE } from '@hazeljs/kag';
41
+
42
+ const knowledge = new KnowledgeGraph({
43
+ tenantId: 'merchant-123',
44
+ graph: 'commerce',
45
+ industry: COMMERCE_INDUSTRY_PROFILE, // opt-in commerce vocabulary
46
+ });
47
+
48
+ await knowledge.entity({
49
+ id: 'merchant-123',
50
+ type: 'merchant',
51
+ properties: { name: 'Demo Restaurant' },
52
+ });
53
+ await knowledge.entity({
54
+ id: 'order-456',
55
+ type: 'order',
56
+ properties: { total: 120 },
57
+ });
58
+ await knowledge.relate({
59
+ from: 'merchant-123',
60
+ to: 'order-456',
61
+ type: 'HAS_ORDER',
62
+ });
63
+
64
+ const result = await knowledge.ask('Why was settlement lower yesterday?', {
65
+ explain: true,
66
+ });
67
+ // { answer, evidence, sources, confidence, explanation }
68
+ ```
69
+
70
+ ## Entities, Relationships, Facts
71
+
72
+ Typed primitives with optional `confidence`, `source` provenance, and `validFrom` / `validUntil`.
73
+
74
+ ## Entity Resolution
75
+
76
+ `EntityResolver` strategies: `exact`, `normalized`, `semantic` (when embed is provided), `custom`. Uncertain matches stay as candidates below `mergeThreshold` (default 0.9).
77
+
78
+ ## Temporal Knowledge, Confidence, Contradictions
79
+
80
+ - Query with `asOf` or `currentFacts()` / `changes(from, to)`
81
+ - Path confidence aggregates with `min` (default) or `product`
82
+ - Contradictions are retained; ranked by authority → timestamp → confidence → priority
83
+ - Policy `reject` throws `KnowledgeConflictError`
84
+
85
+ ## Knowledge Queries & RAG Integration
86
+
87
+ `HeuristicQueryPlanner` is industry-agnostic by default (generic causal/temporal/comparison intents). Opt into a domain with `industry: COMMERCE_INDUSTRY_PROFILE` (or your own `IndustryProfile`). Pass `{ rag: true }` with an injected `KnowledgeRetriever` to fuse document passages.
88
+
89
+ ## Memory Integration
90
+
91
+ `promoteObservation({ validated: true, confidence })` is explicit. No automatic promotion from `@hazeljs/memory`.
92
+
93
+ ## Agent Integration
94
+
95
+ Inject `KagService` as `AgentRuntimeConfig.kagService`. DNA may declare `context.kag.enabled`.
96
+
97
+ ## Security
98
+
99
+ Every store call requires `KnowledgeScope.tenantId`. Optional `KnowledgeAuthorizer` or `createCaslKnowledgeAuthorizer(can)`.
100
+
101
+ ## Production Guide
102
+
103
+ - Start with `InMemoryKnowledgeStore`; design against `KnowledgeStore` for Neo4j/Postgres later
104
+ - Always set tenant scope; add authorizer for entity-level access
105
+ - Prefer `explain: true` for enterprise audit trails (evidence, not model CoT)
106
+
107
+ ## Related
108
+
109
+ - Docs: [hazeljs.ai/docs/packages/kag](https://hazeljs.ai/docs/packages/kag)
110
+ - Blog: [RAG vs CAG vs KAG](https://hazeljs.ai/blog/rag-vs-cag-vs-kag)
111
+ - Lab: [meridian-ops `example:kag`](https://github.com/hazel-js/hazeljs-meridian-ops/tree/main/examples/kag-commerce-agent)
112
+ - `@hazeljs/rag` — GraphRAG import source + document retrieval
113
+ - `@hazeljs/cag` — stable cached context
114
+ - `@hazeljs/context` — unified planner
115
+ - `@hazeljs/memory` — user continuity (promote explicitly)
116
+
117
+ ## License
118
+
119
+ Apache 2.0 © [HazelJS](https://hazeljs.ai)
120
+
121
+ ## Contributing
122
+
123
+ Contributions are welcome! See [CONTRIBUTING.md](../../CONTRIBUTING.md) for details.
@@ -0,0 +1,47 @@
1
+ import type { KnowledgeEntity, KnowledgeExtractor, KnowledgeRelation, KnowledgeScope } from '../types';
2
+ import type { KnowledgeGraph } from '../knowledge-graph';
3
+ /**
4
+ * Minimal GraphRAG-like shapes so KAG can import without a hard dependency
5
+ * on @hazeljs/rag at compile time.
6
+ */
7
+ export interface GraphRagEntityLike {
8
+ id: string;
9
+ name: string;
10
+ type: string;
11
+ description?: string;
12
+ sourceDocIds?: string[];
13
+ metadata?: Record<string, unknown>;
14
+ }
15
+ export interface GraphRagRelationshipLike {
16
+ id: string;
17
+ sourceId: string;
18
+ targetId: string;
19
+ type: string;
20
+ description?: string;
21
+ weight?: number;
22
+ sourceDocIds?: string[];
23
+ }
24
+ export interface GraphStoreLike {
25
+ entities?: Map<string, GraphRagEntityLike> | GraphRagEntityLike[];
26
+ relationships?: Map<string, GraphRagRelationshipLike> | GraphRagRelationshipLike[];
27
+ [key: string]: unknown;
28
+ }
29
+ /**
30
+ * Map GraphRAG entities/relations into KAG writes.
31
+ */
32
+ export declare function importGraph(graph: KnowledgeGraph, graphStore: GraphStoreLike, _scope?: KnowledgeScope): Promise<{
33
+ entities: number;
34
+ relations: number;
35
+ }>;
36
+ /**
37
+ * Maps a GraphRAG-style extraction result into KAG write shapes.
38
+ */
39
+ export declare function mapExtractionResult(result: {
40
+ entities?: GraphRagEntityLike[];
41
+ relationships?: GraphRagRelationshipLike[];
42
+ }): {
43
+ entities: KnowledgeEntity[];
44
+ relations: KnowledgeRelation[];
45
+ };
46
+ export declare function createExtractionMapper(extract: KnowledgeExtractor['extract']): KnowledgeExtractor;
47
+ //# sourceMappingURL=graphrag.adapter.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"graphrag.adapter.d.ts","sourceRoot":"","sources":["../../src/adapters/graphrag.adapter.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAElB,iBAAiB,EACjB,cAAc,EACf,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,cA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AE,CAAC;IAC5B,SAAS,EAAE,iBAAiB,EAAE,CAAC;CAChC,CAkBA;AAED,wBAAgB,sBAAsB,CAAC,OAAO,EAAE,kBAAkB,CAAC,SAAS,CAAC,GAAG,kBAAkB,CAejG"}
@@ -0,0 +1,111 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.importGraph = importGraph;
4
+ exports.mapExtractionResult = mapExtractionResult;
5
+ exports.createExtractionMapper = createExtractionMapper;
6
+ function asList(value) {
7
+ if (!value)
8
+ return [];
9
+ if (Array.isArray(value))
10
+ return value;
11
+ return [...value.values()];
12
+ }
13
+ /**
14
+ * Map GraphRAG entities/relations into KAG writes.
15
+ */
16
+ async function importGraph(graph, graphStore, _scope) {
17
+ // Prefer public getters if present (GraphStore)
18
+ const entities = typeof graphStore.getStats === 'function'
19
+ ? extractEntitiesFromStore(graphStore)
20
+ : asList(graphStore.entities);
21
+ const relationships = typeof graphStore.getStats === 'function'
22
+ ? extractRelationsFromStore(graphStore)
23
+ : asList(graphStore.relationships);
24
+ let entityCount = 0;
25
+ for (const e of entities) {
26
+ await graph.entity({
27
+ id: e.id,
28
+ type: e.type || 'OTHER',
29
+ properties: {
30
+ name: e.name,
31
+ description: e.description ?? '',
32
+ },
33
+ metadata: {
34
+ ...e.metadata,
35
+ graphRagId: e.id,
36
+ sourceDocIds: e.sourceDocIds,
37
+ },
38
+ });
39
+ entityCount++;
40
+ }
41
+ let relationCount = 0;
42
+ for (const r of relationships) {
43
+ await graph.relate({
44
+ id: r.id,
45
+ from: r.sourceId,
46
+ to: r.targetId,
47
+ type: r.type,
48
+ properties: {
49
+ description: r.description,
50
+ weight: r.weight,
51
+ sourceDocIds: r.sourceDocIds,
52
+ },
53
+ confidence: r.weight !== undefined ? Math.min(1, r.weight / 10) : 0.8,
54
+ source: { type: 'graphrag', id: r.id, authority: 50 },
55
+ });
56
+ relationCount++;
57
+ }
58
+ return { entities: entityCount, relations: relationCount };
59
+ }
60
+ function extractEntitiesFromStore(store) {
61
+ // GraphStore keeps private maps; support toJSON() if available
62
+ const maybeJson = store.toJSON?.();
63
+ if (maybeJson?.entities)
64
+ return maybeJson.entities;
65
+ if (store.entities)
66
+ return asList(store.entities);
67
+ return [];
68
+ }
69
+ function extractRelationsFromStore(store) {
70
+ const maybeJson = store.toJSON?.();
71
+ if (maybeJson?.relationships)
72
+ return maybeJson.relationships;
73
+ if (store.relationships) {
74
+ return asList(store.relationships);
75
+ }
76
+ return [];
77
+ }
78
+ /**
79
+ * Maps a GraphRAG-style extraction result into KAG write shapes.
80
+ */
81
+ function mapExtractionResult(result) {
82
+ return {
83
+ entities: (result.entities ?? []).map((e) => ({
84
+ id: e.id,
85
+ type: e.type || 'OTHER',
86
+ properties: { name: e.name, description: e.description ?? '' },
87
+ metadata: { graphRagId: e.id, sourceDocIds: e.sourceDocIds, ...e.metadata },
88
+ })),
89
+ relations: (result.relationships ?? []).map((r) => ({
90
+ id: r.id,
91
+ from: r.sourceId,
92
+ to: r.targetId,
93
+ type: r.type,
94
+ properties: { description: r.description, weight: r.weight },
95
+ confidence: r.weight !== undefined ? Math.min(1, r.weight / 10) : 0.8,
96
+ source: { type: 'graphrag', id: r.id },
97
+ })),
98
+ };
99
+ }
100
+ function createExtractionMapper(extract) {
101
+ return {
102
+ async extract(input) {
103
+ const raw = await extract(input);
104
+ return {
105
+ entities: raw.entities,
106
+ relations: raw.relations,
107
+ facts: raw.facts,
108
+ };
109
+ },
110
+ };
111
+ }
@@ -0,0 +1,7 @@
1
+ import type { ConfidenceAggregation, KnowledgeFact } from './types';
2
+ export declare function aggregateConfidence(values: number[], mode?: ConfidenceAggregation): number;
3
+ /**
4
+ * Rank conflicting facts: source authority → timestamp → confidence → priority.
5
+ */
6
+ export declare function rankFacts(facts: KnowledgeFact[]): KnowledgeFact[];
7
+ //# sourceMappingURL=confidence.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"confidence.d.ts","sourceRoot":"","sources":["../src/confidence.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,qBAAqB,EAAE,aAAa,EAAE,MAAM,SAAS,CAAC;AAGpE,wBAAgB,mBAAmB,CAAC,MAAM,EAAE,MAAM,EAAE,EAAE,IAAI,GAAE,qBAA6B,GAAG,MAAM,CAMjG;AAOD;;GAEG;AACH,wBAAgB,SAAS,CAAC,KAAK,EAAE,aAAa,EAAE,GAAG,aAAa,EAAE,CAkBjE"}
@@ -0,0 +1,40 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.aggregateConfidence = aggregateConfidence;
4
+ exports.rankFacts = rankFacts;
5
+ const temporal_1 = require("./temporal");
6
+ function aggregateConfidence(values, mode = 'min') {
7
+ if (values.length === 0)
8
+ return 1;
9
+ if (mode === 'product') {
10
+ return values.reduce((acc, v) => acc * clamp01(v), 1);
11
+ }
12
+ return Math.min(...values.map(clamp01));
13
+ }
14
+ function clamp01(n) {
15
+ if (!Number.isFinite(n))
16
+ return 0;
17
+ return Math.max(0, Math.min(1, n));
18
+ }
19
+ /**
20
+ * Rank conflicting facts: source authority → timestamp → confidence → priority.
21
+ */
22
+ function rankFacts(facts) {
23
+ return [...facts].sort((a, b) => {
24
+ const authA = a.source?.authority ?? 0;
25
+ const authB = b.source?.authority ?? 0;
26
+ if (authB !== authA)
27
+ return authB - authA;
28
+ const timeA = (0, temporal_1.toDate)(a.createdAt)?.getTime() ?? (0, temporal_1.toDate)(a.validFrom)?.getTime() ?? 0;
29
+ const timeB = (0, temporal_1.toDate)(b.createdAt)?.getTime() ?? (0, temporal_1.toDate)(b.validFrom)?.getTime() ?? 0;
30
+ if (timeB !== timeA)
31
+ return timeB - timeA;
32
+ const confA = a.confidence ?? 0;
33
+ const confB = b.confidence ?? 0;
34
+ if (confB !== confA)
35
+ return confB - confA;
36
+ const priA = a.priority ?? a.source?.priority ?? 0;
37
+ const priB = b.priority ?? b.source?.priority ?? 0;
38
+ return priB - priA;
39
+ });
40
+ }
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Structured KAG errors for robust handling and observability.
3
+ */
4
+ export declare enum KagErrorCode {
5
+ ENTITY_NOT_FOUND = "KAG_ENTITY_NOT_FOUND",
6
+ STORE_ERROR = "KAG_STORE_ERROR",
7
+ CONFLICT = "KAG_CONFLICT",
8
+ ACCESS_DENIED = "KAG_ACCESS_DENIED",
9
+ TENANT_REQUIRED = "KAG_TENANT_REQUIRED",
10
+ VALIDATION_ERROR = "KAG_VALIDATION_ERROR",
11
+ CONFIGURATION_ERROR = "KAG_CONFIGURATION_ERROR"
12
+ }
13
+ export declare class KagError extends Error {
14
+ readonly code: KagErrorCode;
15
+ readonly cause?: Error;
16
+ readonly details?: Record<string, unknown>;
17
+ constructor(message: string, code: KagErrorCode, cause?: Error, details?: Record<string, unknown>);
18
+ static entityNotFound(id: string): KagError;
19
+ static storeError(message: string, cause?: Error): KagError;
20
+ static conflict(message: string, details?: Record<string, unknown>): KagError;
21
+ static accessDenied(resource: string): KagError;
22
+ static tenantRequired(): KagError;
23
+ static validationError(message: string): KagError;
24
+ static configurationError(message: string): KagError;
25
+ }
26
+ /** @deprecated Prefer KagError */
27
+ export declare class KnowledgeEntityNotFoundError extends KagError {
28
+ constructor(id: string);
29
+ }
30
+ /** @deprecated Prefer KagError */
31
+ export declare class KnowledgeStoreError extends KagError {
32
+ constructor(message: string, cause?: Error);
33
+ }
34
+ /** @deprecated Prefer KagError */
35
+ export declare class KnowledgeConflictError extends KagError {
36
+ constructor(message: string, details?: Record<string, unknown>);
37
+ }
38
+ /** @deprecated Prefer KagError */
39
+ export declare class KnowledgeAccessDeniedError extends KagError {
40
+ constructor(resource: string);
41
+ }
42
+ //# sourceMappingURL=kag.error.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kag.error.d.ts","sourceRoot":"","sources":["../../src/errors/kag.error.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,oBAAY,YAAY;IACtB,gBAAgB,yBAAyB;IACzC,WAAW,oBA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AAO,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC;CAI/D;AAED,kCAAkC;AAClC,qBAAa,0BAA2B,SAAQ,QAAQ;gBAC1C,QAAQ,EAAE,MAAM;CAI7B"}
@@ -0,0 +1,80 @@
1
+ "use strict";
2
+ /**
3
+ * Structured KAG errors for robust handling and observability.
4
+ */
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.KnowledgeAccessDeniedError = exports.KnowledgeConflictError = exports.KnowledgeStoreError = exports.KnowledgeEntityNotFoundError = exports.KagError = exports.KagErrorCode = void 0;
7
+ var KagErrorCode;
8
+ (function (KagErrorCode) {
9
+ KagErrorCode["ENTITY_NOT_FOUND"] = "KAG_ENTITY_NOT_FOUND";
10
+ KagErrorCode["STORE_ERROR"] = "KAG_STORE_ERROR";
11
+ KagErrorCode["CONFLICT"] = "KAG_CONFLICT";
12
+ KagErrorCode["ACCESS_DENIED"] = "KAG_ACCESS_DENIED";
13
+ KagErrorCode["TENANT_REQUIRED"] = "KAG_TENANT_REQUIRED";
14
+ KagErrorCode["VALIDATION_ERROR"] = "KAG_VALIDATION_ERROR";
15
+ KagErrorCode["CONFIGURATION_ERROR"] = "KAG_CONFIGURATION_ERROR";
16
+ })(KagErrorCode || (exports.KagErrorCode = KagErrorCode = {}));
17
+ class KagError extends Error {
18
+ constructor(message, code, cause, details) {
19
+ super(message);
20
+ this.name = 'KagError';
21
+ this.code = code;
22
+ this.cause = cause;
23
+ this.details = details;
24
+ Object.setPrototypeOf(this, KagError.prototype);
25
+ }
26
+ static entityNotFound(id) {
27
+ return new KagError(`Knowledge entity "${id}" was not found in the current tenant scope.`, KagErrorCode.ENTITY_NOT_FOUND);
28
+ }
29
+ static storeError(message, cause) {
30
+ return new KagError(message, KagErrorCode.STORE_ERROR, cause);
31
+ }
32
+ static conflict(message, details) {
33
+ return new KagError(message, KagErrorCode.CONFLICT, undefined, details);
34
+ }
35
+ static accessDenied(resource) {
36
+ return new KagError(`Access denied for knowledge resource "${resource}".`, KagErrorCode.ACCESS_DENIED);
37
+ }
38
+ static tenantRequired() {
39
+ return new KagError('tenantId is required for knowledge operations. Pass a KnowledgeScope with tenantId.', KagErrorCode.TENANT_REQUIRED);
40
+ }
41
+ static validationError(message) {
42
+ return new KagError(message, KagErrorCode.VALIDATION_ERROR);
43
+ }
44
+ static configurationError(message) {
45
+ return new KagError(message, KagErrorCode.CONFIGURATION_ERROR);
46
+ }
47
+ }
48
+ exports.KagError = KagError;
49
+ /** @deprecated Prefer KagError */
50
+ class KnowledgeEntityNotFoundError extends KagError {
51
+ constructor(id) {
52
+ super(KagError.entityNotFound(id).message, KagErrorCode.ENTITY_NOT_FOUND);
53
+ this.name = 'KnowledgeEntityNotFoundError';
54
+ }
55
+ }
56
+ exports.KnowledgeEntityNotFoundError = KnowledgeEntityNotFoundError;
57
+ /** @deprecated Prefer KagError */
58
+ class KnowledgeStoreError extends KagError {
59
+ constructor(message, cause) {
60
+ super(message, KagErrorCode.STORE_ERROR, cause);
61
+ this.name = 'KnowledgeStoreError';
62
+ }
63
+ }
64
+ exports.KnowledgeStoreError = KnowledgeStoreError;
65
+ /** @deprecated Prefer KagError */
66
+ class KnowledgeConflictError extends KagError {
67
+ constructor(message, details) {
68
+ super(message, KagErrorCode.CONFLICT, undefined, details);
69
+ this.name = 'KnowledgeConflictError';
70
+ }
71
+ }
72
+ exports.KnowledgeConflictError = KnowledgeConflictError;
73
+ /** @deprecated Prefer KagError */
74
+ class KnowledgeAccessDeniedError extends KagError {
75
+ constructor(resource) {
76
+ super(KagError.accessDenied(resource).message, KagErrorCode.ACCESS_DENIED);
77
+ this.name = 'KnowledgeAccessDeniedError';
78
+ }
79
+ }
80
+ exports.KnowledgeAccessDeniedError = KnowledgeAccessDeniedError;
@@ -0,0 +1,15 @@
1
+ export * from './types';
2
+ export * from './errors/kag.error';
3
+ export * from './kag.module';
4
+ export * from './kag.service';
5
+ export * from './knowledge-graph';
6
+ export * from './stores/in-memory-knowledge.store';
7
+ export * from './resolution/entity-resolver';
8
+ export * from './planner/heuristic-query-planner';
9
+ export * from './planner/industry-profiles';
10
+ export * from './security/authorizer';
11
+ export * from './ingestion/ingest';
12
+ export * from './adapters/graphrag.adapter';
13
+ export * from './temporal';
14
+ export * from './confidence';
15
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,SAAS,CAAC;AACxB,cAAc,oBAAoB,CAAC;AACnC,cAAc,cAAc,CAAC;AAC7B,cAAc,eAAe,CAAC;AAC9B,cAAc,mBAAmB,CAAC;AAClC,cAAc,oCAAoC,CAAC;AACnD,cAAc,8BAA8B,CAAC;AAC7C,cAAc,mCAAmC,CAAC;AAClD,cAAc,6BAA6B,CAAC;AAC5C,cAAc,uBAAuB,CAAC;AACtC,cAAc,oBAAoB,CAAC;AACnC,cAAc,6BAA6B,CAAC;AAC5C,cAAc,YAAY,CAAC;AAC3B,cAAc,cAAc,CAAC"}
package/dist/index.js ADDED
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ __exportStar(require("./types"), exports);
18
+ __exportStar(require("./errors/kag.error"), exports);
19
+ __exportStar(require("./kag.module"), exports);
20
+ __exportStar(require("./kag.service"), exports);
21
+ __exportStar(require("./knowledge-graph"), exports);
22
+ __exportStar(require("./stores/in-memory-knowledge.store"), exports);
23
+ __exportStar(require("./resolution/entity-resolver"), exports);
24
+ __exportStar(require("./planner/heuristic-query-planner"), exports);
25
+ __exportStar(require("./planner/industry-profiles"), exports);
26
+ __exportStar(require("./security/authorizer"), exports);
27
+ __exportStar(require("./ingestion/ingest"), exports);
28
+ __exportStar(require("./adapters/graphrag.adapter"), exports);
29
+ __exportStar(require("./temporal"), exports);
30
+ __exportStar(require("./confidence"), exports);
@@ -0,0 +1,24 @@
1
+ import type { KnowledgeEntity, KnowledgeExtractor, KnowledgeFact, KnowledgeRelation } from '../types';
2
+ import type { KnowledgeGraph } from '../knowledge-graph';
3
+ import { EntityResolver } from '../resolution/entity-resolver';
4
+ export interface IngestBatch {
5
+ entities?: KnowledgeEntity[];
6
+ relations?: KnowledgeRelation[];
7
+ facts?: KnowledgeFact[];
8
+ }
9
+ export interface IngestResult {
10
+ entities: number;
11
+ relations: number;
12
+ facts: number;
13
+ unresolvedCandidates: number;
14
+ }
15
+ /**
16
+ * Ingestion pipeline: extract → resolve → dedupe → validate → write.
17
+ * Uncertain entity matches are not merged.
18
+ */
19
+ export declare function ingestKnowledge(graph: KnowledgeGraph, batch: IngestBatch, options?: {
20
+ extractor?: KnowledgeExtractor;
21
+ raw?: unknown;
22
+ resolver?: EntityResolver;
23
+ }): Promise<IngestResult>;
24
+ //# sourceMappingURL=ingest.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ingest.d.ts","sourceRoot":"","sources":["../../src/ingestion/ingest.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,eAAe,EACf,kBAAkB,EAClB,aAAa,EACb,iBAAiB,EAClB,MAAM,UAAU,CAAC;AAClB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AACzD,OAAO,EAAE,cAAc,EAAE,MAAM,+BAA+B,CAAC;AAE/D,MAAM,WAAW,WAAW;IAC1B,QAAQ,CAAC,EAAE,eAAe,EAAE,CAAC;IAC7B,SAAS,CAAC,EAAE,iBAAiB,EAAE,CAAC;IAChC,KAAK,CAAC,EAAE,aAAa,EAAE,CAAC;CACzB;AAED,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,MAAM,CAAC;IACjB,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,MAAM,CAAC;IACd,oBAAoB,EAAE,MAAM,CAAC;CAC9B;AAED;;;GAGG;AACH,wBAAsB,eAAe,CACnC,KAAK,EAAE,cAAc,EACrB,KAAK,EAAE,WAAW,EAClB,OAAO,CAAC,EAAE;IACR,SAAS,CAAC,EAAE,kBAAkB,CAAC;IAC/B,GAAG,CAAC,EAAE,OAAO,CAAC;IACd,QAAQ,CAAC,EAAE,cAAc,CAAC;CAC3B,GACA,OAAO,CAAC,YAAY,CAAC,CAwDvB"}
@@ -0,0 +1,61 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ingestKnowledge = ingestKnowledge;
4
+ /**
5
+ * Ingestion pipeline: extract → resolve → dedupe → validate → write.
6
+ * Uncertain entity matches are not merged.
7
+ */
8
+ async function ingestKnowledge(graph, batch, options) {
9
+ let entities = batch.entities ?? [];
10
+ let relations = batch.relations ?? [];
11
+ let facts = batch.facts ?? [];
12
+ if (options?.extractor && options.raw !== undefined) {
13
+ const extracted = await options.extractor.extract(options.raw);
14
+ entities = [...entities, ...extracted.entities];
15
+ relations = [...relations, ...extracted.relations];
16
+ facts = [...facts, ...(extracted.facts ?? [])];
17
+ }
18
+ // Deduplicate entities by id
19
+ const entityById = new Map();
20
+ for (const e of entities) {
21
+ entityById.set(e.id, e);
22
+ }
23
+ let unresolvedCandidates = 0;
24
+ for (const entity of entityById.values()) {
25
+ const resolution = await graph.resolve(entity);
26
+ if (resolution.merged) {
27
+ await graph.entity(resolution.merged);
28
+ }
29
+ else {
30
+ if (resolution.candidates.length > 0) {
31
+ unresolvedCandidates += resolution.candidates.length;
32
+ }
33
+ await graph.entity(entity);
34
+ }
35
+ }
36
+ // Deduplicate relations
37
+ const relKeys = new Set();
38
+ let relationCount = 0;
39
+ for (const rel of relations) {
40
+ const key = rel.id ?? `${rel.from}:${rel.type}:${rel.to}`;
41
+ if (relKeys.has(key))
42
+ continue;
43
+ relKeys.add(key);
44
+ await graph.relate(rel);
45
+ relationCount++;
46
+ }
47
+ let factCount = 0;
48
+ for (const fact of facts) {
49
+ // Basic validation
50
+ if (!fact.subject || !fact.predicate)
51
+ continue;
52
+ await graph.fact(fact);
53
+ factCount++;
54
+ }
55
+ return {
56
+ entities: entityById.size,
57
+ relations: relationCount,
58
+ facts: factCount,
59
+ unresolvedCandidates,
60
+ };
61
+ }
@@ -0,0 +1,29 @@
1
+ import { KagService } from './kag.service';
2
+ import type { KagModuleOptions } from './types';
3
+ export declare class KagModule {
4
+ static forRoot(options?: KagModuleOptions): {
5
+ module: typeof KagModule;
6
+ providers: Array<{
7
+ provide: string | typeof KagService;
8
+ useValue?: unknown;
9
+ useFactory?: (...args: unknown[]) => unknown;
10
+ inject?: unknown[];
11
+ }>;
12
+ exports: Array<typeof KagService | string>;
13
+ global: boolean;
14
+ };
15
+ static forRootAsync(options: {
16
+ useFactory: (...args: unknown[]) => Promise<KagModuleOptions> | KagModuleOptions;
17
+ inject?: unknown[];
18
+ }): {
19
+ module: typeof KagModule;
20
+ providers: Array<{
21
+ provide: string | typeof KagService;
22
+ useFactory: (...args: unknown[]) => unknown;
23
+ inject?: unknown[];
24
+ }>;
25
+ exports: Array<typeof KagService | string>;
26
+ global: boolean;
27
+ };
28
+ }
29
+ //# sourceMappingURL=kag.module.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"kag.module.d.ts","sourceRoot":"","sources":["../src/kag.module.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,UAAU,EAAE,MAAM,eAAe,CAAC;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