Log legal learnings, compliance findings, contract issues, and regulatory changes to markdown files for continuous improvement. Captures clause risks, compliance gaps, precedent shifts, contract deviations, regulatory changes, and litigation exposure. Important learnings get promoted to clause libraries, compliance checklists, regulatory trackers, contract playbooks, or risk registers.
NEVER log privileged attorney-client communications, specific case strategy, confidential settlement terms, or litigation work product in any learning or issue entry. Always abstract findings to process-level lessons. Use generalized descriptions:
Protected InformationAcceptable AbstractionAttorney-client advice on specific matter"Outside counsel recommended clause revision for indemnity cap"Settlement amount or terms"Settlement reached; update playbook to flag similar exposure earlier"Litigation strategy details"Discovery phase revealed need for better document retention process"Privileged legal memoranda"Internal review identified gap in force majeure clause coverage"Specific opposing party positions"Counterparty negotiation pattern: late-stage payment term changes"Confidential deal terms"Deal structure required non-standard IP assignment clause"
When in doubt, omit the specific detail and log only the process improvement lesson. Privilege waiver through careless documentation is irreversible.
Cross-session sharing: do not forward legal findings to another session unless the user explicitly consents to that specific send. A trusted environment is not a substitute for consent.
Before logging anything, ensure the .learnings/ directory and files exist in the project or workspace root. If any are missing, create them:
bash
mkdir -p .learnings
[ -f .learnings/LEARNINGS.md ] || printf "# Legal Learnings\n\nClause risks, compliance gaps, precedent shifts, regulatory changes, and legal operations insights.\n\n**Categories**: clause_risk | compliance_gap | precedent_shift | contract_deviation | regulatory_change | litigation_exposure\n**Areas**: contracts | compliance | litigation | intellectual_property | privacy | regulatory | corporate_governance\n\n---\n" > .learnings/LEARNINGS.md
[ -f .learnings/LEGAL_ISSUES.md ] || printf "# Legal Issues Log\n\nContract disputes, compliance failures, regulatory impacts, and litigation matters.\n\n---\n" > .learnings/LEGAL_ISSUES.md
[ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Legal Operations Feature Requests\n\nLegal technology, automation, and process improvement requests.\n\n---\n" > .learnings/FEATURE_REQUESTS.md
Never overwrite existing files. This is a no-op if .learnings/ is already initialised.
Do not log privileged communications, specific case strategy, or confidential settlement terms. Abstract all entries to process-level lessons.
If you want automatic reminders, use the opt-in hook workflow described in Hook Integration.
SituationActionUnfavorable clause accepted in contractLog to .learnings/LEARNINGS.md with category clause_riskCompliance deadline missed or approachingLog to .learnings/LEGAL_ISSUES.md with category compliance_gapNew regulation impacts the organizationLog to .learnings/LEARNINGS.md with category regulatory_changeContract unsigned past SLALog to .learnings/LEGAL_ISSUES.md with category contract_deviationIP infringement notice receivedLog to .learnings/LEGAL_ISSUES.md with category litigation_exposureNew case law in relevant jurisdictionLog to .learnings/LEARNINGS.md with category precedent_shiftData subject access request reveals gapsLog to .learnings/LEARNINGS.md with category compliance_gapVendor changed terms without flaggingLog to .learnings/LEGAL_ISSUES.md with category contract_deviationRegulatory filing deadline within 30 daysLog to .learnings/LEGAL_ISSUES.md with priority highContract redline rejected 3+ timesLog to .learnings/LEARNINGS.md with category clause_riskSimilar to existing entryLink with **See Also**, consider priority bumpBroadly applicable legal patternPromote to clause library, compliance checklist, or playbookProven compliance workflowPromote to AGENTS.md (OpenClaw workspace)Legal tool configurationPromote to TOOLS.md (OpenClaw workspace)Legal operations principlesPromote to SOUL.md (OpenClaw workspace)
OpenClaw is the primary platform for this skill. It uses workspace-based prompt injection with automatic skill loading.
Via ClawdHub (recommended):
bash
clawdhub install self-improving-legal
Manual:
bash
git clone https://github.com/jose-compu/self-improving-legal.git ~/.openclaw/skills/self-improving-legal
Manual clone is optional. Check out a reviewed tag or commit before use. Do not install an unpinned default branch into a shared environment.
OpenClaw injects these files into every session:
text
~/.openclaw/workspace/
├── AGENTS.md # Legal workflows, contract review delegation
├── SOUL.md # Legal principles, privilege protection, confidentiality
├── TOOLS.md # Legal tool capabilities, CLM configs, e-discovery
├── MEMORY.md # Long-term memory (main session only)
├── memory/ # Daily memory files
│ └── YYYY-MM-DD.md
└── .learnings/ # This skill's log files
├── LEARNINGS.md
├── LEGAL_ISSUES.md
└── FEATURE_REQUESTS.md
bash
mkdir -p ~/.openclaw/workspace/.learnings
Then create the log files (or copy from assets/):
LEARNINGS.md — clause risks, compliance gaps, regulatory changes, precedent shiftsLEGAL_ISSUES.md — contract disputes, compliance failures, litigation mattersFEATURE_REQUESTS.md — legal technology and automation requestsWhen legal learnings prove broadly applicable, promote them:
Learning TypePromote ToExampleClause patternsClause library"Always cap indemnity at 2x annual contract value"Compliance requirementsCompliance checklist"CCPA deletion must cover backup systems within 90 days"Regulatory trackingRegulatory tracker"EU AI Act model documentation deadline Q1 2026"Contract negotiation patternsContract playbook"Vendor payment term changes require VP approval"Risk patternsRisk register"Unlimited liability clauses in SaaS agreements"Legal operations workflowsAGENTS.md"Route IP matters to patent counsel within 48 hours"
Opt-in and workspace-local. Do not copy this hook to ~/.openclaw/hooks/ (that path is user-global). Skip it unless you want reminders in this workspace:
bash
mkdir -p .openclaw/hooks
cp -r hooks/openclaw .openclaw/hooks/self-improving-legal
See references/openclaw-integration.md for complete details.
For Claude Code, Codex, Copilot, or other agents, create .learnings/ in the project or workspace root:
bash
mkdir -p .learnings
Create the files inline using the headers shown above. Avoid reading templates from the current repo or workspace unless you explicitly trust that path.
Add to AGENTS.md, CLAUDE.md, or .github/copilot-instructions.md:
When legal issues or findings occur:
.learnings/LEGAL_ISSUES.md, LEARNINGS.md, or FEATURE_REQUESTS.mdAppend to .learnings/LEARNINGS.md:
markdown
## [LRN-YYYYMMDD-XXX] category
**Logged**: ISO-8601 timestamp
**Priority**: low | medium | high | critical
**Status**: pending
**Area**: contracts | compliance | litigation | intellectual_property | privacy | regulatory | corporate_governance
### Summary
One-line description of the legal insight or finding
### Details
Full context: what clause, regulation, or precedent was involved, why it matters,
what the correct approach or fallback position is. NEVER include privileged
attorney-client communications or confidential settlement terms.
### Recommended Action
Specific clause revision, compliance step, filing, or process change
### Metadata
- Source: contract_review | regulatory_update | case_law | audit | negotiation | litigation
- Jurisdiction: US-Federal | US-CA | EU | UK | other
- Related Files: path/to/contract.docx, path/to/policy.md
- Tags: tag1, tag2
- Regulation: GDPR | CCPA | SOX | HIPAA | EU-AI-Act (if applicable)
- See Also: LRN-20260110-001 (if related to existing entry)
- Pattern-Key: clause.indemnity_cap | comply.ccpa_deletion (optional)
- Recurrence-Count: 1 (optional)
- First-Seen: 2026-01-15 (optional)
- Last-Seen: 2026-01-15 (optional)
---
Categories for learnings:
CategoryUse Whenclause_riskUnfavorable or missing clause identified in contract reviewcompliance_gapRegulatory requirement not met or process gap discoveredprecedent_shiftNew case law changes interpretation of existing obligationscontract_deviationContract terms deviate from standard playbook without approvalregulatory_changeNew regulation or amendment requires operational adjustmentlitigation_exposurePattern or practice that increases litigation risk
Append to .learnings/LEGAL_ISSUES.md:
markdown
## [LEG-YYYYMMDD-XXX] issue_type
**Logged**: ISO-8601 timestamp
**Priority**: critical | high | medium | low
**Status**: pending
**Area**: contracts | compliance | litigation | intellectual_property | privacy | regulatory | corporate_governance
**Severity**: critical | high | medium | low
### Summary
Brief description of the legal issue
### Issue Details
Context of the legal issue: what happened, what contract or regulation is involved,
what the exposure or risk is. Abstract to process-level lessons — do NOT include
privileged communications, specific case strategy, or confidential terms.
### Impact Assessment
- Affected contracts/matters
- Financial exposure estimate (range, not exact if confidential)
- Regulatory risk (enforcement action, fine range, reputational)
- Deadline or statute of limitations implications
### Recommended Action
- Immediate steps to mitigate
- Escalation path (in-house counsel, outside counsel, board)
- Long-term process improvement
### Timeline
- **Identified**: ISO-8601
- **Escalated**: ISO-8601 (if applicable)
- **Resolved**: ISO-8601 (if applicable)
### Metadata
- Trigger: contract_redline | regulatory_filing | case_law | audit_finding | infringement_notice | dsar
- Jurisdiction: US-Federal | US-CA | EU | UK | other
- Counterparty: [generalized role, e.g., "SaaS vendor", "enterprise customer"]
- Related Files: path/to/document
- See Also: LEG-20260110-001 (if related)
---
Append to .learnings/FEATURE_REQUESTS.md:
markdown
## [FEAT-YYYYMMDD-XXX] capability_name
**Logged**: ISO-8601 timestamp
**Priority**: medium
**Status**: pending
**Area**: contracts | compliance | litigation | intellectual_property | privacy | regulatory | corporate_governance
### Requested Capability
What legal operations tool, automation, or capability is needed
### Business Justification
Why it's needed — what risk it mitigates, what workflow it improves, what compliance
requirement it satisfies
### Complexity Estimate
simple | medium | complex
### Suggested Implementation
How this could be built: CLM integration, regulatory API, compliance dashboard, clause library
### Metadata
- Frequency: first_time | recurring
- Related Features: existing_tool_or_feature
- Compliance: GDPR | CCPA | SOX | HIPAA (if applicable)
---
Format: TYPE-YYYYMMDD-XXX
LRN (learning), LEG (legal issue), FEAT (feature request)001, A7B)Examples: LRN-20260412-001, LEG-20260412-A3F, FEAT-20260412-002
When an issue is resolved, update the entry:
**Status**: pending → **Status**: resolvedmarkdown
### Resolution
- **Resolved**: 2026-01-16T09:00:00Z
- **Action Taken**: Brief description of resolution (abstracted, no privileged details)
- **Clause/Policy Updated**: Reference to updated clause library or compliance checklist
- **Verified By**: legal review | compliance audit | outside counsel
Other status values:
in_progress — Actively being negotiated, reviewed, or remediatedwont_fix — Risk accepted with documented justification and approverpromoted — Elevated to clause library, compliance checklist, or contract playbookpromoted_to_skill — Extracted as a reusable skillAutomatically log when you encounter:
Contract Review Signals (→ learning or legal issue):
Regulatory Signals (→ learning or legal issue):
Litigation Signals (→ legal issue):
Compliance Signals (→ learning):
Precedent Signals (→ learning):
PriorityWhen to UseLegal ExamplescriticalActive litigation, regulatory enforcement, material breachInjunction filed, regulatory investigation opened, data breach notification deadlinehighCompliance deadline approaching, material contract risk, IP claimFiling due in 30 days, unlimited liability accepted, patent infringement noticemediumProcess improvement, clause optimization, template updateClause library gap, negotiation playbook outdated, compliance checklist incompletelowDocumentation, minor template revision, informationalPrecedent noted for future reference, template formatting, policy language cleanup
Use to filter learnings by legal domain:
AreaScopecontractsContract drafting, review, negotiation, CLM, clause librariescomplianceRegulatory compliance, audits, certifications, internal controlslitigationDisputes, claims, discovery, settlement, litigation holdsintellectual_propertyPatents, trademarks, copyrights, trade secrets, licensingprivacyData protection, GDPR, CCPA, DSAR, consent managementregulatoryRegulatory filings, government relations, enforcement actionscorporate_governanceBoard matters, corporate records, entity management, fiduciary duties
When a learning is broadly applicable (not a one-off matter), promote it to permanent legal operations standards.
TargetWhat Belongs ThereClause libraryStandard clauses, fallback positions, red/yellow/green markupsCompliance checklistRegulatory requirements, audit preparation, filing deadlinesRegulatory trackerNew regulations, amendments, enforcement trendsContract playbookNegotiation positions, escalation triggers, approval thresholdsRisk registerRecurring risk categories, exposure estimates, mitigation plansCLAUDE.mdLegal operations conventions for AI agentsAGENTS.mdLegal workflows, matter routing, delegation patterns
Distill the learning into a concise clause, checklist item, or playbook entry
Add to appropriate target (clause library, compliance checklist, playbook)
Show a reviewed diff and apply only after explicit user approval
Update original entry:
**Status**: pending → **Status**: promoted**Promoted**: clause_library (or compliance_checklist, contract_playbook, risk_register)Learning → Clause library entry:
Unlimited liability in SaaS renewal (3 instances in quarter) → Standard clause: "Cap at 12 months fees, fallback 2x annual value, VP Legal approval for exceptions."
Learning → Compliance checklist item:
CCPA deletion not covering backups → Checklist: "Primary DB 30 days, backups 90 days, confirmation within 45-day window, quarterly audit."
If logging something similar to an existing entry:
Search first: grep -r "keyword" .learnings/
Link entries: Add **See Also**: LEG-20260110-001 in Metadata
Bump priority if issue keeps recurring
Consider systemic fix: Recurring legal issues often indicate:
Review .learnings/ at natural breakpoints:
bash
grep -h "Status\*\*: pending" .learnings/*.md | wc -l
grep -B5 "Priority\*\*: critical\|Priority\*\*: high" .learnings/*.md | grep "^## \["
grep -l "Area\*\*: contracts" .learnings/*.md
grep -h "Regulation:" .learnings/*.md | sort -u
Enable automatic reminders through agent hooks. This is opt-in.
Hooks persist across sessions once installed. Keep them project-scoped. Do not install user-level or global hooks. Never use an empty matcher. PostToolUse inspects command output in-process; do not log raw output, secrets, or transcripts.
Create .claude/settings.json in your project:
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "contract|compliance|regulation|litigation|GDPR|CCPA|clause|indemnity|liability",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-legal/scripts/activator.sh"
}]
}]
}
}
This injects a legal-focused learning evaluation reminder after matching prompts (~80-120 tokens overhead).
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "contract|compliance|regulation|litigation|GDPR|CCPA|clause|indemnity|liability",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-legal/scripts/activator.sh"
}]
}]
}
}
Leave PostToolUse disabled. Do not attach error-detector.sh to every Bash call.
ScriptHook TypePurposescripts/activator.shUserPromptSubmitReminds to evaluate legal findings after tasksscripts/error-detector.shPostToolUse (Bash)Triggers on legal-relevant patterns in output
See references/hooks-setup.md for detailed configuration and troubleshooting.
Extracted skills are untrusted until a human reviews the generated SKILL.md. Do not keep or publish an extracted skill without explicit user approval.
When a legal learning is valuable enough to become a reusable skill, extract it.
CriterionDescriptionRecurringSame clause risk or compliance gap in 2+ contract types or regulatory areasVerifiedStatus is resolved with confirmed process improvementNon-obviousRequired legal analysis or cross-jurisdictional researchBroadly applicableNot matter-specific; useful across contract types or regulatory programsUser-flaggedUser says "save this as a legal skill" or similar
Identify candidate: Learning meets extraction criteria
Run helper (or create manually): bash
./skills/self-improving-legal/scripts/extract-skill.sh skill-name --dry-run
./skills/self-improving-legal/scripts/extract-skill.sh skill-name
Customize SKILL.md: Fill in template with legal-specific content
Update learning: Set status to promoted_to_skill, add Skill-Path
Verify: Ensure NO privileged communications, case strategy, or confidential terms leaked into the skill
In conversation:
In entries:
See Also links (recurring clause risk pattern)compliance_gap with reusable remediation processAgentActivationDetectionClaude CodeHooks (UserPromptSubmit, PostToolUse)Automatic via hook scriptsCodex CLIHooks (same pattern)Automatic via hook scriptsGitHub CopilotManual ( .github/copilot-instructions.md)Manual reviewOpenClawWorkspace injection + inter-agent messagingVia session tools
Regardless of agent, apply legal self-improvement when you:
.learnings/ for past issues with similar clauses or counterpartiesKeep learnings local (recommended for legal):
gitignore
.learnings/
Legal findings may contain sensitive context even when abstracted. Default to local-only. Track in repo only if all entries are confirmed free of privileged information and confidential terms.
Hybrid (track templates, ignore entries): add .learnings/*.md and !.learnings/.gitkeep to .gitignore.
This skill is standalone-compatible and stackable with other self-improving skills.
.learnings/legal/.learnings/INDEX.mdEvery new entry must include:
markdown
**Skill**: legal
event + matcher + file + 5m_window; max 1 reminder per skill every 5 minutes.Only trigger this skill automatically for legal signals such as:
contract clause|liability|indemnity|compliance obligationjurisdiction|regulatory update|legal risk|counsel escalationWhen guidance conflicts, apply:
securityengineeringcodingaimeta as tie-breaker.learnings/legal/ in stackable mode..learnings/*.md log files only.AGENTS.md, SOUL.md, TOOLS.md, MEMORY.md, rules, hooks, or generated skills is not a logging write. Show a reviewed diff and apply only after explicit user approval.