Commit Graph

939 Commits

Author SHA1 Message Date
Дмитрий e101949c27 feat(observer): parser v2 — environment, task_size, prompt_signal extractors 2026-05-19 10:15:17 +03:00
Дмитрий 514d5d09b9 docs(plan): observer factor-analysis implementation plan
12-task plan implementing the spec
docs/superpowers/specs/2026-05-19-observer-factor-analysis-design.md
in 4 layers (schema v2 + capture + enforcement + analysis) plus
normative sync. Each task has TDD steps with full code.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 10:09:56 +03:00
Дмитрий 4243f77868 docs(brain): spec — observer factor-analysis extension
Design for making the brain governance observer rich enough for real
factor analysis. Surfaced during a discussion with the owner: the
observer is "paper-complete" but episodes lack the data factor analysis
needs — the outcome is a hardcoded "success", there is no decision
provenance (who chose the node — Claude autonomously, or the owner
forcing a method), no environment factors, no task grouping.

4-layer architecture:
- Layer 1 — episode schema v2: decision_provenance (+ counterfactual),
  environment block, task_size, real outcome enum, task_ref.
- Layer 2 — capture: deterministic transcript parsing for all factors +
  a one-line routing tag (owner-forced-method only).
- Layer 3 — two-sided enforcement: 3a routing-gate (Stop-hook blocks the
  turn until the tag is present — unbypassable by Claude); 3b observer
  self-discipline (silent failures become recorded observer_error
  markers; coverage + registration verified by a controller).
- Layer 4 — analysis: /brain-retro infers real outcome from the next
  episode's opening prompt, groups episodes into tasks, correlates
  causal chains, builds the factor matrix.

Scope: everything except an independent agent-judge — that, plus
confusion_marker as a real judgment and real-time friction flags, is
phase 2 (separate spec).

Brainstormed via superpowers:brainstorming. Next: writing-plans.

Refs: ADR-011, spec 2026-05-19-brain-governance-design.md, Pravila §16.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 09:15:27 +03:00
Дмитрий 049ca96a07 chore(brain): refresh STATUS.md dashboard
The committed STATUS.md was stale (generated 2026-05-19T03:49, before
the C1/C2 strict-mode fixes and before the post-commit hook existed):
it showed C1/C2 🔴 and "0 episodes". Regenerated via the now-installed
post-commit hook (C4 status-md job) — C1/C2/C3/C4 all , 5 episodes.

Context: `.git/hooks/post-commit` was never installed, so the C4
status-md job (lefthook post-commit) never ran automatically. Fixed
locally via `lefthook install --force` (installs pre-commit/post-commit/
pre-push). The hook files live in `.git/` and are not version-tracked —
re-run `lefthook install` after clone if hooks go missing.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 08:13:19 +03:00
Дмитрий 7108406cca feat(brain): observer captures real session data via transcript parse
The Stop-hook was writing empty-shell episodes (task_id "unknown-<ts>",
node_chosen "unknown", events []). Root cause: buildEpisodeFromContext
read fields from the Stop-event stdin that Claude Code never sends
(primary_rationale, node_chosen, ...) and the session field name was
wrong (ctx.sessionId camelCase vs Claude Code's session_id). The hook
never read transcript_path — the only real source of session data.

New tools/observer-transcript-parser.mjs — pure parseTranscript(text,
fallbackSessionId):
- Scopes to the last turn (from the last real user prompt to EOF) —
  one episode == one prompt→response cycle. A tool_result-carrier user
  message is not treated as a turn boundary.
- Extracts task_id (real sessionId), timestamps (real duration),
  skill_invoked events, a tool_summary event with per-tool counts,
  error events (tool_result is_error), node_chosen (first skill, else
  "direct"), hard_floor (invoked when a superpowers:* skill is used),
  path_type (regulated/improvised), task_classification (keyword
  heuristic on the prompt).
- Reasoning fields triggers_matched/candidates_considered/
  boundaries_applied stay [] — not recoverable from a transcript;
  their capture is a separate ADR-011 follow-up.

observer-stop-hook.mjs: reads ctx.transcript_path + ctx.session_id
(camelCase fallback kept), readFileSync best-effort, delegates to
parseTranscript. No transcript → graceful fallback to ctx defaults.
Episode schema (5 mandatory + 7-field primary_rationale) unchanged —
no normative change. Stop-event is never blocked (exit 0 on any error).

TDD: 17 parseTranscript tests + 1 buildEpisodeFromContext transcript
test. Full tools Vitest 70/70 GREEN. CLI smoke against a real 575-entry
transcript: episode populated — real task_id, ~6.5 min duration,
tool_summary {Bash:5,Read:5,Grep:1,Edit:9,Write:1}, error event.

Refs: ADR-011 brain governance §6.2 (observer evidence loop).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 08:11:10 +03:00
Дмитрий 48369634f3 @
test(supplier): SupplierCsvParserTest под 3-колоночный формат отчёта

Unit-тест ожидал устаревший 6-колоночный формат
vid;project;tag;phone;phones;time, тогда как SupplierCsvParser
переписан эпиком CSV-канала (T2, 18.05.2026) под 3-колоночный
Name;Tag;Phone — yields {project,tag,phone}, vid/time отсутствуют.

Тестовый долг вскрыт полной регрессией: 3 кейса падали
(«array has no key vid»). Тесты приведены к актуальному контракту
парапера. Pest SupplierCsvParserTest 5/5, full-suite 937/934/0/3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@
2026-05-19 07:42:34 +03:00
Дмитрий 2a15dc0d76 @
fix(supplier): реальные endpoint'ы отчёта «Запрос номеров» (discovery T3)

Discovery T3 на живом supplier-портале crm.bp-gr.ru (Playwright MCP)
вскрыл фактические endpoint'ы вместо placeholder'ов из spec §4.3:

- POST /admin/report/save-report (JSON body, selectType=49 + reportFilter)
  — возвращает строку "OK", не JSON с id;
- GET  /admin/report/load-reports — массив отчётов, id извлекается
  title-match'ем «Запрос номеров с {from} по {to}»;
- GET  /admin/report/getfile?id=N — 302 redirect на отдельный
  download-host (oki.needcallbuy.ru), Laravel HTTP follows redirect.

SupplierPortalClient: requestNumbersReport/waitReportReady/downloadReport
переписаны под реальный контракт; request() +параметр asJson;
connectTimeout(30)+timeout(60) против flaky DNS resolve.

refresh-session.js: селекторы login-формы Yii2 — placeholder
input[name=login] → реальные #loginform-username/-password.

Тесты SupplierPortalClientReportTest + CsvReconcileJobTest адаптированы
под новый внутренний контракт. Pest 15/15, Larastan 0.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
@
2026-05-19 07:42:12 +03:00
Дмитрий 2d6b4204d2 refactor(brain): C1 L1-watcher — drop broken reverse drift check
Removes the `missingInSettings` reverse check ("plugin documented in
Tooling but disabled in settings.json"). It was broken by design:
Tooling Прил. Н lists tools by human/group name ("Frontend Design
plugin", "Trail of Bits Skills") while settings.json keys are machine
IDs (`name@marketplace`) — the two namespaces never compare. The
`/#\d+\s+([\w-]+(?:@[\w-]+)?)/` scan also captured the first plain word
after "#NN" ("#1 PostgreSQL MCP" → "PostgreSQL"), so every run emitted
~190 lines of WARN noise.

ADR-011 §6.1 specifies only the settings→Tooling direction (the L1
pattern "plugin enabled without Tooling formalization"). That is the
FAIL path and is unchanged. detectDrift now returns `{ missingInTooling }`
only. CLI output is a clean single line on success.

Closes the cosmetic issue flagged in 10ff755.

TDD: reverse-check test replaced with `not.toHaveProperty
('missingInSettings')`; 12/12 GREEN. Smoke: node tools/l1-watcher.mjs
-> exit 0, "OK — 0 drift" (no WARN block).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 07:36:21 +03:00
Дмитрий 123ca5d516 feat(brain): C1 + C2 lefthook jobs → strict mode
Removes the `|| true` WARN-only guard from pre-commit jobs 11
(l1-watcher) and 12 (cross-ref-checker). Both controllers now block
the commit on real drift.

Safe to flip now that the false-positive sources are closed:
- C1: tools/.l1-watcher-aliases.txt resolves the 9 name@source drifts
  (Frontend Design plugin, Trail of Bits Skills group).
- C2: link-anchored detection + history-block scope-cut removes the
  ~150 «наследие»/arrow-transition false positives.

Verified on the current tree: node tools/l1-watcher.mjs -> exit 0,
node tools/cross-ref-checker.mjs -> exit 0. Comment blocks and
fail_text updated to describe strict behaviour and the alias escape
hatch.

Refs: ADR-011 brain governance §6.1 / §6.2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 07:31:26 +03:00
Дмитрий 86523a8edd feat(brain): C2 cross-ref-checker link-anchored detection — strict-ready
Closes the ~150 false drifts that prevented strict mode. The old regex
`\b(Name)\s+v(\d+\.\d+)` swept the whole file head and matched every
historical version mention, plus the FROM-side of arrow transitions
("v1.30→v1.31"). Real current-vs-header drift in the repo: zero.

Two-tier detection:
- Primary LINK_REF_RE: a markdown-link to a normative file followed by
  the first bold version — "[..](docs/Tooling_v8_3.md) (**Прил. Н
  v2.17**". Link anchor makes it immune to history-block noise. This is
  how CLAUDE.md §0 cross-refs table is written, so CLAUDE.md is fully
  validated. Runs on the whole file.
- Fallback CROSS_REF_RE: plain "Name vX.Y" mention, scoped to the text
  *before* the first history block. Pravila/Tooling/PSR_v1 have no
  markdown-link cross-refs, so the fallback covers them — but their
  shapki list past releases, so the scan stops at the first history
  marker (`**vN.M наследие**` / `**Что изменилось в vN.M относительно**`
  / `**vN.M** — `). dedupe-by-target keeps the first ref per target.

Regex hardening:
- `\b` after the version forbids backtracking to a partial capture
  (so "v1.30→" never collapses to a spurious "v1.3" match).
- `(?!\s*→)` negative lookahead drops the FROM-side of transitions.

TDD: 8 new tests (link-based, "Прил. Н" prefix, multi-file table,
dedupe, two arrow shapes, three history-marker shapes, link-beats-
fallback). 18/18 GREEN.
Smoke: node tools/cross-ref-checker.mjs -> exit 0, "OK — 0 drift in
4 files" (Pravila/CLAUDE.md/Tooling/PSR_v1; MEMORY.md is outside the
repo by design — existsSync-skipped).

Refs: ADR-011 brain governance §6.2 (C2 cross-ref consistency detector).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 07:29:43 +03:00
Дмитрий 10ff755649 feat(brain): C1 L1-watcher alias mechanism — strict-ready
Closes the 9 pre-existing name@source drifts that prevented strict mode:
settings.json lists each marketplace plugin by machine name (e.g.
"frontend-design@claude-plugins-official"), while Tooling Прил. Н
describes them under a human/group name (e.g. "Frontend Design plugin",
"Trail of Bits Skills" — single row #39 for 8 sub-plugins).

Mechanism:
- tools/.l1-watcher-aliases.txt — settings_name=tooling_substring map.
- detectDrift(settings, tooling, aliases): direct match first, then
  alias-substring fallback. Settings name considered formalized if
  Tooling text includes either the name itself or aliases[name].
- parseAliases(raw) exported — line-based KV parser with #-comments
  and split-on-first-= semantics (values may contain "=").

TDD: 6 new tests (3 detectDrift + 4 parseAliases). 12/12 GREEN.
Smoke: node tools/l1-watcher.mjs -> exit 0, "OK — 0 drift".

Known cosmetic baseline issue (pre-existing, not introduced here):
the missingInSettings WARN list is noisy — regex
/#\d+\s+([\w-]+(?:@[\w-]+)?)/g captures the first \w+ after "#NN"
even when it is a plain word (e.g. "#1 PostgreSQL MCP" -> "PostgreSQL"),
producing ~190 WARN entries. WARN is non-blocking, so strict mode flip
in Phase 3 is unaffected; a follow-up filter on names containing "@"
would silence this without behavioural change.

Refs: ADR-011 brain governance §6.1 (C1 L1-watcher detector for the
"plugin in settings.json without Tooling formalization" L1 pattern).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 07:12:05 +03:00
Дмитрий 948577a8e0 fix(observer): STATUS.md plain-text reference to memory file (lychee pre-push fix)
Memory files (e.g. feedback_brain_unused_tools_not_problem.md) live
in C:/Users/.../memory/, OUTSIDE the git repo. Markdown link from
docs/observer/STATUS.md (relative path) resolved to non-existent
in-repo path → lychee broken-link error in pre-push gate.

Fix: plain-text mention of memory key (no markdown link), with
explicit note «outside-repo memory store». Generator updated
accordingly; 31/31 Vitest tests still GREEN.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:49:39 +03:00
Дмитрий d601db819b docs(claude-md): §0 cross-refs sync + §3.6 router-procedure cross-ref (v2.17 → v2.18, Task D1)
Brain governance Phase A/B/C closure sync (ADR-011).

§0 cross-refs:
- Pravila v1.30 → v1.31 (§16 brain governance)
- PSR_v1 v3.15 → v3.16 (R16 brain evidence loop)
- Tooling Прил. Н v2.16 → v2.17 (§0.1 row template + 58 Атрибуты blocks)

§3 structure:
- §3.6 (new — free slot after v2.16 renumber) — cross-ref to
  docs/router-procedure.md v1.0 (5-step router procedure SoT).
- §3.7 (off-phase routing-аид) — +note distinguishing
  router-procedure.md (general 5-step) vs routing-off-phase.md
  (concrete triggers/chains).

§9 +v2.18 entry — Phase A/B/C summary with all commit SHAs (15+6+5)
+ Phase B+C concerns (C1 9 drifts, C2 noise refinement).

+cspell словарь «DWC» (DONE_WITH_CONCERNS abbreviation).

Through /claude-md-management:claude-md-improver per §5 п.10.

Note: cross-ref-checker (C2, just-wired in C5 commit 44f4e84)
surfaces ~150 known historical 'наследие' drifts on this commit
— that's the WARN-only behavior (`|| true`) per follow-up
refinement. Lefthook still passes overall.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:44:29 +03:00
Дмитрий 44f4e84f61 build(lefthook): wire 4 brain controllers — C1/C2/C3/C4 (Task C5)
pre-commit jobs 11-13:
- l1-watcher (WARN-only via || true; glob settings.json + Tooling)
- cross-ref-checker (WARN-only via || true; glob 5 normative files)
- observer-of-observer (always exit 0 by design)

post-commit job 14:
- status-md (regenerates docs/observer/STATUS.md + stages it for
  next commit; never fails commit via || true)

Both l1-watcher and cross-ref-checker are WARN-only initially because:
- l1-watcher surfaces 9 known pre-existing 'name@source' drifts
  (see commit 57098dc); strict mode pending alias resolution.
- cross-ref-checker surfaces noise from historical «наследие» entries
  in headers (see commit aeb81ab DWC); strict mode pending refinement.

observer-of-observer is warn-only by spec (no fail until C3 prune
threshold 54 weeks).

Verified via npx lefthook run pre-commit on staged lefthook.yml —
all 14 jobs evaluate cleanly: 9 skipped (glob mismatch), 5 ran
(including new observer-of-observer warn).

Per ADR-011 + plan Task C5.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:39:41 +03:00
Дмитрий 766b757a30 feat(controller): C4 status-md-generator — dashboard
Aggregates C1/C2/C3 outputs via execFileSync (Security Guidance #40
compliant — uses fixed args array, no shell injection surface) +
observer episode count. Behavioral rule embedded in metric copy.
Per ADR-011 + spec §6.4.

3 Vitest tests GREEN (31/31 total).

Smoke run rebuilds STATUS.md with current state:
- C1 🔴 (l1-watcher surfaces 9 plugins in settings not formalized
  in Tooling Прил. Н by exact name@source — see commit 57098dc)
- C2 🔴 (cross-ref-checker surfaces noise from 'наследие' headers
  — see commit aeb81ab DWC)
- C3  (0 weeks since last read)
- C4  (this file)

Both 🔴 states surface known pre-existing drift (not regressions).
C5 lefthook wiring will handle WARN-vs-FAIL semantics.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:37:27 +03:00
Дмитрий 29f2cb3037 feat(controller): C3 observer-of-observer — 54-week self-prune counter
Pure date math, 0 LLM calls. 5 Vitest tests GREEN (28/28 total).
Per ADR-011 + spec §6.3.

Modes:
- check (default, lefthook): warn if last_read_at >= 54 weeks ago.
- record: bump counter (invoked manually or by future read-tracking hook).

isStale threshold is inclusive (>= 54 weeks) — spec «через 54 недели»
means at-or-past 54 weeks fires the warn.

Smoke run OK — current counter (period_start 2026-05-19) shows
0 weeks ago.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:36:13 +03:00
Дмитрий aeb81abfa2 feat(controller): C2 cross-ref-checker — version drift detector (DONE_WITH_CONCERNS)
Pure regex/JSON, 0 LLM calls. 5 Vitest tests GREEN (23/23 total).
Per ADR-011 + spec §6.2.

Smoke run on real repo surfaces ~150 «drifts» — these are
**historical 'наследие' entries** in headers (CLAUDE.md / Pravila /
Tooling / PSR_v1), not actual current cross-ref mismatches. Each
of these 4 files has a multi-line «v2.X наследие:» / «v1.Y наследие:»
chain in its top header describing past sub-versions; my 50-line
scan picks them all up.

CONCERN: mechanism is correct (test fixtures pass), but real-world
needs refinement before lefthook wiring (C5). Options for follow-up:
- Scope match to explicit «§0 cross-refs» table marker.
- Distinguish «current cross-ref» from «historical наследие mention»
  by surrounding markup.
- Restrict regex to cross-ref tables (markdown | columns) only.

Until refined: C2 will be wired in C5 with caveat (WARN-only, or
disabled) to avoid blocking every commit on pre-existing 'наследие'
entries.

Extracted Tooling Прил. Н version via **Версия:** pattern (file-level
v8.3 wrapper at line 1 was misleading — Прил. Н is v2.17 at line 4).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:34:10 +03:00
Дмитрий 57098dcf63 feat(controller): C1 l1-watcher — settings.json ↔ Tooling drift detector
Pure regex/JSON, 0 LLM calls. 4 Vitest tests GREEN. Per ADR-011 + spec §6.1.

Smoke run surfaces REAL drift (DONE_WITH_CONCERNS — plan B5 said «that's
a real signal, document, don't fix here»): 9 plugins in
~/.claude/settings.json enabledPlugins NOT formalized by exact
«name@source» string in Tooling Прил. Н:
- frontend-design@claude-plugins-official (informally as #30
  «Frontend Design plugin»)
- 8× ToB plugins @trailofbits (differential-review, audit-context-
  building, supply-chain-risk-auditor, insecure-defaults, sharp-
  edges, static-analysis, variant-analysis, agentic-actions-auditor)
  informally as #39 «Trail of Bits Skills»

This is naming-vocabulary mismatch (Tooling uses human-readable
names; settings.json uses machine names). Not architectural drift.
Resolution options for follow-up:
- Add machine names as «external_id» attribute to Tooling Прил. Н rows.
- Add tools/.l1-watcher-aliases.txt with accepted machine→human map.

Until resolved: C1 will FAIL on lefthook (C5 wiring) — addressed in
C5 by adding alias mechanism OR temporarily downgrade to WARN.

Also fixed CLI guard bug in observer-stop-hook.mjs (B3) and l1-watcher
— old guard `import.meta.url === \`file://\${argv[1]}\`` did not match
on Windows (file:/// triple-slash vs file:// double-slash + relative
argv[1]). New guard: argv[1].endsWith('/<filename>.mjs').

Weekly GH Actions cron (Mon 09:00 MSK) opens issue on drift.

Vitest config extended to ../tools/*.test.mjs with exclude for ruflo-*
and subagent-prompt-prefix tests (pre-existing, not part of brain
governance).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:31:18 +03:00
Дмитрий 4216daa03e feat(skills): /brain-retro — observer evidence aggregator
Read-only skill at .claude/skills/brain-retro/. Aggregates JSONL
evidence + optional notes for owner review. Side-effect: bumps
docs/observer/.read-counter.json (used by C3 observer-of-observer
54-week self-prune).

Includes Factor analysis matrix (v1.1+ amendment): 5 axes
(triggers_matched / candidates_dropped_because / boundaries_applied /
hard_floor.rules / task_classification) + cross-tab factor×factor.

Never auto-edits normative files. Per Pravila §16.2 + ADR-011 +
spec v1.1 §5.5.

+cspell словарь «разруливают», «брейн».

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:23:00 +03:00
Дмитрий 290ed1a081 feat(observer): register observer-stop-hook on Stop-event (project-level)
HK1 pre-check passed in B4 (3b9da37): user-level Stop = agent-type
economy verifier (independent slot); project-level Stop was empty.

Added project-level Stop hook: command-type, 5s timeout, never
blocks (exit 0 on error per implementation 4238de9). Per Pravila
§16.2 + ADR-011.

Real-session smoke test deferred to Task D2 end-to-end smoke (semi-
manual — triggers real Claude Stop event).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:19:09 +03:00
Дмитрий 3b9da37cbc docs(observer): HK1 pre-check noted in README (ADR-010 compliance)
Verified Stop event collision before B5 registration:
- User-level (~/.claude/settings.json): Stop hook = agent-type
  Sonnet-4.6 economy compliance verifier (already wired in
  6-component arch).
- Project-level (.claude/settings.json): Stop slot empty.

observer-stop-hook will register as command-type entry in
project-level Stop array. Independent slot from user-level agent;
no overwrite, no collision. Per Pravila ADR-010 HK1 hard-rule.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:17:58 +03:00
Дмитрий 4238de9f94 feat(observer): Stop-event hook — JSONL append with PII filter + primary_rationale validation
Hook contract: reads JSON ctx from stdin (Claude Code Stop-event),
builds episode with 5 mandatory fields including primary_rationale
(7 sub-fields per spec v1.1 §5.2.1), sanitizes via observer-pii-filter,
appends to docs/observer/episodes-YYYY-MM.jsonl. Never blocks
Stop-event (exit 0 on error).

8 Vitest tests verified GREEN (6 in appendEpisode + 2 in
buildEpisodeFromContext): append/append-existing/PII-filter/
missing-required/missing-rationale-field/routing_decision-preserved
+ buildEpisode 5-field extraction + user-rationale-preserved.

Vitest config for tools/ already covers via glob ../tools/observer-*.test.mjs
(extended in B2 commit 0237b3e).

Per Pravila §16.2 + ADR-011 + spec v1.1 §5.2.1 (factor analysis).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:16:36 +03:00
Дмитрий 0237b3e0b0 feat(observer): PII filter — phone/email/Sentry/OpenAI/Bearer masking
Used by Stop-hook before JSONL write. 6 Vitest cases including
idempotence and recursive object sanitization. Per Pravila §16.2 +
ADR-011 + spec §5.4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:11:25 +03:00
Дмитрий 4da6923dc5 feat(observer): docs/observer/ scaffolding — README + STATUS + counter + JSONL seed
Empty infrastructure per ADR-011 + Pravila §16.2. Hook + generators
wire up in subsequent tasks (B2 PII filter, B3 Stop-hook, B5 register
in settings.json, C4 STATUS generator).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 06:07:42 +03:00
Дмитрий 97e2b02561 docs(psr): +R16 brain evidence loop — PSR_v1 v3.15 → v3.16
R16.1-R16.4: observer scope (5 mandatory fields incl. primary_rationale),
stack-conscious events (routing_decision + factor matrix 5 axes),
non-override status, cross-refs. Layered on top of R15 off-phase routing.

Per ADR-011 + spec v1.1 §5.2.1 amendment.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:33:44 +03:00
Дмитрий 5ec71bc50e docs(pravila): +§16 brain governance — router-only + observer + 4 controllers
Pravila v1.30 → v1.31. New §16 sub-sections 16.1-16.6. Level of §13
recommendation (not override-floor §9). Cross-refs ADR-011 / spec /
plan / router-procedure / routing-off-phase.

§16.2 mentions 5 mandatory fields including primary_rationale (per
spec v1.1 §5.2.1 amendment for factor analysis).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:30:24 +03:00
Дмитрий c95b464fc7 docs(tooling): Прил. Н v2.16 → v2.17 — header bump + §13 footer entry (ADR-011 A3 final)
Final header bump after 6 sub-batches of 9-attribute Атрибуты template
application. 58 total Атрибуты blocks now structure the registry:
- §2.4 dump for phase-0 (9 nodes #1-9)
- §3.5 dump for phase-1 (9 nodes #10-18)
- §4.1-§4.4 inline for phase-2 (7 nodes #19-23+#24+#30)
- §5.1 dump for phase-3 (5 nodes #25-29)
- §4.5-§4.17 inline for off-phase #31-42 + ruflo §4.10 (13 blocks)
- §4.18-§4.35 inline for off-phase #43-60 (18 blocks)

dormant=true: #1 PG MCP (replaced by Boost), #17 pg_partman (no
native Windows PG extension; replaced by Artisan command), ruflo
§4.10 (per Pravila §14.9).

Sub-batch commits: 904414a / ce6fe2b / 92035c6 / dc72532 / e340b9e /
9582652 + this header bump. Task A3 complete.

Per spec §4.1, plan Task A3 final step. Structured registry is the
input to router-procedure.md (commit 7da860b) step 3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:26:57 +03:00
Дмитрий 9582652e00 docs(tooling): apply 9-attribute template to §4.18-§4.35 off-phase nodes #43-60 (ADR-011 A3 sub-batch 6 / final)
Inline pattern (matches sub-batches 3 + 5). 18 Атрибуты blocks
covering deptrac/Figma/Universal Icons/Design/openapi-mcp/promptfoo/
Data Scientist/Jupyter/operations/process-modeling/process-analysis/
n8n-mcp/discovery-interview/skill-creator/plugin-dev/hookify/
claude-code-setup/context7.

3 DEFERRED nodes (#44 Figma, #50 Jupyter, #54 n8n-mcp) marked in
boundaries column. Header bump v2.16→v2.17 happens in next commit.

Per spec §4.1, plan Task A3 sub-batch 6.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:24:51 +03:00
Дмитрий e340b9e2a3 docs(tooling): apply 9-attribute template to §4.5-§4.17 off-phase nodes #31-42 + ruflo (ADR-011 A3 sub-batch 5)
Inline pattern (matches Sub-batch 3). 13 Атрибуты blocks placed under
each §4.X heading. Includes ruflo §4.10 dormant=true (Pravila §14.9).
Other 12 nodes (#31-42) dormant=false.

#40 Security Guidance: kind=hook (блокирующий PreToolUse, sys.exit 2).
#34 Sentry MCP: pending Б-1 (Sentry instance deployment), READ-ONLY.

Per spec §4.1, plan Task A3 sub-batch 5.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:19:47 +03:00
Дмитрий dc72532c90 docs(tooling): apply 9-attribute template to §5.1 phase-3 nodes #25-29 (ADR-011 A3 sub-batch 4)
Dump-block pattern (matches Sub-batches 1 §2.4 and 2 §3.5). 5 nodes
covering #25 Semgrep+Semgrep MCP, #26 Trivy, #27 Dependabot,
#28 pg_audit, #29 pg_anonymizer. All dormant=false (registry-known,
phase-3 pre-production per CLAUDE.md §6).

Per spec §4.1, plan Task A3 sub-batch 4.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:15:26 +03:00
Дмитрий 92035c6242 docs(tooling): apply 9-attribute template to §4.1-§4.4 phase-2 nodes #19-23,#24,#30 (ADR-011 A3 sub-batch 3)
Inline pattern (different from Sub-batches 1-2): Атрибуты blocks
placed INSIDE existing §4.1/§4.2/§4.3/§4.4 subsections, not as
separate dump block — to avoid renumbering off-phase §4.5+.

7 attribute rows (1+4+1+1=7) covering #19 Superpowers, #20 Volar,
#21 vue-tsc, #22 ESLint+Prettier+plugin-vue+config-prettier (как
связка), #23 Vitest, #24 Histoire, #30 Frontend Design plugin.

Per spec §4.1, plan Task A3 sub-batch 3.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:12:46 +03:00
Дмитрий ce6fe2bd2d docs(tooling): apply 9-attribute template to §3.5 phase-1 nodes #10-18 (ADR-011 A3 sub-batch 2)
§3.5 «Атрибуты узлов фазы 1» dump block (pattern continues Sub-batch
1 §2.4). #17 pg_partman: dormant=true (replaced by Artisan command
partitions:create-months on native Windows). Other 8 nodes active.

Per spec §4.1, plan Task A3 sub-batch 2.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:09:41 +03:00
Дмитрий 904414ae49 docs(tooling): apply 9-attribute template to §4.1-§4.9 (ADR-011 A3 sub-batch 1)
+ §0.1 row template (one-time, ADR-011 mandated).
+ Атрибуты block for phase-0 nodes #1-#9. #1 PostgreSQL MCP dormant
(replaced by #10 Boost in phase 1).

Per spec §4.1, plan Task A3 sub-batch 1. Tooling header v2.16
remains; final v2.17 bump after all 6 sub-batches.

NB: file-layout adaptation — phase-0 nodes #1-#9 live in §2 tables
(not §4.X subsections); Атрибуты blocks placed in new §2.4
subsection. Plan-template "§4.1..§4.9" referenced the abstract
node-index, not file headings; subsequent sub-batches will follow
same pattern (§3.5 for phase-1 nodes #10-#18, etc.).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 05:04:44 +03:00
Дмитрий 7da860bc01 docs(router): router-procedure.md v1.0 — explicit 5-step routing
Single SoT for task→node routing. Replaces implicit routing scattered
across Pravila/PSR_v1/Tooling/routing-off-phase.md. ADR-011.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:57:33 +03:00
Дмитрий 6a661df101 docs(adr): ADR-011 brain governance — router-only + observer + 4 controllers
Anchor ADR for governance design (spec e2a5394 / v1.1 fd16a10). Sets
Accepted status, captures 4 decisions: router-only, observer scope B,
4 controllers, capability-readiness behavioral rule. Enforced via
adr-judge (lefthook job 9 — checks ## Enforcement section).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:54:31 +03:00
Дмитрий e672e5affc docs(brain): plan amendment — factor analysis в Task A1 ADR-011 + Task B3 + Task B6
Соответствует spec v1.1 (fd16a10). Изменения:

Task A1 (ADR-011 text inside plan):
- Decision #2 «Observer scope B» расширено: упоминание 5 mandatory
  fields (включая primary_rationale 7 sub-fields) + routing_decision
  events для цепочек + что это enables factor analysis.

Task B3 (observer-stop-hook.test.mjs + observer-stop-hook.mjs):
- REQUIRED_FIELDS расширен с 4 до 5 ('primary_rationale').
- Новая константа RATIONALE_FIELDS (7 полей) + validateRationale()
  функция, вызываемая внутри appendEpisode после top-level validation.
- buildEpisodeFromContext возвращает primary_rationale (либо из ctx,
  либо default с extracted hints из ctx.skill_id/triggers_matched/etc).
- Tests: было 5 → стало 8. Новые: «throws when primary_rationale
  field missing», «persists routing_decision events with structured
  fields», «preserves user-provided primary_rationale unchanged».
  Все old fixtures обогащены primary_rationale: defaultRat().

Task B6 (aggregation-template.md):
- Новая большая секция «Factor analysis matrix (v1.1+)» с 5 осями
  факторов + cross-tab factor×factor. Tables для каждой оси:
  triggers_matched, candidates_dropped_because, boundaries_applied,
  hard_floor.rules, task_classification.

Self-review:
- Spec coverage table +row для §5.2.1.

Связано: spec v1.1 (fd16a10), plan v1.0 (e1772da), spec v1.0 (e2a5394).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:49:25 +03:00
Дмитрий fd16a1018e docs(brain): spec v1.0 → v1.1 — factor analysis amendment (routing_decision + primary_rationale)
User-requested перед запуском суб-агента: observer должен фиксировать
не только факт выбора узла, но и причину — чтобы был возможен
факторный анализ через /brain-retro.

Изменения §5.2:

- 4 обязательных поля → 5 (+primary_rationale на эпизод-уровне).
- Новое событие routing_decision в массиве events[] (1 на каждое
  решение роутера в сессии; для цепочки из N — N событий).
- Новая под-секция §5.2.1 — структура 7 полей (step / node_chosen /
  triggers_matched / candidates_considered / boundaries_applied /
  hard_floor / task_classification). primary_rationale — копия
  первого routing_decision для дешёвой агрегации без чтения events[].
- Полный JSON-пример эпизода с цепочкой из 2 узлов.

Изменения §5.5:

- /brain-retro aggregation расширен новой секцией «Факторная матрица»:
  таблица «узел × фактор × частота» + cross-tab «фактор × фактор».
  5 осей факторов: triggers / dropped_because / boundaries /
  hard_floor.rules / task_classification.

Эффект: /brain-retro теперь может выдавать утверждения уровня «#55
выбрался против #53 по ADR-009 7 раз и по triggers-match 5 раз», а
не просто «#55 использован 12 раз». Это closes гэп факторного
анализа.

Header bump v1.0 → v1.1. ADR-011 текст в плане Task A1 будет
обновлён следующим коммитом (план amendment).

Связано: e2a5394 (spec v1.0), e1772da (plan v1.0).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:45:18 +03:00
Дмитрий e1772da3bf docs(brain): план имплементации brain governance (Phase A/B/C/D, ~25 атомарных коммитов)
План имплементации спека e2a5394. 4 фазы:

- Phase A — нормативная foundation: ADR-011 + router-procedure.md +
  Tooling Прил. Н 9 атрибутов на 60 строк + Pravila §16 + PSR_v1 R16
- Phase B — observer infrastructure: docs/observer/ scaffolding +
  PII filter + Stop-hook + HK1 pre-check + settings.json register +
  /brain-retro skill
- Phase C — 4 механических контролёра: L1-watcher + cross-ref-checker +
  observer-of-observer (54w self-prune) + STATUS.md generator +
  lefthook wire-up
- Phase D — финализация: CLAUDE.md sync + smoke test +
  verification-before-completion + memory + push approval

Каждая задача TDD: failing test → implementation → passing test →
commit. Bite-sized steps (2-5 минут каждый). Subprocess через
execFileSync (Security Guidance #40 compliance). Pre-flight sync §15.2
обязателен перед каждой правкой 8 нормативных файлов. HK1 pre-check
обязателен перед регистрацией Stop-hook.

Self-review: spec coverage 15/15 sections , placeholder scan clean,
type consistency verified, all O1-O7 open questions resolved inline.

Execution: subagent-driven (recommended, per Pravila §15.1 Sonnet/Opus
only) или inline через executing-plans.

Связано:
- spec: docs/superpowers/specs/2026-05-19-brain-governance-design.md
- ADR-011 (будет написан в Task A1)
- memory/project_brain_governance_design.md
- memory/feedback_brain_unused_tools_not_problem.md

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:35:52 +03:00
Дмитрий e2a5394628 docs(brain): дизайн архитектуры регламента «мозга» (router-only + observer + 4 контролёра)
Brainstorming-сессия 19.05.2026 — финальный дизайн governance «мозга»
Лидерры. Spec в docs/superpowers/specs/2026-05-19-brain-governance-design.md
(12 секций, 13 verification критериев, 7 открытых вопросов).

Финальные решения:

1. Только роутер. Реестр узлов (Tooling Прил. Н SoT) + процедура роутера.
   Никакого каталога «проверенных цепочек», никакого 3-слойного механизма
   обновления, никакого forced-choice gate. Каждая задача — свежая сборка
   пути. Capability-readiness сохранена.

2. Observer scope B (полный пакет с дня 1). Stop-hook →
   docs/observer/episodes-YYYY-MM.jsonl + опциональные notes/*.md.
   4 обязательных поля + 6 типов структурированных событий + ПДн-фильтр.
   /brain-retro skill раз в спринт. Observer только пишет, не вмешивается.

3. 4 контролёра первой волны (5-й «стейлнес-контролёр» снят как
   избыточный после router-only refinement):
   - L1-watcher — settings.json ↔ Tooling drift detector
     (lefthook + weekly cron); закрывает L1-паттерн UPM/21st/Sentry/Redis/
     Anthropic dev-tooling.
   - Cross-ref consistency — version drift 8 нормативных файлов
     (lefthook, regex-стиль adr-judge, 0 LLM-вызовов); закрывает
     Tooling v2.11 collision 17.05.
   - Observer-of-observer — self-prune счётчик через 54 недели без
     чтений (anti-зомби-инфраструктура механизм).
   - Сигнальный статус — docs/observer/STATUS.md ежедневная приборная
     панель из C1+C2+C3+observer.

4. Поведенческое правило «не использован ≠ проблема» —
   capability-readiness осознанная стратегия заказчика; перевешивает
   аналитический инстинкт «прорезать неиспользуемое».

Также: cspell-words.txt +7 русских технических терминов
(слойного / слойный / рецидивирующие / зарегламентировать / версионный /
стейлнес / апдейты) для lefthook pass.

Статус: written-spec user review пройден, готов к переходу на
superpowers:writing-plans (terminal skill brainstorming-flow).
Имплементация — ноль. Это design document.

Связано:
- docs/discovery/2026-05-18-system-audit-brain.md (SYSTEM-аудит origin)
- memory/project_brain_governance_design.md
- memory/feedback_brain_unused_tools_not_problem.md
- Pravila §12/§14/§15 hard-rules (роутер шаг 1)
- Plugin_stack_rules_v1.md R15 + docs/routing-off-phase.md L1-L12
- ADR-011 (будет написан в writing-plans phase)
- ADR-010 HK1 pre-check (для Stop-hook observer-а)

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-19 04:19:50 +03:00
Дмитрий 435847017e chore(larastan): bump baseline для supplier-integration тестов
5 новых baseline-записей под Pest 4 quirks:
- AdminSupplierIntegrationTest.php: TestCall::getJson() x3 + postJson() x1
- CsvReconcileJobTest.php: Repository::lock() x1

Composer stan: 0 errors после bump.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:14:36 +03:00
Дмитрий bddac35ac0 Merge branch 'worktree-supplier-csv-reconcile' into feat/parallel-sessions-coordination 2026-05-18 18:11:18 +03:00
Дмитрий 35a21bc38d fix(supplier): CsvReconcileJob — insertGetId внутри try (lock release on failure)
Финальный code-review эпика: insertGetId log-строки был вне try → при
падении самого insertGetId (БД недоступна) finally не освобождал
Cache::lock → lock висел LOCK_TTL_SECONDS (600с), пропуская 2 следующих
запуска. Перенесён внутрь try; $logId инициализируется null, catch
guard'ит обращение к нему.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 18:03:47 +03:00
Дмитрий e5e44cde2e feat(supplier): UI-экран «Интеграция с поставщиком» — здоровье CSV-канала 2026-05-18 17:58:53 +03:00
Дмитрий 44d0d478f5 feat(supplier): API «Интеграция с поставщиком» — здоровье CSV-канала + ручная сверка 2026-05-18 17:51:44 +03:00
Дмитрий 56750c1658 feat(supplier): CsvReconcileJob — расписание каждые 30 минут 2026-05-18 17:46:01 +03:00
Дмитрий 553aa1d8ee feat(supplier): CsvReconcileJob — дедуп (phone,project) + async-флоу отчёта 2026-05-18 17:42:23 +03:00
Дмитрий 5397ac4a57 docs(brain): компакция «мозга» findings 2/3/6/7 — single-source счётчиков + §3.3 индекс + ruflo dormant-стаб
SYSTEM-аудит «мозга» через discovery-interview (интервью с заказчиком).
Закрыты 3 из 4 выбранных findings в нормативке (finding 7 — memory, вне git):

- CLAUDE.md v2.17 — §3.3 #31–#60 (30 строк-абзацев) свёрнуты в
  однострочный индекс с пином Tooling §4.NN (finding 2 — устранён
  дубль реестра с Tooling); §3 title / §3.3 footer / §1 row 2b /
  §0 row-label — счётчик «60» → пин на Tooling §0 (finding 3);
  §2 БД + §8 self-review — schema-метрики → пин header db/schema.sql
  (finding 3); §3.5 ruflo — ~17 строк истории → dormant-стаб (finding 6).
- Tooling Прил.Н v2.16 — §0 +anchor «КАНОН СЧЁТЧИКОВ» (единственный
  источник числовых счётчиков); §12 заголовок без stale «35».
- Pravila v1.30 — §14 заголовок +dormant-метка, §14.1 +врезка;
  §13.2 +note-пин счётчиков.
- PSR_v1 v3.15 — R10.1 +note-пин счётчиков на Tooling §0.
- cspell-words.txt +5 терминов («пин» и инфлексии).

План: docs/superpowers/plans/2026-05-18-brain-compaction-findings-2-3-6-7.md

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 17:38:03 +03:00
Дмитрий 8cc097574b feat(supplier): SupplierPortalClient — async-флоу заказа отчёта «Запрос номеров» 2026-05-18 17:36:27 +03:00
Дмитрий fe6b8ce6dc feat(supplier): SupplierCsvParser под отчёт «Запрос номеров» (Name;Tag;Phone) 2026-05-18 17:26:53 +03:00
Дмитрий 649f49fc37 feat(supplier): supplier_leads.vid -> nullable для CSV-recovered лидов
Резервный CSV-канал (Путь 2): отчёт поставщика «Запрос номеров» не
содержит vid -> CSV-recovered лиды имеют vid=NULL. UNIQUE-индекс
idx_supplier_leads_vid_unique сохранён (PostgreSQL NULL != NULL).

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-18 17:20:28 +03:00