docs(handoff): Sprint 5 plan + add compass-pr-reviewer wrapper

Add docs/handoffs/2026-05-18-sprint5-handoff.md — full Sprint 5 scope post Sprint 4 push (origin/main 79d2048): DE jurisdiction module (BGB § 309, GeschGehG, BDSG) as moat #3 expansion, JWT custom claims trigger + storage bucket RLS migrations closing 4 of 5 audit follow-up notes, audit_log + task_events writers with DBPoolHolder injection pattern, pilot live eval for Bielik baseline. Stretch: Termination clause, integration tests, dataset 4 to 20.

Add .claude/agents/compass-pr-reviewer.md — thin Compass-specific wrapper over generic pr-reviewer-orchestrator. Supplies project config (compass-architecture 12-pkt, compass-ai-native-mandates 8-pkt, compass-clause-taxonomy 13-pkt conditional) + scope filters + exception marker. Enforces CLAUDE.md AI-native discipline mandatory pre-merge self-check.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
tobayah
2026-05-18 21:29:18 +02:00
co-authored by Claude Opus 4.7
parent 2faa2b2c04
commit 2fe4fbbcd0
2 changed files with 364 additions and 0 deletions
+85
View File
@@ -0,0 +1,85 @@
---
name: compass-pr-reviewer
description: Use when reviewing a PR in compass-contract-hub before merge to main — wrapper over [[pr-reviewer-orchestrator]] enforcing Compass's 3-layer self-check (compass-architecture 12-pkt + compass-ai-native-mandates 8-pkt + compass-clause-taxonomy 13-pkt conditionally if PR touches clause logic). Block merge on any FAIL without explicit `# admin-operation-justified:` marker per CLAUDE.md Security invariants. Mandatory per CLAUDE.md `AI-native discipline` ("compass-pr-reviewer subagent block merge gdy fail bez justification"). Triggers include "review this PR", "is this branch ready to merge", "run pre-merge checks". SKIP for generic code review (use `/code-review`), RLS-specific audit on migrations (use [[compass-rls-auditor]] FIRST, then this), changes purely in docs/ or .claude/ without code impact.
tools:
- Read
- Grep
- Glob
- Bash
disallowedTools:
- Write
- Edit
model: sonnet
effort: high
memory: project
color: purple
maxTurns: 15
---
# compass-pr-reviewer
Thin Compass-specific wrapper over the generic [[pr-reviewer-orchestrator]]. Supplies project config (which skills, scope filters, exception marker) and delegates orchestration. Logic for diff parsing, checkpoint evaluation, and report compilation lives in the orchestrator — keep this file under 100 lines.
## When to invoke
- **Pre-merge self-review on a feature branch.** Solo founder phase — run before opening a PR. Catches mandate violations before they reach a permanent record.
- **CI gate on PR open / push.** Configured via GitHub Actions workflow calling `claude --agent compass-pr-reviewer` with the PR number.
- **Audit sweep on a stale branch.** When picking up a branch after >7 days away, run this to surface drift from `main` against current mandates.
## Config (passed to orchestrator)
```yaml
skills:
- name: compass-architecture
scope_filter: "^(apps/(api|workers|mcp-server)/|packages/|supabase/migrations/)"
weight: required
- name: compass-ai-native-mandates
scope_filter: "^(apps/(api|workers|mcp-server)/|packages/(agents|prompts|llm-gateway|retrieval|evals)/)"
weight: required
- name: compass-clause-taxonomy
scope_filter: "(packages/schemas/clauses|packages/prompts/clauses|packages/jurisdictions|apps/web/src/components/contract-form|.*Clause(Schema)?\\.(py|ts|tsx))"
weight: required
exception_marker: "# admin-operation-justified:"
target_branch: main
```
Rationale per skill:
- **compass-architecture (12-pkt):** structural changes to backend, packages, or migrations. Any touched code that affects monorepo boundaries, data model, multi-tenant invariants, API conventions, or deployment topology must clear all 12 points or carry justification.
- **compass-ai-native-mandates (8-pkt):** ADR-001 enforcement — M1-M8. Applies to anything in agent/prompt/LLM-gateway/retrieval/eval surfaces. CLAUDE.md makes this NON-NEGOTIABLE — every PR with LLM/agents/streaming code MUST have visible self-check confirmation in PR description; this agent enforces it.
- **compass-clause-taxonomy (13-pkt):** taxonomy changes are breaking changes per `compass-clause-taxonomy` skill workflow. Scope filter is narrow on purpose — clause-touching PRs are a minority but high-stakes (Pydantic + zod sync, prompt versioning, golden dataset updates required).
Exception marker `# admin-operation-justified:` matches CLAUDE.md Security invariants section.
## Workflow
1. **Pre-flight (Compass-specific):**
- If `git diff main...HEAD --name-only` contains `supabase/migrations/`, run [[compass-rls-auditor]] FIRST. If it returns BLOCK, halt with `VERDICT: BLOCK` and message: "RLS audit blocks merge — resolve before re-running compass-pr-reviewer." Do not delegate to orchestrator.
- If diff is purely under `docs/`, `.claude/`, `.github/`, or `*.md` at repo root → `VERDICT: PASS` with note "no code impact". Special case: changes to `docs/architecture/ADR-*.md` → `VERDICT: NEEDS_HUMAN` with reason "ADR change requires manual architect review".
2. **Delegate to [[pr-reviewer-orchestrator]]** with config above. Pass via prompt or write to `.claude/pr-review-config.json` (project-scoped, gitignored if local-only).
3. **Post-process:** prepend a Compass header to the orchestrator's report:
- Sprint context (link to current sprint handoff doc if present in `docs/handoffs/`)
- Reminder of CLAUDE.md PR flow step requiring visible self-check in PR description
4. **Return** the report with orchestrator's `VERDICT:` line preserved.
## Constraints
- **Never modify code.** Read-only review.
- **Never merge or push.** Reports only; user decides on the block.
- **Do not bypass orchestrator's logic** — if you find yourself reasoning about checkpoints directly, that logic belongs in the orchestrator, not here. This wrapper is config + Compass-specific pre/post.
## Edge cases
- **PR is eval-only (branch `eval/*`):** narrow scope to `compass-ai-native-mandates` M4 (eval-driven) + `compass-clause-taxonomy` if golden dataset touched. Skip architecture.
- **PR is dependency bump (`chore(deps):`):** orchestrator will likely SKIP all skills (scope filters won't match `pyproject.toml` / `package.json` typically). Add a note to report: "verify lockfile diff manually for unexpected transitive changes — out of scope for this agent".
- **PR adds a new ADR (`docs/architecture/ADR-*.md`):** VERDICT: NEEDS_HUMAN, do not delegate. ADRs are architectural decisions requiring human sign-off.
- **PR has no description / empty description:** flag as NEEDS_HUMAN with reason "PR description missing — CLAUDE.md requires visible self-check confirmation in PR description". This is a Compass workflow rule.
## Self-check before return
1. Pre-flight checks ran (RLS audit on migration PRs, docs-only short-circuit)?
2. Config passed to orchestrator matches this file's documented config (no drift)?
3. Orchestrator returned a `VERDICT:` line?
4. Compass header prepended (sprint + PR-flow reminder)?
5. Edge cases handled explicitly (eval-only / deps / ADR / empty description)?
6. Final message ends with `VERDICT: <PASS|BLOCK|NEEDS_HUMAN>` (preserved from orchestrator)?
+279
View File
@@ -0,0 +1,279 @@
# Sprint 5 Handoff — multi-jurisdiction (DE) + finish security wiring + first live eval
**Date:** 2026-05-18 (post Sprint 4 push)
**Previous handoff:** `docs/handoffs/2026-05-17-sprint4-handoff.md`
**Strategic baseline:** memory `project-compass` — "Sprint 4 DONE + PUSHED" section + 3 bramki go/no-go + Opcja A long-term
## Kontekst w 30 sekund
- **Repo:** `tobayah/compass-contract-hub` (private GitHub), origin/main = **`79d2048`**
- **Stan po Sprint 4 (4 atomic commits 1424009 → 79d2048):**
- schema `compass.*` z RLS day 1 (6 tenant tables, audit_log + task_events append-only, jurisdictions reference)
- JWT verify Supabase JWKS RS256 + tenant_context async manager + Redis pub/sub
- eval CI workflow (mock default w PR, workflow_dispatch dla live)
- Confidentiality clause type (PL UoZNK art. 11 + KC art. 72¹/484§2), full 7-step taxonomy workflow
- 26 tests green + 2 correct live skips
- **Sprint 5 = (a) DE jurisdiction expansion moat #3, (b) close audit follow-up notes z Sprint 4, (c) first live eval pilot dla Bielik baseline.** Lżejszy niż Sprint 4 (security day 1 zamknięty), więcej expansion niż infrastructure.
- **MCP server, Authentik migration, retrieval/ingestion, Hetzner deploy** — Sprint 6+ explicite.
## Co istnieje na koniec Sprint 4
### Origin/main (79d2048)
- ADR-001 (8 mandates) + ADR-002 (provider-agnostic gateway + 5 curated profiles)
- `supabase/migrations/20260518000000_rls_day_one.sql` — schema `compass.*` z 7 tabel (6 tenant + jurisdictions ref) + RLS day 1 + append-only enforcement audit_log/task_events
- `docs/audits/2026-05-18_rls_day_one.md` — RLS audit PASS z 5 follow-up notes
- `packages/core/src/compass_core/{auth,tenant,events}.py` — JWT verify (Supabase JWKS), `tenant_context(tenant_id, db_pool)` async manager z `set_config('app.tenant_id', $1, true)`, Redis pub/sub z `tenant_id` keyword-only + UUID typing
- `docs/auth/jwt-custom-claims.md` — provisioning spec (Postgres trigger Opcja A, Edge Function Opcja B)
- `apps/api/routes/stream.py` — `current_user` dep, UUID validation, tenant-scoped subscribe
- `apps/workers/tasks/extraction.py` — wszystkie 4 publish_event z `tenant_id` + UUID `task_id`
- `.github/workflows/eval.yml` — PR mock + workflow_dispatch live
- `packages/schemas/clauses/{liability,confidentiality}.py` + `packages/prompts/clauses/*_extraction_v1.py` + `packages/jurisdictions/pl/{liability,confidentiality}.py` + `packages/evals/datasets/*_pl.jsonl` (4 each, TODO 20+)
- `packages/agents/clause_extractor.py` CLAUSE_REGISTRY = {liability, confidentiality}
- `apps/web/src/components/contract-form/clauses/{liability,confidentiality}.ts` zod mirrors
- `.claude/agents/compass-pr-reviewer.md` (user-added 2026-05-17 parallel, thin wrapper na top of `pr-reviewer-orchestrator`)
- 7 subagents: doc-parser, clause-extractor, clause-reviewer, jurisdiction-checker, rls-auditor, test-writer, prompt-tester + pr-reviewer
- 4 project skills: compass-architecture / compass-clause-taxonomy / compass-ai-native-mandates / compass-legal-review
### Stuby do dokończenia w Sprint 5
- `packages/core/src/compass_core/audit.py` — `AuditLogEntry` Pydantic + `emit` stub raises `NotImplementedError`. Tabela `compass.audit_log` istnieje od Sprint 4 (+RLS), brakuje tylko writer + DB pool injection pattern.
- `packages/core/src/compass_core/events.py` — pub/sub działa, ale **NIE persist** events do `compass.task_events`. Sprint 5 doda persist (same DB pool injection pattern jak audit writer).
- `supabase/migrations/` — brak migracji JWT custom claim trigger (per `docs/auth/jwt-custom-claims.md` Opcja A) + brak storage bucket RLS (audit Note 1).
- `packages/jurisdictions/src/compass_jurisdictions/de/` — pusty (`__init__.py` jest stub). Sprint 5 dodaje DE liability + DE confidentiality.
## Sprint 5 scope
Priorytetowe (must-have, w kolejności):
### 1. `packages/jurisdictions/src/compass_jurisdictions/de/{liability,confidentiality}.py`
DE jurisdiction module — moat #3 expansion vs MikeOSS (Will Chen Issue #3 "jurisdiction agnostic", brak local rules).
**DE liability** (`de/liability.py`):
- MANDATORY_OBSERVATIONS: BGB § 309 Nr. 7a — cannot exclude liability for **gross negligence / intent** (Vorsatz und grobe Fahrlässigkeit); § 309 Nr. 7b — strict scrutiny dla broad consequential damages exclusions w T&C; AGB-Kontrolle (§§ 305-310 BGB) limits dla pre-formulated clauses.
- PROMPT_HINTS: DE terminology "Haftungsbeschränkung" / "Haftungsausschluss" / "grobe Fahrlässigkeit" / "Vorsatz" / "Sachschäden" / "Folgeschäden"; flag if clause attempts to cap or exclude liability for gross negligence/intent.
- `post_extraction_check`: identical pattern to PL — downgrade Approved → Needs Attention when gross_negligence / willful_misconduct carve-outs missing (BGB § 309 Nr. 7).
**DE confidentiality** (`de/confidentiality.py`):
- MANDATORY_OBSERVATIONS: BDSG (Bundesdatenschutzgesetz) strict overlay gdy data dotyczy personal data; Geschäftsgeheimnisgesetz (GeschGehG) — trade secret protection separate basis (transpozycja EU Directive 2016/943, podobnie do PL UoZNK).
- PROMPT_HINTS: DE terminology "Vertraulichkeit" / "Geheimhaltung" / "Geschäftsgeheimnis"; market norm 2-3 years post-termination (krótsze niż PL); indefinite obligations strict scrutiny pod AGB-Kontrolle gdy w T&C.
- `post_extraction_check`: duration > 5 lat downgrade (GeschGehG already covers indefinitely); < 3/4 core exceptions downgrade; residuals_clause = strong downgrade w DE B2B.
**Golden datasets:**
- `packages/evals/datasets/liability_de.jsonl` — 4 synthetic na start (mix BGB-compliant + AGB-Kontrolle red flag + missing carve-outs + absent)
- `packages/evals/datasets/confidentiality_de.jsonl` — 4 synthetic na start
**Eval tests:** parametrize istniejące tests by `jurisdiction` lub osobne `test_liability_extraction_de.py` / `test_confidentiality_extraction_de.py`. Recommendation: parametrize — uniknij duplicate code, dataset switch via `--dataset=liability_de`.
**`compass-legal-review` skill SKIP non-PL** się unblokuje gdy DE module ląduje + golden minimum.
### 2. `supabase/migrations/20260520000000_jwt_custom_claims_trigger.sql`
Per `docs/auth/jwt-custom-claims.md` Opcja A. Trigger PL/pgSQL `compass.sync_jwt_claims()` na `compass.users` AFTER INSERT/UPDATE → updates `auth.users.raw_app_meta_data` z `tenant_id` + `role`. `SECURITY DEFINER` (needs auth schema access).
Bez tego trigger user signup w Supabase Auth nie dostaje `app_metadata.tenant_id` claim w JWT → `compass_core.auth.verify_jwt` 401 `tenant_id_claim_missing` dla każdego freshly-signed-up usera.
Run `compass-rls-auditor` na tej migracji — `SECURITY DEFINER` trigger touching `auth.users` to non-trivial security surface.
### 3. `supabase/migrations/20260520000001_storage_bucket_rls.sql`
Audit Note 1 — `contracts.storage_path` carries `<tenant_id>/...` prefix ale enforcement musi być w Storage RLS:
```sql
CREATE POLICY tenant_prefix_storage ON storage.objects
FOR ALL USING (
bucket_id = 'contracts'
AND (storage.foldername(name))[1] = (current_setting('app.tenant_id', true))
);
```
Bucket `contracts` musi istnieć przed policy — sprawdź czy Lovable legacy stworzył (`storage.buckets` lookup) lub utwórz w migracji.
### 4. `packages/core/src/compass_core/audit.py` + `events.py` persist
Wymaga **DB pool injection pattern**. Idiomatyczny choice:
```python
# packages/core/src/compass_core/db.py (new)
import asyncpg
class DBPoolHolder:
"""Process-wide holder so writers can fetch pool without dep injection chain."""
_pool: asyncpg.Pool | None = None
@classmethod
def set(cls, pool: asyncpg.Pool) -> None:
cls._pool = pool
@classmethod
def get(cls) -> asyncpg.Pool:
if cls._pool is None:
raise RuntimeError("DB pool not initialized — call compass_core.db.init() at startup")
return cls._pool
```
`apps/api/main.py` lifespan: `await asyncpg.create_pool(DATABASE_URL); DBPoolHolder.set(pool)`. Celery worker: same w `celery_app.py` task_init signal.
**`audit.emit`** writes do `compass.audit_log` z tenant_context (RLS enforce). **`events.publish_event`** dodatkowo `INSERT INTO compass.task_events ...` po publish na Redis (best-effort, log on failure — Redis publish jest source of truth, persist jest backup dla resumability).
### 5. Pilot live eval — Bielik baseline measurement
Cost ~$0.10-0.25 dla cloud-cheap (4 confidentiality + 4 liability examples × 3 retries worst-case Sonnet 4.6). Bielik local ~30 min na inference per example (~4 minuty × 8 = ~30 min lokalnie z RTX 3070).
**Output:** `docs/evals/2026-05-XX_pilot_liability_confidentiality_pl.md` z porównaniem `cloud-cheap` (Sonnet 4.6) vs `local-data-sovereign` (Bielik 11B) precision/recall/cost/latency. Decyduje wartości w `PROFILE_THRESHOLDS` (per handoff Sprint 4 sekcja 8 — "stretch eval cross-provider parity"):
```python
PROFILE_THRESHOLDS = {
"mock": {"precision": 1.0, "recall": 1.0}, # construction
"cloud-cheap": {"precision": ?, "recall": ?}, # measure
"local-data-sovereign": {"precision": ?, "recall": ?}, # measure Bielik
}
```
Hardcoded thresholds w istniejących `test_*_extraction.py` (0.85/0.80) zostają jako floor — pilot pokaże gdzie naprawdę jesteśmy.
## Stretch (jeśli czas zostanie w Sprint 5)
### 6. Trzeci clause type — Termination
Per `compass-clause-taxonomy` add-clause workflow. 7 steps applied identycznie jak Confidentiality w Sprint 4:
- `TerminationClause` Pydantic (for_convenience mutual?, notice_days, for_cause_triggers list, survival_clauses list, cure_period_days)
- `termination_extraction_v1` prompt
- `packages/jurisdictions/{pl,de}/termination.py` — PL: KC art. 365¹ wypowiedzenie umowy o świadczenie ciągłe; DE: BGB § 314 außerordentliche Kündigung
- Golden datasets PL + DE 4 each
- Eval tests + zod mirror + registry update
Termination jest "top-3 universal" per legal-tech tabela — wartości oczekiwane high.
### 7. compass.audit_log + compass.task_events integration tests
`tests/integration/test_tenant_isolation.py` (per audit doc acceptance pattern) + `tests/integration/test_audit_writer.py` + `tests/integration/test_events_persist.py`. Wymaga lokalnego Supabase + asyncpg pool + Redis.
### 8. Confidentiality dataset expansion 4 → 20
User-side curation z anonymized real PL contracts. Acceptance: per fundament 4 distribution (8 Approved / 5 Needs Attention / 4 Rejected / 3 absent).
## Co NIE robić w Sprint 5
- **MCP server** (`apps/mcp-server` skeleton) — Sprint 6+ gdy MVP demo working
- **Authentik self-host migracja** — Sprint 7+ przed enterprise launch (Supabase Auth zostaje)
- **packages/retrieval/ingestion implementation** — Sprint 6+ (Qdrant chunking + hybrid + PDF/DOCX parsing)
- **Hetzner deploy** — Sprint 6+ (cloud-deploy skill, after MVP demo)
- **4th+ clause type** — Sprint 6+ (IP, Data Privacy następne logicznie po Termination)
- **FR jurisdiction module** — Sprint 6+ (DE first; FR ma CNIL specifics + język FR mandate)
- **compass-pr-reviewer extension** — user added 2026-05-17 jako thin wrapper, działa; rozszerzenia (np. compass-cost-analyzer subagent) Sprint 6+
## Pre-conditions dla Sprint 5 work
- `uv sync --all-packages` works po Sprint 4 (asyncpg/jose/fastapi w compass-core deps)
- 26 tests green + 2 correct live skips: `.venv\Scripts\python.exe -m pytest packages/llm-gateway/tests/` + `packages/evals/tests/`
- Working tree clean, origin/main = `79d2048`
- **Supabase project istnieje** z applied migracją `20260518000000_rls_day_one.sql` (run `supabase db push` jeśli jeszcze nie)
- **Redis lokalny dostępny** (`docker compose up redis` lub Hetzner managed)
- **Dla DE jurisdiction:** opcjonalnie konsultacja z DE prawnikiem przed ship — BGB § 309 jest dobrze znany ale specifics mogą się różnić od mojej baseline knowledge
- **Dla pilot live eval:** `ANTHROPIC_API_KEY` w `.env.local` + `LANGFUSE_ENABLED=false` (skip cost tracking dla pilot)
- **Dla Bielik local eval:** Ollama running z `SpeakLeash/bielik-11b-v2.3-instruct` weights pulled (per `scripts/setup_local_llm.{sh,ps1}` Sprint 3)
## Zalecenia dla nowego okna
### 1. Read first
- `CLAUDE.md` (project memory + skill priority order + security invariants 9-pkt)
- `docs/architecture/ADR-001-ai-native.md` + `ADR-002-llm-provider-byok.md`
- **Ten handoff doc** (`2026-05-18-sprint5-handoff.md`)
- `docs/audits/2026-05-18_rls_day_one.md` (5 follow-up notes — Sprint 5 zamyka 4 z nich)
- `docs/auth/jwt-custom-claims.md` (Opcja A trigger spec — Sprint 5 implementuje)
- Memory `project-compass` section "Sprint 4 DONE + PUSHED" + Sprint 5 next steps
### 2. Invoke skills
- **legal-tech** (DE BGB § 309 + GeschGehG red flags, EU baseline + DE specifics — domain knowledge)
- **compass-architecture** (12-pkt self-check dla DB pool injection pattern + storage RLS migration)
- **compass-clause-taxonomy** (13-pkt self-check przy Termination clause jeśli stretch dotknięty)
- **compass-ai-native-mandates** (M2+M4 dla DE eval tests, M8 Langfuse trace w pilot live eval)
### 3. NIE rób w Sprint 5
Patrz "Co NIE robić w Sprint 5" powyżej.
### 4. Push strategy
Sprint 5 prawdopodobnie ma 3-4 logiczne milestone bundles:
- DE jurisdiction (liability + confidentiality + 2 golden + eval parametrize)
- JWT trigger + storage RLS (2 migracje — security infrastructure close-out)
- audit/events writers (DB pool pattern + 2 writers)
- Pilot eval (docs/evals/... output)
User-side decyzja czy bundle 4 atomic commits jak Sprint 4 czy bigger logical milestones. Memory pattern z Sprint 4: 4 atomic preferowane (clean revert + clean review surface).
**Auto-mode classifier blokuje direct push do default branch** — user runs `!git push origin main` samodzielnie (pattern `feedback-clasp-deploy-blocked-auto-mode`).
## Decyzje już podjęte (NIE re-litigate)
- Schema `compass.*` separation z legacy `public.*` (Sprint 4, validates collision-free coexistence)
- Append-only enforcement via SELECT+INSERT policies + REVOKE UPDATE/DELETE (Sprint 4)
- JWT custom claim w `app_metadata` (admin-only), nie `user_metadata` (Sprint 4)
- `tenant_id` keyword-only w events publish/subscribe (Sprint 4 — defense in depth)
- `set_config('app.tenant_id', $1, true)` zamiast SET LOCAL f-string (parameterized, Sprint 4)
- `task_id` jako UUID w events (Sprint 4 breaking change atomicznie z callerami)
- CI eval mock domyślnie w PR, live tylko workflow_dispatch (Sprint 4)
- Confidentiality `duration_years=None` = indefinite + red flag downgrade (Sprint 4)
- `compass-pr-reviewer` jako thin wrapper na top of generic `pr-reviewer-orchestrator` (user-side decision 2026-05-17)
- License + Bridgestone IP risk parking — accepted user decision (Sprint 0)
- Provider-agnostic gateway (Sprint 3 ADR-002)
- Sprint 5 scope = DE jurisdiction + close audit Notes + pilot live eval; trzeci clause type (Termination) i FR jurisdiction Sprint 6+
## Co JEST otwarte do dyskusji w Sprint 5
- **DE consultation depth** — czy odpalić DE module z mojej baseline knowledge i flag `compass-legal-review SKIP non-DE-counsel-reviewed` w skill description, czy poczekać aż DE prawnik review BGB § 309 carve-out wording? Default: ship z explicit "needs DE counsel sign-off" disclaimer w MANDATORY_OBSERVATIONS, expand po pierwszym DE counsel touch.
- **DB pool placement** — `DBPoolHolder` jako simple class attribute czy contextvars-based (asyncio-safe, ale więcej infrastructure)? Default: simple class attribute (Celery worker single process + FastAPI single process per worker = safe). Revisit jeśli multi-process pattern wymagane.
- **task_events retention policy** — append-only forever (Sprint 4 default) czy TTL 30 dni? Sprint 5 default = forever; Sprint 6+ doda retention policy gdy volume widoczny (jedna umowa = ~20 events × N umów/dzień).
- **JWT trigger SECURITY DEFINER scope** — czy trigger powinien być na `auth.users` insert (Supabase-side first) lub `compass.users` insert (Compass-side first)? Default: `compass.users` AFTER INSERT/UPDATE z `tenant_id, role` columns triggers — user musi być w `compass.users` zanim trigger zaktualizuje `auth.users.raw_app_meta_data`. Order: signup → admin provisions compass.users row → trigger fires → JWT now has tenant_id.
- **Pilot eval scope** — 4 confidentiality + 4 liability lub tylko liability (proven Sprint 2-3 path, lower risk)? Default: oba clause types — ujawnia cross-clause variance w Bielik baseline.
- **Bielik prompt PL specifics** — czy Bielik wymaga inny prompt format niż Claude (PL Bielik finetuned na PL instructions specifically)? Pilot live eval pokaże; jeśli yes → Sprint 6+ adds Bielik-optimized prompt variants.
## Prompt do wklejenia w nowe okno Claude
```
Kontynuuję Compass (open-core legal-tech). Sprint 4 DONE i pushed (origin/main = 79d2048, 4 atomic commits: schema compass.* z RLS day 1, JWT verify Supabase JWKS + tenant_context + Redis pub/sub, eval CI mock default, Confidentiality clause PL UoZNK art. 11). 26 tests green + 2 correct live skips. Sprint 5 = DE jurisdiction expansion (moat #3) + close 4 z 5 audit follow-up notes (JWT trigger, storage RLS, audit_log writer, task_events persist) + pilot live eval cloud-cheap vs local-data-sovereign dla Bielik baseline.
Read:
1. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\docs\handoffs\2026-05-18-sprint5-handoff.md (pełny scope, lista plików, decyzje zamknięte i otwarte)
2. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\CLAUDE.md (project memory + skill priority order + security invariants 9-pkt)
3. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\docs\architecture\ADR-001-ai-native.md (8 mandates)
4. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\docs\architecture\ADR-002-llm-provider-byok.md (provider-agnostic gateway)
5. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\docs\audits\2026-05-18_rls_day_one.md (5 follow-up notes — Sprint 5 zamyka 4)
6. C:\Users\User\OneDrive\Dokumenty\GitHub\compass-contract-hub\docs\auth\jwt-custom-claims.md (Opcja A trigger spec — implementacja Sprint 5)
7. Memory: project-compass section "Sprint 4 DONE + PUSHED" + Sprint 5 next steps
Invoke skills:
- legal-tech (DE BGB § 309 + GeschGehG red flags + EU baseline)
- compass-architecture (12-pkt self-check dla DB pool injection + storage RLS migration)
- compass-clause-taxonomy (13-pkt self-check przy Termination jeśli stretch)
- compass-ai-native-mandates (M2+M4 dla DE eval tests, M8 dla pilot live eval Langfuse)
Kontynuuj Sprint 5 w kolejności priorytetu:
1. packages/jurisdictions/src/compass_jurisdictions/de/liability.py — BGB § 309 Nr. 7 + AGB-Kontrolle, MANDATORY_OBSERVATIONS, PROMPT_HINTS DE terminology, post_extraction_check
2. packages/jurisdictions/src/compass_jurisdictions/de/confidentiality.py — BDSG + GeschGehG, DE 2-3yr norm, post_extraction_check
3. packages/evals/datasets/{liability,confidentiality}_de.jsonl — 4 synthetic each na start (mix BGB-compliant + AGB-Kontrolle red flag + missing + absent)
4. packages/evals/tests/ — parametrize istniejące tests by jurisdiction (DRY) lub osobne test_*_de.py
5. supabase/migrations/20260520000000_jwt_custom_claims_trigger.sql — Postgres trigger compass.sync_jwt_claims() per Opcja A
6. Run compass-rls-auditor subagent na trigger migracji (SECURITY DEFINER non-trivial)
7. supabase/migrations/20260520000001_storage_bucket_rls.sql — bucket 'contracts' policy z <tenant_id>/ prefix enforcement
8. packages/core/src/compass_core/db.py — DBPoolHolder pattern (simple class attribute)
9. packages/core/src/compass_core/audit.py — concrete emit() writer z DB pool + tenant_context
10. packages/core/src/compass_core/events.py — extend publish_event z best-effort persist do compass.task_events
11. Pilot live eval: uv run pytest packages/evals/tests/ -m eval --profile=cloud-cheap (~$0.10-0.25) + lokalny --profile=local-data-sovereign (~30min Bielik); output do docs/evals/2026-05-XX_pilot_liability_confidentiality_pl.md
Po każdym pliku — TaskUpdate completed.
Stretch (jeśli czas):
- Trzeci clause type Termination (full 7-step taxonomy workflow PL + DE)
- Integration tests tenant_isolation + audit_writer + events_persist (wymaga lokalnego Supabase + Redis)
- Confidentiality dataset expansion 4 → 20 (user-side curation z anonimizowanych PL contracts)
NIE rób w Sprint 5: MCP server (Sprint 6+), Authentik (Sprint 7+), retrieval/ingestion (Sprint 6+), Hetzner deploy (Sprint 6+), 4th+ clause type (Sprint 6+ IP / Data Privacy), FR jurisdiction (Sprint 6+).
Po wszystkich fazach: summary + sign-off request przed commit. NIE push automatycznie — auto-mode classifier blokuje default branch (user runs !git push origin main samodzielnie). Sugeruj 3-4 atomic milestone commits.
```