Commit Graph

1732 Commits

Author SHA1 Message Date
Дмитрий 52e1cfec1a fix(router-gate): stream A path-normalization — $& replacement, narrow catch, BOM/EOF, docs
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 19:48:49 +03:00
Дмитрий e0f6c52f37 feat(router-gate): stream A — path-normalization + glob util (§3.1.1) 2026-05-29 19:36:10 +03:00
Дмитрий 480649db30 fix(rationalization-audit): skip quoted citations to remove false-positives 2026-05-29 18:47:21 +03:00
Дмитрий c4c2afd111 docs(plans): router-gate v4 master coordination plan (9 streams, parallel sessions)
Master plan orchestrates 9 streams (A-H + checkpoints) для параллельного
multi-session запуска. Каждый stream работает над disjoint set файлов
в tools/ или docs/ — 0 conflicts по конструкции.

Streams:
- A: Pure decision modules (8 файлов, ~250 unit tests) — independent
- B: Bash/PowerShell content rules — independent (stub path-norm)
- C: Static scan + framework boot + Glob F8 + MCP classifier — independent
- D: LLM-judge Layer 4 (multi-judge + per-tool + response scan) — independent
- E: AskUser parser + subagent return scanner — independent
- F: VM-sandbox setup (user hands-on) — independent
- G: Cleanup 5 v3.9 hooks + settings.json register — sequential after A-E
- Smokes 1-9 user-run — sequential after G
- H: Brain-retro Table 16-17 + recovery docs + Pravila/PSR/Tooling sync — sequential

Wall-clock: 16-23h parallel (vs 49-65h sequential).

User chose Subagent-Driven execution в параллельных сессиях.
Each parallel session invokes writing-plans для своего stream sub-plan'а,
затем subagent-driven-development для реализации.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 18:47:21 +03:00
Дмитрий 972be5c58a ci: fix pre-deploy-checks paths (APP_DIR + backup dir)
Канонические пути из deploy.yml:
- APP_DIR: /opt/liderra/app → /var/www/liderra/app
- Backup dir: /var/backups/postgresql → /home/ubuntu/deploy-backups/
  (deploy.yml сохраняет pre-deploy backups как app-pre-deploy-*.tgz)

Также Check 4 теперь NOTE вместо FAIL для случаев >24h или отсутствия dir —
deploy.yml сам создаёт свежий backup перед раскаткой.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:29:38 +03:00
Дмитрий 7c5b7215a1 ci: pre-deploy-checks workflow (Pravila §2.4 via Azure runner)
Воспроизводит 8 pre-flight проверок project-local агента prod-deploy-validator
через GitHub Actions runner (Azure), обходя YC backbone-фильтр который
блокирует direct SSH с dev-IP 89.144.17.119.

Read-only — ничего не меняет на проде. Возвращает GO/NO-GO в exit code.

Использует тот же LIDERRA_SSH_KEY что deploy.yml.

Cross-ref: docs/Pravila_raboty_Claude_v1_1.md §2.4, .claude/agents/prod-deploy-validator.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:27:08 +03:00
Дмитрий 0c3552393a docs(incidents): handoff для cleanup activity_log_y2026_m05 после ADR-018 fix
Task 7 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Шаги выкатки cleanup'а 6 mismatches в activity_log_y2026_m05 через
исправленный audit:rebuild-chain (per-tenant per ADR-018):

1. Pre-flight: deploy success + verify baseline (6 mismatches expected).
2. Dry-run через artisan-run workflow (НЕ confirm_apply) — verify Scope =
   "PARTITION BY tenant_id" в output (sanity check Task 4 deploy reached prod).
3. Apply через artisan-run --force + confirm_apply=true.
4. Verify ещё раз: 6 партиций intact.
5. Post: закрыть incident в incidents_log, обновить memory.
6. Rollback: бэкап PG + audit_block_mutation охрана.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:41 +03:00
Дмитрий 720697ae43 style(audit): pint auto-fix на shared config + rebuild rewrite
Task 6 Step 4 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Pint auto-fix purely cosmetic (unary_operator_spaces, phpdoc_align,
ordered_imports, fully_qualified_strict_types, no_blank_lines_after_phpdoc).
Никаких semantic-изменений.

Larastan analyse --level=max на 3 файла: 0 errors.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:41 +03:00
Дмитрий 575f7a1f59 docs(adr): ADR-018 enforcement активирован (Tasks 2+4 завершены)
Task 5 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Активированы 2 декларативных правила в ADR-018:

- rebuild-must-use-shared-config: AuditRebuildChain.php должен читать
  partition_clause из AuditChainConfig (require_pattern matches существующему
  коду после Task 4 fix).
- verify-must-use-shared-config: VerifyAuditChains.php должен читать TABLES из
  AuditChainConfig (require_pattern matches коду после Task 2 refactor).

llm_judge=false (declarative only, zero cost).

adr-judge на staged diff: 0 violations / 0 advisories.

Ref: docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:40 +03:00
Дмитрий 6f3929a7a2 fix(audit): AuditRebuildChain per-tenant rebuild (ADR-018, closes Stage 5 #1)
Task 4 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Переписан AuditRebuildChain под per-tenant semantics ADR-018:

- Drop private COLUMN_CONFIG → читаем AuditChainConfig::TABLES + rowExpression()
- Для tenant-таблиц (partition_clause='PARTITION BY tenant_id'): отдельная
  iteration на каждый tenant. prev_hash scoped to last row with id<from-id
  AND tenant_id=X. Iterate rows of that tenant ordered by id, UPDATE +
  propagate prev_hash forward.
- Для BYPASSRLS-таблиц (auth_log/saas_admin_audit_log, partition_clause=''):
  одна global iteration без tenant scope.
- Информационный output показывает scope ('PARTITION BY tenant_id' или
  'global (within partition)').

NB: deviates from plan SQL (CTE с LAG+UPDATE) — той СтратегиЯ страдает
snapshot-isolation bug. PostgreSQL CTE executes on single snapshot, LAG
видит OLD stored log_hash, не propagate'ит новые хеши downstream. Chain
ломается через >1 row. Существующая PHP-loop архитектура iterating prev_hash
через переменную — корректна и сохранена. Tests подтверждают:

- AuditRebuildChainTest: 7/7 GREEN (включая 3 новых Task 3 теста +
  существующие 4 repair/balance/dry-run/reject — multi-tenant flipped
  RED→GREEN с post-rebuild PARTITION BY tenant_id matching).
- tests/Feature/Audit/: 16 tests / 13 passed / 0 failed / 2 errors / 1 skipped.
- 2 errors orthogonal к Task 4 (deal_id NOT NULL bug в AuditChainRace test +
  webhook_log undefined в OperationalFullFlow) — pre-existing baseline noise.

Ref: docs/adr/ADR-018-audit-chain-per-tenant-semantics.md
     docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:40 +03:00
Дмитрий 307a65e786 test(audit): drop pre-rebuild sanity-check в multi-tenant test
Test env (`SharesSupplierPdo` trait + postgres superuser) обходит RLS, поэтому
trigger `audit_chain_hash()` в тестах пишет global chain, не per-tenant. Это
расхождение с prod (где RLS активен и trigger пишет per-tenant) валидно — но
делает pre-rebuild sanity-check невыполнимым assumption'ом.

Multi-tenant test теперь проверяет только self-consistency post-rebuild:
rebuild должен produce chain matching своему partition_clause.

Pre-Task-4 (global LAG): post-rebuild verify с PARTITION BY tenant_id → mismatch
→ RED (текущее состояние).

Post-Task-4 (per-tenant LAG): post-rebuild verify с PARTITION BY tenant_id →
match → GREEN.

Prod RLS-aware trigger semantics валидируется live `audit:verify-chains`, не в
этом тесте.

Ref: docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:39 +03:00
Дмитрий 88cdd34e98 test(audit): failing tests для per-tenant rebuild (ADR-018, RED phase)
Task 3 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
3 новых сценария в AuditRebuildChainTest.php:

1. multi-tenant — 2 tenants, 4 rows interleaved, rebuild from firstId →
   chain должна остаться intact per-tenant. RED: fails на pre-rebuild
   sanity-check (preMismatches=1) — в test env trigger пишет НЕ per-tenant
   chain (SharesSupplierPdo trait → BYPASSRLS). Task 4 имплементер должен
   разобрать: либо trigger в test env починить (RLS-aware), либо тест
   адаптировать к фактической семантике pgsql_supplier.

2. BYPASSRLS auth_log — INSERT direct через pgsql_supplier, partition_clause=''
   (global chain within partition). Сейчас PASS случайно (single global LAG
   совпадает с tенущим rebuild semantics).

3. single-row partition — 1 tenant, 1 row, rebuild → должна работать.
   Сейчас PASS случайно.

+ new const AUTH_LOG_ROW_EXPR mirror'ит AuditChainConfig::TABLES['auth_log'].

Регрессия narrow: 7 tests / 6 passed / 1 failed (RED expected).

Ref: docs/adr/ADR-018-audit-chain-per-tenant-semantics.md
     docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:39 +03:00
Дмитрий 52eebe28c5 refactor(audit): VerifyAuditChains использует shared AuditChainConfig (ADR-018)
Task 2 плана 2026-05-29-audit-rebuild-per-tenant-fix.md.
Regression-safe refactor: drop private TABLE_CONFIG const + buildRowExpression()
helper, заменить на чтение AuditChainConfig::TABLES (создан в Task 1, commit
4cfd9f6b) + AuditChainConfig::rowExpression($table). Поведение не изменилось —
тот же baseline regression Pest (9 passed pre-refactor → 10 passed post-refactor;
+1 = регрессия-guard VerifyAuditChainsTest.php flipped fail→pass; 2 pre-existing
errors orthogonal к Task 2).

VerifyAuditChainsTest.php — TDD regression guard на cleanness рефактора: проверяет
полноту AuditChainConfig::TABLES (6 таблиц), корректность rowExpression() для
всех таблиц, и отсутствие private TABLE_CONFIG const после refactor'а.

Ref: docs/adr/ADR-018-audit-chain-per-tenant-semantics.md
     docs/superpowers/plans/2026-05-29-audit-rebuild-per-tenant-fix.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:14:38 +03:00
Дмитрий b55ca6507d feat(audit): extract AuditChainConfig shared TABLE config (ADR-018 prep) 2026-05-29 18:14:38 +03:00
Дмитрий 0e768f9aa0 docs(spec): router-gate v4.0+v4.1+v4.2 design (behavioral + max-judges + VM sandbox)
Three-spec package for router-gate next-generation:

- v4.0 base (2249 lines) — поведенческий разворот: removes 16 защит-призраков
  v3.9, adds Round 8 closures, adds 5 Directions (safe-baseline metering,
  skill scope verifier, decomposition detector, TodoWrite verifier,
  brain-retro Table 16). Target aggregate bypass ~15-25%.

- v4.1 max-closure amendment (1051 lines) — Layer 1-4: 8 Round 8 GAPs +
  behavioral hard-blocks + universal vocab removal + 3-judge consensus
  (Sonnet+Haiku+Opus) + per-tool LLM-judge + response scan. Target ~2-5%.
  Cost +$300-1500/month ongoing.

- v4.2 VM-sandbox amendment (411 lines) — Layer 5 phased for solo developer:
  Phase 1 VirtualBox isolation сейчас (~$0, 10-12h), Phase 2 biometric +
  Phase 3 HSM via single YubiKey ($50-150) когда захотите. Two-person rule
  removed (solo dev). Target ~0.5-0.8%.

Combined v4.0+v4.1+v4.2 full: ~0.5-0.8% aggregate bypass (close to
theoretical floor ~0.5% per §1.1 7 fundamental limits).

Implementation: ~49-65h sequential / 30-40h parallel through
subagent-driven-development. User wants parallel multi-session execution
for speed; writing-plans skill next.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 18:13:08 +03:00
Дмитрий 292a16bd63 chore(cspell): add vocab for router-gate v4 specs
New terms: todowrite, gpgsign, socat, yubi/yubikey, амендмент(а),
спеках, виртуалка (declensions), субверсия, monitorится.

Required for cspell pass on v4.0+v4.1+v4.2 spec files (next commits).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-29 18:12:45 +03:00
Дмитрий de3736296d docs(pilot): snapshot 29.05 day+2 — ADR-018 accepted + Stage 5 follow-up plan
ADR-018 (commit 0098db66, Дмитрий) закрепил per-tenant chain semantics canonical. 6 mismatches в activity_log_y2026_m05 переклассифицированы как bug AuditRebuildChain (global rebuild под admin без RLS), не divergence design'а. Trigger + verify согласованы по per-tenant, менять не надо. План фикса (commit e964d70c) — 8 TDD-task'ов, shared AuditChainConfig + rewrite rebuild через LAG OVER. Task 1 выполнен в worktree audit-rebuild-per-tenant-fix commit 4cfd9f6b НЕ на main. Прод-код БЕЗ изменений с deploy 26634115769 (29.05 11:15 UTC). cspell-words.txt: +ретраились/сериализуются/OID (pre-existing в L13 unrelated snapshot).
2026-05-29 16:44:43 +03:00
Дмитрий e964d70c28 docs(plans): ADR-018 Stage 5 follow-up — AuditRebuildChain per-tenant fix
8 TDD tasks (~день кода): extract shared AuditChainConfig, refactor VerifyAuditChains (regression-safe), failing tests для multi-tenant/BYPASSRLS/single-row, rewrite AuditRebuildChain через LAG OVER (partition_clause ORDER BY id) симметрично verify, активация ADR-018 enforcement rules, Pint/Larastan/Pest --parallel smoke, handoff для прод-cleanup activity_log_y2026_m05 через gh workflow run artisan-run.yml. Self-review GREEN на spec coverage / placeholders / типы. Execution mode: subagent-driven.
2026-05-29 15:56:35 +03:00
Дмитрий 0098db6628 docs(adr): ADR-018 audit hash-chain per-tenant semantics canonical
29.05 disk-full incident выявил несогласованность между trigger (per-tenant
через RLS), VerifyAuditChains (per-tenant через PARTITION BY tenant_id) и
AuditRebuildChain (global). 6 mismatches в activity_log_y2026_m05 -
следствие неправильного rebuild'а, не оригинальной порчи.

Decision (User: Дмитрий): per-tenant canonical через RLS scope. Trigger и
verify уже согласованы; AuditRebuildChain - bug, переделать в Stage 5
follow-up (отдельный plan). После фикса re-run на activity_log_y2026_m05 -
6 mismatches исчезнут.

Альтернатива global semantics + переписать trigger SECURITY DEFINER + миграция
БД отвергнута: ослабляет 152-ФЗ tamper-detection + рискованная миграция.

Cross-links: ADR-002 RLS multi-tenancy, incidents/2026-05-29-disk-full-pg-recovery.md,
F1 advisory-lock migration 2026_05_30_000001.

Enforcement-block declarative (require_pattern AuditChainConfig::TABLES) -
активируется после имплементации Stage 5 follow-up.

cspell-words.txt: +партиционированы
2026-05-29 15:32:46 +03:00
Дмитрий a6bde2125a spec(router-gate): concentrate v3.9 — убрать audit-trail и version-history overhead
Заказчик: «перепиши спек, убери все лишние оставь только то что необходимо для
создания плана, но сам план не делай. Только помни нельзя потерять в качестве и
объеме ни в коем случае!»

После 10 раундов adversarial audit спек вырос до 2964 строк / 288KB. Большая часть
объёма — audit-trail и история эволюции через раунды:
- 8 «Changes vX → vY» overview-таблиц в начале (~245 lines)
- 11 версионных entries в §11 v3.9-v1 (~380 lines)
- inline traceability markers «v3.6 R5-audit H1 fix:» / «v3.7 R-NEW-4 closure:»

Эта информация дублируется (mechanism описан и в TL;DR overview, и в §11 entry,
и in-place в §3-§5) и НЕ нужна для составления implementation плана.

Что убрано (НИ ОДНОГО технического механизма не потеряно):
- Edit 1: «Changes v3.8 → v3.9» giant overview (13-row table + adversarial pre-check
  + implementation breakdown + Главный урок + Generalisable formula + Methodology +
  Связано) → 1 reference paragraph
- Edit 2: «Changes v3.7 → v3.8», «Changes v3.6 → v3.7», ... «Changes v1 → v2»
  (9 overview blocks + 4 FATAL table + Доп v3.8 closures C5-E30 list + adversarial
  pre-check v3.8 table) → один Timeline эволюции v1→v3.9 paragraph
- Edit 4: §11 v3.8/v3.7/v3.6/v3.5/v3.4/v3.3/v3.2/v3.1/v3/v2/v1 entries → один
  условный compaction-summary («### v1 – v3.8 — 9 раундов, 105 holes»). v3.9
  entry полностью сохранён — план будет ссылаться на R7 closure details.

Что сохранено verbatim (100% technical content):
- §1 Цель и контекст / §2 Принципы дизайна
- §3 Архитектура: §3.0 PowerShell hook / §3.0.1 OS-keychain / §3.1 protected paths
  (~80 paths + path normalization NFC/8.3/inode) / §3.2 subagent inheritance +
  parent_random_id sentinel / §3.2.0 10 smokes / §3.2.1 automated bootstrap /
  §3.3 failure modes / §3.4 subagent constraints + tool_result scanner / §3.5
  atomic writes / §3.6 gate budget + state cache / §3.6.1 dep-checksums /
  §3.6.2 normative-content second-layer
- §4 Decision Flow (Поведения 1-4 + §4.5 AskUser parser + §4.6 partial unlock +
  §4.7 question quality detector 3-layer LLM-judge)
- §5 Безопасная база + MCP classification / §5.1 Bash rules (whitelist +
  hard-blacklist + conditional + path-deny + SKILL_BASH_ALLOW + sub-shell sweep) /
  §5.1.2 PowerShell mirror / §5.2 multi-language static scan (PHP/Ruby/Go/Java)
- §6 Recovery: 3 levels + §6.1 cheatsheet + §6.2 PII guard + §6.3 redacted reason
- §7 Logging + §7.1 coverage-hint coordination
- §8 Этапы реализации (implementation order matrix + риски миграции)
- §9 Open questions + acceptable residuals R-NEW-7..R-NEW-19
- §10 Cross-refs + §10.1 functions/registry + §10.2 ALL state schemas verbatim
  (router-state, chain-state, askuser-decisions, router-gate-decisions, subagent-
  inheritance, subagent-block, parent-sentinel, restricted/journal-access-log,
  edited-files, coverage-hint, gate-errors, gate-config v3.9 fields, session-counters)
  + §10.3 test strategy + §10.4 success metrics + §10.5 rollback + §10.6 parallelism
- §11 v3.9 entry полный (R7 closure mechanism + generalisable formula + 13-row table)

Verification:
- Spec: 2964 → 2404 строк (-560 lines / -19%); технический объём ≥99%
- Mechanism keyword counts: fs.lstatSync 4 / parent_random_id 29 / SKILL_BASH_ALLOW 9
  / schema_version 11 / Поведение[1-4] 17 / node_modules 15 / claude-md-management 19
  / approve_git_operation 28 / subagent-block 14 / restricted/ 21 / keytar 15
  / shell-quote 17 / dep-checksums 11 / multi-judge 8 / NFC|normalize 12
  / mcp_tool_classification 7 / /etc/hosts 11 / git rev-parse HEAD 5
- markdownlint 0 errors; cspell 0 issues
- All §1-§11 sections intact (12 top-level headings preserved)

§0 cross-refs не меняются — spec-only, не tooling-канон / не ADR / не off-phase
подкатегория. Self-contained для writing-plans skill input в следующей сессии.

Methodology: EnterPlanMode → write plan → user approval → ExitPlanMode → 4 Edits
(Edit 3 inline-marker trim skipped как cosmetic — quality бы не выросло).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 14:58:46 +03:00
Дмитрий 34bcc570ad fix(setup-logrotate): add 'su postgres postgres' directive для PG logrotate
ремонт: logrotate отказал rotation PG log из-за insecure parent dir permissions

/var/log/postgresql/ имеет permissions drwxrwxr-t (group-writable + sticky).
Logrotate refuses to rotate без явного su directive в config.
Стандарт postgresql-common тоже использует 'su' — копирую идиому.
2026-05-29 14:48:05 +03:00
Дмитрий 6383da7f12 chore(incident-followup): close 4 tails from 29.05 disk-full incident
ремонт: incident-followup cleanup batch — 4 хвоста

1. Larastan baseline regenerated (was 161 errors pre-existing IDE helper drift)
2. Deptrac Mail: [Model, Service] + ADR-005 amend (was 4 pre-existing violations)
3. PG logrotate config in setup-logrotate.yml
4. F1 6 mismatches — RCA updated (algorithm divergence trigger global vs verify per-tenant)

+3 cspell words: notifempty, missingok, верифицируется.

Ref: docs/incidents/2026-05-29-disk-full-pg-recovery.md §4-5
2026-05-29 14:45:28 +03:00
Дмитрий 8910ae6cd6 spec(router-gate): v3.8 → v3.9 Round 7 audit closure (13 классов, 3 фундаментальные плоскости)
Round 7 adversarial audit (через superpowers:brainstorming skill) выявил 13 классов
которые 9 предыдущих раундов не покрывали:
- 2 FATAL: F5 Read-leak parent_random_id через Glob+Read (R-NEW-4 обнулён),
  F6 subagent tool_result.content exfil
- 4 CRITICAL: C12 system DNS/config (/etc/hosts/~/.ssh/registry) вне §3.1,
  C13 || true exit-code spoof (per-token vs per-chain),
  C14 subagent state exfil,
  C15 §5.2 multi-language gap (PHP/Ruby/Go test runners)
- 5 SERIOUS: S22 Skill(claude-md-management) exemption backdoor,
  S23 Workflow args parameter payload,
  S24 path-equivalence (Unicode NFC/NFD + Windows 8.3 + hardlinks),
  S25 MCP filesystem/redis write tools classification,
  S26 stop-keywords morphology gaps
- 2 EDGE: E31 gate-error reason disclosure (probing pattern),
  E32 LLM-judge cache cross-session persistence

18 spec edits: header bump + TL;DR + Changes v3.8→v3.9 table + §3.1 system paths
+ parent-sentinel→restricted + §3.4 PostToolUse Task scanner + §3.6.2 normative-content
second-layer gate + §4.5 stop-keywords expanded + §4.7 cache per-session + §5 MCP
classification + §5.1 chain ANY-mutating + PostToolUse rev-parse verify + §5.1.2
PowerShell mirror + §5.2 multi-language scan + §6.3 redacted reason mode + §9 13 closures
+ §10.2 gate-config v3.9 fields + §11 v3.9 history entry.

Spec: 2554 → 2964 строк (+410 lines). Budget: 45-60h (v3.8) → 53-72h (v3.9).
Закрыто 118 holes total через 10 раундов adversarial audit.

cspell-words.txt +18 терминов (exfiltration/exfil/NFD/RCE/syscall/Inodes/PROGRA/
resolv/nsswitch/ics/HKCU/HKLM/fsutil/unstar/mvn/popen/брэйншторм/стопаем).

Generalisable formula R7 (новая): для каждого следующего audit задавать 3 вопроса
до enumeration — какие safe tools/paths/chains дают visibility/leverage; какие
границы scope подразумеваются но не enforce'ятся; где per-token vs per-chain
formulation gap есть в композиции.

§0 cross-refs не меняются — spec-only, не tooling-канон / не ADR / не off-phase
подкатегория.

Methodology: superpowers:brainstorming skill + AskUserQuestion scope choice
(user выбрал «Полное v3.9 closure всех 13»).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 14:36:36 +03:00
Дмитрий d181e98046 docs(claude-md): v2.40 add §5 п.13 NB (mixed-diff blocks docs-only short-circuit) + §5 +п.15 (memory-coverage rejects chain channels)
Two operational gotchas discovered в session 29.05.2026 (router-gate v3.6-3.8 sweep + post-sweep memory updates):

1. §5 п.13 NB — docs-only short-circuit считает строго .md-суффикс.
   cspell-words.txt / package.json / lefthook.yml рядом со spec.md
   делают diff mixed → verify-before-push активен → нужен vitest sentinel
   ИЛИ override. Прецедент: commit 46c43169.

2. §5 +п.15 — enforce-memory-coverage hook не принимает chain-каналы
   (chain:commit-push-mem-sync etc); требует строго direct:memory-sync
   в свежем turn'е. Memory updates как часть multi-step задачи планировать
   отдельным turn'ом или использовать memory dump override.
   Прецедент: 4-й шаг sweep задачи заблокирован.

Via /claude-md-management:revise-claude-md skill flow.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 14:29:38 +03:00
Дмитрий c5c7e284e1 feat(exceptions): reduce verbosity для constraint violations (SQLSTATE 23xxx)
ремонт: incident 29.05 cause — 420k stack traces в laravel.log = 8.7 GB

Adds reportable() handler что для QueryException с SQLSTATE 23xxx (integrity
constraint violations) пишет 1-line warning summary вместо default error report.

3 Pest tests cover: 23505 unique → warning, 42P01 non-constraint → error preserved,
23514 check_violation → warning.

Effect: 420k violations × 35KB stack = 14.7 GB → 420k × 200B warning = 84 MB.
175× reduction in log volume during constraint-violation storm.

NB: LEFTHOOK_EXCLUDE=deptrac,larastan because pre-existing violations не от
этого изменения. User-approved bypass; separate PR will address deptrac.yaml
+ IDE helper regeneration + larastan baseline.

Ref: docs/incidents/2026-05-29-disk-full-pg-recovery.md §5
2026-05-29 14:14:04 +03:00
Дмитрий 8fde6a3b50 ops(prevention): disk-usage-alert workflow — cron every 30min
ремонт: prevent recurrence of 29.05 disk-full incident

GitHub Actions cron */30 min: ssh + df -h /. Threshold 85% → warning,
95% → critical (job fails, GitHub notifications fire).
Output: GITHUB_STEP_SUMMARY with size/used/avail + likely causes from incident.

Future: extend sql-runner whitelist для INSERT into incidents_log (post-Б-1
Sentry/Telegram bot integration).
2026-05-29 13:57:40 +03:00
Дмитрий 46c4316966 spec(router-gate): v3.6-3.8 sweep — rounds 5/6 closure (45 holes in 22 classes)
Adversarial audit rounds 5+6 на v3.5 spec выявили 45 attack-векторов:
- Round 5 (v3.5→v3.6 + v3.6→v3.7 maximum-closure): 15 + 7 acceptable residual closed
- Round 6 (v3.7→v3.8): 30 attack-векторов в 18 классах вкл. 4 FATAL

v3.6 — Round 5 closure (15 holes, +9 protected paths, Smoke 4-7,
§5.1↔§4.5 sync, recovery-pattern hard-block в §4.7).

v3.7 — Maximum closure pass (7 v3.6 residual + edge): LLM-judge на
каждую AskUser-опцию (R-NEW-1), parent_random_id 256-bit sentinel
(R-NEW-4), restricted/ subdir + journal-reader CLI (R-NEW-2),
shell-quote tokenizer (R-NEW-3), TF-IDF + LLM-judge для off-topic
(R12), smart batching multi-question AskUser (S6), git stash variants
в conditional class (Edge).

v3.8 — Round 6 closure (30 holes в 18 classes):
- F1 PowerShell tool gate (был полностью вне scope §5.1 — обнуляло
  архитектуру на Windows)
- F2 Workflow internal agent() enumeration (nested агенты вне
  gate-visibility — unlimited bypass)
- F3 node_modules whole-dir hard-deny + dep-checksums verification
  через SHA-256 ключевых deps
- F4 LLM-judge anti-injection (delimiter tokens + pre-filter +
  multi-judge consensus Sonnet+Haiku)

§3.1 protected paths расширен +30 entries (memory/CLAUDE.md/Pravila/
PSR/Tooling с Skill exemption для claude-md-management, CI/CD configs,
lint/build configs, plugin cache, shell init, npm configs, node_modules,
parent-sentinel, dep-checksums, expected-path).

§3.0.1 OS-keychain для LLM key (Windows Credential Manager / Keychain /
libsecret через keytar); key не в process.env → не утечёт через npm
test stdout.

§3.2.1 automated bootstrap smoke (1/5/6/7 на каждый session start,
cached 7 days); user-run остаётся для 3/4/8.

§6.1 docs/recovery-procedures.md новый файл — пошаговая шпаргалка
PowerShell-команд для 3 уровней recovery.

Budget: 13.5-20h (v3.5) → 22.5-32h (v3.6) → 33-44h (v3.7) → 45-60h (v3.8).
Закрыто 105 holes total через 9 раундов adversarial audit.

Generalisable lesson v3.8: каждый раунд аудита должен начинать с
abstract classification классов атак до enumeration конкретных дыр.
v3.7 «maximum closure» был maximum внутри границ воображения v3.6 R5-audit;
Round 6 показал что сами границы имели дыры.

Spec: 1980 → 2554 строк (+1110 inserts / -44 deletes за v3.6-3.8 sweep).
+13 терминов в cspell-words.txt (PowerShell aliases, npm deps).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 13:55:11 +03:00
Дмитрий ef19b9f256 fix(f1-rebuild): canonical ROW(...) expression matching AuditRebuildChain.php
ремонт: prev rebuild left 6 mismatches на activity_log_y2026_m05

Previous workflow used t::text::bytea (full row). Canonical algorithm uses
explicit ROW(col1, ..., NULL::bytea, ..., coln)::text::bytea with COLUMN_CONFIG.
Workflow now switches ROW expression by partition family.

+6 cspell words: psql/euo/coln/esac/cnt/bytea.
2026-05-29 13:53:18 +03:00
Дмитрий 1c4c22ab5e fix(f1-rebuild): use shell expansion для PARTITION/FROM_ID в DO block
ремонт: psql \set vars не expand'ятся в server-side plpgsql DO block

В section 2 (DO $rebuild$ block) использовал :'partition' и :from_id —
client-side psql substitution не работает внутри DO (server-side parse).
Заменил на shell expansion ('$PARTITION', $FROM_ID) до psql.
Sections 1+3 без изменений (plain psql statements там работают).
2026-05-29 13:43:30 +03:00
Дмитрий 1001b89a91 ops(incident-followup): f1-rebuild-via-superuser workflow
ремонт: F1 chain rebuild для 152-ФЗ целостности

Closes deferred item from docs/incidents/2026-05-29-disk-full-pg-recovery.md §4.1.
Sequential hash recomputation в plpgsql DO-блоке через sudo -u postgres psql.
Identical алгоритм с trigger audit_chain_hash() (post-F1 advisory-lock).

Inputs: partition (whitelist), from_id, dry_run/confirm_apply.
Safety: partition whitelist, ON_ERROR_STOP, COMMIT only after full loop.
2026-05-29 13:40:11 +03:00
Дмитрий 9f44b82f8f docs(incident): root-cause report 2026-05-29 disk-full PG recovery loop
ремонт: incident response 29.05 (4h prod downtime) — root cause report + cspell words

Full timeline, 3-factor RCA (B1+SMS constraint loop / no fast-fail / no size-based
logrotate), incident response actions, deferred items (F1 chain rebuild + PG log
rotation), action items.

+3 cspell words: lsn, биндинги, ретрае.
2026-05-29 13:31:19 +03:00
Дмитрий a21712c9e1 ops(incident-prevention): setup-logrotate workflow для Laravel logs
ремонт: 8.7G laravel.log сожрал диск 29.05 — нужна size-based rotation 50M/5 копий

Installs /etc/logrotate.d/laravel-liderra:
- size 50M (rotate when >= 50MB, не daily)
- rotate 5 (keep 5 rotated copies = max ~250MB total)
- compress + delaycompress
- copytruncate (atomic, не сбивает Laravel file handle)
- su/create www-data:www-data

Verified через logrotate --debug + --force.
Prevents recurrence of disk-full incident 2026-05-29.
2026-05-29 13:25:40 +03:00
Дмитрий 1e5378da94 ops(incident): allow audit:rebuild-chain в artisan-run whitelist
Adds audit:rebuild-chain --partition=<name> --from-id=<n> [--force] to MUTATING_RE
regex group. Required to rebuild hash chain on 2 broken partitions
(activity_log_y2026_m05 from id=599, balance_transactions_y2026_m05 from id=462)
after F1 advisory-lock migration applied.

Ref: docs/superpowers/plans/2026-05-29-audit-chain-race-fix.md Step 3.3
2026-05-29 13:15:29 +03:00
Дмитрий 8092bdb024 ops(incident): f1-apply-via-superuser workflow
ремонт: deploy.yml fail на F1 миграции — schema public требует postgres superuser, у crm_migrator нет прав на CREATE OR REPLACE FUNCTION

Applies F1 audit-chain advisory-lock migration via sudo -u postgres psql,
then INSERTs migration row so subsequent php artisan migrate skips it.
Workaround for prod deploy where crm_migrator can't modify public schema.
2026-05-29 13:03:05 +03:00
Дмитрий 7f7036f3ab ops(incident): disk-recover v2 — laravel.log 8.7G + sudo bash redirect для PG log
ремонт: v1 освободил только 440M (apt clean + nginx gz); главный виновник — laravel.log 8.7G + syslog 525M + playwright cache 440M; sudo truncate на PG log дал Permission denied — workaround через sudo bash -c ': > file'

Targeted fixes for v1 issues:
- laravel.log 8.7G + laravel.log.1 572M → truncate via sudo bash redirect
- syslog 525M → truncate
- PG log 497M → workaround via sudo bash redirect (sudo truncate gave Permission denied)
- /var/www/.cache/ms-playwright ~440M → removed (dev cache, not needed in prod)
2026-05-29 12:48:04 +03:00
Дмитрий 883908ea78 ops(incident): disk-recover workflow for liderra.ru / 100% full
ремонт: PG в PANIC loop из-за / 19G/19G/0, нужна целевая чистка логов чтобы PG смог записать checkpoint и завершить recovery

Diagnose + safe cleanup workflow:
- truncate /var/log/postgresql/postgresql-16-main.log (PG в PANIC, inode preserved)
- journalctl --vacuum-size=200M
- nginx old *.gz >3 days
- apt-get clean
- Laravel storage/logs *.log >7 days
- generic /var/log *.gz >50M

Triggered manually via gh workflow run disk-recover.yml -f confirm_apply=true
Guard: confirm_apply must be true.
2026-05-29 12:45:44 +03:00
Дмитрий f187425835 ops(incident): pg-diagnose workflow for PostgreSQL recovery diagnosis (on main for gh workflow run dispatch)
ремонт: PG не отвечает 20+ мин, нужен диагностический workflow

Read-only SSH-based diagnostic for PG-not-accepting-connections incident:
systemctl/journalctl/df/free/uptime + tail /var/log/postgresql/postgresql-16-main.log
+ WAL size + dmesg + HTTPS probe of liderra.ru.

Triggered manually via gh workflow run pg-diagnose.yml.
No production mutations.

(Cherry-picked from feat/router-gate-hard-wall 8cbb84e1 — gh workflow run
requires file on default branch.)
2026-05-29 12:39:18 +03:00
Дмитрий 8b60a18298 plan(router-gate): 51-task implementation plan (audit-integrated)
Master implementation plan covering:
- 6 phases per spec §8 Этапы (1 / 1.1-1.8 / 2 / 2.1.0 smoke / 2.1
  subagent inheritance / 2.2 constraints + block-file / 2.3
  branch-switch / 3 settings.json / 4 recovery / 6 brain-retro)
- 51 TDD tasks with bite-sized 3-5 steps each
- All 8 MUST critical inline fixes integrated (CRITICAL-1/3/4/5/6/8/9/10)
- All 5 SHOULD-FIX findings tasked (vitest globalSetup / git format-patch /
  approved_action_pattern / chain reset organic-only / chain-state
  malformed fail-CLOSE)
- 5 DOS findings tasked (D-1/2/3/8/9) + 2 deferred (D-7 subagent
  reader-writer lock, partial coverage; full split deferred to refinement)

Architecture: single PreToolUse hook tools/enforce-router-gate.mjs
+ PostToolUse handler tools/router-gate-post.mjs. Pure decision
functions in tools/router-gate-{decide,bash,askuser,path,state,
static-scan,quality,chain,coverage,cache,config,subagent}.mjs +
thin I/O wrapper. 10 state files at ~/.claude/runtime/*.

Execution: subagent-driven-development (recommended) или
executing-plans inline. Plan self-review verified all 63 spec
design decisions + 13 audit-driven decisions covered.

Source spec: 2026-05-29-router-gate-hard-wall-design-condensed.md
(commit 71b07e52, audit-integrated).
Audit report: 2026-05-29-router-gate-condensed-adversarial-audit.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 10:06:06 +03:00
Дмитрий 71b07e52eb audit(spec): 51 findings + 8 MUST critical fixes inline
Adversarial audit condensed router-gate spec через 3 parallel
Sonnet adversaries (9 attack zones). 51 finding total:
10 BYPASS-COMPLETE + 17 PARTIAL + 9 DOS + 15 INFO. Spec
заявление «hard wall полный» НЕ выдерживает.

8 MUST critical inline fixes applied:
- §5.1 Bash: <<< here-string, node REPL/stdin block,
  < input redirect, tokenizer per-arg path-deny check
  (closes CRITICAL-9/8/6 + PARTIAL-15)
- §3.1 path normalization: UNC \?\ prefix strip,
  8.3 short names expand via GetLongPathName,
  unresolved $VAR fail-CLOSE
  (closes CRITICAL-3/4/5)
- §4 Поведение 1: source restriction — detector проверяет
  только organic root user prompt, НЕ AskUser chosen_label
  (closes CRITICAL-1 design flaw)
- §8 Implementation order matrix: Этап 2.3 branch-switch
  rewrite MUST complete BEFORE Этап 3 enforce-mode
  (closes CRITICAL-10 S8 migration regression)
- §1.4: gate-config.json protected с Этапа 1.4 ранее
  (closes DOS D-1 tiny-budget patch attack window)

5 SHOULD-FIX + 5 DOS-MUST-ADDRESS deferred в writing-plans
(§9 «Audit findings deferred» documented для plan pickup).

Audit report saved at:
docs/superpowers/audits/2026-05-29-router-gate-condensed-
adversarial-audit.md

cspell-words.txt: +UNC, +EACCES (valid technical terms).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 09:50:18 +03:00
Дмитрий 2c8e6146fb docs(handoff): stage 5 findings 1+2 merged + prod-deploy commands ready 2026-05-29 09:45:59 +03:00
Дмитрий d4f7e681f6 docs(spec): condensed plan-ready router-gate hard wall v3.5
Prep для writing-plans фазы: 1489 → ~850 строк (-43%) убрав
§11 историю версий + 4 TL;DR «Changes vN→vN+1» блока + inline
audit-метки «closes Дыра N v4-audit».

Sonnet subagent verified 63/63 design decisions present + 3
места где condensed улучшил оригинал (subagent-inheritance
schema без stale parent_router_state_path полей, §8 Этап 1.2
+git-pattern, §10.6 sequential 2.1.0→2.1→2.2→2.3).

Оригинал 2026-05-28-router-gate-hard-wall-design.md v3.5 не
тронут (audit-trail сохраняется в git log).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 09:21:19 +03:00
Дмитрий 0067174154 docs(audit): mark Tasks 1-3 complete, add prod deploy instructions
Tasks 1-3 DONE on branch worktree-agent-acf422b86772ab536:
- Task 1 (06fbb238): race condition test (pcntl skip + pg_locks advisory check)
- Task 2 (41fb0d94): migration — pg_advisory_xact_lock in audit_chain_hash
- Task 3 (7081f2a7): audit:rebuild-chain command + 4 GREEN tests

Task 4 updated with factual prod deploy steps:
- merge worktree branch to main + deploy.yml
- artisan-run whitelist needs audit:rebuild-chain in MUTATING_RE
- --force flag required (non-interactive CI mode)
- consecutive_failures reset after verified clean chains

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:20:57 +03:00
Дмитрий b502db8fdc feat(audit): add audit:rebuild-chain command for race-condition recovery
Replays sha256 chain in given audit partition from given id:
1. Uses pgsql_supplier (BYPASSRLS) to see all rows regardless of RLS scope.
2. Bypasses audit_block_mutation trigger via session_replication_role=replica
   (session-local SET, does not affect other connections).
3. Recomputes hash per row using the same formula as audit_chain_hash():
   digest(COALESCE(prev_hash,''::bytea) || ROW(col1,...,NULL::bytea,...,coln)::text::bytea, 'sha256')
   Column order from COLUMN_CONFIG matches TABLE_CONFIG in VerifyAuditChains.
4. Supports --dry-run (count without UPDATE) and --force (skip confirmation).

Validated against breaking partitions:
  --partition=activity_log_y2026_m05 --from-id=599
  --partition=balance_transactions_y2026_m05 --from-id=462

Tests: 4 tests — activity_log rebuild, balance_transactions rebuild,
dry-run no-op, unknown partition rejection. All pass (4/4 GREEN).

Refs: docs/superpowers/plans/2026-05-29-audit-chain-race-fix.md Task 3

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:20:57 +03:00
Дмитрий ba3dbbd9be fix(audit): add pg_advisory_xact_lock to audit_chain_hash trigger
Closes race condition where concurrent INSERT workers (webhook handlers)
all read the same prev_hash before any commits, causing hash chain to
branch. Advisory lock key is derived from the partition OID (TG_RELID):
  lock_key := ('x' || lpad(to_hex(TG_RELID::int), 16, '0'))::bit(64)::bigint

This serializes INSERTs to the SAME partition without blocking concurrent
INSERTs to DIFFERENT partitions (distinct OIDs → distinct lock keys).

Hash formula: verbatim unchanged from db/schema.sql:3107-3127:
  digest(COALESCE(prev_hash, ''::bytea) || NEW::text::bytea, 'sha256')

Tested: pg_locks advisory lock presence test passes (pg_advisory_xact_lock
visible in pg_locks during INSERT transaction).

Refs: docs/superpowers/plans/2026-05-29-audit-chain-race-fix.md Task 2

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:20:56 +03:00
Дмитрий 15df5b4a46 test(audit): failing test for audit_chain_hash race condition
Two tests:
1. pcntl_fork concurrent-INSERT test (skipped on Windows/no pcntl) —
   demonstrates chain branch when 5 workers insert into the same partition
   simultaneously; passes after advisory-lock migration.
2. pg_locks advisory lock presence test (Windows-compatible) —
   verifies that pg_advisory_xact_lock is actually held in pg_locks
   during an INSERT transaction, proving the migration works.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:20:55 +03:00
Дмитрий f97103b05f fix(review): apply F2 review feedback — sql-runner semicolon guard + RouteSupplierLeadJob original_error log capture
Important fix (sql-runner.yml): Reject multi-statement SQL — `SELECT 1; UPDATE supplier_leads ...` was passing READ_RE whitelist and executing the second statement on prod without confirm_mutating=true. Added explicit `*";"*` guard before regex checks.

Minor fix (RouteSupplierLeadJob.php): Capture `$originalError = \$lead->error` BEFORE `\$lead->update(...)`. Laravel mutates the in-memory model, so reading `\$lead->error` after update returns the already-suffixed value, making Log::info `original_error` field useless for debugging.

Both findings from F2 review subagent on commit c8c089cb.

Test verification: 10/10 Pest GREEN (6 SupplierWebhookFastFail + 4 SingleLeadStorm).
2026-05-29 09:11:28 +03:00
Дмитрий c454a3bedd docs(plan): update Task 4 with actual deployment commands (no migrations needed)
Task 4 уточнён: нет миграций (только PHP), fast-fail активируется сразу после
деплоя. Добавлены конкретные gh workflow run команды для cleanup (Steps 3-4 из
sql-runner.yml) и верификации шторма + incidents алерта. Галочки [ ] оставлены
(задача контроллера, не агента).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:11:28 +03:00
Дмитрий 84620665a5 feat(incidents): single-lead-storm detection in incidents:watch-failures
Добавлен БЛОК 5 в IncidentsWatchFailures::handle() — детекция шторма от
одного supplier_lead_id. Если один lead_id генерирует >= threshold-single-lead
failures за окно (default=1000) → severity=high инцидент с root_cause
'single-lead-storm:<lead_id>'. Дедуп по dedup-window как в остальных блоках.

Новая опция: --threshold-single-lead=1000 (configurable).

Мотивация (Finding 2 Stage 5, 2026-05-29): supplier_leads 1110+1157 генерировали
~256k строк в failed_webhook_jobs за 24ч без алерта. Этот блок создаёт incident
уже при 1000+ failures одного лида в 10-минутном окне — что позволяет обнаружить
шторм в течение первого часа.

Связь с Task 2 (fast-fail): вместе эти два изменения stop new storms (Task 2)
и alert on remaining storms (Task 3).

Tests: 4 passing в SingleLeadStormTest.php
- детекция шторма (>= threshold)
- НЕ создаёт incident при распределённых failures
- default threshold=1000
- dedup (второй запуск = 0 новых инцидентов)

Task 3 plan 2026-05-29-supplier-webhook-fast-fail-and-stuck-cleanup.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:11:27 +03:00
Дмитрий b28a9c030c feat(supplier): fast-fail in RouteSupplierLeadJob for terminal errors
Closes failed_webhook_jobs storm class (Finding 2, 2026-05-29):
поставщик crm.bp-gr.ru шлёт B1+SMS combo → DomainException в
SupplierProjectResolver → 3 retries → failed() записывает error в supplier_lead
→ RetryFailedSupplierJobsCommand при следующем dispatch видит тот же lead →
~256k строк/сутки.

Fast-fail guard добавлен в RouteSupplierLeadJob::handle() МЕЖДУ двумя
существующими idempotency-guard'ами и parseProjectField. Если supplier_lead.error
содержит terminal pattern ('does not support' / 'platform mismatch' /
'no matching supplier_project') и processed_at IS NULL — job помечает processed_at
и выходит без записи в failed_webhook_jobs.

Correction 1: реальный класс RouteSupplierLeadJob (не ProcessSupplierWebhookJob).
Correction 3: место вставки — после processed_at guard, до parseProjectField.

Tests: 6 passing в SupplierWebhookFastFailTest.php
- fast-fail на 3 terminal patterns
- НЕ fast-fail при error=null (нормальный лид)
- НЕ fast-fail при processed_at уже установлен (idempotency guard первым)
- НЕ fast-fail при transient ошибке (не matching pattern)

Task 2 plan 2026-05-29-supplier-webhook-fast-fail-and-stuck-cleanup.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:11:27 +03:00
Дмитрий 002b8c4c35 ops(sql-runner): add whitelisted SQL workflow + stuck-leads cleanup doc
.github/workflows/sql-runner.yml — универсальный SQL-runner для прод-операций
через GitHub Actions (workflow_dispatch). Whitelist: SELECT/WITH/EXPLAIN (read-only)
+ targeted UPDATE/DELETE на 5 таблицах при confirm_mutating=true.

docs/ops/2026-05-29-stage5-stuck-leads-cleanup.md — шаблон rollback log + инструкции
для cleanup 2 застрявших supplier_leads (id=1110, 1157, ~256k failed_webhook_jobs).
Root cause: поставщик crm.bp-gr.ru шлёт B1+SMS combo,
constraint chk_supplier_projects_b1_not_for_sms запрещает (Finding 2 Stage 5).

Task 1 plan 2026-05-29-supplier-webhook-fast-fail-and-stuck-cleanup.md.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-29 09:11:26 +03:00