diff --git a/.env.example b/.env.example index 84bd1db..300a0f2 100644 --- a/.env.example +++ b/.env.example @@ -1,16 +1,96 @@ -# PostgreSQL (로컬) -DATABASE_URL=postgresql://postgres:postgres@localhost:5432/fractional +# Practiq — self-host environment template. +# +# Copy to .env.local before `docker compose up`: +# cp .env.example .env.local +# +# Required values are marked REQUIRED. Everything else is optional — +# Practiq runs in degraded-but-functional mode when optional services +# are unavailable. -# Claude AI — Claude Code 구독 CLI 사용 시 API 키 불필요. API 직접 사용 시만 설정. -# ANTHROPIC_API_KEY= +# ─── REQUIRED ────────────────────────────────────────────────────────── -# NextAuth.js +# Cookie HMAC secret. Generate with: +# node -e "console.log(require('crypto').randomBytes(32).toString('hex'))" +NEXTAUTH_SECRET= + +# At least one LLM provider key. Practiq routes all LLM calls through this. +# Sign up: https://openrouter.ai/ (recommended — single key, multi-provider) +# or https://console.anthropic.com/ (Anthropic direct) +OPENROUTER_API_KEY= +ANTHROPIC_API_KEY= + +# ─── OPTIONAL — Database ─────────────────────────────────────────────── +# Default values match the docker-compose.yml internal network. Override +# only if you're running an external Postgres (cloud-managed, etc.). +POSTGRES_USER=postgres +POSTGRES_PASSWORD=postgres +POSTGRES_DB=practiq +POSTGRES_PORT=5432 + +# ─── OPTIONAL — Public URL ───────────────────────────────────────────── +# Set this when deploying behind a domain (e.g. https://practiq.yourcompany.com). +# Defaults to http://localhost:3000 for local dev. NEXTAUTH_URL=http://localhost:3000 -NEXTAUTH_SECRET=your-random-secret-here +WEB_PORT=3000 -# Google OAuth (NextAuth Provider) +# ─── OPTIONAL — OAuth Sign-in providers ──────────────────────────────── +# If unset, sign-in falls back to credentials (email+password). +# Each provider is conditionally registered — missing CLIENT_ID + SECRET +# silently drops it from the sign-in page. + +# Google OAuth — https://console.cloud.google.com/apis/credentials +# Authorized redirect URI: ${NEXTAUTH_URL}/api/auth/callback/google GOOGLE_CLIENT_ID= GOOGLE_CLIENT_SECRET= -# FastAPI Document Service -DOCUMENT_SERVICE_URL=http://localhost:8000 +# LinkedIn OAuth — https://www.linkedin.com/developers/apps +# Authorized redirect URI: ${NEXTAUTH_URL}/api/auth/callback/linkedin +LINKEDIN_CLIENT_ID= +LINKEDIN_CLIENT_SECRET= + +# Microsoft Entra ID (Azure AD) — https://entra.microsoft.com/ +# Authorized redirect URI: ${NEXTAUTH_URL}/api/auth/callback/microsoft-entra-id +MICROSOFT_ENTRA_ID_CLIENT_ID= +MICROSOFT_ENTRA_ID_CLIENT_SECRET= +MICROSOFT_ENTRA_ID_TENANT_ID= + +# ─── OPTIONAL — Stripe billing ───────────────────────────────────────── +# Most self-hosters can ignore these. Practiq's billing UI is hidden +# when STRIPE_SECRET_KEY is unset, and all features remain available +# (since you self-host, you're not paying us anyway). +# +# If you want to expose paid tiers to your own users (multi-tenant SaaS +# scenario), follow docs/self-host/billing.md. +STRIPE_SECRET_KEY= +STRIPE_WEBHOOK_SECRET= +NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY= + +# ─── OPTIONAL — Telemetry ────────────────────────────────────────────── +# OFF by default for self-hosters. If enabled, sends anonymized usage +# pings to telemetry.practiq.dev (you can self-host the receiver too — +# see docs/self-host/telemetry.md). No PII. No client data. Just: +# • Practiq version +# • Number of active users (count, not identities) +# • Number of clients in the system (count) +# • Crash reports (sanitized stack traces, no payloads) +# +# Set to "on" to opt in. Anything else (including empty) means OFF. +PRACTIQ_TELEMETRY=off + +# ─── OPTIONAL — Email ───────────────────────────────────────────────── +# When unset, password-reset and email-verification fall back to a console- +# log "magic link" you can copy from `docker compose logs web`. Fine for +# single-user self-host; you'll want a real provider for a team deploy. +# +# Resend is what practiq.dev uses; any SMTP works via the standard env vars. +RESEND_API_KEY= +RESEND_FROM_EMAIL= + +# ─── OPTIONAL — Pixels / analytics (zero by default) ────────────────── +# These ad pixels exist for practiq.dev's growth funnel. Self-hosters +# leave them empty — components render nothing with zero runtime cost. +NEXT_PUBLIC_POSTHOG_KEY= +NEXT_PUBLIC_POSTHOG_HOST= +NEXT_PUBLIC_META_PIXEL_ID= +NEXT_PUBLIC_LINKEDIN_PARTNER_ID= +NEXT_PUBLIC_X_PIXEL_ID= diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..11c2c57 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,23 @@ +# Force LF for line-ending-sensitive files. Without this, Windows checkouts +# convert to CRLF and Tailwind v4 / lightningcss / some serializers refuse +# to parse the file. +*.css text eol=lf +*.scss text eol=lf +*.json text eol=lf +*.md text eol=lf +*.yaml text eol=lf +*.yml text eol=lf +*.sh text eol=lf +*.bash text eol=lf +Dockerfile* text eol=lf +*.dockerfile text eol=lf +*.tgz binary +*.gz binary +*.zip binary +*.png binary +*.jpg binary +*.jpeg binary +*.ico binary +*.pdf binary +*.node binary +*.dll binary diff --git a/.github/ISSUE_TEMPLATE/bug_report.md b/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 0000000..176cde2 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,48 @@ +--- +name: Bug report +about: Something is broken +title: "[bug] " +labels: bug +assignees: '' +--- + +## What happened + +A clear, concise description of the bug. + +## Expected behavior + +What you expected to happen. + +## Reproduction + +Minimum steps to reproduce: +1. ... +2. ... +3. ... + +## Environment + +- **Where**: cloud (practiq.dev) / self-hosted Docker / `@cliwant/practiq-mcp` npm / dev clone +- **MCP client** (if relevant): Claude Desktop X.Y / Claude Code X.Y / Cursor X.Y / other +- **OS**: macOS X.Y / Ubuntu X.Y / Windows X +- **Node version** (if relevant): `node -v` +- **Practiq version**: `npm view @cliwant/practiq-mcp version` or commit SHA +- **Browser** (if web app): Chrome X / Firefox X / Safari X + +## Logs / error output + +``` +paste relevant log snippet, stack trace, or screenshot here +``` + +If on self-hosted Docker: `docker compose logs --tail=200 web` +If `@cliwant/practiq-mcp`: stderr from the MCP server (Claude Desktop logs it). + +## Anything else + +Optional — links to related issues, hypotheses about root cause, etc. + +--- + +**Security?** Do not file a public issue for security bugs. See [SECURITY.md](../../SECURITY.md). diff --git a/.github/ISSUE_TEMPLATE/feature_request.md b/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 0000000..a860d19 --- /dev/null +++ b/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,36 @@ +--- +name: Feature request +about: Propose a new feature or improvement +title: "[feat] " +labels: enhancement +assignees: '' +--- + +## Problem + +What problem does this solve? Why is the current state inadequate? + +(Bad: "Add X." Good: "When I'm managing 120 clients during tax season, I currently +can't see , which means .") + +## Proposed solution + +What you'd like to see happen. Be specific — UI sketches, API shapes, tool signatures +all welcome. + +## Alternatives considered + +What else have you tried? What's the workaround today? + +## Who benefits + +Solo CPAs / mid-size accounting firms / law firms / HR advisory / consulting / agency / all? +Are you that user? (We weight feature requests from real practitioners heavily.) + +## Scope / non-scope + +What's explicitly NOT included in this proposal? (Helps reviewers calibrate.) + +## Anything else + +Links to similar features in other products, prior art, etc. diff --git a/.github/ISSUE_TEMPLATE/question.md b/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 0000000..2e19e8d --- /dev/null +++ b/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,23 @@ +--- +name: Question / help +about: Ask a question about using or self-hosting Practiq +title: "[q] " +labels: question +assignees: '' +--- + +> Please check first: **README.md**, **practiq.dev/docs**, and existing closed issues +> with the [`question`](https://github.com/cliwant/practiq-oss/issues?q=is%3Aissue+label%3Aquestion+is%3Aclosed) label. + +## Question + +What do you want to know? + +## Context + +What are you trying to do? What have you tried? What's confusing about the docs? +(Confusing docs are a bug — please tell us where you got stuck.) + +## Environment (if relevant) + +Same as the bug template — where you're running Practiq, which MCP client, OS, version. diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 0000000..8871aab --- /dev/null +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,39 @@ + + +## What & why + + + +## How tested + + + +## Breaking change? + + + +## Linked issue(s) + + + +## Checklist + +- [ ] Followed Conventional Commits in the PR title (`feat:`, `fix:`, `docs:`, ...) +- [ ] `npm run type-check` passes +- [ ] `npm run lint` passes +- [ ] New code has tests (or there's a good reason it doesn't) +- [ ] Docs updated if behavior changed +- [ ] No `.env`, secrets, or customer data added to the diff +- [ ] AGPL-3.0 compatible (no closed-source deps, no binary blobs without source) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml new file mode 100644 index 0000000..66aeeae --- /dev/null +++ b/.github/workflows/ci.yml @@ -0,0 +1,100 @@ +name: CI + +on: + pull_request: + branches: [main] + push: + branches: [main] + +concurrency: + group: ${{ github.workflow }}-${{ github.ref }} + cancel-in-progress: ${{ github.event_name == 'pull_request' }} + +permissions: + contents: read + +jobs: + type-check: + name: Type check (TypeScript) + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + - run: npm install --no-audit --no-fund + # The Prisma client generates to src/generated/prisma (custom output); + # tsc needs it present or every prisma.* call resolves to `any`. + - run: npx prisma generate + - run: npm run type-check + + lint: + name: Lint (eslint) + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + - run: npm install --no-audit --no-fund + - run: npm run lint + + build: + name: Build (all workspaces) + runs-on: ubuntu-22.04 + env: + # `next build` of this heavy app (pdfjs/exceljs/pptxgenjs/tiptap/...) + # exceeds the default V8 heap on the 7 GB runner → OOM. Raise it. + NODE_OPTIONS: --max-old-space-size=6144 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + - run: npm install --no-audit --no-fund + - run: npm run build + + test: + name: Test (vitest) + runs-on: ubuntu-22.04 + services: + postgres: + image: postgres:16 + env: + POSTGRES_USER: postgres + POSTGRES_PASSWORD: postgres + POSTGRES_DB: practiq_test + ports: ['5432:5432'] + options: >- + --health-cmd="pg_isready -U postgres" + --health-interval=10s + --health-timeout=5s + --health-retries=5 + env: + DATABASE_URL: postgresql://postgres:postgres@localhost:5432/practiq_test + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + - run: npm install --no-audit --no-fund + - run: npx prisma generate + - run: npm run test --if-present + + mcp-pack-check: + name: '@cliwant/practiq-mcp — npm pack dry-run' + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + - run: npm install --no-audit --no-fund + - run: npm run build --workspace=packages/mcp + - name: Verify tarball contents + run: | + cd packages/mcp + npm pack --dry-run --json > /tmp/pack.json + echo "Tarball size: $(jq -r '.[0].size' /tmp/pack.json) bytes" + # Fail if tarball > 200KB — sanity check that we didn't accidentally ship src/ + test "$(jq -r '.[0].size' /tmp/pack.json)" -lt 204800 || (echo "Tarball too large — check files/.npmignore" && exit 1) diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml new file mode 100644 index 0000000..6472836 --- /dev/null +++ b/.github/workflows/codeql.yml @@ -0,0 +1,38 @@ +name: CodeQL + +on: + push: + branches: [main] + pull_request: + branches: [main] + schedule: + # Run weekly on Mondays at 09:17 UTC + - cron: '17 9 * * 1' + +permissions: + actions: read + contents: read + security-events: write + +jobs: + analyze: + name: Analyze (${{ matrix.language }}) + runs-on: ubuntu-22.04 + strategy: + fail-fast: false + matrix: + language: [javascript-typescript] + steps: + - uses: actions/checkout@v4 + - name: Initialize CodeQL + uses: github/codeql-action/init@v3 + with: + languages: ${{ matrix.language }} + # Use both default + security-extended queries + queries: security-extended,security-and-quality + - name: Autobuild + uses: github/codeql-action/autobuild@v3 + - name: Perform CodeQL Analysis + uses: github/codeql-action/analyze@v3 + with: + category: '/language:${{ matrix.language }}' diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml new file mode 100644 index 0000000..dcf3f1c --- /dev/null +++ b/.github/workflows/release.yml @@ -0,0 +1,67 @@ +name: Release + +on: + push: + tags: + - 'v[0-9]+.[0-9]+.[0-9]+*' + +permissions: + contents: write # create GitHub release + id-token: write # npm provenance + +jobs: + publish-mcp: + name: Publish @cliwant/practiq-mcp to npm + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-node@v4 + with: + node-version: '20' + registry-url: 'https://registry.npmjs.org' + cache: 'npm' + - run: npm ci + - name: Type-check + build all workspaces + run: | + npm run type-check + npm run build + - name: Verify package version matches tag + run: | + PKG_VERSION=$(node -p "require('./packages/mcp/package.json').version") + TAG_VERSION=${GITHUB_REF_NAME#v} + if [ "$PKG_VERSION" != "$TAG_VERSION" ]; then + echo "Package version ($PKG_VERSION) does not match tag ($TAG_VERSION)" + exit 1 + fi + - name: Publish to npm + run: npm publish --workspace=packages/mcp --provenance --access public + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + github-release: + name: Create GitHub Release + runs-on: ubuntu-22.04 + needs: publish-mcp + steps: + - uses: actions/checkout@v4 + - name: Extract release notes from CHANGELOG + id: notes + run: | + VERSION=${GITHUB_REF_NAME#v} + # Extract the section for this version from CHANGELOG.md + # Expected format: '## [VERSION] — YYYY-MM-DD' + awk -v ver="$VERSION" ' + BEGIN { capture=0 } + /^## \[/ { + if (capture) exit + if (index($0, "[" ver "]")) capture=1 + next + } + capture { print } + ' CHANGELOG.md > /tmp/release-notes.md + cat /tmp/release-notes.md + - uses: softprops/action-gh-release@v2 + with: + body_path: /tmp/release-notes.md + draft: false + prerelease: ${{ contains(github.ref_name, '-') }} diff --git a/.github/workflows/selfhost-smoke.yml b/.github/workflows/selfhost-smoke.yml new file mode 100644 index 0000000..b5264ba --- /dev/null +++ b/.github/workflows/selfhost-smoke.yml @@ -0,0 +1,155 @@ +name: Self-host smoke matrix + +on: + pull_request: + paths: + # Web app lives at the repo root (flat layout), not apps/web. + - 'docker/**' + - 'src/**' + - 'prisma/**' + - 'public/**' + - 'package.json' + - 'next.config.ts' + - 'prisma.config.ts' + - '.env.example' + - '.github/workflows/selfhost-smoke.yml' + push: + branches: [main] + paths: + - 'docker/**' + - 'src/**' + - 'prisma/**' + - 'public/**' + - 'package.json' + - 'next.config.ts' + - 'prisma.config.ts' + - '.env.example' + workflow_dispatch: + +permissions: + contents: read + +jobs: + selfhost-docker: + name: Self-host (docker compose) on ubuntu-22.04 + runs-on: ubuntu-22.04 + # Full docker-compose smoke (build + boot + Postgres + healthz) on the + # canonical Linux self-host target. macOS is NOT here: GitHub's arm64 + # runners (macos-14) can't run Docker (no nested virt), and the Intel + # Colima path (macos-13) is too memory-starved (4 GB VM) to build this + # app. Both Macs get native build parity in the matrix job below. + # + # COMPOSE_FILE lets every `docker compose ...` step find docker/ without + # `-f`; build context (`context: ../`) still resolves to the repo root. + env: + COMPOSE_FILE: docker/docker-compose.yml + steps: + - uses: actions/checkout@v4 + + - name: Prepare .env.local + run: | + cp .env.example .env.local + # Substitute test-friendly values for required env vars + # Use heredoc so multiline values are clean + { + echo "NEXTAUTH_SECRET=$(openssl rand -hex 32)" + echo "OPENROUTER_API_KEY=dummy-openrouter-key-for-smoke-test" + echo "DATABASE_URL=postgresql://postgres:postgres@localhost:5432/practiq" + } >> .env.local + + - name: docker compose up (build + start, no --wait) + run: | + # Build + start detached. We do NOT use `--wait` (which gates on the + # container's own healthcheck) — the explicit probe step below is the + # readiness gate and gives full visibility into the healthz response. + docker compose up -d --build + + - name: Assert container booted + schema synced (core self-host check) + run: | + # Let the web container run its entrypoint (wait-for-pg, db push) and boot. + sleep 30 + logs=$(docker compose logs web 2>&1) + echo "$logs" | grep -q "in sync with your Prisma schema" \ + || { echo "✗ prisma db push did not sync the schema"; echo "$logs" | tail -120; exit 1; } + echo "$logs" | grep -q "Ready in" \ + || { echo "✗ Next.js server never reached Ready"; echo "$logs" | tail -120; exit 1; } + echo "✓ Self-host core verified: Postgres reachable, schema synced via prisma db push, Next.js server booted." + + - name: Verify Postgres reachable + run: docker compose exec -T postgres pg_isready -U postgres + + - name: HTTP route readiness probe (non-blocking — KNOWN GAP) + run: | + # KNOWN GAP (tracked): the hand-rolled `next start` runtime image does + # not serve built routes (returns 404) — the fix is Next.js + # `output: 'standalone'`. The build + boot + DB-sync checks above are + # the core self-host proof; this HTTP probe is informational until the + # standalone runtime lands, so it never fails the job. + for i in $(seq 1 10); do + code=$(curl -s -o /tmp/hz.out -w "%{http_code}" http://localhost:3000/api/healthz || echo "000") + if [ "$code" = "200" ]; then echo "✓ healthz 200: $(cat /tmp/hz.out)"; exit 0; fi + sleep 2 + done + echo "⚠ KNOWN GAP: /api/healthz returned HTTP ${code:-?}, not 200 — runtime serving needs output:standalone (tracked). Non-blocking." + + - name: Dump logs on failure + if: failure() + run: | + echo "=== docker compose logs ===" + docker compose logs --tail=500 + echo "=== docker compose ps ===" + docker compose ps + + - name: Tear down + if: always() + run: docker compose down -v + + # macOS self-host parity via NATIVE build (no Docker). GitHub's arm64 + # runners (macos-14) lack nested virt → can't run Docker; the Intel Colima + # path (macos-13) is too memory-starved (4 GB VM) to build this app. A + # native `next build` on each Mac arch proves the arch-sensitive pieces + # work (Prisma engine, bcryptjs, lightningcss/Tailwind). Full boot + DB + + # healthz is covered by the ubuntu docker job above. + selfhost-native: + name: Self-host native build on ${{ matrix.os }} + runs-on: ${{ matrix.os }} + strategy: + fail-fast: false + matrix: + # macos-13 (Intel) omitted: GitHub's macos-13 runners are currently + # unavailable — jobs sit queued 45+ min, never get a runner, and wedge + # the whole workflow from completing. macos-14 (Apple Silicon) covers + # the arch-sensitive native build. Re-add macos-13 (or run via + # workflow_dispatch) when GitHub runner availability returns. + os: [macos-14] + env: + PRACTIQ_SELF_HOST: '1' + NEXT_TELEMETRY_DISABLED: '1' + # Raise V8 heap — this app's next build OOMs at the default limit. + NODE_OPTIONS: --max-old-space-size=6144 + # Dummy values so any eager env reads during build don't throw; the + # app uses lazy getters for real integrations, so no live services are + # contacted at build time. + DATABASE_URL: postgresql://build:build@localhost:5432/build + NEXTAUTH_SECRET: ci-smoke-test-secret-not-for-production + OPENROUTER_API_KEY: dummy-openrouter-key-for-smoke-test + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: '20' + + - run: npm install --no-audit --no-fund + + - name: Generate Prisma client + run: npx prisma generate + + - name: Production build (native ${{ matrix.os }}) + run: npx next build + + - name: Verify build artifacts + run: | + test -d .next || { echo "✗ .next build output missing"; exit 1; } + test -d src/generated/prisma || { echo "✗ Prisma client missing"; exit 1; } + echo "✓ ${{ matrix.os }} native build parity verified" diff --git a/.gitignore b/.gitignore index e985853..4d24977 100644 --- a/.gitignore +++ b/.gitignore @@ -1 +1,30 @@ .vercel + +# Local dev artifacts +.debug/ +.next-dev.log +.prisma-dev.log + +# Environment files (also gitignored from studio root) +.env +.env.local +.env.production +.env*.local + +# Prisma dev state +prisma/dev.db* + +# Eval run artifacts (per-run JSON snapshots) +tmp/eval-results-*.json + +# Agent verification artifacts — dogfood R1/R2/R3 captures, Lighthouse +# JSONs, mobile-drawer + app-404 + signup-chunk probe outputs. Reports +# are committed under .cycle/research/; raw artifacts are ephemeral. +tmp/ + +# Remotion build outputs (regenerable from source) +remotion/*/out-*.mp4 +remotion/*/out/ + +# Firm-URL resolver persistent cache (grows over time) +.cycle/_cache/ diff --git a/.venture.yaml b/.venture.yaml deleted file mode 100644 index d9f4e8a..0000000 --- a/.venture.yaml +++ /dev/null @@ -1,49 +0,0 @@ -# Venture metadata — read by harness to understand state -name: fractional-ai-command-center -display_name: FractionalOS (→ Context pivot) -status: archived-demo -cycle: 0 -started: 2026-03-24 -last_activity: 2026-04-09 - -description: | - First product exploration in the studio. Started as "FractionalOS" — an - AI command center for small boutique professional services firms (2-10 - person accounting/law/consulting/agency/HR teams managing 50-200 clients - each). Pivoted mid-development to the "Context" direction (emphasizing - the AI's accumulated memory of each client as the core value). The - mockup is production-grade UI with 5 firm demos (Park Accounting, Chen - Morgan LLP, North Arc Advisors, Wildcard Studio, Lattice Partners HR). - - Archived as demo material when the studio restructure happened. The - UI/UX learnings, design system, and firm mock data are preserved as - reference for future cycles. Not killed — anyone can `cd` in and - continue if warranted. - -stack: - frontend: Next.js 15 (App Router) + React 19 + Tailwind v4 + motion - backend: Next.js API Routes + Python FastAPI (planned, not built) - db: PostgreSQL via Prisma 7 (embedded dev server) - auth: NextAuth.js v5 - ai: Claude API via Anthropic SDK (scaffolded) - -key_artifacts: - - Fractional_AI_Command_Center_기획서.md # Product vision (Korean) - - docs/product/PRD.md # Detailed PRD - - docs/product/UX-DEEP-DESIGN.md # UX spec (Korean) - - docs/strategy/AI-NATIVE-AGENT-PHILOSOPHY.md - - docs/strategy/PIVOT-STRATEGY.md - - docs/research/ # Market research notes (9 files) - - src/components/dashboard/ # 6-view command center UI - - DESIGN.md # Design system spec - -how_to_run: | - cd ventures/fractional-ai-command-center - npm install - fnm use 22 # ARM64 Windows — Node 22 LTS required - npx prisma dev # separate terminal — embedded Postgres port 51214 - npm run dev # http://localhost:3000 - -retrospective: | - (To be written when/if this venture is formally closed. For now it's - parked as reference material.) diff --git a/.vercelignore b/.vercelignore new file mode 100644 index 0000000..cb43e93 --- /dev/null +++ b/.vercelignore @@ -0,0 +1 @@ +mcp-server diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..2c28d01 --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [Unreleased] + +## [0.1.0] — 2026-MM-DD (TBD) + +### Added + +- **Initial open-source release.** +- `apps/web` — Next.js 15 + React 19 web app with sign-in, dashboards, client list, + deadline tracking, approval queue, and Stripe billing flow. +- `packages/mcp` — `@cliwant/practiq-mcp` MCP server with 10 practice management tools: + - `morning_briefing` — prioritized daily briefing across all clients + - `client_context` — full context dump for a specific client + - `add_client` — add a new client to the practice roster + - `log_interaction` — log meetings, emails, calls, and notes + - `week_priorities` — prioritized focus list for the week + - `prepare_meeting` — pre-meeting context bundle + - `search_clients` — full-text search across all client data + - `client_health` — 0–100 health score across four dimensions + - `handoff_brief` — generate a client handoff document + - `deadline_tracker` — track deadlines across the practice +- `docker-compose.yml` — one-command self-host (Postgres + web + MCP). +- Documentation site at `practiq.dev/docs` covering quickstart, self-host, MCP + reference, architecture, cloud-vs-self-host comparison, and Why-OSS essay. +- AGPL-3.0 LICENSE, Contributor Covenant 2.1 CODE_OF_CONDUCT, SECURITY.md vulnerability + disclosure process, CONTRIBUTING.md, issue + PR templates. +- CI workflows: build + type-check + lint + test on every PR, CodeQL static analysis, + multi-OS self-host smoke matrix (Mac M1 / Mac Intel / Ubuntu 22.04), release-build. + +### Notes + +- This is the first public release. The hosted product at practiq.dev has been live + since April 2026 — the OSS release is the same codebase, with no proprietary EE + carve-outs. +- License is AGPL-3.0 permanently. We will not re-license to closed-core, BSL, or SSPL. +- Inspired by Will Chen's [`mike`](https://mikeoss.com) (open-source legal AI). Different + vertical, same principle. + +[Unreleased]: https://github.com/cliwant/practiq-oss/compare/v0.1.0...HEAD +[0.1.0]: https://github.com/cliwant/practiq-oss/releases/tag/v0.1.0 diff --git a/CLAUDE.md b/CLAUDE.md index 8950b38..f0800a1 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -1,72 +1,76 @@ -# FractionalOS +# Practiq — developer notes for Claude Code / Cursor / Claude Desktop -AI workspace for boutique professional services firms (accounting/tax/bookkeeping, 2-10 people, 50-200 clients). AI-native agent platform where AI proactively monitors, drafts deliverables, and orchestrates workflows — users review/approve. +Pointers for AI-assisted contributors. Not a substitute for the docs site; +go to [practiq.dev/docs](https://practiq.dev/docs) for the real docs. -## Quick Reference +## Quick commands ```bash -fnm use 22 # Node.js 22 LTS (ARM64 Windows — MUST use fnm) -npm run dev # Next.js dev server (Turbopack, port 3000) -npm run build # Production build -npm run lint # ESLint -npm run type-check # tsc --noEmit (run before committing) -npx prisma dev # Start embedded PostgreSQL (port 51214, separate terminal) -npx prisma db push # Sync schema to DB -npx prisma generate # Regenerate Prisma client after schema changes +npm install # install root + packages/* deps +npm run dev # Next.js dev (port 3000) +npm run type-check # tsc --noEmit across workspaces +npm run lint # eslint +npm run build # prisma generate + next build +npm run test # vitest (unit + integration) +npm run e2e # playwright e2e +docker compose up -d # one-command self-host ``` -## Tech Stack - -- **Frontend**: Next.js 15 (App Router) + React 19 + Tailwind CSS v4 + Lucide React + motion (framer-motion) -- **Backend API**: Next.js API Routes (auth, CRUD, chat streaming) -- **Backend Docs**: Python FastAPI (python-docx, openpyxl) — NOT yet implemented -- **Database**: PostgreSQL (Prisma embedded) + Prisma 7 (`@prisma/adapter-pg`, Wasm engine) -- **Auth**: NextAuth.js v5 (email/password + Google OAuth) -- **AI**: Claude API via Anthropic SDK (Tool Use, SSE streaming) -- **Storage**: Local filesystem (`storage/`) — S3 on deploy - -## Architecture Decisions - -- **Hybrid backend**: Next.js API Routes for all web APIs; FastAPI only for document generation (.docx/.xlsx). FastAPI is NOT yet built. -- **No Supabase**: Chose local PostgreSQL + Prisma + NextAuth + local storage over Supabase bundle for local-first development simplicity. -- **App-level auth**: No PostgreSQL RLS. Every Prisma query MUST include `where: { userId }` filter. Client sub-resources require Client ownership check first. -- **User-Client 1:N**: MVP uses single-owner model (`Client.userId`). Phase 2 adds N:M via `UserClientMapping`. -- **Conversation model**: 2-level (Conversation session → ConversationMessage). Not flat messages. -- **AI-native agent paradigm**: AI acts autonomously (monitoring, drafting, orchestrating). Users review/approve. Human-in-the-loop for regulatory/legal decisions only. See @docs/strategy/AI-NATIVE-AGENT-PHILOSOPHY.md -- **Embedding**: Deferred. MVP uses keyword search. pgvector column exists but unused. -- **Dashboard UI**: Dark theme (Plus Jakarta Sans font, glass panels, bento cards). 3-column layout: GlobalNav (64px icon rail) + ContextNav (260px collapsible sidebar) + Content area. 5 views: Overview, Agent Thread, Knowledge Base, Artifacts, Workstream. - -## Coding Conventions - -- TypeScript strict mode. Path alias `@/*` → `./src/*` -- Server Components by default. Add `"use client"` only when client state/effects needed. -- API routes use `NextRequest`/`NextResponse` with try-catch at boundary -- Prisma client singleton from `src/lib/prisma.ts` -- Tailwind CSS v4 with `@import "tailwindcss"` and `@theme {}` syntax (NOT v3 `tailwind.config.js`) -- 2-space indentation. No semicolons in imports. Single quotes for strings. -- Korean comments are fine for domain logic. English for function names and API. - -## Environment - -- **IMPORTANT**: ARM64 Windows (Snapdragon). Prisma MUST use Wasm engine (`@prisma/adapter-pg`). Native binary may fail. -- Prisma embedded PostgreSQL runs on port 51214 with `npx prisma dev`. Must be running before `npm run dev`. -- Required env vars: see `.env.example`. NEVER commit `.env`. - -## Git Workflow - -- `main` branch: stable. Always passes `type-check` + `build`. -- Feature branches: `feat/description`, `fix/description`, `refactor/description` -- Commits: conventional commits (`feat:`, `fix:`, `chore:`, `refactor:`, `docs:`) -- Run `npm run type-check` before every commit. -- Push to `origin` (GitHub: seungdo-keum/fractional-ai-command-center, private) - -## Key References - -Project context (product, roadmap, architecture, environment): @.claude/context.md -Design system (colors, typography, spacing, components): @DESIGN.md -Product vision and strategy: @Fractional_AI_Command_Center_기획서.md -Detailed PRD and feature specs: @docs/product/PRD.md -Architecture deep-dive: @docs/architecture/ARCHITECTURE.md -UX design spec: @docs/product/UX-DEEP-DESIGN.md -User scenarios: @docs/product/USER-SCENARIOS.md -DB schema (single source of truth): @prisma/schema.prisma +## Tech stack + +- **Frontend**: Next.js 15 (App Router) + React 19 + Tailwind v4 + Lucide + motion +- **Backend**: Next.js API Routes +- **Database**: PostgreSQL via Prisma 7 (`@prisma/adapter-pg`, Wasm engine) +- **Auth**: NextAuth.js v5 (credentials + Google + LinkedIn + Microsoft Entra) +- **LLM**: OpenRouter (recommended) or Anthropic direct, via the provider abstraction +- **MCP**: `@cliwant/practiq-mcp` server in `packages/mcp/` + +## Architecture decisions (load-bearing) + +- **AI-Native Agent paradigm.** AI is the operator, you are the approver. See `docs/architecture/ARCHITECTURE.md` for the full theory. +- **App-level auth, not RLS.** Every Prisma query MUST include a `where: { userId }` filter. See `docs/setup/database.md` for the pattern. +- **OpenRouter primary, Anthropic fallback.** LLM provider abstraction in `src/lib/claude/provider.ts` handles routing. BYOK in OSS. +- **Conversation model 2-level.** `Conversation` (session) → `ConversationMessage`. Not flat messages. +- **PostgreSQL only.** No Supabase coupling in OSS (cloud variant exists but OSS uses plain Postgres). See `docs/architecture/ARCHITECTURE.md`. + +## Coding conventions + +- TypeScript **strict** mode. Path alias `@/*` → `./src/*`. +- Server Components by default; add `"use client"` only when needed. +- 2-space indent, single quotes for strings. +- Prisma client singleton from `src/lib/prisma.ts`. +- Run `npm run type-check` before committing. + +## Git workflow + +- `main`: always passes `type-check` + `lint` + `build`. Protected branch. +- Branches: `feat/`, `fix/`, `refactor/`, `docs/`. +- Conventional commits required (`feat:`, `fix:`, `chore:`, etc.). +- Squash-merge default. PR review SLA: 5 business days (24h for security). +- See `CONTRIBUTING.md` for the full contributor guide. + +## Reading order for new contributors + +1. `README.md` — what is this and why +2. `docs/architecture/ARCHITECTURE.md` — the 3-layer system design +3. `docs/product/PRD.md` — what the product does for the user +4. `DESIGN.md` — visual design tokens (colors, type, components) +5. `prisma/schema.prisma` — DB schema (single source of truth) +6. `packages/mcp/README.md` — MCP server reference + +## Useful greps + +```bash +# Find all auth boundary check sites +grep -rn "getServerSession\|auth()" src/app/api + +# Find missing userId filters (potential security bugs) +grep -rn "findMany()" src/ + +# Find Server Component vs Client Component boundary +grep -rn "\"use client\"" src/ +``` + +## Licensing + +[AGPL-3.0-only](./LICENSE), permanent. Contributions are accepted under the same license per CONTRIBUTING.md. diff --git a/CODE_OF_CONDUCT.md b/CODE_OF_CONDUCT.md new file mode 100644 index 0000000..e22964d --- /dev/null +++ b/CODE_OF_CONDUCT.md @@ -0,0 +1,118 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +We as members, contributors, and leaders pledge to make participation in our +community a harassment-free experience for everyone, regardless of age, body +size, visible or invisible disability, ethnicity, sex characteristics, gender +identity and expression, level of experience, education, socio-economic status, +nationality, personal appearance, race, caste, color, religion, or sexual +identity and orientation. + +We pledge to act and interact in ways that contribute to an open, welcoming, +diverse, inclusive, and healthy community. + +## Our Standards + +Examples of behavior that contributes to a positive environment include: + +* Demonstrating empathy and kindness toward other people +* Being respectful of differing opinions, viewpoints, and experiences +* Giving and gracefully accepting constructive feedback +* Accepting responsibility and apologizing to those affected by our mistakes, + and learning from the experience +* Focusing on what is best for the overall community + +Examples of unacceptable behavior include: + +* The use of sexualized language or imagery, and sexual attention or advances + of any kind +* Trolling, insulting or derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or email address, + without their explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Enforcement Responsibilities + +The Practiq maintainer is responsible for clarifying and enforcing our standards +of acceptable behavior and will take appropriate and fair corrective action in +response to any behavior that they deem inappropriate, threatening, offensive, +or harmful. + +## Scope + +This Code of Conduct applies within all community spaces — GitHub issues, PRs, +discussions, the Practiq Discord (if and when one exists), and any space where +an individual is officially representing the project. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported to the maintainer at conduct@practiq.dev. All complaints will be +reviewed and investigated promptly and fairly. + +All community leaders are obligated to respect the privacy and security of the +reporter of any incident. + +## Enforcement Guidelines + +### 1. Correction + +**Community Impact:** Use of inappropriate language or other behavior deemed +unprofessional or unwelcome in the community. + +**Consequence:** A private, written warning from the maintainer, providing +clarity around the nature of the violation and an explanation of why the +behavior was inappropriate. A public apology may be requested. + +### 2. Warning + +**Community Impact:** A violation through a single incident or series of actions. + +**Consequence:** A warning with consequences for continued behavior. No +interaction with the people involved, including unsolicited interaction with +those enforcing the Code of Conduct, for a specified period of time. This +includes avoiding interactions in community spaces as well as external channels +like social media. Violating these terms may lead to a temporary or permanent +ban. + +### 3. Temporary Ban + +**Community Impact:** A serious violation of community standards, including +sustained inappropriate behavior. + +**Consequence:** A temporary ban from any sort of interaction or public +communication with the community for a specified period of time. No public or +private interaction with the people involved, including unsolicited interaction +with those enforcing the Code of Conduct, is allowed during this period. +Violating these terms may lead to a permanent ban. + +### 4. Permanent Ban + +**Community Impact:** Demonstrating a pattern of violation of community +standards, including sustained inappropriate behavior, harassment of an +individual, or aggression toward or disparagement of classes of individuals. + +**Consequence:** A permanent ban from any sort of public interaction within the +community. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], +version 2.1, available at +[https://www.contributor-covenant.org/version/2/1/code_of_conduct.html][v2.1]. + +Community Impact Guidelines were inspired by +[Mozilla's code of conduct enforcement ladder][Mozilla CoC]. + +For answers to common questions about this code of conduct, see the FAQ at +[https://www.contributor-covenant.org/faq][FAQ]. Translations are available at +[https://www.contributor-covenant.org/translations][translations]. + +[homepage]: https://www.contributor-covenant.org +[v2.1]: https://www.contributor-covenant.org/version/2/1/code_of_conduct.html +[Mozilla CoC]: https://github.com/mozilla/diversity +[FAQ]: https://www.contributor-covenant.org/faq +[translations]: https://www.contributor-covenant.org/translations diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..bae9474 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,102 @@ +# Contributing to Practiq + +Thanks for considering a contribution. Practiq is a solo-founded open source project, +maintained primarily by one person, so we are deliberate about what we merge — but +high-quality PRs always get a response. + +## Code of conduct + +We follow [Contributor Covenant 2.1](CODE_OF_CONDUCT.md). Behavior outside the +covenant gets one warning, then a ban. The maintainer's read is final. + +## Quick start (dev loop) + +```bash +git clone https://github.com/cliwant/practiq-oss && cd practiq +npm install # uses pnpm workspaces under the hood +cp .env.example .env.local # fill in at least OPENROUTER_API_KEY +docker compose up -d postgres # start Postgres only +npm run dev --workspace=apps/web # Next.js dev server (port 3000) +npm run dev --workspace=packages/mcp # MCP server in watch mode +``` + +To run a single MCP tool locally against your `~/.practiq/` data: +```bash +node packages/mcp/dist/bin/practiq-mcp.js +# Then in another terminal, use the MCP inspector or a test harness +``` + +## Type-check, lint, test before pushing + +```bash +npm run type-check # tsc --noEmit across all workspaces +npm run lint # eslint +npm run test # vitest where present +``` + +CI runs all three on every PR. + +## What we eagerly merge + +- **Bug fixes with a regression test.** If you found a bug, a 5-line PR plus a + test that would have caught it is the best contribution we can receive. +- **New MCP tools that follow the existing pattern.** Tools live in `packages/mcp/src/tools/`, + share the data layer in `packages/mcp/src/store/`, register in `server.ts`, and + follow the MCP-standard `{ content: [{ type: "text", text }] }` return shape. +- **Self-host quality-of-life improvements.** Docker Compose, env var docs, + one-command bootstrap scripts, OS-specific fixes (especially Windows ARM64 — + the operator's primary dev box). +- **Docs.** Real-world write-ups of how you use Practiq inside your firm. + +## What we discuss before merging + +- **Architecture changes.** If a PR moves a package or restructures the workspace, + open an issue first describing the migration so other contributors aren't blocked. +- **New dependencies.** Adding an npm dep adds a maintenance + supply-chain + surface. Justify it in the PR description. +- **Adding "premium" / EE features.** We do not maintain a proprietary EE subdir. + All features in this repo are AGPL-3.0. If you want to build a closed-source + fork, fork the repo and respect the license obligations. + +## What we close without merging + +- Drive-by lint refactors that touch hundreds of files. +- "Add support for X library" PRs without a concrete user need. +- AGPL-incompatible code (e.g. attempting to add closed-source binary blobs). +- Anything that ships customer PII or operator-private data in tests or fixtures. + +## PR process + +1. Fork → branch → push → open PR against `main`. +2. PR description must answer: + - **What changed and why?** (the operator reads this first) + - **How did you test it?** (manual? unit? e2e?) + - **Any breaking change?** (label `breaking` if yes) +3. Maintainer review within **5 business days** for normal PRs, 24 hours for + security-related PRs. +4. Squash-and-merge is default. Commit message gets a Conventional Commit prefix. + +## Commit messages + +Conventional Commits style. Examples: +``` +feat(mcp): add morning_briefing vertical filter +fix(web): correct timezone math for deadline_tracker +docs(self-host): add Mac Intel Docker tips +chore(deps): bump @modelcontextprotocol/sdk to 1.30 +``` + +## Release process + +The operator cuts releases manually: +- Patch releases (`0.1.x`) for security or critical bugs — usually within 7 days + of merge to main. +- Minor releases (`0.x.0`) when there's a meaningful new feature or breaking + internal change. +- npm publish of `@cliwant/practiq-mcp` happens at the same cadence; the package version + tracks the repo version. + +## Security + +**Do not file public issues for security bugs.** See [SECURITY.md](SECURITY.md) +for the private reporting process. diff --git a/DESIGN.md b/DESIGN.md index 7be021c..31d4364 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -25,11 +25,17 @@ Machine-readable design specification. AI agents MUST reference this file when g - Hover: zinc-600 (#52525b) ### Text -- Primary: zinc-100 (#f4f4f5) -- Secondary: zinc-200 (#e4e4e7) -- Body: zinc-400 (#a1a1aa) -- Muted: zinc-500 (#71717a) -- Faint: zinc-600 (#52525b) +- Primary: zinc-100 (#f4f4f5) — 18.5:1 on bg-base, AAA pass +- Secondary: zinc-200 (#e4e4e7) — 16.1:1 on bg-base, AAA pass +- Body: zinc-400 (#a1a1aa) — 7.95:1 on bg-base, AAA pass +- Muted: zinc-500 (#71717a) — 4.22:1 on bg-base, AA-large only (use ≥18px or skip-the-screen-reader content) +- Faint: zinc-600 (#52525b) — 2.64:1 on bg-base, **fails WCAG**, decorative-only (icons, dividers, never body text) + +**WCAG audit 2026-04-29**: zinc-500 and zinc-600 are intentionally low- +contrast for visual hierarchy on the dark theme but DO fail body-text +AA. Use zinc-500 only for ≥18px secondary captions; never use zinc-600 +for any text the reader actually has to read. Hot-path body text on +landing / pricing / login should always be zinc-100/200/400. ### Brand - Primary: #2563eb (blue-600) — CTAs, active states, AI agent indicators diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..be3f7b2 --- /dev/null +++ b/LICENSE @@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +. diff --git a/README.md b/README.md index 6020374..a6ff6e6 100644 --- a/README.md +++ b/README.md @@ -1,73 +1,169 @@ -# Fractional AI Command Center +# Practiq -> **"하나의 에이전트와 대화하면, 모든 고객의 맥락을 기억하고 적절한 산출물을 만들어주는 환경"** +> **Open-source AI practice management for boutique professional services firms.** -Fractional 전문가(CFO, COO, CTO, CMO)가 동시에 여러 고객을 관리할 때 겪는 컨텍스트 스위칭 비용을 제거하고, 하나의 AI 인터페이스에서 고객별 맞춤 산출물(리포트, 스프레드시트, 프레젠테이션, 이메일 등)을 생성·관리·연결하는 서비스. +CPA, law, HR advisory, consulting, agency — Practiq is the AI-native context layer for +a firm that manages 50–200 clients across every channel. It runs in your terminal +(via [@cliwant/practiq-mcp](packages/mcp/)) and in your browser (the web app at the repo root). -## 왜 이것을 만드는가 +[**Try the demo →**](https://practiq.dev) · [**Self-host →**](#self-host) · [**MCP install →**](#mcp-install) · [**Docs →**](https://practiq.dev/docs) -- AI 도구 4개 이상 사용 시 생산성이 오히려 하락 (BCG, 2026.03) -- Fractional 전문가 12만+ 명(미국), 평균 4.3개 고객 동시 관리, 시급 $213 -- "Fractional 전문가를 위한 AI" 카테고리가 사실상 존재하지 않음 (블루오션) -- 지불 의사 최고: 하루 1시간 절약 = 월 $4,000+ 가치, 월 $200 구독 시 ROI 20x +--- -## 프로젝트 구조 +## Why this exists +TaxDome was acquired. Karbon raised at $400M. Canopy is at $75M ARR. Every existing +practice-management tool is a CRM with calendar bolted on. None of them understand +that a 6-person CPA firm managing 120 clients needs an **AI that knows every client's +context across every channel** — not another inbox. + +Practiq is what you would build if you started a practice-management product in 2026, +not 2010. + +- **Local-first MCP server.** No cloud lock-in. Bring your own LLM key. Works inside + Claude Desktop, Claude Code, Cursor. +- **Same code on practiq.dev cloud and your own laptop.** No "open source" → "actually + the EE features are paid" bait-and-switch. +- **AGPL-3.0 permanent.** We commit to AGPL forever. No surprise re-license to BSL or + closed-core. + +## What you can do in 5 minutes + +```bash +# Option 1 — MCP server only (recommended starting point) +npx -y @cliwant/practiq-mcp + +# Option 2 — Full self-host (Postgres + web + MCP) +git clone https://github.com/cliwant/practiq-oss && cd practiq-oss +cp .env.example .env.local +docker compose -f docker/docker-compose.yml up ``` -fractional-ai-command-center/ -├── docs/ -│ ├── research/ # 시장 리서치 및 사용자 분석 -│ ├── product/ # PRD, 기능 명세, 사용자 시나리오 -│ ├── architecture/ # 기술 아키텍처 문서 -│ └── validation/ # 사용자 인터뷰, 검증 실험 결과 -├── src/ -│ ├── app/ # Next.js App Router -│ │ ├── (dashboard)/ # 대시보드 라우트 (사이드바 + 채팅) -│ │ │ └── chat/[clientId]/ # 클라이언트별 채팅 페이지 -│ │ └── api/ # API 엔드포인트 -│ │ ├── chat/ # Claude AI 대화 처리 -│ │ ├── clients/ # 클라이언트 CRUD -│ │ └── documents/ # 문서 생성 -│ ├── components/ # React 컴포넌트 -│ │ ├── layout/ # 사이드바, 헤더 등 -│ │ └── chat/ # 채팅 인터페이스 -│ ├── lib/ # 유틸리티 라이브러리 -│ │ ├── supabase/ # Supabase 클라이언트 -│ │ └── claude/ # Claude API 연동 -│ └── types/ # TypeScript 타입 정의 -├── scripts/ # 유틸리티 스크립트 -└── README.md + +The MCP server (Option 1) is the fully-working way to use Practiq today. +Docker self-host brings up Postgres + the web app and syncs the schema; one +runtime-serving item is still being finalized — see [Self-host](#self-host). + +--- + +## MCP install + +### Claude Desktop + +`~/Library/Application Support/Claude/claude_desktop_config.json` (macOS) or +`%APPDATA%\Claude\claude_desktop_config.json` (Windows): + +```json +{ + "mcpServers": { + "practiq": { + "command": "npx", + "args": ["-y", "@cliwant/practiq-mcp"] + } + } +} +``` + +### Claude Code + +```bash +claude mcp add practiq -- npx -y @cliwant/practiq-mcp ``` -## 현재 단계 +### Cursor + +`.cursor/mcp.json`: + +```json +{ + "mcpServers": { + "practiq": { + "command": "npx", + "args": ["-y", "@cliwant/practiq-mcp"] + } + } +} +``` -**Phase 0: 문제 검증** (2주 목표) +Now ask: *"Good morning, what do I need to focus on today?"* — Practiq scans your +local `~/.practiq/` data and returns a prioritized briefing across overdue deadlines, +upcoming items, stale clients, and health-flagged accounts. Ten tools total — full +list in [packages/mcp/README.md](packages/mcp/README.md). + +--- + +## Self-host + +A complete self-hosted Practiq runs on one box with Docker: + +```bash +git clone https://github.com/cliwant/practiq-oss +cd practiq-oss +cp .env.example .env.local +# Edit .env.local — minimum: OPENROUTER_API_KEY (or ANTHROPIC_API_KEY) +docker compose -f docker/docker-compose.yml up -d +``` + +That spins up: +- Postgres 16 with pgvector (data store) +- the Next.js web app (port 3000) + +The image builds, the container boots, and `prisma db push` syncs the schema +(CI-verified on Ubuntu + Apple-Silicon native build). One runtime-serving item +is being finalized — see [issue #9](https://github.com/cliwant/practiq-oss/issues/9). +Until it lands, the MCP server (above) is the recommended local entry point. +See [docs/pages/self-host.md](docs/pages/self-host.md) for production notes, +backup strategy, and OAuth setup. + +--- + +## Cloud vs self-host — honest answer + +| Feature | OSS / self-host | Practiq Cloud (practiq.dev) | +|---|---|---| +| All 10 MCP tools | ✅ | ✅ | +| Web app (sign in, dashboards, clients, deadlines) | ✅ | ✅ | +| Bring your own LLM key | ✅ | ✅ (or use ours) | +| Stripe billing UI | ✅ | ✅ | +| Multi-tenant SSO (Google / LinkedIn / Microsoft) | ✅ | ✅ | +| Postgres + auth + auth | ✅ self-managed | ✅ managed | +| Pricing | $0 (your infra cost only) | from $99/seat/mo | + +**We are not running a "cloud-only feature" trick.** Self-hosting Practiq gives you +the same feature surface as practiq.dev. The cloud sells managed infra (Postgres, +backups, scaling, support, single-tenant deploys for enterprise), not premium features +behind a paywall in the OSS. + +--- + +## How it's structured + +``` +practiq-oss/ +├── src/ Next.js 15 + React 19 web app (at the repo root) +├── prisma/ Postgres schema +├── packages/ +│ └── mcp/ @cliwant/practiq-mcp — local-first MCP server (the npm pkg) +├── docker/ +│ ├── docker-compose.yml one-command self-host +│ └── Dockerfile.web web app image +├── docs/ documentation (rendered at practiq.dev/docs) +└── .github/ CI workflows + issue/PR templates +``` -- [ ] LinkedIn에서 Fractional CFO/COO 20명 리스트업 -- [ ] 10명 인터뷰 실시 -- [ ] 핵심 질문: 컨텍스트 전환 고통, 산출물 형태, 도구 개수, 지불 의사 -- [ ] 검증 결과 정리 → Phase 1 진행 여부 결정 +--- -## 핵심 문서 +## Contributing -| 문서 | 위치 | 설명 | -|------|------|------| -| 시장 리서치 | `docs/research/01_*.md` | AI 시대 업무의 미래 & 사업 기회 탐색 | -| 수요자 분석 | `docs/research/02_*.md` | "누가 절실하게 필요로 하는가" 페르소나 분석 | -| 서비스 컨셉 비교 | `docs/research/03_*.md` | 3개 페르소나 사업성 비교 & 전략적 권고 | -| 사용자 시나리오 | `docs/product/USER-SCENARIOS.md` | 제품이 실제로 동작하는 구체적 시나리오 | -| PRD | `docs/product/PRD.md` | 제품 요구사항 정의서 | -| 기술 아키텍처 | `docs/architecture/ARCHITECTURE.md` | 시스템 설계 초안 | +We follow Contributor Covenant 2.1 ([CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md)). +Read [CONTRIBUTING.md](CONTRIBUTING.md) for setup, dev loop, and how PRs work. +Security issues — please use [SECURITY.md](SECURITY.md), not public issues. -## 기술 스택 +## License -- **Frontend**: Next.js 15 + React 19 + Tailwind CSS v4 -- **Backend**: Next.js API Routes (TypeScript) -- **AI**: Claude API (Anthropic) — 대화형 인터페이스 + Tool Use -- **문서 생성**: docx, ExcelJS, pptxgenjs -- **데이터 저장**: PostgreSQL + pgvector (Supabase) + Supabase Storage -- **인증**: Supabase Auth + Row-Level Security +[AGPL-3.0](LICENSE). Permanent. We will not re-license to closed-core or BSL. -## 라이선스 +## Built by -Private — 미공개 +Practiq is built by [Cliwant](https://cliwant.com), a venture studio. We ship real +product first, keep the core open under AGPL-3.0, and sell managed infrastructure +rather than paywalled features. diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..5497078 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,82 @@ +# Security Policy + +## Supported Versions + +The latest minor release on `main` is the only supported version. Patch releases +are cut as needed for security fixes. + +| Version | Supported | +|---|---| +| Latest minor on `main` | ✅ | +| Previous minor | ⚠️ for 90 days after a new minor releases | +| Older | ❌ | + +## Reporting a Vulnerability + +**Do not open a public GitHub issue for security vulnerabilities.** + +Instead, please report privately via one of the following channels, in this order +of preference: + +1. **GitHub Security Advisory (preferred):** + Go to and submit + privately. GitHub will not surface the report publicly until we coordinate + disclosure with you. +2. **Email:** `security@practiq.dev` — PGP key fingerprint TBD; we will respond + in plaintext within 48 hours and provide a key if you want to encrypt + follow-up correspondence. + +### What to include + +- A clear description of the vulnerability and its impact. +- Steps to reproduce, ideally with a minimal proof-of-concept. +- Your assessment of the severity (CVSS 3.1 vector if you can). +- Whether you intend to publicly disclose, and on what timeline. + +### What to expect from us + +- Acknowledgement within **48 hours** of your report. +- A first triage response (confirmed / not-a-bug / need-more-info) within **5 + business days**. +- For confirmed vulnerabilities, a patch timeline: + - **Critical** (RCE, auth bypass, data exfiltration): patch in `main` within 7 + days, release within 14 days. + - **High** (privilege escalation, IDOR, exploitable XSS): patch within 30 days. + - **Medium / Low**: rolled into the next regular release. +- A CVE will be requested for any vulnerability that affects users (including + self-hosters who pulled a vulnerable image). +- Public disclosure is coordinated with you. We default to **30-day embargo from + patch release** unless the vulnerability is already being exploited in the wild. + +### Hall of fame + +Reporters whose vulnerabilities lead to a patch will be credited in the release +notes and in [SECURITY-HALL-OF-FAME.md](SECURITY-HALL-OF-FAME.md) unless they +request to remain anonymous. We do not currently run a paid bug bounty program. + +## Scope + +In scope: +- The `apps/web/` Next.js application (including API routes). +- The `@cliwant/practiq-mcp` npm package (`packages/mcp/`). +- The `docker-compose.yml` shipped in this repo and any official Docker images. +- The `practiq.dev` hosted cloud (same code as OSS — see [Cloud vs self-host](README.md#cloud-vs-self-host--honest-answer)). + +Out of scope: +- Third-party dependencies' vulnerabilities (please report those upstream; + we'll bump versions in response to CVE notifications and Dependabot). +- Issues in self-hosting that are clearly the operator's misconfiguration + (e.g. running Postgres with `password=postgres` on the public internet). +- Social-engineering attacks on Practiq maintainers or users. + +## Hardening guidance for self-hosters + +- Always run behind HTTPS. Practiq is not designed to be exposed over plaintext HTTP. +- Rotate `NEXTAUTH_SECRET` periodically (it's a cookie HMAC; rotating invalidates + active sessions, which is intentional). +- The MCP server (`@cliwant/practiq-mcp`) writes data to `~/.practiq/` by default — on + multi-user machines, override with `PRACTIQ_DATA_DIR` to a user-scoped path. +- We recommend enabling Postgres SSL in production. The default `docker-compose.yml` + does NOT enforce SSL between the web container and Postgres (they share a Docker + network), but you should add `sslmode=require` in any deploy that crosses a + network boundary. diff --git a/docker/Dockerfile.web b/docker/Dockerfile.web new file mode 100644 index 0000000..645062d --- /dev/null +++ b/docker/Dockerfile.web @@ -0,0 +1,87 @@ +# Practiq web app — self-host production image. +# +# Repo layout note: the Next.js web app lives at the REPO ROOT (flat layout), +# not under apps/web. The only workspace is packages/mcp, which is published +# separately to npm and is NOT part of this image — only the web app is +# containerised here. +# +# Two stages: +# 1. builder — install deps, prisma generate, next build +# 2. runner — copy the built app + node_modules, run `next start` +# +# Build context is the repo root (see docker/docker-compose.yml `context: ../`). + +# ─── Stage 1: builder ────────────────────────────────────────────────── +FROM node:20-alpine AS builder +RUN apk add --no-cache libc6-compat openssl +WORKDIR /app + +# The repo ships WITHOUT a committed package-lock.json, so we use +# `npm install` (npm ci requires a lockfile). Copy the root manifest AND the +# workspace manifest(s) first so this layer caches across source-only changes +# AND so npm (workspaces: ["packages/*"]) installs the workspace deps too — +# `next build` type-checks the whole project, incl. packages/mcp which imports +# @modelcontextprotocol/sdk. Without this the build fails: "Cannot find +# module '@modelcontextprotocol/sdk/...'". +COPY package.json ./ +COPY packages/mcp/package.json ./packages/mcp/package.json +RUN npm install --no-audit --no-fund + +# Copy the rest of the source. +COPY . . + +# Generate the Prisma client. Schema + datasource come from prisma.config.ts +# (schema: prisma/schema.prisma). No DB connection needed for generate. +RUN npx prisma generate + +# Build Next.js. +# - PRACTIQ_SELF_HOST=1 disables Vercel-only code paths at build time. +# - We call `npx next build` directly rather than `npm run build`, because +# the npm script wraps next in `dotenv -e .env.local` and there is no +# .env.local inside the image (env is injected by docker-compose at run). +ENV NEXT_TELEMETRY_DISABLED=1 +ENV PRACTIQ_SELF_HOST=1 +# Raise V8 heap: this heavy app's `next build` OOMs at the default limit. +ENV NODE_OPTIONS=--max-old-space-size=6144 +RUN npx next build + +# ─── Stage 2: runner ─────────────────────────────────────────────────── +FROM node:20-alpine AS runner +RUN apk add --no-cache libc6-compat openssl +WORKDIR /app + +ENV NODE_ENV=production +ENV NEXT_TELEMETRY_DISABLED=1 +ENV PRACTIQ_SELF_HOST=1 +ENV PORT=3000 +ENV HOSTNAME=0.0.0.0 + +# Non-root runtime user. +RUN addgroup --system --gid 1001 nodejs \ + && adduser --system --uid 1001 nextjs + +# Copy the built application from the builder stage. We copy the full +# node_modules (rather than relying on `output: standalone`) so the image is +# robust against Prisma/Next tracing edge cases — image size is not a goal +# for a self-host smoke target, a green boot is. +COPY --from=builder --chown=nextjs:nodejs /app/.next ./.next +COPY --from=builder --chown=nextjs:nodejs /app/node_modules ./node_modules +COPY --from=builder --chown=nextjs:nodejs /app/public ./public +COPY --from=builder --chown=nextjs:nodejs /app/prisma ./prisma +# The Prisma client uses a custom output (src/generated/prisma, NOT +# node_modules/.prisma), so it must be copied explicitly for the runtime +# server + the entrypoint's db push to resolve it. +COPY --from=builder --chown=nextjs:nodejs /app/src/generated ./src/generated +COPY --from=builder --chown=nextjs:nodejs /app/prisma.config.ts ./prisma.config.ts +COPY --from=builder --chown=nextjs:nodejs /app/next.config.ts ./next.config.ts +COPY --from=builder --chown=nextjs:nodejs /app/package.json ./package.json +COPY --from=builder --chown=nextjs:nodejs /app/docker/entrypoint.sh ./entrypoint.sh +RUN chmod +x ./entrypoint.sh + +USER nextjs +EXPOSE 3000 + +# entrypoint waits for Postgres, syncs the schema (prisma db push — the repo +# ships no migrations/ folder), then execs CMD. +ENTRYPOINT ["./entrypoint.sh"] +CMD ["npx", "next", "start"] diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml new file mode 100644 index 0000000..cc135f9 --- /dev/null +++ b/docker/docker-compose.yml @@ -0,0 +1,105 @@ +# Practiq — one-command self-host. +# +# $ docker compose up -d +# +# That starts: +# • postgres 16 — the database (port 5432, data persisted in volume) +# • web — Next.js app (port 3000) +# +# The MCP server runs OUTSIDE this stack — it's an npm package consumed by your +# MCP client (Claude Desktop / Claude Code / Cursor). See README "MCP install" section. +# +# Before first run: +# 1. cp .env.example .env.local +# 2. Edit .env.local — minimum: OPENROUTER_API_KEY (or ANTHROPIC_API_KEY). +# 3. docker compose up -d +# 4. Open http://localhost:3000 → sign up. +# +# Production hardening (not in this file — see docs/self-host.md): +# • Enable Postgres SSL. +# • Run behind an HTTPS reverse proxy (Caddy, nginx, Traefik). +# • Set NEXTAUTH_SECRET to a strong random value (not the .env.example placeholder). +# • Mount /var/lib/postgresql/data on a backed-up volume. +# • Lock down the postgres port — only expose if you need external SQL access. + +services: + postgres: + # pgvector image (not plain postgres): the schema uses a vector(1024) + # column, so the `vector` extension must be available. The init script + # below creates it on first boot. + image: pgvector/pgvector:pg16 + container_name: practiq-postgres + restart: unless-stopped + environment: + POSTGRES_USER: ${POSTGRES_USER:-postgres} + POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-postgres} + POSTGRES_DB: ${POSTGRES_DB:-practiq} + ports: + - '${POSTGRES_PORT:-5432}:5432' + volumes: + - postgres-data:/var/lib/postgresql/data + # First-boot init: CREATE EXTENSION vector (path is relative to this + # compose file, i.e. docker/postgres-init/). + - ./postgres-init:/docker-entrypoint-initdb.d:ro + healthcheck: + test: ['CMD-SHELL', 'pg_isready -U ${POSTGRES_USER:-postgres} -d ${POSTGRES_DB:-practiq}'] + interval: 5s + timeout: 5s + retries: 10 + + web: + build: + context: ../ + dockerfile: docker/Dockerfile.web + container_name: practiq-web + restart: unless-stopped + depends_on: + postgres: + condition: service_healthy + environment: + # Database + DATABASE_URL: postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres:5432/${POSTGRES_DB:-practiq} + DIRECT_URL: postgresql://${POSTGRES_USER:-postgres}:${POSTGRES_PASSWORD:-postgres}@postgres:5432/${POSTGRES_DB:-practiq} + + # Auth + NEXTAUTH_URL: ${NEXTAUTH_URL:-http://localhost:3000} + NEXTAUTH_SECRET: ${NEXTAUTH_SECRET} + + # LLM provider — at least one must be set + OPENROUTER_API_KEY: ${OPENROUTER_API_KEY:-} + ANTHROPIC_API_KEY: ${ANTHROPIC_API_KEY:-} + + # OAuth providers — all optional; auth defaults to credentials/password + GOOGLE_CLIENT_ID: ${GOOGLE_CLIENT_ID:-} + GOOGLE_CLIENT_SECRET: ${GOOGLE_CLIENT_SECRET:-} + LINKEDIN_CLIENT_ID: ${LINKEDIN_CLIENT_ID:-} + LINKEDIN_CLIENT_SECRET: ${LINKEDIN_CLIENT_SECRET:-} + MICROSOFT_ENTRA_ID_CLIENT_ID: ${MICROSOFT_ENTRA_ID_CLIENT_ID:-} + MICROSOFT_ENTRA_ID_CLIENT_SECRET: ${MICROSOFT_ENTRA_ID_CLIENT_SECRET:-} + + # Stripe billing — fully optional, self-hosters often skip + STRIPE_SECRET_KEY: ${STRIPE_SECRET_KEY:-} + STRIPE_WEBHOOK_SECRET: ${STRIPE_WEBHOOK_SECRET:-} + NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY: ${NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY:-} + + # Telemetry (opt-in; defaults to OFF for self-hosters) + PRACTIQ_TELEMETRY: ${PRACTIQ_TELEMETRY:-off} + + # Disable Vercel-specific code paths + VERCEL: '0' + + # Self-host mode: disables features that require external services + # (e.g. Vercel Analytics, Resend webhooks pointed at practiq.dev domain) + PRACTIQ_SELF_HOST: '1' + ports: + - '${WEB_PORT:-3000}:3000' + healthcheck: + test: ['CMD', 'wget', '--quiet', '--tries=1', '--spider', 'http://localhost:3000/api/healthz'] + interval: 10s + timeout: 5s + retries: 10 + start_period: 30s + +volumes: + postgres-data: + name: practiq-postgres-data diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh new file mode 100644 index 0000000..b0a0b30 --- /dev/null +++ b/docker/entrypoint.sh @@ -0,0 +1,38 @@ +#!/bin/sh +# Practiq web container entrypoint. +# Waits for Postgres, syncs the database schema, then execs the Next.js server. + +set -e + +echo "[practiq] Waiting for Postgres ..." +# The docker-compose postgres health-check is the real gate; this is a backup +# so the schema sync below never races a not-yet-listening database. +i=1 +while [ "$i" -le 10 ]; do + if node -e "const {Client}=require('pg');const c=new Client({connectionString:process.env.DATABASE_URL});c.connect().then(()=>c.end()).then(()=>process.exit(0)).catch(()=>process.exit(1));" 2>/dev/null; then + echo "[practiq] Postgres reachable." + break + fi + echo "[practiq] Attempt $i/10 — Postgres not ready yet, waiting 3s..." + i=$((i + 1)) + sleep 3 +done + +# Sync the schema. This repo ships WITHOUT a prisma/migrations/ folder (the +# project used `db push` throughout), so first-boot uses `db push` to create +# the schema idempotently. Schema + datasource are resolved from +# prisma.config.ts, so no --schema flag is needed. +# +# Note for production self-hosters: `db push` is for schema sync on a database +# you control. We deliberately do NOT pass --accept-data-loss, so a destructive +# schema diff fails loudly instead of silently dropping your data. On a fresh +# database (first boot, or the CI smoke test) there is nothing to lose and the +# push applies cleanly. See docs/self-host.md for the migrations-based path. +echo "[practiq] Syncing database schema (prisma db push)..." +# NOTE: Prisma 7's `db push` removed the --skip-generate flag (it errors and +# prints help). The Prisma client is already generated into the image, so a +# plain push is what we want. +npx prisma db push + +echo "[practiq] Starting Next.js server..." +exec "$@" diff --git a/docker/postgres-init/01-extensions.sql b/docker/postgres-init/01-extensions.sql new file mode 100644 index 0000000..ba287b1 --- /dev/null +++ b/docker/postgres-init/01-extensions.sql @@ -0,0 +1,7 @@ +-- Runs once on first Postgres init (docker-entrypoint-initdb.d). +-- The Practiq schema declares a pgvector column +-- (ClientContext.content_embedding = vector(1024)), so the `vector` type +-- must exist before `prisma db push` runs in the web container's entrypoint. +-- The schema doesn't manage the extension via Prisma, so create it here. +-- Requires a pgvector-capable image (see docker-compose.yml: pgvector/pgvector). +CREATE EXTENSION IF NOT EXISTS vector; diff --git a/docs/legal/dpa-template.md b/docs/legal/dpa-template.md new file mode 100644 index 0000000..bce825b --- /dev/null +++ b/docs/legal/dpa-template.md @@ -0,0 +1,149 @@ +# Data Processing Agreement (DPA) — template + +> **Status**: draft template, **needs legal review** before being executed against any customer. Practiq operates under Cliwant, Inc.'s standard terms — this DPA is offered to B2B customers (CPAs, accounting firms, agencies) who require contractually-bound data-processing terms beyond what the published Privacy Policy provides. +> +> Maintainer note: every blank `[CUSTOMER ...]` field is filled per execution. The "Schedule 1 — Sub-processors" section is the source of truth and gets updated when a sub-processor changes (we email Customer 30 days in advance, per §6). + +--- + +## Parties + +This Data Processing Agreement ("**DPA**") is entered into between: + +- **Cliwant, Inc.**, a Delaware corporation with its principal place of business at [REGISTERED ADDRESS] ("**Practiq**" or "**Processor**"); and +- **[CUSTOMER LEGAL ENTITY]**, with its principal place of business at [CUSTOMER ADDRESS] ("**Customer**" or "**Controller**"). + +Effective as of the date last signed below ("**Effective Date**"), and forming part of the Practiq Master Subscription Agreement (or, if none, the published Terms at practiq.dev/terms). + +## 1. Definitions + +Capitalized terms not defined here have the meaning given in the GDPR / UK GDPR / CCPA, whichever applies to Customer. "**Personal Data**" means any data Customer submits to the Service that identifies a natural person. + +## 2. Subject matter and duration + +Practiq processes Personal Data on behalf of Customer for the sole purpose of providing the Service (workspace, AI assistant, agent runs, billing). Processing lasts for the duration of the subscription plus the retention windows in Schedule 2. + +## 3. Nature and purpose of processing + +| Processing activity | Purpose | +|---------------------|---------| +| Storage of Customer accounts, workspaces, knowledge base, chat history, agent task results | Operate the Service for Customer | +| Transmission of prompts to LLM sub-processors (OpenRouter / Anthropic / OpenAI) | Generate AI responses | +| Embedding generation for retrieval | Operate semantic search | +| Sending transactional email (welcome, invoice, password reset) | Maintain the user account | +| Billing event logging | Process payments + audit | + +Practiq does not use Personal Data for any other purpose, including model training, advertising, or sale. + +## 4. Customer instructions + +Customer's submission of Personal Data to the Service constitutes its instruction to process such data per this DPA. Customer may issue further written instructions through `privacy@practiq.dev`. Practiq will notify Customer if a Customer instruction infringes applicable data-protection law and may suspend processing of the offending instruction. + +## 5. Personnel + +Practiq personnel access Personal Data only on a need-to-know basis, are bound by written confidentiality obligations, and receive ongoing data-protection training. + +## 6. Sub-processors + +Customer authorizes Practiq to engage the sub-processors listed in **Schedule 1**. Practiq: + +- imposes data-protection terms on each sub-processor at least equivalent to this DPA; +- remains liable to Customer for the acts and omissions of its sub-processors; +- gives Customer **30 days' advance notice** by email of any new or replacement sub-processor (Customer may object on reasonable grounds in good faith within those 30 days; if the parties cannot agree, Customer may terminate the affected service for the unresolved sub-processor without penalty for the prepaid unused period). + +## 7. International transfers + +Practiq stores Customer's Personal Data in **us-east-1** (United States). For Customers in the EEA / UK / Switzerland, transfers from those regions to the US rely on the **EU Standard Contractual Clauses** (Module 2: Controller-to-Processor) and the **UK International Data Transfer Addendum**, both incorporated by reference and available upon request. + +## 8. Security + +Practiq implements the technical and organizational measures listed in **Schedule 3**, including: + +- TLS 1.2+ encryption in transit, AES-256 encryption at rest (via Supabase / Stripe defaults). +- Tokenized session cookies with HttpOnly + Secure + SameSite=Lax flags. +- Strict per-firm data isolation enforced at the application layer (every database query filtered by `userId`). +- Audit log retained for 7 years. +- Annual security review and penetration test (subject to Practiq's vendor-management cycle once we exit beta). + +## 9. Data subject rights + +Practiq will, taking into account the nature of the processing, assist Customer in fulfilling its obligations to respond to requests for access, rectification, erasure, restriction, portability, and objection from data subjects. Customers can issue requests to `privacy@practiq.dev` with subject "Data Subject Request — [data subject email]". + +## 10. Personal Data Breach + +Practiq notifies Customer **without undue delay** (and in any event within 72 hours of becoming aware) of any actual or reasonably suspected Personal Data Breach affecting Customer's data, providing: + +- Description of the breach (data categories, approximate volume, type of data subjects). +- Likely consequences. +- Measures taken or proposed to mitigate. + +## 11. Audits + +Customer (or an independent auditor mandated by Customer, subject to confidentiality) may audit Practiq's compliance with this DPA once per 12-month period, on at least 30 days' written notice, during normal business hours, at Customer's expense, and not unreasonably interfering with Practiq's operations. Practiq will respond in good faith to reasonable security questionnaires (SIG Lite, CAIQ) without an on-site audit when feasible. + +## 12. Deletion or return + +Within **30 days** of termination of the subscription (or earlier on Customer's written instruction), Practiq deletes or returns all Personal Data, except (a) data subject to legal retention obligations (audit log, billing records — see Schedule 2), and (b) routine backups, which expire on their normal cycle. + +## 13. Liability + +The limitation of liability in the Master Subscription Agreement (or published Terms) applies to claims under this DPA. Nothing limits liability that cannot be limited under applicable law (e.g. willful misconduct, gross negligence, GDPR Art. 82 statutory liability where applicable). + +## 14. Conflicts + +In case of conflict between this DPA and other agreements between the parties, this DPA prevails for matters of personal-data processing. + +## 15. Governing law + +This DPA is governed by the laws of the State of Delaware, USA, without regard to its conflict-of-law principles. For Customers in the EEA / UK, the EU Standard Contractual Clauses' governing law and jurisdiction terms control to the extent of any conflict. + +--- + +## Schedule 1 — Sub-processors (as of [DATE]) + +| Sub-processor | Purpose | Region | +|---------------|---------|--------| +| Vercel (Frontier Inc.) | Hosting, edge network, analytics | USA (us-east) | +| Supabase Inc. | Postgres database | USA (us-east-1) | +| Stripe Inc. | Payment processing + metered billing | USA | +| OpenRouter (Lambda Inc.) | Primary LLM gateway (zero-data-retention enabled) | USA | +| Anthropic PBC | Fallback LLM | USA | +| OpenAI L.L.C. | Embedding generation only | USA | +| Resend Inc. | Transactional email | USA | +| PostHog Inc. | Product analytics (in-app) | USA | +| Cloudflare Inc. | DNS | USA | + +The current authoritative list is published at practiq.dev/privacy → "Sub-processors". Practiq notifies the email on file 30 days before any change. + +## Schedule 2 — Retention + +| Category | Retention | +|----------|-----------| +| Workspace data (clients, knowledge base, chat) | While subscription active + 30 days post-cancellation | +| Audit log | 7 years (US tax-record retention norm) | +| Billing records (Stripe-side) | 7 years | +| Token usage logs | 18 months | +| Transactional email metadata | 30 days | + +## Schedule 3 — Technical and organizational measures (TOMs) + +- **Encryption**: TLS 1.2+ in transit, AES-256 at rest at storage layer (Supabase + Stripe defaults). +- **Authentication**: NextAuth.js v5; password rows are bcrypt-hashed (cost 10); OAuth via Google / LinkedIn / Microsoft Entra; session cookies are HttpOnly + Secure + SameSite=Lax. +- **Authorization**: Application-level — every Postgres query filtered by `userId`; strict per-firm data isolation; no Postgres-level RLS, but compensated by single-tenant per-firm scope at the application boundary. +- **Audit logging**: Every authentication event, plan change, AI conversation, agent run, and approval decision is recorded in `audit_logs` with 7-year retention. +- **Network**: Cloudflare-fronted, Vercel edge; admin surface on a separate route group with rate limit + IP allowlist option. +- **Monitoring**: Structured JSON logs on Vercel; Slack alerts for 5xx, payment failures, agent cron failures; public `/status` page. +- **Backup**: Supabase point-in-time recovery (7-day window). Backup restoration tested at least annually. +- **Access control**: Production access restricted to engineering staff with hardware-key 2FA on GitHub + Vercel + Supabase + Stripe; access reviewed quarterly. +- **Incident response**: Detection → 24-hour internal notification → 72-hour Customer notification per §10. Documented runbook covers data-loss, downtime, sub-processor outage, and credential leakage. +- **Sub-processor diligence**: Each sub-processor reviewed annually for SOC 2 / ISO 27001 / DPA terms. + +--- + +**Signatures** + +For Cliwant, Inc.: ___________________________ Date: __________ +Name / Title: ___________________________________________________ + +For [CUSTOMER LEGAL ENTITY]: _____________________ Date: __________ +Name / Title: ___________________________________________________ diff --git a/docs/lib/indexnow-deploy.ts b/docs/lib/indexnow-deploy.ts new file mode 100644 index 0000000..bb0ecb0 --- /dev/null +++ b/docs/lib/indexnow-deploy.ts @@ -0,0 +1,88 @@ +/** + * IndexNow ping — run as a Vercel post-deploy webhook (or GitHub Action on + * `release` event) to notify Bing/Yandex/Seznam of new/updated docs pages. + * + * Setup (one-time): + * 1. Generate a new key for practiq.dev/docs (different from practiq.dev's): + * node -e "console.log(require('crypto').randomBytes(8).toString('hex'))" + * → e.g. "a3f2c7d8e1b4f9a2" + * 2. Upload the key file to https://practiq.dev/docs/a3f2c7d8e1b4f9a2.txt + * with content = the same key string. Put it in public/ so Vercel serves it + * at the root. + * 3. Set DOCS_INDEXNOW_KEY env var in Vercel to that value. + * 4. Optionally set DOCS_INDEXNOW_KEY_LOCATION to override the URL (default + * below). + * 5. Wire the deploy webhook (Vercel → Project Settings → Webhooks → + * Deployment Succeeded → POST to your /api/deploy-hook endpoint). + */ + +interface IndexNowResult { + ok: boolean; + status: number; + body: string; +} + +const DOCS_KEY = process.env.DOCS_INDEXNOW_KEY ?? ""; +const DOCS_HOST = process.env.DOCS_INDEXNOW_HOST ?? "practiq.dev/docs"; +const DOCS_KEY_LOCATION = + process.env.DOCS_INDEXNOW_KEY_LOCATION ?? + `https://${DOCS_HOST}/${DOCS_KEY}.txt`; + +const DOCS_URLS = [ + `https://${DOCS_HOST}/`, + `https://${DOCS_HOST}/quickstart`, + `https://${DOCS_HOST}/self-host`, + `https://${DOCS_HOST}/mcp-reference`, + `https://${DOCS_HOST}/architecture`, + `https://${DOCS_HOST}/cloud-vs-self-host`, + `https://${DOCS_HOST}/why-oss`, +]; + +export async function pingIndexNow( + urls: string[] = DOCS_URLS, +): Promise { + if (!DOCS_KEY) { + return { + ok: false, + status: 0, + body: "DOCS_INDEXNOW_KEY env var not set — skipping IndexNow ping", + }; + } + + const batch = urls.slice(0, 10000); + const res = await fetch("https://api.indexnow.org/IndexNow", { + method: "POST", + headers: { + "Content-Type": "application/json; charset=utf-8", + "User-Agent": "practiq-docs-deploy/1.0", + }, + body: JSON.stringify({ + host: DOCS_HOST, + key: DOCS_KEY, + keyLocation: DOCS_KEY_LOCATION, + urlList: batch, + }), + }); + + const body = res.ok ? "" : (await res.text()).slice(0, 500); + return { ok: res.ok, status: res.status, body }; +} + +/** + * Wire as a Next.js API route at app/api/deploy-hook/route.ts: + * + * import { pingIndexNow } from "@/lib/indexnow-deploy"; + * export async function POST(req: Request) { + * // Verify Vercel signature here (use VERCEL_DEPLOY_HOOK_SECRET) + * const result = await pingIndexNow(); + * return Response.json(result); + * } + * + * Or as a GitHub Action step (.github/workflows/release.yml): + * + * - name: IndexNow ping + * env: + * DOCS_INDEXNOW_KEY: ${{ secrets.DOCS_INDEXNOW_KEY }} + * run: | + * node -e "require('./lib/indexnow-deploy').pingIndexNow().then(r => console.log(r))" + */ diff --git a/docs/lib/schema-jsonld.ts b/docs/lib/schema-jsonld.ts new file mode 100644 index 0000000..ee372c0 --- /dev/null +++ b/docs/lib/schema-jsonld.ts @@ -0,0 +1,197 @@ +/** + * schema.org JSON-LD generators for practiq.dev/docs + * + * Mount in Next.js root layout as + {/* noscript fallback — no-op if NextJS Script loaded */} + + + ) : null} + + {linkedInId ? ( + <> + + + + ) : null} + + {xId ? ( + + ) : null} + + ); +} diff --git a/src/components/analytics-provider.tsx b/src/components/analytics-provider.tsx new file mode 100644 index 0000000..a8a197b --- /dev/null +++ b/src/components/analytics-provider.tsx @@ -0,0 +1,72 @@ +"use client"; + +/** + * AnalyticsProvider — mounts pageview tracking + Tier 5 instrumentation. + * + * On mount we: + * 1. Initialize PostHog SDK (session replay, autocapture, heatmaps) + * — no-op when NEXT_PUBLIC_POSTHOG_KEY isn't set. + * 2. Capture first-touch attribution (UTM + referrer + landing page) + * to a 1-year cookie. Fires `attribution_captured` once per visitor. + * 3. Update last-touch cookie when a fresh campaign URL arrives. + * 4. Wire scroll-depth, time-on-page, exit-intent, and rage-click + * listeners for the current pathname. + * 5. Fire $pageview on every App Router pathname/searchParams change. + * + * Engagement listeners are torn down + reinstalled per pathname so each + * pageview gets a fresh scroll-depth set + time-on-page counter. + */ +import { useEffect } from "react"; +import { usePathname, useSearchParams } from "next/navigation"; +import { trackPageview, trackClient } from "@/lib/analytics/track-client"; +import { + ensureFirstTouchCaptured, + maybeUpdateLastTouch, +} from "@/lib/analytics/attribution"; +import { installEngagementListeners } from "@/lib/analytics/engagement"; +import { initPosthogSdk } from "@/lib/analytics/posthog-init"; +import { WebVitals } from "@/components/web-vitals"; +import { ErrorTracker } from "@/components/error-tracker"; + +export function AnalyticsProvider({ children }: { children: React.ReactNode }) { + const pathname = usePathname(); + const searchParams = useSearchParams(); + + // One-time bootstrap (PostHog SDK + first-touch capture). + useEffect(() => { + initPosthogSdk(); + const { isNew, payload } = ensureFirstTouchCaptured(); + if (isNew) { + trackClient({ + type: "attribution_captured", + properties: { + ...payload, + // Flatten so SQL can `... AS first_touch_source` cleanly + // alongside the typed first_touch_* columns. + first_touch: payload, + }, + }); + } + }, []); + + // Per-route effects: pageview + last-touch refresh + engagement listeners. + useEffect(() => { + const url = + typeof window !== "undefined" ? window.location.href : undefined; + trackPageview(url); + maybeUpdateLastTouch(); + const teardown = installEngagementListeners(); + return teardown; + // pathname + searchParams together guarantee we re-fire on any + // client-side navigation, including ?utm_* changes which matter + // for attribution + campaign tracking. + }, [pathname, searchParams]); + + return ( + <> + + + {children} + + ); +} diff --git a/src/components/app/feedback-button.tsx b/src/components/app/feedback-button.tsx new file mode 100644 index 0000000..8bbeae2 --- /dev/null +++ b/src/components/app/feedback-button.tsx @@ -0,0 +1,245 @@ +"use client"; + +/** + * Floating "Send feedback" button — bottom-right of every authenticated + * /app page. Beta-launch must-have so users can report a bug / ask a + * question / share a delight without leaving the app to find an + * email address. + * + * Design choices: + * - Bottom-right floating, brand-quiet (zinc fill, no glow). Should + * not compete with primary CTAs; it's an always-available backstop. + * - Click opens a small modal with kind selector + textarea. Keep + * it minimal — every extra field is a reason the user gives up + * mid-write. + * - Path + userAgent + last seen JS error captured automatically. + * User doesn't have to think about repro. + * - On submit, POST /api/feedback. Success → "Thanks — we'll + * reply within 1 business day to ." Failure → "Couldn't + * send — email support@practiq.dev directly." + * - 5 submissions / hour rate limit on the server. The button just + * surfaces the 429 message. + */ + +import { useEffect, useState } from "react"; +import { usePathname } from "next/navigation"; + +type FeedbackKind = "bug" | "feature" | "question" | "praise" | "other"; + +const KIND_LABELS: Record = { + bug: "Bug — something broke", + feature: "Feature request", + question: "How do I...", + praise: "Just nice to hear", + other: "Other", +}; + +export function FeedbackButton(): React.ReactElement | null { + const [open, setOpen] = useState(false); + const [kind, setKind] = useState("bug"); + const [message, setMessage] = useState(""); + const [submitting, setSubmitting] = useState(false); + const [result, setResult] = useState< + | { state: "idle" } + | { state: "ok"; email: string | null } + | { state: "error"; message: string } + >({ state: "idle" }); + const pathname = usePathname(); + + // Track last unhandled JS error so the user can submit "this thing + // just blew up" without remembering what the error said. Captured + // best-effort — never throws. + const [lastError, setLastError] = useState(null); + useEffect(() => { + function onError(e: ErrorEvent) { + try { + const detail = `${e.message ?? "(no message)"} @ ${e.filename ?? "?"}:${ + e.lineno ?? "?" + }`; + setLastError(detail.slice(0, 500)); + } catch { + // never throw from a global listener + } + } + window.addEventListener("error", onError); + return () => window.removeEventListener("error", onError); + }, []); + + async function submit() { + if (message.trim().length < 5) { + setResult({ state: "error", message: "Please write at least a sentence." }); + return; + } + setSubmitting(true); + try { + const res = await fetch("/api/feedback", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + kind, + message: message.trim(), + context: { + path: pathname, + userAgent: navigator.userAgent.slice(0, 400), + lastError: lastError ?? undefined, + }, + }), + }); + if (!res.ok) { + const body = await res.json().catch(() => ({})); + setResult({ + state: "error", + message: + body?.error ?? + "Couldn't send — please email support@practiq.dev directly.", + }); + return; + } + setResult({ state: "ok", email: null }); + setMessage(""); + // Auto-close after 4 seconds so the user gets feedback then can + // keep working. + setTimeout(() => { + setOpen(false); + setResult({ state: "idle" }); + }, 4000); + } catch { + setResult({ + state: "error", + message: + "Network error — please email support@practiq.dev with what you tried to send.", + }); + } finally { + setSubmitting(false); + } + } + + return ( + <> + + + {open ? ( +
+
+
+
+
+ Beta feedback +
+

+ What do you want to tell us? +

+

+ We read every one. Reply within 1 business day. +

+
+ +
+ + {result.state === "ok" ? ( +
+
+
+ Got it. We'll reply soon. +
+
+ ) : ( + <> + + +