← All planning documents

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)

IDTitleStatusDecidedSupersedesSuperseded by
D47Published-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.🟢 LIVE2026-07-04—R123-immutable / T109
D46Scale-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).🟢 LIVE2026-07-03—R121 / T255
D45Postgres 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).🟢 EXECUTED2026-07-03—R120 / T254
D44Long-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
D43Tiered 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
D42Long-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
D41Adopt 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
D40Anchor-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.🟢 LIVE2026-07-03—R99 / T229
D39Repeats + 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-01builds on D37 + D38R95, R96
D38Nested-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-01builds on D37R88
D37Sub-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
D36AUTH_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).🟢 LIVE2026-07-01——
D34Database 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.🟢 LIVE2026-06-27——
D35The "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.🟢 LIVE2026-06-28scraps the advertiser-portal "no authed surfaces" guardrail—
D33Breadth-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)🟢 LIVE2026-06-26——
D1Discovery-first before greenfield-vs-salvage decision🟢 LIVE2026-06-13——
D2Lawma2 IS the new product repo (not sidecar)🟢 LIVE2026-06-13——
D3Demo strategy: self-service = mockups; real demos = Riyaz-driven🟢 LIVE2026-06-13——
D4Canonical user-type taxonomy for Lawma2🟢 LIVE2026-06-13——
D5Canonical object/entity taxonomy for Lawma2🟢 LIVE2026-06-13——
D6Paired-mockup convention lifted from Lawma main🟢 LIVE2026-06-13——
D7Path C — in-place refactor + Lawma2 rebrand (build-vs-migrate decision)🟢 LIVE2026-06-13——
D8Every case needs a lead lawyer; missing surfaces as a flag (not a CHECK)🟢 LIVE2026-06-14——
D9Mockup-page architecture: app/(demo-mockups)/personas/ → URL /personas🟢 LIVE2026-06-14——
D10Matchmaking marketplace browse is public; account required only at "request match"🟢 LIVE2026-06-14——
D11Path B locked: main = dev (lawma611) + production = prod (lawmaco); fast-forward only; light gate🟢 LIVE2026-06-14——
D12Retire FOUNDER_EMAIL; lawma_admin IS the platform-owner role🟢 LIVE2026-06-16——
D13Public site = second Netlify deploy off production, env-var gated (NOT a third branch)🟢 LIVE2026-06-16——
D148th-grade reading level baked into every client-facing AI prompt template (not Carmen's edit task)🟢 LIVE2026-06-17——
D15Native court-grade e-signature module inside Lawma (no DocuSign / external e-sig)🟢 LIVE2026-06-17——
D16Capture attorney edits on AI output as a structured corpus + extend /app/admin/ai-feedback with an Edits review tab🟢 LIVE2026-06-17——
D17Dual-role (firm_admin + practicing lawyer) modeled via case_participant, NOT a roles table🟢 LIVE2026-06-17——
D18First lawyer to register a new firm becomes its firm_admin automatically🟢 LIVE2026-06-17——
D19Firm-admins can invite additional firm-admins (existing members or new users); no role cap🟢 LIVE2026-06-17——
D20Firm merge requests via firm_merge_request table; lawma_admin approves; soft-merge via firm.merged_into_firm_id🟢 LIVE2026-06-17——
D21R20 v1 scope = pay-now-with-7-day-refund only; defer two-mode trial-state lifecycle🟢 LIVE2026-06-18——
D22R18 v1 scope = typed-name signatures + 3 non-negotiables; drawn-signature v1.5; polish v2🟢 LIVE2026-06-18——
D24Post-refund answer-handling = RETAIN-WITH-NOTICE (audit-strict; matches CA state-bar 5-year retention)🟢 LIVE2026-06-18—R4 phase 1
D25R18 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-18D29R18 phase 2
D26OCR 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
D27Client-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 pending2026-06-24—T189
D28Auth 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 D302026-06-24D30#8 / R-auth
D29E-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
D30MFA/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
D31User 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
D32Interview 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 queued2026-06-25partly 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:

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:


D2 — Lawma2 IS the new product repo (not a sidecar discovery folder)

Status: 🟢 LIVE Decided: 2026-06-13T19:05:00Z Supersedes: — Dismissed alternatives considered:

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:


D3 — Demo strategy: self-service = mockups; real demos = Riyaz-driven

Status: 🟢 LIVE Decided: 2026-06-13T20:30:00Z Supersedes: — Dismissed alternatives considered:

See also: docs/shark/2026-06-13-demo-mockup-strategy.md, R2.

Two parallel demo surfaces:

  1. 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/).
  2. 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:


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:

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:

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:

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

Rigor observations folded in

  1. 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.
  2. 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.
  3. 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.
  4. 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 surviving implementer strings 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:


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:

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

  1. 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.
  2. 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.
  3. AI Training Data — Lawma Staff train the AI; Network Attorneys + any platform user can submit feedback on AI contributions.

Identity, relationship, gating

  1. User — auth identity with role per D4 taxonomy.
  2. Network Law Firm — multi-tenant parent for Network Lawyers + Network Paralegals.
  3. 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.
  4. case_participant — explicit join entity for who's on a case (Client, Network Lawyer, Network Paralegal, optionally Notary/Process Server in the future).
  5. Attorney Verification — registration queue; human-verified bar standing before a Network Lawyer account exists (built as J163 in lawma-jun11, reverted).
  6. Access Code — second way relationships form; legal-aid clinic hands a code to a Client.

Case workspace

  1. Case — a Client's legal matter. One Client → many Cases. Carries a court_case_number (the future linkage point for Conflict Walls).
  2. 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.
  3. Document — actual work product (filled court forms, assembled .docx letters, etc.). Lifecycle: DRAFT → approved → signed → filed. E-signatures with evidence records. Co-review comments.
  4. Case Analysis — AI-generated briefing for a Case with review-state provenance (per the AI-feature doctrine; runtime applies, fails closed).
  5. Work Plan — attorney-assigned tasks; case checklist ("path to filing"); appointments.
  6. Secure Messages — attorney↔client privileged channel. Emails carry zero content by design (notification-only).

Money

  1. Money / Payments — flat fee on the Engagement + Lawma's share. The single flat fee is the canonical cost story.

Community & monetization

  1. Community Posts & Replies — forum content. Open to all user types (D4); permissions vary.
  2. Ad — individual ad units (placements).
  3. Ad Campaign — campaign-level entity with performance metrics + funding management.
  4. Ad Partner Intake Form — separate intake flow each Ad Partner defines. Each field carries a purpose string so the consent screen can render "what's shared and why" to the Client.

System spine

  1. Audit Spine — append-only log of every privileged action. Records operating user AND represented user (per D4 rigor observation #2).
  2. Notifications — forum bell today; messages/tasks tomorrow; SMS per D65 (referenced from lawma-jun11) eventually.

Future hooks (foundation supports, no v1 build)

  1. 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.
  2. 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

  1. Engagement is per-Case, not per-Client. Everything downstream — Documents, Money, Secure Messages, Work Plan, Case Analysis — hangs off Case + Engagement.
  2. 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.
  3. Conflict walls foundation, not v1 capability. Case carries court_case_number; opposing-party detection is future. Foundation does not preclude; checking is deferred.
  4. 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:


D7 — Path C: in-place refactor + Lawma2 rebrand (build-vs-migrate)

Status: 🟢 LIVE Decided: 2026-06-13T22:30:00Z Supersedes: — Dismissed alternatives considered:

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:

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:

  1. Step 0 — Smoke test (copy lawma-jun11 → Lawma2; tsc + build + tests green BEFORE any changes).
  2. Step 1 — Vocabulary rename pass.
  3. Step 2 — D4/D5 additive schema migrations (5 items).
  4. Step 3 — Policy commitments (CLAUDE.md note on attorney_kind=both).
  5. Step 4 — Lift D6 mockup convention.
  6. Step 5 — Drop -archive clutter.
  7. Step 6 — Deploy Lawma2 to a NEW staging URL (lawma2-staging.netlify.app or similar). DO NOT touch lawmaco.netlify.app until investors are formally re-invited.
  8. Step 7 — Phase 2 capability development begins.

Three mitigations from shark Pass 2:

Cascade required:


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:

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):

  1. 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.
  1. 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 ``
  1. 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.
  1. CI enforcement — lift scripts/check-demo-isolation.sh from Lawma main; grep the mockup directory for forbidden imports; any hit fails the build. Wire into .github/workflows/ci.yml from day 1.
  1. Scenario checklist as prod-push gate — docs/demo/scenario-checklist.md lists every capability whose mockup must walk end-to-end via Playwright. Until the checklist walks, no merges to prod.
  1. 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.
  1. 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:

  1. 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.
  2. 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.
  3. Initialize empty docs/demo/scenario-checklist.md; grows per R-row mockup sub-step.
  4. Preserve the seed cast (names + roles).
  5. Design D4-driven persona cards for the v1 launcher (Network Law Firm as Firm + Lawyer + Paralegal; Ad Partner with per-field consent disclosure mockup).
  6. Every R-row from R3 onward lists a mockup sub-step that references D6.

Cascade required:


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:

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:

  1. 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.
  2. The reassignment writer (Phase 2 — reassignLeadAttorney in lib/cases/case-participants.ts) is the ONLY place that ever changes who the lead is. It runs as a transaction: mark the old row's removed_at, insert the new is_primary row, update engagement.attorneyId, log audit_event.
  3. The firm-manager dashboard reads findCasesNeedingLeadAttorney(firmId) on load and surfaces a "⚠ N cases need a lead" widget when N > 0.
  4. The platform-wide oversight view (Lawma admin / founder) reads the same query with no firmId filter for cross-firm drift detection.
  5. Backfill of legacy data (every existing engagement gets a primary case_participant row) happens in the T106 staging deploy seed script and is a one-time operation; the flag query catches any rows the backfill misses.
  6. When this rule needs upgrading (e.g., co-counsel; multiple simultaneous leads per case), the migration is additive: relax the case_participant_primary_uidx predicate, or add a separate is_supervisor flag.

Cascade required:


D9 — Mockup-page architecture: app/(demo-mockups)/personas/ → URL /personas

Status: 🟢 LIVE Decided: 2026-06-14T14:00:00Z Supersedes: — Dismissed alternatives considered:

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:

  1. Every new capability mockup lands at app/(demo-mockups)/personas/<capability>/page.tsx + app/(demo-mockups)/personas/<capability>/fixtures.ts per D6.
  2. Internal hrefs use /personas/<capability>, never /app/personas/<capability> or /(demo-mockups)/personas/<capability> — the route group is invisible.
  3. scripts/check-demo-isolation.sh greps app/(demo-mockups)/personas/ for forbidden imports + excludes _pattern/ (template) and personas/reset/ (admin-gated real software per D6 carve-out).
  4. The 308 redirects in next.config.ts from /app/personas/ to /personas/ live until ~2026-12-14 (6 months); prune the block after that window.
  5. 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:


D10 — Matchmaking marketplace browse is public; account required only at "request match"

Status: 🟢 LIVE Decided: 2026-06-14 Supersedes: — Dismissed alternatives considered:

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:

  1. 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 uses currentDemoOrSignedInUser, branch on null in the UI, redirect anonymous write-attempts to /app/register?returnTo=….
  2. 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.
  3. 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 + isUndefinedTable helpers from lib/db/util.ts.
  4. The returnTo carry-back is a small contract: post-register redirect honors returnTo only 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:

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.

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:

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:

Dismissed alternatives (don't re-offer):

How to apply:

  1. Every push to main auto-deploys lawma611. No ceremony.
  2. Every promotion to production follows docs/checklists/promote-to-prod.md — gates tick, then git merge --ff-only origin/main + git push origin production.
  3. Forbidden: any commit landing on production that isn't on main. If a fix is needed under demo pressure, land it on main, walk it on lawma611, then fast-forward production. Even at 3am the night before a pitch.
  4. Rollback: Netlify → lawmaco site → Deploys → previous deploy → "Publish deploy." Instant. Belt before suspenders.
  5. 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:


D12 — Retire FOUNDER_EMAIL; lawma_admin IS the platform-owner role

Status: 🟢 LIVE Decided: 2026-06-16T18:00:00Z Supersedes: — Dismissed alternatives considered:

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:

How to apply:

Cascade required:


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:

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:

  1. middleware.ts — 404s investor-only routes (Business Plan, Financial Tables v1/v2, Investment Explorer, Pitch Deck, Revenue Explained, Competitor Lab, Requirements, Data Model, Engineering) when siteMode === 'public'. The 404 is a rewrite to /_not-found, not a redirect — a redirect would leak that the URL exists.
  2. <InternalStepNav> — the Tour bar is the investor walkthrough mechanism and hides entirely on the public site.

Why:

How to apply:

Cascade required:


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:

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:


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:

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:


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:

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:


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

Dismissed alternatives

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


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 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

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


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:

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

Cost of being wrong Low. Adding tiers, caps, or approval gates later is additive.

Cascade


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':

  1. Update every app_user.firm_id from source → target.
  2. Update every engagement.firm_id, case_participant.firm_id, audit_event.firm_id from source → target.
  3. Set firm.merged_into_firm_id = target_firm_id on the source row. The source firm row is NOT deleted — audit trail integrity.
  4. Write one big audit event firm.merged with 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

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


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:

  1. 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.
  2. 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.
  3. 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:

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):

Why Both R18 sharks reached the same v1 cut:

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:

  1. PR for D22 lock + plan ships first (this PR).
  2. 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.
  3. No code change merges to lawma611 (dev) without recordSignatureEvent writing 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.
  4. 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.
  5. Counterparty invite tokens: JWT signed with R18_INVITE_SECRET env var. 15-minute TTL. Single-use enforced via invite_token_used_at column on a new lightweight table.
  6. Detached-signature pattern: recordSignatureEvent accepts documentHashAtSigning as 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.
  7. Audit-spine: every signature_event also writes an audit_event with action='document.signed' AND the same hash payload. Two storage locations on purpose — the audit_event is for the cross-action timeline; the signature_event is the authoritative legal artifact with TSA + IP + UA.

Product / legal:

Dismissed alternatives

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


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:

Why Both Tier-3 shark passes (independently — Pass 1 didn't read Pass 2 and vice versa) converged on the same recommendation:

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:

  1. Paying-customer funnel conversion rate (does pay-now lose so many that trial mode is the only path to revenue?).
  2. Refund rate within the 7-day window (signal for "buyer's remorse" vs. "wrong-attorney-match").
  3. Attorney NPS on the pay-now-only flow (do they hate having no try-before-buy fallback?).
  4. CA state-bar opinion (or analogous opinion from another bar Lawma operates in).

How to apply Engineering:

  1. The implementation in PR #80 (forthcoming) only adds pending_payment | paid | refunded to engagement_status. Do NOT add trial in the same migration; that's a future migration when v2 unblocks.
  2. 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."
  3. Refund window is computed server-side from payment.captured_at + 7 days; never trust client clock.
  4. 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.
  5. 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.
  6. The case-notification kind enum gets three new values; the page copy on /app/attorney/notifications learns them.
  7. Stripe TEST MODE only. Real-money requires a separate D-entry, lawyer-reviewed refund copy, and a deliberate go-live ritual.

Product / non-engineering:

Dismissed alternatives

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


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:

  1. Match-confirm becomes a two-option picker (Pay-now-with-refund stays as the recommended default; "Try interview first" is the new branch).
  2. 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]/commit and choose commit-or-back-out.
  3. 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)

v1.5 deltas that revise the original v2 spec (the load-bearing reason this entry exists)

  1. PI-resume pattern (R20 v1.5 — landed in this same PR): retrievePaymentIntent returns client_secret. v2 writers should NOT use SetupIntent+later-charge — single PI created on commit, single client_secret reused on retry.
  2. 7-day refund window persists into v2: every paid engagement 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."
  3. Attorney-honorarium schema slot: v2 schema gets a NULL trial_compensation_cents column on engagement. 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)

  1. New D-entry (D2x) locks the v2 scope at code-landing time — this entry is architecture-of-record only.
  2. Migration 0050_r20_v2_trial_mode.sql (or whatever number is current) per the plan doc.
  3. lib/payments/r20-v2-writers.ts with startEngagementTrial / commitTrialAndCapture / closeTrialAsBackedOut.
  4. Match-confirm rewrite at /app/find-attorney/[id]/confirm.
  5. Commit screen at /app/interview/[caseId]/commit.
  6. Notification kind extensions (3 new kinds) + page copy.
  7. Roster pill + R3 dashboard rollup.
  8. Demo seed + personas card #7 ("Client trying the interview first").

Dismissed alternatives (revisited from the original v2 spec)

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


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)

  1. 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.
  2. 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.
  3. 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.
  4. 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

Concrete behavior

Cascade

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

  1. Typed-name flow (own-account signer, R18 v1):
    • Does the canonical intent copy on /app/documents/[id]/sign constitute 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?
  1. 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.
  1. 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

Cascade

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

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):

Dismissed alternatives

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)

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:

  1. Secure by default. AUTH_REQUIRE_MFA defaults to ON; only an explicit =false disables it. A forgotten/unset flag fails safe (MFA on).
  2. Loud. resolveAuth0User() logs a warning at process start when MFA is off.
  3. 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

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

  1. 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.
  2. 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.
  3. 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

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

  1. 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).
  2. Author-declared client party (dynamic, but authored): the AUTHOR declares which party is the client on the definition (InterviewDefinition.party_role, across the full PartyRole vocabulary), in the Builder — NOT a runtime question. client_display_name is 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

Cascade required

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


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):

  1. Contract analysis → negotiation guide (R52) — engine extension; IN.
  2. Demand / dispute letters (docx_render) — cheapest new product.
  3. Sued-respondent / eviction Answer (R48 Phase 3) — differentiator.
  4. Small claims (file + respond) (court_form).
  5. Restraining orders (DV / civil harassment) (court_form).
  6. Name change / fee waivers (court_form).

Explicitly OUT this 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:

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.

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.

Dismissed.

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).

  1. 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.
  2. 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.
  3. Self-contained audit. A baked body diffs/greps/reasons with no cross-row lookups.
  4. (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.

Dismissed.

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:

  1. 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.
  2. 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.
  3. 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.

Dismissed.

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:

  1. 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).
  2. 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.
  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):

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:

Open sub-decisions parked for their own council session at trigger time:

Assumptions Riyaz should red-line if wrong:

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.

  1. 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.
  2. 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.
  3. Every save idempotent on (session_id, question_key, repeat_index). The schema already has this unique index. Batch save is a loop over the existing saveAnswerRow primitive inside a single transaction. Retries are safe.
  4. 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.
  5. Tab-close protection is layered. In-app navigation uses the existing custom modal. Tab close / external navigation uses the browser's native beforeunload warning (custom modals are blocked by browsers since ~2016 for anti-phishing reasons) AND navigator.sendBeacon() for a fire-and-forget auto-save at the last moment. On hard crashes where no JS runs, IndexedDB is the recovery path.
  6. 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.
  7. 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.
  8. 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:

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.

Tier B — Backed by a funded startup or well-audited standard, keep + monitor.

Tier C — Individual maintainer, but ACCEPTED with mitigation.

Tier D — Individual maintainer, security-critical or load-bearing → REPLACE, FORK, or VENDOR+AUDIT.

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:

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:

  1. 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).
  2. 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.
  3. 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.
  4. 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:

Vendors NOT subject to this rule (explicit list so it doesn't get misapplied):

Dismissed alternatives considered:

Why this matters strategically (reasoning captured so future decisions inherit the frame):

  1. 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.
  2. 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).
  3. 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.
  4. 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.
  5. 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.
  6. 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):

  1. 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.
  2. 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:

  1. 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.
  2. 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:

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.

Cascade required.

Dismissed alternatives.

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:

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:

Dismissed alternatives considered:

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."