doppelcode 0.7.0b5.post1__py3-none-any.whl

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.
doppelcode/vault.py ADDED
@@ -0,0 +1,85 @@
1
+ """Persistent mapping + baseline (``<project>/.doppel/vault.json``)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+
9
+ FORMAT = 1
10
+
11
+ KIND_PREFIX = {"macro": "M_", "type": "T_", "func": "fn_", "var": "v_", "file": "mod_", "dir": "dir_", "word": "w_",
12
+ "data": "file_", "secret": "K_", "body": "B_"} # data: names of data files used in strings ("rec_01.dat" -> "file_0001.dat")
13
+ OPAQUE_PREFIX = "id_"
14
+
15
+
16
+ class Vault:
17
+ def __init__(self, path: Path):
18
+ self.path = path
19
+ self.data: dict = {
20
+ "format": FORMAT,
21
+ "words": {}, # original word -> generated word (identifiers, file stems, extra words)
22
+ "kinds": {}, # original word -> kind
23
+ "stems": [], # original words that are file stems
24
+ "dirs": {}, # original dir name -> generated dir name
25
+ "counters": {}, # prefix -> last used number
26
+ "twin": None, # absolute twin path
27
+ "baseline": {}, # orig_rel -> {twin, mode, orig_sha, twin_sha}
28
+ "twin_idents": [], # identifiers present in twin C files at last export/import
29
+ "comments": {}, # cmt_0001 -> original comment text (comments = "hide")
30
+ "strings": {}, # str_0001 -> original string literal (strings = "hide")
31
+ "data_twin": [], # data files copied into the twin (twin paths; data_files = "copy")
32
+ "data_dirs_twin": [], # twin folders holding data: ignored by import (program output)
33
+ }
34
+ if path.exists():
35
+ loaded = json.loads(path.read_text(encoding="utf-8"))
36
+ if loaded.get("format") != FORMAT:
37
+ raise ValueError(f"{path}: unsupported vault format {loaded.get('format')}")
38
+ self.data.update(loaded)
39
+
40
+ @property
41
+ def exists(self) -> bool:
42
+ return self.path.exists()
43
+
44
+ @property
45
+ def words(self) -> dict[str, str]:
46
+ return self.data["words"]
47
+
48
+ @property
49
+ def dirs(self) -> dict[str, str]:
50
+ return self.data["dirs"]
51
+
52
+ @property
53
+ def baseline(self) -> dict[str, dict]:
54
+ return self.data["baseline"]
55
+
56
+ def new_name(self, prefix: str, forbidden: set[str]) -> str:
57
+ counters = self.data["counters"]
58
+ used = set(self.words.values()) | set(self.dirs.values())
59
+ n = counters.get(prefix, 0)
60
+ while True:
61
+ n += 1
62
+ cand = f"{prefix}{n:04d}"
63
+ if cand not in forbidden and cand not in used:
64
+ counters[prefix] = n
65
+ return cand
66
+
67
+ def assign(self, word: str, kind: str, naming: str, forbidden: set[str]) -> str:
68
+ if word in self.words:
69
+ return self.words[word]
70
+ prefix = OPAQUE_PREFIX if naming == "opaque" and kind not in ("file", "dir", "data") else KIND_PREFIX[kind]
71
+ gen = self.new_name(prefix, forbidden)
72
+ self.words[word] = gen
73
+ self.data["kinds"][word] = kind
74
+ return gen
75
+
76
+ def assign_dir(self, name: str, forbidden: set[str]) -> str:
77
+ if name not in self.dirs:
78
+ self.dirs[name] = self.new_name(KIND_PREFIX["dir"], forbidden)
79
+ return self.dirs[name]
80
+
81
+ def save(self) -> None:
82
+ self.path.parent.mkdir(parents=True, exist_ok=True)
83
+ tmp = self.path.with_suffix(".tmp")
84
+ tmp.write_text(json.dumps(self.data, indent=1, sort_keys=True) + "\n", encoding="utf-8")
85
+ os.replace(tmp, self.path)
doppelcode/withhold.py ADDED
@@ -0,0 +1,151 @@
1
+ """Withheld functions: the AI sees a function's signature, not its body.
2
+
3
+ Chosen in ``.doppel/config.json`` (or the desktop app's outline):
4
+
5
+ "core_functions": ["dsp/filter.c::design_lowpass", "detector.py::Detector.classify", "detector.py::Detector"]
6
+ "core_modules": ["dsp/", "secret_algo.py"] # every function of these files / folders
7
+
8
+ In the twin each body becomes a stub with an id (``B_0001``); the vault keeps the real body, and
9
+ ``import`` puts it back byte for byte. Calls still work (the twin keeps the signature), and the
10
+ twin still parses (Python) / compiles to objects (C, C++). An AI edit of a stub is a change request:
11
+ the file is not merged until it is accepted (``--accept B_0001``).
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import re
17
+
18
+ from . import ledger
19
+
20
+ PREFIX = "B_"
21
+ LANGS = ("python", "c", "cpp")
22
+ # Python: fails loudly where it is called, not later with a None.
23
+ PY_STUB = 'raise NotImplementedError("doppel: body withheld ({id})")'
24
+ # C / C++: a non-void function returns a zero value, so the twin builds with -Werror=return-type.
25
+ C_STUB = "{{ /* doppel: body withheld ({id}) */{ret} }}"
26
+ STUB_RE = re.compile(
27
+ r'raise NotImplementedError\("(?:doppel|cobf): body withheld \((B_\d{4,})\)"\)'
28
+ r"|\.\.\. # cobf: body withheld \((B_\d{4,})\)" # cobf 0.5.0 twins
29
+ r"|\{ /\* (?:doppel|cobf): body withheld \((B_\d{4,})\) \*/(?: (?:return|throw)\b[^;]*;)? \}")
30
+
31
+ _NOT_TYPE = re.compile(r"\b(?:static|extern|inline|__inline|__inline__|__forceinline|_Noreturn|virtual|explicit|"
32
+ r"constexpr|consteval|friend|register|__declspec\s*\([^)]*\)|"
33
+ r"__attribute__\s*\(\(.*?\)\))\s*|\[\[.*?\]\]\s*|template\s*<[^{};]*?>\s*")
34
+
35
+
36
+ def _id(m: re.Match) -> str:
37
+ return next(g for g in m.groups() if g)
38
+
39
+
40
+ def return_type(src: str, body_start: int, symbol: str) -> str | None:
41
+ """C / C++ return type written before the function name ('' for constructors / destructors,
42
+ None when it cannot be read, e.g. a function returning a function pointer)."""
43
+ name = re.split(r"[.:]", symbol.split("#")[0])[-1]
44
+ head = src[:body_start]
45
+ hits = list(re.finditer(r"(?<![\w~])%s\s*\(" % re.escape(name), head))
46
+ if not hits:
47
+ return None
48
+ before = head[:hits[-1].start()]
49
+ cut = max([before.rfind(c) + len(c) for c in (";", "}", "{", "*/") if c in before] + [0])
50
+ lines = [ln.split("//")[0] for ln in before[cut:].splitlines() if not ln.strip().startswith("#")]
51
+ text = _NOT_TYPE.sub("", " ".join(lines))
52
+ text = re.sub(r"(?:\w+\s*(?:<[^<>]*>)?\s*::\s*)+$", "", text.strip()) # Class:: / ns:: before the name
53
+ text = " ".join(text.split())
54
+ if "(" in text or "[" in text or text.endswith("~"):
55
+ return None if "(" in text or "[" in text else ""
56
+ return text
57
+
58
+
59
+ _RET_TYPE_RE = re.compile(r"(\*/ return \()([^;]*)(\)\{0\}; \}$)")
60
+
61
+
62
+ def translate_stub(text: str, word) -> str:
63
+ """Rename the identifiers of a C stub's return type with the twin's names (word: name -> twin name)."""
64
+ return _RET_TYPE_RE.sub(lambda m: m.group(1) + re.sub(r"[A-Za-z_]\w*", lambda w: word(w.group(0)),
65
+ m.group(2)) + m.group(3), text)
66
+
67
+
68
+ def stub(lang: str, bid: str, ret_type: str | None = "void") -> str:
69
+ if lang == "python":
70
+ return PY_STUB.format(id=bid)
71
+ t = ret_type
72
+ if t is None or t in ("", "void") or re.fullmatch(r"(?:const\s+)?void", t or ""):
73
+ ret = "" # void, constructor, destructor, unknown
74
+ elif lang == "cpp":
75
+ ret = " throw 0;" if "&" in t or t in ("auto", "decltype(auto)") else " return {};"
76
+ else:
77
+ ret = f" return ({t}){{0}};" # C99 compound literal: scalars, pointers, structs
78
+ return C_STUB.format(id=bid, ret=ret)
79
+
80
+
81
+ def chosen(rel: str, symbol: str, cfg: dict) -> bool:
82
+ """Is this function withheld by the config? ``rel::Class`` withholds every method of the class."""
83
+ for m in cfg.get("core_modules", []):
84
+ m = m.replace("\\", "/")
85
+ if rel == m or (m.endswith("/") and rel.startswith(m)) or rel.startswith(m.rstrip("/") + "/"):
86
+ return True
87
+ base = symbol.split("#")[0]
88
+ for entry in cfg.get("core_functions", []):
89
+ f, sep, sym = entry.partition("::")
90
+ if sep and f.replace("\\", "/") == rel and (sym == symbol or sym == base or base.startswith(sym + ".")):
91
+ return True
92
+ return False
93
+
94
+
95
+ def active(cfg: dict) -> bool:
96
+ return bool(cfg.get("core_modules") or cfg.get("core_functions"))
97
+
98
+
99
+ class Plan:
100
+ """The withheld functions of one export: file -> {body start: (body end, stub)}."""
101
+
102
+ def __init__(self, vault):
103
+ self.vault = vault
104
+ self.store: dict[str, dict] = vault.data.setdefault("withheld", {})
105
+ self.ids: dict[str, str] = vault.data.setdefault("withheld_ids", {})
106
+ self.files: dict[str, dict[int, tuple[int, str]]] = {}
107
+ self.symbols: dict[str, set[str]] = {}
108
+ # released for the next export only (`doppel withhold release B_0001`): the body goes to the twin
109
+ self.released: set[str] = set(vault.data.get("withheld_release", []))
110
+
111
+ @property
112
+ def count(self) -> int:
113
+ return sum(len(v) for v in self.files.values())
114
+
115
+ def add(self, rel: str, src: str, lang: str, cfg: dict) -> None:
116
+ if lang not in LANGS:
117
+ return
118
+ spans: list[tuple[int, int, str]] = []
119
+ for fn in ledger.functions(src, lang):
120
+ if fn.body_start < 0 or not chosen(rel, fn.symbol, cfg) or f"{rel}::{fn.symbol}" in self.released:
121
+ continue
122
+ if any(a <= fn.body_start and fn.body_end <= b for a, b, _, _ in spans):
123
+ continue # nested in a function already withheld
124
+ if lang == "python": # a trailing "# comment" belongs to the body
125
+ eol = src.find("\n", fn.body_end)
126
+ eol = len(src) if eol < 0 else eol
127
+ if src[fn.body_end:eol].strip().startswith("#"):
128
+ fn.body_end = len(src[:eol].rstrip("\r"))
129
+ key = f"{rel}::{fn.symbol}"
130
+ bid = self.ids.get(key)
131
+ if bid is None:
132
+ bid = self.vault.new_name(PREFIX, set())
133
+ self.ids[key] = bid
134
+ self.store[bid] = {"file": rel, "symbol": fn.symbol, "body": src[fn.body_start:fn.body_end]}
135
+ ret = None if lang == "python" else return_type(src, fn.body_start, fn.symbol)
136
+ spans.append((fn.body_start, fn.body_end, bid, ret))
137
+ if spans:
138
+ self.files[rel] = {a: (b, stub(lang, bid, ret)) for a, b, bid, ret in spans}
139
+ self.symbols[rel] = {self.store[bid]["symbol"] for _, _, bid, _ in spans}
140
+
141
+
142
+ def restore(text: str, store: dict[str, dict]) -> str:
143
+ """Put the real bodies back where the stubs are."""
144
+ def back(m: re.Match) -> str:
145
+ bid = _id(m)
146
+ return store[bid]["body"] if bid in store else m.group(0)
147
+ return STUB_RE.sub(back, text)
148
+
149
+
150
+ def stub_ids(text: str) -> set[str]:
151
+ return {_id(m) for m in STUB_RE.finditer(text)}
@@ -0,0 +1,418 @@
1
+ Metadata-Version: 2.4
2
+ Name: doppelcode
3
+ Version: 0.7.0b5.post1
4
+ Summary: A private twin of your code for AI agents: the AI works on the twin, its edits merge back into the original
5
+ Author-email: DoppelCode <doppelcode.license@gmail.com>
6
+ License-Expression: PolyForm-Noncommercial-1.0.0
7
+ Project-URL: Homepage, https://github.com/doppelcode/doppelcode
8
+ Project-URL: Source, https://github.com/doppelcode/doppelcode
9
+ Project-URL: Issues, https://github.com/doppelcode/doppelcode/issues
10
+ Classifier: Development Status :: 4 - Beta
11
+ Classifier: Environment :: Console
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Operating System :: Microsoft :: Windows
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.11
17
+ Classifier: Programming Language :: Python :: 3.12
18
+ Classifier: Programming Language :: Python :: 3.13
19
+ Classifier: Programming Language :: Python :: 3.14
20
+ Classifier: Topic :: Software Development
21
+ Requires-Python: >=3.11
22
+ Description-Content-Type: text/markdown
23
+ License-File: LICENSE
24
+ Dynamic: license-file
25
+
26
+ # DoppelCode - a private twin of your code for AI agents
27
+
28
+ **Version:** 0.7.0b5.post1 (public beta)
29
+ **Date:** 2026-11-30
30
+
31
+ DoppelCode lets you use AI coding agents on proprietary code while reducing what an AI sees of your code. It
32
+ writes a **twin** of your project: the same code with your names, file names, comments and strings replaced
33
+ by placeholders, optionally with your tuned constants hidden and your core function bodies left out. The AI
34
+ works only on the twin. `doppel import` merges its edits back into your original with the real names, and
35
+ DoppelCode records what was sent to the AI, so you can show later which parts of your code an AI was given.
36
+
37
+ Python 3.11+, no third-party packages. Optional: gcc/g++ or clang (header harvesting, compile check), git
38
+ (3-way merge).
39
+
40
+ ## Quick Start (5 minutes)
41
+
42
+ ```
43
+ pip install doppelcode # installs the doppel command (or: python -m doppelcode ...)
44
+ pip install . # or: install from source, in a clone of this repo
45
+ doppel init path/to/project # optional: writes .doppel/config.json with the defaults
46
+ doppel export path/to/project --out path/to/twin # writes the twin
47
+ ```
48
+
49
+ 1. Open **the twin folder, not the original**, in your agent (Claude Code, GitHub Copilot agent, Cursor,
50
+ or paste it into a chat). The twin has an `AGENTS.md` / `CLAUDE.md` that tells the agent the rules.
51
+ 2. Let the agent work in the twin as usual.
52
+ 3. `doppel import path/to/project` merges the agent's changes into your original, with your names.
53
+ 4. `doppel check path/to/project` verifies the round trip, scans the twin for leaks and compiles both
54
+ versions (C / C++ machine code is compared; Python syntax trees are compared).
55
+ 5. `doppel report path/to/project` shows which function bodies were made available to an AI, and when.
56
+
57
+ ## Protection Levels
58
+
59
+ | Level | What the AI sees | Config |
60
+ |---|---|---|
61
+ | Names only | your code with names, file names, comments and strings replaced | default (`comments` / `strings`: `scrub` or `hide`) |
62
+ | + secret constants | tuned values and tables replaced by `K_` aliases with dummy values | `secret_symbols`, `secret_values`, `secret_files` |
63
+ | + withheld functions | the signature only; the body stays on your PC | `core_functions`, `core_modules` |
64
+
65
+ Pilot results (DeepSeek, DeepThink on; two small projects, one in C and one in Python; one chat per project
66
+ and condition). The attack question asked for every value and whether the core functions could be rebuilt:
67
+
68
+ | Round | Protection | Values recovered | "Can rebuild the core functions" | Tasks done automatically |
69
+ |---|---|---|---|---|
70
+ | 2 | Names only | all, in both projects | yes | 6 of 6 |
71
+ | 2 | + secrets + withheld | 4 of 16 tones, 3 of 4 symbols (from test code); one unmarked pair | no | 4 of 6 (the 2 others were changes inside withheld bodies, done by the owner) |
72
+ | 4 | + secrets + withheld (after the round 2 fixes) | none | no | 3 of 6, 1 partly right, 2 change requests in plain words |
73
+
74
+ These are small pilots with one model; they show the direction, not a guarantee.
75
+
76
+ ## Languages
77
+
78
+ | Language | Files | What is renamed | Library names kept by | Verified by `check` |
79
+ |---|---|---|---|---|
80
+ | C | `.c .h` | every identifier | system headers the code includes | compile + machine code |
81
+ | C++ | `.cpp .cc .cxx .hpp .hh ...` | every identifier | system / STL headers (via g++) | compile + machine code |
82
+ | Python | `.py .pyw .pyi` | names the project declares | public names of imported modules (read, never run), builtins | syntax trees |
83
+ | C# | `.cs` | names the project declares | keyword / BCL lists, member rule | compile (csc) |
84
+ | Java | `.java` | names the project declares | keyword / JDK lists, member rule | compile (javac) |
85
+ | JavaScript / TypeScript | `.js .mjs .jsx .ts .tsx` | names the project declares | keyword / runtime lists, member rule | compile, syntax only (Node) |
86
+
87
+ For the "declared" languages, a name is kept when it is used as a member of something the project
88
+ does not declare (`os.path`, `sb.Append`, `crypto.createHash`), when it is imported from an outside
89
+ module, when it is a keyword argument to a library call (`json.dumps(indent=2)`), or when it is a
90
+ method of a class derived from a library class (unittest `setUp`, `Thread.run`). Python packages
91
+ (folders with `__init__.py`) are renamed together with their imports; Java files take their public
92
+ class's new name. Code inside `f"{x}"`, `$"{x}"` and `` `${x}` `` is always translated, strings that
93
+ name code (`getattr(o, "x")`, `__all__`, `obj["x"]`, reflection) are renamed with it, and module
94
+ names (`require("crypto")`, `import ... from "lib"`) are never hidden.
95
+
96
+ Machine code is compared against a names-only version of the twin (strings and comments untouched),
97
+ so the comparison proves that renaming changed no code whatever the string policy. With strings set
98
+ to `keep`, a Python twin prints exactly what the original prints.
99
+
100
+ `check` also builds Java, C# and JS / TS. The original is built first; if it does not build with the
101
+ tool found, its files are listed as NOT CHECKED with the reason, so only errors the twin alone has
102
+ count. The twin's code is never run (javac without annotation processors, csc without analyzers,
103
+ JS / TS only compiled). Tools are found automatically and can be set in `.doppel/config.json`:
104
+
105
+ | Key | Default search |
106
+ |---|---|
107
+ | `javac` | PATH, `JAVA_HOME`, `~/.jdks`, Program Files JDKs, Android Studio's `jbr` |
108
+ | `csc` | Visual Studio Roslyn, .NET SDK, then the .NET Framework `csc` (C# 5 only: install the .NET SDK for newer C#) |
109
+ | `node` | PATH, Program Files, then VS Code's built-in Node (TypeScript types are stripped by Node) |
110
+
111
+ With strings set to `keep`, file and folder names inside path strings (`require("./falconRadio")`,
112
+ `fopen("rec_01.dat")`) are still renamed, so the twin finds its renamed modules and data files.
113
+
114
+ ## Desktop app
115
+
116
+ A desktop app is planned for a later release. This beta is the `doppel` command line; everything below
117
+ works with it.
118
+
119
+ ## Workflow
120
+
121
+ ```
122
+ python -m doppelcode init <project> # optional: write .doppel/config.json to tune policies
123
+ python -m doppelcode export <project> [--out DIR] # create/refresh the twin (default <parent>/obf_<hash>)
124
+ ... point the AI agent at the twin folder, let it edit ...
125
+ python -m doppelcode import <project> # merge the AI's changes into the original
126
+ python -m doppelcode check <project> --objects # round trip, leak scan, compile + machine-code compare
127
+ python -m doppelcode lookup <project> fn_0005 # translate a name either way
128
+ ```
129
+
130
+ `import` performs a 3-way merge per file: the AI's changes are applied even if you edited the
131
+ original in the meantime. Only overlapping edits produce `<file>.doppel-merge` (with conflict
132
+ markers; the original is left untouched). `export` refuses to run until those are resolved.
133
+
134
+ ### Review before applying (`--preview`)
135
+
136
+ ```
137
+ python -m doppelcode import <project> --preview DIR # see what import would write
138
+ python -m doppelcode import <project> --from-preview DIR # apply all of it
139
+ python -m doppelcode import <project> --from-preview DIR --only src/a.c # or one file
140
+ ```
141
+
142
+ `--preview DIR` runs the whole import, 3-way merge included, but writes the result to `DIR` at the same
143
+ relative paths (a conflict as `<file>.doppel-merge`) and prints the list of files. Nothing in the project,
144
+ the twin, the vault or `.doppel/config.json` changes. `DIR` must be outside the project and the twin, and
145
+ empty or an earlier preview (which is replaced). `DIR/.doppel-preview.json` records, per file, the twin
146
+ file and the original as they were.
147
+
148
+ `--from-preview DIR` applies exactly what was previewed, with the preview's `--rename` / `--accept`. It
149
+ refuses, and writes nothing, when a twin file or an original changed since the preview: preview again.
150
+ Applied files leave the manifest, so the rest can be applied later. The VS Code extension uses this for
151
+ its review view.
152
+
153
+ ### Files that are not UTF-8, and line ends
154
+
155
+ DoppelCode keeps every file's bytes: a Windows-1255 or Windows-1252 file goes into the twin in its own
156
+ encoding (with `comments: hide` its comments do not go at all) and comes back the same, except the lines the
157
+ AI changed. An AI agent's editor often saves such a twin file as UTF-8 (replacement characters, or the code
158
+ page decoded). Import gives every line whose only change is that re-encoding its original bytes back, and
159
+ writes the lines the AI did change in the file's code page when it can tell which one it is (`encoding:` in
160
+ the output). Line ends do not take part in the merge: the AI adding LF lines to a CRLF file, or your editor
161
+ saving the file again with one style, is not a change; changed lines take the original's style.
162
+
163
+ ### Names the AI coins in DoppelCode's style
164
+
165
+ AI models often name new things like the placeholders they see (`v_0048`, `fn_0017`, `"str_0013"`).
166
+ Mapped back blindly, a new parameter `v_0048` would become an unrelated existing name
167
+ (`fips_expected`), and a new string `"str_0013"` would become an existing text (`"ALL PASS"`).
168
+ On the lines the AI added or changed, `import` therefore flags:
169
+
170
+ - a known alias in a declaration position (function, parameter, local, field, type, macro) that
171
+ the old version of the file did not declare;
172
+ - an alias-shaped name that is not in the vault (`fn_0017`);
173
+ - a string literal that is exactly `"str_NNNN"` and was not in the old version of the file.
174
+
175
+ Plain uses of existing names map silently. Flagged files are **not merged**; the findings go to
176
+ the console and to `.doppel/import_review.txt`. Resolve them and import again:
177
+
178
+ ```
179
+ python -m doppelcode import <project> --rename v_0048=nonce --rename fn_0017=falcon_ctr_crypt
180
+ python -m doppelcode import <project> --rename "str_0013=Decrypt failed"
181
+ python -m doppelcode import <project> --accept v_0017 # keep as written (known alias: its vault meaning)
182
+ python -m doppelcode import <project> --accept # accept every finding
183
+ ```
184
+
185
+ A renamed name gets its own alias in the vault and the twin file is rewritten with it, so twin,
186
+ vault and original agree from then on.
187
+
188
+ `export` also writes `AGENTS.md` and `CLAUDE.md` into the twin root (unless the project has its
189
+ own) asking the agent to give new things plain names; `import` ignores both files.
190
+
191
+ ## Example (samples/aes_project)
192
+
193
+ ```c
194
+ /* original */ /* twin */
195
+ void falcon_encrypt_block( void fn_0002(
196
+ const FalconAesContext *ctx, const T_0001 *v_0006,
197
+ uint8_t block[FALCON_BLOCK_SIZE]); uint8_t v_0008[M_0002]);
198
+ #include "falcon_aes.h" #include "mod_0001.h"
199
+ ```
200
+
201
+ ## Secret constants
202
+
203
+ Renaming hides names, but in DSP or classifier code the numbers are often the real know-how:
204
+ thresholds, coefficients, tuning tables. Marked numbers are replaced in the twin by aliases
205
+ `K_0001`, `K_0002`, ...; the vault keeps the real values and `import` puts them back.
206
+
207
+ | Way to mark | Example | Hides |
208
+ |---|---|---|
209
+ | Line tag | `x = 145 # doppel:secret` | every number on that line, or a table starting there as a whole |
210
+ | `secret_symbols` | `["male_threshold", "lpc_order"]` | every number assigned to that name: assignments, `self.x = ...`, default values, keyword arguments (original names) |
211
+ | `secret_values` | `["0.97", "3.3"]` | every number with that value: an integer mark `"145"` hides every form (`145`, `145.0`, `0x91`, `1.45e2`); a float mark `"3.0"` hides `3.0`, `3.` and `3.0f` but not the integer `3`. Also inside strings and comments (even with `keep`) and in f-string code (`f"{0.97 * x:.2f}"`); format specifications such as `"%.2f"` and the `.2f` of `{x:.2f}` are never touched, JSON / dict text (`{"gain": 0.97}`) is not a format spec |
212
+ | `secret_files` / `secret_functions` | `["dsp/"]` / `["src/f.c::gate"]` | every `secrets suggest` candidate in these files / functions (values and table names; in a function only inside it) |
213
+
214
+ ```
215
+ python -m doppelcode secrets suggest <project> [--all] [--top N] # ranked: tables, algorithm constants,
216
+ # thresholds, the rest (top 50 by default)
217
+ python -m doppelcode secrets list <project> [--show-values]
218
+ ```
219
+
220
+ - **A marked value is hidden everywhere** in the code (each place gets its own alias), and in
221
+ comments and strings too when they are `scrub`bed. `check` fails if the value is still visible
222
+ anywhere in the twin, also written as `0x91`, `1.45e2` or inside a string.
223
+ - `0`, `1`, `-1`, `2` and `0.5` are never hidden by value list (only at a tagged or named place),
224
+ and never count as leaks.
225
+ - **The twin still runs.** A twin-only file gives every alias a neutral dummy value, and each file
226
+ that uses one gets a marked line that `import` removes again:
227
+
228
+ | Language | Dummy file (twin root) | Line added to each file |
229
+ |---|---|---|
230
+ | Python | `doppel_secrets.py`: `K_0001 = 1.0`, tables `[0] * n` | `from doppel_secrets import K_... # DoppelCode` after the imports |
231
+ | C / C++ | `doppel_secrets.h`: `#define K_0001 (1.0f)`, tables `{0, 0, ...}` (same length) | `#include "../doppel_secrets.h" /* DoppelCode */` after the first include |
232
+
233
+ In C a table initializer is replaced as a whole (`static const uint8_t k_rcon[10] = K_0001;`,
234
+ the size kept), and `#define NAME 0x1b` works with `secret_symbols` too. The dummy file is
235
+ never imported; if the AI edits it, the import reports "secret value change requested" and
236
+ keeps the real value.
237
+ - `check` compiles / parses the dummy twin, and compares the original with the twin **with the
238
+ real values put back** (C: machine code, Python: syntax trees).
239
+ - If the AI replaces an alias by a literal (`K_0003` -> `3.5`), the file is not merged until you
240
+ decide: `--accept K_0003` takes 3.5, `--rename K_0003=@keep` keeps the secret,
241
+ `--rename K_0003=@secret` takes 3.5 and adds it to `secret_values`.
242
+ - The elements of a secret table are hidden wherever else they are written in the same form (a test
243
+ generator that hard-codes `400.0` from the tone table), and in comments and strings in any form
244
+ (`400Hz`). Small integers (-15..15) and powers of two stay visible: they are indexes, loop bounds,
245
+ sizes and bit masks. `doppel secrets suggest` lists the functions that write such values - consider
246
+ withholding them.
247
+ - Values computed from secrets (`145 * 2` written as `290`) are out of scope.
248
+
249
+ Supported for Python, C and C++.
250
+
251
+ With withheld functions or secret constants set, `strings` defaults to `hide` (banners and help
252
+ texts would still tell the purpose); set `"strings"` in `.doppel/config.json` to choose otherwise.
253
+ One-word mode strings passed straight to a library call (`filterwarnings("ignore")`,
254
+ `btype="band"`, `encode("utf-8")`) stay, so the twin still runs. Python dict keys are one class: in
255
+ `scrub` and `hide` every identifier-shaped key (`'pitch'`, `'f1'`, `'spectral_centroid'`) gets an
256
+ alias, so the keys do not list what a withheld function computes. Only keys of a library's dict stay
257
+ (`os.environ["PATH"]`, a dict literal handed to a library call); a key that merely matches a
258
+ library name (`'f2'`) is still aliased. A library dict is also followed through names
259
+ (`devs = sd.query_devices()`, `for d in devs`: `d['max_input_channels']` stays, in `hide` too).
260
+ In the text of a function that uses a secret table (its name, one of its values, or a table linked
261
+ by indexing such as `frequencies[target_sequence[i]]`), the table's small integers are hidden too
262
+ ("Symbol 10" -> "Symbol K_0012"); elsewhere small numbers stay. With protected code and
263
+ `"strings": "scrub"`, `check` prints a warning with an example string.
264
+
265
+ ## Withheld functions (optional)
266
+
267
+ Choose functions the AI may call but not read. In the twin their body becomes a stub; everything
268
+ else is obfuscated as before:
269
+
270
+ ```python
271
+ def fn_0004(self, v_0005):
272
+ raise NotImplementedError("doppel: body withheld (B_0001)")
273
+ ```
274
+ ```c
275
+ static void fn_0009(uint8_t v_0021[16])
276
+ { /* doppel: body withheld (B_0002) */ }
277
+
278
+ float fn_0002(const float* v_0014, int v_0015, double v_0016, double v_0017)
279
+ { /* doppel: body withheld (B_0003) */ return (float){0}; }
280
+ ```
281
+
282
+ A non-void C function returns a zero value (`return (T){0};`, C++ `return {};`), so the twin builds
283
+ with `-Werror=return-type`; a Python stub raises, so a twin-side test fails where the function is
284
+ called, not later with a `None`.
285
+
286
+ - **Choosing:** in `.doppel/config.json`:
287
+ `"core_functions": ["detector.py::Detector.classify", "src/filter.c::design_lowpass", "detector.py::Detector"]`
288
+ (a class withholds all its methods), `"core_modules": ["dsp/", "secret_algo.py"]` (whole files).
289
+ - **Import** puts the real bodies back byte for byte; edits elsewhere merge as usual. If the AI
290
+ changes or removes a withheld body, the file is not merged until you take its version with
291
+ `--accept B_0001`.
292
+ - **A change inside a withheld function:** the AI is told to describe it in plain words instead of
293
+ editing the stub, so you apply it yourself. Or release the body for one session:
294
+ `doppel withhold release PROJECT B_0001 --reason "widen the pitch range"`. The next export sends the body, the AI's edit merges as usual, and the
295
+ export after it withholds the function again. The release and the send are both in the exposure
296
+ ledger. `doppel withhold list PROJECT` shows the ids.
297
+ - **Purpose line (optional):** `doppel withhold purpose PROJECT B_0002 "returns (gender, confidence) for
298
+ one chunk"` (or right-click it in the outline) lists that line in the twin's `AGENTS.md`, so the AI
299
+ calls the right withheld function. Off unless you write one; it tells the AI the function's role,
300
+ not its body (names and secret values in it are translated). In pilot round 4 the AI called the
301
+ feature extractor where the gender decision was meant; both were withheld.
302
+ - **check:** the dummy twin still parses / compiles to objects; the machine-code comparison uses
303
+ the full-body copy, so it stays exact; Python syntax trees are compared without the withheld bodies.
304
+ - **Exposure:** withheld functions are logged as `declaration`, not `body`, so `doppel report` and the
305
+ budgets show the real share (e.g. 15 of 17 bodies, 88%).
306
+ - Python, C and C++ (Java and C# need typed stubs; later). The twin's `AGENTS.md` / `CLAUDE.md` tell
307
+ the agent not to implement or change withheld functions.
308
+
309
+ ## Exposure ledger
310
+
311
+ Every `export` records which function bodies it made available to an AI in
312
+ `.doppel/ledger.jsonl` (append-only, kept as an audit trail). A body is logged when it is new or
313
+ changed, or when it is sent again to a new twin folder (`"repeat": true`); a plain refresh adds
314
+ nothing.
315
+
316
+ ```
317
+ python -m doppelcode report <project> # per folder
318
+ python -m doppelcode report <project> --by function # first / last sent, how often
319
+ python -m doppelcode report <project> --since 2026-11-01
320
+
321
+ Exposure report - what was made available to an AI (not what it read)
322
+ folder functions bodies sent share secrets withheld
323
+ src/ 17 17 100% 6
324
+ ```
325
+
326
+ **Budgets:** `"exposure_budget": {"dsp/": 0.3}` stops an export that would make more than that share
327
+ of a folder's function bodies available; `export --allow-over-budget` exports anyway and records
328
+ the override in the ledger. With today's full twin every exported folder is at 100%, so a budget
329
+ acts as a guard ("never export dsp/") until declarations-only export (core modules) exists.
330
+
331
+ ## Key config options (`.doppel/config.json`)
332
+
333
+ | Key | Default | Meaning |
334
+ |---|---|---|
335
+ | `keep`, `keep_prefixes`, `keep_regex` | `[]` | names never renamed (e.g. vendor `HAL_`) |
336
+ | `exclude` | `[]` | third-party folders: copied verbatim, their names kept |
337
+ | `comments` | `scrub` | `scrub` replaces mapped names inside comments, `keep` leaves them, `hide` replaces each whole comment by a placeholder in the file's own syntax (`/* cmt_0007 */`, `// cmt_0007`, `# cmt_0007` in Python, Makefiles and CMake files; same line count) that `import` restores. Set it with `export --comments hide` |
338
+ | `strings` | `scrub` | `scrub` replaces mapped names inside strings, `keep` leaves them, `hide` replaces each string literal by an id and keeps its format skeleton (`"Sample rate: %d Hz\n"` -> `"str_0002 %d\n"`), restored on `import` (also around the AI's edits). `check --objects` compares machine code against a names-only twin, so it works with every string setting. Set it with `export --strings hide` |
339
+ | `data_files` | `none` | `build`: text files that build files name (generated docs, symbol lists) are copied, so the project's own build works; with `none` they are listed in `.doppel/build_inputs.txt` and export prints a note. `copy`: also the data files the code reads, under their aliases. File and folder names in strings always get file-shaped aliases when strings are `scrub`/`hide` (`"InputFiles//"` -> `"dir_0001//"`, `"rec_01.dat"` -> `"file_0001.dat"`); with `copy`, every file in a folder the code names (or named itself) goes to the twin, so the twin program still finds its inputs. Import ignores these folders (no data or program output comes back). Set it with `export --data copy` |
340
+ | `rename_files` | `true` (not set: `false` with a CMake build or build files that compute paths) | rename file names; `false` keeps file and folder names (and CMake target names), so the project's own build finds them |
341
+ | `keep_test_names` | `true` | in a pytest project, keep `test_*` / `Test*` names, `pytest_*` hooks and pytest's fixture names so the twin's tests run (the names are visible); `false` hides them |
342
+ | `rename_words` | `[]` | extra words to rename everywhere |
343
+ | `build_names` | `keep` | `rename`: in Makefiles / CMake files, words made of the project's name parts (`TARGET := falcon_selftest`) get `w_` aliases, so the build produces a renamed binary. With `keep`, `check` reports them as leaks. Set it with `export --build-names rename` |
344
+ | `sensitive_terms` | `[]` | substrings that `check` reports if still present in the twin |
345
+ | `naming` | `kind` | `kind` (fn_/v_/T_/M_) or `opaque` (id_ for all) |
346
+
347
+ Files that are not source, build or known text files are **not copied** to the twin (they may leak); add
348
+ them to `copy_verbatim` if the AI needs them. Build templates, packaging files, scripts (`.sh`, `.pl`,
349
+ `#!` files without an extension) and text files a build file names are copied; scripts are never
350
+ imported as new files, and changes to existing ones are listed for review.
351
+
352
+ ## Security
353
+
354
+ The twin is written by an AI agent, so DoppelCode treats it as untrusted:
355
+
356
+ - **Import** accepts new files only if they are C sources or known text files outside hidden folders.
357
+ Scripts (`.bat`, `.ps1`, `.sh`), binaries, Windows device names and anything under `.github`,
358
+ `.vscode`, `.git` and similar are reported as `BLOCKED` and never written. Changed build and
359
+ config files (Makefile, `*.mk`, `*.json`, ...) are listed under *Review before building*.
360
+ - **Links**: symlinks and junctions inside the twin are never followed (reported as `IGNORED (link)`),
361
+ and `export` refuses to write or delete through them. `export` also refuses to take over a
362
+ non-empty folder it did not create (`--force` to override).
363
+ - **Compile check**: if a twin file includes something outside the twin (absolute, `..` or UNC
364
+ `\\host\share` paths, which would make Windows connect to that host), the compiler is not run.
365
+ - **Leak scan** also reports absolute paths, the project folder name and the Windows user name (as
366
+ a path segment, an e-mail or a handle only, so a user `root` does not flag "rooted"). Absolute
367
+ paths in build and text files (toolchain folders, the source checkout) become `$(DOPPEL_PATH_0001)` in
368
+ the twin and come back on import. Prose that spells a renamed name out ("read audio file" for
369
+ `read_audio_file`) is listed under `hints:`; it does not fail the check (`hide` removes it).
370
+ - **Large projects:** `check` prints a leak summary (counts by kind, the top files, 30 examples, secret
371
+ values and absolute paths first) and writes the full list to `.doppel/leaks.txt` (`--leaks-all` prints
372
+ it). `"leak_allow": ["opus"]` accepts words such as a public project name; secret values and
373
+ absolute paths are always reported. Build and CLI words (cmake, version, option, enable, ...) are not
374
+ name parts. Headers and modules export could not find are counted and listed in `.doppel/missing.txt`.
375
+ - **Includes:** the compile check refuses a twin whose `#include` is absolute, a drive or UNC path, or
376
+ goes above the twin root; `#include "../x.h"` that stays inside the twin is compiled.
377
+ - **Import** warns when a new function reuses an existing alias for its own variable (it would come
378
+ back as the old meaning); keywords and builtins are not listed as new names. With `comments: hide`,
379
+ placeholder comments (`// cmt_0040`) the AI left out when it returned whole functions are put back
380
+ next to the code they belong to; a comment that went together with deleted code stays deleted.
381
+ - IDE and tool state (`.vs`, `.settings`, `*.user`, workspace and `c_cpp_properties.json` files) is
382
+ never copied, because it holds absolute paths and user names.
383
+ - `.doppel/vault.json` holds the real names and the hidden comments and strings in plain text, like the
384
+ project's own sources next to it, so it needs the same care. Keep the project folder private.
385
+ - The compile check uses the compiler's default C dialect (`compile_flags: []`); set the flags of
386
+ your real build if needed. Files it cannot verify are listed as `NOT CHECKED` with the reason.
387
+
388
+ ## Limitations
389
+
390
+ - **A twin builds and compiles like the original, but it does not always behave the same.** With
391
+ `strings: scrub`, names inside data strings (command-line option tables, registry keys) may be replaced;
392
+ with `strings: hide`, the program's text output changes. On librosa (pilot, 0.6.4) the original passed
393
+ 1,957 tests; the twin passed 1,835 (74 failed, 48 errors) with `scrub` and 1,351 (558 failed, 48 errors)
394
+ with `hide`. Run your tests on the original after `doppel import`; do not trust failing tests in the twin.
395
+ - DoppelCode reduces what an AI sees; it does not make code unreadable. Function signatures, call structure, control
396
+ flow and well-known algorithms stay visible in the twin, and a capable model can often tell what a program
397
+ does.
398
+ - Values are hidden only if you mark them (`secret_*`); `doppel secrets suggest` proposes candidates.
399
+ - A withheld function cannot be edited by the AI: it describes the change in plain words and you apply it, or
400
+ you release the body for one session (`doppel withhold release`), which is recorded.
401
+ - A CMake regex that finds several macros by a shared prefix (curl: `"#define LIBCURL_VERSION( |_NUM )"`)
402
+ cannot find them once they are renamed: add those macros to `keep`.
403
+ - With a CMake build (or build files that compute file paths), DoppelCode keeps file and folder names unless the
404
+ config sets `"rename_files": true`, so the twin builds with the project's own build; file names are then
405
+ visible.
406
+ - In a pytest project, test names (`test_*`, `Test*`), `pytest_*` hooks and pytest's fixture names are kept so
407
+ the twin's tests run; they are visible to the AI. `"keep_test_names": false` hides them.
408
+ - Leak scans and pilot results reduce risk; they are not a proof that nothing leaks. Review `check` output.
409
+
410
+ ## Tests
411
+
412
+ ```
413
+ python -m unittest discover -s tests
414
+ ```
415
+
416
+ ## License
417
+
418
+ DoppelCode is free for personal use, education, research and other noncommercial purposes under the [PolyForm Noncommercial License 1.0.0](LICENSE). Any commercial use, including use by or for a company, requires a paid commercial license: see [COMMERCIAL.md](COMMERCIAL.md).