Lawma2 — Decisions Log
Append-only architectural and product decisions. Per the global decision-hygiene skill: never edit history; supersedences are new entries that flip the old entry's status. Dismissed alternatives are captured so they don't get re-offered.
Body structure of every D-entry: the decision, Why:, How to apply:, Cascade required:.
Decision Index (auto-maintained)
| ID | Title | Status | Decided | Supersedes | Superseded by |
|---|---|---|---|---|---|
| D47 | Published-interview immutability (HARD RULE, locked 2026-07-04): any edit to a published interview MUST create a subsequent DRAFT version — the published version is untouched until the new version is either (a) approved through the attorney-review queue + published, or (b) the published version is explicitly deprecated by a Lawma admin. In-flight client sessions on the published version continue against the version they started on (version-pin is D42 Principle 1). No editor path may write to a published body directly; every mutation forks. This governance rule is what keeps a mid-flight client from seeing a form change under them AND what keeps unauthorized edits out of production. Dismissed alternatives: (a) allow "quick fix" edits to published body — rejected, breaks version-pin invariant; a "quick fix" that a running session hits is a mid-flight schema change; (b) auto-publish on save when the editor has admin role — rejected, bypasses the attorney-review gate that gives legal edits their trust; (c) deprecate + edit — that's a two-step, not the default; use it deliberately when a published version is broken and can't wait. | 🟢 LIVE | 2026-07-04 | — | R123-immutable / T109 |
| D46 | Scale-migration execution refinements (refines D41 Phase 2 + D44, supersedes neither): (1) the default AWS migration landing spot is the AWS wrapper ladder — Amplify Hosting for the web tier (AWS's Next.js-aware deploy service on CloudFront), Aurora Serverless v2 + RDS Proxy for the database, SQS + Lambda for workers; raw ECS/Fargate is the graduate-DOWN option, not the entry point (caveat: verify Amplify runs our exact Next.js version at migration time; fallback App Runner → ECS). (2) Phase 2 scale-migration entry gate = EVIDENCE (load growth or enterprise-buyer diligence) AND OPS CAPACITY (DevOps hire or retained AWS-certified MSP), not calendar arrival — until both hold, Netlify + Neon remain correct. (3) Pin-plus-alert is ONE control: exact pins are only safe while vulnerability alerting is live; GitHub vulnerability alerts enabled on the repo 2026-07-03 (zero Actions cost; auto-fix PRs deliberately off). Dismissed: raw ECS as entry default, AWS Managed Services (enterprise-priced overkill), calendar-triggered migration, Dependabot auto-fix PRs (push-minimization). | 🟢 LIVE | 2026-07-03 | — | R121 / T255 |
| D45 | Postgres driver: KEEP postgres (Porsager) + PIN exactly (3.4.9), pg documented as escape hatch — the benchmark in T254 is cancelled (no decision-changing threshold; Neon endorses postgres, Drizzle supports it first-class, it's Aurora-compatible). Also records two R120 execution refinements from the Opus 4.8 review (2026-07-03): json-logic-js is WRAP+PIN (single owned import boundary at lib/interview/json-logic/), NOT fork+rewrite; the PDF/DOCX/ZIP suite is PIN+AUDIT now, sandbox deferred to Phase 2 (T241). Dismissed: benchmark-then-decide (procrastination without a threshold), migrate to pg now (real work for no demonstrated gain), leave on caret range (the unexamined-dependency posture R120 exists to close). | 🟢 EXECUTED | 2026-07-03 | — | R120 / T254 |
| D44 | Long-term infrastructure posture: own the cloud services directly on a tier-1 hyperscaler (AWS default, or GCP/Azure); managed layers on top of the hyperscaler (Netlify, Vercel, Neon, Supabase, etc.) are TEMPORARY pre-scale conveniences unless a specific vendor provides a MEANINGFUL AI ADVANTAGE Lawma engineering could not replicate in ~2 weeks on the hyperscaler natively. Concrete criteria for "meaningful AI advantage": (1) native LLM-provider integration >2 weeks to replicate; (2) infrastructure capability Lawma cannot operate at reasonable cost (e.g. sub-ms-SLA vector DB); (3) cost profile beating AWS-native by >50% for our workload; (4) latency/geography AWS cannot match. Convenience/DX alone does NOT clear the bar. Consequence: Netlify → migrate away in scale phase; Neon → migrate to AWS Aurora Postgres unless Neon's AI story becomes uniquely compelling by decision time; Vercel → considered only if their AI SDK / edge / streaming for LLM beats AWS Bedrock + Lambda@Edge + our own code. Anthropic/Stripe/Sentry/Datadog/Auth0/GitHub are NOT subject (specialized SaaS, not hosting layers). Dismissed: stay on Netlify+Neon indefinitely (single-region-ish, narrower certs, vendor concentration), hybrid managed-dev-AWS-prod as long-term (acceptable as implementation tactic, not long-term posture), multi-cloud from day one (complexity disproportionate at scale). The DX cost of this decision is real and accepted explicitly. | 🟢 LIVE (strategic direction; execution unfolds through scale-infrastructure phase) | 2026-07-03 | — | D41 Phase 2 sub-decisions resolved by this / T241 |
| D43 | Tiered third-party dependency policy — every direct npm dep gets classified: Tier A (major-corp backed: Meta, Microsoft, Anthropic, Stripe, Sentry, Vercel — keep), Tier B (funded startup or well-audited standard: Drizzle, Tailwind, ajv — keep + monitor), Tier C (individual maintainer but accepted with mitigation: jose narrow-scope, dnd-kit Builder-only), Tier D (individual maintainer security-critical or load-bearing — replace / fork / vendor+audit+sandbox). Tier D concrete: (1) bcryptjs REPLACE with Node stdlib crypto.scrypt; (2) json-logic-js FORK into lib/interview/json-logic/; (3) pdf-lib + docx suite + jszip VENDOR + AUDIT + PIN + SANDBOX in Phase 2 workers; (4) postgres driver EVALUATE swap to pg. New-dep policy going forward: every new package.json addition names its tier at PR review; Tier D requires mitigation choice. Dismissed do-nothing (Dependabot is detection not prevention), fork-everything (unmaintainable), replace-all (thousands of hours on pdf-lib alone), single-sprint (moves have different urgencies), parallel-with-runtime-refactor (both touch interview engine — sequence instead). | 🟢 EXECUTED 2026-07-03 (two tactic refinements in D45: json-logic-js WRAP+PIN not fork; postgres driver KEEP+PIN not migrate) | 2026-07-03 | — | R120 / T251–T254 |
| D42 | Long-interview runtime design principles — page-at-a-time server-truth rendering (Principle 1), save-on-page-transition batch (Principle 2, Riyaz's amendment), idempotent (session_id, question_key, repeat_index) saves (Principle 3), IndexedDB per-blur local buffer + restore-on-load (Principle 4), layered tab-close protection with browser beforeunload + sendBeacon + IndexedDB fallback (Principle 5), resume-anywhere URL + section checkpoints (Principle 6), dedicated long-lived interview session cookie decoupled from auth (Principle 7), LLM opt-in/bounded/cached/async-when-possible (Principle 8). Version pinning is a corollary of Principle 1 — sessions lock to a published body at start. Dismissed client-holds-everything (mobile fails), per-blur save (network noise), synchronous LLM per question (rate limits + cost), shared auth cookie (session expiration = data loss), custom modal on tab close (browsers block it since 2016; sendBeacon + IndexedDB is functionally better anyway), big-bang cutover (feature-flag per slice instead), deferring the refactor (same cost later, under production pressure — worse). | 🟡 LOCKED — building (green-lit 2026-07-03) | 2026-07-03 | — | R119 / T244–T250 |
| D41 | Adopt the four-phase enterprise-grade transition plan (docs/plans/2026-07-03-enterprise-grade-transition-plan.md) as the canonical roadmap to real-user readiness. Three tracks — (1) resolve the three named security risks (supply-chain, own-code discipline, client-side secrets) via CI-enforced automation + threat models; (2) scale infra to absorb ~1–10M users / ~500K concurrent (Vercel-or-AWS web tier, Aurora-or-Neon-Enterprise DB with read replicas + PgBouncer, Redis + SQS worker pool, Anthropic Enterprise, Cloudflare/CloudFront + WAF, Datadog); (3) certifications (SOC 2 Type I → Type II → conditional ISO 27001 / HIPAA-adjacent / FedRAMP). Phases: 0 (foundation hygiene, 0–3mo) → 1 (pre-audit readiness + Auth0/RLS live, 3–9mo) → 2 (SOC 2 T1 + scale migration, 9–15mo) → 3 (SOC 2 T2 + multi-region + published SLA, 15–24mo) → 4 (enterprise breadth, 24–36mo). The gating principle: never let engineered scale outrun engineered trust — no shipping at scale without the attestations. Trust Advantages Ledger (added at Phase 0 approval, 2026-07-03) — living section in the plan doc where every shipped deliverable's outcome is captured in plain-English trust language, so it's usable in sales / investor / hiring conversations without translation. Dismissed alternatives: (a) skip SOC 2 until a buyer forces it — rejected: cert takes 12–24mo, waiting until a buyer asks means losing the deal; (b) go straight to Type II — rejected: Type II requires a 6–12mo observation window on documented controls (i.e. on Type I's foundation), skipping Type I doesn't compress the calendar; (c) pursue FedRAMP now — rejected: $500K+, 18–36mo, no federal contract on the table; revisit when one is; (d) build our own IdP instead of Auth0 — rejected, DIY MFA in legal software is existential risk (already D28); (e) self-host on-prem for enterprise buyers — rejected, would drown our velocity; SOC 2 + DPA + BAA is the industry-standard alternative; (f) skip pen test — rejected, real signal an auditor + automation can't produce, and enterprise legal InfoSec reviews expect it. | 🟢 LIVE (Phase 0 approved 2026-07-03; later phases stage-gated) | 2026-07-03 | — | R118 / T234–T243 |
| D40 | Anchor-framing rule for market-gap claims: cite the source-of-record's exact framing verbatim; if the "flavor" version we prefer isn't in-hand from that source, drop the specific number rather than ship an unsourced-but-narratively-convenient one. Applied first to LSC "justice gap" (A1) — CANON.lscGap flipped from "~71% turned away" (unsourced against LSC 2022) to "92%" (LSC 2022 headline verbatim, "civil legal problems inadequately served"); cascade landed same-day through business-plan / pitch-deck / for-attorneys / footnote #2. "Turned away" narrative preserved qualitatively ("capacity-bound") but no unsourced % kept. Dismissed: (b) keep 71% + fix footnote + source it (T229 first pass didn't find one after deliberate search), (c) hybrid headline-92-secondary-71 (secondary still lacked a specific source), (d) do nothing (fails the Skeptic v1 "Google-it-in-30-seconds" test). Same pattern to apply to A4 / A6 / A9 as they cascade. | 🟢 LIVE | 2026-07-03 | — | R99 / T229 |
| D39 | Repeats + tables ride ONE row-index model: section-level repeat (walk a page N times), include-block repeat (bake a nested interview N times at publish — reuses D37's seam), and a first-class type: "table" question. Every surface produces (scope, index, key) tokens the composer + form-fill resolve uniformly. Storage keys by (question_key, repeat_index) — existing schema, no migration. Composer signature is strict-typed — no scalar auto-shim; every composer opts in with a typed path (shark pass 1). Two Builder UXes — section/include repeat share one, tables get their own — on the same storage (shark pass 2). scope on every repeat spec is load-bearing — it's what lets the SAME nested interview loop as "plaintiff" in one parent and "defendant" in another. item_label REQUIRED (default "{scope} {index}"; bake-time validated). Runtime never learns what a block is — same D37 discipline. Cross-row show-if + row reordering deferred. | 🟡 LOCKED — building (slice 1 next) | 2026-07-01 | builds on D37 + D38 | R95, R96 |
| D38 | Nested-interview authoring model (Phase 2 on D37): reuse is linked by default + detach-on-edit (editing a placement's CONTENT copies-on-write into an independent fork; editing its WIRING does not). Two-token wiring — a question's answer key (stable identity: storage/carry/logic) vs. its form token (where it lands on a form); the form token defaults from the answer key and is per-placement overridable without breaking the link. Concretely: no new form_token type — the answer key is the key, the form token is the mapping[], and the override is a per-placement mapping replacement on the include reference (composer forms re-target via the parent's forms[]). Visibility = inline grouping in the parent + a central library. Runtime unchanged. | 🟡 LOCKED — building (slice 1) | 2026-07-01 | builds on D37 | R88 |
| D37 | Sub-interviews = reusable interview blocks inlined at PUBLISH time (not load time). A parent declares include_blocks[]; a pure expandBlocks bakes each referenced block's sections/forms/rules into the parent's flat published body, so the runtime never learns what a "block" is (zero runtime change; no migration — body is jsonb). Chosen over load-time expansion for D24 WYSIWYG attorney review + zero runtime risk + self-contained audit (immutability is also satisfied but is NOT the differentiator — a pinned load-time approach has it too). A block edit requires republishing dependents — that is the D24 control surface, not a cost to remove. Collisions fail-closed at publish. block.ca.family.property is the first block (invoked by every divorce variant). | 🟢 LIVE (Phase 1) | 2026-07-01 | — | R86 |
| D36 | AUTH_MODE fails closed in production: when unset, resolve to auth0 (real auth) in prod and stub only in local dev — so a prod deploy that forgets the var can never silently fall into the stub bypass (no real auth + act-as-anyone switcher). Centralized in one resolveAuthMode() seam every reader routes through. Behavioral no-op for any deploy that sets AUTH_MODE explicitly (lawma611 pins stub in all contexts). | 🟢 LIVE | 2026-07-01 | — | — |
| D34 | Database stays Neon Postgres (not Supabase); Drizzle schema is portable; Neon free tier covers pre-launch. Auth0 already owns login + we own storage, so Supabase's bundled auth/storage would add a rewrite + conflicting auth for zero gain. | 🟢 LIVE | 2026-06-27 | — | — |
| D35 | The "no ads on authenticated surfaces" guardrail is SCRAPPED (Riyaz, 2026-06-28: we already place contextual partner offers on authed surfaces — process-server/notary at interview completion, etc.). Ads run across the product, INCLUDING authed surfaces; the Attorney Forum is ad-eligible. The only line is DATA, not surface: advertisers never receive client identity / intake / document data; targeting is category + jurisdiction + format + time-of-day only, placements contextual. | 🟢 LIVE | 2026-06-28 | scraps the advertiser-portal "no authed surfaces" guardrail | — |
| D33 | Breadth-first capability phase: extend the catalog of legal products on the R48 framework; spine/foundation work parked-stable; negotiation guides in (R52), multilingual out this phase (R53) | 🟢 LIVE | 2026-06-26 | — | — |
| D1 | Discovery-first before greenfield-vs-salvage decision | 🟢 LIVE | 2026-06-13 | — | — |
| D2 | Lawma2 IS the new product repo (not sidecar) | 🟢 LIVE | 2026-06-13 | — | — |
| D3 | Demo strategy: self-service = mockups; real demos = Riyaz-driven | 🟢 LIVE | 2026-06-13 | — | — |
| D4 | Canonical user-type taxonomy for Lawma2 | 🟢 LIVE | 2026-06-13 | — | — |
| D5 | Canonical object/entity taxonomy for Lawma2 | 🟢 LIVE | 2026-06-13 | — | — |
| D6 | Paired-mockup convention lifted from Lawma main | 🟢 LIVE | 2026-06-13 | — | — |
| D7 | Path C — in-place refactor + Lawma2 rebrand (build-vs-migrate decision) | 🟢 LIVE | 2026-06-13 | — | — |
| D8 | Every case needs a lead lawyer; missing surfaces as a flag (not a CHECK) | 🟢 LIVE | 2026-06-14 | — | — |
| D9 | Mockup-page architecture: app/(demo-mockups)/personas/ → URL /personas | 🟢 LIVE | 2026-06-14 | — | — |
| D10 | Matchmaking marketplace browse is public; account required only at "request match" | 🟢 LIVE | 2026-06-14 | — | — |
| D11 | Path B locked: main = dev (lawma611) + production = prod (lawmaco); fast-forward only; light gate | 🟢 LIVE | 2026-06-14 | — | — |
| D12 | Retire FOUNDER_EMAIL; lawma_admin IS the platform-owner role | 🟢 LIVE | 2026-06-16 | — | — |
| D13 | Public site = second Netlify deploy off production, env-var gated (NOT a third branch) | 🟢 LIVE | 2026-06-16 | — | — |
| D14 | 8th-grade reading level baked into every client-facing AI prompt template (not Carmen's edit task) | 🟢 LIVE | 2026-06-17 | — | — |
| D15 | Native court-grade e-signature module inside Lawma (no DocuSign / external e-sig) | 🟢 LIVE | 2026-06-17 | — | — |
| D16 | Capture attorney edits on AI output as a structured corpus + extend /app/admin/ai-feedback with an Edits review tab | 🟢 LIVE | 2026-06-17 | — | — |
| D17 | Dual-role (firm_admin + practicing lawyer) modeled via case_participant, NOT a roles table | 🟢 LIVE | 2026-06-17 | — | — |
| D18 | First lawyer to register a new firm becomes its firm_admin automatically | 🟢 LIVE | 2026-06-17 | — | — |
| D19 | Firm-admins can invite additional firm-admins (existing members or new users); no role cap | 🟢 LIVE | 2026-06-17 | — | — |
| D20 | Firm merge requests via firm_merge_request table; lawma_admin approves; soft-merge via firm.merged_into_firm_id | 🟢 LIVE | 2026-06-17 | — | — |
| D21 | R20 v1 scope = pay-now-with-7-day-refund only; defer two-mode trial-state lifecycle | 🟢 LIVE | 2026-06-18 | — | — |
| D22 | R18 v1 scope = typed-name signatures + 3 non-negotiables; drawn-signature v1.5; polish v2 | 🟢 LIVE | 2026-06-18 | — | — |
| D24 | Post-refund answer-handling = RETAIN-WITH-NOTICE (audit-strict; matches CA state-bar 5-year retention) | 🟢 LIVE | 2026-06-18 | — | R4 phase 1 |
| D25 | R18 production deploy gated on a CA UETA lawyer signoff naming per-flow questions (typed / drawn / counterparty-invite) | 🟠 OVERRIDDEN by D29 (gate waived 2026-06-24) | 2026-06-18 | D29 | R18 phase 2 |
| D26 | OCR PDF-render adapter = MuPDF (wasm), local; gated behind ENABLE_PDF_OCR (off by default). Dismissed @napi-rs/canvas (native-binary serverless risk) + AWS Textract (sends client docs to cloud) | 🟢 LIVE (flag-gated) | 2026-06-23 | — | R48 #5 |
| D27 | Client-intake paradigm = P4 (route by visitor STATE, not legal category), shipped PHASED — Phase 1 = fork + ready-buyer→marketplace + safe interstitial for the other two; consult-queue gated on real Network Lawyers, RAG path gated on a real corpus. Dismissed P1 chat-match, P2 form-first, P3 attorney-pull | 🟡 LOCKED — build pending | 2026-06-24 | — | T189 |
| D28 | Auth provider = Auth0 (free tier; mandatory MFA + RBAC; DB stays source of truth for role/firm). Confirms Riyaz's ask + the 2026-06-22 eval + the 2026-06-18 cutover shark passes. NOTE: the "D27" referenced in lib/auth/auth0.ts + the eval doc meant THIS auth decision — formalized here as D28 (the real D27 is the intake paradigm). Dismissed Clerk (less enterprise gravitas, half the MAU), Supabase Auth (we're on Neon, not Supabase), Auth.js (DIY MFA = existential risk in legal software). Tenant provisioned + integration BUILT & smoke-tested (#363). | 🟢 BUILT (#363); MFA relaxed pre-launch per D30 | 2026-06-24 | D30 | #8 / R-auth |
| D29 | E-signature (R18) made fully available NOW — Riyaz waives the D25 "CA UETA lawyer-signoff before prod" gate, accepting the risk; reversible (turn off anytime). Confirmed there is NO code gate suppressing e-sign (the full sign / evidence / batch-sign / sign-invite flow is live); D25 was a policy gate only. Lawyer review still recommended before scale; this is a pre-launch posture call. | 🟢 LIVE (Riyaz override; reversible) | 2026-06-24 | — | R18 / roadmap #8 |
| D30 | MFA/2FA turned OFF pre-launch to cut demo/dev enrollment friction (Riyaz). Relaxes — does NOT supersede — D28's mandatory-MFA requirement, which stands for launch. Two switches: Auth0 tenant policy + AUTH_REQUIRE_MFA=false (code, secure-by-default). Acceptable now (auth not live, no real users/data). RE-ENABLE AT LAUNCH — hard gate, launch-day-checklist Section 4. Dismissed: deleting the check (loses secure-by-default), tenant-only (fragile vs amr), per-user opt-out (overkill). | 🟠 TEMPORARY (reverts at launch) | 2026-06-24 | — | R-auth / launch |
| D31 | User registration + provisioning = THREE DOORS + shared invite/approval. Client pages → live Client (instant, self-serve, scoped). Attorney/firm pages → PENDING attorney (sign-in only; client-data access gated behind license verification + admin/firm-admin approval). Lawma staff/admin → never self-serve; admin creates user+role in Lawma Workspace → email link → assigned role. Registration intent carried through the Auth0 redirect (appState), app_user provisioned on callback. SECURITY INVARIANT: privileged access never granted by self-registration alone. Dismissed: global-default-client (silent over-provisioning), invite-only-for-all (kills self-serve mission), instant-attorney (self-declared lawyers reach client data — existential hole). | 🟢 LOCKED — build queued (R49) | 2026-06-24 | — | R49 / R4 / R-auth |
| D32 | Interview identity model = multi-token + author-declared client party. (1) alsoPopulates: string[] lets one answer (stored once under its primary key) be exposed under extra tokens at read time — "multiple applications of the same answer" (general Builder feature). (2) The AUTHOR declares which party is the client on the definition (party_role, full PartyRole vocabulary) — NOT a runtime question; client_display_name is DERIVED from that party's name slot. Keeps question keys stable (carry/mapping/show-if unaffected) and satisfies R50's "never assume petitioner" via authoring, not asking. Dismissed: conditional-token-assignment (breaks stable-key invariant), duplicate-answer-storage (drift+migration), per-family party tokens (no cross-family carry), runtime party question (the closed A2 approach). | 🟢 LOCKED — pure core built; runtime/Builder wiring queued | 2026-06-25 | partly supersedes A2 runtime question (#381 closed) | R50 |
D1 — Discovery-first before greenfield-vs-salvage decision
Status: 🟢 LIVE Decided: 2026-06-13T19:00:00Z Supersedes: — Dismissed alternatives considered:
- Full greenfield rewrite from scratch — rejected: recreation from memory had already been attempted for 1-2 days and failed; ~80%+ failure rate for emotional rewrites (Spolsky, "Things You Should Never Do, Part I"); imminent investor demo makes 4-8 weeks of no-shipping untenable.
- Continue iterating on
lawma-jun11directly — rejected: would not resolve the "capabilities don't compose" symptom; loss of confidence would return in 3 weeks.
See also: docs/shark/2026-06-13-foundation-or-salvage.md (both shark passes), D2.
We spend 2-3 days producing the entity map, user-type list, module inventory, and architectural seams audit BEFORE deciding between greenfield rebuild, strangler-fig migration, or hybrid. Output is a document set, not code.
Why:
Riyaz's stated discomfort — "capabilities don't compose" — is a coordination problem more than a foundation problem. We can't tell which without reading the existing code. Recreation-from-memory failed: strong signal we need to read what's in lawma-jun11, not re-derive. The investor demo is imminent and lawmaco.netlify.app is currently working; a 2-3 day discovery preserves runway while a 4-8 week rewrite would not. The decision we'll actually make at the end of discovery may not be "rewrite or migrate" — it may be a third option we can't see yet without evidence.
How to apply:
Until D1 is superseded by the build-vs-migrate decision (forthcoming as D6 or later), all work in Lawma2 stays in Phase 0: discovery documents only. No production code. No touching /Users/zayir/Lawma. If a task would require either, surface as a concern and pause.
Cascade required:
requirements-all.md— log R1 (foundation discovery) ✅project-tasks.md— decompose R1 into T1-T11 ✅STATE.md— record Phase 0 start ✅CLAUDE.md— document Phase 0 status + source-repo read-only posture ✅
D2 — Lawma2 IS the new product repo (not a sidecar discovery folder)
Status: 🟢 LIVE Decided: 2026-06-13T19:05:00Z Supersedes: — Dismissed alternatives considered:
- Sidecar-only — Lawma2 holds only discovery docs; rebuild lives elsewhere — rejected: separating docs from the code they shape adds a synchronization tax forever.
- Rebuild inside
Lawmaon a branch — rejected: the reason for a fresh start was to escape historical baggage; merging discovery into the same repo re-imports the baggage at every git operation.
See also: D1.
Lawma2 holds both discovery artifacts (docs/) and the eventual rebuild code (app/, lib/). One source of truth. Cost of being wrong is a folder rename.
Why:
Single-source-of-truth ergonomics. Docs authored now (entity map, user types, seams audit) are precursors to the code that will follow; they should live together.
How to apply:
When the build-vs-migrate decision (forthcoming) calls for greenfield code, it lands in Lawma2/app/ and Lawma2/lib/. When it calls for strangler-fig migration, ported code from lawma-jun11/ lands in the same place, file-by-file with verification. The lawma-jun11 repo stays read-only.
Cascade required:
CLAUDE.md— document Lawma2 as project identity ✅- No remote configured yet — explicit; will be added when we start porting capability code.
D3 — Demo strategy: self-service = mockups; real demos = Riyaz-driven
Status: 🟢 LIVE Decided: 2026-06-13T20:30:00Z Supersedes: — Dismissed alternatives considered:
- Real authentication framework for self-service investor demos — rejected: multiple demo users in one browser session ran into unavoidable login/cookie/cache collisions that broke the live demo just before investors arrived (Riyaz's lived experience).
- Guided-tour overlay on real product without auth — rejected as v1: requires more engineering than mockup pages and still depends on backend uptime.
See also: docs/shark/2026-06-13-demo-mockup-strategy.md, R2.
Two parallel demo surfaces:
- Self-service investor demos = mockups. Static, clickable pages stitched together to simulate the product. No real auth, no backend, no shared cookies. Public-facing on the live site. Pattern reference: the existing
app/app/personas/surface (14 sub-routes: access-code, builder, ca-divorce-triage, case-analysis, collaboration, document-lifecycle, engagement, find-attorney, forum, interview, partners, payments, small-claims-plaintiff, tx-divorce, plus_pattern/). - Real-software demos = Riyaz-driven. Different browsers / Chrome profiles dodge the cookie/cache/login collision class.
Standing rule: every new capability ships with a mockup version added to the public self-service demo path. Definition of "done" for any feature includes BOTH (a) real implementation in app//lib/ AND (b) a mockup version. Visible "Demo simulation" indicator on the mockup surface so we're not implicitly claiming functional software.
Why:
Cookies/cache/auth collisions when one browser plays multiple user types are an inherent property of stateful auth in a single browser context. Engineering around them is expensive AND fragile. Mockups sidestep the entire class of problems and stay demo-able even when backends fluctuate. Trade-off: mockup parity is a perpetual maintenance tax — worth it for investor reliability.
How to apply:
Every feature requirement (R-row) lists a mockup-parity sub-step. No feature lands in features.md Col E without the mockup also landing. The mockup-page architecture (T11) decides folder layout (candidate: app/(demo)/personas/), state strategy (URL params or localStorage; no session), mock-data approach (per-page hardcoded vs shared lib/mock-data/), and the indicator style.
Cascade required:
CLAUDE.md— Demo strategy section added ✅requirements-all.md— R2 added (standing demo-mockup requirement)project-tasks.md— T10 (extract personas pattern), T11 (design mockup architecture) added- Memory:
feedback-mockup-demos-default(this session) - Memory:
project-lawma2-demo-strategy(this session)
D4 — Canonical user-type taxonomy for Lawma2
Status: 🟢 LIVE Decided: 2026-06-13T20:35:00Z Supersedes: lawma-jun11's user-type nomenclature for "Network Attorney" (now decomposed into Network Law Firm + Network Lawyer + Network Paralegal). Dismissed alternatives considered:
- A single bare "Attorney" user type for both staff and third-party attorneys (as in lawma-jun11's schema) — rejected: the same schema role serving two very different product roles is the canonical example of the "capabilities don't compose" tangle Riyaz cited.
- Network Lawyers as siblings of the Firm without a parent-Firm entity — rejected: client trust attaches to the Firm (contracting party); the Lawyer is operational owner; if the lawyer leaves the firm, the client stays with the firm.
- Notary/Process Server as a v1 user type — DEFERRED, not rejected: noted as a future addition; foundation must not preclude.
See also: docs/shark/2026-06-13-canonical-taxonomy.md, D5, docs/audit/01-canonical-user-types-and-entities.md.
Lawma2's canonical user types are:
1. Lawma Staff (parent category)
The Lawma company's own employees. Subroles within Lawma Staff:
- Lawma Attorney — staff attorney; trains the system, authors Interview Templates, reviews + approves them.
- Lawma Admin — admin permissions for platform operations.
- Lawma Staff (general) — other Lawma employees (operations, support).
The Author function is a permission exercised by Lawma Attorneys and Lawma Admins — NOT a distinct user type.
2. Network Law Firm
A 3rd-party law firm contracting with clients via the platform. The Firm is the contracting entity; individual lawyers operate within it. Sub-user logins under a Network Law Firm:
- Network Lawyer — individual attorney; user-of-record on cases; has a community profile.
- Network Paralegal — separate login (no shared logins); can complete interviews on behalf of clients, message and schedule on behalf of attorneys.
- Sponsor — a FLAG on a Network Lawyer (or Firm) per the business plan; confers paid placement / community badge / matching priority. NOT a separate user type.
3. Clients
Self-represented litigants (SRLs) — the end users the product exists for. Community users. Have multiple cases; each case may be served by a different Network Firm or Network Lawyer.
4. Ad Partners
3rd parties (non-legal services that clients may need: notaries, process servers, financial planners, etc.) who receive intake leads via Lawma. NO connection to case data by default. Clients may explicitly share specific intake replies, one interaction at a time, with full per-field disclosure of what's shared and why.
Deferred
- Notary / Process Server — possible future user type for case-accountability linkage. Foundation must not preclude (the
case_participantjoin entity should be open enough to add them later). Not building v1.
Rigor observations folded in
- Malpractice isolation is organizational discipline, not schema enforcement. "Lawma Staff cannot service clients on their Lawma account; for client-servicing, use a non-Lawma account" is policy — the same human has TWO User records on different emails; the schema cannot prevent the cross-link. Documented so we don't accidentally try to engineer schema enforcement.
- Paralegal action attribution on the audit spine. When a paralegal acts on behalf of a Network Lawyer (or completes an interview on behalf of a Client), the audit spine records BOTH the operating user (paralegal) AND the represented user (lawyer or client). Privilege-relevant.
- Sponsor as a flag, not a user type. Modeled as a
sponsor: boolean(or sponsor-tier enum) on the Network Lawyer or Firm entity. Not a parallel user category. - Author is a function/permission, not a user type. Maps to a permission held by Lawma Attorneys + Lawma Admins. Engine-internal role renamed
implementer→author(DB enum in migration 0006; the lingering code/test/prompt references swept 2026-06-30). The only survivingimplementerstrings are a DIFFERENT concept — the financial-model headcount role + an advertiser-portal review status.
Why:
The foundation must let each user TYPE have a coherent identity that matches the product's mental model. lawma-jun11's "Network Attorney" was a single label covering Firm + Lawyer + Paralegal — which is why so many code paths branched on role-not-enough-info. Decomposing into Firm + Lawyer + Paralegal mirrors how legal practice ACTUALLY works (firms employ attorneys; attorneys delegate to paralegals; clients contract with firms). Ad Partner separation ensures privacy-by-default — there is no path for ad-partner identities to reach case data without explicit per-field client consent.
How to apply:
Every new code path that authorizes a user MUST identify which D4 type/subtype it's authorizing. Where lawma-jun11 code uses attorney role without disambiguating, the migration/port adds the disambiguation. Mockup demos under the personas pattern (D3) model these types as personas — extend the app/app/personas/ pattern for the new taxonomy.
Cascade required:
CLAUDE.md— D4-canonical user types section added; carry-forward qualification ✅docs/audit/01-canonical-user-types-and-entities.md— locked canonical (this session)project-tasks.md— T1 done (canonical audit doc written), T5/T6 rescoped to "map code to canonical" (this session)STATE.md— D4 logged in Done; remove pre-D4 nomenclature from any current-state doc (this session)- Memory:
project-lawma2-canonical-taxonomy(this session)
D5 — Canonical object/entity taxonomy for Lawma2
Status: 🟢 LIVE Decided: 2026-06-13T20:35:00Z Supersedes: lawma-jun11's implicit entity model (no explicit prior locked decision; lawma-jun11's entities are READ as-is and mapped to D5 in T5/T6). Dismissed alternatives considered:
- "Network Attorney" as a single contracting entity (vs. Network Law Firm as parent + Network Lawyer as user) — rejected per D4.
- Court-form definitions as a SEPARATE entity from Interview Templates — rejected: court-form field mapping is authored alongside the interview that produces the answer; same versioning cadence; deterministic AcroForm filling depends on co-authoring.
- Documents and document_templates as a single entity — rejected: Documents are work product (lifecycle DRAFT → approved → signed → filed); document_templates are .docx files Lawma staff upload with placeholder keys. Separate concerns.
See also: docs/shark/2026-06-13-canonical-taxonomy.md, D4, docs/audit/01-canonical-user-types-and-entities.md.
Lawma2's canonical objects:
Engine / authoring layer
- Interview Template — questionnaire authored by Lawma Staff (Author function). Contains deterministic court-form field mapping (LLM never writes a court form). Versioned with court-form revisions: a new form revision from the court = a new Interview Template version.
- document_template — .docx Word file uploaded by Lawma Staff for assembled documents (declarations, letters). Versioned, never edited in place, placeholder keys extracted at upload, question-key → placeholder mapping.
- AI Training Data — Lawma Staff train the AI; Network Attorneys + any platform user can submit feedback on AI contributions.
Identity, relationship, gating
- User — auth identity with role per D4 taxonomy.
- Network Law Firm — multi-tenant parent for Network Lawyers + Network Paralegals.
- Engagement — the attorney-client relationship object. Per-Case, not per-Client (one Client → many Cases → one Engagement each → one Network Firm + one Network Lawyer). Gates everything per the "relationship before coaching" design invariant.
- case_participant — explicit join entity for who's on a case (Client, Network Lawyer, Network Paralegal, optionally Notary/Process Server in the future).
- Attorney Verification — registration queue; human-verified bar standing before a Network Lawyer account exists (built as J163 in lawma-jun11, reverted).
- Access Code — second way relationships form; legal-aid clinic hands a code to a Client.
Case workspace
- Case — a Client's legal matter. One Client → many Cases. Carries a
court_case_number(the future linkage point for Conflict Walls). - Interview Session — individual run of an Interview Template. Cross-user: can be filled by a Client directly, OR by a Network Paralegal on behalf of a Client, OR by a Network Lawyer.
- Document — actual work product (filled court forms, assembled .docx letters, etc.). Lifecycle: DRAFT → approved → signed → filed. E-signatures with evidence records. Co-review comments.
- Case Analysis — AI-generated briefing for a Case with review-state provenance (per the AI-feature doctrine; runtime applies, fails closed).
- Work Plan — attorney-assigned tasks; case checklist ("path to filing"); appointments.
- Secure Messages — attorney↔client privileged channel. Emails carry zero content by design (notification-only).
Money
- Money / Payments — flat fee on the Engagement + Lawma's share. The single flat fee is the canonical cost story.
Community & monetization
- Community Posts & Replies — forum content. Open to all user types (D4); permissions vary.
- Ad — individual ad units (placements).
- Ad Campaign — campaign-level entity with performance metrics + funding management.
- Ad Partner Intake Form — separate intake flow each Ad Partner defines. Each field carries a
purposestring so the consent screen can render "what's shared and why" to the Client.
System spine
- Audit Spine — append-only log of every privileged action. Records operating user AND represented user (per D4 rigor observation #2).
- Notifications — forum bell today; messages/tasks tomorrow; SMS per D65 (referenced from lawma-jun11) eventually.
Future hooks (foundation supports, no v1 build)
- Conflict Wall — opposing parties on the same matter (D27 in lawma-jun11). Court-case-number linkage on Case is the future detection point. Checking is deferred.
- Demo/Seed Identities — permanent maintained object family per D3. USED ONLY by Riyaz's real-software demos in separate Chrome profiles. The mockup-demo path under D3 uses NO auth and NO seed identities.
Rigor observations folded in
- Engagement is per-Case, not per-Client. Everything downstream — Documents, Money, Secure Messages, Work Plan, Case Analysis — hangs off Case + Engagement.
- Ad Partner consent needs "why" metadata. Each Ad Partner Intake Form field has a purpose-string. Consent screen renders "Ad Partner X is asking for field Y because Z" at time of share.
- Conflict walls foundation, not v1 capability. Case carries court_case_number; opposing-party detection is future. Foundation does not preclude; checking is deferred.
- Demo/Seed Identities ≠ mockup-demo path. Two independent things: seed identities are real auth records for Riyaz's real-software demos; mockup demos use no auth at all.
Why:
The objects above cover every product surface lawma-jun11 has, with composition pain explicitly factored out: Engagement is per-Case (so multi-case clients work cleanly), Documents are separated from document_templates (so the work-product lifecycle is independent from the authoring-template lifecycle), Ad Partners have a privacy-by-design data flow (so the "why" disclosure is structural, not a UX afterthought), and the case_participant join makes future additions (Notary/Process Server) easy.
How to apply:
Each canonical object will get a row in T6's output (docs/audit/06-entities.md) with a code-mapping column: lib/db table name (Drizzle schema), owning lib/ folder, any existing types. T7 builds the entity×module matrix from this. Greenfield code uses these names; ported code is renamed to match.
Cascade required:
docs/audit/01-canonical-user-types-and-entities.md— locked (this session)project-tasks.md— T6 rescoped to "map code to canonical objects" (this session)CLAUDE.md— pointer to D5 ✅- Memory:
project-lawma2-canonical-taxonomy(this session)
D7 — Path C: in-place refactor + Lawma2 rebrand (build-vs-migrate)
Status: 🟢 LIVE Decided: 2026-06-13T22:30:00Z Supersedes: — Dismissed alternatives considered:
- Path A — Greenfield rewrite from scratch. Rejected: the T1-T8 audit erased its premise. lawma-jun11's schema is ~90% of D5 already; the architecture invariants (D2 NOT-NULL FK + partial unique index, D27 plane isolation in separate schema files, D54 attorney_kind enum, D63 InterviewDefinition chaining, D64 documentSignatureTable, D72 document_template) are encoded in DDL, not just app code. Greenfield would re-derive 2403 lines of typed Drizzle schema + the engine type contract + the DDL invariants — for 4-8 weeks of work that mostly reproduces what's already there, AND would risk regressions on subtle invariants. The recreation attempt 1-2 days ago already failed; same approach at 20× duration won't succeed.
- Path B — True strangler-fig (two codebases running in parallel). Rejected: B's value is when migration takes weeks AND a single deployed product evolves in parallel. C's migration is 12-18 hours (per audit/09); lawmaco stays on its current main; no parallel evolution needed during that window. B over-engineers for the actual scope.
See also: docs/plans/2026-06-13-foundation-direction.md (both shark passes); docs/audit/09-seams.md; docs/audit/07-entities-code-mapped.md.
Lawma2's main starts by lifting lawma-jun11's code into the Lawma2 repo, then applies the D4/D5/D6 refactors as clean, deliberate commits — vocabulary renames, 5 additive schema migrations, 1 policy decision, plus the D6 mockup convention lift. Total estimated effort: 12-18 hours. The "fresh start" comes from the discipline applied to the migration, not from a blank app/.
Why:
The T1-T8 audit produced 8 cross-checked documents (audit/01 through audit/09) showing:
- 5 of 6 architectural seams are 🟢 clean; 1 is 🟡 mostly-clean (an additive column gap).
- All 6 gaps to D4/D5 parity are additive, not structural.
- Every D5 object has a Drizzle table home.
- Every architectural invariant Riyaz cares about is already in code.
The "capabilities don't compose" feeling Riyaz had was real, but the cause was vocabulary drift + decision-coordination tax across many simultaneous PRs in early June, NOT architectural rot. C addresses both: the rename pass cleans vocabulary; the no-contradictions operating rule (Lawma2 CLAUDE.md) + the lifted convention + the lifted CI enforcement script address the coordination tax going forward.
How to apply:
The 7-step Phase-1 implementation plan in docs/plans/2026-06-13-foundation-direction.md is the canonical sequence:
- Step 0 — Smoke test (copy lawma-jun11 → Lawma2; tsc + build + tests green BEFORE any changes).
- Step 1 — Vocabulary rename pass.
- Step 2 — D4/D5 additive schema migrations (5 items).
- Step 3 — Policy commitments (CLAUDE.md note on
attorney_kind=both). - Step 4 — Lift D6 mockup convention.
- Step 5 — Drop
-archiveclutter. - Step 6 — Deploy Lawma2 to a NEW staging URL (
lawma2-staging.netlify.appor similar). DO NOT touchlawmaco.netlify.appuntil investors are formally re-invited. - Step 7 — Phase 2 capability development begins.
Three mitigations from shark Pass 2:
- Refactor commits are VISIBLE and DELIBERATE — each rename gets its own commit with
BEFORE → AFTERreasoning so the git history of Lawma2'smainbecomes the receipt that the codebase is different. - Phase 1 starts with a SMOKE TEST against unchanged lawma-jun11 code; if anything fails, the audit was incomplete and we pause before committing to C deeply.
- Lawma2 deploys to a NEW staging URL until investors are formally re-invited; lawmaco.netlify.app is untouched throughout Phase 1.
Cascade required:
DECISIONS.md— D7 logged ✅STATE.md— Phase 0 closed; Phase 1 starts (this session)requirements-all.md— R1 marked DONE; R3+ (Phase 1 work) gets filed as it's authored (this session for the initial Phase 1 rows)project-tasks.md— T9 marked DONE; Steps 0-7 from the foundation- direction plan added as Phase 1 task rows (this session)docs/plans/2026-06-13-foundation-direction.md— Phase 1 plan ✅- The recreation work that's been keeping Lawma2 in Phase 0 ends here. Next session opens Phase 1 with Step 0.
D6 — Paired-mockup convention lifted from Lawma main (docs/conventions/demo-mockups.md)
Status: 🟢 LIVE Decided: 2026-06-13T21:00:00Z Supersedes: — Dismissed alternatives considered:
- Reinvent the mockup pattern from scratch. Rejected: the Jun-7 Lawma main pattern is already documented, CI-enforced, battle-tested, and the prior memory
feedback_demos_as_mockups_forevershows Riyaz already worked through this on 2026-06-12. Re-deriving wastes a day and risks introducing the same failure modes the existing pattern avoids. - Lift the lawma-jun11 launch-button approach (cookie-switching via
setDevActingAs). Rejected: this approach REINTRODUCES the multi-user cookie collision that D3 is designed to avoid. The Jun-11 direction was the WRONG direction; the reversion to Jun-7 was correct.
See also: D3, D4, D5, docs/audit/02-personas-pattern.md, _pattern/README.md in Lawma main (/Users/zayir/Lawma/app/app/personas/_pattern/), docs/conventions/demo-mockups.md in Lawma main, the feedback_demos_as_mockups_forever memory in ~/.claude/projects/-Users-zayir-Lawma/memory/.
Lift the existing /app/app/personas/ pattern from Lawma main (Jun-7 state) into Lawma2 with D4 adaptations. This locks the SPECIFICS of D3's standing rule.
The convention (lifted intact):
- Every production capability ships TWO surfaces in the SAME PR:
- The real
/app/*code — seeded with realistic data + persona scenarios so Riyaz can demo it himself by signing in with different Chrome profiles per persona. - A paired mockup under
<demo-path>/personas/<capability>/— same React components, mocked data layer (no DB / cookies / auth), so investors can walk it without session-collision risk.
- File shape per capability: ``
<demo-path>/personas/<capability>/ page.tsx — server component, force-static, presentational only fixtures.ts — typed fixtures, types imported from real-surface``
- Hard rules for mockup pages:
- Server components; prefer
export const dynamic = "force-static". - Forbidden imports:
@/lib/db,cookies(),getSession, any auth-store accessor. - No server actions that write to the DB.
- Fixtures import types from the SAME location the real surface uses (compile-time linkage; mockup breaks loudly when type changes).
- Use the seed cast (Maria Herrera, Carmen Reyes, Riyaz Samnani, Jenna Park, Andre Wilson, David Nguyen, Marcus Johnson, Swift Serve) for continuity.
- CI enforcement — lift
scripts/check-demo-isolation.shfrom Lawma main; grep the mockup directory for forbidden imports; any hit fails the build. Wire into.github/workflows/ci.ymlfrom day 1.
- Scenario checklist as prod-push gate —
docs/demo/scenario-checklist.mdlists every capability whose mockup must walk end-to-end via Playwright. Until the checklist walks, no merges to prod.
- The DEMOS launcher (
<demo-path>/personas/page.tsx) — curated cards, numbered/ordered as a story. Visible "Demo simulation" signals: coral "Internal demos" eyebrow; "Choose a persona to demo." header; footer paragraph clarifying synthetic data only; numbered badges on each card.
- The reset surface (
<demo-path>/personas/reset/) is NOT a mockup — it's an admin-gated real-software tool for Riyaz to wipe demo data between sessions. Stays under the personas folder for discoverability but exempt from mockup CI checks.
Demo personas vs D4 user types — the explicit distinction:
D4 has 4 user types (Lawma Staff, Network Law Firm, Clients, Ad Partners) with sub-roles. Demo personas are concrete instances for storytelling — there can be MORE demo personas than user types because one user type may have multiple demo experiences worth showing separately (e.g., Client path A "looking for an attorney" vs Client path B "Maria with existing case"). v1 launcher should have 6-8 demo personas mapped to D4 types — see docs/audit/02-personas-pattern.md.
Why:
Riyaz already solved this on 2026-06-12 after the 2026-06-11 revert (which itself was caused by the demo and real product sharing data-layer code). The paired-mockup pattern makes session-collision failure structurally impossible: the mockup has no sessions to collide. The convention has been tested in production at lawmaco.netlify.app. Re-deriving wastes a day and risks reintroducing the same failure modes.
How to apply:
- T11 (mockup architecture design) decides the final
<demo-path>(T11 candidates:app/(demo)/personas/for route-group URL hiding;app/app/personas/for parity with Jun-7;app/personas/flat). Locks via D7 or later. - Lift these files from Lawma main into Lawma2 with a D6 header:
app/app/personas/_pattern/README.md→ Lawma2 equivalent.docs/conventions/demo-mockups.md→ Lawma2 equivalent.scripts/check-demo-isolation.sh→ Lawma2 equivalent.- Initialize empty
docs/demo/scenario-checklist.md; grows per R-row mockup sub-step. - Preserve the seed cast (names + roles).
- Design D4-driven persona cards for the v1 launcher (Network Law Firm as Firm + Lawyer + Paralegal; Ad Partner with per-field consent disclosure mockup).
- Every R-row from R3 onward lists a mockup sub-step that references D6.
Cascade required:
CLAUDE.md— Demo strategy section enriched with D6 specifics (this session)docs/audit/02-personas-pattern.md— full pattern audit ✅ (this session)- Memory:
feedback-mockup-demos-default— enriched with specifics (this session) project-tasks.md— T11 description enriched with the lift-from-Lawma-main approach (this session)requirements-all.md— R2 enriched with scenario-checklist gate language (this session)- Future PRs that lift the convention docs, the CI script, the scenario checklist, and the seed-cast continuity into Lawma2 code when we exit Phase 0.
D8 — Every case needs a lead lawyer; missing surfaces as a flag (not a CHECK)
Status: 🟢 LIVE Decided: 2026-06-14T01:00:00Z Supersedes: — Dismissed alternatives considered:
- CHECK constraint on
case_participantenforcingis_primary↔engagement.attorneyIdconsistency — rejected: PostgresCHECKconstraints are intra-row only; an inter-table assertion (case_participant existence given an engagement row) needs a trigger, not a CHECK. - Database trigger to auto-insert a
case_participantis_primary row whenever an engagement is created — rejected: overkill for an invariant the writer can maintain. Triggers add operational complexity (debugging, migration ordering, ORM blind spots) that a query-surfaced flag avoids. - Hard delete on reassignment with no historical preservation — rejected: the firm-manager use case explicitly wants "what cases was Carmen lead on before she left" without reconstructing from
audit_event. Soft-delete viaremoved_at(T108) lets this query stay simple. - Tracking the lead solely on
engagement.attorneyId(nois_primaryon case_participant) — rejected: leaves thecase_participantroster ambiguous about which attorney is the lead vs. co-counsel vs. observers. Single source of truth oncase_participant.is_primaryis clearer; engagement.attorneyId is a denormalized convenience kept in sync by the writer.
See also: T108 at lib/db/schema.ts (case_participant sharpening: is_primary + removed_at + primary_uidx + firm_role_idx) and lib/cases/case-participants.ts (the flag query). R3 in requirements-all.md (the firm-manager UI that consumes the flag).
Every Lawma case that has an active engagement MUST have an active case_participant row with is_primary = true and role = 'attorney'. The absence of that row is the flag — findCasesNeedingLeadAttorney(firmId?) in lib/cases/case-participants.ts surfaces every violation in one query.
Why:
The lead-attorney concept is load-bearing in legal practice: it names the ONE responsible counsel for the matter, gates malpractice attribution, and anchors the attorney-client privilege chain. The product surfaces it in many places — the per-case header, the audit spine, the engagement fee record, the messaging recipient resolver, the firm dashboard's "caseload by lawyer" view. A case without a lead attorney is structurally incomplete; the firm and the client both need to know who's on the hook.
But the schema cannot fully enforce this. case_participant_primary_uidx (partial unique on case_id WHERE is_primary = true AND removed_at IS NULL) expresses AT MOST ONE active primary per case at the DB layer. The other half — AT LEAST ONE for every engagement-bearing case — is an inter-table assertion (engagement → case_participant existence) that needs either a trigger or app-layer discipline. Triggers are overkill for an invariant the reassignment writer can maintain atomically (per T108's design + the Phase-2 reassignLeadAttorney named in the helper commit body). The flag query catches drift quickly; the firm-manager dashboard's "needs reassignment" widget surfaces it for human review.
How to apply:
- Every writer that creates an engagement also inserts the matching
case_participant(case_id, user_id, 'attorney', is_primary=true)row in the same transaction. The two writes are atomic. - The reassignment writer (Phase 2 —
reassignLeadAttorneyinlib/cases/case-participants.ts) is the ONLY place that ever changes who the lead is. It runs as a transaction: mark the old row'sremoved_at, insert the new is_primary row, updateengagement.attorneyId, logaudit_event. - The firm-manager dashboard reads
findCasesNeedingLeadAttorney(firmId)on load and surfaces a "⚠ N cases need a lead" widget when N > 0. - The platform-wide oversight view (Lawma admin / founder) reads the same query with no
firmIdfilter for cross-firm drift detection. - Backfill of legacy data (every existing engagement gets a primary
case_participantrow) happens in the T106 staging deploy seed script and is a one-time operation; the flag query catches any rows the backfill misses. - When this rule needs upgrading (e.g., co-counsel; multiple simultaneous leads per case), the migration is additive: relax the
case_participant_primary_uidxpredicate, or add a separateis_supervisorflag.
Cascade required:
DECISIONS.md— D8 logged ✅CLAUDE.md— Policy Commitments section: add the rule alongside T103 ✅- T108 already implements the schema side (
case_participantsharpening, commits 399fac6 + 71bf8ec). - R3 (firm-manager UI) in
requirements-all.mdconsumes the flag — R-row already captured. - Phase 2
reassignLeadAttorneywriter enforces both halves of the invariant atomically (named inlib/cases/case-participants.tsfile header for the future contributor).
D9 — Mockup-page architecture: app/(demo-mockups)/personas/ → URL /personas
Status: 🟢 LIVE Decided: 2026-06-14T14:00:00Z Supersedes: — Dismissed alternatives considered:
- (b)
app/app/personas/parity with Lawma main — rejected: the/app/prefix inverts the audience signal for Lawma2 (the personas surface is the PUBLIC investor entry point per D3/D6, NOT an in-product page). Lawma-main parity is not a Lawma2 goal (D2). The "double app" filesystem reads awkwardly. - (c)
app/personas/flat — rejected: gives up the route group's named-scope. Aapp/personas/layout.tsxwould apply to anything calledpersonas— including a hypothetical future non-mockuppersonaspage. The named group(demo-mockups)keeps the demo lane structurally isolated. - Group name
(demo)— rejected in favor of(demo-mockups): the longer name is harder to skim past in a filesystem view; pairs with the_pattern/README.mdroute-group note to make the demo intent unmistakable. (Shark Pass 2 mitigation #1.) - No 308 redirects — rejected: even if Lawma2 hasn't been broadly shared at the old
/app/personasURL, Riyaz's own bookmarks + an old deck link might point there. 308s for 6 months bridge any drift, then prune. (Shark Pass 2 mitigation #3.)
See also: docs/plans/2026-06-14-mockup-architecture.md (both shark passes recorded), T109 execution (this same commit), D3 (demo strategy), D6 (paired-mockup convention).
Lawma2's mockup convention lives at app/(demo-mockups)/personas/<capability>/ and renders at the URL /personas/<capability>. The route group is invisible in URL but real in the filesystem — Next.js convention. The group's _pattern/README.md documents the rule for future contributors.
Why:
The /app/ URL prefix Lawma main used for personas existed because the personas surface was reached from inside the product (sign-out from /app/dashboard landed on /app/personas). For Lawma2 per D3 + D6, the personas surface is the PUBLIC INVESTOR ENTRY POINT — visitors land on it from marketing or a deck link, not from inside the product. /app/personas reads as "an in-app page, only useful if you're signed in" — exactly the wrong frame for the audience. /personas (clean, top-level) reads correctly to that audience.
The route group (demo-mockups) buys two things over (demo) or (d): the longer name is structurally clearer in filesystem views, and the named scope lets a group-level layout.tsx wrap every mockup with the D6 "Demo simulation" banner + persona-launcher nav + the "synthetic data" footer line without leaking into the real product's layout.
How to apply:
- Every new capability mockup lands at
app/(demo-mockups)/personas/<capability>/page.tsx+app/(demo-mockups)/personas/<capability>/fixtures.tsper D6. - Internal hrefs use
/personas/<capability>, never/app/personas/<capability>or/(demo-mockups)/personas/<capability>— the route group is invisible. scripts/check-demo-isolation.shgrepsapp/(demo-mockups)/personas/for forbidden imports + excludes_pattern/(template) andpersonas/reset/(admin-gated real software per D6 carve-out).- The 308 redirects in
next.config.tsfrom/app/personas/to/personas/live until ~2026-12-14 (6 months); prune the block after that window. - Future route groups in Lawma2 follow the same pattern: long descriptive names, group-level layout if shared chrome is needed, no group segment in URLs.
Cascade required:
DECISIONS.md— D9 logged ✅CLAUDE.md— D3 (demo strategy) section path references updated ✅docs/conventions/demo-mockups.md— every path reference updated ✅app/(demo-mockups)/personas/_pattern/README.md— lifted with new header + route-group note ✅scripts/check-demo-isolation.sh— grep target updated +/reset/exclusion added ✅next.config.ts— 308 redirects added ✅lib/auth/route-matrix.ts— route prefix/personas✅app/(demo-mockups)/personas/page.tsx+ sub-route refs — internal hrefs/personas/*✅scripts/test-route-matrix.ts— fixture updated ✅- All internal href callers (admin pages, business-plan, builder top-chrome, sign-out-button, internal-step-nav, seed scripts) ✅
project-tasks.mdT11 → DONE; T109 → DONE (single commit per this same execution) ✅STATE.md— D9 + T11/T109 noted (separate STATE tick commit)
D10 — Matchmaking marketplace browse is public; account required only at "request match"
Status: 🟢 LIVE Decided: 2026-06-14 Supersedes: — Dismissed alternatives considered:
- Keep
/app/find-attorneybehind sign-in (the lawma-jun11 posture) — rejected: a litigant has to create an account before discovering whether any lawyer in their budget exists, which is the exact friction Riyaz called out ("What if they don't find a lawyer within their budget?"). It also poisons the demo flow — clicking the persona launcher card dropped visitors at a sign-in wall with no seeded credentials. - Show a "preview list" without prices, gate full details on sign-in — rejected: makes pricing unknowable until commitment; exactly inverts what a self-represented litigant needs to see.
- Lock to anonymous browse but force sign-up earlier (at filter apply) — rejected: the filter is information consumption, not intent expression. Sign-up at the actual write (the match request row) is the correct line.
See also: T122; lib/auth/route-matrix.ts /app/find-attorney public row; the existing action-layer SIGN_IN_FIRST gate in app/app/find-attorney/actions.ts (defense in depth).
The /app/find-attorney route is public. Any visitor — anonymous or signed-in — can complete the Step-1 intake, Step-2 marketplace browse (with filters and the full disclosed-criteria roster), and read every Network Lawyer's bio + pricing. The first step that requires an account is Choose / Request match, which writes a match_request row and so requires identity. Anonymous "Choose" clicks redirect to /app/register?returnTo=/app/find-attorney&attorney=<userId> with the preselection preserved so the request fires immediately after sign-up.
Why:
A marketplace where you must sign up to discover whether you can afford it is anti-consumer. Litigants in a stressed life moment should be able to learn the landscape — what kinds of help exist, who's around, at what prices — without committing personal data to an account they may walk away from. The actual write (a match request) genuinely needs identity, so that's where the sign-up gate belongs. Defense in depth: every server action in actions.ts independently calls currentDemoOrSignedInUser and returns SIGN_IN_FIRST on null, so opening the page can't leak any write capability — the page-level public posture is a UX choice, not a security relaxation.
Riyaz's call, verbatim: "we fundamentally shouldn't gate the matchmaking to creating account. What if they don't find a lawyer within their budget?"
How to apply:
- The pattern — browse is public; the first DB write is the sign-up gate — applies to any future surface where a litigant evaluates before committing (forum read vs post, document templates browse vs fill, etc.). When you build one, follow this layering: route-matrix
public, page usescurrentDemoOrSignedInUser, branch on null in the UI, redirect anonymous write-attempts to/app/register?returnTo=…. - Never relax server-action gates to match a page-level relaxation. Every action in any public-browse surface keeps its own
if (!user) return SIGN_IN_FIRST. Two independent gates — the page can be wrong without leaking writes. - Loaders on public pages must degrade gracefully. A missing DATABASE_URL (local dev) or pre-migration deploy must render with empty data, not 500. Use the
isDatabaseNotConfigured+isUndefinedTablehelpers fromlib/db/util.ts. - The
returnTocarry-back is a small contract: post-register redirect honorsreturnToonly when it points at our own/app/*paths (open-redirect protection — the existing register surface already enforces this; verify when adding new returnTo surfaces).
Cascade required:
DECISIONS.md— D10 logged ✅lib/auth/route-matrix.ts— /app/find-attorneypublicrow + rationale comment ✅scripts/test-route-matrix.ts— expectation updated to EVERYONE ✅app/app/find-attorney/layout.tsx— deleted (was the redundant gate) ✅app/app/find-attorney/page.tsx—currentDemoOrSignedInUserreplacesrequireSignedInPage; loaders wrapped for graceful degradation ✅app/app/find-attorney/_find-attorney-client.tsx—viewer.signedInflag;chooseCardredirects anon to register; Step 2 "browsing as guest" banner ✅lib/db/util.ts—isDatabaseNotConfiguredhelper added ✅project-tasks.md— T122 → DONE (recorded in next STATE tick) ✅STATE.md— D10 + T122 noted (separate STATE tick commit)
D11 — Path B locked: main = dev (lawma611) + production = prod (lawmaco); fast-forward only; light gate
Status: 🟢 LIVE Decided: 2026-06-14 Decided by: Riyaz, after two-shark-pass synthesis (Pass 1 operational + Pass 2 paradigm) on docs/plans/2026-06-14-dev-to-prod-path-b.md and docs/plans/2026-06-14-dev-prod-gate-synthesis.md. Riyaz's session quote: "we're starting today. Don't overcomplicate it." + "this current state of Lawma2 in github is going to become the fork point where we have prod & dev splitting up."
The decision:
riyaz110/Lawma2 carries two long-lived branches.
mainis the dev arm; auto-deploys tolawma611.netlify.appon every push + a 2-hour scheduled cron.productionis the prod arm; deploys tolawmaco.netlify.appon every push.
Promotion ritual: git checkout production && git merge --ff-only origin/main && git push origin production. Fast-forward only.
The cutover from the old riyaz110/lawma direction is a single Netlify config change — repoint the existing lawmaco.netlify.app Netlify site from riyaz110/lawma main to riyaz110/Lawma2 production. No URL rename, no new site, no DB swap. The fork SHA where prod and dev start identical: 9c8c243 (T174).
The T228 hardening additions A–F (synthesis-plan, this session) are approved as written:
- A.
docs/checklists/promote-to-prod.mdwritten + every promotion merge message references it by name. - B/C. DNS TTL pre-warm + post-restore — SKIPPED per Riyaz's "don't overcomplicate." The
*.netlify.appcutover doesn't need it; if we ever attach a custom domain over real DNS we revisit. - D. Single-validator gate (Riyaz) for the first 4–6 promotions; auto-revisit triggers documented in the checklist.
- E. 3-month review (2026-09-14) parked in STATE.md to re-evaluate Path B vs trunk + flags.
- F. No hotfix commits on
productionthat aren't on main; fast-forward only. Drift = the bug Path B exists to prevent.
The migration cutover sub-plan (Addition C in the synthesis — Tier-3, Riyaz wanted it drafted) gets its own doc at docs/plans/2026-06-14-migration-cutover.md (separate task).
Why:
- Path B is structurally simple AND correct enough. Both shark passes converged: trunk + flags is cleaner but premature (no flag infra exists; building it delays the cutover).
- The "production branch is a label, not a divergence" framing removes the historical git-flow concern. As long as fast-forward is the only rule,
productionis a moving pointer at a known-goodmaincommit — it doesn't carry independent history. - The investor demo URL (
lawmaco.netlify.app) is load-bearing. Path B keeps it always reachable, with one-click Netlify rollback to the previous deploy as the belt. - Riyaz reverted from the direction
riyaz110/lawmawas heading. We're not reconciling that arm. Open PRs there are not merged. The repo gets archived (reversible) after the Netlify cutover is confirmed serving Lawma2.
Dismissed alternatives (don't re-offer):
- Path A — keep two repos. The drift between them was the original pain. Already rejected at T173.
- Path C — trunk + feature flags + alias-based promotion. Cleaner long-term but adds a multi-day flag-infra project ahead of the cutover. Defer to the 3-month review trigger.
- Tag-based promotion (no production branch, just a
prodtag). Structurally equivalent but the "merge a branch" idiom is easier for non-engineers to read. Branch wins on ergonomics. - DNS TTL pre-warm + 48hr blackout buffer + 4h lawma611 dwell. Pulled OUT of the synthesis at Riyaz's "no production-grade enterprise SaaS data" call. The synthesis plan's reasoning for including them assumed real public-user data; we don't have that. The risk model is "broken demo" not "data corruption."
- Merge the 3 open PRs on
riyaz110/lawmabefore archiving. Riyaz reverted from that direction; the work is preserved in the archived state without needing additional commits on a dead arm.
How to apply:
- Every push to
mainauto-deploys lawma611. No ceremony. - Every promotion to
productionfollowsdocs/checklists/promote-to-prod.md— gates tick, thengit merge --ff-only origin/main+git push origin production. - Forbidden: any commit landing on
productionthat isn't onmain. If a fix is needed under demo pressure, land it onmain, walk it on lawma611, then fast-forwardproduction. Even at 3am the night before a pitch. - Rollback: Netlify → lawmaco site → Deploys → previous deploy → "Publish deploy." Instant. Belt before suspenders.
- At launch (R16 trigger): the 2h guest-roster visibility filter goes away. The checklist carries an R16-still-parked item until that day.
Cascade required:
DECISIONS.md— D11 logged ✅docs/checklists/promote-to-prod.md— checklist written ✅ (T228-A)docs/plans/2026-06-14-migration-cutover.md— Tier-3 stub + two-shark-pass scaffold (next task)STATE.md— fork SHA + cutover steps Riyaz owns + 2026-09-14 review reminder (T228-D)project-tasks.md— T178 row marked DONE (production branch created + pushed); T179 row for the Netlify cutover (Riyaz's hands); T180 row for the riyaz110/lawma archive (Riyaz's hands, reversible viagh api -X PATCH /repos/riyaz110/lawma -f archived=false)riyaz110/lawmarepo — archived AFTER lawmaco is confirmed serving Lawma2 from the production branch- CLAUDE.md — "Source repos" section gets a note that
riyaz110/lawmais the archived legacy arm (after archive lands)
D12 — Retire FOUNDER_EMAIL; lawma_admin IS the platform-owner role
Status: 🟢 LIVE Decided: 2026-06-16T18:00:00Z Supersedes: — Dismissed alternatives considered:
- Keep FOUNDER_EMAIL as the indirection — rejected: the cutover incident on 2026-06-16 had Riyaz seeded as
role='author'on prod while the NetlifyFOUNDER_EMAILenv var was stillauthor@dev.lawma. Result: the founder hub showed an author chip, hid 6 admin tiles, and silently denied self-approval in the builder — a "promotion" that lived in two places (DB row + env var) and drifted with one of them missing. Decoupling identity from permissions across a row + an env var was the bug, not a feature. - Add a
founderboolean column onapp_user— rejected: another column to forget to set; same drift surface, slightly different shape. The role enum already encodes "who you are"; making founder-tier powers another row on that axis is the cheaper move. - Inline
user.role === "lawma_admin"and deleteisFounderentirely — partially adopted, partially deferred. Every formerisFounder(x)call site now means "is a lawma_admin" anyway, so the function survived as the canonical predicate (rename across 17 files in one PR is churn that changes no behavior). A follow-up PR can sweep the name when there's a reason.
See also: app/app/admin/actions.ts (deactivate + role-change guards), app/app/builder/actions.ts (self-approve gate), components/builder/publish-bar.tsx (isLawmaAdmin prop), lib/auth/template-acl.ts (renamed param), scripts/test-rbac.ts, scripts/test-route-matrix.ts.
The founder, identified by lawma_admin role on the app_user row. Pre-D12 the founder was identified by the FOUNDER_EMAIL env var matching the row's email, so a person carrying role='author' could still get owner-tier privileges (self-approval in the Builder, admin-tile bypass, all-thread inbox in messaging) via the env-var side channel. Post-D12 there is no side channel: owner-tier powers come from the role enum value lawma_admin and nothing else.
Why:
- One source of truth. Pre-D12 the founder lived in two places — the DB row and the Netlify env var — and a single-place update silently downgraded the founder. The 2026-06-16 cutover hit exactly that.
- Role-coherent. Every other privilege gate already keys on
app_user.role. The founder was the odd one out — env-var-driven while everything else was column-driven. Aligning the founder to the same axis as every other gate is one less special case in every reader's head. - Audit-shaped. A role change writes an
admin.user_role_changeaudit row. An env-var flip didn't. The "who is the platform owner" question is now part of the same append-only history as every other privilege change. - Riyaz's call (verbatim): "Can we cancel the founder email thing and just make it one lawma admin." Yes.
How to apply:
- A platform owner is now seeded with
role='lawma_admin'directly. NoFOUNDER_EMAILenv var needed. isFounder(user)is preserved as a predicate but its body now returnsuser.role === 'lawma_admin'. Signature changed fromPick<email>toPick<role>. Three callers that previously passed{email}(admin/actions.ts × 2, messaging/store.ts × 1) were rewritten to use role directly or fold into the existingrole === 'lawma_admin'branch.isAdmin(user)simplified touser.role === 'lawma_admin'(waslawma_admin || isFounder).canAuthorTemplate+canReviewTemplateparameter renamedisFounder→isLawmaAdminso the bypass flag's meaning is literal at call sites.<PublishBar>prop renamedisFounder→isLawmaAdmin. The client component now reads the role-derived boolean.- The lawma hub chip set collapsed: pre-D12 had "Founder — full access" XOR "Full access"; post-D12 has just "Full access" when
isAdmin(me). FOUNDER_EMAILreferences removed fromscripts/propagate- identity.ts,app/data-model/page.tsx, the rbac + route-matrix test suites. The Netlify env var itself can stay (unused, no effect); removing it is harmless cleanup the next time you're in Netlify env settings.- Audit-event payload field
founderSelfApprovalkept its name for log-aggregator continuity (queries against pre-D12 rows key on it). The body now evaluates the lawma_admin role.
Cascade required:
- ✓ DONE — DECISIONS.md (this entry)
- ✓ DONE —
lib/auth/stub.ts+ 16 downstream files - ✓ DONE —
scripts/test-rbac.ts+scripts/test-route-matrix.ts+scripts/test-engine.ts(parameter rename in templates) - ✓ DONE —
app/data-model/page.tsx(platform-settings entity note) - ✓ DONE —
scripts/propagate-identity.ts(rename runbook) - ✓ DONE — On the prod DB:
riyazsamnani@gmail.comset torole='lawma_admin'(wasauthor),session_versionbumped so the existing cookie re-resolves. - ⏸ DEFERRED — Future PR can fully rename
isFounder→ some variant ofisLawmaAdmin/isPlatformOwneracross all 17 callers. Not load-bearing; clarity-only. - ⏸ DEFERRED — Netlify
FOUNDER_EMAILenv var can be deleted (unused now). Harmless to leave.
D13 — Public site = second Netlify deploy off production, env-var gated (NOT a third branch)
Status: 🟢 LIVE Decided: 2026-06-16T18:30:00Z Supersedes: — Dismissed alternatives considered:
- A third long-lived branch
publicthat re-applies a "remove pages" diff — rejected: branch divergence is the exact failure mode D11 was designed to prevent. Every merge toproductionwould need a matching merge topublic, and the "delete the BP / FT / IE / debug pages" diff would have to be re-applied forever on the public side. Drift bugs are inevitable; the cost compounds with every production change. Two Netlify sites on the SAME branch reading ONE env var has none of that tax. - Separate Neon DB branch for the public site — rejected (Riyaz's call): "the demo use cases are going to be 100% identical." Both audiences walk Maria/Carmen/the persona launcher; both expect the same seeded cast. Branching the DB buys isolation we don't need yet and reintroduces the cutover-drift surface area we just spent a day cleaning up. Easy to add later (Neon branch creation is a 30-second op) if pollution ever becomes a real problem.
- Cookie-based "investor mode" on a single URL — rejected: Riyaz wants a distinct URL for the public audience so he can hand it out without exposing investor materials. A cookie isn't the same as a separate audience surface.
- Refactor marketing + app into separate Next.js apps — rejected: days of refactor work to solve a problem one env var solves.
See also: lib/config/site-mode.ts, middleware.ts, the siteMode === 'investor' gate around <InternalStepNav> in app/layout.tsx, docs/checklists/prod-inventory.md (the inventory checker stays valid for both sites since they share the DB).
The Lawma2 production branch deploys to TWO Netlify sites that share one Neon DB. They run identical code; one env var decides what each surfaces.
lawmaco.netlify.app — investor (private, password-gated) NEXT_PUBLIC_IS_PUBLIC unset (defaults to 'investor') lawma-preview.netlify.app — public (open, no password) NEXT_PUBLIC_IS_PUBLIC=true
siteMode is computed once in lib/config/site-mode.ts. Two things read it:
middleware.ts— 404s investor-only routes (Business Plan, Financial Tables v1/v2, Investment Explorer, Pitch Deck, Revenue Explained, Competitor Lab, Requirements, Data Model, Engineering) whensiteMode === 'public'. The 404 is a rewrite to/_not-found, not a redirect — a redirect would leak that the URL exists.<InternalStepNav>— the Tour bar is the investor walkthrough mechanism and hides entirely on the public site.
Why:
- One source of truth. Both audiences see the same product, just different surfaces around it. One branch = one place to update when the product changes. Branch divergence is the bug D11 was built to prevent; D13 stays on the right side of that rule.
- Reversible. Adding/removing an investor-only route is one line in
INVESTOR_ONLY_ROUTES. Adding a third audience later (say, press) is "a third Netlify site + a third env-var value." No schema change, no migration, no DB branching. - DB share matches Riyaz's stated use: the demos are 100% identical for both audiences. A separate DB would be solving a problem neither audience has.
- Public visitors cannot reach investor surfaces. Middleware runs BEFORE page render, so a public-deploy visitor who guesses
/business-plangets a 404 — Next never even builds the React tree for the investor surface on the public deploy.
How to apply:
- Adding a new investor-only surface: drop the path into
INVESTOR_ONLY_ROUTESinlib/config/site-mode.ts. Both sites pick up the new rule on the next deploy. - Removing a surface from investor-only: delete the line. Same.
- Adding a third audience (press, prospects, etc.): a third Netlify site pointed at
production, a new env-var value (NEXT_PUBLIC_IS_PUBLIC=pressor whatever), and the gate function grows from a binary boolean to a discriminated enum. Cost: small. - The Netlify env config is part of the prod-inventory checklist going forward (
docs/checklists/prod-inventory.mdsection A). Both sites must carry the rightNEXT_PUBLIC_IS_PUBLICvalue before a promote.
Cascade required:
- ✓ DONE —
DECISIONS.md(this entry) - ✓ DONE —
lib/config/site-mode.ts+middleware.ts+ the layout gate - ✓ DONE —
docs/checklists/prod-inventory.mdupdated with the new site-mode env var - ⏸ DEFERRED —
app/advertiser-portal/page.tsxcross-links to investor-only pages (/business-plan,/financial-tables,/revenue-explained,/requirements,/engineering) — these will 404 on public when clicked. Acceptable UX gap; gate at the link level in a follow-up if any public visitor surfaces the partner Vision mockup and complains. Not a security gap (the routes themselves 404; only the click is broken).
D14 — 8th-grade reading level baked into every client-facing AI prompt template (not Carmen's edit task)
Status: 🟢 LIVE Decided: 2026-06-17 (Riyaz reviewing R5 Frame 3) Supersedes: — Dismissed alternatives considered:
- Keep the 8th-grade rule as a quality bar attorneys enforce on edit. This is the de-facto state today (NFR-2 lives in prompt guidance docs but not as a baked-in prompt-template constraint). Rejected because it spends attorney time on a constraint the AI can satisfy upstream; the reading-level fix should not be the human-in-the-loop's job.
- One global prompt-prefix injected at the model API layer. Rejected as too crude — different surfaces (interview question, client-translation paragraph, partner-intake "why" string) have different reading-level mechanics. A surface-aware snippet imported per template scales better.
- Embedding-based post-hoc rewriter pass. Rejected as v1 — adds a second LLM call where one is enough; reading level should be a prompt-template instruction, not a post-process.
We bake the 8th-grade reading level instruction into the AI's prompt TEMPLATE for every surface that produces client-facing copy. One canonical snippet at lib/ai/prompts/reading-level.ts is imported by every client-facing prompt. Attorney edits target substance, not reading level.
Why:
Riyaz watching R5 Frame 3 flipped the framing: the AI should not produce court-vocabulary copy that Carmen has to manually translate. That was the right intuition: 8th-grade is a load-bearing constraint (NFR-2), it's reliably achievable at prompt time, and attorney edits are a scarce resource better spent on jurisdictional nuance, tactics, and precision. Spending them on reading-level rewrites silently shortens our edit-feedback signal (per D16) — most attorney edits should now be telling us something the AI got WRONG, not something the AI under-rotated on a well-known constraint.
How to apply:
Every prompt template in lib/ai/* whose output a client will read imports lib/ai/prompts/reading-level.ts and applies the canonical instruction. The snippet specifies: average sentence length ≤ 15 words, Flesch-Kincaid grade ≤ 8.5, no Latinisms without inline gloss, prefer second-person "you" over third-person legal phrasing, verbs over nominalizations. Attorney-facing copy (briefings, internal admin output) is explicitly NOT subject to D14 — those stay at professional reading level. Court-form filling is NOT subject either — forms use the court's exact language via deterministic mapping.
R17 captures the implementation work; D14 captures the policy.
Cascade required:
- ✓ DONE —
DECISIONS.md(this entry) - ✓ DONE —
requirements-all.mdR17 row - ⏸ NEXT —
lib/ai/prompts/reading-level.tsshipped - ⏸ NEXT — every client-facing prompt template imports it
- ⏸ NEXT — R5 Builder mockup Frame 3 reframed so Carmen's edit reads as a precision/jurisdiction edit, not a reading-level edit
- ⏸ NEXT —
features.mdCol E entry on R17 ship
D15 — Native court-grade e-signature module inside Lawma (no DocuSign / external)
Status: 🟢 LIVE Decided: 2026-06-17 (Riyaz reviewing R6 Frame 4) Supersedes: — Dismissed alternatives considered:
- DocuSign / Adobe Sign / HelloSign integration. Rejected: vendor lock-in on a load-bearing signing primitive; per-document SaaS cost on every Lawma case scales worse than building the primitive once; the evidence record we need to integrate with the audit spine is partial / opinionated on each vendor's side, not ours.
- Generic web-form signature with name typing only. Rejected: not court-admissible under California UETA without the captured evidence record (timestamp + IP + UA + document hash + intent declaration). The thin version doesn't actually meet the bar.
- Defer e-sig until launch. Rejected: R6 Frame 4 already promises the surface in the demo; shipping the real flow without the real capability creates a credibility gap with attorneys evaluating Lawma.
We build the e-signature surface natively inside Lawma. It captures the evidence record (timestamp + IP + UA + document hash + intent), seals the resulting PDF with a tamper-evident final hash, and produces an evidence-record export that holds up under California UETA. The surface lives at /app/documents/[id]/sign and writes signature events to the audit spine.
Why:
The e-signature primitive is structurally close to the deterministic- fill primitive (R6): both produce evidence-bearing artifacts that need to survive challenge. Owning both keeps the hash chain Lawma's, not a vendor's. California UETA (Civ. Code §1633) is well-specified and not a moving target; the legal requirement is bounded and implementable. Native ownership also keeps R6's "same hash all the way through" claim literally true.
How to apply:
R18 carries the implementation work. The MVP scope is California family-law cases only; multi-jurisdiction is a follow-on. The Tier-3 doc (docs/plans/2026-XX-XX-native-esignature.md) runs two shark passes per the ROE before the schema lands. CA UETA compliance gets a lawyer signoff before the first non-Lawma-employee uses it. Lawma employees CAN use it in dev for testing; non-employees wait for the legal review.
Cascade required:
- ✓ DONE —
DECISIONS.md(this entry) - ✓ DONE —
requirements-all.mdR18 row - ⏸ NEXT —
docs/plans/2026-XX-XX-native-esignature.mdwith two shark passes - ⏸ NEXT —
signature_eventschema + migration - ⏸ NEXT —
/app/documents/[id]/signsurface - ⏸ NEXT — Sealed-PDF generation + hash equality test
- ⏸ NEXT — Evidence-record export
- ⏸ NEXT — CA UETA lawyer signoff
- ⏸ NEXT — R6 Document Lifecycle mockup Frame 4 updated with explicit "Lawma e-signature" branding (vs. generic "e-sign")
D16 — Capture attorney edits on AI output as a structured corpus + extend /app/admin/ai-feedback with an Edits review tab
Status: 🟢 LIVE Decided: 2026-06-17 (Riyaz reviewing R8 Frame 3) Supersedes: — Dismissed alternatives considered:
- Extend the existing
ai_feedbacktable with abefore/after/edit_typecolumn. Rejected as v1:ai_feedbackis the 👍/👎 + note model with a different cardinality (one per rating); edits have a different lifecycle (per-paragraph diffs, multiple per artifact) and benefit from their own table. We CAN cross-join them at the review-UI layer. - No schema; capture edits in the audit-spine
audit_eventrows only. Rejected: audit-spine rows are for compliance / legal reconstruction; querying them for clustered patterns is awkward and performance-sensitive. A purpose-builtai_edit_capturetable is the right home. - Capture every keystroke for full provenance. Rejected: huge storage cost, low signal-to-noise. The structured diff at "save" time is the unit of interest.
- Defer until 100 attorneys are active. Rejected: the corpus needs to start collecting NOW so it's already meaningful when the first prompt-tuning pass happens; the cost of the table + writer is small, the cost of having no data when we need it is large.
We add an ai_edit_capture table sibling to ai_feedback, write every attorney edit on AI output to it (transparently — no attorney UX cost), and extend /app/admin/ai-feedback with an "Edits" tab that groups captured edits by surface + prompt-version + naive pattern. Lawma Admins use this surface to spot recurring AI shortcomings and tune the prompt templates.
Why:
The edit corpus is the highest-leverage AI-improvement signal Lawma will have. Every edit is an attorney saying "the AI got this wrong in this specific way." Without capture, we burn that signal on each keystroke. With capture, we get a corpus that grades the AI surface by surface, surfaces recurring failure modes, and gives prompt-tuning a target richer than vibes. It's also the upstream piece that lets us measure D14 (8th-grade reading level): we'll be able to see whether reading-level edits drop after R17 lands.
How to apply:
R19 carries the implementation work. The schema lives at ai_edit_capture; the writer at lib/ai/edit-capture.ts; the review surface extends /app/admin/ai-feedback with a tab. Naive grouping in v1 (surface + AI-text prefix similarity); embedding-based clustering is a follow-on once the corpus is large enough to need it. Privacy: actor names visible to lawma_admin only; client PII redacted from review surface payloads unless the firm explicitly opts in (per D24 AI-feature doctrine — runtime never re-emits client content without attorney approval).
The first surfaces with writers wired in are R5 Builder (interview- question edits) and R8 Case Analysis (briefing-bullet edits). Other surfaces follow as they ship their real implementations.
Cascade required:
- ✓ DONE —
DECISIONS.md(this entry) - ✓ DONE —
requirements-all.mdR19 row - ⏸ NEXT —
docs/plans/2026-06-17-edit-capture-corpus.mdwith two short shark passes - ⏸ NEXT —
ai_edit_captureschema + migration on dev Neon branch - ⏸ NEXT —
lib/ai/edit-capture.tswriter - ⏸ NEXT — Wire writer into R5 Builder edit path
- ⏸ NEXT — Wire writer into R8 Case Analysis edit path
- ⏸ NEXT — Extend
/app/admin/ai-feedbackwith Edits tab - ⏸ NEXT — R8 Case Analysis mockup Frame 3 gets an "edit captured for AI improvement" annotation
- ⏸ NEXT —
features.mdCol E entry on R19 ship
D17 — Dual-role (firm_admin + practicing lawyer) via case_participant, NOT a roles table
Status: 🟢 LIVE Decided: 2026-06-17T23:50:00Z Supersedes: — Trigger: Riyaz 2026-06-17 night — "let's have Carmen Reyes's profile have options to assign paralegals on all cases" + the follow-up clarification that the first lawyer registering a new firm becomes the firm-admin automatically, with a dual role.
The decision The same app_user row can act as BOTH firm_admin AND practicing lawyer. We do NOT add a user_role join table. We do NOT add a can_practice_law boolean. We do NOT resurrect attorney_kind='both' (banned by T103).
Instead: app_user.role='firm_admin' is the user's PRIMARY identity (it drives their home surface — /app/firm/dashboard). When they ALSO practice law, they appear as case_participant.role='attorney' rows on the cases they lead. Authorization for "this user can lead/edit case X" checks case_participant, NOT app_user.role.
Page-gate consequences
/app/firm/dashboard— firm_admin home (unchanged)./app/attorney+/app/attorney/[clientId]— gate expands tofirm_admin OR attorney. The page itself uses case_participant for per-case authority decisions (can edit, can approve documents, etc.).roleHome(firm_admin)stays/app/firm/dashboard— that's still their primary identity even if they're also leading cases.
Dismissed alternatives
user_rolejoin table — rejected: real migration, cascading authorization rewrites, no immediate need beyond what case_participant already gives us.can_practice_law: booleanon app_user — rejected: case_participant is already the practice-authority truth (D8 invariant); adding a redundant boolean creates two-sources-of-truth.- Resurrect
attorney_kind='both'— rejected by T103 already. - Two separate
app_userrows for the same human — rejected: conflicts with email uniqueness + creates session-management chaos.
Cost of being wrong Low. If we ever need richer multi-role modeling, the join-table route stays available; case_participant remains correct as the per-case truth.
Cascade
- ⏸ NEXT — Expand
/app/attorney+/app/attorney/[clientId]page-gate to acceptfirm_admin. - ⏸ NEXT — Update authorization helpers that read
me.role === 'attorney'to ALSO acceptfirm_admin(search: lib/auth/*). - ⏸ NEXT — Add "Your cases" link from
/app/firm/dashboardto the new/app/attorney/casesprofile view. - ⏸ NEXT — Update
route-matrix.tsto allow firm_admin on /app/attorney prefix. - ⏸ NEXT — Demo: seed Carmen Reyes (currently
role='attorney', firm=Reyes) so the demo still works. The DUAL-ROLE demo would seed a firm_admin who also has case_participant rows — that's a separate seed/demo, not Carmen's existing flow.
D18 — First lawyer to register a new firm becomes its firm_admin automatically
Status: 🟢 LIVE Decided: 2026-06-17T23:50:00Z Supersedes: — Trigger: Riyaz 2026-06-17 night — "let's make the first lawyer that registers and indicates a new firm, the firm admin automatically. They will have a dual role - firm admin & lawyer."
The decision At registration on /app/attorney/register (or the unified sign-up flow), the user names their firm. The flow does a fuzzy name match against existing firms.
- No match → create the firm row, mint the user with
role='firm_admin'. They can immediately take case assignments via case_participant. D17 lets the same user act as the practicing lawyer. - Match exists → "Did you mean Smith & Co Law? Request to join." The user can still proceed and create a NEW firm row — D20's merge flow handles the duplicate case post-hoc.
No verification gate in v1 The first-to-register flow does NOT require email-domain verification, Lawma-staff approval, or any other gate. Trust + audit. Lawma can revoke firm_admin status manually if abused, and the D20 merge flow collapses unknowingly-duplicated firms.
Dismissed alternatives
- Manual Lawma-staff approval before firm creation — rejected for v1: adds friction to the onboarding moment, slows the demo, and the merge flow (D20) handles the abuse case adequately.
- Email-domain verification (only @smithco.com can register Smith & Co Law) — rejected for v1: lawyers' personal emails (Gmail) vs firm emails make this brittle; trust + audit is simpler.
- Require manual claim flow (firm exists; you request membership) — rejected for v1: too much UX friction for the first user; D20 merge handles the duplicate case.
Cost of being wrong Medium. A bad actor could claim a real firm's name first, locking out the legitimate firm's people. But the merge flow (D20) provides recovery: Lawma staff can collapse the bad-actor firm into the legitimate one. Worst case is one round of inconvenience, not permanent data corruption.
Cascade
- ⏸ NEXT — Update
/app/attorney/registerflow to fuzzy-match firm name + offer "create new firm" vs "request to join" branches. - ⏸ NEXT — On new-firm creation, mint the user with
role='firm_admin'(not'attorney'). D17 keeps their attorney capabilities via case_participant. - ⏸ NEXT — Audit event:
firm.createdwith creator_user_id payload.
D19 — Firm-admins can invite additional firm-admins (no cap)
Status: 🟢 LIVE Decided: 2026-06-17T23:50:00Z Supersedes: — Trigger: Riyaz 2026-06-17 night — "they can add other firm admins, who may or may not be lawyers attached to cases."
The decision An existing firm_admin can invite additional firm_admins from /app/firm/dashboard. Two paths:
- Promote an existing firm member (currently role='attorney' or 'paralegal'): change their
app_user.roleto'firm_admin'. D17 keeps their existing case_participant authority intact. - Invite a new user (not yet at the firm): send invitation email; on signup they're created with
role='firm_admin'and the firm_id set to the inviter's firm.
No cap on the number of firm_admins per firm. A 50-lawyer firm may have 3-5 firm_admins; a solo practice has 1.
The "may or may not practice law" subtlety Firm_admin role doesn't imply attorney capability. An office manager or paralegal can be elevated to firm_admin to handle administrative tasks without ever appearing as case_participant.role='attorney'. The dashboard's "Who's carrying what" still queries case_participant — non-practicing firm_admins simply don't show up there.
Dismissed alternatives
- Single firm_admin per firm — rejected: real firms have multiple managing partners + office managers; structurally too restrictive.
- Tiered admin roles (super_admin vs admin) — rejected for v1: YAGNI; single firm_admin level covers the demo + early customers.
- Lawma-staff approval for firm_admin elevation — rejected for v1: friction; trust the existing firm_admin to invite who they want.
Cost of being wrong Low. Adding tiers, caps, or approval gates later is additive.
Cascade
- ⏸ NEXT —
/app/firm/dashboard→ "Team" section gets an "Invite a firm admin" + "Promote to firm admin" affordance per member. - ⏸ NEXT — Invitation email + signup-from-invite flow.
- ⏸ NEXT — Audit events:
firm.admin_added/firm.admin_promoted/firm.admin_demoted.
D20 — Firm merge requests via firm_merge_request table
Status: 🟢 LIVE Decided: 2026-06-17T23:50:00Z Supersedes: — Trigger: Riyaz 2026-06-17 night — "we may need to create merge requests for lawma employees to approve merging accounts, if two separate attorneys unknowingly create firm accounts. They can request lawma staff to merge from their firm admin page."
The decision New schema entity: firm_merge_request. Firm-admins request the merge from their dashboard; Lawma staff approve from /app/lawma. On approval, all source-firm data migrates to the target firm in one transaction; the source firm row stays in the database with merged_into_firm_id pointing at the target (soft-merge — audit trail outlives the firm).
Schema sketch
firm_merge_request (
id uuid pk,
source_firm_id uuid fk → firm.id,
target_firm_id uuid fk → firm.id,
requested_by_user_id uuid fk → app_user.id,
reason text,
status enum (pending / approved / denied / withdrawn),
reviewed_by_lawma_staff_id uuid? fk → app_user.id,
reviewed_at timestamp?,
review_note text?,
created_at timestamp default now()
)
firm (
...existing columns...,
merged_into_firm_id uuid? fk → firm.id -- soft-merge target; null for live firms
)Approval workflow On firm_merge_request.status = 'approved':
- Update every
app_user.firm_idfrom source → target. - Update every
engagement.firm_id,case_participant.firm_id,audit_event.firm_idfrom source → target. - Set
firm.merged_into_firm_id = target_firm_idon the source row. The source firm row is NOT deleted — audit trail integrity. - Write one big audit event
firm.mergedwith the full payload (source/target ids, mover, row counts, timestamp).
Wrapped in a single DB transaction. If any step fails, the whole merge aborts cleanly.
Conflict refusal If the source + target firms share any active member (same app_user.id on both at the same time — happens because firm_id is currently single-valued, so this can't actually occur via the schema; but if someone hand-edited rows it could), Lawma staff sees the conflict explicitly in the approval surface and the merge button is disabled until resolved.
Dismissed alternatives
- No merge feature; manual DB surgery by Lawma engineers — rejected: every merge is a one-off ticket; doesn't scale; no audit trail of why.
- Self-service merge (firm-admin clicks merge, no Lawma approval) — rejected: too easily abused; merge is destructive enough that an outside reviewer is warranted.
- Hard-delete source firm after merge — rejected: audit-trail integrity matters more than table size. Soft-merge via
merged_into_firm_idkeeps the historical pointer intact.
Cost of being wrong High. A bad merge corrupts cross-tenant data. That's why Lawma-staff approval is a hard gate, why we soft-merge instead of hard-delete, and why every approval writes a big audit row that's easy to find later.
Cascade
- ⏸ NEXT — Migration:
firm_merge_requesttable +firm.merged_into_firm_idcolumn. - ⏸ NEXT — Writer:
requestFirmMerge+approveFirmMerge+denyFirmMergeinlib/firms/merge.ts. - ⏸ NEXT — Firm-admin UX: "Request a merge" section on
/app/firm/dashboard. - ⏸ NEXT — Lawma staff UX: "Firm merge requests" tile on
/app/lawma. - ⏸ NEXT — Page-gate update: all firm-scoped readers should follow
merged_into_firm_idchain (read from the target firm if the queried firm has been merged). - ⏸ NEXT — Audit events:
firm.merge_requested/firm.merge_approved/firm.merge_denied/firm.merged.
D22 — R18 v1 scope = typed-name signatures + 3 non-negotiables; drawn-signature v1.5; polish v2
Status: 🟢 LIVE Decided: 2026-06-18T04:30:00Z Supersedes: — Builds on: D15 (native court-grade e-signature, no DocuSign / external). Sharks consulted: docs/shark/2026-06-17-native-esignature-pass-1.md (failure-mode lens) + docs/shark/2026-06-17-native-esignature-pass-2.md (scope + build-vs-buy lens). Plan: docs/plans/2026-06-18-r18-v1-esignature.md.
Decision R18 v1 ships typed-name signatures (no drawn-signature canvas) with the three non-negotiables from Pass 1 baked in from day one:
- Detached signatures. The signature event captures the document hash AS PRESENTED to the signer (pre-embedding). The AUTHORITATIVE artifact is the pre-embedding hash + the evidence record. The sealed PDF with embedded signatures is a derived artifact.
- RFC 3161 trusted timestamps on every signature event. Server-clock alone is not legally adequate. TSA cost (~$0.005/call via DigiCert or GlobalSign) is negligible relative to legal cost of a contested signature.
- Short-lived invite tokens for counterparty signing. The link a non-account holder receives (e.g. opposing party) expires fast and is single-use; no permanent URLs that leak via email forwarding.
Concretely the v1:
- New
signature_eventtable + indexes (per-document, per-signer, per-action). - Migration adds
signed | signature_pendingtodocument_statusenum. - Writer
recordSignatureEventinlib/signatures/store.ts— captures actor, document hash pre-embedding, server clock, RFC 3161 timestamp, IP, user agent, signature artifact (typed name only in v1). - TSA integration via DigiCert or GlobalSign — single TSA call per signature.
- Signing surface at
/app/documents/[id]/sign— minimal: typed-name input + canonical confirmation copy ("I, [name], intend to sign this document electronically per California UETA"); no drawn-signature canvas. - Counterparty invite flow: short-lived JWT (15-minute TTL, single-use) emailed to the counterparty; landing page is a stub
/app/documents/sign-invite/[token]that lets a non-account holder type their name + sign. - Sealed-PDF generation re-renders the source PDF with the typed signatures embedded as text + a tamper-evident final hash printed in the footer.
- Evidence-record export: HTML the firm can print as a PDF if challenged, listing every captured field + the CA UETA §1633 citation per field.
- Audit-spine integration: every signature event writes one
audit_eventrow withaction='document.signed'and the full hash payload;representedUserIdpopulated viaresolveRepresentedAttorneyIdso a paralegal-initiated signature surfaces "on behalf of". - CA UETA lawyer signoff GATE — v1 cannot reach real customers until a CA-licensed lawyer reviews the typed-name surface + the evidence record + the three non-negotiables and signs off.
v1.5 (one to two weeks after v1): drawn-signature canvas. Same schema; new artifact format on signature_event.artifact_kind (typed vs drawn). Same evidence record. Same CA UETA basis. Adds the wow-factor visual but is NOT a legal upgrade — typed-name and drawn-signature have identical UETA admissibility.
v2 (after v1.5 lands and the lawyer signoff is in hand):
- Tamper-evident final-hash visualization on the SIGNED state in the UI (the R6 mockup's "same hash all the way through" visual claim).
- Multi-signer counterparty flow polish (visual progress bar for two-party signings; expiry email reminders).
- Multi-document batch signing for an attorney signing several documents in one session.
- Evidence-record polish (Lawma-branded PDF generation, custom date/jurisdiction copy per the firm).
Why Both R18 sharks reached the same v1 cut:
- Pass 1 (failure-mode lens): identified three structural failure modes — F1 (embedded-vs-detached signature confusion), F2 (timestamp drift between server clock and RFC 3161), F3 (cross-tenant invite-link mix-up). The three non-negotiables (detached + RFC 3161 + short-lived single-use tokens) are the architectural answers; deferring any of them gambles on a failure mode that's expensive to retrofit.
- Pass 2 (scope lens): asked "is native really right vs. DocuSign?" Steel-manned vendor case; concluded native is right BUT the smallest defensible v1 is typed-name only. Pass 2 verdict: "ship typed-name with all three non-negotiables in week 1 BETTER than the full polish in week 4 — every week between today and the first real signature is a week R6 documents are stuck in APPROVED with no advance."
Pass 2's key insight: drawn-signature has identical UETA legal weight to typed-name. Drawn looks more impressive in a demo, but the legal artifact is the recorded intent + the evidence record. Deferring drawn-signature to v1.5 buys ~2 weeks of build time at zero legal-weight cost.
The R20 + R18 v1 scope-locks share the same compression pattern: cut the original spec to the smallest legally-defensible v1, ship in week 1, defer polish to v1.5/v2 where the polish is decorative (refund button vs. trial mode; typed-name vs. drawn-signature). Pattern is generalizable to other R-rows where the spec is ambitious.
How to apply Engineering:
- PR for D22 lock + plan ships first (this PR).
- Implementation phases land in order: schema → TSA integration → writer → signing surface (own account holders) → invite-token flow (counterparties) → sealed-PDF generation → evidence-record export → audit-spine integration. Each is its own PR per the < 400 LOC / < 24h envelope.
- No code change merges to lawma611 (dev) without
recordSignatureEventwriting the RFC 3161 timestamp. That's a hard CI check — the writer test asserts a non-null TSA token. If the TSA is unreachable during CI, the test mocks the TSA but the code path is exercised. - No real-money / real-customer ON until CA UETA lawyer signoff lands as a separate D-entry. The signing surface CAN be exercised in dev with stub-mode auth + Stripe test mode (R20) before the signoff arrives — but the production deploy gate is the signoff.
- Counterparty invite tokens: JWT signed with
R18_INVITE_SECRETenv var. 15-minute TTL. Single-use enforced viainvite_token_used_atcolumn on a new lightweight table. - Detached-signature pattern:
recordSignatureEventacceptsdocumentHashAtSigningas a parameter; the caller computes the hash AT THE MOMENT of presenting the document; sealing is a separate step that does NOT compute the hash again. - Audit-spine: every signature_event also writes an
audit_eventwithaction='document.signed'AND the same hash payload. Two storage locations on purpose — theaudit_eventis for the cross-action timeline; thesignature_eventis the authoritative legal artifact with TSA + IP + UA.
Product / legal:
- D15 cascade is updated: D22 is the v1 scope-lock for the D15 "native court-grade e-signature" decision; D15 stays LIVE; D22 stays LIVE; both reference each other.
- Mockup at
/personas/document-lifecyclealready exists (R6); SIGNED frame matches the typed-name v1 visual after this PR. - Requirements-all.md R18 row gets the v1/v1.5/v2 split spelled out + status flips to In Progress.
- features.md R18 row written at v1 ship with the trial-mode-style decision-trail in Col E.
- The CA UETA lawyer signoff is the standing gate. Until the signoff D-entry lands, R18 production deploy is forbidden EVEN IF the code is fully shipped.
Dismissed alternatives
- Full R18 spec (drawn-signature + multi-signer polish + tamper-evident visualization in v1) — rejected: Pass 2 identified the time-to-first-signature as the binding cost; full polish adds 2–3 weeks of build time at zero legal weight improvement.
- DocuSign embedded API instead of native — rejected (already locked by D15): vendor lock-in on a load-bearing signing primitive; cross-vendor evidence-record split; D2 brand-native commitment; per-envelope SaaS cost compounds at scale. Pass 2 steel-manned the vendor case and ended up reaffirming D15.
- Skip RFC 3161 in v1; add TSA in v2 — rejected: server-clock alone is legally weaker than RFC 3161; retrofitting TSA on existing signature events would require re-timestamping (legally awkward — what timestamp do you attest to?). Cheaper and cleaner to bake TSA in from day one. The cost is $0.005/signature; meaningless next to legal cost of a contested timestamp.
- Skip detached signatures; embed signatures directly into PDF and hash the result — rejected: Pass 1 F1 explicitly flagged this. Embedded-only signatures conflate "what the signer saw" with "what the court receives"; if the embedded PDF is later re-rendered or has its metadata stripped, the hash invariant breaks. Detached signatures keep the legal artifact independent of the PDF rendering pipeline.
- Long-lived invite URLs for counterparty signing — rejected: Pass 1 F3 cross-tenant mix-up risk; email forwarding leaks; phishing surface. Short-lived single-use JWTs are the cheap correct answer.
- Geolocation as part of evidence record — deferred (not rejected): can land later as a column extension to
signature_event. Privacy-by-default (D5 client_translation pattern) suggests gating geolocation behind explicit consent; v1 skips it to avoid the consent UX scope. - Build R20 first, defer R18 entirely — rejected (sequencing not scope): Riyaz explicitly greenlit both R20 and R18 v1 builds in parallel 2026-06-18 04:14 UTC. R18 unblocks R6 SIGNED state; R20 unblocks the marketplace's revenue thesis; both matter, neither blocks the other architecturally.
Cost of being wrong Medium-to-high. The schema (signature_event table + the three non-negotiables) is the architecturally load-bearing piece — once thousands of signatures land against the schema, changing it (e.g. retrofitting TSA, splitting detached/embedded) is expensive. THAT'S why both sharks made the three non-negotiables non-negotiable: those decisions are committed-once with v1's schema.
Conversely: deferring drawn-signature to v1.5 is essentially free reversibility — same schema, additive artifact-kind value, optional UX. v2 polish is purely decorative.
The asymmetric reversibility points to the chosen cut: lock the schema-level decisions hard in v1; defer the UX-level polish where reversibility is cheap.
Cascade
- ⏸ NEXT — Migration:
signature_eventtable + indexes; extenddocument_statusenum withsignature_pending | signed; newinvite_tokenlightweight table for counterparty single-use tokens. - ⏸ NEXT — TSA integration utility at
lib/signatures/tsa.ts(DigiCert or GlobalSign client). - ⏸ NEXT — Writer
recordSignatureEventinlib/signatures/store.ts. - ⏸ NEXT — Signing surface at
/app/documents/[id]/sign— typed-name only. - ⏸ NEXT — Counterparty invite stub at
/app/documents/sign-invite/[token]+ JWT helper atlib/signatures/invite-tokens.ts. - ⏸ NEXT — Sealed-PDF generation utility at
lib/signatures/sealed-pdf.ts. - ⏸ NEXT — Evidence-record HTML export at
/app/documents/[id]/evidence+ per-field CA UETA §1633 citation copy. - ⏸ NEXT — Audit-spine integration: every signature_event writes the paired audit_event with
representedUserIdresolved. - ⏸ NEXT — Notification kinds:
signature_requested/signature_completed/signature_invite_expired. - ⏸ NEXT — Mockup parity check on
/personas/document-lifecycleSIGNED frame; reconcile any drift between mockup and real v1 surface. - ⏸ NEXT — requirements-all.md R18 status flip with v1/v1.5/v2 split.
- ⏸ FUTURE-V1.5 — Drawn-signature canvas (~1 week after v1).
- ⏸ FUTURE-V2 — Tamper-evident final-hash visualization on SIGNED frame; multi-signer counterparty polish; multi-document batch signing.
- ⏸ GATE — Separate D-entry locking CA UETA lawyer signoff before real customer signatures.
D21 — R20 v1 scope = pay-now-with-7-day-refund only; defer two-mode trial-state lifecycle
Status: 🟢 LIVE Decided: 2026-06-18T04:15:00Z Supersedes: — Sharks consulted: docs/shark/2026-06-17-payment-journey-pass-1.md (funnel/conversion lens), docs/shark/2026-06-17-payment-journey-pass-2.md (D2 invariant + Rule-1.18 legal lens). Plan: docs/plans/2026-06-18-r20-v1-payment.md.
Decision R20 v1 ships pay-now-with-7-day-refund only. The match-confirm step is a single "Pay $X now — full refund within 7 days" flow, not a two-mode picker. The originally-spec'd trial engagement state and the post-interview commit screen are deferred until (a) we have paying-customer funnel data that justifies the conversion-protection thesis AND (b) California state-bar opinion clears the Rule-1.18 exposure for trial-state engagements.
Concretely the v1:
- Extends
engagement_statusenum withpending_payment | paid | refunded(NOTtrial). - Adds
stripe_connect_account_idtoapp_user(nullable; Network Lawyers only — Lawma Staff payouts direct). - Writers in
lib/payments/store.ts:captureFlatFeeNow+refundEngagementWithinWindow. - Single Stripe Payment Intent flow via Elements (NOT Stripe Checkout redirect; brand-native per D2).
- Refund button visible on the SRL's case view for the 7-day window; one-click full refund; engagement →
refunded. - Audit events:
payment.captured,payment.refunded,payment.failed. - Notification kinds via the existing case-notification spine (PR #67):
payment_captured,payment_refunded,payment_failed. - Attorney roster pill:
Pending(gray) /Paid(green) /Refunded(red). - R3 firm-admin dashboard: "Active engagements / Refunded this month" rollup row.
- Stripe TEST MODE only in v1; real-money switch waits on legal review of refund-window copy + CA UETA-equivalent for payment receipts.
Why Both Tier-3 shark passes (independently — Pass 1 didn't read Pass 2 and vice versa) converged on the same recommendation:
- Pass 1 (funnel angle): The conversion-protection thesis (trial-mode SRLs convert higher post-interview) is an untested hypothesis. We have zero paying-customer data. Spending 7–8 engineering days on an unvalidated bet, while taking on the attorney's "I did 6 unpaid hours this week" failure mode, is a poor expected-value trade. The pay-now-with-7-day-refund default removes the hesitation prime ("if you change your mind, you get your money back") without exposing attorneys to unpaid trial work. Conversion is testable in v1; trial mode can come back as v2 if data justifies it.
- Pass 2 (D2 + legal angle): A
trialengagement that unlocks the coaching interview without payment puts the attorney inside California Rule of Professional Conduct 1.18 (duties to prospective client) territory. Confidentiality, conflict-screening, and possibly fiduciary duties attach the moment the SRL reasonably believes Carmen is representing them. The spec's framing ("the SRL sees 'your case is open with Carmen'") all but guarantees that reasonable belief. Until a CA legal opinion explicitly clears trial-state work as outside the relationship boundary, shipping the trial mode is a legal exposure we don't need to take. Pay-now creates a clean, fully-paid relationship; the 7-day refund is a contractual unwind, not a representation-question.
The fact that two independent angles reach the same lean-v1 cut is a strong convergence signal. Both passes also agree on what the deferred work should learn from v1 before being unblocked:
- Paying-customer funnel conversion rate (does pay-now lose so many that trial mode is the only path to revenue?).
- Refund rate within the 7-day window (signal for "buyer's remorse" vs. "wrong-attorney-match").
- Attorney NPS on the pay-now-only flow (do they hate having no try-before-buy fallback?).
- CA state-bar opinion (or analogous opinion from another bar Lawma operates in).
How to apply Engineering:
- The implementation in PR #80 (forthcoming) only adds
pending_payment | paid | refundedtoengagement_status. Do NOT addtrialin the same migration; that's a future migration when v2 unblocks. - UX layer is single-flow: no radio button, no "try first" option. Match-confirm is "Pay $X now — full refund within 7 days, no questions asked."
- Refund window is computed server-side from
payment.captured_at + 7 days; never trust client clock. - Refund button SHOULD be discoverable but not obnoxious — on the SRL's case view, with the days-remaining count and a one-click confirm modal. After day 7, the button disappears.
- Stripe payouts to Network Lawyers go via Connect; payouts to Lawma Staff stay direct to Lawma. The 7-day refund window means we either (a) hold platform-side and release on day 8 OR (b) pay out immediately and reverse via Connect-reversal on refund. Pick (a) for v1 — simpler reconciliation, less Connect-reversal complexity.
- The case-notification kind enum gets three new values; the page copy on
/app/attorney/notificationslearns them. - Stripe TEST MODE only. Real-money requires a separate D-entry, lawyer-reviewed refund copy, and a deliberate go-live ritual.
Product / non-engineering:
- features.md gets an R20 row the moment v1 ships, with the decision-trail Col E noting "Trial mode deferred per D21 + Pass 2 Rule-1.18 risk; revisit when (1)(2)(3)(4) all clear."
- requirements-all.md R20 status flips to 🟡 In Progress with the v1 vs. v2 scope split spelled out.
- The R20 mockup at
/personas/payment(when written) reflects the v1 single-flow, NOT the original two-mode design — D6 paired-mockup convention requires mockup matches the real surface. - The investor demo narrative around R20: "the marketplace converts and refunds cleanly; we'll add try-before-buy when paying-customer data tells us we need it" — owns the lean v1 as a deliberate sequencing call, not a missing feature.
Dismissed alternatives
- Full two-mode trial-state lifecycle (the original
docs/plans/2026-06-17-payment-journey.mdproposal) — rejected: Pass 2 Rule-1.18 exposure on the trial state without paying-customer compensation; Pass 1 conversion-protection thesis is unvalidated with zero customer data. Build cost ~7–8 days for the full mode vs. ~3 days for v1; expected value of the deferral is positive in both data-and-build-cost terms. - Pay-now-only with NO refund — rejected: removes the SRL safety net entirely; transforms every "I'm not sure" into a funnel exit instead of a contained reversal; refund window is the legally-safe analog of "try before commit" without exposing the attorney to unpaid Rule-1.18 duties.
- Pay-now with a longer (30-day) refund window — rejected for v1: 30 days lets the SRL extract weeks of attorney work, then refund — that's the abuse vector Pass 2 explicitly flagged. 7 days is short enough to bound the abuse surface but long enough to let an SRL meet their attorney once, sit with the decision overnight, and back out. Revisit window length if data shows day-6 refunds spike (signal it's too short) or day-1 refunds dominate (signal "wrong-match" — fix the matching, not the window).
- Stripe Checkout (hosted redirect) — rejected: D2 says Lawma-native is the brand commitment. Checkout-redirect breaks the bench experience and prevents us from showing Lawma-branded receipt copy in-app. Stripe Elements keeps the surface ours.
- DocuSign / Stripe Link / external e-commerce platform — rejected for the same D2 reason as the e-sig decision (D15): the moat is the integrated, attorney-supervised surface; redirecting to a third-party page surrenders the user's last conversion moment.
- Defer R20 entirely; ship R18 first — rejected (sequencing call, not a v1-scope question): R20 unblocks the marketplace's revenue thesis directly; R18 unblocks R6 SIGNED state. Both matter; Riyaz explicitly picked both this session. v1 of each can run in parallel without surface collision.
Cost of being wrong Medium. The simpler v1 schema means: if v2 (trial mode) lands later, it's an additive migration (add trial to the enum + add the trial→paid commit-screen flow) — no schema rewrite of v1 paying-customer rows. The cost surface is mostly the foregone funnel data we won't collect from a trial mode that doesn't exist — but Pass 1 explicitly argued that data is more useful AFTER paying customers anyway. If the lean v1 converts poorly AND Rule-1.18 opinion clears trial-state quickly, v2 is a ~5-day add-on, not a do-over.
The reversibility direction is asymmetric: a too-lean v1 expands gracefully into a richer v2; a too-rich v1 with Rule-1.18 exposure could leave attorneys carrying duties Lawma can't insure against. Asymmetric reversibility points to lean v1 as the right risk posture.
Cascade
- ⏸ NEXT — Migration: extend
engagement_statusenum withpending_payment | paid | refunded; addstripe_connect_account_id(nullable) toapp_user. - ⏸ NEXT — Writer:
captureFlatFeeNow+refundEngagementWithinWindowinlib/payments/store.ts. - ⏸ NEXT — Stripe webhook handler: extend
app/api/stripe/webhook/route.tsforpayment_intent.succeeded+payment_intent.payment_failed+charge.refunded. - ⏸ NEXT — Network Lawyer Connect onboarding action at
/app/attorney/profile/stripe-connect. - ⏸ NEXT — Match-confirm UX rewrite on
/app/find-attorney/[id]/confirm: single pay-now flow + 7-day-refund copy. - ⏸ NEXT — SRL refund button on case view, scoped to the 7-day window.
- ⏸ NEXT — Attorney roster pill (Pending / Paid / Refunded) on
/app/attorney. - ⏸ NEXT — R3 firm-admin dashboard rollup: "Active engagements / Refunded this month".
- ⏸ NEXT — Case-notification kind enum:
payment_captured/payment_refunded/payment_failed+ page copy. - ⏸ NEXT — Mockup at
/personas/payment(single-flow pay-now-with-refund) per D6. - ⏸ NEXT — features.md R20 row at v1 ship.
- ⏸ NEXT — requirements-all.md R20 status flip to 🟡 In Progress with v1 vs v2 split spelled out.
- ⏸ FUTURE-V2 — Re-evaluate trial mode after collecting v1 funnel data (conversion rate, refund rate, refund timing distribution, attorney NPS, CA state-bar opinion on Rule-1.18 trial-state exposure). Architecture locked by D23 (2026-06-18); code lands the day the 4 gates clear.
D23 — R20 v2 trial-mode architecture locked + parked behind D21 gates
Status: 🟡 PARKED Decided: 2026-06-18T09:50:00Z Supersedes: — Architecture-of-record: docs/plans/2026-06-18-r20-v2-trial-mode-architecture.md (the full plan; this entry summarizes + locks). Builds on: D21 (v1 scope-lock; v2 gating conditions).
Decision Lock the R20 v2 trial-mode architecture today so that when D21's four gates clear, the build is a mechanical translation of the plan doc into PRs — not a fresh design cycle from the (stale, pre-v1.5) original v2 spec at docs/plans/2026-06-17-payment-journey.md. No code or schema migration lands today; this D-entry exists so the architecture survives whatever delay the gates impose.
The v2 architecture, in three sentences:
- Match-confirm becomes a two-option picker (Pay-now-with-refund stays as the recommended default; "Try interview first" is the new branch).
- The trial branch creates
engagement(trial)with NO Stripe call; the SRL is given coaching-interview access; at interview completion they hit/app/interview/[caseId]/commitand choose commit-or-back-out. - Commit → fresh Payment Intent →
engagement → paid→ standard 7-day refund window opens. Back-out →engagement → trial_backed_out→ attorney notified (no charge, no UX penalty signal).
Why now (architecture; not yet code)
- D21 explicitly tracks 4 gates that must clear: paying-customer funnel data, refund-rate data, attorney NPS, CA state-bar Rule-1.18 opinion. None will clear today; the v1 cohort hasn't even started.
- v1 shipped insights that revise the original v2 spec (pi-resume pattern, 7d refund window persists into v2, attorney-honorarium schema slot). If we don't lock now, the next session unblocking v2 will reconstruct from the stale spec and miss these revisions.
- Architecture has zero blast radius today — it's a docs+D-entry change. Code stays parked.
v1.5 deltas that revise the original v2 spec (the load-bearing reason this entry exists)
- PI-resume pattern (R20 v1.5 — landed in this same PR):
retrievePaymentIntentreturnsclient_secret. v2 writers should NOT use SetupIntent+later-charge — single PI created on commit, single client_secret reused on retry. - 7-day refund window persists into v2: every
paidengagement gets the 7d window, including trial-committed engagements. The trial branch is NOT a "skip refund" path; it's a "delay payment then enter the same paid lifecycle." - Attorney-honorarium schema slot: v2 schema gets a NULL
trial_compensation_centscolumn onengagement. v3 may use it if NPS shows attorneys want compensation for non-converting trial interviews; v2 ships without using it. Adding the slot now means v3 is additive, not a fresh migration.
How to apply (when gates clear)
- New D-entry (D2x) locks the v2 scope at code-landing time — this entry is architecture-of-record only.
- Migration
0050_r20_v2_trial_mode.sql(or whatever number is current) per the plan doc. lib/payments/r20-v2-writers.tswithstartEngagementTrial/commitTrialAndCapture/closeTrialAsBackedOut.- Match-confirm rewrite at
/app/find-attorney/[id]/confirm. - Commit screen at
/app/interview/[caseId]/commit. - Notification kind extensions (3 new kinds) + page copy.
- Roster pill + R3 dashboard rollup.
- Demo seed + personas card #7 ("Client trying the interview first").
Dismissed alternatives (revisited from the original v2 spec)
- SetupIntent + later capture pattern — rejected per v1.5 PI-resume learning. Single PI created on commit is cleaner.
- No 7-day refund window after trial commit — rejected. The window is THE D21 guarantee; trial-committed engagements get it too.
- No attorney honorarium for non-converting trials — partly accepted (v2 ships without it) but the schema slot is added so v3 can layer it without a migration.
- Default the picker to "Try first" (the original spec's choice) — rejected. Pay-now-with-refund remains the "(recommended)" default for both conversion + Rule-1.18 narrative reasons.
- Skip the architecture lock today, design at gate-clear time — rejected. v1.5 deltas would be lost; the next session would build from the stale spec. The lock-now cost is one docs PR; the unlock-time benefit is a clean mechanical build.
Cost of being wrong Low. This entry is architecture-of-record, not a build commitment. If the gates take a year to clear and the v1 cohort surfaces unexpected insights, the next session can write D24 superseding D23. The plan doc itself is editable as new v1 data arrives — that's its job.
Cascade
- ⏸ GATE — D21 gate #1: pilot paying-customer conversion data.
- ⏸ GATE — D21 gate #2: refund-rate distribution.
- ⏸ GATE — D21 gate #3: attorney NPS on pay-now-only flow.
- ⏸ GATE — D21 gate #4: CA state-bar opinion on Rule-1.18 trial-state.
- ⏸ FUTURE — D2x: v2 code-landing D-entry (separate from D23, written the day gates clear).
- ⏸ FUTURE — migration 0050_r20_v2_trial_mode.sql.
- ⏸ FUTURE — lib/payments/r20-v2-writers.ts.
- ⏸ FUTURE —
/app/find-attorney/[id]/confirmtwo-mode picker. - ⏸ FUTURE —
/app/interview/[caseId]/commitpost-interview commit screen. - ⏸ FUTURE — Notification kinds: trial_started / trial_back_out / trial_committed.
- ⏸ FUTURE — Attorney roster Trial pill.
- ⏸ FUTURE — R3 firm-admin "Trials in flight" rollup.
- ⏸ FUTURE — Demo seed trial-mode persona.
- ⏸ FUTURE —
/personascard #7 "Client trying the interview first."
D24 — Post-refund answer-handling = RETAIN-WITH-NOTICE
Status: 🟢 LIVE Decided: 2026-06-18T22:00:00Z Supersedes: — Builds on: D21 (R20 v1 refund window), D2 (relationship-before-coaching gate).
Decision When an R20 v1 engagement flips to refunded (either SRL-initiated within the 7-day window OR operator-initiated post-paid), the SRL's already-typed interview answers + AI-edit-capture rows REMAIN in the database — they are NOT nullified or purged. The attorney's view filters them out (engagement.status='refunded' filter on the roster + on the per-case file), so the attorney loses access on the same beat the refund clears. The retention period matches California State Bar Rule 3-700(D)(1)'s 5-year minimum for closed-matter records.
The refund-receipt email carries an explicit disclosure:
"Your case data stays in our records for five years per California State Bar rules, then is automatically deleted. Your attorney no longer has access. If you'd like us to delete it sooner, write to support@lawma.co — we'll honor the request after confirming it's yours and not part of an active audit."
Why this (not NULLIFY)
- Audit trail under malpractice review. If the SRL later files a state-bar complaint OR the attorney is independently audited for record-keeping, the original answers are the evidence both sides need. NULLIFY destroys that evidence on the SRL's unilateral action — bad for the attorney + bad for the SRL if their complaint relies on what they originally said.
- State-bar retention rules. CA Rule 3-700(D)(1) requires 5-year retention of client files for closed matters. Lawma is the attorney's record-keeping infrastructure for the matters it brokers; nullifying on refund would violate the attorney's own retention obligation.
- Future re-engagement. An SRL who refunds and later returns gets to pick up their work; not retaining = re-starting from zero, which is hostile.
- Disclosure preserves autonomy. The email tells the SRL the policy + offers an opt-out (delete sooner on request). That's the right shape: retention is the default; deletion is the SRL's right.
Dismissed alternatives
- NULLIFY (privacy-strict). Erase answers on refund. Honors the SRL's "I'm walking away" intent. Rejected for the four reasons above.
- NULLIFY-WITH-DELAY. Keep for 30 days then erase. Compromise but still violates state-bar 5-year retention + creates a counter-intuitive cliff. Rejected.
- PARTIAL-RETAIN. Keep metadata (timestamps, counts) but nullify free-text answers. Similar problems to NULLIFY + adds complexity. Rejected.
Concrete behavior
refundEngagementWithinWindowwriter (already shipped in R20 v1) flipsengagement.status='refunded'. No further answer-table mutation.- Attorney roster queries filter
engagement.status IN ('active','paid')— refunded engagements drop off. loadActiveEngagement(lib/matchmaking/store.ts) does NOT return refunded engagements, so the D2 coaching gate closes on the SRL's side too.- New refund-receipt email template will carry the disclosure copy above (lands in R4 phase 5 or earlier when the refund-completion email gets implemented).
Cascade
- 🟢
lib/matchmaking/engagement.ts → canStartCoachingalready returns false forrefunded(R4 phase 1, same PR). - 🟢
lib/matchmaking/store.ts → loadActiveEngagementalready filters refunded out (R4 phase 1, same PR). - ⏸ FUTURE — refund-receipt email template carries the D24 disclosure copy (R4 phase 5 or sooner).
- ⏸ FUTURE —
/app/admin/support-ticketsreviewer adds a "delete-on-request" affordance that wraps a smallpurgeRefundedEngagementAnswers(engagementId)writer. v1 ships without it; manual SQL covers the rare request. - ⏸ FUTURE — 5-year automatic-purge cron job (CA Rule 3-700(D)(1) compliance). Tracked when the first refund actually crosses the 5-year mark, which is years away.
Cost of being wrong Low — RETAIN-WITH-NOTICE is the conservative default. If a future SRL refund-case sets a privacy precedent that requires erasure, D24 can be superseded by a NULLIFY-with-grace-period D-entry without breaking the audit trail (existing refunded answers stay; new ones erase).
D25 — R18 production deploy gated on CA UETA lawyer signoff
Locked: 2026-06-18. Status: 🟡 LAW REVIEW PENDING. Owner: Riyaz (lines up CA UETA-qualified counsel). Builds on: D15 (native commitment), D22 (v1 scope), R18 phase 1 hardening (PR #142).
Decision R18 v1/v1.5 code is production-ready on the engineering axis (4 hardening fixes shipped — GET→POST invite, TSA structural verify, hash-drift cross-check, evidence cross-document check). Production deploy is gated on a CA UETA-qualified attorney's signoff naming per-flow questions as listed below. The signoff is per-flow because each flow involves a different attribution + evidence shape; counsel may bless one and gate the others.
The three flows + the per-flow signoff questions
- Typed-name flow (own-account signer, R18 v1):
- Does the canonical intent copy on
/app/documents/[id]/signconstitute electronic assent under Civ. Code §1633.5(b)? - Is the typed-name capture, paired with the request meta (IP + UA + server clock + RFC 3161 TSA) sufficient attribution under Civ. Code §1633.9(a)?
- Is the detached-signature posture (document hash captured at presentation; sealed PDF a derived artifact) sufficient for non-repudiation under California precedent?
- Drawn flow (own-account signer, R18 v1.5):
- Does the canvas-rendered SVG signature meet the same Civ. Code §1633 attribution bar as typed-name?
- Are there forgery-resistance properties the courts have looked for in drawn signatures that we should additionally capture (pressure, velocity)? v1.5 captures none of these.
- Counterparty invite flow (non-account signer, R18 v1):
- Is the 15-minute single-use JWT, click-to-confirm POST pattern sufficient for the non-account signer's identity?
- Does the email-only delivery channel satisfy §1633.5(d) ("consumer's electronic consent must be reasonably demonstrable that the consumer can access...")? Our flow assumes the signer's working email = sufficient access; counsel should opine.
- The evidence record currently surfaces the signer's typed name + the email the invite was sent to; counsel may want additional prompts (e.g., "I am [name] and I am authorized to sign this document").
Signoff format A written memo from CA UETA-qualified counsel covering all three flows. The memo's hash + the intent copy hash at signoff time go into a new audit table (r18_legal_signoff) that the production deploy gate reads. Re-signoff required when the intent copy changes — the audit row's hash mismatch triggers the gate.
Dismissed alternatives
- Single blanket signoff covering all flows. Rejected — each flow has distinct legal questions; bundling risks a "no" on the weakest flow blocking the strong ones. Per-flow lets us go-live on typed-name while drawn or counterparty signoff still pending.
- Ship to prod without signoff, mark the signed-PDF clearly experimental. Rejected — the moment a real document is signed, the experimental disclaimer doesn't undo Lawma's signaling that this is a court-grade artifact. Either we say it is, or we don't ship.
Cascade
- ⏸ FUTURE —
r18_legal_signofftable + production-deploy gate reading from it. - ⏸ FUTURE — admin surface at
/app/admin/r18-signofffor Lawma staff to record the memo + intent-copy hash at signoff time. - ⏸ FUTURE — re-signoff prompt when the intent copy edits.
- 🟢 LIVE — R18 v1/v1.5 engineering hardening (PR #142, this PR's predecessor).
Cost of being wrong High. Shipping R18 to prod without the signoff means Lawma's e-signature is a court-grade artifact backed only by engineering intuition — no licensed-attorney attestation. The first time the signature is challenged, Lawma has no legal opinion to fall back on. The cost of the signoff itself is days of counsel time + ~$5-15k legal fee. Materially less than the cost of one challenged signature.
D26 — OCR PDF-render adapter = MuPDF (wasm), local; gated behind a flag
Locked: 2026-06-23. Status: 🟢 LIVE (flag-gated). Owner: Riyaz (picked MuPDF via the OCR-engine decision). Builds on: R44/R47 OCR design (the three-tier unpdf → Tesseract → Textract fallback), R48 #5. Shark: docs/shark/2026-06-23-ocr-adapter.md (one pass — new direction overriding the standing "wait for telemetry" defer).
Decision The OCR fallback's missing piece — rasterizing a PDF page to an image so Tesseract can read it (renderPdfPageToImageBytes in lib/document-analysis/parse.ts) — is implemented with MuPDF's pure-WebAssembly renderer. It is lazy-imported and gated behind the ENABLE_PDF_OCR env var, off by default, so production behavior is unchanged until the serverless render+OCR cost/timeout profile is validated; flipping the flag activates the whole Tesseract tier.
Why MuPDF over the alternatives
- vs @napi-rs/canvas + pdfjs: that reuses our existing pdfjs but ships a native prebuilt binary — larger function bundle + real arch/build risk on Netlify's serverless runtime. MuPDF is pure wasm: no binary, no arch risk.
- vs AWS Textract (cloud): best accuracy, but it would send client legal documents to a third-party cloud — a confidentiality regression for a legal product — plus an AWS dependency and per-page cost. MuPDF keeps every byte on our own infra.
- License: MuPDF is AGPL, consistent with the docx-templater community version already accepted at R44. No new license posture.
Cost of being wrong Low. Flag-gated + lazy-imported + reversible (drop the mupdf dep, revert one file). Nothing irreversible, no prod data write, no client-data egress. If the flipped-on serverless cost proves too high, leave the flag off or revisit the dismissed Textract path in a superseding entry.
Verification (at lock) MuPDF rendered public/forms/fl-100.pdf p1 → 1700×2200 PNG (letter @ 200 DPI); Tesseract OCR'd it to 2954 chars of accurate form text. tsc clean; parse tests 6/6; npm run build green (wasm dep dynamically imported + server-only, never in a client bundle).
D27 — Client-intake paradigm = P4 (route by visitor state), shipped phased
Locked: 2026-06-24. Status: 🟡 LOCKED — build pending. Owner: Riyaz ("do the parked items" → I picked the recommended paradigm + planned it; the decision is reversible at the plan stage, nothing shipped). Shark: docs/shark/2026-06-24-t189-intake-paradigm.md (one pass, Tier 2). Options doc: docs/plans/2026-06-22-client-intake-paradigm-alternatives.md. Plan: docs/plans/2026-06-24-t189-p4-implementation.md.
Decision The client-intake paradigm moves from P0 (one find-attorney funnel for every visitor) to P4: route by visitor STATE, not legal category. A visitor arriving with "I want to file FL-100 in LA County tomorrow" is doing different work than one arriving with "I might need a divorce" — P4 routes them differently. This preserves the AI-native triage + the marketplace for ready buyers, and is the strongest investor narrative (first-contact resource, not a referrer).
Shipped PHASED (the shark's refinement — don't build branches whose preconditions don't exist):
- Phase 1 (the T189 build): the routing fork + the ready-buyer branch (→ existing P0 find-attorney flow). The "not sure" and "one question" routes land on a single honest interstitial ("a Lawma attorney will follow up"), NOT a fake consult queue or a half-baked RAG. Zero dependency on unbuilt lawyer supply or an unbuilt corpus.
- Phase 2 (gated on real Network Lawyers): the "not sure" interstitial becomes the real P3-style free-consult queue.
- Phase 3 (gated on a real RAG corpus / R36 productionized): the "one question" interstitial becomes the RAG path.
Dismissed alternatives
- P1 (chat-first AI match): puts the AI risk in the wrong place — the lawyer match is high-stakes + hard to reverse; the visitor should keep agency to compare. Keep AI in triage/coaching/drafting where it's already strong.
- P2 (form-first / LegalZoom shape): kills the entire AI-native differentiation thesis ("we're a better form" = same product as 2008).
- P3 (attorney-pull queue) as the WHOLE paradigm: inverts client agency too far for the high-budget client. Survives only as P4's Phase-2 sub-branch for the "not sure" route.
Cost of being wrong Low-to-medium, reversible here — this locks a plan, not code. If Riyaz prefers a different paradigm or phasing, it's a doc edit. The real operational risk is in the eventual build (a mis-routing triage prompt erodes lawyer trust) — mitigated in Phase 1 by routing non-ready visitors to a safe interstitial, never to lawyers, until branch-detection accuracy is measured.
D28 — Auth provider = Auth0
Locked: 2026-06-24. Status: 🟡 LOCKED — provisioning + build pending. Owner: Riyaz (provisions the tenant + secrets; I build the integration). Confirms: Riyaz's ask ("I want Auth0 if we can do it free"), the 2026-06-22 eval (docs/plans/2026-06-22-auth-provider-evaluation.md, recommended Auth0), and the 2026-06-18 cutover shark passes (docs/shark/2026-06-18-auth0-cutover- pass-1.md + -pass-2.md). Runbook: docs/runbooks/auth0-setup.md.
Decision Replace the stub auth (lib/auth/stub.ts, AUTH_MODE=stub) with Auth0 (AUTH_MODE=auth0 → lib/auth/auth0.ts). Auth0 provides MFA-required + RBAC; the DB (app_user) stays the source of truth for role / firm / attorney_kind — Auth0 is identity + MFA only. The seam is already built: every call site reads currentUser(); flipping AUTH_MODE changes nothing downstream.
Decision-hygiene note: lib/auth/auth0.ts + the eval doc say "D27: Auth0." No D27 existed when those were written (highest was D25); that reference is to THIS decision, now formally D28. The real D27 is the intake paradigm. The stale "D27" string in auth0.ts is corrected to D28 in the same PR as this entry.
Why Auth0 over the alternatives (from the eval)
- Clerk: better DX but half the free MAU (10K vs 25K) + less enterprise gravitas for the malpractice-insurer conversation.
- Supabase Auth: highest free MAU but its bundle benefit (JWT-claim RLS) needs Supabase Postgres — Lawma is on Neon.
- Auth.js: free forever but DIY MFA + session/recovery — auth bugs in a legal-data product are existential; not worth the per-MAU savings.
Hard external dependency Auth0 is a SaaS — going live needs a tenant + 5 env vars (AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_CLIENT_SECRET, AUTH0_SECRET, APP_BASE_URL) that ONLY Riyaz can provision. Until then the integration code can't be tested (no session to read) and must not be wired blind into the live app (auth bugs = data exposure). So: decision + runbook now; build + test once the tenant exists.
Cost of being wrong Medium, bounded at the seam — switching providers later is a new lib/auth/<provider>.ts file, not every call site (the expensive part is the USER migration: password resets + MFA re-enrollment). Reversible before real users register against the tenant.
D29 — E-signature available now; D25 lawyer-signoff gate waived
Locked: 2026-06-24. Status: 🟢 LIVE (Riyaz override; reversible). Owner: Riyaz (explicit call: "make sure e-sign is fully available right now — we'll turn it off if we need to"). Supersedes the GATE in: D25 (D25's per-flow legal analysis stays valid; only its "don't deploy until signoff" gate is waived).
Decision The native e-signature feature (R18 — typed-name v1, drawn v1.5, the sign / evidence / batch-sign / counterparty-sign-invite flows) is made fully available now. D25 had gated R18's production exposure on a CA UETA-qualified attorney's per-flow signoff; Riyaz waives that gate, accepting the risk, with the explicit option to turn it back off.
Findings (confirmed at lock) There is NO code gate suppressing e-sign — no env flag, no "coming soon", no feature-toggle. The full flow is live in app/app/documents/[docId]/sign, /evidence, /batch-sign, /sign-invite, with the document_signature / signature_event ESIGN/UETA evidence schema. D25 was a policy gate (organizational "don't ship to prod yet"), not a code switch. So "make it available" required no build — it records the policy waiver.
Risk + reversibility The risk D25 named is real: e-sign is a court-grade artifact backed (until a lawyer signs off) by engineering intuition, not licensed-attorney attestation. Riyaz accepts this pre-launch. REVERSIBLE: if needed, re-gate by hiding the sign routes / adding a feature flag, or revert to D25's posture. Lawyer review (D25's per-flow questions) remains recommended before real client scale.
D30 — MFA/2FA turned OFF pre-launch; re-enabled at launch
Locked: 2026-06-24. Status: 🟠 TEMPORARY (pre-launch only; reverts at launch). Owner: Riyaz ("turn off 2FA until we are launched"). Relaxes (does NOT supersede): D28's mandatory-MFA requirement — that requirement stands for launch; D30 only defers it during the pre-launch window. Shark: docs/shark/2026-06-24-mfa-off-prelaunch.md.
Decision Multi-factor auth (D28 — "2FA for every account") is turned off until launch to remove enrollment friction during demos + dev. Two coordinated switches: the Auth0 tenant MFA policy (dashboard → "Never") and the code check (AUTH_REQUIRE_MFA=false).
Why this is acceptable now We are pre-launch: auth isn't even live (the app runs on the stub by default), there are no real users, and no real client data exists. MFA protects accounts holding privileged data; with no such accounts yet, the protection is moot and the enrollment friction is pure cost.
The one real risk + how it's mitigated The risk is silent: MFA-off reaches production and nobody re-enables it before real users arrive → a phished/credential-stuffed password is the only barrier to privileged legal data (malpractice/bar-complaint territory; breaks the "banking-grade security" promise). Mitigations:
- Secure by default.
AUTH_REQUIRE_MFAdefaults to ON; only an explicit=falsedisables it. A forgotten/unset flag fails safe (MFA on). - Loud.
resolveAuth0User()logs a warning at process start when MFA is off. - Hard launch gate. Re-enable is Section 4 of
docs/runbooks/launch-day-checklist.md— the single most important security item there, with both switches + a verification step.
Reversibility Fully reversible: unset AUTH_REQUIRE_MFA (local: delete the line; prod: netlify env:unset) + re-enable the Auth0 tenant policy. No data migration.
Dismissed alternatives
- Delete the code MFA check entirely — loses secure-by-default + the audit trail; re-adding it later is error-prone. Rejected for a reversible flag.
- Leave the code check, only disable the tenant policy — fragile: relies on Auth0 happening not to emit an
amrclaim; anamr: ["pwd"]session would then be rejected and break all logins. The explicit flag makes the behavior intentional, not accidental. - Per-user MFA opt-out — more surface, more state, same launch-re-enable problem. Overkill for a pre-launch convenience.
D31 — User registration + role provisioning: three doors + shared invite/approval
Locked: 2026-06-24. Status: 🟢 LOCKED — build queued (R49). Owner: Riyaz. Sits on: D28 (Auth0). Implements: the R4 client-journey signup.
Context Riyaz deliberately registered a brand-new email in Auth0 to test the new-user path. Finding: resolveAuth0User → resolveStubUser throws for any unknown email (lib/auth/stub.ts:257) — a new Auth0 registrant gets no app_user, no role, no access. It fails CLOSED (safe) but there is no provisioning path, so a legitimate new client currently can't get an account. This is the R4 signup gap.
Decision — three doors, one shared invite/approval system
- Client door — registering from client pages/links creates a LIVE client (self-represented litigant) instantly, scoped to its own data; the relationship-before-coaching invariant still gates deep coaching.
- Attorney/firm door — registering from attorney pages creates a PENDING attorney: sign-in works, but client-data surfaces are gated until license/bar verification + a Lawma-admin or firm-admin approval flips it live.
- Lawma staff/admin door — never self-serve. An existing Lawma admin creates the user (name + role) in the Lawma Workspace UI; the system emails an account-setup link; completing it lands the assigned role.
Security invariant Privileged access (attorney live-access, firm-admin, Lawma staff/admin) is NEVER granted by self-registration alone — always invite- or vetting-gated. The role a self-signup can reach without a human in the loop is CLIENT only.
Key technical design The registration INTENT (which door) must survive the Auth0 redirect round-trip. Carry it through Auth0 appState (or a signed returnTo/intent param), then provision the matching app_user row on the callback — keeping the resolver itself fail-closed (no row → no access) for any path that didn't go through a door. Reuse the existing stub-mode role-by-flow signup logic (find-attorney, account-actions); the gap is wiring it to the Auth0 callback.
Dismissed alternatives
- Global default = client for ANY authenticated email — silently over-provisions; anyone who makes an Auth0 account becomes a client without going through intake. Rejected: provisioning must be tied to a door.
- Invite-only for everyone (including clients) — kills the self-service mission (free tier for SRLs is the whole point). Rejected.
- Instant attorney from the attorney page — lets a self-declared "lawyer" reach client data + emit legal output. Existential hole in a legal platform. Rejected in favor of the vetting gate (Riyaz confirmed "vetting gate first").
D32 — Interview identity model: multi-token answers + author-declared client party
Locked: 2026-06-25. Status: 🟢 LOCKED — pure core built; runtime/Builder wiring queued (R50). Owner: Riyaz. Sits on: the interview engine + the token registry (lib/legal/tokens.ts). Refines: R50 (client name). Shark: docs/shark/2026-06-25-multi-token-client-identity.md.
Context R50 (A1 shipped) needs the interview to address the client by name without hard-coding the client as the petitioner. Two of Riyaz's asks shaped the model: "attach multiple tokens to a question so one reply is reusable" and "track the party names per vocabulary (petitioner/respondent OR plaintiff/defendant) but have a token that, based on interview type, says which party is OUR client."
Decision — two clean mechanisms, not one
- Multi-token (static): a question stores its answer ONCE under its primary
key;alsoPopulates: string[]declares extra token names the runtime value scope ALSO exposes the same value under (read-time aliases). One reply, reusable. The primary key stays the single storage identity — carry-plan, form-mapping, and show-if keep addressing it unchanged. General Builder feature (any question, any tokens). - Author-declared client party (dynamic, but authored): the AUTHOR declares which party is the client on the definition (
InterviewDefinition.party_role, across the fullPartyRolevocabulary), in the Builder — NOT a runtime question.client_display_nameis then DERIVED = the name slot for that party (resolveClientDisplayName). The per-vocabulary party name slots stay intact.
Why Conflating the two (a name question whose stored key flips by role) would break the bedrock invariant that a question key is a stable identity. Author-declaring the client party also satisfies R50's "never assume petitioner" WITHOUT a runtime ask: the code never hard-codes a party; the author declares the perspective, and distinct interviews can exist per perspective.
How to apply
- Multi-token:
lib/interview/token-aliases.ts(expandScopeWithAliasesat runtime scope-build;validateTokenAliasesat publish). Aliases must be valid token names and must not collide with another question's key. - Client identity:
lib/interview/client-identity.ts(partyRoleNameToken,resolveClientDisplayName). The client party comes fromparty_role. - Authors reuse
client_display_namefrom the token registry; either attach it to the client's-name question viaalsoPopulates, or let it derive.
Cascade required
- ⚪ Runtime: inject
client_display_name+ expand aliases into the session value scope used by content +docx_render/court-form resolution (DB-backed). - ⚪ Builder: UI to set
party_role(which party is the client) + add/removealsoPopulatestokens per question; runvalidateTokenAliasesat publish. - ⚪ Definitions: where a name question is the client's, add
client_display_nameto itsalsoPopulates(or rely on the derivation).
Supersedes (in part) A2's runtime client_party_role QUESTION (PR #381, closed) — the party is author-declared, not asked of the client. The client_display_name token + the role→name derivation survive (generalized to all vocabularies).
Dismissed alternatives
- Conditional token assignment (a question's stored key flips by role) — breaks the stable-key invariant carry/mapping/show-if depend on. Rejected.
- Duplicate the answer under each token (storage copies) — drift + a migration. Rejected for the read-time alias layer.
- Per-family client-party tokens (
family_party_role,civil_party_role) — N tokens, N resolution paths, no carry across families. Rejected for oneparty_rolewith interview-type-aware values. - Ask the client their party at runtime (the A2 approach) — unnecessary once the author declares the perspective; adds a question and a "never assume" trap. Rejected per Riyaz 2026-06-25.
D33 — Breadth-first capability phase
Status: 🟢 LIVE — Decided: 2026-06-26 (Riyaz)
Verbatim: "i don't want to build spines anymore. Now it's time to start building everything breadth first." + "Analysis should also be a negotiation guide." + "multilingual not in scope right now."
Decision. The project moves out of foundation/spine-building and into a breadth phase: build out the catalog of legal-service "products" on top of the unified R48 interview-builder framework (input primitives: questions + document_upload; output primitives: court_form fill, findings_report, docx_render). New capabilities are predominantly new interview DEFINITIONS + light engine extensions + attorney-authored content — not new architecture. Spine/foundation items (auth cutover, conflict-check service, R4 chain verification) are parked-stable — tracked, not gating this phase.
In scope this phase (priority order, value-per-build-cost):
- Contract analysis → negotiation guide (R52) — engine extension; IN.
- Demand / dispute letters (
docx_render) — cheapest new product. - Sued-respondent / eviction Answer (R48 Phase 3) — differentiator.
- Small claims (file + respond) (
court_form). - Restraining orders (DV / civil harassment) (
court_form). - Name change / fee waivers (
court_form).
Explicitly OUT this phase:
- Multilingual / Spanish (R53) — parked; mission-aligned but a Tier-3 architecture call for a later phase.
The real constraint (named, not a blocker). On the R48 framework the binding constraint is attorney-authored + attorney-reviewed content, not engineering. Build splits cleanly: code/scaffolding/definitions ship; legal text is flagged for human-attorney review (same pattern as R36/R46) and that flag does NOT stop the chain.
A guardrail that rides along (not a spine item). Breadth multiplies the coverage-gap failure — a half-authored interview for an unsupported jurisdiction gives WRONG output, which is worse than an honest "we don't serve this yet." Each new product must fail safe on out-of-coverage inputs. Folded into each product's definition of done, not built as separate infrastructure.
Dismissed alternatives:
- Spine-first (finish conflict-check + UPL-safety + R4 verification before more breadth) — my recommendation; Riyaz overrode it deliberately. Cost of being wrong: a silent legal-safety gap (conflict-check stub, unverified relationship-before-coaching invariant) reaches real users. Mitigation: those items stay tracked and get done before real-client launch, just not as the gate for this build phase.
- Multilingual now — deferred by Riyaz; real architecture decision, not a quick add.
Cross-references: R52, R53, R48 (framework), R38/R47 (analysis engine).
D34 — Database stays Neon Postgres (not Supabase)
Status: 🟢 LIVE — Decided: 2026-06-27 (Riyaz asked: Neon vs Supabase; free/cheap pre-launch?)
Decision. Keep the database on Neon Postgres, accessed through Drizzle. Do NOT migrate to Supabase.
Why.
- We already run Neon + Drizzle with the full schema + migrations. Switching is a data-layer rewrite for zero functional gain pre-launch.
- Supabase's value-add is bundled auth + storage + realtime. We've already committed to Auth0 for login (D28) and our own blob storage; adopting Supabase auth would CONFLICT with Auth0 and adopting its storage duplicates what we have. Net: cost + a second auth story, no benefit.
- Free pre-launch: Neon's free tier (storage + branching) comfortably covers us until real usage; we're already on the almost-free path.
- No lock-in: it's plain Postgres, so the same Drizzle schema can move to Aurora / RDS / Supabase later if a real reason appears.
Dismissed: Supabase now (rewrite + auth conflict); a brand-new DB (we have one). Operational note: the migration journal is drifted from the live schema (T124) — new tables ship as hand-authored idempotent SQL under drizzle/manual/ and are applied directly, not via drizzle-kit migrate, until the journal is reconciled.
D35 — Attorney Forum is an ad-eligible surface
Status: 🟢 LIVE Decided: 2026-06-28 (Riyaz)
Decision. The advertiser-portal guardrail "no ads on authenticated surfaces" is SCRAPPED. Sponsored placements run across the product, INCLUDING authenticated surfaces; the verified-Attorney Forum is ad-eligible.
Why scrapped (Riyaz, 2026-06-28). The rule already contradicted the product: we place contextual partner offers ON authenticated surfaces today — e.g. a process-server or notary offer the moment an interview completes (the Around-the-Case referrals, D43). A rule the product doesn't follow is worse than no rule.
The principle that survives. The line is the DATA, not the surface. Advertisers NEVER receive client identity, intake content, or document data; targeting is category + jurisdiction + format + time-of-day only; placements are contextual, never built from a client's private signals. That privacy boundary is the real guardrail and stays absolute. Where the ad renders (public page, dashboard, attorney forum, post-interview hand-off) is a product/UX call, not a privacy rule.
What changed. advertiser-portal guardrail reworded from "no ads on authed surfaces" → "advertisers never receive client data"; placement-inventory copy now reads "across the product, contextual"; the attorney-forum sidebar carries direct-sold legal-vendor ads (Casetext, Aegis).
Dismissed. Keeping the surface-based rule (even refined to "client-data surfaces only") — it still mis-frames the boundary as location when the real boundary is data, and it would have blocked legitimate contextual placements the product already ships.
Cascade. app/advertiser-portal/page.tsx guardrail + inventory copy (done); app/forum/lawyers sidebar ads (done). The no-client-PII-to-advertisers rule is unchanged and remains the hard line.
D36 — AUTH_MODE fails closed in production
Status: 🟢 LIVE Decided: 2026-07-01 (Riyaz — reactive-input security flag)
Decision. AUTH_MODE now resolves through a single resolveAuthMode() seam (lib/auth/auth-mode.ts). When the var is UNSET: default to auth0 (real auth) in production (NODE_ENV === "production"), and to stub everywhere else (local dev). An explicitly-set value always wins and is passed through verbatim. Every security-load-bearing reader — above all currentUser() — routes through the seam, so there is ONE source of truth for "which auth mode are we in."
Why. The old default was process.env.AUTH_MODE ?? "stub", duplicated in ~12 places. If a PRODUCTION deploy ever shipped with AUTH_MODE unset, the whole app silently fell back to STUB: currentUser() returns a seeded synthetic user with no real auth AND the act-as-anyone dev switcher turns on — a catastrophic auth bypass on a single missing env var. Failing closed (real auth in prod) converts a silent, data-exposing bypass into a loud, data-safe misconfiguration (a 500 / signed-out state). Fail-closed beats fail-open for an auth default.
How to apply.
- Read the mode via
resolveAuthMode(env)/isAuth0Mode(env)/isStubMode(env)from@/lib/auth/auth-mode. NEVER writeprocess.env.AUTH_MODE ?? "stub"again — the idiom was deleted from the codebase so it can't be copied. - Every real deploy sets AUTH_MODE explicitly, so this is a behavioral no-op for them: lawma611 pins
AUTH_MODE=stubin production, deploy-preview, branch- deploy, and dev (verified before merge). The default only bites an unconfigured prod. - Empty-string AUTH_MODE is treated as unset (Netlify footgun) and fails closed.
- An unsupported value passes through so
currentUser()'s "unsupported mode" throw still fires loudly instead of being masked.
Dismissed.
- Patch only the two originally-named files (
isAuth0Mode,assertDevSwitchAllowed). Rejected — the core readercurrentUser()(stub.ts) is neither of them, so the mutation surface would stay bypassed while the login page merely looked locked. A false sense of security is worse than none. All readers must route through the seam. - Keep
stubas the prod default (status quo). Rejected — that IS the vulnerability. - Throw immediately on prod+unset. Equivalent security to auth0-default but needs new throw sites; auth0-default reuses the existing, well-tested throw-closed path in
auth0.ts. - Invent a
locked/deny-all mode. YAGNI — auth0-default already meets the security property (no bypass); add later only if prod-unset becomes common. - Also fix the
AUTH_MODE !== "real"gates (account-actions,reset-actions,email-verification-actions). Deliberately OUT of scope — a different comparison against a value ("real") that is never set, so those dev-convenience gates are effectively always-on. That is its own latent finding for a separate, considered change, not smuggled into this one.
Cascade. lib/auth/auth-mode.ts (resolver + isStubMode); readers routed through it: lib/auth/stub.ts (×3, incl. currentUser), lib/auth/dev-switch.ts, middleware.ts, lib/auth/ephemeral-intake.ts, lib/payments/demo-sim.ts, app/app/interview/page.tsx, app/app/find-attorney/{actions,page}.tsx, app/app/builder/layout.tsx; unit tests in scripts/test-rbac.ts; shark analysis docs/shark/2026-07-01-auth-mode-fail-closed.md. Follow-up (not done): audit the AUTH_MODE !== "real" dev-convenience gates.
D37 — Sub-interviews: reusable blocks inlined at publish time
Status: 🟡 LOCKED — building Phase 1 Decided: 2026-07-01 (Riyaz — "a concept of sub-interviews … invoked in multiple parent interviews … property") Design of record: docs/plans/2026-07-01-sub-interviews.md Shark passes: docs/shark/2026-07-01-sub-interviews-pass-1.md, -pass-2.md
Decision. A sub-interview block is an ordinary interview_definition row (id convention block.<area>.<name>) that is included by parent interviews rather than run as a case entry point. A parent declares include_blocks?: BlockInclusion[] (authoring-only). At publish time — at both seams, the app's approveAndPublish and the repo's scripts/publish-interview-definition.ts — a single pure function expandBlocks(def, resolveBlock) inlines each referenced block's sections[] into the parent (with an optional showIf gate AND-ed onto each section for conditional inclusion), merges the block's forms/rules/computed, records _expanded_blocks provenance, strips include_blocks, and stores a flat, self-contained published body. The runtime, form-fill, carry-plan, visibility, and load paths are unchanged — they never see a block.
Why (in priority order).
- D24 WYSIWYG attorney review. Block content is legal content. Baking puts the actual inlined questions in the attorney's review diff, not an opaque
block_id. And a block edit must republish each dependent parent, which re-runs the attorney-review gate — the D24 control. Load-time auto- propagation would push a block edit to clients with no review. - Zero runtime risk. The runtime never learns what a block is. No hot-path block fetch, no "referenced block missing → parent won't load" failure mode.
- Self-contained audit. A baked body diffs/greps/reasons with no cross-row lookups.
- (Immutability + version pinning is also satisfied — but per shark pass 1 it is NOT the differentiator: a pinned load-time approach is immutable too. We do not lean on it.)
How to apply.
- Author a block as a normal definition with
block.id; give it stably-named, block-scoped keys (prop_) and section ids (prop-). Never add ablock.id toENTRY_INTERVIEWSor anyon_complete.next_interview_id— you include* a block, you don't route/chain to it. - A parent includes it via
include_blocks: [{ block_id, at?, showIf? }].showIfgives conditional inclusion through the existing runtime section- visibility path (publish-time cannot see answers). - Publish the block first, then the parent (the parent's bake resolves the block's latest published version).
- Blocks are jurisdiction-scoped (shark pass 2): there is no universal "property block";
block.ca.family.propertyis CA community-property-specific; a TX one would differ. - Central management: edit block → new block version → re-publish dependents (found via the
_expanded_blocksdependents query). Auto-republish is NOT built (it would bypass D24).
Dismissed.
- Load-time expansion (store the reference, inline every load like
resolveDefinitionRules). Rejected — even pinned (which preserves immutability), it hides legal content from the attorney diff, adds a hot-path fetch + a load failure mode, and (unpinned) silently mutates approved parents, violating D24. Its one edge (auto-propagation) is a liability under D24. - Runtime-native block resolution (engine understands blocks while walking). Rejected — strictly more invasive (touches every downstream consumer) for no gain; it is exactly the "new primitive everyone must learn" pattern this rebuild exists to avoid.
- Copy-paste the questions into each parent. Rejected — fails "central management"; duplicates legal content → drift → the "two contradictory truths" pain (CLAUDE.md decisions-cascade rule) at the worst layer.
- Auto-republish dependents on block edit. Rejected — bypasses the D24 human- review gate. We surface a flag + dependents list; humans re-review.
Cascade (Phase 1). lib/interview/types.ts (include_blocks + BlockInclusion); lib/interview/blocks/expand.ts (expandBlocks + tests); app/app/builder/actions.ts (approveAndPublish calls it); scripts/publish-interview-definition.ts (calls it); lib/interview/definitions/blocks/property.block.json (first block); lib/interview/definitions/demo-divorce.draft.json (references it); scripts/test-engine-forms.ts (must expand parents-with-blocks before the gate-key check — shark pass 2, or the parent-showIf boundary is a silent trap); dependents query. Phase 2b (not this pass): Builder UI to author + drag-include blocks; AI-proposes-inclusion; more blocks (children, business, financial disclosure).
D38 — Nested-interview authoring model (linked/detach + two-token wiring)
Status: 🟡 LOCKED — building (slice 1) Decided: 2026-07-01 (Riyaz — "We are agreed on the nested-interview framework"; two-token wiring: "answer keys and forms wiring as two separate tokens; one defaults the other, but the author can override") Builds on: D37 (publish-time bake). Design of record: docs/plans/2026-07-01-nested-interviews-authoring.md. Shark: docs/shark/2026-07-01-nested-interviews-authoring.md.
Decision. The authoring system on top of D37's engine:
- Reuse = linked by default, detach-on-edit. A placement is linked (baked from the master at publish). Editing its content (question wording, help, type, answer logic, the answer key) copies-on-write into an independent fork, with a confirm. Editing its wiring does not detach.
- Two-token wiring. A question's answer key is its stable identity (storage, carry-forward, conditional logic); its form token is where the value lands on a form. The form token defaults from the answer key and is per-placement overridable without breaking the link.
- Visibility = inline + library. Nested interviews are badged inside the parent editor AND managed in a central library.
Why (per shark). The decisive shape is engine-honest minimalism: there is no new form_token field. The answer key is the existing question key (stable); the form token is the existing mapping[] (AcroForm wiring) or, for composer forms, the answer key the composer reads; the override is a per-placement mapping replacement carried on the include reference; composer re-targeting uses the parent's own forms[]. This satisfies "two tokens, form defaults from key, author overrides" with additive data and no runtime change, rather than a grand new type that fights the engine. Detaching-on-content-edit (not on wiring-edit) is exactly what lets an author re-point paperwork across interviews (incl. many cross-jurisdiction cases) while the questions stay synced.
How to apply.
- Linked reuse =
include_blocks(D37). Wiring override = per-placementmapping_overrides/alias_overrideson the inclusion (slice 1). - Fork = literal sections copied into the parent (no reference), tagged with a
_forked_fromprovenance marker so the library can count linked vs copied. - A block edit → republish dependents (the D24 gate); no auto-propagation.
- Overridden mappings are validated at bake (fail-closed, like D37).
- Cross-jurisdiction link warns (a linked block shares its question WORDING verbatim; the form-token override only fixes the paperwork axis). Fork when the wording itself must differ.
Dismissed.
- A unified
form_tokentype on every question. YAGNI + fights the engine — thekey/mapping[]/forms[]split already models it. (Shark pass 1.) - Choose link-vs-copy explicitly at every insert. Rejected in favor of linked-default + detach-on-edit (fewer decisions; no silent surprises). Still available as an explicit "insert a copy" action.
- Always-independent copies (no linking). Loses the central-management payoff.
- Runtime-native nesting. Rejected — D37's flat bake keeps the runtime dumb.
- Auto-propagate block edits to published parents. Bypasses D24 review.
Cascade (slice 1). lib/interview/types.ts (BlockInclusion.mapping_overrides / alias_overrides; _forked_from marker); lib/interview/blocks/expand.ts (apply overrides at bake + validate); lib/interview/blocks/expand.test.ts (override + validation tests). Later slices (UI): central library (2), inline grouping (3), extract (4), insert + detach-on-edit + override UI (5).
D41 — Adopt phased enterprise-grade transition plan (security + scale + certification)
Status: 🟢 LIVE — Phase 0 approved by Riyaz 2026-07-03; Phases 1–4 stage-gated on their exit criteria Decided: 2026-07-03 (adoption) · Phase 0 approved: 2026-07-03 Supersedes: — Cascades into: R118, T234–T243, and the plan doc docs/plans/2026-07-03-enterprise-grade-transition-plan.md.
The decision. Adopt a four-phase, 24–36-month transition plan as the canonical roadmap to real-user readiness. Three tracks run in parallel across the phases:
- Security-risk resolution — CI-enforced automation for the three risks named 2026-07-03 (supply-chain via Dependabot + Snyk/Socket; own-code discipline via ESLint bans + auth-wrapper conventions + route-matrix tests; client-side secrets via env-var naming + client-bundle scan). Companion policy work (threat models, incident response, data classification).
- Scale infrastructure — migrate off Netlify to Vercel Enterprise or AWS ECS/Fargate; add Aurora Postgres or Neon Enterprise with read replicas + PgBouncer; Redis for hot state and rate limits; SQS + Lambda worker pool for PDF/signatures/batch AI; Anthropic Enterprise Agreement with committed capacity; Cloudflare/CloudFront + WAF; Datadog for tracing. Multi-region active-passive by Phase 3.
- Certifications — SOC 2 Type I (~9mo) → Type II (~21mo total). CCPA + GDPR + PCI DSS SAQ A as foundational. ISO 27001 conditional on international interest. HIPAA-adjacent conditional on health-record-touching case types. FedRAMP ONLY on a real federal contract.
Phase gates (each has an exit criterion that must be met before the next begins):
- Phase 0 (0–3mo): CI security gates green; threat models drafted; off-provider nightly backups tested. Real users can begin using the product.
- Phase 1 (3–9mo): Auth0 + MFA + Postgres RLS live in production; SOC 2 auditor engaged; policies signed; pen test complete + remediated.
- Phase 2 (9–15mo): SOC 2 Type I report published; scale infra migration complete; Type II observation window begun.
- Phase 3 (15–24mo): SOC 2 Type II report published; multi-region tested failover; published SLA (99.9% enterprise tier).
- Phase 4 (24–36mo): ISO 27001, HIPAA-adjacent, or FedRAMP as business signals dictate.
The gating principle: never let engineered scale outrun engineered trust. We do not ship at scale to real clients until the certifications + controls make a GC diligence review pass on pre-existing artifacts.
Escalation triggers (defined in the plan Part 5) — enterprise buyer intent, major firm pilot, security incident (ours or a competitor's), fundraising milestone, federal contract, EU interest — each triggers acceleration or scope changes to this plan; the phase shape stays but the calendar tightens.
Dismissed alternatives considered:
- Skip SOC 2 until a buyer forces it. Rejected: SOC 2 Type II takes 12–24 months. If we wait for a specific buyer to demand it, we lose that deal. Certification is table-stakes for enterprise legal — the cost of being early is small, the cost of being late is a lost sale that doesn't come back.
- Go directly to Type II, skip Type I. Rejected: Type II requires a 6–12 month observation window on the controls Type I documents. Skipping Type I doesn't compress the calendar — it just delays the first credible attestation.
- Pursue FedRAMP now. Rejected: $500K+, 18–36 months, no federal contract on the table today. Trigger reassessment only when a real federal opportunity (LSC, DOJ, state courts) materializes and is funded.
- Build our own IdP instead of Auth0. Rejected — already dismissed in D28. DIY MFA in legal software is existential risk. Reaffirmed.
- Self-host / on-prem offering to close enterprise deals. Rejected. Some enterprise buyers ask for it, but the accepted-industry answer is "our SOC 2 + DPA + BAA + published subprocessor list covers what you need." On-prem would drown our velocity and force a second-product engineering track. Revisit only if a whale customer's need is truly on-prem-only.
- Skip the pen test. Rejected. Pen tests + bug bounties produce signal that CI automation cannot — creative attackers finding novel chains. Enterprise InfoSec reviewers expect them; SOC 2 auditors will look for them.
- Do all this piecemeal without a written plan. Rejected. Certifications and scale infrastructure have real ordering dependencies (Type II needs Type I's observation window; Aurora migration blocks on scale-tier decisions; Auth0 blocks on RLS design). A phased plan is what keeps the ordering right and gives the fundraise a concrete story.
- Wait until Series A to start anything. Rejected. Phase 0 costs are trivial (~$5K/mo tooling). The paperwork foundation (threat models, policies, subprocessor list) that Series-A-diligence expects is exactly what Phase 0 produces. Not starting is the more expensive option.
Open sub-decisions parked for their own council session at trigger time:
- ~~Phase 2: Vercel Enterprise vs AWS ECS/Fargate for the web tier~~ — RESOLVED 2026-07-03 by D44 (default AWS; Vercel only if it clears the meaningful-AI-advantage bar).
- ~~Phase 2: Neon Enterprise vs AWS Aurora Postgres for the DB~~ — RESOLVED 2026-07-03 by D44 (default AWS Aurora; Neon only if uniquely AI-compelling).
- Phase 2: which SOC 2 tooling — Vanta vs Drata vs Secureframe.
- Phase 4: HIPAA-adjacent yes/no (depends on case-type expansion).
- Phase 4: FedRAMP go/no-go (depends on federal contract).
- Anytime: GCP or Azure vs AWS as the primary hyperscaler — D44 leaves this open; AWS is default today.
Assumptions Riyaz should red-line if wrong:
- Target scale = 1–10M registered / ~500K concurrent peak. Faster growth compresses timeline; slower stretches it.
- Budget scales with fundraising — Phase 0 is unfunded-friendly; Phase 2 assumes a Series A close; Phase 3+ assumes ARR growth.
- Priority order: security foundation first, certification second, scale infra third. A different weighting (e.g. scale first) would re-order the phases.
- The three tracks run in parallel across phases, not serially — that's what makes 24–36 months feasible rather than 60.
Why this needs to be a D-entry rather than just a plan doc. A plan is a proposal; a D-entry is a commitment with cascades. When we make future decisions (whether to accept an on-prem-demanding buyer, whether to skip Type II, whether to bump SOC 2 spend), D41 is the frame those decisions get judged against. Without it, the plan drifts and each new pressure re-litigates the same trade-offs.
D42 — Long-interview runtime design principles (page-at-a-time server-truth + layered save)
Status: 🟡 LOCKED — building (green-lit by Riyaz 2026-07-03; execution starts immediately) Decided: 2026-07-03 Supersedes: — Cascades into: R119, T244–T250.
The decision. The interview runtime is refactored around 8 principles designed for interviews of 200–300 questions. These principles are the design contract every future interview-runtime change gets judged against.
- Server is the source of truth. Client never holds the whole interview. The client only ever renders one page at a time. The server sends the current page's questions + prior answers for that page + evaluated show-if state. On Next/Back, the server decides which page comes next.
- Save on page-transition, not per-field-blur. (Riyaz's amendment 2026-07-03.) One transactional batch write per page transition. The client holds page-local answers in React state as the user iterates on that page — no network on blur. On Next/Back, the whole page's answers commit in one server round-trip.
- Every save idempotent on
(session_id, question_key, repeat_index). The schema already has this unique index. Batch save is a loop over the existingsaveAnswerRowprimitive inside a single transaction. Retries are safe. - IndexedDB per-blur local buffer + restore-on-load. Every field blur writes to browser-local IndexedDB (zero network cost). If the tab crashes mid-page, on next load we detect un-synced page-local state and offer to restore. This is the belt-and-suspenders layer under Principle 2 — no in-progress work is lost even to hard tab kills.
- Tab-close protection is layered. In-app navigation uses the existing custom modal. Tab close / external navigation uses the browser's native
beforeunloadwarning (custom modals are blocked by browsers since ~2016 for anti-phishing reasons) ANDnavigator.sendBeacon()for a fire-and-forget auto-save at the last moment. On hard crashes where no JS runs, IndexedDB is the recovery path. - Resume-anywhere UX. Every interview session has a resume URL. Explicit "Save & Continue Later" CTAs at every page. Section-completion checkpoints so users can jump forward/back to any prior section. Email-able resume link on explicit exit.
- Dedicated long-lived interview session cookie, decoupled from auth cookie. A 24-hour rolling cookie for the interview session so answer state survives an Auth0 session expiration mid-flow. User re-authenticates in-place; interview state persists.
- LLM calls are opt-in, bounded, cached, and async-when-possible. No LLM call per question by default. AI hints are user-request. Batch-mode + response caching against
(interview_version, section_id, answer_hash). 10s hard timeout, fails gracefully. Post-completion narrative + document generation runs on the async worker queue (aligns with Phase 2 scale infra), not synchronously in the request.
Version pinning as a corollary of Principle 1. Every interview session locks to the published interview version at session start. Deploys of a new version do not touch in-flight sessions. Because interviews are baked flat at publish (per D37), this is essentially free — a session references a specific published body blob.
Dismissed alternatives considered:
- Client-holds-everything. Rejected — fails on mobile (state bloat, GC pauses, laggy typing) and fails on tab suspension (client state disappears).
- Save-per-field-blur. Rejected by Riyaz 2026-07-03 as too noisy. 300 network calls per session is DB pressure at scale + latency on the user, and the value it adds over batch-per-page is negligible because IndexedDB already covers the "mid-page crash" case.
- Synchronous LLM per question. Rejected — fails on Anthropic rate limits at scale, fails on user latency, fails on cost. Async worker + user-request-triggered AI is the answer.
- No offline resilience. Rejected — wifi drops are a fact of life on mobile; without IndexedDB we lose real work.
- Shared cookie for auth AND interview session. Rejected — a 30-day auth cookie is too long, but a 30-minute auth session mid-interview is a data-loss event. Split them.
- Custom modal on tab close. Rejected because browsers don't allow it (technical constraint, not our call).
sendBeacon+ IndexedDB are functionally better than a modal anyway — the save happens without the user needing to click. - Big-bang cutover. Rejected. Each of the 7 task slices ships behind a feature flag, coexists with the current save path, gets validated, then flips. Roll back per-slice if any misbehaves.
- Defer this until we ship a long interview. Rejected — refactor cost is the same later, but under production-pressure with real users on the line. Doing it ahead is cheaper in every dimension.
Trust advantage this creates (rolls up into the enterprise transition plan's Trust Advantages Ledger): A Lawma interview of any length — including complex 200-300 question family-law asset disclosures — survives tab closes, wifi drops, session expirations, and browser crashes without silent data loss. Users can pause and resume from any device. In-progress work is protected client-side by browser storage; committed work is protected server-side by transactional batch writes.
D43 — Tiered third-party dependency policy (own / fork / vendor+audit / sandbox / accept)
Status: 🟡 LOCKED — building (green-lit by Riyaz 2026-07-03; execution starts AFTER the long-interview runtime refactor) Decided: 2026-07-03 Supersedes: — Cascades into: R120, T251–T254, and every future package.json change.
The decision. Every direct npm dependency gets classified into a tier that determines how we treat it. New deps require the tier to be assessed at PR review time. Existing deps get the classification below.
Tier A — Backed by a major-corporation maintainer, keep as-is.
next,react,react-dom(Meta + Vercel).typescript,@playwright/test(Microsoft).stripe,@stripe/react-stripe-js,@stripe/stripe-js(Stripe Inc).@sentry/nextjs(Sentry Inc).@anthropic-ai/sdk(Anthropic).dotenv(Motdotla — but so widely audited it's effectively standard).- Rationale: as safe as any third-party dependency gets. Any malicious update would be caught within hours by the ecosystem.
Tier B — Backed by a funded startup or well-audited standard, keep + monitor.
drizzle-orm,drizzle-kit(Drizzle Team, funded startup, active corporate use).tailwindcss,@tailwindcss/postcss(Tailwind Labs, funded startup).ajv(JSON-schema.org ecosystem, widely audited).tsx(esbuild-based, dev-only, low prod risk).@types/*(DefinitelyTyped — community, types-only, cannot execute code).- Rationale: mid-sized backing is sufficient given the low individual-actor risk. Monitor for maintainer/ownership changes via Socket.dev.
Tier C — Individual maintainer, but ACCEPTED with mitigation.
jose(Panva). Rationale: highly respected security-community maintainer; used by every Auth0 tutorial; Auth0's own SDK pulls it transitively. Mitigation: minimize direct use in our code (prefer Node stdlibcryptofor HMAC where possible — lib/auth/session.ts already does this).@dnd-kit/core,@dnd-kit/sortable,@dnd-kit/utilities. Rationale: Builder-authoring surface only (Lawma-staff-only, not in client runtime path). Blast radius small. Mitigation: pin, monitor via Socket.dev, upgrade only with intentional PR.
Tier D — Individual maintainer, security-critical or load-bearing → REPLACE, FORK, or VENDOR+AUDIT.
bcryptjs— REPLACE. Password hashing is security-critical. Node stdlibcrypto.scryptis a better primitive (memory-hard, meets OWASP 2024 guidance), zero external dep, transparent user migration on next login. Effort: 2-3 days.json-logic-js— FORK. ~300 LOC. This IS our interview logic engine's brain. Fork intolib/interview/json-logic/with full test suite. External dep frozen at last audited version, then removed once fork is complete. Effort: ~1 week.pdf-lib,docx,docx-templates,mammoth,jszip— VENDOR + AUDIT + PIN + SANDBOX. Too large to realistically fork (tens of thousands of lines each). Mitigation stack: (1) pin exact versions in package.json; (2) written pre-bump review — read the full changelog and diff before every version upgrade; (3) minimize imports (only what we actually use, tree-shake aggressively); (4) run in the async worker pool (Phase 2 scale infrastructure) with least-privilege IAM roles — even a fully compromised worker cannot reach client data / auth cookies / primary database; only worker-scoped queue payloads. Effort: 3-5 days for the audit + pin phase; sandboxing folds into scale infra later.postgres(Porsager driver) — EVALUATE swap topg(node-postgres, larger community, wider corporate use, same Postgres wire protocol so migration is mostly a connection-setup change). Evaluation might result in "keep and audit" or a driver swap. Effort: 3-5 days evaluation, plus migration cost if we swap (~1 week).
New-dep policy (going forward). Every new direct dependency added to package.json requires the PR description to name the tier (A/B/C/D) and, for D, the mitigation choice (replace / fork / vendor+audit+sandbox). Code review enforces this. CI Grep rule to flag package.json changes for reviewer attention.
Dismissed alternatives considered:
- Do nothing — trust Dependabot to catch bad updates. Rejected. Dependabot is a detection layer, not a prevention layer. By the time a malicious version is detected, it may have been installed on developer machines and possibly leaked secrets. For security-critical and load-bearing deps, prevention is worth the effort.
- Replace ALL individual-maintainer deps. Rejected. Fully replacing pdf-lib alone would require thousands of hours of PDF-wire-format work. Not a good use of engineering time when sandboxing gives similar risk reduction.
- Fork everything. Rejected — same reason. Owning code we can't realistically maintain is worse than depending on an actively-maintained repo we monitor.
- Do it in a single sprint. Rejected. The four moves have different urgencies. The bcryptjs replacement is genuinely security-critical and belongs in the security foundation phase. The json-logic-js fork is important but can wait a week. The PDF/Word audit folds into SOC 2 vendor risk assessment. The Postgres driver eval can wait for the Phase 2 database decision. Distributing across natural phases fits better than compressing into a sprint.
- Sequence this WHILE the runtime refactor is in flight. Rejected. Both would touch the interview engine (runtime refactor + json-logic-js fork). Doing them sequentially is safer — runtime refactor lands, gets validated, THEN we start the fork. Riyaz's sequencing call was correct.
Trust advantage this creates (rolls up into the enterprise transition plan's Trust Advantages Ledger): Every load-bearing library in Lawma is either backed by a major corporation (Meta, Microsoft, Anthropic, Stripe, Vercel), maintained by a funded startup (Drizzle, Tailwind), or code we own outright (json-logic-js fork). The remaining individually-maintained libraries either have small blast radius (Builder-only) or run in sandboxed worker environments with least-privilege isolation. Password hashing uses Node standard library cryptography, no external dependency.
D44 — Long-term infrastructure posture: own the cloud services directly (AWS-tier); managed layers must earn their place with meaningful AI advantage
Status: 🟢 LIVE — strategic direction locked 2026-07-03. Execution unfolds through the scale-infrastructure phase of the enterprise transition plan (D41 Phase 2). Decided: 2026-07-03 (Riyaz explicit direction: "I definitely want to go AWS route or a similar grade of provider. Tools like Vercel and Neon, unless they provide a meaningful AI advantage, are not long term solutions for us.") Cascades into: D41's Phase 2 sub-decisions (previously listed as open — the "web tier" and "database" choices now have a locked default of AWS-native; the earlier open-question framing is retired); the plan doc's Part 2 target architecture; CLAUDE.md Tech Stack section; the scale-migration task (T241); every future infrastructure vendor evaluation. Supersedes: —
The decision. Lawma's long-term production infrastructure runs on a tier-1 hyperscaler — AWS by default, or a similar-grade provider (GCP, Azure) — with the raw services owned directly by Lawma. Managed layers on top of a hyperscaler (Netlify, Vercel, Neon, Supabase, Fly.io, Railway, etc.) are TEMPORARY solutions valid only for the pre-scale phase, UNLESS a specific vendor provides a MEANINGFUL AI ADVANTAGE that Lawma engineering could not replicate in ~2 weeks on the hyperscaler natively.
Framing correction (important — this is the decision Lawma is actually making). Neon runs on AWS. Netlify runs on AWS. Vercel runs on AWS. The question is not "AWS or not" — it's already AWS underneath, in every path. The real question is: do we own the raw AWS services directly, or do we pay a managed layer to broker access to them? Riyaz's answer, 2026-07-03: own them directly. Managed layers must earn their place with more than convenience.
What "meaningful AI advantage" means, concretely. A managed vendor clears this bar only if AT LEAST ONE of the following is demonstrably true — measured in feature parity, not marketing claims:
- Native LLM-provider integration with Anthropic (or whichever LLM provider Lawma uses) that would take Lawma engineering >2 weeks to replicate on AWS-native equivalents (Lambda, API Gateway, Bedrock, EventBridge).
- Infrastructure capability Lawma cannot operate at reasonable cost — e.g., a built-in vector database with sub-millisecond retrieval SLA that AWS OpenSearch cannot match; or edge-inference for a specific model that requires proprietary infrastructure.
- Cost profile on the LLM tier beating AWS-native by more than 50% for our specific workload, over a documented benchmark. Not a claim — a measurement.
- Latency or geography advantage AWS cannot match — the vendor reaches a region or user population AWS does not serve well, and that population is material to Lawma's business (e.g., a state with poor AWS region coverage but material self-represented-litigant population).
Convenience alone — better DX, faster deploys, prettier dashboards, cleaner Git integration — does NOT clear the bar. Those are one-time engineering costs that AWS-native inflates but does not make impossible.
What this means for each of our current managed vendors:
- Netlify → migrate away in the scale-infrastructure phase. No AI advantage. It's a static-site + serverless-function convenience layer. Long-term target: AWS ECS/Fargate for the Next.js server + CloudFront for the CDN + AWS WAF for edge protection.
- Neon → migrate to AWS RDS Aurora Postgres (Postgres-compatible, largely a connection-string + verification change) in the scale-infrastructure phase. Neon's serverless scale-to-zero + branching are DX conveniences, not AI advantages. Re-evaluate only if Neon's AI-integration story becomes uniquely compelling by the migration decision point.
- Vercel (candidate that had been considered as the alternative to Netlify) → considered ONLY if Vercel's AI SDK + edge functions + streaming for LLM provides an advantage that AWS Bedrock + Lambda@Edge + our own code cannot match in a 2-week engineering estimate. Default: skip Vercel; go AWS-native.
- Every other managed vendor considered in the future (Supabase, PlanetScale, Fly.io, Railway, Cloudflare Workers, Deno Deploy, etc.) → must clear the same bar to be selected over AWS-native.
Vendors NOT subject to this rule (explicit list so it doesn't get misapplied):
- Anthropic — the LLM provider itself is not a "managed layer on AWS" in the sense this rule addresses. Anthropic is the model provider. AWS Bedrock's Claude integration is an alternative evaluated separately when we negotiate the enterprise agreement; Anthropic-direct is currently better for feature parity + ZDR + first access to latest models.
- Stripe — payment processor, not a hosting layer.
- Sentry, Datadog, Auth0 — specialized SaaS (observability, identity) that would take years to build from scratch, and AWS doesn't offer feature-parity managed alternatives.
- GitHub — source control + CI. Not a hosting layer.
- npm / package registries — dependency management, not hosting.
- Snyk / Socket.dev / Vanta / Drata / Secureframe — security + compliance tooling, not hosting.
Dismissed alternatives considered:
- Stay on Netlify + Neon indefinitely. Rejected. Both are single-region-ish by default; enterprise legal buyers ask for documented multi-region DR; both vendors' compliance certifications are narrower than AWS's (which carries every major cert including FedRAMP); both concentrate vendor risk in ways AWS-direct does not. Convenience today, real limits tomorrow.
- Hybrid: managed layers for dev/staging, AWS for prod, permanently. Real merit as an implementation tactic during migration — keeps DX advantages in development while putting the enterprise-grade posture where it matters (production). May adopt this DURING the migration. But NOT the long-term steady-state — production and staging should both eventually run on the tier-1 hyperscaler directly, so staging faithfully mirrors production behavior.
- AWS via Copilot / App Runner / other AWS-native "managed" abstractions. Acceptable if adopted — AWS controls the underlying primitives, the abstraction is thin, and we can drop down when needed. Not the same as third-party managed layers because there's no separate vendor concentration risk.
- GCP or Azure instead of AWS. Not rejected. "AWS or similar tier-1 hyperscaler." AWS is the default today because most of the AI-native ecosystem (Anthropic Bedrock integration, larger enterprise-legal buyer familiarity, deeper managed-services catalog) points there. If GCP or Azure develops a meaningful advantage by migration time, revisit at that time.
- Multi-cloud (active-active AWS + GCP) from day one. Rejected. Complexity is disproportionate to benefit at Lawma's scale. Single primary hyperscaler with clear migration paths is the right posture. Multi-cloud is a Series-C-scale concern, not a seed-stage one.
- "Just optimize the managed layers we have." Rejected. Optimizing Netlify's function limits and Neon's connection pool doesn't change the strategic posture — we still concentrate risk in a smaller vendor. Optimization is fine as pre-migration life-support, not a substitute for migration.
Why this matters strategically (reasoning captured so future decisions inherit the frame):
- Sales credibility. Enterprise legal buyers ask "who's your infrastructure provider?" AWS is the answer that lands. "Netlify" or "Neon" invites a follow-up question — often skeptical — we don't want to be answering during a diligence call.
- Vendor risk concentration. A managed layer represents concentrated risk — the vendor's billing model, ownership stability, and technical direction all become risks we don't control. AWS-direct reduces the concentration significantly (AWS is uniquely durable as a vendor).
- Compliance surface. AWS carries every major compliance certification (SOC 1, SOC 2, ISO 27001, HIPAA, FedRAMP, PCI, GDPR, C5). We inherit that surface directly when we own the AWS services. A managed layer means transitive AWS inheritance PLUS a dependency on the managed layer's separate certifications and audit reports.
- Cost control at scale. Managed layers charge convenience premiums (typically 30–100% over AWS-native for the same underlying capacity). At small scale, worth it. At the target scale (hundreds of thousands of concurrent users), the premium becomes a real budget line better redirected to product investment.
- Escape hatch. Owning the AWS services directly means we can migrate to GCP or Azure with predictable effort. Owning a managed layer on top of AWS means TWO migrations to leave AWS.
- Optionality on AI infrastructure. AWS Bedrock hosts multiple frontier models (Claude, Llama, Titan, Cohere, Mistral). AWS-native gives us flexibility to run fine-tuned models, split traffic across providers, or use Amazon Q if it ever becomes strategic. Managed layers narrow that optionality.
One thing named honestly: the developer-experience cost of this decision is real. Vercel/Neon/Netlify deliver a genuinely better DX than AWS-native in the current state — faster iteration, cleaner Git integration, better preview environments. The migration is not "throw a switch"; it's engineering weeks per layer. That cost is one-time; the strategic benefits above are durable. Riyaz accepted this trade-off explicitly on 2026-07-03.
Trust advantage this creates (rolls up into the Trust Advantages Ledger): Lawma's production infrastructure runs on AWS (or a similar tier-1 hyperscaler), with the raw services owned and operated directly rather than via managed intermediaries. Our SOC 2 audit surface, disaster-recovery posture, cost economics, and vendor risk profile all inherit directly from a tier-1 cloud provider's certifications and operational maturity, not from a chain of managed layers each with their own certification stack.
D45 — Postgres driver: KEEP postgres (Porsager) + PIN; and two R120 execution refinements (json-logic wrap-not-fork, doc-suite pin-not-sandbox-yet)
Status: 🟢 EXECUTED · Decided: 2026-07-03 · Requirement: R120 · Task: T254
Context. T254 proposed benchmarking postgres (Porsager) vs pg (node-postgres) on Lawma's query mix, then deciding KEEP-or-MIGRATE. The Opus 4.8 strategy review (2026-07-03) recommended cancelling the benchmark and simply writing the decision — a benchmark with no decision-changing threshold is procrastination, and the framing answers itself.
Decision. KEEP postgres, PIN it exactly (3.4.9, caret dropped), document pg as the escape hatch. Full rationale + escape-hatch mechanics in docs/dependencies/postgres-driver-decision-2026-07-03.md. In short: Neon (our current host) leads with postgres; Drizzle supports it first-class; it speaks plain Postgres wire protocol so it's Aurora-compatible for the D44 migration with only a connection-string change; and "individual-maintainer risk" is a category error here (focused high-velocity maintenance is often lower-risk than a large project's slower patch cadence). The value the slice was actually after — turning an unexamined caret-ranged dependency in the DB wire path into a reviewed, pinned one — is delivered by the pin + this decision; the migration question was a red herring.
Two execution refinements this entry also records (so D43's index text doesn't read as contradicted — the tiered dep POLICY is unchanged; only two specific Tier-D tactics were refined during execution):
- json-logic-js: WRAP + PIN, not fork + rewrite. D43 named "FORK into lib/interview/json-logic/." Execution (T252) instead pinned it exactly and routed every rule evaluation through a single owned import boundary (lib/interview/json-logic/index.ts). A rewrite would make every operator edge case + perf regression ours and discard the library's battle-tested property; owning the swap point mitigates the real risk (malicious update / maintainer goes dark) without paying the maintenance tax. Vendoring the ~300 LOC source into that module stays a pre-planned one-file fallback. Audit: docs/dependencies/json-logic-js-audit-2026-07-03.md.
- PDF/DOCX/ZIP suite: PIN + AUDIT now, SANDBOX deferred to Phase 2. D43 named "VENDOR + AUDIT + PIN + SANDBOX." Execution (T253) pinned all five exactly + wrote the audit (docs/dependencies/document-suite-audit-2026-07-03.md); running them in isolated workers stays scoped to the Phase-2 scale work (transition plan T241), where the slice-7 async job queue is the seam they plug into.
Password hashing (T251) landed as specified in D43 — bcryptjs replaced by Node stdlib scrypt, with a transitional dual-format verify + on-login re-hash for the partner portal; bcryptjs stays only until every partner row is scrypt (removal gate in project-tasks.md T251).
Dismissed. Benchmark-then-decide (procrastination without a threshold); migrate to pg now (real validation work across every query path for no demonstrated gain); leave postgres on a caret range (the exact unexamined-dependency posture R120 exists to close).
Trust advantage this creates (rolls up into the Trust Advantages Ledger): Every load-bearing third-party dependency in Lawma's security-critical and document-generation paths is pinned to an exact, reviewed version, with a documented owner-controlled swap point — no unexamined auto-updating package sits between a malicious npm release and the database wire, the interview branching engine, or court-document assembly.
D47 — Published-interview immutability (HARD RULE)
Status: 🟢 LIVE — locked 2026-07-04 (Riyaz: "any edits to a published interview will create a subsequent version. It will not disturb the published interview until the new version is approved and published. Publishing the new version or explicitly deprecating the previous version is the only way to change anything about the published interview")
The decision. A published interview version is immutable. Every authoring action that would mutate it (add/edit/remove a question, change a section title, update a form binding, change venue routing, change on-complete chains, change the tags meta, change the output kind) forks a new draft version instead. The published version stays byte-identical until either:
- The new draft version passes the attorney-review queue and is PUBLISHED — at which point the new version becomes live and the older published version can be deprecated as the author chooses.
- The published version is explicitly DEPRECATED by a Lawma admin, which removes it from the "current" set and stops new sessions from starting on it (existing in-flight sessions per D42 Principle 1 keep running against the version they started on).
Why. Two invariants collapse without this rule:
- Version-pin (D42 Principle 1). A client sessions locks to a published body when they start. If we let edits mutate the same version, a mid-flight client's questions can change under them — which is the exact "no filed document should be from a shifting spec" trust-break we're paying to avoid.
- Attorney-review gate. Legal output has to pass a licensed attorney's eyes before a client can see it. A "just save it" path around that gate turns the human-in-the-loop safety story into an opt-in one.
Codifying this at the D-level pins the invariant so no future editor / API / seed script accidentally reintroduces a write-published path.
How to apply.
- Every editor action that would call
updateInterviewDefinitionBodyorsaveFormBindingsor any comparable path against apublishedrow MUST reject and instead prompt "Fork a new draft first". The fork operation is one click; nothing else edits a published body. - Every seed script (
scripts/seed-*) that mutates definitions operates on drafts, never published rows. Seeded published rows are ONLY written on initial seed (db:seed-engine) or via a new-version publish flow. - Every attorney-review PR that would publish a draft is the only code path that flips
statusfromdraft→published. - The version-pinned client session (D42 Principle 1) is what carries in-flight users through the transition — a session that started on v1 keeps running against v1 even after v2 publishes.
Cascade required.
- Audit every writer of
interviewDefinitionTablefor status=='published' writes — flag any that exists as a bug. - Update the Builder UI to make the "Fork a new draft" affordance obvious wherever a Published version is loaded (already present as the "Published — immutable" banner in the tree editor; verify same banner appears in Forms Mode + the About card + every setup row).
- Reflect the rule in
CLAUDE.mdunder the "Product rules" carry- forward so no future session mis-remembers the invariant.
Dismissed alternatives.
- "Quick fix" edits to published body — rejected. Breaks version- pin; a mid-flight client's questions cannot silently change.
- Auto-publish on save when editor has admin role — rejected. Bypasses the attorney-review gate that gives every legal output its trust. Admin ≠ counsel.
- Deprecate + edit as the default — rejected. Deprecation is a deliberate two-step for the case where the published version is broken and can't wait. Not the everyday edit path.
D46 — Scale-migration execution refinements: AWS wrapper ladder (Amplify Hosting + Aurora Serverless v2 + SQS) as the default landing; evidence + ops-capacity phase gate; pin-plus-alert as one control
Status: 🟢 LIVE — locked 2026-07-03 (Riyaz: "I like the AWS wrapper approach: Amplify Hosting + Aurora Serverless v2 + SQS workers") Decided: 2026-07-03 Supersedes: — (refines D41 Phase 2 and D44 execution; neither is superseded — the AWS-native posture and the phased plan stand unchanged) Cascades into: the transition plan doc Parts 1.1, 2, 3.5, 4 (Phase 2), 6; CLAUDE.md Tech Stack → Hosting; T241's wording; docs/shark/2026-07-03-scale-stack-validation.md (origin analysis).
Origin. The 2026-07-03 shark validation of D41–D45 (docs/shark/2026-07-03-scale-stack-validation.md) confirmed all four decisions and raised two execution red-lines. Riyaz reviewed both, asked for the trustworthy-AWS-wrapper analysis, and locked all three refinements below.
Refinement 1 — the AWS wrapper ladder: Amplify Hosting + Aurora Serverless v2 + SQS is the default migration landing spot. D44 already blessed AWS's own managed abstractions ("Acceptable if adopted — AWS controls the underlying primitives, the abstraction is thin"). This refinement names the concrete default within that allowance:
- Web tier → AWS Amplify Hosting (AWS's Next.js-aware deploy service; builds from the GitHub repo, serves globally on CloudFront, TLS + autoscaling managed). Closest AWS-native equivalent to the Netlify DX we have today — but it IS AWS, on our AWS account, inheriting AWS's compliance surface, with no separate vendor.
- Database → Aurora Serverless v2 Postgres (+ RDS Proxy for connection pooling instead of a self-run PgBouncer sidecar). Removes capacity planning AND pooler operations; AWS owns patching, backups, failover.
- Background jobs → SQS + Lambda workers (unchanged from the plan — already fully managed).
- Raw ECS/Fargate is the graduate-DOWN option, not the entry point. Adopt it only when something specific demands container-level control that Amplify can't provide.
- Named caveat: Amplify's Next.js support historically lags the newest Next major versions and has had middleware/SSR edge cases. At migration time, FIRST verify Amplify runs our exact Next.js version + middleware faithfully (a 1–2 day spike). Fallback ladder if it can't: App Runner (containerized, still high-level) → ECS/Fargate.
Why: the thing D44 rejected was a separate vendor brokering AWS (vendor concentration, second cert chain, convenience premium) — not managed convenience itself. AWS's own wrappers carry none of those costs: same account, same compliance inheritance, same "AWS is our infrastructure provider" diligence answer, at roughly 30% of raw-ECS ops burden and a modest premium over raw that is far below the Vercel/Netlify enterprise premium.
Refinement 2 — the Phase 2 scale-migration entry gate is evidence + ops capacity, not the calendar. The migration does NOT begin because "Month 9" arrived. It begins when BOTH are true: (a) Evidence demands it — sustained load growth approaching managed-layer limits, OR an enterprise buyer's diligence requiring the AWS-direct posture; (b) Ops capacity is on board — a DevOps-capable engineer hired, OR a retained AWS-certified partner (established MSP tier: Rackspace / Mission Cloud / Caylent class, typically low-$K/mo) engaged. Until both hold, Netlify + Neon remain the CORRECT posture regardless of month number. Rationale: a real chunk of the managed-layer premium is ops labor; owning raw services without an operator converts a billing line into an outage risk with legal clients mid-interview.
Refinement 3 — pin-plus-alert is ONE control, not two. Exact version pins (D43/D45) close the malicious-auto-update door but open the stale-CVE door: a pinned package with a newly disclosed vulnerability stays vulnerable until a human bumps it. The pin is only safe while alerting is live. Concretely:
- GitHub vulnerability alerts (Dependabot alerts) enabled on riyaz110/Lawma2 2026-07-03 — repo-side scan against GitHub's advisory DB, zero Actions minutes, zero cost. Automated security-fix PRs deliberately NOT enabled (push-minimization posture; bumps stay deliberate).
- Phase 0 CI work (T234) verifies alert coverage extends to the pinned Tier-D packages, and the SOC 2 evidence set names "pin + alert" as a single control.
- Point-in-time audit note (2026-07-03):
npm auditshowed 6 moderate findings, all dev/build-surface with no clean fix available (old esbuild via drizzle-kit's toolchain — dev-machine only; postcss bundled inside Next itself — no fixed Next release exists yet). No action warranted; recorded so the next audit has a baseline.
Dismissed alternatives considered:
- Raw ECS/Fargate as the migration entry point. Rejected as the default — maximum control, maximum ops burden, no user-visible benefit at entry scale. Remains the graduate-down path.
- AWS Managed Services (AMS, AWS's white-glove ops offering). Rejected — enterprise-priced, sized for Fortune-500 estates. The MSP-partner retainer covers the same need at a fraction of the cost.
- Third-party PaaS wrappers (Vercel etc.). Already excluded by D44 unless the meaningful-AI-advantage bar is cleared; nothing here reopens that.
- Calendar-triggered migration. Rejected — replaced by the evidence + ops-capacity gate (Refinement 2).
- Enabling Dependabot auto-fix PRs alongside alerts. Rejected for now — conflicts with the push-minimization posture; alerts + deliberate human bumps is the right cadence at current team size.
Trust advantage this creates (rolls up into the Trust Advantages Ledger): Lawma's scale migration lands on AWS's own managed services — deployment, database, and queue layers all operated by AWS itself on Lawma's account, inheriting AWS's full compliance surface with no intermediary vendor — and the migration is gated on having professional operations capacity in place before Lawma owns production infrastructure. Every pinned dependency is continuously scanned against the public vulnerability database, so "frozen" never means "unwatched."

