> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Pump every LibreDesk conversation, read-only, into `labeling/auto/conversations/<reference>/` (JSON, attachments, a readable transcript), launched and shown from a new **Conversations** page of the app.
**Architecture:** The pumping lives in `~/aimsight-libredesk/conversations/` (standard library, French, its own `.env` key, a guard test: `GET` only). The app reaches it through a new link `libredesk/` and calls `conversations/pompage.py` as `station.py` calls `extraction/pumping.py`; it lists the pumped folders and renders `transcript.md` safely (escaped, CSP, sandboxed frame, non-image attachments as downloads).
**Tech Stack:** Python 3 stdlib (`urllib`, `html.parser`, `unittest`) in aimsight-libredesk; FastAPI + `markdown` and React/Mantine in the app.
- LibreDesk: only `GET`, only `/api/v1/conversations/all`, `/api/v1/conversations/{uuid}/messages`, and the `attachments[].url` the messages carry; never a URL found in a message's text.
-`Authorization: token <key>:<secret>` only to the LibreDesk host (`add_unredirected_header`, host compared as in `snippets/envoyer.py`); attachments on another host (S3) downloaded without it.
- Key: `LIBREDESK_API_KEY`, `LIBREDESK_API_SECRET` in `~/aimsight-libredesk/.env`; URL `LIBREDESK_URL`, default `https://helpdesk.sensima.ch`. Claude never reads a `.env`.
- Every conversation: all inboxes, all statuses, private notes included, no filter.
-`~/aimsight-libredesk`: standard library only, code/comments/commits in French. The app: English.
- Every time in UTC. Commits by path, never `git add -A`; each message ends with a blank line then `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`. Nothing pushed.
- Nothing committed in `~/aimsight-labeling` by this plan: the user commits `auto/conversations/` after looking at the first range.
## Review Focus
- An attachment name with `/`, `..`, or an empty name → stays inside `attachments/` (sanitized, uuid fallback). Test in Task 2.
- Two attachments with the same name in one conversation → both kept (second prefixed by its uuid). Test in Task 2.
- A `reference_number` that is not `[A-Za-z0-9_-]+` → folder named by the conversation's `uuid`. Test in Task 2.
- A pumping cut halfway (exception after some conversations) → `pumped.json` unchanged, the next run fetches the rest. Test in Task 2.
- A client mail with `<script>`, an `<img src=https://…>` pixel, or an `.svg`/`.html` attachment → shown as text, not loaded, downloaded rather than rendered. Test in Task 4.
---
### Task 0: Branches
- [ ]**Step 1:**`cd ~/aimsight-libredesk && git switch -c feat/conversations` (from `main`; the user's uncommitted `docs/architecture.drawio` stays untouched and uncommitted).
- [ ]**Step 2:**`cd ~/aimsight-app && git switch -c feat/conversations` (from `feat/weather-meteoswiss`, which carries the Support tab; the user's uncommitted `instructions/analyst.md` stays untouched).
- [ ]**Step 3:** Implement `texte` with `html.parser.HTMLParser` (newline at `br`; blank line around `p`, `div`, `li`, `tr`, `h1`–`h6`, `blockquote`; skip `script`/`style` data; collapse 3+ newlines to 2; strip), and `transcript` per the format above. Times through `datetime.fromisoformat(...).astimezone(timezone.utc)`.
-`class Lecteur(url: str, cle: str, secret: str)`: `conversations() -> Iterator[dict]` (pages of `/api/v1/conversations/all?page=N&page_size=100&order_by=updated_at&order=desc` until `page >= total_pages`), `messages(uuid: str) -> list[dict]` (every page of `/api/v1/conversations/{uuid}/messages?page=N&page_size=100`, then sorted by `created_at`), `telecharger(url: str, chemin: Path) -> None` (relative URL joined to `self.url`; header only if same scheme+host as `self.url`). HTTP errors raise (no `sys.exit` inside: the caller decides).
- CLI: `python3 -m conversations.pomper --sortie <folder> [--depuis YYYY-MM-DD --jusqu-a YYYY-MM-DD]`, env `LIBREDESK_URL`, `LIBREDESK_API_KEY`, `LIBREDESK_API_SECRET`; exit 1 with a one-line message on a missing key or an HTTP error.
- No range: mark = `sortie/pumped.json``{"until": ISO}`; walk `conversations()`, stop at the first with `updated_at < until - 1 h`; at the end only, write `{"until": <UTC time at the start of the run>}`. No file: walk everything.
- Per conversation: folder = `reference_number` if `re.fullmatch(r"[A-Za-z0-9_-]+", str(ref))`, else `uuid`. Write `conversation.json` (without `previous_conversations`), `messages.json` (each `attachments[].url` replaced by `attachments/<local name>`, and that URL replaced in `content` too), `transcript.md`; JSON with `ensure_ascii=False, indent=1`.
- Attachment local name: `re.sub(r"[^\w.\- ]", "_", Path(name).name).strip(" .")`, empty → attachment `uuid`; already taken by another attachment of the conversation → `<uuid>_<name>`. Skip the download when the file exists with the same `size`.
-`journal` gets one line per conversation (`#<ref> <subject> : <n> messages, <k> pièces jointes`) and a closing total.
- [ ]**Step 1: Write the failing tests** (`setUp`: a `FauxLibreDesk` for LibreDesk, a second one as "S3"; helper `conv(ref, uuid, updated_at)`; `reponses[("GET", "/api/v1/conversations/all")]` = a callable paging on `?page=`)
```python
deftest_tout_au_premier_pompage(self):# 3 conversations over 2 pages → 3 folders, pumped.json written
deftest_incremental_s_arrete_sous_le_repere(self):# pumped.json until=10:00; convs at 12:00, 09:30, 08:00
# → 12:00 and 09:30 (margin 1 h) fetched, 08:00 not; messages of 08:00 never requested
deftest_interrompu_le_repere_ne_bouge_pas(self):# messages of the 2nd conv answer 500 → raises, pumped.json unchanged
deftest_plage_ne_touche_pas_le_repere(self):# depuis/jusqu_a: only the convs in range, pumped.json absent after
deftest_pieces_jointes_locales(self):
# messages.json url == "attachments/photo.jpg", content's URL replaced, the file's bytes on disk
deftest_nom_de_piece_jointe_assaini(self):# name "../../x.sh" → attachments/x.sh, inside the folder
deftest_noms_en_double(self):# two "a.png" → a.png and <uuid>_a.png
deftest_deja_telechargee_pas_de_requete(self):# second run, same size → no GET on /uploads/
# attachment url on the "S3" fake: downloaded, and no "Authorization" in its entetes; LibreDesk's entetes have it
deftest_aucune_ecriture(self):# after a full run: self.faux.ecritures() == []
```
`test_garde_fou_conversations.py`, as `test_garde_fou_snippets.py`: in every `conversations/*.py`, the `/api/v1/...` routes ⊆ `{"/api/v1/conversations/all", "/api/v1/conversations/{uuid}/messages"}`; none of `"POST"`, `"PUT"`, `"DELETE"`, `"PATCH"`, `method=` appears; and `pomper.py` exists.
- Produces (imported by the app as a plain module, `sys.path` = `conversations/`; no package-relative import):
-`start(depuis: str, jusqu_a: str, sortie: str) -> subprocess.Popen`: `ValueError("a range: From and To, YYYY-MM-DD, From before To")` (the words of `extraction/pumping.py`, shown in the app as they are) if only one date, a date not `YYYY-MM-DD`, `depuis >= jusqu_a`, or `running()`; runs `[pomper.sh, "--sortie", sortie, *(["--depuis", depuis, "--jusqu-a", jusqu_a] if depuis else [])]`, cwd the repository root, stdio to `DEVNULL`.
-`running() -> bool`: `out/conversations.lock` held (`fcntl.flock` non-blocking, as `extraction/pumping.py`).
-`log(lines: int = 40) -> list[str]`: the end of `out/conversations.log`.
`pomper.sh`, modelled on `~/aimsight-data/extraction/pump.sh`: `mkdir -p out`, `flock -n` on `out/conversations.lock`, `=== <UTC> pomper <args>` and `=== <UTC> fin` around `(set -a +u && . ./.env && set +a -u && python3 -m conversations.pomper "$@")`, all `2>&1 | tee -a out/conversations.log`.
- [ ]**Step 1: Write the failing tests:**`start("2026-11-01", "", "/tmp/x")`, `start("2026-11-02", "2026-11-01", …)`, `start("1.11.2026", "2026-11-02", …)` raise `ValueError`; `running()` is `False` without a lock file; `log()` returns the last lines of a temporary `out/conversations.log` (point `pompage.ROOT` at a temp folder).
- [ ]**Step 5:** README: a section « Pomper les conversations » (what, where it writes, read-only, the agent « Lecture conversations » with only `conversations:read_all` and `messages:read`, the two `.env` lines, the command, the app's page); the line « Aucun code de ce dépôt n'écrit dans une conversation » stays true, add the guard test next to `test_garde_fou_base.py`'s mention. Task « Conversations : pomper » in `tasks.json` (`bash conversations/pomper.sh --sortie ~/aimsight-labeling/auto/conversations`).
- Consumes: the routes of Task 4; `call` and `Page` from `common.jsx`.
The page, modelled on `Stations.jsx`: title "Conversations" and a dimmed line ("The LibreDesk conversations, pumped read-only into labeling/auto/conversations/"); a card "Pump" with From/To (`type="date"`, empty by default), the button `Pump` (`loading` while running), the hint "Without dates: what changed since the last pumping; the first time, the whole history.", the log read every 2 s (`GET /api/conversations/pump`) in a `ScrollArea` + `Code block`; a card with a `TextInput` "Search" (subject, contact, reference; case-insensitive) and a `Table` (Reference, Subject, Contact, Status, Last message `YYYY-MM-DD HH:MM`, Messages, Attachments), the list read again when a pumping ends; a click on a row shows `<Page title="Transcript" src={`/api/conversations/${ref}/report.html?dark=${dark}`} />` under the table.
- [ ]**Step 1:** Implement; `cd app/web && npm run build` → builds without error.
- [ ]**Step 2:** Launch the server (`.venv/bin/python app/server/server.py`, or `systemctl --user restart aimsight-app` if the service runs) with the temp conversation of Task 4 copied into `labeling/auto/conversations/42/`; open `http://127.0.0.1:8770/#/conversations`: the row shows, the transcript shows its image and the `<script>` as text, `x.svg` downloads. Then remove `labeling/auto/conversations/42/`.
- [ ]**Step 3:** Docs: `app/README.md` a section "The Conversations page" (what it pumps, where, read-only, the key in `~/aimsight-libredesk/.env`, the protections); `README.md` the link `libredesk/` in the table and the `ln -s` line, a bullet for the page; `CLAUDE.md` the link in **The links**, a line in **The processes** (the Conversations page launches `libredesk/conversations/pomper.sh`, its output in `labeling/auto/conversations/<reference>/`) and in **The contracts** (`~/aimsight-libredesk/conversations/pompage.py`); `docs/architecture.drawio` a box "aimsight-libredesk" in the style of its neighbours (French, like the diagram), an arrow app → aimsight-libredesk ("pompage des conversations") and aimsight-libredesk → aimsight-labeling ("auto/conversations/").
- [ ]**Step 4:**`.venv/bin/python app/server/check.py` → all `ok`.
- [ ]**Step 1:** The user creates in LibreDesk the agent « Lecture conversations », a role with only `conversations:read_all` and `messages:read`, its API key, and adds `export LIBREDESK_API_KEY=…` / `export LIBREDESK_API_SECRET=…` to `~/aimsight-libredesk/.env`. Wait for their word.
- [ ]**Step 2:** From the page, a range of the last 3 days. Check the log ends with `=== … fin` and no error; open two transcripts.
- [ ]**Step 3:** On one `messages.json`, confirm the attachment fields (`name`, `content_type`, `size`, `url`, `uuid`) and whether `updated_at` moved with the last message; if a field differs, fix `pomper.py` and the fake data of `test_pomper.py`, rerun the tests, commit in aimsight-libredesk.
- [ ]**Step 4:** Hand over to the user: the folders to look at, and that the whole history (Pump without dates) is for a quiet hour, then their commit of `auto/conversations/` in `~/aimsight-labeling`.