Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
69ec766
Add RAG M1 progress tracker and repo guidance for build runs
roshni-shah-23 Nov 9, 2026
27a0cc9
Note cloud-run push quirk and missing gh auth for RAG build runs
roshni-shah-23 Nov 9, 2026
c9bd8b0
NRAG-03-lite: ADR for rag-core dependencies (gpt-tokenizer, CJS-compa…
claude Nov 9, 2026
127a716
NRAG-06: scaffold private @promact/rag-core package with 100% line co…
claude Nov 9, 2026
978f0da
NRAG-07: models, provider interfaces and createRag factory with eager…
claude Nov 9, 2026
aeb958c
Log RAG run 1
claude Nov 9, 2026
4a1923e
rag-core: token counters, TXT/Markdown extractors, compact Markdown r…
claude Nov 9, 2026
b25046d
rag-core: whitespace/unicode and duplicate-block cleaners with remova…
claude Nov 9, 2026
41c8f0b
rag-core: fix lint in cleaners (codepoint-range invisible-char filter…
claude Nov 9, 2026
185a2c0
rag-core: structure-aware token-budgeted chunker with parents and sta…
claude Nov 9, 2026
5b71efe
rag-core: in-memory VectorStore and incremental IngestionPipeline (NR…
claude Nov 9, 2026
8dbc985
rag-core: key memory store records by (tenantId, chunkId) to stop cro…
claude Nov 9, 2026
27a7366
rag-core: chunker never emits a chunk above maxTokens, even for tiny …
claude Nov 9, 2026
5bd64b5
rag-core: record a newer documentVersion even when content is unchanged
claude Nov 9, 2026
f40d908
rag-core: retriever, MMR, budgeted context packer and KnowledgeRetrie…
claude Nov 9, 2026
6f2eea8
Log RAG run 3: review summary, fixes, NRAG-12 decisions
claude Nov 9, 2026
bfd800e
Spec: add file-based store (no database server) to v0.1 as NRAG-34
roshni-shah-23 Nov 16, 2026
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions CLAUDE.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
# CLAUDE.md

npm-workspaces monorepo of `@promact/*` TypeScript packages under `packages/`. See `README.md`
for build/test/publish. The RAG work is specified in `docs/specs/rag-service-spec.md`, and its
progress is tracked in `docs/specs/rag-progress.md`.

## Conventions (match the existing packages)

- Node 22+, TypeScript strict (`tsconfig.base.json`), CommonJS output, `tsc -p tsconfig.json`.
- Each package: `package.json`, `tsconfig.json` (extends base, `rootDir: src`, excludes
`*.test.ts`), `jest.config.js` (`displayName`, `ts-jest`, `src/**/*.test.ts`), `README.md`,
`src/index.ts`. Copy `packages/file-service` as the template.
- Tests sit next to source as `*.test.ts`. No real network calls in tests.
- Wiring is via `createXxx(options)` factories that validate eagerly and throw on bad config.
- `npm run lint` must pass (ESLint, `@typescript-eslint/recommended`; unused args prefixed `_`).

## Rules for unattended RAG build runs

- Work **only** on branch `feat/rag-core`. Never push to `master`, never merge, never force-push,
never run `npm publish` / `npm stage publish`, never change `.github/workflows/publish.yml`.
- New RAG packages are `"private": true` until a human decides to release them.
- Don't add a runtime dependency that isn't in spec §4–§5 or doesn't have a permissive licence
(MIT / Apache-2.0 / BSD / ISC). Check with `npm view <pkg> version license` before adding.
- Read `docs/specs/rag-progress.md` first. Read only the spec sections it points to for the
current item; don't read the whole spec.
- After each item: `npm run build && npm run lint && npx jest packages/rag-core` must pass, then
commit (one commit per item) and update `docs/specs/rag-progress.md`.
- Cloud-run quirks (verified 2026-11-09): `git push` may print "unexpected disconnect" / "remote
end hung up" even though it succeeded. Before retrying, run
`git ls-remote --heads origin feat/rag-core` and compare with `git rev-parse HEAD`; if they
match, the push worked. Branch deletion is blocked (403) and `gh` is not authenticated, so
don't delete branches and don't try to open a PR; just push commits.
- If a check still fails after two fix attempts, or the spec is ambiguous, record it under
"Blocked / questions" in the progress file and move to the next independent item or stop.
Never weaken a test or a security rule to make it pass.
21 changes: 21 additions & 0 deletions docs/adr/0001-rag-core-dependencies.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# ADR 0001 — rag-core dependencies (M1)

Status: accepted (unattended run 1; verified with `npm view` and a CommonJS `require` smoke test on 2026-11-09).

## Tokenizer: `gpt-tokenizer` 4.1.0 (MIT)

Pure JS, zero runtime dependencies, `require()` works under CommonJS/ts-jest, built-in
`countTokens`. `js-tiktoken` 1.0.21 (MIT) also works but pulls `base64-js` and needs explicit
encoding selection. An approximate counter (chars/4 with safety margin) covers vendors without a
local tokenizer.

## Markdown parser: `mdast-util-from-markdown` 0.8.5 + `micromark-extension-gfm` 0.3.3 + `mdast-util-gfm` 0.1.2 + `@types/mdast` 3.0.15 (all MIT)

`remark-parse`/`unified` >= 10 and current `mdast-util-from-markdown` are ESM-only, but this repo
builds CommonJS and tests with ts-jest (no ESM/`require(esm)` support). The last CJS-compatible
line is the micromark-2 era (mdast-util-from-markdown 0.8.x). Verified it parses headings, lists,
code and GFM tables via `require`, with 0 `npm audit` findings. We skip `unified`/`remark-parse`
(only a thin wrapper over the same parser). Trade-off: older line, no new features; revisit if the
repo moves to ESM. `marked` 18 was rejected (ESM-only, and not an mdast AST).

All licences permissive (MIT). Packages stay `"private": true`.
110 changes: 110 additions & 0 deletions docs/specs/rag-progress.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
# RAG build progress (M1 — core library)

Branch: `feat/rag-core`. Spec: `docs/specs/rag-service-spec.md` (line numbers below are
approximate; search for the heading if they drift). Rules: see `CLAUDE.md`.

Goal of this branch: milestone **M1** (spec §14, NRAG-06 → NRAG-12) in `packages/rag-core`.
Out of scope here: real databases, Docker, PDF/Office extractors, GraphRAG, the server.

## Items

Status: `[ ]` todo · `[~]` in progress · `[x]` done · `[!]` blocked

| Status | ID | Item | Read in spec |
|---|---|---|---|
| [x] | NRAG-03-lite | Pick and verify deps for M1 only: tokenizer (`gpt-tokenizer` vs `js-tiktoken`), Markdown parser (`remark-parse`/`unified`/`mdast` types). `npm view <pkg> version license`. Record choice + versions + licences in `docs/adr/0001-rag-core-dependencies.md` (short). Note: remark/unified are ESM-only; this repo builds CommonJS — choose a version/approach that works with CommonJS + ts-jest, or a CJS-compatible alternative, and say why. | §4 (l.120–147) |
| [x] | NRAG-06 | Scaffold `packages/rag-core` (copy `file-service` layout), `"private": true`, Jest `coverageThreshold` 100% lines for this package. | §5 (l.149–193), §12 (l.717–743) |
| [x] | NRAG-07 | Models + interfaces (§6.1–6.4) and `createRag` factory skeleton with eager validation (§6.5). Ollama adapters can wait. | §6 (l.195–391) |
| [x] | NRAG-08 | `TokenCounter` (exact + approximate w/ margin), TXT + Markdown extractors → element model, compact Markdown renderer (table as Markdown or CSV, whichever is fewer tokens). | §6.1, §8.1 (l.494–502) |
| [x] | NRAG-09 | Cleaner chain: `whitespaceUnicodeCleaner`, `duplicateBlockCleaner` (+ stats of what was removed). Include an invisible/zero-width-character injection test. | §8.2 (l.504–512) |
| [x] | NRAG-10 | Structure-aware token-budgeted chunker: heading-path prefix, never > `maxTokens`, no mid-table/code splits, parent–child, row-group chunking with repeated header. Chunk id = hash(documentId, contentHash, occurrence). | §6.2, §8.3 (l.514–522) |
| [x] | NRAG-11 | In-memory `VectorStore` + `IngestionPipeline` with incremental logic (doc hash skip, chunk reuse via `findByContentHash`, `documentVersion` last-writer-wins → `stale`, delete). Use a deterministic fake `EmbeddingModel` in tests. | §6.2–6.3, §8.4 (l.524–534), §10.1 |
| [x] | NRAG-12 | Retriever (mandatory tenant/ACL filter applied inside the store search, `minScore`, MMR) + context packer (budget − margin, default 4000, merge adjacent, parent expansion if room, edge ordering, `[n]` citations) + `KnowledgeRetriever`. Cross-tenant leakage test. | §6.4, §8.5 (l.536–549) |

## Run plan

- **Run 1 (Sonnet):** NRAG-03-lite, NRAG-06, NRAG-07.
- **Run 2 (Sonnet):** NRAG-08, NRAG-09, NRAG-10; NRAG-11 if the run is still going well.
- **Run 3 (Opus):** review everything on the branch first (see the review checklist), fix
findings, then continue the next unfinished item only if the review is clean.

Each run: stop after its items, or earlier if blocked. Don't start an `L` item you can't finish.

## Review checklist (run 3)

- Chunk ids are stable when a paragraph is inserted earlier in the document.
- Chunks never exceed `maxTokens`; tables/code never split mid-row/mid-block.
- No public path searches without a tenant filter; filter is applied in the store query, not after.
- Context output never exceeds `maxTokens − margin`.
- Tests assert behaviour (not just "doesn't throw"); no tests weakened or skipped.
- Only permissive licences; package stays `"private": true`.

## Log

Append one short entry per run: date/time, model, items finished, commits, anything notable.

- 2026-11-09, Sonnet 5.5 (run 1): NRAG-03-lite, NRAG-06, NRAG-07 done (commits c9bd8b0, 127a716, 978f0da). Markdown stack pinned to CJS-compatible mdast-util-from-markdown 0.8.5 + GFM 0.x (see ADR 0001). `createRag` ingest/deleteDocument/getContext are stubs until NRAG-11/12; 'embedding dims vs existing collection' check needs async ensureCollection, deferred to NRAG-11. Spec §10 not read: `RetrievalFilter` defined as {tenantId, aclGroups}; verify against §10. gh unauthenticated per CLAUDE.md, so no draft PR opened.

- 2026-11-09, Sonnet 5.5 (run 2): NRAG-08, NRAG-09, NRAG-10, NRAG-11 done (commits 4a1923e, b25046d + lint fix 41c8f0b, 185a2c0, and the NRAG-11 commit). Baseline was green at start. rag-core: 84 tests, 100% line coverage. `createRag.ingest`/`deleteDocument` are now wired (getContext still a stub for NRAG-12). Note: the NRAG-09 commit b25046d was pushed with a lint error (my mistake); fixed in 41c8f0b. See "Blocked / questions" for design decisions.

- 2026-11-09, Opus 5.5 (run 3, review): baseline green (84 tests). Review fixed 3 defects, each with a regression test:
8dbc985 (cross-tenant record overwrite in the memory store), 27a7366 (chunks above maxTokens for tiny budgets with
fenced code), 5bd64b5 (same-content version bump not recorded → an older version could win). Then NRAG-12 done
(f40d908). M1 items all [x]. rag-core: 104 tests, 100% line coverage. No draft PR: gh is not authenticated (CLAUDE.md).

## Blocked / questions for Roshni

No item is blocked. Decisions made unattended that you may want to overrule:

- **`VectorStore.listDocument` added** (not in spec §6.3 sketch). §8.4 (doc-hash skip, vanished-chunk deletion,
version check) cannot be implemented without listing a document's stored chunks. Returns `ChunkRef`s; must filter by tenant.
- **`findByContentHash` has no tenant parameter** (as in the spec). Vectors are reusable across tenants, which reveals only
that identical text exists elsewhere (weak existence oracle). Consider adding a tenant scope in the ADR.
- **Parents are stored as records** with `metadata.role = 'parent'` and an empty vector; leaves have `role = 'leaf'`. Stores must
never rank parents (memory store skips them). NRAG-12's packer needs a way to fetch a parent by id — the `VectorStore`
interface has no `getByIds` yet; add it in NRAG-12.
- **`overlapTokens > 0` is rejected** by the chunker for now (heading-path prefix is the default; spec says overlap is optional).
- **Same-version re-ingest with identical content is `unchanged`** even if a higher version number arrives (records keep the old
version number). An equal version with different content is treated as an update. `failed` outcome is never returned: errors throw.
- `duplicateBlockCleaner` defaults to `minChars: 0` (literal spec); zero-width joiners are stripped (hurts Persian/Indic/emoji ZWJ text).
- Unchanged-detection keys on doc hash + chunking/model signature + ACL set; cleaner-chain config changes are not part of the signature.
- **Store record identity is `(tenantId, chunkId)`** (run 3 fix). Chunk ids hash `documentId`, which is only unique per tenant.
Real adapters (pgvector/Qdrant/…) must use a composite key or include `tenantId` in the stored id. Alternative: put
`tenantId` into the chunk-id hash (deviates from spec §6.2) — your call.
- **`VectorStore.getByIds(collection, filter, ids)` added** (run 3) for parent expansion; filtered like `search`.
- **A same-content re-ingest with a higher `documentVersion` now re-upserts** the records (vectors reused, no embedding)
and reports `unchanged`. This replaces the earlier "records keep the old version number" behaviour, which broke
last-writer-wins.
- **Merged context blocks** share one `[n]` label; `citations` has one entry per chunk with that label. Parent expansion
cites the parent chunk id. Graph modes (`graph-local`/`graph-global`/`mix`) throw until GraphRAG exists.

## Review summary (run 3, Opus 5.5)

**Checked** (`git diff origin/master...feat/rag-core`, packages/rag-core, against the checklist and spec §6.2–6.4,
§8.3–8.5, §10.1): chunk-id derivation and stability, the `maxTokens` invariant (including adversarially tiny budgets),
table/code splitting, cleaner chain (invisible-char stripping), incremental ingestion (hash skip, reuse, stale, vanished
chunks, ACL change), tenant/ACL filtering in every store path, licences of all 39 runtime deps (all MIT), `"private": true`.

**Defects found and fixed** (one commit each, with a test that failed before the fix):
1. *Security / data loss* — memory store keyed records by `chunkId` only; two tenants ingesting the same `documentId`
with identical content collided, and the second silently replaced the first tenant's index (an existing test passed
only because tenant A's data was already gone). Now keyed by `(tenantId, chunkId)`; contract documented on `VectorStore`.
2. *Budget invariant* — with a small `maxTokens`, code was split to single characters but each piece kept its fence,
producing chunks above `maxTokens`. Fence is dropped when it alone exceeds the budget; the chunker now throws rather
than emit an over-budget chunk.
3. *Last-writer-wins* — v1 stored, v3 (identical) → `unchanged` without recording v3, then v2 → accepted and overwrote.
Version bumps are now recorded.

**NRAG-12** implemented after the review was green (retriever, MMR, packer, `KnowledgeRetriever`, cross-tenant test;
packer output is measured on the final rendered text, so it cannot exceed `maxTokens − margin`; property-tested).

**Remaining risks**
- Chunk ids are stable for edits in *other* sections, but inserting a paragraph inside a long section shifts the greedy
packing boundaries after it, so later chunks in that section get new ids (re-embedded only if their text changed).
- `findByContentHash` is not tenant-scoped (existence oracle across tenants; noted above by run 2).
- Code blocks containing a ``` line can break out of their fence in chunk text (prompt-formatting, not access control).
- Memory store's hybrid score is an average of cosine and keyword overlap, not RRF; real adapters should use native hybrid.
- `aclGroups: []` on a document makes it invisible to everyone (deny by default) — confirm that is intended.

**Look at first:** the `(tenantId, chunkId)` decision (it constrains every real adapter), then `src/packer.ts`
(merge/adjacency rule relies on the chunker's ordinal numbering of parents and leaves).
Loading
Loading