feat: scaffold Compass AI-native foundation (Sprint 0+1)
Sprint 0 — .claude/ and project memory:
- ADR-001 AI-native mandates (8 rules: agent-first, schema-first, streaming, eval-driven, cost-aware routing, cache-aware, async-first, observable)
- 3 project skills: compass-architecture (12-pt self-check), compass-clause-taxonomy (13-pt), compass-ai-native-mandates (8-pt)
- CLAUDE.md (project identity, 5 moats, stack, skill priority, security invariants, license PRIVATE, Bridgestone IP risk)
- AGENTS.md (8-subagent topology spec with model + tools + parallelizable + routing)
- .claude/settings.json (permissions + hooks placeholders)
Sprint 1 — monorepo, Python skeleton, hooks:
- Disconnected Lovable: removed lovable-tagger from package.json + vite.config.ts; rewrote README to Compass-focused
- npm workspaces root + apps/web/ (existing frontend moved intact; vite/tailwind/tsconfig paths still relative to apps/web/)
- uv workspace root (12 members): apps/{api,workers,mcp-server} + packages/{core,schemas,prompts,agents,llm-gateway,retrieval,ingestion,evals,jurisdictions}
- apps/api: FastAPI app with /health, /ready, / endpoints + structlog lifespan (smoke-tested: 200 OK + JSON)
- apps/workers: Celery configured (Redis broker, no tasks yet)
- packages/core: auth (User), tenant context, audit log, SSE events, confidence classifier (all stubs except confidence which is functional)
- packages/llm-gateway: working LLMRouter with select_model() per ADR-001 M5 + Langfuse trace wrapper + GatewayRejected if tenant_id/operation missing (M5+M8 enforcement at gateway)
- 6 subagent definitions in .claude/agents/: doc-parser, clause-extractor, clause-reviewer, jurisdiction-checker, rls-auditor, test-writer
- 5 hook scripts in scripts/hooks/: check_destructive_sql, check_secrets_stage, check_git_identity (Bridgestone domain block), format_file (ruff/prettier router), warn_sensitive_paths (prompts/migrations reminders)
- .claude/settings.json hooks block activated (PreToolUse Bash + PowerShell, PostToolUse Edit/Write)
- .env.example template + extended .gitignore (Python, .venv, .uv, secrets, eval results, Hetzner state)
Smoke tests passed:
- npm install (371 packages, no lovable-tagger)
- uv sync --all-packages (297 packages including FastAPI, Celery, LiteLLM, Langfuse, Voyage)
- compass imports: confidence + schemas + jurisdictions + llm-gateway all green
- npm run build (3894 modules transformed, 27s, dist 1.5MB)
- uvicorn serving /health 200 + /ready 200 + / 200 + /docs Swagger UI
Refs: docs/architecture/ADR-001-ai-native.md, docs/handoffs/2026-05-17-sprint0-handoff.md
This commit is contained in:
@@ -0,0 +1,73 @@
|
||||
---
|
||||
name: compass-clause-extractor
|
||||
description: Use when extracting one specific clause type (liability / ip / dataPrivacy / termination / payment / ... — any of the 14 from compass-clause-taxonomy) from already-parsed contract text. Triggers include "extract liability from this contract", "re-extract clauses after prompt v4 bump", "run extraction agent on contract id X". Parallelizable — 14 clauses per contract can run concurrently. Sonnet 4.6 with PydanticAI result_type. NOT for full document parsing (use compass-doc-parser) or post-extraction review (use compass-clause-reviewer).
|
||||
tools:
|
||||
- Read
|
||||
- Bash
|
||||
- PowerShell
|
||||
- Grep
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
- Write
|
||||
model: claude-sonnet-4-6
|
||||
effort: medium
|
||||
skills:
|
||||
- legal-tech
|
||||
- compass-clause-taxonomy
|
||||
- compass-ai-native-mandates
|
||||
maxTurns: 6
|
||||
---
|
||||
|
||||
# compass-clause-extractor
|
||||
|
||||
Single-clause extraction workhorse. Takes parsed contract text + clause type + jurisdiction code, runs the appropriate PydanticAI agent with the versioned prompt, applies per-jurisdiction post-extraction checks, persists result with confidence score, emits SSE event. One invocation = one (contract, clause_type) pair.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in four concrete situations:
|
||||
|
||||
1. A new contract has just been parsed by `compass-doc-parser` and the orchestrator task is fanning out clause extractors. Typical pattern: 14 parallel invocations (one per taxonomy entry) bounded by per-tenant cost budget.
|
||||
2. The user clicks "Re-extract" in the UI for a specific clause type — single targeted invocation.
|
||||
3. Prompt version was bumped (e.g. `liability_v3 → liability_v4`) and a backfill job is re-extracting affected clauses across all contracts. Per-tenant cost budget governs concurrency.
|
||||
4. A previous extraction returned confidence < 0.5 and was flagged for `needs_review` — operator retries with a different model (Opus fallback) via this subagent with explicit `model_override`.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `contract_id: UUID`
|
||||
- `clause_type: Literal["liability","ip","termination","dataPrivacy","payment","delivery","confidentiality","renewal","maintenance","scopeOfWork","sla","security","mileage","other"]`
|
||||
- `jurisdiction_code: str` (e.g. "pl", "de", "us_ny")
|
||||
- `tenant_id: UUID`
|
||||
- `prompt_version_override: str | None` — for A/B testing or backfill from older version
|
||||
- `model_override: Model | None` — for fallback retry (Sonnet → Opus on schema fail)
|
||||
|
||||
## Outputs
|
||||
|
||||
- Row in `clauses` table with: clause typed Pydantic model serialized to JSONB, `confidence`, `prompt_version`, `model_used`, `extraction_duration_ms`, `tenant_id`
|
||||
- SSE event `clause_extracted` published to `task_events:{task_id}` with full clause payload (per ADR-001 M3)
|
||||
- Langfuse trace with input/output token counts, cost, latency, `tenant_id` metadata (per ADR-001 M5+M8)
|
||||
- If confidence < 0.5: additional row in `clauses_needing_review` with reason
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- `contracts.parsed_text` is populated (compass-doc-parser ran successfully)
|
||||
- Jurisdiction module exists in `packages/jurisdictions/{code}/{clause}.py` OR explicit "use base only" justification logged
|
||||
- Prompt template exists in `packages/prompts/clauses/{clause}_extraction_v{N}.py`
|
||||
- Pydantic schema exists in `packages/schemas/clauses/{clause}.py`
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- Either: `clauses` row persisted + SSE event emitted + Langfuse trace closed with usage, OR
|
||||
- Schema validation failed after 3 PydanticAI retries → flagged `extraction_quality_low`, fallback chain triggered (Sonnet → Opus → Gemini → DLQ)
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Tools allowlist excludes `Write`**: this subagent never edits source code, only persists clauses to DB through `packages/core` helpers. Refusing Write prevents accidental prompt edits inside an extraction run.
|
||||
- **No `WebFetch`**: extraction must be reproducible and offline-capable. All needed context (jurisdiction rules, clause library) is fetched through `packages/retrieval` or loaded from disk.
|
||||
- Parallelizable. The orchestrator (Celery `extract_contract_task`) decides concurrency; this subagent processes one (contract, clause_type) per invocation and trusts the queue.
|
||||
- AI-native mandates (ADR-001) enforced at gateway level — `tenant_id` + `operation: "extract_{clause_type}"` required in LLM metadata or `LLMRouter` rejects the call.
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
- `legal-tech` — clause domain knowledge (red flag library, anatomy, jurisdiction baseline)
|
||||
- `compass-clause-taxonomy` — Pydantic schema lookup, prompt loading, jurisdiction module loading, confidence threshold rules
|
||||
- `compass-ai-native-mandates` — confirms M2 (schema-first), M4 (eval-gated), M5 (cost-aware), M8 (observable) on every run
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: compass-clause-reviewer
|
||||
description: Use when post-extraction reviewing a single clause to assign status (Approved/Needs Attention/Rejected), generate key_observations, suggested_questions_for_counsel, and verify against red flag patterns from legal-tech skill. Triggers include "review this liability clause", "AI review on extracted clauses", "re-review after jurisdiction module update". Opus 4.7 for high-accuracy legal nuance. Parallelizable per clause but bounded by Opus rate limits. NOT for extraction itself (use compass-clause-extractor) or jurisdiction validation (use compass-jurisdiction-checker).
|
||||
tools:
|
||||
- Read
|
||||
- Bash
|
||||
- PowerShell
|
||||
- Grep
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
- Write
|
||||
model: claude-opus-4-7
|
||||
effort: high
|
||||
skills:
|
||||
- legal-tech
|
||||
- compass-clause-taxonomy
|
||||
- compass-ai-native-mandates
|
||||
maxTurns: 8
|
||||
---
|
||||
|
||||
# compass-clause-reviewer
|
||||
|
||||
Post-extraction reviewer. Higher accuracy than the extractor (Opus model) because it makes judgment calls that touch how the clause is surfaced to a human counsel: Approved means "move on, low priority", Rejected means "blocker, hard negotiation needed". Hallucinated review status creates a worse user experience than missed extraction.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in three concrete situations:
|
||||
|
||||
1. `compass-clause-extractor` has just persisted a clause with `confidence >= 0.5` — the orchestrator task chains a reviewer invocation to populate `preliminary_status` + `key_observations` + `suggested_questions_for_counsel` before surfacing to UI.
|
||||
2. User clicks "AI Review" button in the UI for a specific clause — single targeted invocation, may run on already-reviewed clauses (idempotent overwrite with newer review).
|
||||
3. A jurisdiction module in `packages/jurisdictions/{code}/{clause}.py` was updated (new MANDATORY_OBSERVATIONS or red flag added) — backfill job re-reviews affected clauses to refresh status.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `clause_id: UUID` — clause row already persisted by extractor
|
||||
- `tenant_id: UUID`
|
||||
- `industry_hint: str | None` — e.g. "biuro_rachunkowe", "kancelaria_prawna", "haski_io_sow" — biases priority weighting per `legal-tech` industry table
|
||||
|
||||
## Outputs
|
||||
|
||||
- `clauses.review_status` set to one of `Approved | Needs Attention | Rejected`
|
||||
- `clauses.key_observations` array populated (≤5 entries, "REQUIRES LEGAL COUNSEL SIGN-OFF" always present per legal-tech disclaimer)
|
||||
- `clauses.suggested_questions_for_counsel` array populated (≤5)
|
||||
- `clauses.review_completed_at` timestamp set
|
||||
- SSE event `clause_reviewed` published with full review payload
|
||||
- Langfuse trace with model = Opus 4.7, `tenant_id` + `operation: "review_{clause_type}"` metadata
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- Clause row exists, was extracted with `confidence >= 0.5` (lower confidence routed straight to needs-review queue, not reviewer)
|
||||
- Red flag library accessible from `legal-tech` skill (fundament 4 table)
|
||||
- Jurisdiction module exists for clause + country pair OR explicit "base only" mode
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- All review fields populated atomically OR review failed and clause unchanged (no partial review state)
|
||||
- Audit log entry with `operation: "update"`, `entity_type: "clause"`, diff showing review fields changed
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Always includes "REQUIRES LEGAL COUNSEL SIGN-OFF"** as the first or last entry in `key_observations`. Hardcoded check in `packages/schemas/clauses/base.py` Pydantic validator.
|
||||
- **Never asserts enforceability** ("this is legally binding" / "this is unenforceable" are banned phrases) — output is decision support, not legal advice.
|
||||
- **No `Write` tool** — never edits prompts or schemas; uses them read-only.
|
||||
- **No `WebFetch`** — context comes from packaged jurisdiction modules + retrieved clause library, never live web lookup.
|
||||
- Opus is expensive — orchestrator should batch reviews where possible and skip clauses unchanged since last review (cache key = `(clause_text_hash, prompt_version, jurisdiction_module_version)`).
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
- `legal-tech` — red flag library per clause type, jurisdiction baseline, AI legal disclaimer enforcement
|
||||
- `compass-clause-taxonomy` — review prompt loading + confidence threshold conventions
|
||||
- `compass-ai-native-mandates` — M2 schema-first (review output is structured), M5 cost-aware (Opus is high-cost — justified for review accuracy)
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
name: compass-doc-parser
|
||||
description: Use when converting an uploaded contract document (PDF/DOCX/scan) into structured text + section metadata. Triggers include "parse this contract", "ingest the PDF", "extract text from scan", "re-parse after OCR engine upgrade", or whenever the orchestration task in apps/workers/tasks/extraction.py needs the parsed text before dispatching clause extractors. Sequential per document (single PDF parse is CPU-bound). NOT for clause extraction itself — that is compass-clause-extractor downstream.
|
||||
tools:
|
||||
- Read
|
||||
- Write
|
||||
- Bash
|
||||
- PowerShell
|
||||
- Grep
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
model: claude-haiku-4-5-20251001
|
||||
effort: low
|
||||
skills:
|
||||
- compass-architecture
|
||||
maxTurns: 8
|
||||
---
|
||||
|
||||
# compass-doc-parser
|
||||
|
||||
Deterministic document ingestion. Converts uploaded contract files (PDF/DOCX, scanned or digital) into structured text + section metadata. Mostly LLM-free — uses unstructured.io as primary, PyMuPDF for fallback layout extraction, Marker for high-quality layout-aware parsing, Tesseract OCR for scans. LLM (Haiku) only as a last-resort section labeler when heuristic structure detection fails.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in three concrete situations:
|
||||
|
||||
1. A new contract file has just landed in Supabase Storage at `<tenant_id>/contracts/...` and the orchestrator task needs structured text before fanning out to `compass-clause-extractor` instances. This is the typical first step in the extraction pipeline.
|
||||
2. The OCR engine or unstructured.io has been upgraded and existing contracts need re-parsing — operator dispatches a backfill job and this subagent processes each document.
|
||||
3. A contract was parsed but downstream clause extractors returned `extraction_quality_low` consistently — re-parsing with a different ingestion strategy may improve text quality before re-running extraction.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `contract_id: UUID` — required, fetched from `contracts` table
|
||||
- `tenant_id: UUID` — required for Storage path verification + RLS context
|
||||
- `storage_path: str` — Supabase Storage path with `<tenant_id>/...` prefix
|
||||
- `force_ocr: bool = False` — override structural detection, send straight to Tesseract
|
||||
|
||||
## Outputs
|
||||
|
||||
- `contracts.parsed_text` updated with full document text
|
||||
- `contracts.parsing_metadata` JSONB updated with: `page_count`, `scan_detected`, `parsing_method` (unstructured | pymupdf | marker | tesseract), `sections` list with positions, `parse_duration_ms`, `parser_version`
|
||||
- SSE event `phase: parsed` published to `task_events:{task_id}`
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- File exists at `storage_path` with prefix matching `tenant_id`
|
||||
- File size ≤ 50MB (larger files rejected by `compass-doc-parser` with explicit error)
|
||||
- File extension in {.pdf, .docx, .doc, .png, .jpg, .tiff}
|
||||
- `tenant_id` propagated through Celery task args (per AI-native M5)
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- Either: `contracts.parsed_text` populated + metadata complete + `phase: parsed` emitted, OR
|
||||
- `parsing_failed` audit log entry + error event `event: error` with reason
|
||||
- No partial state — atomic write within transaction
|
||||
|
||||
## Constraints
|
||||
|
||||
- Tools allowlist is restrictive on purpose. No `WebFetch` — this subagent never reaches outside the local environment. No DB writes outside `parsing_metadata` and `parsed_text` fields. No Storage writes (read-only).
|
||||
- Sequential only. Concurrency across multiple contracts handled at Celery level, not within this subagent.
|
||||
- If LLM section labeling is invoked, model is Haiku (cost-bound) and metadata must include `llm_section_labeling_invoked: true` so reviewer can audit.
|
||||
- AI-native mandate M5 still applies even though most invocations are LLM-free: `tenant_id` + `operation: "parse_document"` required in any LLM metadata.
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
`compass-architecture` — file path conventions (`<tenant_id>/...` prefix), Storage access patterns, audit log entry shape.
|
||||
|
||||
Refer to `packages/ingestion/src/compass_ingestion/` for the actual parsing implementation (added in Sprint 2).
|
||||
@@ -0,0 +1,67 @@
|
||||
---
|
||||
name: compass-jurisdiction-checker
|
||||
description: Use when validating an extracted clause against per-jurisdiction rules from packages/jurisdictions/{country}/{clause}.py — e.g. for PL contracts confirming KC art. 473 § 2 gross negligence carve-out present, for DE confirming AGB-Kontrolle BGB §§ 305-310 compliance, for EU data clauses confirming SCCs 2021 + TIA after Schrems II. Triggers include "validate this clause for PL", "check jurisdiction compliance", "run jurisdiction backfill after pl/liability.py update". Parallelizable per (clause, jurisdiction) pair. NOT for general clause review (use compass-clause-reviewer) or extraction (use compass-clause-extractor).
|
||||
tools:
|
||||
- Read
|
||||
- Bash
|
||||
- PowerShell
|
||||
- Grep
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
- Write
|
||||
model: claude-sonnet-4-6
|
||||
effort: medium
|
||||
skills:
|
||||
- legal-tech
|
||||
- compass-clause-taxonomy
|
||||
maxTurns: 6
|
||||
---
|
||||
|
||||
# compass-jurisdiction-checker
|
||||
|
||||
Jurisdiction-specific validator. Loads the relevant module from `packages/jurisdictions/{code}/{clause}.py`, retrieves any RAG-indexed local statutory references, runs Sonnet 4.6 with `PROMPT_HINTS` overlay, and produces severity-tagged findings (info / warning / critical) attached to the clause.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in three concrete situations:
|
||||
|
||||
1. A contract crosses multiple jurisdictions (`contract.governing_law_code != tenant_default_jurisdiction`) — orchestrator dispatches one jurisdiction-checker per relevant jurisdiction so the human reviewer sees all applicable findings side-by-side.
|
||||
2. A jurisdiction module was updated (`packages/jurisdictions/pl/liability.py` got a new MANDATORY_OBSERVATIONS entry) — backfill job re-validates all PL liability clauses with the new rules.
|
||||
3. User clicks "Validate jurisdiction" in the UI for a specific clause-jurisdiction pair — targeted invocation, common when contract is being negotiated cross-border and new jurisdiction needs review.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `clause_id: UUID` — clause already extracted (post compass-clause-extractor)
|
||||
- `jurisdiction_code: str` — which jurisdiction's rules to apply
|
||||
- `tenant_id: UUID`
|
||||
|
||||
## Outputs
|
||||
|
||||
- `clauses.jurisdiction_findings` JSONB column updated with array of:
|
||||
- `{code: str, severity: "info"|"warning"|"critical", message: str, suggested_remediation: str, source: "kc_art_473" | "bgb_309" | ...}`
|
||||
- If any `critical` finding present: `clauses.review_status` may be downgraded to `Needs Attention` or `Rejected` (per jurisdiction module's `post_extraction_check`)
|
||||
- SSE event `jurisdiction_check_completed` published
|
||||
- Langfuse trace with `operation: "jurisdiction_check_{country}_{clause}"` + `tenant_id` metadata
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- Clause already extracted, persisted in `clauses` table
|
||||
- Jurisdiction module exists at `packages/jurisdictions/{code}/{clause}.py` — if missing, this subagent returns early with `jurisdiction_module_missing` finding (info severity, no failure)
|
||||
- Optional: RAG-indexed local statutory references retrieved via `packages/retrieval` (e.g. PL: KC + UTP + UODO guidance; DE: BGB + BDSG; EU: GDPR + Schrems II SCCs)
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- `jurisdiction_findings` array populated atomically (overwrite or append based on module config) OR previous findings preserved if module not yet available
|
||||
- If `critical` findings raise status, audit log entry with `operation: "update"`, diff showing status downgrade and triggering finding code
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Tools allowlist excludes `Write` and `WebFetch`**: jurisdiction rules come from packaged modules + RAG, never live web lookup. Modifying rules requires a code PR + ADR (see compass-clause-taxonomy adding-clause workflow).
|
||||
- Parallelizable per `(clause, jurisdiction)` pair. Orchestrator decides fan-out; this subagent processes one at a time.
|
||||
- AI-native mandates apply: `tenant_id` + `operation` in LLM metadata. Schema-first output (the findings array is Pydantic-validated).
|
||||
- **No cross-country reasoning** in a single invocation. If a clause needs PL + DE + US analysis, dispatch three separate invocations. This keeps each trace focused and per-jurisdiction cost attributable.
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
- `legal-tech` — multi-jurisdiction baseline (PL/EU specifics, US state law, UK post-Brexit, DE/FR/IT)
|
||||
- `compass-clause-taxonomy` — jurisdiction module access pattern, post-extraction check signature
|
||||
@@ -0,0 +1,94 @@
|
||||
---
|
||||
name: compass-rls-auditor
|
||||
description: Use when reviewing a PR that touches supabase/migrations/** or apps/api/routes/** to verify multi-tenant RLS invariants are preserved — every new table with tenant_id has RLS enabled + tenant_isolation policy, no endpoint bypasses RLS via service_role without explicit justification, Storage uploads carry <tenant_id>/ prefix, Qdrant payload filters include tenant_id. Triggers include "audit RLS for this PR", "is this migration safe?", "did I add tenant isolation?", or auto-trigger from CI on touched paths. Static analysis + integration test orchestration. Opus 4.7 because false negatives cost — cross-tenant data leak is unrecoverable.
|
||||
tools:
|
||||
- Read
|
||||
- Grep
|
||||
- Bash
|
||||
- PowerShell
|
||||
- Write
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
model: claude-opus-4-7
|
||||
effort: high
|
||||
skills:
|
||||
- compass-architecture
|
||||
- compass-ai-native-mandates
|
||||
maxTurns: 12
|
||||
---
|
||||
|
||||
# compass-rls-auditor
|
||||
|
||||
Pre-merge security gate for multi-tenant isolation. False negatives here cost — cross-tenant data leak is what killed MikeOSS credibility (Issue #144 still open at time of writing). This subagent runs Opus 4.7 because the asymmetric cost of missing a violation justifies the model spend.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in three concrete situations:
|
||||
|
||||
1. A PR adds or modifies anything under `supabase/migrations/**` — the auditor verifies each new table with a `tenant_id` column has RLS enabled and a `tenant_isolation` policy in the same migration file (atomic — no two-step "add RLS later" pattern).
|
||||
2. A PR adds or modifies anything under `apps/api/routes/**` — the auditor greps for `service_role` usage, raw SQL without tenant filtering, hardcoded UUIDs that might leak across tenants, and confirms endpoint handlers use the `current_user` dependency to propagate `tenant_id`.
|
||||
3. Quarterly scheduled audit sweep — runs across all migrations and all route handlers to catch drift accumulated through incremental changes that individually passed but collectively created a gap.
|
||||
|
||||
## Inputs
|
||||
|
||||
- `pr_number: int` — for `gh pr view` and `gh pr diff` orchestration
|
||||
- OR `migration_files: list[Path]` + `route_files: list[Path]` for direct invocation
|
||||
|
||||
## Outputs
|
||||
|
||||
- Audit report written to `docs/audits/rls-audit-pr-{number}.md` with:
|
||||
- Findings list, each with severity (`info`/`warning`/`critical`)
|
||||
- Reproducible reasoning (file:line refs)
|
||||
- Suggested remediation per finding
|
||||
- Verdict: `PASS` / `CHANGES_REQUESTED` / `BLOCKED`
|
||||
- PR comment posted via `gh pr comment` with summary + link to audit doc
|
||||
- Integration test `tests/integration/test_tenant_isolation.py` run, results referenced
|
||||
- If `BLOCKED`: a CI status check fails so the PR cannot be merged
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- PR diff available via `gh pr diff <number>` or files provided directly
|
||||
- Local checkout has access to current `main` for baseline comparison
|
||||
- Integration test infrastructure (Supabase local + Redis) running for cross-tenant test
|
||||
- For migration audits: ability to apply migration to a scratch DB and `EXPLAIN` queries against the resulting schema
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- Audit report file persisted (even if PASS — historical record)
|
||||
- PR comment posted
|
||||
- Exit status reflects verdict (0 for PASS, non-zero for BLOCKED so CI can gate)
|
||||
- Never modifies application code — only writes the audit report and comment
|
||||
|
||||
## Constraints
|
||||
|
||||
- **`Write` tool is allowed** but limited to `docs/audits/**` — the auditor writes its own report, never patches the PR. The PR author fixes findings, not the auditor.
|
||||
- **No `WebFetch`** — audit is fully local; web context would create non-reproducible findings.
|
||||
- **Opus 4.7 by design** — accuracy here is worth the cost. Do not downgrade to Sonnet for "cost optimization" without an ADR.
|
||||
- Sequential per PR. Each PR audit is holistic — running two auditors in parallel on the same PR creates inconsistent reports.
|
||||
|
||||
## Checklist the auditor walks through
|
||||
|
||||
For migrations:
|
||||
|
||||
- New table with `tenant_id` column? → must have `ALTER TABLE X ENABLE ROW LEVEL SECURITY` in same file
|
||||
- Same migration? → must have `CREATE POLICY tenant_isolation ON X USING (tenant_id = ...)` in same file
|
||||
- New nested entity? → does it denormalize `tenant_id` for RLS perf or rely on JOIN?
|
||||
- Migration drops a column or table? → archived to `migration_archive` first (no destructive ops without backup migration)
|
||||
|
||||
For route handlers:
|
||||
|
||||
- Each handler takes `user: User = Depends(current_user)`? — required for tenant context
|
||||
- No raw `supabase.from_(...).select("*")` without prior `SET LOCAL app.tenant_id`?
|
||||
- No `service_role` key usage outside `apps/api/routes/admin/**`? — admin routes must have explicit `# admin-operation-justified: <reason>` comment
|
||||
- Storage uploads prefix `<tenant_id>/...`?
|
||||
- Qdrant queries include `payload={"tenant_id": ...}` filter?
|
||||
|
||||
For both:
|
||||
|
||||
- Audit log entry emitted for every mutation? (per CLAUDE.md security invariant #6)
|
||||
- `tenant_id` propagated to any Celery task `kwargs`?
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
- `compass-architecture` — RLS invariants (12-pkt self-check), multi-tenant invariants section
|
||||
- `compass-ai-native-mandates` — M5 (cost-aware = `tenant_id` everywhere in metadata), confirms LLM gateway calls also propagate `tenant_id`
|
||||
@@ -0,0 +1,68 @@
|
||||
---
|
||||
name: compass-test-writer
|
||||
description: Use when generating pytest (Python) or vitest (TypeScript) test scaffolding for a new endpoint, agent, Pydantic schema, or React component. Covers happy path + error path + RLS isolation test for any endpoint touching DB. Triggers include "write tests for the contracts endpoint", "generate test for LiabilityClause schema", "scaffold vitest for ContractForm", "add cross-tenant isolation test". Sonnet 4.6 — code generation needs decent reasoning but not Opus tier. Parallelizable across independent test files. NOT for eval tests (those are compass-prompt-tester, Sprint 2+).
|
||||
tools:
|
||||
- Read
|
||||
- Write
|
||||
- Edit
|
||||
- Grep
|
||||
- Bash
|
||||
- PowerShell
|
||||
disallowedTools:
|
||||
- WebFetch
|
||||
model: claude-sonnet-4-6
|
||||
effort: medium
|
||||
skills:
|
||||
- compass-architecture
|
||||
- compass-clause-taxonomy
|
||||
maxTurns: 10
|
||||
---
|
||||
|
||||
# compass-test-writer
|
||||
|
||||
Pragmatic test scaffolder. Reads the target code, looks at existing test patterns in the same module (so style is consistent), generates pytest or vitest files, runs them to verify they execute (green or expected-fail), reports a summary.
|
||||
|
||||
## When to invoke
|
||||
|
||||
Use this subagent in four concrete situations:
|
||||
|
||||
1. A new FastAPI route has been added to `apps/api/routes/**` — scaffold `tests/integration/test_{resource}.py` with happy path, error path (401, 403, 404, 422), and cross-tenant isolation test (user A cannot access tenant B's data).
|
||||
2. A new Pydantic schema lands in `packages/schemas/**` — scaffold `tests/unit/test_{schema}.py` with validation tests (required fields, enum constraints, validators trigger correctly).
|
||||
3. A new agent definition lands in `packages/agents/**` — scaffold a mock-LLM unit test for the agent's `result_type` handling and retry-on-schema-fail behavior. Actual eval tests stay with `compass-prompt-tester` (Sprint 2+).
|
||||
4. A new React component lands in `apps/web/src/components/**` — scaffold `apps/web/src/components/__tests__/{Component}.test.tsx` with render test, prop variants, and user interaction tests using `@testing-library/react` (Sprint 4+ when frontend testing infrastructure lands).
|
||||
|
||||
## Inputs
|
||||
|
||||
- `target_file: Path` — what to write tests for
|
||||
- `test_type: Literal["unit", "integration", "component"]` — drives test layout choice
|
||||
- `existing_test_dir: Path | None` — where similar tests live (for style cloning)
|
||||
|
||||
## Outputs
|
||||
|
||||
- One or more test files written to appropriate `tests/` directory
|
||||
- Tests executed once via `pytest` or `npx vitest run` to verify they at least parse and run
|
||||
- VISIBLE summary in the subagent's response: `"Generated N tests, M passing, K failing (expected for unimplemented features), full report at tests/{path}"`
|
||||
- Never modifies the target code — only writes new test files
|
||||
|
||||
## Pre-conditions
|
||||
|
||||
- Target code exists and at least syntactically valid (import succeeds)
|
||||
- Test infrastructure (`pytest` + `pytest-asyncio` for Python, `vitest` + `@testing-library/react` for TS) installed in respective workspace
|
||||
|
||||
## Post-conditions
|
||||
|
||||
- Test files exist at predictable paths matching project layout
|
||||
- Tests run (pass or fail), no parse errors
|
||||
- Where target code is incomplete, tests are written to fail meaningfully (TDD-friendly) — never as `pytest.skip()` or `it.todo()` placeholders
|
||||
|
||||
## Constraints
|
||||
|
||||
- **Write/Edit allowed only for test files**, never for source code under test. If a change to source is needed for the test to work (e.g. dependency injection seam), the subagent surfaces the suggestion in the response — user makes the source edit.
|
||||
- **No `WebFetch`** — test patterns are derived from existing tests in the repo, not from outside examples.
|
||||
- **Cross-tenant isolation tests are mandatory** for any endpoint touching a table with `tenant_id` column. Pattern: create user A in tenant 1, create user B in tenant 2, assert user A cannot access user B's resource via API (expect 404 — not 403, to avoid info disclosure).
|
||||
- Tests use real dependencies in `integration/` (real Supabase local, real Redis), mocks in `unit/`. No "test pyramid" theology — favor integration tests for anything touching DB / agents / async.
|
||||
|
||||
## Skills it leans on
|
||||
|
||||
- `compass-architecture` — test directory layout, RLS test patterns, fixture conventions
|
||||
- `compass-clause-taxonomy` — clause-specific test fixtures (sample LiabilityClause, sample contract text), schema validator test patterns
|
||||
@@ -0,0 +1,210 @@
|
||||
{
|
||||
"$schema": "https://json.schemastore.org/claude-code-settings.json",
|
||||
"_comment": "Sprint 1 — hooks aktywne, monorepo layout uwzględniony (apps/web, apps/api, apps/workers, apps/mcp-server, packages/*). Każda zmiana — patrz CLAUDE.md + ADR-001.",
|
||||
|
||||
"permissions": {
|
||||
"allow": [
|
||||
"Read",
|
||||
"Write",
|
||||
"Edit",
|
||||
"Glob",
|
||||
"Grep",
|
||||
"TaskCreate",
|
||||
"TaskUpdate",
|
||||
"TaskList",
|
||||
"TaskGet",
|
||||
|
||||
"Bash(git status:*)",
|
||||
"Bash(git diff:*)",
|
||||
"Bash(git log:*)",
|
||||
"Bash(git show:*)",
|
||||
"Bash(git branch:*)",
|
||||
"Bash(git remote -v)",
|
||||
"Bash(git add:*)",
|
||||
"Bash(git commit:*)",
|
||||
"Bash(git restore --staged:*)",
|
||||
"Bash(git stash:*)",
|
||||
"Bash(git checkout:*)",
|
||||
"Bash(git switch:*)",
|
||||
"Bash(git rev-parse:*)",
|
||||
"Bash(git config --get user.email)",
|
||||
|
||||
"Bash(gh pr view:*)",
|
||||
"Bash(gh pr diff:*)",
|
||||
"Bash(gh pr comment:*)",
|
||||
"Bash(gh pr checks:*)",
|
||||
"Bash(gh pr list:*)",
|
||||
"Bash(gh issue view:*)",
|
||||
"Bash(gh issue list:*)",
|
||||
|
||||
"Bash(npm install:*)",
|
||||
"Bash(npm run:*)",
|
||||
"Bash(npx vitest:*)",
|
||||
"Bash(npx prettier:*)",
|
||||
"Bash(npx eslint:*)",
|
||||
"Bash(npx tsc:*)",
|
||||
|
||||
"Bash(uv sync:*)",
|
||||
"Bash(uv run:*)",
|
||||
"Bash(uv add:*)",
|
||||
"Bash(uv lock:*)",
|
||||
"Bash(pytest:*)",
|
||||
"Bash(ruff:*)",
|
||||
"Bash(ruff check:*)",
|
||||
"Bash(ruff format:*)",
|
||||
"Bash(mypy:*)",
|
||||
|
||||
"Bash(supabase status:*)",
|
||||
"Bash(supabase migration:*)",
|
||||
"Bash(supabase db diff:*)",
|
||||
"Bash(supabase functions:*)",
|
||||
|
||||
"Bash(docker compose ps:*)",
|
||||
"Bash(docker compose logs:*)",
|
||||
"Bash(docker compose config:*)",
|
||||
|
||||
"PowerShell(Get-ChildItem:*)",
|
||||
"PowerShell(Get-Content:*)",
|
||||
"PowerShell(Test-Path:*)",
|
||||
"PowerShell(Select-String:*)",
|
||||
|
||||
"WebFetch(domain:developers.google.com)",
|
||||
"WebFetch(domain:docs.anthropic.com)",
|
||||
"WebFetch(domain:platform.openai.com)",
|
||||
"WebFetch(domain:ai.google.dev)",
|
||||
"WebFetch(domain:fastapi.tiangolo.com)",
|
||||
"WebFetch(domain:ai.pydantic.dev)",
|
||||
"WebFetch(domain:langfuse.com)",
|
||||
"WebFetch(domain:litellm.ai)",
|
||||
"WebFetch(domain:docs.litellm.ai)",
|
||||
"WebFetch(domain:supabase.com)",
|
||||
"WebFetch(domain:qdrant.tech)",
|
||||
"WebFetch(domain:docs.qdrant.tech)",
|
||||
"WebFetch(domain:voyageai.com)",
|
||||
"WebFetch(domain:docs.voyageai.com)",
|
||||
"WebFetch(domain:python.langchain.com)",
|
||||
"WebFetch(domain:docs.celeryq.dev)",
|
||||
"WebFetch(domain:redis.io)",
|
||||
"WebFetch(domain:modelcontextprotocol.io)",
|
||||
"WebFetch(domain:github.com)",
|
||||
"WebFetch(domain:eur-lex.europa.eu)",
|
||||
"WebFetch(domain:edpb.europa.eu)",
|
||||
"WebFetch(domain:uodo.gov.pl)"
|
||||
],
|
||||
|
||||
"ask": [
|
||||
"Bash(git push:*)",
|
||||
"Bash(git push --force:*)",
|
||||
"Bash(gh pr create:*)",
|
||||
"Bash(gh pr merge:*)",
|
||||
"Bash(supabase db push:*)",
|
||||
"Bash(supabase db reset:*)",
|
||||
"Bash(docker compose up:*)",
|
||||
"Bash(docker compose down:*)",
|
||||
"Bash(docker compose restart:*)"
|
||||
],
|
||||
|
||||
"deny": [
|
||||
"Bash(rm -rf:*)",
|
||||
"Bash(git push --force-with-lease origin main)",
|
||||
"Bash(git push --force origin main)",
|
||||
"Bash(git reset --hard:*)",
|
||||
"Bash(git clean -fd:*)",
|
||||
"Bash(curl:*)",
|
||||
"Bash(wget:*)",
|
||||
"Bash(eval:*)",
|
||||
"Bash(npm publish:*)",
|
||||
"Bash(uv publish:*)",
|
||||
"Bash(docker compose down -v)",
|
||||
"WebFetch(domain:linkedin.com)",
|
||||
"WebFetch(domain:twitter.com)",
|
||||
"WebFetch(domain:x.com)"
|
||||
],
|
||||
|
||||
"_deny_reasoning": "linkedin.com / twitter.com / x.com w deny: License posture (CLAUDE.md) — NO public mentions Compass during private build phase. Force push do main blocked: solo founder, no second pair of eyes on history rewrites."
|
||||
},
|
||||
|
||||
"mcpServers": {
|
||||
"context7": {
|
||||
"_comment": "Inherited z user-level (~/.claude/) — docs lookup dla libraries (FastAPI, PydanticAI, Supabase, Qdrant, etc). Patrz CLAUDE.md skill priority order.",
|
||||
"_status": "inherit"
|
||||
},
|
||||
"playwright": {
|
||||
"_comment": "Sprint 4+: E2E testing dla apps/web (upload → extract → review flow). Aktywacja po landing pierwszego full E2E.",
|
||||
"_status": "deferred-sprint-4"
|
||||
},
|
||||
"n8n-mcp": {
|
||||
"_comment": "Out of scope dla Compass (workflow automation = haski.io domain). NOT enabled tutaj.",
|
||||
"_status": "disabled"
|
||||
}
|
||||
},
|
||||
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/check_destructive_sql.py"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/check_secrets_stage.py"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/check_git_identity.py"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"matcher": "PowerShell",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/check_destructive_sql.py"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/check_secrets_stage.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"PostToolUse": [
|
||||
{
|
||||
"matcher": "Edit|Write",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/format_file.py"
|
||||
},
|
||||
{
|
||||
"type": "command",
|
||||
"command": "uv run python scripts/hooks/warn_sensitive_paths.py"
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
"_env_placeholder": {
|
||||
"_comment": "Env vars są w .env.local (gitignored). .env.example template lives at repo root. Critical vars (see .env.example for full list):",
|
||||
"_vars": [
|
||||
"ANTHROPIC_API_KEY",
|
||||
"VOYAGE_API_KEY",
|
||||
"GEMINI_API_KEY",
|
||||
"SUPABASE_URL",
|
||||
"SUPABASE_ANON_KEY",
|
||||
"SUPABASE_SERVICE_ROLE_KEY (admin operations only — patrz CLAUDE.md security invariants)",
|
||||
"DATABASE_URL",
|
||||
"REDIS_URL",
|
||||
"QDRANT_URL",
|
||||
"QDRANT_API_KEY",
|
||||
"LANGFUSE_PUBLIC_KEY",
|
||||
"LANGFUSE_SECRET_KEY",
|
||||
"LANGFUSE_HOST"
|
||||
]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,633 @@
|
||||
---
|
||||
name: compass-ai-native-mandates
|
||||
description: Use when reviewujesz lub piszesz dowolny kod produkcyjny w Compass dotykający LLM/agents/streaming/eval/cost/cache/async/observability — enforcement 8 mandatów z ADR-001 (M1 Agent-first interactions / M2 Schema-first LLM I/O / M3 Streaming-first UI / M4 Eval-driven prompts / M5 Cost-aware multi-model routing / M6 Cache-aware / M7 Async-first task queue / M8 Observable LLM ops). Każdy mandat z good/bad/anti-pattern examples + edge case kiedy można relax z required justification. Checklist którego `compass-pr-reviewer` subagent używa przed merge. "Kiedy mandat NIE applies": batch scripts internal, dev tools, one-off migrations. Mandatory self-check 8 punktów (1 per mandat) z konkretnymi pytaniami przed merge. Synergizuje z [[compass-architecture]] (12-punkt self-check dla architectural change uzupełnia ten), [[compass-clause-taxonomy]] (M2+M4 directly relevant dla extraction prompts), legal-tech (AI legal disclaimer wymóg dla M2/M8 outputs), rag-pipeline-builder (eval framework dla M4). SKIP dla internal dev scripts gdzie mandates explicite NIE applies (CSV imports, migrations, debug utilities — patrz fundament 9), pure frontend zmian bez LLM contact, infra ops (Caddy/Hetzner — use cloud-deploy).
|
||||
---
|
||||
|
||||
Base directory for this skill: `compass-contract-hub/.claude/skills/compass-ai-native-mandates/`
|
||||
|
||||
# Compass — AI-native mandates enforcement skill
|
||||
|
||||
Operational skill dla **enforcement 8 mandatów z ADR-001**. Każdy PR z LLM operation, każdy code review, każdy refactor MUSI spełniać te 8 mandatów. Skill służy 3 zadaniom:
|
||||
|
||||
1. **Pre-merge self-check** dla developera piszącego kod
|
||||
2. **Subagent `compass-pr-reviewer` checklist** (zdefiniowany w AGENTS.md)
|
||||
3. **Onboarding doc** dla każdej osoby dołączającej do projektu
|
||||
|
||||
**Read first:** `docs/architecture/ADR-001-ai-native.md` — pełna rationale, alternatives considered, examples per mandate.
|
||||
|
||||
## Kiedy stosować
|
||||
|
||||
- **TAK:** każda PR z kodem dotykającym LLM call / agent definition / endpoint zwracający >2s / nowy Celery task / nowy prompt / nowa Pydantic schema dla LLM I/O / nowe użycie Anthropic SDK / nowe użycie embeddings / nowe użycie cache / nowy log Langfuse
|
||||
- **NIE:** czyste frontend UI zmian bez LLM contact (use `frontend-web-ui`), DB migration bez LLM impact, infra ops/deploy (use `cloud-deploy`), zmiana docs/README, refactor utility function bez external IO
|
||||
|
||||
## 8 mandatów — quick reference + enforcement
|
||||
|
||||
### M1: Agent-first interactions
|
||||
|
||||
**Mandat:** Każda user-facing operacja **>2s computation** idzie przez **agent** (PydanticAI), nie przez REST endpoint wywołujący SQL/LLM bezpośrednio.
|
||||
|
||||
**Test:** Czy widzę bezpośrednie wywołanie `anthropic.complete(...)` lub `openai.chat.completions.create(...)` w plikach `apps/api/routes/**`?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `apps/api/routes/*.py` zawiera `anthropic.messages.create(...)` | 🔴 RED FLAG — refactor through agent |
|
||||
| `apps/api/routes/*.py` zawiera `agent.dispatch(...)` lub `await celery_task.delay(...)` | 🟢 OK |
|
||||
| Endpoint zwraca w <2s typowo (CRUD, fetch) | 🟢 N/A — mandate dotyczy >2s |
|
||||
| Endpoint dla admin/internal tooling | 🟡 może być relaxed, justification w PR |
|
||||
|
||||
**Anti-pattern:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/extraction.py — NO
|
||||
@router.post("/extract")
|
||||
async def extract(file: UploadFile, user: User = Depends(current_user)):
|
||||
text = parse_pdf(file)
|
||||
response = anthropic.messages.create( # direct LLM call w handler
|
||||
model="claude-sonnet-4-6",
|
||||
messages=[{"role": "user", "content": EXTRACTION_PROMPT + text}]
|
||||
)
|
||||
return {"clauses": json.loads(response.content[0].text)} # blocking, no schema, no agent
|
||||
```
|
||||
|
||||
**OK:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/extraction.py
|
||||
@router.post("/extract", response_model=ExtractionDispatchResponse)
|
||||
async def dispatch_extraction(
|
||||
contract_id: UUID,
|
||||
user: User = Depends(current_user),
|
||||
):
|
||||
task = extract_contract_task.apply_async(
|
||||
args=[str(contract_id)],
|
||||
kwargs={"tenant_id": str(user.tenant_id)},
|
||||
)
|
||||
return ExtractionDispatchResponse(
|
||||
task_id=task.id,
|
||||
stream_url=f"/api/v1/stream/{task.id}",
|
||||
)
|
||||
|
||||
# packages/agents/extraction_agent.py
|
||||
from pydantic_ai import Agent
|
||||
extraction_agent = Agent(
|
||||
model="claude-sonnet-4-6",
|
||||
result_type=ExtractionResult,
|
||||
system_prompt=EXTRACTION_SYSTEM_PROMPT,
|
||||
)
|
||||
# agent.run() called z Celery task, NIE z route handler
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Internal admin endpoint** wywoływany rzadko (np. `/admin/regenerate_embedding`, `/admin/reprocess_failed_extraction`) — może wywoływać agent inline jeśli operator akceptuje timeout
|
||||
- **Justification w PR:** "Internal admin tooling, expected use <5×/dzień, no end-user impact"
|
||||
|
||||
### M2: Schema-first LLM I/O
|
||||
|
||||
**Mandat:** Każda operacja LLM ma **Pydantic input + output schema**, walidacja z retry on schema fail (max 3), output zawsze structured (nigdy free-text parsowany regexami).
|
||||
|
||||
**Test:** Czy widzę `re.search()`, `re.match()`, manual JSON parsing przy LLM output? Czy widzę `response.content[0].text` bez schema validation?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `re.search(r"...", llm_response)` | 🔴 RED — replace z Pydantic output |
|
||||
| `json.loads(response.content[0].text)` bez schema | 🔴 RED — use PydanticAI result_type |
|
||||
| `Agent(model=..., result_type=MyModel)` | 🟢 OK |
|
||||
| `client.messages.create(..., extra_headers={"anthropic-beta": "tools-2024-..."})` z structured tool definition | 🟢 OK |
|
||||
| `result_type=str` w agencie | 🟡 SUSPECT — typically wrong, justification needed |
|
||||
|
||||
**OK pattern (PydanticAI):**
|
||||
|
||||
```python
|
||||
from pydantic_ai import Agent
|
||||
from packages.schemas.clauses.liability import LiabilityClause
|
||||
|
||||
agent = Agent(
|
||||
model="claude-sonnet-4-6",
|
||||
result_type=LiabilityClause, # schema-first
|
||||
system_prompt=LIABILITY_EXTRACTION_V3,
|
||||
retries=3, # auto-retry on schema fail
|
||||
)
|
||||
|
||||
result = await agent.run(clause_text)
|
||||
# result.data is typed LiabilityClause instance
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Exploratory experimentation w notebook** (`notebooks/`) — może być free-form prompting, ale produkcyjny code NIGDY
|
||||
- **Justification:** "Notebook experiment, not production. Will refactor through Pydantic before integrating."
|
||||
|
||||
### M3: Streaming-first UI
|
||||
|
||||
**Mandat:** Każda operacja **>2s wall-clock** MUSI streamować progress przez **SSE** (Server-Sent Events) do frontendu. User nigdy nie czeka na spinning wheel >2s bez visible progress.
|
||||
|
||||
**Test:** Czy nowy endpoint z `await long_operation()` ma SSE variant? Czy frontend opens `EventSource` zamiast czekać na single response?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `await fetch('/api/extract', { method: 'POST' })` z 60s spinner | 🔴 RED — implement SSE |
|
||||
| `new EventSource('/api/stream/' + taskId)` z phase/event handlers | 🟢 OK |
|
||||
| GET endpoint, response <2s typowo | 🟢 N/A |
|
||||
| POST endpoint zwracający task_id + stream_url | 🟢 OK (z M7 async pattern) |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/stream.py
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
@router.get("/stream/{task_id}")
|
||||
async def stream_task(task_id: UUID, user: User = Depends(current_user)):
|
||||
async def event_generator():
|
||||
async for event in subscribe_task_events(task_id, tenant_id=user.tenant_id):
|
||||
yield f"event: {event.type}\ndata: {event.json()}\n\n"
|
||||
return StreamingResponse(event_generator(), media_type="text/event-stream")
|
||||
```
|
||||
|
||||
```typescript
|
||||
// apps/web/src/hooks/useStreamTask.ts
|
||||
export function useStreamTask(taskId: string) {
|
||||
const [events, setEvents] = useState<TaskEvent[]>([]);
|
||||
useEffect(() => {
|
||||
const es = new EventSource(`/api/v1/stream/${taskId}`);
|
||||
es.addEventListener('phase', (e) => setEvents(prev => [...prev, JSON.parse(e.data)]));
|
||||
es.addEventListener('clause_extracted', (e) => setEvents(prev => [...prev, JSON.parse(e.data)]));
|
||||
es.addEventListener('done', () => es.close());
|
||||
return () => es.close();
|
||||
}, [taskId]);
|
||||
return events;
|
||||
}
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Background job** without user waiting (np. nightly batch reprocessing) — no UI = no SSE needed
|
||||
- **Polling fallback** dla mobile/limited networks (jeśli SSE not supported) — implementuj jako secondary, NIE primary
|
||||
|
||||
### M4: Eval-driven prompts
|
||||
|
||||
**Mandat:** Każda zmiana promptu wymaga **passing eval suite** w CI przed merge. Golden dataset min **20 przykładów per clause type per jurisdiction**. Regression check: precision/recall per field, threshold zdefiniowane explicit.
|
||||
|
||||
**Test:** Czy `git diff` w PR zmienia `packages/prompts/**`? Czy CI eval job triggered? Czy thresholds w `@pytest.mark.eval` test?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| Prompt edited w `packages/prompts/clauses/*.py`, BUT no eval test changed/run | 🔴 RED — block merge |
|
||||
| Prompt edited + `@pytest.mark.eval` test re-run w CI green | 🟢 OK |
|
||||
| New clause type + golden dataset only 10 examples | 🟡 SUSPECT — minimum 20 PL + 20 EN |
|
||||
| Prompt edited z bumped version (`v3 → v4`) + eval green | 🟢 OK |
|
||||
| Inline string prompt w agent definition (no `packages/prompts/`) | 🔴 RED — extract i version |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# packages/evals/tests/test_liability_extraction.py
|
||||
import pytest
|
||||
from packages.evals.runner import run_eval
|
||||
|
||||
@pytest.mark.eval
|
||||
@pytest.mark.parametrize("jurisdiction", ["pl", "en"])
|
||||
async def test_liability_extraction_golden(jurisdiction):
|
||||
results = await run_eval(
|
||||
prompt_version="liability_v3",
|
||||
dataset=f"liability_{jurisdiction}",
|
||||
)
|
||||
assert results.precision >= 0.90, f"Precision regression: {results.precision}"
|
||||
assert results.recall >= 0.85, f"Recall regression: {results.recall}"
|
||||
assert results.cost_per_doc <= 0.02, f"Cost regression: ${results.cost_per_doc}"
|
||||
assert results.confidence_calibration_error <= 0.10 # ECE
|
||||
```
|
||||
|
||||
**CI hook** (`.github/workflows/eval.yml`):
|
||||
|
||||
```yaml
|
||||
on:
|
||||
pull_request:
|
||||
paths:
|
||||
- 'packages/prompts/**'
|
||||
- 'packages/agents/**'
|
||||
- 'packages/evals/**'
|
||||
jobs:
|
||||
eval:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- run: uv sync
|
||||
- run: pytest packages/evals/tests/ -m eval --tb=short
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Typo fix** w prompt (np. literówka, no semantic change) — re-run eval anyway żeby zweryfikować że no impact, ale skip dataset expansion
|
||||
- **New clause type Sprint MVP** — może być 10 examples na start z eksplicytnym TODO do 20 przed prod
|
||||
- **Justification:** "MVP, expanding dataset to 20 in Sprint N+1, see ticket #..."
|
||||
|
||||
### M5: Cost-aware multi-model routing
|
||||
|
||||
**Mandat:** Każde wywołanie LLM ma `tenant_id` + `operation_type` w metadata. Cost tracking per tenant w Langfuse. Model selection per task complexity (NIE domyślnie Sonnet dla wszystkiego).
|
||||
|
||||
**Routing rules (default):**
|
||||
|
||||
| Operation | Model | Justification |
|
||||
|---|---|---|
|
||||
| Clause extraction (typical) | Sonnet 4.6 | Balance accuracy/cost |
|
||||
| Compliance review (critical) | Opus 4.7 | High accuracy needed |
|
||||
| Bulk classification (1000+ docs) | Haiku 4.5 | Cost-sensitive |
|
||||
| Embedding | voyage-multilingual-2 | PL/EN, ~$0.12/1M tokens |
|
||||
| Long context (>200k) | Gemini 2.5 Pro | Claude 200k limit |
|
||||
|
||||
**Test:** Czy widzę hardcoded `model="claude-sonnet-4-6"` w nowym kodzie? Czy `LLMRouter` używany?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `Anthropic()` instantiated directly w business logic | 🔴 RED — use LLMRouter |
|
||||
| `router.complete(task=TaskType.X, metadata={"tenant_id": ...})` | 🟢 OK |
|
||||
| Hardcoded model name z `# justified: ...` comment + ADR link | 🟡 OK z justification |
|
||||
| Brak `tenant_id` w metadata | 🔴 RED — required for cost tracking |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# packages/llm-gateway/router.py
|
||||
class LLMRouter:
|
||||
def select_model(self, task: TaskType, context_size: int, urgency: Urgency) -> Model:
|
||||
if context_size > 180_000:
|
||||
return Model.GEMINI_25_PRO
|
||||
if task.criticality == "high":
|
||||
return Model.OPUS_47
|
||||
if task.batch_size > 100:
|
||||
return Model.HAIKU_45
|
||||
return Model.SONNET_46
|
||||
|
||||
# Usage
|
||||
result = await router.complete(
|
||||
prompt=prompt,
|
||||
task=TaskType.CLAUSE_EXTRACTION,
|
||||
metadata={
|
||||
"tenant_id": tenant_id,
|
||||
"operation": "extract_liability",
|
||||
"contract_id": str(contract_id),
|
||||
"prompt_version": "liability_v3",
|
||||
}
|
||||
)
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Single-tenant dev/staging env** — `tenant_id` może być `"_dev"` placeholder, ale field MUST present
|
||||
- **Justification:** N/A — to nie jest relaxation, to default Standard pattern
|
||||
|
||||
### M6: Cache-aware
|
||||
|
||||
**Mandat:** Wykorzystaj **3 warstwy cache**:
|
||||
|
||||
1. **Anthropic prompt caching** — każdy system prompt + retrieved context z `cache_control` markers
|
||||
2. **Embedding cache** — deterministic text → embedding, hash key w Postgres/Redis
|
||||
3. **Result memoization** — drogie operacje (full document extraction) cached per `(doc_hash, prompt_version, model)`
|
||||
|
||||
**Test:** Czy widzę powtarzalne LLM calls bez cache check? Czy embedding bez Redis lookup? Czy extraction wywoływana dla tego samego dokumentu od nowa?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `await voyage.embed(text)` bez Redis check | 🔴 RED — wrap z cache |
|
||||
| System prompt bez `cache_control` markers | 🟡 SUSPECT — check if Anthropic prompt cache enabled |
|
||||
| Full document extraction bez `(doc_hash, prompt_v, model)` key check | 🔴 RED — memoize |
|
||||
| `@lru_cache` na deterministic function | 🟢 OK (in-memory layer 1) |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# packages/llm-gateway/cache.py
|
||||
async def embed_cached(text: str) -> list[float]:
|
||||
key = f"emb:{hash_text(text)}"
|
||||
if cached := await redis.get(key):
|
||||
langfuse.score(name="cache_hit", value=1, comment="embedding")
|
||||
return json.loads(cached)
|
||||
result = await voyage.embed(text)
|
||||
await redis.set(key, json.dumps(result), ex=86400 * 30) # 30 dni
|
||||
return result
|
||||
|
||||
async def extract_cached(doc_hash: str, prompt_version: str, model: str) -> ExtractionResult:
|
||||
key = f"extract:{doc_hash}:{prompt_version}:{model}"
|
||||
if cached := await redis.get(key):
|
||||
return ExtractionResult.parse_raw(cached)
|
||||
result = await extract(...)
|
||||
await redis.set(key, result.json(), ex=86400) # 24h dla potential prompt iteration
|
||||
return result
|
||||
```
|
||||
|
||||
**Anthropic prompt cache:**
|
||||
|
||||
```python
|
||||
result = await agent.run(
|
||||
user_input,
|
||||
cache_control=[
|
||||
{"type": "ephemeral", "content": JURISDICTION_RULES_PL}, # cached 5min Anthropic
|
||||
{"type": "ephemeral", "content": CLAUSE_LIBRARY_CONTEXT},
|
||||
]
|
||||
)
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **High-cardinality input** (np. unique full-contract text per request) — cache layer 3 (memoization) może mieć low hit rate; layer 1 (Anthropic prompt cache na system prompt) i layer 2 (embedding) nadal applies
|
||||
- **Justification:** "High cardinality input, memoization layer disabled. Anthropic prompt cache + embedding cache active."
|
||||
|
||||
### M7: Async-first task queue
|
||||
|
||||
**Mandat:** Każda operacja **>5s wall-clock** idzie przez **Celery task queue**. Sync API nigdy nie blokuje na LLM call. User dostaje `task_id`, polling/SSE dla updates.
|
||||
|
||||
**Test:** Czy `await long_running_op()` w request handler? Czy load balancer timeout possible?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `await extraction_agent.run(file)` w `apps/api/routes/*.py` | 🔴 RED — wrap w Celery task |
|
||||
| `task = extract_contract.delay(...)` + return task_id | 🟢 OK |
|
||||
| Synchronous operation <5s typical (CRUD, simple validation) | 🟢 N/A |
|
||||
| `asyncio.create_task(...)` bez Celery (fire-and-forget) | 🔴 RED — może nie survive restart, brak retry |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/extraction.py
|
||||
@router.post("/contracts/{id}/extract")
|
||||
async def dispatch_extract(id: UUID, user: User = Depends(current_user)):
|
||||
task = extract_contract_task.apply_async(
|
||||
args=[str(id)],
|
||||
kwargs={"tenant_id": str(user.tenant_id)},
|
||||
)
|
||||
return {"task_id": task.id, "stream_url": f"/api/v1/stream/{task.id}"}
|
||||
|
||||
# apps/workers/tasks/extraction.py
|
||||
@celery_app.task(
|
||||
bind=True,
|
||||
retry_backoff=True,
|
||||
max_retries=3,
|
||||
autoretry_for=(LLMTransientError, ConnectionError),
|
||||
)
|
||||
def extract_contract_task(self, contract_id: str, tenant_id: str):
|
||||
publish_event(self.request.id, "phase", {"phase": "parsing"})
|
||||
# ... run extraction agent, emit SSE events
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Streaming response from LLM directly do client** (np. ChatGPT-style chat completion) — operation może być długa ale streaming z LLM provider; nadal preferred Celery + SSE bridge dla retry/observability, ale acceptable jako direct streaming dla low-latency UX
|
||||
- **Justification:** "Direct LLM streaming for sub-second time-to-first-token UX. Trace captured w Langfuse via streaming callback."
|
||||
|
||||
### M8: Observable LLM ops
|
||||
|
||||
**Mandat:** Każde wywołanie LLM logged w Langfuse z: `prompt_version`, `model`, `input_tokens`, `output_tokens`, `cost_usd`, `latency_ms`, `tenant_id`, `operation`, `trace_id`. Każdy agent run = jeden Langfuse trace z spans per LLM call.
|
||||
|
||||
**Test:** Czy widzę `print()` debugging? Brak Langfuse trace wrap? Brak `tenant_id` w trace metadata?
|
||||
|
||||
| Pattern | Action |
|
||||
|---|---|
|
||||
| `print(f"LLM response: {response}")` w agent code | 🔴 RED — use Langfuse trace |
|
||||
| `trace = langfuse.trace(...)` + `generation = trace.generation(...)` | 🟢 OK |
|
||||
| `LLMRouter` z auto-Langfuse instrumentation built-in | 🟢 OK |
|
||||
| Brak `tenant_id` w trace metadata | 🔴 RED — required per M5 + M8 |
|
||||
|
||||
**OK pattern:**
|
||||
|
||||
```python
|
||||
# packages/agents/clause_extractor.py
|
||||
from langfuse import Langfuse
|
||||
langfuse = Langfuse()
|
||||
|
||||
async def extract_clause(text: str, clause_type: str, tenant_id: str, contract_id: UUID):
|
||||
trace = langfuse.trace(
|
||||
name=f"extract_{clause_type}",
|
||||
metadata={
|
||||
"tenant_id": tenant_id,
|
||||
"contract_id": str(contract_id),
|
||||
"clause_type": clause_type,
|
||||
},
|
||||
tags=[clause_type, "extraction"],
|
||||
)
|
||||
|
||||
generation = trace.generation(
|
||||
name="extraction_llm_call",
|
||||
model="claude-sonnet-4-6",
|
||||
input={"system_prompt": PROMPT_VERSION, "text_preview": text[:500]},
|
||||
metadata={"prompt_version": "liability_v3"},
|
||||
)
|
||||
|
||||
result = await agent.run(text)
|
||||
|
||||
generation.end(
|
||||
output=result.data.dict(),
|
||||
usage={
|
||||
"input": result.usage.input_tokens,
|
||||
"output": result.usage.output_tokens,
|
||||
},
|
||||
)
|
||||
return result.data
|
||||
```
|
||||
|
||||
**Edge case (relax allowed):**
|
||||
|
||||
- **Unit tests** używające mock LLM responses — Langfuse tracking disabled w test environment (`LANGFUSE_ENABLED=false`)
|
||||
- **Justification:** N/A — standard test pattern, no relaxation needed in production code
|
||||
|
||||
## "Kiedy mandat NIE applies"
|
||||
|
||||
Niektóre konteksty są **out of scope** dla mandatów. Wymaga eksplicytnej justifications w code:
|
||||
|
||||
### 1. Internal batch scripts (`scripts/`)
|
||||
|
||||
- Migration scripts, data backfill, one-off operations
|
||||
- Mandates M3 (streaming), M7 (Celery) **NIE applies** — script może być sync long-running
|
||||
- Mandates M2 (schema), M4 (eval), M5 (cost), M8 (Langfuse) **NADAL applies** — schema-first nawet w batch, eval nawet dla batch prompts, cost trackable
|
||||
|
||||
### 2. Dev tools / debug utilities (`tools/`, notebooks/)
|
||||
|
||||
- Exploratory analysis, debugging helpers
|
||||
- Mandates relaxed: M1 (agent), M3 (streaming), M7 (async) — może być direct call
|
||||
- Mandates **NADAL applies**: M2 (schema for production code), M8 (Langfuse w prod)
|
||||
- **Notebooks** mogą być free-form dla experimentation, BUT prompt promoted do production = full mandate compliance
|
||||
|
||||
### 3. One-off migrations (`supabase/migrations/`)
|
||||
|
||||
- DB schema migrations
|
||||
- LLM nie wywoływana z migracji typically — N/A
|
||||
- Jeśli backfill wymaga LLM (np. re-extract clauses z istniejących kontraktów po prompt v4 launch) — write Celery task, full mandate compliance
|
||||
|
||||
### 4. Internal admin operations (`apps/api/routes/admin/*`)
|
||||
|
||||
- Operator-facing, niskie volume (<100/dzień)
|
||||
- M3 (streaming) może być relaxed — operator akceptuje sync wait
|
||||
- M5 (cost tracking) **NADAL applies** — admin operations też kosztują
|
||||
- Justification w PR description
|
||||
|
||||
**Każdy relax wymaga:**
|
||||
|
||||
```python
|
||||
# JUSTIFIED RELAX of M3 (streaming):
|
||||
# Internal admin endpoint, expected <10 uses/day, operator-only.
|
||||
# See ADR-001 "Kiedy mandat NIE applies" section.
|
||||
```
|
||||
|
||||
## Self-check — OBOWIĄZKOWO
|
||||
|
||||
**8 punktów (1 per mandat)** przed każdym merge PR dotykającego LLM/agents. Wykonaj punkt po punkcie:
|
||||
|
||||
### M1 — Agent-first (1)
|
||||
|
||||
1. **Czy operacja >2s idzie przez agent?** — czy `apps/api/routes/**` zawiera direct `anthropic.complete()` / `openai.chat.completions.create()`? Jeśli tak — refactor through PydanticAI agent. Jeśli nie — ✓ albo justified relax.
|
||||
|
||||
### M2 — Schema-first (2)
|
||||
|
||||
2. **Czy LLM I/O ma Pydantic schema?** — czy widzę `re.search()` / `json.loads(response.text)` bez schema validation? Każdy LLM call MUSI mieć `result_type=PydanticModel` lub równoważne structured output. Jeśli `result_type=str` — justify dlaczego (rare valid case).
|
||||
|
||||
### M3 — Streaming-first (3)
|
||||
|
||||
3. **Czy operacja >2s ma SSE variant?** — czy endpoint zwraca task_id + stream_url (M7 pattern)? czy client opens EventSource? Jeśli nie — implement SSE lub justify relax (background batch, admin op).
|
||||
|
||||
### M4 — Eval-driven (4)
|
||||
|
||||
4. **Czy zmiana promptu ma passing eval w CI?** — czy `git diff` rusza `packages/prompts/**`? czy CI eval job triggered? czy thresholds explicit (precision/recall/cost)? Jeśli new clause type — czy golden dataset min 20 PL + 20 EN?
|
||||
|
||||
### M5 — Cost-aware routing (5)
|
||||
|
||||
5. **Czy LLM call ma tenant_id w metadata + model wybrany przez router?** — hardcoded `model="claude-sonnet-4-6"` w business logic = RED. `router.complete(task=..., metadata={"tenant_id": ...})` = OK. Hardcoded model z justification comment = acceptable.
|
||||
|
||||
### M6 — Cache-aware (6)
|
||||
|
||||
6. **Czy 3 warstwy cache active?** — Anthropic prompt cache na system prompt? Embedding cache (Redis)? Result memoization dla extraction key `(doc_hash, prompt_v, model)`? Każda warstwa missing = RED (chyba że justified — high cardinality input).
|
||||
|
||||
### M7 — Async-first (7)
|
||||
|
||||
7. **Czy operacja >5s idzie przez Celery?** — `await long_op()` w route handler = RED. `task.apply_async(...)` + return task_id = OK. Background sync long-running w request thread = blocker dla horizontal scale.
|
||||
|
||||
### M8 — Observable (8)
|
||||
|
||||
8. **Czy LLM call logged w Langfuse?** — `print()` debugging = RED. `trace = langfuse.trace(...) → generation = trace.generation(...) → generation.end(usage=...)` = OK. Brak `tenant_id` w trace metadata = RED (per M5 + M8 cross-requirement).
|
||||
|
||||
**Format PR description** (mandatory dla każdej PR dotykającej LLM):
|
||||
|
||||
```
|
||||
AI-native mandates self-check:
|
||||
- M1 Agent-first ✓ / N/A (internal admin) / ⚠️ relax: <justification>
|
||||
- M2 Schema-first ✓
|
||||
- M3 Streaming ✓ / N/A (background batch)
|
||||
- M4 Eval-driven ✓ (eval CI green, link to run)
|
||||
- M5 Cost-aware ✓ (tenant_id propagated, model via router)
|
||||
- M6 Cache-aware ✓ (3 layers active) / ⚠️ layer 3 disabled: <justification>
|
||||
- M7 Async-first ✓ (Celery task) / N/A (sync <5s op)
|
||||
- M8 Observable ✓ (Langfuse trace ID: <link>)
|
||||
|
||||
Cross-skill:
|
||||
- [[compass-architecture]] self-check (12 pts): <link or inline>
|
||||
- [[compass-clause-taxonomy]] self-check (13 pts): N/A / <link>
|
||||
- legal-tech disclaimer in user-facing output: ✓
|
||||
```
|
||||
|
||||
## Mini-przykłady — PR review walkthrough
|
||||
|
||||
### Przykład 1: PR adding new extraction endpoint
|
||||
|
||||
**Reviewer (lub `compass-pr-reviewer` subagent) sprawdza:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/security_clause.py
|
||||
@router.post("/contracts/{id}/extract-security")
|
||||
async def extract_security(id: UUID, user: User = Depends(current_user)):
|
||||
contract = await db.fetch_one("SELECT * FROM contracts WHERE id = %s", id)
|
||||
response = anthropic.messages.create( # ❌ M1 fail (direct LLM call)
|
||||
model="claude-sonnet-4-6", # ❌ M5 fail (hardcoded model)
|
||||
messages=[{"role": "user", "content": SECURITY_PROMPT + contract.text}]
|
||||
)
|
||||
clauses = json.loads(response.content[0].text) # ❌ M2 fail (no schema)
|
||||
print(f"Extracted: {clauses}") # ❌ M8 fail (print, no Langfuse)
|
||||
return clauses
|
||||
```
|
||||
|
||||
**Verdict:** 4× RED. Block merge. Comment z linkami do mandatów + refactor template.
|
||||
|
||||
**Acceptable refactor:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/security_clause.py
|
||||
@router.post("/contracts/{id}/extract-security", response_model=ExtractionDispatchResponse)
|
||||
async def dispatch_security_extraction(id: UUID, user: User = Depends(current_user)):
|
||||
task = extract_security_task.apply_async(
|
||||
args=[str(id)],
|
||||
kwargs={"tenant_id": str(user.tenant_id), "operation": "extract_security"},
|
||||
)
|
||||
return ExtractionDispatchResponse(task_id=task.id, stream_url=f"/api/v1/stream/{task.id}")
|
||||
|
||||
# apps/workers/tasks/security_extraction.py
|
||||
@celery_app.task(bind=True, retry_backoff=True, max_retries=3)
|
||||
def extract_security_task(self, contract_id: str, tenant_id: str, operation: str):
|
||||
publish_event(self.request.id, "phase", {"phase": "parsing"})
|
||||
contract = fetch_contract(contract_id, tenant_id=tenant_id)
|
||||
|
||||
trace = langfuse.trace(name="extract_security", metadata={"tenant_id": tenant_id, "operation": operation})
|
||||
|
||||
agent = Agent(
|
||||
model="claude-sonnet-4-6", # justified via LLMRouter inside; or use router.complete()
|
||||
result_type=SecurityClause,
|
||||
system_prompt=load_prompt("security_extraction_v1"),
|
||||
)
|
||||
|
||||
result = agent.run_sync(contract.text)
|
||||
|
||||
persist_clause(result.data, contract_id=contract_id, tenant_id=tenant_id)
|
||||
publish_event(self.request.id, "clause_extracted", result.data.dict())
|
||||
publish_event(self.request.id, "done", {})
|
||||
```
|
||||
|
||||
### Przykład 2: Prompt change without eval
|
||||
|
||||
```diff
|
||||
# packages/prompts/clauses/liability_extraction_v3.py
|
||||
- SYSTEM_PROMPT = """You are an AI assistant supporting legal review..."""
|
||||
+ SYSTEM_PROMPT = """You are a legal AI assistant. Extract liability clause..."""
|
||||
```
|
||||
|
||||
**Reviewer:** PR zmienia prompt, ale brak triggered eval w CI (no commit do `packages/evals/**`, no test re-run logged). **M4 fail.**
|
||||
|
||||
**Action:** Comment "M4 violation — re-run eval suite, attach results to PR description. If thresholds drop, address before merge."
|
||||
|
||||
### Przykład 3: Justified relax (internal admin)
|
||||
|
||||
```python
|
||||
# apps/api/routes/admin/reprocess.py
|
||||
"""
|
||||
Internal admin endpoint for reprocessing failed extractions.
|
||||
Expected use: <5/week, operator-only via admin UI.
|
||||
|
||||
JUSTIFIED RELAX of M3 (streaming):
|
||||
- Operator triggers reprocess and waits in admin UI for completion.
|
||||
- No end-user impact, operator accepts up to 5min sync wait.
|
||||
- M7 (Celery) NOT relaxed — still dispatches via task queue for retry semantics.
|
||||
"""
|
||||
|
||||
@router.post("/admin/reprocess/{contract_id}")
|
||||
@require_role("admin")
|
||||
async def reprocess_contract(contract_id: UUID, user: User = Depends(current_user)):
|
||||
task = extract_contract_task.apply_async(
|
||||
args=[str(contract_id)],
|
||||
kwargs={"tenant_id": str(user.tenant_id), "operation": "admin_reprocess"},
|
||||
)
|
||||
# Sync wait — operator OK with this for internal tool
|
||||
result = task.get(timeout=300) # 5 min max
|
||||
return {"status": "completed", "task_id": task.id, "result": result}
|
||||
```
|
||||
|
||||
**Reviewer:** M3 relax z justification — OK. M5/M8 nadal applies (`operation="admin_reprocess"` w metadata).
|
||||
|
||||
## Cross-references
|
||||
|
||||
- **ADR-001** (`docs/architecture/ADR-001-ai-native.md`) — source of truth dla 8 mandatów + alternatives considered
|
||||
- [[compass-architecture]] — 12-punkt self-check dla architectural change (RLS, tenant_id, monorepo boundaries) — uzupełnia mandates
|
||||
- [[compass-clause-taxonomy]] — M2 (schema-first) + M4 (eval-driven) directly relevant dla prompt engineering
|
||||
- **legal-tech** (user-level) — AI legal disclaimer requirement (każdy user-facing LLM output musi mieć "REQUIRES LEGAL COUNSEL SIGN-OFF")
|
||||
- **rag-pipeline-builder** (user-level) — eval infrastructure (RAGAS, hit rate, MRR) dla M4
|
||||
- **cloud-deploy** (user-level) — Langfuse self-hosted deployment dla M8
|
||||
|
||||
## Zasada główna
|
||||
|
||||
**Mandates są MANDATORY, nie aspirational.** Każda PR z LLM operation MUSI mieć VISIBLE self-check w description (8 punktów). `compass-pr-reviewer` subagent (AGENTS.md) używa tego skilla jako baseline — block merge gdy mandate fail bez justification. **Relax acceptable** dla internal/admin/dev tools, ale ZAWSZE z explicit justification w komentarzu kodu + PR description. **Production user-facing code = full compliance, no exceptions.**
|
||||
@@ -0,0 +1,506 @@
|
||||
---
|
||||
name: compass-architecture
|
||||
description: Use when projektujesz, modyfikujesz lub debugujesz system Compass — monorepo structure (apps/web|api|workers|mcp-server + packages/agents|prompts|schemas|ingestion|llm-gateway|retrieval|evals|jurisdictions|core), data model (Tenant/User/Company/Contract/Clause/ClauseLibraryEntry/Jurisdiction/Evaluation z RLS day 1), multi-tenant invariants (tenant_id w JWT, RLS policy każdej tabeli, audit log każdej operacji), API conventions (RESTful + SSE streaming, Pydantic input/output, error shape), deployment topology (Supabase Auth/DB/Storage + Hetzner CCX23 Python API + Celery + Qdrant + Langfuse + Redis), komunikacja frontend↔backend (Supabase JWT verification w FastAPI, SSE via /api/stream/{task_id}, Edge Functions jako bridge). 7 fundamentów (monorepo + uv workspace, data model + RLS, multi-tenant invariants, API conventions, deployment topology, communication patterns, package boundaries). Mandatory self-check 12 punktów przed architectural change. Synergizuje z [[compass-ai-native-mandates]] (każda zmiana musi przejść 8 mandatów z ADR-001), [[compass-clause-taxonomy]] (Pydantic+zod sync), legal-tech (clause taxonomy domain), rag-pipeline-builder (retrieval implementation), cloud-deploy (Hetzner ops), mcp-server-builder (apps/mcp-server). SKIP dla zmian czysto frontend bez wpływu na backend/data model (use frontend-web-ui), dla one-off scripts internal (mandates nie applies — patrz [[compass-ai-native-mandates]] "kiedy NIE applies").
|
||||
---
|
||||
|
||||
Base directory for this skill: `compass-contract-hub/.claude/skills/compass-architecture/`
|
||||
|
||||
# Compass — architecture skill
|
||||
|
||||
System-level skill dla Compass = open-core legal-tech contract management. Definiuje monorepo structure, data model, multi-tenant invariants, API conventions, deployment topology. **Każda architectural decision** w projekcie przechodzi przez ten skill PLUS 8 mandatów z [[compass-ai-native-mandates]] (ADR-001).
|
||||
|
||||
## Kontekst projektu (must-read przed każdą sesją)
|
||||
|
||||
- **Repo:** `compass-contract-hub` (private, Lovable.dev origin, dotychczas Vite+React+Supabase frontend bez AI infrastructure)
|
||||
- **Strategia:** Opcja B Hybrid — frontend zostaje (apps/web), Python AI layer dodajemy (apps/api + apps/workers + apps/mcp-server), Supabase zostaje na start (auth+DB+storage), Hetzner CCX23 dla Python services
|
||||
- **License posture:** PRIVATE repo, no public commits, no LinkedIn mentions, no monetization podczas Bridgestone employment
|
||||
- **AI-native mandate:** ADR-001 obowiązuje od dnia 1 — patrz [[compass-ai-native-mandates]]
|
||||
|
||||
## Kiedy stosować
|
||||
|
||||
- **TAK:** dodajesz/zmieniasz endpoint, dodajesz nową entity/table, zmiana RLS policy, refactor cross-package, nowy package, deployment topology change, communication frontend↔backend, MCP server design
|
||||
- **NIE:** czyste UI tweaks bez data layer (use `frontend-web-ui`), refactor wewnątrz jednego modułu (no architectural impact), one-off migration script, prompt iteration bez schema change (use [[compass-clause-taxonomy]] + [[compass-ai-native-mandates]] M4)
|
||||
|
||||
## 7 fundamentów
|
||||
|
||||
### 1. Monorepo structure + uv workspace
|
||||
|
||||
**Target structure** (po Sprint 1 restructure, NIE wymuszaj teraz):
|
||||
|
||||
```
|
||||
compass-contract-hub/
|
||||
├── apps/
|
||||
│ ├── web/ # Vite + React 18 + TS + shadcn (current src/ → tutaj)
|
||||
│ ├── api/ # FastAPI + PydanticAI agents
|
||||
│ │ ├── routes/
|
||||
│ │ ├── agents/
|
||||
│ │ ├── middleware/ # JWT verify, tenant_id propagation, request_id
|
||||
│ │ └── main.py
|
||||
│ ├── workers/ # Celery tasks (>5s operations)
|
||||
│ │ ├── tasks/
|
||||
│ │ └── celery_app.py
|
||||
│ └── mcp-server/ # MCP server (Compass jako MCP — distribution moat)
|
||||
│ └── server.py
|
||||
├── packages/ # shared Python packages (uv workspace)
|
||||
│ ├── agents/ # PydanticAI agent definitions
|
||||
│ ├── prompts/ # versioned prompts (clauses/, jurisdictions/, reviews/)
|
||||
│ ├── schemas/ # Pydantic models (per clause, per entity)
|
||||
│ ├── ingestion/ # PDF/DOCX/OCR pipeline
|
||||
│ ├── llm-gateway/ # LiteLLM wrapper + router + cache + Langfuse
|
||||
│ ├── retrieval/ # Qdrant client + chunking + hybrid search
|
||||
│ ├── evals/ # golden datasets + promptfoo runners
|
||||
│ ├── jurisdictions/ # pl/, de/, fr/, ... per-country rules
|
||||
│ └── core/ # auth helpers, tenant context, audit log
|
||||
├── docs/
|
||||
│ ├── architecture/ # ADRs
|
||||
│ └── handoffs/
|
||||
├── supabase/ # migrations + Edge Functions
|
||||
├── .claude/
|
||||
│ ├── skills/
|
||||
│ ├── agents/ # subagent definitions per AGENTS.md
|
||||
│ └── settings.json
|
||||
├── CLAUDE.md
|
||||
├── AGENTS.md
|
||||
├── pyproject.toml # uv workspace root
|
||||
└── package.json # npm workspace root (apps/web only)
|
||||
```
|
||||
|
||||
**Boundary rules:**
|
||||
|
||||
- `apps/*` mogą importować z `packages/*`
|
||||
- `apps/*` NIGDY nie importują z innych `apps/*`
|
||||
- `packages/*` mogą importować z `packages/core` i `packages/schemas`
|
||||
- `packages/agents` może importować `packages/prompts`, `packages/schemas`, `packages/llm-gateway`
|
||||
- `packages/llm-gateway` jest **leaf** — nie importuje agents/prompts (single-responsibility router+cache+observability)
|
||||
- `packages/jurisdictions/{country}/` self-contained — local rules dla danego kraju, no cross-country imports
|
||||
|
||||
**uv workspace** (`pyproject.toml` root):
|
||||
|
||||
```toml
|
||||
[tool.uv.workspace]
|
||||
members = ["apps/api", "apps/workers", "apps/mcp-server", "packages/*"]
|
||||
```
|
||||
|
||||
### 2. Data model — entities + RLS day 1
|
||||
|
||||
**Core entities** (Postgres + RLS na każdej tabeli):
|
||||
|
||||
| Entity | Klucz | Multi-tenant scope | Notes |
|
||||
|---|---|---|---|
|
||||
| `tenants` | `id (uuid)` | self | top-level tenant, billing target |
|
||||
| `users` | `id (uuid)` | `tenant_id` | Supabase Auth user mirror, role: admin/member/viewer |
|
||||
| `companies` | `id (uuid)` | `tenant_id` | counterparties (vendor/client), reusable across contracts |
|
||||
| `contracts` | `id (uuid)` | `tenant_id` | doc metadata + file ref + extracted clauses join |
|
||||
| `clauses` | `id (uuid)` | `tenant_id` | extracted clauses per contract, typed (14 taxonomy) |
|
||||
| `clause_library_entries` | `id (uuid)` | `tenant_id` | reusable clause templates, tagged by jurisdiction + type |
|
||||
| `jurisdictions` | `code (text PK)` | global (no RLS) | reference table: pl, de, fr, us-ny, ... |
|
||||
| `evaluations` | `id (uuid)` | `tenant_id` | eval run results per prompt_version per dataset |
|
||||
| `audit_log` | `id (uuid)` | `tenant_id` | append-only, every mutation logged |
|
||||
| `task_events` | `id (uuid)` | `tenant_id` | SSE event stream per task_id (Celery task progress) |
|
||||
|
||||
**Relationships:**
|
||||
|
||||
- `contracts.tenant_id → tenants.id` (RLS scope)
|
||||
- `contracts.vendor_company_id → companies.id`
|
||||
- `contracts.client_company_id → companies.id`
|
||||
- `clauses.contract_id → contracts.id` + `clauses.tenant_id → tenants.id` (denormalized for RLS perf)
|
||||
- `clauses.clause_type` enum (liability/ip/termination/... — 14 typów z [[compass-clause-taxonomy]])
|
||||
- `clauses.jurisdiction_code → jurisdictions.code`
|
||||
- `clause_library_entries.tenant_id` NULLABLE — `NULL` = global Compass-provided library, non-NULL = tenant-private
|
||||
|
||||
**RLS policy template** (każda tabela z `tenant_id`):
|
||||
|
||||
```sql
|
||||
ALTER TABLE contracts ENABLE ROW LEVEL SECURITY;
|
||||
|
||||
CREATE POLICY tenant_isolation ON contracts
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
```
|
||||
|
||||
Python FastAPI middleware ustawia `SET LOCAL app.tenant_id = '<uuid>'` na początku każdej transakcji, po JWT verify.
|
||||
|
||||
**Audit log** — append-only, każda mutacja:
|
||||
|
||||
```python
|
||||
class AuditLogEntry(BaseModel):
|
||||
tenant_id: UUID
|
||||
user_id: UUID
|
||||
operation: Literal["create", "update", "delete", "view_sensitive"]
|
||||
entity_type: str
|
||||
entity_id: UUID
|
||||
diff: dict | None # JSON patch
|
||||
request_id: str
|
||||
timestamp: datetime
|
||||
```
|
||||
|
||||
### 3. Multi-tenant invariants — non-negotiable
|
||||
|
||||
**Te invariants są MANDATORY day 1, nie "dodamy później":**
|
||||
|
||||
1. **`tenant_id` w JWT claims** — Supabase JWT custom claim, weryfikowany w FastAPI middleware
|
||||
2. **RLS na każdej tabeli z `tenant_id`** — żaden endpoint nie omija RLS przez `service_role` key (poza explicit admin operations, logged)
|
||||
3. **`tenant_id` propagation** — każdy LLM call ma `tenant_id` w Langfuse metadata (per M5 z ADR-001), każda Celery task ma `tenant_id` w args, każdy log line ma `tenant_id`
|
||||
4. **Cross-tenant queries zakazane** — jeśli endpoint musi cross-tenant (np. admin analytics), explicit `with_admin_context()` wrapper który logguje + waliduje user role
|
||||
5. **Storage isolation** — file paths prefixed `<tenant_id>/...` w Supabase Storage bucket, Storage policy enforces prefix match z JWT tenant_id
|
||||
6. **Vector DB isolation** — Qdrant payload filter `{"tenant_id": "..."}` ZAWSZE w query, no cross-tenant similarity search
|
||||
7. **Background jobs isolation** — Celery routes per-tenant queue (`extract.{tenant_id}`) lub global queue z tenant_id w task args, NIGDY shared state cross-tenant
|
||||
|
||||
**Anti-pattern (real-world MikeOSS Issue #144):**
|
||||
|
||||
```python
|
||||
# NO — bypasses RLS via service_role
|
||||
supabase.from_("contracts").select("*").execute() # returns ALL tenants
|
||||
```
|
||||
|
||||
**OK:**
|
||||
|
||||
```python
|
||||
# tenant context set by middleware after JWT verify
|
||||
async with db.tenant_context(tenant_id):
|
||||
contracts = await db.fetch("SELECT * FROM contracts WHERE ...")
|
||||
# RLS enforces tenant_id filter via app.tenant_id session var
|
||||
```
|
||||
|
||||
### 4. API conventions — RESTful + SSE streaming
|
||||
|
||||
**REST resources** (FastAPI routers):
|
||||
|
||||
```
|
||||
GET /api/v1/contracts # list (paginated, RLS-filtered)
|
||||
POST /api/v1/contracts # create (sync, metadata only)
|
||||
GET /api/v1/contracts/{id} # detail
|
||||
PATCH /api/v1/contracts/{id} # partial update
|
||||
DELETE /api/v1/contracts/{id} # soft delete (sets deleted_at)
|
||||
|
||||
POST /api/v1/contracts/{id}/extract # dispatch extraction agent → returns task_id
|
||||
GET /api/v1/tasks/{task_id} # task status snapshot
|
||||
GET /api/v1/stream/{task_id} # SSE stream (per M3 ADR-001)
|
||||
|
||||
GET /api/v1/clauses/{id} # single clause detail
|
||||
POST /api/v1/clauses/{id}/review # human review sign-off (Approved/Rejected/Needs Attention)
|
||||
```
|
||||
|
||||
**Pydantic input/output everywhere** (per M2 ADR-001):
|
||||
|
||||
```python
|
||||
class ContractCreateInput(BaseModel):
|
||||
title: str
|
||||
vendor_company_id: UUID
|
||||
client_company_id: UUID
|
||||
jurisdiction_code: str
|
||||
|
||||
class ContractResponse(BaseModel):
|
||||
id: UUID
|
||||
title: str
|
||||
status: Literal["draft", "extracting", "extracted", "reviewed", "signed", "active", "expired"]
|
||||
extraction_task_id: UUID | None
|
||||
created_at: datetime
|
||||
|
||||
@router.post("/contracts", response_model=ContractResponse)
|
||||
async def create_contract(body: ContractCreateInput, user: User = Depends(current_user)):
|
||||
...
|
||||
```
|
||||
|
||||
**Error response shape** (uniform):
|
||||
|
||||
```python
|
||||
class ErrorResponse(BaseModel):
|
||||
error: str # machine-readable code, e.g. "tenant_mismatch", "schema_validation_failed"
|
||||
message: str # human-readable
|
||||
request_id: str # for log correlation
|
||||
details: dict | None # additional context
|
||||
```
|
||||
|
||||
**SSE streaming convention** (`/api/v1/stream/{task_id}`):
|
||||
|
||||
```
|
||||
event: phase
|
||||
data: {"phase": "parsing", "progress": 0.1}
|
||||
|
||||
event: clause_extracted
|
||||
data: {"clause_type": "liability", "confidence": 0.92, "text": "..."}
|
||||
|
||||
event: done
|
||||
data: {"total_clauses": 12, "duration_ms": 45000}
|
||||
|
||||
event: error
|
||||
data: {"error": "doc_parsing_failed", "message": "..."}
|
||||
```
|
||||
|
||||
**Client subscribes** via `EventSource`, server publishes events via Redis pub/sub from Celery workers (`packages/core/events.py`).
|
||||
|
||||
### 5. Deployment topology
|
||||
|
||||
**Phase 0 (Sprint 1-4) — Hybrid Supabase + Hetzner:**
|
||||
|
||||
```
|
||||
┌─────────────────────────┐ ┌──────────────────────────────────┐
|
||||
│ Vercel / Netlify │ │ Hetzner CCX23 (Falkenstein DE) │
|
||||
│ apps/web (Vite/React) │ │ │
|
||||
│ │ │ ┌────────────────────────────┐ │
|
||||
└────────────┬────────────┘ │ │ Caddy reverse proxy + TLS │ │
|
||||
│ JWT (Supabase) │ └─────────┬──────────────────┘ │
|
||||
│ │ │ │
|
||||
▼ │ ┌─────────▼──────────┐ │
|
||||
┌──────────────────┐ │ │ FastAPI (apps/api) │ │
|
||||
│ Supabase │ │ └─────────┬──────────┘ │
|
||||
│ - Auth │ │ │ │
|
||||
│ - Postgres+RLS │◄────────────┼────────────┘ │
|
||||
│ - Storage │ │ ┌────────────────────┐ │
|
||||
│ - Edge Funcs │ │ │ Celery workers │ │
|
||||
│ (bridge) │ │ │ (apps/workers) │ │
|
||||
└──────────────────┘ │ └─────────┬──────────┘ │
|
||||
│ │ │
|
||||
│ ┌─────────▼──────────┐ │
|
||||
│ │ Redis (broker+SSE) │ │
|
||||
│ └────────────────────┘ │
|
||||
│ ┌────────────────────┐ │
|
||||
│ │ Qdrant (vectors) │ │
|
||||
│ └────────────────────┘ │
|
||||
│ ┌────────────────────┐ │
|
||||
│ │ Langfuse self-host │ │
|
||||
│ └────────────────────┘ │
|
||||
└──────────────────────────────────┘
|
||||
```
|
||||
|
||||
**Phase 1 (przed enterprise launch) — full Hetzner self-host:**
|
||||
|
||||
- Migracja Supabase → self-host Postgres + Authentik na Hetzner
|
||||
- Storage: Hetzner Storage Box S3-compatible
|
||||
- Reasoning: EU data residency, enterprise sovereignty requirements, brak vendor lock-in
|
||||
|
||||
**Docker compose** structure (Hetzner):
|
||||
|
||||
```yaml
|
||||
# docker-compose.yml (Hetzner)
|
||||
services:
|
||||
caddy: # reverse proxy + TLS
|
||||
api: # FastAPI
|
||||
workers: # Celery
|
||||
redis:
|
||||
qdrant:
|
||||
langfuse-web:
|
||||
langfuse-worker:
|
||||
langfuse-db: # separate Postgres dla Langfuse
|
||||
```
|
||||
|
||||
Detale ops (firewall, fail2ban, backups, monitoring) → invoke `cloud-deploy` skill przy actual deploy.
|
||||
|
||||
### 6. Communication patterns frontend ↔ backend
|
||||
|
||||
**Auth flow:**
|
||||
|
||||
1. User login → Supabase Auth → JWT z custom claim `tenant_id`
|
||||
2. Frontend stores JWT (httpOnly cookie via Supabase SDK)
|
||||
3. Each request do `apps/api`: `Authorization: Bearer <jwt>`
|
||||
4. FastAPI middleware (`packages/core/auth.py`):
|
||||
- Verify JWT signature (Supabase JWKS)
|
||||
- Extract `user_id`, `tenant_id`, `role`
|
||||
- `SET LOCAL app.tenant_id = ...` na Postgres session
|
||||
- Attach to `request.state.user`
|
||||
|
||||
**Long-running operations (>5s):**
|
||||
|
||||
1. Frontend POST `/api/v1/contracts/{id}/extract` → instant 202 z `task_id`
|
||||
2. Frontend opens `EventSource('/api/v1/stream/{task_id}')`
|
||||
3. Celery worker emituje events do Redis pub/sub: `task_events:{task_id}`
|
||||
4. SSE endpoint subscribes Redis → forwards do client
|
||||
5. On `event: done` → client closes EventSource, refetch contract detail
|
||||
|
||||
**Webhooks (rare — np. third-party integrations):**
|
||||
|
||||
- Supabase Edge Function jako bridge — receives external webhook, JWT-signs forward do Python API, ensures tenant context
|
||||
- Reason: Edge Functions mają już dostęp do Supabase secrets + RLS context, prostsze niż secondary auth layer
|
||||
|
||||
**File upload:**
|
||||
|
||||
1. Client → Supabase Storage direct upload (signed URL z Edge Function, prefix `<tenant_id>/contracts/...`)
|
||||
2. Client POST `/api/v1/contracts/{id}/extract` z `storage_path`
|
||||
3. Worker fetches file z Supabase Storage przez service_role (within tenant context check)
|
||||
|
||||
### 7. Package boundaries — kto wie o czym
|
||||
|
||||
**Dependency direction (acyclic):**
|
||||
|
||||
```
|
||||
apps/api ──┐
|
||||
apps/workers ──┼──► packages/agents ──► packages/prompts
|
||||
apps/mcp-server ──┘ └──► packages/schemas
|
||||
└──► packages/llm-gateway ──► (LiteLLM, Anthropic SDK)
|
||||
└──► packages/retrieval ──► (Qdrant, Voyage)
|
||||
|
||||
packages/ingestion ──► packages/schemas
|
||||
packages/evals ──► packages/prompts + packages/agents
|
||||
packages/jurisdictions/{country} ──► packages/schemas
|
||||
|
||||
packages/core ◄── (everyone) — auth, tenant context, audit, events
|
||||
```
|
||||
|
||||
**Co należy gdzie — decision tree:**
|
||||
|
||||
| Co tworzysz | Gdzie |
|
||||
|---|---|
|
||||
| Pydantic model dla entity (Contract, Clause) | `packages/schemas/entities/` |
|
||||
| Pydantic model dla LLM output (LiabilityCap, ConfidentialityClause) | `packages/schemas/clauses/` |
|
||||
| Prompt template (versioned) | `packages/prompts/clauses/{type}_v{N}.py` |
|
||||
| PydanticAI agent definition | `packages/agents/{name}_agent.py` |
|
||||
| FastAPI route handler | `apps/api/routes/{resource}.py` |
|
||||
| Celery task | `apps/workers/tasks/{operation}.py` |
|
||||
| RLS migration | `supabase/migrations/{timestamp}_{name}.sql` |
|
||||
| MCP tool definition | `apps/mcp-server/tools/{name}.py` |
|
||||
| Country-specific rule (DE BGB AGB-Kontrolle) | `packages/jurisdictions/de/{clause}.py` |
|
||||
| Eval golden dataset | `packages/evals/datasets/{clause}_{jurisdiction}.jsonl` |
|
||||
| Eval test | `packages/evals/tests/test_{clause}_{jurisdiction}.py` |
|
||||
| Auth/tenant helper | `packages/core/auth.py` lub `packages/core/tenant.py` |
|
||||
| Audit log helper | `packages/core/audit.py` |
|
||||
| SSE event publisher | `packages/core/events.py` |
|
||||
|
||||
## Self-check — OBOWIĄZKOWO
|
||||
|
||||
**12 punktów** przed każdą architectural change. Wykonaj punkt po punkcie:
|
||||
|
||||
### Monorepo + packages (1-3)
|
||||
|
||||
1. **Boundary respected** — czy nowy import nie łamie kierunku (apps→packages, nie odwrotnie)? czy nie tworzy cyklu między packages?
|
||||
2. **Properly placed** — czy plik jest w właściwym package per tabela "Co należy gdzie"?
|
||||
3. **uv workspace consistent** — czy `pyproject.toml` package zaktualizowany (dependencies, name)?
|
||||
|
||||
### Data model + RLS (4-6)
|
||||
|
||||
4. **RLS day 1** — czy nowa tabela ma RLS enabled + tenant_isolation policy w tym samym migration file?
|
||||
5. **tenant_id denormalized gdzie trzeba** — czy nested entity (np. clauses) ma własny tenant_id column dla RLS perf, nie polega na JOIN?
|
||||
6. **Audit log entry** — czy nowa mutation operation emituje audit_log entry przez `packages/core/audit`?
|
||||
|
||||
### Multi-tenant invariants (7-9)
|
||||
|
||||
7. **tenant_id propagation** — czy nowy LLM call ma tenant_id w Langfuse metadata? czy nowa Celery task ma tenant_id w args? czy nowy log line ma tenant_id w context?
|
||||
8. **No service_role bypass** — czy nie używam `service_role` key do omijania RLS (poza explicit admin operation z log)?
|
||||
9. **Storage/Vector isolation** — czy nowy file path ma `<tenant_id>/...` prefix? czy nowy Qdrant query ma payload filter `tenant_id`?
|
||||
|
||||
### API + communication (10-11)
|
||||
|
||||
10. **Schema-first** — czy endpoint ma Pydantic input + output model? error response zgodny z `ErrorResponse` shape?
|
||||
11. **Streaming dla >2s** — czy long-running operation ma SSE variant + task_id pattern (per M3+M7 ADR-001)?
|
||||
|
||||
### Cross-skill consistency (12)
|
||||
|
||||
12. **8 mandatów ADR-001** — czy zmiana przeszła [[compass-ai-native-mandates]] self-check (8 punktów osobno)?
|
||||
|
||||
**Dla każdej PR z architectural change** — VISIBLE confirmation w PR description:
|
||||
|
||||
```
|
||||
Architecture self-check:
|
||||
- Monorepo boundary ✓
|
||||
- File placement ✓
|
||||
- uv workspace ✓
|
||||
- RLS day 1 ✓
|
||||
- tenant_id denormalization ✓
|
||||
- Audit log ✓
|
||||
- tenant_id propagation ✓
|
||||
- No RLS bypass ✓
|
||||
- Storage/Vector isolation ✓
|
||||
- Schema-first I/O ✓
|
||||
- SSE streaming (if applicable) ✓ / N/A
|
||||
- ADR-001 mandates ✓ (link to compass-ai-native-mandates checklist)
|
||||
```
|
||||
|
||||
## Mini-przykłady
|
||||
|
||||
### Przykład 1: dodanie nowego endpoint extraction status
|
||||
|
||||
**Złe:**
|
||||
|
||||
```python
|
||||
# apps/api/main.py — wrzucone bezpośrednio do main.py
|
||||
@app.get("/status/{task_id}")
|
||||
def get_status(task_id: str):
|
||||
return celery_app.AsyncResult(task_id).state # NO — brak RLS, brak Pydantic output, brak tenant check
|
||||
```
|
||||
|
||||
**OK:**
|
||||
|
||||
```python
|
||||
# apps/api/routes/tasks.py
|
||||
from packages.core.auth import current_user, User
|
||||
from packages.core.tasks import get_task_status
|
||||
|
||||
class TaskStatusResponse(BaseModel):
|
||||
task_id: UUID
|
||||
status: Literal["pending", "in_progress", "completed", "failed"]
|
||||
progress: float
|
||||
tenant_id: UUID # echo for sanity
|
||||
|
||||
@router.get("/tasks/{task_id}", response_model=TaskStatusResponse)
|
||||
async def get_task(task_id: UUID, user: User = Depends(current_user)):
|
||||
status = await get_task_status(task_id, tenant_id=user.tenant_id)
|
||||
if status is None:
|
||||
raise HTTPException(404, "Task not found or not accessible") # 404 nie 403 — info disclosure
|
||||
return status
|
||||
```
|
||||
|
||||
### Przykład 2: dodanie nowej entity `negotiation_session`
|
||||
|
||||
1. **Migration** (`supabase/migrations/20260520_negotiation_sessions.sql`):
|
||||
```sql
|
||||
CREATE TABLE negotiation_sessions (
|
||||
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
tenant_id uuid NOT NULL REFERENCES tenants(id),
|
||||
contract_id uuid NOT NULL REFERENCES contracts(id),
|
||||
status text NOT NULL CHECK (status IN ('open', 'closed')),
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
ALTER TABLE negotiation_sessions ENABLE ROW LEVEL SECURITY;
|
||||
CREATE POLICY tenant_isolation ON negotiation_sessions
|
||||
USING (tenant_id = (current_setting('app.tenant_id', true))::uuid)
|
||||
WITH CHECK (tenant_id = (current_setting('app.tenant_id', true))::uuid);
|
||||
```
|
||||
2. **Pydantic schema** (`packages/schemas/entities/negotiation_session.py`)
|
||||
3. **Route** (`apps/api/routes/negotiations.py`) z RLS-respecting handler
|
||||
4. **Audit log** — emit entry on create/close
|
||||
5. **Self-check 12 punktów** w PR description
|
||||
|
||||
### Przykład 3: dispatching agent z tenant context
|
||||
|
||||
```python
|
||||
# apps/api/routes/contracts.py
|
||||
@router.post("/contracts/{contract_id}/extract")
|
||||
async def dispatch_extraction(contract_id: UUID, user: User = Depends(current_user)):
|
||||
task = extract_contract_task.apply_async(
|
||||
args=[str(contract_id)],
|
||||
kwargs={"tenant_id": str(user.tenant_id), "user_id": str(user.id)},
|
||||
queue=f"extract.{user.tenant_id}", # per-tenant queue isolation (optional, scale-up tactic)
|
||||
)
|
||||
return {"task_id": task.id, "stream_url": f"/api/v1/stream/{task.id}"}
|
||||
|
||||
# apps/workers/tasks/extraction.py
|
||||
@celery_app.task(bind=True, retry_backoff=True, max_retries=3)
|
||||
def extract_contract_task(self, contract_id: str, tenant_id: str, user_id: str):
|
||||
# tenant context for DB queries
|
||||
with db.tenant_context(tenant_id):
|
||||
contract = db.fetch_one("SELECT * FROM contracts WHERE id = %s", contract_id)
|
||||
|
||||
# Langfuse trace z tenant_id
|
||||
trace = langfuse.trace(name="extract_contract", metadata={"tenant_id": tenant_id, "user_id": user_id})
|
||||
|
||||
# dispatch agent
|
||||
result = extraction_agent.run_sync(
|
||||
contract.text,
|
||||
deps={"tenant_id": tenant_id, "jurisdiction": contract.jurisdiction_code},
|
||||
)
|
||||
# ... persist clauses, emit SSE events
|
||||
```
|
||||
|
||||
## Cross-references
|
||||
|
||||
- [[compass-ai-native-mandates]] — 8 mandatów ADR-001, każda zmiana MUSI też przejść tamtejszy self-check
|
||||
- [[compass-clause-taxonomy]] — schema-first realization dla 14 clauses (Pydantic + zod sync)
|
||||
- legal-tech (user-level) — domain knowledge: anatomy of contract, red flags, GDPR/RODO checklist
|
||||
- rag-pipeline-builder (user-level) — `packages/retrieval` implementation (chunking, hybrid search, eval)
|
||||
- cloud-deploy (user-level) — Hetzner deployment ops (Caddy, fail2ban, backups)
|
||||
- mcp-server-builder (user-level) — `apps/mcp-server` implementation
|
||||
- frontend-web-ui (user-level) — `apps/web` UI changes (SSE consumer, Pydantic→TS type sync)
|
||||
|
||||
## Zasada główna
|
||||
|
||||
**Architecture decisions are sticky.** Database schema, RLS policies, package boundaries, communication patterns — wszystko to jest hard to reverse po pierwszym customer w prod. **Sprint 0-1 to jedyne okno** żeby je ustawić raz a dobrze. Każda decision musi przejść self-check 12 punktów + ADR-001 mandates. Jeśli decision jest istotna (nowa entity, nowy package, nowa komunikacja cross-service) → ADR osobny dokument w `docs/architecture/ADR-NNN-*.md` z context/decision/consequences/alternatives. Jeśli to refactor zakresu jednego pliku — nie potrzeba ADR, ale self-check tak.
|
||||
@@ -0,0 +1,581 @@
|
||||
---
|
||||
name: compass-clause-taxonomy
|
||||
description: Use when projektujesz, modyfikujesz lub debugujesz extraction/review/storage dla 14-clause taxonomy w Compass (liability, ip, termination, dataPrivacy, payment, delivery, confidentiality, renewal, maintenance, scopeOfWork, sla, security, mileage, other) — Pydantic schema per clause type (fields + validators + confidence + source_location), zod mirror w `src/components/contract-form/schema.ts` (sync rule Python↔TS), per-jurisdiction variants w `packages/jurisdictions/{country}/{clause}.py` (PL/DE/FR/US z local rules), extraction prompt templates w `packages/prompts/clauses/{clause}_extraction_v{N}.py` (versioned, eval-gated), confidence score conventions (0..1 confloat, threshold 0.7 display / <0.5 flag human), red flag patterns (delegated do legal-tech skill który ma pełną tabelę), workflow dodawania nowej clause type (Pydantic + zod mirror + prompt + golden 20+ + eval + migration + UI field). 7 fundamentów (14-clause baseline matchuje legal-tech, Pydantic schema template, zod mirror sync, per-jurisdiction package, prompt versioning, confidence thresholds, add-clause workflow). Mandatory self-check 13 punktów przed dodaniem/zmianą clause type. Synergizuje z legal-tech (full red flag library + GDPR/AI Act + multi-jurisdiction baseline), [[compass-ai-native-mandates]] (M2 schema-first + M4 eval-driven), [[compass-architecture]] (RLS na clauses table, tenant_id propagation). SKIP dla generic legal questions (use legal-tech), drafting umowy from scratch (legal-tech "kiedy NIE"), zmian w UI bez schema change (use frontend-web-ui).
|
||||
---
|
||||
|
||||
Base directory for this skill: `compass-contract-hub/.claude/skills/compass-clause-taxonomy/`
|
||||
|
||||
# Compass — clause taxonomy skill
|
||||
|
||||
Implementation skill dla **14-clause taxonomy** w Compass. Domain knowledge (red flags, jurisdiction variants, anatomy of contract) jest w user-level `legal-tech` skill — TEN skill dotyczy **technicznej realizacji**: Pydantic schemas, zod mirrors, prompt templates, golden datasets, eval gates.
|
||||
|
||||
## Baseline — 14 typów (NIE zmieniać bez ADR)
|
||||
|
||||
Taxonomy MUSI matchować user-level `legal-tech` skill + istniejący zod schema w `src/components/contract-form/schema.ts`. Lista kanoniczna (kolejność z `clauseDisplayConfig`):
|
||||
|
||||
| Klucz | Polski display | Industry priority hint |
|
||||
|---|---|---|
|
||||
| `liability` | Liability | universal (top-1 dla all) |
|
||||
| `ip` | Intellectual Property | tech/consulting/agencja (top-3 dla haski.io SOW) |
|
||||
| `termination` | Termination Conditions | universal (top-3 dla SaaS) |
|
||||
| `dataPrivacy` | Data Privacy | RODO data flows (top-1 dla biura rachunkowe/finanse) |
|
||||
| `payment` | Payment Terms | universal |
|
||||
| `delivery` | Delivery & Scope | logistyka/dostawa fizyczna |
|
||||
| `confidentiality` | Confidentiality | top-1 dla kancelarie prawne |
|
||||
| `renewal` | Renewal | SaaS/subskrypcje |
|
||||
| `maintenance` | Maintenance | utrzymanie systemów |
|
||||
| `scopeOfWork` | Scope of Work | SOW dla services (top-1 haski.io) |
|
||||
| `sla` | Service Level Agreement | top-1 dla finanse/critical infra |
|
||||
| `security` | Security | top-2 dla finanse/health/legal |
|
||||
| `mileage` | Mileage & Usage | logistyka/leasing/usage-based pricing |
|
||||
| `other` | Other Key Clauses | catch-all (force majeure, indemnity, warranty) |
|
||||
|
||||
**Adding nowy clause type = ADR osobny** (taxonomy change to breaking change dla istniejących extractions + golden datasets + zod schema + UI form). Patrz **fundament 7** poniżej dla workflow.
|
||||
|
||||
## Kiedy stosować
|
||||
|
||||
- **TAK:** dodajesz/zmieniasz Pydantic schema clause type, tworzysz/iterujesz extraction prompt, dodajesz golden dataset example, dodajesz per-jurisdiction variant (DE/FR/US specifics), syncujesz zod mirror, debugujesz extraction quality (low precision/recall), dodajesz nowy clause type (z ADR), zmieniasz confidence threshold
|
||||
- **NIE:** generic legal questions ("co to liability cap?") — use `legal-tech`; drafting umowy from scratch — use `legal-tech`; zmiana UI form layout bez schema change — use `frontend-web-ui`; eval infrastructure setup (promptfoo runner, RAGAS) — use `rag-pipeline-builder`
|
||||
|
||||
## 7 fundamentów
|
||||
|
||||
### 1. Pydantic schema template per clause type
|
||||
|
||||
**Convention:** każdy clause type ma Pydantic model w `packages/schemas/clauses/{clause}.py` z **standardowymi 5 polami** + clause-specific fields.
|
||||
|
||||
**Standardowe pola (każdy clause):**
|
||||
|
||||
```python
|
||||
from decimal import Decimal
|
||||
from typing import Literal
|
||||
from pydantic import BaseModel, Field, confloat
|
||||
|
||||
class ClauseBase(BaseModel):
|
||||
"""Base for all extracted clauses. Subclass per clause type."""
|
||||
found: bool # True jeśli clause obecna w kontrakcie
|
||||
text: str | None = Field(None, description="Verbatim text from contract")
|
||||
source_location: str | None = Field(None, description="e.g. 'Section 5.2', 'Annex B', 'Clause 12(a)'")
|
||||
confidence: confloat(ge=0, le=1) = Field(description="LLM confidence 0..1")
|
||||
extraction_prompt_version: str = Field(description="e.g. 'liability_v3'")
|
||||
requires_counsel_review: Literal[True] = True # always True per legal-tech disclaimer
|
||||
```
|
||||
|
||||
**Per-clause example — Liability:**
|
||||
|
||||
```python
|
||||
# packages/schemas/clauses/liability.py
|
||||
from typing import Literal
|
||||
from decimal import Decimal
|
||||
from .base import ClauseBase
|
||||
|
||||
class LiabilityCap(BaseModel):
|
||||
amount: Decimal | None
|
||||
currency: Literal["EUR", "USD", "PLN", "GBP", "CHF"] | None
|
||||
scope: Literal["aggregate", "per_event", "per_claim", "annual"] | None
|
||||
multiplier_of_fees: float | None = Field(None, description="e.g. 1.0 = 12mo fees, 2.0 = 24mo")
|
||||
|
||||
class LiabilityClause(ClauseBase):
|
||||
cap: LiabilityCap | None
|
||||
excludes_indirect: bool | None
|
||||
excludes_consequential: bool | None
|
||||
excludes_lost_profits: bool | None
|
||||
mutual: bool | None = Field(None, description="True = both parties, False = asymmetric")
|
||||
carve_outs: list[Literal[
|
||||
"gross_negligence", "willful_misconduct", "ip_indemnity",
|
||||
"confidentiality_breach", "data_breach", "fraud"
|
||||
]] = Field(default_factory=list)
|
||||
preliminary_status: Literal["Approved", "Needs Attention", "Rejected"] | None
|
||||
key_observations: list[str] = Field(default_factory=list, max_length=5)
|
||||
suggested_questions_for_counsel: list[str] = Field(default_factory=list, max_length=5)
|
||||
```
|
||||
|
||||
**Validator example** (catch obvious extraction errors):
|
||||
|
||||
```python
|
||||
from pydantic import model_validator
|
||||
|
||||
class LiabilityClause(ClauseBase):
|
||||
# ... fields ...
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_consistency(self):
|
||||
if self.found and self.cap is None and self.preliminary_status == "Approved":
|
||||
# unlimited liability accepted? probably extraction error
|
||||
self.preliminary_status = "Needs Attention"
|
||||
self.key_observations.insert(0, "No cap found — verify if unlimited liability is intentional")
|
||||
return self
|
||||
```
|
||||
|
||||
**Per-clause Pydantic models** (do utworzenia w Sprint 2+, prompt per clause):
|
||||
|
||||
| Clause | File | Key fields beyond base |
|
||||
|---|---|---|
|
||||
| `liability` | `liability.py` | cap, excludes_*, carve_outs, mutual |
|
||||
| `ip` | `ip.py` | ownership (vendor/client/joint/license), background_ip_carve_out, license_scope, perpetual |
|
||||
| `termination` | `termination.py` | for_convenience (mutual?), notice_days, for_cause_triggers, survival_clauses |
|
||||
| `dataPrivacy` | `data_privacy.py` | dpa_attached, sub_processors_policy, sccs_present, data_transfer_outside_eea, retention_policy |
|
||||
| `payment` | `payment.py` | net_days, late_payment_interest_rate, currency, fx_clause, taxes_inclusive |
|
||||
| `delivery` | `delivery.py` | milestones, acceptance_procedure, delay_penalty |
|
||||
| `confidentiality` | `confidentiality.py` | duration_years, mutual, exceptions, residuals_clause |
|
||||
| `renewal` | `renewal.py` | auto_renewal, notice_days, rate_increase_cap, evergreen |
|
||||
| `maintenance` | `maintenance.py` | sla_tier, response_time_business_hours, response_time_critical |
|
||||
| `scopeOfWork` | `scope_of_work.py` | deliverables, change_request_procedure, exclusions |
|
||||
| `sla` | `sla.py` | uptime_percent, response_time_levels, credits_or_penalties |
|
||||
| `security` | `security.py` | encryption_at_rest, encryption_in_transit, certifications, audit_rights, breach_notification_hours |
|
||||
| `mileage` | `mileage.py` | usage_caps, overage_fee_multiplier, hard_caps |
|
||||
| `other` | `other.py` | catch-all dict[str, str] + flagged_items |
|
||||
|
||||
### 2. Zod mirror — TS frontend sync
|
||||
|
||||
**Source of truth:** Pydantic w `packages/schemas/clauses/`. Zod schema w `src/components/contract-form/schema.ts` to **mirror** generowany lub utrzymywany manualnie.
|
||||
|
||||
**Aktualny stan** (Sprint 0): zod schema generic (`clauseDetailSchema` z `location: string`, `text: string`, `review.status`) — wszystkie 14 klucze używają tego samego shape. **Wystarczające na MVP**, ale ograniczone:
|
||||
|
||||
```typescript
|
||||
// src/components/contract-form/schema.ts (current — generic)
|
||||
const clauseDetailSchema = z.object({
|
||||
location: z.string().max(100).optional().or(z.literal('')),
|
||||
text: z.string().max(1000).optional().or(z.literal('')),
|
||||
review: clauseReviewSchema.optional(),
|
||||
}).optional();
|
||||
```
|
||||
|
||||
**Target** (Sprint 2+, gdy frontend zacznie display per-clause structured data):
|
||||
|
||||
**Opcja A — manual mirror per clause (recommended dla Compass scale):**
|
||||
|
||||
```typescript
|
||||
// src/components/contract-form/clauses/liability.ts
|
||||
import * as z from 'zod';
|
||||
|
||||
export const liabilityClauseSchema = z.object({
|
||||
found: z.boolean(),
|
||||
text: z.string().nullable(),
|
||||
source_location: z.string().nullable(),
|
||||
confidence: z.number().min(0).max(1),
|
||||
cap: z.object({
|
||||
amount: z.number().nullable(),
|
||||
currency: z.enum(["EUR", "USD", "PLN", "GBP", "CHF"]).nullable(),
|
||||
scope: z.enum(["aggregate", "per_event", "per_claim", "annual"]).nullable(),
|
||||
multiplier_of_fees: z.number().nullable(),
|
||||
}).nullable(),
|
||||
excludes_indirect: z.boolean().nullable(),
|
||||
excludes_consequential: z.boolean().nullable(),
|
||||
excludes_lost_profits: z.boolean().nullable(),
|
||||
mutual: z.boolean().nullable(),
|
||||
carve_outs: z.array(z.enum([
|
||||
"gross_negligence", "willful_misconduct", "ip_indemnity",
|
||||
"confidentiality_breach", "data_breach", "fraud"
|
||||
])),
|
||||
preliminary_status: z.enum(["Approved", "Needs Attention", "Rejected"]).nullable(),
|
||||
key_observations: z.array(z.string()).max(5),
|
||||
suggested_questions_for_counsel: z.array(z.string()).max(5),
|
||||
});
|
||||
|
||||
export type LiabilityClause = z.infer<typeof liabilityClauseSchema>;
|
||||
```
|
||||
|
||||
**Opcja B — auto-gen z Pydantic** (preferred dla scale, Sprint 3+):
|
||||
|
||||
- Tool: [`datamodel-code-generator`](https://github.com/koxudaxi/datamodel-code-generator) Python → JSON Schema → [`json-schema-to-zod`](https://github.com/StefanTerdell/json-schema-to-zod)
|
||||
- Script `scripts/sync-schemas.py` triggered w CI on changes do `packages/schemas/clauses/**`
|
||||
- Output `apps/web/src/types/clauses.generated.ts` (gitignored, regenerated on build)
|
||||
- Zaleta: zero drift Pydantic ↔ zod
|
||||
- Wada: extra build step, debug generation issues
|
||||
|
||||
**Sync rule (krytyczna, MANDATORY):**
|
||||
|
||||
> Każda zmiana w `packages/schemas/clauses/{clause}.py` MUSI być sync-owana z `src/components/contract-form/clauses/{clause}.ts` (manual) lub regenerated (auto) w tym samym PR. CI test (kontrakt API): `pytest tests/integration/test_schema_sync.py` walidujący że zod z apps/web matches Pydantic JSON schema z packages/schemas.
|
||||
|
||||
### 3. Per-jurisdiction variants
|
||||
|
||||
**Struktura:** `packages/jurisdictions/{country_code}/{clause}.py` z local rules, validators, prompt hints.
|
||||
|
||||
```
|
||||
packages/jurisdictions/
|
||||
├── __init__.py
|
||||
├── pl/
|
||||
│ ├── __init__.py
|
||||
│ ├── liability.py # KC art. 484 § 2, 473 § 2 mandatory liability
|
||||
│ ├── payment.py # UTP Net 60 max, ustawowe odsetki
|
||||
│ ├── data_privacy.py # UODO specifics, ROPA
|
||||
│ └── ...
|
||||
├── de/
|
||||
│ ├── liability.py # BGB §§ 305-310 AGB-Kontrolle, § 309 Nr. 7 gross negligence
|
||||
│ ├── data_privacy.py # BDSG strict
|
||||
│ └── ...
|
||||
├── fr/
|
||||
│ ├── data_privacy.py # CNIL specifics
|
||||
│ └── ...
|
||||
├── us_ny/ # state-level dla US
|
||||
│ ├── liability.py # UCC + NY common law
|
||||
│ └── ...
|
||||
└── eu/ # cross-EU regulations
|
||||
├── gdpr.py # GDPR + Schrems II + SCCs 2021
|
||||
├── ai_act.py # risk tier classification
|
||||
└── ...
|
||||
```
|
||||
|
||||
**Per-jurisdiction module template** (`packages/jurisdictions/pl/liability.py`):
|
||||
|
||||
```python
|
||||
"""Polish-specific liability clause rules.
|
||||
|
||||
Sources:
|
||||
- Kodeks cywilny (KC) art. 361 § 2, 473 § 2, 483-484
|
||||
- Reasoning: KC art. 484 § 2 allows court to reduce "rażąco wygórowana"
|
||||
contractual penalty; KC art. 473 § 2 prohibits exclusion of liability
|
||||
for gross negligence (cannot be waived).
|
||||
"""
|
||||
from packages.schemas.clauses.liability import LiabilityClause
|
||||
|
||||
MANDATORY_OBSERVATIONS = [
|
||||
"PL law (KC art. 473 § 2): liability for gross negligence cannot be excluded — verify carve-out present",
|
||||
"PL law (KC art. 484 § 2): courts may reduce contractual penalty if 'rażąco wygórowana' — strict cap not absolute",
|
||||
]
|
||||
|
||||
PROMPT_HINTS = """
|
||||
For PL jurisdiction contracts, additionally check:
|
||||
- Czy klauzula wyłącza odpowiedzialność za rażące niedbalstwo / winę umyślną? (jeśli tak — invalid under KC art. 473 § 2)
|
||||
- Czy kara umowna jest "rażąco wygórowana" (per KC art. 484 § 2) — flag for counsel review
|
||||
- Czy są odsetki za opóźnienie zgodne z UTP (ustawa o terminach zapłaty w transakcjach handlowych)?
|
||||
"""
|
||||
|
||||
def post_extraction_check(clause: LiabilityClause) -> LiabilityClause:
|
||||
"""Apply PL-specific validations after extraction."""
|
||||
if clause.found and "gross_negligence" not in clause.carve_outs:
|
||||
clause.key_observations.insert(0, MANDATORY_OBSERVATIONS[0])
|
||||
if clause.preliminary_status == "Approved":
|
||||
clause.preliminary_status = "Needs Attention"
|
||||
return clause
|
||||
```
|
||||
|
||||
**Usage w extraction agent:**
|
||||
|
||||
```python
|
||||
# packages/agents/clause_extractor.py
|
||||
from packages.jurisdictions import get_jurisdiction_module
|
||||
|
||||
async def extract_clause(text: str, clause_type: str, jurisdiction_code: str, tenant_id: str):
|
||||
base_prompt = load_prompt(f"clauses/{clause_type}_extraction_v3")
|
||||
jurisdiction = get_jurisdiction_module(jurisdiction_code, clause_type)
|
||||
|
||||
full_prompt = base_prompt + (jurisdiction.PROMPT_HINTS if jurisdiction else "")
|
||||
|
||||
agent = Agent(model="claude-sonnet-4-6", result_type=get_clause_schema(clause_type), system_prompt=full_prompt)
|
||||
result = await agent.run(text)
|
||||
|
||||
if jurisdiction and hasattr(jurisdiction, "post_extraction_check"):
|
||||
result.data = jurisdiction.post_extraction_check(result.data)
|
||||
|
||||
return result.data
|
||||
```
|
||||
|
||||
### 4. Prompt templates — versioned, code-first
|
||||
|
||||
**Convention:** `packages/prompts/clauses/{clause}_extraction_v{N}.py` jako Python module z **versioned constant** + few-shot examples + system prompt + Langfuse registration.
|
||||
|
||||
```python
|
||||
# packages/prompts/clauses/liability_extraction_v3.py
|
||||
|
||||
PROMPT_VERSION = "liability_v3"
|
||||
|
||||
SYSTEM_PROMPT = """You are an AI assistant supporting legal review. You extract
|
||||
liability clauses from commercial contracts. You DO NOT provide legal advice.
|
||||
|
||||
Task: From the contract text below, extract the liability clause (if present).
|
||||
Return structured JSON matching the LiabilityClause schema.
|
||||
|
||||
Rules:
|
||||
1. If multiple liability provisions exist (e.g., main clause + indemnification),
|
||||
focus on the primary cap/exclusion clause. Note related provisions in
|
||||
key_observations.
|
||||
2. confidence: 0.9+ = unambiguous text directly stating cap/exclusions;
|
||||
0.7-0.9 = inferable but requires interpretation;
|
||||
<0.7 = ambiguous, flag for human review.
|
||||
3. If clause not found, set found=false and return.
|
||||
4. source_location: use the contract's own structure (e.g. "Section 5.2",
|
||||
"Clause 12(a)", "Annex B"). NEVER invent section numbers.
|
||||
5. carve_outs: only list those EXPLICITLY excluded from the liability cap/exclusion.
|
||||
6. preliminary_status:
|
||||
- "Approved" — symmetric cap, reasonable carve-outs (gross negligence, IP,
|
||||
confidentiality), no obvious red flags
|
||||
- "Needs Attention" — missing carve-outs, asymmetric, cap below typical
|
||||
market (e.g. cap < 6mo fees for SaaS)
|
||||
- "Rejected" — unlimited liability accepted, no carve-outs for gross
|
||||
negligence, one-sided exclusion benefitting only vendor
|
||||
|
||||
ALWAYS include "REQUIRES LEGAL COUNSEL SIGN-OFF" in observations.
|
||||
NEVER assert that anything is legally enforceable or unenforceable.
|
||||
"""
|
||||
|
||||
FEW_SHOT_EXAMPLES = [
|
||||
{
|
||||
"input": "Section 8.1 Limitation of Liability. The total aggregate liability of either Party arising out of or in connection with this Agreement shall not exceed an amount equal to the fees paid by Client in the twelve (12) months preceding the event giving rise to liability. Neither Party shall be liable for indirect, consequential, or special damages. The foregoing limitations shall not apply to (a) breach of confidentiality, (b) indemnification obligations under Section 9, or (c) gross negligence or willful misconduct.",
|
||||
"output": {
|
||||
"found": True,
|
||||
"text": "...", # verbatim
|
||||
"source_location": "Section 8.1",
|
||||
"confidence": 0.95,
|
||||
"cap": {"amount": None, "currency": None, "scope": "aggregate", "multiplier_of_fees": 1.0},
|
||||
"excludes_indirect": True,
|
||||
"excludes_consequential": True,
|
||||
"excludes_lost_profits": False,
|
||||
"mutual": True,
|
||||
"carve_outs": ["confidentiality_breach", "ip_indemnity", "gross_negligence", "willful_misconduct"],
|
||||
"preliminary_status": "Approved",
|
||||
"key_observations": [
|
||||
"Mutual aggregate cap at 12 months fees — market standard for B2B SaaS",
|
||||
"Standard carve-outs present (confidentiality, IP, gross negligence)",
|
||||
"REQUIRES LEGAL COUNSEL SIGN-OFF"
|
||||
],
|
||||
"suggested_questions_for_counsel": [
|
||||
"Is 12-month cap appropriate given contract value and risk profile?",
|
||||
"Are carve-outs complete for client's industry (e.g. data breach for personal data processing)?"
|
||||
]
|
||||
}
|
||||
},
|
||||
# ... add 2-3 more examples covering edge cases (unlimited, asymmetric, missing carve-outs)
|
||||
]
|
||||
```
|
||||
|
||||
**Prompt registration w Langfuse** (Sprint 2+):
|
||||
|
||||
```python
|
||||
# packages/prompts/__init__.py
|
||||
from langfuse import Langfuse
|
||||
langfuse = Langfuse()
|
||||
|
||||
def register_prompt(version: str, system_prompt: str, examples: list):
|
||||
langfuse.create_prompt(
|
||||
name=version,
|
||||
prompt=system_prompt,
|
||||
config={"few_shot_examples": examples},
|
||||
tags=["clause_extraction", version.split("_")[0]],
|
||||
)
|
||||
|
||||
# On import / CI:
|
||||
register_prompt(PROMPT_VERSION, SYSTEM_PROMPT, FEW_SHOT_EXAMPLES)
|
||||
```
|
||||
|
||||
**Versioning rules:**
|
||||
|
||||
- **Bump version (`v3 → v4`)** dla: structural change w schema, significant prompt rewrite, model change z impact
|
||||
- **Same version, minor edit OK** dla: typo, clarification bez schema impact (but re-run eval anyway per M4)
|
||||
- **Old versions kept** w git — required dla reproducing past extractions
|
||||
- **Active version** wybierany w `packages/agents/clause_extractor.py` per clause type — easy A/B test (route 10% traffic do v4 vs 90% v3)
|
||||
|
||||
### 5. Confidence score conventions
|
||||
|
||||
**Threshold rules (consistent across wszystkich clause types):**
|
||||
|
||||
| Confidence | Treatment |
|
||||
|---|---|
|
||||
| `≥ 0.9` | Display directly w UI z green badge, no flag |
|
||||
| `0.7 - 0.9` | Display z yellow badge "AI confidence moderate, verify before accepting" |
|
||||
| `0.5 - 0.7` | Display z orange badge "Low confidence, human review required" |
|
||||
| `< 0.5` | **Hide from main UI**, surface w "Needs Review" queue, force human sign-off przed display do counsel |
|
||||
|
||||
**Implementation:**
|
||||
|
||||
```python
|
||||
# packages/core/confidence.py
|
||||
from enum import Enum
|
||||
|
||||
class ConfidenceLevel(str, Enum):
|
||||
HIGH = "high" # >= 0.9
|
||||
MODERATE = "moderate" # 0.7 - 0.9
|
||||
LOW = "low" # 0.5 - 0.7
|
||||
INSUFFICIENT = "insufficient" # < 0.5
|
||||
|
||||
def classify_confidence(score: float) -> ConfidenceLevel:
|
||||
if score >= 0.9: return ConfidenceLevel.HIGH
|
||||
if score >= 0.7: return ConfidenceLevel.MODERATE
|
||||
if score >= 0.5: return ConfidenceLevel.LOW
|
||||
return ConfidenceLevel.INSUFFICIENT
|
||||
```
|
||||
|
||||
**Per-clause-type override** (jeśli clause type wymaga wyższego bar — np. `dataPrivacy` ma regulatory exposure):
|
||||
|
||||
```python
|
||||
# packages/jurisdictions/eu/data_privacy.py
|
||||
MIN_CONFIDENCE_FOR_DISPLAY = 0.85 # higher bar dla DPA-relevant extractions
|
||||
```
|
||||
|
||||
### 6. Red flag patterns — delegated to legal-tech
|
||||
|
||||
Pełna tabela red flagów per clause type (unlimited liability / brak DPA / auto-renewal trap / indefinite confidentiality / etc.) jest w user-level `legal-tech` skill — fundament 4 "Risk scoring + red flags per clause type". **NIE duplikuj tutaj.**
|
||||
|
||||
**Co Compass dodaje na top:**
|
||||
|
||||
1. **Automated red flag detection w post-extraction** — w `packages/jurisdictions/{country}/{clause}.py:post_extraction_check()`
|
||||
2. **Severity tagging** — każdy red flag ma severity (`info`/`warning`/`critical`):
|
||||
```python
|
||||
class RedFlagFinding(BaseModel):
|
||||
code: str # e.g. "unlimited_liability", "missing_dpa", "auto_renewal_trap"
|
||||
severity: Literal["info", "warning", "critical"]
|
||||
message: str
|
||||
suggested_remediation: str
|
||||
```
|
||||
3. **UI surfacing** — critical findings blok contract status do "Needs Attention" automatycznie
|
||||
4. **Aggregation** — `Contract.risk_score` calculated as weighted sum of findings (weights from `packages/core/risk_scoring.py`)
|
||||
|
||||
### 7. Adding new clause type — workflow
|
||||
|
||||
**Trigger:** branża klienta wymaga clause type non w taxonomy (np. `forceMa
|
||||
jeure` jako standalone, `escrow`, `nonCompete`, `assignment`). **Wymaga ADR** + sync w 7 miejscach:
|
||||
|
||||
**Workflow (1 sprint, ~3-5 dni):**
|
||||
|
||||
1. **ADR** (`docs/architecture/ADR-NNN-add-clause-{name}.md`) — context, decision, alternatives (czy `other` wystarczy?), consequences
|
||||
2. **Pydantic schema** (`packages/schemas/clauses/{name}.py`) — fields + validators
|
||||
3. **Zod mirror** (`src/components/contract-form/clauses/{name}.ts`) lub regen
|
||||
4. **Update central enum** — `packages/schemas/clauses/__init__.py:CLAUSE_TYPES` + zod `keyClauses` w formSchema
|
||||
5. **Prompt template v1** (`packages/prompts/clauses/{name}_extraction_v1.py`) z 3-5 few-shot examples
|
||||
6. **Golden dataset** (`packages/evals/datasets/{name}_pl.jsonl` + `{name}_en.jsonl`) — **min 20 examples per jurisdiction**, mix of "found / not found / edge cases / red flags"
|
||||
7. **Eval test** (`packages/evals/tests/test_{name}_extraction.py`) z thresholds:
|
||||
```python
|
||||
@pytest.mark.eval
|
||||
async def test_name_extraction_pl_golden():
|
||||
results = await run_eval("name_extraction_v1", "name_pl")
|
||||
assert results.precision >= 0.85
|
||||
assert results.recall >= 0.80
|
||||
assert results.cost_per_doc <= 0.02 # USD
|
||||
```
|
||||
8. **Migration** (`supabase/migrations/{ts}_add_{name}_clause_type.sql`) — add enum value, no schema break
|
||||
9. **UI form field** — add do `ContractForm` w `clauseDisplayConfig`
|
||||
10. **Per-jurisdiction variants** (opcjonalnie initially — `packages/jurisdictions/pl/{name}.py` jeśli PL ma specifics)
|
||||
11. **Industry priority hint** — update tabela "Branżowy priority" w `legal-tech` skill jeśli relevant
|
||||
|
||||
**PR checklist** (template w `.github/pull_request_template.md`):
|
||||
|
||||
```
|
||||
Adding new clause type: <name>
|
||||
- [ ] ADR created (docs/architecture/ADR-NNN-...)
|
||||
- [ ] Pydantic schema (packages/schemas/clauses/...)
|
||||
- [ ] Zod mirror (apps/web/src/components/contract-form/clauses/...)
|
||||
- [ ] CLAUSE_TYPES enum updated
|
||||
- [ ] Prompt v1 (packages/prompts/clauses/...)
|
||||
- [ ] Golden dataset PL (20+) + EN (20+)
|
||||
- [ ] Eval test passing in CI
|
||||
- [ ] Migration (supabase/migrations/...)
|
||||
- [ ] UI form field
|
||||
- [ ] Per-jurisdiction variants (PL minimum if PL clients present)
|
||||
- [ ] Self-check 13 punktów ✓
|
||||
```
|
||||
|
||||
## Self-check — OBOWIĄZKOWO
|
||||
|
||||
**13 punktów** przed dodaniem/zmianą clause type lub extraction prompt. Wykonaj punkt po punkcie:
|
||||
|
||||
### Schema (1-3)
|
||||
|
||||
1. **Pydantic schema validated** — fields typed properly (Literal dla enums, Decimal dla money, confloat dla confidence)? validators dla cross-field consistency?
|
||||
2. **Zod mirror sync** — odpowiadający zod schema zaktualizowany w tym samym PR? CI sync test passing?
|
||||
3. **CLAUSE_TYPES enum** consistent — Python `packages/schemas/clauses/__init__.py` + TS `clauseDisplayConfig` + DB enum w migration?
|
||||
|
||||
### Prompt (4-6)
|
||||
|
||||
4. **Prompt versioned** — `{clause}_extraction_v{N}.py` z `PROMPT_VERSION` constant? bump version przy structural change?
|
||||
5. **Few-shot examples** — min 3 examples covering: standard case, edge case (np. missing), red flag case?
|
||||
6. **Disclaimer hardcoded** — system prompt ma "DO NOT provide legal advice" + "REQUIRES LEGAL COUNSEL SIGN-OFF" w output?
|
||||
|
||||
### Eval (7-9)
|
||||
|
||||
7. **Golden dataset** present — min 20 examples per jurisdiction (PL + EN baseline)? mix found/not-found/red-flag?
|
||||
8. **Eval test** w CI — precision/recall/cost thresholds explicit? blocks merge on regression?
|
||||
9. **Prompt change triggers eval** — czy CI hook na `packages/prompts/**` change uruchamia eval suite?
|
||||
|
||||
### Jurisdiction + confidence (10-11)
|
||||
|
||||
10. **Per-jurisdiction handling** — jeśli clause ma PL/EU specifics, czy `packages/jurisdictions/{country}/{clause}.py` istnieje z `post_extraction_check`?
|
||||
11. **Confidence threshold** — czy używasz default 0.9/0.7/0.5 czy override dla high-stakes clause (np. `dataPrivacy` 0.85+ minimum)?
|
||||
|
||||
### Cross-skill (12-13)
|
||||
|
||||
12. **legal-tech red flags** — czy red flag patterns z user-level `legal-tech` skill są reflected w `post_extraction_check`?
|
||||
13. **ADR-001 mandates** — czy zmiana przeszła [[compass-ai-native-mandates]] self-check 8 punktów (zwłaszcza M2 schema-first + M4 eval-driven + M8 Langfuse trace)?
|
||||
|
||||
**Dla każdej PR dotyczącej clause type / prompt** — VISIBLE confirmation w PR description:
|
||||
|
||||
```
|
||||
Clause taxonomy self-check:
|
||||
- Pydantic schema ✓ / Zod mirror ✓ / Enum sync ✓
|
||||
- Prompt versioned ✓ / Few-shot ✓ / Disclaimer ✓
|
||||
- Golden dataset PL+EN ✓ / Eval CI ✓ / Trigger hook ✓
|
||||
- Jurisdiction handling ✓ (or N/A) / Confidence threshold ✓
|
||||
- Legal-tech red flags ✓ / ADR-001 mandates ✓
|
||||
```
|
||||
|
||||
## Mini-przykłady
|
||||
|
||||
### Przykład 1: Adding `forceMaj
|
||||
eure` clause type (faza Sprint 5)
|
||||
|
||||
User feedback: SOW haski.io dla budowlanki ma istotne force majeure provisions (COVID/wojna/strikes), `other` catch-all nie wystarcza dla risk scoring.
|
||||
|
||||
1. ADR-007 — decision: standalone clause type
|
||||
2. `packages/schemas/clauses/force_majeure.py`:
|
||||
```python
|
||||
class ForceMajeureClause(ClauseBase):
|
||||
found: bool
|
||||
events_covered: list[str] # e.g. ["war", "pandemic", "natural_disaster", "strikes"]
|
||||
notice_required_days: int | None
|
||||
performance_suspension: bool # czy zawiesza obowiązki
|
||||
termination_right_after_days: int | None # right do termination jeśli FM trwa > N dni
|
||||
preliminary_status: Literal["Approved", "Needs Attention", "Rejected"]
|
||||
```
|
||||
3. Zod mirror + enum update
|
||||
4. Prompt `force_majeure_extraction_v1` z 5 few-shot (covering: standard COVID-era boilerplate, narrow scope, broad scope, missing entirely, asymmetric (only vendor benefits))
|
||||
5. Golden dataset 20 PL contracts (budowlanka + logistyka focus)
|
||||
6. Eval threshold: precision 0.85, recall 0.80
|
||||
7. Migration `ALTER TYPE clause_type_enum ADD VALUE 'forceMaj
|
||||
eure'`
|
||||
8. UI form field
|
||||
|
||||
### Przykład 2: bumping prompt version z eval regression
|
||||
|
||||
Zmiana w `liability_extraction_v3 → v4` dodaje better handling dla mutual asymmetry detection.
|
||||
|
||||
```python
|
||||
# Eval results CI:
|
||||
# v3: precision 0.91, recall 0.86, cost 0.018
|
||||
# v4: precision 0.93, recall 0.85, cost 0.022
|
||||
|
||||
# Test fails because recall regression 0.86 → 0.85
|
||||
# CI blocks merge.
|
||||
|
||||
# Fix: improve few-shot examples for cases where asymmetry detection
|
||||
# dropped recall, re-run eval, threshold met → merge
|
||||
```
|
||||
|
||||
### Przykład 3: PL-specific post-extraction check
|
||||
|
||||
```python
|
||||
# packages/jurisdictions/pl/data_privacy.py
|
||||
from packages.schemas.clauses.data_privacy import DataPrivacyClause
|
||||
|
||||
def post_extraction_check(clause: DataPrivacyClause) -> DataPrivacyClause:
|
||||
if clause.found and not clause.dpa_attached:
|
||||
clause.preliminary_status = "Rejected"
|
||||
clause.key_observations.insert(0,
|
||||
"PL/EU RODO violation in itself: no DPA for personal data processing. "
|
||||
"Cannot proceed without DPA attached or executed separately.")
|
||||
if clause.found and clause.data_transfer_outside_eea and not clause.sccs_present:
|
||||
clause.preliminary_status = "Rejected"
|
||||
clause.key_observations.insert(0,
|
||||
"Schrems II: transfer outside EEA without SCCs 2021 + TIA is RODO violation.")
|
||||
return clause
|
||||
```
|
||||
|
||||
## Cross-references
|
||||
|
||||
- **legal-tech** (user-level) — pełna domain knowledge: anatomy, red flag library per clause type, GDPR/RODO checklist, multi-jurisdiction baseline, AI Act risk tiers. **TEN skill = technical implementation**, legal-tech = domain.
|
||||
- [[compass-ai-native-mandates]] — M2 schema-first, M4 eval-driven, M6 cache-aware (prompt caching), M8 Langfuse observability
|
||||
- [[compass-architecture]] — RLS na `clauses` table, `tenant_id` propagation w extraction agent
|
||||
- **rag-pipeline-builder** (user-level) — eval infrastructure (RAGAS, hit rate, MRR), retrieval dla long contracts (Compass > 200k context)
|
||||
- **pisanie-pl** (user-level) — gdy clause text destined for client report w PL (descriptions, key_observations)
|
||||
|
||||
## Zasada główna
|
||||
|
||||
**Schema-first + eval-driven + versioned everything.** Każda extraction = Pydantic input/output, każdy prompt versioned + golden dataset + eval w CI, każda zmiana taxonomy = ADR + 7-step workflow. **Domain knowledge zostaje w `legal-tech` skill** (red flags, jurisdiction rules, AI Act) — TEN skill mówi jak zaprogramować technicznie żeby legal logic was correctly applied. AI extraction NIGDY nie zastępuje human counsel review — `requires_counsel_review=True` hardcoded w base schema.
|
||||
@@ -0,0 +1,48 @@
|
||||
# Compass — env template. Copy to .env.local and populate.
|
||||
# NEVER commit .env.local — see CLAUDE.md security invariant #9.
|
||||
|
||||
# ---------- LLM providers ----------
|
||||
ANTHROPIC_API_KEY=sk-ant-...
|
||||
VOYAGE_API_KEY=pa-...
|
||||
GEMINI_API_KEY=AIza...
|
||||
# Optional: OPENAI_API_KEY=sk-... (only if multi-provider fallback chain enabled)
|
||||
|
||||
# ---------- Supabase (auth + DB + storage) ----------
|
||||
SUPABASE_URL=https://<project-ref>.supabase.co
|
||||
SUPABASE_ANON_KEY=eyJ...
|
||||
# Service role: ADMIN operations only, never used in business-logic handlers
|
||||
# (see CLAUDE.md security invariant #1)
|
||||
SUPABASE_SERVICE_ROLE_KEY=eyJ...
|
||||
|
||||
# ---------- Database (direct connection for migrations + Celery beat schedules) ----------
|
||||
DATABASE_URL=postgresql://postgres:<password>@db.<project-ref>.supabase.co:5432/postgres
|
||||
|
||||
# ---------- Redis (Celery broker + SSE pub/sub) ----------
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
# ---------- Qdrant (vector store, multi-tenant payload filtering) ----------
|
||||
QDRANT_URL=http://localhost:6333
|
||||
QDRANT_API_KEY=
|
||||
|
||||
# ---------- Langfuse (LLM observability, per ADR-001 M8) ----------
|
||||
LANGFUSE_PUBLIC_KEY=pk-lf-...
|
||||
LANGFUSE_SECRET_KEY=sk-lf-...
|
||||
LANGFUSE_HOST=http://localhost:3001
|
||||
# Set to "false" in pytest unit tests to disable Langfuse roundtrip
|
||||
LANGFUSE_ENABLED=true
|
||||
|
||||
# ---------- FastAPI app ----------
|
||||
APP_ENV=development # development | staging | production
|
||||
APP_LOG_LEVEL=INFO
|
||||
APP_PORT=8000
|
||||
APP_CORS_ORIGINS=http://localhost:8080
|
||||
|
||||
# ---------- Frontend (apps/web — Vite exposes only VITE_*) ----------
|
||||
VITE_SUPABASE_URL=https://<project-ref>.supabase.co
|
||||
VITE_SUPABASE_ANON_KEY=eyJ...
|
||||
VITE_API_BASE_URL=http://localhost:8000
|
||||
|
||||
# ---------- Optional, Sprint 3+ ----------
|
||||
# AUTHENTIK_URL= # self-hosted SSO (replaces Supabase Auth pre enterprise)
|
||||
# HETZNER_STORAGE_BOX_ACCESS_KEY= # S3-compatible file storage on self-hosted phase
|
||||
# HETZNER_STORAGE_BOX_SECRET=
|
||||
+82
-9
@@ -1,5 +1,14 @@
|
||||
# Logs
|
||||
logs
|
||||
# --- Node / web ---
|
||||
node_modules/
|
||||
dist/
|
||||
dist-ssr/
|
||||
*.local
|
||||
.vite/
|
||||
.eslintcache
|
||||
.tsbuildinfo
|
||||
|
||||
# --- Logs ---
|
||||
logs/
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
@@ -7,18 +16,82 @@ yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
# --- Python ---
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.egg-info/
|
||||
*.egg
|
||||
.eggs/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
.coverage
|
||||
.coverage.*
|
||||
htmlcov/
|
||||
.tox/
|
||||
.nox/
|
||||
|
||||
# Editor directories and files
|
||||
# uv
|
||||
.venv/
|
||||
.venv.*
|
||||
.uv/
|
||||
uv.lock
|
||||
|
||||
# --- Env / secrets ---
|
||||
.env
|
||||
.env.local
|
||||
.env.*.local
|
||||
.env.development
|
||||
.env.staging
|
||||
.env.production
|
||||
*.pem
|
||||
*.key
|
||||
*.pfx
|
||||
*.p12
|
||||
credentials.json
|
||||
service-account.json
|
||||
service_account.json
|
||||
secrets.yml
|
||||
secrets.yaml
|
||||
|
||||
# --- Supabase local state ---
|
||||
supabase/.branches/
|
||||
supabase/.temp/
|
||||
supabase/seed.local.sql
|
||||
|
||||
# --- Docker volumes ---
|
||||
.docker-volumes/
|
||||
docker-data/
|
||||
|
||||
# --- Eval outputs (regenerated each run) ---
|
||||
packages/evals/results/*.json
|
||||
packages/evals/results/*.jsonl
|
||||
!packages/evals/results/.gitkeep
|
||||
|
||||
# --- IDE / editor ---
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
!.vscode/settings.recommended.json
|
||||
.idea/
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
.DS_Store
|
||||
|
||||
# --- OS junk ---
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
Desktop.ini
|
||||
|
||||
# --- Compass-specific ---
|
||||
# Per-tenant cost reports cached locally before Langfuse upload
|
||||
.cost-reports/
|
||||
# Local agent traces (Langfuse fallback when service unavailable)
|
||||
.langfuse-offline/
|
||||
# Hetzner deploy state (Ansible / Terraform — Sprint 4+)
|
||||
deploy/.state/
|
||||
deploy/*.tfstate
|
||||
deploy/*.tfstate.backup
|
||||
|
||||
@@ -0,0 +1,423 @@
|
||||
# AGENTS.md — compass-contract-hub
|
||||
|
||||
Multi-agent topology dla Compass. Definiuje 8 specialized subagentów (+ 1 placeholder dla Sprint 5) used przez Claude Code w tym repo. **Każdy subagent ma single clear responsibility**, properly scoped tools (least-privilege), and explicit routing rules.
|
||||
|
||||
Subagent definition files: `.claude/agents/<name>.md` (do utworzenia w Sprint 1, ten dokument to spec — kontrakt).
|
||||
|
||||
**Domain context:** patrz `CLAUDE.md` (Compass overview, 5 moats, stack), `docs/architecture/ADR-001-ai-native.md` (8 AI-native mandates).
|
||||
|
||||
## Routing logic — który subagent dla której operacji
|
||||
|
||||
| User intent / task | Primary subagent | Parallel co-agents | Reason |
|
||||
|---|---|---|---|
|
||||
| "Extract clauses from this contract" | `compass-clause-extractor` | `compass-doc-parser` (sequential first) | E2E extraction pipeline |
|
||||
| "Review this liability clause" (post-extraction) | `compass-clause-reviewer` | `compass-jurisdiction-checker` | High-accuracy review + jurisdiction validation |
|
||||
| "Add new clause type force-majeure" | (main thread orchestrates) | `compass-prompt-tester` (eval), `compass-test-writer` (tests) | Multi-step adding-clause workflow |
|
||||
| "I'm changing prompt liability_v3 → v4" | `compass-prompt-tester` | — | Eval gate przed merge |
|
||||
| "PR review przed merge" | `compass-pr-reviewer` | `compass-rls-auditor` (jeśli migrations), `compass-prompt-tester` (jeśli prompts changed) | Pre-merge gate |
|
||||
| "Add new table contracts_attachments" | `compass-rls-auditor` | `compass-test-writer` | Migration + RLS audit |
|
||||
| "Write integration test dla new endpoint" | `compass-test-writer` | — | Test scaffolding |
|
||||
| "Parse this scanned PDF" | `compass-doc-parser` | — | Doc ingestion |
|
||||
|
||||
**Default behavior** (gdy intent unclear): main Claude thread asks user OR consults `compass-pr-reviewer` jako "second opinion" agent.
|
||||
|
||||
## Cost attribution — universal rule
|
||||
|
||||
**Każde wywołanie LLM przez subagent MUSI mieć w metadata:**
|
||||
|
||||
```python
|
||||
{
|
||||
"tenant_id": str(tenant_id),
|
||||
"operation": "<descriptive verb>", # e.g. "extract_liability", "review_dpa"
|
||||
"subagent": "<name>", # e.g. "compass-clause-extractor"
|
||||
"trace_id": str(parent_trace_id), # link do parent operation
|
||||
"contract_id": str(contract_id), # jeśli applicable
|
||||
}
|
||||
```
|
||||
|
||||
Enforced przez `packages/llm-gateway/router.py` — calls bez `tenant_id` + `operation` are rejected at gateway level.
|
||||
|
||||
## Error handling — universal patterns
|
||||
|
||||
### Retry semantics
|
||||
|
||||
| Error type | Retry policy |
|
||||
|---|---|
|
||||
| Transient LLM error (rate limit, 503) | Exponential backoff, max 3 retries via Celery `autoretry_for=(LLMTransientError,)` |
|
||||
| Schema validation fail (Pydantic) | Retry 3× z LLM (per PydanticAI default), then surface jako `extraction_quality_low` event |
|
||||
| Doc parse fail (corrupted PDF) | No retry — surface error to user with "Try re-uploading or convert to DOCX" |
|
||||
| RLS violation | No retry — bug, alert immediately, halt task |
|
||||
| Cost budget exceeded (per-tenant) | No retry — surface "Cost cap reached, contact admin" |
|
||||
|
||||
### Fallback chain
|
||||
|
||||
Per ADR-001 M5 — multi-model routing implies graceful fallback:
|
||||
|
||||
```
|
||||
Sonnet 4.6 (primary)
|
||||
→ Opus 4.7 (jeśli schema fail po 3 retries)
|
||||
→ Gemini 2.5 Pro (jeśli Anthropic-wide outage detected via LiteLLM)
|
||||
→ Dead letter queue (preserve task w `failed_extractions` table dla manual review)
|
||||
```
|
||||
|
||||
Implementuje `packages/llm-gateway/router.py:complete_with_fallback()`.
|
||||
|
||||
### Dead letter queue
|
||||
|
||||
Failed extractions trafiają do `failed_extractions` table z:
|
||||
|
||||
```python
|
||||
{
|
||||
"task_id": str,
|
||||
"contract_id": str,
|
||||
"tenant_id": str,
|
||||
"error_chain": [<error per attempt>],
|
||||
"last_attempt_at": datetime,
|
||||
"needs_manual_review": True,
|
||||
}
|
||||
```
|
||||
|
||||
Operator-facing UI w `apps/web/src/pages/Admin.tsx` surfaces queue dla retry/abandon decisions.
|
||||
|
||||
### Eval gate — które invocations require passing eval
|
||||
|
||||
Per ADR-001 M4:
|
||||
|
||||
| Subagent | Eval gate before return? |
|
||||
|---|---|
|
||||
| `compass-clause-extractor` | **YES** — confidence < 0.5 → flag `needs_review`, NIE return jako extracted |
|
||||
| `compass-clause-reviewer` | **YES** — wymaga matching golden review dataset 20+ per clause type |
|
||||
| `compass-jurisdiction-checker` | **YES** — per-country eval threshold (precision ≥ 0.85) |
|
||||
| `compass-prompt-tester` | itself IS the eval gate |
|
||||
| `compass-doc-parser` | NO — deterministic processing, no LLM (or minimal) |
|
||||
| `compass-rls-auditor` | NO — rule-based static analysis |
|
||||
| `compass-test-writer` | NO — code generation, manual review pre-commit |
|
||||
| `compass-pr-reviewer` | NO — synthesizes other agents' results |
|
||||
|
||||
## Agent specs
|
||||
|
||||
### 1. compass-clause-extractor
|
||||
|
||||
**Purpose:** Extract single clause type z contract text using PydanticAI agent + clause-specific prompt + jurisdiction overlay. Core extraction workhorse.
|
||||
|
||||
**Model:** `claude-sonnet-4-6` (per ADR-001 M5 default for extraction). Fallback: Opus 4.7 → Gemini 2.5 Pro.
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (clause schema, prompt templates, jurisdiction modules)
|
||||
- Bash/PowerShell (run eval test post-extraction jeśli confidence low — optional)
|
||||
- LLM gateway (`packages/llm-gateway`)
|
||||
- Langfuse trace API
|
||||
- Postgres write (`clauses` table) — through `packages/core/db` z tenant context
|
||||
|
||||
**Tools disallowed:**
|
||||
- Direct Supabase service_role access
|
||||
- Cross-tenant queries
|
||||
- Network calls outside LLM gateway + Langfuse + DB
|
||||
- File write outside `clauses/` ingestion log
|
||||
|
||||
**Parallelizable:** YES — multiple clause types per contract can run in parallel (14 clauses × 1 agent each, bounded by per-tenant cost budget). Use `asyncio.gather()` w Celery orchestration task.
|
||||
|
||||
**Invocation conditions:**
|
||||
- New contract uploaded → orchestrator task triggers 14× `compass-clause-extractor` w parallel (per ADR-001 M7)
|
||||
- User clicks "Re-extract" w UI → single contract re-run
|
||||
- Prompt version bumped + backfill triggered → admin operation, all-contracts re-extract
|
||||
|
||||
**Pre-conditions:**
|
||||
- Contract text parsed by `compass-doc-parser` (sequential dependency)
|
||||
- `jurisdiction_code` resolved
|
||||
- `tenant_id` propagated
|
||||
|
||||
**Post-conditions:**
|
||||
- `clauses` row inserted z `tenant_id` + `confidence` + `prompt_version`
|
||||
- SSE event `clause_extracted` published (per ADR-001 M3)
|
||||
- Langfuse trace closed z usage (input/output tokens, cost, latency)
|
||||
- If confidence < 0.5 → also row w `clauses_needing_review`
|
||||
|
||||
**Skills invoked internally:** `compass-clause-taxonomy` (Pydantic schema + prompt loading), `compass-ai-native-mandates` (compliance check)
|
||||
|
||||
### 2. compass-clause-reviewer
|
||||
|
||||
**Purpose:** Post-extraction review — assign status (Approved/Needs Attention/Rejected), generate key_observations, suggested_questions_for_counsel. Higher-accuracy than extractor (Opus model).
|
||||
|
||||
**Model:** `claude-opus-4-7` (per ADR-001 M5 "compliance review (critical) → Opus 4.7"). High accuracy needed; cost OK because called less frequently (only on extracted clauses, not all contract text).
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (clause text from DB, jurisdiction rules, red flag library from legal-tech skill)
|
||||
- LLM gateway
|
||||
- Langfuse trace API
|
||||
- Postgres update (`clauses.review_*` fields)
|
||||
|
||||
**Tools disallowed:** same as extractor
|
||||
|
||||
**Parallelizable:** YES — per-clause reviews independent, bounded by Opus rate limits + per-tenant cost budget.
|
||||
|
||||
**Invocation conditions:**
|
||||
- After `compass-clause-extractor` returns clause z confidence ≥ 0.5
|
||||
- User clicks "AI Review" button per clause w UI
|
||||
- Bulk review job dla istniejących extracted clauses
|
||||
|
||||
**Pre-conditions:** clause extracted, jurisdiction resolved
|
||||
**Post-conditions:** clause row updated z `preliminary_status` + `key_observations` + `suggested_questions_for_counsel`, "REQUIRES LEGAL COUNSEL SIGN-OFF" always present w observations
|
||||
|
||||
**Skills invoked:** `legal-tech` (red flag library per clause type), `compass-clause-taxonomy` (review prompt templates)
|
||||
|
||||
### 3. compass-jurisdiction-checker
|
||||
|
||||
**Purpose:** Validate extracted clause against per-jurisdiction rules (`packages/jurisdictions/{country}/{clause}.py`). E.g. dla PL: KC art. 473 § 2 (mandatory liability for gross negligence), UTP Net 60 days max.
|
||||
|
||||
**Model:** `claude-sonnet-4-6` — accuracy OK z properly engineered prompt + jurisdiction rules retrieved as context.
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (jurisdiction modules, retrieved local statutory references)
|
||||
- `packages/retrieval` (RAG over jurisdiction-specific legal corpus jeśli available)
|
||||
- LLM gateway
|
||||
- Langfuse trace API
|
||||
- Postgres update (`clauses.jurisdiction_findings` JSON column)
|
||||
|
||||
**Tools disallowed:** same as extractor
|
||||
|
||||
**Parallelizable:** YES — independent per clause + per jurisdiction.
|
||||
|
||||
**Invocation conditions:**
|
||||
- After extractor + reviewer, before final UI display
|
||||
- Contract crosses multiple jurisdictions (governing_law ≠ tenant_default) → run dla każdej relevant jurisdiction
|
||||
- Re-run on jurisdiction module update (`packages/jurisdictions/{country}/*.py` change)
|
||||
|
||||
**Pre-conditions:** clause extracted, `governing_law_code` resolved
|
||||
**Post-conditions:** `jurisdiction_findings` populated z severity-tagged findings (info/warning/critical)
|
||||
|
||||
**Skills invoked:** `legal-tech` (multi-jurisdiction baseline), `compass-clause-taxonomy` (jurisdiction module access)
|
||||
|
||||
### 4. compass-prompt-tester
|
||||
|
||||
**Purpose:** Run eval suite for prompt version. Calculate precision/recall/F1/cost/confidence_calibration per clause type per jurisdiction against golden dataset. Block merge if regression.
|
||||
|
||||
**Model:** `claude-haiku-4-5-20251001` — eval runs są high-volume, Haiku tańszy + szybszy + sufficient dla eval orchestration. Faktyczne extraction LLM calls w eval używają target prompt's model (Sonnet/Opus).
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (golden datasets `packages/evals/datasets/*.jsonl`, prompts, test files)
|
||||
- Bash/PowerShell (`pytest -m eval`)
|
||||
- `packages/evals/runner` (custom eval framework)
|
||||
- LLM gateway (via prompt under test)
|
||||
- Langfuse trace API
|
||||
- Write (eval results to `packages/evals/results/<timestamp>_<prompt>_<jurisdiction>.json`)
|
||||
|
||||
**Tools disallowed:**
|
||||
- Network calls outside LLM gateway + Langfuse
|
||||
- Modification of golden datasets (read-only — datasets curated manually)
|
||||
- DB write outside results
|
||||
|
||||
**Parallelizable:** YES across prompt × jurisdiction × dataset combinations.
|
||||
|
||||
**Invocation conditions:**
|
||||
- CI trigger on `packages/prompts/**` PR change
|
||||
- Manual run via `pytest packages/evals/tests/test_<clause>_extraction.py -m eval`
|
||||
- Pre-merge hook via `compass-pr-reviewer`
|
||||
- Periodic regression check (nightly, prod prompts vs current golden)
|
||||
|
||||
**Pre-conditions:** prompt versioned, golden dataset present (min 20 PL + 20 EN), test file w `packages/evals/tests/`
|
||||
**Post-conditions:** eval results written, CI gate green/red, Langfuse experiment recorded
|
||||
|
||||
**Skills invoked:** `rag-pipeline-builder` (RAGAS metrics, evaluation framework), `compass-ai-native-mandates` (M4 enforcement)
|
||||
|
||||
### 5. compass-doc-parser
|
||||
|
||||
**Purpose:** Convert uploaded document (PDF/DOCX/scan) → structured text + metadata. OCR fallback for scans. Section detection (Section X.Y headers).
|
||||
|
||||
**Model:** zazwyczaj **brak LLM** — używa `unstructured.io` + `PyMuPDF` + `Marker` + Tesseract OCR. Opcjonalnie LLM dla section labeling jeśli structure ambiguous (`claude-haiku-4-5-20251001` dla cost).
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (uploaded file z Supabase Storage)
|
||||
- `packages/ingestion` (PDF/DOCX/OCR pipeline)
|
||||
- Postgres update (`contracts.parsed_text`, `contracts.parsing_metadata`)
|
||||
- LLM gateway (only dla section labeling fallback)
|
||||
|
||||
**Tools disallowed:**
|
||||
- Network calls outside Supabase Storage + LLM gateway
|
||||
- DB write outside parsing metadata
|
||||
|
||||
**Parallelizable:** NO (sequential per contract — single PDF parse is CPU-bound). Multiple contracts can parse concurrently jako separate Celery tasks.
|
||||
|
||||
**Invocation conditions:**
|
||||
- New contract file uploaded → first step in extraction pipeline
|
||||
- Re-parse triggered (e.g., after OCR engine upgrade)
|
||||
|
||||
**Pre-conditions:** file w Supabase Storage z `<tenant_id>/` prefix, `tenant_id` propagated
|
||||
**Post-conditions:** `contracts.parsed_text` populated, `parsing_metadata` z page count + scan_detected + parsing_method, SSE event `phase: parsed`
|
||||
|
||||
**Skills invoked:** none (deterministic pipeline). Optional: minimal LLM dla section labeling tylko if structure detection fails.
|
||||
|
||||
### 6. compass-rls-auditor
|
||||
|
||||
**Purpose:** Pre-merge audit migrations + new endpoints for RLS compliance. Static analysis: każda nowa tabela z `tenant_id` ma RLS enabled? każdy nowy endpoint nie bypasses RLS przez `service_role`? Storage uploads have `<tenant_id>/` prefix?
|
||||
|
||||
**Model:** `claude-opus-4-7` — high accuracy needed dla security critical analysis. Cost OK because runs only on PR review (low frequency).
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (migration SQL files, endpoint code, Storage policies)
|
||||
- Grep (search for `service_role`, `bypassRLS`, raw SQL bez tenant filter, hardcoded UUIDs)
|
||||
- Bash/PowerShell (run integration test cross-tenant isolation)
|
||||
- Write (audit report `docs/audits/rls-audit-<pr-number>.md`)
|
||||
|
||||
**Tools disallowed:**
|
||||
- DB write (read-only analysis)
|
||||
- Direct code modification (only flags issues, doesn't fix)
|
||||
- Network calls
|
||||
|
||||
**Parallelizable:** NO (sequential per PR — audit is holistic across changeset).
|
||||
|
||||
**Invocation conditions:**
|
||||
- CI trigger on PR z changes do `supabase/migrations/**` lub `apps/api/routes/**`
|
||||
- Manual invocation przez `compass-pr-reviewer` jako critical sub-check
|
||||
- Quarterly scheduled audit (all-routes, all-migrations sweep)
|
||||
|
||||
**Pre-conditions:** PR diff available
|
||||
**Post-conditions:** audit report z findings (severity: info/warning/critical), critical findings block merge, integration test `test_tenant_isolation.py` cross-references findings
|
||||
|
||||
**Skills invoked:** `compass-architecture` (RLS invariants), `compass-ai-native-mandates` (M5 cost-aware = `tenant_id` everywhere)
|
||||
|
||||
### 7. compass-test-writer
|
||||
|
||||
**Purpose:** Generate pytest (Python) + vitest (TS) test scaffolding for new endpoints, agents, schemas. Cover happy path + error path + RLS isolation test.
|
||||
|
||||
**Model:** `claude-sonnet-4-6` — code generation needs decent reasoning, but not Opus-tier. Test generation is medium complexity.
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (target code, existing test patterns, schemas)
|
||||
- Write (test files w `tests/` dir)
|
||||
- Bash/PowerShell (run generated tests to verify they execute — green or fail)
|
||||
- Grep (find similar test patterns dla style consistency)
|
||||
|
||||
**Tools disallowed:**
|
||||
- Modification of target code (only writes tests)
|
||||
- Network calls
|
||||
- DB writes
|
||||
|
||||
**Parallelizable:** YES — multiple test files independent.
|
||||
|
||||
**Invocation conditions:**
|
||||
- New endpoint added → generate integration test
|
||||
- New Pydantic schema → generate validation test
|
||||
- New agent → generate eval test scaffold (handed off to `compass-prompt-tester` for actual eval)
|
||||
- User: "write tests for X"
|
||||
|
||||
**Pre-conditions:** target code committed, schemas defined
|
||||
**Post-conditions:** test files created, tests execute (green or expected-fail), VISIBLE summary "Generated N tests, M passing, K failing (expected for unimplemented features)"
|
||||
|
||||
**Skills invoked:** `compass-architecture` (multi-tenant test patterns), `compass-clause-taxonomy` (clause-specific test fixtures)
|
||||
|
||||
### 8. compass-pr-reviewer
|
||||
|
||||
**Purpose:** Pre-merge gate. Orchestrates other subagents (`compass-prompt-tester`, `compass-rls-auditor`) and synthesizes findings. Checks ADR-001 8 mandates self-check VISIBLE w PR description. Block merge bez full pass.
|
||||
|
||||
**Model:** `claude-opus-4-7` — synthesis + judgment needed dla nuanced reviews. Cost OK because runs once per PR.
|
||||
|
||||
**Tools allowed:**
|
||||
- Read (PR diff, code, ADRs, existing skills/agents)
|
||||
- Bash/PowerShell (`gh pr view`, `gh pr diff`, run subagents)
|
||||
- Write (review comments via `gh pr comment`)
|
||||
- Subagent dispatch (`compass-prompt-tester`, `compass-rls-auditor`)
|
||||
|
||||
**Tools disallowed:**
|
||||
- Direct code modification (only flags + comments)
|
||||
- Force merge
|
||||
|
||||
**Parallelizable:** NO (sequential per PR — holistic review).
|
||||
|
||||
**Invocation conditions:**
|
||||
- PR opened w private repo (auto-trigger via GitHub Action)
|
||||
- Manual: `claude --agent compass-pr-reviewer --pr <number>`
|
||||
- Re-run after PR update
|
||||
|
||||
**Pre-conditions:** PR has commits, CI ran
|
||||
**Post-conditions:** review comment posted z VISIBLE checklist:
|
||||
|
||||
```
|
||||
## Compass PR Review
|
||||
|
||||
### Mandates (compass-ai-native-mandates 8-pkt)
|
||||
- [ ] M1 Agent-first
|
||||
- [ ] M2 Schema-first
|
||||
- [ ] M3 Streaming
|
||||
- [ ] M4 Eval-driven
|
||||
- [ ] M5 Cost-aware
|
||||
- [ ] M6 Cache-aware
|
||||
- [ ] M7 Async-first
|
||||
- [ ] M8 Observable
|
||||
|
||||
### Architecture (compass-architecture 12-pkt) — if architectural change
|
||||
- [ ] Boundary respected
|
||||
- [ ] RLS day 1
|
||||
- [ ] tenant_id propagation
|
||||
- ... (full list)
|
||||
|
||||
### Clause taxonomy (compass-clause-taxonomy 13-pkt) — if prompt/schema change
|
||||
- [ ] Pydantic schema validated
|
||||
- [ ] Zod mirror sync
|
||||
- ... (full list)
|
||||
|
||||
### Cross-cutting
|
||||
- [ ] Tests added (compass-test-writer ran)
|
||||
- [ ] Eval green (compass-prompt-tester ran) — if prompts changed
|
||||
- [ ] RLS audit clean (compass-rls-auditor ran) — if migrations/endpoints
|
||||
- [ ] Legal disclaimer present in user-facing outputs
|
||||
|
||||
**Verdict:** APPROVED / CHANGES_REQUESTED / BLOCKED
|
||||
```
|
||||
|
||||
**Skills invoked:** all `compass-*` skills + `legal-tech` (disclaimer check)
|
||||
|
||||
### 9. compass-cost-analyzer (Sprint 5+, placeholder)
|
||||
|
||||
**Purpose:** Periodic per-tenant cost analysis z Langfuse data. Generate reports: cost per tenant per month, cost per operation type, cache hit rate, model distribution. Alert na anomalies.
|
||||
|
||||
**Model:** `claude-haiku-4-5-20251001` — high-volume queries, simple aggregation.
|
||||
|
||||
**Status:** **Sprint 5+ feature**. Skip dla Sprint 0-4. Mentioned tutaj dla planning visibility.
|
||||
|
||||
**Skills invoked:** `compass-ai-native-mandates` (M5 cost tracking discipline)
|
||||
|
||||
## Initialization order — Sprint 1 implementation
|
||||
|
||||
Po Sprint 0 sign-off, w Sprint 1 tworzymy `.claude/agents/<name>.md` files w tej kolejności (dependencies):
|
||||
|
||||
1. `compass-doc-parser` — no deps, ingestion foundation
|
||||
2. `compass-clause-extractor` — deps na doc-parser
|
||||
3. `compass-clause-reviewer` — deps na extractor
|
||||
4. `compass-jurisdiction-checker` — deps na extractor
|
||||
5. `compass-rls-auditor` — independent, infra security
|
||||
6. `compass-test-writer` — independent, dev productivity
|
||||
7. `compass-prompt-tester` — deps na first prompt (Sprint 2)
|
||||
8. `compass-pr-reviewer` — last (synthesizes 1-7)
|
||||
9. `compass-cost-analyzer` — Sprint 5+
|
||||
|
||||
## Frontmatter template dla `.claude/agents/<name>.md`
|
||||
|
||||
```yaml
|
||||
---
|
||||
name: <name>
|
||||
description: <Use when ... (full description, third-person literal triggers)>
|
||||
tools: [Read, Write, Bash, Grep, ...] # explicit allowlist
|
||||
disallowedTools: [WebFetch, ...] # explicit denylist
|
||||
model: claude-sonnet-4-6 | claude-opus-4-7 | claude-haiku-4-5-20251001
|
||||
effort: low | medium | high
|
||||
skills: [legal-tech, compass-clause-taxonomy, ...] # pre-loaded skills
|
||||
maxTurns: 10
|
||||
permissionMode: acceptEdits
|
||||
---
|
||||
```
|
||||
|
||||
Body: focused expert persona w drugiej osobie, mandatory `When to invoke` H2 section z 2-4 prose scenarios.
|
||||
|
||||
## Cross-references
|
||||
|
||||
- `CLAUDE.md` — project identity, stack, skill priority order
|
||||
- `docs/architecture/ADR-001-ai-native.md` — 8 mandates baseline
|
||||
- `.claude/skills/compass-architecture/SKILL.md` — system architecture
|
||||
- `.claude/skills/compass-clause-taxonomy/SKILL.md` — clause domain implementation
|
||||
- `.claude/skills/compass-ai-native-mandates/SKILL.md` — mandates enforcement (used by `compass-pr-reviewer`)
|
||||
- User-level skills referenced: `legal-tech`, `rag-pipeline-builder`, `mcp-server-builder`, `cloud-deploy`, `frontend-web-ui`, `pisanie-pl`, `tworzenie-agentow` (meta-skill dla `.claude/agents/*.md` creation Sprint 1)
|
||||
|
||||
## Zasada główna
|
||||
|
||||
**Single responsibility + least privilege + cost attribution.** Każdy subagent ma jeden clear job, properly scoped tools (no over-privileged general-purpose), `tenant_id` w każdym LLM call metadata. **`compass-pr-reviewer` = synthesis gate** — żadna PR nie merge'uje bez VISIBLE checklist potwierdzający że pozostali agents (prompt-tester, rls-auditor, test-writer) ran clean. Sprint 1 creates `.claude/agents/<name>.md` files per template w sekcji "Frontmatter template".
|
||||
@@ -0,0 +1,256 @@
|
||||
# CLAUDE.md — compass-contract-hub
|
||||
|
||||
Project memory for Claude Code working in this repository. **Read first w każdej sesji.** Komplementuje `~/.claude/CLAUDE.md` (user-level global instructions).
|
||||
|
||||
## Project identity
|
||||
|
||||
**Compass** = open-core legal-tech contract management. Differentiated od konkurencji (MikeOSS, Ironclad, Robin AI) przez **5 moats**:
|
||||
|
||||
1. **AI-native architecture** (ADR-001) — LLM/agents/embeddings w core data flow, nie bolted on
|
||||
2. **Multi-tenant RLS day 1** — Postgres RLS na każdej tabeli (vs MikeOSS Issue #144 "No RLS")
|
||||
3. **Multi-jurisdiction** ~30 krajów (Bridgestone-inspired scope) — `packages/jurisdictions/{country}/` z local rules
|
||||
4. **On-prem self-host** — Hetzner CCX23 + Authentik + Storage Box (vs MikeOSS Will Chen explicite "Prohibited Areas: local-hosting refactors")
|
||||
5. **EU regulatory focus** — GDPR/RODO/Schrems II/AI Act first-class
|
||||
|
||||
**Target users:** SME legal teams (10-200 contracts/mc), boutique law firms, in-house counsel w multi-jurisdiction operations. **NOT** big-law BigCorp (Ironclad/Harvey AI target).
|
||||
|
||||
**Solo founder:** Tobiasz Badura. **Build phase:** private (no public commits, no LinkedIn mentions, no monetization podczas Bridgestone employment — patrz "License posture" + "Bridgestone IP risk" poniżej).
|
||||
|
||||
## Stack final (zatwierdzony 2026-05-17)
|
||||
|
||||
**Frontend (apps/web/):**
|
||||
- Vite + React 18 + TypeScript + shadcn/ui + Tailwind
|
||||
- Supabase JS SDK (auth + storage)
|
||||
- ~80-120h pracy wykonanej dotychczas — NIE wyrzucamy
|
||||
|
||||
**Backend (apps/api/, apps/workers/, apps/mcp-server/):**
|
||||
- **FastAPI** (Python) — primary backend
|
||||
- **PydanticAI** — agent framework primary
|
||||
- **LangGraph** — selective (multi-step flows tylko)
|
||||
- **LiteLLM** — multi-provider gateway, cost tracking, model routing
|
||||
- **Celery + Redis** — task queue dla operacji >5s
|
||||
|
||||
**Data:**
|
||||
- **Postgres 16** (Supabase initially → self-host na Hetzner przed enterprise launch)
|
||||
- **RLS day 1** — non-negotiable, każda tabela z `tenant_id`
|
||||
- **Qdrant** — vector store (multi-tenant payload filtering)
|
||||
- **Voyage AI** `voyage-multilingual-2` — embeddings (PL/EN)
|
||||
|
||||
**Doc processing:**
|
||||
- **unstructured.io** + **PyMuPDF** + **Marker** + Tesseract OCR fallback
|
||||
|
||||
**Observability + Evals:**
|
||||
- **Langfuse** self-hosted — LLM traces, prompt versioning, A/B testing
|
||||
- **promptfoo** + custom golden datasets — eval w CI
|
||||
|
||||
**Hosting:** Hetzner CCX23 Falkenstein DE (DE data residency for EU customers)
|
||||
|
||||
**Reasoning per choice:** patrz `docs/architecture/ADR-001-ai-native.md`. Nie zmieniaj stacku bez ADR.
|
||||
|
||||
## Skill priority order
|
||||
|
||||
Gdy Claude pracuje nad zadaniem dotykającym legal-tech / Compass kodu, **invoke skille w tej kolejności**:
|
||||
|
||||
### Level 1 — Domain (user-level, global)
|
||||
|
||||
- **`legal-tech`** — clause taxonomy domain knowledge, red flags per type, GDPR/RODO/AI Act, multi-jurisdiction baseline. **Invoke first** dla każdego task z słowem "klauzula" / "contract" / "review" / "extraction".
|
||||
|
||||
### Level 2 — Project (compass-* skille, local)
|
||||
|
||||
- **`compass-architecture`** — system overview, monorepo, data model, RLS, deployment topology (12-pkt self-check)
|
||||
- **`compass-clause-taxonomy`** — Pydantic schemas, zod mirror, prompt templates, jurisdiction variants, add-clause workflow (13-pkt self-check)
|
||||
- **`compass-ai-native-mandates`** — enforcement ADR-001 8 mandatów (8-pkt self-check; mandatory dla każdej PR z LLM operation)
|
||||
|
||||
### Level 3 — Framework (user-level, global)
|
||||
|
||||
- **`rag-pipeline-builder`** — eval infrastructure (RAGAS, hit rate), retrieval implementation w `packages/retrieval`
|
||||
- **`mcp-server-builder`** — `apps/mcp-server` design + auth + transport
|
||||
- **`cloud-deploy`** — Hetzner ops (Caddy, fail2ban, backups, Docker compose)
|
||||
- **`frontend-web-ui`** — `apps/web` UI changes (semantic HTML, a11y, modern CSS, Refactoring UI principles)
|
||||
- **`bielik-router`** — gdy decyzja Bielik vs Claude API dla privacy-sensitive PL operations (rzadko, batch only)
|
||||
|
||||
### Level 4 — Communication (user-level)
|
||||
|
||||
- **`pisanie-pl`** — gdy generujesz PL content (clause descriptions w UI, error messages, key_observations)
|
||||
|
||||
### Routing rule
|
||||
|
||||
> **Najpierw legal-tech** (domain), **potem compass-*** (project), **potem framework** (rag/mcp/cloud), **na końcu pisanie-pl** (output text).
|
||||
|
||||
## AI-native discipline — non-negotiable
|
||||
|
||||
**Read `docs/architecture/ADR-001-ai-native.md`** w każdej sesji dotykającej LLM. 8 mandatów:
|
||||
|
||||
1. **M1 Agent-first** — operacje >2s przez PydanticAI agent, nie direct LLM call w handler
|
||||
2. **M2 Schema-first** — Pydantic input/output, retry 3×, NIGDY regex parsing
|
||||
3. **M3 Streaming** — SSE dla każdej operacji >2s, EventSource w UI
|
||||
4. **M4 Eval-driven** — prompt change wymaga passing eval w CI, golden dataset min 20 PL + 20 EN
|
||||
5. **M5 Cost-aware routing** — LLMRouter wybiera model (Sonnet default, Opus critical, Haiku bulk, Gemini long-ctx), `tenant_id` + `operation` w metadata
|
||||
6. **M6 Cache-aware** — Anthropic prompt cache + embedding cache (Redis) + result memoization (doc_hash + prompt_v + model)
|
||||
7. **M7 Async-first** — operacje >5s przez Celery, return task_id + stream_url
|
||||
8. **M8 Observable** — Langfuse trace per agent run, `tenant_id` w metadata
|
||||
|
||||
**Każda PR** z LLM/agents/streaming code MUSI mieć VISIBLE self-check 8 punktów w description. `compass-pr-reviewer` subagent block merge gdy fail bez justification. Enforcement details: skill `compass-ai-native-mandates`.
|
||||
|
||||
## Test discipline
|
||||
|
||||
- **Every prompt change** → eval run w CI (M4). Threshold: precision ≥ 0.85, recall ≥ 0.80, cost_per_doc ≤ $0.02. Regression blocks merge.
|
||||
- **Every endpoint** → pytest (Python) + vitest (TS) test. Integration test covers happy path + error path + RLS isolation.
|
||||
- **Every migration** → RLS audit (subagent `compass-rls-auditor`) przed merge. Critical: czy nowa tabela ma RLS enabled + tenant_isolation policy?
|
||||
- **TDD preferred** dla agents/extraction logic — write Pydantic schema + 1 golden example test → fail → implement → green
|
||||
- **No commits z `pytest --skip-eval`** chyba że justified w PR (rare)
|
||||
|
||||
## Security invariants
|
||||
|
||||
**Non-negotiable from day 1, NIE "dodamy później":**
|
||||
|
||||
1. **RLS na każdej tabeli z `tenant_id`** — żaden endpoint nie omija przez `service_role` (poza explicit admin operations, logged)
|
||||
2. **`tenant_id` w JWT claims** — Supabase custom claim, weryfikowane w FastAPI middleware
|
||||
3. **`tenant_id` propagation** — Langfuse trace metadata + Celery task args + log lines context
|
||||
4. **Storage isolation** — file paths `<tenant_id>/contracts/...`, Storage RLS policy enforces
|
||||
5. **Qdrant payload filter `tenant_id`** — zawsze w query, no cross-tenant similarity
|
||||
6. **Audit log** — append-only, każda mutation persisted z user_id + tenant_id + diff + request_id
|
||||
7. **Never log PII** w plaintext — redact patterns (`pesel`, `nip`, `email`, `phone`) przed log persist
|
||||
8. **AI legal disclaimer** — każdy user-facing LLM output zawiera "REQUIRES LEGAL COUNSEL SIGN-OFF" hardcoded w Pydantic base schema
|
||||
9. **Secrets** — NIGDY w git, `.env.local` w gitignore, Hetzner deploy używa env vars przez Docker secrets
|
||||
|
||||
**RLS bypass detection** — `compass-rls-auditor` subagent skanuje PR diff for `service_role` usage, `bypassRLS()` calls, raw SQL bez tenant filter. Block merge bez explicit `# admin-operation-justified: <reason>` comment.
|
||||
|
||||
## Cost discipline
|
||||
|
||||
- **Per-tenant cost tracking** w Langfuse od dnia 1 — każdy LLM call z `tenant_id` + `operation` metadata
|
||||
- **Model routing rules** (per ADR-001 M5):
|
||||
- Clause extraction → Sonnet 4.6
|
||||
- Compliance review (critical) → Opus 4.7
|
||||
- Bulk classification (>100 docs) → Haiku 4.5
|
||||
- Embedding → voyage-multilingual-2
|
||||
- Long context (>200k) → Gemini 2.5 Pro
|
||||
- **Cost annotation w task definition** — każda nowa operacja w `apps/workers/tasks/` ma docstring z estimated cost per typical document
|
||||
- **Cache hit ratio monitoring** — Langfuse scorer dla cache hits, alert jeśli <30% dla extraction
|
||||
- **Monthly per-tenant cost report** — automated z Langfuse → email do operator (subagent `compass-cost-analyzer` Sprint 5+)
|
||||
|
||||
## Workflow conventions
|
||||
|
||||
### Commits
|
||||
|
||||
- **Atomic commits** — każdy commit = jedna sensowna zmiana, kompiluje, testy pass
|
||||
- **Conventional commits** style: `feat(api): add liability extraction endpoint`, `fix(rls): contract isolation regression`, `chore(deps): bump fastapi 0.110 → 0.115`
|
||||
- **Branch naming:** `feat/<topic>`, `fix/<topic>`, `chore/<topic>`, `eval/<prompt-name>-v<N>`
|
||||
- **NIE commituj** `--no-verify` (skip hooks) bez explicit user request
|
||||
|
||||
### PR flow
|
||||
|
||||
1. Branch z `main` → implement → local test pass
|
||||
2. Self-check per skill applicable (compass-architecture 12-pkt + compass-ai-native-mandates 8-pkt + compass-clause-taxonomy 13-pkt jeśli relevant)
|
||||
3. PR description z VISIBLE self-check confirmation
|
||||
4. `compass-pr-reviewer` subagent run (AGENTS.md) — block merge if fail
|
||||
5. CI green (pytest + vitest + eval suite jeśli prompts changed + RLS audit jeśli migrations)
|
||||
6. Manual review (solo founder phase = self-review z 24h cooldown dla istotnych PR)
|
||||
7. Squash merge to `main`
|
||||
|
||||
### Files to create vs edit
|
||||
|
||||
- **Prefer edit** over create — istniejący frontend ma wzorce, follow them
|
||||
- **NIGDY** nie twórz `*.md` doc files bez user request (poza ADR które są mandatory dla architectural decisions)
|
||||
- **ADR** dla każdej istotnej architectural decision — `docs/architecture/ADR-NNN-<topic>.md` z context/decision/consequences/alternatives
|
||||
- **Handoff doc** przy long-running multi-session work — `docs/handoffs/YYYY-MM-DD-<topic>.md`
|
||||
|
||||
## Naming conventions
|
||||
|
||||
### Python (apps/api, apps/workers, apps/mcp-server, packages/*)
|
||||
|
||||
- Modules: `snake_case.py`
|
||||
- Classes: `PascalCase`
|
||||
- Functions/methods: `snake_case`
|
||||
- Constants: `UPPER_SNAKE_CASE`
|
||||
- Pydantic schemas dla LLM output: `<ClauseType>Clause` (np. `LiabilityClause`, `IPClause`)
|
||||
- Pydantic schemas dla entities: `<Entity>` (np. `Contract`, `User`)
|
||||
- Agents: `<purpose>_agent.py` z `agent = Agent(...)` constant
|
||||
- Tasks: `apps/workers/tasks/<verb>_<noun>.py` z `<verb>_<noun>_task = celery_app.task(...)`
|
||||
- Prompts: `packages/prompts/clauses/<clause>_<purpose>_v<N>.py` z `PROMPT_VERSION`, `SYSTEM_PROMPT`, `FEW_SHOT_EXAMPLES`
|
||||
|
||||
### TypeScript (apps/web)
|
||||
|
||||
- Files: `kebab-case.tsx` dla components, `camelCase.ts` dla utils/hooks
|
||||
- Components: `PascalCase` (`ContractList.tsx`)
|
||||
- Hooks: `use<Name>` (`useStreamTask.ts`)
|
||||
- Types/interfaces: `PascalCase`, no `I` prefix
|
||||
- Zod schemas: `<entity>Schema`, exported types `<Entity>` (`liabilityClauseSchema` → `type LiabilityClause`)
|
||||
|
||||
### SQL (supabase/migrations)
|
||||
|
||||
- Tables: `snake_case`, plural (`contracts`, `clauses`, `audit_log` exception singular dla append-only)
|
||||
- Columns: `snake_case`
|
||||
- Migration filename: `YYYYMMDDHHMMSS_<verb>_<noun>.sql` (np. `20260518120000_add_clauses_table.sql`)
|
||||
- Enums: `<table>_<purpose>_enum` (np. `clause_status_enum`)
|
||||
|
||||
## License posture
|
||||
|
||||
**PRIVATE — no public commits, no LinkedIn mentions, no monetization.**
|
||||
|
||||
- Repo settings: GitHub private, no public forks, no GitHub Actions outputs leaking content
|
||||
- **DO NOT** create LinkedIn posts mentioning Compass nazwą / brand
|
||||
- **DO NOT** add Compass do haski.io portfolio
|
||||
- **DO NOT** commit do public repos with Compass-derived code
|
||||
- License file: **deferred** (decyzja przy publikacji — Apache 2.0 vs AGPL-3.0+Commercial Exception, pending IP lawyer review)
|
||||
- Trademark "Compass": **deferred** (brand może się zmienić, EUIPO check at publication time)
|
||||
|
||||
**Sign-off przed any public mention:**
|
||||
|
||||
1. IP lawyer review (Maruta Wachta / Lubasz / RKKW) — license + trademark + taxonomy
|
||||
2. Bridgestone clearance (employment lawyer) — IP risk + carve-out per kontrakt
|
||||
3. EUIPO trademark availability check
|
||||
4. ADR documenting decision to go public
|
||||
|
||||
## Bridgestone IP risk — known, accepted, mitigated
|
||||
|
||||
User świadomie absorbuje IP risk per analysis 2026-05-17. **Kontekst:**
|
||||
|
||||
- Bridgestone employment kontrakt zawiera proaktywny disclosure obligation, automatic IP transfer, cooperation obligation
|
||||
- Multi-jurisdiction legal-tech ~30 krajów = direct overlap z user's role Senior Global Legal Tech Counsel
|
||||
- "Własny sprzęt + prywatny czas" defense **legalnie irrelevant** pod tymi klauzulami
|
||||
|
||||
**Mitigation tactical (enforced via tooling + discipline):**
|
||||
|
||||
- **NIGDY** używaj Bridgestone hardware / network / email / colleagues dla Compass work
|
||||
- Commits z personal GitHub account only — sprawdź `git config --get user.email` (musi być `baduratobiasz@gmail.com`, nie `tobiasz@bridgestone...`)
|
||||
- No publication / monetization / public brand association podczas zatrudnienia Bridgestone
|
||||
- Sprint 0 = private foundation only, deferring all public-facing decisions
|
||||
|
||||
**Calendar reminder:** 2026-07-15 — review status (employment, runway, MVP progress) przed any escalation.
|
||||
|
||||
## Sprint sequence (high-level, see docs/handoffs/ dla details)
|
||||
|
||||
- **Sprint 0** (current): `.claude/` foundation — skille + CLAUDE.md + AGENTS.md + settings.json + ADR-001 done
|
||||
- **Sprint 1:** Lovable disconnect + monorepo restructure (move `src/` → `apps/web/src/`, create `apps/api/` z FastAPI skeleton, `pyproject.toml` uv workspace root)
|
||||
- **Sprint 2:** First module — Liability extraction PL (Pydantic schema + prompt v1 + golden 20 PL + eval w CI + Langfuse trace + Celery task + SSE streaming)
|
||||
- **Sprint 3:** RLS multi-tenant day 1 (migration + middleware + RLS audit subagent + integration test cross-tenant isolation)
|
||||
- **Sprint 4:** MCP server skeleton + end-to-end demo (upload → extract → display → review)
|
||||
- **Po Sprint 4:** working demo dla NDA-protected paying pilot (jeśli go/no-go bramki passed)
|
||||
|
||||
## Anti-patterns (specific to this project)
|
||||
|
||||
- ❌ **Direct `anthropic.messages.create()` w route handler** — violates M1, refactor through agent
|
||||
- ❌ **Free-text LLM output parsed regexami** — violates M2, use Pydantic `result_type`
|
||||
- ❌ **`service_role` Supabase key w business logic** — violates RLS day 1, użyj user JWT context
|
||||
- ❌ **`await long_op()` w route handler bez Celery** — violates M7, use task queue
|
||||
- ❌ **Inline prompt w agent definition** (`Agent(system_prompt="...")` z hardcoded string) — violates M4, extract do `packages/prompts/`
|
||||
- ❌ **`print(f"LLM: {response}")` debugging** — violates M8, use Langfuse trace
|
||||
- ❌ **Adding clause type bez ADR** — taxonomy change to breaking change, wymaga ADR + 7 step workflow z compass-clause-taxonomy skill
|
||||
- ❌ **Commit secrets / .env values do git** — credential rotation cost > whole sprint
|
||||
- ❌ **LinkedIn post about Compass** podczas private phase — patrz License posture
|
||||
- ❌ **Generic "fix" commits** — atomic commits + conventional style
|
||||
|
||||
## Cross-references
|
||||
|
||||
- `docs/architecture/ADR-001-ai-native.md` — pełna ADR z 8 mandates + alternatives considered + status
|
||||
- `AGENTS.md` — 8 subagents topology (clause-extractor, clause-reviewer, jurisdiction-checker, prompt-tester, doc-parser, rls-auditor, test-writer, pr-reviewer)
|
||||
- `.claude/skills/compass-architecture/SKILL.md`
|
||||
- `.claude/skills/compass-clause-taxonomy/SKILL.md`
|
||||
- `.claude/skills/compass-ai-native-mandates/SKILL.md`
|
||||
- `.claude/settings.json` — permissions + hooks placeholder + MCPs scope
|
||||
- `~/.claude/CLAUDE.md` — user-level global instructions (kto pyta, stack defaults, anti-patterns)
|
||||
|
||||
## Zasada główna
|
||||
|
||||
**AI-native discipline + RLS day 1 + private build phase.** Każda PR przechodzi 3-warstwowy self-check (architecture + mandates + taxonomy gdzie relevant). Każda mutation w DB ma audit log entry. Każdy LLM call ma `tenant_id` + Langfuse trace. Stack final zatwierdzony — nie zmieniaj bez ADR. License + Bridgestone clearance + public brand = deferred do post-MVP review (cal 2026-07-15).
|
||||
@@ -1,73 +1,117 @@
|
||||
# Welcome to your Lovable project
|
||||
# Compass — open-core legal-tech contract management
|
||||
|
||||
## Project info
|
||||
**Status:** PRIVATE. Build phase. No public mentions, no monetization, no LinkedIn references.
|
||||
**See:** `CLAUDE.md` (project memory + license posture), `docs/architecture/ADR-001-ai-native.md` (AI-native architecture mandates), `AGENTS.md` (multi-agent topology).
|
||||
|
||||
**URL**: https://lovable.dev/projects/d7960738-6043-4a9e-b816-3320a007a439
|
||||
## What
|
||||
|
||||
## How can I edit this code?
|
||||
Multi-tenant legal-tech contract management for SME legal teams, boutique law firms, in-house counsel in multi-jurisdiction operations. Differentiated by:
|
||||
|
||||
There are several ways of editing your application.
|
||||
1. AI-native architecture (LLM/agents/embeddings in core data flow, not bolted on)
|
||||
2. Multi-tenant Postgres RLS day 1
|
||||
3. Multi-jurisdiction (~30 countries) clause variants
|
||||
4. On-prem self-host (Hetzner) — vs hosted-only competitors
|
||||
5. EU regulatory focus (GDPR/RODO/Schrems II/AI Act)
|
||||
|
||||
**Use Lovable**
|
||||
## Monorepo layout
|
||||
|
||||
Simply visit the [Lovable Project](https://lovable.dev/projects/d7960738-6043-4a9e-b816-3320a007a439) and start prompting.
|
||||
|
||||
Changes made via Lovable will be committed automatically to this repo.
|
||||
|
||||
**Use your preferred IDE**
|
||||
|
||||
If you want to work locally using your own IDE, you can clone this repo and push changes. Pushed changes will also be reflected in Lovable.
|
||||
|
||||
The only requirement is having Node.js & npm installed - [install with nvm](https://github.com/nvm-sh/nvm#installing-and-updating)
|
||||
|
||||
Follow these steps:
|
||||
|
||||
```sh
|
||||
# Step 1: Clone the repository using the project's Git URL.
|
||||
git clone <YOUR_GIT_URL>
|
||||
|
||||
# Step 2: Navigate to the project directory.
|
||||
cd <YOUR_PROJECT_NAME>
|
||||
|
||||
# Step 3: Install the necessary dependencies.
|
||||
npm i
|
||||
|
||||
# Step 4: Start the development server with auto-reloading and an instant preview.
|
||||
npm run dev
|
||||
```
|
||||
compass-contract-hub/
|
||||
├── apps/
|
||||
│ ├── web/ # Vite + React 18 + TS + shadcn (frontend)
|
||||
│ ├── api/ # FastAPI + PydanticAI agents (Python)
|
||||
│ ├── workers/ # Celery tasks (Python)
|
||||
│ └── mcp-server/ # MCP server (Python)
|
||||
├── packages/ # shared Python packages (uv workspace)
|
||||
│ ├── core/ # auth, tenant context, audit, events
|
||||
│ ├── schemas/ # Pydantic models (entities + LLM I/O)
|
||||
│ ├── prompts/ # versioned prompts
|
||||
│ ├── agents/ # PydanticAI agent definitions
|
||||
│ ├── llm-gateway/ # LiteLLM + router + cache + Langfuse
|
||||
│ ├── retrieval/ # Qdrant + chunking + hybrid search
|
||||
│ ├── ingestion/ # PDF/DOCX/OCR pipeline
|
||||
│ ├── evals/ # golden datasets + promptfoo runners
|
||||
│ └── jurisdictions/ # pl/, de/, fr/, ... per-country rules
|
||||
├── supabase/ # migrations + Edge Functions
|
||||
├── scripts/hooks/ # Claude Code hooks (PreToolUse/PostToolUse)
|
||||
├── docs/
|
||||
│ ├── architecture/ # ADRs
|
||||
│ └── handoffs/ # session handoff docs
|
||||
├── .claude/
|
||||
│ ├── skills/ # project-specific skills (compass-*)
|
||||
│ ├── agents/ # subagent definitions
|
||||
│ └── settings.json
|
||||
├── CLAUDE.md
|
||||
├── AGENTS.md
|
||||
├── pyproject.toml # uv workspace root
|
||||
└── package.json # npm workspace root
|
||||
```
|
||||
|
||||
**Edit a file directly in GitHub**
|
||||
## Stack
|
||||
|
||||
- Navigate to the desired file(s).
|
||||
- Click the "Edit" button (pencil icon) at the top right of the file view.
|
||||
- Make your changes and commit the changes.
|
||||
- **Frontend:** Vite + React 18 + TypeScript + shadcn/ui + Tailwind + Supabase JS
|
||||
- **Backend:** Python 3.12 + FastAPI + PydanticAI + LangGraph (selective) + LiteLLM
|
||||
- **DB:** Supabase Postgres + RLS day 1 (migration to self-hosted Hetzner pre enterprise launch)
|
||||
- **Vector:** Qdrant + Voyage AI `voyage-multilingual-2`
|
||||
- **Doc processing:** unstructured.io + PyMuPDF + Marker + Tesseract OCR
|
||||
- **Observability:** Langfuse self-hosted
|
||||
- **Eval:** promptfoo + custom golden datasets, CI regression
|
||||
- **Task queue:** Celery + Redis
|
||||
- **Hosting:** Hetzner CCX23 Falkenstein DE
|
||||
|
||||
**Use GitHub Codespaces**
|
||||
## Setup (local dev)
|
||||
|
||||
- Navigate to the main page of your repository.
|
||||
- Click on the "Code" button (green button) near the top right.
|
||||
- Select the "Codespaces" tab.
|
||||
- Click on "New codespace" to launch a new Codespace environment.
|
||||
- Edit files directly within the Codespace and commit and push your changes once you're done.
|
||||
Requirements:
|
||||
- Node.js 20+ (`nvm install 20`)
|
||||
- Python 3.12+
|
||||
- `uv` (`pip install uv`)
|
||||
- Docker + docker compose
|
||||
- Supabase CLI (`brew install supabase/tap/supabase` / `scoop install supabase`)
|
||||
|
||||
## What technologies are used for this project?
|
||||
```bash
|
||||
# Frontend
|
||||
cd apps/web
|
||||
npm install
|
||||
npm run dev # http://localhost:8080
|
||||
|
||||
This project is built with:
|
||||
# Backend (separate terminal)
|
||||
uv sync # installs all packages in workspace
|
||||
cd apps/api
|
||||
uv run uvicorn main:app --reload --port 8000
|
||||
|
||||
- Vite
|
||||
- TypeScript
|
||||
- React
|
||||
- shadcn-ui
|
||||
- Tailwind CSS
|
||||
# Workers (separate terminal)
|
||||
cd apps/workers
|
||||
uv run celery -A celery_app worker --loglevel=info
|
||||
|
||||
## How can I deploy this project?
|
||||
# Local services (Redis, Qdrant, Langfuse)
|
||||
docker compose -f docker-compose.dev.yml up -d
|
||||
```
|
||||
|
||||
Simply open [Lovable](https://lovable.dev/projects/d7960738-6043-4a9e-b816-3320a007a439) and click on Share -> Publish.
|
||||
Env vars: copy `.env.example` → `.env.local` and populate. **Never commit `.env*`.**
|
||||
|
||||
## Can I connect a custom domain to my Lovable project?
|
||||
## Working in this repo
|
||||
|
||||
Yes, you can!
|
||||
**Read `CLAUDE.md` first.** Defines:
|
||||
|
||||
To connect a domain, navigate to Project > Settings > Domains and click Connect Domain.
|
||||
- Project identity + 5 moats
|
||||
- Stack final + skill priority order (legal-tech → compass-* → framework → communication)
|
||||
- 8 AI-native mandates (ADR-001) — non-negotiable for every PR with LLM ops
|
||||
- Security invariants (RLS day 1, `tenant_id` everywhere, audit log, AI legal disclaimer)
|
||||
- Cost discipline (per-tenant tracking, model routing rules)
|
||||
- License posture (PRIVATE — no public commits, no LinkedIn mentions)
|
||||
|
||||
Read more here: [Setting up a custom domain](https://docs.lovable.dev/tips-tricks/custom-domain#step-by-step-guide)
|
||||
**Per-PR self-check** required in description:
|
||||
|
||||
- `compass-ai-native-mandates` 8-point checklist (every LLM/agent change)
|
||||
- `compass-architecture` 12-point checklist (architectural changes)
|
||||
- `compass-clause-taxonomy` 13-point checklist (prompt/schema changes)
|
||||
|
||||
PR review gated by `compass-pr-reviewer` subagent (see `AGENTS.md`).
|
||||
|
||||
## License
|
||||
|
||||
Deferred. Decision pending IP lawyer review (Apache 2.0 vs AGPL-3.0 + Commercial Exception). Until then: **no public distribution, no published forks, no derivative works outside this private repo**.
|
||||
|
||||
## Owner
|
||||
|
||||
Tobiasz Badura — solo founder (private build phase). Contact via personal channels only; **do not use Bridgestone work email or systems for anything related to this project**.
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
"""Compass FastAPI application entry point.
|
||||
|
||||
Sprint 1 baseline: health endpoint + minimal middleware shell.
|
||||
Future sprints layer in:
|
||||
- JWT verification middleware (Supabase JWKS)
|
||||
- tenant_id propagation via SET LOCAL app.tenant_id
|
||||
- SSE streaming endpoint /api/v1/stream/{task_id}
|
||||
- Route handlers per resource (contracts, clauses, tasks)
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from contextlib import asynccontextmanager
|
||||
|
||||
import structlog
|
||||
from fastapi import FastAPI
|
||||
|
||||
from apps.api.routes import health
|
||||
|
||||
log = structlog.get_logger()
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
log.info("compass_api.startup", version=app.version)
|
||||
yield
|
||||
log.info("compass_api.shutdown")
|
||||
|
||||
|
||||
app = FastAPI(
|
||||
title="Compass API",
|
||||
version="0.1.0",
|
||||
description="Compass — open-core legal-tech contract management backend",
|
||||
lifespan=lifespan,
|
||||
)
|
||||
|
||||
app.include_router(health.router, tags=["health"])
|
||||
|
||||
|
||||
@app.get("/")
|
||||
async def root() -> dict[str, str]:
|
||||
return {"name": "compass-api", "version": app.version, "status": "running"}
|
||||
@@ -0,0 +1,33 @@
|
||||
[project]
|
||||
name = "compass-api"
|
||||
version = "0.1.0"
|
||||
description = "Compass FastAPI backend (agent dispatch + SSE streaming + REST)"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"fastapi>=0.115",
|
||||
"uvicorn[standard]>=0.30",
|
||||
"pydantic>=2.9",
|
||||
"pydantic-settings>=2.5",
|
||||
"python-jose[cryptography]>=3.3",
|
||||
"httpx>=0.27",
|
||||
"asyncpg>=0.29",
|
||||
"supabase>=2.7",
|
||||
"redis>=5.0",
|
||||
"celery>=5.4",
|
||||
"structlog>=24.4",
|
||||
"compass-core",
|
||||
"compass-schemas",
|
||||
"compass-llm-gateway",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
compass-core = { workspace = true }
|
||||
compass-schemas = { workspace = true }
|
||||
compass-llm-gateway = { workspace = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["."]
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Health and readiness endpoints.
|
||||
|
||||
`/health` — liveness probe (returns 200 if app reachable).
|
||||
`/ready` — readiness probe (verifies dependencies: DB, Redis, Qdrant).
|
||||
Sprint 1 stub: ready check returns OK without probing dependencies yet —
|
||||
real probes are added when DB/Redis/Qdrant clients land in `packages/core`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import UTC, datetime
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import APIRouter
|
||||
from pydantic import BaseModel
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
class HealthResponse(BaseModel):
|
||||
status: Literal["ok"]
|
||||
service: str
|
||||
version: str
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
class ReadinessResponse(BaseModel):
|
||||
status: Literal["ready", "degraded"]
|
||||
checks: dict[str, Literal["ok", "fail", "skip"]]
|
||||
timestamp: datetime
|
||||
|
||||
|
||||
@router.get("/health", response_model=HealthResponse)
|
||||
async def health() -> HealthResponse:
|
||||
return HealthResponse(
|
||||
status="ok",
|
||||
service="compass-api",
|
||||
version="0.1.0",
|
||||
timestamp=datetime.now(UTC),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/ready", response_model=ReadinessResponse)
|
||||
async def ready() -> ReadinessResponse:
|
||||
checks: dict[str, Literal["ok", "fail", "skip"]] = {
|
||||
"database": "skip",
|
||||
"redis": "skip",
|
||||
"qdrant": "skip",
|
||||
"langfuse": "skip",
|
||||
}
|
||||
overall: Literal["ready", "degraded"] = "ready"
|
||||
return ReadinessResponse(status=overall, checks=checks, timestamp=datetime.now(UTC))
|
||||
@@ -0,0 +1,20 @@
|
||||
[project]
|
||||
name = "compass-mcp-server"
|
||||
version = "0.1.0"
|
||||
description = "Compass MCP server (Sprint 4+: distribution moat — Compass exposed as MCP server)"
|
||||
requires-python = ">=3.12"
|
||||
dependencies = [
|
||||
"mcp>=1.0",
|
||||
"pydantic>=2.9",
|
||||
"compass-core",
|
||||
]
|
||||
|
||||
[tool.uv.sources]
|
||||
compass-core = { workspace = true }
|
||||
|
||||
[build-system]
|
||||
requires = ["hatchling"]
|
||||
build-backend = "hatchling.build"
|
||||
|
||||
[tool.hatch.build.targets.wheel]
|
||||
packages = ["."]
|
||||
@@ -0,0 +1,19 @@
|
||||
"""Compass MCP server entry point.
|
||||
|
||||
Sprint 1: skeleton only. Sprint 4+ implements actual tools:
|
||||
- compass.list_contracts
|
||||
- compass.get_clause
|
||||
- compass.extract_contract
|
||||
- compass.review_clause
|
||||
|
||||
Read mcp-server-builder user-level skill for transport / auth / SDK patterns.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
|
||||
def main() -> None:
|
||||
raise NotImplementedError("Compass MCP server skeleton — Sprint 4+ implementation pending")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Generated
+7326
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,85 @@
|
||||
{
|
||||
"name": "@compass/web",
|
||||
"private": true,
|
||||
"version": "0.1.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build",
|
||||
"build:dev": "vite build --mode development",
|
||||
"lint": "eslint .",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@radix-ui/react-accordion": "^1.2.0",
|
||||
"@radix-ui/react-alert-dialog": "^1.1.1",
|
||||
"@radix-ui/react-aspect-ratio": "^1.1.0",
|
||||
"@radix-ui/react-avatar": "^1.1.0",
|
||||
"@radix-ui/react-checkbox": "^1.1.1",
|
||||
"@radix-ui/react-collapsible": "^1.1.0",
|
||||
"@radix-ui/react-context-menu": "^2.2.1",
|
||||
"@radix-ui/react-dialog": "^1.1.2",
|
||||
"@radix-ui/react-dropdown-menu": "^2.1.1",
|
||||
"@radix-ui/react-hover-card": "^1.1.1",
|
||||
"@radix-ui/react-label": "^2.1.0",
|
||||
"@radix-ui/react-menubar": "^1.1.1",
|
||||
"@radix-ui/react-navigation-menu": "^1.2.0",
|
||||
"@radix-ui/react-popover": "^1.1.1",
|
||||
"@radix-ui/react-progress": "^1.1.0",
|
||||
"@radix-ui/react-radio-group": "^1.2.0",
|
||||
"@radix-ui/react-scroll-area": "^1.1.0",
|
||||
"@radix-ui/react-select": "^2.1.1",
|
||||
"@radix-ui/react-separator": "^1.1.0",
|
||||
"@radix-ui/react-slider": "^1.2.0",
|
||||
"@radix-ui/react-slot": "^1.1.0",
|
||||
"@radix-ui/react-switch": "^1.1.0",
|
||||
"@radix-ui/react-tabs": "^1.1.0",
|
||||
"@radix-ui/react-toast": "^1.2.1",
|
||||
"@radix-ui/react-toggle": "^1.1.0",
|
||||
"@radix-ui/react-toggle-group": "^1.1.0",
|
||||
"@radix-ui/react-tooltip": "^1.1.4",
|
||||
"@supabase/supabase-js": "^2.50.0",
|
||||
"@tanstack/react-query": "^5.56.2",
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"cmdk": "^1.0.0",
|
||||
"date-fns": "^3.6.0",
|
||||
"embla-carousel-react": "^8.3.0",
|
||||
"framer-motion": "^12.18.1",
|
||||
"input-otp": "^1.2.4",
|
||||
"lucide-react": "^0.462.0",
|
||||
"next-themes": "^0.3.0",
|
||||
"react": "^18.3.1",
|
||||
"react-day-picker": "^8.10.1",
|
||||
"react-dom": "^18.3.1",
|
||||
"react-hook-form": "^7.53.0",
|
||||
"react-resizable-panels": "^2.1.3",
|
||||
"react-router-dom": "^6.26.2",
|
||||
"recharts": "^2.12.7",
|
||||
"sonner": "^1.5.0",
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"vaul": "^0.9.3",
|
||||
"zod": "^3.23.8",
|
||||
"zustand": "^4.5.7"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.9.0",
|
||||
"@tailwindcss/typography": "^0.5.15",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/react": "^18.3.3",
|
||||
"@types/react-dom": "^18.3.0",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
|
||||
"eslint-plugin-react-refresh": "^0.4.9",
|
||||
"globals": "^15.9.0",
|
||||
"postcss": "^8.4.47",
|
||||
"tailwindcss": "^3.4.11",
|
||||
"typescript": "^5.5.3",
|
||||
"typescript-eslint": "^8.0.1",
|
||||
"vite": "^5.4.1"
|
||||
}
|
||||
}
|
||||
|
Before Width: | Height: | Size: 7.5 KiB After Width: | Height: | Size: 7.5 KiB |
|
Before Width: | Height: | Size: 3.2 KiB After Width: | Height: | Size: 3.2 KiB |
+1
-1
@@ -74,7 +74,7 @@ export const FuturisticPieChart: React.FC<FuturisticPieChartProps> = ({ data, co
|
||||
{data.map((entry) => (
|
||||
<Cell
|
||||
key={`cell-${entry.name}`}
|
||||
fill={colors[entry.name] || '#ccc'}
|
||||
fill={colors[entry.name] || '#a1a1aa'}
|
||||
strokeWidth={0}
|
||||
/>
|
||||
))}
|
||||
@@ -2,6 +2,7 @@
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { supabase } from '@/integrations/supabase/client';
|
||||
import { useAuthStore } from '@/auth/use-auth-store';
|
||||
import { NegotiationMessage } from '@/data/types';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
@@ -25,12 +26,11 @@ const fetchMessages = async (negotiationRoomId: string): Promise<NegotiationMess
|
||||
return data || [];
|
||||
};
|
||||
|
||||
const addComment = async ({ negotiationRoomId, content }: { negotiationRoomId: string; content: string }) => {
|
||||
// For now, sender is hardcoded. This would be replaced with authenticated user info.
|
||||
const addComment = async ({ negotiationRoomId, content, senderName, senderRole }: { negotiationRoomId: string; content: string; senderName: string; senderRole: string }) => {
|
||||
const { data, error } = await supabase.from('negotiation_messages').insert({
|
||||
negotiation_room_id: negotiationRoomId,
|
||||
sender_name: 'John Doe', // Placeholder
|
||||
sender_role: 'Internal', // Placeholder
|
||||
sender_name: senderName,
|
||||
sender_role: senderRole,
|
||||
message_type: 'comment',
|
||||
content: content,
|
||||
}).select().single();
|
||||
@@ -39,11 +39,11 @@ const addComment = async ({ negotiationRoomId, content }: { negotiationRoomId: s
|
||||
return data;
|
||||
};
|
||||
|
||||
const addFileMessage = async ({ negotiationRoomId, fileUrl, fileName }: { negotiationRoomId: string; fileUrl: string, fileName: string }) => {
|
||||
const addFileMessage = async ({ negotiationRoomId, fileUrl, fileName, senderName, senderRole }: { negotiationRoomId: string; fileUrl: string; fileName: string; senderName: string; senderRole: string }) => {
|
||||
const { data, error } = await supabase.from('negotiation_messages').insert({
|
||||
negotiation_room_id: negotiationRoomId,
|
||||
sender_name: 'John Doe', // Placeholder
|
||||
sender_role: 'Internal', // Placeholder
|
||||
sender_name: senderName,
|
||||
sender_role: senderRole,
|
||||
message_type: 'file',
|
||||
file_url: fileUrl,
|
||||
file_name: fileName,
|
||||
@@ -55,11 +55,25 @@ const addFileMessage = async ({ negotiationRoomId, fileUrl, fileName }: { negoti
|
||||
|
||||
export default function NegotiationChat({ negotiationRoomId }: NegotiationChatProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { user, role } = useAuthStore();
|
||||
const [comment, setComment] = useState('');
|
||||
const [file, setFile] = useState<File | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const messagesEndRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { data: profile } = useQuery({
|
||||
queryKey: ['profile', user?.id],
|
||||
queryFn: async () => {
|
||||
if (!user) return null;
|
||||
const { data } = await supabase.from('profiles').select('full_name').eq('id', user.id).single();
|
||||
return data;
|
||||
},
|
||||
enabled: !!user,
|
||||
});
|
||||
|
||||
const senderName = profile?.full_name || user?.email || 'Unknown';
|
||||
const senderRole = role === 'admin' ? 'Admin' : 'Internal';
|
||||
|
||||
const { data: messages, isLoading, isError } = useQuery({
|
||||
queryKey: ['negotiation-messages', negotiationRoomId],
|
||||
queryFn: () => fetchMessages(negotiationRoomId),
|
||||
@@ -115,7 +129,7 @@ export default function NegotiationChat({ negotiationRoomId }: NegotiationChatPr
|
||||
const handleCommentSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (comment.trim()) {
|
||||
commentMutation.mutate({ negotiationRoomId, content: comment.trim() });
|
||||
commentMutation.mutate({ negotiationRoomId, content: comment.trim(), senderName, senderRole });
|
||||
}
|
||||
};
|
||||
|
||||
@@ -150,7 +164,7 @@ export default function NegotiationChat({ negotiationRoomId }: NegotiationChatPr
|
||||
.from('negotiation-files')
|
||||
.getPublicUrl(filePath);
|
||||
|
||||
fileMutation.mutate({ negotiationRoomId, fileUrl: publicUrl, fileName: file.name });
|
||||
fileMutation.mutate({ negotiationRoomId, fileUrl: publicUrl, fileName: file.name, senderName, senderRole });
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useState } from "react";
|
||||
import { useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuthStore } from "@/auth/use-auth-store";
|
||||
import { Contract } from "@/data/types";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Textarea } from "@/components/ui/textarea";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { ChevronRight, RotateCcw, CheckCircle2, XCircle, PlayCircle } from "lucide-react";
|
||||
|
||||
const WORKFLOW_STAGES = [
|
||||
{ name: "Drafting", role: "Sales Manager" },
|
||||
{ name: "Internal Review", role: "Head of Sales" },
|
||||
{ name: "Vendor Negotiation", role: "Sales Manager" },
|
||||
{ name: "Legal Review", role: "Lawyer" },
|
||||
{ name: "Final Approval", role: "Managing Director" },
|
||||
{ name: "Signed", role: "All Parties" },
|
||||
];
|
||||
|
||||
function getStageIndex(stage: string): number {
|
||||
return WORKFLOW_STAGES.findIndex((s) => s.name === stage);
|
||||
}
|
||||
|
||||
function getNextStage(currentStage: string): (typeof WORKFLOW_STAGES)[0] | null {
|
||||
const idx = getStageIndex(currentStage);
|
||||
if (idx < 0 || idx >= WORKFLOW_STAGES.length - 1) return null;
|
||||
return WORKFLOW_STAGES[idx + 1];
|
||||
}
|
||||
|
||||
function getPreviousStage(currentStage: string): (typeof WORKFLOW_STAGES)[0] | null {
|
||||
const idx = getStageIndex(currentStage);
|
||||
if (idx <= 0) return null;
|
||||
return WORKFLOW_STAGES[idx - 1];
|
||||
}
|
||||
|
||||
interface WorkflowActionsProps {
|
||||
contract: Contract;
|
||||
}
|
||||
|
||||
export default function WorkflowActions({ contract }: WorkflowActionsProps) {
|
||||
const queryClient = useQueryClient();
|
||||
const { user, role } = useAuthStore();
|
||||
const [confirmAction, setConfirmAction] = useState<"advance" | "return" | "start" | null>(null);
|
||||
const [note, setNote] = useState("");
|
||||
|
||||
const currentStage = contract.workflowStage;
|
||||
const nextStage = currentStage ? getNextStage(currentStage) : null;
|
||||
const prevStage = currentStage ? getPreviousStage(currentStage) : null;
|
||||
const isSigned = currentStage === "Signed";
|
||||
const hasWorkflow = !!currentStage;
|
||||
|
||||
const transitionMutation = useMutation({
|
||||
mutationFn: async ({
|
||||
newStage,
|
||||
action,
|
||||
}: {
|
||||
newStage: string;
|
||||
action: "advanced" | "returned" | "started";
|
||||
}) => {
|
||||
const stageInfo = WORKFLOW_STAGES.find((s) => s.name === newStage);
|
||||
|
||||
// Build workflow history entry
|
||||
const historyEntry = {
|
||||
from: currentStage || null,
|
||||
to: newStage,
|
||||
action,
|
||||
note: note.trim() || undefined,
|
||||
by: user?.id,
|
||||
at: new Date().toISOString(),
|
||||
};
|
||||
|
||||
const updateData: Record<string, unknown> = {
|
||||
workflow_stage: newStage,
|
||||
current_reviewer: newStage === "Signed"
|
||||
? null
|
||||
: { name: stageInfo?.role || "", role: stageInfo?.role || "" },
|
||||
};
|
||||
|
||||
// If advancing to Signed, set status to Active
|
||||
if (newStage === "Signed") {
|
||||
updateData.status = "Active";
|
||||
}
|
||||
|
||||
const { error } = await supabase
|
||||
.from("contracts")
|
||||
.update(updateData)
|
||||
.eq("id", contract.id);
|
||||
|
||||
if (error) throw error;
|
||||
|
||||
// Log to audit
|
||||
await supabase.from("audit_logs").insert({
|
||||
action: `contract.workflow_${action}`,
|
||||
entity_type: "contract",
|
||||
entity_id: contract.id,
|
||||
user_id: user!.id,
|
||||
details: historyEntry,
|
||||
});
|
||||
},
|
||||
onSuccess: (_, variables) => {
|
||||
queryClient.invalidateQueries({ queryKey: ["contract", contract.id] });
|
||||
queryClient.invalidateQueries({ queryKey: ["contracts"] });
|
||||
const actionLabel =
|
||||
variables.action === "advanced"
|
||||
? "advanced"
|
||||
: variables.action === "returned"
|
||||
? "returned"
|
||||
: "started";
|
||||
toast.success(`Workflow ${actionLabel} to "${variables.newStage}".`);
|
||||
setNote("");
|
||||
setConfirmAction(null);
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error("Failed to update workflow: " + err.message);
|
||||
setConfirmAction(null);
|
||||
},
|
||||
});
|
||||
|
||||
const handleAdvance = () => {
|
||||
if (!nextStage) return;
|
||||
transitionMutation.mutate({ newStage: nextStage.name, action: "advanced" });
|
||||
};
|
||||
|
||||
const handleReturn = () => {
|
||||
if (!prevStage) return;
|
||||
transitionMutation.mutate({ newStage: prevStage.name, action: "returned" });
|
||||
};
|
||||
|
||||
const handleStart = () => {
|
||||
transitionMutation.mutate({ newStage: "Drafting", action: "started" });
|
||||
};
|
||||
|
||||
// No workflow started yet
|
||||
if (!hasWorkflow) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center justify-between py-4">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
No workflow has been started for this contract.
|
||||
</p>
|
||||
<Button size="sm" onClick={() => setConfirmAction("start")}>
|
||||
<PlayCircle className="mr-2 h-4 w-4" />
|
||||
Start Workflow
|
||||
</Button>
|
||||
|
||||
<AlertDialog open={confirmAction === "start"} onOpenChange={(open) => !open && setConfirmAction(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Start Workflow?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will begin the approval workflow at the <strong>Drafting</strong> stage
|
||||
and assign it to the <strong>Sales Manager</strong>.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="py-2">
|
||||
<Textarea
|
||||
placeholder="Add a note (optional)"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleStart} disabled={transitionMutation.isPending}>
|
||||
{transitionMutation.isPending ? "Starting..." : "Start Workflow"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Workflow is complete
|
||||
if (isSigned) {
|
||||
return (
|
||||
<Card>
|
||||
<CardContent className="flex items-center gap-3 py-4">
|
||||
<CheckCircle2 className="h-5 w-5 text-green-500 dark:text-green-400" />
|
||||
<p className="text-sm font-medium">
|
||||
Workflow complete — contract has been signed by all parties.
|
||||
</p>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
// Active workflow — show actions
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-base flex items-center justify-between">
|
||||
<span>Workflow Actions</span>
|
||||
<Badge variant="secondary">{currentStage}</Badge>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Currently assigned to: <strong>{contract.currentReviewer?.name || contract.currentReviewer?.role || "—"}</strong>
|
||||
</p>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
{nextStage && (
|
||||
<Button size="sm" onClick={() => setConfirmAction("advance")}>
|
||||
<ChevronRight className="mr-1 h-4 w-4" />
|
||||
Advance to {nextStage.name}
|
||||
</Button>
|
||||
)}
|
||||
{prevStage && (
|
||||
<Button size="sm" variant="outline" onClick={() => setConfirmAction("return")}>
|
||||
<RotateCcw className="mr-1 h-4 w-4" />
|
||||
Return to {prevStage.name}
|
||||
</Button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Advance confirmation */}
|
||||
<AlertDialog open={confirmAction === "advance"} onOpenChange={(open) => !open && setConfirmAction(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Advance Workflow?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Move this contract from <strong>{currentStage}</strong> to{" "}
|
||||
<strong>{nextStage?.name}</strong>.
|
||||
{nextStage?.name === "Signed" && (
|
||||
<span className="block mt-2 text-green-600 dark:text-green-400 font-medium">
|
||||
This will mark the contract as Active and complete the workflow.
|
||||
</span>
|
||||
)}
|
||||
{nextStage && nextStage.name !== "Signed" && (
|
||||
<span className="block mt-1">
|
||||
It will be assigned to: <strong>{nextStage.role}</strong>
|
||||
</span>
|
||||
)}
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="py-2">
|
||||
<Textarea
|
||||
placeholder="Add a note (optional)"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction onClick={handleAdvance} disabled={transitionMutation.isPending}>
|
||||
{transitionMutation.isPending ? "Advancing..." : "Advance"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
|
||||
{/* Return confirmation */}
|
||||
<AlertDialog open={confirmAction === "return"} onOpenChange={(open) => !open && setConfirmAction(null)}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Return to Previous Stage?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Send this contract back from <strong>{currentStage}</strong> to{" "}
|
||||
<strong>{prevStage?.name}</strong>.
|
||||
<span className="block mt-1">
|
||||
It will be reassigned to: <strong>{prevStage?.role}</strong>
|
||||
</span>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<div className="py-2">
|
||||
<Textarea
|
||||
placeholder="Reason for returning (optional)"
|
||||
value={note}
|
||||
onChange={(e) => setNote(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleReturn}
|
||||
disabled={transitionMutation.isPending}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{transitionMutation.isPending ? "Returning..." : "Return"}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { cn } from "@/lib/utils";
|
||||
import { Clock, CheckCircle2, Circle, Loader2 } from "lucide-react";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
|
||||
const workflowStages = [
|
||||
{ name: 'Drafting', role: 'Sales Manager', description: 'Initial contract draft preparation' },
|
||||
{ name: 'Internal Review', role: 'Head of Sales', description: 'Internal stakeholder review' },
|
||||
{ name: 'Vendor Negotiation', role: 'Sales Manager', description: 'Negotiate terms with vendor' },
|
||||
{ name: 'Legal Review', role: 'Lawyer', description: 'Legal compliance check' },
|
||||
{ name: 'Final Approval', role: 'Managing Director', description: 'Executive sign-off' },
|
||||
{ name: 'Signed', role: 'All Parties', description: 'Contract fully executed' },
|
||||
];
|
||||
|
||||
interface WorkflowTimelineProps {
|
||||
currentStage?: string;
|
||||
}
|
||||
|
||||
const WorkflowTimeline = ({ currentStage }: WorkflowTimelineProps) => {
|
||||
const currentStageIndex = currentStage ? workflowStages.findIndex(stage => stage.name === currentStage) : -1;
|
||||
|
||||
if (!currentStage) return null;
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h4 className="text-lg font-semibold mb-6 flex items-center gap-2">
|
||||
<Clock className="h-5 w-5 text-primary" />
|
||||
Workflow Status
|
||||
</h4>
|
||||
<ol className="relative border-s border-border ml-1">
|
||||
{workflowStages.map((stage, index) => {
|
||||
const isCompleted = currentStageIndex > index;
|
||||
const isCurrent = currentStageIndex === index;
|
||||
const isPending = currentStageIndex < index;
|
||||
|
||||
return (
|
||||
<li key={stage.name} className="mb-8 ms-6">
|
||||
<span className={cn(
|
||||
"absolute flex items-center justify-center w-6 h-6 rounded-full -start-3",
|
||||
isCompleted && "bg-primary text-primary-foreground",
|
||||
isCurrent && "bg-primary text-primary-foreground ring-4 ring-primary/20",
|
||||
isPending && "bg-muted text-muted-foreground"
|
||||
)}>
|
||||
{isCompleted ? (
|
||||
<CheckCircle2 className="h-4 w-4" />
|
||||
) : isCurrent ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Circle className="h-3 w-3" />
|
||||
)}
|
||||
</span>
|
||||
<div className="ml-2">
|
||||
<div className="flex items-center gap-2 flex-wrap">
|
||||
<p className={cn(
|
||||
"font-semibold text-sm",
|
||||
isCurrent ? "text-primary" : isCompleted ? "text-foreground" : "text-muted-foreground"
|
||||
)}>
|
||||
{stage.name}
|
||||
</p>
|
||||
{isCurrent && <Badge variant="default" className="text-xs">In Progress</Badge>}
|
||||
{isCompleted && <Badge variant="outline" className="text-xs text-green-600 border-green-300 dark:text-green-400 dark:border-green-700">Completed</Badge>}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
{stage.role} — {stage.description}
|
||||
</p>
|
||||
</div>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ol>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
export default WorkflowTimeline;
|
||||
@@ -0,0 +1,229 @@
|
||||
import { useEffect } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { useForm } from "react-hook-form";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuthStore } from "@/auth/use-auth-store";
|
||||
import { toast } from "sonner";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Switch } from "@/components/ui/switch";
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { Separator } from "@/components/ui/separator";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Save } from "lucide-react";
|
||||
|
||||
interface SettingsForm {
|
||||
expiration_warning_days: number;
|
||||
max_file_size_mb: number;
|
||||
feature_ai_clause_review: boolean;
|
||||
feature_negotiation_rooms: boolean;
|
||||
}
|
||||
|
||||
async function fetchSettings(): Promise<Record<string, unknown>> {
|
||||
const { data, error } = await supabase.from("app_settings").select("key, value");
|
||||
if (error) throw error;
|
||||
|
||||
const settings: Record<string, unknown> = {};
|
||||
(data || []).forEach((row) => {
|
||||
settings[row.key] = row.value;
|
||||
});
|
||||
return settings;
|
||||
}
|
||||
|
||||
async function logAuditEvent(action: string, userId: string, details: Record<string, unknown>) {
|
||||
await supabase.from("audit_logs").insert({
|
||||
action,
|
||||
entity_type: "settings",
|
||||
entity_id: null,
|
||||
user_id: userId,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
export function AdminSettings() {
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = useAuthStore();
|
||||
|
||||
const { data: settings, isLoading, isError } = useQuery({
|
||||
queryKey: ["app-settings"],
|
||||
queryFn: fetchSettings,
|
||||
});
|
||||
|
||||
const { register, handleSubmit, setValue, watch, reset } = useForm<SettingsForm>({
|
||||
defaultValues: {
|
||||
expiration_warning_days: 60,
|
||||
max_file_size_mb: 5,
|
||||
feature_ai_clause_review: true,
|
||||
feature_negotiation_rooms: true,
|
||||
},
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
if (settings) {
|
||||
reset({
|
||||
expiration_warning_days: (settings.expiration_warning_days as number) ?? 60,
|
||||
max_file_size_mb: (settings.max_file_size_mb as number) ?? 5,
|
||||
feature_ai_clause_review:
|
||||
(settings.features as Record<string, boolean>)?.ai_clause_review ?? true,
|
||||
feature_negotiation_rooms:
|
||||
(settings.features as Record<string, boolean>)?.negotiation_rooms ?? true,
|
||||
});
|
||||
}
|
||||
}, [settings, reset]);
|
||||
|
||||
const saveMutation = useMutation({
|
||||
mutationFn: async (formData: SettingsForm) => {
|
||||
const upserts = [
|
||||
{
|
||||
key: "expiration_warning_days",
|
||||
value: formData.expiration_warning_days as unknown as Record<string, unknown>,
|
||||
updated_at: new Date().toISOString(),
|
||||
updated_by: user!.id,
|
||||
},
|
||||
{
|
||||
key: "max_file_size_mb",
|
||||
value: formData.max_file_size_mb as unknown as Record<string, unknown>,
|
||||
updated_at: new Date().toISOString(),
|
||||
updated_by: user!.id,
|
||||
},
|
||||
{
|
||||
key: "features",
|
||||
value: {
|
||||
ai_clause_review: formData.feature_ai_clause_review,
|
||||
negotiation_rooms: formData.feature_negotiation_rooms,
|
||||
} as unknown as Record<string, unknown>,
|
||||
updated_at: new Date().toISOString(),
|
||||
updated_by: user!.id,
|
||||
},
|
||||
];
|
||||
|
||||
for (const row of upserts) {
|
||||
const { error } = await supabase
|
||||
.from("app_settings")
|
||||
.upsert(row, { onConflict: "key" });
|
||||
if (error) throw error;
|
||||
}
|
||||
|
||||
await logAuditEvent("settings.updated", user!.id, {
|
||||
expiration_warning_days: formData.expiration_warning_days,
|
||||
max_file_size_mb: formData.max_file_size_mb,
|
||||
features: {
|
||||
ai_clause_review: formData.feature_ai_clause_review,
|
||||
negotiation_rooms: formData.feature_negotiation_rooms,
|
||||
},
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["app-settings"] });
|
||||
toast.success("Settings saved successfully.");
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error("Failed to save settings: " + err.message);
|
||||
},
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<Skeleton className="h-32 w-full" />
|
||||
<Skeleton className="h-32 w-full" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <p className="text-destructive">Failed to load settings.</p>;
|
||||
}
|
||||
|
||||
const aiClauseReview = watch("feature_ai_clause_review");
|
||||
const negotiationRooms = watch("feature_negotiation_rooms");
|
||||
|
||||
return (
|
||||
<form onSubmit={handleSubmit((data) => saveMutation.mutate(data))} className="space-y-6">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Contract Settings</CardTitle>
|
||||
<CardDescription>
|
||||
Configure contract-related thresholds and limits.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="grid gap-4 sm:grid-cols-2">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="expiration_warning_days">
|
||||
Expiration Warning (days)
|
||||
</Label>
|
||||
<Input
|
||||
id="expiration_warning_days"
|
||||
type="number"
|
||||
min={1}
|
||||
max={365}
|
||||
{...register("expiration_warning_days", { valueAsNumber: true })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Notify users when contracts expire within this many days.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="max_file_size_mb">Max File Upload Size (MB)</Label>
|
||||
<Input
|
||||
id="max_file_size_mb"
|
||||
type="number"
|
||||
min={1}
|
||||
max={50}
|
||||
{...register("max_file_size_mb", { valueAsNumber: true })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Maximum file size allowed for uploads.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Feature Toggles</CardTitle>
|
||||
<CardDescription>
|
||||
Enable or disable platform features.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>AI Clause Review</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Allow AI-powered analysis of contract clauses using Google Gemini.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={aiClauseReview}
|
||||
onCheckedChange={(checked) => setValue("feature_ai_clause_review", checked)}
|
||||
/>
|
||||
</div>
|
||||
<Separator />
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label>Negotiation Rooms</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Enable real-time negotiation chat rooms for contracts.
|
||||
</p>
|
||||
</div>
|
||||
<Switch
|
||||
checked={negotiationRooms}
|
||||
onCheckedChange={(checked) => setValue("feature_negotiation_rooms", checked)}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<div className="flex justify-end">
|
||||
<Button type="submit" disabled={saveMutation.isPending}>
|
||||
<Save className="mr-2 h-4 w-4" />
|
||||
{saveMutation.isPending ? "Saving..." : "Save Settings"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery } from "@tanstack/react-query";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { format } from "date-fns";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { ScrollArea } from "@/components/ui/scroll-area";
|
||||
import { FileText, Users, Building2, Settings, Activity } from "lucide-react";
|
||||
|
||||
const ACTION_CATEGORIES = [
|
||||
{ value: "all", label: "All Actions" },
|
||||
{ value: "user", label: "User Actions" },
|
||||
{ value: "contract", label: "Contract Actions" },
|
||||
{ value: "company", label: "Company Actions" },
|
||||
{ value: "settings", label: "Settings Actions" },
|
||||
];
|
||||
|
||||
const ENTITY_ICONS: Record<string, React.ReactNode> = {
|
||||
user: <Users className="h-4 w-4" />,
|
||||
contract: <FileText className="h-4 w-4" />,
|
||||
company: <Building2 className="h-4 w-4" />,
|
||||
settings: <Settings className="h-4 w-4" />,
|
||||
};
|
||||
|
||||
function actionBadgeVariant(action: string): "default" | "secondary" | "destructive" | "outline" {
|
||||
if (action.includes("deleted") || action.includes("removed")) return "destructive";
|
||||
if (action.includes("created") || action.includes("added")) return "default";
|
||||
if (action.includes("updated") || action.includes("changed")) return "secondary";
|
||||
return "outline";
|
||||
}
|
||||
|
||||
interface AuditLog {
|
||||
id: string;
|
||||
action: string;
|
||||
entity_type: string | null;
|
||||
entity_id: string | null;
|
||||
user_id: string | null;
|
||||
details: Record<string, unknown> | null;
|
||||
created_at: string;
|
||||
user_name?: string;
|
||||
}
|
||||
|
||||
async function fetchAuditLogs(filter: string): Promise<AuditLog[]> {
|
||||
let query = supabase
|
||||
.from("audit_logs")
|
||||
.select("*")
|
||||
.order("created_at", { ascending: false })
|
||||
.limit(200);
|
||||
|
||||
if (filter !== "all") {
|
||||
query = query.like("action", `${filter}.%`);
|
||||
}
|
||||
|
||||
const { data, error } = await query;
|
||||
if (error) throw error;
|
||||
|
||||
// Fetch profile names for user_ids
|
||||
const userIds = [...new Set((data || []).map((l) => l.user_id).filter(Boolean))] as string[];
|
||||
let nameMap = new Map<string, string>();
|
||||
|
||||
if (userIds.length > 0) {
|
||||
const { data: profiles } = await supabase
|
||||
.from("profiles")
|
||||
.select("id, full_name")
|
||||
.in("id", userIds);
|
||||
|
||||
if (profiles) {
|
||||
nameMap = new Map(profiles.map((p) => [p.id, p.full_name || "Unknown"]));
|
||||
}
|
||||
}
|
||||
|
||||
return (data || []).map((log) => ({
|
||||
...log,
|
||||
details: log.details as Record<string, unknown> | null,
|
||||
user_name: log.user_id ? nameMap.get(log.user_id) || "Unknown" : "System",
|
||||
}));
|
||||
}
|
||||
|
||||
export function AuditLogs() {
|
||||
const [filter, setFilter] = useState("all");
|
||||
|
||||
const { data: logs, isLoading, isError } = useQuery({
|
||||
queryKey: ["audit-logs", filter],
|
||||
queryFn: () => fetchAuditLogs(filter),
|
||||
});
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 6 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-10 w-full" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <p className="text-destructive">Failed to load audit logs.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{logs?.length ?? 0} log entries
|
||||
</p>
|
||||
<Select value={filter} onValueChange={setFilter}>
|
||||
<SelectTrigger className="w-[180px]">
|
||||
<SelectValue placeholder="Filter by type" />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
{ACTION_CATEGORIES.map((cat) => (
|
||||
<SelectItem key={cat.value} value={cat.value}>
|
||||
{cat.label}
|
||||
</SelectItem>
|
||||
))}
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<ScrollArea className="h-[500px] rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead className="w-[180px]">Timestamp</TableHead>
|
||||
<TableHead>Action</TableHead>
|
||||
<TableHead>Performed By</TableHead>
|
||||
<TableHead>Entity</TableHead>
|
||||
<TableHead>Details</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{logs?.map((log) => (
|
||||
<TableRow key={log.id}>
|
||||
<TableCell className="text-xs text-muted-foreground whitespace-nowrap">
|
||||
{format(new Date(log.created_at), "MMM d, yyyy HH:mm")}
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Badge variant={actionBadgeVariant(log.action)}>
|
||||
{log.action.replace(".", " / ")}
|
||||
</Badge>
|
||||
</TableCell>
|
||||
<TableCell className="text-sm">{log.user_name}</TableCell>
|
||||
<TableCell>
|
||||
{log.entity_type && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
{ENTITY_ICONS[log.entity_type] || <Activity className="h-4 w-4" />}
|
||||
<span className="font-mono text-xs">
|
||||
{log.entity_id ? log.entity_id.slice(0, 8) + "..." : "—"}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
</TableCell>
|
||||
<TableCell className="max-w-[200px]">
|
||||
{log.details && Object.keys(log.details).length > 0 ? (
|
||||
<pre className="text-xs text-muted-foreground whitespace-pre-wrap break-all">
|
||||
{JSON.stringify(log.details, null, 1)}
|
||||
</pre>
|
||||
) : (
|
||||
<span className="text-xs text-muted-foreground">—</span>
|
||||
)}
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
))}
|
||||
{(!logs || logs.length === 0) && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={5} className="text-center text-muted-foreground py-8">
|
||||
No audit log entries yet.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,429 @@
|
||||
import { useState } from "react";
|
||||
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||
import { supabase } from "@/integrations/supabase/client";
|
||||
import { useAuthStore } from "@/auth/use-auth-store";
|
||||
import { toast } from "sonner";
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
TableCell,
|
||||
TableHead,
|
||||
TableHeader,
|
||||
TableRow,
|
||||
} from "@/components/ui/table";
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from "@/components/ui/select";
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from "@/components/ui/alert-dialog";
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogFooter,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
} from "@/components/ui/dialog";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Badge } from "@/components/ui/badge";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { Label } from "@/components/ui/label";
|
||||
import { Skeleton } from "@/components/ui/skeleton";
|
||||
import { Trash2, Shield, User, UserPlus } from "lucide-react";
|
||||
|
||||
interface UserWithRole {
|
||||
id: string;
|
||||
full_name: string | null;
|
||||
avatar_url: string | null;
|
||||
email?: string;
|
||||
role: "admin" | "user";
|
||||
role_row_id: string;
|
||||
}
|
||||
|
||||
async function fetchUsersWithRoles(): Promise<UserWithRole[]> {
|
||||
const { data: profiles, error: profilesError } = await supabase
|
||||
.from("profiles")
|
||||
.select("id, full_name, avatar_url");
|
||||
|
||||
if (profilesError) throw profilesError;
|
||||
|
||||
const { data: roles, error: rolesError } = await supabase
|
||||
.from("user_roles")
|
||||
.select("id, user_id, role");
|
||||
|
||||
if (rolesError) throw rolesError;
|
||||
|
||||
const roleMap = new Map(roles?.map((r) => [r.user_id, { role: r.role as "admin" | "user", id: r.id }]));
|
||||
|
||||
return (profiles || []).map((p) => {
|
||||
const roleEntry = roleMap.get(p.id);
|
||||
return {
|
||||
id: p.id,
|
||||
full_name: p.full_name,
|
||||
avatar_url: p.avatar_url,
|
||||
role: roleEntry?.role ?? "user",
|
||||
role_row_id: roleEntry?.id ?? "",
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
async function logAuditEvent(action: string, entityType: string, entityId: string, userId: string, details: Record<string, unknown>) {
|
||||
await supabase.from("audit_logs").insert({
|
||||
action,
|
||||
entity_type: entityType,
|
||||
entity_id: entityId,
|
||||
user_id: userId,
|
||||
details,
|
||||
});
|
||||
}
|
||||
|
||||
export function UserManagement() {
|
||||
const queryClient = useQueryClient();
|
||||
const { user } = useAuthStore();
|
||||
const [updatingUserId, setUpdatingUserId] = useState<string | null>(null);
|
||||
const [addDialogOpen, setAddDialogOpen] = useState(false);
|
||||
const [newEmail, setNewEmail] = useState("");
|
||||
const [newName, setNewName] = useState("");
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [newRole, setNewRole] = useState<"admin" | "user">("user");
|
||||
|
||||
const { data: users, isLoading, isError } = useQuery({
|
||||
queryKey: ["admin-users"],
|
||||
queryFn: fetchUsersWithRoles,
|
||||
});
|
||||
|
||||
const changeRoleMutation = useMutation({
|
||||
mutationFn: async ({ roleRowId, userId, newRole }: { roleRowId: string; userId: string; newRole: "admin" | "user" }) => {
|
||||
const { error } = await supabase
|
||||
.from("user_roles")
|
||||
.update({ role: newRole })
|
||||
.eq("id", roleRowId);
|
||||
if (error) throw error;
|
||||
|
||||
await logAuditEvent("user.role_changed", "user", userId, user!.id, {
|
||||
target_user_id: userId,
|
||||
new_role: newRole,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin-users"] });
|
||||
toast.success("User role updated successfully.");
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error("Failed to update role: " + err.message);
|
||||
},
|
||||
onSettled: () => setUpdatingUserId(null),
|
||||
});
|
||||
|
||||
const deleteUserMutation = useMutation({
|
||||
mutationFn: async ({ userId }: { userId: string }) => {
|
||||
// Delete role, then profile (cascade will handle auth cleanup if configured)
|
||||
const { error: roleError } = await supabase
|
||||
.from("user_roles")
|
||||
.delete()
|
||||
.eq("user_id", userId);
|
||||
if (roleError) throw roleError;
|
||||
|
||||
const { error: profileError } = await supabase
|
||||
.from("profiles")
|
||||
.delete()
|
||||
.eq("id", userId);
|
||||
if (profileError) throw profileError;
|
||||
|
||||
await logAuditEvent("user.deleted", "user", userId, user!.id, {
|
||||
target_user_id: userId,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin-users"] });
|
||||
toast.success("User removed successfully.");
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error("Failed to remove user: " + err.message);
|
||||
},
|
||||
});
|
||||
|
||||
const addUserMutation = useMutation({
|
||||
mutationFn: async ({ email, name, password, role }: { email: string; name: string; password: string; role: "admin" | "user" }) => {
|
||||
// Sign up the new user via Supabase Auth
|
||||
const { data: signUpData, error: signUpError } = await supabase.auth.signUp({
|
||||
email,
|
||||
password,
|
||||
options: {
|
||||
data: { full_name: name },
|
||||
},
|
||||
});
|
||||
if (signUpError) throw signUpError;
|
||||
if (!signUpData.user) throw new Error("User creation failed");
|
||||
|
||||
const newUserId = signUpData.user.id;
|
||||
|
||||
// Update the profile name (trigger creates profile, but name may not be set)
|
||||
await supabase
|
||||
.from("profiles")
|
||||
.update({ full_name: name })
|
||||
.eq("id", newUserId);
|
||||
|
||||
// If role should be admin, update (trigger defaults to 'user' for non-first users)
|
||||
if (role === "admin") {
|
||||
await supabase
|
||||
.from("user_roles")
|
||||
.update({ role: "admin" })
|
||||
.eq("user_id", newUserId);
|
||||
}
|
||||
|
||||
await logAuditEvent("user.created", "user", newUserId, user!.id, {
|
||||
email,
|
||||
name,
|
||||
role,
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries({ queryKey: ["admin-users"] });
|
||||
toast.success("User created successfully. They can log in with the provided credentials.");
|
||||
setAddDialogOpen(false);
|
||||
setNewEmail("");
|
||||
setNewName("");
|
||||
setNewPassword("");
|
||||
setNewRole("user");
|
||||
},
|
||||
onError: (err: Error) => {
|
||||
toast.error("Failed to create user: " + err.message);
|
||||
},
|
||||
});
|
||||
|
||||
const handleAddUser = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!newEmail.trim() || !newPassword.trim()) {
|
||||
toast.error("Email and password are required.");
|
||||
return;
|
||||
}
|
||||
if (newPassword.length < 6) {
|
||||
toast.error("Password must be at least 6 characters.");
|
||||
return;
|
||||
}
|
||||
addUserMutation.mutate({
|
||||
email: newEmail.trim(),
|
||||
name: newName.trim(),
|
||||
password: newPassword,
|
||||
role: newRole,
|
||||
});
|
||||
};
|
||||
|
||||
const handleRoleChange = (userEntry: UserWithRole, newRole: "admin" | "user") => {
|
||||
if (newRole === userEntry.role) return;
|
||||
setUpdatingUserId(userEntry.id);
|
||||
changeRoleMutation.mutate({
|
||||
roleRowId: userEntry.role_row_id,
|
||||
userId: userEntry.id,
|
||||
newRole,
|
||||
});
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
{Array.from({ length: 4 }).map((_, i) => (
|
||||
<Skeleton key={i} className="h-12 w-full" />
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (isError) {
|
||||
return <p className="text-destructive">Failed to load users.</p>;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{users?.length ?? 0} registered user(s)
|
||||
</p>
|
||||
<Dialog open={addDialogOpen} onOpenChange={setAddDialogOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size="sm">
|
||||
<UserPlus className="mr-2 h-4 w-4" />
|
||||
Add User
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<form onSubmit={handleAddUser}>
|
||||
<DialogHeader>
|
||||
<DialogTitle>Add New User</DialogTitle>
|
||||
<DialogDescription>
|
||||
Create a new account. The user can log in with these credentials.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<div className="space-y-4 py-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-email">Email</Label>
|
||||
<Input
|
||||
id="new-email"
|
||||
type="email"
|
||||
placeholder="user@example.com"
|
||||
value={newEmail}
|
||||
onChange={(e) => setNewEmail(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-name">Full Name</Label>
|
||||
<Input
|
||||
id="new-name"
|
||||
type="text"
|
||||
placeholder="John Smith"
|
||||
value={newName}
|
||||
onChange={(e) => setNewName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-password">Password</Label>
|
||||
<Input
|
||||
id="new-password"
|
||||
type="password"
|
||||
placeholder="Min. 6 characters"
|
||||
value={newPassword}
|
||||
onChange={(e) => setNewPassword(e.target.value)}
|
||||
required
|
||||
minLength={6}
|
||||
/>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="new-role">Role</Label>
|
||||
<Select value={newRole} onValueChange={(val) => setNewRole(val as "admin" | "user")}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
</div>
|
||||
<DialogFooter>
|
||||
<Button type="submit" disabled={addUserMutation.isPending}>
|
||||
{addUserMutation.isPending ? "Creating..." : "Create User"}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</form>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</div>
|
||||
|
||||
<div className="rounded-md border">
|
||||
<Table>
|
||||
<TableHeader>
|
||||
<TableRow>
|
||||
<TableHead>User</TableHead>
|
||||
<TableHead>Role</TableHead>
|
||||
<TableHead className="w-[100px] text-right">Actions</TableHead>
|
||||
</TableRow>
|
||||
</TableHeader>
|
||||
<TableBody>
|
||||
{users?.map((u) => {
|
||||
const isSelf = u.id === user?.id;
|
||||
return (
|
||||
<TableRow key={u.id}>
|
||||
<TableCell>
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="flex h-8 w-8 items-center justify-center rounded-full bg-muted">
|
||||
{u.role === "admin" ? (
|
||||
<Shield className="h-4 w-4 text-primary" />
|
||||
) : (
|
||||
<User className="h-4 w-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium leading-none">
|
||||
{u.full_name || "Unnamed User"}
|
||||
{isSelf && (
|
||||
<Badge variant="outline" className="ml-2 text-xs">
|
||||
You
|
||||
</Badge>
|
||||
)}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground mt-1 font-mono">
|
||||
{u.id.slice(0, 8)}...
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</TableCell>
|
||||
<TableCell>
|
||||
<Select
|
||||
value={u.role}
|
||||
onValueChange={(val) => handleRoleChange(u, val as "admin" | "user")}
|
||||
disabled={isSelf || updatingUserId === u.id}
|
||||
>
|
||||
<SelectTrigger className="w-[120px]">
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="admin">Admin</SelectItem>
|
||||
<SelectItem value="user">User</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</TableCell>
|
||||
<TableCell className="text-right">
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
disabled={isSelf}
|
||||
title={isSelf ? "You cannot remove yourself" : "Remove user"}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 text-destructive" />
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Remove user?</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
This will remove <strong>{u.full_name || "this user"}</strong> and
|
||||
their role from the system. This action cannot be undone.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={() => deleteUserMutation.mutate({ userId: u.id })}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
Remove
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
);
|
||||
})}
|
||||
{(!users || users.length === 0) && (
|
||||
<TableRow>
|
||||
<TableCell colSpan={3} className="text-center text-muted-foreground py-8">
|
||||
No users found.
|
||||
</TableCell>
|
||||
</TableRow>
|
||||
)}
|
||||
</TableBody>
|
||||
</Table>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+1
-1
@@ -14,7 +14,7 @@ interface IndustryChartProps {
|
||||
const industryBarChartConfig = {
|
||||
contracts: {
|
||||
label: "Contracts",
|
||||
color: "#fb923c",
|
||||
color: "hsl(var(--chart-2))",
|
||||
},
|
||||
};
|
||||
|
||||
+4
-4
@@ -3,7 +3,7 @@ import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
|
||||
import { FileText, CheckCircle, XCircle, AlertTriangle, DollarSign, Calendar } from "lucide-react";
|
||||
import { Contract } from "@/data/types";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { STATUS_COLORS } from "@/lib/constants";
|
||||
|
||||
|
||||
interface StatsCardsProps {
|
||||
contracts: Contract[];
|
||||
@@ -44,7 +44,7 @@ export const StatsCards = ({ contracts }: StatsCardsProps) => {
|
||||
<Card onClick={() => navigate('/contracts?status=Active')} className="cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Active Contracts</CardTitle>
|
||||
<CheckCircle className="h-4 w-4" style={{ color: STATUS_COLORS.Active }} />
|
||||
<CheckCircle className="h-4 w-4 text-green-600 dark:text-green-400" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{activeContracts.length}</div>
|
||||
@@ -62,7 +62,7 @@ export const StatsCards = ({ contracts }: StatsCardsProps) => {
|
||||
<Card onClick={() => navigate('/contracts')} className="cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Expiring Soon (60d)</CardTitle>
|
||||
<AlertTriangle className="h-4 w-4 text-orange-500" />
|
||||
<AlertTriangle className="h-4 w-4 text-orange-500 dark:text-orange-400" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{expiringSoon.length}</div>
|
||||
@@ -71,7 +71,7 @@ export const StatsCards = ({ contracts }: StatsCardsProps) => {
|
||||
<Card onClick={() => navigate('/contracts?status=Expired')} className="cursor-pointer hover:bg-muted/50 transition-colors">
|
||||
<CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
|
||||
<CardTitle className="text-sm font-medium">Expired Contracts</CardTitle>
|
||||
<XCircle className="h-4 w-4" style={{ color: STATUS_COLORS.Expired }} />
|
||||
<XCircle className="h-4 w-4 text-red-600 dark:text-red-400" />
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="text-2xl font-bold">{expiredContracts.length}</div>
|
||||
+1
-1
@@ -45,7 +45,7 @@ export const StatusChart = ({ contracts }: StatusChartProps) => {
|
||||
<div className="flex flex-wrap justify-center gap-x-4 gap-y-2 mt-4 text-sm">
|
||||
{chartData.map((entry) => (
|
||||
<div key={entry.name} className="flex items-center gap-2">
|
||||
<span className="h-3 w-3 rounded-full" style={{ backgroundColor: STATUS_COLORS[entry.name] || '#ccc' }}></span>
|
||||
<span className="h-3 w-3 rounded-full" style={{ backgroundColor: STATUS_COLORS[entry.name] || 'hsl(var(--muted-foreground))' }}></span>
|
||||
<span>{entry.name}</span>
|
||||
</div>
|
||||
))}
|
||||
+1
-1
@@ -13,7 +13,7 @@ interface VendorChartProps {
|
||||
const barChartConfig = {
|
||||
contracts: {
|
||||
label: "Contracts",
|
||||
color: "#16a34a",
|
||||
color: "hsl(var(--primary))",
|
||||
},
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user