Imported from Alex1980Alex/1C-Framework (
AGENTS.md). Install upstream withnpx skills add Alex1980Alex/1C-Framework. Copyright stays with the author.
AGENTS.md — AI Agent Instructions
This file contains instructions for AI agents (Claude Code, Cursor, etc.). Human-readable project overview is in CLAUDE.md.
Task Protocol (MANDATORY)
Every task: classify → (decompose) → Skill() check → execute → verify.
Enforcement: task-protocol-enforcer blocks Write/Edit until Skill() is called.
Full algorithm: Skill('task-protocol').
- ALL tasks (including trivial) require
Skill()before Write/Edit - trivial (< 1 file, < 30 words): Skill() → Write/Edit
- medium (1-3 files): TaskCreate → Skill() → Write/Edit
- complex (4+ files): TaskCreate (full decomposition) → Skill() → Write/Edit
- Phase machine:
idle → classified → [decomposed] → skill_checked → ALLOW Write/Edit - Exempt:
.claude/,docs/,data/, config files (.json, .toml, .yml, .env)
Token Economy: Z.AI Delegation Protocol (MANDATORY — NEVER SKIP)
RULE: Before generating ANY content > 15 lines, ALWAYS ask: "Can Z.AI generate this?" If YES → MUST delegate. If NO → explain why (architecture/security/debug only). Violation: generating 50+ lines of docs/tests/boilerplate yourself = wasted Opus tokens.
Minimize Opus token usage by delegating content generation to Z.AI via LLM Rotation.
Agent() Model Selection (MANDATORY — NEVER USE OPUS FOR AGENTS)
RULE: NEVER launch Agent() without explicit model parameter. Default inherits Opus = waste.
| Agent task type | Model | Alternative (preferred) |
|---|---|---|
| Web research (GitHub, docs) | DO NOT USE Agent | Direct WebSearch + WebFetch in parallel |
| File search / code lookup | DO NOT USE Agent | Direct Glob + Grep + Read |
| Deep code analysis (10+ files) | model: "sonnet" |
— |
| Code generation in worktree | model: "sonnet" |
llm_complete() + Opus review |
| Simple lookup | model: "haiku" |
Direct tools |
| Architecture / security | DO NOT USE Agent | Opus in main conversation |
Decision flow: Task → Can solve with direct tools? → YES → use them. NO → Agent with model: "sonnet" (never opus).
Violation: Agent() without model parameter = Opus tokens wasted on delegatable work.
Delegation Levels
- Soft (no review): bulk ops (10+ items), translations, formatting
- Medium (Opus review mandatory): docs, decomposition, tests, boilerplate, checklists, templates
- Hard (Opus thorough review mandatory): code writing, refactoring, analysis
- Never delegate: architecture decisions, security, debugging, tasks < 30 lines output, 1C/BSL code (
.bsl/.os) — Z.AI hallucinates the 1C platform API; Opus writes it directly at any size
Orchestrator Mode (MUST use for 3+ output files OR single file >100 lines)
- DECOMPOSE — Opus разбивает задачу на подзадачи, классифицирует каждую (Soft/Medium/Hard/Never)
- PREPARE — Opus строит промпт для каждой делегируемой подзадачи (задача+контекст+формат+ограничения). Each llm_complete call: max_tokens=2048, narrow context per section. ANTI-PATTERN: One llm_complete for entire document → bad quality → Opus rewrites 80% → no savings.
- DELEGATE —
mcp__llm-rotation__llm_complete()для каждой подзадачи (параллельно если независимы) - REVIEW — Opus ревьюит каждый результат (Medium: accuracy; Hard: +logic+security)
- ASSEMBLE — Opus собирает финальный результат, Write() файлы
- FALLBACK — Если Z.AI недоступен (all providers failed) → Opus пишет сам, НЕ останавливается
Single Task Mode (1-2 files, output > 15 lines)
- Classify -> delegation level
mcp__llm-rotation__llm_complete(prompt=..., max_tokens=4096)- Review (Medium/Hard) -> fix inline
- Write final result
If >50% rewrite needed -> reclassify as Never, do it yourself.
Mandatory Opus Review (ALWAYS — NEVER SKIP)
After writing ANY code (.py, .js, .ts, .bsl, etc.) — self-review is MANDATORY:
- Code (any complexity): re-read written code, check logic, edge cases, naming
- Hard tasks: thorough review — logic + security + patterns + edge cases + error handling
- After Z.AI draft: verify names, imports, API calls exist (Z.AI hallucinates project details)
- Format: brief inline review after Write/Edit, before moving to next task
- NEVER skip even for "trivial" code changes — bugs hide in small fixes
- Hook
code-review-enforcer.pyfires on every Write|Edit of code files
Self-Check Questions (ask before EVERY generative task)
- Output > 15 lines? → MUST delegate to Z.AI
- 3+ output files? → MUST use Orchestrator Mode
- Code file changed? → MUST self-review (THOROUGH if src/tools/infra/scripts)
- Z.AI down? → Opus writes, but note "Z.AI unavailable, writing directly"
Full protocol: Skill('z-ai-delegation'). Hooks: z-ai-delegation-enforcer.py (UserPromptSubmit), z-ai-write-guard.py (PreToolUse:Write|Edit — blocks >15 lines without llm_complete), code-review-enforcer.py (PreToolUse Write|Edit).
Триада: Hook + Skill + MCP
Каждое решение, принятое в разговоре, должно стать артефактом. Иначе — потеряно.
- Hook (.py) — автоматизация на событие (
.claude/hooks/) - Skill (.md) — процедурное знание (
.claude/skills/) - MCP Tool — внешний инструмент (
src/mcp_server/) - Cache — накопленные знания (
skills/<domain>/cache/)
Создание компонентов: skill triad-factory (алгоритм) + create-hook (хуки) + doc-to-skill (скиллы).
Hooks Infrastructure
.claude/hooks/
base/protocol.py # BaseHook — abstract base, stdin/stdout JSON, auto-logging (USE THIS)
base/base.py # Alt dataclass-based HookInput with auto-detect event
shared/
invocation_logger.py # JSONL logger (data/hook-invocations.jsonl)
session_state.py # Session: activated/recommended skills dedup, prompt_id, pending_learn, task_protocol, llm_delegation
ralph_state.py # Ralph Wiggum state management
otel_exporter.py # OpenTelemetry OTLP exporter
task_master.py # Task management from hooks (session_start_cleanup: git + code-verify)
code-skill-patterns.json # Pattern->Skill mappings (7 sections, 43 rules)
trust_scorer.py # Trust scoring for sources (Context7/GitHub/SO/Infostart)
skill-router.py # UserPromptSubmit: skill recommendations
skill-eval-enforcer-shell.py # UserPromptSubmit: task protocol + activation enforcement
task-protocol-observer.py # PreToolUse:Skill|TaskCreate|llm_complete: records decomposition, skill activation, Z.AI delegation (migrated from PostToolUse)
task-protocol-enforcer.py # PreToolUse:Write|Edit: blocks if protocol phase is idle
code-skill-enforcer.py # PreToolUse:Write|Edit|Bash: skill-first enforcement (6 levels A-F + A.1 research_protocol, protocol.py base)
code-verify-reminder.py # PreToolUse:Write|Edit: mandatory code verification task creation (migrated from PostToolUse)
code-review-enforcer.py # PreToolUse:Write|Edit: mandatory code review reminder (migrated from PostToolUse)
docs-change-tracker.py # PreToolUse:Write|Edit: maps code changes to docs (migrated from PostToolUse)
factory-enforcer.py # PreToolUse:Write: factory steps enforcement for .claude/ files (migrated from PostToolUse)
bulk-action-guard.py # PreToolUse:Bash: detects destructive commands BEFORE execution (migrated from PostToolUse, now proactive)
approval-gate.py # PreToolUse:Skill: blocks implement-1c-task/opsx:apply without approved design (SDD Phase 3)
skill-usage-metrics.py # PreToolUse:Skill: logs skill invocations (migrated from PostToolUse)
posttooluse-skill-metrics.py # PostToolUse:Skill: confirmed activation logging + hookSpecificOutput feedback
posttooluse-web-cache.py # PostToolUse:WebSearch|WebFetch: cache results 24h TTL
posttooluse-docs-tracker.py # PostToolUse:Write|Edit: instant docs update reminder via hookSpecificOutput
posttooluse-quality-feedback.py # PostToolUse:Write|Edit: ruff check on *.py, errors via hookSpecificOutput
posttooluse-delegation-tracker.py # PostToolUse:mcp__llm-rotation__llm_complete: delegation outcome tracking
knowledge-cache-reminder.py # PostToolUse:WebSearch|WebFetch: research cache reminder (migrated from Stop)
auto-git-save.py # Stop: auto-commit on threshold
auto-git-save-prompt.py # UserPromptSubmit: commit reminders
git-commit-enforcer.py # Stop: uncommitted changes check
docs-change-enforcer.py # Stop: documentation coverage check (skips infra/, tools/, docker/, *.log, configuration/, src/bsl/). Cooldown: blocks once, then allows for 30 min (prevents infinite loop)
task-enforcer.py # Stop: task list completion check (v2.2: auto-clean stale code-verify tasks)
ralph_wiggum_stop.py # Stop: Ralph iteration enforcement
memory-sync.py # Stop: memory system change advisory
z-ai-write-guard.py # PreToolUse:Write|Edit: blocks >15 lines code without Z.AI delegation
delegation-outcome-tracker.py # PreToolUse:Write: records Write >15 lines to delegation-outcomes.jsonl
delegation-outcome-stop.py # Stop: appends session delegation summary to JSONL
skill-quality-monitor.py # UserPromptSubmit: passive quality metrics logging (data/skill-quality-metrics.jsonl)
bsl-tool-router.py # UserPromptSubmit: routes BSL/1C queries to bsl-development skill
AutoResearch: scripts/skill-health-analyzer.py (health report) + scripts/audit-skill-freshness.py (freshness audit) + scripts/autoresearch.ps1 (autonomous cycle). Templates: ralph.bat --template skill-health|quality|1c-study|autoresearch. Archive: .claude/skills/_archived/. Docs: Chapter 18 (v1), Chapter 20 (v2). AutoResearch v2: three-agent engine (Executor+Reviewer+Comparator), autoresearch.sh (bash), eval: scripts/eval-autoresearch.py, dashboard: scripts/autoresearch-dashboard.py.
Evaluation: scripts/eval-hooks.py + tests/eval/hook_prompts.json (40 тестов, 16 скиллов).
Skill Router Eval: scripts/eval-skill-router.py (64 ground truth, F1/precision/recall) + scripts/skill-router-dashboard.py (CLI dashboard) + CI gate в .github/workflows/ci.yml.
Dashboard: scripts/hook-dashboard.py (CLI) + scripts/skill-enforcement-dashboard.py (enforcement) + src/ui/pages/hook_dashboard.py (Streamlit).
Monitoring: src/pdf_framework/observability/hook_metrics_db.py (SQLite) + tracer.py (OTLP) + /metrics/html (unified dashboard).
Migration: scripts/skill-migration-advisor.py (pattern coverage analysis).
Ralph Wiggum — Autonomous Loop
При работе в автономном цикле (scripts/ralph.bat / ralph.sh):
- В начале итерации:
git log --oneline -5+git diff --stat - Коммиты с префиксом
[RALPH], по одному на логическое изменение - После 3 неудачных попыток — объяснить почему, не зацикливаться
- Маркер завершения:
RALPH_DONE(только когда ВСЕ критерии выполнены) - Stop Hook блокирует преждевременную остановку
- Не изменять файлы вне scope, не удалять
data/без инструкции - Шаблоны:
--template reindex|test-coverage|evaluation|documentation|lint
Spec Driven Development (OpenSpec)
Проект использует OpenSpec v1.2.0 для spec-driven разработки.
- Спецификации:
openspec/specs/ - Активные изменения:
openspec/changes/ - Команды:
/opsx:explore,/opsx:propose,/opsx:approve,/opsx:apply,/opsx:archive - Workflow: Explore → Propose → Approve → Apply → Archive
- Approval Gate: hook
approval-gate.pyблокируетimplement-1c-taskиopsx:applyбезapprovedв.openspec.yaml - Одобрение:
/opsx:approve <change>(ревью + approve) или--reject --comment "причина" - Статус в
openspec/changes/<name>/.openspec.yaml→approval.status: pending|approved|rejected - MCP:
openspec-mcpv0.4.2 (дашборд, approval workflow, WebSocket) - Спецификация — единственный источник правды. Правь спеку, а не код.
- Не создавать новых объектов метаданных без явного указания в specs.
- Валидация: после
/opsx:applyзапуститьbrownfield-validate(Gap + Design + Impl validators) - Delta-specs (brownfield): каждый requirement ОБЯЗАН начинаться с
## ADDEDили## MODIFIEDADDED— объект НЕ существует в конфигурации (проверить черезget_metadata)MODIFIED— объект существует, описывать только дельту (что/было/стало)- НЕ переписывать весь модуль, НЕ дублировать типовую логику БСП/ERP
/opsx:proposeавтоматически вызывает MCP для определения маркера