[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M71K9JDPZJ3TMN84SHS2W959":3,"skill-same:01M71K9JDPZJ3TMN84SHS2W959":77},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":31,"publishedAt":42,"linkOnly":43,"markdownContent":44,"markdownBody":45,"frontMatter":46,"refName":47,"commitSha":48,"skillDirectory":49,"forksCount":50,"repositoryHtmlUrl":51,"repositoryHomepageUrl":52,"ownerHtmlUrl":53,"ownerBlogUrl":54,"ownerDescription":55,"updatedAt":56,"install":57,"resources":70},"01M71K9JDPZJ3TMN84SHS2W959","legal-contract",null,"Draft, review, or explain legal documents — NDAs, contracts, privacy policies, and more.","clawdsolana\u002FOpenClawd","clawdsolana","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F279036008?v=4","01M71JTVF9FNGKE2SVJRPTQM31","OpenClawd","01M71JTVGCKWBSS8ZYC1HYWVA5",2,"MIT","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fsecondary_skills\u002Flegal-contract\u002FSKILL.md",[18,23,26],{"categoryNo":19,"categoryName":20,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000002","文档处理","SCENARIO","使用场景",{"categoryNo":24,"categoryName":25,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000009","前端开发",{"categoryNo":27,"categoryName":28,"taxonomyType":29,"taxonomyTypeDesc":30},"01JBSEEDCAT000000000000037","律师与法务","PROFESSION","适用职业",[32,33,34,35,36,37,38,39,40,41],"legal","legal contract","contract","documents","explain","review","contracts","more","draft","privacy","2026-11-10 10:12:30",false,"---\nname: legal-contract\ndescription: Draft, review, or explain legal documents — NDAs, contracts, privacy policies, and more.\n---\n\n# Legal Contract Assistant\n\n## OpenClawd Operator Adaptation\n\nRun this skill as part of the OpenClawd operator deck. Preserve the skill-specific workflow below, but frame outputs for Solana-native agents when relevant: prefer OpenClawd language, note whether the work can support autonomous agent operations, and keep financial, legal, tax, hiring, medical, or other regulated outputs informational unless the skill already requires a stricter disclaimer. Use the Llobster Legend persona only as light operator framing; do not let branding override accuracy, safety, or the user's stated domain.\n\n\nFull-stack legal platform with three core capabilities: (1) draft and review any type of legal document — NDAs, service agreements, LOIs, purchase agreements, privacy policies, terms of service, and more; (2) manage documents on a dashboard with owner-scoped access; (3) run interactive due diligence rooms for M&A transactions with file uploads, status tracking, comments, participant access control, and activity logging.\n\n## IMPORTANT DISCLAIMER: This provides general information and templates only. It does NOT constitute legal advice. Always consult a qualified attorney for legal matters\n\n## Platform Capabilities\n\nThis skill powers a full legal platform with three major capability areas. When the user arrives, guide them to the right capability based on their need:\n\n### 1. Document Drafting & Review\n\nGenerate any type of legal document from templates and review existing contracts for red flags.\n\n#### What users can do\n\n- Draft NDAs, service agreements, freelancer contracts, LOIs, term sheets, asset\u002Fstock purchase agreements, operating agreements, board resolutions, leases, privacy policies, terms of service — or any other legal document type\n- Review contracts they've received and get a plain-language analysis with flagged risks\n\n- Generate multi-document packages for transactions (e.g., LOI + NDA for an acquisition)\n- Export documents as PDF and DOCX for signing and redlining\n\n##### How it works\n\n1. User describes the document they need or pastes a contract for review\n2. For drafting: start from open-source templates (Bonterms\u002FCommon Paper for NDAs\u002Fservice agreements) or standard clause structures (for M&A documents). See \"Open-Source Template Libraries\" and \"M&A \u002F Transaction Documents\" sections below.\n\n3. For reviews: run the red-flag checklist and playbook checks, then output using the \"Review Output Format\"\n4. Store the document in the platform via the Documents System (any `documentType` string — the system is type-agnostic)\n\n5. Deliver PDF + DOCX exports using the generation pipeline in \"Output: Always Produce PDF & DOCX\"\n\n### 2. Document Management (Dashboard)\n\nStore, organize, and manage all legal documents with owner-scoped access.\n\n#### What users can do (2)\n\n- View all their documents on the dashboard with type badges and status indicators\n- Open any document to view its full content\n\n- Delete documents they no longer need (with confirmation)\n- Link documents to DD rooms for transaction context\n\n##### How it works (2)\n\n- Documents are stored in the `documents`table with a flexible`documentType` field — supports any type, not just LOIs\n- All access is owner-scoped: users only see their own documents\n\n- See the \"Documents System\" section below for schema and API details\n\n### 3. Due Diligence Rooms\n\nInteractive workspaces for managing M&A due diligence checklists with file uploads, comments, and team collaboration.\n\n#### What users can do (3)\n\n- Create DD rooms pre-populated with 8 standard M&A categories and 57 checklist items\n- Add custom categories and items beyond the standard template\n\n- Upload files against checklist items (directly to object storage via presigned URLs)\n- Download uploaded files with room-level authorization\n\n- Track item status through the workflow: not*started → uploaded → under*review → approved\u002Fflagged\n- Comment on items for team discussion\n\n- Invite participants by email with role-based access (viewer, contributor, admin)\n- Monitor progress via per-category and overall completion statistics\n\n- Review a full activity feed of all room actions\n\n##### How it works (3)\n\n- Room creation auto-populates from the `DD_TEMPLATE`in`dd-rooms.ts`\n- All routes are protected by room-level access control middleware\n\n- Files go through a presigned URL upload flow (request URL → upload to storage → register in DB)\n- See the \"Due Diligence Room Platform\" section below for full architecture and API details\n\n## When to Use\n\n- User needs any type of legal document drafted — NDA, service agreement, freelancer contract, consulting agreement, partnership agreement, operating agreement, LLC agreement, board resolution, employment agreement, offer letter, non-compete, non-solicitation agreement, equity\u002Fstock option agreement, SLA, DPA, or any other contract\n- User needs a Letter of Intent (LOI), term sheet, earnout agreement, or asset\u002Fstock purchase agreement\n\n- User wants a plain-language review of a contract they received (\"review this contract\", \"what does this clause mean\", \"help me understand this agreement\", \"is this contract fair\")\n- User needs to understand specific legal terms or clauses\n\n- User wants a lease or rental agreement reviewed for red flags\n- User needs multiple related transaction documents (e.g., LOI + NDA for an acquisition)\n\n- User needs a Privacy Policy or Terms of Service for a web app or SaaS product\n- User asks to \"draft a contract\", \"write me a contract\", or \"create an agreement\"\n\n- User wants to manage and organize their legal documents on a dashboard\n- User needs to set up or work within a due diligence room, data room, or deal room for an M&A transaction\n\n- User wants an M&A checklist, acquisition checklist, or due diligence checklist\n- User wants to upload, track, or review due diligence documents with a team\n\n## When NOT to Use\n\n- Complex litigation or regulatory compliance\n- Employment law disputes\n\n- International trade agreements\n- Anything involving criminal law\n\n- Situations requiring jurisdiction-specific legal analysis\n\n## Open-Source Template Libraries (Use These First)\n\n**Never draft from scratch.** Start from committee-vetted open-source agreements released under CC BY 4.0:\n\n| Source | Documents | Style | Get it |\n\n|--------|-----------|-------|--------|\n\n| **Bonterms** | Mutual NDA, Cloud Terms (SaaS), SLA, DPA, PSA, AI Standard Clauses | US; \"cover page + standard terms\" | `github.com\u002FBonterms` |\n\n| **Common Paper** | Mutual NDA, Cloud Service Agreement, DPA, Design Partner Agreement | US; standards committee of 40+ attorneys | `commonpaper.com\u002Fstandards` |\n\n| **oneNDA** | NDA (777 words), oneDPA | UK\u002FEU; strict variable-only edits | `onenda.org` |\n\n**Workflow:** `webFetch(\"https:\u002F\u002Fbonterms.com\u002Fforms\u002Fmutual-nda\u002F\")` → extract the standard terms → build a cover page with the user's deal-specific variables (parties, effective date, term, governing law, jurisdiction). Don't modify the body; that's the whole point of standards.\n\n**Note:** These libraries cover NDAs and SaaS\u002Fservice agreements well, but do not include M&A documents (LOIs, term sheets, purchase agreements). For those document types, draft using the standard clause structures in the \"M&A \u002F Transaction Documents\" section below.\n\n## M&A \u002F Transaction Documents\n\nWhen a user needs documents for buying\u002Fselling a business, these are the common document types and their standard clause structures:\n\n### Letter of Intent (LOI)\n\nStandard sections for an LOI:\n\n1. **Transaction Structure** — asset purchase vs. stock\u002Fequity purchase\n2. **Purchase Price** — total price, payment structure (cash at closing, earnout, seller financing, escrow holdback)\n\n3. **Earnout provisions** — if applicable: percentage, performance milestones, measurement period, payment schedule\n4. **Due Diligence** — period length (typically 30-60 days), scope, access to records, extension rights\n\n5. **Exclusivity \u002F No-Shop** — period length (typically 60-90 days), binding on seller\n6. **Closing Timeline** — target closing date\n\n7. **Conditions to Closing** — due diligence completion, definitive agreement, reps & warranties accuracy, third-party consents, no MAE, ancillary agreements\n8. **Representations and Warranties** — reference to customary reps in definitive agreement\n\n9. **Confidentiality** — binding obligation\n10. **Expenses** — each party bears own costs; binding\n\n11. **Non-Binding Nature** — clearly state which sections ARE binding (typically: exclusivity, confidentiality, expenses, non-binding clause itself) and which are non-binding\n12. **Governing Law** — leave as fill-in-the-blank for jurisdiction\n\n13. **Expiration** — LOI expires if not signed within X days (typically 10-15)\n\n**Key variables to collect from user:** buyer name, seller\u002Ftarget name, purchase price, deal structure (asset vs. stock), due diligence period, exclusivity period, closing timeline, earnout terms (if any).\n\n### Mutual NDA (Transaction-Specific)\n\nWhen drafting an NDA for a specific transaction (vs. a general-purpose NDA), include these additional elements:\n\n- **WHEREAS clauses** that reference the specific transaction and any related LOI\n- **Permitted Purpose** scoped specifically to evaluating\u002Fnegotiating the transaction\n\n- **Non-Solicitation** of the other party's employees (typically 12 months)\n- **No Obligation to Proceed** — neither party is obligated to complete the transaction\n\n- Cross-reference the LOI or term sheet by name in the recitals\n\nStandard NDA sections: definition of confidential information, exclusions, receiving party obligations, no license\u002Fwarranty, return\u002Fdestruction, term (typically 2 years), remedies (injunctive relief), governing law, miscellaneous (entire agreement, amendments, assignment, severability, waiver, counterparts, notices).\n\n### Multi-Document Transactions\n\nWhen a transaction requires multiple related documents (e.g., LOI + NDA):\n\n1. **Maintain consistent definitions** — party names, defined terms (\"Transaction,\" \"Business,\" \"Purchased Assets\"), and entity references must match across all documents\n2. **Cross-reference between documents** — the NDA should reference the LOI in its recitals; the LOI's confidentiality section should note that a separate NDA governs\n\n3. **Align timelines** — the NDA's term should cover at least the LOI's exclusivity + due diligence + closing periods\n4. **Use the same governing law** placeholder in all documents\n\n5. **Draft and present together** — generate all documents in a single session so the user has a complete package\n\n## Privacy Policy & Terms of Service (Web Apps \u002F SaaS)\n\nPrivacy Policies and Terms of Service are among the most common legal documents a web app needs. They are not contracts between two parties — they are public-facing declarations. Treat them as a separate document type from the contract\u002FNDA\u002FLOI workflow.\n\n### Key questions to ask before drafting\n\n1. **Legal entity name** — Always ask for the exact registered legal name separately from the brand name. The brand is what users see (\"NiDO\"); the legal entity is what appears in formal documents (\"NiDO Finanzas S.A.S.\"). Never assume they are the same.\n2. **Country of incorporation** — Determines which data protection law applies (GDPR for EU, LGPD for Brazil, Ley 172-13 for Dominican Republic, CCPA for California, etc.).\n\n3. **What data is collected** — Account info (name, email), financial\u002Ftransactional data, uploaded files, usage\u002Fanalytics?\n4. **Third-party data processors** — Ask the user to enumerate every service that touches user data: auth provider, database host, AI\u002FML services, payment processor, analytics, email provider, CDN. Each must be disclosed in the Privacy Policy.\n\n5. **Are there paid plans?** — If yes, the Terms must cover payment terms, auto-renewal, cancellation, and refund policy.\n6. **Minimum age** — Typically 18 for financial apps, 13 for general consumer apps.\n\n7. **Contact email for privacy\u002Flegal** — Often different from the support email. Ask explicitly.\n\n### Third-party processor disclosure pattern\n\nFor every integration the app uses, include a line in the Privacy Policy. Format:\n\n```text\n\n- **[Provider] ([function]):** [What they receive and why]. [Link to their privacy policy if possible.]\n\n```\n\nExample:\n\n```text\n\n- **Neon (base de datos):** almacenamiento seguro de sus datos financieros en servidores PostgreSQL.\n- **Google Gemini (IA):** genera categorías y análisis. Solo recibe descripciones de transacciones; nunca datos personales identificables.\n\n- **Stripe (pagos):** procesa pagos con tarjeta. NiDO no almacena datos de tarjetas.\n- **Replit Auth (autenticación):** gestiona el inicio de sesión vía Google\u002FGitHub.\n\n```\n\nIf the app uses analytics, advertising pixels, or session recording (Hotjar, FullStory, etc.), these MUST be disclosed and typically require explicit consent in GDPR jurisdictions.\n\n### Privacy Policy required sections\n\n1. Who we are (legal entity name, contact email for privacy)\n2. What data we collect (account info, user-generated data, uploaded files, usage logs)\n\n3. How we use it (provide service, personalization, legal compliance)\n4. Third-party processors (enumerate all — see above)\n\n5. Data storage and security (encryption at rest\u002Fin transit, access controls)\n6. User rights (access, correction, deletion, export)\n\n7. Cookies (session-only vs. tracking; consent requirements if in GDPR territory)\n8. Minors (minimum age, what happens if a minor's data is discovered)\n\n9. Changes to the policy (notice method and timing — typically 15–30 days)\n10. Governing law (jurisdiction's data protection statute)\n\n### Terms of Service required sections\n\n1. Acceptance (clicking\u002Fusing = agreement)\n2. Service description (what it does and does NOT do)\n\n3. Account registration (age requirement, accurate info, responsibility for activity)\n4. Acceptable use (prohibited behaviors: fraud, scraping, reverse engineering, illegal activity)\n\n5. **Financial\u002Fmedical disclaimer** — if the app gives any advice-like output (budget suggestions, AI analysis), include an explicit \"not financial\u002Flegal\u002Fmedical advice\" clause\n6. User data ownership (user owns their data; limited license to operator to run the service)\n\n7. Payments (if applicable: billing cycle, auto-renewal, cancellation, refunds, payment processor)\n8. Service availability (no uptime guarantee unless SLA offered)\n\n9. Limitation of liability (cap at fees paid in last 12 months or a fixed floor like $100)\n10. IP ownership (brand, code, design belong to the operator)\n\n11. Termination (user can delete account; operator can suspend for violations; data deletion timeline)\n12. Changes to terms (notice period — typically 15 days for material changes)\n\n13. Governing law and jurisdiction\n\n### Delivery format for web apps — routed pages, not PDFs\n\nFor web apps, the best delivery format for Privacy Policy and Terms of Service is **routed pages within the app itself**, not PDFs or DOCX files. This is the standard for all modern SaaS products.\n\n#### Pattern\n\n- Create `client\u002Fsrc\u002Fpages\u002FPrivacy.tsx`and`client\u002Fsrc\u002Fpages\u002FTerms.tsx`\n- Register them as **public routes**— accessible without authentication. Place the route check**before** the auth loading state in `AppContent`:\n\n```tsx\n\nfunction AppContent() {\n\nconst { isLoading, isAuthenticated } = useAuth();\n\nconst [location] = useLocation();\n\n\u002F\u002F Public legal pages — always accessible, no auth required\n\nif (location === \"\u002Fprivacidad\") return \u003CPrivacy \u002F>;\n\nif (location === \"\u002Fterminos\") return \u003CTerms \u002F>;\n\n\u002F\u002F Auth guard below\n\nif (isLoading) return \u003CLoadingScreen \u002F>;\n\nreturn isAuthenticated ? \u003CAuthenticatedLayout \u002F> : \u003CLanding \u002F>;\n\n}\n\n```\n\n##### Page layout pattern\n\n- Minimal header: logo + \"Back to home\" link\n- Amber disclaimer banner at the top: *\"Este documento es una plantilla informativa y no constituye asesoramiento legal.\"*\n\n- Clean `max-w-3xl mx-auto`prose layout,`text-sm leading-relaxed`\n- Footer with cross-links: Privacy ↔ Terms ↔ Contact ↔ Home\n\n- No sidebar, no app navigation — these are public documents\n\n**After creating the pages, always update the footer links** in the landing page or marketing page. Footer links that point to `href=\"#\"`are broken. Replace with`href=\"\u002Fprivacidad\"`and`href=\"\u002Fterminos\"`, and change the \"Contact\" link to`mailto:` rather than another dead hash.\n\n**Consistency check after any company name change:** If the user changes the legal entity name, search ALL files — not just the legal pages. Invoice templates, billing pages, and email footers often also contain the company name and will need updating too.\n\n### Disclaimer banner (always include on the rendered page)\n\nEvery rendered legal page should display a visible disclaimer. Do not only warn the user in chat — put it on the page itself:\n\n```tsx\n\n\u003Cdiv className=\"bg-amber-50 dark:bg-amber-950\u002F30 border border-amber-200 dark:border-amber-800 rounded-md px-4 py-3 mb-10 text-sm text-amber-800 dark:text-amber-300\">\n\nEste documento es una plantilla informativa y no constituye asesoramiento legal.\n\nConsulte un abogado calificado para asuntos legales específicos.\n\n\u003C\u002Fdiv>\n\n```\n\n## Red-Flag Language to Grep For\n\nWhen reviewing, search the document text for these exact phrases — each is a known risk pattern:\n\n| Phrase | Why it's dangerous | Suggested fix |\n\n|--------|-------------------|---------------|\n\n| `\"any and all claims\"` | Unlimited indemnity scope | \"claims arising directly from [Party]'s breach of Section X\" |\n\n| `\"indemnify, defend, and hold harmless\"` | \"Hold harmless\" blocks your counterclaims even if they caused the loss | Strike \"and hold harmless\"; keep \"indemnify and defend\" |\n\n| `\"sole discretion\"`\u002F`\"absolute discretion\"` | One party can act arbitrarily (block settlements, reject deliverables) | \"consent not to be unreasonably withheld, conditioned, or delayed\" |\n\n| `\"including but not limited to\"` in IP assignment | Open-ended IP grab beyond deliverables | Enumerate specific deliverables; add \"excluding pre-existing IP\" |\n\n| No liability cap stated | Courts default to **unlimited** liability | \"Aggregate liability capped at fees paid in the 12 months preceding the claim\" |\n\n| `\"time is of the essence\"` | Any delay = material breach | Delete, or limit to payment obligations only |\n\n| Indemnity **carved out** of liability cap | Your cap doesn't protect you where exposure is highest | \"Indemnification obligations are subject to the cap in Section X\" |\n\n| Auto-renewal with \u003C30-day opt-out window | Easy to miss; locked in another term | 60–90 day notice window; email notice permitted |\n\n| `\"perpetual\"`+`\"irrevocable\"` license | Can never be revoked even after breach | Term-limited; terminable on material breach |\n\n**Indemnity forms (escalating risk):** *Limited*= you cover only your own negligence.*Intermediate*= everything except their sole negligence.*Broad* = you cover losses **even when caused entirely by them**. Flag intermediate and broad as Critical.\n\n## Playbook Checks (What Harvey\u002FSpellbook Actually Run)\n\nAI contract tools run a fixed checklist per document type. For a **Service Agreement** run these checks and grade each Pass\u002FFlag\u002FMissing:\n\n1. Is there a liability cap? Is it mutual? Is it tied to fees paid (1x, 2x)?\n2. Is indemnity mutual or one-way? Subject to the cap or carved out?\n\n3. Does IP assignment exclude contractor's pre-existing tools\u002Flibraries?\n4. Is there a cure period (typically 30 days) before termination for breach?\n\n5. Are \"consequential damages\" (lost profits, lost data) excluded? Mutually?\n6. Payment terms: Net 30 or better? Late fee specified?\n\n7. Can the client terminate for convenience? If so, is there a kill fee?\n8. Governing law + venue: neutral, or the other party's home court?\n\nFor a **Letter of Intent** run these checks:\n\n1. Are binding vs. non-binding sections clearly identified?\n2. Is there an exclusivity\u002Fno-shop clause? Is it binding?\n\n3. Is the purchase price clearly stated with payment structure?\n4. Is the due diligence period defined with access rights?\n\n5. Are conditions to closing enumerated?\n6. Is there a confidentiality obligation (binding)?\n\n7. Does the LOI have an expiration date?\n8. If there's an earnout, are the metrics and measurement methodology specified (or deferred to the definitive agreement)?\n\n## Review Output Format\n\n```text\n\n# Contract Review: [Document Type]\n\n**NOT LEGAL ADVICE — for informational purposes only. Consult an attorney before signing.**\n\n## Summary\n\n[2–3 sentences: what this is, who it favors, biggest concern]\n\n## Critical — Do Not Sign Without Addressing\n\n1. **[Clause §X.Y]**: [quote the exact language]\n\n- **Risk**: [plain English]\n- **Suggested redline**: \"[replacement text]\"\n\n## Warnings — Negotiate If You Have Leverage\n\n## Notes — Standard But Be Aware\n\n## Missing Protections\n\n[clauses that should be here but aren't — e.g., no liability cap, no cure period]\n\n## Overall: [Fair \u002F Favors Counterparty \u002F Consult Attorney Before Signing]\n\n```\n\n## Output: Always Produce PDF & DOCX\n\n**Every drafted contract MUST be delivered as both a PDF and a DOCX file.** Clients need PDF for signing and DOCX for redlining — always provide both.\n\n### Architecture: React + Vite → Puppeteer PDF + python-docx DOCX\n\nBuild the contract as a React web artifact first (source of truth for layout), then export:\n\n#### PDF via Puppeteer\n\nInstall `puppeteer-core`in the`scripts`package:`pnpm --filter @workspace\u002Fscripts add puppeteer-core`\n\n```typescript\n\n\u002F\u002F scripts\u002Fsrc\u002Fgenerate-contract.ts\n\nimport puppeteer from 'puppeteer-core';\n\n\u002F\u002F Find Chromium — pick the latest version from the list:\n\n\u002F\u002F ls \u002Fnix\u002Fstore\u002F*chromium*\u002Fbin\u002Fchromium | sort -V | tail -1\n\nconst CHROMIUM_PATH = \"\u002Fnix\u002Fstore\u002FFIND_LATEST_PATH\u002Fbin\u002Fchromium\";\n\n\u002F\u002F Use the artifact's actual URL, not localhost\n\nconst CONTRACT_URL = `https:\u002F\u002F${process.env.REPLIT_DEV_DOMAIN}\u002FARTIFACT-ROUTE`;\n\nconst browser = await puppeteer.launch({\n\nexecutablePath: CHROMIUM_PATH,\n\nheadless: true,\n\nargs: ['--no-sandbox', '--disable-setuid-sandbox'],\n\n});\n\nconst page = await browser.newPage();\n\nawait page.setViewport({ width: 816, height: 1056 }); \u002F\u002F Match page container dimensions\n\nawait page.goto(CONTRACT_URL, { waitUntil: 'networkidle0' });\n\n\u002F\u002F IMPORTANT: Set document.title for correct PDF metadata title.\n\n\u002F\u002F Without this, the PDF viewer title bar shows the HTML \u003Ctitle> from index.html,\n\n\u002F\u002F which may be wrong when generating multiple documents from the same app.\n\nawait page.evaluate(() => { document.title = \"Your Document Title Here\"; });\n\nawait page.pdf({\n\npath: 'contract.pdf',\n\nformat: 'Letter',\n\nprintBackground: true,\n\n\u002F\u002F IMPORTANT: Use zero margins — the page containers already include internal padding.\n\n\u002F\u002F Non-zero Puppeteer margins + fixed-height containers = blank overflow pages.\n\nmargin: { top: '0', bottom: '0', left: '0', right: '0' },\n\n});\n\nawait browser.close();\n\n```\n\nAdd a script entry in `scripts\u002Fpackage.json`:`\"generate-contract\": \"tsx .\u002Fsrc\u002Fgenerate-contract.ts\"`\n\nRun via: `pnpm --filter @workspace\u002Fscripts run generate-contract`\n\n##### DOCX via python-docx\n\nPython may not be available via `pip`in the Replit environment. Use`nix-shell`to get`python-docx`:\n\n```bash\n\nnix-shell -p python3Packages.python-docx --run \"python3 scripts\u002Fsrc\u002Fgenerate-contract.py\"\n\n```\n\n```python\n\n# scripts\u002Fsrc\u002Fgenerate-contract.py\n\nfrom docx import Document\n\nfrom docx.shared import Pt, Inches, RGBColor\n\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\n\ndoc = Document()\n\n# Set default font\n\nstyle = doc.styles['Normal']\n\nfont = style.font\n\nfont.name = 'Times New Roman'\n\nfont.size = Pt(12)\n\n# Set margins\n\nfor section in doc.sections:\n\nsection.top_margin = Inches(1)\n\nsection.bottom_margin = Inches(1)\n\nsection.left_margin = Inches(1.25)\n\nsection.right_margin = Inches(1.25)\n\n# Title\n\ntitle = doc.add_paragraph()\n\ntitle.alignment = WD_ALIGN_PARAGRAPH.CENTER\n\nrun = title.add_run('DOCUMENT TITLE')\n\nrun.bold = True\n\nrun.font.size = Pt(18)\n\n# Preamble\n\ndoc.add_paragraph(\n\n'This Agreement is entered into as of [DATE] by and between:'\n\n)\n\n# Parties table\n\ntable = doc.add_table(rows=1, cols=2)\n\ntable.style = 'Table Grid'\n\n# ... populate with party details\n\n# Sections with numbered clauses\n\nheading = doc.add_paragraph()\n\nrun = heading.add_run('1. Section Title')\n\nrun.bold = True\n\ndoc.add_paragraph('Section body text...')\n\n# Signature block\n\nsig_table = doc.add_table(rows=5, cols=2)\n\n# Row 0: labels (BUYER \u002F SELLER)\n\n# Rows 1-4: Signature, Printed Name, Title, Date lines\n\ndoc.save('contract.docx')\n\n```\n\n### Styling for Legal Documents\n\n- **Font**: Times New Roman 12pt (standard for legal docs) or similar serif\n- **Margins**: 1\" top\u002Fbottom, 1.25\" left\u002Fright\n\n- **Line spacing**: 1.5 or double-spaced (jurisdiction dependent)\n- **Section numbering**: Use hierarchical numbering (1, 1.1, 1.1.1)\n\n- **Page numbers**: Bottom center, \"Page X of Y\"\n- **Headers**: Document title and date on each page\n\n- **Signature blocks**: Two-column layout with lines for signature, printed name, title, date\n\n### Page-Aware Layout (Preventing Blank PDF Pages)\n\nUse fixed-height page containers that map 1:1 to physical letter pages. This ensures content stays within page boundaries on screen and in PDF output.\n\n#### Page container constants (letter size at 96 DPI)\n\n- `PAGE_W = \"816px\"` (8.5 inches)\n- `PAGE_H = \"1056px\"` (11 inches)\n\n- Internal padding: `48px`top\u002Fbottom,`72px` left\u002Fright\n\n##### Page container component pattern\n\n```tsx\n\n\u003Cdiv\n\nclassName=\"page-container mx-auto bg-white shadow-lg print:shadow-none mb-8 print:mb-0 flex flex-col overflow-hidden\"\n\nstyle={{\n\nwidth: PAGE_W,\n\nheight: PAGE_H,\n\npageBreakAfter: pageNum \u003C TOTAL_PAGES ? \"always\" : undefined,\n\nbreakAfter: pageNum \u003C TOTAL_PAGES ? \"page\" : undefined,\n\n}}\n\n>\n\n{\u002F* Page header with \"Page X of Y\" *\u002F}\n\n{\u002F* Content area with internal padding *\u002F}\n\n\u003C\u002Fdiv>\n\n```\n\n###### Critical CSS for print\u002FPDF — add to your global stylesheet\n\n```css\n\n@page {\n\nsize: letter;\n\nmargin: 0;\n\n}\n\n@media print {\n\nhtml, body {\n\nmargin: 0 !important;\n\npadding: 0 !important;\n\nbackground: white !important;\n\n}\n\n.page-container {\n\nbox-shadow: none !important;\n\nmargin: 0 !important;\n\n}\n\n}\n\n```\n\n**Why blank pages happen:** If Puppeteer adds its own margins (e.g., `margin: { top: \"0.5in\" }`) on top of 1056px containers, each container exceeds the physical page height. The overflow creates a blank page before the next`breakAfter: \"page\"`fires. The fix: always use`margin: { top: \"0\", bottom: \"0\", left: \"0\", right: \"0\" }`in Puppeteer and`@page { margin: 0 }` in CSS, since the page containers already include their own internal padding.\n\n**Do NOT override `height: auto` in print media** — removing the fixed height lets containers expand beyond one page, defeating the 1:1 page mapping. Keep the fixed height; the CSS page breaks handle pagination.\n\n###### Outer wrapper must neutralize screen-only styles for print\n\n```tsx\n\n\u003Cdiv className=\"min-h-screen bg-gray-100 py-8 px-4 print:bg-white print:py-0 print:px-0 print:min-h-0\">\n\n```\n\n**Viewport must match page width** in Puppeteer: `page.setViewport({ width: 816, height: 1056 })` so content renders at the correct scale.\n\n**Content balancing:** Use `breakInside: \"avoid\"` on sections and distribute content across pages so no page overflows. Check the rendered layout in the browser at 816px width before generating PDFs.\n\n### Contract Review Output\n\nFor **reviews** (not drafting), output the review analysis directly as text using the Review Output Format above. Do not generate PDF\u002FDOCX for reviews — the review is commentary, not a document.\n\n### Multi-Document Routing\n\nWhen generating multiple documents for the same transaction (e.g., LOI + NDA), use a single React artifact with separate routes for each document:\n\n```tsx\n\n\u002F\u002F App.tsx\n\n\u003CRoute path=\"\u002F\" component={LOIDocument} \u002F>\n\n\u003CRoute path=\"\u002Fnda\" component={NDADocument} \u002F>\n\n```\n\nThen generate separate PDF\u002FDOCX files for each document by pointing Puppeteer at each route and running a separate python-docx script per document. Present all files together so the user receives the complete package.\n\n**IMPORTANT:** Since all routes share the same `index.html`, the HTML`\u003Ctitle>`tag applies to every document. Each PDF generation script must call`page.evaluate(() => { document.title = \"Correct Document Title\"; })`before`page.pdf()` to set the correct PDF metadata title. Otherwise the PDF viewer's title bar will show the wrong document name.\n\n## Drafting Rules\n\n1. **Always include the disclaimer** at the top of every output — this is not legal advice\n2. Start from Bonterms\u002FCommon Paper for NDAs and service agreements; use the clause structures in \"M&A \u002F Transaction Documents\" for LOIs and purchase agreements\n\n3. Quote exact problem text with section numbers, then give replacement language\n4. Flag jurisdiction dependencies — non-compete enforceability, anti-indemnity statutes, and consumer protection vary wildly by state\u002Fcountry\n\n5. When stakes are high (>$50K, equity, exclusivity, personal guarantees) → recommend attorney review explicitly\n6. For multi-document transactions, ensure consistent terminology and cross-references across all documents\n\n## Documents System\n\nThe platform includes a generic document management system for any type of legal document. Documents are owner-scoped and can optionally be linked to a DD room.\n\n### Schema (`documents` table)\n\n| Column | Type | Description |\n\n|--------|------|-------------|\n\n| `id` | text (UUID) | Primary key |\n\n| `ownerId` | text | Clerk user ID of the document owner |\n\n| `title` | varchar(500) | Document title |\n\n| `documentType` | varchar(100) | Flexible type field (e.g., \"LOI\", \"NDA\", \"APA\", \"Employment Agreement\", \"Lease\") |\n\n| `content` | text | Full document content (Markdown\u002Fplain text) |\n\n| `status` | varchar(50) | Document status, default \"draft\" |\n\n| `ddRoomId` | text | Optional link to a DD room |\n\n| `createdAt` | timestamp | Auto-set on creation |\n\n| `updatedAt` | timestamp | Auto-set on creation and update |\n\n### Key Design Principles\n\n- **Type-agnostic:** The `documentType` field is a free-text string, not an enum. Any document type can be stored — LOIs, NDAs, asset purchase agreements, operating agreements, board resolutions, etc.\n- **Owner-scoped:** All document endpoints filter by the authenticated user's `ownerId`. Users can only see, edit, and delete their own documents.\n\n- **Room linkable:** Documents can optionally reference a `ddRoomId` to associate them with a due diligence room (e.g., the LOI for an acquisition).\n\n### API Endpoints\n\n| Method | Path | Description |\n\n|--------|------|-------------|\n\n| GET | `\u002Fdocuments` | List all documents owned by the current user |\n\n| GET | `\u002Fdocuments\u002F:documentId` | Get a single document (owner-only) |\n\n| DELETE | `\u002Fdocuments\u002F:documentId` | Delete a document (owner-only) |\n\n### Frontend\n\n- **Dashboard:** Document cards appear below the DD rooms section. Each card shows title, type badge, status, and creation date. Hovering reveals a delete button with inline confirm\u002Fcancel.\n- **Document view:** `\u002Fdocuments\u002F:documentId` renders the full document content.\n\n## Due Diligence Room Platform\n\nThe legal platform includes an interactive Due Diligence (DD) room for M&A transactions. This is a full-stack feature with its own database schema, API endpoints, and React UI.\n\n### Architecture\n\n- **Frontend:** `artifacts\u002Flegal-platform\u002Fsrc\u002Fpages\u002Fdd-room.tsx` — React + shadcn\u002Fui\n- **API:** `artifacts\u002Fapi-server\u002Fsrc\u002Froutes\u002Fdd-*.ts` — Express REST endpoints\n\n- **DB:** PostgreSQL via Drizzle ORM — tables in `lib\u002Fdb\u002Fsrc\u002Fschema\u002Fdd-*.ts`\n- **Auth:** Clerk; middleware at `artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireAuth.ts`\n\n- **Room Auth:** `artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireRoomAccess.ts` — room-level authorization\n- **File Storage:** Replit Object Storage via `@google-cloud\u002Fstorage`\n\n- **OpenAPI:** `lib\u002Fapi-spec\u002Fopenapi.yaml`with codegen to`@workspace\u002Fapi-client-react`and`@workspace\u002Fapi-zod`\n\n### Database Tables\n\n| Table | Purpose |\n\n|-------|---------|\n\n| `dd_rooms` | Room metadata: name, buyer\u002Fseller, purchase price, deal structure, ownerId |\n\n| `dd_categories` | Checklist categories (8 auto-created from template, plus custom) |\n\n| `dd_items` | Individual checklist items with status tracking |\n\n| `dd_files` | Uploaded documents linked to items (object storage paths) |\n\n| `dd_comments` | Item-level discussion threads |\n\n| `dd_activity` | Audit log of all actions |\n\n| `dd_participants` | Room access control (email + role: viewer\u002Fcontributor\u002Fadmin) |\n\n### Standard Checklist Template\n\nWhen a room is created, 8 categories with 57 items are auto-populated from `DD_TEMPLATE`in`dd-rooms.ts`:\n\n1. **Corporate & Organizational** (7 items) — Formation docs, bylaws, minutes, cap table, good standing, org chart, jurisdictions\n2. **Financial** (8 items) — Audited\u002Finterim statements, tax returns, debt schedule, AR\u002FAP aging, revenue breakdown, projections, bank accounts\n\n3. **Contracts & Agreements** (7 items) — Customer\u002Fvendor\u002Fpartnership\u002Fdistribution\u002Ffranchise\u002Fgovernment contracts, change-of-control provisions\n4. **Intellectual Property** (8 items) — Patents, trademarks, copyrights, domains, software licenses, IP assignments, open-source audit, trade secrets\n\n5. **Employees & Benefits** (9 items) — Census, employment agreements, contractors, handbook, non-competes, benefits, stock options, workers' comp, OSHA\n6. **Litigation & Legal** (6 items) — Pending litigation, settlements, consent decrees, investigations, insurance claims, regulator correspondence\n\n7. **Insurance** (4 items) — All policies, claims history, broker info, certificates\n8. **Technology & Data** (8 items) — Architecture docs, data flows, SOC 2, breach history, BCP\u002FDR, SLA reports, vendor assessments, privacy policy\n\nCustom categories and items can be added per-room via the API.\n\n### Item Status Workflow\n\nItems track progress through these statuses:\n\n```text\n\nnot_started → uploaded → under_review → approved\n\n→ flagged (with note)\n\n```\n\n#### Automatic transitions\n\n- Uploading a file to a `not_started`item changes its status to`uploaded`\n- Deleting all files from an `uploaded`item reverts its status to`not_started`\n\n- All other transitions (under_review, approved, flagged) are manual via the UI\n\n### Access Control\n\nRoom-level authorization is enforced via `requireRoomAccess`middleware (`artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireRoomAccess.ts`) and its variants. Each variant looks up the resource chain to find the parent room, then checks if the user is the room owner or an active participant.\n\n| Middleware | Lookup Chain | Used On |\n\n|-----------|-------------|---------|\n\n| `requireRoomAccess(roomIdParam)` | Direct roomId | Room detail, update, stats, activity, participants, categories |\n\n| `requireCategoryRoomAccess(categoryIdParam)` | category → room | Delete category, create items |\n\n| `requireItemRoomAccess(itemIdParam)` | item → category → room | Update\u002Fdelete items, list\u002Fcreate files, list\u002Fcreate comments |\n\n| `requireFileRoomAccess(fileIdParam)` | file → item → category → room | Delete files |\n\n| `requireCommentRoomAccess(commentIdParam)` | comment → item → category → room | Delete comments |\n\n#### Privilege levels\n\n- **Room owner:** Full access to everything including participant management\n- **Admin participant:** Can manage participants (add\u002Fremove) and all room content\n\n- **Contributor\u002FViewer participant:** Can access room content but cannot manage participants\n- **Non-participant:** Receives 403 on all room-scoped endpoints\n\nThe `GET \u002Fdd-rooms` listing only returns rooms where the user is owner or participant (no cross-tenant leakage).\n\nPrivate file downloads (`GET \u002Fstorage\u002Fobjects\u002F*`) also enforce room access by looking up the file's parent room through the`dd_files → dd_items → dd_categories` chain.\n\n### Activity Feed Events\n\nAll significant actions are logged to `dd_activity` with the following event types:\n\n| Action | Trigger |\n\n|--------|---------|\n\n| `file_uploaded` | File registered on an item |\n\n| `file_deleted` | File removed from an item |\n\n| `comment_deleted` | Comment removed from an item |\n\n| `participant_removed` | Participant removed from room |\n\n| `status_changed` | Item status updated |\n\nEach activity entry records: `roomId`,`userId`,`userName`,`itemId`(optional),`action`,`details`,`createdAt`.\n\n### File Upload Flow\n\n1. Frontend requests presigned upload URL via `POST \u002Fapi\u002Fstorage\u002Fuploads\u002Frequest-url` (sends file name, size, contentType as JSON)\n2. Frontend uploads file directly to object storage using the presigned URL (PUT to GCS)\n\n3. Frontend registers the file via `POST \u002Fapi\u002Fdd-items\u002F:itemId\u002Ffiles` with the returned storage URL\n4. Backend normalizes the GCS URL to an object entity path (`\u002Fobjects\u002F\u003CentityId>`) and validates:\n\n- URL must normalize to `\u002Fobjects\u002F` prefix format\n- URL must not already be registered (prevents duplicate registration \u002F IDOR)\n\n1. File downloads served via `GET \u002Fapi\u002Fstorage\u002Fobjects\u002F*path` with room-level authorization\n\n### API Endpoints (2)\n\n| Method | Path | Auth | Description |\n\n|--------|------|------|-------------|\n\n| GET | `\u002Fdd-rooms` | requireAuth | List rooms (filtered by owner\u002Fparticipant) |\n\n| POST | `\u002Fdd-rooms` | requireAuth | Create a new DD room (auto-populates 8 categories) |\n\n| GET | `\u002Fdd-rooms\u002F:roomId` | requireAuth + roomAccess | Get room with categories and items |\n\n| PUT | `\u002Fdd-rooms\u002F:roomId` | requireAuth + roomAccess | Update room metadata |\n\n| POST | `\u002Fdd-rooms\u002F:roomId\u002Fcategories` | requireAuth + roomAccess | Add a custom category |\n\n| DELETE | `\u002Fdd-categories\u002F:categoryId` | requireAuth + categoryRoomAccess | Delete a category and its items |\n\n| POST | `\u002Fdd-categories\u002F:categoryId\u002Fitems` | requireAuth + categoryRoomAccess | Add an item to a category |\n\n| PUT | `\u002Fdd-items\u002F:itemId` | requireAuth + itemRoomAccess | Update item (name, status, notes) |\n\n| DELETE | `\u002Fdd-items\u002F:itemId` | requireAuth + itemRoomAccess | Delete an item |\n\n| GET | `\u002Fdd-items\u002F:itemId\u002Ffiles` | requireAuth + itemRoomAccess | List files for an item |\n\n| POST | `\u002Fdd-items\u002F:itemId\u002Ffiles` | requireAuth + itemRoomAccess | Register an uploaded file |\n\n| DELETE | `\u002Fdd-files\u002F:fileId` | requireAuth + fileRoomAccess | Delete a file |\n\n| GET | `\u002Fdd-items\u002F:itemId\u002Fcomments` | requireAuth + itemRoomAccess | List comments for an item |\n\n| POST | `\u002Fdd-items\u002F:itemId\u002Fcomments` | requireAuth + itemRoomAccess | Add a comment |\n\n| DELETE | `\u002Fdd-comments\u002F:commentId` | requireAuth + commentRoomAccess | Delete a comment |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Fstats` | requireAuth + roomAccess | Get completion statistics |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Factivity` | requireAuth + roomAccess | Get activity feed |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Fparticipants` | requireAuth + roomAccess | List participants |\n\n| POST | `\u002Fdd-rooms\u002F:roomId\u002Fparticipants` | requireAuth + roomAccess (owner\u002Fadmin) | Add a participant |\n\n| DELETE | `\u002Fdd-participants\u002F:participantId` | requireAuth + roomAccess (owner\u002Fadmin) | Remove a participant |\n\n| POST | `\u002Fstorage\u002Fuploads\u002Frequest-url` | requireAuth | Get presigned upload URL |\n\n| GET | `\u002Fstorage\u002Fobjects\u002F*` | requireAuth + fileRoomAccess | Download a file |\n\n## Limitations\n\n- NOT a substitute for legal advice from a licensed attorney\n- Cannot account for jurisdiction-specific laws\n\n- Cannot verify legal enforceability of any clause\n- Cannot handle litigation, regulatory filings, or court documents\n\n- Templates are starting points, not final legal documents\n","# Legal Contract Assistant\n\n## OpenClawd Operator Adaptation\n\nRun this skill as part of the OpenClawd operator deck. Preserve the skill-specific workflow below, but frame outputs for Solana-native agents when relevant: prefer OpenClawd language, note whether the work can support autonomous agent operations, and keep financial, legal, tax, hiring, medical, or other regulated outputs informational unless the skill already requires a stricter disclaimer. Use the Llobster Legend persona only as light operator framing; do not let branding override accuracy, safety, or the user's stated domain.\n\n\nFull-stack legal platform with three core capabilities: (1) draft and review any type of legal document — NDAs, service agreements, LOIs, purchase agreements, privacy policies, terms of service, and more; (2) manage documents on a dashboard with owner-scoped access; (3) run interactive due diligence rooms for M&A transactions with file uploads, status tracking, comments, participant access control, and activity logging.\n\n## IMPORTANT DISCLAIMER: This provides general information and templates only. It does NOT constitute legal advice. Always consult a qualified attorney for legal matters\n\n## Platform Capabilities\n\nThis skill powers a full legal platform with three major capability areas. When the user arrives, guide them to the right capability based on their need:\n\n### 1. Document Drafting & Review\n\nGenerate any type of legal document from templates and review existing contracts for red flags.\n\n#### What users can do\n\n- Draft NDAs, service agreements, freelancer contracts, LOIs, term sheets, asset\u002Fstock purchase agreements, operating agreements, board resolutions, leases, privacy policies, terms of service — or any other legal document type\n- Review contracts they've received and get a plain-language analysis with flagged risks\n\n- Generate multi-document packages for transactions (e.g., LOI + NDA for an acquisition)\n- Export documents as PDF and DOCX for signing and redlining\n\n##### How it works\n\n1. User describes the document they need or pastes a contract for review\n2. For drafting: start from open-source templates (Bonterms\u002FCommon Paper for NDAs\u002Fservice agreements) or standard clause structures (for M&A documents). See \"Open-Source Template Libraries\" and \"M&A \u002F Transaction Documents\" sections below.\n\n3. For reviews: run the red-flag checklist and playbook checks, then output using the \"Review Output Format\"\n4. Store the document in the platform via the Documents System (any `documentType` string — the system is type-agnostic)\n\n5. Deliver PDF + DOCX exports using the generation pipeline in \"Output: Always Produce PDF & DOCX\"\n\n### 2. Document Management (Dashboard)\n\nStore, organize, and manage all legal documents with owner-scoped access.\n\n#### What users can do (2)\n\n- View all their documents on the dashboard with type badges and status indicators\n- Open any document to view its full content\n\n- Delete documents they no longer need (with confirmation)\n- Link documents to DD rooms for transaction context\n\n##### How it works (2)\n\n- Documents are stored in the `documents`table with a flexible`documentType` field — supports any type, not just LOIs\n- All access is owner-scoped: users only see their own documents\n\n- See the \"Documents System\" section below for schema and API details\n\n### 3. Due Diligence Rooms\n\nInteractive workspaces for managing M&A due diligence checklists with file uploads, comments, and team collaboration.\n\n#### What users can do (3)\n\n- Create DD rooms pre-populated with 8 standard M&A categories and 57 checklist items\n- Add custom categories and items beyond the standard template\n\n- Upload files against checklist items (directly to object storage via presigned URLs)\n- Download uploaded files with room-level authorization\n\n- Track item status through the workflow: not*started → uploaded → under*review → approved\u002Fflagged\n- Comment on items for team discussion\n\n- Invite participants by email with role-based access (viewer, contributor, admin)\n- Monitor progress via per-category and overall completion statistics\n\n- Review a full activity feed of all room actions\n\n##### How it works (3)\n\n- Room creation auto-populates from the `DD_TEMPLATE`in`dd-rooms.ts`\n- All routes are protected by room-level access control middleware\n\n- Files go through a presigned URL upload flow (request URL → upload to storage → register in DB)\n- See the \"Due Diligence Room Platform\" section below for full architecture and API details\n\n## When to Use\n\n- User needs any type of legal document drafted — NDA, service agreement, freelancer contract, consulting agreement, partnership agreement, operating agreement, LLC agreement, board resolution, employment agreement, offer letter, non-compete, non-solicitation agreement, equity\u002Fstock option agreement, SLA, DPA, or any other contract\n- User needs a Letter of Intent (LOI), term sheet, earnout agreement, or asset\u002Fstock purchase agreement\n\n- User wants a plain-language review of a contract they received (\"review this contract\", \"what does this clause mean\", \"help me understand this agreement\", \"is this contract fair\")\n- User needs to understand specific legal terms or clauses\n\n- User wants a lease or rental agreement reviewed for red flags\n- User needs multiple related transaction documents (e.g., LOI + NDA for an acquisition)\n\n- User needs a Privacy Policy or Terms of Service for a web app or SaaS product\n- User asks to \"draft a contract\", \"write me a contract\", or \"create an agreement\"\n\n- User wants to manage and organize their legal documents on a dashboard\n- User needs to set up or work within a due diligence room, data room, or deal room for an M&A transaction\n\n- User wants an M&A checklist, acquisition checklist, or due diligence checklist\n- User wants to upload, track, or review due diligence documents with a team\n\n## When NOT to Use\n\n- Complex litigation or regulatory compliance\n- Employment law disputes\n\n- International trade agreements\n- Anything involving criminal law\n\n- Situations requiring jurisdiction-specific legal analysis\n\n## Open-Source Template Libraries (Use These First)\n\n**Never draft from scratch.** Start from committee-vetted open-source agreements released under CC BY 4.0:\n\n| Source | Documents | Style | Get it |\n\n|--------|-----------|-------|--------|\n\n| **Bonterms** | Mutual NDA, Cloud Terms (SaaS), SLA, DPA, PSA, AI Standard Clauses | US; \"cover page + standard terms\" | `github.com\u002FBonterms` |\n\n| **Common Paper** | Mutual NDA, Cloud Service Agreement, DPA, Design Partner Agreement | US; standards committee of 40+ attorneys | `commonpaper.com\u002Fstandards` |\n\n| **oneNDA** | NDA (777 words), oneDPA | UK\u002FEU; strict variable-only edits | `onenda.org` |\n\n**Workflow:** `webFetch(\"https:\u002F\u002Fbonterms.com\u002Fforms\u002Fmutual-nda\u002F\")` → extract the standard terms → build a cover page with the user's deal-specific variables (parties, effective date, term, governing law, jurisdiction). Don't modify the body; that's the whole point of standards.\n\n**Note:** These libraries cover NDAs and SaaS\u002Fservice agreements well, but do not include M&A documents (LOIs, term sheets, purchase agreements). For those document types, draft using the standard clause structures in the \"M&A \u002F Transaction Documents\" section below.\n\n## M&A \u002F Transaction Documents\n\nWhen a user needs documents for buying\u002Fselling a business, these are the common document types and their standard clause structures:\n\n### Letter of Intent (LOI)\n\nStandard sections for an LOI:\n\n1. **Transaction Structure** — asset purchase vs. stock\u002Fequity purchase\n2. **Purchase Price** — total price, payment structure (cash at closing, earnout, seller financing, escrow holdback)\n\n3. **Earnout provisions** — if applicable: percentage, performance milestones, measurement period, payment schedule\n4. **Due Diligence** — period length (typically 30-60 days), scope, access to records, extension rights\n\n5. **Exclusivity \u002F No-Shop** — period length (typically 60-90 days), binding on seller\n6. **Closing Timeline** — target closing date\n\n7. **Conditions to Closing** — due diligence completion, definitive agreement, reps & warranties accuracy, third-party consents, no MAE, ancillary agreements\n8. **Representations and Warranties** — reference to customary reps in definitive agreement\n\n9. **Confidentiality** — binding obligation\n10. **Expenses** — each party bears own costs; binding\n\n11. **Non-Binding Nature** — clearly state which sections ARE binding (typically: exclusivity, confidentiality, expenses, non-binding clause itself) and which are non-binding\n12. **Governing Law** — leave as fill-in-the-blank for jurisdiction\n\n13. **Expiration** — LOI expires if not signed within X days (typically 10-15)\n\n**Key variables to collect from user:** buyer name, seller\u002Ftarget name, purchase price, deal structure (asset vs. stock), due diligence period, exclusivity period, closing timeline, earnout terms (if any).\n\n### Mutual NDA (Transaction-Specific)\n\nWhen drafting an NDA for a specific transaction (vs. a general-purpose NDA), include these additional elements:\n\n- **WHEREAS clauses** that reference the specific transaction and any related LOI\n- **Permitted Purpose** scoped specifically to evaluating\u002Fnegotiating the transaction\n\n- **Non-Solicitation** of the other party's employees (typically 12 months)\n- **No Obligation to Proceed** — neither party is obligated to complete the transaction\n\n- Cross-reference the LOI or term sheet by name in the recitals\n\nStandard NDA sections: definition of confidential information, exclusions, receiving party obligations, no license\u002Fwarranty, return\u002Fdestruction, term (typically 2 years), remedies (injunctive relief), governing law, miscellaneous (entire agreement, amendments, assignment, severability, waiver, counterparts, notices).\n\n### Multi-Document Transactions\n\nWhen a transaction requires multiple related documents (e.g., LOI + NDA):\n\n1. **Maintain consistent definitions** — party names, defined terms (\"Transaction,\" \"Business,\" \"Purchased Assets\"), and entity references must match across all documents\n2. **Cross-reference between documents** — the NDA should reference the LOI in its recitals; the LOI's confidentiality section should note that a separate NDA governs\n\n3. **Align timelines** — the NDA's term should cover at least the LOI's exclusivity + due diligence + closing periods\n4. **Use the same governing law** placeholder in all documents\n\n5. **Draft and present together** — generate all documents in a single session so the user has a complete package\n\n## Privacy Policy & Terms of Service (Web Apps \u002F SaaS)\n\nPrivacy Policies and Terms of Service are among the most common legal documents a web app needs. They are not contracts between two parties — they are public-facing declarations. Treat them as a separate document type from the contract\u002FNDA\u002FLOI workflow.\n\n### Key questions to ask before drafting\n\n1. **Legal entity name** — Always ask for the exact registered legal name separately from the brand name. The brand is what users see (\"NiDO\"); the legal entity is what appears in formal documents (\"NiDO Finanzas S.A.S.\"). Never assume they are the same.\n2. **Country of incorporation** — Determines which data protection law applies (GDPR for EU, LGPD for Brazil, Ley 172-13 for Dominican Republic, CCPA for California, etc.).\n\n3. **What data is collected** — Account info (name, email), financial\u002Ftransactional data, uploaded files, usage\u002Fanalytics?\n4. **Third-party data processors** — Ask the user to enumerate every service that touches user data: auth provider, database host, AI\u002FML services, payment processor, analytics, email provider, CDN. Each must be disclosed in the Privacy Policy.\n\n5. **Are there paid plans?** — If yes, the Terms must cover payment terms, auto-renewal, cancellation, and refund policy.\n6. **Minimum age** — Typically 18 for financial apps, 13 for general consumer apps.\n\n7. **Contact email for privacy\u002Flegal** — Often different from the support email. Ask explicitly.\n\n### Third-party processor disclosure pattern\n\nFor every integration the app uses, include a line in the Privacy Policy. Format:\n\n```text\n\n- **[Provider] ([function]):** [What they receive and why]. [Link to their privacy policy if possible.]\n\n```\n\nExample:\n\n```text\n\n- **Neon (base de datos):** almacenamiento seguro de sus datos financieros en servidores PostgreSQL.\n- **Google Gemini (IA):** genera categorías y análisis. Solo recibe descripciones de transacciones; nunca datos personales identificables.\n\n- **Stripe (pagos):** procesa pagos con tarjeta. NiDO no almacena datos de tarjetas.\n- **Replit Auth (autenticación):** gestiona el inicio de sesión vía Google\u002FGitHub.\n\n```\n\nIf the app uses analytics, advertising pixels, or session recording (Hotjar, FullStory, etc.), these MUST be disclosed and typically require explicit consent in GDPR jurisdictions.\n\n### Privacy Policy required sections\n\n1. Who we are (legal entity name, contact email for privacy)\n2. What data we collect (account info, user-generated data, uploaded files, usage logs)\n\n3. How we use it (provide service, personalization, legal compliance)\n4. Third-party processors (enumerate all — see above)\n\n5. Data storage and security (encryption at rest\u002Fin transit, access controls)\n6. User rights (access, correction, deletion, export)\n\n7. Cookies (session-only vs. tracking; consent requirements if in GDPR territory)\n8. Minors (minimum age, what happens if a minor's data is discovered)\n\n9. Changes to the policy (notice method and timing — typically 15–30 days)\n10. Governing law (jurisdiction's data protection statute)\n\n### Terms of Service required sections\n\n1. Acceptance (clicking\u002Fusing = agreement)\n2. Service description (what it does and does NOT do)\n\n3. Account registration (age requirement, accurate info, responsibility for activity)\n4. Acceptable use (prohibited behaviors: fraud, scraping, reverse engineering, illegal activity)\n\n5. **Financial\u002Fmedical disclaimer** — if the app gives any advice-like output (budget suggestions, AI analysis), include an explicit \"not financial\u002Flegal\u002Fmedical advice\" clause\n6. User data ownership (user owns their data; limited license to operator to run the service)\n\n7. Payments (if applicable: billing cycle, auto-renewal, cancellation, refunds, payment processor)\n8. Service availability (no uptime guarantee unless SLA offered)\n\n9. Limitation of liability (cap at fees paid in last 12 months or a fixed floor like $100)\n10. IP ownership (brand, code, design belong to the operator)\n\n11. Termination (user can delete account; operator can suspend for violations; data deletion timeline)\n12. Changes to terms (notice period — typically 15 days for material changes)\n\n13. Governing law and jurisdiction\n\n### Delivery format for web apps — routed pages, not PDFs\n\nFor web apps, the best delivery format for Privacy Policy and Terms of Service is **routed pages within the app itself**, not PDFs or DOCX files. This is the standard for all modern SaaS products.\n\n#### Pattern\n\n- Create `client\u002Fsrc\u002Fpages\u002FPrivacy.tsx`and`client\u002Fsrc\u002Fpages\u002FTerms.tsx`\n- Register them as **public routes**— accessible without authentication. Place the route check**before** the auth loading state in `AppContent`:\n\n```tsx\n\nfunction AppContent() {\n\nconst { isLoading, isAuthenticated } = useAuth();\n\nconst [location] = useLocation();\n\n\u002F\u002F Public legal pages — always accessible, no auth required\n\nif (location === \"\u002Fprivacidad\") return \u003CPrivacy \u002F>;\n\nif (location === \"\u002Fterminos\") return \u003CTerms \u002F>;\n\n\u002F\u002F Auth guard below\n\nif (isLoading) return \u003CLoadingScreen \u002F>;\n\nreturn isAuthenticated ? \u003CAuthenticatedLayout \u002F> : \u003CLanding \u002F>;\n\n}\n\n```\n\n##### Page layout pattern\n\n- Minimal header: logo + \"Back to home\" link\n- Amber disclaimer banner at the top: *\"Este documento es una plantilla informativa y no constituye asesoramiento legal.\"*\n\n- Clean `max-w-3xl mx-auto`prose layout,`text-sm leading-relaxed`\n- Footer with cross-links: Privacy ↔ Terms ↔ Contact ↔ Home\n\n- No sidebar, no app navigation — these are public documents\n\n**After creating the pages, always update the footer links** in the landing page or marketing page. Footer links that point to `href=\"#\"`are broken. Replace with`href=\"\u002Fprivacidad\"`and`href=\"\u002Fterminos\"`, and change the \"Contact\" link to`mailto:` rather than another dead hash.\n\n**Consistency check after any company name change:** If the user changes the legal entity name, search ALL files — not just the legal pages. Invoice templates, billing pages, and email footers often also contain the company name and will need updating too.\n\n### Disclaimer banner (always include on the rendered page)\n\nEvery rendered legal page should display a visible disclaimer. Do not only warn the user in chat — put it on the page itself:\n\n```tsx\n\n\u003Cdiv className=\"bg-amber-50 dark:bg-amber-950\u002F30 border border-amber-200 dark:border-amber-800 rounded-md px-4 py-3 mb-10 text-sm text-amber-800 dark:text-amber-300\">\n\nEste documento es una plantilla informativa y no constituye asesoramiento legal.\n\nConsulte un abogado calificado para asuntos legales específicos.\n\n\u003C\u002Fdiv>\n\n```\n\n## Red-Flag Language to Grep For\n\nWhen reviewing, search the document text for these exact phrases — each is a known risk pattern:\n\n| Phrase | Why it's dangerous | Suggested fix |\n\n|--------|-------------------|---------------|\n\n| `\"any and all claims\"` | Unlimited indemnity scope | \"claims arising directly from [Party]'s breach of Section X\" |\n\n| `\"indemnify, defend, and hold harmless\"` | \"Hold harmless\" blocks your counterclaims even if they caused the loss | Strike \"and hold harmless\"; keep \"indemnify and defend\" |\n\n| `\"sole discretion\"`\u002F`\"absolute discretion\"` | One party can act arbitrarily (block settlements, reject deliverables) | \"consent not to be unreasonably withheld, conditioned, or delayed\" |\n\n| `\"including but not limited to\"` in IP assignment | Open-ended IP grab beyond deliverables | Enumerate specific deliverables; add \"excluding pre-existing IP\" |\n\n| No liability cap stated | Courts default to **unlimited** liability | \"Aggregate liability capped at fees paid in the 12 months preceding the claim\" |\n\n| `\"time is of the essence\"` | Any delay = material breach | Delete, or limit to payment obligations only |\n\n| Indemnity **carved out** of liability cap | Your cap doesn't protect you where exposure is highest | \"Indemnification obligations are subject to the cap in Section X\" |\n\n| Auto-renewal with \u003C30-day opt-out window | Easy to miss; locked in another term | 60–90 day notice window; email notice permitted |\n\n| `\"perpetual\"`+`\"irrevocable\"` license | Can never be revoked even after breach | Term-limited; terminable on material breach |\n\n**Indemnity forms (escalating risk):** *Limited*= you cover only your own negligence.*Intermediate*= everything except their sole negligence.*Broad* = you cover losses **even when caused entirely by them**. Flag intermediate and broad as Critical.\n\n## Playbook Checks (What Harvey\u002FSpellbook Actually Run)\n\nAI contract tools run a fixed checklist per document type. For a **Service Agreement** run these checks and grade each Pass\u002FFlag\u002FMissing:\n\n1. Is there a liability cap? Is it mutual? Is it tied to fees paid (1x, 2x)?\n2. Is indemnity mutual or one-way? Subject to the cap or carved out?\n\n3. Does IP assignment exclude contractor's pre-existing tools\u002Flibraries?\n4. Is there a cure period (typically 30 days) before termination for breach?\n\n5. Are \"consequential damages\" (lost profits, lost data) excluded? Mutually?\n6. Payment terms: Net 30 or better? Late fee specified?\n\n7. Can the client terminate for convenience? If so, is there a kill fee?\n8. Governing law + venue: neutral, or the other party's home court?\n\nFor a **Letter of Intent** run these checks:\n\n1. Are binding vs. non-binding sections clearly identified?\n2. Is there an exclusivity\u002Fno-shop clause? Is it binding?\n\n3. Is the purchase price clearly stated with payment structure?\n4. Is the due diligence period defined with access rights?\n\n5. Are conditions to closing enumerated?\n6. Is there a confidentiality obligation (binding)?\n\n7. Does the LOI have an expiration date?\n8. If there's an earnout, are the metrics and measurement methodology specified (or deferred to the definitive agreement)?\n\n## Review Output Format\n\n```text\n\n# Contract Review: [Document Type]\n\n**NOT LEGAL ADVICE — for informational purposes only. Consult an attorney before signing.**\n\n## Summary\n\n[2–3 sentences: what this is, who it favors, biggest concern]\n\n## Critical — Do Not Sign Without Addressing\n\n1. **[Clause §X.Y]**: [quote the exact language]\n\n- **Risk**: [plain English]\n- **Suggested redline**: \"[replacement text]\"\n\n## Warnings — Negotiate If You Have Leverage\n\n## Notes — Standard But Be Aware\n\n## Missing Protections\n\n[clauses that should be here but aren't — e.g., no liability cap, no cure period]\n\n## Overall: [Fair \u002F Favors Counterparty \u002F Consult Attorney Before Signing]\n\n```\n\n## Output: Always Produce PDF & DOCX\n\n**Every drafted contract MUST be delivered as both a PDF and a DOCX file.** Clients need PDF for signing and DOCX for redlining — always provide both.\n\n### Architecture: React + Vite → Puppeteer PDF + python-docx DOCX\n\nBuild the contract as a React web artifact first (source of truth for layout), then export:\n\n#### PDF via Puppeteer\n\nInstall `puppeteer-core`in the`scripts`package:`pnpm --filter @workspace\u002Fscripts add puppeteer-core`\n\n```typescript\n\n\u002F\u002F scripts\u002Fsrc\u002Fgenerate-contract.ts\n\nimport puppeteer from 'puppeteer-core';\n\n\u002F\u002F Find Chromium — pick the latest version from the list:\n\n\u002F\u002F ls \u002Fnix\u002Fstore\u002F*chromium*\u002Fbin\u002Fchromium | sort -V | tail -1\n\nconst CHROMIUM_PATH = \"\u002Fnix\u002Fstore\u002FFIND_LATEST_PATH\u002Fbin\u002Fchromium\";\n\n\u002F\u002F Use the artifact's actual URL, not localhost\n\nconst CONTRACT_URL = `https:\u002F\u002F${process.env.REPLIT_DEV_DOMAIN}\u002FARTIFACT-ROUTE`;\n\nconst browser = await puppeteer.launch({\n\nexecutablePath: CHROMIUM_PATH,\n\nheadless: true,\n\nargs: ['--no-sandbox', '--disable-setuid-sandbox'],\n\n});\n\nconst page = await browser.newPage();\n\nawait page.setViewport({ width: 816, height: 1056 }); \u002F\u002F Match page container dimensions\n\nawait page.goto(CONTRACT_URL, { waitUntil: 'networkidle0' });\n\n\u002F\u002F IMPORTANT: Set document.title for correct PDF metadata title.\n\n\u002F\u002F Without this, the PDF viewer title bar shows the HTML \u003Ctitle> from index.html,\n\n\u002F\u002F which may be wrong when generating multiple documents from the same app.\n\nawait page.evaluate(() => { document.title = \"Your Document Title Here\"; });\n\nawait page.pdf({\n\npath: 'contract.pdf',\n\nformat: 'Letter',\n\nprintBackground: true,\n\n\u002F\u002F IMPORTANT: Use zero margins — the page containers already include internal padding.\n\n\u002F\u002F Non-zero Puppeteer margins + fixed-height containers = blank overflow pages.\n\nmargin: { top: '0', bottom: '0', left: '0', right: '0' },\n\n});\n\nawait browser.close();\n\n```\n\nAdd a script entry in `scripts\u002Fpackage.json`:`\"generate-contract\": \"tsx .\u002Fsrc\u002Fgenerate-contract.ts\"`\n\nRun via: `pnpm --filter @workspace\u002Fscripts run generate-contract`\n\n##### DOCX via python-docx\n\nPython may not be available via `pip`in the Replit environment. Use`nix-shell`to get`python-docx`:\n\n```bash\n\nnix-shell -p python3Packages.python-docx --run \"python3 scripts\u002Fsrc\u002Fgenerate-contract.py\"\n\n```\n\n```python\n\n# scripts\u002Fsrc\u002Fgenerate-contract.py\n\nfrom docx import Document\n\nfrom docx.shared import Pt, Inches, RGBColor\n\nfrom docx.enum.text import WD_ALIGN_PARAGRAPH\n\ndoc = Document()\n\n# Set default font\n\nstyle = doc.styles['Normal']\n\nfont = style.font\n\nfont.name = 'Times New Roman'\n\nfont.size = Pt(12)\n\n# Set margins\n\nfor section in doc.sections:\n\nsection.top_margin = Inches(1)\n\nsection.bottom_margin = Inches(1)\n\nsection.left_margin = Inches(1.25)\n\nsection.right_margin = Inches(1.25)\n\n# Title\n\ntitle = doc.add_paragraph()\n\ntitle.alignment = WD_ALIGN_PARAGRAPH.CENTER\n\nrun = title.add_run('DOCUMENT TITLE')\n\nrun.bold = True\n\nrun.font.size = Pt(18)\n\n# Preamble\n\ndoc.add_paragraph(\n\n'This Agreement is entered into as of [DATE] by and between:'\n\n)\n\n# Parties table\n\ntable = doc.add_table(rows=1, cols=2)\n\ntable.style = 'Table Grid'\n\n# ... populate with party details\n\n# Sections with numbered clauses\n\nheading = doc.add_paragraph()\n\nrun = heading.add_run('1. Section Title')\n\nrun.bold = True\n\ndoc.add_paragraph('Section body text...')\n\n# Signature block\n\nsig_table = doc.add_table(rows=5, cols=2)\n\n# Row 0: labels (BUYER \u002F SELLER)\n\n# Rows 1-4: Signature, Printed Name, Title, Date lines\n\ndoc.save('contract.docx')\n\n```\n\n### Styling for Legal Documents\n\n- **Font**: Times New Roman 12pt (standard for legal docs) or similar serif\n- **Margins**: 1\" top\u002Fbottom, 1.25\" left\u002Fright\n\n- **Line spacing**: 1.5 or double-spaced (jurisdiction dependent)\n- **Section numbering**: Use hierarchical numbering (1, 1.1, 1.1.1)\n\n- **Page numbers**: Bottom center, \"Page X of Y\"\n- **Headers**: Document title and date on each page\n\n- **Signature blocks**: Two-column layout with lines for signature, printed name, title, date\n\n### Page-Aware Layout (Preventing Blank PDF Pages)\n\nUse fixed-height page containers that map 1:1 to physical letter pages. This ensures content stays within page boundaries on screen and in PDF output.\n\n#### Page container constants (letter size at 96 DPI)\n\n- `PAGE_W = \"816px\"` (8.5 inches)\n- `PAGE_H = \"1056px\"` (11 inches)\n\n- Internal padding: `48px`top\u002Fbottom,`72px` left\u002Fright\n\n##### Page container component pattern\n\n```tsx\n\n\u003Cdiv\n\nclassName=\"page-container mx-auto bg-white shadow-lg print:shadow-none mb-8 print:mb-0 flex flex-col overflow-hidden\"\n\nstyle={{\n\nwidth: PAGE_W,\n\nheight: PAGE_H,\n\npageBreakAfter: pageNum \u003C TOTAL_PAGES ? \"always\" : undefined,\n\nbreakAfter: pageNum \u003C TOTAL_PAGES ? \"page\" : undefined,\n\n}}\n\n>\n\n{\u002F* Page header with \"Page X of Y\" *\u002F}\n\n{\u002F* Content area with internal padding *\u002F}\n\n\u003C\u002Fdiv>\n\n```\n\n###### Critical CSS for print\u002FPDF — add to your global stylesheet\n\n```css\n\n@page {\n\nsize: letter;\n\nmargin: 0;\n\n}\n\n@media print {\n\nhtml, body {\n\nmargin: 0 !important;\n\npadding: 0 !important;\n\nbackground: white !important;\n\n}\n\n.page-container {\n\nbox-shadow: none !important;\n\nmargin: 0 !important;\n\n}\n\n}\n\n```\n\n**Why blank pages happen:** If Puppeteer adds its own margins (e.g., `margin: { top: \"0.5in\" }`) on top of 1056px containers, each container exceeds the physical page height. The overflow creates a blank page before the next`breakAfter: \"page\"`fires. The fix: always use`margin: { top: \"0\", bottom: \"0\", left: \"0\", right: \"0\" }`in Puppeteer and`@page { margin: 0 }` in CSS, since the page containers already include their own internal padding.\n\n**Do NOT override `height: auto` in print media** — removing the fixed height lets containers expand beyond one page, defeating the 1:1 page mapping. Keep the fixed height; the CSS page breaks handle pagination.\n\n###### Outer wrapper must neutralize screen-only styles for print\n\n```tsx\n\n\u003Cdiv className=\"min-h-screen bg-gray-100 py-8 px-4 print:bg-white print:py-0 print:px-0 print:min-h-0\">\n\n```\n\n**Viewport must match page width** in Puppeteer: `page.setViewport({ width: 816, height: 1056 })` so content renders at the correct scale.\n\n**Content balancing:** Use `breakInside: \"avoid\"` on sections and distribute content across pages so no page overflows. Check the rendered layout in the browser at 816px width before generating PDFs.\n\n### Contract Review Output\n\nFor **reviews** (not drafting), output the review analysis directly as text using the Review Output Format above. Do not generate PDF\u002FDOCX for reviews — the review is commentary, not a document.\n\n### Multi-Document Routing\n\nWhen generating multiple documents for the same transaction (e.g., LOI + NDA), use a single React artifact with separate routes for each document:\n\n```tsx\n\n\u002F\u002F App.tsx\n\n\u003CRoute path=\"\u002F\" component={LOIDocument} \u002F>\n\n\u003CRoute path=\"\u002Fnda\" component={NDADocument} \u002F>\n\n```\n\nThen generate separate PDF\u002FDOCX files for each document by pointing Puppeteer at each route and running a separate python-docx script per document. Present all files together so the user receives the complete package.\n\n**IMPORTANT:** Since all routes share the same `index.html`, the HTML`\u003Ctitle>`tag applies to every document. Each PDF generation script must call`page.evaluate(() => { document.title = \"Correct Document Title\"; })`before`page.pdf()` to set the correct PDF metadata title. Otherwise the PDF viewer's title bar will show the wrong document name.\n\n## Drafting Rules\n\n1. **Always include the disclaimer** at the top of every output — this is not legal advice\n2. Start from Bonterms\u002FCommon Paper for NDAs and service agreements; use the clause structures in \"M&A \u002F Transaction Documents\" for LOIs and purchase agreements\n\n3. Quote exact problem text with section numbers, then give replacement language\n4. Flag jurisdiction dependencies — non-compete enforceability, anti-indemnity statutes, and consumer protection vary wildly by state\u002Fcountry\n\n5. When stakes are high (>$50K, equity, exclusivity, personal guarantees) → recommend attorney review explicitly\n6. For multi-document transactions, ensure consistent terminology and cross-references across all documents\n\n## Documents System\n\nThe platform includes a generic document management system for any type of legal document. Documents are owner-scoped and can optionally be linked to a DD room.\n\n### Schema (`documents` table)\n\n| Column | Type | Description |\n\n|--------|------|-------------|\n\n| `id` | text (UUID) | Primary key |\n\n| `ownerId` | text | Clerk user ID of the document owner |\n\n| `title` | varchar(500) | Document title |\n\n| `documentType` | varchar(100) | Flexible type field (e.g., \"LOI\", \"NDA\", \"APA\", \"Employment Agreement\", \"Lease\") |\n\n| `content` | text | Full document content (Markdown\u002Fplain text) |\n\n| `status` | varchar(50) | Document status, default \"draft\" |\n\n| `ddRoomId` | text | Optional link to a DD room |\n\n| `createdAt` | timestamp | Auto-set on creation |\n\n| `updatedAt` | timestamp | Auto-set on creation and update |\n\n### Key Design Principles\n\n- **Type-agnostic:** The `documentType` field is a free-text string, not an enum. Any document type can be stored — LOIs, NDAs, asset purchase agreements, operating agreements, board resolutions, etc.\n- **Owner-scoped:** All document endpoints filter by the authenticated user's `ownerId`. Users can only see, edit, and delete their own documents.\n\n- **Room linkable:** Documents can optionally reference a `ddRoomId` to associate them with a due diligence room (e.g., the LOI for an acquisition).\n\n### API Endpoints\n\n| Method | Path | Description |\n\n|--------|------|-------------|\n\n| GET | `\u002Fdocuments` | List all documents owned by the current user |\n\n| GET | `\u002Fdocuments\u002F:documentId` | Get a single document (owner-only) |\n\n| DELETE | `\u002Fdocuments\u002F:documentId` | Delete a document (owner-only) |\n\n### Frontend\n\n- **Dashboard:** Document cards appear below the DD rooms section. Each card shows title, type badge, status, and creation date. Hovering reveals a delete button with inline confirm\u002Fcancel.\n- **Document view:** `\u002Fdocuments\u002F:documentId` renders the full document content.\n\n## Due Diligence Room Platform\n\nThe legal platform includes an interactive Due Diligence (DD) room for M&A transactions. This is a full-stack feature with its own database schema, API endpoints, and React UI.\n\n### Architecture\n\n- **Frontend:** `artifacts\u002Flegal-platform\u002Fsrc\u002Fpages\u002Fdd-room.tsx` — React + shadcn\u002Fui\n- **API:** `artifacts\u002Fapi-server\u002Fsrc\u002Froutes\u002Fdd-*.ts` — Express REST endpoints\n\n- **DB:** PostgreSQL via Drizzle ORM — tables in `lib\u002Fdb\u002Fsrc\u002Fschema\u002Fdd-*.ts`\n- **Auth:** Clerk; middleware at `artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireAuth.ts`\n\n- **Room Auth:** `artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireRoomAccess.ts` — room-level authorization\n- **File Storage:** Replit Object Storage via `@google-cloud\u002Fstorage`\n\n- **OpenAPI:** `lib\u002Fapi-spec\u002Fopenapi.yaml`with codegen to`@workspace\u002Fapi-client-react`and`@workspace\u002Fapi-zod`\n\n### Database Tables\n\n| Table | Purpose |\n\n|-------|---------|\n\n| `dd_rooms` | Room metadata: name, buyer\u002Fseller, purchase price, deal structure, ownerId |\n\n| `dd_categories` | Checklist categories (8 auto-created from template, plus custom) |\n\n| `dd_items` | Individual checklist items with status tracking |\n\n| `dd_files` | Uploaded documents linked to items (object storage paths) |\n\n| `dd_comments` | Item-level discussion threads |\n\n| `dd_activity` | Audit log of all actions |\n\n| `dd_participants` | Room access control (email + role: viewer\u002Fcontributor\u002Fadmin) |\n\n### Standard Checklist Template\n\nWhen a room is created, 8 categories with 57 items are auto-populated from `DD_TEMPLATE`in`dd-rooms.ts`:\n\n1. **Corporate & Organizational** (7 items) — Formation docs, bylaws, minutes, cap table, good standing, org chart, jurisdictions\n2. **Financial** (8 items) — Audited\u002Finterim statements, tax returns, debt schedule, AR\u002FAP aging, revenue breakdown, projections, bank accounts\n\n3. **Contracts & Agreements** (7 items) — Customer\u002Fvendor\u002Fpartnership\u002Fdistribution\u002Ffranchise\u002Fgovernment contracts, change-of-control provisions\n4. **Intellectual Property** (8 items) — Patents, trademarks, copyrights, domains, software licenses, IP assignments, open-source audit, trade secrets\n\n5. **Employees & Benefits** (9 items) — Census, employment agreements, contractors, handbook, non-competes, benefits, stock options, workers' comp, OSHA\n6. **Litigation & Legal** (6 items) — Pending litigation, settlements, consent decrees, investigations, insurance claims, regulator correspondence\n\n7. **Insurance** (4 items) — All policies, claims history, broker info, certificates\n8. **Technology & Data** (8 items) — Architecture docs, data flows, SOC 2, breach history, BCP\u002FDR, SLA reports, vendor assessments, privacy policy\n\nCustom categories and items can be added per-room via the API.\n\n### Item Status Workflow\n\nItems track progress through these statuses:\n\n```text\n\nnot_started → uploaded → under_review → approved\n\n→ flagged (with note)\n\n```\n\n#### Automatic transitions\n\n- Uploading a file to a `not_started`item changes its status to`uploaded`\n- Deleting all files from an `uploaded`item reverts its status to`not_started`\n\n- All other transitions (under_review, approved, flagged) are manual via the UI\n\n### Access Control\n\nRoom-level authorization is enforced via `requireRoomAccess`middleware (`artifacts\u002Fapi-server\u002Fsrc\u002Fmiddlewares\u002FrequireRoomAccess.ts`) and its variants. Each variant looks up the resource chain to find the parent room, then checks if the user is the room owner or an active participant.\n\n| Middleware | Lookup Chain | Used On |\n\n|-----------|-------------|---------|\n\n| `requireRoomAccess(roomIdParam)` | Direct roomId | Room detail, update, stats, activity, participants, categories |\n\n| `requireCategoryRoomAccess(categoryIdParam)` | category → room | Delete category, create items |\n\n| `requireItemRoomAccess(itemIdParam)` | item → category → room | Update\u002Fdelete items, list\u002Fcreate files, list\u002Fcreate comments |\n\n| `requireFileRoomAccess(fileIdParam)` | file → item → category → room | Delete files |\n\n| `requireCommentRoomAccess(commentIdParam)` | comment → item → category → room | Delete comments |\n\n#### Privilege levels\n\n- **Room owner:** Full access to everything including participant management\n- **Admin participant:** Can manage participants (add\u002Fremove) and all room content\n\n- **Contributor\u002FViewer participant:** Can access room content but cannot manage participants\n- **Non-participant:** Receives 403 on all room-scoped endpoints\n\nThe `GET \u002Fdd-rooms` listing only returns rooms where the user is owner or participant (no cross-tenant leakage).\n\nPrivate file downloads (`GET \u002Fstorage\u002Fobjects\u002F*`) also enforce room access by looking up the file's parent room through the`dd_files → dd_items → dd_categories` chain.\n\n### Activity Feed Events\n\nAll significant actions are logged to `dd_activity` with the following event types:\n\n| Action | Trigger |\n\n|--------|---------|\n\n| `file_uploaded` | File registered on an item |\n\n| `file_deleted` | File removed from an item |\n\n| `comment_deleted` | Comment removed from an item |\n\n| `participant_removed` | Participant removed from room |\n\n| `status_changed` | Item status updated |\n\nEach activity entry records: `roomId`,`userId`,`userName`,`itemId`(optional),`action`,`details`,`createdAt`.\n\n### File Upload Flow\n\n1. Frontend requests presigned upload URL via `POST \u002Fapi\u002Fstorage\u002Fuploads\u002Frequest-url` (sends file name, size, contentType as JSON)\n2. Frontend uploads file directly to object storage using the presigned URL (PUT to GCS)\n\n3. Frontend registers the file via `POST \u002Fapi\u002Fdd-items\u002F:itemId\u002Ffiles` with the returned storage URL\n4. Backend normalizes the GCS URL to an object entity path (`\u002Fobjects\u002F\u003CentityId>`) and validates:\n\n- URL must normalize to `\u002Fobjects\u002F` prefix format\n- URL must not already be registered (prevents duplicate registration \u002F IDOR)\n\n1. File downloads served via `GET \u002Fapi\u002Fstorage\u002Fobjects\u002F*path` with room-level authorization\n\n### API Endpoints (2)\n\n| Method | Path | Auth | Description |\n\n|--------|------|------|-------------|\n\n| GET | `\u002Fdd-rooms` | requireAuth | List rooms (filtered by owner\u002Fparticipant) |\n\n| POST | `\u002Fdd-rooms` | requireAuth | Create a new DD room (auto-populates 8 categories) |\n\n| GET | `\u002Fdd-rooms\u002F:roomId` | requireAuth + roomAccess | Get room with categories and items |\n\n| PUT | `\u002Fdd-rooms\u002F:roomId` | requireAuth + roomAccess | Update room metadata |\n\n| POST | `\u002Fdd-rooms\u002F:roomId\u002Fcategories` | requireAuth + roomAccess | Add a custom category |\n\n| DELETE | `\u002Fdd-categories\u002F:categoryId` | requireAuth + categoryRoomAccess | Delete a category and its items |\n\n| POST | `\u002Fdd-categories\u002F:categoryId\u002Fitems` | requireAuth + categoryRoomAccess | Add an item to a category |\n\n| PUT | `\u002Fdd-items\u002F:itemId` | requireAuth + itemRoomAccess | Update item (name, status, notes) |\n\n| DELETE | `\u002Fdd-items\u002F:itemId` | requireAuth + itemRoomAccess | Delete an item |\n\n| GET | `\u002Fdd-items\u002F:itemId\u002Ffiles` | requireAuth + itemRoomAccess | List files for an item |\n\n| POST | `\u002Fdd-items\u002F:itemId\u002Ffiles` | requireAuth + itemRoomAccess | Register an uploaded file |\n\n| DELETE | `\u002Fdd-files\u002F:fileId` | requireAuth + fileRoomAccess | Delete a file |\n\n| GET | `\u002Fdd-items\u002F:itemId\u002Fcomments` | requireAuth + itemRoomAccess | List comments for an item |\n\n| POST | `\u002Fdd-items\u002F:itemId\u002Fcomments` | requireAuth + itemRoomAccess | Add a comment |\n\n| DELETE | `\u002Fdd-comments\u002F:commentId` | requireAuth + commentRoomAccess | Delete a comment |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Fstats` | requireAuth + roomAccess | Get completion statistics |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Factivity` | requireAuth + roomAccess | Get activity feed |\n\n| GET | `\u002Fdd-rooms\u002F:roomId\u002Fparticipants` | requireAuth + roomAccess | List participants |\n\n| POST | `\u002Fdd-rooms\u002F:roomId\u002Fparticipants` | requireAuth + roomAccess (owner\u002Fadmin) | Add a participant |\n\n| DELETE | `\u002Fdd-participants\u002F:participantId` | requireAuth + roomAccess (owner\u002Fadmin) | Remove a participant |\n\n| POST | `\u002Fstorage\u002Fuploads\u002Frequest-url` | requireAuth | Get presigned upload URL |\n\n| GET | `\u002Fstorage\u002Fobjects\u002F*` | requireAuth + fileRoomAccess | Download a file |\n\n## Limitations\n\n- NOT a substitute for legal advice from a licensed attorney\n- Cannot account for jurisdiction-specific laws\n\n- Cannot verify legal enforceability of any clause\n- Cannot handle litigation, regulatory filings, or court documents\n\n- Templates are starting points, not final legal documents\n",{"name":5,"description":7},"main","6b4a291df75c639681e93b4b5b812126443fd6ed","secondary_skills\u002Flegal-contract",3,"https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd","https:\u002F\u002Fsolanaclawd.com\u002Fopenclawd","https:\u002F\u002Fgithub.com\u002Fclawdsolana","https:\u002F\u002Fmusebook.trade","Welcome to Open Clawd. The future of Ai on and off chain. Bringing webMCP to web 3 using X402, A2A, MPP and so much more!","2026-08-01 09:30:51",{"source":8,"skillName":5,"commands":58,"prompt":68,"zipAvailable":69},[59,62,65],{"tool":60,"command":61},"npx","npx skills add clawdsolana\u002FOpenClawd --skill legal-contract",{"tool":63,"command":64},"bunx","bunx skills add clawdsolana\u002FOpenClawd --skill legal-contract",{"tool":66,"command":67},"pnpm","pnpm dlx skills add clawdsolana\u002FOpenClawd --skill legal-contract","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fsecondary_skills\u002Flegal-contract\u002FSKILL.md",true,[71],{"path":72,"resourceType":73,"resourceTypeDesc":74,"sizeBytes":75,"sourceHtmlUrl":76},".fingerprint","OTHER","其他",32,"https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fsecondary_skills\u002Flegal-contract\u002F.fingerprint",[78,109,137,163,173,197],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":87,"publishedAt":108},"01M71KRBD0W01EAXJ8YM4M1SJ2","solana-dev","End-to-end Solana development playbook (Jan 2026). Prefer Solana Foundation framework-kit (@solana\u002Fclient + @solana\u002Freact-hooks) for React\u002FNext.js UI. Prefer @solana\u002Fkit for all new client\u002FRPC\u002Ftransaction code. When legacy dependencies require web3.js, isolate it behind @solana\u002Fweb3-compat (or @solana\u002Fweb3.js as a true legacy fallback). Covers wallet-standard-first connection (incl. ConnectorKit), Anchor\u002FPinocchio programs, Codama-based client generation, LiteSVM\u002FMollusk\u002FSurfpool testing, and security checklists.","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fsrc\u002Fskills\u002Fsolana-dev\u002FSKILL.md",[84],{"categoryNo":85,"categoryName":86,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000008","测试与质量",[88,89,90,91,92,93,94,95,96,97,98,99,100,101,102,103,104,105,106,107],"solana dev","dev","solana","Wallet","end","testing","hooks","kit","new","when","web3","code","react","next","2026","playbook","security","ui","fallback","framework","2026-11-10 10:56:23",{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":118,"publishedAt":108},"01M71KR8QPESSY61SVE8ZTFNVT","xurl","A CLI tool for making authenticated requests to the X (Twitter) API. Use this skill when you need to post tweets, reply, quote, search, read posts, manage followers, send DMs, upload media, or interact with any X API v2 endpoint.","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fskills\u002Fxurl\u002FSKILL.md",[115],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},"01JBSEEDCAT000000000000023","Skill与智能体开发",[111,119,120,121,122,123,124,97,125,126,127,128,129,130,131,132,133,134,135,136],"posts","Media","x api","search","send","tap","you","api","cli","read","install","cli tool","endpoint","brew","for","manage","tool","twitter",{"skillNo":138,"name":139,"nameZh":6,"description":140,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":141,"categories":142,"keywords":144,"publishedAt":108},"01M71KR6FSXV88YDKWP7NBY3SH","wurk-integration","WURK API integration for monetizing agents with x402 payments on Solana\u002FBase - create social jobs, custom challenges, and agent help tasks","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fskills\u002Fwurk-integration\u002FSKILL.md",[143],{"categoryNo":116,"categoryName":117,"taxonomyType":21,"taxonomyTypeDesc":22},[145,146,147,148,149,150,151,152,126,153,154,155,156,157,158,159,133,160,161,162],"wurk","wurk integration","integration","x402","social","payments","tasks","team","create","social-jobs","command","agent-help","custom-jobs","clawd","safe","api integration","custom","true",{"skillNo":164,"name":165,"nameZh":6,"description":166,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":167,"categories":168,"keywords":169,"publishedAt":108},"01M71KR4HCX41BPAK9GP7RPRRP","workflows","Manage application workflows including configuration, restart, and removal.","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fskills\u002Fworkflows\u002FSKILL.md",[],[165,134,170,171,172],"configuration","application","restart",{"skillNo":174,"name":175,"nameZh":6,"description":176,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":177,"categories":178,"keywords":179,"publishedAt":108},"01M71KR1VM0F5GPEQDNG5J7A0H","web-search","Search the web, fetch content, extract branding profiles, and capture screenshots from URLs. Use for real-time information, API documentation, current events, design matching, and visual reference.","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fskills\u002Fweb-search\u002FSKILL.md",[],[180,122,181,182,183,133,184,185,186,187,188,189,190,126,191,192,193,194,195,196],"web search","web","fetch","api documentation","real-time","time","profiles","design","use","information","visual","documentation","branding","matching","reference","capture","content",{"skillNo":198,"name":199,"nameZh":6,"description":200,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":201,"categories":202,"keywords":203,"publishedAt":108},"01M71KQZN5MR1JFQHG5GWXYAHS","weather","Get current weather and forecasts via wttr.in or Open-Meteo. Use when: user asks about weather, temperature, or forecasts for any location. NOT for: historical weather data, severe weather alerts, or detailed meteorological analysis. No API key needed.","https:\u002F\u002Fgithub.com\u002Fclawdsolana\u002FOpenClawd\u002Fblob\u002Fmain\u002Fskills\u002Fweather\u002FSKILL.md",[],[199,204,133,205,188,97,206,126,207,208,209,210,211,212,213,214,215,216],"get","open","analysis","alerts","temperature","curl","via","help","about","https","location","data","user"]