From 60967a630d7753441d7254236a66f4764fca9acc Mon Sep 17 00:00:00 2001 From: Danijel Martinek Date: Thu, 7 May 2026 20:41:54 +0200 Subject: [PATCH] docs(plan-10): finalize ADR-014 + tick refactor log MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replaces the ADR-014 stub with the full Accepted-status decision record: context, the 7 numbered decisions (vendor-neutral interfaces, full-depth instrumentation, throw-site capture, PII rules, three Sentry projects, ESLint boundary, Recording* test pair), alternatives considered, positive/negative consequences, and an "execution notes" section covering the spec deviations and surprises encountered. Updates the refactor log: ticks all 33 tasks, populates "Decisions deviated from spec" (PII key list extended with ipaddress; spec section appended as §16 not §10; vite.config skipped; HTML section numbering kept conservative) and "Notable surprises" (apps needed direct core-shared deps; deep subpath exports for dynamic import; peerDependenciesMeta.optional for @sentry/node and @sentry/react; pre-existing lint debt; allowlist patterns needed **/-prefix for flat-config glob matching from sub-package cwd). Final verification (run before commit): - pnpm test → 26/26 tasks pass - pnpm lint → 15/15 tasks pass (warnings-only) - pnpm typecheck → 14/14 tasks pass - R31 grep gate (sendDefaultPii: true) → clean, no matches Co-Authored-By: Claude Opus 4.7 (1M context) --- .../adr-014-instrumentation-sentry.md | 68 +++++++++++++- .../2026-05-06-instrumentation-sentry.md | 90 ++++++++++++------- 2 files changed, 120 insertions(+), 38 deletions(-) diff --git a/docs/decisions/adr-014-instrumentation-sentry.md b/docs/decisions/adr-014-instrumentation-sentry.md index 6ea3d0a..5adba53 100644 --- a/docs/decisions/adr-014-instrumentation-sentry.md +++ b/docs/decisions/adr-014-instrumentation-sentry.md @@ -1,17 +1,77 @@ # ADR-014 — Instrumentation & Sentry Logging -**Status:** Proposed (will be Accepted on Plan 10 completion) +**Status:** Accepted **Date:** 2026-05-06 **Spec:** docs/superpowers/specs/2026-05-06-instrumentation-sentry-design.md +**Plan:** docs/superpowers/plans/2026-05-06-plan-10-instrumentation-sentry.md ## Context -(stub — finalized in Task 33) +The monorepo had no distributed tracing or error capture. Production failures surfaced only via stdout / stderr from a Vercel function log. We needed: + +1. End-to-end traces (browser → tRPC → use case → repo → Payload) to diagnose latency without ad-hoc timers. +2. Centralized exception capture so silent failures (especially in CMS mutations) get a permanent record with stack + context. +3. Privacy posture suitable for production: scrubbing for PII, masked replay, no opaque-vs-named user identifiers. + +The Lazar Nikolov reference repo (`nextjs-clean-architecture`) demonstrates a Sentry-driven pattern with `Sentry.startSpan` and `Sentry.captureException` calls inline in use cases and repos. We needed to adapt this to: + +- Three apps (web-next, cms, web-tanstack) — not one. +- Per-feature DI (ADR-008) — not a single container. +- Vendor neutrality — feature packages must not import `@sentry/*` directly. ## Decision -(stub — finalized in Task 33) +**1. Vendor-neutral interfaces in `core-shared/instrumentation/`.** Two interfaces (`ITracer`, `ILogger`) with three implementation pairs (`Noop*`, `Sentry*`, `Recording*`). Feature packages depend only on the interfaces. + +**2. Full-depth instrumentation.** Spans nest at every layer: tRPC procedure (auto) → controller (DI-wrapped) → use case (DI-wrapped) → repository (explicit `startSpan`) → Payload (auto). Use case + controller spans applied via `withSpan` higher-order wrapper at DI binding time so factory code stays unchanged. Repositories pay explicit boilerplate per method — accepted cost for per-method visibility. + +**3. Throw-site capture with double-report guard.** `Sentry.captureException` fires only at the layer that originates the error (repos catch infra; use cases catch their own throws; controllers catch parse failures; middleware does not capture). A non-enumerable `__sentryReported` flag prevents re-capture as errors bubble. + +**4. Hard PII rules (R31–R38).** `sendDefaultPii: false` (CI-grep enforced); replay default-masks all text/inputs/media (allowlist empty by default); `beforeSend` / `beforeSendTransaction` scrubbers strip emails/passwords/tokens/cookies/auth/IPs (substring-matched, including derived names like `userEmail`, `accessToken`, `apiKey`, `ipAddress`); `setUser` accepts only `{ id }`. + +**5. Three Sentry projects, orthogonal binding.** Each app gets its own DSN. `bindAll()`'s Rule 0 (DSN → Sentry vs Noop) is independent of `USE_DEV_SEED` / `NODE_ENV` repo binding. Optional dev-mode Sentry: developer can run `pnpm dev` with `SENTRY_DSN` set to test integration locally. + +**6. ESLint boundary rule (R40).** `no-restricted-imports` blocks `@sentry/*` outside the allowlisted paths: `core-shared/instrumentation/sentry/**`, `instrumentation/di/bind-sentry-instrumentation.{ts,test.ts}`, `core-testing/setup/no-sentry.{ts,test.ts}`, and the apps' `instrumentation*.{ts,mjs}` / `next.config.{mjs}` / `vite.config.{ts}` entries. Allowlist patterns use `**/`-prefix so they match whether ESLint runs from the repo root or from inside a sub-package. + +**7. Test-side `RecordingTracer` / `RecordingLogger`** in `core-testing/instrumentation/`. Tests inject them directly into factory functions (consistent with R27 from Plan 9 — direct-injection, not container manipulation). The `core-testing/setup/no-sentry.ts` setup file mocks `@sentry/nextjs`, `@sentry/node`, and `@sentry/react` at the module level, so any code that imports them gets a no-op surface during vitest runs (R49). + +## Alternatives considered + +- **Direct `@sentry/nextjs` imports in features (Lazar's pattern).** Rejected — couples every feature package to a vendor SDK, violating the architecture's vendor-isolation principle. +- **Procedure-only spans (no per-use-case or per-repo spans).** Rejected — would lose the breakdown that makes a slow request diagnosable. The middle path (procedure + use case + controller, no per-repo) was rejected for the same reason at a finer granularity. +- **Capture in `defineErrorMiddleware` only.** Rejected — would noisily report every input-parse / unauthenticated error as a Sentry event, polluting the inbox. +- **Single Sentry project for all apps with environment tags.** Rejected — different alert routing, different quotas. Three projects scale better. +- **Always-Sentry in all environments.** Rejected — `pnpm test` and `pnpm dev` should not initialize a real SDK by default. Optional dev (DSN-driven) is the cleanest rule. +- **Replay flags as configurable env vars.** Rejected — the privacy posture must be the default; opt-out requires per-selector justification (R34, R51). ## Consequences -(stub — finalized in Task 33) +**Positive:** +- End-to-end traces in Sentry with full context. +- One captured event per error (no double-report, no noise from expected domain errors). +- Privacy-by-default replay and scrubbing. +- Vendor-swappable: replacing Sentry means writing one new adapter pair in `core-shared/instrumentation//`. +- Tests run against `Recording*` for assertions; `Noop*` by default. + +**Negative:** +- Every public repo method gains ~6 lines of `tracer.startSpan(...)` boilerplate. Mitigated by uniform pattern; if it ever proves excessive, a `withRepoSpan` collapse helper can be added. +- `__sentryReported` flag mutates errors. Non-enumerable, so JSON / spread are unaffected; flag is checked only inside `SentryLogger`. +- Three Sentry projects to administer. +- Replay bundle peak (~250KB on errored sessions) — accepted; healthy sessions don't load replay payload. + +## Notes from execution + +- **PII key-substring extension (deviation from spec):** the original spec listed only explicit PII keys (`email`, `password`, `token`, etc.) for substring matching. During Task 25 we added `ipaddress` to `PII_KEY_SUBSTRINGS` so keys like `ipAddress` trigger key-level redaction. This is a tighter privacy posture than the spec's substring list — the spec's intent (no PII in events) is honoured strictly; existing `scrub.test.ts` cases continue to pass. +- **Web-tanstack vite.config.ts deferred:** the app currently has no `vite.config.ts` (build is a placeholder per its `package.json`). The `@sentry/vite-plugin` dep is added but unused until the TanStack Start build is wired in a later plan. A minimal `src/vite-env.d.ts` shims `ImportMetaEnv` for the client entry until the full Vite types land. +- **Subpath exports:** `core-shared/package.json` gained five new subpath entries (`./instrumentation/sentry/{init-server,init-client,init-server-node,init-client-react,scrub}`) so the apps' `instrumentation*.ts` files can import the helpers via deep paths without pulling the entire barrel. +- **`@sentry/node` + `@sentry/react`** added as optional `peerDependencies` of `core-shared` (so feature packages don't transitively pull them) and as `devDependencies` (so typecheck/test runs in `core-shared` resolve them). +- **Pre-existing lint nits surfaced when Task 28's restricted-imports rule lit up `pnpm lint`:** added `argsIgnorePattern: "^_"` to the shared eslint config (matches the underscore convention used throughout the repo); added `globals.node` for `*.{mjs,cjs,js}` and `*.config.{ts,tsx}` so `next.config.mjs`'s `process.env` lints clean; cleared two unused-import / unused-disable nits in marketing-pages and core-testing that were unrelated to instrumentation but blocked the lint gate. +- **Direct `@repo/core-shared` deps:** `apps/cms` and `apps/web-tanstack` previously had only transitive access to `@repo/core-shared`; both gained explicit `workspace:*` deps so the deep `./instrumentation/sentry/*` subpath imports resolve. + +## Related + +- ADR-008 — per-feature DI containers +- ADR-011 — TDD foundation +- ADR-012 — Lazar pattern conformance +- ADR-013 — input/output unification +- Plan 10 spec (R31–R55) diff --git a/docs/superpowers/refactor-logs/2026-05-06-instrumentation-sentry.md b/docs/superpowers/refactor-logs/2026-05-06-instrumentation-sentry.md index 51d2842..faed6ae 100644 --- a/docs/superpowers/refactor-logs/2026-05-06-instrumentation-sentry.md +++ b/docs/superpowers/refactor-logs/2026-05-06-instrumentation-sentry.md @@ -8,43 +8,65 @@ ## Tasks - [x] Task 1 — Scaffold refactor log + ADR-014 stub -- [ ] Task 2 — Tracer interface + ISpan + AttributeValue + SpanOpts -- [ ] Task 3 — NoopTracer -- [ ] Task 4 — Logger interface + NoopLogger + Breadcrumb + CaptureContext -- [ ] Task 5 — withSpan helper -- [ ] Task 6 — Symbols + index barrel -- [ ] Task 7 — SentryTracer adapter -- [ ] Task 8 — SentryLogger adapter (with double-report guard) -- [ ] Task 9 — pii-fields constants + scrub.beforeSend / scrub.beforeSendTransaction -- [ ] Task 10 — init-server helper -- [ ] Task 11 — init-client helper (browser-only) -- [ ] Task 12 — bindNoopInstrumentation + bindSentryInstrumentation -- [ ] Task 13 — apps/web-next bindAll() Rule 0 dispatcher -- [ ] Task 14 — Tests for bindAll() orthogonality (R47) -- [ ] Task 15 — RecordingTracer in core-testing -- [ ] Task 16 — RecordingLogger in core-testing -- [ ] Task 17 — vitest.setup.ts binds Noop by default -- [ ] Task 18 — Blog feature wiring (pilot) -- [ ] Task 19 — Auth feature wiring -- [ ] Task 20 — Marketing-pages feature wiring -- [ ] Task 21 — Navigation feature wiring -- [ ] Task 22 — Media feature wiring -- [ ] Task 23 — defineContractSuite expectSpan helper -- [ ] Task 24 — Update repo contract suites to assert span shape -- [ ] Task 25 — apps/web-next instrumentation files + scrubber test -- [ ] Task 26 — apps/cms instrumentation files + scrubber test -- [ ] Task 27 — apps/web-tanstack instrumentation files + scrubber test -- [ ] Task 28 — ESLint boundary rule (R40) + CI grep gate (R31) -- [ ] Task 29 — turbo.json globalEnv updates -- [ ] Task 30 — Doc updates (CLAUDE.md, AGENTS.md, vertical-feature-spec.md) -- [ ] Task 31 — Doc updates (tdd-workflow.md, testing-strategy.md, dependency-flow.md, core-shared/AGENTS.md) -- [ ] Task 32 — HTML updates (data-flow-explainer §07, di-explainer additions) -- [ ] Task 33 — ADR-014 final + refactor log final +- [x] Task 2 — Tracer interface + ISpan + AttributeValue + SpanOpts +- [x] Task 3 — NoopTracer +- [x] Task 4 — Logger interface + NoopLogger + Breadcrumb + CaptureContext +- [x] Task 5 — withSpan helper +- [x] Task 6 — Symbols + index barrel +- [x] Task 7 — SentryTracer adapter +- [x] Task 8 — SentryLogger adapter (with double-report guard) +- [x] Task 9 — pii-fields constants + scrub.beforeSend / scrub.beforeSendTransaction +- [x] Task 10 — init-server helper +- [x] Task 11 — init-client helper (browser-only) +- [x] Task 12 — bindNoopInstrumentation + bindSentryInstrumentation +- [x] Task 13 — apps/web-next bindAll() Rule 0 dispatcher +- [x] Task 14 — Tests for bindAll() orthogonality (R47) +- [x] Task 15 — RecordingTracer in core-testing +- [x] Task 16 — RecordingLogger in core-testing +- [x] Task 17 — vitest.setup.ts binds Noop by default +- [x] Task 18 — Blog feature wiring (pilot) +- [x] Task 19 — Auth feature wiring +- [x] Task 20 — Marketing-pages feature wiring +- [x] Task 21 — Navigation feature wiring +- [x] Task 22 — Media feature wiring +- [x] Task 23 — defineContractSuite expectSpan helper +- [x] Task 24 — Update repo contract suites to assert span shape +- [x] Task 25 — apps/web-next instrumentation files + scrubber test +- [x] Task 26 — apps/cms instrumentation files + scrubber test +- [x] Task 27 — apps/web-tanstack instrumentation files + scrubber test +- [x] Task 28 — ESLint boundary rule (R40) + CI grep gate (R31) +- [x] Task 29 — turbo.json globalEnv updates +- [x] Task 30 — Doc updates (CLAUDE.md, AGENTS.md, vertical-feature-spec.md) +- [x] Task 31 — Doc updates (tdd-workflow.md, testing-strategy.md, dependency-flow.md, core-shared/AGENTS.md) +- [x] Task 32 — HTML updates (data-flow-explainer §06, di-explainer §08) +- [x] Task 33 — ADR-014 final + refactor log final ## Decisions deviated from spec -(populate as work progresses) +- **PII key-substring list extended (Task 25).** Added `"ipaddress"` to `PII_KEY_SUBSTRINGS` so keys like `ipAddress` trigger full key-level redaction in addition to the existing IPv4/IPv6 string-pattern redaction. The plan's R38 PII-scrubber test expected `result.extra.ipAddress === "[redacted]"`, which the original substring list (without "ipaddress") could not satisfy. Tighter posture than the spec; existing scrub.test.ts continues to pass. + +- **vertical-feature-spec.md numbering (Task 30).** The plan instructed to add the instrumentation section as "§10". The spec already had 15 sections, so the section was appended as **§16** (rather than renumbering §10–§15) to avoid invalidating every cross-reference in the spec. + +- **Web-tanstack `vite.config.ts` modifications skipped (Task 27, Step 6).** The app is a placeholder — its `package.json` has `"build": "echo 'placeholder — TanStack Start build configured in later plan'"` and there's no `vite.config.ts`. The `@sentry/vite-plugin` dep is installed but dormant; it will be wired into the build when TanStack Start build is configured. A minimal `src/vite-env.d.ts` shims `ImportMetaEnv` for the client entry's `import.meta.env` reads. + +- **data-flow-explainer.html section numbering (Task 32).** The plan asked to renumber the verdict from §06 to §07 and slot the new tracing section in as §06 — done. The `