diff --git a/CHANGELOG.md b/CHANGELOG.md index 6b4a0c7..b503e0d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,13 @@ +## [Unreleased — dependency security] — 2026-12-01 — cross-spawn production audit fix + +Pinned the transitive `cross-spawn` dependency to `7.1.2` through an npm override. +A newly published advisory (GHSA-ghv9-86vm-4v8m) marks `7.0.0 - 7.0.6` as +critical for command injection on Windows; the CI production audit gate began +failing on the existing lockfile. `npm audit --omit=dev --audit-level=critical` +now reports 0 critical vulnerabilities (9 remaining: 5 high, 4 moderate, with +no non-breaking fix available for the rest). No product source behaviour +changed. + ## [Unreleased — Layer A] — 2026-11-30 — staged German content generation Owner explicitly selected A and authorised sequential work through B, C and D. Added @@ -18,37 +28,50 @@ instruction remain owner gates. B, C and D were not started as code: no licence- documents, no attached device and no authenticated live rail credential were observed. Evidence: `docs/evidence/S101-A-language-content-staging.md`. -## [Unreleased — Layer B] — 2026-11-30 — RAG source import infrastructure (staged, not executed) +## [Unreleased — Layer B] — 2026-12-01 — RAG source import infrastructure corrected to the real schema (staged, not executed) Owner-authorized sequential layer B after A. Added gate-safe RAG import infrastructure with no content imported: - `src/rag/documentProcessor.ts` — shared validation (API key, JWT, GitHub token, - email, phone, card-like PII detection) and deterministic chunking - (`chunk-{docId}-{sha256}`, unique IDs, sequential indices, overlap splitting) + email, phone, card-like PII detection) and deterministic chunking. Rejection + messages name the pattern only and never echo matched secret/PII material. + Chunk IDs include the chunk ordinal so repeated identical paragraphs cannot + collide. - `scripts/rag/import-documents.mjs` — pure Node ESM import plan generator; reads `.txt`/`.md` from `docs/rag-sources/`, validates, chunks, emits JSON plan; requires `--license-confirmed` (fail-closed, no output without it) -- `scripts/rag/governedImporter.ts` — writes the plan through - `Database.governedWrite` to `documents` + `document_chunks`; every row stamped - `source_status: 'USER_PRIVATE'`, `provenance: 'user_imported'`, owner `user_id`, - portal type; idempotent upsert via `matchFields`; fails closed on write error -- `tests/rag/documentImport.test.ts` — adversarial tests: secret/PII rejection, - deterministic unique chunk IDs, USER_PRIVATE marking, owner/portal stamping, - idempotent upsert, fail-closed on write error, all three portal types +- `scripts/rag/governedImporter.ts` — routes the plan through the shipped + `storeChunks` ingestion path (`lib/knowledge.ts` → `Database.governedWrite`) + instead of writing invented schema columns. Document and chunk ids are + deterministic UUIDs; import metadata lives in the JSONB `metadata` column; + every row is `USER_PRIVATE`; idempotent upsert; rejects document or chunk write + failures explicitly. +- `tests/rag/documentImport.test.ts` — adversarial tests: secret/PII rejection + without echo, deterministic unique chunk IDs including repeated paragraphs, + real-schema column allowlist, UUID ids, USER_PRIVATE marking, owner/portal + stamping, idempotent upsert, fail-closed on document and chunk write errors, + all three portal types - `docs/rag-sources/README.md` — intake rules: no documents without a written licence/rights basis, USER_PRIVATE default, governed boundary only, `--license-confirmed` required -- `docs/evidence/S101-B-rag-import-staging.md` — staging evidence and blocker - documentation +- `docs/evidence/S101-B-rag-import-staging.md` — corrected staging evidence, + red/green proof and blocker documentation + +The first Layer B merge wrote `documents.source_status`, `document_chunks.chunk_id` +and other columns that do not exist in the committed schema; its mock accepted +arbitrary columns, so the tests passed while the real insert would fail. The +corrected test file against base `78f0b06` exited 1 with 5 failed / 20 passed +(25 tests), and the corrected tree passed 25/25. No document was imported before +or after the correction. Layer B remains **blocked on owner input**: `docs/rag-sources/` is intentionally empty; no licence-cleared documents, no licence/rights basis and no named human reviewer have been supplied. No document has been imported. No OFFICIAL or COMMUNITY claim is made. C and D were not started as code. -Suite ratchet moved by measurement from 130 files / 697 tests to 131 files / 722 tests in -`AGENTS.md` and CI. No threshold was lowered. +Suite ratchet is 131 files / 722 tests in `AGENTS.md`, CI and README. No threshold +was lowered. ## [1.18.0] — 2026-11-30 — Sprint 101 release close-out diff --git a/README.md b/README.md index 5b598b5..3cff63d 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ [![Supabase](https://img.shields.io/badge/Backend-Supabase%20%2B%20pgvector-3ECF8E?style=for-the-badge&logo=supabase&logoColor=white)](https://supabase.com) [![Ollama](https://img.shields.io/badge/Local%20AI-Ollama-000000?style=for-the-badge&logo=ollama&logoColor=white)](https://ollama.com) [![TypeScript](https://img.shields.io/badge/TypeScript-strict-3178C6?style=for-the-badge&logo=typescript&logoColor=white)](https://www.typescriptlang.org) -[![Tests](https://img.shields.io/badge/tests-697%20passing-emerald)](https://github.com/dmuhoro/easytutor) +[![Tests](https://img.shields.io/badge/tests-722%20passing-emerald)](https://github.com/dmuhoro/easytutor) [![Constitution](https://img.shields.io/badge/constitution-Article%20I--VII-purple)](CONSTITUTION.md) [![License: MIT](https://img.shields.io/badge/License-MIT-blue)](LICENSE) @@ -115,18 +115,23 @@ the off-palette blue is gone from the rendered quiz tree ### RAG Source Import (Layer B — staged, not executed) -Documents can be imported through the governed layer with deterministic chunk IDs. -`scripts/rag/import-documents.mjs` reads `.txt`/`.md` from `docs/rag-sources/`, -validates (no secrets, no PII, size limit), chunks deterministically and emits -an import plan. `scripts/rag/governedImporter.ts` writes that plan through -`Database.governedWrite` to `documents` + `document_chunks`, both owner-column -governed (`user_id`) and portal-scoped. Every import is `source_status: -'USER_PRIVATE'` / `provenance: 'user_imported'` by default; no OFFICIAL or -COMMUNITY claim is made. The script requires `--license-confirmed` and exits -without it (fail-closed). `tests/rag/documentImport.test.ts` covers secret/PII -rejection, deterministic unique chunk IDs, USER_PRIVATE marking, owner/portal -stamping, idempotent upsert, fail-closed on write error and all three portal -types. +The staged import path assigns deterministic UUID ids through the shipped +`storeChunks` ingestion path, but it has not been executed on any document. +`scripts/rag/import-documents.mjs` reads +`.txt`/`.md` from `docs/rag-sources/`, validates (no secrets, no PII, size +limit), chunks deterministically and emits an import plan. +`scripts/rag/governedImporter.ts` routes that plan through `storeChunks` +(`lib/knowledge.ts` → `Database.governedWrite`) to `documents` + +`document_chunks`, both owner-column governed (`user_id`) and portal-scoped. +Every import is `USER_PRIVATE` with `user_imported` metadata by default; no +OFFICIAL or COMMUNITY claim is made. Import metadata lives in the JSONB +`metadata` column; no non-schema columns are written. The script requires +`--license-confirmed` and exits without it (fail-closed). Rejection messages +name the pattern only and never echo matched secret/PII material. +`tests/rag/documentImport.test.ts` covers secret/PII rejection, deterministic +unique chunk IDs, the real schema column allowlist, UUID ids, USER_PRIVATE +marking, owner/portal stamping, idempotent upsert, fail-closed on document and +chunk write errors and all three portal types. Layer B remains **blocked on owner input**: no licence-cleared documents have been supplied, `docs/rag-sources/` is intentionally empty, and no import has @@ -224,7 +229,7 @@ All must be green before a push: ```bash npm run typecheck # tsc --noEmit, 0 errors npm run lint # eslint, 0 errors -npm test # vitest, 130 files / 697 tests (real-screen route smoke, one-home tab-nav, quiz reliability, Mathematics evidence gates, M1 routing/retrieval/citation proofs, answer-source + excerpt-on-tap, wired practice/tutor route truth, German pack/review/explanation/drill path, locale coverage, desktop shell + orientation, idle-startup scheduling, C13 Socratic wiring, C37 state handlers, Lighthouse and capacity controls) +npm test # vitest, 131 files / 722 tests (real-screen route smoke, one-home tab-nav, quiz reliability, Mathematics evidence gates, M1 routing/retrieval/citation proofs, answer-source + excerpt-on-tap, wired practice/tutor route truth, German pack/review/explanation/drill path, locale coverage, desktop shell + orientation, idle-startup scheduling, C13 Socratic wiring, C37 state handlers, Lighthouse and capacity controls) npm run test:auth-flow # live local Supabase Auth + Mailpit proof (needs local Supabase running) npm run e2e:smoke # no-backend 390px route/PWA smoke (9 tests; also runs in CI) npm run e2e:full # real 390px app + local Supabase (5 tests; needs local stack) diff --git a/STATUS.md b/STATUS.md index 256f7f5..0478327 100644 --- a/STATUS.md +++ b/STATUS.md @@ -91,7 +91,7 @@ remote. The published tag is not moved. The owner's exact `TAG v1.18.0` instruct | Sprint 101 production deployment | **OBSERVED READY** — `dpl_5dPmRBZnhTEfAXfuhKqPsH8Niq5y` (`485bd79`), `dpl_7L3nxSvJTSUv7YRLeUchHw97y3YK` (`71b388f`), `dpl_AYXTdqf9gCimoLEgm3VwnaDQsNPp` (`1bab683`), `dpl_FQEUFjNzYzxzqpgCugZdXTKHtwc5` (`7f21700`, the `v1.18.0` tag SHA) `dpl_2SWNsFDwWTNhFHE6W418KqfFsYMR` (`03a44ca`, first docs merge) and `dpl_4yPp4uxCMYvSBWZrABYC7rqu8Fc8` (`e4e548a`, second docs merge) are production `READY`, aliased to `easytutor-ten.vercel.app`; HTTP `200` on `/` and `/login` for earlier SHAs and on `/` for `7f21700`, `03a44ca` and `e4e548a`. No browser Lighthouse/device proof. | `docs/evidence/S101-promotion-ci-deployment.md`, `docs/evidence/S101-v1.18.0-release-closeout.md` | | Sprint 101 owner-gated expansion triage | **NOT EXECUTED BY DESIGN** — no 100-card generation, DW/Goethe import, KINAP registration, hosted AI live call or reminder toggle was shipped. Each needs provenance, licence, human review, device or live-rail proof before a new spec-driven layer can exist. | `docs/evidence/S101-owner-task-triage.md` | | Sprint 101 Layer A — staged German content generation | **ENGINEERING DONE, PROMOTION BLOCKED** — owner selected A. ADR-012 spec, 120-concept seed, pinned `gemma2:2b` generator and a staged `COMMUNITY`/`UNREVIEWED` 120-card candidate under `docs/evidence/`. Pinned parameters; 13/120 cards changed across runs, so model text is not claimed byte-reproducible. Fail-closed on single-token output; negative control made the test exit 1 before restore. Authoritative schema + four red controls green; drill still imports only the original 12-card pack. Daniel's accuracy review and a separate version/tag/release remain owner gates; no OFFICIAL claim. | `docs/adr/ADR-012-language-content-generation.md`, `docs/evidence/S101-A-language-content-staging.md` | -| Sprint 101 Layers B/C/D | **LAYER B INFRASTRUCTURE DONE, IMPORT BLOCKED** — B: RAG import validator, chunker and governed importer implemented (`src/rag/documentProcessor.ts`, `scripts/rag/import-documents.mjs`, `scripts/rag/governedImporter.ts`, `tests/rag/documentImport.test.ts`); all imports USER_PRIVATE by default, governed database boundary only, `--license-confirmed` required. No licence-cleared documents supplied, `docs/rag-sources/` empty, no import performed. C: no attached device or Apple team. D: no AI provider credential in local env. No simulated proof was created for any layer. | `docs/evidence/S101-B-rag-import-staging.md`, `docs/evidence/S101-A-language-content-staging.md` | +| Sprint 101 Layers B/C/D | **LAYER B ENGINEERING CORRECTED, IMPORT BLOCKED** — B: RAG validator, chunker and importer implemented (`src/rag/documentProcessor.ts`, `scripts/rag/import-documents.mjs`, `scripts/rag/governedImporter.ts`, `tests/rag/documentImport.test.ts`). The importer now routes through the shipped `storeChunks` ingestion path instead of writing invented schema columns; ids are deterministic UUIDs, import metadata lives in JSONB `metadata`, and every import is USER_PRIVATE with `--license-confirmed` required. Observed red control on base `78f0b06`: 5 failed / 20 passed; corrected tree 25/25. No licence-cleared documents supplied, `docs/rag-sources/` empty, no import performed. C: no attached device or Apple team. D: no AI provider credential in local env. No simulated proof was created for any layer. | `docs/evidence/S101-B-rag-import-staging.md`, `docs/evidence/S101-A-language-content-staging.md` | | Sprint 101 W3 capacity model | **FAIL-CLOSED GATE RED; NO ROW PROMOTED** — `scripts/ops/capacity_model.mjs` reads versioned provenance (200 calls/user/day + 1000 tokens from `DEC-05.md`, 200,000 tokens/day from `daniel-D07.md`) and refuses to pass while D16 is unsigned. Real `--learners 100` run exits 1: demand 20,000,000/day, shortfall 19,800,000/day. Pure integer helpers proved with four fixture tests (green at 1 learner, red at 10). `capacity:check` stays out of blocking CI; `GT-18`/`E16-T1` remain UNPROMOTED. Exact ratchet strengthened to 125 files / 664 tests. | `docs/evidence/S101-capacity-model-red.md` | | Sprint 101 W2 state coverage + mobile Lighthouse | **GATES LANDED, REAL MOBILE SCORE RED; NO ROW PROMOTED** — `tests/design/states.test.ts` maps all nine state-bearing Stitch entries to exact handlers in shipped files; a loose matcher was rejected as a false gate and the exact-match red control was observed. Mobile Lighthouse preset added with D12 floor 60 from versioned provenance and median-of-3; fixture controls green (7 tests), real local run RED (`/` 45, `/login` 45), desktop unchanged and also locally below its 80 floor (72/78). No floor lowered; the gate stays out of blocking CI. `GT-24`/`E15-T2`/`E15-T3` remain UNPROMOTED. Exact ratchet strengthened to 124 files / 660 tests. | `docs/evidence/S101-state-coverage-and-mobile-lighthouse.md` | diff --git a/docs/evidence/S101-B-rag-import-staging.md b/docs/evidence/S101-B-rag-import-staging.md index 38f1d97..a122d7b 100644 --- a/docs/evidence/S101-B-rag-import-staging.md +++ b/docs/evidence/S101-B-rag-import-staging.md @@ -1,16 +1,73 @@ # Sprint 101 Layer B — RAG source import staging (gate-safe, not executed) -**Date:** 2026-11-30 · **Status:** ENGINEERING DONE, IMPORT BLOCKED ON OWNER INPUT +**Date:** 2026-12-01 · **Status:** ENGINEERING CORRECTED TO THE REAL SCHEMA, IMPORT BLOCKED ON OWNER INPUT ## What was built (gate-safe engineering only) | Artifact | Purpose | |---|---| -| `src/rag/documentProcessor.ts` | Shared validation (secrets/PII detection) and deterministic chunking logic | -| `scripts/rag/import-documents.mjs` | Pure Node ESM import plan generator; reads `.txt`/`.md` from `docs/rag-sources/`, validates, chunks, emits JSON plan; requires `--license-confirmed` (fail-closed) | -| `scripts/rag/governedImporter.ts` | Writes an import plan through `Database.governedWrite` to `documents` + `document_chunks`; all rows stamped `source_status: 'USER_PRIVATE'`, `provenance: 'user_imported'`, owner `user_id`, portal type | -| `tests/rag/documentImport.test.ts` | Adversarial tests: secret/PII rejection, deterministic chunk IDs, uniqueness, governed-write USER_PRIVATE marking, owner/portal stamping, idempotent upsert, fail-closed on write error, all three portal types | -| `docs/rag-sources/README.md` | Intake rules: no documents without licence/rights basis, USER_PRIVATE default, governed boundary only, `--license-confirmed` required | +| `src/rag/documentProcessor.ts` | Shared validation (secrets/PII detection) and deterministic chunking. Rejection labels identify the pattern only; matched secret/PII material is never echoed. Chunk IDs include the chunk ordinal so repeated identical paragraphs cannot collide. | +| `scripts/rag/import-documents.mjs` | Pure Node ESM import plan generator; reads `.txt`/`.md` from `docs/rag-sources/`, validates, chunks, emits JSON plan; requires `--license-confirmed` (fail-closed). Mirrors the validator/chunker behaviour above. | +| `scripts/rag/governedImporter.ts` | Routes the plan through the shipped `storeChunks` ingestion path (`lib/knowledge.ts`) to `documents` + `document_chunks`, which uses `Database.governedWrite`. Derives deterministic UUID document/chunk ids and puts `sourceStatus`, `provenance`, `chunkIndex` and source metadata in the JSONB `metadata` column. No invented schema columns. | +| `tests/rag/documentImport.test.ts` | Adversarial tests: secret/PII rejection without echo, deterministic unique chunk IDs including repeated paragraphs, real-schema column allowlist, UUID ids, `USER_PRIVATE` scope, owner/portal stamping, idempotent upsert, fail-closed on document and chunk write errors, all three portal types. | +| `docs/rag-sources/README.md` | Intake rules: no documents without a written licence/rights basis, USER_PRIVATE default, governed boundary only, `--license-confirmed` required. | + +## Boundary correction (why the first Layer B merge was not accepted) + +The first Layer B merge wrote `documents.source_status`, `documents.provenance`, +`documents.size_bytes`, `documents.source_dir`, `documents.generated_at`, +`document_chunks.chunk_id`, `document_chunks.chunk_index`, +`document_chunks.size_chars`, `document_chunks.source_document`, +`document_chunks.source_status` and `document_chunks.provenance`. Those columns do +not exist in the committed schema, and the plan's `chunk-…` strings were written +into a UUID primary key. The old mock accepted arbitrary columns, so the tests +passed while the real insertion would fail. + +The corrected importer does not duplicate the ingestion write. It calls the +shipped `storeChunks` path, which already owns `documents` / `document_chunks` +governance, UUID ids, `USER_PRIVATE` scope and FTS/embedding handling. The test +allowlist is the real committed column set plus governed stamps. + +## Observed red → green proof + +Red control (base `78f0b06`, final test file): the targeted suite exited 1 with +**5 failed / 20 passed (25 tests)**. The five failures were: + +1. `findSecrets` echoed abbreviated key material instead of returning the + `openai_key` label. +2. `findPii` echoed abbreviated PII instead of returning the `email` label. +3. Repeated identical paragraphs produced 3 unique chunk IDs for 4 chunks. +4. The document row had no `id`, so no UUID existed for the primary key. +5. The chunk rows had no `id` UUIDs (they carried only `chunk_id` strings). + +Green control (corrected tree): the same targeted suite passed **25/25**. + +Planner fail-closed checks, exercised on a temporary directory outside the repo: + +- no `--license-confirmed` → exit 1, no file read or plan emitted; +- missing source directory → exit 1; +- PII-bearing document → exit 1 with `PII_DETECTED:possible PII: email` + (the address itself was not printed); +- repeated identical paragraphs → 3 chunks and 3 unique chunk IDs. + +## Test results + +- `validateDocument`: clean German text passes; API keys, JWTs, GitHub tokens, + emails, phone numbers and card-like numbers are rejected by label only. +- `chunkText`: deterministic IDs (`chunk-{docId}-{sha256(index:content)}`), + unique IDs for repeated paragraphs, sequential indices, overlap splitting for + long paragraphs, empty paragraphs ignored. +- `importDocumentPlan`: requires `license_confirmed: true` and + `default_source_status: 'USER_PRIVATE'`; writes through `storeChunks`; + deterministic UUID ids; idempotent upsert; rejects on document or chunk write + failure; works across `high_school`, `university`, `knowledge_explorer`. +- A failed import is rejected explicitly. The write is not claimed to be an + atomic transaction: `storeChunks` records chunk failures and the importer + throws with the document and failure count, so no failed chunk is silently + accepted. +- Re-importing an unchanged plan is idempotent. Changed-content replacement is + **not claimed**: stale-chunk cleanup after a changed source is not implemented + and must be specified and tested before any real import. ## What was NOT done (honest blockers) @@ -21,15 +78,10 @@ | OFFICIAL or COMMUNITY provenance | **NOT CLAIMED** | All imports would be `USER_PRIVATE` / `user_imported` only | | Promote to a new version/tag/release | **NOT EXECUTED** | Separate owner instruction required | -## Test results - -- `validateDocument`: clean German text passes; API keys, JWTs, GitHub tokens, emails, phone numbers and card-like numbers are rejected -- `chunkText`: deterministic IDs (`chunk-{docId}-{sha256}`), unique IDs, sequential indices, overlap splitting for long paragraphs, empty paragraphs ignored -- `importDocumentPlan`: requires `license_confirmed: true` and `default_source_status: 'USER_PRIVATE'`; writes documents with `user_id` and `portal_type` stamps; idempotent upsert via `matchFields`; fails closed on governed-write errors; works across `high_school`, `university`, `knowledge_explorer` - ## Owner gate Layer B cannot proceed past infrastructure until the owner supplies: + 1. Licence-cleared documents in `docs/rag-sources/` 2. A written licence/rights basis 3. A named human reviewer diff --git a/docs/rag-sources/README.md b/docs/rag-sources/README.md index 773e876..6cb70ac 100644 --- a/docs/rag-sources/README.md +++ b/docs/rag-sources/README.md @@ -9,23 +9,29 @@ may be imported into EasyTutor through the governed RAG import path 1. **No documents may be added without a written licence/rights basis.** Third-party, copyrighted or official material (DW, Goethe, telc, KICD, etc.) is prohibited until Daniel reviews the licence and provenance. -2. **All imports are USER_PRIVATE by default.** `source_status` is always - `USER_PRIVATE` and `provenance` is always `user_imported`. No OFFICIAL or - COMMUNITY claim is made by import. +2. **All imports are USER_PRIVATE by default.** The importer calls the shipped + `storeChunks` path, which always writes `curriculum_scope: 'USER_PRIVATE'`. + `sourceStatus: 'USER_PRIVATE'` and `provenance: 'user_imported'` are stored + in each chunk's JSONB `metadata`; they are not invented table columns. No + OFFICIAL or COMMUNITY claim is made by import. 3. **Imports go through the governed database boundary** (`documents` and - `document_chunks` tables, owner-column `user_id`, portal-scoped). No direct - Supabase writes from UI code. + `document_chunks` tables, owner-column `user_id`, portal-scoped, with + deterministic UUID ids). No direct Supabase writes from UI code. 4. **No document is imported without `--license-confirmed`.** The import script exits with an error if this flag is absent. 5. **No secrets, tokens, learner data or PII** may be present in any document. The validator rejects documents containing API keys, JWTs, emails, phone - numbers or card-like numbers. + numbers or card-like numbers; rejection messages name the pattern only and + never echo the matched material. ## Current state This directory is intentionally empty. No licence-cleared documents have been supplied. Layer B infrastructure (validator, chunker, governed importer, adversarial tests) is implemented but no import has been performed. +Changed-content cleanup is not implemented: re-importing a modified source does +not delete its prior chunks. Do not rely on a re-import to replace content until +that behaviour is specified and tested. Layer B remains **blocked on owner input**: supply licence-cleared documents, a written licence/rights basis and a named human reviewer before any import diff --git a/package-lock.json b/package-lock.json index 633e5f5..11ec268 100644 --- a/package-lock.json +++ b/package-lock.json @@ -7381,9 +7381,9 @@ } }, "node_modules/cross-spawn": { - "version": "7.0.6", - "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", - "integrity": "sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA==", + "version": "7.1.2", + "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.1.2.tgz", + "integrity": "sha512-8BPK2r+sKWC8sDinRwLwrFMq2lXTBBwzYYEB9LiCznfMurOi4FOvQflq3XOLGG+HPdMSVpe+k/s96+AtDEOgPg==", "license": "MIT", "dependencies": { "path-key": "^3.1.0", diff --git a/package.json b/package.json index 4a24ca1..290d409 100644 --- a/package.json +++ b/package.json @@ -118,6 +118,7 @@ }, "private": true, "overrides": { + "cross-spawn": "7.1.2", "shell-quote": "1.12.0" } } diff --git a/scripts/rag/governedImporter.ts b/scripts/rag/governedImporter.ts index 8950f3f..fbdb669 100644 --- a/scripts/rag/governedImporter.ts +++ b/scripts/rag/governedImporter.ts @@ -2,17 +2,21 @@ * Governed RAG document importer (Layer B). * * Writes an import plan produced by scripts/rag/import-documents.mjs through - * the governed database boundary (`Database.governedWrite`). Every imported - * document and chunk is stamped `source_status: 'USER_PRIVATE'` and written - * through `documents` / `document_chunks`, both of which are owner-column - * governed and portal-scoped tables. + * the shipped `storeChunks` ingestion path (`lib/knowledge.ts`), which itself + * uses the governed database boundary (`Database.governedWrite`). * - * No import happens without an authenticated user and a resolved portal. - * No third-party, copyrighted or official material may be imported without - * a written licence/rights basis and a named human reviewer. + * The committed schema for `documents` and `document_chunks` has UUID primary + * keys and no `source_status` / `provenance` / `chunk_id` / `chunk_index` + * columns. This importer therefore derives UUID ids and puts import metadata + * in the JSONB `metadata` column instead of inventing schema columns. + * + * Every imported chunk is stamped USER_PRIVATE by `storeChunks`; no import + * happens without an authenticated user and a resolved portal. No third-party, + * copyrighted or official material may be imported without a written + * licence/rights basis and a named human reviewer. */ -import { Database } from '../../src/infrastructure/database'; -import type { GovernedPayload } from '../../src/infrastructure/database/taxonomyGuards'; +import { storeChunks } from '../../lib/knowledge'; +import { stableHashId } from '../../lib/stableId'; import type { PortalType } from '../../src/types/canonical'; export interface ImportedDocument { @@ -47,12 +51,14 @@ export interface ImportResult { } /** - * Writes an import plan through the governed database boundary. Each document - * row is inserted into `documents`; each chunk row into `document_chunks`. - * Both tables are owner-column governed (`user_id`) and portal-scoped. + * Writes an import plan through the real ingestion path. Each document gets a + * deterministic UUID derived from its source directory and filename; each + * chunk gets a deterministic UUID derived from the document id and the + * plan's chunk id. Re-importing the same plan therefore upserts, never + * duplicates. * - * Returns a result summary; throws on the first failure so no partial import - * is silently accepted. + * Returns a result summary; throws after collecting explicit errors so no + * failed or dropped chunk is silently accepted. */ export async function importDocumentPlan( plan: ImportPlan, @@ -70,55 +76,42 @@ export async function importDocumentPlan( let totalChunks = 0; for (const doc of plan.documents) { - const docPayload: GovernedPayload = { - title: doc.document, - source_status: 'USER_PRIVATE', - provenance: 'user_imported', - size_bytes: doc.size_bytes, - source_dir: plan.source_dir, - generated_at: plan.generated_at, - portal_type: portalType, - }; + const documentId = stableHashId(`${plan.source_dir}|${doc.document}`); + const chunks = doc.chunks.map((chunk) => ({ + id: stableHashId(`${documentId}|${chunk.id}`), + content: chunk.content, + metadata: { + chunkIndex: chunk.index, + sizeChars: chunk.size_chars, + sourceDocument: doc.document, + sourceDir: plan.source_dir, + sourceId: chunk.id, + generatedAt: plan.generated_at, + sourceStatus: doc.source_status, + provenance: doc.provenance, + }, + })); try { - await Database.governedWrite('documents', docPayload, { - portalType, + const result = await storeChunks({ userId, - matchFields: { title: doc.document, user_id: userId }, + portalType, + documentId, + title: doc.document, + chunks, }); + totalChunks += result.stored; + if (result.failed > 0 || result.stored !== result.total) { + errors.push({ + document: doc.document, + error: `${result.failed} of ${result.total} chunk write(s) failed`, + }); + } } catch (err: unknown) { errors.push({ document: doc.document, error: err instanceof Error ? err.message : String(err), }); - continue; - } - - for (const chunk of doc.chunks) { - const chunkPayload: GovernedPayload = { - chunk_id: chunk.id, - content: chunk.content, - chunk_index: chunk.index, - size_chars: chunk.size_chars, - source_document: doc.document, - source_status: 'USER_PRIVATE', - provenance: 'user_imported', - portal_type: portalType, - }; - - try { - await Database.governedWrite('document_chunks', chunkPayload, { - portalType, - userId, - matchFields: { chunk_id: chunk.id, user_id: userId }, - }); - totalChunks += 1; - } catch (err: unknown) { - errors.push({ - document: doc.document, - error: `chunk ${chunk.index}: ${err instanceof Error ? err.message : String(err)}`, - }); - } } } diff --git a/scripts/rag/import-documents.mjs b/scripts/rag/import-documents.mjs index f62c4f3..ed8b455 100644 --- a/scripts/rag/import-documents.mjs +++ b/scripts/rag/import-documents.mjs @@ -27,18 +27,18 @@ const MAX_CHUNK_CHARS = 1200; const CHUNK_OVERLAP_CHARS = 100; const SECRET_PATTERNS = [ - /sk-[A-Za-z0-9]{20,}/g, // OpenAI-style keys - /pk_[A-Za-z0-9]{20,}/g, // Publishable keys - /AKIA[0-9A-Z]{16}/g, // AWS access keys - /ghp_[A-Za-z0-9]{20,}/g, // GitHub personal tokens - /eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, // JWT - /[0-9a-f]{32,}/gi, // raw hex secrets + { code: 'openai_key', pattern: /sk-[A-Za-z0-9]{20,}/g }, + { code: 'publishable_key', pattern: /pk_[A-Za-z0-9]{20,}/g }, + { code: 'aws_access_key', pattern: /AKIA[0-9A-Z]{16}/g }, + { code: 'github_token', pattern: /ghp_[A-Za-z0-9]{20,}/g }, + { code: 'jwt', pattern: /eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g }, + { code: 'raw_hex_secret', pattern: /[0-9a-f]{32,}/gi }, ]; const PII_PATTERNS = [ - /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, // email - /\b\d{3}[-.]\d{3}[-.]\d{4}\b/g, // US phone - /\b\d{4}[-\s]\d{4}[-\s]\d{4}[-\s]\d{4}\b/g, // card-like numbers + { code: 'email', pattern: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g }, + { code: 'phone', pattern: /\b\d{3}[-.]\d{3}[-.]\d{4}\b/g }, + { code: 'card_like_number', pattern: /\b\d{4}[-\s]\d{4}[-\s]\d{4}[-\s]\d{4}\b/g }, ]; function slugify(value) { @@ -61,19 +61,21 @@ function chunkText(text, docId) { for (const para of paragraphs) { const trimmed = para.trim(); if (trimmed.length <= MAX_CHUNK_CHARS) { + const chunkIndex = index++; chunks.push({ - id: `chunk-${docId}-${sha256(trimmed).slice(0, 12)}`, + id: `chunk-${docId}-${sha256(`${chunkIndex}:${trimmed}`).slice(0, 12)}`, content: trimmed, - index: index++, + index: chunkIndex, }); } else { let offset = 0; while (offset < trimmed.length) { + const chunkIndex = index++; const piece = trimmed.slice(offset, offset + MAX_CHUNK_CHARS); chunks.push({ - id: `chunk-${docId}-${sha256(piece).slice(0, 12)}`, + id: `chunk-${docId}-${sha256(`${chunkIndex}:${piece}`).slice(0, 12)}`, content: piece, - index: index++, + index: chunkIndex, }); offset += MAX_CHUNK_CHARS - CHUNK_OVERLAP_CHARS; } @@ -84,23 +86,19 @@ function chunkText(text, docId) { } function findSecrets(content) { - const found = []; - for (const pattern of SECRET_PATTERNS) { - for (const match of content.matchAll(pattern)) { - found.push(match[0].slice(0, 8) + '…'); - } + const found = new Set(); + for (const { code, pattern } of SECRET_PATTERNS) { + if (content.match(pattern)) found.add(code); } - return found; + return [...found]; } function findPii(content) { - const found = []; - for (const pattern of PII_PATTERNS) { - for (const match of content.matchAll(pattern)) { - found.push(match[0].slice(0, 12) + '…'); - } + const found = new Set(); + for (const { code, pattern } of PII_PATTERNS) { + if (content.match(pattern)) found.add(code); } - return found; + return [...found]; } function validateDocument(filePath, content) { diff --git a/sprints/sprint_101_promotion_and_hosted_infrastructure.md b/sprints/sprint_101_promotion_and_hosted_infrastructure.md index 7de851f..1e245a8 100644 --- a/sprints/sprint_101_promotion_and_hosted_infrastructure.md +++ b/sprints/sprint_101_promotion_and_hosted_infrastructure.md @@ -119,28 +119,36 @@ created for cleanup itself; the final handover records the observed result. - Suite ratchet moved by measurement from 129 files / 690 tests to 130 files / 697 tests in `AGENTS.md`, `.github/workflows/ci.yml` and `README.md`. No threshold was lowered. -## Layer 9 — owner-selected B: RAG source import infrastructure · ENGINEERING DONE, IMPORT BLOCKED +## Layer 9 — owner-selected B: RAG source import infrastructure · ENGINEERING CORRECTED, IMPORT BLOCKED - Gate-safe infrastructure only; no document imported. - `src/rag/documentProcessor.ts` — shared validation (API key, JWT, GitHub token, email, - phone, card-like PII detection) and deterministic chunking (`chunk-{docId}-{sha256}`, - unique IDs, sequential indices, overlap splitting). + phone, card-like PII detection) and deterministic chunking + (`chunk-{docId}-{sha256(index:content)}`, unique IDs including repeated paragraphs, + sequential indices, overlap splitting). Rejections return pattern labels only; matched + secret/PII material is never echoed. - `scripts/rag/import-documents.mjs` — pure Node ESM import plan generator; reads `.txt`/`.md` from `docs/rag-sources/`, validates, chunks, emits JSON plan; requires `--license-confirmed` (fail-closed). -- `scripts/rag/governedImporter.ts` — writes the plan through `Database.governedWrite` to - `documents` + `document_chunks`; every row stamped `source_status: 'USER_PRIVATE'`, - `provenance: 'user_imported'`, owner `user_id`, portal type; idempotent upsert via - `matchFields`; fails closed on write error. -- `tests/rag/documentImport.test.ts` — adversarial tests: secret/PII rejection, deterministic - unique chunk IDs, USER_PRIVATE marking, owner/portal stamping, idempotent upsert, fail-closed - on write error, all three portal types (`high_school`, `university`, `knowledge_explorer`). +- `scripts/rag/governedImporter.ts` — routes the plan through the shipped `storeChunks` + ingestion path (`lib/knowledge.ts` → `Database.governedWrite`) to `documents` + + `document_chunks`; deterministic UUID document/chunk ids; `USER_PRIVATE` scope is enforced + by `storeChunks`; import metadata lives in the JSONB `metadata` column. No invented schema + columns (`source_status`, `chunk_id`, etc. do not exist in the committed schema). +- `tests/rag/documentImport.test.ts` — adversarial tests: secret/PII rejection without echo, + deterministic unique chunk IDs including repeated paragraphs, real-schema column allowlist, + UUID ids, USER_PRIVATE marking, owner/portal stamping, idempotent upsert, fail-closed on + document and chunk write errors, all three portal types (`high_school`, `university`, + `knowledge_explorer`). +- Observed red control: the final test file against base `78f0b06` exited 1 with 5 failed / + 20 passed (25 tests). Corrected tree passed 25/25. - `docs/rag-sources/README.md` — intake rules: no documents without a written licence/rights basis, USER_PRIVATE default, governed boundary only, `--license-confirmed` required. -- `docs/evidence/S101-B-rag-import-staging.md` — staging evidence and blocker documentation. +- `docs/evidence/S101-B-rag-import-staging.md` — corrected staging evidence and blocker + documentation. **Blocked on owner input:** `docs/rag-sources/` is intentionally empty; no licence-cleared documents, no licence/rights basis and no named human reviewer have been supplied. No document has been imported. No OFFICIAL or COMMUNITY claim is made. C and D were not started as code. -Suite ratchet unchanged at 130 files / 697 tests. +Suite ratchet unchanged at 131 files / 722 tests. diff --git a/src/rag/documentProcessor.ts b/src/rag/documentProcessor.ts index 4a16a49..fdd7555 100644 --- a/src/rag/documentProcessor.ts +++ b/src/rag/documentProcessor.ts @@ -24,19 +24,19 @@ export const MAX_DOCUMENT_BYTES = 1_048_576; // 1 MiB export const MAX_CHUNK_CHARS = 1200; export const CHUNK_OVERLAP_CHARS = 100; -export const SECRET_PATTERNS: RegExp[] = [ - /sk-[A-Za-z0-9]{20,}/g, - /pk_[A-Za-z0-9]{20,}/g, - /AKIA[0-9A-Z]{16}/g, - /ghp_[A-Za-z0-9]{20,}/g, - /eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, - /[0-9a-f]{32,}/gi, +export const SECRET_PATTERNS: ReadonlyArray<{ code: string; pattern: RegExp }> = [ + { code: 'openai_key', pattern: /sk-[A-Za-z0-9]{20,}/g }, + { code: 'publishable_key', pattern: /pk_[A-Za-z0-9]{20,}/g }, + { code: 'aws_access_key', pattern: /AKIA[0-9A-Z]{16}/g }, + { code: 'github_token', pattern: /ghp_[A-Za-z0-9]{20,}/g }, + { code: 'jwt', pattern: /eyJ[A-Za-z0-9_-]+\.eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g }, + { code: 'raw_hex_secret', pattern: /[0-9a-f]{32,}/gi }, ]; -export const PII_PATTERNS: RegExp[] = [ - /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, - /\b\d{3}[-.]\d{3}[-.]\d{4}\b/g, - /\b\d{4}[-\s]\d{4}[-\s]\d{4}[-\s]\d{4}\b/g, +export const PII_PATTERNS: ReadonlyArray<{ code: string; pattern: RegExp }> = [ + { code: 'email', pattern: /[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g }, + { code: 'phone', pattern: /\b\d{3}[-.]\d{3}[-.]\d{4}\b/g }, + { code: 'card_like_number', pattern: /\b\d{4}[-\s]\d{4}[-\s]\d{4}[-\s]\d{4}\b/g }, ]; export function slugify(value: string): string { @@ -51,24 +51,22 @@ export function sha256(content: string): string { return createHash('sha256').update(content, 'utf8').digest('hex'); } +// Never echo matched material: a rejection message that repeats a secret or +// PII turns a fail-closed gate into a leak. Only the pattern label is returned. export function findSecrets(content: string): string[] { - const found: string[] = []; - for (const pattern of SECRET_PATTERNS) { - for (const match of content.matchAll(pattern)) { - found.push(match[0].slice(0, 8) + '…'); - } + const found = new Set(); + for (const { code, pattern } of SECRET_PATTERNS) { + if (content.match(pattern)) found.add(code); } - return found; + return [...found]; } export function findPii(content: string): string[] { - const found: string[] = []; - for (const pattern of PII_PATTERNS) { - for (const match of content.matchAll(pattern)) { - found.push(match[0].slice(0, 12) + '…'); - } + const found = new Set(); + for (const { code, pattern } of PII_PATTERNS) { + if (content.match(pattern)) found.add(code); } - return found; + return [...found]; } export function validateDocument(content: string): ValidationIssue[] { @@ -95,20 +93,22 @@ export function chunkText(text: string, docId: string): DocumentChunk[] { for (const para of paragraphs) { const trimmed = para.trim(); if (trimmed.length <= MAX_CHUNK_CHARS) { + const chunkIndex = index++; chunks.push({ - id: `chunk-${docId}-${sha256(trimmed).slice(0, 12)}`, + id: `chunk-${docId}-${sha256(`${chunkIndex}:${trimmed}`).slice(0, 12)}`, content: trimmed, - index: index++, + index: chunkIndex, size_chars: trimmed.length, }); } else { let offset = 0; while (offset < trimmed.length) { + const chunkIndex = index++; const piece = trimmed.slice(offset, offset + MAX_CHUNK_CHARS); chunks.push({ - id: `chunk-${docId}-${sha256(piece).slice(0, 12)}`, + id: `chunk-${docId}-${sha256(`${chunkIndex}:${piece}`).slice(0, 12)}`, content: piece, - index: index++, + index: chunkIndex, size_chars: piece.length, }); offset += MAX_CHUNK_CHARS - CHUNK_OVERLAP_CHARS; diff --git a/tests/rag/documentImport.test.ts b/tests/rag/documentImport.test.ts index d7ab15a..6baeec7 100644 --- a/tests/rag/documentImport.test.ts +++ b/tests/rag/documentImport.test.ts @@ -5,14 +5,36 @@ import { findPii, chunkText, sha256, - MAX_DOCUMENT_BYTES, - MAX_CHUNK_CHARS, CHUNK_OVERLAP_CHARS, } from '../../src/rag/documentProcessor'; import { mockSupabase, TEST_USER_ID } from '../utils/mockSupabase'; import { importDocumentPlan } from '../../scripts/rag/governedImporter'; import type { ImportPlan } from '../../scripts/rag/governedImporter'; +const UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i; +const DOCUMENT_COLUMNS = new Set(['id', 'user_id', 'title', 'portal_type', 'updated_at', 'created_at']); +const CHUNK_COLUMNS = new Set([ + 'id', + 'document_id', + 'user_id', + 'content', + 'embedding', + 'metadata', + 'portal_type', + 'taxonomy_scope', + 'curriculum_scope', + 'school_scope', + 'vector_namespace', + 'created_at', + 'content_tsv', +]); + +function expectOnlyColumns(row: Record, allowed: Set) { + for (const key of Object.keys(row)) { + expect(allowed.has(key)).toBe(true); + } +} + function makePlan(overrides: Partial = {}): ImportPlan { return { generated_at: '2026-11-30T00:00:00.000Z', @@ -72,18 +94,33 @@ describe('document validation', () => { expect(issues.some((i) => i.code === 'PII_DETECTED')).toBe(true); }); - it('findSecrets returns abbreviated matches', () => { + it('findSecrets returns pattern labels without echoing key material', () => { const keyPrefix = 'sk-'; const keyBody = '1234567890abcdef1234567890abcdef'; - const found = findSecrets(keyPrefix + keyBody); - expect(found.length).toBe(2); - expect(found[0]).toBe('sk-12345…'); + const raw = keyPrefix + keyBody; + const found = findSecrets(raw); + expect(found).toContain('openai_key'); + expect(found.join(' ')).not.toContain(keyBody); + expect(found.join(' ')).not.toContain(keyPrefix); + + const detail = validateDocument(`My key is ${raw}.`).find((issue) => issue.code === 'SECRET_DETECTED')?.detail; + expect(detail).toBeDefined(); + expect(detail).not.toContain(keyBody); + expect(detail).not.toContain(keyPrefix); }); - it('findPii returns abbreviated matches', () => { - const found = findPii('user@example.com'); - expect(found.length).toBe(1); - expect(found[0]).toBe('user@example…'); + it('findPii returns pattern labels without echoing PII', () => { + const raw = 'user@example.com'; + const found = findPii(raw); + expect(found).toEqual(['email']); + expect(found.join(' ')).not.toContain(raw); + + const detail = validateDocument(`Contact me at ${raw} for details.`).find( + (issue) => issue.code === 'PII_DETECTED', + )?.detail; + expect(detail).toBeDefined(); + expect(detail).not.toContain(raw); + expect(detail).not.toContain('user@'); }); it('does not flag normal German words as secrets', () => { @@ -102,11 +139,12 @@ describe('deterministic chunking', () => { expect(a).toEqual(b); }); - it('produces unique chunk IDs', () => { - const text = 'Paragraph one.\n\nParagraph two.\n\nParagraph three.'; + it('produces unique chunk IDs, including repeated identical paragraphs', () => { + const text = 'Paragraph one.\n\nParagraph two.\n\nSame paragraph.\n\nSame paragraph.'; const chunks = chunkText(text, 'doc-test-abc123'); const ids = chunks.map((c) => c.id); expect(new Set(ids).size).toBe(ids.length); + expect(chunks).toHaveLength(4); }); it('assigns sequential chunk indices starting at 0', () => { @@ -175,7 +213,7 @@ describe('governed importer', () => { expect(mockSupabase.db.document_chunks).toHaveLength(0); }); - it('writes each document through the governed boundary with USER_PRIVATE marking', async () => { + it('writes each document through the governed boundary using only real schema columns', async () => { const plan = makePlan(); const result = await importDocumentPlan(plan, 'knowledge_explorer', TEST_USER_ID); @@ -183,33 +221,39 @@ describe('governed importer', () => { expect(result.errors).toHaveLength(0); const docRow = mockSupabase.db.documents[0]; + expect(docRow.id).toMatch(UUID_PATTERN); expect(docRow.title).toBe('sample.txt'); - expect(docRow.source_status).toBe('USER_PRIVATE'); - expect(docRow.provenance).toBe('user_imported'); expect(docRow.user_id).toBe(TEST_USER_ID); expect(docRow.portal_type).toBe('knowledge_explorer'); - expect(docRow.size_bytes).toBe(42); + expectOnlyColumns(docRow, DOCUMENT_COLUMNS); }); - it('writes each chunk through the governed boundary with USER_PRIVATE marking', async () => { + it('writes each chunk through the governed boundary with UUID ids, owner portal and USER_PRIVATE scope', async () => { const plan = makePlan(); await importDocumentPlan(plan, 'knowledge_explorer', TEST_USER_ID); + const docRow = mockSupabase.db.documents[0]; const chunkRows = mockSupabase.db.document_chunks; expect(chunkRows).toHaveLength(2); for (const row of chunkRows) { - expect(row.source_status).toBe('USER_PRIVATE'); - expect(row.provenance).toBe('user_imported'); + expect(row.id).toMatch(UUID_PATTERN); + expect(row.document_id).toBe(docRow.id); expect(row.user_id).toBe(TEST_USER_ID); expect(row.portal_type).toBe('knowledge_explorer'); - expect(row.chunk_id).toMatch(/^chunk-/); + expect(row.curriculum_scope).toBe('USER_PRIVATE'); + expect(row.metadata.sourceStatus).toBe('USER_PRIVATE'); + expect(row.metadata.provenance).toBe('user_imported'); + // These fields are stamped by the real storeChunks ingestion path, so + // their presence proves the importer did not write a private schema. + expect(row.metadata.source).toBe('knowledge_explorer'); + expect(row.vector_namespace).toBe('portal:knowledge_explorer'); expect(typeof row.content).toBe('string'); - expect(typeof row.chunk_index).toBe('number'); + expectOnlyColumns(row, CHUNK_COLUMNS); } - expect(chunkRows[0].chunk_index).toBe(0); - expect(chunkRows[1].chunk_index).toBe(1); + expect(chunkRows[0].metadata.chunkIndex).toBe(0); + expect(chunkRows[1].metadata.chunkIndex).toBe(1); }); it('uses matchFields for idempotent upsert on documents', async () => { @@ -223,15 +267,26 @@ describe('governed importer', () => { expect(mockSupabase.db.document_chunks).toHaveLength(2); }); - it('fails closed when a governed write fails', async () => { - mockSupabase.failNext('documents', 'upsert', 'row-level security policy violation', '42501'); + it('fails closed when a document or chunk governed write fails', async () => { const plan = makePlan(); + mockSupabase.failNext('documents', 'upsert', 'row-level security policy violation', '42501'); await expect(importDocumentPlan(plan, 'knowledge_explorer', TEST_USER_ID)).rejects.toThrow( /GOVERNANCE ERROR/, ); - // No partial data should remain because the document write failed + // No partial data should remain because the document write failed. expect(mockSupabase.db.documents).toHaveLength(0); + + mockSupabase.reset(); + mockSupabase.failNext('document_chunks', 'upsert', 'row-level security policy violation', '42501'); + mockSupabase.failNext('document_chunks', 'upsert', 'row-level security policy violation', '42501'); + await expect(importDocumentPlan(plan, 'knowledge_explorer', TEST_USER_ID)).rejects.toThrow( + /GOVERNANCE ERROR/, + ); + // storeChunks records the chunk failure instead of silently dropping it; + // the importer turns that into an explicit rejection. The parent document + // row may exist, but no chunk was silently accepted. + expect(mockSupabase.db.document_chunks).toHaveLength(0); }); it('works across all three portal types', async () => {