Commit graph

722 commits

Author SHA1 Message Date
e4b5f14939 test(tradein): estimator pure-helper unit tests + fix None crash in _filter_outliers (#580) (#640)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 48s
Deploy Trade-In / deploy (push) Successful in 33s
2026-05-29 08:24:18 +00:00
b6cddcd9a8 fix(tradein): plain natural-key dedup_hash for rosreestr deals (#576) (#638)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Successful in 25s
Deploy Trade-In / build-backend (push) Successful in 45s
Deploy Trade-In / deploy (push) Successful in 37s
2026-05-29 06:56:35 +00:00
40002cfcd2 fix(deploy-tradein): track SQL migrations with _schema_migrations + baseline (#637)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-backend (push) Successful in 26s
Deploy Trade-In / build-frontend (push) Successful in 31s
Deploy Trade-In / deploy (push) Successful in 44s
2026-05-29 06:34:01 +00:00
bd3e5c8216 feat(tradein): аккаунт praktika + лимит 15 оценок/мес, чистка PRINZIP в UI (#635)
All checks were successful
Deploy / changes (push) Successful in 5s
Deploy Trade-In / changes (push) Successful in 7s
Deploy / build-backend (push) Successful in 29s
Deploy / build-frontend (push) Successful in 28s
Deploy / build-worker (push) Successful in 29s
Deploy Trade-In / build-backend (push) Successful in 46s
Deploy / deploy (push) Successful in 58s
Deploy Trade-In / build-frontend (push) Successful in 1m40s
Deploy Trade-In / deploy (push) Successful in 39s
2026-05-28 22:04:58 +00:00
312df8536a feat(tradein): infer repair_state from listing description text (#622) (#632)
All checks were successful
Deploy Trade-In / changes (push) Successful in 6s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / deploy (push) Successful in 38s
Deploy Trade-In / build-backend (push) Successful in 48s
2026-05-28 15:37:34 +00:00
6cb3d7515c fix(tradein): per-bucket velocity formula + realistic срок продажи (#574) (#631)
All checks were successful
Deploy / build-backend (push) Successful in 1m25s
Deploy / build-worker (push) Successful in 2m57s
Deploy / deploy (push) Successful in 1m10s
Deploy / changes (push) Successful in 5s
Deploy / build-frontend (push) Has been skipped
2026-05-28 15:35:16 +00:00
e72cf87e35 feat(tradein): автоматизация cian-backfill + rosreestr-import через scheduler (#560 #563) (#630)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy / changes (push) Successful in 6s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy / build-frontend (push) Has been skipped
Deploy / build-backend (push) Successful in 29s
Deploy / build-worker (push) Successful in 30s
Deploy Trade-In / build-backend (push) Successful in 47s
Deploy Trade-In / deploy (push) Successful in 43s
Deploy / deploy (push) Successful in 58s
2026-05-28 15:31:24 +00:00
d842811390 refactor(tradein): normalize repair_state raw→enum at ingest (#621) (#629)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 49s
Deploy Trade-In / deploy (push) Successful in 36s
2026-05-28 15:18:11 +00:00
4e4762f234 fix(tradein): backfill kn obj_class (parser + 3-pass) (#572) (#628)
All checks were successful
Deploy / changes (push) Successful in 6s
Deploy / build-frontend (push) Has been skipped
Deploy / build-backend (push) Successful in 1m27s
Deploy / build-worker (push) Successful in 3m9s
Deploy / deploy (push) Successful in 1m9s
2026-05-28 15:04:32 +00:00
1731704ddc feat(tradein): houses.cian_zhk_url column + backfill (#568) (#627)
All checks were successful
Deploy Trade-In / changes (push) Successful in 6s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 51s
Deploy Trade-In / deploy (push) Successful in 36s
2026-05-28 13:57:43 +00:00
609ac8ea9d fix(tradein): backfill kn price_per_m2 via sale_graph + peer median (#573) (#625)
All checks were successful
Deploy / changes (push) Successful in 6s
Deploy / build-frontend (push) Has been skipped
Deploy / build-backend (push) Successful in 1m43s
Deploy / build-worker (push) Successful in 2m41s
Deploy / deploy (push) Successful in 1m11s
2026-05-28 13:50:45 +00:00
07106d744a chore(mv): regression test + sql rule for weighted AVG (#295) (#626)
Some checks failed
Deploy / changes (push) Successful in 5s
Deploy / build-frontend (push) Has been skipped
Deploy / build-worker (push) Successful in 33s
Deploy / build-backend (push) Successful in 37s
Deploy / deploy (push) Has been cancelled
2026-05-28 13:49:54 +00:00
ec26e5813f fix(tradein): implement listings_snapshots + offer_price_history writers (#567) (#624)
Some checks are pending
Deploy Trade-In / deploy (push) Successful in 43s
Deploy Trade-In / build-backend (push) Successful in 1m2s
Deploy / changes (push) Waiting to run
Deploy / build-backend (push) Blocked by required conditions
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy / build-worker (push) Blocked by required conditions
Deploy / build-frontend (push) Blocked by required conditions
Deploy / deploy (push) Blocked by required conditions
2026-05-28 13:49:52 +00:00
6553e5830f fix(tradein-imv): harden Avito IMV anti-bot path (#565) (#620)
All checks were successful
Deploy Trade-In / deploy (push) Successful in 36s
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 42s
2026-05-28 11:29:11 +00:00
81bf7e6def fix(tradein-imv): harden Avito IMV anti-bot path + offline contract tests (#565)
Add warm-up GET /evaluation/realty + production browser header set (Sec-Fetch,
X-Requested-With, 25s timeout) mirroring avito.py, чтобы защитить 3-step IMV flow
от server-IP анти-бот 403. Refactor step B/C парсинга в pure helpers
(_parse_geo_position/_parse_price/_parse_placement_history/_parse_suggestions)
+ fixture-driven offline тесты из живых JSON-captures.

Честный диагноз: контракт (geoFieldsHash, price-блок, categoryId=24) НЕ менялся —
проверено живым capture'ом с этой машины (A→B→C, recommended 7.39M). Реальная
причина #565 — скорее анти-бот по PROD-IP, не код → если #565 останется после
deploy, настоящий фикс = ротация egress IP воркера (devops, отдельно).

code-reviewer:  APPROVE no critical — warm-up non-fatal, injected-session path
unchanged, refactor preserves shapes, graceful-None сохранён, fixtures без PII.
Tests: 12 new (27 total). Ruff clean.

Closes #565
2026-05-28 16:29:05 +05:00
3dfa179d47 feat(tradein): калибровка repair-коэффициентов base 1.0 (#7) (#619)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 44s
Deploy Trade-In / deploy (push) Successful in 35s
2026-05-28 11:15:59 +00:00
33ee00c065 feat(tradein): калибровка repair-коэффициентов с base 1.0 (#7)
_REPAIR_COEF → tunable market-эвристика: needs_repair=0.94, standard=1.00
(baseline no-op; было 0.98 — срезало 2% с каждой standard-оценки), good=1.05,
excellent=1.10. Деривация из данных отклонена: listings.repair_state покрытие
~2%, сырые un-normalized значения, медианы confounded площадью (issue #7).

+ regression-тест (читает _REPAIR_COEF динамически — переживёт рекалибровку):
ratio excellent/needs_repair, standard/None no-op, наличие/отсутствие note.
Поправлен mislabeled comment над _IMV_HOUSE_TYPE_MAP. _IMV_REPAIR_MAP не тронут.

code-reviewer:  APPROVE no critical/minor. Tests: 5 new + 7 cian-integration.
Ruff clean.

Closes #7
2026-05-28 16:15:54 +05:00
1058dc2430 fix(tradein): decode Avito houses URL-encoded __preloadedState__ (#566) (#618)
All checks were successful
Deploy Trade-In / build-backend (push) Successful in 44s
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / deploy (push) Successful in 35s
2026-05-28 10:58:54 +00:00
a3f45a6722 fix(tradein): decode Avito houses URL-encoded __preloadedState__ (#566)
Avito switched the houses-catalog state blob from JSON.parse("<js-escaped>")
to a URL-encoded string literal, wrapped the 10 widgets in
placeholders[0].widgets, и re-nested developmentData под props.housePage.
JS-unescape path silently failed → houses rows перестали наполняться
(starve'ит #6 same-building + #569 deal centroids).

Extract decode в pure _extract_preloaded_state (urllib.parse.unquote,
JSON.parse fallback для старой формы), add _flatten_widgets, и сделать
_parse_house_page tolerant к обеим developmentData/ratingPreview формам.
Real-HTML fixture (Yumasheva-6 EKB) + 4 regression-теста.

code-reviewer:  APPROVE no critical (regex anchoring verified, decode
safe — no eval/unicode_escape, backward-compat реальный, delisted-house
envelope degrade'ит gracefully, fixture без PII/secrets). Tests: 22 passed.

Closes #566
2026-05-28 15:58:19 +05:00
7c715c9249 feat(tradein): бейдж точности адреса qc_geo на карточке (accuracy #1) (#617)
All checks were successful
Deploy Trade-In / build-frontend (push) Successful in 1m42s
Deploy Trade-In / deploy (push) Successful in 36s
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-backend (push) Successful in 47s
2026-05-28 10:37:54 +00:00
492dd0aba6 feat(tradein): бейдж точности адреса (qc_geo) на карточке оценки (accuracy #1)
Честность к пользователю: показываем насколько точно определён адрес —
«до дома» / «до улицы» / «приблизительно» — рядом с confidence.

- schemas/trade_in.py: address_precision: Literal["house","street","approximate"]|None
- estimator.py: _qc_geo_to_precision (qc_geo 0→house, 1→street, ≥2→approximate,
  None→None), set в основном return + _empty_estimate
- api/v1/trade_in.py: get_estimate + estimate_pdf теперь rehydrate'ят DaData-поля
  (canonical_address, house_cadnum, house_fias_id, address_precision, metro_nearest)
  из row — раньше на ?id= reopen / в PDF вся Q1-обогащёнка пропадала (поймал
  code-reviewer). Колонки уже persisted, фикс read-path.
- frontend: AddressPrecision type + precision-badge в HeroSummary (.card-meta),
  токены --success/--accent-2/--bg-card-alt, без новых токенов.

Канон: tech-analyst (план) → backend-engineer + frontend-engineer → code-reviewer
( APPROVE, поймал reopen-path gap) → fold-in fix. Tests: 7 passed, tsc clean, ruff clean.
match_house_readonly wiring отложен (fast-follow).
2026-05-28 15:37:33 +05:00
e716252081 feat(tradein): приоритизировать DaData house-backfill на дома с листингами (#2) (#616)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 46s
Deploy Trade-In / deploy (push) Successful in 36s
2026-05-28 10:17:06 +00:00
47ba362303 feat(tradein): приоритизировать DaData house-backfill на дома с листингами (accuracy #2)
ORDER BY has_active_listings DESC, id во всех priority-бакетах + новый
--priority listings (focused sweep: NULL cadnum + есть active listing).
Дневной 100/day budget сначала закрывает дома, которые реально появляются
в оценках → estimator #6 cadastr_exact same-building матчинг загорается на
real estimate targets за дни, а не недели.

Correlated EXISTS бьёт по partial-индексу listings_house_id_fk_idx.
Write-path / EKB-guard / SAVEPOINT / qc_geo rules не тронуты.

code-reviewer:  APPROVE no critical. Tests: 40 passed. Ruff clean.
2026-05-28 15:17:01 +05:00
04a90810b2 feat(tradein): geocode leftover deals via Nominatim (#569 Step 3) (#615)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 1m57s
Deploy Trade-In / deploy (push) Successful in 43s
2026-05-28 09:59:49 +00:00
783a85ad2b feat(tradein): geocode leftover deals via Nominatim fallback (#569 Step 3)
Добавляет scripts/geocode_deals_nominatim.py для ~14% сделок всё ещё
lat IS NULL после house-centroid прохода (Step 2) — улицы без геокодированных
домов, которые centroid-join не покрывает. Переиспользует geocoder.geocode
(cache → Cadastral FDW → Yandex → Nominatim), дедупит по адресу (distinct
улицы определяют число вызовов, не 7k строк), и стампит geocode_tried_at на
КАЖДОЙ попытке (успех И чистый промах) чтобы un-geocodable строки не крутились
по 1 req/s. Resume: lat IS NULL + 30-day staleness, per-address SAVEPOINT,
--limit/--dry-run/--batch/--stale-days.

Pre-push review (code-reviewer):  APPROVE, no critical — проверены SQL-safety,
no-infinite-reloop (mark-tried на miss, no-stamp на raised exc), window-cap,
geom-not-manual, dedup, async. Tests: 17 passed. Ruff clean.
2026-05-28 14:59:24 +05:00
aeaba42ed3 feat(tradein): backfill deals.lat/lon из house street-центроидов (#569 Step 2) (#614)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / deploy (push) Successful in 34s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 44s
2026-05-28 09:26:00 +00:00
1c6d59e3ee feat(tradein): backfill deals.lat/lon из house street-центроидов (#569)
deals (49,791 ДКП-сделок Росреестра) на 100% NULL geom → estimator
_fetch_deals (ST_DWithin) никогда не матчит, actual_deals всегда пустой
(корень #571 «deals disabled»). Добавляет scripts/geocode_deals_from_houses.py:
строит per-street центроиды из ~8.6k геокодированных houses и проставляет
lat/lon каждой сделке по нормализованному ключу улицы (geom авто-заполняется
триггером deals_set_geom_trg). Zero внешних geocoder-вызовов; --dry-run
проецирует coverage и топ-10 unmatched улиц.

Pre-push review поймал data-corruption баг: _APT_SUFFIX_RE без правого якоря
жрал реальные улицы на кв/корп/оф/пом/стр («Строителей»→'ул.' garbage key →
неверный центроид). Fix: требовать цифру после суффикс-токена + регресс-тест.

Tests: 26 (street-key нормализация вкл. regression, centroid AVG, matched UPDATE,
no_street_match, --dry-run no-op, SAVEPOINT isolation, geom-not-manual). Ruff clean.
2026-05-28 14:25:26 +05:00
1d296dd77a feat(tradein): same-building матчинг аналогов по house_id (#6) (#613)
All checks were successful
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / deploy (push) Successful in 41s
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-backend (push) Successful in 47s
2026-05-28 08:56:59 +00:00
30a80ee608 feat(tradein): same-building матчинг аналогов по house_id (#6)
Estimator теперь резолвит target-адрес в КАНОНИЧЕСКИЙ house_id (read-only,
без создания записи) и матчит аналоги по listings.house_id_fk — детерминированный
Tier S «тот же дом» вместо хрупкого address-string prefix match. 99% листингов
слинкованы с houses, поэтому это срабатывает уже сегодня и точнее работает между
разнородными источниками (Avito/Cian/Yandex форматируют адрес по-разному).

- matching/houses.py: match_house_readonly() — read-only target→house резолвер
  (cadastr_exact → fingerprint → geo_proximity 50m), без INSERT / house_sources /
  advisory lock. Возвращает None если уверенного match нет.
- estimator.estimate_quality: после geocode+DaData резолвит target_house_id
  (cadastr от DaData → cadastr_exact заработает по мере backfill houses), graceful.
- estimator._fetch_analogs: новый param target_house_id + канонический Tier S
  (WHERE house_id_fk = target) ПЕРЕД address-prefix Tier S (теперь fallback).
  tier label 'S' сохранён (frontend уже рендерит).

Эффект: вместо «похожие в радиусе 800-1000м» — «вот что в ЭТОМ доме», прямой
выигрыш в точности оценки. Foundation под cadastr/FIAS exact match (DaData Q1/Q3).

Tests: 9 новых (match_house_readonly tiers + never-inserts + canonical Tier S
fires/fallback/too-few). Ruff clean. Pre-existing 4 fail в test_estimator_source_quota
(unpack 2≠3, красные на main до этого PR) — не затронуты.
2026-05-28 13:55:51 +05:00
3fcac6818a Merge pull request 'fix(stale-claims): avoid SIGPIPE 141 — pass file path не pipe' (#612) from feat/stale-claims-sigpipe-fix into main
Reviewed-on: #612
2026-05-27 22:06:45 +00:00
lekss361
8c9d1344cc fix(stale-claims): avoid SIGPIPE 141 — pass file path не pipe
Root cause: `cat $ISSUES_TMP | python3 <<EOF ... sys.exit(0)` — Python exits
0 early, cat получает SIGPIPE, set -o pipefail → script exits 141 = failure.

Fix: передача file path через env var вместо stdin pipe. Python читает файл
напрямую. No pipe → no SIGPIPE.

Verified локально на VPS с bot-qa token: exit 0, '[OK] 0 wip issues —
nothing to do'.

Also remove diagnostic steps from workflow (added в PR #611, нужно для
поиска root cause, теперь убираем).

Refs: PR #611 (diagnostic), runs #1514-1520 failures.
2026-05-28 01:05:56 +03:00
4ad309133e Merge pull request 'chore(workflow): diagnostic для stale-claims.yml' (#611) from fix/stale-claims-diagnostic into main
Reviewed-on: #611
2026-05-27 22:03:20 +00:00
lekss361
b86688bc0f chore(workflow): add diagnostic output to stale-claims.yml
Adds runner env + token sanity check + bash -x trace перед запуском cleanup
script. Цель — увидеть actual failure cause в Forgejo Actions logs (manual
runs #1514-1517 все упали ~4s, но script локально работает с тем же PAT).

Diag steps:
- runner environment (python3/curl/mktemp)
- token validity (curl /api/v1/user)
- bash -x для script trace

После merge — trigger manual dispatch + читать logs. Diagnostic строки уберём
fixup-commit'ом после диагноза.

Refs: PR #610 (stale-claims initial), runs #1514-1517 failures.
2026-05-28 01:01:29 +03:00
26559e16e5 Merge pull request 'feat(claude): env-vars refactor + stale-claim cron (Phase 2 final)' (#610) from feat/claude-envvars-and-stale-cron into main
Reviewed-on: #610
2026-05-27 21:40:28 +00:00
lekss361
e4dc866e20 fixup(claude): address review-bot blockers on PR #610
🔴 Critical (3):

1. cleanup-stale-claims.sh: export CUTOFF + STALE_HOURS
   Без `export` Python heredoc child process получал "0" вместо реального
   cutoff → cron всегда видел все issues как fresh → ничего не освобождал.
   Plus added abort при CUTOFF=0 в Python heredoc для defense-in-depth.

2. cleanup-stale-claims.sh: datetime.UTC → datetime.timezone.utc
   datetime.UTC требует Python 3.11+. Forgejo runner ubuntu-latest имеет 3.10.
   datetime.timezone.utc works в 3.8+.

3. cleanup-stale-claims.sh: invert label order — DELETE wip FIRST, потом
   POST ready. Если step 2 (add ready) fails — issue в neutral state без
   status/*, менее опасно чем оба status/ready+status/wip одновременно.

🟠 + 🟡 + 🟢 (5):

4. Added pagination loop (defensive cap 10 pages × 50 = 500 issues), но
   реализована через temp file + Python parsing (не bash JSON concat).

5. Removed dead code: iso_to_epoch() shell helper не использовался.

6. _autonomous_pickup.md: fix broken `Out-Null | if (-not $?)` pattern.
   GetEnvironmentVariable НЕ throws при missing — возвращает $null. $? у
   Get* всегда $true. Заменено на прямую проверку результата.

7. stale-claims.yml: добавлен concurrency group чтобы overlapping runs
   не stomp'ились (хотя 5-min timeout делает overlap unlikely, defensive).

8. Documented updated_at != heartbeat assumption в header script'а.

Не сделано (low/optional):

- Setup script tokens в memory (UX trade-off — не critical)
- Token suffix в console output (минор info leak в shell history)

Refs: PR #610 review by review-bot (sha=297eb29, verdict=changes)
2026-05-28 00:33:27 +03:00
lekss361
297eb29d65 feat(claude): env-vars refactor + stale-claim cron (Phase 2 finalization)
#11: slash-commands и _autonomous_pickup.md теперь читают persistent User-scope
env vars напрямую (FORGEJO_TOKEN_<ROLE>) вместо file-based из ~/.claude/secrets/.

Один раз: scripts/setup-bot-env.ps1 (запускается user'ом локально, кладёт
токены из vault в Windows User registry). После этого окна grab credentials
через [System.Environment]::GetEnvironmentVariable() — никаких файлов.

Все 5 work-as-*.md обновлены (analyst/backend/frontend/reviewer/qa).

#12: stale-claim cleanup — cron каждые 30 минут.

- scripts/cleanup-stale-claims.sh — bash, parses Forgejo API + Python для JSON
- .forgejo/workflows/stale-claims.yml — cron schedule `*/30 * * * *`

Освобождает issues застрявшие в status/wip >4h:
  - assignees=[]
  - +status/ready -status/wip
  - comment "stale claim released, worker likely crashed"

Использует secret FORGEJO_BOT_QA_TOKEN (минимум прав = write:issue).

Setup: secret нужно завести в Forgejo Actions UI после merge —
git.gendsgn.ru/lekss361/gendesign/-/settings/actions/secrets.

Refs: PRs #608, #609. Closes TODO с PR #608 (stale-claim cron).
2026-05-28 00:24:45 +03:00
532b8cdda2 Merge pull request 'feat(claude): Phase 2 — slash-commands + pre-flight + Forgejo labels' (#609) from feat/claude-phase2-labels-commands into main
Reviewed-on: #609
2026-05-27 20:59:33 +00:00
lekss361
018eb1e2ee feat(claude): Phase 2 — slash-commands + pre-flight + Forgejo labels
Phase 2 prep для autonomous multi-window workflow (Phase 1 — PR #608).

Изменения:

1. `.claude/agents/_autonomous_pickup.md` — добавлена Pre-flight checklist:
   - Шаг 1: где взять PAT из vault meta/00_credentials.md
   - Шаг 2: env vars + git identity (GIT_AUTHOR_NAME/EMAIL — критично!)
   - Шаг 3: bot-remote setup (отдельный remote с bot's PAT для audit log)
   - Шаг 4: sanity check identity (curl /user → должен вернуть bot-<role>)

   Без этого commits писались бы под lekss361, не под ботом.

2. `.claude/commands/work-as-*.md` (5 файлов) — slash-commands для запуска окон:
   - work-as-analyst (sonnet, /loop 30m)
   - work-as-backend  (sonnet, /loop dynamic)
   - work-as-frontend (sonnet, /loop dynamic)
   - work-as-reviewer (opus, /loop 5m)
   - work-as-qa       (sonnet, /loop 10m)

   Каждый command:
   - Описывает pre-flight для конкретной роли
   - Ссылается на соответствующий .claude/agents/auto-*.md
   - Перечисляет hard rules для роли
   - Объясняет per-tick workflow

3. Forgejo labels (16 шт, созданы через REST API — не в этом diff):
   scope/{backend,frontend,db,qa,devops}
   status/{ready,wip,review,qa,done,blocked}
   priority/{p0,p1,p2}
   pause-bots, needs-human

Что осталось для активации:

- 5 Forgejo bot-users + PATs (уже созданы 2026-05-27, см. vault)
- ~/.claude/secrets/forgejo-bot-*.token — выгрузка PAT'ов из vault user'ом вручную
- Stale-claim cron (отдельный PR)
- Optional: multi-window launcher через tmux/wezterm

Refs: PR #608 (Phase 1), runbooks/multi_agent_autonomous_workflow.md
2026-05-27 23:50:58 +03:00
29e7e7cdb4 Merge pull request 'feat(claude): auto-* agent stubs для autonomous multi-window workflow (DRAFT)' (#608) from feat/claude-auto-agents-stubs into main
Reviewed-on: #608
2026-05-27 20:27:33 +00:00
lekss361
024bd4c68f merge: forgejo/main into feat/claude-auto-agents-stubs
.gitignore conflict resolved by accepting main's explicit-blacklist approach
(per-path list of .claude/cache, .claude/sessions, etc) — лучше чем мой
.claude/* + whitelist подход, потому что новые .claude/agents/auto-*.md и
.claude/rules/*.md auto-track без необходимости whitelist gymnastics.

Main's структура также удаляет .sentryclirc / sshkey.txt / cian-cookies
mentions — приняты как есть.
2026-05-27 23:20:24 +03:00
lekss361
76784e91fd fixup(claude): address review-bot findings on PR #608
Some checks failed
CI / backend (pull_request) Failing after 43s
CI / frontend (pull_request) Successful in 1m35s
🟠 High:
- auto-backend.md: drop execute_sql из tools (DDL/DML blast radius)
- auto-code-reviewer.md: drop execute_sql + add analyze_query_indexes
- _autonomous_pickup.md: env vars FORGEJO_PAT/BASE_URL → FORGEJO_TOKEN/URL (align с rules/git-pr.md)
- auto-code-reviewer.md: добавлен canonical marker template
  <!-- gendesign-review-bot: sha=X verdict=Y --> + SHA guard перед merge
- auto-code-reviewer.md: self-extending guard exception (NEVER merge PRs
  меняющие git-pr.md auto-merge policy / CLAUDE.md critical rules /
  этот файл / содержащие литеральные secrets)

🟡 Medium:
- _autonomous_pickup.md: STRICT claim race check (length==1 AND assignee==me)
  + best-effort rollback при race lost
- _autonomous_pickup.md: pause-bots mid-work policy (finish current, не abort)
- _autonomous_pickup.md: stale-claim cron explicitly marked TODO
- auto-qa-tester.md: differentiate flaky/prod_down/feature_regression — global
  pause только при prod_down (3× FAIL на /health endpoint), не на flaky
- auto-backend.md: PR body template из rules/git-pr.md (Summary + Test plan + Closes)

🟢 Low:
- _autonomous_pickup.md: BOT_USERNAME documented в env list
- _autonomous_pickup.md: PAT scope guidance (narrow repo, не user-scope)
- auto-analyst.md: de-dup через forgejo_issue frontmatter preferred (fuzzy
  query — fallback)

Refs: PR #608 review by @lekss361 (gendesign-review-bot marker)
2026-05-27 23:11:58 +03:00
lekss361
89303c9769 feat(claude): auto-* agent stubs для autonomous multi-window workflow
Some checks failed
CI / backend (pull_request) Failing after 48s
CI / frontend (pull_request) Successful in 1m39s
DRAFT-файлы для autonomous /loop окон (5 ролей: analyst/backend/frontend/
code-reviewer/qa-tester). НЕ для invoke через Task tool — только как
--append-system-prompt для standalone Claude Code windows с /loop.

Все файлы помечены status:draft. Не активны до сборки .claude/commands/
work-as-* wrappers + Forgejo labels + bot-PATs (см. runbook
multi_agent_autonomous_workflow.md в vault).

Также fix .gitignore: .claude/ → .claude/* чтобы whitelist'ы
!.claude/agents/** работали (git не allow re-include children of ignored
directory).

Refs: runbooks/multi_agent_autonomous_workflow.md (vault)
2026-05-27 22:57:16 +03:00
0380fe9e34 fix(tradein): DaData backfill — Екатеринбург city context (#606 hotfix) (#607)
All checks were successful
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 56s
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / deploy (push) Successful in 36s
2026-05-27 14:49:11 +00:00
27fc8101e5 fix(tradein): DaData backfill — Екатеринбург city context (#606 hotfix)
Dry-run на проде показал, что DaData без явного города мапит короткие
street-адреса в Москву по умолчанию («улица Просторная» → «г Москва, ул
Просторная»). Это бы привело к catastrophic false-positive enrichment'у
если бы скрипт запустили без --dry-run.

Two-layer fix:

1. `_with_city_context(addr)` — pre-pends «Екатеринбург, » если в адресе
   ещё нет упоминания города. Идемпотентен, case-insensitive.

2. `_result_in_ekb(result)` — post-filter. Проверяет `raw.city`
   (структурное поле DaData) с fallback на substring search в
   `canonical_address`. Защищает даже если DaData проигнорирует city-префикс
   и всё равно вернёт другой город (например для homonym streets).

`_is_enriched_result()` теперь требует обе проверки: qc_geo IN (0,1)
AND coords AND city == Екатеринбург. Только так делаем UPDATE coords/cadnum.

Без этого fix'а нельзя запускать backfill — все non-EKB false-positives
перезаписали бы NULL coords мусором.

9 новых тестов: city context (prepend / idempotent / case / empty),
post-filter (raw.city / canonical / Moscow reject / None).
Combined 29 passed.
2026-05-27 19:48:37 +05:00
08feb60a7f feat(tradein): DaData /clean/address backfill для houses (PR Q3) (#606)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 47s
Deploy Trade-In / deploy (push) Successful in 35s
2026-05-27 14:43:51 +00:00
e332052d0e feat(tradein): DaData /clean/address backfill для houses (PR Q3)
Migration 070 — добавляет houses.house_fias_id + dadata_qc_geo / qc_house /
enriched_at для tracking. Скрипт scripts/backfill_houses_dadata.py
проходит по ~3.8k rows с NULL coords + ~8.6k с NULL cadnum daily 100/day
(DaData demo quota → ~124 дня walltime для полного прохода).

Per-row SAVEPOINT, resume-safe (фильтр dadata_enriched_at IS NULL),
qc_geo IN (0,1) → overwrite coord-payload, иначе только tracking.
--priority coords|cadnum|both, --dry-run, --limit N (default 100).

20 тестов покрывают happy path qc_geo=0, qc_geo=3 city-level skip,
DaData None response, per-row exception isolation, --dry-run, --limit,
--priority filter, и missing-creds fail-fast.
2026-05-27 19:43:07 +05:00
f438f536b8 feat(tradein): DaData /suggest tier в /suggest endpoint (PR Q2) (#605)
All checks were successful
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 58s
Deploy Trade-In / deploy (push) Successful in 42s
Deploy Trade-In / changes (push) Successful in 5s
2026-05-27 14:09:31 +00:00
386fa8c0e3 feat(tradein): DaData /suggest tier в /suggest endpoint (PR Q2)
Yandex Suggest заблокирован (демо 1k/день исчерпан) — DaData /suggest/address
(10k/день free, token-only auth, лучшее покрытие РФ) заменяет его как Tier 2
после Cadastral FDW. Yandex остаётся как Tier 3 fallback.

- app/services/dadata.py: DadataSuggestion dataclass + async suggest_addresses()
  (token-only, без X-Secret; graceful [] на все ошибки; 5s timeout;
  classifies fias_level→kind: 8=house, 7=street, ≤6=city; count clamp ≤20)
- app/services/geocoder.py: _dadata_suggest() обёртка, дропает entries без
  координат; suggest() теперь Cadastral → DaData → Yandex → Nominatim
- tests/services/test_dadata.py: 15 новых unit-тестов (happy + все error paths)
- tests/services/test_cadastral_reverse.py: +тест DaData до Yandex, update
  fallback теста под новый tier chain

Tests: 62 passed (35 dadata + 20 cadastral reverse + 7 geocode reverse api).
Ruff clean. Reuse DADATA_API_TOKEN from PR Q1 (#604) — secret не нужен для suggest.
2026-05-27 19:08:58 +05:00
0b31431b99 feat(tradein): DaData on-demand enrichment в estimate flow (PR Q1) (#604)
All checks were successful
Deploy Trade-In / changes (push) Successful in 5s
Deploy Trade-In / deploy (push) Successful in 37s
Deploy Trade-In / build-frontend (push) Has been skipped
Deploy Trade-In / build-backend (push) Successful in 48s
Closes follow-ups: PR Q2 frontend Suggest swap, PR Q3 NULL-coords backfill, T0_per_house tier matching for Rosreestr deals.

Migration 069 ALTER TABLE adds 6 nullable columns to trade_in_estimates.
ENV: DADATA_API_TOKEN + DADATA_API_SECRET must be set on VPS .env.runtime before requests will be enriched. Without them the service tихо disables and estimator continues as before.

Verified: 20/20 dadata unit tests pass, ruff clean, no regressions in 46 estimator tests. Pre-existing 6 failures in test_estimator_source_quota/test_search_api/test_cian_valuation are unrelated and tracked separately.
2026-05-27 13:56:14 +00:00
a7fa1a4ffa feat(tradein): DaData on-demand enrichment в estimate flow (PR Q1)
Добавляет app/services/dadata.py — async client для DaData /clean/address,
обогащающий target адрес canonical-формой, kadastr_num, ФИАС, координатами
и ближайшим метро. Migration 069 расширяет trade_in_estimates 6 nullable
колонками; estimator.estimate_quality вызывает service после geocode и
сохраняет результат в основной INSERT. AggregatedEstimate отдаёт
canonical_address / house_cadnum / house_fias_id / metro_nearest наружу.

Service graceful: пустые credentials / quota 429 / 5xx / network fail → None,
estimator продолжает работу. Demo tier 100 req/день — хватит для low-traffic
prod и тестов. ENV: DADATA_API_TOKEN, DADATA_API_SECRET.

Tests: 20 unit-тестов через httpx.MockTransport, zero real DaData calls.
Покрыто: happy path, отсутствие creds, короткий адрес, timeout/network,
HTTP 429/401/403/500/502/503, пустой массив, malformed shape, partial
payload, coerce строковых qc-кодов в int, проверка request body+headers.

Закладывает базу для PR Q2 (frontend DaData Suggest, 10k/день free) и
PR Q3 (backfill 339 NULL-coords houses) — обе используют тот же сервис.
2026-05-27 18:50:12 +05:00