agent-rag-mcp 0.2.0 → 0.3.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
@@ -33,6 +33,17 @@ The `rag` commands available today are:
33
33
  - `rag restore --from <dir>` — Restores a backup under this root.
34
34
  - `rag reindex` — Rebuilds the database from the manifest and objects.
35
35
 
36
+ ### CLI output
37
+
38
+ Interactive terminals render document lists as aligned columns and other supported results as concise summaries. When output is piped, commands keep the single-line JSON envelope. Set `RAG_FORMAT=json` or `RAG_FORMAT=pretty` to override terminal detection; an invalid value falls back to automatic detection. `rag --help` defaults to raw usage text on a terminal, while `RAG_FORMAT=json` restores its JSON envelope for scripts that parse the legacy help output. Set `NO_COLOR` (any value, including empty) to disable ANSI styling without changing the output layout.
39
+
40
+ `rag ls` includes each document's `documentId`. Copy that value to relabel the same document:
41
+
42
+ ```sh
43
+ rag ls
44
+ rag relabel <document-id> --label "replacement label"
45
+ ```
46
+
36
47
  Structured files can use `.yaml`, `.yml`, `.json`, or `.jsonl`; each structured file yields one section per top-level key.
37
48
 
38
49
  The default knowledge-base root is `%USERPROFILE%\.rag\`. Each client has its own `rag.db` under `.rag\clients\<client>\`; projects are logical within that client and are identified by `project_id`. The namespace is the pair `(client, project)`. By default, `failClosed` is `true`; without a namespace, reads are allowed, and when `failClosed` is set to `false`, writes go to the reserved `default/default` namespace. The Tier 3 human review queue is available through `rag review list`.
@@ -78,7 +89,7 @@ The namespace travels in every `rag_find` or `rag_read` call; it does not come f
78
89
  - `npm test` runs the tests with Node's `node:test`.
79
90
  - `npm run typecheck` runs the TypeScript typecheck without emitting files.
80
91
 
81
- ## Known limits in 0.1.0
92
+ ## Known limits
82
93
 
83
94
  Version 0.1.0 has no embeddings or Tier 2; scanned PDFs go through OCR. Document parsing runs in a child process with a 512 MB V8 heap cap.
84
95
 
@@ -0,0 +1,106 @@
1
+ const ANSI_ESCAPE = /\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\))/g;
2
+ function record(value) {
3
+ return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
4
+ }
5
+ function oneLine(value) {
6
+ return String(value ?? "").replace(/[\r\n]+/g, " ");
7
+ }
8
+ function styled(value, code, enabled) {
9
+ return enabled ? `\x1B[${code}m${value}\x1B[0m` : value;
10
+ }
11
+ function resolveOutputFormat(env, isTTY) {
12
+ const requested = env.RAG_FORMAT?.trim().toLowerCase();
13
+ if (requested === "json" || requested === "pretty") return requested;
14
+ return isTTY ? "pretty" : "json";
15
+ }
16
+ function useColor(env) {
17
+ return !Object.hasOwn(env, "NO_COLOR");
18
+ }
19
+ function stripAnsi(value) {
20
+ return value.replace(ANSI_ESCAPE, "");
21
+ }
22
+ function padVisible(value, width) {
23
+ return value.padEnd(width + value.length - stripAnsi(value).length);
24
+ }
25
+ function renderDocuments(documents, color) {
26
+ if (documents.length === 0) return "No documents.";
27
+ const columns = [
28
+ { header: "DOCUMENT ID", value: (row) => row.documentId },
29
+ { header: "ENTITY", value: (row) => row.entityKey },
30
+ { header: "LABEL", value: (row) => row.label },
31
+ { header: "VERSION", value: (row) => row.versionLabel }
32
+ ];
33
+ const rows = documents.map((item) => record(item) ?? {});
34
+ const widths = columns.map((column) => Math.max(
35
+ column.header.length,
36
+ ...rows.map((row) => stripAnsi(oneLine(column.value(row))).length)
37
+ ));
38
+ const header = columns.map((column, index) => padVisible(
39
+ styled(column.header, "1", color),
40
+ widths[index]
41
+ )).join(" ").trimEnd();
42
+ const body = rows.map((row) => columns.map((column, index) => padVisible(
43
+ oneLine(column.value(row)),
44
+ widths[index]
45
+ )).join(" ").trimEnd());
46
+ return [header, ...body].join("\n");
47
+ }
48
+ function renderDoctor(result) {
49
+ const checked = Number(result.checked ?? 0);
50
+ if (result.ok === true) return `Doctor: healthy (${checked} objects checked)`;
51
+ const missing = Array.isArray(result.missing) ? result.missing.length : 0;
52
+ const corrupt = Array.isArray(result.corrupt) ? result.corrupt.length : 0;
53
+ const details = [`${missing} missing`, `${corrupt} corrupt`];
54
+ if (typeof result.chunks === "number" && typeof result.indexedChunks === "number" && result.chunks !== result.indexedChunks) {
55
+ details.push(`index ${result.indexedChunks}/${result.chunks}`);
56
+ }
57
+ if (typeof result.unreferencedObjects === "number" && result.unreferencedObjects > 0) {
58
+ details.push(`${result.unreferencedObjects} orphan objects`);
59
+ }
60
+ if (typeof result.leftoverTemporaries === "number" && result.leftoverTemporaries > 0) {
61
+ details.push(`${result.leftoverTemporaries} leftover temporaries`);
62
+ }
63
+ return `Doctor: issues found (${checked} checked; ${details.join(", ")})`;
64
+ }
65
+ function renderImport(result) {
66
+ const summary = record(result.summary) ?? {};
67
+ const count = (key) => typeof summary[key] === "number" ? summary[key] : 0;
68
+ return `Import: ${count("inserted")} inserted, ${count("unchanged")} unchanged, ${count("skipped")} skipped, ${count("failed")} failed (${count("total")} total)`;
69
+ }
70
+ function renderDocumentAction(result) {
71
+ const status = oneLine(result.status);
72
+ const documentId = oneLine(result.documentId);
73
+ if (status === "relabeled") return `Relabeled document ${documentId}: ${oneLine(result.label)}`;
74
+ if (status === "retired") return `Retired document ${documentId}`;
75
+ const action = status === "inserted" ? "Added" : status === "unchanged" ? "Unchanged" : "Updated";
76
+ const label = typeof result.label === "string" ? ` ${oneLine(result.label)}` : " document";
77
+ return `${action}${label} (${status}; documentId: ${documentId})`;
78
+ }
79
+ function renderError(error) {
80
+ const code = oneLine(error.code || "error");
81
+ return `Error [${code}]: ${oneLine(error.message || "Unknown error")}`;
82
+ }
83
+ function renderOutput(output, env) {
84
+ const envelope = record(output);
85
+ if (!envelope) return JSON.stringify(output) ?? "null";
86
+ const error = record(envelope.error);
87
+ if (error) return renderError(error);
88
+ const result = record(envelope.result);
89
+ if (!result) return JSON.stringify(output) ?? "null";
90
+ const color = useColor(env);
91
+ if (Array.isArray(result.documents)) return renderDocuments(result.documents, color);
92
+ if (typeof result.documents === "number" && typeof result.versions === "number" && typeof result.objects === "number") {
93
+ return `Documents: ${result.documents} | Versions: ${result.versions} | Objects: ${result.objects}`;
94
+ }
95
+ if (typeof result.ok === "boolean" && typeof result.checked === "number") return renderDoctor(result);
96
+ if (Array.isArray(result.files) && record(result.summary)) return renderImport(result);
97
+ if (typeof result.status === "string" && typeof result.documentId === "string") return renderDocumentAction(result);
98
+ return JSON.stringify(output) ?? "null";
99
+ }
100
+ export {
101
+ padVisible,
102
+ renderOutput,
103
+ resolveOutputFormat,
104
+ stripAnsi,
105
+ useColor
106
+ };
@@ -11,6 +11,7 @@ import { clientDbPath, openDatabase, validateClientName } from "../store/db.mjs"
11
11
  import { backupRoot, reindexRoot, restoreRoot, writeRootManifest } from "../store/backup.mjs";
12
12
  import { readObject } from "../store/objects.mjs";
13
13
  import { getActiveLimits } from "../limits.mjs";
14
+ import { renderOutput, resolveOutputFormat } from "./format.mjs";
14
15
  import {
15
16
  linkReviewVersions,
16
17
  listReviewCandidates,
@@ -46,6 +47,14 @@ Options:
46
47
  --type <type> Human relation type for rag review link
47
48
  --label <text> Replacement label for rag relabel
48
49
  --help Show this help`;
50
+ const HELP = `${USAGE}
51
+
52
+ Output format:
53
+ Interactive terminals render human-readable output; pipes use JSON.
54
+ RAG_FORMAT=json|pretty overrides auto-detection; NO_COLOR disables ANSI styling.
55
+ --help defaults to raw usage on a terminal; RAG_FORMAT=json restores its JSON envelope.
56
+
57
+ Use the documentId shown by rag ls with rag relabel <document-id> --label <text>.`;
49
58
  const NAMED_ERROR_CODES = /* @__PURE__ */ new Set([
50
59
  "usage",
51
60
  "ingest_failed",
@@ -223,11 +232,16 @@ function queryDocuments(root, namespace) {
223
232
  try {
224
233
  const project = db.prepare(`SELECT p.project_id FROM project AS p
225
234
  JOIN client AS c ON c.client_id = p.client_id WHERE c.name = ? AND p.slug = ?`).get(namespace.client, namespace.project);
226
- const rows = project ? db.prepare(`SELECT e.entity_key AS entityKey, d.label AS label, dv.version_label AS versionLabel
235
+ const rows = project ? db.prepare(`SELECT d.document_id AS documentId, e.entity_key AS entityKey, d.label AS label, dv.version_label AS versionLabel
227
236
  FROM document AS d JOIN entity AS e ON e.entity_id = d.entity_id
228
237
  JOIN doc_version AS dv ON dv.document_id = d.document_id AND dv.is_current = 1
229
238
  WHERE d.project_id = ? AND d.deleted_at IS NULL ORDER BY e.entity_key, d.label`).all(project.project_id) : [];
230
- const documents = rows.map((row) => ({ entityKey: row.entityKey, label: row.label, versionLabel: row.versionLabel }));
239
+ const documents = rows.map((row) => ({
240
+ documentId: row.documentId,
241
+ entityKey: row.entityKey,
242
+ label: row.label,
243
+ versionLabel: row.versionLabel
244
+ }));
231
245
  return { namespace, result: { documents } };
232
246
  } finally {
233
247
  db.close();
@@ -647,9 +661,11 @@ async function runCli(options) {
647
661
  }
648
662
  async function main(dependencies = {}) {
649
663
  const writeStdout = dependencies.writeStdout ?? ((line) => process.stdout.write(line));
664
+ const writeStderr = dependencies.writeStderr ?? ((line) => process.stderr.write(line));
650
665
  const setExitCode = dependencies.setExitCode ?? ((exitCode) => {
651
666
  process.exitCode = exitCode;
652
667
  });
668
+ const format = resolveOutputFormat(process.env, process.stdout.isTTY === true);
653
669
  try {
654
670
  const result = await (dependencies.runCli ?? runCli)({
655
671
  argv: process.argv.slice(2),
@@ -657,12 +673,25 @@ async function main(dependencies = {}) {
657
673
  cwd: process.cwd(),
658
674
  homeDir: process.env.RAG_HOME ?? homedir()
659
675
  });
660
- writeStdout(`${JSON.stringify(result.output)}
676
+ const output = result.output;
677
+ if (format === "pretty" && result.exitCode === 0 && typeof output === "object" && output !== null && "result" in output && output.result === USAGE) {
678
+ writeStdout(`${HELP}
679
+ `);
680
+ } else if (format === "pretty") {
681
+ const rendered = `${renderOutput(output, process.env)}
682
+ `;
683
+ if (typeof output === "object" && output !== null && "error" in output) writeStderr(rendered);
684
+ else writeStdout(rendered);
685
+ } else {
686
+ writeStdout(`${JSON.stringify(output)}
661
687
  `);
688
+ }
662
689
  setExitCode(result.exitCode);
663
690
  } catch (error) {
664
691
  const message = publicErrorMessage(error);
665
- writeStdout(`${JSON.stringify({ namespace: null, error: { code: "internal_error", message } })}
692
+ if (format === "pretty") writeStderr(`${renderOutput({ error: { code: "internal_error", message } }, process.env)}
693
+ `);
694
+ else writeStdout(`${JSON.stringify({ namespace: null, error: { code: "internal_error", message } })}
666
695
  `);
667
696
  setExitCode(1);
668
697
  }
@@ -671,6 +700,7 @@ if (process.argv[1] && path.resolve(process.argv[1]) === fileURLToPath(import.me
671
700
  await main();
672
701
  }
673
702
  export {
703
+ HELP,
674
704
  USAGE,
675
705
  main,
676
706
  runCli
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "agent-rag-mcp",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Deterministic, namespace-isolated document retrieval with a CLI and MCP server.",
5
5
  "license": "MIT",
6
6
  "repository": {