Log security learnings, incidents, and compliance findings to markdown files for continuous improvement. Security-specific entries track vulnerabilities, misconfigurations, access violations, and incident response outcomes. Mature patterns get promoted to security runbooks, hardening checklists, incident response playbooks, and compliance matrices.
NEVER log actual secrets, credentials, tokens, private keys, API keys, passwords, connection strings, or PII in any learning or incident entry. Always redact sensitive values before writing. Use placeholders:
Sensitive DataRedacted FormAPI keysREDACTED_API_KEYPasswordsREDACTED_PASSWORDAccess tokens (JWT, bearer, session)REDACTED_TOKENPrivate keysREDACTED_PRIVATE_KEYConnection stringsREDACTED_CONNECTION_STRINGPII (emails, SSNs)REDACTED_PIIIP addresses (internal)REDACTED_INTERNAL_IPCertificate contentsREDACTED_CERT
When logging an incident involving exposed secrets, describe what kind of secret was exposed, where it appeared, and the remediation taken — never the secret itself.
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 "# Security Learnings\n\nVulnerabilities, misconfigurations, compliance gaps, and security insights.\n\n**Categories**: vulnerability | misconfiguration | access_violation | compliance_gap | incident_response | threat_intelligence\n**Areas**: authentication | authorization | encryption | network | endpoint | compliance | cloud\n\n---\n" > .learnings/LEARNINGS.md
[ -f .learnings/SECURITY_INCIDENTS.md ] || printf "# Security Incidents Log\n\nVulnerability discoveries, access violations, secrets exposure, and active security incidents.\n\n---\n" > .learnings/SECURITY_INCIDENTS.md
[ -f .learnings/FEATURE_REQUESTS.md ] || printf "# Security Feature Requests\n\nSecurity capabilities and hardening improvements requested or identified.\n\n---\n" > .learnings/FEATURE_REQUESTS.md
Never overwrite existing files. This is a no-op if .learnings/ is already initialised.
If you want automatic reminders or setup assistance, use the opt-in hook workflow described in Hook Integration.
No credentials or access tokens are required by this skill.
SituationActionCVE found in dependencyLog to .learnings/SECURITY_INCIDENTS.md with category vulnerabilitySecrets exposed in logs/outputLog to .learnings/SECURITY_INCIDENTS.md — REDACT the secret firstAccess violation or unauthorized accessLog to .learnings/SECURITY_INCIDENTS.md with category access_violationMisconfigured permissions/policiesLog to .learnings/LEARNINGS.md with category misconfigurationCompliance audit failureLog to .learnings/LEARNINGS.md with category compliance_gapIncident response executedLog to .learnings/LEARNINGS.md with category incident_responseThreat intelligence gatheredLog to .learnings/LEARNINGS.md with category threat_intelligenceSecurity feature neededLog to .learnings/FEATURE_REQUESTS.mdHardening improvement identifiedLog to .learnings/LEARNINGS.md with category misconfigurationSSL/TLS or certificate issueLog to .learnings/SECURITY_INCIDENTS.md with area encryptionCORS misconfigurationLog to .learnings/LEARNINGS.md with area networkAuthentication bypass foundLog to .learnings/SECURITY_INCIDENTS.md with area authenticationSimilar to existing entryLink with **See Also**, consider priority bumpBroadly applicable security patternPromote to hardening checklist, runbook, or playbookProven incident workflowPromote to AGENTS.md (OpenClaw workspace)Security tool gotchaPromote to TOOLS.md (OpenClaw workspace)Security 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-security
Manual:
bash
git clone https://github.com/jose-compu/self-improving-security.git ~/.openclaw/skills/self-improving-security
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 # Incident response workflows, delegation patterns
├── SOUL.md # Security principles, assume-breach mindset
├── TOOLS.md # Security tool capabilities, scanner configs
├── MEMORY.md # Long-term memory (main session only)
├── memory/ # Daily memory files
│ └── YYYY-MM-DD.md
└── .learnings/ # This skill's log files
├── LEARNINGS.md
├── SECURITY_INCIDENTS.md
└── FEATURE_REQUESTS.md
bash
mkdir -p ~/.openclaw/workspace/.learnings
Then create the log files (or copy from assets/):
LEARNINGS.md — misconfigurations, compliance gaps, threat intelligence, best practicesSECURITY_INCIDENTS.md — vulnerabilities, access violations, secrets exposureFEATURE_REQUESTS.md — security capabilities and hardening requestsWhen security learnings prove broadly applicable, promote them:
Learning TypePromote ToExampleSecurity principlesSOUL.md"Assume breach, defense in depth"Incident response workflowsAGENTS.md"Rotate credentials before root cause analysis"Security tool hardeningTOOLS.md"Always pass --no-cache to docker build in CI"Hardening checklist itemsHARDENING.md"Disable directory listing on all web servers"Incident response stepsPLAYBOOKS.md"Secrets exposure containment procedure"Compliance requirementsCOMPLIANCE.md"GDPR data retention audit quarterly"
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-security
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 security issues or findings occur:
.learnings/SECURITY_INCIDENTS.md, LEARNINGS.md, or FEATURE_REQUESTS.mdCLAUDE.md - security conventions and constraintsAGENTS.md - incident response workflows.github/copilot-instructions.md - security context for CopilotAppend to .learnings/LEARNINGS.md:
markdown
## [LRN-YYYYMMDD-XXX] category
**Logged**: ISO-8601 timestamp
**Priority**: low | medium | high | critical
**Status**: pending
**Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud
**CVSS**: N/A or score (e.g., 7.5)
### Summary
One-line description of the security finding or learning
### Details
Full context: what was found, the security impact, affected systems, root cause
### Remediation
Specific fix, hardening step, or compensating control
### Metadata
- Source: cve_advisory | pen_test | audit | user_feedback | incident | scan
- Related Files: path/to/file.ext
- Tags: tag1, tag2
- CVE: CVE-YYYY-NNNNN (if applicable)
- CWE: CWE-XXX (if applicable)
- See Also: LRN-20250110-001 (if related to existing entry)
- Pattern-Key: harden.input_validation | comply.gdpr_consent (optional)
- Recurrence-Count: 1 (optional)
- First-Seen: 2025-01-15 (optional)
- Last-Seen: 2025-01-15 (optional)
---
Append to .learnings/SECURITY_INCIDENTS.md:
markdown
## [SEC-YYYYMMDD-XXX] incident_type
**Logged**: ISO-8601 timestamp
**Priority**: critical | high | medium | low
**Status**: pending
**Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud
**Severity**: critical | high | medium | low
**CVSS**: score or N/A
### Summary
Brief description of the security incident
### Incident Details
Sanitized error output, log excerpt, or finding description. NEVER include actual secrets, tokens, keys, or PII here.
text
### Impact Assessment
- Affected systems/services
- Data at risk (type, not content)
- Blast radius estimate
### Containment & Remediation
- Immediate containment steps taken
- Root cause (if known)
- Long-term remediation plan
### Timeline
- **Detected**: ISO-8601
- **Contained**: ISO-8601 (if applicable)
- **Resolved**: ISO-8601 (if applicable)
### Metadata
- CVE: CVE-YYYY-NNNNN (if applicable)
- CWE: CWE-XXX (if applicable)
- Attack Vector: network | adjacent | local | physical
- Reproducible: yes | no | unknown
- Related Files: path/to/file.ext
- See Also: SEC-20250110-001 (if related)
---
Append to .learnings/FEATURE_REQUESTS.md:
markdown
## [FEAT-YYYYMMDD-XXX] capability_name
**Logged**: ISO-8601 timestamp
**Priority**: medium
**Status**: pending
**Area**: authentication | authorization | encryption | network | endpoint | compliance | cloud
### Requested Capability
What security capability is needed
### Security Justification
Why this capability matters — what risk it mitigates, what compliance requirement it satisfies
### Complexity Estimate
simple | medium | complex
### Suggested Implementation
How this could be built, what security controls it enables
### Metadata
- Frequency: first_time | recurring
- Related Features: existing_feature_name
- Compliance: SOC2 | GDPR | HIPAA | PCI-DSS | ISO27001 (if applicable)
---
Format: TYPE-YYYYMMDD-XXX
LRN (learning), SEC (security incident), FEAT (feature request)001, A7B)Examples: LRN-20250415-001, SEC-20250415-A3F, FEAT-20250415-002
When an issue is fixed or mitigated, update the entry:
**Status**: pending → **Status**: resolvedmarkdown
### Resolution
- **Resolved**: 2025-01-16T09:00:00Z
- **Commit/PR**: abc123 or #42
- **Remediation Applied**: Brief description of fix or compensating control
- **Verified By**: pen test | scan | manual review
Other status values:
in_progress - Actively being investigated or remediatedwont_fix - Risk accepted (add justification in Resolution notes)promoted - Elevated to hardening checklist, runbook, or playbookpromoted_to_skill - Extracted as a reusable skillWhen a finding is broadly applicable, promote it to permanent security documentation.
TargetWhat Belongs ThereCLAUDE.mdSecurity constraints, banned patterns, safe defaultsAGENTS.mdIncident response workflows, security scan automation.github/copilot-instructions.mdSecurity coding standards for CopilotSOUL.mdSecurity mindset: assume breach, defense in depth, least privilegeTOOLS.mdSecurity scanner configs, tool-specific hardeningHARDENING.mdInfrastructure and application hardening checklistPLAYBOOKS.mdIncident response playbooksCOMPLIANCE.mdCompliance matrices and audit evidence
Distill the finding into a concise security rule or control
Prepare a minimal patch for the appropriate section in the target file (create file if needed)
Show a reviewed diff and apply only after explicit user approval
Update original entry:
**Status**: pending → **Status**: promoted**Promoted**: HARDENING.md (or whichever target)If logging something similar to an existing entry:
Search first: grep -r "keyword" .learnings/
Link entries: Add **See Also**: SEC-20250110-001 in Metadata
Bump priority if issue keeps recurring
Consider systemic fix: Recurring security issues often indicate:
Automatically log when you notice:
Vulnerability Indicators (→ security incident):
CVE- prefix in output or advisoriesCRITICAL or HIGH severity in scan resultsvulnerability or exploit in dependency audit outputSecrets Exposure (→ security incident, REDACT IMMEDIATELY):
.env files with secrets committed to gitAccess Control Issues (→ security incident):
Permission denied in unexpected contexts403 Forbidden or 401 Unauthorized errorsInfrastructure Signals (→ learning):
SSL or TLS handshake failurescertificate expired or certificate verify failedCORS policy violations or misconfigurationsinsecure flag usage in tools or configsCompliance Signals (→ learning):
Feature Requests (→ feature request):
PriorityWhen to UsecriticalActive exploitation, data breach, secrets exposed in production, zero-dayhighKnown CVE unpatched, secrets in CI/CD logs, missing auth on public endpointmediumMisconfiguration with compensating controls, compliance gap with workaroundlowHardening improvement, defense-in-depth enhancement, informational finding
Use to filter findings by security domain:
AreaScopeauthenticationLogin, MFA, session management, credential storageauthorizationRBAC, ABAC, permission models, access policiesencryptionTLS/SSL, at-rest encryption, key management, certificatesnetworkFirewalls, CORS, DNS, load balancers, ingress/egressendpointAPI security, input validation, rate limiting, WAFcomplianceSOC2, GDPR, HIPAA, PCI-DSS, ISO 27001, audit trailscloudIAM policies, S3 buckets, security groups, KMS, cloud posture
Review .learnings/ at natural breakpoints:
bash
# Count pending security items
grep -h "Status\*\*: pending" .learnings/*.md | wc -l
# List pending critical/high items
grep -B5 "Priority\*\*: critical\|Priority\*\*: high" .learnings/*.md | grep "^## \["
# Find findings for a specific area
grep -l "Area\*\*: authentication" .learnings/*.md
# List all CVEs referenced
grep -h "CVE:" .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.
UserPromptSubmit with scripts/activator.sh only.Create .claude/settings.json in your project:
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "security|vuln|CVE|auth|permission|secret|credential|compliance",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-security/scripts/activator.sh"
}]
}]
}
}
json
{
"hooks": {
"UserPromptSubmit": [{
"matcher": "security|vuln|CVE|auth|permission|secret|credential|compliance",
"hooks": [{
"type": "command",
"command": "./skills/self-improving-security/scripts/activator.sh"
}]
}]
}
}
ScriptHook TypePurposescripts/activator.shUserPromptSubmitReminds to evaluate security findingsscripts/error-detector.shPostToolUse (Bash)Detects security-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 security learning is valuable enough to become a reusable skill, extract it.
CriterionDescriptionRecurringHas See Also links to 2+ similar findingsVerifiedStatus is resolved with confirmed remediationNon-obviousRequired investigation or specialized knowledgeBroadly applicableNot environment-specific; useful across projectsUser-flaggedUser says "save this as a security skill"
Identify candidate: Finding meets extraction criteria
Run helper (or create manually): bash
./skills/self-improving-security/scripts/extract-skill.sh skill-name --dry-run
./skills/self-improving-security/scripts/extract-skill.sh skill-name
Customize SKILL.md: Fill in template with finding content
Update entry: Set status to promoted_to_skill, add Skill-Path
Verify: Ensure no secrets or sensitive data leaked into the skill
In conversation:
In entries:
See Also links (recurring vulnerability pattern)incident_response with documented procedureKeep learnings local (recommended for security):
gitignore
.learnings/
Security findings may contain sensitive context. Default to local-only.
Track learnings in repo (team-wide, sanitized): Only if all entries are confirmed free of secrets, credentials, and PII.
Activation: Hooks (UserPromptSubmit, PostToolUse)
Setup: .claude/settings.json with hook configuration
Detection: Automatic via hook scripts
Activation: Hooks (same pattern as Claude Code)
Setup: .codex/settings.json with hook configuration
Activation: Manual (no hook support)
Setup: Add security self-improvement guidance to .github/copilot-instructions.md
Activation: Workspace injection + inter-agent messaging Setup: See "OpenClaw Setup" section above
Regardless of agent, apply security self-improvement when you:
This skill is standalone-compatible and stackable with other self-improving skills.
.learnings/security/.learnings/INDEX.mdEvery new entry must include:
markdown
**Skill**: security
event + matcher + file + 5m_window; max 1 reminder per skill every 5 minutes.Only trigger this skill automatically for security signals such as:
cve-|vulnerability|exploit|secret|token|credential|key leakedauth bypass|privilege escalation|tls|ssl|cors misconfigurationWhen guidance conflicts, apply:
securityengineeringcodingaimeta as tie-breaker.learnings/security/ 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.