@roilab/crm-cli 0.1.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/CHANGELOG.md +195 -25
  2. package/SKILL.md +256 -7
  3. package/SURFACE.txt +237 -69
  4. package/dist/bin/crm.js +28 -2
  5. package/dist/bin/crm.js.map +1 -1
  6. package/dist/src/commands/access.js +104 -0
  7. package/dist/src/commands/access.js.map +1 -0
  8. package/dist/src/commands/brief.js +52 -0
  9. package/dist/src/commands/brief.js.map +1 -0
  10. package/dist/src/commands/chat.js +220 -0
  11. package/dist/src/commands/chat.js.map +1 -0
  12. package/dist/src/commands/commands.js +89 -0
  13. package/dist/src/commands/commands.js.map +1 -0
  14. package/dist/src/commands/comment.js +1 -0
  15. package/dist/src/commands/comment.js.map +1 -1
  16. package/dist/src/commands/generic.js +335 -5
  17. package/dist/src/commands/generic.js.map +1 -1
  18. package/dist/src/commands/integrations.js +236 -0
  19. package/dist/src/commands/integrations.js.map +1 -0
  20. package/dist/src/commands/mention.js +139 -0
  21. package/dist/src/commands/mention.js.map +1 -0
  22. package/dist/src/commands/options.js +21 -1
  23. package/dist/src/commands/options.js.map +1 -1
  24. package/dist/src/commands/rank.js +300 -0
  25. package/dist/src/commands/rank.js.map +1 -0
  26. package/dist/src/commands/report.js +209 -0
  27. package/dist/src/commands/report.js.map +1 -0
  28. package/dist/src/commands/review.js +136 -0
  29. package/dist/src/commands/review.js.map +1 -1
  30. package/dist/src/commands/skill.js +1005 -0
  31. package/dist/src/commands/skill.js.map +1 -0
  32. package/dist/src/commands/task.js +298 -4
  33. package/dist/src/commands/task.js.map +1 -1
  34. package/dist/src/commands/time.js +242 -0
  35. package/dist/src/commands/time.js.map +1 -0
  36. package/dist/src/lib/skillBundles.js +84 -0
  37. package/dist/src/lib/skillBundles.js.map +1 -0
  38. package/dist/src/lib/skillManifest.js +77 -0
  39. package/dist/src/lib/skillManifest.js.map +1 -0
  40. package/dist/src/lib/skillSidecar.js +69 -0
  41. package/dist/src/lib/skillSidecar.js.map +1 -0
  42. package/dist/src/lib/skillWriter.js +162 -0
  43. package/dist/src/lib/skillWriter.js.map +1 -0
  44. package/dist/src/transport/envelope.js +12 -2
  45. package/dist/src/transport/envelope.js.map +1 -1
  46. package/dist/src/transport/http.js +27 -0
  47. package/dist/src/transport/http.js.map +1 -1
  48. package/dist/src/transport/run.js +6 -0
  49. package/dist/src/transport/run.js.map +1 -1
  50. package/dist/src/types.js.map +1 -1
  51. package/dist/src/utils/server-nudge.js +57 -0
  52. package/dist/src/utils/server-nudge.js.map +1 -0
  53. package/dist/src/utils/version-check.js +68 -0
  54. package/dist/src/utils/version-check.js.map +1 -1
  55. package/package.json +58 -57
  56. package/skill-bundles/tools/ahrefs-tool/SKILL.md +134 -0
  57. package/skill-bundles/tools/brightlocal-tool/SKILL.md +154 -0
  58. package/skill-bundles/tools/dataforseo-tool/SKILL.md +118 -0
  59. package/skill-bundles/tools/google-analytics-tool/SKILL.md +143 -0
  60. package/skill-bundles/tools/google-search-console-tool/SKILL.md +133 -0
  61. package/skill-bundles/tools/local-falcon-tool/SKILL.md +142 -0
  62. package/skill-bundles/tools/localseodata-tool/SKILL.md +388 -0
  63. package/skill-bundles/tools/lsa-spy-tool/SKILL.md +113 -0
  64. package/skill-bundles/tools/screaming-frog-tool/SKILL.md +166 -0
  65. package/skill-bundles/tools/semrush-tool/SKILL.md +121 -0
  66. package/skill-bundles/tools/serpapi-tool/SKILL.md +148 -0
  67. package/skill-bundles/tools/task-preflight/SKILL.md +149 -0
  68. package/skill-bundles/tools/tool-routing/SKILL.md +59 -0
  69. package/skill-bundles/tools/whitespark-tool/SKILL.md +129 -0
package/CHANGELOG.md CHANGED
@@ -1,25 +1,195 @@
1
- # Changelog
2
-
3
- Todos los cambios notables se documentan aquí. El formato sigue
4
- [Keep a Changelog](https://keepachangelog.com/es/) y el versionado es
5
- [SemVer](https://semver.org/lang/es/).
6
-
7
- ## [Unreleased]
8
-
9
- ### Added
10
- - Comprobación diaria de versión contra el registro de npm; `crm doctor` avisa
11
- cuando hay una versión más reciente.
12
-
13
- ## [0.1.0] — 2026-04-23
14
-
15
- ### Added
16
- - Publicación inicial en npm como `@roilab/crm-cli`.
17
- - Flujo de dispositivo (OAuth-style) para login sin pegar API keys.
18
- - Sustantivos: `auth`, `task`, `comment`, `client`, `domain`, `backlink`,
19
- `change`, `scope`, `competitor`, `tag`, `member`, `recall`, `search`,
20
- `inbox`, `review`, `doctor`.
21
- - Flag `--shadow` para forzar que una escritura aterrice como propuesta
22
- pendiente de revisión.
23
- - Flag `--wait-for-approval` para bloquear hasta decisión humana.
24
- - `crm recall <url>` como memoria cross-entity antes de crear trabajo nuevo.
25
- - Todas las cadenas visibles en español.
1
+ # Changelog
2
+
3
+ Todos los cambios notables se documentan aquí. El formato sigue
4
+ [Keep a Changelog](https://keepachangelog.com/es/) y el versionado es
5
+ [SemVer](https://semver.org/lang/es/).
6
+
7
+ ## [Unreleased]
8
+
9
+ _Ningún cambio pendiente todavía._
10
+
11
+ ## [0.6.0] — 2026-05-18
12
+
13
+ ### Added
14
+
15
+ - **`crm chat get <threadId> [--message-limit n]`.** Devuelve el hilo
16
+ completo (metadata + participantes + `unreadCount` + últimos mensajes)
17
+ en una sola llamada. Mapea a `GET /chats/:id`. Cierra el hueco entre
18
+ `chat list` (sólo metadata) y `chat read` (sólo mensajes paginados).
19
+ - **`crm skill {revisions,revision,create,set,archive,restore}`.** Cierra
20
+ la superficie de gestión de skills en Convex:
21
+ - `skill revisions <slug>` → historial publicado (`GET /skills/:slug/revisions`).
22
+ - `skill revision <id>` → revisión inmutable completa
23
+ (`GET /skills/revisions/:id`).
24
+ - `skill create --slug --name --description --category [--kind --tag
25
+ --visibility --body --frontmatter]` → crea draft
26
+ (`POST /skills`). La primera publicación va con `skill push <slug>
27
+ --publish`.
28
+ - `skill set <slug> [--name --description --category --kind --tag
29
+ --visibility]` → patch de metadatos
30
+ (`PATCH /skills/:slug`). El cuerpo y frontmatter se editan con
31
+ `skill push` — `set` cubre sólo los campos del registro.
32
+ - `skill archive <slug>` / `skill restore <slug>` → ocultar / restaurar
33
+ (`POST /skills/:slug/archive` y `/restore`).
34
+
35
+ ### Fixed
36
+
37
+ - **`task create --no-review` ahora aplica el flag.** Antes el CLI lo
38
+ enviaba pero el schema Zod de `create_task` no lo declaraba, así que
39
+ Zod lo descartaba antes de llegar a `apiGateway.createTask`. Añadido
40
+ `reviewRequired` al schema y a `GATEWAY_ONLY_FIELDS` para que la ruta
41
+ de cookies Better-Auth siga limpiando el campo (la mutación directa
42
+ `api.tasks.create` no lo acepta — `actorType` decide el valor server-
43
+ side para callers no-agente).
44
+
45
+ ## [0.5.0] — 2026-05-17
46
+
47
+ ### Added
48
+
49
+ - **`crm rank {list,get,add,tag,archive,restore,delete}`.** CLI completo
50
+ para keywords del rank tracker. Reads cubren filtros `--domain` /
51
+ `--country` / `--device` / `--state` / `--unranked` / `--canibalised`
52
+ / `--search`; `--ids-only` deja pipear a las operaciones bulk.
53
+ Writes: `add` importa keywords desde `--text` / `--file` / `--stdin`;
54
+ `tag` acepta `--add` / `--remove` / `--replace`; `archive`,
55
+ `restore` y `delete` operan en lotes hasta 500 ids. Todos los bulk
56
+ aceptan ids posicionales, `--stdin` (newline / coma / espacio) o
57
+ `--ids-from-file`. Endpoints REST equivalentes:
58
+ `/api/v1/rank-tracker/keywords*`. Requiere los scopes
59
+ `rank-tracker:read` / `rank-tracker:write` (concedidos por defecto
60
+ a owner / admin / member; nunca a roles cliente).
61
+
62
+ ## [0.4.0] — 2026-05-12
63
+
64
+ ### Added
65
+
66
+ - **Task participants completos.** `task create` y `task update` aceptan
67
+ `--collaborator <id...>` (followers — notificados pero no responsables) además
68
+ de `--assignee`. También cierra otros huecos del registro REST que el CLI no
69
+ exponía: `--start <date>`, `--completion-strategy <all|any|manual>`,
70
+ `--board <id>` (mover de tablero en `update`), y `--tag <id...>` /
71
+ `--assignee <id...>` en `update`. Equivalente Convex: el campo
72
+ `tasks.collaborators` ya existía pero no estaba enrutado por el gateway ni
73
+ el endpoint REST — ahora sí.
74
+ - **`crm backlink {pending,verify,reject,rejection-report}`.** Cubre el flujo
75
+ humano de QA de backlinks. `reject` requiere `--reason` estructurado del
76
+ catálogo (`spammy_source | wrong_anchor | wrong_target | nofollow_unexpected
77
+ | dead_on_arrival | duplicate | policy_violation | other`).
78
+ - **`crm review feedback [--retryable-only]`.** Loop de iteración del agente
79
+ documentado en `SKILL.md`: lee tus propuestas rechazadas con `rejectionReason`
80
+ + `allowRetry` para re-proponer. Mapea a `GET /reviews/feedback`.
81
+ - **`crm review bulk-approve` / `bulk-reject`.** Aprueba o rechaza hasta 100
82
+ propuestas en una sola llamada. Items por stdin (NDJSON o tokens `kind:id`),
83
+ típico encadenado: `crm review list --jq '.data[] | "\(.kind):\(.id)"' | crm
84
+ review bulk-approve`.
85
+ - **`crm report {create,update,delete}`.** Schedules CRUD. Body JSON por
86
+ `--body <json | @path | ->` para no aplanar la unión scope/cadence/approval
87
+ en flags mutuamente dependientes.
88
+ - **`crm access {request,list,approve,deny}`.** Namespace canónico para
89
+ solicitudes de acceso vía chat. Las variantes antiguas bajo `crm task
90
+ {request-access,list-access-requests,approve-access,deny-access}` siguen
91
+ funcionando con un aviso `[DEPRECATED]` en stderr; se retiran en la
92
+ próxima release mayor.
93
+ - **`crm commands`.** Dump JSON del árbol completo del CLI (verbos, args,
94
+ flags) para que los agentes introspeccionen la superficie sin parsear
95
+ `--help`. Devuelve `{ data: { tree, flat } }`.
96
+ - **`crm dashboard summary --start --end`.** Time-series agregado de todo el
97
+ workspace para overviews. Mapea a `GET /dashboard/summary`.
98
+ - **`crm domain get <id>`.** Single-domain fetch con tags + propiedades
99
+ resueltas. Nuevo endpoint `GET /domains/:id` en el registro REST.
100
+ - **`crm time list-task <taskId>`.** Lista entradas de tiempo de una tarea
101
+ sin filtro por fecha. Mapea a `GET /tasks/:taskId/time-entries`.
102
+
103
+ ### Changed
104
+
105
+ - **`task update --client-visible` ahora es simétrico.** Antes era
106
+ `--client-visible <bool>` (string parseado). Ahora se usan los flags
107
+ booleanos de commander: `--client-visible` para marcar visible,
108
+ `--no-client-visible` para marcar interna. Omitir el flag deja la
109
+ visibilidad sin cambios. `task create --client-visible` ya era el flag
110
+ booleano correcto.
111
+ - **Notificación de actualización a usuarios — dos canales nuevos:**
112
+ - **Cache auto-refresh en segundo plano.** Al ejecutar cualquier comando
113
+ el CLI lanza un hijo *detached* (no bloquea el foreground) que
114
+ refresca `~/.config/crm/cache.json` contra `registry.npmjs.org` cuando
115
+ está caducada (>24h) o no existe. Antes solo `crm doctor` refrescaba;
116
+ ahora cualquier invocación cierra el hueco "nunca corro doctor". El
117
+ nudge instantáneo (`maybeNudgeFromCache`) sigue siendo síncrono y sin
118
+ red — el hijo solo escribe la cache para la siguiente invocación.
119
+ - **`User-Agent` + `X-Crm-Cli-Version` en cada llamada HTTP.** El
120
+ servidor compara contra `RECOMMENDED_CLI_VERSION` y `MIN_CLI_VERSION`
121
+ en `src/lib/cli-version-policy.ts`. Si el caller va por detrás, estampa
122
+ `meta.cliUpdate: { current, recommended, severity }` en cada envelope
123
+ (tanto éxito como error, también en replays idempotentes). El CLI lee
124
+ `meta.cliUpdate` y muestra un aviso por stderr una vez por proceso —
125
+ "soft" para upgrades recomendados, "ATENCIÓN" para versiones por
126
+ debajo del mínimo. Mecanismo controlado para forzar avisos sin esperar
127
+ a la TTL de cache de 24h.
128
+
129
+ ## [0.3.0] — 2026-05-04
130
+
131
+ ### Added
132
+ - `crm task preflight --title <t> [--url <u>] [--domain <id>]` — bundle de
133
+ un round-trip que un agente debe ejecutar **antes** de cualquier
134
+ `crm task create`. Devuelve seis secciones acotadas (≤5 items por
135
+ defecto): `similarTasks` (FTS de título re-rankeado por Jaccard +
136
+ recencia + bonus same-domain), `recall` (cuando pasas `--url` —
137
+ fan-out por URL como en `crm recall`, capeado a 10), `recentChanges`,
138
+ `urlScopedTasks` (tareas abiertas ya enlazadas a esa URL),
139
+ `recentBacklinks`, `openTaskCounts` del dominio y `hints[]` en
140
+ español. El `summary` del envelope prioriza la pista accionable
141
+ (duplicado → cargas en URL → similares → adelante).
142
+ Equivalente REST: `GET /tasks/preflight?title=…&url=…&domainId=…`.
143
+ - Skill bundle nuevo `task-preflight` (lazy) con árbol de decisión:
144
+ cuándo NO crear, cuándo cargar GSC/GA4 vivo después del preflight,
145
+ anti-patrones, ejemplo realista. Cárgalo sólo si el envelope deja
146
+ al agente en duda — el `summary` resuelve el 80% de los casos.
147
+
148
+ ### Changed
149
+ - `cli/SKILL.md` — la regla operativa #1 pasa de "always recall before
150
+ creating" a el **ritual obligatorio del preflight**. Documenta que no
151
+ hay que pre-crawlear con Screaming Frog para entender una URL puntual
152
+ (usa `WebFetch` 1-shot) y que GSC/GA4 vivos se llaman *después* del
153
+ preflight, no antes.
154
+ - `tool-routing` añade fila para "decidir si crear tarea" → apunta a
155
+ `task-preflight` antes de cargar cualquier otro skill.
156
+
157
+ ## [0.2.0] — 2026-05-01
158
+
159
+ ### Added
160
+ - `crm task list --review-pending` y `--review-acked` para filtrar tareas
161
+ según `reviewRequired`. Útil para que un agente encuentre rápidamente las
162
+ tareas que él mismo creó y siguen pendientes de validación humana.
163
+ Equivalente REST: `GET /tasks?reviewRequired=true|false`.
164
+ - Banner `⚠ REVISAR` en el formato `--markdown`/`--styled`: cuando una fila
165
+ individual tiene `reviewRequired: true` la salida se prefija con un aviso
166
+ recordando que la tarea es tentativa hasta que un humano la valide; en
167
+ listados, cada fila pendiente se anota inline y el footer cuenta cuántas
168
+ hay pendientes.
169
+
170
+ ### Changed
171
+ - Las descripciones de `list_tasks` y `get_task` (visibles en MCP/OpenAPI)
172
+ ahora documentan el campo `reviewRequired` y la regla operativa: las
173
+ tareas pendientes deben tratarse como tentativas, sin construir trabajo
174
+ derivado encima.
175
+
176
+ ## [0.1.0] — 2026-04-23
177
+
178
+ Primera publicación pública en npm como
179
+ [`@roilab/crm-cli`](https://www.npmjs.com/package/@roilab/crm-cli).
180
+
181
+ ### Added
182
+ - Flujo de dispositivo (OAuth-style) para login sin pegar API keys en disco.
183
+ Tokens corto/largo con rotación (`crm_at_` / `crm_rt_`).
184
+ - Sustantivos: `auth`, `task`, `comment`, `client`, `domain`, `backlink`,
185
+ `change`, `scope`, `competitor`, `tag`, `member`, `recall`, `search`,
186
+ `inbox`, `review`, `doctor`.
187
+ - Flag `--shadow` para forzar que una escritura aterrice como propuesta
188
+ pendiente de revisión humana.
189
+ - Flag `--wait-for-approval --timeout <dur>` para bloquear hasta decisión
190
+ humana.
191
+ - `crm recall <url>` como memoria cross-entity antes de crear trabajo nuevo.
192
+ - Comprobación diaria de versión contra el registro de npm; `crm doctor`
193
+ avisa cuando hay una versión más reciente. Nudge en stderr, sin bloquear
194
+ stdout JSON.
195
+ - Todas las cadenas visibles en español.
package/SKILL.md CHANGED
@@ -70,7 +70,27 @@ Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit co
70
70
 
71
71
  ## Work as an agent, not a human
72
72
 
73
- 1. **Always `recall` before creating**. When a user asks you to "fix the H1 on /pricing", run `crm recall "https://example.com/pricing"` first. You may find a task already open for it, a past fix that was reverted, or a competitor overlap note. Skipping this is how you duplicate work.
73
+ 1. **Preflight ritual antes de `task create` (OBLIGATORIO)**. Una sola llamada antes de cualquier creación de tarea — el server hace fan-out por ti:
74
+
75
+ ```bash
76
+ crm task preflight \
77
+ --title "Arreglar H1 en /pricing" \
78
+ --url https://example.com/pricing \
79
+ --domain dom_xyz \
80
+ --jq .data.hints
81
+ ```
82
+
83
+ El envelope trae 6 secciones acotadas (≤5 items por defecto):
84
+ `similarTasks` (FTS por título re-rankeado por Jaccard + recencia + same-domain), `recall` (cuando pasas `--url`), `recentChanges`, `urlScopedTasks`, `recentBacklinks`, `openTaskCounts`. Y `hints[]` — cadenas en español que el agente lee primero. Reglas:
85
+
86
+ - Si `hints[0]` empieza por **"Posible duplicado"** → **PARA**. Lee la tarea con `crm task get <id>` y decide: editar la existente, comentar en ella, o (si de verdad es trabajo nuevo) crear citando la otra con `#[Title](id)`.
87
+ - Si `urlScopedTasks` no está vacío → la URL ya tiene cargas abiertas; añade un comentario o referencia, no dupliques.
88
+ - Si `openTaskCounts.todo + .doing + .blocked >= 8` → el dominio está sobrecargado; pregunta al humano antes de añadir más.
89
+ - `recentChanges` te dice qué se editó en esa URL/dominio últimamente — si tu tarea coincide con un cambio reciente, casi seguro ya está hecha o en curso.
90
+
91
+ **No pre-crawlees.** Para entender el contenido de una URL específica usa `WebFetch` sobre la URL puntual (1 GET) — Screaming Frog se reserva para auditorías de dominio completas. Para datos GSC/GA4 puntuales (clicks/impr/CTR/posición de la URL), tira `crm gsc query --filters "page=<url>"` o `crm ga4 query --filters "pagePath=<url>"` después del preflight, no antes — solo si el preflight indica que merece crear la tarea.
92
+
93
+ `crm recall` sigue existiendo como herramienta cruda para análisis post-hoc; el preflight ya la incluye.
74
94
 
75
95
  2. **Log decisions explicitly**. Comments default to `--kind=agent_log` for you (a minor trace). When you *chose* a course of action, use `--kind=decision`:
76
96
  ```bash
@@ -86,6 +106,8 @@ Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit co
86
106
 
87
107
  4. **Use `reviewRequired`**. Your task creates default to `reviewRequired=true` — the human sees them in a dedicated inbox section. Only pass `--no-review` for low-stakes rework (e.g. re-filing a recurring instance).
88
108
 
109
+ **Read side — when you see `reviewRequired: true` on a task you didn't create**: treat it as tentative. The row is live but a human hasn't acknowledged it yet, and may still edit, reassign, or reject the framing. Don't build downstream work that assumes it's settled (no offers linked to it, no auto-complete on its goals, no marking siblings as duplicates of it). You can't approve your own writes — only humans clear the flag. If you're blocked waiting, leave a `--kind decision` agent_log comment, don't change status. Filter the queue with `crm task list --review-pending` (or `GET /tasks?reviewRequired=true`).
110
+
89
111
  5. **Every write gets an idempotency key**. The CLI autogenerates one per invocation, so retries within a single command are safe. If you're orchestrating retries across invocations, pass `--idempotency-key <ulid>` so the retry replays instead of double-creating.
90
112
 
91
113
  6. **You choose shadow or autonomous per write**. Every write has two possible fates:
@@ -106,15 +128,142 @@ Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit co
106
128
 
107
129
  **Rule of thumb**: if the change is hard to reverse (deleting work, merging branches of logic, sending external messages, big content rewrites), pass `--shadow` even if your default is autonomous. Low-stakes routine updates (status nudges, agent_log comments, tag adjustments) can run autonomously.
108
130
 
131
+ ## Mentioning humans + linking tasks
132
+
133
+ Comments and task descriptions are markdown. Two special syntaxes — both
134
+ already wired up to fan out the right side effects when the row lands live:
135
+
136
+ - **`@[Name](memberId)`** — pings a workspace member. Fires a
137
+ `comment_mentioned` notification + email. **Important authorization side
138
+ effect:** mentioning a `client` user auto-grants them domain access for
139
+ this task. Mentioning a `client_lead` outside their own client is rejected.
140
+ - **`#[Title](taskId)`** — adds a graph edge between tasks (parent / blocker
141
+ / duplicate-of / follow-up). Updates the target's "Referenced by" panel.
142
+ No notification fires — purely a graph operation.
143
+
144
+ ### Resolve IDs before composing
145
+
146
+ Don't hand-roll memberIds or taskIds. Use the resolver helpers; they exit
147
+ non-zero when the query is wrong:
148
+
149
+ ```bash
150
+ # Resolve a name → markdown chip. Exits 8 if ambiguous, 2 if no match.
151
+ crm mention member "luis" # → @[Luis Fernández](mem_abc)
152
+ crm mention member --domain dom_xyz "sarah"
153
+ crm mention task "fix h1 pricing" # → #[Fix H1 on /pricing](tsk_xyz)
154
+
155
+ # Or list candidates first if you want to pick by hand:
156
+ crm member list --query "luis"
157
+ crm member list --domain dom_xyz --role member,admin
158
+ crm task search "h1" --limit 10
159
+ ```
160
+
161
+ Compose into a write with shell substitution — the chips are plain markdown,
162
+ not JSON:
163
+
164
+ ```bash
165
+ crm comment create --task tsk_abc \
166
+ --body "$(crm mention member luis) please check the audit results — \
167
+ blocking $(crm mention task 'crawl audit GB')"
168
+ ```
169
+
170
+ If the resolver exits 8 the shell substitution captures stderr (not stdout),
171
+ so the outer command will land with a literal empty chip — that's the
172
+ intended failure mode. Read the stderr disambiguation hint and re-run.
173
+
174
+ ### Assemble context BEFORE mentioning anything
175
+
176
+ The legitimate pool of mentionable members for a write is **the union of**:
177
+ the existing task's assignees + collaborators (already inlined as
178
+ `participants` on `crm task get`), the staff returned by `crm brief`, and
179
+ anyone the human explicitly named. Anything outside that pool is almost
180
+ always the wrong person — ask before mentioning.
181
+
182
+ ```bash
183
+ # For an existing task: pulls participants (with role + expertise) + parent
184
+ # domain brief + cross-references already linked. Run this BEFORE adding a
185
+ # comment.
186
+ crm brief --task tsk_abc
187
+
188
+ # For a new task: scope to the domain so the staff list is the working pool.
189
+ crm brief --domain dom_xyz
190
+
191
+ # For "is there already a task tracking this?" before adding a #link:
192
+ crm task related tsk_abc # tasks already linked + same-domain + shared-tags
193
+ crm recall https://example.com/pricing
194
+ ```
195
+
196
+ `crm brief --task` is the URL-equivalent of `recall` for tasks: the right
197
+ pre-write context every time.
198
+
199
+ #### Sensitive handling notes
200
+
201
+ Profile responses carry an `internalNotes` field (markdown, staff-only) on
202
+ clients, domains and members. Treat it as binding handling guidance, not
203
+ flavour text — it's where the human team writes things like "never mention
204
+ project X to this CEO", "always cc Eric Collado as follower on every task",
205
+ "careful — this person prefers blunt feedback". Always read these before
206
+ drafting any comment, mention or task that touches the entity. They flow
207
+ through automatically on:
208
+
209
+ - `crm brief <clientId>` → `clientProfile.internalNotes` and per-domain / per-staff notes
210
+ - `crm brief --domain <id>` → domain + parent client + staff with activity
211
+ - `crm brief --task <id>` → each `participants[].internalNotes` + parent domain + parent client
212
+ - `crm client profile <id>` / `domain profile <id>` / `member profile <id>` → single-entity fetch
213
+ - `crm task get <id>` → `participants[].internalNotes` for staff callers
214
+
215
+ Never echo `internalNotes` into client-visible surfaces (shared chat threads,
216
+ client-visible tasks, replies through the portal). They are agency-internal.
217
+
218
+ ### When to mention vs. not
219
+
220
+ - **Mention** when attention is genuinely needed *now*: a decision blocking
221
+ next steps, a completed item awaiting review, a regression you've spotted.
222
+ - **Don't mention** on routine `agent_log` traces ("ran the audit, here's
223
+ the output"). The volume drowns inboxes; the badge already shows it's
224
+ agent work.
225
+ - **`#`-link** when the relationship is real graph (blocker, duplicate-of,
226
+ follow-up). Not as decoration, not to "show your work" — that goes in
227
+ prose.
228
+ - **Self-mentions are filtered server-side** so you don't ping your own
229
+ underlying member.
230
+
231
+ ### Notifications fire on approval, not on submission
232
+
233
+ This is the rule that matters for shadow-mode writes:
234
+
235
+ - **Autonomous write** with `@[Name](id)` → notification fires immediately,
236
+ scope grants apply immediately, `taskMentions` index updates immediately.
237
+ - **Shadow proposal** with `@[Name](id)` → **nothing fires until a human
238
+ approves**. The chip renders to reviewers in the markdown so they can see
239
+ the intent, but the mentioned user is not pinged, no scope is granted, no
240
+ graph edge lands. On approval, all three side effects fire — attributed
241
+ to the original agent's name (so the user reads "Agent X mentioned you")
242
+ but the notification's `createdAt` is the approval moment.
243
+ - **Shadow proposal that's rejected** → side effects never fire. The chip
244
+ goes nowhere.
245
+
246
+ The point: a `--shadow` write that mentions someone is not a way to "ping
247
+ them with a heads-up before review." It's a deferred mention. If you need
248
+ the human aware before approval, write a `--kind decision` autonomous
249
+ comment.
250
+
251
+ ### Edits to descriptions are diffed
252
+
253
+ Updating a task's description with a new `@mention` only fires for the
254
+ **newly added** mention, not the ones already present. Same for `#`-links.
255
+ You can safely edit a description that already references people without
256
+ re-pinging them.
257
+
109
258
  ## Common recipes
110
259
 
111
260
  ```bash
112
261
  # Read-only triage before acting
113
- crm recall https://example.com/pricing --jq '.data[] | {type, when, snippet}'
262
+ crm task preflight --title "Fix H1 on /pricing" --url https://example.com/pricing --domain dom_xyz
114
263
  crm change list --domain dom_xyz --url /pricing --jq '.data[].items[].type'
115
264
  crm backlink lost --domain dom_xyz --since 2026-01-01 --count
116
265
 
117
- # Create a measured task
266
+ # Create a measured task — sólo si el preflight no encontró duplicados
118
267
  crm task create \
119
268
  --title "Fix H1 on /pricing" \
120
269
  --domain dom_xyz \
@@ -126,17 +275,117 @@ crm task create \
126
275
 
127
276
  # Search across everything
128
277
  crm search "meta title" --kind change --domain dom_xyz --limit 5
278
+
279
+ # Live provider-API queries (tokens stay on the server)
280
+ crm integration list --jq '.data[] | {id:._id, provider, services}'
281
+ crm gsc query --property prop_abc --dimension page \
282
+ --filters "page contains /blog/" --start 2026-03-01 --end 2026-04-01 --limit 50
283
+ crm ga4 query --property prop_abc --start 2026-03-01 --end 2026-04-01 \
284
+ --filters "pagePath contains /pricing"
285
+ crm bing query --property prop_bing --start 2026-03-01 --end 2026-04-01
286
+ crm integration sync --property prop_abc # forces fresh ingestion (15m cooldown)
287
+
288
+ # Agency skills — pull the library so Claude Code picks them up
289
+ crm skill list --category local-seo --quiet
290
+ crm skill pull --all # writes .claude/skills/<slug>/SKILL.md
291
+ crm skill update # refresh any outdated skill
292
+ crm skill diff auditoria-seo-local # local vs remote state
129
293
  ```
130
294
 
295
+ ## Decision tree for analytics questions
296
+
297
+ 1. **Rollups / trends** → `crm domain metrics <id> --start … --end …`. Reads from Tinybird; cheap and fast.
298
+ 2. **Per-query / per-page breakdowns, or custom filters** → `crm gsc query` / `crm ga4 query`. Hits the live provider API through our backend; pass `--dimension page`, `--filters "…"`, `--cursor <n>` for pagination.
299
+ 3. **Data must be fresher than the last daily cron** → `crm integration sync --property <id>`. Respects a 15m cooldown; returns `queued | cooldown | already_running` so you can branch instead of polling.
300
+
301
+ Prefer 1 over 2 when it answers the question — Tinybird reads don't touch provider quotas. Drop down to 2 only when you need the dimensional detail.
302
+
131
303
  ## Things that are not obvious
132
304
 
133
305
  - Task ids start with `tsk_`, domains with `dom_`, scopes with `sco_`. You pass these as the first positional arg to `get`/`update`. Never pass a URL where an id is expected.
134
306
  - **Scope comments are useful**: if a task has a scoped propertyLink (via `scopeId`), use `crm scope get <id>` to see the fingerprint + filters before assuming the KPI measurement window.
135
- - Layer 3 GSC queries (top queries / top pages by URL filter) are an **in-flight v2 addition**. For now use `crm domain metrics` for time-series.
136
- - Web UI paths: `/dashboard/tasks/<id>` for a specific task, `/dashboard/inbox` for your review queue, `/developers` for the endpoint catalog.
307
+ - **Provider tokens never reach you**. The CLI forwards `--filters`, `--start`, `--end` through our REST layer; Convex decrypts and calls GSC / GA4 / Bing server-side. If you need a shape our wrappers don't cover, open an endpoint — don't try to exfiltrate tokens.
308
+ - **Bing daily feed has no per-query/per-page breakdown**. `crm bing query` returns the aggregate with a `meta.note` saying so.
309
+ - Web UI paths: `/dashboard/tasks/<id>` for a specific task, `/dashboard/inbox` for your review queue, `/developers` for the endpoint catalog, `/dashboard/settings?tab=api-usage` for the provider-API usage log.
310
+
311
+ ## Task participants — assignees vs collaborators
312
+
313
+ Two distinct member lists on every task:
314
+
315
+ - **`--assignee <id...>`** — the **responsible** parties. Their queue counts include this task; auto-assigned watchers; show up first in the UI.
316
+ - **`--collaborator <id...>`** — **followers**. They receive notifications for the task but are not responsible. Use this for stakeholders who need awareness without ownership (e.g. a domain lead reviewing what a member ships).
317
+
318
+ Both flags accept multiple values and exist on both `crm task create` and `crm task update`. **Lists replace** on update — pass the full set, not a diff. To clear, pass `--assignee` with no value? No — that's commander rejecting it. To clear, omit the flag (no change) or set the next intent explicitly.
319
+
320
+ Other task fields the CLI now passes end-to-end: `--start <date>`, `--completion-strategy <all|any|manual>`, `--board <id>` (move between kanban boards on update). See `crm task update --help` for the full set.
321
+
322
+ ## Reading rejection feedback (iteration loop)
323
+
324
+ When a reviewer rejects your shadow proposal, the row carries `rejectionReason` (free text from the human) and `allowRetry` (true = revise + re-propose; false = drop the work item).
325
+
326
+ ```bash
327
+ # Just the actionable ones — items the reviewer wants you to redo.
328
+ crm review feedback --retryable-only
329
+
330
+ # Everything that's been rejected for this API key, with reasons.
331
+ crm review feedback
332
+ ```
333
+
334
+ Read this **before** assuming a rejected proposal is dead. The reviewer often wants a smaller scope, a different framing, or a citation you didn't include — not "never do this." If `allowRetry=false`, drop the work and don't re-propose without a human asking.
335
+
336
+ ## Access requests — `crm access`
337
+
338
+ When a client (or an agent on a client key) spots a task in a chat thread and wants to see it, the flow is:
339
+
340
+ ```bash
341
+ # Client side — file the request, citing the chat message that exposed the task.
342
+ crm access request <task-id> --via <message-id> --message "Need to review the H1 fix"
343
+
344
+ # Staff side — list pending, then approve or deny with a scope choice.
345
+ crm access list
346
+ crm access approve <request-id> --scope task # smallest blast radius
347
+ crm access approve <request-id> --scope board # whole board (for cross-client tasks)
348
+ crm access deny <request-id> --note "Task is internal QA"
349
+ ```
350
+
351
+ The older `crm task {request-access,list-access-requests,approve-access,deny-access}` aliases still work for one release with a deprecation warning — prefer the canonical `crm access` namespace.
352
+
353
+ ## Backlink human-QA
354
+
355
+ Linkbuilding rows can sit in a pending-review queue until staff verifies the source. Agents with `backlinks:verify` scope can drive the queue:
356
+
357
+ ```bash
358
+ crm backlink pending --domain dom_xyz
359
+ crm backlink verify <id> # idempotent
360
+ crm backlink reject <id> --reason wrong_anchor --notes "Anchor text drifted to brand-only"
361
+ crm backlink rejection-report --client cli_xyz --since-days 90
362
+ ```
363
+
364
+ Reasons are a closed catalog (`spammy_source | wrong_anchor | wrong_target | nofollow_unexpected | dead_on_arrival | duplicate | policy_violation | other`) — server validates and notifies the original creator.
365
+
366
+ ## Bulk approve / reject your queue
367
+
368
+ `crm review` supports bulk operations via stdin (NDJSON or `kind:id` tokens, ≤100 per call):
369
+
370
+ ```bash
371
+ # Approve every pending proposal from your key:
372
+ crm review list --mine --quiet --jq '.[] | "\(.kind):\(._id)"' | crm review bulk-approve
373
+
374
+ # Reject many with one reason (allowRetry defaults to true):
375
+ echo -e "task:tsk_a\ntask:tsk_b" | crm review bulk-reject --reason "Out of scope this quarter"
376
+ ```
137
377
 
138
378
  ## Escape hatches
139
379
 
140
- - `crm doctor --json` — always safe; doesn't mutate anything.
141
- - `crm commands` — future v2 addition that dumps the full command catalog as JSON (see `SURFACE.txt` in this package meanwhile).
380
+ - `crm commands` — dumps the full CLI surface as JSON (`{ data: { tree, flat } }`). Use this for catalog introspection without parsing `--help`. `SURFACE.txt` in this package is the grep-able mirror.
381
+ - `crm doctor --json` — always safe; doesn't mutate anything. Also forces a fresh npm registry check.
142
382
  - `crm auth whoami` — what identity am I acting under? Check this first if attribution looks wrong in the UI.
383
+
384
+ ## Update notifications
385
+
386
+ Two channels surface a stale CLI version, both shown via stderr (never on stdout — they don't break `--quiet` pipes):
387
+
388
+ - **Cache nudge**: `[crm] hay una versión nueva: X (tienes Y)`. Printed at startup when `~/.config/crm/cache.json` says a newer version exists on npm. The cache auto-refreshes in a detached background child every 24h on any CLI invocation — `crm doctor` is the explicit refresh path.
389
+ - **Server nudge**: when the API stamps `meta.cliUpdate` on the envelope (caller's `X-Crm-Cli-Version` header is behind the server's `RECOMMENDED_CLI_VERSION` / `MIN_CLI_VERSION`). `"soft"` = friendly upgrade hint; `"required"` = louder `ATENCIÓN` block warning the API surface may have moved. Dedupes once per process.
390
+
391
+ Both are non-blocking — they print and continue. If your agent runs in `--quiet` / pipeline mode and you need to suppress stderr, redirect explicitly (`2>/dev/null`) but you'll lose error messages too.