Commit Graph

996 Commits

Author SHA1 Message Date
Дмитрий 774763c21c feat(brain): aggregator — node heat, distributions, redirect rate (+4 tests) 2026-05-19 16:23:50 +03:00
Дмитрий c1b690edd3 feat(brain): Лента auto-poll with pause (5s interval, view-driven) 2026-05-19 16:23:50 +03:00
Дмитрий e34b11aca5 feat(brain): Лента view — groupBySession + grouped feed UI 2026-05-19 16:23:49 +03:00
Дмитрий b4f4f441b5 feat(brain): Разбор view UI — list + filters + trajectory highlight 2026-05-19 16:23:49 +03:00
Дмитрий 475e233c2a feat(brain): filterEpisodes + 3 tests (Task 7 logic; UI deferred)
Worktree has no app/node_modules — vitest not run here; final regression
deferred to main-checkout post parallel-session release. Logic is a 7-line
pure filter; tests cover empty filter, classification, errors-only.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:23:48 +03:00
Дмитрий 3e289479f0 feat(brain): Карта view — plain topology + design conflicts list 2026-05-19 16:23:48 +03:00
Дмитрий 0cee520f0d feat(brain): dashboard shell + graph banner + view switching 2026-05-19 16:23:47 +03:00
Дмитрий c3392bef13 feat(brain): node attribution — episode signals to graph nodes 2026-05-19 16:23:46 +03:00
Дмитрий 7fed5bc18b feat(brain): episode JSONL parser + v1/v2 normalizer 2026-05-19 16:23:46 +03:00
Дмитрий 43028228c8 refactor(brain): extract automation-graph topology to a shared data file 2026-05-19 16:23:45 +03:00
Дмитрий f1092772fb feat(brain): static server + /api/episodes for the dashboard 2026-05-19 16:23:45 +03:00
Дмитрий 702c2ff7b5 fix(brain): correct vitest command in plan — run from app/
The config's include `../tools/*.test.mjs` resolves relative to its
own dir (app/), not cwd. Baseline verified 2026-05-19 from app/:
11 files, 169 tests passing, 0 failures.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:23:44 +03:00
Дмитрий b75f9e3d21 docs(brain): brain dashboard implementation plan
13 tasks across 3 phases — static server + topology extraction + 4 views
(Карта / Разбор / Лента / Агрегат). TDD on dashboard-core.js, smoke on UI.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:23:44 +03:00
Дмитрий 2e26edbb3a docs(brain): brain dashboard design spec
Standalone HTML dashboard that visualises the observer episode log over
the automation-graph topology — 4 views (map / task-replay / session
feed / aggregate), graph as shared canvas, 3-phase build order.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 16:23:43 +03:00
Дмитрий 643e1a5dcf fix(supplier): refresh-session.js — устранена гонка Promise.all/click
Логин-страница уже в состоянии networkidle → waitForLoadState резолвился
мгновенно (до пост-логин редиректа), скрипт хватал PHPSESSID
неаутентифицированной логин-страницы. CSV-сверка 11:00 (19.05) упала
"load-reports returned non-array response" — портал отдал HTTP 200
+ HTML логин-страницы вместо JSON-массива отчётов.

После клика submit:
- waitForFunction опрашивает исчезновение #loginform-username из DOM
  (переживает навигацию);
- guard exit 1, если форма осталась — отклонённый логин больше не
  маскируется под «успех» (exit 0).

Verified: 2× RefreshSupplierSessionJob → валидная сессия (load-reports
JSON-массив из 39 отчётов); CsvReconcileJob id=7 status=ok.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 15:26:39 +03:00
Дмитрий 21f1d7833b chore: .gitattributes — force LF for *.mjs (prevent CRLF/vitest breakage)
core.autocrlf=true rewrites .mjs to CRLF in the working tree on
checkout/rebase. vitest fails to load CRLF .mjs files with imports
(SyntaxError: Invalid or unexpected token, no location) — node --check
and esbuild tolerate it, only vitest's transform breaks. `*.mjs text
eol=lf` pins LF in the working tree regardless of autocrlf.

See memory quirk #100. Repo blobs were already LF — no content change.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 14:05:36 +03:00
Дмитрий 9e1a07aad3 chore(observer): remove 5 empty unknown-* episode stubs + commit session episodes
unknown-<ts>, empty events, fake outcome:success) — zero information.
Removed; remaining episodes carry real data. One-time cleanup of
pre-extension garbage — append-only stays the operational rule.
STATUS.md regenerated by C4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:40:37 +03:00
Дмитрий b2b9a75731 feat(observer): AskUserQuestion in-turn choice + parallel_session narrowing
#1 — detectAskUserQuestionChoice: when a turn contains an AskUserQuestion
whose answer exactly matches an offered option label, classify as
user_chose_from_options. The answered entry carries a structured
toolUseResult (questions[].options[].label + answers map). A custom
"Other" free-text answer is NOT a pick — falls through. Wired into
parseTranscript after the text-list detector.

#3 — parallel_session: dropped broad word matches (параллельн /
"parallel session") that false-fired on any casual mention. Now only
strong collision evidence (foreign git index / чужой staged /
index.lock / another git process). Best-effort per spec R2 — prefer
false-negative over false-positive.

169/169 tools tests GREEN (+9 new).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:39:09 +03:00
Дмитрий 287332eddf docs: CLAUDE.md header version drift fix — 2.18 -> 2.20
Header «Версия» line lagged at 2.18 while §9 already carried v2.19
(factor-analysis extension) and v2.20 (phase 1.1) entries — pre-existing
drift from f7f37fb. Header now reflects actual latest version; v2.18
summary demoted to «v2.18 наследие». Full per-version detail stays in §9.

Через /claude-md-management:claude-md-improver (§5 п.10).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:39:08 +03:00
Дмитрий 8550ba243d fix(observer): exclude synthetic user-role messages from turn detection
Root cause (systematic-debugging): isRealUserPrompt treated skill-content
("Base directory for this skill:"), local-command output
(<local-command-stdout>), and interrupt markers as genuine prompts.
findTurnStart then anchored a turn on the synthetic message — the turn
slice missed the genuine prompt's UserPromptSubmit hook_additional_context
attachment → economy_level: null, wrong prompt_signal/task_classification.
Same cause made extractLastUserPromptText return skill content, so the
Stop-hook routing-gate false-positive-blocked autonomous §12 skill
invocations (detectMethodDirected saw the node name in skill text).

Fix: SYNTHETIC_PROMPT_MARKERS + isSyntheticPrompt — isRealUserPrompt
returns false for synthetic messages. One fix closes both the
economy_level capture gap and the 2nd routing-gate FP class.

160/160 tools tests GREEN (+3 new).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:39:06 +03:00
Дмитрий ad09db606a docs(supplier): closure — project channel failover epic (12 tasks)
Все 12 задач плана docs/superpowers/plans/2026-05-19-supplier-project-channel-failover.md
выполнены. Резервный канал миграции проектов Лидерра → crm.bp-gr.ru:
3 яруса — AJAX rt-project-* → авто-браузер формы «Мои проекты» →
operator worklist (supplier_manual_sync_queue).

Задачи: T1 live recon rt-project-* контракта · T2 SupplierProjectChannel
interface + AjaxProjectChannel · T3 supplier_manual_sync_queue (schema v8.25)
· T4 FailoverProjectChannel escalation matrix · T5 portal-side dedup ·
T6 manage-project.js · T7 FormProjectChannel + DI · T8 wire jobs ·
T9 cron 20:30→18:00 / 20:15→17:45 · T10 admin endpoints · T11 admin UI ·
T12 регрессия + code-review.

Регрессия зелёная: Pest 973/970/0 / 3 skipped / 2847 assertions;
Vitest 882/0 / 3 skipped (111 files); Pint clean; gitleaks 14 commits /
0 leaks; markdownlint + lychee clean. Larastan: изолированный прогон по
supplier-failover файлам — 0 реальных ошибок (полный baseline-drift —
артефакт worktree-env, _ide_helper_models.php отсутствовал; финальная
larastan-верификация — в основной копии после merge, memory quirk).

Финальное code-review (Opus): найден + исправлен 1 CRITICAL (контракт
listProjects — нормализация сырых rt-строк) + I1 (log дедуп-сбоя).

ОГРАНИЧЕНИЯ (не верифицировано в этой сессии):
- Live smoke по 3 ярусам (план T12.1-12.3) НЕ выполнен — требует боевого
  портала crm.bp-gr.ru, queue worker, форс-фейлов DI и создания тестовых
  проектов на живом портале. Откладывается на отдельную сессию с
  присутствием заказчика.
- Code-review I2 (partial-unique индекс supplier_manual_sync_queue от
  дубль-эскалаций при job-retry) и I3 (lockForUpdate в manualQueueResolve)
  — follow-up до прод-релиза (эпик гейтится Б-1, не в проде).
- Larastan полный baseline — пересинхронизировать в основной копии.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:12:30 +03:00
Дмитрий c27539ca29 chore(supplier): markdownlint fix — CHANGELOG v8.25 metrics line
Строка метрик начиналась с «+ 121 индекс» после переноса → markdownlint
MD004/MD032 (трактовал как list-item). Переформулирована через запятые.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:11:32 +03:00
Дмитрий 9b4bff48f0 fix(supplier): normalize rt-projects-load — dedup contract (code-review C1)
Финальное code-review вскрыло CRITICAL: dedup-сверка findOnPortal и
manualQueueResolve матчат строки портала по {platform, signal_type,
unique_key}, но listProjects отдавал сырое тело rt-projects-load.

Сырая форма (verified из recon-снапшота 2026-05-19):
- ответ — конверт {projects:[443 строки], tags, users, ...}, НЕ голый массив
  → listProjects возвращал весь dict, findOnPortal итерировал по ключам
  конверта (projects/tags/...) вместо строк проектов;
- строка проекта: {id, name:"B<n>_<key>", type:"hosts|calls|sms", content}
  — без platform/signal_type/unique_key.

Фикс:
- SupplierPortalClient::listProjects — извлекает body['projects'].
- AjaxProjectChannel::listProjects — нормализует сырые строки в контракт
  SupplierProjectChannel: platform <- префикс name "B<n>_", signal_type <-
  type (hosts->site/calls->call/sms->sms), unique_key <- content. Сырые
  поля сохранены. findOnPortal + manualQueueResolve матчат корректно.
- AjaxProjectChannelTest — тест нормализации против фактической формы
  портала (не идеального мока); SupplierPortalClientRtProjectTest —
  listProjects против конверта {projects}.

Также (code-review I1): findOnPortal catch — Log::warning проглоченного
исключения, иначе провал дедупа невидим (молчаливый дубль rt-проекта).

Code-review I2 (partial-unique индекс supplier_manual_sync_queue от
дубль-эскалаций при job-retry) и I3 (lockForUpdate в manualQueueResolve) —
follow-up до прод-релиза (эпик гейтится Б-1, не в проде).

Регрессия Pest 973/970/0 / 3 skipped.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 13:09:48 +03:00
Дмитрий 6c30c248bc fix(supplier): larastan deadCode + Pest higher-order cleanup (T12)
FailoverProjectChannel: убран unreachable throw new LogicException после
try-catch в createProjectForLiderra — все ветки уже терминируют (return /
throw WindowDeferred / escalateToTier3(): never). phpstan deadCode.unreachable.

SupplierManualQueueTest: test()-> заменён на $this-> (идиома проекта,
как AdminPricingTiersControllerTest) — phpstan не типизирует Pest
higher-order test(); authAdmin() helper убран, actingAs inline в it().

Изолированный phpstan по supplier-failover файлам — 0 реальных ошибок.
Task 12 cleanup. Channel-тесты 7/7, admin-тесты 4/4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:11 +03:00
Дмитрий 9443b5b446 feat(supplier): manual queue section in AdminSupplierIntegrationView
Таблица pending-записей яруса 3 + кнопка «Отметить выполнено» с confirm-
диалогом, дёргает POST .../manual-queue/{id}/resolve. Реюз существующего
админ-экрана интеграции с поставщиком (после «Истории сверок»).

NB: spec в tests/Frontend/ (vitest include — tests/Frontend/**, не
resources/.../__tests__/ как указал план Step 11.1). loadManualQueue
defensive Array.isArray-guard — иначе onMounted в чужих spec'ах
(mockResolvedValue без queue-ключа) ловил undefined.length.

Spec §4.6. Task 11 of 12. Vitest 5/5 (2 новых + 3 существующих).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:10 +03:00
Дмитрий 25088e4a33 feat(supplier): admin endpoints for Tier 3 manual queue
GET /api/admin/supplier-integration/manual-queue — pending список (limit 100).
POST /manual-queue/{id}/resolve — оператор пометил, что вручную создал проект
на портале; reconcile через channel->listProjects() по (platform, signal_type,
unique_key), 409 если не найден.

ОТКЛОНЕНИЕ ОТ plan Step 10.3: план писал portal external_id прямо в
projects.supplier_b*_project_id (FK на local supplier_projects.id) — FK
violation. Resolve делает firstOrCreate local supplier_projects row с
verified external_id, в FK пишет local id.

Routes — в группе saas-admin (web.php, EnsureSaasAdmin стаб). Task 10 of 12.
Tests 4/4 (index pending / exclude resolved / resolve match / resolve 409).

Spec §4.6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:09 +03:00
Дмитрий fcd06afcb2 feat(supplier): retime supplier sync crons 20:30→18:00, 20:15→17:45
Запас ~3 часа до портального дедлайна 21:00 — эскалация на ярус 2/3
(медленный браузер / ручной оператор) происходит в рабочее время.
RefreshSupplierSessionJob daily — на 15 мин раньше sync (17:45).
Hourly RefreshSupplierSessionJob — без изменений.

Spec §4.7. Task 9 of 12. Tests 2/2 (cron expression + timezone).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:09 +03:00
Дмитрий 2f55632792 feat(supplier): wire jobs to FailoverProjectChannel
Оба job'а инжектят SupplierProjectChannel (DI → FailoverProjectChannel)
вместо прямого SupplierPortalClient. Catch TierEscalatedException +
WindowDeferredException — эскалация/перенос пропускают элемент, не валят job.

SyncSupplierProjectJob (singular): handle переписан — find-or-create local
supplier_projects row, portal-create через channel. ОТКЛОНЕНИЕ ОТ plan Step 8.1:
план писал channel-результат (portal external_id) прямо в projects.supplier_b*_
project_id, но эта колонка — FK на supplier_projects.id (local), не portal id.
Сохранена семантика ensureSupplierProject — job создаёт local row с
supplier_external_id и пишет в FK local id. ensureSupplierProject удалён из
SupplierPortalClient (был единственный consumer — этот job).

SyncSupplierProjectsJob (plural): handle/syncOne принимают channel; create →
createProjectForLiderra, update → updateProjectForLiderra (context-project из
liderraProjects->first() для project_id в очереди яруса 3).

Tests: singular переписан под SupplierProjectChannel mock (6 tests, incl.
idempotency reuse); plural — handle(AjaxProjectChannel) для non-failover
ветки (Http::fake-контракт сохранён). Larastan отложен на T12 (worktree
quirk — гонится в основной копии). Регрессия Pest 966/963/0 / 3 skipped.

Spec §5. Task 8 of 12.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:08 +03:00
Дмитрий 54365015d8 feat(supplier): FormProjectChannel (Tier 2) + DI binding
PHP wrapper над manage-project.js через PlaywrightBridge.
+PlaywrightBridge::run(array): generic Node-скрипт runner (refreshSession
не тронут) — план Step 7.4 предусмотрел расширение bridge.
SupplierProjectChannel::class в DI резолвится в FailoverProjectChannel
(ярус 1 AjaxProjectChannel → ярус 2 FormProjectChannel → ярус 3 queue).

Spec §4.3, §4.4. Task 7 of 12. Channel-тесты 16/16 (Ajax 4 + Failover 7 + Form 5).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:08 +03:00
Дмитрий 4dd40f609f feat(supplier): manage-project.js — Playwright drives «Мои проекты» form
create/update/list через headless Chromium по образцу refresh-session.js.
Селекторы зафиксированы из recon-снапшота rt-add-project-form.yml (Task 1).
stdin/stdout JSON, exit codes 0/1/2/3/4 (success/auth/selector/timeout/input).

Фикстурный тест против локального HTML — без живого портала. Runner —
встроенный node:test (app/playwright не использует @playwright/test, только
playwright core); skipLogin режим открывает фикстуру напрямую.

Spec §4.3. Task 6 of 12. Node-тесты 2/2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:07 +03:00
Дмитрий d760036972 feat(supplier): FailoverProjectChannel portal-side dedup before create
listProjects() матч по (platform, signal_type, unique_key) до create.
Защита от дубля при полу-успехе яруса 1 (create прошёл на портале, но
локальная запись не сохранилась → следующий запуск дублировал бы).
listProjects-сбой проглатывается — ярус-эскалация всё равно покроет.

Spec §4.4 шаг 2, §7. Task 5 of 12. Тесты 7/7 (19 assertions).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:07 +03:00
Дмитрий 0e27844a28 feat(supplier): FailoverProjectChannel skeleton — escalation matrix without dedup
Tier 1 → классификация исключения → ярус 2 (плейсхолдер) / ярус 3 (queue).
Без портального dedup (см. Task 5). Без реального Tier 2 (см. Task 7).

Матрица эскалации:
- Tier 1 success → return id
- WindowDeferredException → re-throw (операция переносится, без queue/alert)
- SupplierTransientException → сразу Tier 3 (skip Tier 2 — хост недоступен)
- SupplierClient/AuthException → Tier 2; success → failover_to_form alert;
  fail → Tier 3 queue + manual_required alert + TierEscalatedException
- escalateToTier3 пишет supplier_manual_sync_queue + queue'ит критический alert.

6 тестов матрицы эскалации зелёные (17 assertions). Spec §4.4, §6, §8.
Task 4 of 12.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:06 +03:00
Дмитрий d369383c7d feat(supplier): supplier_manual_sync_queue table (Tier 3 queue)
SaaS-level (без tenant_id, без RLS, как supplier_csv_reconcile_log).
+3 CHECK (platform/operation/status), +2 индекса, +2 FK
(project_id→projects CASCADE, resolved_by_user_id→users SET NULL).

Миграция через DB::unprepared (PG prepared statement не разрешает multi-SQL).
schema.sql bumped v8.24 → v8.25 (64 base tables / 121 indexes / 40 RLS).
SchemaDeltaTest обновлён под новые метрики (63→64 tables, 119→121 indexes).

§15.2 pre-flight: rebase на origin/main f7f37fb выполнен до коммита.
Spec §4.5. Task 3 of 12. Регрессия: schema+delta тесты 11/11.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:06 +03:00
Дмитрий 54fcc4b094 feat(supplier): SupplierProjectChannel interface + AjaxProjectChannel (Tier 1)
Тонкий адаптер над SupplierPortalClient. Существующий клиент не меняется —
он остаётся HTTP-плумбингом, адаптер реализует интерфейс контракта.

Spec §4.1, §4.2. Task 2 of 12.

Tests: 4/4 passing (1 instanceof + 3 delegation: create/update/list).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:05 +03:00
Дмитрий e87b1385cf feat(supplier): verify rt-project-* contract live on crm.bp-gr.ru
Live discovery через Playwright MCP (Task 1):
- создан LIDPOTOK_TEST_DELETE_ME (B1+B2+B3) → 3 rt-проекта на портале;
- записаны сетевые запросы /admin/visit/rt-*;
- все три проекта удалены вручную, портал чист.

Endpoints (verified):
- POST /admin/visit/rt-project-save (create id:0, update id:N — same URL)
- POST /admin/visit/rt-project-delete (id строкой)
- GET  /admin/visit/rt-projects-load?src=none

Все три — application/json. Конверт ответа:
- success: HTTP 200 + {status:OK, message, result, id?:string}
- error:   HTTP 200 + {status:Error, message, result:null}
ID — строка (12721245), приводится к int (fits в int64).
Один save с B1+B2+B3 включёнными создаёт 3 rt-проекта — toPayload()
шлёт ровно один платформенный флаг (srcrt|srcbl|srcmt).

SupplierPortalClient:
- docblock переписан под verified контракт
- listProjects: путь /admin/visit/rt-projects-load + ?src=none query
- saveProject: путь /admin/visit/rt-project-save, asJson, парсинг id
- updateProject: тот же endpoint что save, id:N в body
- deleteProject: путь /admin/visit/rt-project-delete, asJson, id строкой
- new assertStatusOk() — HTTP 200 + status:Error → SupplierClientException
- toPayload(): полный Vuex-payload с маппингом DTO → portal:
  - platform B1/B2/B3 → srcrt/srcbl/srcmt (single-true)
  - signalType site/call/sms → type:hosts/calls/sms
  - workdays int[] → string[]
  - status active/paused → bool
  - + tag:_lidpotok, name/content из uniqueKey, defaults для show/depth/etc

Tests:
- new: tests/Feature/Supplier/SupplierPortalClientRtProjectTest.php (7 tests,
  contract: save+update+delete+list + 2 status:Error error-paths + B2/calls
  mapping)
- Sync/Cleanup/Unit тесты обновлены под новый URL + envelope shape.

Закрывает spec §1 honest-caveat «placeholder, не верифицирован»
и журнал решений запись 9. Регрессия: Pest 944/941/0 failed / 3 skipped
/ 2768 assertions / 59.2s.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:05 +03:00
Дмитрий 66ca57f187 sessions: claim supplier-project-channel-failover
Per Pravila §15.2: pre-flight `git fetch origin && git log HEAD..origin/main` clean
after rebase onto d484e60. Worktree env restored (composer install + npm ci
--legacy-peer-deps + npm run build + storage/framework dirs); Pest baseline
GREEN 937/934 / 0 failed / 3 skipped / 2756 assertions / 51.7s.

Scope: 17 files (interface + 3 channels + 2 exceptions + 2 jobs + DI + migration
+ schema/CHANGELOG + node script + controller + view + console route).
Version-claim: db/schema.sql v8.21 → v8.22 (Task 3 +supplier_manual_sync_queue).
Closes: docs/superpowers/plans/2026-05-19-supplier-project-channel-failover.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:55:04 +03:00
Дмитрий 430efe624d docs(brain): phase 1.1 normative sync — user_chose_from_options 3rd kind
Pravila v1.32 -> v1.33: §16.2 decision_provenance.kind extended to 3
values (autonomous | user_directed_method | user_chose_from_options);
§16.7 +paragraph «Граница user_chose_from_options» (routing-gate does
not block collaborative-choice); §16.6 +plan cross-ref; §10 +v1.32
(missing) +v1.33 entries.

Tooling §0 cross-ref string Pravila v1.32 -> v1.33 (no header bump).
CLAUDE.md §0 Pravila row v1.32 -> v1.33, §3.6 +phase 1.1 sentence,
§9 +v2.20 entry (via claude-md-management plugin, §5 п.10).

cross-ref-checker: 0 drift in 4 files.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:14:12 +03:00
Дмитрий dc6d2dd358 test(brain-retro): regression guard — 3rd provenance kind in factor matrix
buildFactorMatrix already buckets decision_provenance.kind dynamically
(brain-retro-analyzer.mjs:112) — no production change needed. Test
pins that user_chose_from_options is counted on the provenance axis.

12/12 brain-retro tests GREEN.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:06:56 +03:00
Дмитрий 4969363f78 feat(observer): routing-gate no-block for user_chose_from_options
When episode is user_chose_from_options, routing-gate does NOT block —
collaborative-choice from Claude-offered options doesn't require a
routing-tag (detector is deterministic). 18/18 stop-hook tests GREEN.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:05:49 +03:00
Дмитрий 0e3938f845 feat(observer): parser integration — user_chose_from_options before routing-tag
detectChoiceProvenance runs BEFORE parseRoutingTag; if last assistant
turn offered options and user prompt references one, decision_provenance
becomes user_chose_from_options. Otherwise falls back to existing
routing-tag / autonomous logic.

3 new parser tests GREEN; all existing tests still GREEN (43/43).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 12:04:25 +03:00
Дмитрий 7f379bd6a2 feat(observer): choice detector — user_chose_from_options kind
Pure module — extracts options (numbered/lettered/bullets/AskUserQuestion)
from last assistant message, detects user reference (position-based +
substring), returns decision_provenance for the 3rd kind.

23/23 tests GREEN.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:57:36 +03:00
Дмитрий f751ded65b docs(observer): implementation plan — phase 1.1 user_chose_from_options
5 tasks TDD plan with explicit code per step. Task 1 creates
observer-choice-detector.mjs pure module (23 tests). Task 2 wires
into transcript-parser. Task 3 extends routingGateDecision (no-block).
Task 4 extends brain-retro factor matrix. Task 5 normative sync
(Pravila §16.2 + CLAUDE.md §3.6 + spec cross-ref).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:53:53 +03:00
Дмитрий 0c8d0fa8d1 docs(observer): spec v1.1 — phase 1.1 amendment user_chose_from_options
Adds 3rd decision_provenance kind for collaborative-choice case
(user picks one of options Claude offered). Distinct from
user_directed_method: counterfactual = Claude's recommended option,
not "what Claude would have done autonomously". Routing-gate does
NOT block this kind — collaborative choice from Claude-designed
choice-space.

Trigger: 19.05.2026 live false-positives — "1 экономия 0%",
"в делаем", "делай 2" classified as user_directed_method.

§11 + 8 subsections; 7-attribute decision_provenance schema;
new tools/observer-choice-detector.mjs (pure module); parser
+routing-gate +/brain-retro extensions.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:47:30 +03:00
Дмитрий f7f37fb4e4 docs(brain): observer factor-analysis extension — normative sync
ADR-011 amended: +Decision §5 (observer v2 four-layer), §3 4→5
controllers (+C5), Enforcement +routing-gate + C5 bullets, related
+factor-analysis spec/plan.

Pravila v1.31→v1.32: §16.2 +абзац «Схема эпизода v2», §16.3 4→5
контролёров (+C5 row), +§16.7 routing-тег-дисциплина (mechanical
Stop-hook decision:block, stop_hook_active loop guard), +§16.8
самодисциплина наблюдателя (observer_error marker, parse_gap event,
C5 lefthook warn-only), §16.6 +cross-refs на factor-analysis spec/plan.

PSR_v1 v3.16→v3.17: R16.1 +предложение про schema v2 поля и
расширенные события; R16.4 +cross-refs.

Tooling Прил. Н v2.17: §0 cross-ref strings 1.31/3.16 → 1.32/3.17
(no header version bump).

brain-governance spec: related +factor-analysis spec.
observer-factor-analysis-design.md: status draft→accepted.

CLAUDE.md v2.19: §0 Pravila/PSR_v1 cross-refs bumped to v1.32/v3.17
with v2 summary prepended (legacy preserved as «v1.31 наследие» /
«v3.16 наследие»); §3.6 appended observer schema v2 + routing-gate +
C5 + brain-retro analyzer paragraph; §9 +v2.19 entry.

cross-ref-checker: 0 drift in 4 files.

Plan: docs/superpowers/plans/2026-05-19-observer-factor-analysis.md
Spec: docs/superpowers/specs/2026-05-19-observer-factor-analysis-design.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 11:08:55 +03:00
Дмитрий d484e60c46 docs(observer): brain-retro skill + README for schema v2
Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-05-19 10:55:37 +03:00
Дмитрий a6f44e5bb4 feat(observer): brain-retro analyzer — outcome inference + factor matrix
Pure deterministic Layer-4 aggregation module (spec §6) for the /brain-retro
skill. Exports: dedupeEpisodes, inferOutcome, groupEpisodesToTasks,
findCausalChains, buildFactorMatrix, analyze. Read-only — never writes JSONL.
11/11 tests green. CLI smoke: 10 real episodes → valid JSON with all 5 keys.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:47:57 +03:00
Дмитрий 363357bff4 chore(observer): wire C5 coverage-checker into lefthook (job 15) 2026-05-19 10:44:10 +03:00
Дмитрий 843123bbdb docs(supplier): plan — project channel failover (12 tasks, TDD)
Реализация по спеку 2026-05-19-supplier-project-channel-failover-design.md.

12 атомарных задач:
T1 live discovery + Tier 1 contract verification
T2 SupplierProjectChannel interface + AjaxProjectChannel
T3 supplier_manual_sync_queue table (migration + schema.sql + CHANGELOG)
T4 FailoverProjectChannel skeleton + Window/TierEscalated exceptions
T5 portal-side idempotency dedup
T6 manage-project.js Node script
T7 FormProjectChannel + DI wiring
T8 wire jobs to FailoverProjectChannel
T9 schedule retiming 20:30→18:00, 20:15→17:45
T10 admin worklist endpoints
T11 admin worklist UI
T12 live smoke + final regression

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:43:05 +03:00
Дмитрий 1d76d930bd chore(cspell): allow plan vocabulary (имплементациями, алёрт, инжектят, инжектим, фикстурный, роута)
Русская проектная лексика для плана резерва канала миграции проектов
(docs/superpowers/plans/2026-05-19-supplier-project-channel-failover.md).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:43:01 +03:00
Дмитрий cde9478899 feat(observer): STATUS.md — C5 row + observer_error metric 2026-05-19 10:41:17 +03:00