@roilab/crm-cli 0.1.0 → 0.4.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 (67) hide show
  1. package/CHANGELOG.md +125 -6
  2. package/SKILL.md +256 -7
  3. package/SURFACE.txt +148 -3
  4. package/dist/bin/crm.js +26 -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 +203 -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/report.js +209 -0
  25. package/dist/src/commands/report.js.map +1 -0
  26. package/dist/src/commands/review.js +136 -0
  27. package/dist/src/commands/review.js.map +1 -1
  28. package/dist/src/commands/skill.js +836 -0
  29. package/dist/src/commands/skill.js.map +1 -0
  30. package/dist/src/commands/task.js +298 -4
  31. package/dist/src/commands/task.js.map +1 -1
  32. package/dist/src/commands/time.js +242 -0
  33. package/dist/src/commands/time.js.map +1 -0
  34. package/dist/src/lib/skillBundles.js +84 -0
  35. package/dist/src/lib/skillBundles.js.map +1 -0
  36. package/dist/src/lib/skillManifest.js +77 -0
  37. package/dist/src/lib/skillManifest.js.map +1 -0
  38. package/dist/src/lib/skillSidecar.js +69 -0
  39. package/dist/src/lib/skillSidecar.js.map +1 -0
  40. package/dist/src/lib/skillWriter.js +162 -0
  41. package/dist/src/lib/skillWriter.js.map +1 -0
  42. package/dist/src/transport/envelope.js +12 -2
  43. package/dist/src/transport/envelope.js.map +1 -1
  44. package/dist/src/transport/http.js +27 -0
  45. package/dist/src/transport/http.js.map +1 -1
  46. package/dist/src/transport/run.js +6 -0
  47. package/dist/src/transport/run.js.map +1 -1
  48. package/dist/src/types.js.map +1 -1
  49. package/dist/src/utils/server-nudge.js +57 -0
  50. package/dist/src/utils/server-nudge.js.map +1 -0
  51. package/dist/src/utils/version-check.js +68 -0
  52. package/dist/src/utils/version-check.js.map +1 -1
  53. package/package.json +2 -1
  54. package/skill-bundles/tools/ahrefs-tool/SKILL.md +134 -0
  55. package/skill-bundles/tools/brightlocal-tool/SKILL.md +154 -0
  56. package/skill-bundles/tools/dataforseo-tool/SKILL.md +118 -0
  57. package/skill-bundles/tools/google-analytics-tool/SKILL.md +143 -0
  58. package/skill-bundles/tools/google-search-console-tool/SKILL.md +133 -0
  59. package/skill-bundles/tools/local-falcon-tool/SKILL.md +142 -0
  60. package/skill-bundles/tools/localseodata-tool/SKILL.md +388 -0
  61. package/skill-bundles/tools/lsa-spy-tool/SKILL.md +113 -0
  62. package/skill-bundles/tools/screaming-frog-tool/SKILL.md +166 -0
  63. package/skill-bundles/tools/semrush-tool/SKILL.md +121 -0
  64. package/skill-bundles/tools/serpapi-tool/SKILL.md +148 -0
  65. package/skill-bundles/tools/task-preflight/SKILL.md +149 -0
  66. package/skill-bundles/tools/tool-routing/SKILL.md +59 -0
  67. package/skill-bundles/tools/whitespark-tool/SKILL.md +129 -0
package/CHANGELOG.md CHANGED
@@ -6,20 +6,139 @@ Todos los cambios notables se documentan aquí. El formato sigue
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ _Ningún cambio pendiente todavía._
10
+
11
+ ## [0.4.0] — 2026-05-12
12
+
13
+ ### Added
14
+
15
+ - **Task participants completos.** `task create` y `task update` aceptan
16
+ `--collaborator <id...>` (followers — notificados pero no responsables) además
17
+ de `--assignee`. También cierra otros huecos del registro REST que el CLI no
18
+ exponía: `--start <date>`, `--completion-strategy <all|any|manual>`,
19
+ `--board <id>` (mover de tablero en `update`), y `--tag <id...>` /
20
+ `--assignee <id...>` en `update`. Equivalente Convex: el campo
21
+ `tasks.collaborators` ya existía pero no estaba enrutado por el gateway ni
22
+ el endpoint REST — ahora sí.
23
+ - **`crm backlink {pending,verify,reject,rejection-report}`.** Cubre el flujo
24
+ humano de QA de backlinks. `reject` requiere `--reason` estructurado del
25
+ catálogo (`spammy_source | wrong_anchor | wrong_target | nofollow_unexpected
26
+ | dead_on_arrival | duplicate | policy_violation | other`).
27
+ - **`crm review feedback [--retryable-only]`.** Loop de iteración del agente
28
+ documentado en `SKILL.md`: lee tus propuestas rechazadas con `rejectionReason`
29
+ + `allowRetry` para re-proponer. Mapea a `GET /reviews/feedback`.
30
+ - **`crm review bulk-approve` / `bulk-reject`.** Aprueba o rechaza hasta 100
31
+ propuestas en una sola llamada. Items por stdin (NDJSON o tokens `kind:id`),
32
+ típico encadenado: `crm review list --jq '.data[] | "\(.kind):\(.id)"' | crm
33
+ review bulk-approve`.
34
+ - **`crm report {create,update,delete}`.** Schedules CRUD. Body JSON por
35
+ `--body <json | @path | ->` para no aplanar la unión scope/cadence/approval
36
+ en flags mutuamente dependientes.
37
+ - **`crm access {request,list,approve,deny}`.** Namespace canónico para
38
+ solicitudes de acceso vía chat. Las variantes antiguas bajo `crm task
39
+ {request-access,list-access-requests,approve-access,deny-access}` siguen
40
+ funcionando con un aviso `[DEPRECATED]` en stderr; se retiran en la
41
+ próxima release mayor.
42
+ - **`crm commands`.** Dump JSON del árbol completo del CLI (verbos, args,
43
+ flags) para que los agentes introspeccionen la superficie sin parsear
44
+ `--help`. Devuelve `{ data: { tree, flat } }`.
45
+ - **`crm dashboard summary --start --end`.** Time-series agregado de todo el
46
+ workspace para overviews. Mapea a `GET /dashboard/summary`.
47
+ - **`crm domain get <id>`.** Single-domain fetch con tags + propiedades
48
+ resueltas. Nuevo endpoint `GET /domains/:id` en el registro REST.
49
+ - **`crm time list-task <taskId>`.** Lista entradas de tiempo de una tarea
50
+ sin filtro por fecha. Mapea a `GET /tasks/:taskId/time-entries`.
51
+
52
+ ### Changed
53
+
54
+ - **`task update --client-visible` ahora es simétrico.** Antes era
55
+ `--client-visible <bool>` (string parseado). Ahora se usan los flags
56
+ booleanos de commander: `--client-visible` para marcar visible,
57
+ `--no-client-visible` para marcar interna. Omitir el flag deja la
58
+ visibilidad sin cambios. `task create --client-visible` ya era el flag
59
+ booleano correcto.
60
+ - **Notificación de actualización a usuarios — dos canales nuevos:**
61
+ - **Cache auto-refresh en segundo plano.** Al ejecutar cualquier comando
62
+ el CLI lanza un hijo *detached* (no bloquea el foreground) que
63
+ refresca `~/.config/crm/cache.json` contra `registry.npmjs.org` cuando
64
+ está caducada (>24h) o no existe. Antes solo `crm doctor` refrescaba;
65
+ ahora cualquier invocación cierra el hueco "nunca corro doctor". El
66
+ nudge instantáneo (`maybeNudgeFromCache`) sigue siendo síncrono y sin
67
+ red — el hijo solo escribe la cache para la siguiente invocación.
68
+ - **`User-Agent` + `X-Crm-Cli-Version` en cada llamada HTTP.** El
69
+ servidor compara contra `RECOMMENDED_CLI_VERSION` y `MIN_CLI_VERSION`
70
+ en `src/lib/cli-version-policy.ts`. Si el caller va por detrás, estampa
71
+ `meta.cliUpdate: { current, recommended, severity }` en cada envelope
72
+ (tanto éxito como error, también en replays idempotentes). El CLI lee
73
+ `meta.cliUpdate` y muestra un aviso por stderr una vez por proceso —
74
+ "soft" para upgrades recomendados, "ATENCIÓN" para versiones por
75
+ debajo del mínimo. Mecanismo controlado para forzar avisos sin esperar
76
+ a la TTL de cache de 24h.
77
+
78
+ ## [0.3.0] — 2026-05-04
79
+
9
80
  ### 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.
81
+ - `crm task preflight --title <t> [--url <u>] [--domain <id>]` — bundle de
82
+ un round-trip que un agente debe ejecutar **antes** de cualquier
83
+ `crm task create`. Devuelve seis secciones acotadas (≤5 items por
84
+ defecto): `similarTasks` (FTS de título re-rankeado por Jaccard +
85
+ recencia + bonus same-domain), `recall` (cuando pasas `--url` —
86
+ fan-out por URL como en `crm recall`, capeado a 10), `recentChanges`,
87
+ `urlScopedTasks` (tareas abiertas ya enlazadas a esa URL),
88
+ `recentBacklinks`, `openTaskCounts` del dominio y `hints[]` en
89
+ español. El `summary` del envelope prioriza la pista accionable
90
+ (duplicado → cargas en URL → similares → adelante).
91
+ Equivalente REST: `GET /tasks/preflight?title=…&url=…&domainId=…`.
92
+ - Skill bundle nuevo `task-preflight` (lazy) con árbol de decisión:
93
+ cuándo NO crear, cuándo cargar GSC/GA4 vivo después del preflight,
94
+ anti-patrones, ejemplo realista. Cárgalo sólo si el envelope deja
95
+ al agente en duda — el `summary` resuelve el 80% de los casos.
96
+
97
+ ### Changed
98
+ - `cli/SKILL.md` — la regla operativa #1 pasa de "always recall before
99
+ creating" a el **ritual obligatorio del preflight**. Documenta que no
100
+ hay que pre-crawlear con Screaming Frog para entender una URL puntual
101
+ (usa `WebFetch` 1-shot) y que GSC/GA4 vivos se llaman *después* del
102
+ preflight, no antes.
103
+ - `tool-routing` añade fila para "decidir si crear tarea" → apunta a
104
+ `task-preflight` antes de cargar cualquier otro skill.
105
+
106
+ ## [0.2.0] — 2026-05-01
107
+
108
+ ### Added
109
+ - `crm task list --review-pending` y `--review-acked` para filtrar tareas
110
+ según `reviewRequired`. Útil para que un agente encuentre rápidamente las
111
+ tareas que él mismo creó y siguen pendientes de validación humana.
112
+ Equivalente REST: `GET /tasks?reviewRequired=true|false`.
113
+ - Banner `⚠ REVISAR` en el formato `--markdown`/`--styled`: cuando una fila
114
+ individual tiene `reviewRequired: true` la salida se prefija con un aviso
115
+ recordando que la tarea es tentativa hasta que un humano la valide; en
116
+ listados, cada fila pendiente se anota inline y el footer cuenta cuántas
117
+ hay pendientes.
118
+
119
+ ### Changed
120
+ - Las descripciones de `list_tasks` y `get_task` (visibles en MCP/OpenAPI)
121
+ ahora documentan el campo `reviewRequired` y la regla operativa: las
122
+ tareas pendientes deben tratarse como tentativas, sin construir trabajo
123
+ derivado encima.
12
124
 
13
125
  ## [0.1.0] — 2026-04-23
14
126
 
127
+ Primera publicación pública en npm como
128
+ [`@roilab/crm-cli`](https://www.npmjs.com/package/@roilab/crm-cli).
129
+
15
130
  ### Added
16
- - Publicación inicial en npm como `@roilab/crm-cli`.
17
- - Flujo de dispositivo (OAuth-style) para login sin pegar API keys.
131
+ - Flujo de dispositivo (OAuth-style) para login sin pegar API keys en disco.
132
+ Tokens corto/largo con rotación (`crm_at_` / `crm_rt_`).
18
133
  - Sustantivos: `auth`, `task`, `comment`, `client`, `domain`, `backlink`,
19
134
  `change`, `scope`, `competitor`, `tag`, `member`, `recall`, `search`,
20
135
  `inbox`, `review`, `doctor`.
21
136
  - 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.
137
+ pendiente de revisión humana.
138
+ - Flag `--wait-for-approval --timeout <dur>` para bloquear hasta decisión
139
+ humana.
24
140
  - `crm recall <url>` como memoria cross-entity antes de crear trabajo nuevo.
141
+ - Comprobación diaria de versión contra el registro de npm; `crm doctor`
142
+ avisa cuando hay una versión más reciente. Nudge en stderr, sin bloquear
143
+ stdout JSON.
25
144
  - 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.
package/SURFACE.txt CHANGED
@@ -10,21 +10,77 @@ CMD crm auth logout [name]
10
10
 
11
11
  CMD crm task list --status <status> --domain <id> --assignee <id> --tag <id> --limit <n>
12
12
  CMD crm task get <id>
13
+ # task get returns `participants[]` with name, role, expertise, and
14
+ # internalNotes (staff-only, markdown handling rules) — use it instead of a
15
+ # follow-up `member list` when composing @mentions on an existing task.
16
+ CMD crm task related <id>
17
+ # task related groups: referenced (already linked via #), sameDomain, sharedTags.
13
18
  CMD crm task search <query> --limit <n>
14
- CMD crm task create --title <title> --description <text> --domain <id> --status <status> --assignee <id...> --tag <id...> --due <date> --client-visible --no-review
15
- CMD crm task update <id> --title <title> --status <status> --domain <id> --due <date> --client-visible <bool>
19
+ # task preflight — OBLIGATORIO antes de `task create`. Bundle de 1 round-trip:
20
+ # similarTasks (FTS + Jaccard) · recall si --url · recentChanges en el dominio
21
+ # · urlScopedTasks · recentBacklinks · openTaskCounts del dominio · hints[].
22
+ # Si `hints` empieza con "Posible duplicado", PARA: revisa la tarea existente
23
+ # antes de crear una nueva.
24
+ CMD crm task preflight --title <title> --url <url> --domain <id> --limit <n> --since-ms <epoch>
25
+ # task create / update accept the full mutation surface: `--assignee` (responsible)
26
+ # vs `--collaborator` (follower); `--start` + `--due`; `--completion-strategy`
27
+ # (all|any|manual); `--board` (move to another board on update). `task update`
28
+ # uses `--client-visible` / `--no-client-visible` (symmetric boolean flags).
29
+ CMD crm task create --title <title> --description <text> --domain <id> --board <id> --status <status> --assignee <id...> --collaborator <id...> --tag <id...> --start <date> --due <date> --completion-strategy <all|any|manual> --client-visible --no-review
30
+ CMD crm task update <id> --title <title> --status <status> --domain <id> --board <id> --assignee <id...> --collaborator <id...> --tag <id...> --start <date> --due <date> --completion-strategy <all|any|manual> --client-visible --no-client-visible
31
+ # Phase 41 — task ↔ backlink linking. `assets` returns the primary FK +
32
+ # outgoing mentions in one payload; `link-backlink` / `link-offer` set the
33
+ # primary FK (use --unlink to clear); `complete-with-evidence` closes a task
34
+ # citing a backlink/offer (server validates the comment cites the asset).
35
+ CMD crm task assets <id>
36
+ CMD crm task link-backlink <task-id> <backlink-id> --unlink
37
+ CMD crm task link-offer <task-id> <offer-id> --unlink
38
+ CMD crm task complete-with-evidence <task-id> --asset <kind:id> --comment <id>
16
39
 
17
40
  CMD crm comment list <taskId>
18
41
  CMD crm comment create --task <id> --body <text> --kind <note|agent_log|decision>
19
42
 
43
+ # Chat — conversaciones ancladas a workspace/cliente/dominio + DMs y grupos.
44
+ # Per-cliente las salas Interna y Compartida se auto-crean. Para chats libres
45
+ # usa `chat dm` (1:1 idempotente; varios miembros = grupo). `chat reply`
46
+ # crea sub-hilos sin salir del CLI; `chat react` activa/desactiva una de
47
+ # las 8 reacciones curadas. Markdown + @[Name](id) + #[Title](id) soportados.
48
+ CMD crm chat list --scope <workspace|client|dm> --client <id>
49
+ CMD crm chat read <threadId> --page-limit <n> --before <ms>
50
+ CMD crm chat thread --workspace --client <id> --shared
51
+ CMD crm chat send <threadId> --body <text> --kind <message|agent_log> --parent <messageId>
52
+ CMD crm chat reply <messageId> --thread <id> --body <text> --kind <message|agent_log>
53
+ CMD crm chat react <messageId> --emoji <👍|✅|👀|🙏|❤️|❓|🔥|🚀>
54
+ CMD crm chat dm --member <id> --title <name> --client <id>
55
+ CMD crm chat mark-read <threadId> --message <id>
56
+
20
57
  CMD crm client list
21
58
  CMD crm client get <id>
59
+ # Profile responses carry `internalNotes` (markdown, staff-only) — handling
60
+ # rules like "never mention X to this CEO" / "always cc Eric as follower".
61
+ # Read these before drafting any comment/mention. Never echo into client-
62
+ # visible surfaces (shared chat, client-visible tasks, portal).
63
+ CMD crm client profile <id>
64
+ CMD crm client profile-set <id> --ceo-name <text> --ceo-role <text> --industry <text> --what-they-sell <text> --target-audience <text> --objectives <text> --usps <csv> --pain-points <csv> --tone-of-voice <text> --language-prefs <csv> --comms-preferences <text> --brief <md> --internal-notes <md>
22
65
 
23
66
  CMD crm domain list --client <id>
67
+ CMD crm domain get <id>
24
68
  CMD crm domain metrics <id> --start <date> --end <date>
69
+ CMD crm domain profile <id>
70
+ CMD crm domain profile-set <id> --positioning <text> --tone-override <text> --audience-override <text> --content-guidelines <text> --brief <md> --internal-notes <md>
25
71
 
26
72
  CMD crm backlink list --domain <id> --status <status>
27
73
  CMD crm backlink lost --domain <id> --since <iso>
74
+ CMD crm backlink list-tasks <backlink-id>
75
+ # Human-QA verbs (staff-only). `pending` lists rows awaiting review; `verify`
76
+ # is idempotent; `reject` requires a structured `--reason` and notifies the
77
+ # creator; `rejection-report` aggregates rejected rows with reason breakdown.
78
+ CMD crm backlink pending --domain <id> --client <id>
79
+ CMD crm backlink verify <id>
80
+ CMD crm backlink reject <id> --reason <spammy_source|wrong_anchor|wrong_target|nofollow_unexpected|dead_on_arrival|duplicate|policy_violation|other> --notes <text>
81
+ CMD crm backlink rejection-report --domain <id> --client <id> --since-days <n>
82
+
83
+ CMD crm offer list-tasks <offer-id>
28
84
 
29
85
  CMD crm change list --domain <id> --url <url> --since <iso>
30
86
 
@@ -34,7 +90,21 @@ CMD crm scope get <id>
34
90
  CMD crm competitor list --domain <id>
35
91
 
36
92
  CMD crm tag list
37
- CMD crm member list
93
+ # member list filters help resolve a name fragment to a memberId before composing @[Name](id).
94
+ CMD crm member list --query <text> --email <text> --client <id> --domain <id> --role <csv>
95
+ CMD crm member profile <id>
96
+ CMD crm member profile-set <id> --title <text> --bio <text> --expertise <csv> --preferred-contact <text> --timezone <iana> --working-hours <text> --internal-notes <md>
97
+
98
+ # Mention resolvers — print the markdown chip on stdout, exit 8 on ambiguous, 2 on no match.
99
+ # Compose into writes via shell substitution: --body "$(crm mention member luis) ping"
100
+ CMD crm mention member <query> --client <id> --domain <id> --role <csv>
101
+ CMD crm mention task <query> --domain <id> --status <status>
102
+
103
+ # Agent memory primer — aggregates client profile + all domain profiles + assigned staff.
104
+ # Call this before drafting client-visible content (comments, task titles, proposals).
105
+ # --domain narrows to staff with activity on a domain + open tasks under it.
106
+ # --task is the URL-of-tasks: participants + parent domain + cross-refs already linked.
107
+ CMD crm brief [clientId] --domain <id> --task <id>
38
108
 
39
109
  CMD crm recall <url> --since <iso>
40
110
  # search result rows: { id, kind: task|description|comment|change, score, snippet, breadcrumb[] }
@@ -48,6 +118,81 @@ CMD crm review list --mine --key <apiKeyId>
48
118
  CMD crm review show <task|comment|edit> <id>
49
119
  CMD crm review approve <task|comment|edit> <id>
50
120
  CMD crm review reject <task|comment|edit> <id> --reason <text>
121
+ # Agent iteration loop — read your own rejected proposals + the reviewer's
122
+ # reason. `--retryable-only` filters to items the reviewer wants you to redo.
123
+ CMD crm review feedback --retryable-only --key <apiKeyId>
124
+ # Bulk approve / reject — items via stdin (NDJSON or 'kind:id' tokens; ≤100).
125
+ # Example: crm review list --mine --jq '.data[] | "\(.kind):\(.id)"' | crm review bulk-approve
126
+ CMD crm review bulk-approve
127
+ CMD crm review bulk-reject --reason <text> --no-retry
128
+
129
+ # Access requests — chat-driven flow. Clients (or agents acting as clients)
130
+ # request access to a task they spotted in a chat thread; staff resolve.
131
+ # The verbs used to live under `crm task {request,list,approve,deny}-access`
132
+ # (still work for one release with a deprecation hint).
133
+ CMD crm access request <task-id> --via <message-id> --message <text>
134
+ CMD crm access list
135
+ CMD crm access approve <request-id> --scope <task|board> --note <text>
136
+ CMD crm access deny <request-id> --note <text>
137
+
138
+ # Workspace-wide rollup of all properties for a date range — useful for
139
+ # overview prompts. Sources from Tinybird.
140
+ CMD crm dashboard summary --start <date> --end <date>
141
+
142
+ CMD crm integration list
143
+ CMD crm integration sites --account <id> --service <gsc|ga4|bing>
144
+ CMD crm integration sync --property <id>
145
+
146
+ # gsc/ga4/bing query hit the live provider API (tokens stay on server).
147
+ # --filters is ';'-separated. Format: "<dim> <op> <expr>; ..."
148
+ # Operators (GSC + Bing): equals | contains | regex | not_equals | not_contains | not_regex
149
+ # Operators (GA4 adds): batch (inListFilter; value is newline-separated)
150
+ CMD crm gsc query --property <id> --account <id> --site-url <url> --start <date> --end <date> --dimension <date|page|query|country|device> --filters <expr> --cursor <n>
151
+ CMD crm ga4 query --property <id> --account <id> --ga4-property <num> --start <date> --end <date> --filters <expr>
152
+ CMD crm bing query --property <id> --account <id> --site-url <url> --start <date> --end <date>
153
+
154
+ # Agency skills — librería de playbooks para Claude Code. `pull` escribe en
155
+ # `.claude/skills/<slug>/SKILL.md` + recursos; el manifest se guarda en
156
+ # `.claude/skills/.crm-manifest.json` para que `update` detecte desactualizados.
157
+ CMD crm skill list --category <name> --status <draft|published|archived> --tag <id> --q <text>
158
+ CMD crm skill show <slug> --revision <id>
159
+ CMD crm skill pull <slug> --revision <id> --dry-run
160
+ CMD crm skill pull --all --category <name> --tag <id>
161
+ CMD crm skill update --dry-run
162
+ CMD crm skill diff <slug>
163
+
164
+ CMD crm time log --task <id> --description <text> --date <YYYY-MM-DD> --started-at <epoch|iso> --ended-at <epoch|iso> --duration <minutes>
165
+ CMD crm time list --from <YYYY-MM-DD> --to <YYYY-MM-DD> --user <id>
166
+ # Entries linked to a specific task (no date filter).
167
+ CMD crm time list-task <taskId>
168
+ CMD crm time status
169
+ CMD crm time start --task <id> --description <text>
170
+ CMD crm time stop --description <text>
171
+ CMD crm time discard
172
+ CMD crm time update <id> --started-at <epoch|iso> --ended-at <epoch|iso> --description <text> --task <id>
173
+ CMD crm time delete <id> --reason <text>
174
+ CMD crm time hours <YYYY-MM> --employee <email>
175
+ CMD crm time budgets
176
+ CMD crm time usage <id>
177
+
178
+ # Report schedules — list/get/run/snapshots/approve/reject covered. CRUD
179
+ # bodies are too rich for flat flags; `create` and `update` take JSON via
180
+ # --body (inline string | '@file.json' | '-' for stdin).
181
+ CMD crm report types
182
+ CMD crm report list
183
+ CMD crm report get <id>
184
+ CMD crm report create --body <json|@path|->
185
+ CMD crm report update <id> --body <json|@path|->
186
+ CMD crm report delete <id>
187
+ CMD crm report run <id>
188
+ CMD crm report snapshots --schedule <id> --limit <n>
189
+ CMD crm report snapshot <id>
190
+ CMD crm report approve <id> --note <text>
191
+ CMD crm report reject <id> --reason <text>
192
+
193
+ # Dump the full CLI surface as JSON so agents can introspect without help-text
194
+ # parsing. `{ data: { tree, flat } }` — `flat` is the linear command list.
195
+ CMD crm commands
51
196
 
52
197
  CMD crm doctor
53
198