d3ro-voice/docs/map/02-infrastructure.md

307 lines
36 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# 02 — Repository & Infrastructure Map
> Surface: whole repo
> Last updated: 2026-11-13 — Source/packaging hygiene (`clean:deep`, trimmed `apps/desktop/resources/sox`, macOS-only `@nut-tree-fork` `asarUnpack`, Android R8 + `shrinkResources` + 12-locale `localeFilters`), `@d3ro/i18n` 2,500-key split, `site/` static/build CI gate, and TDD v2.0 Phase 2–5 gates (`check:i18n`, `check:ds-contract`, `test:affected`, `release:installer:smoke`)
> Source of truth for: layout, workspaces, build/test commands, CI/CD, Docker, deploy, scripts, resources
---
## 1. Repository layout
```
D:/workspace/D3ROVoice
├── apps/
│ ├── desktop/ Electron app (npm workspace @d3ro/desktop)
│ ├── web/ Next.js console (npm workspace @d3ro/web); basePath `/app`, served at `d3ro.chanpaca.net/app`
│ ├── admin/ Next.js back office (npm workspace @d3ro/admin)
│ ├── mobile-rn/ React Native product mobile app (NOT an npm workspace)
│ ├── api-server/ ASP.NET Core 10 API (D3ROVoice.Api)
│ ├── api-server.Tests/ xUnit tests for the API
│ └── admin-swagger/ Static Swagger UI + openapi.json
├── packages/ Shared TS packages (npm workspaces)
│ ├── core/ @d3ro/core — types, errors, IPC channels, crypto, utils
│ ├── ui/ @d3ro/ui — web/desktop design system (MUI + tokens)
│ ├── ui-native/ @d3ro/ui-native — React Native design system
│ ├── i18n/ @d3ro/i18n — 12 locales, provider, formatters
│ └── api-client/ @d3ro/api-client — Supabase wrapper + shared types
├── server/
│ ├── supabase/ Supabase project: config.toml, migrations/, functions/, tests/
│ ├── cloudflare-worker/ Edge gateway (wrangler.toml + src/index.ts)
│ └── cloudflare-site-bridge/ Site bridge worker: forwards `/app/*` to WEB_APP_ORIGIN, rewrites upstream redirects, else proxies to Pages
├── site/ Vite landing site (deployed to Cloudflare Pages; GitHub Pages removed 2026-09-26, Wave 3)
├── release/ Version identity SSOT + license/evidence public keys
├── scripts/ Automation scripts + scripts/ci/ (32, incl. clean-deep.mjs) + scripts/lib/ + scripts/verification/
├── docs/ Design, phases, v2/v3 plans, deployment, map/ (this map)
├── memory/ Project status, handoffs, archive
├── test-results/ Last-run artifacts (root tests/e2e removed 2026-11-04 — orphaned duplicates)
├── scratch/ Large local evidence (APKs, screenshots, DBs) — not build input
├── supabase/ Empty scaffolding (.branches/, snippets/) — real project is server/supabase
├── .gitlab-ci.yml GitLab CI (primary desktop/mobile release pipeline)
├── .forgejo/workflows/ Forgejo Actions (CI, site deploy to Cloudflare Pages, payple-renew cron, portable/release)
├── docker-compose.yml, docker-compose.nas.yml
├── apps/api-server/Dockerfile, apps/admin/Dockerfile, apps/web/Dockerfile
├── tsconfig.json, tsconfig.base.json
├── package.json monorepo root, npm workspaces
├── CLAUDE.md Claude-specific project rules
└── AGENTS.md Cross-agent entry: rules + map obligation (this map's anchor)
```
Note: root `package.json` is the only workspace manifest and declares npm workspaces `apps/desktop`, `apps/web`, `apps/admin`, `packages/*`. The unused `turbo.json` and `pnpm-workspace.yaml` manifests were removed in Wave 4. **Mobile is intentionally outside the workspace.**
---
## 2. Toolchain & versions
| Tool | Version | Source |
|---|---|---|
| Node | 24.19.0 | `.nvmrc` |
| TypeScript | 5.7 | root `package.json` |
| .NET SDK | 10.0.300 (rollForward latestPatch) | `global.json` |
| Deno | 2.8.1 | CI (`edge-functions`) |
| JDK | 17 | mobile CI |
| Electron | 33.4.11 | `apps/desktop/electron-builder.yml` |
| koffi | 3.3.1 | `apps/desktop/package.json` — FFI into user32/kernel32 for foreground window title/pid/exe/bounds (`utils/win32-foreground.ts`). Chosen over `get-windows` because that package needs an install script this repo does not run; koffi ships N-API 8 prebuilds as optional deps. `asarUnpack` covers `koffi`/`@koromix`. |
| uiautomation / comtypes | 2.0.29 / 1.4.17 | `apps/desktop/sidecar/requirements.txt` (Windows only) — UI Automation snapshot behind `GET /uia/focus` (`sidecar/uia_bridge.py`). Dev install: `apps/desktop/sidecar/.venv/Scripts/python.exe -m pip install uiautomation comtypes`. |
| React Native | 0.85 | `apps/mobile-rn/package.json` |
---
## Runtime-inclusive desktop release (2026-11-01)
When required sidecar changes ship, run `node --env-file-if-exists=.env scripts/ci/release-desktop.mjs minor --with-runtime` on clean main. It preserves the normal version/tag/signature/installer gates, rebuilds the sidecar, runs `verify-sidecar-bundle.mjs --smoke` on a separate loopback port, builds portable/runtime artifacts, and publishes their immutable manifests before pushing the tag and publishing the desktop update. `--release-artifacts-only` keeps generated Scoop metadata in the release directory. Before the first upload, `release-artifacts.json` records the tag commit and file hashes. Resume with `--resume --with-runtime`: verify and reuse those bytes, then rerun the idempotent publishers to recover missing files and latest aliases. Existing output without a valid checkpoint is preserved and requires investigation, never silently rebuilt. Forgejo portable CI skips only completed immutable and latest indexes; partial publication fails closed. Desktop Vitest and mobile Jest use at most four workers; timeouts remain unchanged. Sidecar minimum is 1.16.0; ffmpeg has no new minimum. [Evidence](../evidence/2026-11-01-completion.md).
## 3. Root scripts (`package.json`)
```bash
npm run dev # desktop dev (electron-vite)
npm run build # desktop production build
npm run build:admin # admin production build
npm run build:all | npm run ci # typecheck + test + desktop/admin/web production builds
npm run checksum # scripts/ci/generate-checksums.mjs
npm run version:check | version:sync
npm run release:metadata[:test]
npm run release:installer:smoke[:test] # PE64, gzip blockmap, SHA-512, app-update.yml, ASAR Pickle, Ed25519 .sig smoke gate
npm run release:forgejo[:check] # canonical Forgejo publisher/feed
npm run release:tag # annotated/signed immutable release tag
npm run security:secrets[:test] # hardcoded-secret scanner
npm run check:desktop-renderer[:test] # built renderer pages reference only assets on disk
npm run check:migrations[:test] # Supabase migration filename/order/non-empty metadata checks (74 migrations); no DB replay or remote drift
npm run check:i18n[:test] # 12-locale 2,500-key parity, placeholder consistency, literal t() existence & orphan budget
npm run check:ds-contract[:test] # @d3ro/ui DS exports, theme-token purity, ARIA roles, and contract test coverage
npm run rebuild:app # rebuild better-sqlite3 in-place for Electron ABI
npm run rebuild:test # rebuild better-sqlite3 in-place for host Node ABI (Vitest)
node scripts/ci/verify-native-abi.mjs --self-test # required packaged N-API prebuild missing/present fixture
node scripts/ci/sync-i18n-locales.mjs [--check] # verify/sync 12 locales against ko/en SSOT (zero hardcoded translations)
npm run test:e2e:red # content-report red e2e
npm run release:mobile:boundary[:test]
npm run release:mobile:config[:test]
npm run release:mobile:build-config:test
npm run release:play:assets[:test]
npm run typecheck # all workspaces; web/admin run `next typegen` before `tsc`
npm run typecheck:site # site/ tsc --noEmit (outside npm workspaces)
npm run test # all workspaces (desktop, web, api-client, core, i18n, ui)
npm run test:affected[:test] # affected test selector over git diff (falls back to full suite on unknown paths)
npm run lint # eslint apps/desktop apps/web apps/admin packages
npm run lint:site # eslint site/src --max-warnings=0
npm run format # prettier
npm run typecheck:mobile # apps/mobile-rn tsc (outside npm workspaces)
npm run lint:mobile # apps/mobile-rn eslint --max-warnings=0
npm run test:mobile # apps/mobile-rn test:ci (jest --runInBand)
npm run verify:all # aggregate: hygiene + protected-tests + quality + i18n + ds-contract + workspaces + mobile + site
npm run clean:deep # remove build outputs, caches, temp browser profiles, dangling symlinks (--dry-run supported)
```
Per-app commands that matter:
| App | Commands |
|---|---|
| desktop | `npm run dev --workspace=@d3ro/desktop`, `build`, `typecheck`, `test` (vitest), playwright e2e; local STT engine: `npm --prefix apps/desktop run sidecar:setup` then `sidecar:build` (PyInstaller → `sidecar-dist/sidecar`), full local Windows package: `npm --prefix apps/desktop run dist:win:full`; `setup:sox` re-downloads the bundled SoX |
| mobile-rn | `npm run typecheck:mobile` / `lint:mobile` / `test:mobile` (root; Jest uses `test:ci`/`--runInBand`), or `npm --prefix apps/mobile-rn run lint/typecheck/test`; android gradle builds, Maestro E2E |
| api-server | `dotnet build`, `dotnet test` (also `apps/api-server.Tests`) |
| web | `next typegen && tsc --noEmit`, `next build`, `test` (vitest, `apps/web/tests`), playwright e2e in `apps/web/e2e` |
| admin | `next typegen && tsc --noEmit`, `next build` (`build:admin`) |
Desktop Vitest uses one `apps/desktop/vitest.config.ts` SSOT with mode-specific include globs:
| Command (`npm --prefix apps/desktop run …`) | Scope |
|---|---|
| `test` | Deterministic offline unit + service tests (default gate) |
| `test:unit` | `tests/unit` only |
| `test:service` | `tests/main` + `tests/red` with process/network/model doubles |
| `test:integration` | Real Ollama/Supabase tests; requires their documented environment variables |
| `test:eval` | Suggestion quality/latency evaluation and pure replay metrics |
| `test:all` | All Vitest scopes (external tests skip when their environment is absent) |
| `test:e2e` | Playwright GUI tests |
2026-10-31 baseline (GAP-QA-03): `test:unit` 286 passed; `test:service` 2478 passed; default `test` 2764 passed; `test:all` 2788 passed / 10 skipped / 0 failed. External Ollama/Supabase tests were not run because their environment variables were absent. Run the full test gate separately from other CPU-heavy checks because voice timing suites can contend for resources.
Desktop GUI execution rule (from `CLAUDE.md` / `.agents/rules/`): run via `run-desktop.bat` or an external terminal; do not background-launch GUI from an agent subshell.
Desktop input verification (2026-10-30, INFRA-20):
```powershell
node scripts/verification/typing-race-proof.mjs
pwsh -File scripts/verification/typing-fixture/build.ps1
pwsh -File scripts/verification/typing-runtime/build.ps1
```
The first command overlays only `InputTelemetryService`, `TypoCorrectionService` and `TextInsertService` from read-only `git show HEAD`; dependencies, test doubles and tests stay current in both runs. It writes timestamped reports under `test-results/typing-load/race-proof-*` without launching a GUI or injecting keys. This is not a full historical-release comparison. The 2026-10-30 [`report.json`](../../test-results/typing-load/race-proof-2026-10-30T00-50-32-284Z/report.json) records HEAD 1/17 and current 17/17: three independently varied timing signals reproduce text corruption in the old services; the remaining 13 failures concern snapshot invalidation, metadata and query coalescing. Unchanged-input correction passes in both runs.
The build commands use the installed .NET Framework compiler to create `test-results/typing-load/fixture/D3ROTypingFixture.exe` and `test-results/typing-load/runtime/D3ROTypingRuntime.exe`. Launch these from the interactive desktop, following [`verification/README.md`](../../scripts/verification/README.md) and [`typing-fixture/README.md`](../../scripts/verification/typing-fixture/README.md). The runtime launcher refuses to start while an installed `D3RO Voice` process is running; it does not terminate it. The product bundle must already be built. For this experiment, use this launcher rather than `run-desktop.bat`, which terminates other Electron processes.
`scripts/verification/typing-runtime/main.cjs` is a verification-only entry into the existing `apps/desktop/out/main/index.js` bundle. Its profile/logs/runtime receipt live under `test-results/typing-load`, separate from personal config. A new local-only profile starts with automatic correction, model correction, suggestions, typed-text learning and telemetry disabled; protocol registration and OS startup registration are blocked. `runtime.json` records the product package version and bundle SHA-256 because the wrapper's version is not the product release identity.
The runtime profile is retained across launches, so record its actual settings with every result. Model cold/warm and correction on/off coverage must be explicit; the default profile alone does not test model loading or correction. Runtime syntax checking and launcher compilation passed, but the runtime has not started and no interactive GUI/IME/CPU/model pass is claimed (GAP-INPUT-11). These tools are local verification commands, not new release/CI gates.
---
## 4. Shared packages
See [`03-shared-packages.md`](./03-shared-packages.md). Summary:
| Package | Provides |
|---|---|
| `@d3ro/core` | Domain types, `D3ROError`/`ErrorCode`, IPC channel SSOT, key-binding SSOT (`./keybinding`), plan/quota catalog including `knowledge_embedding`, constants, `crypto-license`, `pii-redactor`, `secure-memory`, `supabase-config`, `meeting-markdown`, `markdown-to-docx`, plus cross-surface `guards`, `csv`, `format`, `unified-search`, `admin-roles`, speaker diarization helpers (`meeting-transcript`), and deterministic `Clock`/`Random` `ports`; Deno consumes the generated contract checked by `contract:check`; has vitest tests (`packages/core/vitest.config.ts`, 38 files / 618 tests) |
| `@d3ro/ui` | Theme tokens, CSS vars, MUI DS components (web/desktop), ARIA-accessible `SegmentControl` (`tablist`/`tab`), and DS contract tests (`packages/ui/__tests__/ds-contract.test.tsx`, guarded by `check:ds-contract`) |
| `@d3ro/ui-native` | RN design system (MetalCard, PhosphorText, Led, PhysicalButton, WaveBars, …) + `>=600dp` tablet/foldable responsive primitives (`responsive.tsx`: `resolveResponsiveLayout`, `useResponsiveLayout`, `useContentWidth`, `<ContentColumn>`) |
| `@d3ro/i18n` | 12 locales / 2,500 parity-checked keys (253 orphan keys pruned on 2026-11-13), `I18nProvider`, `t()`, date/number/relative formatters; guarded by `check:i18n` and `packages/i18n/__tests__/locale-contract.test.ts` (15 tests) |
| `@d3ro/api-client` | Supabase browser/server clients, meetings/history/usage/transcribe wrappers, canonical push-token/provider + push/quota RPC types, `meeting_memos.revision` CAS shape; has vitest tests (4 files / 31 tests) |
---
## 5. CI/CD
> `.github/workflows/` was deleted 2026-09-26 (Wave 3, dc43884): the repository has Forgejo and GitLab
> remotes but no GitHub remote, so nothing under it ever ran — including the daily Payple renewal cron.
> CI now runs only on Forgejo Actions (`.forgejo/workflows/`); see below.
### GitLab CI (`.gitlab-ci.yml`)
Stages `validate → test → build → e2e → package → publish → deploy`. Primary pipeline for desktop Windows/macOS releases (Forgejo Generic Registry is the canonical updater feed; GitLab project 1172 is a legacy mirror) and production mobile releases (`mobile-production-release`, manual/protected). Admin NAS deploy job is intentionally **disabled**. `package-windows`/`package-macos` build the faster-whisper sidecar (`sidecar:setup` → `sidecar:build`) and run `scripts/ci/verify-sidecar-bundle.mjs` before electron-builder, so a release can never ship without the local STT engine. Every pipeline that runs `npm run build --workspace=@d3ro/desktop` (`.forgejo` CI/release/portable) then runs `scripts/ci/verify-desktop-renderer-bundles.mjs`, which fails packaging when a renderer page references an asset the build did not emit (GAP-INFRA-05).
### Forgejo Actions (`.forgejo/workflows/`)
`ci.yml` — CI is now Forgejo-only (`.github/workflows` deleted 2026-09-26, Wave 3, dc43884). Jobs: `quality` (`version:check`, `contract:check`, `release:metadata:test`, `release:installer:smoke:test`, migration checker self-test + actual 74-migration filename/order/non-empty check, secret scan, mobile release/config/build-config self-tests, Play asset contract, `test:hygiene[:test]`, `check:protected-tests[:test]`, `test:quality[:test]`, `check:i18n[:test]`, `check:ds-contract[:test]`, `test:affected:test`, `lint`, `lint:site`, `typecheck`, `typecheck:site`, Vitest across desktop/web/api-client/core/i18n/ui), `build-validation` (desktop renderer verification + admin + web + `site/` production builds), `mobile-quality`, `edge-functions` (Deno), `api-server-tests`. Web/admin typecheck runs Next 16 `typegen` before `tsc`, so a clean checkout generates and checks route/root-param declarations instead of relying on a prior dev/build artifact. The migration checks are file metadata/order gates only; Supabase replay, shadow DB, and remote drift remain separate runtime/integration gates. A separate isolated local run on 2026-11-04 applied all 73 prior migrations from empty and after reset, then returned an empty `pg-delta --strict-coverage` shadow diff; that runtime gate is not yet part of CI and says nothing about linked remote drift.
`payple-renew.yml` — daily cron (+ manual dispatch) → `payple-renew` edge function; ported from the never-run `.github/workflows/payple-renew.yml` because the repository has no GitHub remote. Requires Forgejo secrets `SUPABASE_URL`, `CRON_SECRET`. 2026-09-26~10-11 `SUPABASE_URL` 시크릿이 로컬 주소(`127.0.0.1:55321`)라 한 번도 성공하지 못했다(GAP-OPS-03).
**Forgejo 시크릿 정본 = 루트 `.env`.** 웹 UI에서 손으로 넣지 않는다. `.env`를 고친 뒤 `node scripts/ci/set-forgejo-secrets.mjs --check` → `--write [NAME…]`. 스크립트가 Forgejo 시크릿 이름 ↔ `.env` 키 표(SUPABASE_URL, CRON_SECRET, CF_API_TOKEN←CLOUDFLARE_API_TOKEN, CF_ACCOUNT_ID←CLOUDFLARE_ACCOUNT_ID, FORGEJO_TOKEN, WIN_CSC_*)를 갖고, URL 시크릿에 로컬 주소가 있으면 아무것도 쓰지 않는다.
**러너:** `linux-builder` 라벨은 러너 `kd-desktop` 하나뿐이고, 그 호스트는 노트북 `ChanpacaLaptop`(ssh `vd-linux`, systemd `forgejo-runner.service`, host executor)이다. 노트북이 꺼지면 CI·크론이 전부 멈추고 Forgejo가 대기 잡을 Canceled 처리한다(실측: 2026-09-29 13:24 ~ 10-09 08:30 KST 꺼짐 → run #128~#137 Canceled, `3cac14f` push CI 미실행). GAP-CI-02.
`portable.yml` — 태그/수동 실행으로 **서명 없이** portable 채널(95MiB 7z 분할 볼륨 + Scoop 매니페스트 + 설치 스크립트)을 게시한다. `WIN_CSC_*` 불필요, updater feed는 건드리지 않는다.
`deploy-site.yml` — 유일한 사이트 배포 경로(Linux, Cloudflare Pages). Windows 수동 중복 워크플로(`deploy-site-windows.yml`)는 2026-09-26 삭제됐다(dc43884). build `site`, write release identity, deploy to Cloudflare Pages `d3ro` (`d3ro.pages.dev`), verify live commit/version, app-links, legal URLs. 커스텀 도메인 `d3ro.chanpaca.net` 은 Pages 커스텀 도메인이 DNS CNAME을 요구하므로, DNS를 건드릴 수 없는 동안은 Workers 라우트 브리지 `server/cloudflare-site-bridge/`(`d3ro.chanpaca.net/*` → Pages 프록시, 수동 `npx wrangler deploy`)가 서빙한다. CNAME을 추가한 뒤 브리지를 삭제하면 Pages 커스텀 도메인으로 직접 서빙된다(GAP-REL-09b).
`release.yml` — tag-triggered Windows build + `verify-desktop-installer-smoke.mjs` (PE64/blockmap/SHA-512/ASAR/feed smoke gate) + `publish-forgejo-release.mjs` to the canonical Forgejo feed/release hub.
---
## 6. Docker & deployment
| File | Purpose |
|---|---|
| `apps/admin/Dockerfile` | Next.js standalone runner for `.next/standalone` (the old root `Dockerfile.admin` 3-stage build was a duplicate, deleted 2026-09-26, Wave 3, cd9d199) |
| `apps/api-server/Dockerfile` | Multi-stage .NET 10 (sdk → aspnet runtime), port 5000, `VOLUME /app/data`; no longer serves static files (`wwwroot` removed — see `07-api-server.md`) |
| `apps/web/Dockerfile` | Next.js standalone runner for `@d3ro/web`, basePath `/app`, port 3002 (added 2026-09-26, Wave 3, b6fe588) |
| `docker-compose.yml` | Dev/self-host: `d3ro-api-server` (5050→5000, `./data` volume), `d3ro-admin` (3001), `d3ro-web` (3002, `@d3ro/web` basePath `/app`, Supabase/Payple keys as build args), optional `ollama` (profile `ai`, 11434) |
| `docker-compose.nas.yml` | NAS: prebuilt `d3ro-voice-api:latest` / `d3ro-voice-admin:latest` / `d3ro-voice-web:latest` (3002) / `d3ro-whisper` (faster-whisper, OpenAI-compatible). No legal-doc `wwwroot` mount and no `NEXT_PUBLIC_API_URL` — both were dropped 2026-09-26 (Wave 3, b6fe588); legal pages are served only from `site/public`. |
Deploy scripts: `scripts/deploy-nas.ps1`, `scripts/deploy-nas.sh`, `scripts/nas-control.sh` (start/stop/restart/status/logs/backup/update). `scripts/deploy-site-to-nas.js` was deleted 2026-09-26 (Wave 3, cd9d199) — site deploy is Cloudflare Pages only (`.forgejo/workflows/deploy-site.yml`).
Public endpoints (production): `https://d3ro.chanpaca.net` — **랜딩/다운로드 센터**(site/, Pages `d3ro` 배포본을 Workers 라우트 브리지가 서빙), `https://d3ro.chanpaca.net/app` — **웹앱**(`apps/web`, basePath `/app`; 사이트 브리지 워커가 `WEB_APP_ORIGIN`(터널 호스트)으로 전달하며, 호스트가 비어 있으면 `/app`은 503을 반환한다 — 터널 호스트 설정 대기), `https://d3ro-admin.chanpaca.net` (admin CRM). Edge: `server/cloudflare-worker` proxying to the NAS origin, plus a **Cron Trigger** (`* * * * *`) that drains the Supabase push outbox via `send-push?mode=drain` (`src/push-drain.ts`; needs `SUPABASE_URL` var + `SUPABASE_SERVICE_ROLE_KEY` secret). Tunnel: Cloudflare Tunnel `kd-nas` (NAS 포털/API는 현재 이 호스트네임에 바인딩되어 있지 않다).
---
## 7. `server/supabase` (backend)
- `config.toml` — project `d3ro-voice`, ports 55321-55324, DB major 17, Supabase CLI 3.x `[local_smtp]`, auth redirects (localhost, `d3ro.chanpaca.net`, `d3ro-voice://auth-callback`), providers Google/GitHub/Apple. `audio-purge` has an explicit function stanza with gateway JWT verification disabled because its handler verifies the exact pg_cron service credential. An isolated local stack proved missing/non-service key 401, service 200, and pg_cron/Vault/pg_net removal of the queue row, `audio_files` row, and Storage object; deployment and the production schedule remain unverified.
- `migrations/` — **74 SQL migrations** (schema, RLS, auth triggers, storage, team invites, knowledge/pgvector, push outbox, Payple billing (legacy Stripe columns/provider values kept for history), admin roles, mobile platform/monetization, atomic command reorder, device revocation, content reporting, audit log, meeting documents, STT quota reservations, ad reward replay protection, team activity feed, cross-device sync parity & tombstones, and immutable `meeting_memos.revision` CAS `20261113000001`).
- `functions/` — **24 Deno Edge Functions** (`stt-proxy`, `llm-proxy`, `content-report`, `generate-meeting-document`, `embed-chunks`, `search-knowledge`, `realtime-token`, `team-invite`, `team-accept`, `send-push`, `audio-purge`, `account-delete`, `admin-users`, `admin-subscriptions`, `admin-payments`, `admin-audit-log`, billing `billing-catalog`/`payple-checkout`/`payple-manage`/`payple-renew`/`payple-webhook`, `iap-verify`, `admob-ssv`, `google-play-rtdn`; Stripe functions removed 2026-09-26). Shared contracts in `functions/_shared/` — push transports now include `webpush.ts` (VAPID + RFC 8291) and `apns.ts` (.p8 token) alongside FCM. CI (`edge-functions`) runs `deno check` + `deno test` and also the Cloudflare worker drain test.
- `tests/` — integration/E2E for content report, mobile platform/recording/reward-race, payments, mobile release preflight, push, team push security, STT quota.
Full detail: [`09-supabase-backend.md`](./09-supabase-backend.md).
---
## 8. `scripts/` groups
- **CI (`scripts/ci/`, 33 files):** build/version/release (`build-all`, `sync-version`, `generate-checksums`, `verify-release-metadata`, `create-release-tag`, `extract-release-notes`), security (`check-no-hardcoded-secrets`), mobile release gates (`verify-mobile-release-boundary/-config/-build-config`, `verify-android-artifact/-app-links`, `verify-play-store-assets`, `prepare-whisper-model`, `create-mobile-release-evidence`, `prepare-mobile-release-publication`, emulator/CSPRNG gates), keys (`create-desktop-license-keypair`, `create-release-evidence-key`, etc.), publish (`publish-forgejo-release` canonical, `publish-gitlab-release` mirror; the legacy `sync-and-publish-forgejo-release`/`upload-asset-to-forgejo-release` scripts were deleted 2026-09-26, Wave 3, cd9d199), env/tooling (`bootstrap-linux-toolchain.sh`, `audit-nas-stt-config.ps1`, mobile local E2E scripts).
- **Packaged native gate:** `verify-native-abi.mjs` rejects a packaged `better_sqlite3.node` that the host Node runtime can load (wrong ABI) and requires the target-specific `uiohook-napi/prebuilds/<platform>-<arch>/uiohook-napi.node`. `--self-test` proves the missing/present N-API fixture; relative and absolute `--dir` inputs resolve to the same package. `build-desktop-installer.mjs` and `build-portable.mjs` repair only the better-sqlite3 ABI, verify both native contracts, and require `resources/app-update.yml` before publication.
- **Deploy/release:** `deploy-nas.ps1/.sh`, `nas-control.sh`, `publish-gh.ps1`, `gen-keystore.js` (`deploy-site-to-nas.js` deleted 2026-09-26, Wave 3, cd9d199 — site deploy is Cloudflare Pages only).
- **Android artifact verification (2026-11-01):** `verify-android-artifact.mjs` parses both legacy `Signer #1` and Build Tools 37 `V2/V3.x Signer` certificate output. Self-test and the actual universal E2E APK verification pass with Build Tools `37.0.0`.
- **GCP/Google OAuth automation + inspection (~70 `*.mjs`):** `auto-configure-oauth`, `automate-google-oauth`, `setup-consent`, `create-*-client`, `check-*`, `inspect-*` — mostly one-off/browser-driven console automation.
- **AdMob console automation:** `admob-probe.mjs` (read-only login/app/ad-unit probe), `admob-login.mjs` (one interactive headful Chrome login into a persistent profile), `admob-automate.mjs` (dry-run by default; `--apply` creates/verifies banner+rewarded units and reports Play-store link). Uses `playwright` with `channel: 'chrome'` and the gitignored `.chrome-playwright-profile`.
- **Clean-up:** `scripts/ci/clean-deep.mjs` (`npm run clean:deep`, `--dry-run`) strips monorepo `out`/`dist`/`.next`/`bin`/`obj`/Android `build`/`.maestro-output`, temp `.chrome-*`/`.playwright-*` profiles, and any dangling `apps/mobile-rn/node_modules/d3ro-voice-monorepo` reparse point. The untracked `scripts/local/` dump directory (109 one-off probe scripts) and 16 unreferenced loose root scripts were deleted on 2026-11-13.
- **E2E / verification:** `test-and-capture-all-10-ad-services.js`, `verify-live-production-d3ro.js`. The old ad-hoc `e2e-desktop-*.js` / `real-app-multi-tab-e2e.js` / `run_e2e_*.cjs` runners were deleted 2026-11-04 (machine-specific paths, no references); Playwright specs under `apps/desktop/tests/e2e` are the E2E path.
- **Screenshots/captures:** `capture-*.js`.
- **Forgejo ops:** `check-forgejo-actions-runs.js`, `capture-forgejo-*.js`.
> `scripts/` is large and partially scratch. Prefer `scripts/ci/*` for anything release-gated, and `server/supabase/tests` for backend integration.
---
## 9. Release & versioning SSOT
| File | Purpose |
|---|---|
| `release/product-version.json` | version `1.16.5`, `androidVersionCode`/`iosBuildNumber` `1160500`, desktop license keyId |
| `release/android-release-identity.json` | package `com.d3ro.voice`, Play app ID, app-signing SHA-256, upload cert SHA-256, evidence keyId, AdMob unit IDs |
| `release/desktop-license-public.pem` | Ed25519 public key for desktop offline licenses |
| `release/mobile-release-evidence-public.pem` | Ed25519 public key for mobile release evidence |
| `apps/desktop/electron-builder.yml` | appId `com.d3ro.voice`, NSIS x64 (forced code signing), macOS DMG/ZIP arm64, generic Forgejo publish feed, asarUnpack native modules (`better-sqlite3`, `uiohook-napi`, `koffi`, `@koromix`, `@ffmpeg-installer`; `@nut-tree-fork` unpacked on macOS only), extraResources (icons, sounds, filtered `sox.exe`+`zlib1.dll`+`LICENSE.GPL.txt`, **sidecar**, ffmpeg, ollama) |
| `apps/desktop/src/main/update-feed.ts` | Auto-update feed SSOT (canonical Forgejo + legacy GitLab mirror, channels) |
| `release/update-policy.json` | Update policy SSOT (channels, minimum supported version, forced update, delta/full, staged rollout, kill switch) |
| `site/src/release.ts` | Download-center desktop release contract (installer filename + release date); version and date are kept on the SSOT by `npm run version:sync` (drifted to 1.2.0 once — GAP-REL-08). `apps/web/src/lib/desktop-release.ts` and the `apps/web` download/releases pages were deleted 2026-09-26 (Wave 3, cd9d199) — `site/` is the only download surface, and `/download`/`/releases` on `apps/web` now redirect to it |
| `apps/desktop/src/main/update-policy.ts` | Policy parsing/decision logic |
| `scripts/ci/publish-forgejo-release.mjs` | Canonical Forgejo registry + Release + feed publisher |
Version sync is enforced by `scripts/ci/sync-version.mjs` and `verify-release-metadata.mjs`; `npm run version:check` should be clean.
---
## 10. Resources & tests
- `apps/desktop/resources/sox/` — canonical bundled Windows SoX (`sox.exe`, `zlib1.dll`, `LICENSE.GPL.txt`; PE-verified, unused `wget.exe`/`pthreadgc2.dll`/PDFs and duplicate root `resources/sox/` removed 2026-11-13) for audio capture.
- `resources/ffmpeg/` — optional bundled ffmpeg (CI or manual); `getFfmpegPath()` also resolves the `@ffmpeg-installer/ffmpeg` binary from `app.asar.unpacked`.
- `apps/desktop/sidecar-dist/` — PyInstaller sidecar bundle consumed by `extraResources` (gitignored; built by `npm --prefix apps/desktop run sidecar:build`).
- `resources/icons/` — empty; electron-builder falls back to `build/icon.ico|png`.
- Desktop tests: `apps/desktop/tests/` — `unit/`, `main/`, `red/`, `shared/`, `integration/`, `eval/` run under Vitest; `e2e/` holds Playwright specs plus the shared `e2e/support/electron-app.ts` fixture (per-test temp user-data dir). Artifacts in `apps/desktop/test-results/`.
- Test taxonomy + hygiene gate: `docs/tdd-red/06-repo-application.md`. `npm run test:hygiene` (+ `:test`) rejects `.only`, reason-less `.skip()`, trivial assertions, `isVisible()`-gated assertions, machine-specific paths, `waitForTimeout`, and `.e2e.test.ts` names; wired into CI `quality`.
- Test-system gates (TDD 2.0 Phases 0–5, 2026-11-08..13):
- `npm run test:metrics` / `test:metrics:write` — suite/file/case/assertion counts across all 10 suites (incl. `@d3ro/i18n` and `@d3ro/ui`) plus weak-assertion and ambient-time totals; writes `docs/tdd-red/metrics/<date>.md`. Metric only, never fails.
- `npm run check:protected-tests` (+ `:test`) — `scripts/ci/check-protected-tests.mjs` diffs the six protected acceptance specs (`06 §5`) against a base revision and fails when tests, assertions, or `.only`/`.skip` change without an `allow-protected-change:` commit marker. CI runs it against `HEAD^` (the quality job fetches depth 2).
- `npm run test:quality` (+ `:test`, `:update`) — ratchet over `scripts/ci/test-quality-baseline.json`: per-file weak-assertion and ambient-time counts may only go down (scans both tracked and untracked working-tree test files). `--update` is a reviewed action.
- `npm run check:i18n` (+ `:test`) — `scripts/ci/check-i18n-contract.mjs` verifies 12-locale 2,500-key set equality, non-empty strings, `{{placeholder}}` parity, literal `t('...')` key existence, and unreferenced-key budget (`<=35`).
- `npm run check:ds-contract` (+ `:test`) — `scripts/ci/check-ds-contract.mjs` verifies `@d3ro/ui` DS component exports, zero raw hex outside `theme.ts`/`theme-raw.ts`, required ARIA roles (`SegmentControl` `tablist`/`tab`), and DS contract test references.
- `npm run test:affected` (+ `:test`) — `scripts/ci/run-affected-tests.mjs` maps git diffs to targeted Vitest/Jest/Deno/.NET test commands and safely falls back to the full suite on unmapped paths (CI continues to run full suites).
- `npm run release:installer:smoke` (+ `:test`) — `scripts/ci/verify-desktop-installer-smoke.mjs` validates NSIS `.exe` PE64 headers, gzip `.blockmap` magic, `latest.yml` SHA-512 & byte size, `win-unpacked` `D3RO Voice.exe` PE64, `resources/app-update.yml` feed URL, `resources/app.asar` Chromium Pickle JSON header, and optional Ed25519 `.sig` manifest signature inside `release-desktop.mjs` and `.forgejo/workflows/release.yml`.
- Shared file-detection helpers live in `scripts/ci/lib/test-files.mjs` so `test:metrics` and `test:quality` inspect the exact same test files.
- Mobile tests: `apps/mobile-rn/__tests__/` (89 suites / 605 tests PASS on 2026-11-13), `.maestro/` + `.maestro-output/` E2E evidence. Note: a full parallel Jest run can hit the 5s render timeout on slow machines; `test:mobile` uses `--runInBand`.
- Web tests: `apps/web/tests/` (vitest pure-logic contracts: billing catalog, Web Push client, web STT client — now part of root `npm test`) and `apps/web/e2e/` (playwright: `smoke.spec.ts` owns the unauthenticated surface contract; billing/payple/dashboard/history are fixture-based browser journeys). Web declares its own `@playwright/test` + `vitest` devDeps (2026-11-04) instead of relying on the desktop workspace's hoisted copies.
- API tests: `apps/api-server.Tests/` (xUnit).
- Root: `test-results/.last-run.json` (no root-level e2e suite).
---
## 11. Known infrastructure gaps
See [`11-gap-backlog.md`](./11-gap-backlog.md) for the maintained list (`INFRA-*`). Headlines:
- `apps/mobile-rn` is not an npm workspace member; use `typecheck:mobile`/`lint:mobile`/`test:mobile` or `verify:all`.
- Admin NAS deploy job disabled in GitLab CI; the `package-admin-docker`→GHCR publish step lived only in the now-deleted `.github/workflows/release.yml` (2026-09-26, dc43884) and was not ported to Forgejo, so admin image publish + NAS compose update is manual (`GAP-INFRA-02`).
- Two identity systems (.NET JWT/SQLite vs Supabase); a canonical resolver now exists in `@d3ro/core/entitlement` but web/mobile/.NET adoption is incremental (`11` GAP-ID-02).
## 운영 자격 증명 위치 (2026-09-26, 값은 적지 않는다)
재로그인 없이 배포·운영하려고 모은 목록이다. 로컬 값은 루트 `.env`(gitignore), 이름 목록은 `.env.example`이 정본이다.
| 용도 | 루트 `.env` 키 | 다른 곳의 같은 값 |
|---|---|---|
| Cloudflare 터널 ingress·DNS·Pages·브리지 워커 | `CLOUDFLARE_API_TOKEN`(토큰 이름 "D3RO Voice — tunnel + DNS"), `CLOUDFLARE_ACCOUNT_ID`, `CLOUDFLARE_ZONE_ID`, `CLOUDFLARE_TUNNEL_ID`(kd-nas) | Forgejo 시크릿 `CF_API_TOKEN`·`CF_ACCOUNT_ID` |
| Supabase CLI·Management API | `SUPABASE_ACCESS_TOKEN`(만료 2027-09-25), `SUPABASE_PROJECT_REF` | — |
| Payple 정기 갱신 cron | `CRON_SECRET` | Supabase 함수 시크릿 `CRON_SECRET`, Forgejo 시크릿 `CRON_SECRET` |
| NAS 배포(ssh 별칭 `yunchan-nas`) | `NAS_HOST`, `NAS_USER`, `NAS_SSH_PORT`, `NAS_DEPLOY_PATH` | — |
| NAS compose 필수 값 | `SUPABASE_URL`, `SUPABASE_SERVICE_ROLE_KEY`, `ADMIN_BOOTSTRAP_TOKEN`, `API_SERVER_URL` 외 | NAS `/volume1/docker/d3ro/.env` |
| 웹앱 이미지 build arg | `NEXT_PUBLIC_SUPABASE_URL`, `NEXT_PUBLIC_SUPABASE_ANON_KEY`; 선택적 `NEXT_PUBLIC_PAYPLE_CLIENT_KEY`와 `NEXT_PUBLIC_VAPID_PUBLIC_KEY` (`WEBPUSH_VAPID_PUBLIC_KEY`와 같은 공개키). VAPID 공개키 누락 시 알림 UI는 unavailable로 fail-closed | `.env` / NAS build environment; `NEXT_PUBLIC_*`는 이미지 build-time에 고정 |
| Forgejo API | `FORGEJO_TOKEN` | Forgejo 시크릿 `FORGEJO_TOKEN` |
- 공개 라우팅: `d3ro.chanpaca.net` → 브리지 워커 → `/app`·`/api`·`/health`는 터널 kd-nas(NAS 3002·5050), 그 밖은 Pages `d3ro`. 터널 ingress `d3ro.chanpaca.net` path `^/app` → `http://192.168.0.39:3002`.
- Supabase Auth: `site_url=https://d3ro.chanpaca.net/app`, 허용 목록에 `/app/**`.