doc2vec 2.10.6 → 2.12.0

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
@@ -52,6 +52,7 @@ The primary goal is to prepare documentation content for Retrieval-Augmented Gen
52
52
  * **Incremental Updates:** For GitHub and Zendesk sources, tracks the last run date to only fetch new or updated issues/tickets.
53
53
  * **Cleanup:** Removes obsolete chunks from the database corresponding to pages or files that are no longer found during processing.
54
54
  * **Configuration:** Driven by a YAML configuration file (`config.yaml`) specifying sites, repositories, local directories, Zendesk instances, database types, metadata, and other parameters.
55
+ * **[Controller Mode](#controller-mode):** Optionally runs as a long-lived controller that schedules sync jobs from multiple config files (cron `schedule` field), persists run history and statistics in Postgres, and serves a web UI with live log streaming — read-only (configs from files/ConfigMap) or read-write (create/edit configs from the UI).
55
56
  * **Structured Logging:** Uses a custom logger (`logger.ts`) with levels, timestamps, colors, progress bars, and child loggers for clear execution monitoring.
56
57
 
57
58
  ## Chunk Metadata & Page Reconstruction
@@ -437,6 +438,103 @@ The script will then:
437
438
  7. Cleanup obsolete chunks.
438
439
  8. Output detailed logs.
439
440
 
441
+ ## Controller Mode
442
+
443
+ Besides the one-shot sync, doc2vec can run as a **long-lived controller** that schedules sync jobs, records run history and statistics in Postgres, and serves a web UI for monitoring and managing configs:
444
+
445
+ ```bash
446
+ doc2vec controller --database-url postgres://user:pass@host:5432/doc2vec ./configs/
447
+ ```
448
+
449
+ Open http://localhost:8080 to see the dashboard: configs with their schedule and next run, run history with per-source statistics, and live log streaming for running jobs.
450
+
451
+ ### Scheduling
452
+
453
+ Add a top-level cron `schedule` (and optionally a display `name`) to a config file, and the controller runs it automatically:
454
+
455
+ ```yaml
456
+ name: product-docs
457
+ schedule: "0 2 * * *" # every day at 02:00
458
+ sources:
459
+ - type: website
460
+ ...
461
+ ```
462
+
463
+ Configs without a `schedule` are still listed in the UI and can be triggered manually with **Run now**. Each run executes `doc2vec run <config.yaml>` as a child process; overlapping runs of the same config are skipped, and `--max-parallel` (default 1) caps how many sync jobs run at once — keep it low, since website sources launch a headless Chromium.
464
+
465
+ ### Flags
466
+
467
+ | Flag | Default | Description |
468
+ |------|---------|-------------|
469
+ | `--database-url <url>` | `DATABASE_URL` env | Postgres connection string (required) |
470
+ | `--port <n>` | `8080` (or `PORT`) | HTTP port for the API and UI |
471
+ | `--read-write` | off (read-only) | Allow creating/editing/deleting configs from the UI |
472
+ | `--config-dir <dir>` | — | Where UI-created configs are written (required with `--read-write`) |
473
+ | `--max-parallel <n>` | `1` | Max concurrent sync jobs |
474
+ | `--reload-interval <s>` | `30` | How often config files are re-read for changes |
475
+ | `--log-retention-days <n>` | `14` | Run logs older than this are pruned (run history is kept) |
476
+ | `--slack-webhook-url <url>` | `SLACK_WEBHOOK_URL` env | Slack incoming webhook — post a message when a run finishes |
477
+ | `--slack-notify <mode>` | `all` | `all` or `failures` (failures also covers canceled runs) |
478
+ | `--public-url <url>` | `PUBLIC_URL` env | Externally reachable base URL, used for "view run" links in notifications |
479
+
480
+ Positional arguments are config files and/or directories (directories are scanned for `*.yaml`/`*.yml`, and re-scanned on every reload).
481
+
482
+ ### Slack notifications
483
+
484
+ With `--slack-webhook-url` (or `SLACK_WEBHOOK_URL`) set, the controller posts to a [Slack incoming webhook](https://api.slack.com/messaging/webhooks) whenever a run reaches a terminal state — ✅ succeeded, ❌ failed (naming the failing sources and their errors), or ⚠️ canceled. Overlap-`skipped` runs are not notified. Set `--slack-notify failures` to silence successes, and `--public-url https://doc2vec.example.com` to get clickable "view run" links.
485
+
486
+ ### Read-only vs read-write
487
+
488
+ - **Read-only** (default): configs come solely from the files passed on the command line — ideal for Kubernetes, where they live in a ConfigMap. The UI can view configs, trigger runs, and browse history/stats, but not modify anything. ConfigMap updates are picked up automatically via content-hash polling.
489
+ - **Read-write** (`--read-write --config-dir ./configs`): the UI can also create, edit, and delete config YAML files. Files stay the source of truth on disk; concurrent edits are protected by a content-hash check.
490
+
491
+ In both modes the UI always shows raw YAML: `${ENV_VAR}` secret placeholders are **never** resolved outside the sync job itself.
492
+
493
+ ### Kubernetes example
494
+
495
+ ```yaml
496
+ apiVersion: apps/v1
497
+ kind: Deployment
498
+ metadata:
499
+ name: doc2vec-controller
500
+ spec:
501
+ replicas: 1 # keep a single replica: the scheduler is not distributed
502
+ selector:
503
+ matchLabels: { app: doc2vec-controller }
504
+ template:
505
+ metadata:
506
+ labels: { app: doc2vec-controller }
507
+ spec:
508
+ containers:
509
+ - name: controller
510
+ image: ghcr.io/kagent-dev/doc2vec:latest
511
+ command: ["node", "dist/doc2vec.js", "controller", "/etc/doc2vec"]
512
+ ports:
513
+ - containerPort: 8080
514
+ env:
515
+ - name: DATABASE_URL
516
+ valueFrom:
517
+ secretKeyRef: { name: doc2vec-secrets, key: database-url }
518
+ - name: OPENAI_API_KEY
519
+ valueFrom:
520
+ secretKeyRef: { name: doc2vec-secrets, key: openai-api-key }
521
+ volumeMounts:
522
+ - name: configs
523
+ mountPath: /etc/doc2vec
524
+ resources:
525
+ requests: { memory: 1Gi }
526
+ limits: { memory: 4Gi } # website sources launch headless Chromium
527
+ volumes:
528
+ - name: configs
529
+ configMap: { name: doc2vec-configs }
530
+ ```
531
+
532
+ The controller detects ConfigMap updates without a restart. Health endpoint: `GET /api/health`.
533
+
534
+ ### API
535
+
536
+ The UI is backed by a small REST API you can also use directly: `GET /api/configs`, `POST /api/configs/:id/run`, `GET /api/runs?configId=`, `GET /api/runs/:id/logs`, `POST /api/runs/:id/cancel`, `GET /api/configs/:id/stats?days=30`, plus server-sent events at `GET /api/events` and `GET /api/runs/:id/logs/stream`.
537
+
440
538
  ## Database Options
441
539
 
442
540
  ### SQLite (`database_config.type: 'sqlite'`)
@@ -36,7 +36,8 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
38
  Object.defineProperty(exports, "__esModule", { value: true });
39
- exports.ContentProcessor = void 0;
39
+ exports.ContentProcessor = exports.BrowserLaunchError = void 0;
40
+ exports.resolveBrowserExecutablePath = resolveBrowserExecutablePath;
40
41
  const readability_1 = require("@mozilla/readability");
41
42
  const axios_1 = __importDefault(require("axios"));
42
43
  const cheerio_1 = require("cheerio");
@@ -48,6 +49,97 @@ const fs = __importStar(require("fs"));
48
49
  const path = __importStar(require("path"));
49
50
  const utils_1 = require("./utils");
50
51
  const code_chunker_1 = require("./code-chunker");
52
+ /**
53
+ * Thrown when the browser cannot be launched at all (even after a retry).
54
+ * Without a browser no page in the crawl can be processed, so this aborts the
55
+ * whole website source — the run is then reported as failed instead of
56
+ * "succeeding" with an error on every URL.
57
+ */
58
+ class BrowserLaunchError extends Error {
59
+ constructor(message) {
60
+ super(message);
61
+ this.name = 'BrowserLaunchError';
62
+ }
63
+ }
64
+ exports.BrowserLaunchError = BrowserLaunchError;
65
+ /**
66
+ * Resolve which browser binary to launch, in order of preference:
67
+ * 1. PUPPETEER_EXECUTABLE_PATH (explicit override)
68
+ * 2. Puppeteer's own downloaded Chrome for Testing (version-matched, the
69
+ * reliable choice — Debian's chromium package has shipped builds that
70
+ * crash at startup in containers, e.g. 150.0.7871 SIGTRAPs immediately)
71
+ * 3. A system chromium, as the fallback (also covers linux/arm64, where
72
+ * Chrome for Testing is not published)
73
+ * 4. undefined — let puppeteer decide
74
+ */
75
+ function resolveBrowserExecutablePath() {
76
+ const override = process.env.PUPPETEER_EXECUTABLE_PATH;
77
+ if (override)
78
+ return override;
79
+ try {
80
+ const bundled = puppeteer_1.default.executablePath();
81
+ if (bundled && fs.existsSync(bundled))
82
+ return bundled;
83
+ }
84
+ catch {
85
+ // no browser downloaded for this platform
86
+ }
87
+ if (fs.existsSync('/usr/bin/chromium'))
88
+ return '/usr/bin/chromium';
89
+ if (fs.existsSync('/usr/bin/chromium-browser'))
90
+ return '/usr/bin/chromium-browser';
91
+ return undefined;
92
+ }
93
+ /**
94
+ * Best-effort snapshot of process + container memory, for diagnosing browser
95
+ * launch failures (the usual cause in Kubernetes is the pod's memory cgroup —
96
+ * Chromium forks, then its renderers are immediately OOM-killed).
97
+ */
98
+ function memoryDiagnostics() {
99
+ const gib = (bytes) => `${(bytes / 1024 ** 3).toFixed(2)}GiB`;
100
+ const parts = [`node rss ${gib(process.memoryUsage().rss)}`];
101
+ try {
102
+ // cgroup v2, else v1 — absent entirely outside Linux/containers
103
+ let current;
104
+ let max;
105
+ if (fs.existsSync('/sys/fs/cgroup/memory.current')) {
106
+ current = fs.readFileSync('/sys/fs/cgroup/memory.current', 'utf8').trim();
107
+ max = fs.readFileSync('/sys/fs/cgroup/memory.max', 'utf8').trim();
108
+ }
109
+ else if (fs.existsSync('/sys/fs/cgroup/memory/memory.usage_in_bytes')) {
110
+ current = fs.readFileSync('/sys/fs/cgroup/memory/memory.usage_in_bytes', 'utf8').trim();
111
+ max = fs.readFileSync('/sys/fs/cgroup/memory/memory.limit_in_bytes', 'utf8').trim();
112
+ }
113
+ if (current !== undefined && max !== undefined) {
114
+ const unlimited = max === 'max' || Number(max) > 2 ** 60;
115
+ parts.push(`cgroup ${gib(Number(current))} used / ${unlimited ? 'no limit' : gib(Number(max))}`);
116
+ }
117
+ }
118
+ catch {
119
+ // diagnostics only — never fail because of them
120
+ }
121
+ try {
122
+ // /proc/meminfo reflects the NODE in Kubernetes — catches host-level pressure
123
+ const meminfo = fs.readFileSync('/proc/meminfo', 'utf8');
124
+ const available = meminfo.match(/^MemAvailable:\s+(\d+) kB/m);
125
+ if (available) {
126
+ parts.push(`node available ${gib(Number(available[1]) * 1024)}`);
127
+ }
128
+ }
129
+ catch {
130
+ // not Linux
131
+ }
132
+ try {
133
+ // Chromium writes its profile and (with --disable-dev-shm-usage) its
134
+ // shared memory under /tmp — a full disk breaks launches
135
+ const stat = fs.statfsSync('/tmp');
136
+ parts.push(`/tmp free ${gib(stat.bavail * stat.bsize)}`);
137
+ }
138
+ catch {
139
+ // statfs unavailable
140
+ }
141
+ return parts.join(', ');
142
+ }
51
143
  class ContentProcessor {
52
144
  constructor(logger) {
53
145
  this.logger = logger;
@@ -329,16 +421,8 @@ class ContentProcessor {
329
421
  let browser = null;
330
422
  let page = null;
331
423
  const launchBrowser = async () => {
332
- let executablePath = process.env.PUPPETEER_EXECUTABLE_PATH;
333
- if (!executablePath) {
334
- if (fs.existsSync('/usr/bin/chromium')) {
335
- executablePath = '/usr/bin/chromium';
336
- }
337
- else if (fs.existsSync('/usr/bin/chromium-browser')) {
338
- executablePath = '/usr/bin/chromium-browser';
339
- }
340
- }
341
- const b = await puppeteer_1.default.launch({
424
+ const executablePath = resolveBrowserExecutablePath();
425
+ const launchOptions = {
342
426
  executablePath,
343
427
  args: [
344
428
  '--no-sandbox',
@@ -348,7 +432,25 @@ class ContentProcessor {
348
432
  '--disable-extensions',
349
433
  ],
350
434
  protocolTimeout: 60000,
351
- });
435
+ };
436
+ let b;
437
+ try {
438
+ b = await puppeteer_1.default.launch(launchOptions);
439
+ }
440
+ catch (firstError) {
441
+ // One retry after a pause — the failure may be transient (e.g.
442
+ // memory pressure from a page that just closed). If the browser
443
+ // cannot launch at all, no page in this crawl can be processed,
444
+ // so escalate as fatal instead of failing every URL one by one.
445
+ logger.warn(`Browser launch failed (${memoryDiagnostics()}), retrying once in 5s...`, firstError);
446
+ await new Promise(resolve => setTimeout(resolve, 5000));
447
+ try {
448
+ b = await puppeteer_1.default.launch(launchOptions);
449
+ }
450
+ catch (secondError) {
451
+ throw new BrowserLaunchError(`browser failed to launch twice (${memoryDiagnostics()}): ${secondError instanceof Error ? secondError.message : String(secondError)}`);
452
+ }
453
+ }
352
454
  const p = await b.newPage();
353
455
  return { browser: b, page: p };
354
456
  };
@@ -682,6 +784,13 @@ class ContentProcessor {
682
784
  }
683
785
  }
684
786
  catch (error) {
787
+ // A browser that cannot launch is fatal for the whole crawl —
788
+ // rethrow so the source (and the run) is reported as failed
789
+ // rather than logging an error per URL and finishing "green".
790
+ if (error instanceof BrowserLaunchError) {
791
+ logger.error(`Aborting crawl of ${baseUrl}: ${error.message}`);
792
+ throw error;
793
+ }
685
794
  const status = this.getHttpStatus(error);
686
795
  // ── Handle 429 (Too Many Requests) with retry ──
687
796
  if (status === 429) {
@@ -846,17 +955,8 @@ class ContentProcessor {
846
955
  }
847
956
  else {
848
957
  // Standalone mode: launch a browser for this single page
849
- let executablePath = process.env.PUPPETEER_EXECUTABLE_PATH;
850
- if (!executablePath) {
851
- if (fs.existsSync('/usr/bin/chromium')) {
852
- executablePath = '/usr/bin/chromium';
853
- }
854
- else if (fs.existsSync('/usr/bin/chromium-browser')) {
855
- executablePath = '/usr/bin/chromium-browser';
856
- }
857
- }
858
958
  browser = await puppeteer_1.default.launch({
859
- executablePath,
959
+ executablePath: resolveBrowserExecutablePath(),
860
960
  args: [
861
961
  '--no-sandbox',
862
962
  '--disable-setuid-sandbox',
@@ -0,0 +1,209 @@
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 __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.lookupChunks = lookupChunks;
40
+ const better_sqlite3_1 = __importDefault(require("better-sqlite3"));
41
+ const path = __importStar(require("path"));
42
+ const sqliteVec = __importStar(require("sqlite-vec"));
43
+ const yaml = __importStar(require("js-yaml"));
44
+ const js_client_rest_1 = require("@qdrant/js-client-rest");
45
+ const types_1 = require("./types");
46
+ const MAX_CHUNKS = 500;
47
+ /**
48
+ * Read-only lookup of the chunks stored for a URL in a source's vector store.
49
+ * Resolves the store the same way a sync job would (same defaults as
50
+ * DatabaseManager.initDatabase, same ${ENV_VAR} substitution as Doc2Vec's
51
+ * config loader), but never creates tables or collections.
52
+ */
53
+ async function lookupChunks(configContent, selector, url) {
54
+ const source = findSource(configContent, selector);
55
+ const dbConfig = source.database_config ?? {};
56
+ const params = dbConfig.params ?? {};
57
+ if (dbConfig.type === 'sqlite') {
58
+ const dbPath = params.db_path
59
+ || path.join(process.cwd(), `${String(source.product_name).replace(/\s+/g, '_')}-${source.version}.db`);
60
+ return {
61
+ source: { product_name: source.product_name, type: source.type, version: source.version },
62
+ database: { type: 'sqlite', path: dbPath },
63
+ chunks: lookupSqlite(dbPath, url),
64
+ };
65
+ }
66
+ if (dbConfig.type === 'qdrant') {
67
+ const qdrantUrl = params.qdrant_url || 'http://localhost:6333';
68
+ const qdrantPort = params.qdrant_port || 443;
69
+ const collectionName = params.collection_name
70
+ || `${String(source.product_name).toLowerCase().replace(/\s+/g, '_')}_${source.version}`;
71
+ const client = new js_client_rest_1.QdrantClient({ url: qdrantUrl, apiKey: process.env.QDRANT_API_KEY, port: qdrantPort });
72
+ return {
73
+ source: { product_name: source.product_name, type: source.type, version: source.version },
74
+ database: { type: 'qdrant', url: qdrantUrl, collection: collectionName },
75
+ chunks: await lookupQdrant(client, collectionName, url),
76
+ };
77
+ }
78
+ throw new types_1.ValidationError(`source has unsupported database type: ${dbConfig.type}`);
79
+ }
80
+ function findSource(configContent, selector) {
81
+ // Same ${VAR} substitution the sync job applies when it loads the config
82
+ const substituted = configContent.replace(/\$\{([^}]+)\}/g, (match, varName) => process.env[varName] !== undefined ? process.env[varName] : match);
83
+ let parsed;
84
+ try {
85
+ parsed = yaml.load(substituted);
86
+ }
87
+ catch (err) {
88
+ throw new types_1.ValidationError(`config does not parse: ${err instanceof Error ? err.message : String(err)}`);
89
+ }
90
+ const sources = Array.isArray(parsed?.sources) ? parsed.sources : [];
91
+ const source = sources.find(s => s?.product_name === selector.product_name
92
+ && (selector.type === undefined || s?.type === selector.type)
93
+ && (selector.version === undefined || String(effectiveVersion(s)) === selector.version));
94
+ if (!source) {
95
+ throw new types_1.NotFoundError(`source '${selector.product_name}' not found in config`);
96
+ }
97
+ return { ...source, version: effectiveVersion(source) };
98
+ }
99
+ // Mirrors the version defaulting in Doc2Vec.loadConfig for code sources
100
+ function effectiveVersion(source) {
101
+ if (source?.version && String(source.version).trim().length > 0)
102
+ return String(source.version);
103
+ if (source?.type === 'code') {
104
+ if (source.branch && String(source.branch).trim().length > 0)
105
+ return String(source.branch);
106
+ return 'local';
107
+ }
108
+ return String(source?.version ?? '');
109
+ }
110
+ function lookupSqlite(dbPath, url) {
111
+ let db;
112
+ try {
113
+ db = new better_sqlite3_1.default(dbPath, { readonly: true, fileMustExist: true, allowExtension: true });
114
+ }
115
+ catch {
116
+ throw new types_1.NotFoundError(`SQLite database not found at ${dbPath} (has this source ever been synced?)`);
117
+ }
118
+ try {
119
+ sqliteVec.load(db);
120
+ const hasDates = db
121
+ .prepare(`SELECT name FROM sqlite_master WHERE type = 'table' AND name = 'vec_chunk_dates'`)
122
+ .get() !== undefined;
123
+ const rows = db.prepare(`
124
+ SELECT v.chunk_id, v.url, v.product_name, v.version, v.section, v.heading_hierarchy,
125
+ v.chunk_index, v.total_chunks, v.hash, v.content
126
+ ${hasDates ? ', d.created_at AS created_at' : ', NULL AS created_at'}
127
+ FROM vec_items v
128
+ ${hasDates ? 'LEFT JOIN vec_chunk_dates d ON d.chunk_id = v.chunk_id' : ''}
129
+ WHERE v.url = ?
130
+ LIMIT ${MAX_CHUNKS}
131
+ `).all(url);
132
+ return sortChunks(rows.map(row => ({
133
+ chunk_id: String(row.chunk_id),
134
+ url: String(row.url),
135
+ product_name: row.product_name ?? null,
136
+ version: row.version ?? null,
137
+ section: row.section ?? null,
138
+ heading_hierarchy: parseHierarchy(row.heading_hierarchy),
139
+ chunk_index: row.chunk_index === null || row.chunk_index === undefined ? null : Number(row.chunk_index),
140
+ total_chunks: row.total_chunks === null || row.total_chunks === undefined ? null : Number(row.total_chunks),
141
+ hash: row.hash ?? null,
142
+ created_at: row.created_at ?? null,
143
+ content: String(row.content ?? ''),
144
+ })));
145
+ }
146
+ finally {
147
+ db.close();
148
+ }
149
+ }
150
+ async function lookupQdrant(client, collectionName, url) {
151
+ const chunks = [];
152
+ let offset = undefined;
153
+ do {
154
+ const response = await client.scroll(collectionName, {
155
+ limit: 200,
156
+ offset,
157
+ with_payload: true,
158
+ with_vector: false,
159
+ filter: {
160
+ must: [{ key: 'url', match: { value: url } }],
161
+ must_not: [{ key: 'is_metadata', match: { value: true } }],
162
+ },
163
+ });
164
+ for (const point of response.points) {
165
+ const p = point.payload ?? {};
166
+ chunks.push({
167
+ chunk_id: String(p.original_chunk_id ?? point.id),
168
+ url: String(p.url ?? url),
169
+ product_name: p.product_name ?? null,
170
+ version: p.version ?? null,
171
+ section: p.section ?? null,
172
+ heading_hierarchy: parseHierarchy(p.heading_hierarchy),
173
+ chunk_index: p.chunk_index === null || p.chunk_index === undefined ? null : Number(p.chunk_index),
174
+ total_chunks: p.total_chunks === null || p.total_chunks === undefined ? null : Number(p.total_chunks),
175
+ hash: p.hash ?? null,
176
+ created_at: p.created_at ?? null,
177
+ content: String(p.content ?? ''),
178
+ });
179
+ if (chunks.length >= MAX_CHUNKS)
180
+ return sortChunks(chunks);
181
+ }
182
+ offset = response.next_page_offset;
183
+ } while (offset !== null && offset !== undefined);
184
+ return sortChunks(chunks);
185
+ }
186
+ function parseHierarchy(value) {
187
+ if (Array.isArray(value))
188
+ return value.map(String);
189
+ if (typeof value === 'string' && value.trim().startsWith('[')) {
190
+ try {
191
+ const parsed = JSON.parse(value);
192
+ if (Array.isArray(parsed))
193
+ return parsed.map(String);
194
+ }
195
+ catch { /* fall through */ }
196
+ }
197
+ return value ? [String(value)] : [];
198
+ }
199
+ // Default order: position within the page. The UI offers per-column sorting
200
+ // (including by creation date) on top of this.
201
+ function sortChunks(chunks) {
202
+ return chunks.sort((a, b) => {
203
+ const ai = a.chunk_index ?? Number.MAX_SAFE_INTEGER;
204
+ const bi = b.chunk_index ?? Number.MAX_SAFE_INTEGER;
205
+ if (ai !== bi)
206
+ return ai - bi;
207
+ return a.chunk_id.localeCompare(b.chunk_id);
208
+ });
209
+ }
@@ -40,6 +40,7 @@ exports.createServer = createServer;
40
40
  const express_1 = __importDefault(require("express"));
41
41
  const fs = __importStar(require("fs"));
42
42
  const path = __importStar(require("path"));
43
+ const chunk_inspector_1 = require("./chunk-inspector");
43
44
  const config_registry_1 = require("./config-registry");
44
45
  const types_1 = require("./types");
45
46
  const SSE_HEARTBEAT_MS = 15000;
@@ -151,6 +152,34 @@ function createServer(deps) {
151
152
  const days = Number(req.query.days) || 30;
152
153
  res.json(await store.getConfigStats(id, days));
153
154
  });
155
+ // Inspect the chunks currently stored for a URL in one source's vector store.
156
+ // This reads the live store, so results reflect the present state, not a
157
+ // historical run.
158
+ app.get('/api/configs/:id/chunks', async (req, res) => {
159
+ const config = registry.get(parseId(String(req.params.id)));
160
+ if (!config)
161
+ throw new types_1.NotFoundError('config not found');
162
+ const url = typeof req.query.url === 'string' ? req.query.url.trim() : '';
163
+ const productName = typeof req.query.product_name === 'string' ? req.query.product_name : '';
164
+ if (!url)
165
+ throw new types_1.ValidationError('url query parameter is required');
166
+ if (!productName)
167
+ throw new types_1.ValidationError('product_name query parameter is required');
168
+ try {
169
+ res.json(await (0, chunk_inspector_1.lookupChunks)(config.content, {
170
+ product_name: productName,
171
+ type: typeof req.query.type === 'string' && req.query.type ? req.query.type : undefined,
172
+ version: typeof req.query.version === 'string' && req.query.version ? req.query.version : undefined,
173
+ }, url));
174
+ }
175
+ catch (err) {
176
+ if (err instanceof types_1.NotFoundError || err instanceof types_1.ValidationError)
177
+ throw err;
178
+ // Vector store unreachable (e.g. Qdrant down) — surface the reason
179
+ logger.error('Chunk lookup failed:', err);
180
+ res.status(502).json({ error: `chunk lookup failed: ${err instanceof Error ? err.message : String(err)}` });
181
+ }
182
+ });
154
183
  // ------------------------------------------------------------------ runs
155
184
  app.get('/api/runs', async (req, res) => {
156
185
  res.json(await store.listRuns({