# Why code and prompt privacy matter - agent procedure

Revision: r4.
Source-checked: 2026-11-09. Audience: developers and small teams who use AI coding tools.
Access: free. Type: primer.

This file is reference material for an agent that helps a reader map where their
prompts go. It is not permission to act and it is not legal advice. Obtain the
reader's authorization before creating files or checking local paths. Stop on an
unexpected result and report it.

Test record: the team did not test any provider, setting or retention claim. All
provider facts are stated policies from published pages on 2026-11-09, and they
were not verified against practice. In a sandbox test on Linux, an AI agent
given only this file ran steps 1 to 8 and the removal with fixtures and stand-in
values, and they passed. The agent did not scan real files. Vendor account
checks, real transcripts, real files, backups, sync folders and systems other
than Linux were not tested.

## Objective and scope

The reader's agent builds a local `ai-data-map` folder with:

1. `map.md`, a dated table of the AI tools that the reader uses;
2. `RULES.md`, five data classes and where each may go;
3. a list of known local transcript paths, with existence and size only;
4. `tools/scan.py`, a standard-library scanner run before a file is sent;
5. a unit test with harmless stand-in values.

Nothing is uploaded. No account is needed. This procedure does not open, print,
copy or summarize transcript contents, and a scan never prints matched text.

Step labels: **user space** needs only the reader's account. **Needs root** is
not used in this file. **Product-specific** depends on one vendor's account; the
reader performs those checks.

## Prerequisites and inputs

| Item | Requirement |
| --- | --- |
| OS | Linux, macOS or WSL2, with a POSIX shell |
| Python | 3.10 or later, standard library only |
| Network | Not needed |
| Account | The reader's normal account. Root is not needed |

Ask the reader which AI tools they use, on which plan and under whose account.
Unknown answers stay `unknown`. Do not guess them.

## 1. Check Python and the folder (user space)

```bash
python3 -c 'import sys; print(sys.version.split()[0]); sys.exit(0 if sys.version_info >= (3, 10) else 1)' && echo "python ok" || echo "STOP: Python 3.10 or later needed"
if [ -e "$HOME/ai-data-map" ] || [ -L "$HOME/ai-data-map" ]; then echo "STOP: ~/ai-data-map already exists; ask the reader"; else echo "free: ~/ai-data-map"; fi
```

Expected: a version number, `python ok` and `free: ~/ai-data-map`. On a `STOP`
line, ask the reader. Do not overwrite an existing folder.

## 2. Create the folder (user space)

The folder is private because it can describe where sensitive data is.

```bash
mkdir -m 700 "$HOME/ai-data-map" && mkdir -m 700 "$HOME/ai-data-map/tools" && echo "folder ok"
```

Expected: `folder ok`.

## 3. Write the data map (user space)

```bash
test ! -e "$HOME/ai-data-map/map.md" && cat > "$HOME/ai-data-map/map.md" <<'MAP_END_4F'
# AI data map

Each value has a source. If a value is not known, write "unknown".
Do not put keys, tokens or transcript text in this file.

| Tool | Plan | Account owner | Training setting | Retention | Storage region | Local transcript path | Source URL | Check date |
| --- | --- | --- | --- | --- | --- | --- | --- | --- |
MAP_END_4F
grep -c '^| ' "$HOME/ai-data-map/map.md"
```

Expected: `2`. Add one row per tool with the reader's answers. These stated
policies were current on 2026-11-09. Read the page again before recording one.

| Service | Stated training | Stated retention | Page |
| --- | --- | --- | --- |
| Claude Free, Pro, Max, Ultra | When the setting is on | 5 years if on; 30 days if off | code.claude.com/docs/en/data-usage |
| Claude Team, Enterprise, API | Not unless the customer chooses | API: privacy centre says within 30 days, with exceptions (flagged content up to 2 years, scores up to 7 years, and longer where law requires). The API retention page says that, where a feature needs storage, conversation content is not retained by default, except certain models. Plan on the 30 days unless the contract says otherwise | privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data |
| OpenAI API | Not unless opted in | Abuse logs up to 30 days by default; some stored objects until deleted | developers.openai.com/api/docs/guides/your-data |
| ChatGPT personal plans | unknown: pages could not be loaded | unknown | Reader checks data controls in settings |
| Copilot Free, Pro, Pro+ | Yes unless opted out, from April 24 (post dated 2026-03-25) | unknown | github.blog (Copilot interaction data post) |
| Copilot Business, Enterprise | Not affected by that change | unknown | same post |
| Cursor Privacy Mode | Stated no training when enabled | See its privacy policy | cursor.com/security, cursor.com/privacy |

For Cursor, the pages read do not say whether code passes through Cursor servers
or whether model providers keep zero data. Record `unknown` for both.

## 4. Write the sorting rule (user space)

```bash
test ! -e "$HOME/ai-data-map/RULES.md" && cat > "$HOME/ai-data-map/RULES.md" <<'RULES_END_9B'
# Where data may go

The reader decides. These are starting defaults. Date each change.

| Class | Example | May go to |
| --- | --- | --- |
| Public | Open-source code, published documents | Any tool accepted for other reasons |
| Internal | Ordinary private code | Accounts with training off, checked and dated |
| Confidential | Client code, unreleased plans | Only under a business contract that has been read |
| Personal | Names, emails, customer records | De-identify first; otherwise only where authorized |
| Secret | Keys, passwords, tokens | Never in a prompt. If one was sent, rotate it |
RULES_END_9B
grep -c '^| ' "$HOME/ai-data-map/RULES.md"
```

Expected: `7`. Ask the reader to confirm or change the middle rows. The `Secret`
row stays.

## 5. List local transcript paths (user space)

Transcripts can hold code, names and credentials. This block reports only whether
a known path exists and its total size. Do not open, print, search, copy or
summarize anything inside these paths, and do not run the scanner on them.

```bash
for p in "$HOME/.claude/projects" "$HOME/.codex" "$HOME/.local/share/goose/sessions" "$HOME/.config/goose"; do
  if [ -e "$p" ]; then printf 'exists  %s  %s\n' "$(du -sh -- "$p" 2>/dev/null | cut -f1)" "$p"; else printf 'absent  -  %s\n' "$p"; fi
done
```

Expected: one line per path, `exists` with a size or `absent`. Copy paths and
sizes only into the map's transcript column: `.claude/projects` is Claude Code,
`.codex` is Codex, and the two goose paths are goose. If a found path has no row,
add one for that tool with `unknown` answers. This list is not complete. Other
tools keep other paths, and Aider writes `.aider.chat.history.md` inside each
project by default. Ask the reader whether backups or sync folders include these
paths. Do not check inside backups.

## 6. Write the scanner (user space)

```bash
test ! -e "$HOME/ai-data-map/tools/scan.py" && cat > "$HOME/ai-data-map/tools/scan.py" <<'SCAN_END_3Q'
#!/usr/bin/env python3
"""Flag obvious secrets and email addresses in files before they are sent.

Usage: scan.py FILE [FILE ...]
Prints file, line and pattern name. It never prints the matched text.
Exit: 0 no findings, 1 findings, 2 a file could not be scanned.
A clean result does not prove that a file is safe.
"""
import pathlib
import re
import stat
import sys

MAX_BYTES = 10_000_000
PATTERNS = {
    'private_key_header': re.compile(r'-----BEGIN [A-Z ]*PRIVATE KEY-----'),
    'aws_access_key_id': re.compile(r'\b(?:AKIA|ASIA)[0-9A-Z]{16}\b'),
    'password_assignment': re.compile(
        r'\b(?:password|passwd|pwd|secret|api[_-]?key|token)\b["\']?\s*[:=]\s*\S+', re.I),
    'token_prefix': re.compile(r'\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_\w{20,}|sk-[A-Za-z0-9_-]{20,})'),
    'email_address': re.compile(r'\b[\w.+-]+@[\w-]+(?:\.[\w-]+)+\b'),
}


def scan_text(text):
    found = []
    for number, line in enumerate(text.splitlines(), 1):
        for name, pattern in PATTERNS.items():
            if pattern.search(line):
                found.append((number, name))
    return found


def main(argv):
    if len(argv) < 2:
        print('usage: scan.py FILE [FILE ...]', file=sys.stderr)
        return 2
    total = 0
    failed = False
    for arg in argv[1:]:
        path = pathlib.Path(arg)
        shown = ''.join(ch for ch in arg if ch.isprintable())
        try:
            info = path.stat()
            if not stat.S_ISREG(info.st_mode):
                raise ValueError('not a regular file')
            if info.st_size > MAX_BYTES:
                raise ValueError('larger than the limit')
            raw = path.read_bytes()
            if b'\0' in raw:
                raise ValueError('contains NUL bytes')
            text = raw.decode('utf-8', 'replace')
        except (OSError, ValueError) as error:
            reason = error if isinstance(error, ValueError) else type(error).__name__
            print(f'{shown}: not scanned ({reason})', file=sys.stderr)
            failed = True
            continue
        for number, name in scan_text(text):
            print(f'{shown}:{number}: {name}')
            total += 1
    print(f'findings: {total}')
    print('A clean result does not prove that a file is safe.')
    if failed:
        return 2
    return 1 if total else 0


if __name__ == '__main__':
    sys.exit(main(sys.argv))
SCAN_END_3Q
python3 -I -B -c 'import ast,os; ast.parse(open(os.path.expanduser("~/ai-data-map/tools/scan.py")).read()); print("syntax ok")'
```

Expected: `syntax ok`.

## 7. Test the scanner (user space, harmless values)

`AKIAIOSFODNN7EXAMPLE` is the example key from the AWS documentation and
`user@example.invalid` uses a reserved domain. Neither is real.

```bash
test ! -e "$HOME/ai-data-map/tools/fixture.txt" && cat > "$HOME/ai-data-map/tools/fixture.txt" <<'FIXTURE_END_8Z'
key = AKIAIOSFODNN7EXAMPLE
contact user@example.invalid
this line is clean
FIXTURE_END_8Z
test ! -e "$HOME/ai-data-map/tools/test_scan.py" && cat > "$HOME/ai-data-map/tools/test_scan.py" <<'TEST_END_1D'
import contextlib
import io
import pathlib
import tempfile
import unittest

import scan

FIXTURE = pathlib.Path(__file__).resolve().parent / 'fixture.txt'


class ScanTest(unittest.TestCase):
    def quiet_main(self, target):
        with contextlib.redirect_stderr(io.StringIO()), contextlib.redirect_stdout(io.StringIO()):
            return scan.main(['scan.py', str(target)])

    def test_two_findings_and_clean_line(self):
        found = scan.scan_text(FIXTURE.read_text())
        self.assertEqual(found, [(1, 'aws_access_key_id'), (2, 'email_address')])

    def test_output_has_no_matched_text(self):
        out = io.StringIO()
        with contextlib.redirect_stdout(out):
            code = scan.main(['scan.py', str(FIXTURE)])
        self.assertEqual(code, 1)
        self.assertNotIn('AKIAIOSFODNN7EXAMPLE', out.getvalue())
        self.assertNotIn('user@example.invalid', out.getvalue())

    def test_private_key_header(self):
        line = '-----BEGIN ' + 'RSA PRIVATE KEY-----'
        self.assertEqual(scan.scan_text(line), [(1, 'private_key_header')])

    def test_password_assignment(self):
        self.assertEqual(scan.scan_text('password = stand-in'), [(1, 'password_assignment')])

    def test_token_prefix(self):
        self.assertEqual(scan.scan_text('ghp_' + 'a' * 36), [(1, 'token_prefix')])
        self.assertEqual(scan.scan_text('sk-' + 'ant-' + 'a' * 30), [(1, 'token_prefix')])

    def test_nul_bytes_not_scanned(self):
        with tempfile.TemporaryDirectory() as folder:
            path = pathlib.Path(folder) / 'wide.txt'
            path.write_bytes('text'.encode('utf-16'))
            self.assertEqual(self.quiet_main(path), 2)

    def test_directory_not_scanned(self):
        with tempfile.TemporaryDirectory() as folder:
            self.assertEqual(self.quiet_main(folder), 2)

    def test_missing_file_is_an_error(self):
        err = io.StringIO()
        with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()):
            code = scan.main(['scan.py', str(FIXTURE) + '.missing'])
        self.assertEqual(code, 2)


if __name__ == '__main__':
    unittest.main()
TEST_END_1D
cd "$HOME/ai-data-map" && if python3 -I -B -m unittest discover -s tools -p 'test_*.py' -v; then python3 -I -B tools/scan.py tools/fixture.txt; echo "exit $?"; else echo "STOP: unit tests failed"; fi
```

Expected: eight tests pass, then these lines:

```text
tools/fixture.txt:1: aws_access_key_id
tools/fixture.txt:2: email_address
findings: 2
A clean result does not prove that a file is safe.
exit 1
```

Neither stand-in value appears in the output. If a test fails, stop and report.

To use the scanner on a real file, the reader runs this in their own terminal:
`python3 -I -B ~/ai-data-map/tools/scan.py FILE`. An agent must not run it on
a real file, because its results name files and lines, and anything an agent
reads enters its conversation, which is itself a prompt. Do not ask the reader
to paste the results. Keep them out of shared folders and prompts. Patterns
miss names, addresses and business context. Tell the reader to read the file
as well.

## 8. Report (user space)

```bash
cd "$HOME/ai-data-map" && echo "unknown values in map: $(grep '^| ' map.md | grep -o -i 'unknown' | wc -l | tr -d ' ')"; python3 -I -B -c 'import datetime as d; print("recheck by:", d.date.today() + d.timedelta(days=90))'
```

Expected: a count and a date. Ninety days is a suggested interval; the reader can
choose another. Tell the reader each `unknown`, and these product-specific checks
for them to make in their own accounts: the training setting, the retention term
in the contract or plan, and any data-region option. State that the policies are
as published and were not verified against practice.

## Security controls

- Transcript paths: existence and size only (step 5).
- The scanner prints no matched text and does not transmit anything.
- The folder is mode 700. Keep scan results out of shared folders.
- If the reader finds a real secret, advise them to remove and rotate it. Do
  not ask for the secret, the file name or the line.

## Maintenance, backup and restore

- Update: repeat step 3 for each tool by the recheck date, on any plan change,
  and when a vendor announces new terms. Date each row.
- Backup: copy `~/ai-data-map` to the reader's normal backup location. It holds
  no prompts, but it does describe their tools.
- Restore: copy it back with mode 700, then repeat step 7.

## Rollback and removal

Destructive. Ask the reader first, and show the path.

```bash
rm -r -- "$HOME/ai-data-map"
```

This removes only the folder from this procedure. It does not touch transcripts.

## Replacement path

The map and rules are plain Markdown and work with any tool or provider. When a
tool changes, replace its row and rerun step 5 with the new tool's documented
path. To replace the scanner, use a dedicated secret scanner chosen by the reader
and review it first.

## Evidence and testing

Source-based: the provider and legal statements, read on 2026-11-09. Not verified
against practice. Sandbox test: steps 1 to 8 and the removal, with fixtures and
stand-in values, passed. The agent did not scan real files. Not tested: vendor
account checks, real transcripts, real files, backups, sync folders and systems
other than Linux.

## Full primer text

A test is failing at the end of a long day. You copy the function into your
coding assistant, and because the bug only shows up with real data, you paste a
row from the customer table as well. The assistant finds the off-by-one error in
seconds. Where did that customer's name go?

Most answers to that question are either alarm or reassurance, and neither helps
you decide what to paste tomorrow. A more useful approach is to follow the prompt
from stop to stop and ask the same thing at each one: who holds this now, for how
long, and what controls that? The answers depend far more on your plan and your
settings than on the name of the vendor. Everything below about providers comes
from what they publish, as read on 2026-11-09. Nobody outside these companies can
easily confirm that practice matches the policy, and we did not try to.

## Three questions that get merged into one

"We do not train on your data" sounds like a complete answer. It settles one
question out of three.

**Training** asks whether your text can shape a future model. **Retention** asks
how long a copy exists. **Access** asks who can read that copy while it does,
including safety reviewers, a court, or someone who has stolen a password. A
provider can decline to train on a prompt and still keep it for a month, and a
month is long enough for each kind of access to apply. Keep the three apart as
you read any policy, including the summaries below.

## First stop: your own machine

The prompt has not left your laptop and it has already been copied. Coding tools
keep transcripts so that you can resume a session. Claude Code
[stores them in plain text](https://code.claude.com/docs/en/data-usage) under
`~/.claude/projects/`, for 30 days by default. Other tools keep their own records
in their own formats, and those files sit inside whatever your backup software
already collects. That customer row may now be in a transcript, a nightly backup
and a cloud sync folder.

The practical step is modest: find out which tools on your machine keep
transcripts, and treat those folders as you would treat the data you pasted.

## Second stop: anything in the middle

Between the tool and the model there may be an editor extension, a proxy or a
router that lets you switch providers. Each one sees the prompt, and each one
also holds keys worth stealing. In March 2026, two releases of the LiteLLM
routing library on PyPI
[were compromised](https://docs.litellm.ai/blog/security-update-march-2026). They
were live for about 40 minutes and, according to the project's notice, appear
to have included a credential stealer. The notice says users of its official
Docker image were not affected, which is a
useful reminder that how you install a middle layer matters as well as which one
you choose. Pin the versions of anything that handles your prompts and your keys,
and know what would need replacing if one of them turned on you.

## Third stop: the provider, and which plan you are on

This is the stop people usually mean, and the plan matters more than the brand.
The table holds stated policies on the check date, and these change often.

| Service | Used for training? | How long is it kept? |
| --- | --- | --- |
| [Claude, personal plans](https://code.claude.com/docs/en/data-usage) (Free, Pro, Max, Ultra) | Yes, when the setting is on | [5 years if on](https://www.anthropic.com/news/updates-to-our-consumer-terms); 30 days if off |
| [Claude, commercial](https://code.claude.com/docs/en/data-usage) (Team, Enterprise, API) | Not unless the customer chooses to provide data | [Privacy centre: within 30 days for API](https://privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data), with exceptions. The [API retention page](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention) says that, where a feature needs storage, conversation content is not retained by default, except certain models. Plan on the 30 days unless your contract says otherwise |
| [OpenAI API](https://developers.openai.com/api/docs/guides/your-data) | Not unless you opt in | Abuse-monitoring logs up to 30 days by default; some stored objects until deleted |
| [Copilot Free, Pro, Pro+](https://github.blog/news-insights/company-news/updates-to-github-copilot-interaction-data-usage-policy/) | Yes, unless you opt out | Not stated in the announcement |
| Copilot Business, Enterprise | Not affected by that change | Not stated in the announcement |
| [Cursor with Privacy Mode](https://cursor.com/security) | Stated no-training when enabled | See its [privacy policy](https://cursor.com/privacy) |

Three rows deserve a closer look. GitHub's change took effect from April 24,
according to a post dated March 25, 2026, and the wording is careful. Private
repository content "at rest" is excluded, but code you are actively working on
with Copilot counts as interaction data. So a private repository offers less
protection here than the word suggests.

Cursor says it applies technical controls and contract terms to its model
providers when Privacy Mode is on. The pages we read do not say whether code
passes through Cursor's own servers, or that providers keep nothing, so do not
assume either.

We could not load OpenAI's pages on consumer ChatGPT plans when we checked, so
the table has no row for them. Check the data controls in your own ChatGPT
settings, and read that page yourself rather than relying on what the API
terms say. API terms do not describe a personal subscription.

The same warning applies in reverse to anyone reasoning from the word "enterprise".
Find the contract or the settings page that covers your exact account, and note
the date you read it.

## Fourth stop: people, and the exceptions

"Deleted within 30 days" nearly always has a list after it. Anthropic's
[retention article](https://privacy.claude.com/en/articles/7996866-how-long-do-you-store-my-organization-s-data)
says inputs and outputs flagged by its automated safety systems can be kept for
up to two years, and classification scores for up to seven, and that it may keep
data as the law requires. Zero-data-retention terms are a separate approved
arrangement, and they [do not cover everything](https://platform.claude.com/docs/en/manage-claude/api-and-data-retention):
Anthropic lists certain models that require 30-day retention. OpenAI similarly
says abuse logs may be kept longer when the law requires it.

These exceptions exist for understandable reasons. They still mean that a
retention figure is a default, and you should not plan as if it were a ceiling.

## Fifth stop: a court

In 2025, in the New York Times copyright case, a US court required OpenAI to keep
ChatGPT output logs it would otherwise have deleted. The press
[dated that order to May](https://www.engadget.com/ai/openai-no-longer-has-to-preserve-all-of-its-chatgpt-data-with-some-exceptions-192422093.html).
A [stipulation and order filed on 2025-10-09](https://blogs.duanemorris.com/classactiondefense/wp-content/uploads/sites/56/2025/10/In-re-Open-AI-Inc.-Copyright-Infringement-Litig.-10.9.25-Order-ECF-No.-992.pdf)
ended the ongoing duty to "preserve and segregate all output log data that would
otherwise be deleted" as of September 26. It did not end everything. Logs already
preserved stayed preserved, apart from those originating in the European Economic
Area, Switzerland or the United Kingdom, and OpenAI would keep preserving logs
from accounts tied to domains named by the plaintiffs.

Nobody in that dispute was thinking about your customer's row. That is the point.
A deletion setting describes the normal course of business, and a legal hold can
override it for reasons that have nothing to do with you.

## Two ways out that no setting covers

Human error needs no flaw in any product. In 2023,
[Bloomberg reported an internal Samsung memo](https://www.techradar.com/news/samsung-bans-chatgpt-use-after-employee-leak)
that restricted generative AI tools on company devices, and press accounts
connected this to staff entering source code into ChatGPT. We have read those
reports and no statement from Samsung itself, and details vary between them. The
pattern is familiar enough without the details: someone in a hurry pastes what is
in front of them. The Canadian Centre for Cyber Security
[lists the same risk](https://www.cyber.gc.ca/en/guidance/generative-artificial-intelligence-ai-itsap00041),
warning that people can paste confidential business data or details about
individuals without realizing it.

Agents add a second route, because they act on what they read. Researchers at
Invariant Labs [demonstrated](https://invariantlabs.ai/blog/mcp-github-vulnerability)
an agent reading a planted issue in a public repository and then copying private
repository data into a public pull request. That was a demonstration with demo
repositories, but it shows why an agent with access to both private
data and a public channel deserves more care than a chat window.

Secrets are a separate case from personal data, and simpler. If an API key or
password went into a prompt, rotate it. Do not spend time working out whether the
provider's policy makes that unnecessary.

## A rule you can apply while tired

Everything above comes down to a decision you make in a few seconds, so it helps
to make it once in advance. Sort what you might paste into five classes and
decide where each may go.

| Class | Example | A reasonable default |
| --- | --- | --- |
| Public | Open-source code, published documents | Any tool you accept for other reasons |
| Internal | Ordinary private code | Only accounts with training off, checked and dated |
| Confidential | Client code, unreleased plans | Only under a business contract that you have read |
| Personal | Names, emails, customer records | De-identify first. Otherwise only where authorized |
| Secret | Keys, passwords, tokens | Never in a prompt |

The defaults are our suggestion, and yours may be stricter. The agent download
turns this into a dated map of your tools and a small scanner that flags obvious
secrets and email addresses before you send a file. A clean scan proves very
little, since no pattern can recognize a customer's name in a comment.

Then choose your controls. A settings change is free and takes a minute. A
business contract costs money and buys defined terms. Replacing that customer row
with made-up values costs thirty seconds and removes the question entirely.
Running a local model removes the provider stop, while adding the stops you now
operate yourself: the machine, the logs, the backups and the updates.

None of these makes a prompt private in any absolute sense. They reduce how many
hands it passes through, and they let you say which hands those are. Back at the
failing test, the better paste was the function and an invented customer named
Test User. The bug was never in the name.
