diff --git a/content/blog/a-cli-from-one-config/cover.jpg b/content/blog/a-cli-from-one-config/cover.jpg new file mode 100644 index 00000000..30afcbbe Binary files /dev/null and b/content/blog/a-cli-from-one-config/cover.jpg differ diff --git a/content/blog/a-cli-from-one-config/index.es.md b/content/blog/a-cli-from-one-config/index.es.md new file mode 100644 index 00000000..dc70f84c --- /dev/null +++ b/content/blog/a-cli-from-one-config/index.es.md @@ -0,0 +1,137 @@ +--- +title: Un CLI para tu propio servicio a partir de un solo config +description: En una semana enseñé a la plantilla de WireCat a montar un CLI entero a partir de un solo archivo, wirecat.config.ts. Así salieron attio, linear y wordpress en 3 días, con sync a una copia local, servidor MCP y tests. Cuento cuánto código se escribió a mano, qué se rompió con un WordPress de verdad y si encaja con tu CRM. +date: 2026-11-21 +tags: [cli, ai-agents, mcp] +cover: ./cover.jpg +coverAlt: "Una tarjeta pequeña sobre una mesa oscura, de la que salen hilos violetas luminosos hacia una consola grande y terminada con interruptores, cajoncitos de fichero y un candado pequeño en uno de los interruptores" +author: viacheslav-ptsarev +glance: + - value: "0 líneas" + label: "de hooks en linear y wordpress, toda la fuente está en el config" + href: "#3-cli-en-3-días" + - value: "42 líneas" + label: "a mano en attio después de new, hubspot sin config tiene 2340, pero también hace mucho más" + href: "#3-cli-en-3-días" + - value: "1 h 55 min" + label: "de las 2 h 54 min de linear se fueron en arreglar los paquetes comunes, no el config" + href: "#el-tiempo-no-se-fue-en-el-config" +draft: false +--- + +He hecho que un CLI nuevo de WireCat se monte a partir de un solo archivo. Escribes `wirecat.config.ts` - qué servicio es, dónde está la descripción de su API, cómo comprobar un token y qué campos de sus respuestas son personas, empresas y tratos. Luego un solo comando, `new --from-config`, crea un CLI con sync a una copia local, servidor MCP y tests para su categoría. De momento hay 3 categorías: CRM, gestor de tareas y contenido (posts en un sitio), y la descripción de la API puede ser OpenAPI, un esquema GraphQL o el índice `wp-json` de un sitio WordPress. + +Lo escribo sobre todo para quien tiene en su empresa un CRM o un helpdesk propio y quiere que su agente trabaje con él igual que con el correo y los chats en WireCat. Digo ya dónde está el límite: un CRM desde config de momento solo lee, y un helpdesk que solo tiene una API REST todavía no encaja en ninguna categoría (más detalles al final). + +Con el config ya hay 3 CLI de verdad - attio, linear y wordpress. Los montaron agentes a partir de la plantilla, y yo respondía a sus preguntas, decidía qué arreglar y leía las revisiones. Así que los tiempos de las tablas son tiempo de los agentes, no mío. + +Antes de esto la plantilla ([cli-template](https://github.com/WireCatLabs/cli-template)) ya tenía `new --spec-url`: le das la dirección de una descripción de API y obtienes un comando por operación. Con la descripción de PokeAPI salen 102 comandos, una respuesta real y un servidor MCP que funciona en 16 segundos, sin contar lo que tarda npx en descargar la propia plantilla. Pero son solo llamadas en vivo a la API. Para que un agente busque rápido en un CRM hace falta una copia local, un sync solo de los cambios y las personas enlazadas con el resto de fuentes de WireCat. Antes todo eso se escribía a mano en cada CLI. + +Ahora todo eso se describe en el config. Un ejemplo para un CRM inventado: + +```ts +import { defineCli } from "@wirecat/cli-core/manifest" + +export default defineCli({ + identity: { command: "acme", package: "@acme/acme-cli", prefix: "ACME", service: "Acme CRM", owner: "acme" }, + spec: { kind: "openapi", from: "https://crm.acme.example/openapi.json" }, + auth: { preset: "token", verify: { operation: "getMe", id: "workspace.id", name: "workspace.name" } }, + category: "crm", + source: { + provider: "acme", + kinds: ["person"], + entities: { + person: { + list: { operation: "listContacts", query: { limit: 100 } }, + changes: { operation: "listContacts", query: { limit: 100, updated_since: "{since}" }, since: "iso" }, + get: { operation: "getContact", path: { id: "{id}" } }, + map: { externalId: "id", name: "full_name", emails: { each: "emails", value: "address" } }, + }, + }, + }, +}) +``` + +```sh +npx @wirecat/cli-template new --from-config wirecat.config.ts +cd acme-cli && pnpm install && pnpm generate +node dist/bin/acme.js work session start # toma el token y lo comprueba con la operación de auth.verify +node dist/bin/acme.js work sync # copia los registros, después solo lo que cambió +``` + +`work` aquí es el nombre de un perfil, lo eliges tú, y el CLI nunca toma una cuenta por defecto. Sin `changes` el sync también funciona, solo que relee la lista entera cada vez. `pnpm source:check` comprueba que cada operación y cada ruta de `map` existen de verdad en la API generada, así que una errata en `full_name` aparece antes del primer sync. La paginación, los cursores y la base de datos local donde va la copia vienen de cli-core, el paquete común de todas las herramientas de WireCat. Lo que no se puede describir en el config (por ejemplo, que el servicio guarda los valores antiguos de un campo junto al actual) va en `src/hooks.ts`. + +Además recibes tests desde el principio. Cada operación de la API se envía a un fake, un servidor de mentira dentro del test, construido a partir de la descripción de la API. Es estricto, así que rechaza cualquier petición que la descripción no permita. Y la fuente pasa por los contratos de su categoría, un conjunto común de tests que comprueba igual a todos los CRM de WireCat. Hay casos como "la lista se cortó después de la primera página, la siguiente ejecución sigue desde esa página, nada perdido ni repetido". + +## 3 CLI en 3 días + +El propio `--from-config` salió el 17 de noviembre y al principio solo sabía hacer CRM. Justo después los agentes empezaron a montar CLI de verdad con él, cada uno encontraba huecos, y se arreglaban en la plantilla y no en el CLI. En 4 días la plantilla pasó de un solo CRM a 3 categorías, y para el 21 de noviembre (versión 0.33.0) WordPress se monta a partir del índice completo del sitio. + +Los 3 CLI tienen `wirecat.config.ts` en su primer commit: + +| | [attio-cli](https://github.com/WireCatLabs/attio-cli) | [linear-cli](https://github.com/WireCatLabs/linear-cli) | [wordpress-cli](https://github.com/WireCatLabs/wordpress-cli) | +| --- | --- | --- | --- | +| Qué es | CRM, OpenAPI | gestor de tareas, GraphQL | contenido, `wp-json` | +| Plantilla | 0.28.0 | 0.31.0 | 0.32.0 | +| Líneas de config | 64 | 102 | 117 | +| Líneas de hooks | 23 | 0 | 0 | +| Código a mano después de `new`, hooks incluidos | 42 | 7 | 81 | +| Generado | 107 operaciones | 493 operaciones | 147 operaciones | +| De `new` a `cli-dev ready` en verde, sin la comprobación en vivo | unas 2 h 40 min | 2 h 54 min | unos 40 min | +| Primera versión | 18 nov | 19 nov | 19 nov | + +`cli-dev ready` es un comando que pasa todas las comprobaciones antes de una versión (lint, tests, contratos, documentación, etc.) y dice de cada una si pasó o no. La comprobación en vivo es ejecutar el CLI contra una cuenta de prueba real del servicio, y no está en la tabla. + +Todas las cifras son del primer montaje de cada CLI, de las mediciones en cli-testing ([attio](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/source-manifest/README.md), [linear](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/linear-from-config/README.md), [wordpress](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/wordpress-from-config/README.md)). Los configs han crecido desde entonces. Para su primera versión attio ganó los tratos, el config pasó a 126 líneas y el hook bajó a 8. + +Para comparar, [hubspot-cli](https://github.com/WireCatLabs/hubspot-cli) también sale de la plantilla, pero de antes del config, y tiene 2340 líneas a mano, sobre todo el mapeo de las respuestas de HubSpot a registros de CRM. De aquí no sale un porcentaje de ahorro, porque hubspot sincroniza mucho más (tratos, leads, actividades, etc.), y el primer montaje de attio solo sincronizaba personas, empresas y miembros del workspace. Se ve el orden de la diferencia, una cifra exacta no hay. + +En wordpress-cli las 81 líneas a mano no tienen nada que ver con el mapeo. 10 líneas son textos que ven el usuario y Desktop, y 71 vinieron de las revisiones, casi todas sobre claves de permisos. + +## Qué se rompió con un WordPress de verdad + +La plantilla tenía su propio caso de prueba de WordPress con 19 rutas, y un WordPress 6.9.4 real sin plugins tiene 127 en su índice. + +Con el índice completo `pnpm generate` se paró enseguida. `GET /wp/v2/block-types/{namespace}` recibió el mismo nombre de comando que leer un solo tipo de bloque, y borrar todas las contraseñas de aplicación de un usuario el mismo que borrar una. Ahora son `block-types-list-namespace` y `users-application-passwords-delete-all`. + +La ruta `wp_pattern_category` rompió todavía más. El generador escribe una clave de permiso para cada operación, y todas las claves están en los mismos ajustes del CLI. La comprobación de ajustes no conocía una clave con guion bajo, y por eso no falló un test sino todos los de `api`, 151. Ahora el CI de la plantilla monta WordPress a partir de todo el índice de 6.9.4, no de un recorte, para que esto se detecte enseguida. + +Después un agente hizo una comprobación en vivo con WordPress en Docker y 3 usuarios de prueba: un Contributor, un Author y un Editor. Los fakes aceptan cualquier llamada que permita la descripción de la API, pero un sitio real rechaza según el rol. Un Author y un Contributor no pueden leer etiquetas con `context=edit`, aunque el nombre y el slug de una etiqueta son públicos, así que el config ahora las lee sin él. Además WordPress responde a estos 2 roles con HTTP 400 (con un 403 dentro) a la lista de páginas, y ese rechazo tumbaba el sync de todos los posts, y cada ejecución siguiente fallaba en la misma llamada. Ahora la lista de páginas necesita el permiso `edit_pages`, sin él la llamada simplemente no se envía, y el sync dice al final qué faltó. + +Y una revisión hecha por un agente nuevo encontró un agujero cuando todas las comprobaciones ya pasaban. El grupo `api` ofrecía un comando para crear una contraseña de aplicación, y WordPress devuelve la contraseña nueva en texto plano, mientras que su índice no marca ese campo como secreto de ninguna forma. O sea, un agente podía crear una contraseña y recibirla en el chat. En wordpress-cli se cerró a mano antes del primer push, y el 21 de noviembre cli-base empezó a marcar ese campo como secreto en cualquier CLI de WordPress, así que esas llamadas ya no están en `api`. + +La misma revisión vio que denegar `posts create` no paraba exactamente la misma llamada por `api posts-create`, y que las escrituras que cambian todo el sitio (plugins, ajustes, usuarios) se ejecutaban sin preguntar. Ahora el CLI pregunta antes por defecto. + +## El tiempo no se fue en el config + +El config en sí casi no llevó tiempo. Un agente escribió attio en 1 h 20 min, luego fallaron 17 tests, y los 17 eran bugs de los paquetes comunes, ninguno de attio. Arreglarlos con revisiones llevó unas 1 h 20 min más, y 2 versiones. + +En linear, unas 1 h 55 min de las 2 h 54 min se fueron en los paquetes comunes. `cli-dev ready` no conocía la categoría de gestor de tareas, cli-core no tenía un fake para pasar el contrato de tareas sobre una fuente sacada de un config (son unas 930 líneas), y el test GraphQL de `api` se quedaba sin memoria. En Linear los filtros se anidan unos dentro de otros (`IssueFilter` llega a `TeamFilter` y vuelve), y el test que intentaba rellenar cada campo opcional construía filtro dentro de filtro hasta que el worker no pudo más. Ahora las 493 operaciones de Linear pasan en unos 20 segundos. + +Antes de una versión, el CI exige que cada comando del CLI y cada uno de sus flags tenga al menos un test, si no `release:check` no deja pasar la versión. Después de la revisión a linear-cli aún le faltaba test a 562 de esos flags y comandos, por ejemplo `--body-file` y `--all` del grupo `api`, o los comandos de tareas. Esos tests pasaron a la plantilla, pero cubrían el gestor de tareas y no WordPress, así que a wordpress-cli le pasó lo mismo con 501. Esos también pasaron a la plantilla el mismo día. + +El tercer CLI salió varias veces más rápido que los dos primeros: unos 40 minutos hasta un `cli-dev ready` en verde, frente a 2 h 40 min de attio y 2 h 54 min de linear. El commit de la versión de wordpress, con 2 revisiones y la comprobación en vivo, llegó 1 h 20 min después de `new`. + +## Lo que estas cifras no muestran + +- Linear con un workspace real en la propia medición: ahí el config se comprobó contra el esquema y un fake construido a partir de él, la comprobación en vivo pasó después, antes de la primera versión. +- Un sitio WordPress real con plugins, caché o una capa de seguridad que oculta rutas. Todas las comprobaciones en vivo fueron con 6.9.4 en Docker. +- Los tratos de attio con datos reales. El workspace de prueba no tiene ninguno, así que el mapeo de tratos se comprobó solo contra el fake. +- Mi tiempo. No me cronometré, solo sé que respondí a los agentes 3 preguntas sobre attio, 1 sobre linear y ninguna sobre wordpress. +- Una comparación exacta entre los CLI. Las cifras de attio salen de un contador de líneas distinto al de linear y wordpress, y el alcance es distinto en cada uno, así que la tabla de arriba muestra la escala aproximada. + +## Si tienes tu propio CRM o helpdesk + +Qué hace falta para que funcione: + +- Una descripción de la API - OpenAPI 3 o Swagger 2.0, en JSON o YAML, y para un gestor de tareas un esquema GraphQL (`new` lo obtiene por introspección). Si la descripción está mal en algunos sitios, el parche con su motivo va en `scripts/spec-model.ts`. Si una lista no tiene la paginación descrita, el test de contrato falla a propósito hasta que la describas. +- Acceso con token y una operación que lea con ese token quién eres (`auth.verify`), porque la copia local se guarda bajo esa cuenta. Si distintos usuarios de tu servicio ven registros distintos, yo guardaría una copia aparte para cada usuario en vez de una por workspace. En linear una revisión pilló justo esto: el sync de un miembro podía marcar como borradas las tareas privadas de otro. +- Una cuenta de prueba. El montaje y todas las comprobaciones antes de la de en vivo corren contra el fake, pero para la comprobación en vivo y el uso real `session start` comprueba el token en el servicio de verdad. + +De momento no encaja con todo. A 21 de noviembre un CRM desde config solo lee (sync, listas, búsqueda en la copia), y los comandos de escritura al CRM se escriben a mano. `new` se niega a hacer un gestor de tareas sobre OpenAPI, porque el fake de tareas de cli-core por ahora solo responde a GraphQL. O sea, un helpdesk con solo una API REST ahora no encaja en ninguna categoría de config, y le queda `new --spec-url` con llamadas en vivo, o escribir la fuente uno mismo. OAuth tampoco sale todavía del config, se conecta con el módulo `oauth` de cli-core. Y todo esto es solo Node y TypeScript. + +Antes de conectar un agente yo revisaría los permisos de escritura. En una terminal cada escritura con nivel `ask` te pregunta, pero por MCP no hay nadie para responder, así que simplemente se ejecuta. Por eso `mcp add` no conecta un perfil que puede escribir hasta que añades `--allow-writes`, y cada escritura queda después en `runs list`. Si el perfil que le das al agente no debe borrar nada en tu CRM, pon `config set permissions.api readonly`, o `deny` en operaciones concretas. Este párrafo ahora se escribe solo en el README de cada CLI nuevo con grupo `api`. + +Si el CLI no va a formar parte de WireCat, en `package` va tu propio scope y en `owner` tu nombre, y cómo preparar el repositorio y publicar en npm está en [Publishing outside WireCat](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#publishing-outside-wirecat). Todos los campos de `wirecat.config.ts` están en la [referencia del kit](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#new-name), y cómo montar tu propia herramienta con la plantilla y un agente y conectarla a WireCat está [en la documentación](/es/docs/build-create-cli). + +El siguiente en el plan es Ghost, el segundo CLI de contenido después de WordPress. Para empezar con tu CRM, toma el ejemplo de arriba, pon la dirección de tu descripción, tus operaciones y tus rutas en `map`, y ejecuta `npx @wirecat/cli-template new --from-config wirecat.config.ts`. diff --git a/content/blog/a-cli-from-one-config/index.md b/content/blog/a-cli-from-one-config/index.md new file mode 100644 index 00000000..bb0bb362 --- /dev/null +++ b/content/blog/a-cli-from-one-config/index.md @@ -0,0 +1,137 @@ +--- +title: A CLI for your own service from one config file +description: In a week I taught the WireCat template to build a whole CLI from one file, wirecat.config.ts. That's how attio, linear and wordpress came out in 3 days, with a sync into a local copy, an MCP server and tests. Here's how much code was hand-written, what broke on a real WordPress, and whether it fits your CRM. +date: 2026-11-21 +tags: [cli, ai-agents, mcp] +cover: ./cover.jpg +coverAlt: "A small card on a dark table, with glowing violet threads running from it to a big finished console with toggle switches, little filing drawers and a small padlock on one switch" +author: viacheslav-ptsarev +glance: + - value: "0 lines" + label: "of hooks in linear and wordpress, the whole source is in the config" + href: "#3-clis-in-3-days" + - value: "42 lines" + label: "hand-written in attio after new, while hubspot, built without a config, has 2,340 but also does much more" + href: "#3-clis-in-3-days" + - value: "1 h 55 min" + label: "of the 2 h 54 min linear build went into fixing the shared packages, not the config" + href: "#where-the-time-went-not-the-config" +draft: false +--- + +I made it possible to build a new WireCat CLI from one file. You write `wirecat.config.ts` - what the service is, where its API description lives, how to check a token, and which fields in its responses are people, companies and deals. Then one command, `new --from-config`, makes a CLI with a sync into a local copy, an MCP server and tests for its category. There are 3 categories so far: CRM, issue tracker and content (posts on a site), and the API description can be OpenAPI, a GraphQL schema or the `wp-json` index of a WordPress site. + +I'm writing this mostly for people whose company has its own CRM or helpdesk and who want their agent to work with it the way it works with mail and chats in WireCat. Let me say up front where the limit is: a CRM from a config only reads for now, and a helpdesk that has only a REST API doesn't fit any category yet (more on that at the end). + +3 real CLIs are already built on the config - attio, linear and wordpress. Agents built them from the template, and I answered their questions, decided what to fix and read the reviews. So the times in the tables below are agent time, not mine. + +Before this the template ([cli-template](https://github.com/WireCatLabs/cli-template)) already had `new --spec-url`: you give it the address of an API description and get one command per operation. From PokeAPI's description that's 102 commands, a real response and a working MCP server in 16 seconds, not counting the time npx takes to download the template itself. But that's only live API calls. For an agent to search a CRM fast you need a local copy, a sync of only the changes, and people linked to the rest of WireCat's sources. Before, all of that was written by hand in every CLI. + +Now it's all described in the config. Here's an example for a made-up CRM: + +```ts +import { defineCli } from "@wirecat/cli-core/manifest" + +export default defineCli({ + identity: { command: "acme", package: "@acme/acme-cli", prefix: "ACME", service: "Acme CRM", owner: "acme" }, + spec: { kind: "openapi", from: "https://crm.acme.example/openapi.json" }, + auth: { preset: "token", verify: { operation: "getMe", id: "workspace.id", name: "workspace.name" } }, + category: "crm", + source: { + provider: "acme", + kinds: ["person"], + entities: { + person: { + list: { operation: "listContacts", query: { limit: 100 } }, + changes: { operation: "listContacts", query: { limit: 100, updated_since: "{since}" }, since: "iso" }, + get: { operation: "getContact", path: { id: "{id}" } }, + map: { externalId: "id", name: "full_name", emails: { each: "emails", value: "address" } }, + }, + }, + }, +}) +``` + +```sh +npx @wirecat/cli-template new --from-config wirecat.config.ts +cd acme-cli && pnpm install && pnpm generate +node dist/bin/acme.js work session start # takes the token and checks it with the auth.verify operation +node dist/bin/acme.js work sync # copies the records in, then only what changed +``` + +`work` here is a profile name, you pick it yourself, and the CLI never takes an account by default. Without `changes` the sync still works, it just reads the whole list every time. `pnpm source:check` checks that every operation and every path in `map` really exists in the generated API, so a typo in `full_name` shows up before the first sync. Paging, cursors and the local database the copy goes into come from cli-core, the shared package of all WireCat tools. What the config can't describe (say, the service keeps old values of a field next to the current one) goes into `src/hooks.ts`. + +Plus you get tests right away. Every API operation is sent to a fake - a pretend server inside the test, built from the API description. It's strict, so it refuses any request the description doesn't allow. And the source runs through the category's contracts, a shared set of tests that checks every CRM in WireCat the same way. There are cases like "the list broke off after its first page, the next run goes on from that page, nothing lost or repeated". + +## 3 CLIs in 3 days + +`--from-config` itself came out on Nov 17 and at first could only do CRM. Right after that agents started building real CLIs on it, each one found gaps, and those were fixed in the template rather than in the CLI. In 4 days the template went from one CRM to 3 categories, and by Nov 21 (version 0.33.0) WordPress builds from the site's full index. + +All 3 CLIs have `wirecat.config.ts` in their very first commit: + +| | [attio-cli](https://github.com/WireCatLabs/attio-cli) | [linear-cli](https://github.com/WireCatLabs/linear-cli) | [wordpress-cli](https://github.com/WireCatLabs/wordpress-cli) | +| --- | --- | --- | --- | +| What it is | CRM, OpenAPI | tracker, GraphQL | content, `wp-json` | +| Template | 0.28.0 | 0.31.0 | 0.32.0 | +| Config lines | 64 | 102 | 117 | +| Hook lines | 23 | 0 | 0 | +| Hand-written code after `new`, hooks included | 42 | 7 | 81 | +| Generated | 107 operations | 493 operations | 147 operations | +| From `new` to a green `cli-dev ready`, without the live check | about 2 h 40 min | 2 h 54 min | about 40 min | +| First release | Nov 18 | Nov 19 | Nov 19 | + +`cli-dev ready` is a command that runs every check before a release (lint, tests, contracts, docs and so on) and says for each one whether it passed. The live check is a run of the CLI against a real test account of the service, and it isn't in the table. + +All numbers are from each CLI's first build, from the measurements in cli-testing ([attio](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/source-manifest/README.md), [linear](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/linear-from-config/README.md), [wordpress](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/wordpress-from-config/README.md)). The configs have grown since. By its first release attio got deals, the config became 126 lines and the hook shrank to 8. + +For comparison, [hubspot-cli](https://github.com/WireCatLabs/hubspot-cli) is also made from the template, but before the config, and it has 2,340 hand-written lines, mostly mapping HubSpot's responses to CRM records. You can't get a percentage saving out of this, because hubspot syncs a lot more (deals, leads, activities and so on), and attio's first build synced only people, companies and workspace members. You can see the order of magnitude, there's no exact number. + +In wordpress-cli the 81 lines aren't about mapping at all. 10 lines are text the user and Desktop see, and 71 came from the reviews, almost all of them about permission keys. + +## What broke on a real WordPress + +The template had its own WordPress test case with 19 routes, and a real WordPress 6.9.4 without plugins has 127 in its index. + +On the full index `pnpm generate` stopped right away. `GET /wp/v2/block-types/{namespace}` got the same command name as reading one block type, and deleting all of a user's application passwords the same as deleting one. Now they're `block-types-list-namespace` and `users-application-passwords-delete-all`. + +The route `wp_pattern_category` broke even more. The generator writes a permission key for every operation, and all the keys live in the CLI's one settings file. The settings check didn't know a key with an underscore, and because of that it wasn't one test that failed but every `api` test, 151 of them. Now the template's CI builds WordPress from the full 6.9.4 index, not from a trimmed sample, so this gets caught right away. + +Then an agent ran a live check on WordPress in Docker with 3 test users: a Contributor, an Author and an Editor. The fakes accept any call the API description allows, but a real site refuses by role. An Author and a Contributor can't read tags with `context=edit`, even though a tag's name and slug are public, so the config now reads them without it. WordPress also returns HTTP 400 (with a 403 inside) to these 2 roles on the pages list, and that refusal broke the sync of all posts, and every run after that failed on the same call. Now the pages list needs the `edit_pages` right, without it the call simply isn't sent, and the sync says at the end what was missing. + +And a review by a fresh agent found a hole after all the checks were already passing. The `api` group offered a command that creates an application password, and WordPress returns the new password in plain text, while its index doesn't mark that field as secret in any way. So an agent could make a password and get it into the chat. In wordpress-cli this was closed by hand before the first push, and on Nov 21 cli-base started marking that field secret for every WordPress CLI, so those calls are gone from `api`. + +The same review found that a deny on `posts create` didn't stop the very same call through `api posts-create`, and that writes that change the whole site (plugins, settings, users) ran without asking. Now the CLI asks first by default. + +## Where the time went (not the config) + +The config itself took almost no time. An agent wrote attio in 1 h 20 min, then 17 tests failed, and all 17 were bugs in the shared packages, none of them in attio. Fixing them with reviews took about 1 h 20 min more, plus 2 releases. + +In linear, about 1 h 55 min of the 2 h 54 min went into the shared packages. `cli-dev ready` didn't know the tracker category, cli-core had no fake to run the tracker contract on a source from a config (that's about 930 lines), and the GraphQL `api` test ran out of memory. Linear's filters nest inside each other (`IssueFilter` reaches `TeamFilter` and back), and the test that tried to fill every optional field built filter inside filter until the worker gave up. Now all 493 Linear operations pass in about 20 seconds. + +Before a release, CI wants every command of the CLI and every one of its flags to have at least one test, otherwise `release:check` won't let the version through. After the review linear-cli still had 562 such flags and commands without a test, for example `--body-file` and `--all` in the `api` group, or the tracker commands. Those tests moved into the template, but they covered the tracker and not WordPress, so wordpress-cli hit the same thing with 501 of them. They moved into the template the same day too. + +The third CLI came together several times faster than the first two: about 40 minutes to a green `cli-dev ready`, against 2 h 40 min for attio and 2 h 54 min for linear. The release commit for wordpress, with 2 reviews and the live check, came 1 h 20 min after `new`. + +## What these numbers don't show + +- Linear on a real workspace in the measurement itself: there the config was checked against the schema and a fake built from it, the live check passed later, before the first release. +- A real WordPress site with plugins, caching or a security layer that hides routes. All live checks ran on 6.9.4 in Docker. +- Attio deals on real data. The test workspace has none, so the deal mapping was checked against the fake only. +- Human time. I didn't time myself, all I know is that I answered the agents 3 questions for attio, 1 for linear and none for wordpress. +- An exact comparison between the CLIs. Attio's numbers come from a different line counter than linear's and wordpress's, and the scope differs for each, so the table above shows the rough scale. + +## If you have your own CRM or helpdesk + +What you need to get it running: + +- An API description - OpenAPI 3 or Swagger 2.0, in JSON or YAML, and for a tracker a GraphQL schema (`new` gets it by introspection). If the description is wrong in places, a patch with its reason goes into `scripts/spec-model.ts`. If a list has no paging described, the contract test fails on purpose until you describe it. +- A token sign-in and an operation that reads who you are with that token (`auth.verify`), because the local copy is kept under that account. If different users of your service see different records, I'd keep a separate copy for each user instead of one per workspace. In linear a review caught exactly this: one member's sync could mark someone else's private issues as deleted. +- A test account. The build and every check before the live one run against the fake, but for the live check and for real work `session start` checks the token against the real service. + +It doesn't fit everyone yet. As of Nov 21 a CRM built from a config is read-only (sync, lists, search in the copy), and write commands to the CRM are hand-written. `new` refuses a tracker over OpenAPI, because cli-core's tracker fake only answers GraphQL for now. So a helpdesk with only a REST API doesn't fit any config category right now, and what's left for it is `new --spec-url` with live calls, or writing the source yourself. OAuth can't come from the config yet either, you wire it up with cli-core's `oauth` module. And all of this is Node and TypeScript only. + +Before connecting an agent I'd check the write permissions. In a terminal every write at the `ask` level asks you, but over MCP there's nobody to answer, so it just runs. That's why `mcp add` won't connect a profile that can write until you add `--allow-writes`, and every write then shows up in `runs list`. If the profile you give the agent must not delete anything in your CRM, set `config set permissions.api readonly`, or `deny` for specific operations. This paragraph is now written into the README of every new CLI with an `api` group. + +If the CLI won't be part of WireCat, `package` gets your own scope and `owner` your name, and how to set up the repository and publishing to npm is in [Publishing outside WireCat](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#publishing-outside-wirecat). Every field of `wirecat.config.ts` is in the [kit reference](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#new-name), and how to build your own tool with the template and an agent and connect it to WireCat is [in the docs](/en/docs/build-create-cli). + +Ghost is next on the plan, the second content CLI after WordPress. To start with your own CRM, take the example above, put in your description's address, your operations and your paths in `map`, and run `npx @wirecat/cli-template new --from-config wirecat.config.ts`. diff --git a/content/blog/a-cli-from-one-config/index.ru.md b/content/blog/a-cli-from-one-config/index.ru.md new file mode 100644 index 00000000..07aa1d0f --- /dev/null +++ b/content/blog/a-cli-from-one-config/index.ru.md @@ -0,0 +1,137 @@ +--- +title: CLI для своего сервиса из одного конфига +description: За неделю я научил шаблон WireCat собирать целый CLI из одного файла wirecat.config.ts. Так за 3 дня вышли attio, linear и wordpress, с синком в локальную копию, MCP-сервером и тестами. Рассказываю, сколько там кода руками, что сломалось на настоящем WordPress и подойдет ли это вашей CRM. +date: 2026-11-21 +tags: [cli, ai-agents, mcp] +cover: ./cover.jpg +coverAlt: "Маленькая карточка на темном столе, от нее тянутся светящиеся фиолетовые нити к большому собранному пульту с тумблерами, ящичками картотеки и маленьким замком на одном переключателе" +author: viacheslav-ptsarev +glance: + - value: "0 строк" + label: "хуков у linear и wordpress, весь источник описан в конфиге" + href: "#3-cli-за-3-дня" + - value: "42 строки" + label: "руками у attio после new, у hubspot без конфига 2 340, но он и умеет намного больше" + href: "#3-cli-за-3-дня" + - value: "1 ч 55 мин" + label: "из 2 ч 54 мин сборки linear ушли на починку общих пакетов, а не на конфиг" + href: "#время-ушло-не-на-конфиг" +draft: false +--- + +Я сделал так, что новый CLI в WireCat собирается из одного файла. Вы пишете `wirecat.config.ts` - что это за сервис, где лежит описание его API, как проверить токен и какие поля в ответах это люди, компании и сделки. Дальше одна команда `new --from-config` делает CLI с синком в локальную копию, MCP-сервером и тестами под категорию. Категорий пока 3: CRM, трекер задач и контент (посты на сайте), а описанием API может быть OpenAPI, GraphQL-схема или индекс `wp-json` сайта на WordPress. + +Пишу это в первую очередь для тех, у кого в компании своя CRM или хелпдеск, и хочется, чтобы агент работал с ней так же, как с почтой и чатами в WireCat. Сразу скажу, где граница: CRM из конфига пока только читает, а хелпдеск, у которого есть только REST API, не ложится ни в одну категорию (подробнее в конце). + +На конфиге уже собраны 3 настоящих CLI - attio, linear и wordpress. Собирали их агенты по шаблону, а я отвечал на их вопросы, решал, что чинить, и читал ревью. Так что время в таблицах ниже - это время работы агентов, а не мое. + +До этого у шаблона ([cli-template](https://github.com/WireCatLabs/cli-template)) уже была команда `new --spec-url`: даете адрес описания API, получаете по команде на каждую операцию. Из описания PokeAPI так выходит 102 команды, настоящий ответ и рабочий MCP-сервер за 16 секунд, не считая того, что npx сначала скачивает сам шаблон. Но это только живые вызовы API. Чтобы агент быстро искал по CRM, нужна локальная копия, синк только изменений, связь людей с остальными источниками WireCat. Раньше все это писалось руками в каждом CLI. + +Теперь все это описывается в конфиге, вот пример для выдуманной CRM: + +```ts +import { defineCli } from "@wirecat/cli-core/manifest" + +export default defineCli({ + identity: { command: "acme", package: "@acme/acme-cli", prefix: "ACME", service: "Acme CRM", owner: "acme" }, + spec: { kind: "openapi", from: "https://crm.acme.example/openapi.json" }, + auth: { preset: "token", verify: { operation: "getMe", id: "workspace.id", name: "workspace.name" } }, + category: "crm", + source: { + provider: "acme", + kinds: ["person"], + entities: { + person: { + list: { operation: "listContacts", query: { limit: 100 } }, + changes: { operation: "listContacts", query: { limit: 100, updated_since: "{since}" }, since: "iso" }, + get: { operation: "getContact", path: { id: "{id}" } }, + map: { externalId: "id", name: "full_name", emails: { each: "emails", value: "address" } }, + }, + }, + }, +}) +``` + +```sh +npx @wirecat/cli-template new --from-config wirecat.config.ts +cd acme-cli && pnpm install && pnpm generate +node dist/bin/acme.js work session start # берет токен и проверяет его операцией из auth.verify +node dist/bin/acme.js work sync # копирует записи, дальше только то, что поменялось +``` + +`work` тут - имя профиля, его вы выбираете сами, CLI никогда не берет аккаунт по умолчанию. Без `changes` синк тоже заработает, просто каждый раз будет перечитывать весь список. `pnpm source:check` проверяет, что каждая операция и каждый путь из `map` реально есть в сгенерированном API, так что опечатка в `full_name` всплывет еще до первого синка. Пейджинг, курсоры и локальная база, куда ложится копия, берутся из cli-core, общего пакета всех инструментов WireCat. То, что в конфиге не описать (например, сервис хранит старые значения поля рядом с текущим), пишется в `src/hooks.ts`. + +Плюс вы сразу получаете тесты. Каждая операция API отправляется в фейк - поддельный сервер внутри теста, собранный из описания API. Он строгий и отказывает в любом запросе, которого описание не разрешает. А источник прогоняется через контракты категории, это общий набор тестов, которым одинаково проверяется любая CRM в WireCat. Там есть кейсы вроде "список оборвался после первой страницы, в новом запуске синк продолжает с нее, ничего не потеряно и не повторено". + +## 3 CLI за 3 дня + +Сам `--from-config` появился 17.11 и сначала умел только CRM. Дальше агенты сразу собирали на нем настоящие CLI, каждый находил дыры, и их чинили в шаблоне, а не в самом CLI. За 4 дня шаблон прошел путь от одной CRM до 3 категорий, и к 21.11 (версия 0.33.0) WordPress собирается из полного индекса сайта. + +У всех 3 CLI `wirecat.config.ts` лежит в первом же коммите: + +| | [attio-cli](https://github.com/WireCatLabs/attio-cli) | [linear-cli](https://github.com/WireCatLabs/linear-cli) | [wordpress-cli](https://github.com/WireCatLabs/wordpress-cli) | +| --- | --- | --- | --- | +| Что это | CRM, OpenAPI | трекер, GraphQL | контент, `wp-json` | +| Шаблон | 0.28.0 | 0.31.0 | 0.32.0 | +| Строк в конфиге | 64 | 102 | 117 | +| Строк в хуках | 23 | 0 | 0 | +| Кода руками после `new`, с хуками | 42 | 7 | 81 | +| Сгенерировано | 107 операций | 493 операции | 147 операций | +| От `new` до зеленого `cli-dev ready`, без живой проверки | около 2 ч 40 мин | 2 ч 54 мин | около 40 мин | +| Первый релиз | 18.11 | 19.11 | 19.11 | + +`cli-dev ready` - команда, которая прогоняет все проверки перед релизом (линт, тесты, контракты, доки итд) и по каждой говорит, прошла она или нет. Живая проверка - это прогон CLI на настоящем тестовом аккаунте сервиса, ее в таблице нет. + +Все цифры с первой сборки каждого CLI, из замеров в cli-testing ([attio](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/source-manifest/README.md), [linear](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/linear-from-config/README.md), [wordpress](https://github.com/WireCatLabs/cli-testing/blob/main/performance/generation/wordpress-from-config/README.md)). Конфиги с тех пор выросли. У attio к первому релизу добавились сделки, конфиг стал 126 строк, а хук сжался до 8. + +Для сравнения, [hubspot-cli](https://github.com/WireCatLabs/hubspot-cli) тоже сделан из шаблона, но до конфига, и там 2 340 строк руками, в основном маппинг ответов HubSpot в записи CRM. Процент экономии из этого не посчитать, потому что hubspot синкает куда больше (сделки, лиды, активности итд), а attio на первой сборке только людей, компании и участников воркспейса. Порядок разницы видно, точной цифры нет. + +У wordpress-cli 81 строка руками вообще не про маппинг. 10 строк - тексты, которые видит пользователь и Desktop, а 71 пришла из ревью, почти вся про ключи разрешений. + +## Что сломалось на настоящем WordPress + +В шаблоне был свой тестовый WordPress-кейс на 19 маршрутах, а настоящий WordPress 6.9.4 без плагинов отдает в индексе 127. + +На полном индексе `pnpm generate` сразу встал. `GET /wp/v2/block-types/{namespace}` получил то же имя команды, что чтение одного типа блока, а удаление всех паролей приложений пользователя то же, что удаление одного. Теперь это `block-types-list-namespace` и `users-application-passwords-delete-all`. + +Маршрут `wp_pattern_category` сломал еще больше. Для каждой операции генератор пишет ключ разрешения, и все ключи лежат в одних настройках CLI. Ключ с подчеркиванием проверка настроек не знала, и из-за этого упал не один тест, а все тесты `api`, их 151. Сейчас шаблон в своем CI собирает WordPress из всего индекса 6.9.4, а не из нарезки, чтобы такое ловилось сразу. + +Дальше агент прогнал живую проверку на WordPress в Docker с 3 тестовыми пользователями: Contributor, Author и Editor. Фейки принимают любой вызов, который разрешает описание API, а настоящий сайт отказывает по ролям. Author и Contributor не могут читать теги с `context=edit`, хотя имя и слаг тега публичные, так что конфиг теперь читает их без него. Еще этим 2 ролям WordPress отвечает HTTP 400 (а внутри 403) на список страниц, и этот отказ ронял синк вообще всех постов, причем каждый следующий запуск падал на том же вызове. Сейчас для списка страниц нужно право `edit_pages`, без него вызов просто не отправляется, а синк в конце пишет, чего не хватило. + +А ревью свежим агентом нашло дыру уже после того, как все проверки стали проходить. Группа `api` предлагала команду создания пароля приложения, а WordPress отдает новый пароль в ответе открытым текстом, и в индексе это поле никак не помечено как секрет. Т.е. агент мог сделать пароль и получить его в чат. В wordpress-cli это закрыли руками еще до первого пуша, а 21.11 cli-base стал помечать это поле секретом для любого WordPress CLI, и такие вызовы из `api` пропали совсем. + +Там же выяснилось, что запрет на `posts create` не останавливал тот же самый вызов через `api posts-create`, и что записи, которые меняют весь сайт (плагины, настройки, пользователи), выполнялись без вопроса. Теперь перед ними CLI по умолчанию спрашивает вас. + +## Время ушло не на конфиг + +На сам конфиг время почти не уходило. attio агент написал за 1 ч 20 мин, после чего 17 тестов упали, и все 17 были багами общих пакетов, а не attio. Еще около 1 ч 20 мин ушло на их фиксы с ревью, плюс 2 релиза. + +У linear из 2 ч 54 мин около 1 ч 55 мин ушли на общие пакеты. `cli-dev ready` не знал категорию трекера, в cli-core не было фейка, чтобы прогнать контракт трекера на источнике из конфига (это около 930 строк), а GraphQL-тест `api` падал по памяти. У Linear фильтры вложены друг в друга (`IssueFilter` доходит до `TeamFilter` и обратно), и тест, который пытался заполнить каждое необязательное поле, строил фильтр в фильтре, пока воркеру не стало плохо. Теперь все 493 операции Linear проходят где-то за 20 секунд. + +Перед релизом CI требует, чтобы у каждой команды CLI и у каждого ее флага был хотя бы один тест, иначе `release:check` не пропустит версию. После ревью у linear-cli 562 таких флага и команды оставались без теста, например `--body-file` и `--all` у группы `api` или команды трекера. Эти тесты переехали в шаблон, но они покрывали трекер, а не WordPress, так что у wordpress-cli повторилось то же самое, там таких было 501. Их тоже перенесли в шаблон в тот же день. + +Третий CLI собрался в разы быстрее первых двух: около 40 минут до зеленого `cli-dev ready` против 2 ч 40 мин у attio и 2 ч 54 мин у linear. До релизного коммита, с 2 ревью и живой проверкой, у wordpress ушло 1 ч 20 мин. + +## Чего эти цифры не показывают + +- Linear на настоящем воркспейсе в самом замере: там конфиг проверен по схеме и фейку из нее, живая проверка прошла уже потом, перед первым релизом. +- Настоящий WordPress-сайт с плагинами, кэшем или защитой, которая прячет маршруты. Все живые проверки шли на 6.9.4 в Docker. +- Сделки attio на реальных данных. В тестовом воркспейсе их нет, маппинг сделок проверен только на фейке. +- Мое время. Его я не засекал, известно только, что я ответил агентам на 3 вопроса по attio, на 1 по linear и ни на один по wordpress. +- Точное сравнение между CLI. Цифры attio сняты другим счетчиком строк, чем у linear и wordpress, и объем у всех разный, так что таблица выше показывает примерный масштаб. + +## Если у вас своя CRM или хелпдеск + +Что нужно, чтобы это завелось: + +- Описание API - OpenAPI 3 или Swagger 2.0, в JSON или YAML, для трекера GraphQL-схема (ее `new` берет интроспекцией). Если описание местами кривое, патч с причиной идет в `scripts/spec-model.ts`. Если для списка не описан пейджинг, контрактный тест специально упадет, пока вы его не опишете. +- Вход по токену и операция, которая этим токеном читает, кто вы (`auth.verify`), потому что локальная копия хранится под этим аккаунтом. Если в вашем сервисе разные пользователи видят разные записи, я бы хранил копию отдельно для каждого пользователя, а не одну на воркспейс. В linear ревью поймало ровно это: синк одного участника мог пометить удаленными чужие приватные задачи. +- Тестовый аккаунт. Сборка и все проверки до живой проходят на фейке, но для живой проверки и реальной работы `session start` проверяет токен на настоящем сервисе. + +Подойдет это пока не всем. CRM из конфига на 21.11 только читает (синк, списки, поиск по копии), а команды записи в CRM пишутся руками. Трекер поверх OpenAPI `new` отказывается делать, потому что фейк трекера в cli-core пока отвечает только на GraphQL. Т.е. хелпдеск с одним REST API сейчас не ложится ни в одну категорию из конфига, для него остается `new --spec-url` с живыми вызовами или источник руками. OAuth из конфига тоже пока не делается, его придется подключать через модуль `oauth` из cli-core. И все это только Node и TypeScript. + +До того как подключать агента, я бы проверил разрешения на запись. В терминале каждая запись с уровнем `ask` спрашивает вас, а по MCP отвечать некому, так что она просто выполняется. `mcp add` поэтому не подключит профиль, который может писать, пока вы не добавите `--allow-writes`, а каждая запись потом сохраняется в `runs list`. Если профиль, который вы отдаете агенту, не должен ничего удалять в вашей CRM, поставьте `config set permissions.api readonly` или `deny` на конкретные операции. Этот абзац теперь сам пишется в README каждого нового CLI с группой `api`. + +Если CLI не будет частью WireCat, в `package` идет ваш scope, в `owner` ваше имя, а как настроить репозиторий и публикацию в npm, описано в разделе [Publishing outside WireCat](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#publishing-outside-wirecat). Все поля `wirecat.config.ts` есть в [справке по kit](https://github.com/WireCatLabs/cli-template/blob/main/kit/README.md#new-name), а как собрать свой инструмент с шаблоном и агентом и подключить его к WireCat, рассказано [в доках](/ru/docs/build-create-cli). + +Следующим по плану Ghost, второй CLI для контента после WordPress. Начать со своей CRM можно прямо с примера выше: поменяйте адрес описания, операции и пути в `map` на свои и запустите `npx @wirecat/cli-template new --from-config wirecat.config.ts`. diff --git a/content/blog/one-line-that-broke-sqlite-locks/cover.jpg b/content/blog/one-line-that-broke-sqlite-locks/cover.jpg new file mode 100644 index 00000000..1c96ae49 Binary files /dev/null and b/content/blog/one-line-that-broke-sqlite-locks/cover.jpg differ diff --git a/content/blog/one-line-that-broke-sqlite-locks/index.es.md b/content/blog/one-line-that-broke-sqlite-locks/index.es.md new file mode 100644 index 00000000..93e84c73 --- /dev/null +++ b/content/blog/one-line-that-broke-sqlite-locks/index.es.md @@ -0,0 +1,142 @@ +--- +title: Una línea quitó todos los bloqueos de SQLite y rompió una base de 6 GB +description: Modo WAL, busy_timeout, sin caídas ni errores de disco, y aun así "database disk image is malformed". La causa fue un writeFileSync antes de cada apertura. Cómo lo encontré con /proc/locks, lo reproduje en un archivo vacío y por qué la recuperación decía que no se había perdido nada. +date: 2026-11-09 +tags: [cli] +cover: ./cover.jpg +coverAlt: "Un candado de latón abierto con el cuerpo de vidrio ahumado, dentro unas láminas de vidrio agrietadas y desplazadas, un alfiler de costura que apenas roza su lado, junto a un frasco vacío y otro que se deshace en polvo" +author: viacheslav-ptsarev +draft: false +--- + +Pues se me rompió la base de datos. El almacén común de WireCat es un archivo SQLite en el que escriben a la vez varios CLI (Telegram, correo, memo, etc.), y el mío pesa 6 GB. Modo WAL, `busy_timeout` de 5 segundos, la misma versión de SQLite en todos los CLI, ni caídas ni errores de disco en el journal, y aun así en algún momento la sincronización del correo falló con "database disk image is malformed", y detrás cayó todo lo demás. + +Lo rompió una línea que solo tenía que asegurarse de que el archivo existe: + +```js +writeFileSync(file, "", { flag: "a", mode: 0o600 }) +``` + +Se ejecutaba antes de cada apertura del almacén para escritura. Añadir cero bytes al final de un archivo suena de lo más inofensivo, pero en Linux bastó para quitar todos los bloqueos de SQLite a un proceso que ya tenía el almacén abierto. Lo encontré con `/proc/locks` y esa misma noche lo reproduje en un archivo vacío. Y después la recuperación dijo 2 veces de 3 que no se había perdido nada, cuando sí se había perdido. + +## Cómo se notó + +La primera sincronización del correo falló hacia las 17:10 UTC, y desde ese momento el temporizador de memo falló en cada ejecución, más de 60 veces hasta la noche. La búsqueda de mensajes fallaba en cada consulta. Nadie se enteró, porque un temporizador que falla escribe una línea en stderr, y solo se ve en la siguiente ejecución a mano. Mientras tanto `memo doctor` decía que el almacén estaba bien, no comprobaba ni `quick_check` ni los índices de búsqueda. + +Lo encontró un agente que por la noche revisaba la búsqueda y vio `fts5: corruption`. Pasé `quick_check` sobre una copia y salieron 687 líneas de problemas en unas 36 tablas, no solo en índices sino también en las tablas de origen. Había páginas a las que apuntan dos tablas a la vez, índices con un número de entradas equivocado, páginas que nadie usa. No parece un sector dañado, más bien dos procesos escribiendo el archivo sin verse el uno al otro. + +Paré los temporizadores y fui a ver quién tenía el archivo abierto. Los más sospechosos eran dos procesos `wa serve` de larga duración (el servidor del CLI de WhatsApp) que llevaban en marcha desde la madrugada. Esto es lo que tenían en `/proc/locks` (los números de proceso e inode aquí son inventados): + +```text +POSIX ADVISORY READ 4101 103:05:7777 128 128 +POSIX ADVISORY READ 4102 103:05:7777 128 128 +``` + +Es un bloqueo sobre un byte del archivo `-shm`, con el que SQLite sabe que un proceso sigue vivo (el dead-man lock). Y sobre el archivo de la base en sí no tenían ningún bloqueo. Una conexión normal en modo WAL tiene durante toda su vida un bloqueo compartido sobre una zona de servicio del archivo de la base, bytes alrededor de 1073741826, muy lejos de los datos, y así los demás procesos ven que alguien está usando la base. Lo comprobé luego en un archivo limpio. Estos 2 procesos no tenían ese bloqueo. + +Y en `/proc//fd` de los dos aparecía `wirecat.db-wal (deleted)` y `wirecat.db-shm (deleted)`. O sea, el WAL ya se había borrado del disco, y estos procesos seguían escribiendo en él, la última vez hacia las 21:20, 4 horas después del primer error. Además cada uno tenía el almacén abierto dos veces, y justo esa segunda apertura era lo que lo rompía todo. + +## Una línea y los bloqueos POSIX + +En Unix SQLite guarda sus bloqueos con POSIX advisory locks (`fcntl`). Tienen una propiedad muy fea - `close()` de cualquier descriptor de un archivo quita todos los bloqueos POSIX que el proceso tiene sobre ese archivo, no solo los que se tomaron con ese descriptor. Y el proceso no tiene forma de saber que sus bloqueos han desaparecido. La documentación de SQLite tiene un apartado sobre esto en [How To Corrupt An SQLite Database File](https://www.sqlite.org/howtocorrupt.html#_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_). La propia librería lo esquiva, el problema solo aparece cuando algo en el mismo proceso abre el archivo de la base por fuera de SQLite. + +Y `writeFileSync(file, "", { flag: "a" })` hace exactamente eso, abre el archivo, añade cero bytes y lo cierra. Por sí solo no rompe nada. Pero `wa serve` abría el almacén dos veces, la conexión principal y otra aparte para el registro de acciones del agente. La segunda apertura ejecutaba esta línea, y la primera conexión se quedaba sin bloqueos sin enterarse. + +Luego la cadena va así: + +1. Otro proceso cierra su última conexión. No ve ningún bloqueo de `wa serve`, así que se cree el último, hace checkpoint y borra `-wal` y `-shm`. +2. `wa serve` sigue escribiendo en su WAL, que ya está borrado. Para él no ha cambiado nada. +3. Los demás procesos mientras tanto crean un WAL nuevo y escriben en el archivo real. +4. Cuando `wa serve` junta suficientes páginas, hace su propio checkpoint y escribe páginas viejas encima de un archivo que los demás ya han cambiado hace rato. + +Así salen páginas que pertenecen a dos tablas. Y probablemente por eso todo parecía normal durante horas - el almacén no se rompe cuando se pierden los bloqueos, se rompe cuando se hace checkpoint del WAL caducado, y para eso hacen falta unas 1000 páginas escritas o un checkpoint explícito. + +Lo reproduje esa misma noche, sin cli-core, con tablas sintéticas. Resumido queda así (el archivo completo: [T1-minimal.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/T1-minimal.mjs)): + +```js +const db = new DatabaseSync(path) // el proceso de larga duración +db.exec("PRAGMA journal_mode=WAL; CREATE TABLE a(...); CREATE TABLE b(...); INSERT INTO a ...") +writeFileSync(path, "", { flag: "a" }) // la línea: ya no hay bloqueos sobre la base +execFileSync("sqlite3", [path, "INSERT INTO b ..."]) // el close de otro borra -wal y -shm +db.exec("INSERT INTO a ...") // escribimos en un WAL borrado +other("3000 inserciones en b") // otro proceso hace crecer el archivo real +for (let i = 0; i < 1500; i++) db.exec("INSERT INTO a ...") +db.exec("PRAGMA wal_checkpoint(TRUNCATE)") // páginas viejas sobre el archivo vivo +``` + +En la primera prueba, antes del `writeFileSync`, en `/proc/locks` el proceso tiene el bloqueo sobre la base y el byte en `-shm`, y después solo queda el byte. Cuando `sqlite3` cierra, ya no hay `-wal` ni `-shm` en el disco, y el descriptor del WAL del primer proceso está marcado `(deleted)`. Cuando este hace checkpoint, una conexión nueva recibe el mismo "database disk image is malformed" que la sincronización del correo, y `quick_check` dice `Tree 3 page 3 cell 0: invalid page number 2904`. + +La corrección también es, en el fondo, una línea: [cli-core #2578](https://github.com/WireCatLabs/cli-core/pull/2578). Si el archivo no existe, se crea con el flag `wx`, y si existe, solo se comprueba el permiso de escritura con `accessSync`, que no abre ningún descriptor. Salió en cli-core 0.599.0, y ese mismo día tg, max, wa, memo y mail pasaron a esa versión o a la siguiente. Con la corrección va un test que abre el almacén, toma `BEGIN IMMEDIATE`, cuenta las líneas de su proceso en `/proc/locks`, abre el almacén una segunda vez y comprueba que el número no cambia. Con el código viejo falla. Después los procesos empezaron a pasar a una sola conexión, para que aunque esto vuelva no haya segunda apertura. + +## Quién borró el WAL + +Yo pensaba que cualquier proceso que cierra el último podía borrar el WAL. En las notas que iba tomando mientras lo investigaba hasta escribí que `node:sqlite` también lo borra después de un `wal_checkpoint(TRUNCATE)` explícito. Y en el informe del incidente taché "distintas versiones de SQLite" de los sospechosos: todos los CLI corren en Node 24.19.0 con SQLite 3.53.3, y el `sqlite3` del sistema, 3.46.1, solo se usa en la copia de seguridad semanal. + +Luego monté un banco de pruebas en cli-testing para romper el almacén a propósito, con datos sintéticos. Como casi todo el código de aquí, lo escribieron y lo ejecutaron agentes, y yo ponía las tareas y decidía qué hacer con los resultados. Las primeras ejecuciones con el cli-core viejo simplemente no se rompían. Una razón la encontré rápido - mi `serve` de prueba escribía y hacía checkpoint a menudo, y SQLite se salta el checkpoint al cerrar (y el borrado con él) si alguien escribió en el archivo desde la última lectura del proceso que cierra. El `wa serve` real escribía poco. Pero incluso con eso, sin `sqlite3` en el escenario el almacén seguía entero. + +Así que probé cada "cerrador" por separado ([closers.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/closers.mjs)). Un proceso mantiene el almacén abierto, otro lo abre, hace una cosa y cierra. Cada variante la pasé 2 veces, una con el primer proceso sin bloqueos y otra con sus bloqueos intactos. + +| Quién cierra | El primero perdió sus bloqueos | El primero mantuvo sus bloqueos | +| --- | --- | --- | +| Node (SQLite 3.53.3): solo open/close, SELECT, INSERT, INSERT y checkpoint PASSIVE o TRUNCATE | WAL sigue ahí | WAL sigue ahí | +| Bun (SQLite 3.53.0): INSERT | WAL sigue ahí | WAL sigue ahí | +| Shell `sqlite3` 3.46.1: SELECT o INSERT | WAL y shm borrados | WAL sigue ahí | + +O sea, en mi máquina solo el shell viejo borró el WAL, incluso con un simple SELECT, y solo al lado de un proceso que ya había perdido sus bloqueos. Mi propia nota sobre Node no se confirmó en el banco. Lo que significa que el bug necesita un segundo actor con un SQLite más viejo, y seguramente por eso estuvo escondido tanto tiempo, en mis pruebas los procesos Node de los CLI nunca se borraron el WAL entre sí. + +Por qué 3.53 no lo hace y 3.46.1 sí, no llegué a averiguarlo. La misma página de SQLite dice que desde la 3.51.0 hay defensas adicionales justo contra estos bloqueos quitados por `close()`, para WAL y varios procesos. Parece la explicación, pero no lo comprobé en el código. También es una deducción, no un hecho, que ese día abriera mi almacén el shell u otro programa con un SQLite viejo. Nada registró qué programa abrió el archivo. Y cuándo se borró el WAL lo sé solo más o menos. + +En el banco, el escenario T1 (un `serve` de larga duración abre el almacén una segunda vez, al lado 3 escritores cortos y `sqlite3`, 60 segundos) rompió el almacén en 3 de 3 ejecuciones con cli-core 0.593.0, el primer error de un escritor a los 5-8 segundos. Con cli-core 0.608.0 el mismo escenario pasó 3 de 3, con `serve` abriendo el almacén una segunda vez 17-18 veces por ejecución sin que pasara nada. + +## La recuperación dijo que no se había perdido nada + +Restauré el almacén con `store recover run`, que un agente hizo a petición mía justo después del incidente. Copia todas las filas legibles con el `.recover` del shell `sqlite3`, vuelve a llenar los índices de búsqueda y de vectores, comprueba la copia y cambia el archivo. El archivo salió entero. Le faltaban al menos 31 correos, se encontraron por sus ids, y seguían en el servidor de correo. + +Luego pasé la misma recuperación por almacenes que había roto el banco y lo comparé con los registros de los escritores, donde está apuntado cada lote confirmado. + +| Almacén roto | Tiempo de recuperación | El informe dijo perdido | Mensajes confirmados en la ejecución / faltan después | +| --- | ---: | --- | --- | +| 1 | 4.0 s | nada | 970 / 50 | +| 2 | 4.0 s | 97 mensajes | 1 490 / 250 | +| 3 | 4.7 s | nada | 910 / 50 | + +Cada vez el archivo recuperado pasaba `quick_check`, `integrity_check` y las 25 comprobaciones de FTS5, y aun así le faltaban mensajes confirmados, y 2 veces de 3 el informe decía que no se había perdido nada. La recuperación contaba filas antes y después de su propia copia, y las filas que el checkpoint caducado había machacado antes ya no estaban en el archivo dañado, no había nada que contar. + +Luego pasé el banco 3 veces más, ya con escritores que escriben como los tg, mail y memo de verdad, y recuperé también esos 3 almacenes. En 1 ejecución de 3 todas las comprobaciones pasaron sobre el almacén tal cual, así que nadie habría lanzado una recuperación, y aun así faltaban 80 mensajes confirmados. Son las filas que `serve` escribió en el WAL que el close de otro había borrado, nunca llegaron al archivo de la base. En total, en las 6 recuperaciones (3 de la tabla y estas 3) se perdieron cada vez entre 50 y 300 mensajes confirmados (y en una ejecución además 40 notas), y ningún informe los nombró enteros: 5 veces no informó de ninguna pérdida, 1 vez 97 de 250. + +El informe ya no miente así ([cli-core #2759](https://github.com/WireCatLabs/cli-core/pull/2759), salió en la 0.618.0). Antes de la copia compara cada índice del archivo dañado con su tabla. Una página caducada machaca la tabla pero los índices se quedan como estaban, y la diferencia muestra cuántas filas desaparecieron. Es una cota inferior, así que el informe dice "se perdieron al menos N" o "no se sabe cuántas se perdieron", y nunca "no se perdió nada". Y la cota queda bastante por debajo de la realidad, en el segundo almacén dice "al menos 200" donde faltan 241. + +De paso empezó a devolver filas que `.recover` mete en una tabla aparte para filas sin dueño. En el segundo almacén esa tabla tenía 9 mensajes. Pero lo perdido no lo devuelve, en ese mismo almacén siguen faltando 241 de 250. Eso solo puede volver desde el origen. Por eso después de una recuperación los chats y las carpetas de correo se marcan como no descargados desde un día antes de la última comprobación profunda que pasó, y la siguiente sincronización normal los vuelve a bajar. En el banco lo comprobé en otros 3 almacenes y solo con mensajes, y la sincronización los bajó todos. El correo solo lo comprobé con un test, y con un mensajero real no lo probé. Lo que se perdió antes de esa fecha, y además las notas y todo lo que solo vivía en el almacén, no vuelve así. + +Por cierto, la primera versión de ese recuento usaba `EXCEPT`, y SQLite 3.53 contó 144 filas perdidas en un índice dañado donde se habían perdido 50. Recorría el orden del índice, y un índice dañado no tiene orden. El shell 3.46 dio 50 con la misma consulta. Lo reescribimos con `GROUP BY`. + +## Si tienes Node y SQLite en un mismo proceso + +No abras el archivo de la base con nada que no sea SQLite mientras el proceso tenga una conexión. No solo `writeFileSync`, también `readFileSync`, `copyFileSync`, un hash del archivo, etc., cualquiera de ellos quita los bloqueos al cerrar. `statSync`, `existsSync` y `accessSync` no abren descriptor, esos se pueden usar. Para copiar una base viva está `backup()` en `node:sqlite` o `store backup`, y el `.backup` del shell `sqlite3` yo lo lanzaría sobre una copia, no sobre el archivo vivo, porque un shell viejo al lado de un proceso sin bloqueos es justo lo que borra el WAL. + +Además, una conexión por proceso. Aunque alguien vuelva a meter una línea así, no habrá segunda apertura. De momento lo he comprobado solo en memo, y cualquier otra apertura del archivo con `fs` sigue quitando los bloqueos. + +Tampoco una sincronización que falla debería seguir intentando escribir en silencio en un almacén roto. Mis temporizadores lo hicieron unas 5 horas, desde el primer error hasta que los paré. Ahora con el primer "malformed" aparece una marca de daño junto al almacén, y hasta que se recupere nadie lo abre para escribir. A un servidor que ya tiene una conexión abierta esto no lo para, la marca solo bloquea aperturas nuevas. Y `doctor --deep` revisa todo el archivo y recuerda la última vez que el almacén estaba entero. + +Cuando intentaba entender qué se había perdido exactamente, resultó que las sincronizaciones correctas de correo y memo no dejan ningún registro, y la "última escritura limpia" hubo que reconstruirla por la hora de fin de los temporizadores. Ahora una escritura confirmada en el almacén deja un evento en el registro de la ejecución (tabla, tipo de cambio, número de filas, sin contenido). Con escrituras como las de los CLI reales cuesta un 0-3%, y en el peor caso, cuando cada transacción inserta una fila y nada más, entre un 8% con 2 000 transacciones y un 18% con 200. + +Y yo no me fiaría a ciegas de un informe de recuperación, ni del mío. Después de cualquier daño, compara con el origen (el servidor de correo, el mensajero, una copia de seguridad). + +El banco de pruebas ahora comprueba mucho más que este bug: + +- 50 `kill -9` en medio de una transacción, 50 en medio de un checkpoint, migraciones matadas, etc. El cli-core actual lo aguantó todo. +- Lo único que lo rompió fueron otros programas que tocan los archivos del almacén por su cuenta, como un `-shm` borrado, un `-wal` cambiado o un cliente de sincronización que pone una copia vieja encima del archivo vivo. +- Así que yo no tendría el almacén en una carpeta sincronizada. +- Si SQLite deshacía ella misma una transacción por un error de entrada/salida, nuestro propio `ROLLBACK` fallaba con "cannot rollback - no transaction is active", y hacia fuera salía ese error en lugar del real. Eso también se corrigió en #2759. + +## Lo que no medí + +- Un corte de luz de verdad. El banco mata procesos, y la caché de páginas sobrevive a eso. Una prueba honesta necesita `dm-flakey`, y eso pide root. +- Un disco lleno de verdad. En su lugar hay un límite de tamaño de archivo por proceso, y SQLite lo reporta como error de entrada/salida. +- Ejecuciones largas. Los escenarios duraron de 1 a 2.5 minutos, la mayoría una vez por versión. Lo que pasó una vez podría haberse roto en una segunda. +- Mi almacén de 6 GB, ni ninguno de más de unos 130 MB. El del banco es pequeño a propósito, para que el checkpoint automático ocurra cada pocos segundos. +- Bun como runtime principal de los escritores. +- Los textos largos de correos en mi almacén. Sus páginas de continuación pudieron quedar machacadas, y no comprobé si se cortaron. +- Por qué SQLite 3.53 no borra el WAL donde 3.46.1 sí lo borra. + +Todos los scripts y resultados están en [cli-testing](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md), junto con una lista de [lo que puede volver a pasar](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md#what-can-happen-again). Todo es sintético, `T1-minimal.mjs` y `closers.mjs` funcionan sin cli-core, solo hace falta el shell `sqlite3`. Si con otra versión de SQLite te sale distinto, escríbeme. Quiero saber quién más borra el WAL debajo de un proceso sin bloqueos. diff --git a/content/blog/one-line-that-broke-sqlite-locks/index.md b/content/blog/one-line-that-broke-sqlite-locks/index.md new file mode 100644 index 00000000..bb8913be --- /dev/null +++ b/content/blog/one-line-that-broke-sqlite-locks/index.md @@ -0,0 +1,142 @@ +--- +title: One line dropped every SQLite lock, and a 6 GB database broke +description: WAL mode, busy_timeout, no crashes and no disk errors, and still "database disk image is malformed". The cause was one writeFileSync before every open. How I found it through /proc/locks, reproduced it on an empty file, and why the recovery said nothing was lost. +date: 2026-11-09 +tags: [cli] +cover: ./cover.jpg +coverAlt: "An open brass padlock with a smoked glass body, cracked and shifted glass sheets inside, a sewing pin barely touching its side, next to an empty jar and a second jar crumbling into dust" +author: viacheslav-ptsarev +draft: false +--- + +So my database broke. The shared WireCat store is one SQLite file that several CLIs write at once (Telegram, mail, memo and so on), and mine is 6 GB. WAL mode, `busy_timeout` of 5 seconds, the same SQLite build in every CLI, no crashes and no disk errors in the journal, and still at some point the mail sync failed with "database disk image is malformed", and everything else followed. + +What broke it was one line that was only supposed to make sure the file exists: + +```js +writeFileSync(file, "", { flag: "a", mode: 0o600 }) +``` + +It ran before every writable open of the store. Appending zero bytes to a file sounds as harmless as it gets, but on Linux it was enough to drop every SQLite lock of a process that already had the store open. I found it through `/proc/locks` and reproduced it on an empty file the same evening. And later the recovery said 2 times out of 3 that nothing was lost, when something was. + +## How it got noticed + +The first mail sync failed at about 17:10 UTC, and from then on the memo timer failed on every run, more than 60 times by the evening. Message search failed on every query. Nobody heard about it, because a failed timer writes one line to stderr, and you only see it on the next manual run. `memo doctor` meanwhile said the store was fine, it didn't run `quick_check` or look at the search indexes. + +An agent that was checking search in the evening ran into `fts5: corruption`. I ran `quick_check` on a copy and got 687 lines of problems in about 36 tables, not only in indexes but in the source tables too. There were pages that two tables point to at once, indexes with the wrong number of entries, pages nobody uses. That doesn't look like a bad sector, more like two processes writing the file without seeing each other. + +I stopped the timers and went to see who was holding the file. The most suspicious were two long-lived `wa serve` processes (the WhatsApp CLI server) that had been running since the night. Here's what `/proc/locks` had for them (the process and inode numbers here are made up): + +```text +POSIX ADVISORY READ 4101 103:05:7777 128 128 +POSIX ADVISORY READ 4102 103:05:7777 128 128 +``` + +That's a lock on one byte in the `-shm` file, which SQLite uses to tell that a process is still alive (the dead-man lock). And on the database file itself they held no lock at all. A normal WAL connection holds a shared lock on a service area of the database file for its whole life, bytes around 1073741826, far past the data, and that's how other processes see someone is using the database. I checked that later on a clean file. These 2 processes had no such lock. + +And `/proc//fd` for both showed `wirecat.db-wal (deleted)` and `wirecat.db-shm (deleted)`. So the WAL had been deleted on disk, and these processes kept writing into it, the last time around 21:20, 4 hours after the first error. Plus each of them had the store open twice, and that second open is exactly what broke everything. + +## One line and POSIX locks + +On Unix SQLite keeps its locks with POSIX advisory locks (`fcntl`). They have a nasty property - `close()` of any descriptor of a file drops every POSIX lock the process holds on that file, not only the ones taken through that descriptor. And the process has no way to find out its locks are gone. The SQLite docs have a section about it in [How To Corrupt An SQLite Database File](https://www.sqlite.org/howtocorrupt.html#_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_). The library itself works around this, the problem appears only when something in the same process opens the database file behind SQLite's back. + +And `writeFileSync(file, "", { flag: "a" })` does exactly that, it opens the file, appends zero bytes and closes it. On its own it breaks nothing. But `wa serve` opened the store twice, the main connection and a separate one for the agent's action log. The second open ran this line, and the first connection was silently left without locks. + +Then the chain goes like this: + +1. Some other process closes its last connection. It can't see any locks from `wa serve`, so it thinks it's the last one, checkpoints and deletes `-wal` and `-shm`. +2. `wa serve` keeps writing into its WAL, which is already deleted. For it nothing has changed. +3. The other processes meanwhile create a new WAL and write into the real file. +4. When `wa serve` has gathered enough pages, it runs its own checkpoint and writes old pages over a file the others have long since changed. + +That's how you get pages that belong to two tables. And that's most likely why everything looked fine for hours - the store doesn't break when the locks are lost, it breaks when the stale WAL is checkpointed, which takes about 1000 pages of writes or an explicit checkpoint. + +I reproduced it the same evening, without cli-core, on synthetic tables. Shortened, it looks like this (full file: [T1-minimal.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/T1-minimal.mjs)): + +```js +const db = new DatabaseSync(path) // the long-lived process +db.exec("PRAGMA journal_mode=WAL; CREATE TABLE a(...); CREATE TABLE b(...); INSERT INTO a ...") +writeFileSync(path, "", { flag: "a" }) // the line: no more locks on the database +execFileSync("sqlite3", [path, "INSERT INTO b ..."]) // someone else's close deletes -wal and -shm +db.exec("INSERT INTO a ...") // writing into a deleted WAL +other("3000 inserts into b") // another process grows the real file +for (let i = 0; i < 1500; i++) db.exec("INSERT INTO a ...") +db.exec("PRAGMA wal_checkpoint(TRUNCATE)") // old pages over the live file +``` + +In the first probe, before the `writeFileSync`, `/proc/locks` shows the process with both the lock on the database and the byte in `-shm`, after it only the byte is left. After `sqlite3` closes, there's no `-wal` or `-shm` on disk, and the first process's WAL descriptor is marked `(deleted)`. When it checkpoints, a new connection gets the same "database disk image is malformed" as the mail sync, and `quick_check` says `Tree 3 page 3 cell 0: invalid page number 2904`. + +The fix is basically one line too: [cli-core #2578](https://github.com/WireCatLabs/cli-core/pull/2578). If the file is missing, it's created with the `wx` flag, and if it exists, only write access is checked with `accessSync`, which opens no descriptor. It came out in cli-core 0.599.0, and tg, max, wa, memo and mail moved to it or the next version the same day. The fix comes with a test that opens the store, takes `BEGIN IMMEDIATE`, counts its own process's lines in `/proc/locks`, opens the store a second time and checks the count is the same. It fails on the old code. After that processes started moving to one connection, so even if this regresses there is no second open. + +## Who deleted the WAL + +I thought any process that closes last could delete the WAL. In the notes I kept while digging into it I even wrote that `node:sqlite` deletes it too after an explicit `wal_checkpoint(TRUNCATE)`. And in the incident report I crossed "different SQLite builds" off the suspects: every CLI runs on Node 24.19.0 with SQLite 3.53.3, and the system `sqlite3` 3.46.1 is only used in the weekly backup. + +Then I built a harness in cli-testing to break the store on purpose, on synthetic data. Like almost all the code here, agents wrote and ran it, and I set the tasks and decided what to do with the results. The first runs on the old cli-core just didn't break. I found one reason fast - my test `serve` wrote and checkpointed often, and SQLite skips the checkpoint on close (and the deletion with it) if someone wrote to the file since the closing process last read it. The real `wa serve` wrote rarely. But even with that, without `sqlite3` in the scenario the store stayed intact. + +So I checked each "closer" on its own ([closers.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/closers.mjs)). One process keeps the store open, a second one opens it, does one thing and closes. I ran each variant 2 times, once with the first process having lost its locks and once with its locks kept. + +| Who closes | First lost its locks | First kept its locks | +| --- | --- | --- | +| Node (SQLite 3.53.3): plain open/close, SELECT, INSERT, INSERT then checkpoint PASSIVE or TRUNCATE | WAL kept | WAL kept | +| Bun (SQLite 3.53.0): INSERT | WAL kept | WAL kept | +| `sqlite3` shell 3.46.1: SELECT or INSERT | WAL and shm deleted | WAL kept | + +So on my machine only the old shell deleted the WAL, even on a plain SELECT, and only next to a process that had already lost its locks. My own note about Node didn't hold up on the harness. Which means the bug needs a second actor with an older SQLite, and that's probably why it stayed hidden so long, in my runs the CLIs' Node processes never deleted each other's WAL. + +Why 3.53 doesn't do it and 3.46.1 does, I never figured out. The same SQLite page says that starting with 3.51.0 there are extra defenses against these locks dropped by `close()`, for WAL and several processes. Looks like the explanation, but I didn't check it in the code. It's also an inference, not a fact, that the shell or another program with an older SQLite opened my store that day. Nothing recorded which program opened the file. I also only know roughly when the WAL was deleted. + +On the harness, scenario T1 (a long-lived `serve` opens the store a second time, 3 short writers and `sqlite3` next to it, 60 seconds) broke the store in 3 of 3 runs on cli-core 0.593.0, the first writer error after 5-8 seconds. On cli-core 0.608.0 the same scenario passed 3 of 3, with `serve` opening the store a second time 17-18 times per run and nothing happening. + +## The recovery said nothing was lost + +I restored the store with `store recover run`, which an agent built at my request right after the incident. It copies every readable row with the `sqlite3` shell's `.recover`, fills the search and vector indexes again, checks the copy and swaps the file. The file came out intact. At least 31 emails were missing from it, they were found by their ids, and they were still on the mail server. + +Then I ran the same recovery on stores the harness had broken and compared against the writers' ledgers, where every committed batch is recorded. + +| Broken store | Recovery time | Report said lost | Messages committed in the run / missing after | +| --- | ---: | --- | --- | +| 1 | 4.0 s | nothing | 970 / 50 | +| 2 | 4.0 s | 97 messages | 1,490 / 250 | +| 3 | 4.7 s | nothing | 910 / 50 | + +Every time the recovered file passed `quick_check`, `integrity_check` and all 25 FTS5 checks, and committed messages were still missing from it, and 2 times out of 3 the report said nothing was lost. The recovery counted rows before and after its own copy, and the rows the stale checkpoint had overwritten earlier were no longer in the damaged file, there was nothing to count. + +Then I ran the harness 3 more times, now with writers that write like the real tg, mail and memo, and recovered those 3 stores too. In 1 run of 3 every check passed on the store as it was, so nobody would even have run a recovery, and 80 committed messages were still gone. Those are the rows `serve` wrote into the WAL someone else's close had deleted, they never reached the database file. Over the 6 recoveries in all (3 from the table and these 3), 50 to 300 committed messages were lost each time (and in one run 40 notes too), and no report named them in full: 5 times it reported no loss at all, once 97 of 250. + +The report doesn't lie like that anymore ([cli-core #2759](https://github.com/WireCatLabs/cli-core/pull/2759), out in 0.618.0). Before the copy it compares each index of the damaged file with its table. A stale page overwrites the table but the indexes stay old, and the difference shows how many rows disappeared. That's a lower bound, so the report says "at least N gone" or "how many were lost is unknown", and never "nothing lost". And the bound is well below the truth, on the second store it says "at least 200" where 241 are gone. + +Along the way it started putting back rows that `.recover` puts into a separate table for rows with no owner. On the second store that table held 9 messages. But it doesn't bring back what was lost, the same store is still missing 241 of 250. Those can only come back from the source. So after a recovery the chats and mail folders are marked as not fetched from a day before the last deep check that passed, and the next ordinary sync fetches them again. On the harness I checked that on 3 other stores and only for messages, and the sync fetched them all. Mail I only checked with a test, and I didn't try it on a real messenger. Whatever was lost before that day, plus notes and anything that only lived in the store, doesn't come back this way. + +By the way, the first version of that count used `EXCEPT`, and SQLite 3.53 counted 144 lost rows on a damaged index where 50 were lost. It walked the index's order, and a damaged index has no order. The 3.46 shell gave 50 on the same query. We rewrote it with `GROUP BY`. + +## If you have Node and SQLite in one process + +Don't open the database file with anything other than SQLite while the process has a connection. Not only `writeFileSync`, but `readFileSync`, `copyFileSync`, a hash of the file and so on, any of them drops the locks on close. `statSync`, `existsSync` and `accessSync` open no descriptor, those are fine. For a copy of a live database there's `backup()` in `node:sqlite` or `store backup`, and I'd run the `sqlite3` shell's `.backup` on a copy, not on the live file, because an old shell next to a process without locks is what deletes the WAL. + +Plus one connection per process. Even if someone brings such a line back, there's no second open. So far I've checked that only on memo, and any other `fs` open of the file still drops the locks. + +Also a failed sync shouldn't keep quietly trying to write into a broken store. Mine did that for about 5 hours, from the first error until I stopped the timers. Now on the first "malformed" a damage marker appears next to the store, and until it's recovered nobody opens it for writing. A server that already holds a connection isn't stopped by it, the marker only blocks new opens. And `doctor --deep` checks the whole file and remembers the last time the store was intact. + +When I tried to work out what was lost, it turned out that successful mail and memo syncs leave no records at all, and the "last clean write" had to be pieced together from timer finish times. Now a committed write to the store leaves an event in the run record (table, kind of change, row count, no content). On writes shaped like the real CLIs it costs 0-3%, and in the worst case, where each transaction inserts one row and nothing else, from 8% at 2,000 transactions to 18% at 200. + +And I wouldn't take a recovery report at its word, even my own. After any damage, check against the source (the mail server, the messenger, a backup). + +The harness now tests a lot more than this one bug: + +- 50 `kill -9`s in the middle of a transaction, 50 in the middle of a checkpoint, killed migrations and so on. The current cli-core survived all of it. +- The only things that broke it were other programs touching the store's files themselves, like a deleted `-shm`, a swapped `-wal` or a sync client putting an old copy back over the live file. +- So I wouldn't keep the store in a synced folder. +- If SQLite rolled a transaction back itself because of an I/O error, our own `ROLLBACK` failed with "cannot rollback - no transaction is active", and that error went out instead of the real one. That was fixed in #2759 too. + +## What I didn't measure + +- A real power cut. The harness kills processes, and the page cache survives that. An honest test needs `dm-flakey`, which needs root. +- A really full disk. Instead there's a per-process file size limit, and SQLite reports it as an I/O error. +- Long runs. Scenarios ran 1 to 2.5 minutes, most of them once per version. What passed once could have broken on a second run. +- My 6 GB store, or any store over about 130 MB. The harness store is small on purpose, so an automatic checkpoint happens every few seconds. +- Bun as the writers' main runtime. +- Long email bodies in my store. Their continuation pages could have been overwritten, and I didn't check whether they got cut. +- Why SQLite 3.53 doesn't delete the WAL where 3.46.1 does. + +All scripts and results are in [cli-testing](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md), with a list of [what can happen again](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md#what-can-happen-again). It's all synthetic, `T1-minimal.mjs` and `closers.mjs` run without cli-core, you only need the `sqlite3` shell. If you get something different on another SQLite version, write to me. I want to know who else deletes the WAL under a process without locks. diff --git a/content/blog/one-line-that-broke-sqlite-locks/index.ru.md b/content/blog/one-line-that-broke-sqlite-locks/index.ru.md new file mode 100644 index 00000000..00e5af91 --- /dev/null +++ b/content/blog/one-line-that-broke-sqlite-locks/index.ru.md @@ -0,0 +1,142 @@ +--- +title: Одна строка сняла все локи SQLite, и база на 6 ГБ сломалась +description: WAL, busy_timeout, никаких падений и ошибок диска, а база все равно "database disk image is malformed". Причина была в одном writeFileSync перед каждым открытием. Как я это нашел через /proc/locks, воспроизвел на пустом файле и почему восстановление говорило, что ничего не потеряно. +date: 2026-11-09 +tags: [cli] +cover: ./cover.jpg +coverAlt: "Открытый латунный замок с корпусом из дымчатого стекла, внутри треснувшие и сдвинутые стеклянные пластины, сбоку его едва касается швейная булавка, рядом пустая банка и вторая, рассыпающаяся в пыль" +author: viacheslav-ptsarev +draft: false +--- + +Короче, у меня сломалась база. Общее хранилище WireCat - это один файл SQLite, в который пишут сразу несколько CLI (Telegram, почта, memo итд), у меня он весит 6 ГБ. База в режиме WAL, `busy_timeout` 5 секунд, у всех CLI одна сборка SQLite, в журнале ни падений, ни ошибок диска, а синк почты в какой-то момент все равно упал с "database disk image is malformed", и за ним все остальное. + +Сломала ее одна строка, которая должна была просто убедиться, что файл существует: + +```js +writeFileSync(file, "", { flag: "a", mode: 0o600 }) +``` + +Она выполнялась перед каждым открытием базы на запись. Дописать ноль байт в конец файла звучит максимально безобидно, но на Linux этого хватило, чтобы снять все локи SQLite у процесса, который уже держал базу открытой. Нашел я это через `/proc/locks` и в тот же вечер воспроизвел на пустом файле. А восстановление потом 2 раза из 3 сказало, что ничего не потеряно, хотя потеряно было. + +## Как это заметили + +Первый синк почты упал около 17:10 по UTC, и с этого момента таймер memo падал на каждом запуске, больше 60 раз до вечера. Поиск по сообщениям падал на каждом запросе. Никто об этом не узнал, потому что упавший таймер пишет одну строчку в stderr, а ее видно только при следующем ручном запуске. `memo doctor` при этом говорил, что с базой все в порядке, он не проверял ни `quick_check`, ни поисковые индексы. + +Наткнулся на это агент, который вечером проверял поиск и увидел `fts5: corruption`. Я прогнал `quick_check` на копии и получил 687 строк проблем примерно в 36 таблицах, и не только в индексах, но и в исходных таблицах. Там были страницы, на которые ссылаются сразу две таблицы, индексы с неправильным числом записей, страницы, которые никто не использует. На битый сектор не похоже, скорее два процесса писали в файл и не видели друг друга. + +Я остановил таймеры и пошел смотреть, кто сейчас держит файл. Самыми подозрительными были два долгоживущих процесса `wa serve` (сервер WhatsApp CLI), которые работали с ночи. В `/proc/locks` у них было вот что (номера процессов и inode тут выдуманные): + +```text +POSIX ADVISORY READ 4101 103:05:7777 128 128 +POSIX ADVISORY READ 4102 103:05:7777 128 128 +``` + +Это лок на один байт в файле `-shm`, по нему SQLite понимает, что процесс еще жив (dead-man lock). А на самом файле базы у них не было ни одного лока. Нормальное соединение в режиме WAL всю свою жизнь держит общий (shared) лок на служебном участке файла базы, это байты в районе 1073741826, далеко за данными, и по нему другие процессы видят, что базой кто-то пользуется. Я потом проверил это на чистом файле. У этих 2 процессов такого лока не было. + +А в `/proc//fd` у обоих висело `wirecat.db-wal (deleted)` и `wirecat.db-shm (deleted)`. Т.е. WAL на диске уже удалили, а эти процессы продолжали в него писать, последний раз около 21:20, через 4 часа после первой ошибки. Плюс каждый из них держал базу открытой дважды, и как раз второе открытие все и ломало. + +## Одна строка и POSIX-локи + +SQLite на Unix держит свои блокировки через POSIX advisory locks (`fcntl`). У них есть неприятная особенность - `close()` любого дескриптора файла снимает все POSIX-локи процесса на этом файле, а не только те, что взяты через этот дескриптор. И процесс никак не узнает, что его локи пропали. В документации SQLite про это есть раздел в [How To Corrupt An SQLite Database File](https://www.sqlite.org/howtocorrupt.html#_posix_advisory_locks_canceled_by_a_separate_thread_doing_close_). Сама библиотека эту особенность обходит, проблема появляется, только когда кто-то в том же процессе открывает файл базы мимо SQLite. + +А `writeFileSync(file, "", { flag: "a" })` именно это и делает, открывает файл, дописывает ноль байт и закрывает. Сам по себе он ничего не портит. Но `wa serve` открывал базу дважды, основное соединение и отдельное для лога действий агента. Второе открытие вызывало эту строку, и первое соединение молча оставалось без локов. + +Дальше цепочка такая: + +1. Какой-то другой процесс закрывает свое последнее соединение. Локов `wa serve` он не видит, поэтому считает себя последним, делает checkpoint и удаляет `-wal` и `-shm`. +2. `wa serve` продолжает писать в свой уже удаленный WAL. Для него ничего не изменилось. +3. Остальные процессы в это время создают новый WAL и пишут в настоящий файл. +4. Когда у `wa serve` набирается достаточно страниц, он делает свой checkpoint и записывает старые страницы поверх файла, в котором другие уже давно все поменяли. + +Так и получаются страницы, которые принадлежат двум таблицам. И по идее поэтому часами все выглядело нормально - база ломается не когда пропали локи, а когда протухший WAL чекпоинтится, а это примерно 1000 страниц записи или явный checkpoint. + +Воспроизвести получилось в тот же вечер, без cli-core, на синтетических таблицах. Сокращенно выглядит так (полный файл - [T1-minimal.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/T1-minimal.mjs)): + +```js +const db = new DatabaseSync(path) // долгоживущий процесс +db.exec("PRAGMA journal_mode=WAL; CREATE TABLE a(...); CREATE TABLE b(...); INSERT INTO a ...") +writeFileSync(path, "", { flag: "a" }) // та самая строка: локов на базе больше нет +execFileSync("sqlite3", [path, "INSERT INTO b ..."]) // чужой close удаляет -wal и -shm +db.exec("INSERT INTO a ...") // пишем в удаленный WAL +other("3000 вставок в b") // другой процесс растит настоящий файл +for (let i = 0; i < 1500; i++) db.exec("INSERT INTO a ...") +db.exec("PRAGMA wal_checkpoint(TRUNCATE)") // старые страницы поверх живого файла +``` + +В первой пробе до `writeFileSync` в `/proc/locks` у процесса есть и лок на базе, и байт в `-shm`, а после остается только байт. После закрытия `sqlite3` файлов `-wal` и `-shm` на диске нет, а у первого процесса дескриптор WAL помечен `(deleted)`. Когда он делает checkpoint, новое соединение получает тот же "database disk image is malformed", что и синк почты, а `quick_check` пишет `Tree 3 page 3 cell 0: invalid page number 2904`. + +Сам фикс по сути тоже одна строка: [cli-core #2578](https://github.com/WireCatLabs/cli-core/pull/2578). Если файла нет, он создается с флагом `wx`, а если есть, то проверяется только право на запись через `accessSync`, который дескриптор не открывает. Вышло это в cli-core 0.599.0, и в тот же день tg, max, wa, memo и mail обновились на него или на следующую версию. К фиксу есть тест, он открывает базу, берет `BEGIN IMMEDIATE`, считает строки своего процесса в `/proc/locks`, открывает базу второй раз и проверяет, что строк столько же. На старом коде он падает. Потом процессы стали переводить на одно соединение, чтобы даже при регрессии второго открытия просто не было. + +## Кто удалил WAL + +Я думал, что WAL может удалить любой процесс, который закрывается последним. В заметках, которые я вел по ходу разбора, я даже записал, что `node:sqlite` после явного `wal_checkpoint(TRUNCATE)` тоже его удаляет. А в отчете об инциденте вычеркнул "разные сборки SQLite" из подозреваемых: все CLI работают на Node 24.19.0 с SQLite 3.53.3, а системный `sqlite3` 3.46.1 используется только в еженедельном бэкапе. + +Потом я сделал стенд в cli-testing, чтобы ломать базу специально и на синтетике. Стенд, как и почти весь код здесь, писали и гоняли агенты, а я ставил задачи и решал, что делать с результатами. Первые прогоны на старом cli-core просто не ломались. Одну причину я нашел быстро - мой тестовый `serve` писал и чекпоинтил часто, а SQLite пропускает checkpoint при закрытии (и удаление вместе с ним), если после последнего чтения закрывающегося процесса в файл кто-то писал. Настоящий `wa serve` писал редко. Но даже с этим без `sqlite3` в сценарии база оставалась целой. + +Поэтому я проверил каждого "закрывающего" по отдельности ([closers.mjs](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/closers.mjs)). Один процесс держит базу открытой, второй открывает, делает одну вещь и закрывается. Каждый вариант я прогнал 2 раза, когда первый потерял локи и когда сохранил. + +| Кто закрывается | Первый потерял локи | Первый сохранил локи | +| --- | --- | --- | +| Node (SQLite 3.53.3): просто open/close, SELECT, INSERT, INSERT и checkpoint PASSIVE или TRUNCATE | WAL на месте | WAL на месте | +| Bun (SQLite 3.53.0): INSERT | WAL на месте | WAL на месте | +| Шелл `sqlite3` 3.46.1: SELECT или INSERT | WAL и shm удалены | WAL на месте | + +Получается, на моей машине WAL удалил только старый шелл, даже от простого SELECT, и только рядом с процессом, который уже потерял локи. Моя же заметка про Node на стенде не подтвердилась. Значит, багу нужен второй участник со старой SQLite, и наверное поэтому он так долго не вылезал, в моих прогонах Node-процессы CLI друг другу WAL не удаляли. + +Почему 3.53 так не делает, а 3.46.1 делает, я так и не разобрался. В той же статье SQLite написано, что начиная с 3.51.0 добавлены дополнительные защиты как раз от локов, снятых через `close()`, для WAL и нескольких процессов. Выглядит как объяснение, но по коду я это не проверял. И что в тот день мою базу открыл шелл или другая программа со старой SQLite, это вывод, а не факт, потому что никто не записал, какая программа открывала файл. И когда именно удалили WAL, я знаю только примерно. + +На стенде сценарий T1 (долгоживущий `serve` открывает базу второй раз, рядом 3 коротких писателя и `sqlite3`, 60 секунд) на cli-core 0.593.0 сломал базу в 3 из 3 прогонов, первая ошибка у писателей через 5-8 секунд. На cli-core 0.608.0 тот же сценарий прошел 3 из 3, и `serve` за прогон открывал базу второй раз 17-18 раз без последствий. + +## Восстановление сказало, что ничего не потеряно + +Базу я восстановил командой `store recover run`, которую агент по моей просьбе сделал сразу после инцидента. Она копирует все читаемые строки через `.recover` шелла `sqlite3`, заново заполняет поисковые и векторные индексы, проверяет копию и подменяет файл. Файл получился целый. Из него пропало как минимум 31 письмо, их нашли по id, и они остались на почтовом сервере. + +А потом я прогнал то же восстановление на базах, которые сломал стенд, и сравнил с журналами писателей, где записан каждый закоммиченный батч. + +| Сломанная база | Время восстановления | Отчет сказал, что потеряно | Сообщений закоммичено за прогон / нет после | +| --- | ---: | --- | --- | +| 1 | 4.0 с | ничего | 970 / 50 | +| 2 | 4.0 с | 97 сообщений | 1 490 / 250 | +| 3 | 4.7 с | ничего | 910 / 50 | + +Файл после восстановления каждый раз проходил `quick_check`, `integrity_check` и все 25 проверок FTS5, а закоммиченных сообщений в нем все равно не хватало, и 2 раза из 3 отчет говорил, что ничего не потеряно. Восстановление считало строки до своей копии и после нее, а строк, которые протухший checkpoint затер раньше, в поврежденном файле уже не было, считать там было нечего. + +Потом я прогнал стенд еще 3 раза, уже с писателями, которые пишут как настоящие tg, mail и memo, и восстановил эти 3 базы тоже. В 1 прогоне из 3 все проверки прошли на базе как есть, так что восстановление никто бы и не запустил, а 80 закоммиченных сообщений все равно не было. Это строки, которые `serve` записал в WAL, удаленный чужим close, в файл базы они так и не попали. Всего на 6 восстановлениях (3 из таблицы и эти 3) каждый раз пропадало от 50 до 300 закоммиченных сообщений (а в 1 прогоне еще 40 заметок), и ни один отчет не назвал их полностью: 5 раз он не сообщил о потере ничего, 1 раз 97 из 250. + +Сейчас отчет так не врет ([cli-core #2759](https://github.com/WireCatLabs/cli-core/pull/2759), вышло в 0.618.0). До копии он сравнивает каждый индекс поврежденного файла с его таблицей. Протухшая страница затирает таблицу, а индексы остаются старыми, и разница показывает, сколько строк исчезло. Это нижняя граница, поэтому отчет пишет "пропало как минимум N" или "сколько пропало, неизвестно", и никогда "ничего не потеряно". И она заметно ниже настоящей цифры, на второй базе отчет пишет "как минимум 200", а не хватает 241. + +Попутно он стал возвращать строки, которые `.recover` складывает в отдельную таблицу для строк без хозяина. На второй базе там нашлось 9 сообщений. Но потерянное он не возвращает, на той же базе не хватает 241 из 250. Вернуть их можно только из источника. Поэтому после восстановления чаты и папки почты помечаются как недокачанные, начиная с дня до последней успешной глубокой проверки, и следующий обычный синк качает их заново. На стенде я проверил это на других 3 базах и только на сообщениях, там синк докачал все. Почту я проверял только тестом, а с настоящим мессенджером так не пробовал. Что пропало раньше этой даты, а еще заметки и все, что было только в базе, так не вернется. + +Кстати, первая версия этого подсчета была через `EXCEPT`, и SQLite 3.53 на поврежденном индексе насчитала 144 пропавших строки там, где пропало 50. Она шла по порядку индекса, а у поврежденного индекса порядка нет. Шелл 3.46 на том же запросе дал 50. Переписали на `GROUP BY`. + +## Если у вас Node и SQLite в одном процессе + +Не открывайте файл базы ничем, кроме SQLite, пока в процессе есть соединение. Это не только `writeFileSync`, но и `readFileSync`, `copyFileSync` или хэш файла, любой из них при закрытии снимет локи. `statSync`, `existsSync` и `accessSync` дескриптор не открывают, ими можно. Для копии живой базы есть `backup()` в `node:sqlite` или `store backup`, а шелл `sqlite3` с `.backup` я бы запускал на копии, а не на живом файле, потому что старый шелл рядом с процессом без локов как раз и удаляет WAL. + +Плюс одно соединение на процесс. Даже если кто-то вернет такую строку, второго открытия не будет. Проверял я это пока только на memo. И от других открытий файла через `fs` это не спасает, они все равно снимут локи. + +Еще упавший синк не должен молча пытаться писать в битую базу. У меня таймеры делали это около 5 часов, с первой ошибки и пока я их не остановил. Теперь при первом "malformed" рядом с базой появляется отметка о повреждении, и пока база не восстановлена, на запись ее больше никто не открывает. Сервер, который уже держит соединение, отметка не остановит, она закрывает только новые открытия. А `doctor --deep` проверяет весь файл и запоминает последний момент, когда база была целой. + +Когда я пытался понять, что именно пропало, оказалось, что успешные синки почты и memo вообще не оставляют записей, и "последнюю чистую запись" пришлось восстанавливать по времени завершения таймеров. Теперь закоммиченная запись в базу оставляет событие в записи запуска (таблица, вид изменения, число строк, без содержимого). На нагрузке, похожей на настоящие CLI, это стоит 0-3%, а в худшем случае, когда каждая транзакция вставляет одну строку и больше ничего, от 8% на 2 000 транзакциях до 18% на 200. + +И отчету о восстановлении я бы на слово не верил, даже своему. После любого повреждения сверяйтесь с источником (почтовый сервер, мессенджер, бэкап). + +Ну и стенд в итоге проверяет не только этот баг: + +- 50 раз `kill -9` посреди транзакции, 50 раз посреди checkpoint, убитые миграции итд. Текущий cli-core все это пережил. +- Ломали его только другие программы, которые сами трогают файлы базы, например удаленный `-shm`, подмененный `-wal` или синк-клиент, вернувший старую копию поверх живого файла. +- Поэтому я бы не держал базу в папке, которую что-то синхронизирует. +- Если SQLite сама откатила транзакцию из-за ошибки ввода-вывода, наш `ROLLBACK` падал с "cannot rollback - no transaction is active", и наружу уходила эта ошибка вместо настоящей. Это тоже поправили в #2759. + +## Что я не мерил + +- Настоящее отключение питания. Стенд убивает процессы, а кэш страниц при этом живет. Для честного теста нужен `dm-flakey`, а это root. +- Настоящий полный диск. Вместо него лимит размера файла на процесс, и SQLite отдает его как ошибку ввода-вывода. +- Длинные прогоны. Сценарии шли от 1 до 2.5 минут, большинство по 1 разу на версию. То, что прошло 1 раз, на втором прогоне могло и сломаться. +- Мою базу на 6 ГБ и вообще базы больше примерно 130 МБ. Стенд специально маленький, чтобы автоматический checkpoint случался каждые несколько секунд. +- Bun как основной рантайм писателей. +- Длинные тексты писем в моей базе. Их страницы продолжения могли быть затерты, и я не проверял, не обрезались ли они. +- Причину, по которой SQLite 3.53 не удаляет WAL там, где 3.46.1 удаляет. + +Все скрипты и результаты лежат в [cli-testing](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md), там же список того, [что может повториться](https://github.com/WireCatLabs/cli-testing/blob/main/performance/store/integrity/README.md#what-can-happen-again). Все на синтетике, `T1-minimal.mjs` и `closers.mjs` запускаются без cli-core, нужен только шелл `sqlite3`. Если у вас на другой версии SQLite выйдет по-другому, напишите. Хочу понять, кто еще удаляет WAL под процессом без локов. diff --git a/content/blog/one-reboot-broke-the-background/cover.jpg b/content/blog/one-reboot-broke-the-background/cover.jpg new file mode 100644 index 00000000..9370e34f Binary files /dev/null and b/content/blog/one-reboot-broke-the-background/cover.jpg differ diff --git a/content/blog/one-reboot-broke-the-background/index.es.md b/content/blog/one-reboot-broke-the-background/index.es.md new file mode 100644 index 00000000..6dcbe8ca --- /dev/null +++ b/content/blog/one-reboot-broke-the-background/index.es.md @@ -0,0 +1,98 @@ +--- +title: Qué necesita un servicio en segundo plano para sobrevivir al reinicio del portátil +description: Mi portátil se reinició de noche, y cada pieza en segundo plano de un CLI local-first falló a su manera. Lo que tuve que arreglar para que el servicio y las tareas programadas en un escritorio sobrevivan a un reinicio y a un keyring bloqueado. +date: 2026-11-02 +tags: [cli, telegram] +cover: ./cover.jpg +coverAlt: "Un portátil de noche sobre una mesa oscura con la pantalla apagada, rodeado de pequeñas máquinas de latón con engranajes que se han detenido, un candado cerrado delante y un tubo fino de cristal partido en dos entre ellas" +author: viacheslav-ptsarev +draft: false +--- + +En la noche del 1 al 2 de noviembre mi portátil se reinició, y por la mañana no funcionaba nada en segundo plano. No sé por qué se reinició. Los servicios de tg y max no arrancaron, las sincronizaciones completas de la noche fallaron, y una sincronización lanzada a mano por la mañana murió justo después del comando que la lanzó. Todo falló de forma distinta, y el problema nunca estuvo en el código de la sincronización. + +El segundo plano en WireCat son 2 cosas. `serve` mantiene la conexión con el mensajero y escribe los mensajes nuevos en el archivo local, es un servicio de usuario de systemd (un LaunchAgent en Mac). Y las tareas programadas, por ejemplo una sincronización completa una vez al día por la noche, que es un timer de systemd. Parece simple, pero esa noche se rompieron 4 sitios distintos, y cada uno tiene su sección abajo. + +Esa noche yo dormía y un agente de IA estaba terminando la app de escritorio. Sobre las 06:30 vio que los servicios estaban parados y los arrancó a mano, y las sincronizaciones completas también. A partir de ahí los agentes lanzaron los comandos y escribieron las correcciones, y yo los dirigía y decidía qué arreglar y cómo. + +## El servicio que nadie habilitó + +`tg personal server install` escribía el archivo de la unit en `~/.config/systemd/user/` y ahí se quedaba. A una persona le mostraba una pista de cómo arrancar el servicio ahora y cómo habilitarlo al iniciar sesión (`systemctl --user enable ...`). Pero muchas veces quien instala el servicio no es una persona, sino un agente de IA o la app de escritorio, y leen JSON, donde esa pista no está. Así que la unit estaba en el disco y `systemctl --user is-enabled` decía disabled. + +systemd no tiene la culpa, hace justo lo que dice la documentación: [`enable`](https://www.freedesktop.org/software/systemd/man/latest/systemctl.html#enable%20UNIT%E2%80%A6) crea los enlaces simbólicos de la sección `[Install]` y no arranca nada. Y sin el enlace el servicio no arranca después de un reinicio. + +Y esto ya lo habíamos visto. En octubre pasó lo mismo con el CLI de WhatsApp, entonces habilité su unit a mano, y en las notas quedó "cli-core debería habilitarla en install", y nadie se puso con ello antes de este reinicio. + +Ahora `server install` escribe el archivo, ejecuta `daemon-reload` y `enable`, y sigue sin arrancar nada. En Mac es lo mismo con `launchctl enable`, y el plist ya no tiene `Disabled`. `server uninstall` primero deshabilita la unit y luego borra el archivo. Y `server status` responde `starts_at_login`, así que tanto una persona como la app de escritorio ven de antemano si el servicio volverá después de un reinicio. Los tests lo cubren, pero con un reinicio de verdad todavía no lo he comprobado. + +Una unit de una copia de trabajo (una build de una rama con sus propias carpetas de configuración y datos) la dejo sin habilitar a propósito, solo se escribe en el disco. Los agentes lanzan builds así todo el rato, y no quiero para nada que una rama cualquiera arranque en cada inicio de sesión y lea mi keyring. + +## El timer llegó antes que yo + +La sincronización completa es un timer con `OnCalendar=` y [`Persistent=true`](https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html#Persistent=). Según la documentación, Persistent lanza el servicio enseguida si le habría tocado ejecutarse al menos una vez mientras el timer estaba inactivo. Para un portátil que de noche está apagado o suspendido, en principio es justo lo que hace falta. + +Los timers de usuario viven en el gestor del propio usuario, eso sí, y yo tengo linger activado. Según la [documentación de loginctl](https://www.freedesktop.org/software/systemd/man/latest/loginctl.html#enable-linger%20USER%E2%80%A6), entonces el gestor del usuario arranca con el sistema y sigue vivo después de cerrar sesión. Parece que eso es lo que pasó esa noche, y los timers recuperaron obedientemente la ejecución perdida mientras el keyring seguía bloqueado. Y el keyring donde está la sesión de Telegram solo se abre cuando yo inicio sesión. + +tg no pudo leer las claves y salió con `auth.failed`, código 4. El propio texto del error decía que probablemente el keyring no estaba accesible. Pero quien mira el código y no el texto ve un error de sesión, o sea, vuelve a iniciar sesión. La sesión no se había perdido, el keyring simplemente seguía bloqueado. Volver a iniciar sesión no lo arregla, y la ejecución de ese día se pierde igualmente. + +max falló por otra razón: "name a profile", aunque el archivo de la tarea tiene `MAX_PROFILE=default`. Resultó ser un bug en `schedule exec`. En cli-core lo corrigieron la tarde anterior, y el nuevo max con esa corrección salió esa misma mañana, antes de que nos pusiéramos a mirarlo. Yo tenía la versión anterior. + +Para el keyring separé 2 casos. Si el perfil nunca ha iniciado sesión en esta máquina, es un error de sesión real, código 4. Pero cuando un perfil que ya inició sesión no puede leer sus claves en segundo plano (serve o una ejecución del timer), devuelve `provider_unavailable`, código 12, con el motivo `credentials.unreachable`. Un comando escrito a mano sigue hablando de iniciar sesión, porque hay una persona delante que puede desbloquear el keyring. + +Y `schedule exec` (es lo que llama el timer), cuando recibe ese motivo, espera y lo intenta de nuevo. La primera pausa es de un minuto. Cada pausa siguiente dura el doble, hasta 15 minutos. Espera 12 horas como máximo. Así la ejecución de la noche espera a que yo inicie sesión por la mañana, y si en 12 horas no ha pasado, falla tal cual. + +Llegará una sola notificación, y solo si al final no salió. No se manda una por intento. Solo esperan las tareas diarias y las de una sola vez. Las que se repiten cada cierto intervalo no esperan, ya tendrán su siguiente ejecución. Y `schedule run` a mano también falla al momento, esperar 12 horas a espaldas de una persona sería raro. + +Además, a los timers ya instalados les basta con actualizar el CLI. El reintento vive en el código que llama el timer, y el archivo de la unit no cambia. + +## El código 4, que systemd tenía orden de no reiniciar nunca + +La unit de serve de tg tiene esto: + +```ini +Restart=on-failure +RestartSec=30 +RestartPreventExitStatus=4 +``` + +[`Restart=on-failure`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#Restart=) reinicia el servicio con cualquier código distinto de cero, y [`RestartPreventExitStatus=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#RestartPreventExitStatus=) impide el reinicio con los códigos de la lista, diga lo que diga `Restart=`. El 4 está en esa lista porque con una sesión revocada o perdida el servicio falla igual en cada reintento, así que reiniciarlo no tiene sentido. En max el motivo es aún más serio - un servicio que se reinicia tras un inicio de sesión rechazado volvería a iniciar sesión cada 30 segundos, y cada uno de esos inicios añadiría un dispositivo más a la cuenta de MAX. Por eso max no tiene solo el 4 en la lista, también el límite de peticiones (8) y el error del proveedor (11). + +Y max con el keyring bloqueado también salía con 4. Así que, aunque la unit hubiera estado habilitada, serve habría arrancado con el sistema, no habría leído el token, habría salido con 4, y systemd, tal como se le pidió, no lo habría vuelto a tocar hasta el siguiente reinicio, que habría terminado igual. tg ya devolvía 12 en este caso, max no. Por eso por la mañana el agente arrancó los dos servicios a mano, pero no activó el arranque automático: antes de iniciar sesión el keyring está bloqueado, y el servicio fallaría. + +Pasé max también al 12 con el motivo `credentials.unreachable`, el 12 no está en la lista, y systemd vuelve a levantar serve cada 30 segundos hasta que inicio sesión y se abre el keyring. El propio bucle de reconexión de max serve tampoco lo trata ya como un inicio de sesión rechazado. De momento esto solo funciona en Linux. En Mac un LaunchAgent con una lista de códigos sin reinicio no se reinicia nunca, así que allí el código 12 no vuelve a levantar serve. + +Había una opción más simple: colgar la unit de `graphical-session.target`, para que arranque con la sesión gráfica, cuando el keyring ya está abierto. Pero entonces el servicio no arrancaría nunca donde systemd no tiene session targets, ni en una máquina a la que solo se entra por ssh. Así que la unit se quedó en `default.target`, y el keyring bloqueado se resuelve con el código de salida. Un reinicio cada 30 segundos hasta el inicio de sesión me parece un precio razonable por un servicio que arranca en cualquier Linux, incluso sin sesión gráfica. + +## 30 segundos y una tubería cerrada + +Por la mañana el agente lanzó a mano una sincronización completa: `tg personal schedule run full-sync`. El comando esperó 30 segundos, devolvió `timeout` (código 9) y salió. Y la sincronización que había lanzado murió justo después con `write EPIPE`. Esa misma noche, antes del reinicio, una sincronización lanzada desde la app de escritorio había muerto igual: a los 18 minutos la app cerró la tubería por su lado, y la sincronización falló en la siguiente escritura. + +EPIPE es lo que pasa cuando un proceso escribe en una tubería y ya nadie la lee. El manejador de cli-core paraba cualquier comando con EPIPE y código 0. Para `tg ... | head` eso es correcto, head ya leyó sus 10 líneas, cerró la tubería y no tiene sentido seguir. Una sincronización, en cambio, dura un par de horas y escribe en el archivo, su salida es solo un log, y abandonar el trabajo porque se cerró la salida está mal. + +Ahora una sincronización (decide sola cuándo parar) y `schedule run`/`schedule exec` (esperan el trabajo que lanzaron) siguen después de EPIPE, solo que su salida ya no va a ninguna parte. Cómo terminó la ejecución sigue quedando en su registro. Los demás comandos salen con 0, como espera `| head`. Y `watch` también sale, sin nadie leyendo no tiene nada que hacer. + +Y los 30 segundos de `schedule run` ya estaban corregidos, esa corrección salió en un tg nuevo esa misma mañana. Yo tenía el anterior. O sea, 2 de los fallos de esa noche ya estaban corregidos por la mañana, solo que no en mi máquina. + +Luego el agente lanzó `tg personal messages sync --all` directamente, con la salida a un archivo, y llegó hasta el final (menos 11 chats no disponibles). De paso cerró un hueco en el archivo de Telegram: desde el 28 de octubre llegaban de 6 a 107 mensajes al día en vez de 7-10 mil. + +## Qué hago distinto ahora + +Para un CLI local-first en un escritorio, con un servicio y tareas programadas, esto es lo que hago ahora: + +- habilitar el servicio al instalarlo en vez de mostrar una pista, porque muchas veces no lo instala una persona +- tratar un keyring bloqueado al arrancar como un error temporal con su propio código +- dejar en `RestartPreventExitStatus=` solo los códigos en los que reintentar seguro que no sirve +- esperar al inicio de sesión con pausas y avisar a la persona una vez si al final no salió +- no abandonar un trabajo largo cuando se cierra la salida + +Y actualizar, sí. Las dos versiones nuevas con las correcciones salieron esa misma mañana, menos de una hora antes de que nos pusiéramos a mirarlo, así que simplemente no me dio tiempo a actualizar. + +Todo esto salió el 2 de noviembre: cli-core 0.552.0, max 0.97.0 y tg 0.114.0. Detalles en los PR: [cli-core #2401](https://github.com/WireCatLabs/cli-core/pull/2401) (habilitar la unit, reintento con el keyring bloqueado, EPIPE), [tg-cli #812](https://github.com/WireCatLabs/tg-cli/pull/812) y [max-cli #901](https://github.com/WireCatLabs/max-cli/pull/901) (código 12 en vez de 4). + +Lo que todavía no he comprobado: + +- Un reinicio con las versiones nuevas. Los tests cubren la habilitación de la unit, los reintentos con pausas y EPIPE, pero ni `server install` ni un timer se ejecutaron sobre mis units reales. +- Mac. El análisis de `launchctl print-disabled` lo comprobé contra la salida de la documentación, no en un Mac de verdad. +- Cuántos reinicios acumula serve antes del inicio de sesión y cómo se ve eso en el journal de systemd. + +Si tienes el servicio de tg o max, actualiza y ejecuta otra vez `tg server install` (o lo mismo para max). Una unit de una versión anterior no se habilita sola. Luego `server status`, y `starts_at_login` debería ser true. diff --git a/content/blog/one-reboot-broke-the-background/index.md b/content/blog/one-reboot-broke-the-background/index.md new file mode 100644 index 00000000..35e53f62 --- /dev/null +++ b/content/blog/one-reboot-broke-the-background/index.md @@ -0,0 +1,98 @@ +--- +title: What a background service needs to survive a laptop reboot +description: My laptop rebooted at night, and every background piece of a local-first CLI failed in its own way. What I had to fix so the service and the schedules on a desktop survive a reboot and a locked keyring. +date: 2026-11-02 +tags: [cli, telegram] +cover: ./cover.jpg +coverAlt: "A laptop on a dark table at night with its screen off, surrounded by small brass clockwork machines that have stopped, a closed padlock in front and a thin glass tube broken in two between them" +author: viacheslav-ptsarev +draft: false +--- + +Overnight into November 2 my laptop rebooted, and by morning nothing in the background was running. I don't know why it rebooted. The tg and max services didn't come up, the nightly full syncs failed, and a sync started by hand in the morning died right after the command that started it. Everything failed differently, and the sync code itself was never the problem. + +Background work in WireCat is 2 things. `serve` holds the connection to the messenger and writes new messages into the local archive, it's a systemd user service (a LaunchAgent on a Mac). And schedules, for example a full sync once a day at night, which is a systemd timer. Looks simple, but that night 4 different places broke, and each one gets its own section below. + +That night I was asleep and an AI agent was finishing the desktop app. Around 06:30 it noticed the services were down and started them by hand, the full syncs too. From there agents ran the commands and wrote the fixes, and I steered them and decided what to fix and how. + +## The service nobody enabled + +`tg personal server install` wrote the unit file to `~/.config/systemd/user/` and stopped there. For a person it printed a hint on how to start the service now and how to enable it at login (`systemctl --user enable ...`). But often it's an AI agent or the desktop app that installs the service, not a person, and they read JSON, which has no such hint. So the unit sat on disk and `systemctl --user is-enabled` said disabled. + +It's not systemd's fault, it does exactly what the docs say: [`enable`](https://www.freedesktop.org/software/systemd/man/latest/systemctl.html#enable%20UNIT%E2%80%A6) creates the symlinks from the `[Install]` section and starts nothing. And without the symlink the service doesn't start after a reboot. + +And we'd seen this before. In October the same thing turned up in the WhatsApp CLI, I enabled its unit by hand back then, and the notes said "cli-core should enable it on install", and nobody got to it before this reboot. + +Now `server install` writes the file, runs `daemon-reload` and `enable`, and still starts nothing. On a Mac it's the same through `launchctl enable`, and the plist no longer has `Disabled`. `server uninstall` disables the unit first and then removes the file. And `server status` reports `starts_at_login`, so both a person and the desktop app can see in advance whether the service comes back after a reboot. The tests cover this, I haven't checked it with a real reboot yet. + +I deliberately don't enable a unit from a working copy (a build from a branch with its own config and data folders), it's only written to disk. Agents run builds like that all the time, and I really don't want some branch to start at every login and read my keyring. + +## The timer got there before me + +The full sync schedule is a timer with `OnCalendar=` and [`Persistent=true`](https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html#Persistent=). The docs say Persistent triggers the service right away if it would have run at least once while the timer was inactive. For a laptop that's off or asleep at night that's pretty much what you want. + +User timers live in the user's own manager, though, and I have linger enabled. According to the [loginctl docs](https://www.freedesktop.org/software/systemd/man/latest/loginctl.html#enable-linger%20USER%E2%80%A6) the user manager then starts at boot and stays around after logout. It looks like that's what happened that night, and the timers dutifully caught up on the missed run while the keyring was still locked. And the keyring that holds the Telegram sign-in only opens when I log in. + +tg couldn't read the keys and exited with `auth.failed`, code 4. The error text itself said the keyring was probably out of reach. But anything that looks at the code and not the text sees a sign-in error, meaning sign in again. The sign-in hadn't gone anywhere, the keyring was just still locked. Signing in again doesn't fix it, and the run for that day is lost anyway. + +max failed for another reason: "name a profile", although the schedule file has `MAX_PROFILE=default`. That turned out to be a bug in `schedule exec`. cli-core fixed it the evening before, and the new max with that fix came out the same morning, before we even sat down to look. I had the previous version. + +For the keyring I split it into 2 cases. If the profile has never signed in on this machine, it's a real sign-in error, code 4. But when a profile that has signed in before can't read its keys in the background (serve or a timer run), it returns `provider_unavailable`, code 12, with the reason `credentials.unreachable`. A command typed by hand still talks about signing in, because a person is right there and can unlock the keyring. + +And `schedule exec` (that's what the timer calls), when it gets that reason, waits and tries again. The first pause is a minute. Each next pause is twice as long, up to 15 minutes. It waits 12 hours at most. So the night's run waits until I log in in the morning, and if that hasn't happened in 12 hours, it fails as it is. + +You get one notification, and only if it never worked. Not one per try. Only daily and one-off schedules wait. The ones that repeat at an interval don't, they'll have their next run anyway. And `schedule run` by hand fails at once too, waiting 12 hours behind a person's back would be weird. + +Plus timers that are already installed only need a CLI update. The retry lives in the code the timer calls, and the unit file doesn't change. + +## Exit 4, which systemd was told never to restart + +tg's serve unit file has this: + +```ini +Restart=on-failure +RestartSec=30 +RestartPreventExitStatus=4 +``` + +[`Restart=on-failure`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#Restart=) restarts the service on any non-zero exit code, and [`RestartPreventExitStatus=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#RestartPreventExitStatus=) prevents the restart for the listed codes, whatever `Restart=` says. 4 is on that list because with a revoked or missing sign-in the service fails the same way on every retry, so restarting it makes no sense. With max the reason is even more serious - a service that restarts on a refused sign-in would sign in again every 30 seconds, and each of those sign-ins would add one more device to the MAX account. That's why max has not only 4 on the list, but also rate limit (8) and provider error (11). + +And max exited with 4 on a locked keyring too. So even if the unit had been enabled, serve would have started at boot, failed to read the token, exited with 4, and systemd, as it was told, would never touch it again until the next reboot, which would end the same way. tg already returned 12 in this case, max didn't. That's why the agent started both services by hand in the morning but didn't turn on autostart: before login the keyring is locked, and the service would fail. + +I moved max to 12 with the reason `credentials.unreachable` as well, 12 isn't on the list, and systemd brings serve back every 30 seconds until I log in and the keyring opens. max serve's own reconnect loop also no longer treats this as a refused sign-in. This only works on Linux for now. On a Mac a LaunchAgent that has a list of no-restart codes doesn't restart at all, so there exit 12 won't bring serve back. + +There was a simpler option: hook the unit to `graphical-session.target`, so it starts with the graphical session, when the keyring is already open. Then the service would never start where systemd has no session targets, or on a machine people only reach over ssh. So the unit stayed in `default.target`, and the locked keyring is handled by the exit code. A restart every 30 seconds until login seems like a fair price to me for a service that starts on any Linux, even without a graphical session. + +## 30 seconds and a closed pipe + +In the morning the agent started a full sync by hand: `tg personal schedule run full-sync`. The command waited 30 seconds, returned `timeout` (code 9) and quit. And the sync it had started died right after with `write EPIPE`. That same night, before the reboot, a sync started from the desktop app had died the same way: after 18 minutes the app closed the pipe on its side, and the sync failed on its next write. + +EPIPE is what you get when a process writes to a pipe and nobody is reading it anymore. The handler in cli-core stopped any command on EPIPE with exit 0. For `tg ... | head` that's right, head has read its 10 lines, closed the pipe, and there's no point going on. A sync runs for a couple of hours and writes into the archive, though, its output is just a log, and dropping the work because the output closed is wrong. + +Now a sync (it decides by itself when to stop) and `schedule run`/`schedule exec` (they wait for work they started) keep going after EPIPE, their output just doesn't go anywhere. How the run ended is still in the run record. Other commands exit with 0, as `| head` expects. And `watch` also quits, without a reader it has nothing to do. + +And the 30 seconds in `schedule run` had already been fixed, that fix came out in a new tg the same morning. I had the previous one. So 2 of that night's failures were already fixed by morning, just not on my machine. + +Then the agent ran `tg personal messages sync --all` directly, with the output going to a file, and it went all the way (except 11 unavailable chats). It also closed a gap in the Telegram archive: since October 28 it had been getting 6 to 107 messages a day instead of 7-10 thousand. + +## What I do differently now + +For a local-first CLI on a desktop that has a service and schedules, this is what I do now: + +- enable the service on install instead of printing a hint, because often it's not a person who installs it +- treat a locked keyring at boot as a temporary error with its own code +- keep only the codes where a retry really can't help in `RestartPreventExitStatus=` +- wait for the login with pauses and tell the person once if it never worked +- don't drop long work when the output closes + +And update, yes. Both new versions with the fixes came out that same morning, less than an hour before we sat down to look, so I just hadn't had time to update. + +All of this came out on Nov 2: cli-core 0.552.0, max 0.97.0 and tg 0.114.0. Details in the PRs: [cli-core #2401](https://github.com/WireCatLabs/cli-core/pull/2401) (enabling the unit, retry on a locked keyring, EPIPE), [tg-cli #812](https://github.com/WireCatLabs/tg-cli/pull/812) and [max-cli #901](https://github.com/WireCatLabs/max-cli/pull/901) (exit 12 instead of 4). + +What I haven't checked yet: + +- A reboot with the new versions. The tests cover enabling the unit, retries with pauses and EPIPE, but neither `server install` nor a timer was run on my live units. +- Mac. I checked the parsing of `launchctl print-disabled` against the output in the docs, not on a real Mac. +- How many restarts serve racks up before login and how that looks in the systemd journal. + +If you run the tg or max service, update and run `tg server install` (or the same for max) once more. A unit from an older version won't enable itself. Then `server status`, and `starts_at_login` should be true. diff --git a/content/blog/one-reboot-broke-the-background/index.ru.md b/content/blog/one-reboot-broke-the-background/index.ru.md new file mode 100644 index 00000000..d92c5c4d --- /dev/null +++ b/content/blog/one-reboot-broke-the-background/index.ru.md @@ -0,0 +1,98 @@ +--- +title: Что нужно фоновой службе, чтобы пережить перезагрузку ноутбука +description: Ноутбук перезагрузился ночью, и каждая фоновая часть local-first CLI упала по-своему. Что пришлось починить, чтобы служба и расписания на десктопе переживали перезагрузку и закрытый keyring. +date: 2026-11-02 +tags: [cli, telegram] +cover: ./cover.jpg +coverAlt: "Ноутбук ночью на темном столе с погасшим экраном, вокруг него остановились маленькие латунные механизмы с шестеренками, впереди запертый навесной замок, а тонкая стеклянная трубка между ними разломана надвое" +author: viacheslav-ptsarev +draft: false +--- + +В ночь на 2 ноября мой ноутбук перезагрузился, и к утру в фоне не работало ничего. Почему он перезагрузился, я не знаю. Службы tg и max не поднялись, ночные полные синхронизации упали, а синк, запущенный утром руками, умер следом за командой, которая его запустила. Причем упало все по-разному, и ни разу дело не было в самом коде синка. + +Фон в WireCat - это 2 вещи. `serve` держит соединение с мессенджером и пишет новые сообщения в локальный архив, это user service в systemd (на маке LaunchAgent). И расписания, например полная синхронизация раз в сутки ночью, это systemd timer. Выглядит просто, но той ночью сломалось 4 разных места, и про каждое ниже отдельный раздел. + +Той ночью я спал, а AI-агент доделывал десктопное приложение. Около 06:30 он заметил, что службы стоят, и запустил руками и их, и полные синхронизации. Дальше команды запускали и фиксы писали агенты, а я их направлял и решал, что и как чинить. + +## Служба, которую никто не включил + +`tg personal server install` писал unit-файл в `~/.config/systemd/user/` и на этом заканчивал. Человеку он печатал подсказку, как запустить службу сейчас и как включить ее при входе в систему (`systemctl --user enable ...`). Только ставят службу часто не люди, а AI-агент или десктоп, и они читают JSON, где этой подсказки нет. В итоге unit лежал на диске, а `systemctl --user is-enabled` отвечал disabled. + +systemd тут ни при чем, он делает ровно то, что написано в доках: [`enable`](https://www.freedesktop.org/software/systemd/man/latest/systemctl.html#enable%20UNIT%E2%80%A6) создает симлинки по секции `[Install]` и при этом ничего не запускает. А без симлинка служба после перезагрузки не стартует. + +И мы это уже видели. В октябре то же самое нашлось у WhatsApp CLI, я тогда включил его unit руками, а в заметках осталось "cli-core должен включать сам при install", и до этой перезагрузки до него так никто и не дошел. + +Теперь `server install` пишет файл, делает `daemon-reload` и `enable` и по-прежнему ничего не запускает. На маке то же самое через `launchctl enable`, и в plist больше нет `Disabled`. `server uninstall` сначала выключает unit, потом удаляет файл. А `server status` отвечает `starts_at_login`, так что и человек, и десктоп заранее видят, поднимется ли служба после перезагрузки. Это покрыто тестами, а настоящей перезагрузкой я это пока не проверял. + +Unit из рабочей копии (сборка из ветки со своими папками конфига и данных) я специально не включаю, он только записывается. Агенты гоняют такие сборки постоянно, и мне совсем не надо, чтобы какая-то ветка стартовала при каждом входе и читала мой keyring. + +## Таймер успел раньше меня + +Расписание полного синка - это timer с `OnCalendar=` и [`Persistent=true`](https://www.freedesktop.org/software/systemd/man/latest/systemd.timer.html#Persistent=). По докам Persistent запускает службу сразу, если она должна была сработать хотя бы раз, пока таймер был неактивен. По идее для ноутбука, который ночью выключен или спит, это то что надо. + +Только таймеры пользователя живут в его user manager, а у меня включен linger. По [докам loginctl](https://www.freedesktop.org/software/systemd/man/latest/loginctl.html#enable-linger%20USER%E2%80%A6) тогда user manager поднимается при загрузке и не умирает после выхода. Судя по всему, так было и той ночью, и таймеры честно догнали пропущенный запуск, пока keyring еще был закрыт. А keyring, где лежит вход в Telegram, открывается только когда я вхожу в систему. + +tg не смог прочитать ключи и ответил `auth.failed`, код 4. В самом тексте ошибки было написано, что keyring, скорее всего, недоступен. Но кто смотрит на код, а не на текст, видит ошибку входа, т.е. залогиньтесь заново. А вход никуда не делся, keyring просто еще закрыт. Новый вход проблему не решает, и запуск за этот день все равно потерян. + +max упал по другой причине: "name a profile", хотя в файле расписания стоит `MAX_PROFILE=default`. Это оказался баг в `schedule exec`, в cli-core его исправили накануне вечером, а новый max с этим фиксом вышел в то же утро, еще до того, как мы сели разбираться. У меня стояла предыдущая версия. + +Для keyring я развел 2 случая. Если профиль на этой машине ни разу не входил, это настоящая ошибка входа, код 4. А профиль, который уже входил, но сейчас не может прочитать ключи, в фоне (serve или запуск по таймеру) отвечает `provider_unavailable`, код 12, с причиной `credentials.unreachable`. Команда, набранная руками, по-прежнему говорит про вход, потому что человек рядом и может открыть keyring сам. + +А `schedule exec` (его и вызывает таймер), когда получает эту причину, ждет и пробует снова. Первая пауза - минута. Потом каждая пауза в 2 раза длиннее, но не больше 15 минут. Всего он ждет не дольше 12 часов. Так ночной запуск дожидается, пока я утром войду. Если за 12 часов не дождался, падает как есть. + +Уведомление придет только одно, если в итоге так и не получилось. На каждую попытку оно не шлется. Ждут только ежедневные и разовые расписания. Те, что повторяются через интервал, не ждут, у них и так будет следующий запуск. И `schedule run` руками тоже падает сразу, ждать за спиной у человека 12 часов странно. + +Плюс уже установленным таймерам хватит обновления CLI. Повтор живет в коде, который таймер вызывает, и unit-файл менять не надо. + +## Код 4, который systemd просили не перезапускать + +У serve tg в unit-файле стоит вот что: + +```ini +Restart=on-failure +RestartSec=30 +RestartPreventExitStatus=4 +``` + +[`Restart=on-failure`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#Restart=) перезапускает службу на любом ненулевом коде, а [`RestartPreventExitStatus=`](https://www.freedesktop.org/software/systemd/man/latest/systemd.service.html#RestartPreventExitStatus=) отменяет перезапуск для перечисленных кодов, что бы ни стояло в `Restart=`. А 4 в этом списке потому, что с отозванным или пропавшим входом служба на каждом повторе падает одинаково, и перезапускать ее бессмысленно. У max причина еще серьезнее - служба, которая перезапускается на отказанном входе, логинилась бы заново каждые 30 секунд, и каждый такой вход добавлял бы в аккаунт MAX еще одно устройство. Поэтому у max в этом списке не только 4, но и rate limit (8) и ошибка провайдера (11). + +И вот max на закрытом keyring тоже отвечал 4. Так что даже если бы unit был включен, serve стартовал бы при загрузке, не прочитал токен, вышел с 4, и systemd, как ему и сказали, больше бы его не трогал до следующей перезагрузки, а она закончилась бы так же. tg в этом случае уже отвечал 12, а max нет. Поэтому агент утром запустил обе службы руками, а автозапуск включать не стал: до входа keyring закрыт, и служба упала бы. + +max я тоже перевел на 12 с причиной `credentials.unreachable`, 12 в списке нет, и systemd поднимает serve каждые 30 секунд, пока я не войду и keyring не откроется. Собственный цикл переподключения в max serve тоже больше не считает это отказом во входе. Но это пока работает только на Linux. На маке LaunchAgent, если у него есть список кодов без перезапуска, не перезапускается вообще, так что там код 12 serve не поднимет. + +Был вариант проще: вешать unit на `graphical-session.target`, чтобы он стартовал вместе с графической сессией, когда keyring уже открыт. Но тогда служба вообще не поднимется там, где у systemd нет session targets, и на машине, куда заходят только по ssh. Поэтому unit остался в `default.target`, а закрытый keyring решается кодом выхода. Рестарт раз в 30 секунд до входа, мне кажется, нормальная цена за то, что служба стартует на любом Linux, даже без графической сессии. + +## 30 секунд и закрытый пайп + +Утром агент запустил полный синк руками: `tg personal schedule run full-sync`. Команда подождала 30 секунд, ответила `timeout` (код 9) и вышла. А синк, который она запустила, умер следом с `write EPIPE`. Той же ночью, еще до перезагрузки, так же умер синк, запущенный из десктопа: через 18 минут работы десктоп закрыл пайп со своей стороны, и синк упал на следующей записи. + +EPIPE - это когда процесс пишет в пайп, а читать его уже некому. Обработчик в cli-core на EPIPE останавливал любую команду с кодом 0. Для `tg ... | head` это правильно, head прочитал свои 10 строк, закрыл пайп, и продолжать незачем. А синк идет пару часов и пишет в архив, вывод для него просто лог, и бросать работу из-за закрытого вывода нельзя. + +Теперь синк (он сам решает, когда остановиться) и `schedule run`/`schedule exec` (они ждут работу, которую запустили) после EPIPE работают дальше, просто их вывод уже никуда не пишется. Чем закончился запуск, все равно видно в записи о запуске. Остальные команды выходят с 0, как ждет `| head`. И `watch` тоже выходит, ему без читателя делать нечего. + +А 30 секунд в `schedule run` были уже исправлены, этот фикс вышел в новой версии tg тем же утром. У меня стояла предыдущая. Т.е. 2 поломки этой ночи к утру уже были исправлены, просто не у меня. + +Потом агент запустил `tg personal messages sync --all` напрямую, с выводом в файл, и он дошел до конца (кроме 11 недоступных чатов). Заодно он закрыл пробел в архиве Telegram: с 28 октября туда приходило от 6 до 107 сообщений в день вместо 7-10 тысяч. + +## Что я теперь делаю по-другому + +Для local-first CLI на десктопе, у которого есть служба и расписания, я теперь делаю так: + +- включать службу при установке, а не печатать подсказку, потому что ставит ее часто не человек +- считать закрытый keyring при загрузке временной ошибкой со своим кодом +- в `RestartPreventExitStatus=` держать только коды, на которых повтор точно не поможет +- ждать входа с паузами и написать человеку один раз, если так и не вышло +- не бросать долгую работу, когда вывод закрыли + +И обновляться, да. Обе новые версии с готовыми фиксами вышли тем же утром, меньше чем за час до того, как мы сели разбираться, так что обновиться я просто не успел. + +Все это вышло 2 ноября: cli-core 0.552.0, max 0.97.0 и tg 0.114.0. Подробности в PR: [cli-core #2401](https://github.com/WireCatLabs/cli-core/pull/2401) (включение unit, повтор на закрытом keyring, EPIPE), [tg-cli #812](https://github.com/WireCatLabs/tg-cli/pull/812) и [max-cli #901](https://github.com/WireCatLabs/max-cli/pull/901) (код 12 вместо 4). + +Что я пока не проверил: + +- Перезагрузку с новыми версиями. Тесты покрывают включение unit, повторы с паузами и EPIPE, но на моих живых unit-ах не запускались ни `server install`, ни таймер. +- Мак. Разбор `launchctl print-disabled` я сверял с выводом из доков, на живом Mac не запускал. +- Сколько рестартов serve набирает до входа и как это выглядит в журнале systemd. + +Если у вас стоит служба tg или max, обновитесь и выполните `tg <профиль> server install` (или то же для max) еще раз. Unit от старой версии сам не включится. Потом `server status`, в `starts_at_login` должно быть true. diff --git a/content/blog/wirecat-desktop-0-8/cover.es.jpg b/content/blog/wirecat-desktop-0-8/cover.es.jpg new file mode 100644 index 00000000..e91e7aea Binary files /dev/null and b/content/blog/wirecat-desktop-0-8/cover.es.jpg differ diff --git a/content/blog/wirecat-desktop-0-8/cover.jpg b/content/blog/wirecat-desktop-0-8/cover.jpg new file mode 100644 index 00000000..39368229 Binary files /dev/null and b/content/blog/wirecat-desktop-0-8/cover.jpg differ diff --git a/content/blog/wirecat-desktop-0-8/cover.ru.jpg b/content/blog/wirecat-desktop-0-8/cover.ru.jpg new file mode 100644 index 00000000..a333afc4 Binary files /dev/null and b/content/blog/wirecat-desktop-0-8/cover.ru.jpg differ diff --git a/content/blog/wirecat-desktop-0-8/index.es.md b/content/blog/wirecat-desktop-0-8/index.es.md new file mode 100644 index 00000000..dbc618e6 --- /dev/null +++ b/content/blog/wirecat-desktop-0-8/index.es.md @@ -0,0 +1,85 @@ +--- +title: "WireCat Desktop 0.8: herramientas nuevas sin actualizar la app, y Permisos ahora dice qué hace de verdad Preguntar antes" +description: "Las herramientas oficiales nuevas de WireCat aparecen en la app sin actualizarla, y la sección Permisos ahora dice que a un agente conectado por MCP no se le pregunta en Preguntar antes. Además el catálogo tiene 6 herramientas nuevas, entre ellas amoCRM, Yandex Disk y HubSpot, tu modelo de IA ordena tu correo y en Linux las actualizaciones llegan por apt." +date: 2026-11-24 +tags: [release-notes, security] +cover: ./cover.es.jpg +coverAlt: "WireCat Desktop 0.8 junto a la página Herramientas en modo oscuro: Telegram y WhatsApp están instalados, y los detalles de WhatsApp están abiertos con la cuenta personal marcada como sesión iniciada, los botones Iniciar sesión aquí y Abrir terminal, y el comando para instalarlo desde un terminal." +author: viacheslav-ptsarev +draft: false +--- + +WireCat Desktop instala las herramientas de WireCat, inicia sesión por ti y le da a tu agente de IA tus chats, correo, reuniones, documentos y notas. Todo queda en tu ordenador. + +Después de la 0.7 saqué 5 versiones pequeñas en una semana, de la 0.7.1 a la 0.7.5, y no escribí una nota para ninguna, así que aquí va todo junto. En esa semana el catálogo ganó 6 herramientas nuevas, tu modelo de IA ahora ordena tu correo y en Linux las actualizaciones llegan por apt. + +La propia 0.8 trae dos cosas principales. Las herramientas oficiales nuevas llegan desde wirecat.dev sin actualizar la app. Y la sección Permisos ahora dice tal cual que Preguntar antes no frena a un agente por MCP. + +## Herramientas nuevas sin una app nueva + +La app ahora descarga una vez al día una lista de herramientas oficiales desde wirecat.dev, y una herramienta nueva aparece en la página Herramientas con su icono y sus textos en tu idioma, si la lista los trae. Antes una herramienta nueva llegaba a la app solo con una versión nueva de Desktop, y sin ella solo podías añadirla como herramienta propia, en inglés y con un icono genérico. + +La lista está firmada, y la app solo la guarda si la firma coincide con la clave que lleva dentro. Una lista nueva se aplica desde el siguiente arranque, para que la página no cambie delante de ti. Sin red la app usa la última lista verificada que guardó, aunque sea antigua, y si no hay ninguna, la lista que lleva dentro. En la lista solo entra un paquete `@wirecat` de un repositorio de WireCatLabs, y al instalar la app sigue comprobando en npm que el paquete lo construyó el propio GitHub Actions de la herramienta. + +En las herramientas incluidas la lista solo cambia los textos y el icono, y los comandos siguen siendo los probados en el catálogo de la app. Cuando comparé los manifiestos de los 17 CLI incluidos con el catálogo, salieron 60 diferencias. La mayoría son solo otra redacción, pero en Zoom, por ejemplo, el catálogo tiene un comando de sincronización y el manifiesto otro, así que por ahora las herramientas incluidas no toman sus comandos de la lista. + +## Preguntar antes no frena a un agente por MCP + +En la sección Permisos de cada herramienta, cada grupo de comandos tiene 4 niveles: **Permitir**, **Preguntar antes**, **Solo lectura** y **Bloquear**. Preguntar antes solo funciona en una terminal. Por MCP no hay a quién preguntar, y el cambio del agente simplemente se ejecuta. Es así desde el principio, y la 0.8 no lo cambia. + +Solo cambió el texto - antes decía que por MCP decide la app del agente, y se leía como si alguien te fuera a preguntar igualmente. Ahora debajo de cada grupo y comando en Preguntar antes, y en el diálogo donde confirmas el cambio, dice que los agentes por MCP hacen estos cambios sin preguntarte. Para pararlos, elige **Solo lectura** o **Bloquear**. + +En HubSpot esto salió con el borrado RGPD de un contacto. Elimina el contacto con todo lo que tiene y bloquea su dirección, y estaba en Preguntar antes. Por MCP un agente habría borrado un contacto sin preguntar a nadie, así que en [hubspot 0.5.0](https://github.com/WireCatLabs/hubspot-cli/releases/tag/v0.5.0) está bloqueado por defecto. Los borrados normales se quedaron en Preguntar antes. + +## 6 herramientas nuevas en el catálogo + +En cada una inicias sesión en la ventana de la app, y ahí mismo están los pasos para sacar el token o la contraseña. + +- **amoCRM y Kommo.** Inicia sesión con la dirección de la cuenta y un token de larga duración, y WireCat copia a tu ordenador tus negociaciones con sus contactos y empresas. Tú y tu agente veis qué cambió en ellas. ([docs de amo](/es/docs/amo)) +- **Yandex Disk.** Sacas el token en las propias páginas de Yandex y eliges carpetas por su ruta en el Disco, luego WireCat las copia igual que Google Drive. También lee escaneos e imágenes, por defecto con tesseract en tu ordenador. ([docs de ydisk](/es/docs/ydisk)) +- **Attio.** Las negociaciones, personas y empresas se copian a tu ordenador, y puedes encontrar una negociación por el sentido de sus notas. феррара escrito en cirílico encuentra Ferrara. ([docs de attio](/es/docs/attio)) +- **HubSpot.** HubSpot tiene un único cupo diario de peticiones para todas las apps de la cuenta, y cuando se acaba, hubspot dice enseguida cuándo vuelve en lugar de seguir machacando la API. ([docs de hubspot](/es/docs/hubspot)) +- **Linear.** Issues, proyectos, comentarios y documentos. ([docs de linear](/es/docs/linear)) +- **WordPress.** Escribes la dirección del sitio, el nombre de usuario y la contraseña de aplicación en un solo formulario, y la contraseña llega a la herramienta por su entrada estándar, nunca como argumento de un comando. Una entrada nueva de un agente siempre es un borrador, pero publicar está en Preguntar antes, así que un agente por MCP publica sin preguntar. Publicar tiene su propia clave, así que si no quieres eso, ponla en Bloquear y los borradores siguen funcionando. ([docs de wordpress](/es/docs/wordpress)) + +Slack no está en esta lista. [slk](/es/docs/slk) 0.1.0 salió el 24 de noviembre y funciona desde la terminal, y Slack llegará a Desktop en una versión posterior. + +## Tu modelo de IA ordena tu correo + +Resúmenes tiene una pestaña nueva, **Bandeja**. El modelo de IA que elegiste en Ajustes ordena el correo nuevo de todas las cuentas en 3 grupos: **Necesita respuesta**, **Para leer** y **Puede esperar**. Cada hilo muestra por qué el modelo lo puso ahí, y un clic en la fila abre el hilo. Necesita mail 0.35, y el remitente se ve desde la 0.36. + +Si el modelo funciona fuera de tu ordenador y memo está configurado para preguntar antes de enviar, WireCat primero muestra cuántos correos y tokens saldrían y más o menos cuánto costaría, y pregunta. Desde mail 0.36 la pregunta llega en tu idioma, y después de ordenar ves qué modelo trabajó y cuánto costó, lo que no llega a un céntimo sale como < $0.01. Las reglas de correo pasaron a su propio diálogo, con búsqueda y páginas. + +Si el modelo no está en tu ordenador, una ordenación programada envía tu correo a su proveedor sin preguntar. + +## Ve a quién unió un agente + +Un agente ahora puede unir por su cuenta dos entradas de una misma persona, cuando dos fuentes distintas tienen para ella un móvil personal o una dirección que nadie más tiene. Para un número, al menos una de las fuentes tiene que ser un mensajero o una llamada. La página Contactos muestra estas uniones en una lista aparte. Ves qué agente lo hizo, con qué número o dirección y por qué, y puedes deshacerlo si se equivocó. + +Esto lo hace memo, la herramienta de WireCat que enlaza a las personas de todas tus fuentes, y necesita memo 0.141.0. Si no quieres que un agente una personas por su cuenta, pon `"agent_merges": "propose"` en [los ajustes de memo](/es/docs/memo/configuration), y cada unión te esperará. + +Una coincidencia que espera tu decisión ahora dice por qué no se unió sola, por ejemplo el número resultó ser la línea de oficina de una empresa. Cada lado de una coincidencia muestra sus últimos mensajes o llamadas, su empresa y su negociación. + +## Actualizaciones por apt en Linux + +Desde la 0.7.4 el .deb añade el repositorio apt de WireCat, apt.wirecat.dev. Las versiones nuevas llegan por el Actualizador de software o con `sudo apt update && sudo apt install wirecat`, y la ventana de actualización de la app ahora lo dice y no descarga el paquete. + +El App Center de Ubuntu no mostraba el desarrollador de un .deb descargado, solo lo muestra para un paquete de un repositorio, así que tuve que montar el nuestro. App Center lee el nombre del desarrollador solo de la clave antigua DeveloperName, que `appstreamcli convert` ya no escribe. Y una Ubuntu 26.04 Desktop recién instalada no trae curl, así que los comandos para añadir el repositorio a mano en apt.wirecat.dev usan wget. Desde la 0.7.5 App Center además muestra la fecha de la versión en lugar de Unknown. + +## Detalles + +- **WhatsApp dice lo frescos que están sus datos.** WhatsApp no tiene sincronización completa, los mensajes nuevos llegan solo mientras funciona su servicio en segundo plano. La cuenta dice **En vivo** mientras el servicio está conectado, y **Datos al 9:05** cuando no. Necesita whatsapp-cli 0.46.0. +- **Tus propias herramientas inician sesión en la ventana.** Una herramienta que añadiste por su nombre de npm, como beeline (llamadas de la centralita de Beeline), puede definir sus propios pasos de inicio de sesión, y pegas el token en la ventana, sin terminal. Con la versión nueva de la herramienta su menú de cuenta tiene **Cerrar sesión** y **Quitar cuenta**. WireCat comprueba que estos pasos solo ejecutan comandos de la propia herramienta, y te pregunta antes de usarlos. +- **Ajustes en dos pestañas.** Una para la app y otra para cada herramienta. Ahí también eliges cuánto correo sincronizar. +- **Cambia el id de un perfil.** El menú de la cuenta tiene **Cambiar el id del perfil**, y la sesión, los ajustes y los datos pasan al id nuevo. Funciona cuando la versión nueva de la propia herramienta lo admite. +- **Google Calendar se sincroniza desde la app.** También muestra cuándo lo hizo por última vez. +- **Elige páginas y bases de datos de Notion.** WireCat copia las que elegiste, igual que las carpetas de Google Drive. Los pasos para iniciar sesión ya están en ruso y en español, y llevan a la página nueva de tokens de Notion. +- **El resumen matutino del CRM está en Resúmenes.** Primero las negociaciones ganadas y perdidas, luego las tareas vencidas, y cada negociación abre su propia ficha. +- **Resúmenes, tareas y documentos salen de la beta.** +- **La biblioteca de cookies de la app está actualizada**, por el aviso [RUSTSEC-2026-0594](https://rustsec.org/advisories/RUSTSEC-2026-0594.html). + +## Cómo conseguirla + +Si tienes la 0.7, la app te ofrecerá la actualización, y si instalaste un .deb de la 0.7.4 o posterior, llega por el Actualizador de software. ¿Eres nuevo? Descarga WireCat en [wirecat.dev/es/download](/es/download) para macOS, Windows o Linux. La [guía de Desktop](/es/docs/desktop) cubre cada página, y cada versión de la 0.7.1 a la 0.8.0 tiene sus propias [notas de la versión en GitHub](https://github.com/WireCatLabs/wirecat-desktop/releases). + +Las ideas de qué hacer después van en [la página de ideas](/es/ideas), y las preguntas en [Discord](https://discord.gg/DebENqbRrJ) o en [GitHub](https://github.com/WireCatLabs/wirecat-desktop/issues). diff --git a/content/blog/wirecat-desktop-0-8/index.md b/content/blog/wirecat-desktop-0-8/index.md new file mode 100644 index 00000000..4e0b072d --- /dev/null +++ b/content/blog/wirecat-desktop-0-8/index.md @@ -0,0 +1,85 @@ +--- +title: "WireCat Desktop 0.8: new tools without an app update, and Permissions now say what Ask first really does" +description: "New official WireCat tools show up in the app without an app update, and the Permissions section now says that an agent connected over MCP is not asked at Ask first. The catalog also has 6 new tools, among them amoCRM, Yandex Disk and HubSpot, your AI model sorts your mail, and Linux updates come through apt." +date: 2026-11-24 +tags: [release-notes, security] +cover: ./cover.jpg +coverAlt: "WireCat Desktop 0.8 next to the Tools page in dark mode: Telegram and WhatsApp are installed, and WhatsApp's details are open with the personal account marked signed in, the Sign in here and Open terminal buttons, and the command to install it from a terminal." +author: viacheslav-ptsarev +draft: false +--- + +WireCat Desktop installs the WireCat tools, signs you in and gives your AI agent your chats, mail, meetings, documents and notes. It all stays on your computer. + +After 0.7 I shipped 5 small versions in a week, 0.7.1 to 0.7.5, and didn't write a post for any of them, so here it all is at once. In that week the catalog got 6 new tools, your AI model now sorts your mail, and on Linux updates come through apt. + +0.8 itself brings two main things. New official tools come from wirecat.dev without an app update. And the Permissions section now says straight out that Ask first doesn't stop an agent over MCP. + +## New tools without a new app + +The app now fetches a list of official tools from wirecat.dev once a day, and a new tool shows up on the Tools page with its icon and text in your language, when the list has them. Before, a new tool reached the app only with a new Desktop version, and without one you could only add it as your own tool, in English and with a generic icon. + +The list is signed, and the app keeps it only when the signature matches the key built into the app. A new list takes effect from the next start, so the page doesn't change in front of you. With no network the app uses the last verified list it saved, even an old one, and if there is none, the list built into the app. Only a `@wirecat` package from a WireCatLabs repository gets into the list, and at install the app still checks on npm that the package was built by the tool's own GitHub Actions. + +For the built-in tools the list changes only the text and the icon, and the commands stay the ones tested in the app's catalog. When I compared the manifests of the 17 built-in CLIs with the catalog, I found 60 differences. Most are just different wording, but for Zoom, for example, the catalog has one sync command and the manifest another, so for now the built-in tools don't take their commands from the list. + +## Ask first doesn't stop an agent over MCP + +In each tool's Permissions section every group of commands has 4 levels: **Allow**, **Ask first**, **Read only** and **Block**. Ask first works only in a terminal. For an agent connected over MCP there's nobody to ask, and the agent's change just runs. It has been like this from the start, and 0.8 doesn't change it. + +Only the text changed - it used to say that over MCP the agent's app decides, and that read as if someone would still ask you. Now under every group and command set to Ask first, and in the dialog where you confirm the choice, it says that these agents make these changes without asking you. To stop them, choose **Read only** or **Block**. + +In HubSpot this came up with the GDPR erase of a contact. It deletes the contact with everything on it and blocks its address, and it was set to Ask first. Over MCP the agent would have erased a contact without asking anyone, so in [hubspot 0.5.0](https://github.com/WireCatLabs/hubspot-cli/releases/tag/v0.5.0) it's blocked by default. Ordinary deletes stayed at Ask first. + +## 6 new tools in the catalog + +You sign in to each one in the app window, with the steps for where to get the token or password right there. + +- **amoCRM and Kommo.** Sign in with the account's address and a long-lived token, and WireCat copies your deals with their contacts and companies to your computer. You and your agent see what changed in them. ([amo docs](/en/docs/amo)) +- **Yandex Disk.** You get the token on Yandex's own pages and pick folders by their path on the Disk, then WireCat copies them the same way as Google Drive. It reads scans and pictures too, by default with tesseract on your computer. ([ydisk docs](/en/docs/ydisk)) +- **Attio.** Deals, people and companies are copied to your computer, and you can find a deal by the meaning of its notes. феррара typed in Cyrillic finds Ferrara. ([attio docs](/en/docs/attio)) +- **HubSpot.** HubSpot has one daily request limit shared by every app on the account, and when it's spent, hubspot says right away when it comes back instead of hammering the API. ([hubspot docs](/en/docs/hubspot)) +- **Linear.** Issues, projects, comments and documents. ([linear docs](/en/docs/linear)) +- **WordPress.** You enter the site address, user name and application password in one form, and the password goes to the tool over stdin, never as a command argument. A new post from an agent is always a draft, but publishing is set to Ask first, so an agent over MCP publishes without asking. Publishing has its own key, so if you don't want that, set it to Block and the drafts stay. ([wordpress docs](/en/docs/wordpress)) + +Slack isn't on this list. [slk](/en/docs/slk) 0.1.0 came out on Nov 24 and works from the terminal, and Slack comes to Desktop in a later version. + +## Your AI model sorts your mail + +Digests has a new **Inbox** tab. The AI model you picked in Settings sorts the new mail of every account into 3 groups: **Needs an answer**, **To read** and **Can wait**. Each thread shows why the model put it there, and clicking the row opens the thread. It needs mail 0.35, and the sender shows from 0.36. + +If the model runs outside your computer and memo is set to ask before sending, WireCat first shows how many emails and tokens would go out and roughly what it would cost, and asks. Since mail 0.36 the question comes in your language, and after a sort you see which model ran and what it cost, anything under a cent shows as < $0.01. Mail rules moved to their own dialog, with search and pages. + +If the model isn't on your computer, a scheduled sort sends your mail to its provider without asking. + +## See who an agent joined + +An agent can now join two entries for one person by itself, when two different sources have a personal mobile number or address for them that nobody else has. For a phone number, at least one of the sources must be a messenger or a call. The Contacts page lists these joins separately. You see which agent did it, by which number or address and why, and you can undo it if the agent got it wrong. + +This is done by memo, the WireCat tool that links people across all your sources, and it needs memo 0.141.0. If you don't want an agent to join people by itself, set `"agent_merges": "propose"` in [memo's settings](/en/docs/memo/configuration), and every join waits for you. + +A match that waits for your decision now says why it wasn't joined on its own, for example the number turned out to be a company's office line. Each side of a match shows its last messages or calls, its company and its deal. + +## Updates through apt on Linux + +Since 0.7.4 the .deb adds WireCat's apt repository, apt.wirecat.dev. New versions arrive in Software Updater or with `sudo apt update && sudo apt install wirecat`, and the update window in the app now says so and doesn't download the package. + +Ubuntu's App Center showed no developer for a downloaded .deb, it shows one only for a package from a repository, so I had to set up our own. App Center reads the developer's name only from the old DeveloperName key, which `appstreamcli convert` no longer writes. And a fresh Ubuntu 26.04 Desktop has no curl, so the commands to add the repository by hand on apt.wirecat.dev use wget. Since 0.7.5 App Center also shows the release date instead of Unknown. + +## Small things + +- **WhatsApp shows how fresh its data is.** WhatsApp has no full sync, new messages arrive only while its background service runs. The account says **Live** while the service is connected, and **Fresh as of 9:05 AM** when it's not. It needs whatsapp-cli 0.46.0. +- **Your own tools sign in inside the window.** A tool you added by its npm name, such as beeline (Beeline cloud PBX calls), can set its own sign-in steps, and you paste the token right in the window, with no terminal. With the tool's new version its account menu has **Sign out** and **Remove account**. WireCat checks that these steps run only the tool's own commands, and asks you before it uses them. +- **Settings in two tabs.** One for the app, the other for each tool. That's also where you choose how much mail to sync. +- **Change a profile id.** The account menu has **Change profile id**, and the sign-in, settings and data move to the new id. It works once the tool's own new version supports it. +- **Google Calendar syncs from the app.** It also shows when it last did. +- **Choose Notion pages and databases.** WireCat copies the ones you chose, the same way as Google Drive folders. The sign-in steps are now in Russian and Spanish too, and point to Notion's new token page. +- **The morning CRM digest is in Digests.** Deals won and lost come first, then overdue tasks, and each deal opens its own card. +- **Digests, tasks and documents are out of beta.** +- **The cookie library inside the app is updated**, for the advisory [RUSTSEC-2026-0594](https://rustsec.org/advisories/RUSTSEC-2026-0594.html). + +## Get it + +If you have 0.7, the app will offer the update, and if you installed a .deb of 0.7.4 or later, it comes through Software Updater. New here? Download WireCat from [wirecat.dev/download](/en/download) for macOS, Windows or Linux. The [Desktop guide](/en/docs/desktop) covers each page, and every version from 0.7.1 to 0.8.0 has its own [release notes on GitHub](https://github.com/WireCatLabs/wirecat-desktop/releases). + +Ideas for what to build next go on [the ideas page](/en/ideas), and questions to [Discord](https://discord.gg/DebENqbRrJ) or [GitHub](https://github.com/WireCatLabs/wirecat-desktop/issues). diff --git a/content/blog/wirecat-desktop-0-8/index.ru.md b/content/blog/wirecat-desktop-0-8/index.ru.md new file mode 100644 index 00000000..674a9ca7 --- /dev/null +++ b/content/blog/wirecat-desktop-0-8/index.ru.md @@ -0,0 +1,85 @@ +--- +title: "WireCat Desktop 0.8: новые инструменты без обновления приложения и честная подпись у уровня Спрашивать" +description: "Новые официальные инструменты WireCat появляются в приложении без его обновления, а раздел Разрешения теперь пишет, что агент через MCP на уровне Спрашивать ничего не спрашивает. Еще в каталоге 6 новых инструментов, среди них amoCRM, Яндекс Диск и HubSpot, почту разбирает модель, а на Linux обновления идут через apt." +date: 2026-11-24 +tags: [release-notes, security] +cover: ./cover.ru.jpg +coverAlt: "WireCat Desktop 0.8 рядом со страницей Инструменты в темной теме: Telegram, MAX и WhatsApp установлены, у WhatsApp открыты аккаунт personal с отметкой вход выполнен, кнопки Войти здесь и Открыть терминал и команда установки из терминала." +author: viacheslav-ptsarev +draft: false +--- + +WireCat Desktop ставит инструменты WireCat, входит в ваши аккаунты и дает вашему ИИ-агенту чаты, почту, встречи, документы и заметки. Все это хранится на вашем компьютере. + +После 0.7 я за неделю выпустил 5 маленьких версий, с 0.7.1 по 0.7.5, и ни к одной не написал заметку, так что здесь все сразу. За эту неделю в каталоге появилось 6 новых инструментов, почту теперь разбирает модель ИИ, а на Linux обновления идут через apt. + +В самой 0.8 главного две вещи. Новые официальные инструменты приходят с wirecat.dev без обновления приложения. А раздел Разрешения теперь пишет как есть, что уровень Спрашивать агента через MCP не останавливает. + +## Новые инструменты без нового приложения + +Приложение теперь раз в день забирает с wirecat.dev список официальных инструментов, и новый инструмент появляется на странице Инструменты со своим значком и текстами на вашем языке, если они есть в списке. До этого он попадал в приложение только с новой версией Desktop, а без нее его можно было добавить только как свой инструмент, по-английски и с общим значком. + +Список подписан, и приложение сохраняет его, только если подпись сходится с ключом, встроенным в само приложение. Новый список начинает работать со следующего запуска, чтобы страница не менялась у вас на глазах. Без сети приложение берет последний проверенный список, который сохранило раньше, даже старый, а если такого нет, то список, встроенный в приложение. В список попадает только пакет `@wirecat` из репозитория WireCatLabs, и при установке приложение по-прежнему проверяет по npm, что пакет собрал GitHub Actions самого инструмента. + +У встроенных инструментов список меняет только тексты и значок, а команды остаются те, что проверены в каталоге приложения. Когда я сравнил манифесты 17 встроенных CLI с каталогом, нашлось 60 расхождений. Большая часть - просто разные формулировки, но у Zoom, например, команда синка в каталоге одна, а в манифесте другая, поэтому команды из списка для встроенных инструментов пока не берутся. + +## Спрашивать не останавливает агента через MCP + +В разделе Разрешения у каждого инструмента 4 уровня для каждой группы команд: **Разрешить**, **Спрашивать**, **Только чтение** и **Запретить**. Спрашивать работает только в терминале. Через MCP спросить некого, и изменение агента просто выполняется. Так было с самого начала, 0.8 это не меняет. + +Поменялся только текст - там было написано, что через MCP решает приложение агента, и это читалось так, будто кто-то вас все-таки спросит. Теперь под каждой группой и командой с уровнем Спрашивать и в окне, где вы подтверждаете выбор, написано, что агенты через MCP вносят эти изменения без вопросов. Чтобы их остановить, выберите **Только чтение** или **Запретить**. + +В HubSpot это вылезло на удалении контакта по GDPR. Оно стирает контакт вместе со всем, что на нем висит, и блокирует его адрес, а стояло на уровне Спрашивать. Через MCP агент стер бы контакт и никого не спросил, поэтому в [hubspot 0.5.0](https://github.com/WireCatLabs/hubspot-cli/releases/tag/v0.5.0) оно по умолчанию запрещено. Обычные удаления остались на Спрашивать. + +## 6 новых инструментов в каталоге + +Каждый входит в аккаунт в окне приложения, и там же шаги, где взять токен или пароль. + +- **amoCRM и Kommo.** Войдите по адресу аккаунта и долгосрочному токену, и WireCat скопирует на ваш компьютер ваши сделки с их контактами и компаниями. Вы с агентом видите, что в них поменялось. ([доки amo](/ru/docs/amo)) +- **Яндекс Диск.** Токен берете на страницах самого Яндекса, а папки выбираете по пути на Диске, дальше WireCat копирует их так же, как Google Drive. Сканы и картинки он тоже читает, по умолчанию через tesseract на вашем компьютере. ([доки ydisk](/ru/docs/ydisk)) +- **Attio.** Сделки, люди и компании копируются на ваш компьютер, и сделку можно найти по смыслу ее заметок. Если набрать феррара по-русски, найдется Ferrara. ([доки attio](/ru/docs/attio)) +- **HubSpot.** У HubSpot один дневной лимит запросов на все приложения аккаунта, и когда он кончился, hubspot сразу говорит, когда лимит вернется, а не долбит API дальше. ([доки hubspot](/ru/docs/hubspot)) +- **Linear.** Задачи, проекты, комментарии и документы. ([доки linear](/ru/docs/linear)) +- **WordPress.** Адрес сайта, имя пользователя и пароль приложения вводятся в одной форме, и пароль уходит инструменту через стандартный ввод, а не аргументом команды. Новый пост от агента всегда черновик, но публикация стоит на Спрашивать, так что агент через MCP опубликует без вопросов. У публикации свой ключ, и если вы этого не хотите, поставьте ей Запретить, а черновики останутся. ([доки wordpress](/ru/docs/wordpress)) + +Slack в этот список не попал. [slk](/ru/docs/slk) 0.1.0 вышел 24 ноября и работает из терминала, а в Desktop Slack придет в одной из следующих версий. + +## Почту разбирает модель + +В Сводках появилась вкладка **Входящие**. Модель ИИ, которую вы выбрали в Настройках, разбирает новую почту всех аккаунтов на 3 группы: **Ждет ответа**, **Прочитать** и **Может подождать**. У каждой цепочки видно, почему модель положила ее туда, и щелчок по строке открывает саму переписку. Нужен mail 0.35, а отправитель виден с 0.36. + +Если модель работает не на вашем компьютере и в memo стоит спрашивать перед отправкой, WireCat спрашивает, сколько писем и токенов уйдет и примерно во сколько это обойдется. С mail 0.36 вопрос приходит на вашем языке, а после разбора видно, какая модель работала и сколько это стоило, все, что меньше цента, показано как < $0.01. Правила почты переехали в отдельное окно, с поиском и страницами. + +Если модель не на вашем компьютере, разбор по расписанию отправляет вашу почту ее провайдеру без вопроса. + +## Видно, кого объединил агент + +Агент теперь может сам объединить две записи одного человека, если в двух разных источниках WireCat нашел у них личный мобильный номер или адрес, которого больше ни у кого нет. Для номера хотя бы один из источников должен быть мессенджером или звонком. На странице Контакты такие объединения идут отдельным списком. Там видно, какой агент это сделал, по какому номеру или адресу и почему, и можно отменить, если он ошибся. + +Это делает memo, инструмент WireCat, который связывает людей из всех ваших источников, и нужна его версия 0.141.0. Если вы не хотите, чтобы агент объединял сам, поставьте `"agent_merges": "propose"` в [настройках memo](/ru/docs/memo/configuration), и каждое объединение будет ждать вас. + +У совпадения, которое ждет вашего решения, теперь написано, почему оно не объединилось само, например номер оказался офисной линией компании. У каждой стороны совпадения видны последние сообщения или звонки, компания и сделка. + +## Обновления через apt на Linux + +С 0.7.4 пакет .deb сам добавляет репозиторий WireCat apt.wirecat.dev. Новые версии приходят через Обновление приложений или командой `sudo apt update && sudo apt install wirecat`, а окно обновления в самом приложении теперь пишет об этом и не качает пакет. + +App Center в Ubuntu не показывал разработчика у скачанного .deb, он показывает его только у пакета из репозитория, поэтому пришлось поднять свой. App Center читает имя разработчика только из старого ключа DeveloperName, который `appstreamcli convert` уже не пишет. А в свежей Ubuntu 26.04 Desktop нет curl, поэтому команды для ручного добавления репозитория на apt.wirecat.dev через wget. С 0.7.5 App Center еще и показывает дату выпуска вместо Unknown. + +## Мелочи + +- **WhatsApp показывает, насколько свежие данные.** У WhatsApp нет полного синка, новые сообщения приходят, только пока работает его фоновая служба. У аккаунта написано **В реальном времени**, пока служба подключена, и **Данные на 9:05**, когда нет. Нужен whatsapp-cli 0.46.0. +- **Свои инструменты входят в окне.** Инструмент, который вы добавили по имени npm, например beeline (звонки облачной АТС Билайна), может сам задать шаги входа, и токен вставляется прямо в окно, без терминала. С новой версией такого инструмента в меню аккаунта есть **Выйти** и **Удалить аккаунт**. WireCat проверяет, что эти шаги запускают только команды самого инструмента, и спрашивает вас перед ними. +- **Настройки в двух вкладках.** Одна для приложения, вторая для каждого инструмента. Там же выбирается, сколько почты синхронизировать. +- **Id профиля можно сменить.** В меню аккаунта есть **Изменить id профиля**, вход, настройки и данные переходят к новому id. Работает, если это умеет новая версия самого инструмента. +- **Google Календарь синхронизируется из приложения.** Там же видно, когда это было в последний раз. +- **В Notion можно выбрать страницы и базы.** WireCat копирует те, что вы выбрали, так же, как папки Google Drive. Шаги входа теперь есть на русском и испанском и ведут на новую страницу токенов Notion. +- **Утренняя сводка по CRM теперь в Сводках.** Сначала выигранные и проигранные сделки, потом просроченные задачи, и каждая сделка открывается своей карточкой. +- **Сводки, задачи и документы вышли из беты.** +- **Обновлена библиотека cookie внутри приложения**, из-за уязвимости [RUSTSEC-2026-0594](https://rustsec.org/advisories/RUSTSEC-2026-0594.html). + +## Как получить + +Если у вас 0.7, приложение само предложит обновление, а если вы ставили .deb 0.7.4 или новее, оно придет через Обновление приложений. Вы здесь впервые? Скачайте WireCat на [wirecat.dev/download](/ru/download) для macOS, Windows или Linux. [Руководство по Desktop](/ru/docs/desktop) описывает каждую страницу, а у каждой версии с 0.7.1 до 0.8.0 есть свои [заметки о выпуске на GitHub](https://github.com/WireCatLabs/wirecat-desktop/releases). + +Идеи, что сделать дальше, оставляйте на [странице идей](/ru/ideas), а вопросы в [Discord](https://discord.gg/DebENqbRrJ) или на [GitHub](https://github.com/WireCatLabs/wirecat-desktop/issues).