@roilab/crm-cli 0.12.0 → 0.14.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.
package/SKILL.md CHANGED
@@ -1,587 +1,602 @@
1
- ---
2
- name: crm
3
- description: Drive the ROILab SEO+CRM from a shell. Tasks, comments, file attachments, chat threads, analytics, backlinks, change events, and cross-entity recall — every action is auditable and attributed to you as an agent.
4
- ---
5
-
6
- # `crm` — CLI for AI agents + humans
7
-
8
- This skill teaches you to operate the ROILab SEO+CRM via the `crm` binary. All writes you make are stamped `actorType: "agent"` and associated with your API key, so there is a robot badge next to your changes in the web UI. Humans can filter and review what you did.
9
-
10
- ## Capabilities you might miss (flags, not verbs)
11
-
12
- Some features ship as **flags on existing commands**, not as new subcommands —
13
- if you only list verbs (`crm task --help`) you won't see them. Look for these:
14
-
15
- | Flag | Where | What it does |
16
- |---|---|---|
17
- | `--file <path...>` | `crm task create` / `task update` / `comment create` / `chat send` / `chat reply` | Adjunta archivo(s) en la misma escritura. Repetible. Máx 10 MB; aviso desde 2 MB. Detalles en "Adjuntar archivos" más abajo. |
18
- | `--shadow` | cualquier write | Fuerza propuesta pendiente de revisión humana. |
19
- | `--wait-for-approval --timeout 30m` | cualquier write con shadow | Bloquea hasta que un humano decida. |
20
- | `--idempotency-key <key>` | cualquier write | Reintentos seguros entre invocaciones. |
21
- | `--ids-only` / `--quiet` / `--count` / `--markdown` / `--jq <expr>` | cualquier comando | Modos de salida (mutuamente excluyentes salvo `--jq`). |
22
-
23
- Si dudas si una capacidad existe, **revisa los flags de cada verbo**
24
- (`crm <noun> <verb> --help`), no sólo la lista de verbos. También puedes
25
- grepear `cli/SURFACE.txt` (envoltura plana de la superficie).
26
-
27
- ## Getting started
28
-
29
- Two ways to authenticate, pick the one that matches your environment.
30
-
31
- **Device flow — for human-driven use (recommended):**
32
-
33
- ```bash
34
- crm auth login --api-url https://crm.roilab.es
35
- # Prints a URL + 8-char code. Open the URL in your already-signed-in
36
- # browser and click "Approve". The CLI polls and stores a 1-hour access
37
- # token + 30-day refresh token. Tokens auto-rotate; nothing long-lived
38
- # ends up on disk.
39
- ```
40
-
41
- **API key — for unattended use (CI, agents-as-a-service):**
42
-
43
- ```bash
44
- export CRM_API_KEY=crm_ak_... # or crm auth login crm_ak_...
45
- crm doctor # verify reachability + auth
46
- crm task list --status todo --limit 5
47
- ```
48
-
49
- API keys are long-lived and workspace-scoped; leak-sensitive. Prefer the
50
- device flow for interactive use; use raw keys only where a browser isn't
51
- available.
52
-
53
- If you need a new API key, ask the human to visit `Settings → Developers
54
- → API Keys` in the web UI and share one.
55
-
56
- ## Output contract — read this carefully
57
-
58
- Every command emits a JSON envelope. Use `--jq` for filtering, **never pipe to `jq`**:
59
-
60
- ```bash
61
- crm task list --jq '.data[].title' # OK
62
- crm task list | jq '.data[].title' # WRONG — the envelope matters
63
- ```
64
-
65
- Flags (mutually exclusive except `--jq`):
66
- - `--json` — default. Full envelope with `ok`, `data`, `summary`, `breadcrumbs`, `meta`.
67
- - `--quiet` — just `data`. Good for pipelines.
68
- - `--ids-only` — one id per line.
69
- - `--count` — a single integer.
70
- - `--markdown` — human preview (NOT JSON, do not parse).
71
- - `--jq <expr>` — tiny path filter: `.a`, `.a.b`, `.a[]`, `.a[].b`, `.a[0]`, `.`. **Pipes (`|`), string interpolation (`\(.x)`), and object/array projection (`{…}`, `[.]`) are NOT supported** — pipe through real `jq` after `--quiet` if you need those.
72
-
73
- Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit codes:
74
-
75
- | Code | Meaning |
76
- |------|---------|
77
- | 0 | success |
78
- | 2 | not found |
79
- | 3 | auth failure |
80
- | 4 | forbidden / missing scope |
81
- | 5 | rate-limited |
82
- | 6 | network / timeout |
83
- | 7 | validation |
84
- | 8 | ambiguous ("which one did you mean?") |
85
- | 9 | conflict / idempotency key mismatch |
86
- | 10 | business rule violation |
87
-
88
- ## Work as an agent, not a human
89
-
90
- 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:
91
-
92
- ```bash
93
- crm task preflight \
94
- --title "Arreglar H1 en /pricing" \
95
- --url https://example.com/pricing \
96
- --domain dom_xyz \
97
- --jq .data.hints
98
- ```
99
-
100
- El envelope trae 6 secciones acotadas (≤5 items por defecto):
101
- `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:
102
-
103
- - 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)`.
104
- - Si `urlScopedTasks` no está vacío → la URL ya tiene cargas abiertas; añade un comentario o referencia, no dupliques.
105
- - Si `openTaskCounts.todo + .doing + .blocked >= 8` → el dominio está sobrecargado; pregunta al humano antes de añadir más.
106
- - `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.
107
-
108
- **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.
109
-
110
- `crm recall` sigue existiendo como herramienta cruda para análisis post-hoc; el preflight ya la incluye.
111
-
112
- 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`:
113
- ```bash
114
- crm comment create --task tsk_abc --kind decision \
115
- --body "Chose to revert meta title; A/B showed −8% CTR in 14d"
116
- ```
117
-
118
- 3. **Mark completed tasks explicitly**. Pair the status change with a `--kind decision` comment that explains the outcome — that's what the UI surfaces as the closing summary:
119
- ```bash
120
- crm task update tsk_abc --status done
121
- crm comment create --task tsk_abc --kind decision \
122
- --body "Cerrado: H1 reemplazado, A/B +12% CTR a 14d (ver crm change list)"
123
- ```
124
-
125
- 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). (The flag has only been wired end-to-end since 0.6.0 — earlier CLIs sent it but the server stripped it.)
126
-
127
- **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`).
128
-
129
- 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.
130
-
131
- 6. **You choose shadow or autonomous per write**. Every write has two possible fates:
132
- - **autonomous** — the write lands live immediately.
133
- - **shadow** — the write lands as a pending proposal; the human reviews + approves / rejects in `/dashboard/inbox` before it materialises.
134
-
135
- How it gets decided on a single call:
136
- - Your key has a per-action default (`autonomous` or `shadow`). Absence ⇒ `autonomous`.
137
- - Pass `--shadow` on the command to *upgrade* this specific call into shadow (e.g. for risky or irreversible writes). This is strictly safer and **always honored**.
138
- - You **cannot** downgrade a key's `shadow` default to autonomous on a per-call basis. If a human set your key to shadow-by-default for an action, they wanted review every time. If you need autonomy, ask the human to update the key policy.
139
- - **Hard deny** (you cannot perform this action at all) is *not* a policy value — it's expressed via `scopes` on the key. A missing scope returns a plain 403; it never enters the shadow/autonomous decision.
140
-
141
- Once a write is in shadow mode:
142
- - `meta.approvalStatus === "pending"` on the envelope. Do not create follow-up work (comments, edits, change events) that depends on it being visible — it is not.
143
- - Either poll with `crm review show <kind> <id>` until the status changes, or add `--wait-for-approval --timeout 30m` to the write so the CLI blocks for you.
144
- - Check your own pending queue with `crm review list --mine`.
145
- - The response envelope includes breadcrumbs: "Poll decision" (for you) and "View in Inbox" (for the human).
146
-
147
- **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.
148
-
149
- 7. **After every write that returns an id, surface the full dashboard URL to the human.** When you report a `create` or `update` result back in chat, paste the complete `https://crm.roilab.es/dashboard/<entity>/<id>` URL alongside the id so the human can copy-paste it straight into the browser. The CLI envelope returns the id in `data.id` (and `data._id` for tasks). Build the URL with the API root from the active profile (default `https://crm.roilab.es`; check `crm doctor` if unsure).
150
-
151
- | Entity | URL template |
152
- |---|---|
153
- | Task | `https://crm.roilab.es/dashboard/tasks?taskId=<id>` |
154
- | Backlink | `https://crm.roilab.es/dashboard/backlinks/<id>` |
155
- | Domain | `https://crm.roilab.es/dashboard/domains/<id>` |
156
- | Client | `https://crm.roilab.es/dashboard/clients/<id>` |
157
- | Chat thread | `https://crm.roilab.es/dashboard/chat?t=<threadId>` |
158
- | Chat message (deep link) | `https://crm.roilab.es/dashboard/chat?m=<messageId>` |
159
-
160
- **Do NOT confuse this with `[[feedback_task_refs_use_chip_syntax]]`**: inside task descriptions, comments, and chat bodies you still use `#[Title](taskId)` chips, never raw dashboard URLs. The dashboard URL goes only in your chat reply to the human reviewing your work — that is where they need a one-click destination.
161
-
162
- ## Mentioning humans + linking tasks
163
-
164
- Comments and task descriptions are markdown. Two special syntaxes — both
165
- already wired up to fan out the right side effects when the row lands live:
166
-
167
- - **`@[Name](memberId)`** — pings a workspace member. Fires a
168
- `comment_mentioned` notification + email. **Important authorization side
169
- effect:** mentioning a `client` user auto-grants them domain access for
170
- this task. Mentioning a `client_lead` outside their own client is rejected.
171
- - **`#[Title](taskId)`** — adds a graph edge between tasks (parent / blocker
172
- / duplicate-of / follow-up). Updates the target's "Referenced by" panel.
173
- No notification fires — purely a graph operation.
174
-
175
- ### Anti-pattern: NEVER reference a task by bare id
176
-
177
- Whenever you mention another task — in a description, a comment, a
178
- `## Tareas relacionadas` block, an audit trail, anywhere markdown is
179
- rendered — use the chip syntax `#[Título](taskId)`. **A bare id in
180
- backticks is dead text**: no clickable link, no graph edge, no
181
- "Referenced by" entry, and human readers have to copy-paste it into the
182
- URL bar to navigate.
183
-
184
- ```markdown
185
- ❌ Bad — `m172v5tesszx27fhbfmj7abb45868z64` — "Modificar hreflang en dominio .NET"
186
- ❌ Bad — https://crm.roilab.es/dashboard/tasks?taskId=m172v5tesszx27fhbfmj7abb45868z64
187
- ✅ Good — #[Modificar hreflang en dominio .NET](m172v5tesszx27fhbfmj7abb45868z64)
188
- ```
189
-
190
- This applies equally to inline mentions and to lists. A `## Tareas
191
- relacionadas` bullet must lead with the chip, not with the id:
192
-
193
- ```markdown
194
- - #[Eliminar hreflang chile de la home y ajustar hreflang es](m1716nym1jej9vevfnmgp6yzhn869vbz) (done 2024-05-30) → quitó `hreflang="es-CL"`…
195
- ```
196
-
197
- Special characters in the title (`[`, `]`, parens) must be backslash-escaped
198
- so the markdown round-trips through the tokenizer:
199
-
200
- ```markdown
201
- #[\[GB\] Eliminar hreflangs apuntando hacia growbarato.it](m1767y1wqrz93q3kvqtej350398695fj)
202
- #[Añadir nuevo schema Carousel \(ItemList\) en categorías](m178j0p99dwmfcwy37c0jr9t3s86819z)
203
- ```
204
-
205
- When you don't know the title off the top of your head, **resolve it
206
- first** — see the next subsection. Don't fall back to a bare id "for now";
207
- you'll forget to come back.
208
-
209
- ### Resolve IDs before composing
210
-
211
- Don't hand-roll memberIds or taskIds. Use the resolver helpers; they exit
212
- non-zero when the query is wrong:
213
-
214
- ```bash
215
- # Resolve a name → markdown chip. Exits 8 if ambiguous, 2 if no match.
216
- crm mention member "luis" # → @[Luis Fernández](mem_abc)
217
- crm mention member --domain dom_xyz "sarah"
218
- crm mention task "fix h1 pricing" # → #[Fix H1 on /pricing](tsk_xyz)
219
-
220
- # Or list candidates first if you want to pick by hand:
221
- crm member list --query "luis"
222
- crm member list --domain dom_xyz --role member,admin
223
- crm task search "h1" --limit 10
224
- ```
225
-
226
- Compose into a write with shell substitution — the chips are plain markdown,
227
- not JSON:
228
-
229
- ```bash
230
- crm comment create --task tsk_abc \
231
- --body "$(crm mention member luis) please check the audit results — \
232
- blocking $(crm mention task 'crawl audit GB')"
233
- ```
234
-
235
- If the resolver exits 8 the shell substitution captures stderr (not stdout),
236
- so the outer command will land with a literal empty chip — that's the
237
- intended failure mode. Read the stderr disambiguation hint and re-run.
238
-
239
- ### Assemble context BEFORE mentioning anything
240
-
241
- The legitimate pool of mentionable members for a write is **the union of**:
242
- the existing task's assignees + collaborators (already inlined as
243
- `participants` on `crm task get`), the staff returned by `crm brief`, and
244
- anyone the human explicitly named. Anything outside that pool is almost
245
- always the wrong person — ask before mentioning.
246
-
247
- ```bash
248
- # For an existing task: pulls participants (with role + expertise) + parent
249
- # domain brief + cross-references already linked. Run this BEFORE adding a
250
- # comment.
251
- crm brief --task tsk_abc
252
-
253
- # For a new task: scope to the domain so the staff list is the working pool.
254
- crm brief --domain dom_xyz
255
-
256
- # For "is there already a task tracking this?" before adding a #link:
257
- crm task related tsk_abc # tasks already linked + same-domain + shared-tags
258
- crm recall https://example.com/pricing
259
- ```
260
-
261
- `crm brief --task` is the URL-equivalent of `recall` for tasks: the right
262
- pre-write context every time.
263
-
264
- #### Sensitive handling notes
265
-
266
- Profile responses carry an `internalNotes` field (markdown, staff-only) on
267
- clients, domains and members. Treat it as binding handling guidance, not
268
- flavour text — it's where the human team writes things like "never mention
269
- project X to this CEO", "always cc Eric Collado as follower on every task",
270
- "careful — this person prefers blunt feedback". Always read these before
271
- drafting any comment, mention or task that touches the entity. They flow
272
- through automatically on:
273
-
274
- - `crm brief <clientId>` → `clientProfile.internalNotes` and per-domain / per-staff notes
275
- - `crm brief --domain <id>` → domain + parent client + staff with activity
276
- - `crm brief --task <id>` → each `participants[].internalNotes` + parent domain + parent client
277
- - `crm client profile <id>` / `domain profile <id>` / `member profile <id>` → single-entity fetch
278
- - `crm task get <id>` → `participants[].internalNotes` for staff callers
279
-
280
- Never echo `internalNotes` into client-visible surfaces (shared chat threads,
281
- client-visible tasks, replies through the portal). They are agency-internal.
282
-
283
- ### When to mention vs. not
284
-
285
- - **Mention** when attention is genuinely needed *now*: a decision blocking
286
- next steps, a completed item awaiting review, a regression you've spotted.
287
- - **Don't mention** on routine `agent_log` traces ("ran the audit, here's
288
- the output"). The volume drowns inboxes; the badge already shows it's
289
- agent work.
290
- - **`#`-link** when the relationship is real graph (blocker, duplicate-of,
291
- follow-up). Not as decoration, not to "show your work" — that goes in
292
- prose.
293
- - **Self-mentions are filtered server-side** so you don't ping your own
294
- underlying member.
295
-
296
- ### Notifications fire on approval, not on submission
297
-
298
- This is the rule that matters for shadow-mode writes:
299
-
300
- - **Autonomous write** with `@[Name](id)` → notification fires immediately,
301
- scope grants apply immediately, `taskMentions` index updates immediately.
302
- - **Shadow proposal** with `@[Name](id)` → **nothing fires until a human
303
- approves**. The chip renders to reviewers in the markdown so they can see
304
- the intent, but the mentioned user is not pinged, no scope is granted, no
305
- graph edge lands. On approval, all three side effects fire — attributed
306
- to the original agent's name (so the user reads "Agent X mentioned you")
307
- but the notification's `createdAt` is the approval moment.
308
- - **Shadow proposal that's rejected** → side effects never fire. The chip
309
- goes nowhere.
310
-
311
- The point: a `--shadow` write that mentions someone is not a way to "ping
312
- them with a heads-up before review." It's a deferred mention. If you need
313
- the human aware before approval, write a `--kind decision` autonomous
314
- comment.
315
-
316
- ### Edits to descriptions are diffed
317
-
318
- Updating a task's description with a new `@mention` only fires for the
319
- **newly added** mention, not the ones already present. Same for `#`-links.
320
- You can safely edit a description that already references people without
321
- re-pinging them.
322
-
323
- ## Adjuntar archivos
324
-
325
- Cuatro comandos aceptan `--file <ruta>` (repetible) y suben el archivo a
326
- Convex storage antes de enviar la escritura:
327
-
328
- - `crm chat send <threadId> --file <ruta>` y `crm chat reply <msgId> --thread <id> --file <ruta>`
329
- - `crm task create --file <ruta>` y `crm task update <id> --file <ruta>`
330
- - `crm comment create --task <id> --file <ruta>`
331
-
332
- El flujo siempre es el mismo (dos pasos: URL firmada → `POST` directo a Convex
333
- storage). Reglas y límites compartidos:
334
-
335
- - **Máx 10 MB por archivo** — el CLI rechaza localmente antes de tocar la red.
336
- - **Aviso a partir de 2 MB** en stderr (`[AVISO] ... la subida puede tardar.`).
337
- - MIME se sniffa por extensión; lo desconocido viaja como `application/octet-stream`,
338
- que el servidor acepta y la UI renderiza como tarjeta genérica.
339
- - `--body` (chat / comentario) es opcional si pasas `--file` (mensajes /
340
- comentarios sólo-archivos están permitidos).
341
- - **Cuidado con `task update --file`**: la lista de adjuntos es REEMPLAZO,
342
- no merge. Los archivos previos desaparecen. Para vaciar explícitamente, usa
343
- `--clear-files`; para conservar los previos hay que pasarlos también.
344
- - **Para añadir/quitar UN archivo sin tocar el resto** usa `task attach` en vez
345
- de `task update --file` (que reemplaza toda la lista):
346
- - `crm task attach list <taskId>` — lista los adjuntos (con su `_id`).
347
- - `crm task attach add <taskId> --file <ruta...>` — añade sin clobber.
348
- - `crm task attach remove <taskId> <attachmentId>` — quita uno por id.
349
- Tope: 50 archivos/tarea. Los clientes pueden adjuntar a tareas que ven.
350
-
351
- ```bash
352
- # Chat
353
- crm chat send "$TID" --body "captura del 404" --file ./bug.png
354
- crm chat reply <msgId> --thread "$TID" --file ./report.pdf --file ./logs.txt
355
-
356
- # Tarea — en la creación / reemplazo total
357
- crm task create --title "Migración H1" --domain dom_xyz --file ./brief.pdf
358
- crm task update tsk_abc --file ./new-spec.pdf --clear-files
359
-
360
- # Tarea — gestión incremental de adjuntos (sin reemplazar la lista)
361
- crm task attach add tsk_abc --file ./extra.pdf --file ./shot.png
362
- crm task attach list tsk_abc
363
- crm task attach remove tsk_abc att_xyz
364
-
365
- # Comentario
366
- crm comment create --task tsk_abc --kind decision \
367
- --body "Cerrado: ver diff y screenshots" \
368
- --file ./before.png --file ./after.png
369
- ```
370
-
371
- ## Common recipes
372
-
373
- ```bash
374
- # Read-only triage before acting
375
- crm task preflight --title "Fix H1 on /pricing" --url https://example.com/pricing --domain dom_xyz
376
- crm change list --domain dom_xyz --url /pricing --jq '.data[].items[].type'
377
- crm backlink lost --domain dom_xyz --since 2026-01-01 --count
378
-
379
- # Create a measured task — sólo si el preflight no encontró duplicados
380
- crm task create \
381
- --title "Fix H1 on /pricing" \
382
- --domain dom_xyz \
383
- --description "Current H1 buries the value prop; replace with 'Plans that scale with you'." \
384
- --idempotency-key 01HY8X...
385
-
386
- # Log change events after shipping — SOLO en tareas de Redacción (kind:
387
- # "content"). Las tareas generales no registran cambios on-page y el backend
388
- # los rechaza. No hay verbo CLI todavía; hit the REST endpoint directly:
389
- # POST /api/v1/domains/<domainId>/changes (autogenerates an idempotency key
390
- # per call; same envelope contract).
391
-
392
- # Search across everything
393
- crm search "meta title" --kind change --domain dom_xyz --limit 5
394
-
395
- # Live provider-API queries (tokens stay on the server)
396
- crm integration list --quiet | jq -r '.[] | "\(._id) \(.provider) \(.services|join(","))"'
397
- crm gsc query --property prop_abc --dimension page \
398
- --filters "page contains /blog/" --start 2026-03-01 --end 2026-04-01 --limit 50
399
- crm ga4 query --property prop_abc --start 2026-03-01 --end 2026-04-01 \
400
- --filters "pagePath contains /pricing"
401
- crm bing query --property prop_bing --start 2026-03-01 --end 2026-04-01
402
- crm integration sync --property prop_abc # forces fresh ingestion (15m cooldown)
403
-
404
- # Agency skills — read the library + sync it to disk so Claude Code picks it up
405
- crm skill list --category local-seo --quiet # all published in category
406
- crm skill show auditoria-seo-local # metadata + revision id
407
- crm skill revisions auditoria-seo-local # publish history
408
- crm skill revision <revisionId> # single immutable revision
409
- crm skill pull --all # writes .claude/skills/<slug>/SKILL.md
410
- crm skill update # refresh any outdated skill
411
- crm skill diff auditoria-seo-local # local vs remote state
412
-
413
- # Agency skills — authoring (owner / admin / member with skills:write)
414
- crm skill create --slug my-playbook --name "Mi playbook" \
415
- --description "Cuándo y cómo aplicarlo" --category content
416
- crm skill set my-playbook --visibility staff_only # metadata-only PATCH
417
- crm skill push my-playbook --note "primera revisión" --publish # body+frontmatter
418
- crm skill archive my-playbook # hide from library
419
- crm skill restore my-playbook # un-archive
420
-
421
- # Chat — read threads, post messages, react, attach files (max 10 MB each)
422
- crm chat list --scope client --client cli_abc
423
- crm chat get <threadId> --message-limit 50 # metadata + recent msgs
424
- crm chat read <threadId> --page-limit 50 --before <ms> # paginate backwards
425
- crm chat send <threadId> --body "$(crm mention member luis) revisado"
426
- crm chat send <threadId> --body "informe adjunto" --file ./audit.pdf --file ./serp.png
427
- crm chat reply <messageId> --thread <threadId> --body "ok, mañana"
428
- crm chat react <messageId> --emoji "👀" # toggle (re-run unreacts)
429
- crm chat dm --member mem_xyz --title "1:1 review"
430
- crm chat mark-read <threadId>
431
- ```
432
-
433
- ## Playbooks de tarea incluidos en este paquete
434
-
435
- Este paquete trae playbooks en `skill-bundles/tools/<name>/SKILL.md` — viajan
436
- con el CLI, así que sólo quien se baja/actualiza el CLI los tiene. Cuando una
437
- tarea encaje con uno, **cárgalo y síguelo** (no improvises el método):
438
-
439
- - **`tool-routing`** — matriz para elegir qué herramienta externa usar.
440
- - **`task-preflight`** — cómo leer `crm task preflight` antes de crear tareas.
441
-
442
- Además, la **librería de skills de la agencia** (Convex, no bundled) trae
443
- playbooks que se bajan a `.claude/skills/` con `crm skill pull <slug>`:
444
-
445
- - **`optimizar-metas`** — metodología para optimizar/validar **meta title +
446
- meta description** de una URL: valida la KW en el Rank Tracker (Ahrefs **sin
447
- gastar créditos**) → analiza GSC de la URL → clasifica la SERP y mira a los
448
- competidores → **desambigua y caza canibalización** entre URLs propias, y sólo
449
- entonces redacta. Para una tarea "Optimizar PDP / metas":
450
- `crm skill pull optimizar-metas` y síguelo.
451
-
452
- ## Decision tree for analytics questions
453
-
454
- 1. **Rollups / trends** → `crm domain metrics <id> --start … --end …`. Reads from Tinybird; cheap and fast.
455
- 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.
456
- 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.
457
-
458
- 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.
459
-
460
- ## Things that are not obvious
461
-
462
- - 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.
463
- - **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.
464
- - **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.
465
- - **Bing daily feed has no per-query/per-page breakdown**. `crm bing query` returns the aggregate with a `meta.note` saying so.
466
- - Web UI paths: `/dashboard/tasks?taskId=<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.
467
-
468
- ## Task participants — assignees vs collaborators
469
-
470
- Two distinct member lists on every task:
471
-
472
- - **`--assignee <id...>`** — the **responsible** parties. Their queue counts include this task; auto-assigned watchers; show up first in the UI.
473
- - **`--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).
474
-
475
- 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.
476
-
477
- 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.
478
-
479
- ## Reading rejection feedback (iteration loop)
480
-
481
- 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).
482
-
483
- ```bash
484
- # Just the actionable ones — items the reviewer wants you to redo.
485
- crm review feedback --retryable-only
486
-
487
- # Everything that's been rejected for this API key, with reasons.
488
- crm review feedback
489
- ```
490
-
491
- 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.
492
-
493
- ## Access requests — `crm access`
494
-
495
- 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:
496
-
497
- ```bash
498
- # Client side — file the request, citing the chat message that exposed the task.
499
- crm access request <task-id> --via <message-id> --message "Need to review the H1 fix"
500
-
501
- # Staff side — list pending, then approve or deny with a scope choice.
502
- crm access list
503
- crm access approve <request-id> --scope task # smallest blast radius
504
- crm access approve <request-id> --scope board # whole board (for cross-client tasks)
505
- crm access deny <request-id> --note "Task is internal QA"
506
- ```
507
-
508
- 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.
509
-
510
- ## Backlink human-QA
511
-
512
- Linkbuilding rows can sit in a pending-review queue until staff verifies the source. Agents with `backlinks:verify` scope can drive the queue:
513
-
514
- ```bash
515
- crm backlink pending --domain dom_xyz
516
- crm backlink verify <id> # idempotent
517
- crm backlink reject <id> --reason wrong_anchor --notes "Anchor text drifted to brand-only"
518
- crm backlink rejection-report --client cli_xyz --since-days 90
519
- ```
520
-
521
- 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.
522
-
523
- ### Manual health-status override
524
-
525
- `status` (active/removed/nofollowed/…) is the automated probe's verdict; it's orthogonal to the verify/reject QA verdict above. When the crawler gets a row wrong, override it (audited):
526
-
527
- ```bash
528
- crm backlink set-status <id> --status non_crawlable --note "Enlace dentro de documento Issuu — hotspot JS, no rastreable"
529
- crm backlink set-status <id> --status active --note "Verificado: <a> dofollow real cargado por JS (SPA); el fetch http no lo veía"
530
- crm backlink set-status <id> --status manual_override --note "Parqueado: …" # 'manual_override' detiene el cron
531
- ```
532
-
533
- If the registered source URL is simply wrong (points at a profile sub-tab that doesn't carry the link, but a sibling page does), fix the URL instead of overriding the status — the cron then re-validates the right page:
534
-
535
- ```bash
536
- crm backlink update <id> --source-url "https://host/correct-page"
537
- ```
538
-
539
- The cron now auto-classifies flipbook/document hosts (Issuu, Calameo, Yumpu reader, Scribd) as `non_crawlable` — their link is a per-page JS hotspot, not a crawlable `<a href>`, so it's neither `removed` nor a live followable link. For SPA/UA-403 hosts the health check falls back to a real headless render before declaring a link dead. Use `set-status` only when you've verified the live page yourself and the automation still disagrees.
540
-
541
- ## Perfiles sociales (`crm social`)
542
-
543
- Los handles sociales de cada dominio (y los de marca global del cliente) viven en una tabla propia. Léelos antes de redactar contenido social o de proponer diversificación de enlaces — saber qué cuentas existen evita inventar handles.
544
-
545
- ```bash
546
- crm social list --domain dom_xyz # perfiles de un sitio
547
- crm social list --client cli_abc # + handles de marca sin dominio
548
- crm social create --domain dom_xyz --platform instagram --handle growbarato \
549
- --url https://instagram.com/growbarato --primary
550
- crm social create --client cli_abc --platform other --label Crunchbase \
551
- --url https://www.crunchbase.com/organization/growbarato
552
- crm social update soc_123 --notes "Cuenta oficial verificada"
553
- crm social delete soc_123 # archiva (borrado suave, restaurable)
554
- ```
555
-
556
- Reglas: indica `--domain` (perfil del sitio) **o** `--client` (handle de marca sin sitio concreto). `platform` es un catálogo cerrado (`instagram | facebook | x | youtube | tiktok | linkedin | pinterest | threads | trustpilot | other`); `other` exige `--label`. El handle se normaliza quitando la `@`. `--internal-notes` queda staff-only (no se muestra al cliente). Scope `social:write` — staff-only.
557
-
558
- ## Bulk approve / reject your queue
559
-
560
- `crm review` supports bulk operations via stdin (NDJSON or `kind:id` tokens, ≤100 per call):
561
-
562
- ```bash
563
- # Approve every pending proposal from your key. The CLI's mini-jq only
564
- # walks paths — it doesn't support `|` or string interpolation — so use
565
- # real `jq` after `--quiet` for the projection:
566
- crm review list --mine --quiet \
567
- | jq -r '[.tasks[]|"task:"+.id, .comments[]|"comment:"+.id, .edits[]|"edit:"+.id] | .[]' \
568
- | crm review bulk-approve
569
-
570
- # Reject many with one reason (allowRetry defaults to true):
571
- printf 'task:tsk_a\ntask:tsk_b\n' | crm review bulk-reject --reason "Out of scope this quarter"
572
- ```
573
-
574
- ## Escape hatches
575
-
576
- - `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.
577
- - `crm doctor --json` — always safe; doesn't mutate anything. Also forces a fresh npm registry check.
578
- - `crm auth whoami` — what identity am I acting under? Check this first if attribution looks wrong in the UI.
579
-
580
- ## Update notifications
581
-
582
- Two channels surface a stale CLI version, both shown via stderr (never on stdout — they don't break `--quiet` pipes):
583
-
584
- - **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.
585
- - **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.
586
-
587
- 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.
1
+ ---
2
+ name: crm
3
+ description: Drive the ROILab SEO+CRM from a shell. Tasks, comments, file attachments, chat threads, analytics, backlinks, change events, and cross-entity recall — every action is auditable and attributed to you as an agent.
4
+ ---
5
+
6
+ # `crm` — CLI for AI agents + humans
7
+
8
+ This skill teaches you to operate the ROILab SEO+CRM via the `crm` binary. All writes you make are stamped `actorType: "agent"` and associated with your API key, so there is a robot badge next to your changes in the web UI. Humans can filter and review what you did.
9
+
10
+ ## Capabilities you might miss (flags, not verbs)
11
+
12
+ Some features ship as **flags on existing commands**, not as new subcommands —
13
+ if you only list verbs (`crm task --help`) you won't see them. Look for these:
14
+
15
+ | Flag | Where | What it does |
16
+ |---|---|---|
17
+ | `--file <path...>` | `crm task create` / `task update` / `comment create` / `chat send` / `chat reply` | Adjunta archivo(s) en la misma escritura. Repetible. Máx 10 MB; aviso desde 2 MB. Detalles en "Adjuntar archivos" más abajo. |
18
+ | `--shadow` | cualquier write | Fuerza propuesta pendiente de revisión humana. |
19
+ | `--wait-for-approval --timeout 30m` | cualquier write con shadow | Bloquea hasta que un humano decida. |
20
+ | `--idempotency-key <key>` | cualquier write | Reintentos seguros entre invocaciones. |
21
+ | `--ids-only` / `--quiet` / `--count` / `--markdown` / `--jq <expr>` | cualquier comando | Modos de salida (mutuamente excluyentes salvo `--jq`). |
22
+
23
+ Si dudas si una capacidad existe, **revisa los flags de cada verbo**
24
+ (`crm <noun> <verb> --help`), no sólo la lista de verbos. También puedes
25
+ grepear `cli/SURFACE.txt` (envoltura plana de la superficie).
26
+
27
+ ## Getting started
28
+
29
+ Two ways to authenticate, pick the one that matches your environment.
30
+
31
+ **Device flow — for human-driven use (recommended):**
32
+
33
+ ```bash
34
+ crm auth login --api-url https://crm.roilab.es
35
+ # Prints a URL + 8-char code. Open the URL in your already-signed-in
36
+ # browser and click "Approve". The CLI polls and stores a 1-hour access
37
+ # token + 30-day refresh token. Tokens auto-rotate; nothing long-lived
38
+ # ends up on disk.
39
+ ```
40
+
41
+ **API key — for unattended use (CI, agents-as-a-service):**
42
+
43
+ ```bash
44
+ export CRM_API_KEY=crm_ak_... # or crm auth login crm_ak_...
45
+ crm doctor # verify reachability + auth
46
+ crm task list --status todo --limit 5
47
+ ```
48
+
49
+ API keys are long-lived and workspace-scoped; leak-sensitive. Prefer the
50
+ device flow for interactive use; use raw keys only where a browser isn't
51
+ available.
52
+
53
+ If you need a new API key, ask the human to visit `Settings → Developers
54
+ → API Keys` in the web UI and share one.
55
+
56
+ ## Output contract — read this carefully
57
+
58
+ Every command emits a JSON envelope. Use `--jq` for filtering, **never pipe to `jq`**:
59
+
60
+ ```bash
61
+ crm task list --jq '.data[].title' # OK
62
+ crm task list | jq '.data[].title' # WRONG — the envelope matters
63
+ ```
64
+
65
+ Flags (mutually exclusive except `--jq`):
66
+ - `--json` — default. Full envelope with `ok`, `data`, `summary`, `breadcrumbs`, `meta`.
67
+ - `--quiet` — just `data`. Good for pipelines.
68
+ - `--ids-only` — one id per line.
69
+ - `--count` — a single integer.
70
+ - `--markdown` — human preview (NOT JSON, do not parse).
71
+ - `--jq <expr>` — tiny path filter: `.a`, `.a.b`, `.a[]`, `.a[].b`, `.a[0]`, `.`. **Pipes (`|`), string interpolation (`\(.x)`), and object/array projection (`{…}`, `[.]`) are NOT supported** — pipe through real `jq` after `--quiet` if you need those.
72
+
73
+ Errors **always** appear on stderr with full envelope, bypassing `--jq`. Exit codes:
74
+
75
+ | Code | Meaning |
76
+ |------|---------|
77
+ | 0 | success |
78
+ | 2 | not found |
79
+ | 3 | auth failure |
80
+ | 4 | forbidden / missing scope |
81
+ | 5 | rate-limited |
82
+ | 6 | network / timeout |
83
+ | 7 | validation |
84
+ | 8 | ambiguous ("which one did you mean?") |
85
+ | 9 | conflict / idempotency key mismatch |
86
+ | 10 | business rule violation |
87
+
88
+ ## Work as an agent, not a human
89
+
90
+ 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:
91
+
92
+ ```bash
93
+ crm task preflight \
94
+ --title "Arreglar H1 en /pricing" \
95
+ --url https://example.com/pricing \
96
+ --domain dom_xyz \
97
+ --jq .data.hints
98
+ ```
99
+
100
+ El envelope trae 6 secciones acotadas (≤5 items por defecto):
101
+ `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:
102
+
103
+ - 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)`.
104
+ - Si `urlScopedTasks` no está vacío → la URL ya tiene cargas abiertas; añade un comentario o referencia, no dupliques.
105
+ - Si `openTaskCounts.todo + .doing + .blocked >= 8` → el dominio está sobrecargado; pregunta al humano antes de añadir más.
106
+ - `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.
107
+
108
+ **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.
109
+
110
+ `crm recall` sigue existiendo como herramienta cruda para análisis post-hoc; el preflight ya la incluye.
111
+
112
+ 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`:
113
+ ```bash
114
+ crm comment create --task tsk_abc --kind decision \
115
+ --body "Chose to revert meta title; A/B showed −8% CTR in 14d"
116
+ ```
117
+
118
+ 3. **Mark completed tasks explicitly**. Pair the status change with a `--kind decision` comment that explains the outcome — that's what the UI surfaces as the closing summary:
119
+ ```bash
120
+ crm task update tsk_abc --status done
121
+ crm comment create --task tsk_abc --kind decision \
122
+ --body "Cerrado: H1 reemplazado, A/B +12% CTR a 14d (ver crm change list)"
123
+ ```
124
+
125
+ 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). (The flag has only been wired end-to-end since 0.6.0 — earlier CLIs sent it but the server stripped it.)
126
+
127
+ **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`).
128
+
129
+ 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.
130
+
131
+ 6. **You choose shadow or autonomous per write**. Every write has two possible fates:
132
+ - **autonomous** — the write lands live immediately.
133
+ - **shadow** — the write lands as a pending proposal; the human reviews + approves / rejects in `/dashboard/inbox` before it materialises.
134
+
135
+ How it gets decided on a single call:
136
+ - Your key has a per-action default (`autonomous` or `shadow`). Absence ⇒ `autonomous`.
137
+ - Pass `--shadow` on the command to *upgrade* this specific call into shadow (e.g. for risky or irreversible writes). This is strictly safer and **always honored**.
138
+ - You **cannot** downgrade a key's `shadow` default to autonomous on a per-call basis. If a human set your key to shadow-by-default for an action, they wanted review every time. If you need autonomy, ask the human to update the key policy.
139
+ - **Hard deny** (you cannot perform this action at all) is *not* a policy value — it's expressed via `scopes` on the key. A missing scope returns a plain 403; it never enters the shadow/autonomous decision.
140
+
141
+ Once a write is in shadow mode:
142
+ - `meta.approvalStatus === "pending"` on the envelope. Do not create follow-up work (comments, edits, change events) that depends on it being visible — it is not.
143
+ - Either poll with `crm review show <kind> <id>` until the status changes, or add `--wait-for-approval --timeout 30m` to the write so the CLI blocks for you.
144
+ - Check your own pending queue with `crm review list --mine`.
145
+ - The response envelope includes breadcrumbs: "Poll decision" (for you) and "View in Inbox" (for the human).
146
+
147
+ **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.
148
+
149
+ 7. **After every write that returns an id, surface the full dashboard URL to the human.** When you report a `create` or `update` result back in chat, paste the complete `https://crm.roilab.es/dashboard/<entity>/<id>` URL alongside the id so the human can copy-paste it straight into the browser. The CLI envelope returns the id in `data.id` (and `data._id` for tasks). Build the URL with the API root from the active profile (default `https://crm.roilab.es`; check `crm doctor` if unsure).
150
+
151
+ | Entity | URL template |
152
+ |---|---|
153
+ | Task | `https://crm.roilab.es/dashboard/tasks?taskId=<id>` |
154
+ | Backlink | `https://crm.roilab.es/dashboard/backlinks/<id>` |
155
+ | Domain | `https://crm.roilab.es/dashboard/domains/<id>` |
156
+ | Client | `https://crm.roilab.es/dashboard/clients/<id>` |
157
+ | Chat thread | `https://crm.roilab.es/dashboard/chat?t=<threadId>` |
158
+ | Chat message (deep link) | `https://crm.roilab.es/dashboard/chat?m=<messageId>` |
159
+
160
+ **Do NOT confuse this with `[[feedback_task_refs_use_chip_syntax]]`**: inside task descriptions, comments, and chat bodies you still use `#[Title](taskId)` chips, never raw dashboard URLs. The dashboard URL goes only in your chat reply to the human reviewing your work — that is where they need a one-click destination.
161
+
162
+ ## Mentioning humans + linking tasks
163
+
164
+ Comments and task descriptions are markdown. Two special syntaxes — both
165
+ already wired up to fan out the right side effects when the row lands live:
166
+
167
+ - **`@[Name](memberId)`** — pings a workspace member. Fires a
168
+ `comment_mentioned` notification + email. **Important authorization side
169
+ effect:** mentioning a `client` user auto-grants them domain access for
170
+ this task. Mentioning a `client_lead` outside their own client is rejected.
171
+ - **`#[Title](taskId)`** — adds a graph edge between tasks (parent / blocker
172
+ / duplicate-of / follow-up). Updates the target's "Referenced by" panel.
173
+ No notification fires — purely a graph operation.
174
+
175
+ ### Anti-pattern: NEVER reference a task by bare id
176
+
177
+ Whenever you mention another task — in a description, a comment, a
178
+ `## Tareas relacionadas` block, an audit trail, anywhere markdown is
179
+ rendered — use the chip syntax `#[Título](taskId)`. **A bare id in
180
+ backticks is dead text**: no clickable link, no graph edge, no
181
+ "Referenced by" entry, and human readers have to copy-paste it into the
182
+ URL bar to navigate.
183
+
184
+ ```markdown
185
+ ❌ Bad — `m172v5tesszx27fhbfmj7abb45868z64` — "Modificar hreflang en dominio .NET"
186
+ ❌ Bad — https://crm.roilab.es/dashboard/tasks?taskId=m172v5tesszx27fhbfmj7abb45868z64
187
+ ✅ Good — #[Modificar hreflang en dominio .NET](m172v5tesszx27fhbfmj7abb45868z64)
188
+ ```
189
+
190
+ This applies equally to inline mentions and to lists. A `## Tareas
191
+ relacionadas` bullet must lead with the chip, not with the id:
192
+
193
+ ```markdown
194
+ - #[Eliminar hreflang chile de la home y ajustar hreflang es](m1716nym1jej9vevfnmgp6yzhn869vbz) (done 2024-05-30) → quitó `hreflang="es-CL"`…
195
+ ```
196
+
197
+ Special characters in the title (`[`, `]`, parens) must be backslash-escaped
198
+ so the markdown round-trips through the tokenizer:
199
+
200
+ ```markdown
201
+ #[\[GB\] Eliminar hreflangs apuntando hacia growbarato.it](m1767y1wqrz93q3kvqtej350398695fj)
202
+ #[Añadir nuevo schema Carousel \(ItemList\) en categorías](m178j0p99dwmfcwy37c0jr9t3s86819z)
203
+ ```
204
+
205
+ When you don't know the title off the top of your head, **resolve it
206
+ first** — see the next subsection. Don't fall back to a bare id "for now";
207
+ you'll forget to come back.
208
+
209
+ ### Resolve IDs before composing
210
+
211
+ Don't hand-roll memberIds or taskIds. Use the resolver helpers; they exit
212
+ non-zero when the query is wrong:
213
+
214
+ ```bash
215
+ # Resolve a name → markdown chip. Exits 8 if ambiguous, 2 if no match.
216
+ crm mention member "luis" # → @[Luis Fernández](mem_abc)
217
+ crm mention member --domain dom_xyz "sarah"
218
+ crm mention task "fix h1 pricing" # → #[Fix H1 on /pricing](tsk_xyz)
219
+
220
+ # Or list candidates first if you want to pick by hand:
221
+ crm member list --query "luis"
222
+ crm member list --domain dom_xyz --role member,admin
223
+ crm task search "h1" --limit 10
224
+ ```
225
+
226
+ Compose into a write with shell substitution — the chips are plain markdown,
227
+ not JSON:
228
+
229
+ ```bash
230
+ crm comment create --task tsk_abc \
231
+ --body "$(crm mention member luis) please check the audit results — \
232
+ blocking $(crm mention task 'crawl audit GB')"
233
+ ```
234
+
235
+ If the resolver exits 8 the shell substitution captures stderr (not stdout),
236
+ so the outer command will land with a literal empty chip — that's the
237
+ intended failure mode. Read the stderr disambiguation hint and re-run.
238
+
239
+ ### Assemble context BEFORE mentioning anything
240
+
241
+ The legitimate pool of mentionable members for a write is **the union of**:
242
+ the existing task's assignees + collaborators (already inlined as
243
+ `participants` on `crm task get`), the staff returned by `crm brief`, and
244
+ anyone the human explicitly named. Anything outside that pool is almost
245
+ always the wrong person — ask before mentioning.
246
+
247
+ ```bash
248
+ # For an existing task: pulls participants (with role + expertise) + parent
249
+ # domain brief + cross-references already linked. Run this BEFORE adding a
250
+ # comment.
251
+ crm brief --task tsk_abc
252
+
253
+ # For a new task: scope to the domain so the staff list is the working pool.
254
+ crm brief --domain dom_xyz
255
+
256
+ # For "is there already a task tracking this?" before adding a #link:
257
+ crm task related tsk_abc # tasks already linked + same-domain + shared-tags
258
+ crm recall https://example.com/pricing
259
+ ```
260
+
261
+ `crm brief --task` is the URL-equivalent of `recall` for tasks: the right
262
+ pre-write context every time.
263
+
264
+ #### Sensitive handling notes
265
+
266
+ Profile responses carry an `internalNotes` field (markdown, staff-only) on
267
+ clients, domains and members. Treat it as binding handling guidance, not
268
+ flavour text — it's where the human team writes things like "never mention
269
+ project X to this CEO", "always cc Eric Collado as follower on every task",
270
+ "careful — this person prefers blunt feedback". Always read these before
271
+ drafting any comment, mention or task that touches the entity. They flow
272
+ through automatically on:
273
+
274
+ - `crm brief <clientId>` → `clientProfile.internalNotes` and per-domain / per-staff notes
275
+ - `crm brief --domain <id>` → domain + parent client + staff with activity
276
+ - `crm brief --task <id>` → each `participants[].internalNotes` + parent domain + parent client
277
+ - `crm client profile <id>` / `domain profile <id>` / `member profile <id>` → single-entity fetch
278
+ - `crm task get <id>` → `participants[].internalNotes` for staff callers
279
+
280
+ Never echo `internalNotes` into client-visible surfaces (shared chat threads,
281
+ client-visible tasks, replies through the portal). They are agency-internal.
282
+
283
+ ### When to mention vs. not
284
+
285
+ - **Mention** when attention is genuinely needed *now*: a decision blocking
286
+ next steps, a completed item awaiting review, a regression you've spotted.
287
+ - **Don't mention** on routine `agent_log` traces ("ran the audit, here's
288
+ the output"). The volume drowns inboxes; the badge already shows it's
289
+ agent work.
290
+ - **`#`-link** when the relationship is real graph (blocker, duplicate-of,
291
+ follow-up). Not as decoration, not to "show your work" — that goes in
292
+ prose.
293
+ - **Self-mentions are filtered server-side** so you don't ping your own
294
+ underlying member.
295
+
296
+ ### Notifications fire on approval, not on submission
297
+
298
+ This is the rule that matters for shadow-mode writes:
299
+
300
+ - **Autonomous write** with `@[Name](id)` → notification fires immediately,
301
+ scope grants apply immediately, `taskMentions` index updates immediately.
302
+ - **Shadow proposal** with `@[Name](id)` → **nothing fires until a human
303
+ approves**. The chip renders to reviewers in the markdown so they can see
304
+ the intent, but the mentioned user is not pinged, no scope is granted, no
305
+ graph edge lands. On approval, all three side effects fire — attributed
306
+ to the original agent's name (so the user reads "Agent X mentioned you")
307
+ but the notification's `createdAt` is the approval moment.
308
+ - **Shadow proposal that's rejected** → side effects never fire. The chip
309
+ goes nowhere.
310
+
311
+ The point: a `--shadow` write that mentions someone is not a way to "ping
312
+ them with a heads-up before review." It's a deferred mention. If you need
313
+ the human aware before approval, write a `--kind decision` autonomous
314
+ comment.
315
+
316
+ ### Edits to descriptions are diffed
317
+
318
+ Updating a task's description with a new `@mention` only fires for the
319
+ **newly added** mention, not the ones already present. Same for `#`-links.
320
+ You can safely edit a description that already references people without
321
+ re-pinging them.
322
+
323
+ ## Adjuntar archivos
324
+
325
+ Cuatro comandos aceptan `--file <ruta>` (repetible) y suben el archivo a
326
+ Convex storage antes de enviar la escritura:
327
+
328
+ - `crm chat send <threadId> --file <ruta>` y `crm chat reply <msgId> --thread <id> --file <ruta>`
329
+ - `crm task create --file <ruta>` y `crm task update <id> --file <ruta>`
330
+ - `crm comment create --task <id> --file <ruta>`
331
+
332
+ El flujo siempre es el mismo (dos pasos: URL firmada → `POST` directo a Convex
333
+ storage). Reglas y límites compartidos:
334
+
335
+ - **Máx 10 MB por archivo** — el CLI rechaza localmente antes de tocar la red.
336
+ - **Aviso a partir de 2 MB** en stderr (`[AVISO] ... la subida puede tardar.`).
337
+ - MIME se sniffa por extensión; lo desconocido viaja como `application/octet-stream`,
338
+ que el servidor acepta y la UI renderiza como tarjeta genérica.
339
+ - `--body` (chat / comentario) es opcional si pasas `--file` (mensajes /
340
+ comentarios sólo-archivos están permitidos).
341
+ - **Cuidado con `task update --file`**: la lista de adjuntos es REEMPLAZO,
342
+ no merge. Los archivos previos desaparecen. Para vaciar explícitamente, usa
343
+ `--clear-files`; para conservar los previos hay que pasarlos también.
344
+ - **Para añadir/quitar UN archivo sin tocar el resto** usa `task attach` en vez
345
+ de `task update --file` (que reemplaza toda la lista):
346
+ - `crm task attach list <taskId>` — lista los adjuntos (con su `_id`).
347
+ - `crm task attach add <taskId> --file <ruta...>` — añade sin clobber.
348
+ - `crm task attach remove <taskId> <attachmentId>` — quita uno por id.
349
+ Tope: 50 archivos/tarea. Los clientes pueden adjuntar a tareas que ven.
350
+
351
+ ```bash
352
+ # Chat
353
+ crm chat send "$TID" --body "captura del 404" --file ./bug.png
354
+ crm chat reply <msgId> --thread "$TID" --file ./report.pdf --file ./logs.txt
355
+
356
+ # Tarea — en la creación / reemplazo total
357
+ crm task create --title "Migración H1" --domain dom_xyz --file ./brief.pdf
358
+ crm task update tsk_abc --file ./new-spec.pdf --clear-files
359
+
360
+ # Tarea — gestión incremental de adjuntos (sin reemplazar la lista)
361
+ crm task attach add tsk_abc --file ./extra.pdf --file ./shot.png
362
+ crm task attach list tsk_abc
363
+ crm task attach remove tsk_abc att_xyz
364
+
365
+ # Comentario
366
+ crm comment create --task tsk_abc --kind decision \
367
+ --body "Cerrado: ver diff y screenshots" \
368
+ --file ./before.png --file ./after.png
369
+ ```
370
+
371
+ ## Common recipes
372
+
373
+ ```bash
374
+ # Read-only triage before acting
375
+ crm task preflight --title "Fix H1 on /pricing" --url https://example.com/pricing --domain dom_xyz
376
+ crm change list --domain dom_xyz --url /pricing --jq '.data[].items[].type'
377
+ crm backlink lost --domain dom_xyz --since 2026-01-01 --count
378
+
379
+ # Create a measured task — sólo si el preflight no encontró duplicados
380
+ crm task create \
381
+ --title "Fix H1 on /pricing" \
382
+ --domain dom_xyz \
383
+ --description "Current H1 buries the value prop; replace with 'Plans that scale with you'." \
384
+ --idempotency-key 01HY8X...
385
+
386
+ # Log change events after shipping — SOLO en tareas de Redacción (kind:
387
+ # "content"). Las tareas generales no registran cambios on-page y el backend
388
+ # los rechaza. No hay verbo CLI todavía; hit the REST endpoint directly:
389
+ # POST /api/v1/domains/<domainId>/changes (autogenerates an idempotency key
390
+ # per call; same envelope contract).
391
+
392
+ # Search across everything
393
+ crm search "meta title" --kind change --domain dom_xyz --limit 5
394
+
395
+ # Live provider-API queries (tokens stay on the server)
396
+ crm integration list --quiet | jq -r '.[] | "\(._id) \(.provider) \(.services|join(","))"'
397
+ crm gsc query --property prop_abc --dimension page \
398
+ --filters "page contains /blog/" --start 2026-03-01 --end 2026-04-01 --limit 50
399
+ crm ga4 query --property prop_abc --start 2026-03-01 --end 2026-04-01 \
400
+ --filters "pagePath contains /pricing"
401
+ crm bing query --property prop_bing --start 2026-03-01 --end 2026-04-01
402
+ crm integration sync --property prop_abc # forces fresh ingestion (15m cooldown)
403
+
404
+ # Google Ads — discover, analyse, manage budgets (staff-only, cost is sensitive)
405
+ crm ads accounts --account acc_google # enumerate MCC child accounts (customerId/name/currency)
406
+ crm ads campaigns --property prop_ads --start 2026-06-01 --end 2026-06-30 \
407
+ --compare-start 2026-05-01 --compare-end 2026-05-31 # per-campaign CPA/ROAS + PoP deltas
408
+ # Proactive intelligence: anomalies across ALL ads accounts (omit --property), vs the prior period
409
+ crm ads anomalies --start 2026-06-01 --end 2026-06-30 \
410
+ --compare-start 2026-05-01 --compare-end 2026-05-31 --jq '.data.anomalies'
411
+ # Budget pacing: MTD spend vs budget + end-of-month projection (pass the month bounds explicitly)
412
+ crm ads pacing --month-start 2026-06-01 --as-of 2026-06-29
413
+ crm ads budget --property prop_ads # read budget
414
+ crm ads budget --property prop_ads --set 3000 # set / --clear to remove
415
+ crm ads import # trigger a fresh Ads ingestion pass
416
+
417
+ # Agency skills — read the library + sync it to disk so Claude Code picks it up
418
+ crm skill list --category local-seo --quiet # all published in category
419
+ crm skill show auditoria-seo-local # metadata + revision id
420
+ crm skill revisions auditoria-seo-local # publish history
421
+ crm skill revision <revisionId> # single immutable revision
422
+ crm skill pull --all # writes .claude/skills/<slug>/SKILL.md
423
+ crm skill update # refresh any outdated skill
424
+ crm skill diff auditoria-seo-local # local vs remote state
425
+
426
+ # Agency skills — authoring (owner / admin / member with skills:write)
427
+ crm skill create --slug my-playbook --name "Mi playbook" \
428
+ --description "Cuándo y cómo aplicarlo" --category content
429
+ crm skill set my-playbook --visibility staff_only # metadata-only PATCH
430
+ crm skill push my-playbook --note "primera revisión" --publish # body+frontmatter
431
+ crm skill archive my-playbook # hide from library
432
+ crm skill restore my-playbook # un-archive
433
+
434
+ # Chat — read threads, post messages, react, attach files (max 10 MB each)
435
+ crm chat list --scope client --client cli_abc
436
+ crm chat get <threadId> --message-limit 50 # metadata + recent msgs
437
+ crm chat read <threadId> --page-limit 50 --before <ms> # paginate backwards
438
+ crm chat send <threadId> --body "$(crm mention member luis) revisado"
439
+ crm chat send <threadId> --body "informe adjunto" --file ./audit.pdf --file ./serp.png
440
+ crm chat reply <messageId> --thread <threadId> --body "ok, mañana"
441
+ crm chat react <messageId> --emoji "👀" # toggle (re-run unreacts)
442
+ crm chat dm --member mem_xyz --title "1:1 review"
443
+ crm chat mark-read <threadId>
444
+ ```
445
+
446
+ ## Playbooks de tarea incluidos en este paquete
447
+
448
+ Este paquete trae playbooks en `skill-bundles/tools/<name>/SKILL.md` — viajan
449
+ con el CLI, así que sólo quien se baja/actualiza el CLI los tiene. Cuando una
450
+ tarea encaje con uno, **cárgalo y síguelo** (no improvises el método):
451
+
452
+ - **`tool-routing`** — matriz para elegir qué herramienta externa usar.
453
+ - **`task-preflight`** — cómo leer `crm task preflight` antes de crear tareas.
454
+
455
+ Además, la **librería de skills de la agencia** (Convex, no bundled) trae
456
+ playbooks que se bajan a `.claude/skills/` con `crm skill pull <slug>`:
457
+
458
+ - **`optimizar-metas`** — metodología para optimizar/validar **meta title +
459
+ meta description** de una URL: valida la KW en el Rank Tracker (Ahrefs **sin
460
+ gastar créditos**) → analiza GSC de la URL → clasifica la SERP y mira a los
461
+ competidores → **desambigua y caza canibalización** entre URLs propias, y sólo
462
+ entonces redacta. Para una tarea "Optimizar PDP / metas":
463
+ `crm skill pull optimizar-metas` y síguelo.
464
+
465
+ ## Decision tree for analytics questions
466
+
467
+ 1. **Rollups / trends** → `crm domain metrics <id> --start … --end …`. Reads from Tinybird; cheap and fast.
468
+ 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.
469
+ 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.
470
+
471
+ 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.
472
+
473
+ ## Things that are not obvious
474
+
475
+ - 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.
476
+ - **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.
477
+ - **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.
478
+ - **Bing daily feed has no per-query/per-page breakdown**. `crm bing query` returns the aggregate with a `meta.note` saying so.
479
+ - Web UI paths: `/dashboard/tasks?taskId=<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.
480
+
481
+ ## Task participants — assignees vs collaborators
482
+
483
+ Two distinct member lists on every task:
484
+
485
+ - **`--assignee <id...>`** — the **responsible** parties. Their queue counts include this task; auto-assigned watchers; show up first in the UI.
486
+ - **`--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).
487
+
488
+ 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.
489
+
490
+ 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.
491
+
492
+ ## Reading rejection feedback (iteration loop)
493
+
494
+ 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).
495
+
496
+ ```bash
497
+ # Just the actionable ones — items the reviewer wants you to redo.
498
+ crm review feedback --retryable-only
499
+
500
+ # Everything that's been rejected for this API key, with reasons.
501
+ crm review feedback
502
+ ```
503
+
504
+ 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.
505
+
506
+ ## Access requests — `crm access`
507
+
508
+ 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:
509
+
510
+ ```bash
511
+ # Client side — file the request, citing the chat message that exposed the task.
512
+ crm access request <task-id> --via <message-id> --message "Need to review the H1 fix"
513
+
514
+ # Staff side — list pending, then approve or deny with a scope choice.
515
+ crm access list
516
+ crm access approve <request-id> --scope task # smallest blast radius
517
+ crm access approve <request-id> --scope board # whole board (for cross-client tasks)
518
+ crm access deny <request-id> --note "Task is internal QA"
519
+ ```
520
+
521
+ 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.
522
+
523
+ ## Backlink human-QA
524
+
525
+ Linkbuilding rows can sit in a pending-review queue until staff verifies the source. Agents with `backlinks:verify` scope can drive the queue:
526
+
527
+ ```bash
528
+ crm backlink pending --domain dom_xyz
529
+ crm backlink verify <id> # idempotent
530
+ crm backlink reject <id> --reason wrong_anchor --notes "Anchor text drifted to brand-only"
531
+ crm backlink rejection-report --client cli_xyz --since-days 90
532
+ ```
533
+
534
+ 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.
535
+
536
+ ### Manual health-status override
537
+
538
+ `status` (active/removed/nofollowed/…) is the automated probe's verdict; it's orthogonal to the verify/reject QA verdict above. When the crawler gets a row wrong, override it (audited):
539
+
540
+ ```bash
541
+ crm backlink set-status <id> --status non_crawlable --note "Enlace dentro de documento Issuu — hotspot JS, no rastreable"
542
+ crm backlink set-status <id> --status active --note "Verificado: <a> dofollow real cargado por JS (SPA); el fetch http no lo veía"
543
+ crm backlink set-status <id> --status manual_override --note "Parqueado: …" # 'manual_override' detiene el cron
544
+ ```
545
+
546
+ If the registered source URL is simply wrong (points at a profile sub-tab that doesn't carry the link, but a sibling page does), fix the URL instead of overriding the status — the cron then re-validates the right page:
547
+
548
+ ```bash
549
+ crm backlink update <id> --source-url "https://host/correct-page"
550
+ ```
551
+
552
+ To sanity-check the crawler against an independent oracle, `crm backlink reconcile --domain <id>` cross-checks our suspect rows (removed/broken/blocked/non_crawlable) against Ahrefs and flags disagreements for review — it never changes a status. It is **credit-safe**: dry-run by default (shows remaining Ahrefs units + what it would query); add `--confirm` to spend units on ONE filtered call that aborts if the budget is below `--unit-floor` (default 1500). Then fix confirmed mismatches with `set-status` / `update --source-url`.
553
+
554
+ The cron now auto-classifies flipbook/document hosts (Issuu, Calameo, Yumpu reader, Scribd) as `non_crawlable` — their link is a per-page JS hotspot, not a crawlable `<a href>`, so it's neither `removed` nor a live followable link. For SPA/UA-403 hosts the health check falls back to a real headless render before declaring a link dead. Use `set-status` only when you've verified the live page yourself and the automation still disagrees.
555
+
556
+ ## Perfiles sociales (`crm social`)
557
+
558
+ Los handles sociales de cada dominio (y los de marca global del cliente) viven en una tabla propia. Léelos antes de redactar contenido social o de proponer diversificación de enlaces — saber qué cuentas existen evita inventar handles.
559
+
560
+ ```bash
561
+ crm social list --domain dom_xyz # perfiles de un sitio
562
+ crm social list --client cli_abc # + handles de marca sin dominio
563
+ crm social create --domain dom_xyz --platform instagram --handle growbarato \
564
+ --url https://instagram.com/growbarato --primary
565
+ crm social create --client cli_abc --platform other --label Crunchbase \
566
+ --url https://www.crunchbase.com/organization/growbarato
567
+ crm social update soc_123 --notes "Cuenta oficial verificada"
568
+ crm social delete soc_123 # archiva (borrado suave, restaurable)
569
+ ```
570
+
571
+ Reglas: indica `--domain` (perfil del sitio) **o** `--client` (handle de marca sin sitio concreto). `platform` es un catálogo cerrado (`instagram | facebook | x | youtube | tiktok | linkedin | pinterest | threads | trustpilot | other`); `other` exige `--label`. El handle se normaliza quitando la `@`. `--internal-notes` queda staff-only (no se muestra al cliente). Scope `social:write` — staff-only.
572
+
573
+ ## Bulk approve / reject your queue
574
+
575
+ `crm review` supports bulk operations via stdin (NDJSON or `kind:id` tokens, ≤100 per call):
576
+
577
+ ```bash
578
+ # Approve every pending proposal from your key. The CLI's mini-jq only
579
+ # walks paths — it doesn't support `|` or string interpolation — so use
580
+ # real `jq` after `--quiet` for the projection:
581
+ crm review list --mine --quiet \
582
+ | jq -r '[.tasks[]|"task:"+.id, .comments[]|"comment:"+.id, .edits[]|"edit:"+.id] | .[]' \
583
+ | crm review bulk-approve
584
+
585
+ # Reject many with one reason (allowRetry defaults to true):
586
+ printf 'task:tsk_a\ntask:tsk_b\n' | crm review bulk-reject --reason "Out of scope this quarter"
587
+ ```
588
+
589
+ ## Escape hatches
590
+
591
+ - `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.
592
+ - `crm doctor --json` — always safe; doesn't mutate anything. Also forces a fresh npm registry check.
593
+ - `crm auth whoami` — what identity am I acting under? Check this first if attribution looks wrong in the UI.
594
+
595
+ ## Update notifications
596
+
597
+ Two channels surface a stale CLI version, both shown via stderr (never on stdout — they don't break `--quiet` pipes):
598
+
599
+ - **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.
600
+ - **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.
601
+
602
+ 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.