cograph 0.1.22 → 0.1.24

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.
package/README.md CHANGED
@@ -116,6 +116,8 @@ new Client({
116
116
  - `ask(question, { kg? })` — returns `{ answer, sparql?, ... }`.
117
117
  - `listKgs()`, `createKg(name, description?)`, `deleteKg(name)` — knowledge-graph CRUD.
118
118
  - `ontologyTypes()` — list every type in the tenant ontology with attributes and parents.
119
+ - `ontologyResolve(ask, { knowledge_graph? })` — resolve a fuzzy natural-language ontology-evolution ask (no exact type/attribute/relationship names needed) against the current schema. Returns `{ applied, proposals, summary }`; high-confidence changes land automatically, ambiguous/new-type ones come back as `proposals`.
120
+ - `ontologyApply(proposal)` — confirm and commit a single `ResolvedChange` from `ontologyResolve`'s `proposals`. Pass the object through unchanged; returns `{ applied, operations, summary }`.
119
121
  - `typeCounts(kg)` — `[{ name, entity_count }]` for the given KG, sorted desc. Powers `/types`.
120
122
  - `typeUsage(kg, name, { includeSystem? })` — full breakdown for one type: attributes (with usage counts), relationships, and 3 sample entities. Powers `/type`. System predicates filtered by default.
121
123
 
@@ -16,6 +16,13 @@ var CographError = class extends Error {
16
16
  this.body = opts?.body;
17
17
  }
18
18
  };
19
+ var SCHEMA_SAMPLE_CAP = 5e3;
20
+ function stridedSample(rows, cap = SCHEMA_SAMPLE_CAP) {
21
+ if (rows.length <= cap) return rows;
22
+ const out = [];
23
+ for (let i = 0; i < cap; i++) out.push(rows[Math.floor(i * rows.length / cap)]);
24
+ return out;
25
+ }
19
26
  function envVar(name, fallback) {
20
27
  return process.env[`COGRAPH_${name}`] || process.env[`OMNIX_${name}`] || fallback;
21
28
  }
@@ -224,13 +231,7 @@ var Client = class {
224
231
  const rows = parseCsv(content);
225
232
  if (rows.length === 0) throw new CographError("CSV is empty");
226
233
  const headers = Object.keys(rows[0]);
227
- const sampleRows = rows.map((row, idx) => ({
228
- row,
229
- idx,
230
- score: Object.values(row).filter(
231
- (v) => v != null && String(v).trim() !== ""
232
- ).length
233
- })).sort((a, b) => b.score - a.score || a.idx - b.idx).slice(0, 10).map((s) => s.row);
234
+ const sampleRows = stridedSample(rows);
234
235
  const schemaBody = {
235
236
  headers,
236
237
  sample_rows: sampleRows,
@@ -242,6 +243,17 @@ var Client = class {
242
243
  schemaBody,
243
244
  3e5
244
245
  );
246
+ let mappingToPost = mapping;
247
+ if (opts.onSchemaInferred) {
248
+ const reviewed = await opts.onSchemaInferred(mapping, {
249
+ totalRows: rows.length,
250
+ rowsProfiled: sampleRows.length
251
+ });
252
+ if (reviewed == null) {
253
+ return { cancelled: true, message: "Ingest cancelled before any rows were written." };
254
+ }
255
+ mappingToPost = reviewed;
256
+ }
245
257
  const batches = [];
246
258
  for (let i = 0; i < rows.length; i += batchSize) {
247
259
  batches.push(rows.slice(i, i + batchSize));
@@ -252,7 +264,7 @@ var Client = class {
252
264
  let nextBatch = 0;
253
265
  const postBatch = async (batch) => {
254
266
  const body = {
255
- mapping,
267
+ mapping: mappingToPost,
256
268
  rows: batch,
257
269
  source: "client"
258
270
  };
@@ -309,6 +321,18 @@ var Client = class {
309
321
  if (opts.model) body.model = opts.model;
310
322
  return this.request("POST", `${this.base()}/ask`, body, 6e4);
311
323
  }
324
+ /** List the tenants the authenticated user can access (GET /v1/me/tenants).
325
+ * Keyed by the API key (X-API-Key → user), so it's independent of the active
326
+ * tenant. Throws CographError with status 501 on deployments without a tenant
327
+ * provider (e.g. OSS-only). */
328
+ async listTenants() {
329
+ return this.request(
330
+ "GET",
331
+ `${this.baseUrl}/v1/me/tenants`,
332
+ void 0,
333
+ 15e3
334
+ );
335
+ }
312
336
  /** List all knowledge graphs for the current tenant. */
313
337
  async listKgs() {
314
338
  const data = await this.request(
@@ -349,6 +373,34 @@ var Client = class {
349
373
  );
350
374
  return Array.isArray(data) ? data : [];
351
375
  }
376
+ /**
377
+ * Resolve a natural-language ontology change against the existing ontology.
378
+ * The caller does not need to know exact type/attribute/relationship names —
379
+ * the server matches the plain-language `ask` to the current schema and
380
+ * returns auto-applied changes plus proposals that need confirmation.
381
+ */
382
+ async ontologyResolve(ask, opts = {}) {
383
+ const body = { ask };
384
+ if (opts.knowledge_graph) body.knowledge_graph = opts.knowledge_graph;
385
+ return this.request(
386
+ "POST",
387
+ `${this.base()}/ontology/resolve`,
388
+ body,
389
+ 6e4
390
+ );
391
+ }
392
+ /**
393
+ * Apply a single resolved ontology change — one of the `proposals` returned
394
+ * by {@link ontologyResolve}. Pass the proposal object through unchanged.
395
+ */
396
+ async ontologyApply(proposal) {
397
+ return this.request(
398
+ "POST",
399
+ `${this.base()}/ontology/apply`,
400
+ proposal,
401
+ 6e4
402
+ );
403
+ }
352
404
  /**
353
405
  * Second-pass entity resolution: re-run ER over an already-ingested KG to
354
406
  * collapse intra-batch fragments. Synchronous on the server; returns a
@@ -468,4 +520,4 @@ export {
468
520
  CographError,
469
521
  Client
470
522
  };
471
- //# sourceMappingURL=chunk-X7YVTWAD.js.map
523
+ //# sourceMappingURL=chunk-YFM3KDCO.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/client.ts"],"sourcesContent":["import { existsSync, readFileSync, statSync } from \"node:fs\";\nimport { extname } from \"node:path\";\nimport { readConfig } from \"./config.js\";\n\nexport class CographError extends Error {\n status?: number;\n body?: string;\n\n constructor(message: string, opts?: { status?: number; body?: string }) {\n super(message);\n this.name = \"CographError\";\n this.status = opts?.status;\n this.body = opts?.body;\n }\n}\n\nexport interface ClientOptions {\n apiKey?: string;\n baseUrl?: string;\n tenant?: string;\n}\n\nexport interface IngestOptions {\n kg?: string;\n contentType?: \"text\" | \"csv\" | \"json\" | string;\n /** Rows per batch for CSV ingest. Default 200. Larger = fewer round-trips\n * but higher per-request memory; 200 is a good balance for typical KGs. */\n batchSize?: number;\n /** Max number of batches in flight at once. Default 4. Higher saturates\n * the backend faster but risks 429s on large ingests. */\n concurrency?: number;\n /** Called after each batch completes during CSV ingest, in batch order.\n * Use for progress UI. Not invoked for text/json ingest. */\n onProgress?: (progress: IngestProgress) => void;\n /** CSV only. Called once after schema inference and BEFORE any rows are\n * written, with the inferred mapping. Return the (possibly edited/approved)\n * mapping to ingest, or `null` to cancel without writing anything. When\n * omitted the inferred mapping is applied as-is (non-interactive). This is\n * the same confirm/override gate the Explorer surfaces in its review step. */\n onSchemaInferred?: (\n mapping: Record<string, unknown>,\n info: { totalRows: number; rowsProfiled: number },\n ) => Promise<Record<string, unknown> | null>;\n}\n\nexport interface IngestProgress {\n rowsProcessed: number;\n totalRows: number;\n entitiesResolved: number;\n triplesInserted: number;\n}\n\n/** Rows sent to schema inference. Profile fidelity = decision quality, so we\n * send the whole file up to this cap, evenly strided across it (never the\n * head — head-of-file bias is exactly what evidence-grounded inference fixes).\n * Matches the Explorer's SCHEMA_SAMPLE_CAP. */\nexport const SCHEMA_SAMPLE_CAP = 5000;\n\nfunction stridedSample<T>(rows: T[], cap: number = SCHEMA_SAMPLE_CAP): T[] {\n if (rows.length <= cap) return rows;\n const out: T[] = [];\n for (let i = 0; i < cap; i++) out.push(rows[Math.floor((i * rows.length) / cap)]!);\n return out;\n}\n\nexport interface AskOptions {\n kg?: string;\n model?: string;\n}\n\nfunction envVar(name: string, fallback?: string): string | undefined {\n // Prefer COGRAPH_, fall back to OMNIX_ so old configs keep working.\n return (\n process.env[`COGRAPH_${name}`] ||\n process.env[`OMNIX_${name}`] ||\n fallback\n );\n}\n\nconst EXT_FORMAT: Record<string, string> = {\n \".csv\": \"csv\",\n \".json\": \"json\",\n \".jsonl\": \"json\",\n \".txt\": \"text\",\n};\n\n/**\n * Parse a CSV string into an array of row objects.\n *\n * Minimal RFC-4180-ish parser: handles quoted fields with commas, escaped\n * quotes (`\"\"`), CRLF/LF line endings. Does not handle BOM stripping or\n * encoding detection — we assume UTF-8 text in.\n */\nexport function parseCsv(content: string): Record<string, string>[] {\n const rows: string[][] = [];\n let cur: string[] = [];\n let field = \"\";\n let inQuotes = false;\n\n for (let i = 0; i < content.length; i++) {\n const ch = content[i];\n if (inQuotes) {\n if (ch === '\"') {\n if (content[i + 1] === '\"') {\n field += '\"';\n i++;\n } else {\n inQuotes = false;\n }\n } else {\n field += ch;\n }\n } else {\n if (ch === '\"') {\n inQuotes = true;\n } else if (ch === \",\") {\n cur.push(field);\n field = \"\";\n } else if (ch === \"\\n\") {\n cur.push(field);\n rows.push(cur);\n cur = [];\n field = \"\";\n } else if (ch === \"\\r\") {\n // swallow; handled by the following \\n in CRLF, or treat lone \\r as line end\n if (content[i + 1] !== \"\\n\") {\n cur.push(field);\n rows.push(cur);\n cur = [];\n field = \"\";\n }\n } else {\n field += ch;\n }\n }\n }\n // flush trailing field/row\n if (field.length > 0 || cur.length > 0) {\n cur.push(field);\n rows.push(cur);\n }\n\n if (rows.length === 0) return [];\n const headers = rows[0]!.map((h) => h.trim());\n const out: Record<string, string>[] = [];\n for (let r = 1; r < rows.length; r++) {\n const row = rows[r]!;\n // skip blank trailing lines\n if (row.length === 1 && row[0] === \"\") continue;\n const obj: Record<string, string> = {};\n for (let c = 0; c < headers.length; c++) {\n obj[headers[c]!] = row[c] ?? \"\";\n }\n out.push(obj);\n }\n return out;\n}\n\nexport class Client {\n apiKey: string | undefined;\n baseUrl: string;\n tenant: string;\n\n constructor(opts: ClientOptions = {}) {\n // Resolution order for each field: explicit opts → env var → ~/.cograph/config.json\n // (written by `cograph login`) → built-in default. Reading the config eagerly\n // is cheap (small JSON file) and lets users skip env vars entirely after login.\n const cfg = readConfig();\n this.apiKey = opts.apiKey ?? envVar(\"API_KEY\") ?? cfg.apiKey;\n const url =\n opts.baseUrl ?? envVar(\"API_URL\") ?? cfg.apiUrl ?? \"https://api.cograph.cloud\";\n this.baseUrl = url.replace(/\\/+$/, \"\");\n this.tenant = opts.tenant ?? envVar(\"TENANT\") ?? cfg.tenant ?? \"demo-tenant\";\n }\n\n private headers(): Record<string, string> {\n const h: Record<string, string> = { \"Content-Type\": \"application/json\" };\n if (this.apiKey) h[\"X-API-Key\"] = this.apiKey;\n return h;\n }\n\n private base(): string {\n return `${this.baseUrl}/graphs/${this.tenant}`;\n }\n\n /**\n * Probe the backend to determine reachability and whether endpoints\n * require an X-API-Key header. Used at shell startup to distinguish\n * cloud (auth required) from self-hosted open-access deployments.\n */\n async healthCheck(): Promise<{\n ok: boolean;\n requiresAuth: boolean;\n url: string;\n }> {\n const healthUrl = `${this.baseUrl}/health`;\n try {\n const res = await fetch(healthUrl, {\n signal: AbortSignal.timeout(5000),\n });\n if (!res.ok) return { ok: false, requiresAuth: false, url: this.baseUrl };\n } catch {\n return { ok: false, requiresAuth: false, url: this.baseUrl };\n }\n // Probe whether endpoints require auth by hitting /kgs without X-API-Key.\n // 401 = requires auth; 200/empty = open access; anything else = treat as\n // auth-required to be safe.\n try {\n const res = await fetch(`${this.base()}/kgs`, {\n headers: { \"Content-Type\": \"application/json\" },\n signal: AbortSignal.timeout(5000),\n });\n return {\n ok: true,\n requiresAuth: res.status === 401,\n url: this.baseUrl,\n };\n } catch {\n return { ok: true, requiresAuth: true, url: this.baseUrl };\n }\n }\n\n private async request<T = unknown>(\n method: string,\n url: string,\n body?: unknown,\n timeoutMs: number = 120_000,\n ): Promise<T> {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), timeoutMs);\n let res: Response;\n try {\n res = await fetch(url, {\n method,\n headers: this.headers(),\n body: body === undefined ? undefined : JSON.stringify(body),\n signal: controller.signal,\n });\n } catch (err) {\n clearTimeout(timer);\n if (err instanceof Error && err.name === \"AbortError\") {\n throw new CographError(`Request to ${url} timed out after ${timeoutMs}ms`);\n }\n throw new CographError(\n `Network error contacting ${url}: ${err instanceof Error ? err.message : String(err)}`,\n );\n }\n clearTimeout(timer);\n\n if (!res.ok) {\n let text = \"\";\n try {\n text = await res.text();\n } catch {\n // ignore\n }\n throw new CographError(`HTTP ${res.status}: ${text}`, {\n status: res.status,\n body: text,\n });\n }\n\n // 204 No Content\n if (res.status === 204) return undefined as T;\n\n const ct = res.headers.get(\"content-type\") ?? \"\";\n if (ct.includes(\"application/json\")) {\n return (await res.json()) as T;\n }\n // fall back to text\n const text = await res.text();\n try {\n return JSON.parse(text) as T;\n } catch {\n return text as unknown as T;\n }\n }\n\n /**\n * Ingest a file path or raw text into a knowledge graph.\n *\n * If `pathOrText` points to an existing file, its contents are read and the\n * format is inferred from the extension (.csv, .json, .txt) unless\n * `contentType` is given. CSV files use the two-step schema-inference + row\n * mapping flow.\n */\n async ingest(\n pathOrText: string,\n opts: IngestOptions = {},\n ): Promise<Record<string, unknown>> {\n let content: string;\n let fmt: string;\n\n let isFile = false;\n try {\n isFile = existsSync(pathOrText) && statSync(pathOrText).isFile();\n } catch {\n isFile = false;\n }\n\n if (isFile) {\n const ext = extname(pathOrText).toLowerCase();\n if (ext === \".pdf\") {\n throw new CographError(\n \"PDF ingest not yet supported in the Node CLI; use the Python CLI or POST raw bytes to the API.\",\n );\n }\n content = readFileSync(pathOrText, \"utf-8\");\n fmt = opts.contentType ?? EXT_FORMAT[ext] ?? \"text\";\n if (fmt === \"csv\") {\n return this.ingestCsv(content, opts);\n }\n } else {\n content = pathOrText;\n fmt = opts.contentType ?? \"text\";\n }\n\n const body: Record<string, unknown> = {\n content,\n content_type: fmt,\n source: \"client\",\n };\n if (opts.kg) body.kg_name = opts.kg;\n return this.request(\"POST\", `${this.base()}/ingest`, body, 120_000);\n }\n\n private async ingestCsv(\n content: string,\n opts: IngestOptions,\n ): Promise<Record<string, unknown>> {\n const kgName = opts.kg;\n const batchSize = opts.batchSize ?? 200;\n const concurrency = opts.concurrency ?? 4;\n\n const rows = parseCsv(content);\n if (rows.length === 0) throw new CographError(\"CSV is empty\");\n const headers = Object.keys(rows[0]!);\n\n // Send the whole file to the profiler, evenly strided across it (never the\n // head — head-of-file bias, e.g. a key column that goes sparse later, is\n // exactly what evidence-grounded inference fixes). Profile fidelity =\n // decision quality. Mirrors the Explorer's upload flow.\n const sampleRows = stridedSample(rows);\n\n const schemaBody = {\n headers,\n sample_rows: sampleRows,\n total_rows: rows.length,\n };\n const mapping = await this.request<Record<string, unknown>>(\n \"POST\",\n `${this.base()}/ingest/csv/schema`,\n schemaBody,\n 300_000,\n );\n\n // Confirm/override gate (same contract as the Explorer's review step): the\n // caller inspects the inferred mapping and returns what to ingest, or null\n // to cancel before any rows are written. /ingest/csv/rows applies exactly\n // what we post back. When no hook is given, apply the inference as-is.\n let mappingToPost: Record<string, unknown> = mapping;\n if (opts.onSchemaInferred) {\n const reviewed = await opts.onSchemaInferred(mapping, {\n totalRows: rows.length,\n rowsProfiled: sampleRows.length,\n });\n if (reviewed == null) {\n return { cancelled: true, message: \"Ingest cancelled before any rows were written.\" };\n }\n mappingToPost = reviewed;\n }\n\n // Slice rows into batches up front so we can fire them off in a\n // bounded worker pool. Sequential 50-row batches over 891 rows took\n // ~60s end-to-end (18 round-trips); 200-row batches × 4 in flight\n // brings that to ~5s on the same backend.\n const batches: Array<Record<string, string>[]> = [];\n for (let i = 0; i < rows.length; i += batchSize) {\n batches.push(rows.slice(i, i + batchSize));\n }\n\n let totalEntities = 0;\n let totalTriples = 0;\n let rowsProcessed = 0;\n let nextBatch = 0;\n\n const postBatch = async (batch: Record<string, string>[]) => {\n const body: Record<string, unknown> = {\n mapping: mappingToPost,\n rows: batch,\n source: \"client\",\n };\n if (kgName) body.kg_name = kgName;\n const result = await this.request<{\n entities_resolved?: number;\n triples_inserted?: number;\n }>(\"POST\", `${this.base()}/ingest/csv/rows`, body, 300_000);\n return {\n entities: result.entities_resolved ?? 0,\n triples: result.triples_inserted ?? 0,\n size: batch.length,\n };\n };\n\n const worker = async (): Promise<void> => {\n while (true) {\n const idx = nextBatch++;\n if (idx >= batches.length) return;\n const r = await postBatch(batches[idx]!);\n totalEntities += r.entities;\n totalTriples += r.triples;\n rowsProcessed += r.size;\n opts.onProgress?.({\n rowsProcessed,\n totalRows: rows.length,\n entitiesResolved: totalEntities,\n triplesInserted: totalTriples,\n });\n }\n };\n\n const workers: Array<Promise<void>> = [];\n for (let i = 0; i < Math.min(concurrency, batches.length); i++) {\n workers.push(worker());\n }\n await Promise.all(workers);\n\n // All batches are in — kick off a background recompute of the Explorer\n // type-stats for this KG so type-detail views load instantly. The endpoint\n // returns immediately (the scan runs server-side in the background); this\n // is best-effort and never fails the ingest.\n if (kgName) {\n try {\n await this.request(\n \"POST\",\n `${this.base()}/explore/kgs/${encodeURIComponent(kgName)}/recompute-stats`,\n {},\n 15_000,\n );\n } catch {\n // non-fatal — stats fall back to a live scan until the next recompute\n }\n }\n\n return {\n entities_resolved: totalEntities,\n triples_inserted: totalTriples,\n mapping,\n };\n }\n\n /** Ask a natural language question and return the parsed response. */\n async ask(\n question: string,\n opts: AskOptions = {},\n ): Promise<Record<string, unknown>> {\n const body: Record<string, unknown> = { question };\n if (opts.kg) body.kg_name = opts.kg;\n if (opts.model) body.model = opts.model;\n return this.request(\"POST\", `${this.base()}/ask`, body, 60_000);\n }\n\n /** List the tenants the authenticated user can access (GET /v1/me/tenants).\n * Keyed by the API key (X-API-Key → user), so it's independent of the active\n * tenant. Throws CographError with status 501 on deployments without a tenant\n * provider (e.g. OSS-only). */\n async listTenants(): Promise<Array<{ id: string; label: string }>> {\n return this.request<Array<{ id: string; label: string }>>(\n \"GET\",\n `${this.baseUrl}/v1/me/tenants`,\n undefined,\n 15_000,\n );\n }\n\n /** List all knowledge graphs for the current tenant. */\n async listKgs(): Promise<Array<Record<string, unknown>>> {\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/kgs`,\n undefined,\n 15_000,\n );\n if (Array.isArray(data)) return data as Array<Record<string, unknown>>;\n if (data && typeof data === \"object\" && \"kgs\" in data) {\n const kgs = (data as { kgs?: unknown }).kgs;\n if (Array.isArray(kgs)) return kgs as Array<Record<string, unknown>>;\n }\n return [];\n }\n\n /** Create a knowledge graph. */\n async createKg(\n name: string,\n description?: string,\n ): Promise<Record<string, unknown>> {\n const body: Record<string, unknown> = { name };\n if (description) body.description = description;\n return this.request(\"POST\", `${this.base()}/kgs`, body, 15_000);\n }\n\n /** Delete a knowledge graph by name. */\n async deleteKg(name: string): Promise<Record<string, unknown>> {\n return this.request(\n \"DELETE\",\n `${this.base()}/kgs/${encodeURIComponent(name)}`,\n undefined,\n 30_000,\n );\n }\n\n /** List ontology types. */\n async ontologyTypes(): Promise<Array<Record<string, unknown>>> {\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/ontology/types`,\n undefined,\n 15_000,\n );\n return Array.isArray(data) ? (data as Array<Record<string, unknown>>) : [];\n }\n\n /**\n * Resolve a natural-language ontology change against the existing ontology.\n * The caller does not need to know exact type/attribute/relationship names —\n * the server matches the plain-language `ask` to the current schema and\n * returns auto-applied changes plus proposals that need confirmation.\n */\n async ontologyResolve(\n ask: string,\n opts: { knowledge_graph?: string } = {},\n ): Promise<OntologyResolveResult> {\n const body: Record<string, unknown> = { ask };\n if (opts.knowledge_graph) body.knowledge_graph = opts.knowledge_graph;\n return this.request<OntologyResolveResult>(\n \"POST\",\n `${this.base()}/ontology/resolve`,\n body,\n 60_000,\n );\n }\n\n /**\n * Apply a single resolved ontology change — one of the `proposals` returned\n * by {@link ontologyResolve}. Pass the proposal object through unchanged.\n */\n async ontologyApply(\n proposal: ResolvedChange,\n ): Promise<OntologyApplyResult> {\n return this.request<OntologyApplyResult>(\n \"POST\",\n `${this.base()}/ontology/apply`,\n proposal,\n 60_000,\n );\n }\n\n /**\n * Second-pass entity resolution: re-run ER over an already-ingested KG to\n * collapse intra-batch fragments. Synchronous on the server; returns a\n * per-type before/after report. Generous timeout — it rewrites triples.\n */\n async erRebuild(kg: string): Promise<Record<string, unknown>> {\n return this.request<Record<string, unknown>>(\n \"POST\",\n `${this.base()}/explore/kgs/${encodeURIComponent(kg)}/er-rebuild`,\n {},\n 300_000,\n );\n }\n\n /** Per-KG type counts: every type with ≥1 instance, sorted desc. */\n async typeCounts(kg: string): Promise<TypeCount[]> {\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/kgs/${encodeURIComponent(kg)}/type-counts`,\n undefined,\n 30_000,\n );\n return Array.isArray(data) ? (data as TypeCount[]) : [];\n }\n\n /** Plan + run an enrichment job. Returns immediately with the job id. */\n async enrichRun(req: EnrichRequest): Promise<EnrichJobCreate> {\n return this.request<EnrichJobCreate>(\n \"POST\",\n `${this.base()}/enrich/jobs`,\n req,\n 30_000,\n );\n }\n\n /** List recent enrichment jobs for the current tenant. */\n async enrichJobs(): Promise<JobSummary[]> {\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/enrich/jobs`,\n undefined,\n 15_000,\n );\n return Array.isArray(data) ? (data as JobSummary[]) : [];\n }\n\n /** Fetch a single enrichment job (with truncated results). */\n async enrichJob(jobId: string): Promise<EnrichJob> {\n return this.request<EnrichJob>(\n \"GET\",\n `${this.base()}/enrich/jobs/${encodeURIComponent(jobId)}`,\n undefined,\n 15_000,\n );\n }\n\n /** Fetch the conflict review queue for a job. */\n async enrichConflicts(jobId: string): Promise<ConflictReview[]> {\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/enrich/jobs/${encodeURIComponent(jobId)}/conflicts`,\n undefined,\n 30_000,\n );\n return Array.isArray(data) ? (data as ConflictReview[]) : [];\n }\n\n /** Apply a set of conflict review decisions to a job. */\n async enrichApply(\n jobId: string,\n decisions: ConflictReview[],\n ): Promise<{ applied: number }> {\n return this.request<{ applied: number }>(\n \"POST\",\n `${this.base()}/enrich/jobs/${encodeURIComponent(jobId)}/apply`,\n { decisions },\n 60_000,\n );\n }\n\n /** Cancel an enrichment job. */\n async enrichCancel(jobId: string): Promise<void> {\n await this.request<void>(\n \"DELETE\",\n `${this.base()}/enrich/jobs/${encodeURIComponent(jobId)}`,\n undefined,\n 15_000,\n );\n }\n\n /** Per-type breakdown for one type in one KG: definition + counts + samples.\n *\n * System predicates (rdfs:label, ingested_at, source) are hidden by default\n * — they're attached to every entity at 100% and drown out the columns the\n * user cares about. Pass `includeSystem: true` to see them. */\n async typeUsage(\n kg: string,\n typeName: string,\n opts: { includeSystem?: boolean } = {},\n ): Promise<TypeUsage> {\n const qs = opts.includeSystem ? \"?include_system=true\" : \"\";\n return this.request<TypeUsage>(\n \"GET\",\n `${this.base()}/kgs/${encodeURIComponent(kg)}/types/${encodeURIComponent(typeName)}/usage${qs}`,\n undefined,\n 30_000,\n );\n }\n\n /** Explorer summary for a type — like typeUsage but adds coverage_pct + avg_degree. */\n async typeSummary(kg: string, typeName: string): Promise<TypeSummary> {\n return this.request<TypeSummary>(\n \"GET\",\n `${this.base()}/explore/kgs/${encodeURIComponent(kg)}/types/${encodeURIComponent(typeName)}/summary`,\n undefined,\n 30_000,\n );\n }\n\n /** Search types or attributes by name substring within a KG. */\n async exploreSearch(\n kg: string,\n q: string,\n kind: \"type\" | \"attr\" = \"type\",\n ): Promise<Array<Record<string, unknown>>> {\n const qs = new URLSearchParams({ kg, q, kind }).toString();\n const data = await this.request<unknown>(\n \"GET\",\n `${this.base()}/explore/search?${qs}`,\n undefined,\n 15_000,\n );\n return Array.isArray(data) ? (data as Array<Record<string, unknown>>) : [];\n }\n}\n\n/**\n * A single ontology change resolved against the existing schema. The same\n * shape is returned under `applied`/`proposals` by {@link Client.ontologyResolve}\n * and accepted as the request body by {@link Client.ontologyApply}.\n */\nexport interface ResolvedChange {\n kind: \"attribute\" | \"relationship\";\n subject_type: string;\n name: string;\n datatype_or_target: string;\n action: \"reuse\" | \"extend\" | \"create\";\n confidence: number;\n reason: string;\n}\n\nexport interface OntologyResolveResult {\n applied: ResolvedChange[];\n proposals: ResolvedChange[];\n summary: string;\n}\n\nexport interface OntologyApplyResult {\n applied: ResolvedChange;\n operations: number;\n summary: string;\n}\n\nexport interface TypeCount {\n name: string;\n entity_count: number;\n}\n\nexport interface AttributeUsage {\n name: string;\n datatype: string;\n count: number;\n}\n\nexport interface RelationshipUsage {\n name: string;\n target_type: string | null;\n count: number;\n}\n\nexport interface EntitySample {\n uri: string;\n label: string;\n}\n\nexport interface TypeUsage {\n name: string;\n description: string;\n parent_type: string | null;\n entity_count: number;\n attributes: AttributeUsage[];\n relationships: RelationshipUsage[];\n samples: EntitySample[];\n}\n\nexport interface AttributeSummary {\n name: string;\n predicate_uri: string;\n datatype: string;\n count: number;\n coverage_pct: number;\n}\n\nexport interface RelationshipSummary {\n name: string;\n predicate_uri: string;\n target_type: string | null;\n count: number;\n coverage_pct: number;\n avg_degree: number;\n}\n\nexport interface TypeSummary {\n name: string;\n description: string;\n parent_type: string | null;\n entity_count: number;\n attributes: AttributeSummary[];\n relationships: RelationshipSummary[];\n}\n\nexport type EnrichmentTier = \"lite\" | \"base\" | \"core\" | \"pro\";\nexport type JobStatus =\n | \"queued\"\n | \"running\"\n | \"review\"\n | \"applied\"\n | \"cancelled\"\n | \"failed\";\nexport type ConflictPolicy = \"skip\" | \"verify\" | \"overwrite\" | \"stage\";\nexport type RowAction =\n | \"filled\"\n | \"verified\"\n | \"conflict\"\n | \"skipped\"\n | \"no_match\";\nexport type ReviewDecision = \"accept\" | \"reject\" | \"skip\";\n\nexport interface EnrichRequest {\n type_name: string;\n attributes: string[];\n tier?: EnrichmentTier;\n kg_name: string;\n conflict_policy?: ConflictPolicy;\n confidence_min?: number;\n limit?: number;\n}\n\nexport interface EnrichJobCreate {\n job_id: string;\n status: JobStatus;\n estimated_cost_usd: number;\n total_entities: number;\n}\n\nexport interface Verdict {\n value: string;\n confidence: number;\n source: string;\n source_url?: string | null;\n reasoning?: string | null;\n}\n\nexport interface JobProgress {\n total: number;\n processed: number;\n filled: number;\n verified: number;\n conflicts: number;\n skipped: number;\n cache_hits: number;\n}\n\nexport interface RowResult {\n entity_uri: string;\n attribute: string;\n existing_value: string | null;\n verdict: Verdict | null;\n action: RowAction;\n}\n\nexport interface JobSummary {\n id: string;\n tenant_id: string;\n kg_name: string;\n type_name: string;\n attributes: string[];\n tier: EnrichmentTier;\n status: JobStatus;\n progress: JobProgress;\n created_at: string;\n started_at?: string | null;\n completed_at?: string | null;\n conflict_policy: ConflictPolicy;\n confidence_min: number;\n error?: string | null;\n}\n\nexport interface EnrichJob extends JobSummary {\n results?: RowResult[];\n limit?: number | null;\n}\n\nexport interface ConflictReview {\n entity_uri: string;\n attribute: string;\n existing_value: string;\n proposed: Verdict;\n decision?: ReviewDecision | null;\n}\n"],"mappings":";;;;;;AAAA,SAAS,YAAY,cAAc,gBAAgB;AACnD,SAAS,eAAe;AAGjB,IAAM,eAAN,cAA2B,MAAM;AAAA,EACtC;AAAA,EACA;AAAA,EAEA,YAAY,SAAiB,MAA2C;AACtE,UAAM,OAAO;AACb,SAAK,OAAO;AACZ,SAAK,SAAS,MAAM;AACpB,SAAK,OAAO,MAAM;AAAA,EACpB;AACF;AA0CO,IAAM,oBAAoB;AAEjC,SAAS,cAAiB,MAAW,MAAc,mBAAwB;AACzE,MAAI,KAAK,UAAU,IAAK,QAAO;AAC/B,QAAM,MAAW,CAAC;AAClB,WAAS,IAAI,GAAG,IAAI,KAAK,IAAK,KAAI,KAAK,KAAK,KAAK,MAAO,IAAI,KAAK,SAAU,GAAG,CAAC,CAAE;AACjF,SAAO;AACT;AAOA,SAAS,OAAO,MAAc,UAAuC;AAEnE,SACE,QAAQ,IAAI,WAAW,IAAI,EAAE,KAC7B,QAAQ,IAAI,SAAS,IAAI,EAAE,KAC3B;AAEJ;AAEA,IAAM,aAAqC;AAAA,EACzC,QAAQ;AAAA,EACR,SAAS;AAAA,EACT,UAAU;AAAA,EACV,QAAQ;AACV;AASO,SAAS,SAAS,SAA2C;AAClE,QAAM,OAAmB,CAAC;AAC1B,MAAI,MAAgB,CAAC;AACrB,MAAI,QAAQ;AACZ,MAAI,WAAW;AAEf,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,KAAK,QAAQ,CAAC;AACpB,QAAI,UAAU;AACZ,UAAI,OAAO,KAAK;AACd,YAAI,QAAQ,IAAI,CAAC,MAAM,KAAK;AAC1B,mBAAS;AACT;AAAA,QACF,OAAO;AACL,qBAAW;AAAA,QACb;AAAA,MACF,OAAO;AACL,iBAAS;AAA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jB;AACpB,UAAM,KAAK,KAAK,gBAAgB,yBAAyB;AACzD,WAAO,KAAK;AAAA,MACV;AAAA,MACA,GAAG,KAAK,KAAK,CAAC,QAAQ,mBAAmB,EAAE,CAAC,UAAU,mBAAmB,QAAQ,CAAC,SAAS,EAAE;AAAA,MAC7F;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,YAAY,IAAY,UAAwC;AACpE,WAAO,KAAK;AAAA,MACV;AAAA,MACA,GAAG,KAAK,KAAK,CAAC,gBAAgB,mBAAmB,EAAE,CAAC,UAAU,mBAAmB,QAAQ,CAAC;AAAA,MAC1F;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAAA;AAAA,EAGA,MAAM,cACJ,IACA,GACA,OAAwB,QACiB;AACzC,UAAM,KAAK,IAAI,gBAAgB,EAAE,IAAI,GAAG,KAAK,CAAC,EAAE,SAAS;AACzD,UAAM,OAAO,MAAM,KAAK;AAAA,MACtB;AAAA,MACA,GAAG,KAAK,KAAK,CAAC,mBAAmB,EAAE;AAAA,MACnC;AAAA,MACA;AAAA,IACF;AACA,WAAO,MAAM,QAAQ,IAAI,IAAK,OAA0C,CAAC;AAAA,EAC3E;AACF;","names":["text"]}
package/dist/cli.js CHANGED
@@ -2,8 +2,12 @@
2
2
  import {
3
3
  Client,
4
4
  CographError
5
- } from "./chunk-X7YVTWAD.js";
6
- import "./chunk-7VVBEUZQ.js";
5
+ } from "./chunk-YFM3KDCO.js";
6
+ import {
7
+ configPathForDisplay,
8
+ readConfig,
9
+ writeConfig
10
+ } from "./chunk-7VVBEUZQ.js";
7
11
 
8
12
  // src/cli.ts
9
13
  import { createInterface } from "readline";
@@ -21,7 +25,11 @@ function pkgVersion() {
21
25
  }
22
26
  }
23
27
  function client() {
24
- return new Client();
28
+ const g = program.opts();
29
+ return new Client({
30
+ ...g.tenant ? { tenant: g.tenant } : {},
31
+ ...g.local ? { baseUrl: "http://localhost:8000" } : {}
32
+ });
25
33
  }
26
34
  function fail(msg, code = 1) {
27
35
  process.stderr.write(msg.endsWith("\n") ? msg : msg + "\n");
@@ -46,9 +54,144 @@ async function confirm(prompt) {
46
54
  });
47
55
  });
48
56
  }
57
+ async function confirmYes(prompt) {
58
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
59
+ return new Promise((resolve) => {
60
+ rl.question(`${prompt} [Y/n] `, (ans) => {
61
+ rl.close();
62
+ const a = ans.trim().toLowerCase();
63
+ resolve(a === "" || a === "y" || a === "yes");
64
+ });
65
+ });
66
+ }
67
+ var useColor = Boolean(process.stdout.isTTY) && !process.env.NO_COLOR;
68
+ var sgr = (code) => (s) => useColor ? `\x1B[${code}m${s}\x1B[0m` : s;
69
+ var bold = sgr("1");
70
+ var dim = sgr("2");
71
+ function entityViews(m) {
72
+ if (Array.isArray(m.entities) && m.entities.length > 0) {
73
+ return m.entities.map((e) => ({
74
+ name: e.name,
75
+ type_name: e.type_name,
76
+ id_column: e.id_column,
77
+ id_from: e.id_from,
78
+ key_strategy: e.key_strategy ?? null,
79
+ confidence: e.confidence,
80
+ why: e.why
81
+ }));
82
+ }
83
+ return [
84
+ {
85
+ name: m.entity_type,
86
+ type_name: m.entity_type,
87
+ key_strategy: m.key_strategy ?? null,
88
+ confidence: m.confidence,
89
+ why: m.why
90
+ }
91
+ ];
92
+ }
93
+ function heldTypes(m) {
94
+ const types = m.ontology_extensions?.types;
95
+ return Array.isArray(types) ? types.filter((t) => t.held_for_review) : [];
96
+ }
97
+ function buildMappingForIngest(m, approved) {
98
+ const out = { entity_type: m.entity_type, columns: m.columns };
99
+ if (m.entities) out.entities = m.entities;
100
+ if (m.relationships) out.relationships = m.relationships;
101
+ const types = m.ontology_extensions?.types;
102
+ if (Array.isArray(types)) {
103
+ out.ontology_extensions = {
104
+ types: types.filter(
105
+ (t) => !t.held_for_review || approved.has(t.type_name)
106
+ )
107
+ };
108
+ }
109
+ return out;
110
+ }
111
+ function fmtConf(v) {
112
+ if (v == null) return "";
113
+ const n = Number(v);
114
+ if (Number.isNaN(n)) return "";
115
+ return dim(` (${n.toFixed(2)}${n < 0.7 ? " !" : ""})`);
116
+ }
117
+ function renderMapping(m, info) {
118
+ const w = (s) => process.stdout.write(s);
119
+ w(
120
+ "\n" + bold("Proposed schema") + dim(
121
+ ` (profiled ${info.rowsProfiled.toLocaleString()} of ${info.totalRows.toLocaleString()} rows)`
122
+ ) + "\n"
123
+ );
124
+ w(dim("Review how the data maps to the graph before any rows are written.") + "\n\n");
125
+ const ents = entityViews(m);
126
+ const multi = Array.isArray(m.entities) && m.entities.length > 0;
127
+ w(bold("Entities & keys") + "\n");
128
+ for (const e of ents) {
129
+ const key = e.id_column ? `key: ${e.id_column}` : e.id_from && e.id_from.length ? `key: ${e.id_from.join(" + ")}` : e.key_strategy === "synthetic" ? "key: (synthetic)" : "key: \u2014";
130
+ w(` \u2022 ${bold(e.type_name)} ${dim(key)}${fmtConf(e.confidence)}
131
+ `);
132
+ if (e.why) w(` ${dim(e.why)}
133
+ `);
134
+ const cols = (m.columns ?? []).filter(
135
+ (col) => multi ? col.entity === e.name : true
136
+ );
137
+ for (const col of cols) {
138
+ const role = col.role === "type_id" ? "key " : col.role === "relationship" ? "edge" : "attr";
139
+ let detail = "";
140
+ if (col.role === "relationship" && col.target_type)
141
+ detail = ` \u2192 ${col.target_type}`;
142
+ else if (col.role === "attribute" && col.attribute_name && col.attribute_name !== col.column_name)
143
+ detail = ` as ${col.attribute_name}`;
144
+ const dt = col.datatype && col.datatype !== "string" ? " " + dim(`[${col.datatype}]`) : "";
145
+ w(
146
+ ` ${dim("[" + role + "]")} ${col.column_name}${detail}${dt}${fmtConf(col.confidence)}
147
+ `
148
+ );
149
+ }
150
+ }
151
+ const rels = m.relationships ?? [];
152
+ if (rels.length) {
153
+ w("\n" + bold("Edges") + "\n");
154
+ for (const r of rels)
155
+ w(` \u2022 ${r.subject} ${dim(r.predicate)} ${r.object}${fmtConf(r.confidence)}
156
+ `);
157
+ }
158
+ const vio = m.violations ?? [];
159
+ if (vio.length) {
160
+ w(
161
+ "\n" + dim(
162
+ `Refute pass corrected ${vio.length} issue${vio.length === 1 ? "" : "s"}: ${vio.map((v) => v.template).join(", ")}`
163
+ ) + "\n"
164
+ );
165
+ }
166
+ }
167
+ async function reviewMapping(m, info) {
168
+ renderMapping(m, info);
169
+ const approved = /* @__PURE__ */ new Set();
170
+ const held = heldTypes(m);
171
+ if (held.length) {
172
+ process.stdout.write(
173
+ "\n" + bold(`${held.length} new type${held.length === 1 ? "" : "s"} held for review`) + dim(" \u2014 approve to create, or skip to leave for later") + "\n"
174
+ );
175
+ for (const t of held) {
176
+ const from = t.promoted_from_attribute ? dim(` (from "${t.promoted_from_attribute}")`) : "";
177
+ process.stdout.write(` \u2022 ${t.type_name}${from}${fmtConf(t.confidence)}
178
+ `);
179
+ if (await confirm(` Approve "${t.type_name}"?`)) approved.add(t.type_name);
180
+ }
181
+ }
182
+ process.stdout.write("\n");
183
+ const ok = await confirmYes(
184
+ `Apply this mapping and ingest ${info.totalRows.toLocaleString()} rows?`
185
+ );
186
+ if (!ok) return null;
187
+ return buildMappingForIngest(m, approved);
188
+ }
49
189
  var program = new Command();
50
- program.name("cograph").description("Cograph Knowledge Graph CLI").version(pkgVersion()).option("--local", "Use http://localhost:8000 and skip login (self-hosted)").option("--no-login", "Skip browser login (assume open-access backend)").action(async (opts) => {
51
- const { runShell } = await import("./shell-YE3K2LYX.js");
190
+ program.name("cograph").description("Cograph Knowledge Graph CLI").version(pkgVersion()).option("--local", "Use http://localhost:8000 and skip login (self-hosted)").option("--no-login", "Skip browser login (assume open-access backend)").option(
191
+ "--tenant <id>",
192
+ "Target a specific tenant for this command (overrides the saved default)"
193
+ ).action(async (opts) => {
194
+ const { runShell } = await import("./shell-2NGJGEKC.js");
52
195
  await runShell({
53
196
  local: opts.local,
54
197
  // commander's --no-login inverts: opts.login === false when flag passed.
@@ -90,9 +233,60 @@ kg.command("delete <name>").description("Delete a knowledge graph").action(async
90
233
  `);
91
234
  });
92
235
  });
236
+ var tenantCmd = program.command("tenant").description("Show or switch the active tenant");
237
+ tenantCmd.command("current", { isDefault: true }).description("Show the active tenant").action(() => {
238
+ const active = client().tenant;
239
+ const saved = readConfig().tenant;
240
+ process.stdout.write(`Active tenant: ${bold(active)}
241
+ `);
242
+ process.stdout.write(
243
+ saved ? dim(` saved default in ${configPathForDisplay()}
244
+ `) : dim(` (built-in default \u2014 set one with: cograph tenant use <id>)
245
+ `)
246
+ );
247
+ });
248
+ tenantCmd.command("list").description("List the tenants you can access").action(async () => {
249
+ await withErrors(async () => {
250
+ const c = client();
251
+ let tenants;
252
+ try {
253
+ tenants = await c.listTenants();
254
+ } catch (err) {
255
+ if (err instanceof CographError && err.status === 501) {
256
+ fail(
257
+ "This backend doesn't support tenant management (no tenant provider configured)."
258
+ );
259
+ }
260
+ throw err;
261
+ }
262
+ if (!tenants.length) {
263
+ process.stdout.write("No tenants found for your account.\n");
264
+ return;
265
+ }
266
+ const active = c.tenant;
267
+ for (const t of tenants) {
268
+ const marker = t.id === active ? "*" : " ";
269
+ process.stdout.write(` ${marker} ${t.id.padEnd(24)} ${dim(t.label)}
270
+ `);
271
+ }
272
+ process.stdout.write(dim(`
273
+ Switch with: cograph tenant use <id>
274
+ `));
275
+ });
276
+ });
277
+ tenantCmd.command("use <id>").description("Set the active tenant (saved to ~/.cograph/config.json)").action((id) => {
278
+ writeConfig({ tenant: id });
279
+ process.stdout.write(`${bold("\u2713")} Active tenant set to ${bold(id)}
280
+ `);
281
+ process.stdout.write(dim(`Saved to ${configPathForDisplay()}
282
+ `));
283
+ });
93
284
  program.command("ingest [file]").description("Ingest data from a file or --text").option("-t, --text <text>", "Inline text to ingest").option("--kg <name>", "Target knowledge graph name").option(
94
285
  "-f, --format <fmt>",
95
286
  "Override format detection (text|csv|json)"
287
+ ).option(
288
+ "-y, --yes",
289
+ "Skip the CSV schema review and apply the inferred mapping non-interactively"
96
290
  ).action(
97
291
  async (file, opts) => {
98
292
  await withErrors(async () => {
@@ -112,12 +306,24 @@ program.command("ingest [file]").description("Ingest data from a file or --text"
112
306
  if (!file) {
113
307
  fail("Provide a file or --text");
114
308
  }
309
+ const interactive = Boolean(process.stdin.isTTY) && Boolean(process.stdout.isTTY) && !opts.yes;
310
+ const onSchemaInferred = interactive ? reviewMapping : (m) => Promise.resolve(
311
+ buildMappingForIngest(
312
+ m,
313
+ new Set(heldTypes(m).map((t) => t.type_name))
314
+ )
315
+ );
115
316
  process.stdout.write(`Ingesting ${file}...
116
317
  `);
117
318
  const result = await c.ingest(file, {
118
319
  kg: opts.kg,
119
- contentType: opts.format
320
+ contentType: opts.format,
321
+ onSchemaInferred
120
322
  });
323
+ if (result.cancelled) {
324
+ process.stdout.write("Cancelled \u2014 nothing was written.\n");
325
+ return;
326
+ }
121
327
  printIngestResult(result);
122
328
  });
123
329
  }
@@ -436,7 +642,7 @@ program.command("login").description("Sign in via your browser and save an API k
436
642
  program.command("shell").description("Start an interactive REPL").option("--kg <name>", "Knowledge graph to use").option("--local", "Use http://localhost:8000 and skip login (self-hosted)").option("--no-login", "Skip browser login (assume open-access backend)").action(
437
643
  async (opts) => {
438
644
  const parentOpts = program.opts();
439
- const { runShell } = await import("./shell-YE3K2LYX.js");
645
+ const { runShell } = await import("./shell-2NGJGEKC.js");
440
646
  await runShell({
441
647
  kg: opts.kg,
442
648
  local: opts.local || parentOpts.local,