@aiaiai-pt/piramidedb-cli 0.0.0-stage → 0.14.1

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
@@ -1,3 +1,19 @@
1
- # Temporary Holding Version
1
+ # @aiaiai-pt/piramidedb-cli
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
+ CLI and agent skill installer for **PiramideDB** — crash-safe hybrid BM25 + int8 vector + grant-scoped search inside PostgreSQL 17 & 18.
4
+
5
+ ## Install the skill
6
+
7
+ ### Claude Code
8
+ ```bash
9
+ mkdir -p ~/.claude/skills/piramidedb && npx -y @aiaiai-pt/piramidedb-cli@latest skill > ~/.claude/skills/piramidedb/SKILL.md
10
+ ```
11
+
12
+ ### Codex
13
+ ```bash
14
+ mkdir -p ~/.agents/skills/piramidedb && npx -y @aiaiai-pt/piramidedb-cli@latest skill > ~/.agents/skills/piramidedb/SKILL.md
15
+ ```
16
+
17
+ ## Documentation
18
+
19
+ https://piramidedb.nomadriver.co
package/SKILL.md ADDED
@@ -0,0 +1,173 @@
1
+ ---
2
+ name: piramidedb
3
+ description: Crash-safe PostgreSQL 17 & 18 access method for multi-tenant hybrid BM25, int8 vector ANN, temporal validity, and row-level grant-scoped search (https://piramidedb.nomadriver.co). Use whenever creating or querying PiramideDB indexes, wiring agentic/MCP search over Postgres, tuning scoring modes or language analyzers, verifying index integrity, or integrating the optional piramidedb-agentic vectorization and grounding layer.
4
+ ---
5
+
6
+ # PiramideDB Reference (`0.14.0`)
7
+
8
+ PiramideDB is a native PostgreSQL 17 & 18 index access method (`USING piramidedb`) written in Rust (`pgrx`). Every write goes through PostgreSQL's own generic WAL, so indexes survive crash recovery, stream cleanly to hot standbys without sidecars or logical replication, and never leak hidden rows through BM25 statistics.
9
+
10
+ Documentation: `https://piramidedb.nomadriver.co`
11
+
12
+ ---
13
+
14
+ ## 1. Creating an Index
15
+
16
+ Always use `format = 7` for full hybrid + temporal + grant-scoped support:
17
+
18
+ ```sql
19
+ CREATE EXTENSION IF NOT EXISTS piramidedb;
20
+
21
+ CREATE INDEX docs_pdb_idx ON docs
22
+ USING piramidedb (tenant, body)
23
+ WITH (
24
+ format = 7,
25
+ analyzer = 'en',
26
+ scoring = 'visible'
27
+ );
28
+ ```
29
+
30
+ ### Index Reloptions (`WITH (...)`)
31
+
32
+ | Option | Values | Notes |
33
+ |---|---|---|
34
+ | `format` | `7` (recommended) | Enables int8 IVF vector ANN, temporal `valid_at`, facets, grants, and hybrid RRF in one index. |
35
+ | `analyzer` | `'standard'` (default), `'en'`, `'pt'`, `'es'`, `'fr'`, `'de'`, `'it'`, `'nl'` | Opt-in Snowball stemmers (`en`, `pt`, etc.) improve prose recall while `'standard'` keeps exact code/identifier tokens. |
36
+ | `scoring` | `'visible'` (recommended for multi-grant), `'constant'`, `'corpus'` | See Scoring & D-021 Zero-Leak section below. |
37
+ | `constant_avgdl` | positive `real` (default `50.0`) | Online-tunable via `ALTER INDEX docs_pdb_idx SET (constant_avgdl = 120.0)` under `ShareUpdateExclusiveLock` (no rebuild). |
38
+
39
+ ---
40
+
41
+ ## 2. Scoring Modes & Zero-Leak Security (D-021)
42
+
43
+ When rows are protected by row-level `grants`, corpus-wide BM25 statistics (`N`, `df`, `avgdl`) leak the existence and term frequency of hidden rows into visible scores. PiramideDB solves this inside the index:
44
+
45
+ - **`scoring = 'visible'` (recommended):** computes exact `N`, `df`, and `avgdl` strictly over rows admitted by the caller's grants. Zero cross-grant leakage, exact BM25 relevance (`fiqa` +259% nDCG@10 vs `constant` under 50% hidden rows), and refuses operand downgrade to `corpus`.
46
+ - **`scoring = 'constant'`:** uses fixed IDF and `constant_avgdl` (tunable online with `ALTER INDEX ... SET (constant_avgdl = ...)`). Zero leakage with constant work per posting.
47
+ - **`scoring = 'corpus'`:** classic corpus-wide BM25 stats for single-ACL / public corpora.
48
+
49
+ ---
50
+
51
+ ## 3. Core SQL Operators & Agent Search Functions
52
+
53
+ ### Basic Lexical Search (`@@@` and `<=>`)
54
+
55
+ ```sql
56
+ SELECT id, title
57
+ FROM docs
58
+ WHERE tenant = 'acme'
59
+ AND body @@@ 'vpn credentials rotated'
60
+ ORDER BY body <=> 'vpn credentials rotated'
61
+ LIMIT 10;
62
+ ```
63
+
64
+ ### Single-Scan Hybrid Search (`index_ctids_hybrid`)
65
+
66
+ Fuses lexical BM25 and quantized `int8` vector ANN inside one Postgres snapshot using Reciprocal Rank Fusion (default `rrf_k = 60`, `lex_weight = 0.25`, `vec_weight = 1.0`):
67
+
68
+ ```sql
69
+ SELECT d.id, d.title, h.score, h.lex_rank, h.vec_rank
70
+ FROM index_ctids_hybrid(
71
+ 'docs_pdb_idx'::regclass,
72
+ 'acme',
73
+ '{"q":"vpn rotation","grants":["role:eng"],"valid_at":"2026-12-06","max_per_group":1}',
74
+ $1::bytea, -- 8-byte <HBBf header + dims signed int8 vector (or NULL for lexical-only)
75
+ 20, -- final limit
76
+ 80, -- candidate pool per leg
77
+ 60, -- rrf_k
78
+ 0.25, -- lex_weight (0.14.0 default)
79
+ 1.0 -- vec_weight
80
+ ) AS h
81
+ JOIN docs AS d ON d.ctid = h.ctid
82
+ ORDER BY h.score DESC;
83
+ ```
84
+
85
+ ### Temporal Validity, Phrases, Deduplication & Snippets
86
+
87
+ Pass JSON query options to filter stale versions, enforce exact phrases, deduplicate document versions, and return grounded excerpts:
88
+
89
+ ```sql
90
+ SELECT d.id, snippet_doc(d.body, 'vpn credentials rotated', 160)
91
+ FROM index_ctids_hybrid(
92
+ 'docs_pdb_idx'::regclass,
93
+ 'acme',
94
+ '{"q":"vpn credentials rotated","valid_at":"2025-06-01","phrases":["vpn credentials"],"max_per_group":1,"grants":["role:eng"]}',
95
+ NULL, 5, 20, 60, 0.25, 1.0
96
+ ) AS h
97
+ JOIN docs AS d ON d.ctid = h.ctid
98
+ ORDER BY h.score DESC;
99
+ ```
100
+
101
+ ### Grant-Safe Facets, Zero-Hit Diagnosis & Batched Queries
102
+
103
+ - **`facet_counts(index, tenant, query_json, field)`**: counts matching rows per facet value strictly within the caller's visible grants.
104
+ - **`diagnose_query(index, tenant, query_json)`**: identifies zero-hit terms without leaking terms that exist only in hidden rows (a hidden term produces the same diagnosis as a nonexistent word).
105
+ - **`search_batch(index, tenant, queries_json)`**: executes multiple agent sub-queries against one consistent snapshot in a single round trip.
106
+
107
+ ---
108
+
109
+ ## 4. Maintenance & Integrity Verification
110
+
111
+ PiramideDB provides a built-in heap-to-index verifier (analogous to `amcheck`'s `heapallindexed`):
112
+
113
+ ```sql
114
+ -- Returns 0 rows when every visible heap tuple is indexed and consistent.
115
+ SELECT count(*) FROM verify('docs_pdb_idx'::regclass);
116
+
117
+ -- Flush write buffer into immutable segments / compact segments online:
118
+ SELECT spill('docs_pdb_idx'::regclass);
119
+ SELECT merge('docs_pdb_idx'::regclass);
120
+ ```
121
+
122
+ Run `verify()` after migrations, failovers, or bulk backfills. Any non-zero count indicates missing or divergent index entries.
123
+
124
+ ---
125
+
126
+ ## 5. Binary Vector Wire Format (`bytea`)
127
+
128
+ PiramideDB stores `int8` scalar-quantized vectors in a compact, deterministic little-endian wire format (`<HBBf` + `dims` signed `int8` bytes):
129
+
130
+ - Bytes `0..2`: `dims` (`uint16`, `1..=4096`, default `512` for MRL models)
131
+ - Byte `2`: `quant` (`uint8`, `1` = per-vector max-abs `int8`)
132
+ - Byte `3`: `reserved` (`uint8`, must be `0`)
133
+ - Bytes `4..8`: `scale` (`float32`, `max_abs(vec) / 127.0`, or `0.0` for zero vector)
134
+ - Bytes `8..8+dims`: `dims` signed `int8` values (`round(v[i] / scale)` clamped to `[-127, 127]`)
135
+
136
+ Exact dot product: `a.scale * b.scale * sum_i(a.q[i] * b.q[i])`.
137
+
138
+ ---
139
+
140
+ ## 6. Optional Ecosystem Layer (`piramidedb-agentic` & MCP)
141
+
142
+ Core `piramidedb.so` never makes network or LLM calls. When building agentic search systems, opt into the companion packages:
143
+
144
+ - **MCP Server (`mcp/piramidedb_mcp.py`)**: exposes `search`, `facets`, `diagnose`, and `batch_search` over Model Context Protocol directly against Postgres.
145
+ - **`extras/piramidedb-agentic` (Python)**:
146
+ - `EmbedderClient`: soft-dependency async client for HuggingFace TEI (`/embed`) or OpenAI-compatible (`/v1/embeddings`) endpoints with immediate-trip circuit breaker and zero query-text logging.
147
+ - `SchemaEmbeddingIndex` (Tier 0): ACL-filtered in-memory `512d` int8 catalog for entity types, relations, and enums with threshold + margin guards.
148
+ - `ground_parse` + `MarthaParserClient` (Tier 1): deterministic grounding gate that verifies every LLM-proposed type, relation, or enum filter against the caller's authorized catalog before executing `index_ctids_hybrid`, silently dropping anything unreadable or hallucinated.
149
+
150
+ ---
151
+
152
+ ## 7. 60-Second Docker Quickstart
153
+
154
+ ```bash
155
+ docker build -f quickstart/Dockerfile -t piramidedb-quickstart .
156
+ docker run --rm -d --name pdb -p 5433:5432 -e POSTGRES_PASSWORD=piramidedb piramidedb-quickstart
157
+ psql "postgresql://postgres:piramidedb@localhost:5433/postgres" -f quickstart/try.sql
158
+ ```
159
+
160
+ Optional embedder overlay:
161
+
162
+ ```bash
163
+ docker compose -f quickstart/docker-compose.agentic.yml --profile embedder up -d
164
+ ```
165
+
166
+ ---
167
+
168
+ ## 8. Verified Performance Baselines (`0.14.0`, quiet host, `verify() = 0`)
169
+
170
+ - **BEIR lexical (`analyzer = 'en'`):** `scifact` `0.6924` (beats ES BM25 `0.665`), `fiqa` `0.2473` (beats ES BM25 `0.236`), `nfcorpus` `0.3161`.
171
+ - **BEIR hybrid RRF (`lex_weight = 0.25`):** `arguana` `+9.9%` (`0.4254`), `scidocs` `+4.8%` (`0.2029`), `scifact` `0.7260`, `nfcorpus` `0.3608`.
172
+ - **ANN (`dbpedia 100K × 1536`, int8 IVF):** `nprobe=32` `0.9915` recall@10 in `29.75 ms` (`34.6 QPS`); index build `53.9 s`.
173
+ - **Mixed R/W concurrency (`100K` multi-tenant 384d, 80% R / 20% W + live `spill`/`merge`):** `2,930.5 ops/s` at 8 clients (`1.6–3.0 ms` p50), `183,121` total ops, `0` errors, `verify() = 0`.
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ import { readFileSync } from "node:fs";
3
+ import { dirname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+
6
+ const here = dirname(fileURLToPath(import.meta.url));
7
+ const root = join(here, "..");
8
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf8"));
9
+ const cmd = process.argv[2] ?? "help";
10
+
11
+ switch (cmd) {
12
+ case "skill": {
13
+ process.stdout.write(readFileSync(join(root, "SKILL.md"), "utf8"));
14
+ break;
15
+ }
16
+ case "quickstart": {
17
+ process.stdout.write(
18
+ [
19
+ "# PiramideDB 60-second Docker quickstart",
20
+ "docker build -f quickstart/Dockerfile -t piramidedb-quickstart .",
21
+ "docker run --rm -d --name pdb -p 5433:5432 -e POSTGRES_PASSWORD=piramidedb piramidedb-quickstart",
22
+ 'psql "postgresql://postgres:piramidedb@localhost:5433/postgres" -f quickstart/try.sql',
23
+ "",
24
+ "# Docs: https://piramidedb.nomadriver.co",
25
+ "",
26
+ ].join("\n"),
27
+ );
28
+ break;
29
+ }
30
+ case "-v":
31
+ case "--version":
32
+ case "version": {
33
+ process.stdout.write(`${pkg.version}\n`);
34
+ break;
35
+ }
36
+ case "-h":
37
+ case "--help":
38
+ case "help": {
39
+ process.stdout.write(
40
+ [
41
+ `piramidedb ${pkg.version} — CLI & agent skill for PiramideDB`,
42
+ "",
43
+ "Usage:",
44
+ " piramidedb skill Print SKILL.md for Claude Code or Codex",
45
+ " piramidedb quickstart Print the 60-second Docker quickstart commands",
46
+ " piramidedb --version Print CLI version",
47
+ "",
48
+ "Docs: https://piramidedb.nomadriver.co",
49
+ "",
50
+ ].join("\n"),
51
+ );
52
+ break;
53
+ }
54
+ default: {
55
+ process.stderr.write(`Unknown command: ${cmd}\nRun \`piramidedb help\` for usage.\n`);
56
+ process.exit(1);
57
+ }
58
+ }
package/package.json CHANGED
@@ -1,6 +1,19 @@
1
1
  {
2
2
  "name": "@aiaiai-pt/piramidedb-cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.14.1",
4
+ "description": "CLI and agent skill for PiramideDB — crash-safe hybrid BM25 + vector + grant-scoped Postgres search",
5
+ "type": "module",
6
+ "license": "Apache-2.0",
7
+ "bin": {
8
+ "piramidedb": "bin/piramidedb.mjs"
9
+ },
10
+ "files": [
11
+ "bin/piramidedb.mjs",
12
+ "SKILL.md",
13
+ "README.md"
14
+ ],
15
+ "engines": {
16
+ "node": ">=18.0.0"
17
+ },
18
+ "dependencies": {}
19
+ }