Установка
SKILL.md
Legalize ES — Git-репозиторий законодательства Испании
Навык от ara.so — коллекция Daily 2026 Skills.
Что это
legalize-es — это Git-репозиторий, содержащий более 8 600 испанских законов в виде файлов Markdown, причём каждая законодательная реформа зафиксирована как Git-коммит. Каждый закон — это отдельный .md файл, названный по его идентификатору BOE (например, BOE-A-1978-31229.md для Конституции Испании). История реформ восходит к 1960 году.
Ключевые возможности:
- Полнотекстовый поиск по всем законам с помощью
grep - Точный diff между любыми двумя версиями закона с помощью
git diff - Хронология всех реформ конкретного закона с помощью
git log - Историческое состояние любого закона на любой момент времени с помощью
git show/git checkout
Установка
# Clone the full repo (includes all history)
git clone https://github.com/legalize-dev/legalize-es.git
cd legalize-es
# Shallow clone if you only need current state (much faster)
git clone --depth 1 https://github.com/legalize-dev/legalize-es.git
cd legalize-es
Все файлы законов находятся в spain/ каталоге.
Структура файлов
spain/
├── BOE-A-1978-31229.md # Constitución Española
├── BOE-A-1995-25444.md # Código Penal
├── BOE-A-2015-11430.md # Estatuto de los Trabajadores
├── BOE-A-2000-323.md # Ley de Enjuiciamiento Civil
└── ... (8,600+ laws)
YAML Frontmatter
Каждый файл начинается со структурированных метаданных:
---
titulo: "Constitución Española"
identificador: "BOE-A-1978-31229"
pais: "es"
rango: "constitucion"
fecha_publicacion: "1978-12-29"
ultima_actualizacion: "2024-02-17"
estado: "vigente"
fuente: "https://www.boe.es/eli/es/c/1978/12/27/(1)"
---
rango значения:
constitucionley-organicaleyreal-decreto-leyreal-decreto-legislativo
estado значения:
vigente— в настоящее время действуетderogado— отменён
Ключевые команды
Найти закон по теме
# Search law titles in frontmatter
grep -rl "trabajo" spain/ | head -20
# Search for a keyword across all law bodies
grep -rl "huelga" spain/
# Case-insensitive search for a concept
grep -rli "protección de datos" spain/
Прочитать конкретную статью
# Find Article 18 of the Constitution
grep -A 20 "Artículo 18" spain/BOE-A-1978-31229.md
# Find an article with context (10 lines before, 30 after)
grep -B 10 -A 30 "Artículo 135" spain/BOE-A-1978-31229.md
Найти закон по его идентификатору BOE
# If you know the BOE ID
cat spain/BOE-A-1995-25444.md
# Search by partial identifier
ls spain/ | grep "BOE-A-1995"
Фильтр по типу закона
# List all Organic Laws
grep -rl 'rango: "ley-organica"' spain/
# List all currently active laws
grep -rl 'estado: "vigente"' spain/
# List all repealed laws
grep -rl 'estado: "derogado"' spain/
Команды истории Git
Посмотреть все реформы закона
# Full reform history of the Spanish Constitution
git log --oneline -- spain/BOE-A-1978-31229.md
# With dates
git log --format="%h %ad %s" --date=short -- spain/BOE-A-1978-31229.md
# With full commit messages (includes reform source URL)
git log -- spain/BOE-A-1978-31229.md
Diff между двумя версиями
# Diff of a specific reform commit
git show 6660bcf -- spain/BOE-A-1978-31229.md
# Diff between two commits
git diff 6660bcf^..6660bcf -- spain/BOE-A-1978-31229.md
# Diff between two dates
git diff $(git rev-list -1 --before="2011-01-01" HEAD) \
$(git rev-list -1 --before="2012-01-01" HEAD) \
-- spain/BOE-A-1978-31229.md
Прочитать историческую версию закона
# State of the Constitution as of 2010-01-01
git show $(git rev-list -1 --before="2010-01-01" HEAD):spain/BOE-A-1978-31229.md
# Check out law at a specific commit (read-only inspection)
git show abc1234:spain/BOE-A-1978-31229.md
Найти, когда конкретный текст был добавлен или удалён
# Find which commit introduced "estabilidad presupuestaria"
git log -S "estabilidad presupuestaria" -- spain/BOE-A-1978-31229.md
# Find which commit changed a specific phrase
git log -G "límite de déficit estructural" --oneline -- spain/BOE-A-1978-31229.md
Шаблоны программного доступа
Shell-скрипт: извлечь все названия законов
#!/bin/bash
# Extract titles and identifiers from all laws
for file in spain/*.md; do
id=$(grep 'identificador:' "$file" | head -1 | sed 's/.*: "//;s/".*//')
title=$(grep 'titulo:' "$file" | head -1 | sed 's/.*: "//;s/".*//')
echo "$id | $title"
done
Shell-скрипт: найти законы, обновлённые после даты
#!/bin/bash
# Laws updated after 2023-01-01
TARGET_DATE="2023-01-01"
grep -rl "ultima_actualizacion:" spain/ | while read file; do
date=$(grep 'ultima_actualizacion:' "$file" | head -1 | grep -o '[0-9]\{4\}-[0-9]\{2\}-[0-9]\{2\}')
if [[ "$date" > "$TARGET_DATE" ]]; then
echo "$date $file"
fi
done | sort -r
Python: разобрать frontmatter закона
import os
import yaml
def parse_law(filepath):
"""Parse a law Markdown file and return frontmatter + body."""
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Extract YAML frontmatter between --- delimiters
if content.startswith('---'):
parts = content.split('---', 2)
if len(parts) >= 3:
metadata = yaml.safe_load(parts[1])
body = parts[2].strip()
return metadata, body
return {}, content
# Example: list all active laws
laws_dir = 'spain'
active_laws = []
for filename in os.listdir(laws_dir):
if filename.endswith('.md'):
filepath = os.path.join(laws_dir, filename)
meta, body = parse_law(filepath)
if meta.get('estado') == 'vigente':
active_laws.append({
'id': meta.get('identificador'),
'titulo': meta.get('titulo'),
'rango': meta.get('rango'),
'ultima_actualizacion': meta.get('ultima_actualizacion'),
})
# Sort by last update
active_laws.sort(key=lambda x: x['ultima_actualizacion'] or '', reverse=True)
for law in active_laws[:10]:
print(f"{law['ultima_actualizacion']} [{law['rango']}] {law['titulo']}")
Python: получение истории реформ через Git
import subprocess
import json
def get_reform_history(boe_id):
"""Get all commits that modified a law file."""
filepath = f"spain/{boe_id}.md"
result = subprocess.run(
['git', 'log', '--format=%H|%ad|%s', '--date=short', '--', filepath],
capture_output=True, text=True
)
reforms = []
for line in result.stdout.strip().split('\n'):
if line:
hash_, date, subject = line.split('|', 2)
reforms.append({'hash': hash_, 'date': date, 'subject': subject})
return reforms
# Example usage
history = get_reform_history('BOE-A-1978-31229')
for reform in history:
print(f"{reform['date']} {reform['hash'][:7]} {reform['subject']}")
Python: сравнение двух версий закона
import subprocess
def diff_law_versions(boe_id, commit_before, commit_after):
"""Get unified diff between two versions of a law."""
filepath = f"spain/{boe_id}.md"
result = subprocess.run(
['git', 'diff', f'{commit_before}..{commit_after}', '--', filepath],
capture_output=True, text=True
)
return result.stdout
def get_law_at_date(boe_id, date_str):
"""Get the text of a law as it was on a given date (YYYY-MM-DD)."""
filepath = f"spain/{boe_id}.md"
# Find the last commit before date
rev = subprocess.run(
['git', 'rev-list', '-1', f'--before={date_str}', 'HEAD'],
capture_output=True, text=True
).stdout.strip()
if not rev:
return None
content = subprocess.run(
['git', 'show', f'{rev}:{filepath}'],
capture_output=True, text=True
).stdout
return content
# Example: see Constitution before and after 2011 reform
old_text = get_law_at_date('BOE-A-1978-31229', '2011-09-26')
new_text = get_law_at_date('BOE-A-1978-31229', '2011-09-28')
print("Pre-reform length:", len(old_text))
print("Post-reform length:", len(new_text))
Python: поиск по всем законам
import os
import re
def search_laws(query, laws_dir='spain', rango=None, estado='vigente'):
"""Search for a regex pattern across all laws."""
results = []
pattern = re.compile(query, re.IGNORECASE)
for filename in os.listdir(laws_dir):
if not filename.endswith('.md'):
continue
filepath = os.path.join(laws_dir, filename)
with open(filepath, 'r', encoding='utf-8') as f:
content = f.read()
# Filter by frontmatter fields
if estado and f'estado: "{estado}"' not in content:
continue
if rango and f'rango: "{rango}"' not in content:
continue
matches = list(pattern.finditer(content))
if matches:
titulo_match = re.search(r'titulo: "([^"]+)"', content)
titulo = titulo_match.group(1) if titulo_match else filename
results.append({
'file': filename,
'titulo': titulo,
'match_count': len(matches),
'first_match_context': content[max(0, matches[0].start()-100):matches[0].end()+100]
})
return sorted(results, key=lambda x: x['match_count'], reverse=True)
# Example: find all active organic laws mentioning "privacidad"
hits = search_laws("privacidad", rango="ley-organica")
for h in hits:
print(f"[{h['match_count']} matches] {h['titulo']}")
print(f" Context: ...{h['first_match_context'].strip()[:150]}...")
print()
Типовые сценарии
Сценарий 1: исследование правовой темы
# 1. Find relevant laws
grep -rl "protección de datos personales" spain/ > relevant_laws.txt
# 2. Get titles of matching files
while read file; do
grep 'titulo:' "$file" | head -1
done < relevant_laws.txt
# 3. Find the primary law (LOPD/GDPR implementation)
grep -rl 'rango: "ley-organica"' spain/ | xargs grep -l "protección de datos"
Сценарий 2: отслеживание конкретной реформы
# 1. Find when Article 135 changed (2011 constitutional reform)
git log -S "estabilidad presupuestaria" --oneline -- spain/BOE-A-1978-31229.md
# 2. View the exact changes
git show <commit-hash> -- spain/BOE-A-1978-31229.md
# 3. Read the commit message for official source
git show --format="%B" <commit-hash> | head -10
Сценарий 3: экспорт законов в JSON
import os, yaml, json
laws = []
for fname in os.listdir('spain'):
if not fname.endswith('.md'):
continue
with open(f'spain/{fname}', 'r', encoding='utf-8') as f:
content = f.read()
if content.startswith('---'):
parts = content.split('---', 2)
if len(parts) >= 3:
meta = yaml.safe_load(parts[1])
meta['filename'] = fname
laws.append(meta)
with open('laws_index.json', 'w', encoding='utf-8') as f:
json.dump(laws, f, ensure_ascii=False, indent=2, default=str)
print(f"Exported {len(laws)} laws")
Устранение неполадок
Репозиторий слишком велик для клонирования
# Use shallow clone for current state only
git clone --depth 1 https://github.com/legalize-dev/legalize-es.git
# Or clone with limited history
git clone --depth 50 https://github.com/legalize-dev/legalize-es.git
Git Log не показывает историю после поверхностного клонирования
# Fetch more history
git fetch --deepen=100
# Fetch full history
git fetch --unshallow
Проблемы с кодировкой в Windows
# Force UTF-8 in git
git config core.quotepath false
git config i18n.logoutputencoding utf-8
# In Python, always open files with encoding='utf-8'
Поиск закона без его BOE ID
# Search by partial title (case-insensitive)
grep -ril "enjuiciamiento civil" spain/ | head -5
# Or search in frontmatter only (faster)
grep -rl "Ley de Enjuiciamiento Civil" spain/
Источник данных и лицензия
- Законодательный контент: Общественное достояние — источник: BOE Open Data API
- Структура репозитория, метаданные, инструменты: Лицензия MIT
- Официальный источник для каждого закона: См.
fuente:поле во frontmatter каждого файла - Часть проекта: Проект Legalize для нескольких стран
- Скоро: Программный API на legalize.dev
Вставить в README
Ссылка на карточку для вашего README — без картинок и счётчиков.
[DarkPlay: legalize-es-spanish-legislation](https://darkplay.ru/ai/skills/aradotso-trending-skills-legalize-es-spanish-legislation)
Из того же репозитория
Похожие скиллы и другие разделы каталога
Самые востребованные скиллов раздела по установкам и звёздам.
find-skillsvercel-labs · Помогает находить и устанавливать навыки агентов по запросам вроде «как сделать X»…
grill-memattpocock · Настойчивое интервью для доработки плана или дизайна.
hyperframesheygen-com · Обязательная точка входа для любых задач по видео, анимации и motion-графике в…
hyperframes-cliheygen-com · Цикл разработки HyperFrames CLI: init, add, render, preview, publish и другие команды.
agent-browservercel-labs · CLI для автоматизации браузера для ИИ-агентов: навигация по страницам, заполнение форм…
media-useheygen-com · Agent Media OS: единый навык для медиа в HyperFrames — BGM, SFX, изображения, голос, LUT.
hyperframes-registryheygen-com · Установка и подключение блоков реестра в композиции HyperFrames через add и catalog.
grill-with-docsmattpocock · Настойчивое интервью для доработки плана или дизайна, попутно создающее документацию (ADR…
improve-codebase-architecturemattpocock · Поиск в кодовой базе возможностей для углубления, визуальный HTML-отчёт о них и детальный…
tddmattpocock · Разработка через тестирование (TDD): red-green-refactor и интеграционные тесты.Соседние разделы каталога: возможно, нужный инструмент живёт там.
anti-ai-writinganthropics · Редактирует черновик, убирая слова, фразы и конструкции, выдающие текст как…
anticipating-shadow-pointsanthropics · Помогает доводить сложную инженерную работу, не упуская очевидное. До написания кода ASP…
blueprint-triggeranthropics · Blueprint Trigger: структурированный приём запросов для продуктовых и дизайн-команд до…
canadian-regulatory-complianceanthropics · Отвечает на вопросы канадского комплаенса в 13 областях: приватность, трудовое право…
claude-english-buddyanthropics · Хук UserPromptSubmit, помогающий неносителям английского улучшать язык при работе с…
cpa-practice-toolkitanthropics · Плагин Claude Cowork для частных бухгалтеров и небольших фирм. Автоматизирует рутинные…
don-cheli-sdd-frameworkanthropics · Фреймворк SDD: превращает требования в протестированный код через 7 фаз, с командами…
tendersanthropics · Поиск, анализ и мониторинг европейских госзакупок (TED и 18 национальных источников) и…
AEMETmmillan76 · MCP-сервер с прогнозами, данными станций и предупреждениями AEMET (испанское…
Aemps Cimapipeworx-io · MCP для AEMPS CIMA: публичный реестр лекарств Испании.Лучшие ИИ-инструменты для генерации видео
Подборка нейросетей для генерации и монтажа видео. Инструменты, которые превращают текст в готовые ролики, экономят часы на съемках и постпродакшне. Подходит для SMM-специалистов,
VEED.IOVeed
MootionMootion
Sora (OpenAI)OpenAI
viralpulse.appViralpulse
Viral Maker AIViral-makerЛучшие ИИ-инструменты для генерации текста и копирайтинга
Подборка нейросетей для генерации текстов и копирайтинга. Сервисы, которые помогают создавать статьи, посты и рекламные объявления с нуля или по черновику, экономя часы рутинной ра
NeuroscribeNeuroscribe
GoGPTGogpt
НейроТекстерNeuro-texter
ChatGPTOpenAI
Cosmo ScribeCosmoscribe
Memo HelperCopilot33
LibraChatLibrachatЛучшие ИИ-инструменты для генерации изображений
Подборка нейросетей для генерации изображений от фотореализма до концепт-арта. Сервисы, которые экономят часы ручной работы, создавая визуал для блогов, рекламы и дизайна за минуты
MagviMagvi
DALL-E 3OpenAI
SupaLabSupalab
Freestyling.aiFreestyling
ArtGeneration.meArtgeneration
BigjpgBigjpg
Художник от VKVK
Avato AI12ai
Virton AIVirton