Project Context

Внутренний инструмент для подготовки качественного контекста проекта Polymarket Lab для нейронки: памятка, current task, ASCII-дерево, выбор таблиц БД, dump схемы, relationships, summary файлов, содержимое выбранных файлов и деление полного context на части.
Project: polymarket_lab
Root: /var/www/polymarket_lab

Current Task

Этот текст будет включён в общий Project Context. Лучше всегда явно описывать текущую задачу.

Разделение на части

Укажи, на сколько частей делить итоговый context. Деление идёт по целым смысловым блокам, файлы не режутся.

AI Project Memo

Большая памятка для нейронки: смысл проекта, архитектура, правила написания кода и текущие приоритеты.
POLYMARKET LAB — AI PROJECT MEMO

======================================================================
1. WHAT THIS PROJECT IS
======================================================================

Polymarket Lab is a separate internal engineering project for collecting,
storing, viewing and later analyzing data from Polymarket.

Project goals:
- collect Polymarket markets via API
- store them in our own MariaDB database
- store history of market snapshots
- run cron-friendly jobs
- provide a PHP web dashboard for internal viewing
- later add CLOB market data
- later build signals
- later add paper trading
- later add analytics and possibly AI-assisted analysis

This is not a marketing website.
This is an internal data/engineering lab.

======================================================================
2. MAIN PROJECT PRINCIPLE
======================================================================

Architecture first, code second.

Any new code must fit into the project architecture cleanly.
Do not write chaotic code.
Do not mix responsibilities between layers.

Before proposing implementation, always understand:
- where the file belongs
- why it belongs there
- who will call it
- what it should return
- what layer it belongs to

======================================================================
3. PROJECT CONTEXT FROM USER
======================================================================

Important project rules explicitly requested by the user:

1. SQL rule:
Whenever proposing tables or columns for MySQL / MariaDB,
always explain every column:
- purpose
- values it stores
- meaning in project logic

Additionally, when appropriate, use COMMENT on table columns directly in SQL.

2. Architecture rule:
The user wants to design project structure and expandable architecture carefully first,
so the project does not become confusing later.

This rule must be preserved in future answers.

======================================================================
4. CURRENT PROJECT STRUCTURE
======================================================================

Python backend:
- app/clients/        external API access only
- app/repositories/   database access only
- app/services/       business logic
- app/jobs/           cron-friendly entry points
- app/utils/          common helpers/utilities
- app/models/         schemas / internal models

SQL:
- sql/                migrations / schema files

Web:
- web/public/         public PHP entry points
- web/public/api/     internal web API endpoints
- web/includes/       config, DB, layout, helpers
- web/public/assets/  CSS / JS / static assets

Runtime:
- var/logs/           application logs

======================================================================
5. PYTHON LAYER RULES
======================================================================

5.1 clients
Files in app/clients:
- work only with external APIs
- do not write directly to DB
- do not contain business orchestration
- return raw or lightly normalized data

Examples:
- polymarket_gamma.py
- polymarket_clob.py

5.2 repositories
Files in app/repositories:
- work only with DB
- contain SQL operations
- do not call external APIs
- do not perform business orchestration

Examples:
- upsert_market(...)
- insert_snapshot(...)
- create_job_log(...)

5.3 services
Files in app/services:
- contain business logic
- connect clients + repositories
- normalize data
- decide how to store and process data

5.4 jobs
Files in app/jobs:
- are cron-friendly entry points
- should be thin wrappers around services
- should not contain heavy business logic
- should:
  - create start log
  - run service
  - finish log
  - handle exceptions properly

======================================================================
6. SQL RULES
======================================================================

IMPORTANT PROJECT RULE:

Whenever proposing:
- a new table
- a new column
- a schema change
- an index

You must always explain EACH column:
- purpose of the column
- what values it stores
- what it means in the project logic
- whether it can be NULL
- typical expected values

Additionally:
- use COMMENT on tables when appropriate
- use COMMENT on columns when appropriate

Do not give raw CREATE TABLE without explaining the meaning of fields.

======================================================================
7. FILE HEADER RULE
======================================================================

Important files should contain a short header comment explaining:
- file path
- purpose
- what it does
- who calls it
- how to run it
- important notes

This is useful for:
- humans
- future maintenance
- AI analysis

======================================================================
8. LOGGING RULES
======================================================================

Project uses a simplified logging approach.

Main log file:
- var/logs/app.log

It stores:
- job start
- job finish
- errors
- API requests
- processing summaries
- important service steps

jobs_log table:
- is NOT a full technical log
- stores only short execution summaries:
  - job name
  - status
  - message
  - rows processed
  - timestamps

Do not overcomplicate logging without a real need.

======================================================================
9. CRON RULES
======================================================================

The project is intentionally cron-friendly.

Correct approach:
- separate job files
- no single infinite loop process unless really needed
- each job should be runnable:
  - manually
  - via cron

Example:
- python -m app.jobs.collect_markets
- docker compose exec -T polymarket_lab python -m app.jobs.collect_markets

Jobs should remain small and predictable.

======================================================================
10. WEB / PHP RULES
======================================================================

The PHP dashboard is an internal technical dashboard.

It should be:
- light
- compact
- tabular
- informative
- minimalistic
- easy to scan

The web UI should help understand:
- project data
- DB structure
- field names
- Russian explanation of DB fields

Do not turn it into a flashy public UI.

======================================================================
11. DO NOT DO THESE THINGS
======================================================================

Do not:
- mix client/service/repository layers
- put business logic into jobs
- put DB writes into API clients
- overengineer too early
- add unnecessary abstractions
- expose secrets from .env
- break working architecture for cosmetic reasons

======================================================================
12. WHAT IS ALREADY IMPLEMENTED
======================================================================

Already implemented:
- separate Docker project
- shared MariaDB usage
- Gamma API collector
- markets table
- market_snapshots table
- jobs_log table
- unified app log
- PHP dashboard
- project context tool

Working core files include:
- app/config.py
- app/db.py
- app/clients/polymarket_gamma.py
- app/repositories/*
- app/services/collector_service.py
- app/jobs/collect_markets.py
- app/utils/logger.py
- main PHP dashboard pages
- project context files

======================================================================
13. WHAT EXISTS AS PLACEHOLDERS
======================================================================

Some files may exist as architectural placeholders and still be empty.
That is intentional.

Typical placeholders:
- app/clients/polymarket_clob.py
- app/jobs/analyze_markets.py
- app/jobs/run_paper_trading.py
- app/models/*
- app/services/analyzer_service.py
- app/services/signal_service.py
- app/services/trader_service.py
- app/utils/dt.py
- app/utils/parsing.py
- sql/*.sql (if not yet filled)
- README.md
- health.php

AI must distinguish between:
- implemented production logic
- placeholders prepared for future work

======================================================================
14. CURRENT PRIORITY
======================================================================

Priority order should generally be:

1. Fix and store SQL schema files in sql/
2. Add CLOB client
3. Add collect_clob_snapshots job
4. Collect best_bid / best_ask / spread / midpoint
5. Then signals
6. Then paper trading
7. Then analytics

Do not jump too far ahead unless specifically requested.

======================================================================
15. RUNTIME PATHS
======================================================================

Important path distinction:

Host machine path:
- /srv/sites/polymarket_lab

Web/PHP runtime path inside container mount:
- /var/www/polymarket_lab

AI should keep this distinction in mind and not confuse host path with runtime path.

======================================================================
16. HOW TO ANSWER WELL FOR THIS PROJECT
======================================================================

Good answer pattern for this project:

First:
- explain where the new file/table/module belongs in architecture
- explain why it belongs there

Then:
- give implementation

If SQL is involved:
- explain every column carefully

If a new module is proposed:
- explain:
  - purpose
  - caller
  - input
  - output
  - role in architecture

======================================================================
17. BEST CONTEXT PACKAGE FOR AI
======================================================================

Best package to send to AI for this project includes:

1. AI Project Memo
2. Current Task
3. Project Tree
4. File Path List
5. Database Schema Dump
6. Table Relationships
7. Implemented vs Placeholder
8. Files Summary
9. File Contents

If the full context is too long for a model,
split it into multiple sequential parts.
Parts must preserve whole file blocks.

======================================================================
18. CURRENT TASK SHOULD ALWAYS BE EXPLICIT
======================================================================

When working with AI on this project, always state the current task clearly.

Examples:
- now we are fixing SQL migrations
- now we are designing CLOB layer
- now we are building collect_clob_snapshots.py
- now we are improving dashboard
- now we are not touching paper trading yet

This improves relevance and reduces architectural drift.

======================================================================
19. SUMMARY
======================================================================

Polymarket Lab is a modular internal engineering project.
The main value is not fast random code, but a clean maintainable system.

Good solutions for this project are:
- readable
- layered
- predictable
- expandable
- aligned with architecture
- careful with SQL meaning
- careful with runtime paths
- useful for both humans and AI

Database Schema Dump

Таблицы, столбцы, типы, nullable, default, ключи, комментарии и индексы из INFORMATION_SCHEMA.
DATABASE SCHEMA DUMP
Database: polymarket_lab
Generated at: 2026-03-14 19:00:56

======================================================================
TABLE: jobs_log
======================================================================
table_comment: Журнал запусков фоновых задач проекта: сбор рынков, анализ, сигналы и другие процессы.
engine: InnoDB
collation: utf8mb4_unicode_ci

COLUMNS:

- id
  - type: bigint(20) unsigned
  - nullable: NO
  - default: NULL
  - key: PRI
  - extra: auto_increment
  - comment: Внутренний технический ID записи журнала. Значения: 1,2,3... Используется как первичный ключ.

- job_name
  - type: varchar(100)
  - nullable: NO
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Имя задачи или джобы. Значения: collect_markets, analyze_markets, run_paper_trading и т.п. Нужно для понимания, какой процесс создал запись.

- status
  - type: varchar(20)
  - nullable: NO
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Статус выполнения задачи. Значения: started, success, error, warning. Нужен для контроля результата запуска.

- message
  - type: text
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Текстовое описание результата или ошибки. Значения: произвольный текст либо NULL. Нужно для диагностики без просмотра docker-логов.

- rows_processed
  - type: int(11)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Количество обработанных сущностей. Значения: целое число >= 0 либо NULL. Нужно для контроля объёма работы джобы.

- started_at
  - type: datetime
  - nullable: YES
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Момент начала выполнения задачи в UTC. Значения: DATETIME либо NULL. Нужен для оценки длительности.

- finished_at
  - type: datetime
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Момент завершения выполнения задачи в UTC. Значения: DATETIME либо NULL. Нужен для расчёта длительности и поиска зависших задач.

- created_at
  - type: datetime
  - nullable: NO
  - default: current_timestamp()
  - key: MUL
  - extra: (none)
  - comment: Момент создания записи лога в нашей БД. Значения: системный timestamp. Техническое поле аудита.

INDEXES:

- idx_jobs_log_created_at
  - unique: no
  - columns: created_at

- idx_jobs_log_job_name
  - unique: no
  - columns: job_name

- idx_jobs_log_started_at
  - unique: no
  - columns: started_at

- idx_jobs_log_status
  - unique: no
  - columns: status

- PRIMARY
  - unique: yes
  - columns: id

======================================================================
TABLE: markets
======================================================================
table_comment: Справочник рынков Polymarket. Одна строка = один рынок как сущность без временной истории.
engine: InnoDB
collation: utf8mb4_unicode_ci

COLUMNS:

- id
  - type: bigint(20) unsigned
  - nullable: NO
  - default: NULL
  - key: PRI
  - extra: auto_increment
  - comment: Внутренний технический ID записи в нашей БД. Значения: 1,2,3... Используется как первичный ключ.

- market_id
  - type: varchar(64)
  - nullable: NO
  - default: NULL
  - key: UNI
  - extra: (none)
  - comment: Внешний ID рынка из Polymarket API. Значения: строковый идентификатор рынка, например 531202. Нужен для однозначного сопоставления нашей записи с рынком в источнике.

- question
  - type: text
  - nullable: NO
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Текст вопроса рынка. Значения: полный текст события, например Will Bitcoin hit 150k by June?. Это основной смысловой текст рынка для отображения и анализа.

- slug
  - type: varchar(255)
  - nullable: YES
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Человекочитаемый slug рынка. Значения: строка вида bitboy-convicted либо NULL. Нужен для удобной отладки, поиска и возможных ссылок.

- end_date
  - type: datetime
  - nullable: YES
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Дата и время завершения или экспирации рынка в UTC. Значения: DATETIME либо NULL, если дата не пришла из API. Нужна для фильтрации по дедлайну и анализа горизонта события.

- active
  - type: tinyint(1)
  - nullable: NO
  - default: 1
  - key: MUL
  - extra: (none)
  - comment: Признак активности рынка. Значения: 1 = рынок активен и торгуется, 0 = неактивен. Нужен для быстрого отбора актуальных рынков.

- closed
  - type: tinyint(1)
  - nullable: NO
  - default: 0
  - key: (none)
  - extra: (none)
  - comment: Признак закрытия рынка. Значения: 1 = рынок закрыт, 0 = рынок ещё открыт. Нужен для понимания текущего состояния рынка.

- archived
  - type: tinyint(1)
  - nullable: NO
  - default: 0
  - key: (none)
  - extra: (none)
  - comment: Признак архивации рынка в нашей системе. Значения: 1 = рынок отправлен в архив, 0 = рабочий рынок. Нужен, чтобы не удалять старые рынки физически, а мягко выводить их из активной обработки.

- category
  - type: varchar(100)
  - nullable: YES
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Категория рынка. Значения: politics, crypto, sports, entertainment и т.п. либо NULL. Нужна для тематической фильтрации и будущих стратегий.

- source_created_at
  - type: datetime
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Дата создания рынка на стороне источника, если начнём её забирать. Значения: DATETIME либо NULL. Нужна для разделения времени жизни рынка в источнике и времени появления записи у нас.

- created_at
  - type: datetime
  - nullable: NO
  - default: current_timestamp()
  - key: (none)
  - extra: (none)
  - comment: Дата и время первого создания строки в нашей БД. Значения: системный timestamp. Нужна для аудита.

- updated_at
  - type: datetime
  - nullable: NO
  - default: current_timestamp()
  - key: (none)
  - extra: on update current_timestamp()
  - comment: Дата и время последнего обновления строки в нашей БД. Значения: системный timestamp. Нужна для контроля свежести синхронизации.

INDEXES:

- idx_markets_active_closed
  - unique: no
  - columns: active, closed

- idx_markets_category
  - unique: no
  - columns: category

- idx_markets_end_date
  - unique: no
  - columns: end_date

- idx_markets_slug
  - unique: no
  - columns: slug

- PRIMARY
  - unique: yes
  - columns: id

- uq_markets_market_id
  - unique: yes
  - columns: market_id

======================================================================
TABLE: market_snapshots
======================================================================
table_comment: История снимков состояния рынков. Одна строка = одно наблюдение рынка в конкретный момент времени.
engine: InnoDB
collation: utf8mb4_unicode_ci

COLUMNS:

- id
  - type: bigint(20) unsigned
  - nullable: NO
  - default: NULL
  - key: PRI
  - extra: auto_increment
  - comment: Внутренний технический ID записи снимка. Значения: 1,2,3... Используется как первичный ключ строки истории.

- market_id
  - type: varchar(64)
  - nullable: NO
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Внешний ID рынка из Polymarket API. Значения: строковый идентификатор рынка, например 531202. Показывает, к какому рынку относится данный снимок.

- data_source
  - type: varchar(20)
  - nullable: NO
  - default: 'gamma'
  - key: (none)
  - extra: (none)
  - comment: Источник данных snapshot-строки. Значения: gamma = данные из Gamma API, clob = данные из CLOB API. Нужен для разделения снимков по источникам.

- yes_price
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Цена исхода YES на момент снимка. Значения: число от 0.0000 до 1.0000 либо NULL. По сути отражает рыночную вероятность YES.

- no_price
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Цена исхода NO на момент снимка. Значения: число от 0.0000 до 1.0000 либо NULL. Нужна для хранения противоположного исхода.

- last_traded_price
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Последняя цена сделки, если она получена из API. Значения: число от 0.0000 до 1.0000 либо NULL. Нужна для анализа фактической последней сделки.

- best_bid
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Лучшая текущая цена покупки. Значения: число от 0.0000 до 1.0000 либо NULL. Показывает, по какой цене рынок сейчас готов купить.

- best_ask
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Лучшая текущая цена продажи. Значения: число от 0.0000 до 1.0000 либо NULL. Показывает, по какой цене рынок сейчас готов продать.

- spread
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Разница между best_ask и best_bid. Значения: положительное число либо NULL. Нужна для оценки ликвидности и торгового трения.

- midpoint
  - type: decimal(10,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Средняя цена между best_bid и best_ask. Значения: число от 0.0000 до 1.0000 либо NULL. Нужна как сглаженная рыночная оценка.

- volume
  - type: decimal(18,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Объём рынка, возвращаемый API. Значения: неотрицательное число либо NULL. Нужен для оценки активности рынка.

- liquidity
  - type: decimal(18,4)
  - nullable: YES
  - default: NULL
  - key: (none)
  - extra: (none)
  - comment: Ликвидность рынка, возвращаемая API. Значения: неотрицательное число либо NULL. Нужна для отбора пригодных рынков.

- fetched_at
  - type: datetime
  - nullable: NO
  - default: NULL
  - key: MUL
  - extra: (none)
  - comment: Момент времени, когда мы получили этот снимок из API, в UTC. Значения: DATETIME. Главное временное поле для построения истории.

- created_at
  - type: datetime
  - nullable: NO
  - default: current_timestamp()
  - key: (none)
  - extra: (none)
  - comment: Момент записи snapshot-строки в нашу БД. Значения: системный timestamp. Нужен для аудита сохранения.

INDEXES:

- idx_snapshots_fetched_at
  - unique: no
  - columns: fetched_at

- idx_snapshots_market_created
  - unique: no
  - columns: market_id, created_at

- idx_snapshots_market_fetched
  - unique: no
  - columns: market_id, fetched_at

- idx_snapshots_market_id
  - unique: no
  - columns: market_id

- idx_snapshots_market_source_fetched
  - unique: no
  - columns: market_id, data_source, fetched_at

- PRIMARY
  - unique: yes
  - columns: id

Context Parts

Здесь показываются части итогового context. Можно переключаться между ними и копировать текущую часть отдельно.
После сборки появится информация по частям.
Загрузка...

Итоговый Project Context

Это полный context целиком: current task, ASCII-дерево, список путей, dump схемы БД, relationships, implemented vs placeholder, summary файлов и содержимое выбранных файлов.
После загрузки дерева можно обновить и скопировать полный context.
Загрузка...