1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
|
# Redact Tool Implementation Plan
> **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:** A `redact` tool that writes a copy of an attached PDF or image with personal data blacked out, beside the original, and opens it for review.
**Architecture:** `examples/tools/redact.py` (stdlib plus pdftotext, pdftoppm, tesseract, magick) finds word boxes, matches regex PII and model-supplied items over the joined words, draws black boxes on page renders and writes a pixels-only PDF itself (ImageMagick's policy forbids PDF output). The daemon gains the file's path in each attachment block (images get a block too) and a per-provider `cloud` list on tools.
**Tech Stack:** Python 3 stdlib, poppler-utils, tesseract 5.5 (+ ita/eng data), ImageMagick 7.
Spec: `docs/superpowers/specs/2026-11-09-redact-tool-design.md`.
Spec adjustments found while planning (Task 7 writes them into the spec):
- The check is `redact.py --test`, like `updates.py --test`, not a shell script.
- A document with nothing to redact writes nothing and says so.
- Images get a one-line block (`--- image: name (path) ---`): today they have no text block, so the model would not know their path.
- Image output passes `-strip`: EXIF (GPS, camera owner) goes too.
- Only pages with no text layer are OCR'd. Text baked into an image inside a text page is not seen (ceiling).
---
### Task 1: Detection (`find`, validators)
**Files:**
- Create: `examples/tools/redact.py`
- [ ] **Step 1: Write the file with the self-check and stub functions**
```python
#!/usr/bin/env python3
# desktop-assistant tool: black out personal data in a PDF or image.
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License version 2 as published
# by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
# Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
"""redact.py PATH [ITEMS]: writes PATH's copy with personal data blacked
out as <name>-redacted.<ext> beside it, and opens it in REDACT_VIEWER
(default xdg-open). ITEMS is extra strings, one per line. Emails, phones,
IBANs, codici fiscali and card numbers are always found. A PDF comes out
as page images only: no text layer, nothing under the boxes. --test runs
the self-check.
"""
import os
import re
import sys
def iban_ok(s):
s = s.replace(" ", "")
n = int("".join(str(int(c, 36)) for c in s[4:] + s[:4]))
return n % 97 == 1
def luhn_ok(s):
d = [int(c) for c in s if c.isdigit()][::-1]
return sum(x if i % 2 == 0 else (x * 2 - 9 if x > 4 else x * 2)
for i, x in enumerate(d)) % 10 == 0
RULES = [
("email", re.compile(r"[\w.+-]+@[\w-]+(?:\.[\w-]+)+"), None),
("iban", re.compile(r"\b[A-Z]{2}\d{2}(?: ?[A-Z0-9]{4}){2,7}(?: ?[A-Z0-9]{1,3})?\b"), iban_ok),
("codice fiscale", re.compile(r"\b[A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST]"
r"[0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z]\b"), None),
("card", re.compile(r"(?<!\d)(?:\d[ -]?){12,18}\d(?!\d)"), luhn_ok),
# Mobile (3xx), landline (0x), or international with + prefix.
("phone", re.compile(r"(?<![\w+])(?:\+\d{1,3}[ .-]?\d[\d .-]{5,13}\d"
r"|3\d{2}[ .-]?\d{3}[ .-]?\d{3,4}|0\d{1,3}[ .-]?\d{5,8})(?!\w)"), None),
]
def find(words, items):
"""words: [(text, box)] of one page. Returns (indices of words to black
out, {kind: matches}, set of items seen)."""
text, starts = "", []
for w, _ in words:
starts.append(len(text))
text += w + " "
hits, counts, seen = set(), {}, set()
def mark(kind, a, b):
hits.update(i for i, s in enumerate(starts) if s < b and s + len(words[i][0]) > a)
counts[kind] = counts.get(kind, 0) + 1
for kind, rx, ok in RULES:
for m in rx.finditer(text):
if ok is None or ok(m.group()):
mark(kind, *m.span())
for it in items:
# Whole words only, any spacing: a name split over two words or lines.
rx = re.compile(r"(?<!\w)" + r"\s+".join(map(re.escape, it.split())) + r"(?!\w)", re.I)
for m in rx.finditer(text):
mark("items", *m.span())
seen.add(it)
return hits, counts, seen
def test():
assert iban_ok("IT60X0542811101000000123456") and iban_ok("IT60 X054 2811 1010 0000 0123 456")
assert not iban_ok("IT61X0542811101000000123456")
assert luhn_ok("4111 1111 1111 1111") and not luhn_ok("4111 1111 1111 1112")
words = [(w, (i, 0, i + 1, 1)) for i, w in enumerate(
"Gentile Mario Rossi, scriva a mario@example.org o al 333 123 4567. "
"IBAN IT60X0542811101000000123456 BIC X. CF RSSMRA85T10A562S. "
"Carta 4111 1111 1111 1111, ordine 4111 1111 1111 1112. Rossini.".split())]
hits, counts, seen = find(words, ["mario rossi", "Via Roma 3", "Rossi"])
got = {words[i][0] for i in hits}
assert counts == {"email": 1, "iban": 1, "codice fiscale": 1, "card": 1, "phone": 1,
"items": 2}, counts
assert {"Mario", "Rossi,", "mario@example.org", "333", "123", "4567.",
"IT60X0542811101000000123456", "RSSMRA85T10A562S."} <= got, got
assert "Rossini." not in got and "BIC" not in got and "1112." not in got, got
assert seen == {"mario rossi", "Rossi"}
print("ok")
if __name__ == "__main__":
if sys.argv[1:] == ["--test"]:
test()
```
`counts["items"] == 2`: "mario rossi" once, "Rossi" once in "Rossi," (whole words, so not "Rossini."), "Via Roma 3" never.
- [ ] **Step 2: Run it**
Run: `chmod +x examples/tools/redact.py && examples/tools/redact.py --test`
Expected: `ok`. On an assertion error, fix the regex, not the test, unless the test's expectation is wrong (say which).
- [ ] **Step 3: Commit**
```bash
git add examples/tools/redact.py
git commit -m "tools: redact, PII detection over words"
```
---
### Task 2: Text PDF end to end (boxes, render, draw, PDF writer)
**Files:**
- Modify: `examples/tools/redact.py`
- [ ] **Step 1: Add the end-to-end test to `test()` (before `print("ok")`)**
```python
import hashlib, subprocess, tempfile
with tempfile.TemporaryDirectory() as d:
src = os.path.join(d, "x.pdf")
tiny_pdf(src, ["Mario Rossi mario@example.org", "nothing here"])
before = hashlib.sha256(open(src, "rb").read()).hexdigest()
env = {**os.environ, "REDACT_VIEWER": "true"}
run1 = subprocess.run([__file__, src, "Mario Rossi"], capture_output=True, text=True, env=env)
assert run1.returncode == 0 and "redacted 2 on 1 of 2 pages: 1 email, 1 items" in run1.stdout, run1
out = os.path.join(d, "x-redacted.pdf")
assert subprocess.run(["pdftotext", out, "-"], capture_output=True, text=True).stdout.strip() == ""
assert "Pages: 2" in subprocess.run(["pdfinfo", out], capture_output=True, text=True).stdout
# At 72 dpi pixels are points: the email's box centre must be black.
_, _, words = pdf_words(src)[0]
x0, y0, x1, y1 = next(b for t, b in words if "@" in t)
subprocess.run(["pdftoppm", "-f", "1", "-l", "1", "-r", "72", "-png", "-singlefile",
out, os.path.join(d, "check")], check=True)
px = subprocess.run(["magick", os.path.join(d, "check.png"), "-format",
f"%[pixel:p{{{(x0 + x1) / 2:.0f},{(y0 + y1) / 2:.0f}}}]", "info:"],
capture_output=True, text=True).stdout
assert px in ("gray(0)", "srgb(0,0,0)", "black"), px
subprocess.run([__file__, src, ""], capture_output=True, env=env)
assert os.path.exists(os.path.join(d, "x-redacted-2.pdf"))
assert hashlib.sha256(open(src, "rb").read()).hexdigest() == before
empty = os.path.join(d, "e.pdf")
tiny_pdf(empty, ["hello"])
r = subprocess.run([__file__, empty, "Nobody"], capture_output=True, text=True, env=env)
assert r.stdout.strip() == 'nothing to redact found. Not found: "Nobody"', r
assert not os.path.exists(os.path.join(d, "e-redacted.pdf"))
bad = subprocess.run([__file__, "rel.pdf", ""], capture_output=True, text=True, env=env)
assert bad.returncode == 1 and "cannot read rel.pdf" in bad.stderr
```
And the PDF fixture, a copy of `assistant.py`'s `tiny_pdf` at module level (above `test`):
```python
def tiny_pdf(path, pages):
# Test fixture: one Helvetica line per page, "" is a page with no text.
objs = ["<< /Type /Catalog /Pages 2 0 R >>",
"<< /Type /Pages /Kids [%s] /Count %d >>"
% (" ".join(f"{4 + 2 * i} 0 R" for i in range(len(pages))), len(pages)),
"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
for i, t in enumerate(pages):
stream = f"BT /F1 24 Tf 72 700 Td ({t}) Tj ET" if t else ""
objs += [f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Resources "
f"<< /Font << /F1 3 0 R >> >> /Contents {5 + 2 * i} 0 R >>",
f"<< /Length {len(stream)} >>\nstream\n{stream}\nendstream"]
pdf_file(path, [o.encode() for o in objs])
```
- [ ] **Step 2: Run, verify it fails**
Run: `examples/tools/redact.py --test`
Expected: `NameError: name 'pdf_file' is not defined`.
- [ ] **Step 3: Implement (add imports `html`, `subprocess`, `tempfile`, `zlib`, `functools`; functions above `test`)**
```python
PAGE_PX = 1600 # longest side of a render, as the daemon's
DPI = 150.0
PAD = 2 # pixels around each box
def run(argv):
p = subprocess.run(argv, capture_output=True)
if p.returncode:
last = p.stderr.decode(errors="replace").strip().splitlines()[-1:]
sys.exit(f"{argv[0]}: {last[0] if last else 'failed'}")
return p.stdout
def pdf_words(path):
"""[(width pt, height pt, [(text, box pt)])] per page; no words = a scan."""
pages = []
for m in re.finditer(r'<page width="([\d.]+)" height="([\d.]+)">|<word xMin="([\d.]+)" '
r'yMin="([\d.]+)" xMax="([\d.]+)" yMax="([\d.]+)">([^<]*)</word>',
run(["pdftotext", "-bbox", path, "-"]).decode(errors="replace")):
if m[1]:
pages.append((float(m[1]), float(m[2]), []))
else:
pages[-1][2].append((html.unescape(m[7]), tuple(map(float, m.group(3, 4, 5, 6)))))
return pages
@functools.cache
def check_langs():
if not {"ita", "eng"} <= set(run(["tesseract", "--list-langs"]).decode().split()):
sys.exit("tesseract has no ita and eng language data: images and scanned pages cannot be read")
def ocr_words(png):
check_langs()
words = []
for line in run(["tesseract", png, "-", "-l", "ita+eng", "tsv"]).decode().splitlines()[1:]:
f = line.split("\t")
if len(f) == 12 and f[0] == "5" and f[11].strip():
x, y, w, h = map(int, f[6:10])
words.append((f[11], (x, y, x + w, y + h)))
return words
def render_pdf(path, tmp):
"""[(png, width pt, height pt, [(text, box px)])] per page."""
pages = []
for n, (w, h, words) in enumerate(pdf_words(path), 1):
dpi = min(DPI, PAGE_PX * 72 / max(w, h))
base = os.path.join(tmp, f"p{n}")
run(["pdftoppm", "-f", str(n), "-l", str(n), "-r", f"{dpi:.2f}", "-png",
"-singlefile", path, base])
k = dpi / 72
words = ([(t, tuple(v * k for v in b)) for t, b in words] if words
else ocr_words(base + ".png"))
pages.append((base + ".png", w, h, words))
return pages
def draw(src, boxes, dst):
# -strip: an image's EXIF (GPS, owner) is personal data too.
argv = ["magick", src, "-strip", "-fill", "black"]
for x0, y0, x1, y1 in boxes:
argv += ["-draw", f"rectangle {x0 - PAD:.0f},{y0 - PAD:.0f} {x1 + PAD:.0f},{y1 + PAD:.0f}"]
run(argv + [dst])
def pdf_file(path, objs):
# objs: object bodies, numbered from 1; object 1 is the catalog.
out, offsets = b"%PDF-1.4\n", []
for k, o in enumerate(objs, 1):
offsets.append(len(out))
out += f"{k} 0 obj\n".encode() + o + b"\nendobj\n"
xref = len(out)
out += (f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
+ b"".join(f"{o:010d} 00000 n \n".encode() for o in offsets)
+ f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\n"
f"startxref\n{xref}\n%%EOF\n".encode())
with open(path, "wb") as f:
f.write(out)
def stream(head, data):
return f"<< {head} /Length {len(data)} >>\nstream\n".encode() + data + b"\nendstream"
def write_pdf(pages, dst):
# ImageMagick's policy forbids writing PDF: one lossless RGB image per
# page, at the original page size. No text, no metadata.
objs, kids = [b"<< /Type /Catalog /Pages 2 0 R >>", b""], []
for png, w, h in pages:
pw, ph = map(int, run(["magick", "identify", "-format", "%w %h", png]).split())
rgb = run(["magick", png, "-background", "white", "-alpha", "remove", "-depth", "8", "rgb:-"])
n = len(objs) + 1
kids.append(f"{n} 0 R")
objs += [f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w:.2f} {h:.2f}] /Resources "
f"<< /XObject << /I {n + 1} 0 R >> >> /Contents {n + 2} 0 R >>".encode(),
stream(f"/Type /XObject /Subtype /Image /Width {pw} /Height {ph} /ColorSpace "
"/DeviceRGB /BitsPerComponent 8 /Filter /FlateDecode", zlib.compress(rgb)),
stream("", f"q {w:.2f} 0 0 {h:.2f} 0 0 cm /I Do Q".encode())]
objs[1] = f"<< /Type /Pages /Kids [{' '.join(kids)}] /Count {len(kids)} >>".encode()
pdf_file(dst, objs)
def free_name(path):
stem, ext = os.path.splitext(path)
dst, n = f"{stem}-redacted{ext}", 1
while os.path.exists(dst):
n += 1
dst = f"{stem}-redacted-{n}{ext}"
return dst
def main(path, items_arg):
if not (os.path.isabs(path) and os.path.isfile(path) and os.access(path, os.R_OK)):
sys.exit(f"cannot read {path}")
items = [s.strip() for s in items_arg.splitlines() if s.strip()]
is_pdf = path.lower().endswith(".pdf")
with tempfile.TemporaryDirectory() as tmp:
pages = render_pdf(path, tmp) if is_pdf else [(path, 0, 0, ocr_words(path))]
counts, seen, marked = {}, set(), []
for png, w, h, words in pages:
hits, c, s = find(words, items)
for k, v in c.items():
counts[k] = counts.get(k, 0) + v
seen |= s
marked.append([words[i][1] for i in hits])
missing = [it for it in items if it not in seen]
tail = (" Not found: " + ", ".join(f'"{m}"' for m in missing)) if missing else ""
if not counts:
print("nothing to redact found." + tail)
return
dst = free_name(path)
if is_pdf:
done = []
for i, ((png, w, h, _), boxes) in enumerate(zip(pages, marked)):
out = os.path.join(tmp, f"r{i}.png")
draw(png, boxes, out)
done.append((out, w, h))
write_pdf(done, dst)
else:
draw(path, marked[0], dst)
subprocess.Popen([os.environ.get("REDACT_VIEWER", "xdg-open"), dst], start_new_session=True,
stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
touched = sum(1 for b in marked if b)
kinds = ", ".join(f"{n} {k}" for k, n in counts.items())
print(f"redacted {sum(counts.values())} on {touched} of {len(pages)} pages: {kinds}. "
f"Written to {dst}, opened for review." + tail)
```
And the entry point:
```python
if __name__ == "__main__":
if sys.argv[1:] == ["--test"]:
test()
else:
main(sys.argv[1] if len(sys.argv) > 1 else "", sys.argv[2] if len(sys.argv) > 2 else "")
```
`1 email, 1 items` is `counts` in insertion order: rules first, items last.
- [ ] **Step 4: Run**
Run: `examples/tools/redact.py --test`
Expected: `ok`. If `pdftotext -bbox` emits no `<page>` for a blank page, `pdf_words` misnumbers pages: check with `pdftotext -bbox` on the 2-page fixture.
- [ ] **Step 5: Commit**
```bash
git add examples/tools/redact.py
git commit -m "tools: redact, text PDFs to a pixels-only redacted copy"
```
---
### Task 3: Tool file
**Files:**
- Create: `examples/tools/redact.toml`
- [ ] **Step 1: Write it**
```toml
description = "Redact personal data (PII) from an attached PDF or image: writes a copy with black boxes, '<name>-redacted.<ext>' beside the original, and opens it for the user to check. Emails, phone numbers, IBANs, codici fiscali and card numbers are always found. Pass in items every other piece of personal data you see in the document: names, addresses, account or document numbers, exactly as written there. The original is not changed. Report what the tool says, including anything not found."
command = ["redact.py", "{path}", "{items}"]
cloud = ["hetzner"]
timeout = 120
[params.path]
type = "string"
description = "Absolute path of the attached file, from its file or image block."
[params.items]
type = "string"
description = "Extra strings to black out, one per line, exactly as they appear in the document. Empty if none."
```
`cloud = ["hetzner"]` fails `load_tools` until Task 5. Do not install it before Task 5 lands.
- [ ] **Step 2: Commit**
```bash
git add examples/tools/redact.toml
git commit -m "tools: redact.toml"
```
---
### Task 4: Path in attachment blocks (daemon)
**Files:**
- Modify: `assistant.py:367-394` (`attach`), tests at `assistant.py:1487-1520`
- [ ] **Step 1: Change the tests first**
At `assistant.py:1487-1489` the image now has a block too, and every block carries its path:
```python
blocks, refs, chips = attach([code, pdf, png], 100000)
assert blocks[0].startswith(f"--- file: a.py ({code}) ---\nprint('hi')") and "(truncated)" not in blocks[0]
assert "[page 1]\nhello pdf" in blocks[1] and "[page 2]" in blocks[1]
assert blocks[2] == f"--- image: red.png ({png}) ---"
```
At `assistant.py:1519` a path with a newline shows no path (it would close the block):
```python
assert c[0]["name"] == "a b.txt" and b[0].startswith("--- file: a b.txt ---\n")
```
(unchanged line, still true.) Any other test that compares a whole block or counts blocks with images present: run the self-check and update each to the new format.
- [ ] **Step 2: Run, verify fail**
Run: `python3 assistant.py --test`
Expected: assertion error at the `a.py ({code})` line.
- [ ] **Step 3: Implement in `attach`**
Inside the loop, after `chips.append(chip)`:
```python
# The path lets a tool (redact) open the file; a newline in it would
# close the block early, so such a path is left out.
where = f" ({p})" if "\n" not in p else ""
if kind == "image":
refs.append({"type": "image_ref", "name": name, "path": p, "sha256": sha256(p)})
blocks.append(f"--- image: {name}{where} ---")
continue
```
and the final append:
```python
blocks.append(f"--- file: {name}{where}{note} ---\n{body}\n--- end file ---")
```
- [ ] **Step 4: Run**
Run: `python3 assistant.py --test`
Expected: passes (prints its ok line).
- [ ] **Step 5: Commit**
```bash
git add assistant.py
git commit -m "attach: file and image blocks carry the path"
```
---
### Task 5: Per-provider tool trust (daemon)
**Files:**
- Modify: `assistant.py:123-124` (`load_tools`), `assistant.py:1162-1166` (`answer`), tests near `assistant.py:1340-1347`
- Modify: `examples/config.toml:23-24` (comment)
- [ ] **Step 1: Tests first, next to the existing `cloud = "yes"` test**
Replace its expected message and add:
```python
assert "cloud must be true, false or a list of provider names" in str(e)
with tempfile.TemporaryDirectory() as d:
with open(os.path.join(d, "x.toml"), "w") as f:
f.write('description = "d"\ncommand = ["date"]\ncloud = [1]\n')
try:
load_tools(d)
assert False
except SystemExit as e:
assert "list of provider names" in str(e)
with open(os.path.join(d, "x.toml"), "w") as f:
f.write('description = "d"\ncommand = ["date"]\ncloud = ["hetzner"]\n')
assert load_tools(d)["x"]["cloud"] == ["hetzner"]
tl = {"any": {"cloud": True}, "het": {"cloud": ["hetzner"]}, "local": {}, "no": {"cloud": False}}
assert offered_tools(tl, None) == tl
assert set(offered_tools(tl, "hetzner")) == {"any", "het"}
assert set(offered_tools(tl, "other")) == {"any"}
```
- [ ] **Step 2: Run, verify fail**
Run: `python3 assistant.py --test`
Expected: assertion on the new message.
- [ ] **Step 3: Implement**
`load_tools`:
```python
c = t.get("cloud", False)
if not (isinstance(c, bool) or isinstance(c, list) and all(isinstance(x, str) for x in c)):
raise SystemExit(f"{path}: cloud must be true, false or a list of provider names")
```
New function after `load_tools`:
```python
def offered_tools(tools, provider):
# A cloud chat is offered only tools whose cloud is true or names its
# provider: the others would send mail, money or calendar to it. A list
# names trusted no-retention providers; one added later gets nothing.
if not provider:
return tools
return {n: t for n, t in tools.items()
if t.get("cloud") is True or isinstance(t.get("cloud"), list) and provider in t["cloud"]}
```
In `answer`, replace the comment and `offered = ...` lines (`assistant.py:1162-1166`):
```python
# One not offered but called anyway (copied from history) answers
# "no tool named".
offered = offered_tools(TOOLS, route(model)[3])
```
`examples/config.toml` lines 23-24 comment:
```toml
# fetches the list with `assistant.py --cloud-models <name>`. A cloud chat
# is offered only the tools whose file says cloud = true, or names the
# provider: cloud = ["hetzner"].
```
- [ ] **Step 4: Run**
Run: `python3 assistant.py --test`
Expected: passes.
- [ ] **Step 5: Commit**
```bash
git add assistant.py examples/config.toml
git commit -m "tools: cloud may name trusted providers"
```
---
### Task 6: OCR data and images (user step, then live)
- [ ] **Step 1: Ask the user** which tesseract data to install and how (package in `my-slackbuilds`, or a manual copy into `/usr/share/tessdata/`):
- tessdata_fast: eng 4.1 MB, ita 2.7 MB.
- tessdata (standard): eng 23.5 MB, ita 16.0 MB.
Recommend standard: printed documents, accuracy over size. Do not download without the answer.
- [ ] **Step 2: Add the OCR case to `test()`**, run only when the data is there:
```python
langs = subprocess.run(["tesseract", "--list-langs"], capture_output=True, text=True).stdout.split()
if {"ita", "eng"} <= set(langs):
img = os.path.join(d, "s.png")
subprocess.run(["magick", "-size", "900x200", "xc:white", "-pointsize", "40",
"-annotate", "+20+100", "Scrivi a mario@example.org", img], check=True)
r = subprocess.run([__file__, img, ""], capture_output=True, text=True, env=env)
assert "1 email" in r.stdout and os.path.exists(os.path.join(d, "s-redacted.png")), r
scan = os.path.join(d, "scan.pdf")
tiny_pdf(scan, [""]) # a text-less page: OCR'd, nothing found
r = subprocess.run([__file__, scan, ""], capture_output=True, text=True, env=env)
assert r.stdout.startswith("nothing to redact found"), r
else:
print("skipped OCR: no ita/eng tesseract data")
```
- [ ] **Step 3: Run** `examples/tools/redact.py --test`. Expected: `ok`, without the skip line.
- [ ] **Step 4: Install and restart**
```bash
cp examples/tools/redact.py examples/tools/redact.toml ~/.config/desktop-assistant/tools/
./assistant.sh restart
```
Inspect `~/.config/desktop-assistant/tools/` first; nothing named redact should be there.
- [ ] **Step 5: Live check through the canvas**, with a scratch document (no real personal data): a text PDF and a phone photo of a printed page, each with a fake name, email, IBAN (`IT60X0542811101000000123456`) and address. Ask "redact the personal data in this". Record: tool called with the right path, items chosen, counts, what was missed, time, viewer opened. Then the same in a Hetzner chat: tool offered and called. Then in a chat on another provider if one exists, or by reasoning from Task 5's test: not offered.
- [ ] **Step 6: Commit** the OCR test.
```bash
git add examples/tools/redact.py
git commit -m "tools: redact, OCR check for images and scans"
```
---
### Task 7: Docs
**Files:**
- Modify: `docs/superpowers/specs/2026-11-09-redact-tool-design.md` (status, the adjustments listed at the top of this plan)
- Modify: `AGENTS.md` (a "Redact tool, live check (2026-11-..)" section under Findings, from Task 6 step 5; the cloud-list rule in the "Cloud models" intro paragraph)
- [ ] **Step 1:** Write both; measurements as numbers, no personal data.
- [ ] **Step 2:** Ask the user before committing (AGENTS rule), then:
```bash
git add AGENTS.md docs/superpowers/specs/2026-11-09-redact-tool-design.md
git commit -m "docs: redact tool live check"
```
|