AI Playbook中文

Local & private AI

Redact before you upload: placeholders, a local mapping file, a human look

Verification

Tested on
2026-11-23
What was tested
redact.py / restore.py / leakcheck.py on made-up sample text only; no real documents, PDFs, images or cloud models
Evidence level
Run locally with simulated inputs only
Status
Published
Version
0.1.0
Updated
2026-12-05
Source commit
e16314b8c3
Tools
python3 (standard library only) — the scripts below, any cloud chat/API model (the destination), or a local model (no redaction needed)
Models
Not filled in
Audience
creators, knowledge-workers, developers
Availability in mainland China
Available
Alternatives for mainland China
keep the whole job local (see local-model-jetson-consumer-gpu, offline-lm-studio), a data-masking tool or DLP feature your company already approves, manual redaction for short texts

Scope: this reduces risk; it is not an anonymization guarantee. Regexes recognise formats, not every kind of sensitive information; truly confidential material should go to a local model. All sample data here is made up. Framing: a solo developer's workflow. The destination can be any cloud model (Kimi, GLM, Qwen, DeepSeek, or Claude / GPT as examples); the scripts are vendor-neutral. If you use Claude: Anthropic has not supported mainland China, Hong Kong or Macau since 2026-11-12 (checked 2026-11-23).

Situation

Outcome

Steps

  1. Decide whether it may go to the cloud at all using the classification table. "Confidential" stays local.
  2. List names in names.txt: client names, company names, project code names, internal system names, one per line. Regexes can't find names; only you can.
  3. Run the redaction: python3 redact.py in.txt out.txt map.json names.txt. map.json is written with mode 600 (the script forces 600 even if the file already existed); keep it local — never upload or commit it.
  4. Read out.txt yourself for what slipped through (addresses, company abbreviations, business details, text inside screenshots); add to names.txt and rerun if needed.
  5. Upload out.txt with a note: "bracketed placeholders are redactions; keep them verbatim".
  6. Restore: save the reply as ans.txt, run python3 restore.py ans.txt map.json back.txt.
  7. Delete map.json and intermediates when done (or keep them on an encrypted disk).

Templates

The scripts are in the Chinese section (code is in English). Classification table (English):

| Level | Examples | Handling |
|---|---|---|
| Public | published articles, official docs | may go to the cloud as is |
| Internal | ordinary work docs, logs without personal data | redact then cloud, or local |
| Sensitive | client data with personal information, financial detail | local only; ask compliance before any cloud use |
| Confidential | keys, unpublished contract terms, NDA-covered content | never to a cloud or third-party AI; only a local model on a machine you control may process it |

Failure cases

China alternatives

Safety notes

Test notes

Verification

来源 / Sources

  • OWASP MCP Security Cheat Sheet (data exfiltration risks in tool use): https://cheatsheetseries.owasp.org/cheatsheets/MCP_Security_Cheat_Sheet.html
  • Anthropic Supported Regions Policy (checked 2026-11-23): https://www.anthropic.com/legal/supported-regions

Source links

Export to your agent

Path: redact-before-upload/SKILL.md

Preview
---
name: redact-before-upload
description: "Redact before you upload: placeholders, a local mapping file, a human look. Use when the user asks for help with this task."
metadata:
  version: "0.1.0"
  status: "published"
  source-commit: "5f7272be13826bec473d6f2e073c82a5a620f1d2"
---

# Redact before you upload: placeholders, a local mapping file, a human look

- Version: 0.1.0
- Status: published
- Tested on: 2026-11-23
- Tested scope: redact.py / restore.py / leakcheck.py on made-up sample text only; no real documents, PDFs, images or cloud models
- Evidence level: local-simulated-test
- Source commit: 5f7272be13826bec473d6f2e073c82a5a620f1d2

> Reference playbook: follow it only when the user asks for this task, and ask a human before running commands or irreversible actions.

## English

> **Scope:** this reduces risk; it is **not an anonymization guarantee**. Regexes recognise formats, not every kind of sensitive information; truly confidential material should go to a local model. All sample data here is made up.
> **Framing: a solo developer's workflow.** The destination can be any cloud model (Kimi, GLM, Qwen, DeepSeek, or Claude / GPT as examples); the scripts are vendor-neutral. If you use Claude: Anthropic has not supported mainland China, Hong Kong or Macau since 2026-11-12 (checked 2026-11-23).

### Situation
- **Audience:** you want a cloud model to process contracts, support transcripts, logs or customer sheets that contain emails, phone numbers, ID numbers, keys, internal IPs or client names.
- **When to use:** the task needs a cloud model's capability but the **specific personal/client details don't matter** to it (e.g. "categorize this support chat").
- **When not to use:** the sensitive data is the subject of the task (e.g. "verify this person's ID number") — use a local model; data that law or contract forbids sending out — ask compliance, don't rely on masking.

### Outcome
- A local script replacing emails, phone-number-shaped strings, ID-shaped numbers, card-shaped numbers, IPs, common key prefixes and your listed names/companies/projects with placeholders like `[EMAIL_1]`;
- a mapping file that never leaves the machine, used to restore placeholders in the model's reply;
- a pre-upload review checklist.

### Steps
1. **Decide whether it may go to the cloud at all** using the classification table. "Confidential" stays local.
2. **List names in `names.txt`:** client names, company names, project code names, internal system names, one per line. Regexes can't find names; only you can.
3. **Run the redaction:** `python3 redact.py in.txt out.txt map.json names.txt`. `map.json` is written with mode 600 (the script forces 600 even if the file already existed); **keep it local — never upload or commit it.**
4. **Read `out.txt` yourself** for what slipped through (addresses, company abbreviations, business details, text inside screenshots); add to `names.txt` and rerun if needed.
5. **Upload `out.txt`** with a note: "bracketed placeholders are redactions; keep them verbatim".
6. **Restore:** save the reply as `ans.txt`, run `python3 restore.py ans.txt map.json back.txt`.
7. **Delete `map.json` and intermediates** when done (or keep them on an encrypted disk).

### Templates
The scripts are in the Chinese section (code is in English). Classification table (English):
```markdown
| Level | Examples | Handling |
|---|---|---|
| Public | published articles, official docs | may go to the cloud as is |
| Internal | ordinary work docs, logs without personal data | redact then cloud, or local |
| Sensitive | client data with personal information, financial detail | local only; ask compliance before any cloud use |
| Confidential | keys, unpublished contract terms, NDA-covered content | never to a cloud or third-party AI; only a local model on a machine you control may process it |
```

### Failure cases
- **Regex misses (boundaries found while testing):** formats only. Names, addresses, company abbreviations and "that big client" are not replaced — rely on `names.txt` and a human read.
- **False positives:** 16-digit order numbers or date strings can look like card numbers; 18-digit strings may be other IDs. Hence the review and the visible `map.json`.
- **A leaked mapping file defeats the purpose:** it holds every original value.
- **The model rewrites placeholders:** ask for verbatim retention and check placeholder counts before restoring.
- **Other formats:** text only. PDFs, images and spreadsheets must be converted first; text inside screenshots is especially risky; not handled here.

### China alternatives
- `china_availability: yes`: the scripts use only the local standard library. Use Kimi / GLM / Qwen / DeepSeek or any domestic service as destination; whether a data category may go to a given service depends on **your contracts, company policy and applicable law** — this is not compliance advice.
- ID and phone formats follow common mainland-China shapes; add rules for other countries yourself.

### Safety notes
- **Never send "confidential" material to a cloud model, redacted or not** (processing it with a local model on a machine you control is fine).
- Redacted text can sometimes be re-identified from context; for high risk use a local model.
- Scripts and mapping run locally only; **never commit a real mapping file** — only samples belong in repos.
- Don't use real keys or ID numbers as test data; use made-up data like the sample here.

### Test notes
- 2026-11-23, local machine (WSL2 Linux, Python 3.8, stdlib only), **made-up** sample text: an email, a phone-shaped number, an 18-char ID-shaped number, a card-shaped number, an IPv4, a fake `sk-` key and two names/project names — 8 values replaced; a repeated email got the same placeholder; `map.json` mode 600 (a pre-existing 644 file is forced to 600); `leakcheck.py` passed, and on un-redacted text it fails and prints placeholder names only, never the values; replacement is a single pass: with `NAME` in the names list and `[NAME_1]` / `[EMAIL_1]` already in the input, new placeholders skip the existing ones and restoring reproduces the original (name case follows the first occurrence); `restore.py` restored placeholders in a reply.
- **Not tested:** real documents; PDF/images; Chinese addresses and names; how any cloud model handles the placeholders.

### Verification
- Run on the sample and confirm `out.txt` contains no original values (`leakcheck.py` plus a human read).
- Before real work, run the whole flow on a realistic fake document.

## 来源 / Sources

- OWASP MCP Security Cheat Sheet (data exfiltration risks in tool use): https://cheatsheetseries.owasp.org/cheatsheets/MCP_Security_Cheat_Sheet.html
- Anthropic Supported Regions Policy (checked 2026-11-23): https://www.anthropic.com/legal/supported-regions

## Code and templates from the Chinese section (may contain Chinese comments or text)

**Block 1 — `redact.py`**

```python
#!/usr/bin/env python3
"""Replace sensitive-looking strings with placeholders BEFORE text leaves your machine (single pass over the ORIGINAL text).
usage: redact.py in.txt out.txt map.json [names.txt]
- map.json stays local (mode 600) and is used by restore.py to put the originals back into the model's answer.
- names.txt: one name / company / project per line (regex can't find names by itself)."""
import json, os, re, sys

PATTERNS = [                       # alternation order = priority at the same position
    ("KEY",    r"\b(?:sk|pk|ghp|gho|xox[bp])[-_][A-Za-z0-9_-]{16,}\b"),
    ("EMAIL",  r"\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b"),
    ("IDCARD", r"(?<!\d)\d{17}[\dXx](?!\d)"),                 # mainland-China 18-char resident ID shape
    ("PHONE",  r"(?<!\d)1[3-9]\d{9}(?!\d)"),                   # mainland-China mobile number shape
    ("CARD",   r"(?<!\d)\d{4}[ -]?\d{4}[ -]?\d{4}[ -]?\d{3,4}(?!\d)"),
    ("IP",     r"(?<!\d)(?:\d{1,3}\.){3}\d{1,3}(?!\d)"),
]
src, dst, mp = sys.argv[1:4]
names = sorted({l.strip() for l in open(sys.argv[4], encoding="utf-8") if l.strip()}, key=len, reverse=True) if len(sys.argv) > 4 else []
text = open(src, encoding="utf-8").read()
parts = [f"(?P<{k}>{p})" for k, p in PATTERNS]
if names: parts.append("(?P<NAME>" + "|".join(re.escape(n) for n in names) + ")")
rx = re.compile("|".join(parts), re.I if names else 0)
mapping, seen, counters = {}, {}, {}

def placeholder(kind):
    while True:                                      # never reuse a placeholder-shaped string that already occurs in the input
        counters[kind] = counters.get(kind, 0) + 1
        ph = f"[{kind}_{counters[kind]}]"
        if ph not in text and ph not in mapping: return ph

def rep(m):
    kind, v = m.lastgroup, m.group(0)
    key = (kind, v.lower() if kind == "NAME" else v)
    if key not in seen:
        ph = placeholder(kind); seen[key] = ph; mapping[ph] = v
    return seen[key]

out = rx.sub(rep, text)                              # one pass: placeholders are never re-scanned
open(dst, "w", encoding="utf-8").write(out)
fd = os.open(mp, os.O_WRONLY | os.O_CREAT, 0o600)
os.fchmod(fd, 0o600)                                 # open() keeps the mode of an EXISTING file, so force 600 before writing
os.ftruncate(fd, 0)
with os.fdopen(fd, "w", encoding="utf-8") as f: json.dump(mapping, f, ensure_ascii=False, indent=1)
kinds = {}
for ph in mapping: kinds[ph[1:ph.index("_")]] = kinds.get(ph[1:ph.index("_")], 0) + 1
print(f"{len(mapping)} distinct values replaced: " + ", ".join(f"{k}={v}" for k, v in kinds.items()))
```

**Block 2 — `restore.py`**

```python
#!/usr/bin/env python3
"""usage: restore.py answer.txt map.json out.txt  — put originals back into the model's reply (local only; single pass)."""
import json, re, sys
t = open(sys.argv[1], encoding="utf-8").read(); m = json.load(open(sys.argv[2], encoding="utf-8"))
open(sys.argv[3], "w", encoding="utf-8").write(re.sub(r"\[[A-Z]+_\d+\]", lambda x: m.get(x.group(0), x.group(0)), t))
```

**Block 3 — `leakcheck.py`**

```python
#!/usr/bin/env python3
"""usage: leakcheck.py redacted.txt map.json — exit 1 if any original value still appears in the redacted text (prints placeholder names only)."""
import json, sys
t = open(sys.argv[1], encoding="utf-8").read()
leaks = [ph for ph, v in json.load(open(sys.argv[2], encoding="utf-8")).items() if v in t]   # report placeholders, never the secret values
print(f"LEAK: {len(leaks)} original value(s) still present, for placeholders: {', '.join(leaks)}" if leaks else "no known originals left"); sys.exit(1 if leaks else 0)
```