From 75c7a1286d5c3b3d02d38a48a07079bc696a1ab8 Mon Sep 17 00:00:00 2001 From: leemour Date: Sat, 10 Oct 2026 19:19:19 +0200 Subject: [PATCH 1/2] docs: explain functional performance security and UX testing --- content/docs/meta.es.json | 3 +- content/docs/meta.json | 3 +- content/docs/meta.ru.json | 3 +- content/docs/search-architecture.es.mdx | 2 + content/docs/search-architecture.mdx | 2 + content/docs/search-architecture.ru.mdx | 2 + content/docs/testing.es.mdx | 97 +++++++++++++++++++++++++ content/docs/testing.mdx | 97 +++++++++++++++++++++++++ content/docs/testing.ru.mdx | 97 +++++++++++++++++++++++++ docs/README.md | 1 + docs/reviews/2026-10-10-testing.md | 40 ++++++++++ lib/docs-sidebar-tree.tsx | 1 + 12 files changed, 345 insertions(+), 3 deletions(-) create mode 100644 content/docs/testing.es.mdx create mode 100644 content/docs/testing.mdx create mode 100644 content/docs/testing.ru.mdx create mode 100644 docs/reviews/2026-10-10-testing.md diff --git a/content/docs/meta.es.json b/content/docs/meta.es.json index 6cb835f2..b76143a4 100644 --- a/content/docs/meta.es.json +++ b/content/docs/meta.es.json @@ -30,6 +30,7 @@ "max", "---Detalles técnicos---", "architecture", - "search-architecture" + "search-architecture", + "testing" ] } diff --git a/content/docs/meta.json b/content/docs/meta.json index 7934ac8d..ffaa50df 100644 --- a/content/docs/meta.json +++ b/content/docs/meta.json @@ -30,6 +30,7 @@ "max", "---Technical details---", "architecture", - "search-architecture" + "search-architecture", + "testing" ] } diff --git a/content/docs/meta.ru.json b/content/docs/meta.ru.json index f6d8da0c..783f5ca5 100644 --- a/content/docs/meta.ru.json +++ b/content/docs/meta.ru.json @@ -30,6 +30,7 @@ "max", "---Технические подробности---", "architecture", - "search-architecture" + "search-architecture", + "testing" ] } diff --git a/content/docs/search-architecture.es.mdx b/content/docs/search-architecture.es.mdx index 104e44d2..89df3f04 100644 --- a/content/docs/search-architecture.es.mdx +++ b/content/docs/search-architecture.es.mdx @@ -227,3 +227,5 @@ Código del motor en [`cli-messaging`](https://github.com/WireCatLabs/cli-messag La gramática exacta, los campos, los presets y los límites están en la referencia del lenguaje de consulta de [Telegram](./tg/query-language.md) o [MAX](./max/query-language.md). La preparación y las opciones están en las guías del archivo de [Telegram](./tg/archive.md) y [MAX](./max/archive.md). ¿Quieres probarlo? Sigue los ejemplos de búsqueda para **[Telegram](./tg/search.md)** o **[MAX](./max/search.md)**. + +Consulta [pruebas](./testing.mdx) para las comprobaciones funcionales, métricas de clasificación, mediciones de rendimiento y sus límites. diff --git a/content/docs/search-architecture.mdx b/content/docs/search-architecture.mdx index 02987d82..c22dec0d 100644 --- a/content/docs/search-architecture.mdx +++ b/content/docs/search-architecture.mdx @@ -209,6 +209,8 @@ The [interactive playground](./search-playground.mdx) runs the shared query pars The browser opens no account and runs no conversation build, embedding or live AI. Its short summaries are prepared examples shown only when their evidence is retrieved. The interface is translated; the sample messages stay in English. Use it to learn how to inspect a source, then use the messenger guides for a real archive. +See [testing](./testing.mdx) for functional checks, ranking metrics, performance measurements and their limits. + ## Source map Engine source in [`cli-messaging`](https://github.com/WireCatLabs/cli-messaging/tree/v0.211.0), the shared library behind both tg and max. These references describe an inspected implementation snapshot, not the installed version or a performance promise. diff --git a/content/docs/search-architecture.ru.mdx b/content/docs/search-architecture.ru.mdx index 39a2469e..b6ac5e0a 100644 --- a/content/docs/search-architecture.ru.mdx +++ b/content/docs/search-architecture.ru.mdx @@ -227,3 +227,5 @@ max conversations related "Project team" 4521 --json Точная грамматика, поля, preset и пределы — в справке по языку запросов [Telegram](./tg/query-language.md) или [MAX](./max/query-language.md). Подготовка и опции — на страницах архива [Telegram](./tg/archive.md) и [MAX](./max/archive.md). Готовы попробовать? Перейдите к примерам поиска в **[Telegram](./tg/search.md)** или **[MAX](./max/search.md)**. + +В разделе [тестирование](./testing.mdx) описаны функциональные проверки, метрики ранжирования, замеры производительности и их ограничения. diff --git a/content/docs/testing.es.mdx b/content/docs/testing.es.mdx new file mode 100644 index 00000000..01f6ec11 --- /dev/null +++ b/content/docs/testing.es.mdx @@ -0,0 +1,97 @@ +--- +title: Pruebas +description: "Comprobaciones funcionales, evaluaciones de búsqueda, seguridad y recorridos del lector: qué demuestran y cómo repetirlas." +--- + +Al evaluar o modificar `tg` y `max`, usa comprobaciones distintas para corrección, velocidad, seguridad y facilidad de uso. Esta guía explica qué evidencia aporta cada una y dónde reproducirla. Las comprobaciones automáticas cubren casos definidos; superarlas no demuestra que toda búsqueda encuentre una respuesta ni que todas las cuentas y dispositivos se comporten igual. + +## Qué comprobamos + +| Área | Qué verifica una comprobación | Cómo lo comprobamos | +| --- | --- | --- | +| Funcionalidad | Salidas, errores y códigos de terminación esperados; filtros de cuenta, chat, autor y fecha | Pruebas unitarias, integración con almacenes aislados y contratos CLI/MCP | +| Compatibilidad | Los cambios compartidos funcionan en ambas herramientas y entornos compatibles | Pruebas de adopción, Node.js/Bun, plataformas e instalación de paquetes | +| Calidad de búsqueda | Se recuperan fuentes relevantes y se ordenan de forma útil | Preguntas sintéticas con mensajes relevantes etiquetados, consultas negativas y métricas de clasificación | +| Rendimiento | Latencia y consumo de recursos con una carga definida | Consultas cronometradas, escalado del archivo y mediciones separadas de descarga, incorporación y consulta | +| Seguridad | Se respetan límites concretos de permisos, privacidad y entradas; los analizadores detectan candidatos para revisión | Pruebas negativas, análisis de secretos, dependencias y código, e investigación manual | +| Experiencia de usuario (UX) | El lector completa una tarea y entiende el resultado | Recorridos en navegador, teclado y móvil, accesibilidad y revisión editorial | + +La cobertura indica cuánto código ejecutan las pruebas. No mide la relevancia de búsqueda, la utilidad de una guía ni la ausencia de vulnerabilidades. + +## Funcionalidad y paquetes publicados + +Las pruebas de implementación permanecen junto al código. `cli-messaging` comprueba el análisis compartido de consultas, almacenamiento, migraciones, búsqueda y permisos. `tg-cli` y `max-cli` comprueban sus adaptadores y la adopción del comportamiento compartido. Las cuentas sintéticas y los almacenes temporales permiten reproducir regresiones sin mensajes personales. + +Las pruebas de búsqueda separan las coincidencias estrictas de `--discover`, comprueban los filtros obligatorios tanto en el mensaje coincidente como en la respuesta recuperada, la sintaxis explícita y los límites de trabajo. La [arquitectura de búsqueda](./search-architecture.mdx) explica estos contratos. Una respuesta solo es útil si sigue cumpliendo el alcance solicitado. + +[cli-testing](https://github.com/WireCatLabs/cli-testing) contiene comprobaciones reutilizables que acceden desde fuera a ejecutables compilados, servidores MCP o paquetes publicados, además de investigación entre herramientas. Sus pruebas unitarias comprueban el ejecutor; son distintas de ejecutar una batería contra una herramienta. Su [arquitectura](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/ARCHITECTURE.md) y [plan](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/BACKLOG.md) indican los grupos y su estado de implementación. + +La [comprobación de búsqueda publicada](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/released/README.md) instala paquetes elegidos explícitamente, crea un archivo sintético y ejecuta los binarios con acceso a red bloqueado. Comprueba recuperación de respuestas, aislamiento del autor y búsqueda estricta sin cambios; es una comprobación pequeña del contrato, separada de la evaluación de relevancia. + +En una copia de desarrollo de `tg-cli` o `max-cli`, ejecuta: + +```sh +pnpm lint +pnpm typecheck +pnpm test:coverage +pnpm release:check +``` + +`release:check` compila y comprueba el contrato de publicación; no prueba una cuenta en vivo. La verificación de paquetes anterior es una ejecución separada bajo demanda. + +## Calidad de búsqueda y clasificación + +Un **candidato** es un mensaje recuperado para su posible inclusión antes del orden definitivo. La recuperación de candidatos y la clasificación necesitan mediciones distintas: un clasificador no puede promover una respuesta que nunca se recuperó. + +| Métrica | Qué pregunta responde | +| --- | --- | +| Success@k, también Hit@k | ¿Hay al menos un resultado relevante etiquetado entre las primeras *k* posiciones? | +| Recall@k | ¿Qué proporción de todos los resultados relevantes etiquetados aparece en esas posiciones? | +| Precision@k | ¿Qué proporción de esas posiciones contiene resultados relevantes? | +| Mean reciprocal rank (MRR) | ¿En qué posición aparece el primer resultado relevante, promediada entre consultas? | +| nDCG@k | ¿Qué calidad tiene el orden con grados de relevancia y mayor peso en las primeras posiciones? | +| Recuperación de candidatos | ¿Incluye el conjunto de candidatos los resultados relevantes etiquetados antes de ordenarlos? | + +MRR promedia `1 / rank` del primer resultado relevante y usa cero cuando no se encuentra en la salida evaluada. Declara cualquier límite de profundidad. nDCG compara el orden con relevancia graduada con un orden ideal al mismo límite. + +Por ejemplo, **43,8% Success@10** significa que el 43,8% de las consultas evaluadas tiene al menos un resultado relevante etiquetado entre los diez primeros. No dice si se recuperaron todos los resultados relevantes o si la respuesta aparece primero. La décima y la primera posición cuentan por igual como éxito; MRR y nDCG muestran la diferencia. + +Las etiquetas deben distinguir una respuesta real de un mensaje que solo menciona el tema. Incluye preguntas sin respuesta, calificadores desconocidos, formulaciones engañosas y respuestas sin las palabras clave de la pregunta. Las coincidencias parciales son posibles fuentes, no prueba de que exista una respuesta. + +Usa ejemplos de desarrollo para encontrar fallos y un conjunto separado para evaluar cambios. Cuando un ejemplo ha influido en la implementación, pasa a ser evidencia de desarrollo. Registra consultas, etiquetas, límite de candidatos, compilación y reglas de agregación para comparar porcentajes. La [guía de evaluación](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/combined-search-evaluation.md) y el [índice de experimentos](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/README.md) contienen la investigación reproducible. + +## Rendimiento y recursos + +Mide la consulta completa y sus etapas: recuperación, puntuación, ampliación con respuestas y salida. La **puntuación** asigna un valor de relevancia; la **reclasificación** cambia el orden de candidatos ya recuperados. Una puntuación rápida no garantiza por sí sola una orden rápida. + +Informa de la latencia mediana (**p50**) y aquella por debajo de la cual termina el 95% de las ejecuciones medidas (**p95**), junto con tamaño del archivo, número de consultas y candidatos, equipo, entorno, compilación y estado frío o caliente. Registra el máximo de memoria del proceso, no solo el tamaño de los pesos de un modelo. Mide la incorporación de datos por separado. Si se usa un modelo, separa bytes y tiempo de descarga, estado de caché, tiempo de carga y memoria. + +Los [experimentos de búsqueda](https://github.com/WireCatLabs/cli-testing/tree/main/performance/search) comparan enfoques de clasificación y tamaños de archivos. Se ejecutan bajo demanda, fuera del paquete publicado del ejecutor. Las mediciones sintéticas describen esa carga y ese equipo; compara configuraciones en las mismas condiciones antes de elegir un modo predeterminado. + +## Seguridad y privacidad + +Las comprobaciones de seguridad prueban acciones denegadas, entradas incorrectas, aislamiento de cuentas y límites de recursos. El análisis de secretos, dependencias y código produce hallazgos para revisión; un análisis limpio no demuestra ausencia de vulnerabilidades. El [método de seguridad](https://github.com/WireCatLabs/cli-testing/blob/main/docs/security/METHOD.md) define la auditoría y el tratamiento de la evidencia. + +Los ejemplos sin conexión usan datos sintéticos, configuración y almacenamiento aislados. El acceso a red o credenciales debe fallar en una comprobación que promete ejecución sin conexión. Las baterías en vivo y con agentes requieren una configuración privada de pruebas seleccionada explícitamente y autorización; no se ejecutan automáticamente sobre la cuenta del propietario. Los resultados de auditorías operativas y de cuentas privadas permanecen privados. La investigación pública usa datos sintéticos. + +Consulta los controles del usuario y sus límites en [seguridad](./security.mdx) y [permisos](./permissions.mdx). Los permisos de la CLI no restringen acciones de un agente mediante otras herramientas. + +## Experiencia de usuario y documentación + +Las pruebas de navegador siguen recorridos del lector: abrir una guía, navegar, probar la búsqueda, copiar órdenes de instalación y leer Markdown. Las comprobaciones específicas cubren teclado, diseño móvil, idiomas y accesibilidad. El análisis automático de accesibilidad detecta problemas concretos; la lectura y revisión manual evalúan claridad, utilidad y comprensión de resultados incompletos. + +Las comprobaciones de documentación validan enlaces, ejemplos, estructura por idioma, huellas de fuentes y contratos de órdenes revisados. La revisión editorial lee todo el texto modificado en cada idioma. Que las traducciones tengan la misma estructura no demuestra que su significado sea correcto. + +En `cli-docs`, ejecuta estas comprobaciones locales: + +```sh +pnpm lint +pnpm typecheck +pnpm test +pnpm docs:check +pnpm test:browser +``` + +La orden local de navegador ejecuta los recorridos esenciales; CI ejecuta la exportación completa, enlaces, SEO y pruebas de navegador más amplias. Para cambios fuera de esos recorridos, ejecuta directamente la prueba afectada. Otros repositorios publican sus órdenes en la [guía de pruebas de cli-testing](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/TESTING.md) y en su documentación para colaboradores. + +Al comparar resultados, separa fallos funcionales, cambios de relevancia, regresiones de rendimiento y hallazgos pendientes. Elige la siguiente comprobación según el comportamiento modificado y conserva sus entradas y evidencia para que otro colaborador pueda repetirla. diff --git a/content/docs/testing.mdx b/content/docs/testing.mdx new file mode 100644 index 00000000..258b70ad --- /dev/null +++ b/content/docs/testing.mdx @@ -0,0 +1,97 @@ +--- +title: Testing +description: "Functional checks, search benchmarks, security review and reader journeys — what their results prove and how to repeat them." +--- + +When evaluating or changing `tg` and `max`, use different checks for correctness, speed, safety and usability. This guide explains the evidence each check provides and where to reproduce it. Automated checks cover defined cases; passing them does not establish that every search finds an answer or that every account and device behaves identically. + +## What we test + +| Area | What a check verifies | How we check it | +| --- | --- | --- | +| Functionality | Commands return the expected output, errors and exit codes; account, chat, author and date filters hold | Unit tests, isolated store integration tests and CLI/MCP contract tests | +| Compatibility | Shared changes work in both tools and supported runtimes | Consumer adoption tests, Node.js/Bun checks, platform and package installation jobs | +| Search quality | Relevant evidence is retrieved and ordered usefully | Synthetic questions with labelled relevant messages, negative queries and ranking metrics | +| Performance | Latency and resource use under a defined workload | Timed query runs, archive scaling and separate download, ingestion and query measurements | +| Security | Specific permission, privacy and input boundaries hold; scanners identify review candidates | Negative tests, secret/dependency/static scans and manual investigation | +| User experience (UX) | A reader can complete a task and understand the result | Browser journeys, keyboard and mobile checks, accessibility checks and editorial review | + +Coverage reports show how much code tests execute. They do not measure search relevance, the usability of a guide or the absence of vulnerabilities. + +## Functionality and released packages + +Implementation tests stay with their code. `cli-messaging` checks shared parsing, storage, migrations, search and permissions. `tg-cli` and `max-cli` check their adapters and adoption of the shared behavior. Tests use synthetic accounts and temporary stores so a regression can be reproduced without personal messages. + +Search checks distinguish strict matching from explicit `--discover`, test hard filters on both a matching message and a retrieved reply, and check explicit query syntax and bounded work. The [search architecture](./search-architecture.mdx) explains these contracts. A reply containing an answer is useful only if it still satisfies the requested scope. + +[cli-testing](https://github.com/WireCatLabs/cli-testing) owns reusable checks that drive built binaries, MCP servers or published packages from outside, plus cross-tool research. Its own unit tests verify the runner; they are separate from executing a suite against a tool. Suite groups and their implementation status are recorded in its [architecture](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/ARCHITECTURE.md) and [backlog](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/BACKLOG.md). + +The [released search check](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/released/README.md) installs explicitly selected packages, seeds a synthetic archive and runs the actual binaries with network access blocked. It checks reply retrieval, author isolation and unchanged strict search; it is a small contract check, separate from relevance benchmarks. + +In a `tg-cli` or `max-cli` contributor checkout, the focused functional checks are: + +```sh +pnpm lint +pnpm typecheck +pnpm test:coverage +pnpm release:check +``` + +`release:check` builds and checks the release contract; it is not a live account test. The package verification above is a separate on-demand run. + +## Search quality and ranking + +A **candidate** is a message retrieved for possible inclusion before the final ordering. The candidate stage and the ranking stage need separate measurements: a ranker cannot promote an answer that retrieval never found. + +| Metric | Question it answers | +| --- | --- | +| Success@k, also called Hit@k | Does at least one labelled relevant result occur in the first *k* positions? | +| Recall@k | What fraction of all labelled relevant results occurs in those positions? | +| Precision@k | What fraction of those positions contains relevant results? | +| Mean reciprocal rank (MRR) | How early does the first relevant result appear, averaged across queries? | +| nDCG@k | How good is the ordering when relevance has grades, giving higher positions more weight? | +| Candidate recall | Did the retrieved candidate pool include the labelled relevant results before ranking? | + +MRR averages `1 / rank` for the first relevant result, using zero when none is found within the evaluated output. Declare any cutoff. nDCG compares the graded ordering with an ideal ordering at the same cutoff. + +For example, **43.8% Success@10** means that 43.8% of evaluated queries have at least one labelled relevant result in the first ten. It says nothing about retrieving every relevant result or placing the answer first. A result at position ten counts as success just as a result at position one does; MRR and nDCG expose that difference. + +Labels must distinguish an actual answer from a message merely mentioning the topic. Include questions with no answer, unknown qualifiers, misleading wording and replies whose answer omits the question's keywords. Partial hits are evidence candidates, not proof that an answer exists. + +Use development fixtures to find failures, then a separate evaluation set to assess changes. Once a fixture has influenced the implementation, it is development evidence. Record the query set, labels, candidate limit, build and aggregation rules so percentages remain comparable. The [search evaluation guide](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/combined-search-evaluation.md) and [experiment index](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/README.md) contain the reproducible research. + +## Performance and resource use + +Measure the whole query as well as individual stages: retrieval, scoring, reply expansion and output. **Scoring** assigns a relevance value; **reranking** reorders already retrieved candidates. A fast scoring stage alone does not guarantee a fast command. + +Report median latency (**p50**) and the latency below which 95% of measured runs finish (**p95**), with archive size, query count, candidate counts, hardware, runtime, build and cold or warm state. Record peak process memory, rather than only the size of model weights. Measure ingestion separately from querying. If a model is used, report download bytes/time, cache state, loading time and memory as separate costs. + +[Search experiments](https://github.com/WireCatLabs/cli-testing/tree/main/performance/search) compare ranking approaches and archive sizes. They run on demand, outside the published test-runner package. Synthetic timings describe that workload and machine; compare configurations under the same conditions before choosing a default. + +## Security and privacy + +Security checks exercise denied actions, malformed input, account isolation and resource limits. Secret, dependency and static-code scans provide findings for review; a clean scan does not prove vulnerability-free software. The [security method](https://github.com/WireCatLabs/cli-testing/blob/main/docs/security/METHOD.md) defines the audit workflow and evidence handling. + +Offline fixtures use synthetic data and isolated configuration and storage. Network or credential access should fail in a check that promises offline execution. Live and agent suites require an explicitly selected private test setup and authorization; they do not run automatically against the owner's account. Operational audit results and private-account evidence stay private. Public research uses synthetic data. + +For user-facing controls and their boundaries, read [security](./security.mdx) and [permissions](./permissions.mdx). A CLI permission check does not constrain actions an agent performs through other tools. + +## User experience and documentation + +Browser tests exercise reader paths: opening a guide, navigating, trying the query playground, copying installation commands and reading Markdown output. Targeted checks cover keyboard interaction, mobile layout, localization and accessibility. Automated accessibility checks catch specific issues; manual reading and task review assess clarity, useful guidance and understandable incomplete results. + +Documentation checks validate links, examples, locale structure, source fingerprints and reviewed command contracts. Editorial review reads the changed prose in every language. Matching translations structurally does not prove that their meaning is correct. + +In `cli-docs`, use these local checks: + +```sh +pnpm lint +pnpm typecheck +pnpm test +pnpm docs:check +pnpm test:browser +``` + +The local browser command runs the smoke suite; CI runs the full export, links, SEO and broader browser suite. Run an affected browser test directly for changes outside the smoke paths. Other repositories publish their own commands in [cli-testing's testing guide](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/TESTING.md) and their contributor documentation. + +When comparing results, keep functional failures, relevance changes, performance regressions and unresolved review findings separate. Choose the next check from the behavior being changed, then preserve its inputs and evidence so another contributor can repeat it. diff --git a/content/docs/testing.ru.mdx b/content/docs/testing.ru.mdx new file mode 100644 index 00000000..29bcfe77 --- /dev/null +++ b/content/docs/testing.ru.mdx @@ -0,0 +1,97 @@ +--- +title: Тестирование +description: "Проверки функций, качества поиска, безопасности и удобства — что доказывают результаты и как их повторить." +--- + +При оценке или изменении `tg` и `max` нужны отдельные проверки корректности, скорости, безопасности и удобства. Здесь объясняется, какие выводы позволяет сделать каждая проверка и где её повторить. Автоматические проверки охватывают заданные случаи; их успех не означает, что любой поиск найдёт ответ или что все аккаунты и устройства ведут себя одинаково. + +## Что мы проверяем + +| Область | Что подтверждает проверка | Как проверяем | +| --- | --- | --- | +| Функциональность | Ожидаемые результаты команд, ошибки и коды завершения; соблюдение фильтров аккаунта, чата, автора и даты | Модульные тесты, интеграционные тесты изолированного хранилища и проверки контрактов CLI/MCP | +| Совместимость | Общие изменения работают в обоих инструментах и поддерживаемых средах | Тесты подключения общей библиотеки, проверки Node.js/Bun, платформ и установки пакетов | +| Качество поиска | Нужные источники найдены и расположены в полезном порядке | Синтетические вопросы с размеченными релевантными сообщениями, отрицательные запросы и метрики ранжирования | +| Производительность | Задержка и расход ресурсов при заданной нагрузке | Замеры запросов, масштабирование архива и отдельные измерения загрузки, наполнения и поиска | +| Безопасность | Соблюдение конкретных границ разрешений, приватности и входных данных; выявление проблем для разбора | Отрицательные тесты, поиск секретов, анализ зависимостей и кода, ручное исследование | +| Удобство (UX) | Читатель может выполнить задачу и понять результат | Сценарии в браузере, клавиатура и мобильный экран, доступность и редакторская проверка | + +Отчёт о покрытии показывает, какую часть кода выполняют тесты. Он не измеряет релевантность поиска, понятность руководства или отсутствие уязвимостей. + +## Функциональность и опубликованные пакеты + +Тесты реализации остаются рядом с кодом. `cli-messaging` проверяет общие разбор запросов, хранение, миграции, поиск и разрешения. `tg-cli` и `max-cli` проверяют свои адаптеры и использование общей библиотеки. Синтетические аккаунты и временные хранилища позволяют воспроизвести сбой без личных сообщений. + +Проверки поиска разделяют строгий поиск и явный `--discover`, проверяют обязательные фильтры и для найденного сообщения, и для добавленного ответа, явный синтаксис и ограничения объёма работы. Эти контракты описаны в [архитектуре поиска](./search-architecture.mdx). Ответ полезен лишь тогда, когда он также соответствует заданной области поиска. + +[cli-testing](https://github.com/WireCatLabs/cli-testing) содержит переиспользуемые проверки собранных исполняемых файлов, MCP-серверов и опубликованных пакетов через внешние интерфейсы, а также исследования для нескольких инструментов. Его собственные модульные тесты проверяют механизм запуска; это отдельная работа от запуска набора проверок для инструмента. Группы проверок и состояние их реализации указаны в [архитектуре](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/ARCHITECTURE.md) и [плане](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/BACKLOG.md). + +[Проверка опубликованного поиска](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/released/README.md) устанавливает явно выбранные пакеты, создаёт синтетический архив и запускает настоящие исполняемые файлы с заблокированной сетью. Она проверяет получение ответа, изоляцию автора и неизменность строгого поиска; это небольшая проверка контракта, отдельная от оценки релевантности. + +В рабочей копии `tg-cli` или `max-cli` для разработки запускайте: + +```sh +pnpm lint +pnpm typecheck +pnpm test:coverage +pnpm release:check +``` + +`release:check` собирает пакет и проверяет контракт выпуска; это не проверка живого аккаунта. Описанная выше проверка опубликованного пакета запускается отдельно по запросу. + +## Качество поиска и ранжирование + +**Кандидат** — сообщение, полученное для возможного включения в результат до окончательной сортировки. Получение кандидатов и ранжирование нужно измерять отдельно: сортировка не поднимет ответ, который вообще не был найден. + +| Метрика | На какой вопрос отвечает | +| --- | --- | +| Success@k, также Hit@k | Есть ли хотя бы один размеченный релевантный результат на первых *k* позициях? | +| Recall@k | Какая доля всех размеченных релевантных результатов попала на эти позиции? | +| Precision@k | Какая доля этих позиций содержит релевантные результаты? | +| Mean reciprocal rank (MRR) | Насколько рано появляется первый релевантный результат в среднем по запросам? | +| nDCG@k | Насколько хорош порядок при разных степенях релевантности и большем весе верхних позиций? | +| Полнота кандидатов | Содержит ли набор кандидатов размеченные релевантные результаты до сортировки? | + +MRR усредняет `1 / rank` для первого релевантного результата, используя ноль, если в оцениваемой выдаче его нет. Указывайте ограничение глубины оценки. nDCG сравнивает порядок с оценками релевантности с идеальным порядком на той же глубине. + +Например, **43,8% Success@10** означает, что у 43,8% проверенных запросов хотя бы один размеченный релевантный результат попал в первую десятку. Это не говорит о нахождении всех нужных сообщений или о первом месте ответа. Десятая и первая позиции одинаково считаются успехом; MRR и nDCG показывают разницу. + +Разметка должна отличать настоящий ответ от простого упоминания темы. Добавляйте вопросы без ответа, неизвестные уточнения, вводящие в заблуждение формулировки и ответы без ключевых слов вопроса. Частичные совпадения — кандидаты в источники, а не доказательство существования ответа. + +Используйте примеры разработки для поиска ошибок, а отдельный набор оценки — для сравнения изменений. Когда пример повлиял на реализацию, он становится свидетельством разработки. Сохраняйте запросы, разметку, лимит кандидатов, сборку и правила усреднения. Воспроизводимые исследования находятся в [руководстве по оценке](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/combined-search-evaluation.md) и [каталоге экспериментов](https://github.com/WireCatLabs/cli-testing/blob/main/performance/search/README.md). + +## Производительность и ресурсы + +Измеряйте весь запрос и отдельные этапы: получение кандидатов, оценку, добавление ответов и вывод. **Оценка** присваивает значение релевантности; **повторное ранжирование** меняет порядок уже полученных кандидатов. Быстрый этап оценки сам по себе не гарантирует быструю команду. + +Указывайте медианную задержку (**p50**) и задержку, в которую укладываются 95% измеренных запусков (**p95**), вместе с размером архива, числом запросов и кандидатов, оборудованием, средой, сборкой и холодным или прогретым состоянием. Измеряйте пиковую память процесса, а не только размер весов модели. Наполнение архива измеряйте отдельно от запросов. Если используется модель, отдельно сообщайте объём и время загрузки, состояние кеша, время запуска и память. + +[Эксперименты поиска](https://github.com/WireCatLabs/cli-testing/tree/main/performance/search) сравнивают подходы к ранжированию и размеры архивов. Они запускаются по запросу вне опубликованного пакета механизма тестирования. Синтетические замеры характеризуют эту нагрузку и компьютер; сравнивайте варианты в одинаковых условиях перед выбором режима по умолчанию. + +## Безопасность и приватность + +Проверки безопасности охватывают запрещённые действия, некорректный ввод, изоляцию аккаунтов и ограничения ресурсов. Поиск секретов, анализ зависимостей и статический анализ дают находки для разбора; отсутствие находок не доказывает отсутствие уязвимостей. [Методика безопасности](https://github.com/WireCatLabs/cli-testing/blob/main/docs/security/METHOD.md) описывает аудит и работу с доказательствами. + +Локальные тестовые примеры используют синтетические данные, отдельные настройки и хранилища. Доступ к сети или учётным данным должен завершаться ошибкой в проверке, обещающей автономное выполнение. Проверки живого аккаунта и агента требуют явно выбранной приватной тестовой среды и разрешения; они не запускаются автоматически для аккаунта владельца. Результаты рабочих аудитов и данные приватных аккаунтов остаются приватными. Публичные исследования используют синтетические данные. + +О доступных пользователю ограничениях читайте в разделах [безопасность](./security.mdx) и [разрешения](./permissions.mdx). Разрешения CLI не ограничивают действия агента через другие инструменты. + +## Удобство и документация + +Браузерные тесты проходят путь читателя: открытие руководства, навигация, примеры поиска, копирование команд установки и чтение Markdown. Целевые проверки охватывают клавиатуру, мобильную вёрстку, языки и доступность. Автоматический анализ доступности находит определённые проблемы; чтение и ручная проверка задачи оценивают ясность, полезность и понятность неполных результатов. + +Проверки документации проверяют ссылки, примеры, структуру языковых версий, отпечатки источников и рассмотренные контракты команд. Редакторская проверка читает изменённый текст на каждом языке. Совпадение структуры переводов не доказывает совпадение смысла. + +В `cli-docs` запускайте локально: + +```sh +pnpm lint +pnpm typecheck +pnpm test +pnpm docs:check +pnpm test:browser +``` + +Локальная браузерная команда выполняет короткий набор основных сценариев; CI проверяет полный экспорт, ссылки, SEO и более широкий набор браузерных сценариев. Для изменений вне короткого набора запускайте затронутый браузерный тест отдельно. Команды других репозиториев описаны в [руководстве cli-testing](https://github.com/WireCatLabs/cli-testing/blob/main/docs/dev/TESTING.md) и их документации для разработчиков. + +При сравнении результатов разделяйте функциональные ошибки, изменения релевантности, замедления и нерешённые замечания проверки. Выбирайте следующую проверку по изменяемому поведению и сохраняйте входные данные и доказательства, чтобы другой разработчик мог её повторить. diff --git a/docs/README.md b/docs/README.md index dcda50f6..281321a6 100644 --- a/docs/README.md +++ b/docs/README.md @@ -43,6 +43,7 @@ These pages and shared interface/Markdown behavior belong to this repository. | What can read or change my data? | `security.mdx` | Explanation | Lead with user decisions, then verified detail | | Can I try search without connecting? | `search-playground.mdx` | Interactive explanation | Keep sample behavior and limitations accurate | | How do the tools work internally? | `architecture.mdx` | Technical explanation | Trial beautiful-mermaid on one existing diagram | +| What do tests prove and how can I repeat them? | `testing.mdx` | Technical explanation | Keep evidence and reproduction paths aligned with cli-testing and owning repositories | | How do search and conversation processing work? | `search-architecture.mdx` | Technical explanation | Reconcile playground description; keep source/release boundary | | How do I check questions and activity in my group? | `group-admins.md` | Task guide | Start with a request and sources; inspect coverage before changes | | How do I save or override settings? | `configuration.mdx` | Configuration guide | Explain when settings matter and how to verify the effective value | diff --git a/docs/reviews/2026-10-10-testing.md b/docs/reviews/2026-10-10-testing.md new file mode 100644 index 00000000..730aa10e --- /dev/null +++ b/docs/reviews/2026-10-10-testing.md @@ -0,0 +1,40 @@ +# Testing explanation review + +Reader: a contributor or technical reader assessing evidence for tg/max changes. The page explains +which check to reproduce and what a passing result establishes. New Technical details entry, +decorative laboratory icon and inbound search-architecture links are present in EN/RU/ES. + +| Page and locale | Reader task | Terms and opening | Behavior evidence | Links and exports | Result and owner | +| --- | --- | --- | --- | --- | --- | +| testing, en | Understand and repeat functional, quality, performance, security and UX checks | Full prose read; candidate, scoring, reranking, percentiles and metrics defined; opening sets scope | Sources below; automated checks distinguished from on-demand/live and manual review | Local commands checked against owning package scripts; locale-equivalent fences | Reviewed by Codex | +| testing, ru | Same task | Full prose read; same contracts and limitations | Same sources; no new capability claims | Same links and executable examples | Reviewed by Codex | +| testing, es | Same task | Full prose read; rank described as a position rather than elapsed time | Same sources; no new capability claims | Same links and executable examples | Reviewed by Codex | +| search-architecture, en/ru/es | Find the explanation of test evidence | Existing opening and ending read; contextual inbound link added | Existing search facts preserved | Existing URLs and anchors preserved | Reviewed by Codex | + +## Evidence + +- cli-testing at `e72718968c8343ac107ad21df4af22ae331c1631`: CLAUDE.md, + docs/dev/ARCHITECTURE.md, TESTING.md, BACKLOG.md and docs/security/METHOD.md define suite boundaries, + private results, on-demand execution and implementation status. Its unit tests verify the runner. +- The same commit's performance/search/ contains the evaluation guide, historical benchmarks, + model resources, fresh development validation and the standalone released-package verifier. + That verifier was executed against fresh tg 0.44.0 and max 0.43.0 installs with install scripts + disabled, isolated synthetic stores and network preloading. Both actual binaries retrieved the + eligible reply and its parent, excluded the other author, and kept strict search empty. +- Reviewed tg v0.44.0 and max v0.43.0 package scripts provide lint, typecheck, test:coverage and + release:check. Their adoption tests and shared cli-messaging v0.216.0 implementation tests supply + filter, strict/discovery and bounds evidence. The small binary fixture does not establish + ranking quality, platform coverage or live-provider behavior. +- cli-docs at `06211560b22049bace355e125a19dbc2d3296473`: package.json, + playwright.smoke.config.ts, playwright.config.ts, .github/workflows/ci.yml and deploy.yml, + tests/site-quality.spec.ts, tests/doc-hints.spec.ts and docs/DEVELOPMENT.md establish local smoke, + full CI, accessibility, Markdown and editorial checks. + +Success@10's 43.8% is explicitly a hypothetical interpretation, not a new measurement. Recall, +Precision, MRR and nDCG are distinguished; relevance labels and cutoffs must be declared. Fixtures +that influenced implementation are development evidence. Coverage and scanner success are not +quality or vulnerability guarantees. No term changes or new release capabilities are introduced. + +Local lint, typecheck, 257 unit tests, localization, refreshed release contracts and strict docs +checks pass: 915 reference entries, zero gaps and zero invalid examples. Browser reader review and +full export/link/SEO/browser CI are required before merging. diff --git a/lib/docs-sidebar-tree.tsx b/lib/docs-sidebar-tree.tsx index 9dcb4d31..e3ffe08a 100644 --- a/lib/docs-sidebar-tree.tsx +++ b/lib/docs-sidebar-tree.tsx @@ -72,6 +72,7 @@ export const sidebarIcons = { prompting: MessageSquare, "drafts-and-templates": PenLine, architecture: Network, + testing: FlaskConical, "search-architecture": Layers, "search-playground": FlaskConical, "bot-api": Webhook, From 50cd6fe7a8ca99d0c8ef329658ceccc779252c58 Mon Sep 17 00:00:00 2001 From: leemour Date: Sat, 10 Oct 2026 19:22:39 +0200 Subject: [PATCH 2/2] docs(testing): distinguish available metrics from emitted reports --- content/docs/testing.es.mdx | 2 ++ content/docs/testing.mdx | 2 ++ content/docs/testing.ru.mdx | 2 ++ 3 files changed, 6 insertions(+) diff --git a/content/docs/testing.es.mdx b/content/docs/testing.es.mdx index 01f6ec11..09be2145 100644 --- a/content/docs/testing.es.mdx +++ b/content/docs/testing.es.mdx @@ -52,6 +52,8 @@ Un **candidato** es un mensaje recuperado para su posible inclusión antes del o | nDCG@k | ¿Qué calidad tiene el orden con grados de relevancia y mayor peso en las primeras posiciones? | | Recuperación de candidatos | ¿Incluye el conjunto de candidatos los resultados relevantes etiquetados antes de ordenarlos? | +Cada informe debe indicar qué métricas calcula realmente. La tabla define medidas disponibles; no implica que cada ejecutor informe de todas ellas. + MRR promedia `1 / rank` del primer resultado relevante y usa cero cuando no se encuentra en la salida evaluada. Declara cualquier límite de profundidad. nDCG compara el orden con relevancia graduada con un orden ideal al mismo límite. Por ejemplo, **43,8% Success@10** significa que el 43,8% de las consultas evaluadas tiene al menos un resultado relevante etiquetado entre los diez primeros. No dice si se recuperaron todos los resultados relevantes o si la respuesta aparece primero. La décima y la primera posición cuentan por igual como éxito; MRR y nDCG muestran la diferencia. diff --git a/content/docs/testing.mdx b/content/docs/testing.mdx index 258b70ad..79a92051 100644 --- a/content/docs/testing.mdx +++ b/content/docs/testing.mdx @@ -52,6 +52,8 @@ A **candidate** is a message retrieved for possible inclusion before the final o | nDCG@k | How good is the ordering when relevance has grades, giving higher positions more weight? | | Candidate recall | Did the retrieved candidate pool include the labelled relevant results before ranking? | +Each report must name the metrics it actually computes. This table defines available measures; it does not imply that every runner reports all of them. + MRR averages `1 / rank` for the first relevant result, using zero when none is found within the evaluated output. Declare any cutoff. nDCG compares the graded ordering with an ideal ordering at the same cutoff. For example, **43.8% Success@10** means that 43.8% of evaluated queries have at least one labelled relevant result in the first ten. It says nothing about retrieving every relevant result or placing the answer first. A result at position ten counts as success just as a result at position one does; MRR and nDCG expose that difference. diff --git a/content/docs/testing.ru.mdx b/content/docs/testing.ru.mdx index 29bcfe77..dc40b76d 100644 --- a/content/docs/testing.ru.mdx +++ b/content/docs/testing.ru.mdx @@ -52,6 +52,8 @@ pnpm release:check | nDCG@k | Насколько хорош порядок при разных степенях релевантности и большем весе верхних позиций? | | Полнота кандидатов | Содержит ли набор кандидатов размеченные релевантные результаты до сортировки? | +Каждый отчёт должен указывать, какие метрики он действительно вычисляет. Таблица объясняет доступные меры, но не означает, что каждый механизм проверки сообщает их все. + MRR усредняет `1 / rank` для первого релевантного результата, используя ноль, если в оцениваемой выдаче его нет. Указывайте ограничение глубины оценки. nDCG сравнивает порядок с оценками релевантности с идеальным порядком на той же глубине. Например, **43,8% Success@10** означает, что у 43,8% проверенных запросов хотя бы один размеченный релевантный результат попал в первую десятку. Это не говорит о нахождении всех нужных сообщений или о первом месте ответа. Десятая и первая позиции одинаково считаются успехом; MRR и nDCG показывают разницу.