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/project.py ADDED
@@ -0,0 +1,2343 @@
1
+ """Project-level operations: export (create twin), import (sync back), check."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ast
6
+ import getpass
7
+ import hashlib
8
+ import json
9
+ import os
10
+ import re
11
+ import shutil
12
+ import subprocess
13
+ import tempfile
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+
17
+ from . import pyparse
18
+ from . import (aliascheck, analyze, commentkeep, declare, encodingfix, headers, languages, ledger, lexer, merge, pyharvest, secretconst,
19
+ strhide, toolchains, withhold)
20
+ from .languages import LANGUAGES, is_code
21
+ from .config import LEGACY_STATE_DIR, PROTECTION_KEYS, STATE_DIR, load_config, state_dir_name, path_matches, set_config_value, user_config
22
+ from .keepset import ALWAYS_KEEP, is_reserved
23
+ from .translate import (COMMENT_PREFIX, STRING_ID_RE, STRING_PREFIX, WORD_RE, Translator, build_language_words,
24
+ name_parts, word_parts)
25
+
26
+ CODE_KINDS = ("func", "type", "var", "macro")
27
+
28
+ # Written into the twin root for AI agents (Claude Code reads CLAUDE.md, most others AGENTS.md).
29
+ AGENT_NOTE_FILES = ("AGENTS.md", "CLAUDE.md")
30
+ AGENT_NOTES = """# Notes for AI agents
31
+
32
+ Names like `fn_0012`, `v_0034`, `T_0003`, `M_0002` and strings like `"str_0005"` in this project are
33
+ placeholders that stand for existing things. Use them as they are when you refer to those things.
34
+
35
+ **When you add something new** - a function, parameter, variable, field, type, macro, string or
36
+ comment - give it a plain descriptive name in words, for example `nonce`, `block_count`,
37
+ `ctr_crypt`, `"Decrypt failed"`. Never invent a new name in the placeholder style (`fn_0017`,
38
+ `v_0048`, `"str_0013"`) and never reuse an existing placeholder for something new: those names
39
+ already mean other things.
40
+
41
+ Do not edit this file.
42
+ """
43
+ WITHHELD_NOTE = """
44
+ Functions whose body is `raise NotImplementedError("doppel: body withheld (B_NNNN)")` (Python) or
45
+ `{ /* doppel: body withheld (B_NNNN) */ ... }` (C / C++) are implemented on the owner's PC. Call them
46
+ as their signature says, but do not implement, change or remove them. If a task needs a change
47
+ inside one, do not edit the stub: describe the change in plain words for the owner (which B_NNNN,
48
+ what should change and why).
49
+ """
50
+ SECRET_NOTE = """
51
+ Names `K_NNNN` are secret constants. Their values are hidden on purpose; do not edit `doppel_secrets.*`
52
+ and do not guess the values. Ask if a task depends on a value.
53
+ """
54
+ from .vault import Vault
55
+
56
+ C_MODE, TEXT_MODE, VERBATIM_MODE = "c", "text", "verbatim"
57
+
58
+
59
+ class DoppelError(Exception):
60
+ pass
61
+
62
+
63
+ CobfError = DoppelError # the name before the rename (one version)
64
+
65
+
66
+ def sha(data: bytes) -> str:
67
+ return hashlib.sha256(data).hexdigest()
68
+
69
+
70
+ def decode(data: bytes) -> str:
71
+ return data.decode("utf-8", errors="surrogateescape")
72
+
73
+
74
+ def encode(text: str) -> bytes:
75
+ return text.encode("utf-8", errors="surrogateescape")
76
+
77
+
78
+ @dataclass
79
+ class SourceFile:
80
+ rel: str
81
+ mode: str
82
+ data: bytes
83
+ excluded: bool = False # third-party: verbatim, identifiers kept
84
+
85
+
86
+ @dataclass
87
+ class ExportReport:
88
+ twin: Path
89
+ files: list[tuple[str, str]] = field(default_factory=list) # (orig_rel, twin_rel)
90
+ skipped: list[str] = field(default_factory=list)
91
+ renamed: int = 0
92
+ new_names: int = 0
93
+ unresolved_headers: set[str] = field(default_factory=set)
94
+ compiler: str | None = None
95
+ data_files: int = 0
96
+ data_dirs: list[str] = field(default_factory=list)
97
+ languages: dict[str, int] = field(default_factory=dict) # language title -> number of files
98
+ unresolved_modules: set[str] = field(default_factory=set) # Python imports not found
99
+ missing_file: str = "" # both lists, one per line (.doppel/missing.txt)
100
+ agent_notes: list[str] = field(default_factory=list) # AGENTS.md / CLAUDE.md written into the twin
101
+ secrets: int = 0 # secret constant sites hidden (K_ aliases)
102
+ withheld: int = 0 # function bodies withheld (B_ stubs)
103
+ released: list[str] = field(default_factory=list) # withheld functions sent for this session
104
+ session: str = "" # ledger session of this export
105
+ bodies_logged: int = 0 # function bodies newly made available
106
+ over_budget: list[str] = field(default_factory=list) # folders exported over their budget
107
+
108
+
109
+ @dataclass
110
+ class ImportReport:
111
+ changed: list[str] = field(default_factory=list)
112
+ merged: list[str] = field(default_factory=list) # AI change merged with the user's own edits
113
+ new: list[str] = field(default_factory=list)
114
+ conflicts: list[str] = field(default_factory=list)
115
+ deleted: list[str] = field(default_factory=list)
116
+ removed: list[str] = field(default_factory=list)
117
+ new_identifiers: set[str] = field(default_factory=set)
118
+ blocked: list[str] = field(default_factory=list) # new files the AI created that are not imported
119
+ review: list[str] = field(default_factory=list) # build / config files changed: review before building
120
+ unsafe: list[str] = field(default_factory=list) # twin entries reached through a link (ignored)
121
+ alias_open: list[str] = field(default_factory=list) # findings that stop a file from merging
122
+ alias_resolved: list[str] = field(default_factory=list) # findings resolved by --rename / --accept
123
+ refused: list[str] = field(default_factory=list) # files not merged because of alias_open
124
+ twin_updated: list[str] = field(default_factory=list) # twin files rewritten with the new aliases
125
+ review_file: str | None = None # where the alias findings were written
126
+ secret_requests: list[str] = field(default_factory=list) # the AI edited doppel_secrets.* (ignored)
127
+ alias_warnings: list[str] = field(default_factory=list) # merged, but worth a look (alias reused)
128
+ comments_kept: list[str] = field(default_factory=list) # comments the AI dropped, put back
129
+ encoding_kept: list[str] = field(default_factory=list) # lines the AI's editor re-encoded, given back
130
+ preview_dir: str | None = None # import --preview: where the merged files are
131
+ preview_files: list[dict] = field(default_factory=list) # import --preview: one entry per written file
132
+
133
+
134
+ PREVIEW_MANIFEST = ".doppel-preview.json"
135
+
136
+
137
+ # Leak kinds, most serious first: secret values and absolute paths are always listed first and are never
138
+ # suppressed by "leak_allow".
139
+ LEAK_KINDS = ("secret value", "absolute path", "user name", "sensitive term", "renamed name", "name part",
140
+ "file name")
141
+
142
+
143
+ @dataclass
144
+ class CheckReport:
145
+ roundtrip_failures: list[str] = field(default_factory=list)
146
+ leaks: list[str] = field(default_factory=list)
147
+ hints: list[str] = field(default_factory=list) # names spelled out in prose: worth a look, not a failure
148
+ # (file, line, [(kind, text)]) of every leak line, most serious first (LEAK_KINDS order); line 0 = file name
149
+ leak_items: list[tuple[str, int, list[tuple[str, str]]]] = field(default_factory=list)
150
+ leaks_file: str = "" # the full list (.doppel/leaks.txt)
151
+ warnings: list[str] = field(default_factory=list) # setup advice (strings: scrub with protection on)
152
+ compile_errors: list[str] = field(default_factory=list)
153
+ compiled: int = 0
154
+ objects_compared: int = 0
155
+ objects_differ: list[str] = field(default_factory=list)
156
+ objects_skipped: str = "" # why the machine-code comparison was not done
157
+ compiler: str | None = None
158
+ unsafe_includes: list[str] = field(default_factory=list) # twin not compiled because of these
159
+ not_checked: list[str] = field(default_factory=list) # files the check could not verify, and why
160
+ python_checked: int = 0 # Python files compared as syntax trees
161
+ python_differ: list[str] = field(default_factory=list)
162
+ c_files: int = 0 # C / C++ files in the project
163
+ builds: list[str] = field(default_factory=list) # Java / C# / JS / TS: one summary line each
164
+
165
+ @property
166
+ def ok(self) -> bool:
167
+ return not (self.roundtrip_failures or self.leaks or self.compile_errors or self.objects_differ
168
+ or self.unsafe_includes or self.python_differ)
169
+
170
+
171
+ class Project:
172
+ def __init__(self, root: Path | str, twin: Path | str | None = None):
173
+ self.root = Path(root).resolve()
174
+ if not self.root.is_dir():
175
+ raise DoppelError(f"project folder not found: {self.root}")
176
+ self.cfg = load_config(self.root)
177
+ self.vault = Vault(self.root / state_dir_name(self.root) / "vault.json")
178
+ # a project made with cobf (the old name): its .cobf folder is used until it is renamed to .doppel
179
+ self.legacy_state = state_dir_name(self.root) == LEGACY_STATE_DIR
180
+ self._twin_override = Path(twin).resolve() if twin else None
181
+ self.auto_notes: list[str] = [] # defaults chosen from the project (printed by export)
182
+ self._auto_done = False
183
+
184
+ # -- locations -------------------------------------------------------
185
+ @property
186
+ def twin(self) -> Path:
187
+ if self._twin_override:
188
+ return self._twin_override
189
+ if self.vault.data.get("twin"):
190
+ return Path(self.vault.data["twin"])
191
+ if self.cfg["twin_dir"]:
192
+ p = Path(self.cfg["twin_dir"])
193
+ return (p if p.is_absolute() else self.root / p).resolve()
194
+ tag = hashlib.sha1(str(self.root).lower().encode()).hexdigest()[:6]
195
+ return self.root.parent / f"obf_{tag}"
196
+
197
+ # -- file discovery --------------------------------------------------
198
+ def _mode_for(self, rel: str) -> str | None:
199
+ name = rel.rsplit("/", 1)[-1]
200
+ ext = ("." + name.rsplit(".", 1)[-1].lower()) if "." in name else ""
201
+ lang = languages.for_path(rel, self.cfg["c_extensions"])
202
+ if lang:
203
+ return lang # "c", "cpp", "csharp", "java", "javascript", "typescript", "python"
204
+ if name.lower().endswith((".h.in", ".h.cmake.in", ".h.cmake", ".hpp.in", ".hh.in")):
205
+ return "c" # config.h.cmake.in: a C header template (#cmakedefine, @VAR@)
206
+ if ext in self.cfg["text_extensions"] or name in self.cfg["text_filenames"]:
207
+ return TEXT_MODE
208
+ if path_matches(rel, self.cfg["copy_verbatim"]):
209
+ return VERBATIM_MODE
210
+ return None
211
+
212
+ def scan(self) -> tuple[list[SourceFile], list[str]]:
213
+ files: list[SourceFile] = []
214
+ skipped: list[str] = []
215
+ twin = self.twin
216
+ for path in sorted(self.root.rglob("*")):
217
+ if not path.is_file():
218
+ continue
219
+ if twin == path or twin in path.parents:
220
+ continue
221
+ rel = path.relative_to(self.root).as_posix()
222
+ if path_matches(rel, self.cfg["ignore"] + [STATE_DIR, LEGACY_STATE_DIR]):
223
+ continue
224
+ data = path.read_bytes()
225
+ if path_matches(rel, self.cfg["exclude"]):
226
+ files.append(SourceFile(rel, VERBATIM_MODE, data, excluded=True))
227
+ continue
228
+ mode = self._mode_for(rel)
229
+ if mode is None and "." not in path.name and data.startswith(b"#!"):
230
+ mode = TEXT_MODE # a script without an extension (curl scripts/cd2nroff)
231
+ if mode is None:
232
+ skipped.append(rel)
233
+ else:
234
+ files.append(SourceFile(rel, mode, data))
235
+ # a text file that a build file names is a build input (curl docs/libcurl/symbols-in-versions,
236
+ # docs/cmdline-opts/mainpage.idx): copied as text like the build files when data_files is "build" or
237
+ # "copy"; with "none" they are only listed (.doppel/build_inputs.txt), so no data leaves unasked
238
+ self.build_inputs: list[str] = []
239
+ if skipped:
240
+ build_text = "\n".join(decode(f.data) for f in files if self._has_hash_comments(f.rel))
241
+ tokens = set(re.findall(r"[\w.\-]+", build_text))
242
+ copy_inputs = self.cfg["data_files"] in ("build", "copy")
243
+ for rel in [r for r in skipped if r.rsplit("/", 1)[-1] in tokens]:
244
+ data = (self.root / rel).read_bytes()
245
+ if b"\0" not in data[:4096]:
246
+ with __import__("contextlib").suppress(UnicodeDecodeError):
247
+ data.decode("utf-8")
248
+ self.build_inputs.append(rel)
249
+ if copy_inputs:
250
+ files.append(SourceFile(rel, TEXT_MODE, data))
251
+ skipped.remove(rel)
252
+ files.sort(key=lambda f: f.rel)
253
+ if self.build_inputs and not copy_inputs:
254
+ listing = self.state_dir / "build_inputs.txt"
255
+ with __import__("contextlib").suppress(OSError):
256
+ listing.parent.mkdir(parents=True, exist_ok=True)
257
+ listing.write_text("# Text files the build files name; not copied (data_files: none)\n"
258
+ + "".join(f"{r}\n" for r in self.build_inputs), encoding="utf-8")
259
+ self.auto_notes[:] = [n for n in self.auto_notes if "build files name were not copied" not in n]
260
+ self.auto_notes.append(
261
+ f"{len(self.build_inputs)} text file(s) that build files name were not copied (list in "
262
+ f'{listing}); "data_files": "build" copies them so the project\'s own build works')
263
+ self._auto_config(files)
264
+ return files, skipped
265
+
266
+ def _auto_config(self, files: list[SourceFile]) -> None:
267
+ """Defaults that depend on the project, for keys the user's config does not set: a CMake build (or a
268
+ build file that computes file paths) keeps file names, so the twin builds with it; a pytest project
269
+ keeps the names pytest finds tests, hooks and fixtures by."""
270
+ if self._auto_done:
271
+ return
272
+ self._auto_done = True
273
+ user = user_config(self.root)
274
+ live = [f for f in files if not f.excluded]
275
+ if "rename_files" not in user:
276
+ cmake = any(f.rel.rsplit("/", 1)[-1] == "CMakeLists.txt" for f in live)
277
+ computed = [f.rel for f in live if self._has_hash_comments(f.rel)
278
+ and _COMPUTED_PATH_RE.search(decode(f.data))]
279
+ if cmake or computed:
280
+ self.cfg["rename_files"] = False
281
+ self.auto_notes.append(
282
+ f"file and folder names kept ({'CMake build found' if cmake else 'build files compute paths'}), "
283
+ 'so the twin builds with the project\'s own build; "rename_files": true in .doppel/config.json '
284
+ "renames them")
285
+ if user.get("keep_test_names", True) and _uses_pytest(live):
286
+ hook_args = set()
287
+ for f in live:
288
+ if f.rel.rsplit("/", 1)[-1] == "conftest.py":
289
+ with __import__("contextlib").suppress(SyntaxError):
290
+ for node in ast.walk(pyparse.parse(decode(f.data))):
291
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and \
292
+ node.name.startswith("pytest_"):
293
+ hook_args |= {a.arg for a in node.args.args + node.args.kwonlyargs}
294
+ self.cfg["keep"] = sorted(set(self.cfg["keep"]) | PYTEST_NAMES | hook_args)
295
+ self.cfg["keep_regex"] = list(self.cfg["keep_regex"]) + [r"test_\w*", r"Test\w*", r"pytest_\w*",
296
+ r"\w*_test"]
297
+ self.auto_notes.append("pytest found: test_* / Test* names, pytest_* hooks and pytest's fixture names "
298
+ 'are kept so the twin\'s tests run (the test names are visible); '
299
+ '"keep_test_names": false hides them')
300
+
301
+ # -- mapping ---------------------------------------------------------
302
+ def _keep_rule(self, harvested: set[str], langs: set[str] | None = None):
303
+ cfg = self.cfg
304
+ keep = set(cfg["keep"])
305
+ for lang in langs or ():
306
+ keep |= LANGUAGES[lang].keywords | LANGUAGES[lang].keep
307
+ force = set(cfg["force_rename"])
308
+ prefixes = tuple(cfg["keep_prefixes"])
309
+ regexes = [re.compile(r) for r in cfg["keep_regex"]]
310
+ short = int(cfg["keep_short"])
311
+
312
+ def keep_name(name: str, any_length: bool = False) -> bool:
313
+ if name in force:
314
+ return False
315
+ return (name in ALWAYS_KEEP or is_reserved(name) or name in harvested or name in keep
316
+ or (len(name) <= short and not any_length) or (prefixes and name.startswith(prefixes))
317
+ or any(r.fullmatch(name) for r in regexes))
318
+ return keep_name
319
+
320
+ def build_mapping(self, files: list[SourceFile], report: ExportReport | None = None,
321
+ other_files: list[str] | None = None) -> Translator:
322
+ cfg = self.cfg
323
+ stats: dict[str, analyze.NameStats] = {}
324
+ system_headers: set[str] = set()
325
+ harvested: set[str] = set()
326
+ project_basenames = {f.rel.rsplit("/", 1)[-1] for f in files}
327
+ all_words: set[str] = set()
328
+
329
+ langs: set[str] = set()
330
+ decls: list[declare.FileDecl] = []
331
+ lang_count: dict[str, int] = {}
332
+ for f in files:
333
+ text = decode(f.data)
334
+ all_words.update(WORD_RE.findall(text))
335
+ lang = f.mode if is_code(f.mode) else (self._mode_for(f.rel) if f.excluded else None)
336
+ if not is_code(lang):
337
+ continue
338
+ toks = lexer.tokenize(text, lang)
339
+ if f.excluded:
340
+ harvested.update(t.text for t in toks if t.kind == lexer.IDENT)
341
+ continue
342
+ langs.add(lang)
343
+ lang_count[LANGUAGES[lang].title] = lang_count.get(LANGUAGES[lang].title, 0) + 1
344
+ if lang in ("c", "cpp"):
345
+ for t in toks:
346
+ if t.kind == lexer.HEADER:
347
+ inner = t.text[1:-1].strip()
348
+ if inner.rsplit("/", 1)[-1] not in project_basenames:
349
+ system_headers.add((inner, lang))
350
+ analyze.analyze(toks, stats)
351
+ else:
352
+ decls.append(declare.scan(text, toks, lang))
353
+
354
+ compiler = headers.find_compiler(cfg["compiler"])
355
+ inc_dirs = [Path(d) for d in cfg["include_dirs"]]
356
+ if compiler:
357
+ inc_dirs += headers.system_include_dirs(compiler)
358
+ if "cpp" in langs:
359
+ cxx = headers.find_cxx_compiler(cfg["cxx_compiler"], compiler)
360
+ if cxx:
361
+ inc_dirs += [d for d in headers.system_include_dirs(cxx, "c++") if d not in inc_dirs]
362
+ sys_idents, unresolved = headers.harvest({h for h, _ in system_headers}, inc_dirs)
363
+ harvested |= sys_idents
364
+
365
+ # Python: names of the external modules the project imports (read from source, not run)
366
+ project_modules = {f.rel.rsplit("/", 1)[-1].rsplit(".", 1)[0] for f in files if f.mode == "python"}
367
+ project_modules |= {f.rel.split("/")[0] for f in files if f.mode == "python" and "/" in f.rel}
368
+ py_names, py_unresolved = pyharvest.harvest(set().union(*(d.modules for d in decls)) if decls else set(),
369
+ project_modules)
370
+ harvested |= py_names
371
+ # Python packages (folders with __init__.py) are import names: renamed like modules below.
372
+ py_packages = {f.rel.rsplit("/", 2)[-2] for f in files
373
+ if f.mode == "python" and f.rel.endswith("/__init__.py") and not f.excluded}
374
+ if not cfg["rename_dirs"]:
375
+ # Directory names stay visible; a same-named identifier must stay too, or path
376
+ # words in Makefiles / comments would be rewritten while the folder is not.
377
+ harvested |= {d for f in files for d in f.rel.split("/")[:-1]} - py_packages
378
+ keep_name = self._keep_rule(harvested, langs)
379
+ if report is not None:
380
+ report.unresolved_headers = unresolved
381
+ report.compiler = compiler
382
+ report.languages = lang_count
383
+ report.unresolved_modules = py_unresolved
384
+ missing = self.state_dir / "missing.txt"
385
+ with __import__("contextlib").suppress(OSError):
386
+ if unresolved or py_unresolved:
387
+ missing.parent.mkdir(parents=True, exist_ok=True)
388
+ missing.write_text(
389
+ "# Not found during export: names used from them may get renamed. Install / configure the\n"
390
+ "# project (or add include_dirs) so DoppelCode can read them.\n"
391
+ + "".join(f"header {h}\n" for h in sorted(unresolved))
392
+ + "".join(f"module {m}\n" for m in sorted(py_unresolved)), encoding="utf-8")
393
+ report.missing_file = str(missing)
394
+ elif missing.exists():
395
+ missing.unlink()
396
+
397
+ # Generated names must never occur in the original project.
398
+ clashes = sorted(set(self.vault.words.values()) & all_words - set(self.vault.words))
399
+ forbidden = all_words | set(self.vault.words)
400
+ naming = cfg["naming"]
401
+ before = len(self.vault.words)
402
+
403
+ active: dict[str, str] = {}
404
+ for name, st in sorted(stats.items(), key=lambda kv: kv[1].order):
405
+ if keep_name(name) or (st.only_external_conditions and name not in cfg["force_rename"]):
406
+ continue
407
+ active[name] = self.vault.assign(name, st.kind, naming, forbidden)
408
+
409
+ # "declared" languages (Python, C#, Java, JS, TS): rename what the project declares, except
410
+ # names used as members of something the project does not declare (library objects).
411
+ declared: dict[str, str] = {}
412
+ for d in decls:
413
+ for name, kind in d.declared.items():
414
+ if declared.get(name) != "type":
415
+ declared[name] = kind
416
+ project_receivers = set(declared) | project_modules | {"this", "self", "cls", "base", "super"}
417
+
418
+ def external_import(module: str, relative: bool) -> bool:
419
+ top = module.lstrip(".").split(".")[0].split("/")[0]
420
+ return not relative and bool(top) and top not in project_modules and top not in declared
421
+ # names bound by imports from external modules / namespaces must keep their names
422
+ external_imports = {name for d in decls for name, module, rel in d.import_pairs
423
+ if ((not rel) if d.by_path else external_import(module, rel))}
424
+ external_members = {name for d in decls for recv, name in d.members if recv not in project_receivers}
425
+ # Python: obj.name where the project defines "name" only as a local (h = hashlib.sha256();
426
+ # h.digest() next to a local "digest"): obj may be a library object, keep the name
427
+ py_decls = [d for d in decls if d.member_declared is not None]
428
+ py_member_declared = set().union(*(d.member_declared for d in py_decls)) if py_decls else set()
429
+ external_members |= {name for d in py_decls for _, name in d.members if name not in py_member_declared}
430
+ # keyword arguments passed to library functions (json.dumps(indent=2)) keep their names
431
+ external_members |= {kw for d in decls for root, kw in d.kwargs if root not in project_receivers}
432
+ # methods of classes derived from library classes may be hooks found by name
433
+ # (unittest test_* / setUp, Thread.run, do_GET, __str__): keep them
434
+ project_types = {n for n, k in declared.items() if k == "type"}
435
+ external_members |= {m for d in decls for roots, m in d.overrides
436
+ if any(r not in project_types for r in roots)}
437
+ self.external_members = external_members
438
+ for name, kind in declared.items():
439
+ if name in active or keep_name(name) or name in external_members:
440
+ continue
441
+ if name in external_imports:
442
+ continue
443
+ active[name] = self.vault.assign(name, kind, naming, forbidden)
444
+ self.member_names = {name for d in decls for _, name in d.members}
445
+
446
+ stems: set[str] = set()
447
+ if cfg["rename_files"]:
448
+ for f in files:
449
+ if not is_code(f.mode) or f.excluded:
450
+ continue
451
+ name = f.rel.rsplit("/", 1)[-1]
452
+ # a template (config.h.cmake.in -> config.h) is named by its first part, like the file it makes
453
+ stem = name.split(".", 1)[0] if name.lower().endswith((".in", ".h.cmake")) else name.rsplit(".", 1)[0]
454
+ if not keep_name(stem):
455
+ active[stem] = self.vault.assign(stem, "file", naming, forbidden)
456
+ stems.add(stem)
457
+ for word in cfg["rename_words"]:
458
+ active[word] = self.vault.assign(word, "word", naming, forbidden)
459
+ # Build files: with build_names "rename", targets and variables made of the project's name parts
460
+ # (TARGET := falcon_selftest) get w_ aliases too. Off by default: it changes what the build produces.
461
+ if cfg["build_names"] == "rename":
462
+ kinds = self.vault.data["kinds"]
463
+ parts = name_parts(w for w in active if kinds.get(w) in CODE_KINDS)
464
+ for f in files:
465
+ if f.excluded or not self._has_hash_comments(f.rel):
466
+ continue
467
+ for w in sorted(set(WORD_RE.findall(decode(f.data)))):
468
+ if w not in active and not w.isdigit() and not keep_name(w) and word_parts(w) & parts:
469
+ active[w] = self.vault.assign(w, "word", naming, forbidden)
470
+
471
+ # Python dict keys are one class: all aliased or none. Otherwise 'pitch' (also a variable) gets an
472
+ # alias while 'f1', 'spectral_centroid' stay and list what a withheld function computes (R2.4).
473
+ # A key is kept when its dict belongs to a library (os.environ['PATH'], a dict handed to a library
474
+ # call), not because the word is also a library name: 'f2' is one in numpy (pilot round 5).
475
+ self._library_keys: set[str] = set()
476
+ if cfg["strings"] in ("scrub", "hide"):
477
+ keep_key = self._keep_rule(set(), langs)
478
+ # parts of imported external module names ('numpy' in {"numpy": np.__version__}): a key with that
479
+ # spelling must not rename the import itself (librosa twin: 'import w_0027 as np')
480
+ # a key spelled like a project file ('config' of config.h.cmake.in) would rename the file and
481
+ # the build files that name it, while C code includes "config.h" (libopus twin build)
482
+ file_first_names = {f.rel.rsplit("/", 1)[-1].split(".", 1)[0] for f in files}
483
+ file_first_names |= {r.rsplit("/", 1)[-1].split(".", 1)[0] for r in other_files or []}
484
+ module_parts = {part for d in decls for mod in d.modules for part in mod.lstrip(".").split(".")
485
+ if mod.lstrip(".").split(".")[0] not in project_modules}
486
+ for f in files:
487
+ if f.mode != "python" or f.excluded:
488
+ continue
489
+ src = decode(f.data)
490
+ library_keys = python_library_keys(src, external_imports)
491
+ self._library_keys |= library_keys
492
+ for w in sorted(python_dict_keys(src)):
493
+ if (w in active or len(w) < 2 or keep_key(w, any_length=True) or w in library_keys
494
+ or w in file_first_names
495
+ or w in external_members or w in external_imports or w in module_parts):
496
+ continue
497
+ active[w] = self.vault.assign(w, "word", naming, forbidden)
498
+
499
+ # File / folder names inside strings ("InputFiles//", "rec_01.dat") get file-shaped aliases
500
+ # (dir_0003, file_0001) so the twin program can still open its renamed data files.
501
+ self.data_dirs, self.data_stems = set(), set()
502
+ if cfg["strings"] in ("scrub", "hide"):
503
+ for f in files:
504
+ if not is_code(f.mode) or f.excluded:
505
+ continue
506
+ for t in lexer.tokenize(decode(f.data), f.mode):
507
+ if t.kind != lexer.STRING or t.directive in lexer.TEXT_DIRECTIVES:
508
+ continue
509
+ if not strhide.is_path_literal(t.text):
510
+ continue
511
+ for w, role in strhide.path_words(t.text):
512
+ (self.data_dirs if role == "dir" else self.data_stems).add(w)
513
+ if w in active or keep_name(w):
514
+ continue
515
+ active[w] = self.vault.assign(w, "dir" if role == "dir" else "data", naming, forbidden)
516
+ if cfg["data_files"] == "copy":
517
+ # every data file in a referenced folder gets an alias too (no original names in the twin)
518
+ for rel in other_files or []:
519
+ parts = rel.split("/")
520
+ stem = parts[-1].rsplit(".", 1)[0]
521
+ if any(d in self.data_dirs for d in parts[:-1]) or stem in self.data_stems:
522
+ for w in strhide.path_words('"' + rel + '"'):
523
+ if w[0] not in active and not keep_name(w[0]):
524
+ active[w[0]] = self.vault.assign(w[0], "dir" if w[1] == "dir" else "data",
525
+ naming, forbidden)
526
+
527
+ dirs: dict[str, str] = {}
528
+ for pkg in sorted(py_packages):
529
+ if not keep_name(pkg):
530
+ active[pkg] = self.vault.assign(pkg, "file", naming, forbidden)
531
+ self.vault.dirs[pkg] = active[pkg] # folder and import name get the same alias
532
+ dirs[pkg] = active[pkg]
533
+ stems.add(pkg)
534
+ if cfg["rename_dirs"]:
535
+ for f in files:
536
+ if f.excluded:
537
+ continue
538
+ for d in f.rel.split("/")[:-1]:
539
+ if not keep_name(d):
540
+ dirs[d] = self.vault.assign_dir(d, forbidden)
541
+
542
+ # Token pasting (#define F(stem) prefix_ ## stem ## _mixing): a name the code builds by pasting gets
543
+ # the pasted parts' aliases as its alias, so pasting in the twin yields the declared name (libopus
544
+ # mapping_matrix_foa_mixing -> v_4104v_4108v_4105 = alias of 'mapping_matrix_' + 'foa' + '_mixing').
545
+ # CMake check_type_size(T SIZEOF_X) also sets SIZEOF_X_CODE, which a config template writes as
546
+ # ${SIZEOF_X_CODE}: it must follow SIZEOF_X's alias (curl twin: "too small curl_off_t")
547
+ for name in [n for n in active if n.endswith("_CODE") and n[:-5] in active]:
548
+ active[name] = self.vault.words[name] = active[name[:-5]] + "_CODE"
549
+ for name, alias in _pasted_aliases(files, active).items():
550
+ if alias == name: # every part kept: the name must stay too
551
+ active.pop(name, None)
552
+ self.vault.words.pop(name, None)
553
+ else:
554
+ active[name] = alias
555
+ self.vault.words[name] = alias
556
+
557
+ # Words that were mapped before but are generated names now present in the original.
558
+ if clashes:
559
+ raise DoppelError("generated names already present in the original project: " + ", ".join(clashes[:20]))
560
+
561
+ self.vault.data["stems"] = sorted(set(self.vault.data["stems"]) | stems)
562
+ if report is not None:
563
+ report.renamed = len(active)
564
+ report.new_names = len(self.vault.words) - before
565
+ comment_forbidden = forbidden
566
+
567
+ def alloc_comment() -> str:
568
+ return self.vault.new_name(COMMENT_PREFIX, comment_forbidden)
569
+
570
+ def alloc_string() -> str:
571
+ return self.vault.new_name(STRING_PREFIX, comment_forbidden)
572
+
573
+ tr = Translator(active, stems, dirs,
574
+ scrub_comments=cfg["comments"] in ("scrub", "hide"),
575
+ scrub_strings=cfg["strings"] in ("scrub", "hide"),
576
+ hide_strings=cfg["strings"] == "hide",
577
+ string_store=self.vault.data.setdefault("strings", {}),
578
+ string_alloc=alloc_string,
579
+ hide_comments=cfg["comments"] == "hide",
580
+ comment_store=self.vault.data.setdefault("comments", {}),
581
+ comment_alloc=alloc_comment)
582
+ tr.library_keys = self._library_keys # 'max_input_channels' of a library dict: never hidden
583
+ every = [f.rel for f in files] + list(other_files or [])
584
+ tr.copied_names = {f.rel.rsplit("/", 1)[-1] for f in files if not f.excluded}
585
+ tr.path_words = ({r.rsplit("/", 1)[-1].split(".", 1)[0] for r in every}
586
+ | {d for r in every for d in r.split("/")[:-1]})
587
+ if not cfg["rename_files"]:
588
+ # file names are kept for the project's own build: its outputs keep their names too
589
+ tr.build_keep = {m.group(1) for f in files if self._is_cmake(f.rel)
590
+ for m in _CMAKE_TARGET_RE.finditer(decode(f.data))}
591
+ tr.secret_plan = self._secret_plan(files, forbidden)
592
+ tr.withheld = withhold.Plan(self.vault)
593
+ if withhold.active(self.cfg):
594
+ for f in files:
595
+ if not f.excluded:
596
+ tr.withheld.add(f.rel, decode(f.data), f.mode, self.cfg)
597
+ if tr.secret_plan.active:
598
+ tr.secret_text = tr.secret_plan.text_alias
599
+ return tr
600
+
601
+ def secret_candidates(self) -> list[tuple[secretconst.Candidate, bool]]:
602
+ """`doppel secrets suggest`: (candidate, already marked) for every file the twin would get."""
603
+ files, _ = self.scan()
604
+ out = []
605
+ for f, src, marked in self._secret_files(files)[0]:
606
+ fns = [(fn.start_line, fn.end_line, fn.symbol) for fn in ledger.functions(src, f.mode)]
607
+ marked_values = {secretconst.num_key(s.text) for s in marked.sites if s.kind == "scalar"}
608
+ marked_lines = {n for s in marked.sites for n in range(s.line, s.line + s.text.count("\n") + 1)}
609
+ for c in secretconst.suggest(src, f.rel, f.mode):
610
+ inner = [s for a, b, s in fns if a <= c.line <= b]
611
+ c.function = inner[-1] if inner else ""
612
+ k = secretconst.num_key(c.text)
613
+ out.append((c, (k is not None and k in marked_values) or c.line in marked_lines))
614
+ return sorted(out, key=lambda cm: secretconst.rank_key(cm[0]))
615
+
616
+ def secret_list(self) -> list[dict]:
617
+ """`doppel secrets list`: the secrets of the last export (alias, file, line, type, literal)."""
618
+ current = {a for a in self.vault.data.get("secret_sites", {}).values()}
619
+ store = self.vault.data.get("secrets", {})
620
+ return [dict(alias=a, **store[a]) for a in sorted(current) if a in store]
621
+
622
+ def _secret_plan(self, files: list[SourceFile], forbidden: set[str]) -> "secretconst.Plan":
623
+ """Secret constants of this export (see secretconst): marked by tag, symbol or value."""
624
+ plan = secretconst.Plan(self.vault, forbidden)
625
+ marked, table = self._secret_files(files)
626
+ for f, _, fs in marked:
627
+ plan.add(f.rel, fs, f.mode)
628
+ plan.table_values = {k[0] for k in table}
629
+ plan.local_small = secretconst.local_small_values(marked)
630
+ if plan.active: # the marks themselves: "145" in text even if code only has 145.0
631
+ plan.scalars |= secretconst.value_keys(self.cfg["secret_values"])
632
+ return plan
633
+
634
+ def _secret_files(self, files: list[SourceFile]) -> tuple[list, set]:
635
+ """(file, source, FileSecrets) of every Python / C / C++ file, and the keys of the secret-table
636
+ elements. A table's elements are hidden wherever else they are written in the same form."""
637
+ symbols = set(self.cfg["secret_symbols"])
638
+ values = secretconst.value_keys(self.cfg["secret_values"])
639
+ code = [(f, decode(f.data)) for f in files if not f.excluded and f.mode in ("python", "c", "cpp")]
640
+
641
+ def scan(f: SourceFile, src: str, syms: set, vals: set) -> "secretconst.FileSecrets":
642
+ if not (syms or vals or secretconst.TAG in src or secretconst.LEGACY_TAG in src):
643
+ return secretconst.FileSecrets()
644
+ return (secretconst.python_secrets(src, f.rel, syms, vals) if f.mode == "python"
645
+ else secretconst.c_secrets(src, f.rel, f.mode, syms, vals))
646
+
647
+ def mark(f: SourceFile, src: str, vals: set) -> "secretconst.FileSecrets":
648
+ fs = scan(f, src, symbols, vals)
649
+ scope = self._secret_scope(f, src)
650
+ if scope is None:
651
+ return fs
652
+ extra_vals, extra_syms, spans = scope
653
+ wide = scan(f, src, symbols | extra_syms, vals | extra_vals)
654
+ if spans is not None: # secret_functions: the extra marks count inside those functions only
655
+ base = {s.start for s in fs.sites}
656
+ wide.sites = [s for s in wide.sites if s.start in base or any(a <= s.line <= b for a, b in spans)]
657
+ return wide
658
+ first = [(f, src, mark(f, src, values)) for f, src in code]
659
+ table: set = set()
660
+ for f, _, fs in first:
661
+ table |= secretconst.table_keys(fs.sites, f.mode)
662
+ if not table:
663
+ return first, table
664
+ return [(f, src, mark(f, src, values | table)) for f, src in code], table
665
+
666
+ def _secret_scope(self, f: SourceFile, src: str):
667
+ """secret_files / secret_functions: (values, names, line spans or None for the whole file) of the
668
+ `secrets suggest` candidates they cover in this file, or None."""
669
+ files_cfg = self.cfg.get("secret_files") or []
670
+ funcs_cfg = self.cfg.get("secret_functions") or []
671
+ if not (files_cfg or funcs_cfg):
672
+ return None
673
+ spans = None
674
+ if not path_matches(f.rel, files_cfg):
675
+ spans = [(fn.start_line, fn.end_line) for fn in ledger.functions(src, f.mode)
676
+ if withhold.chosen(f.rel, fn.symbol, {"core_functions": funcs_cfg})]
677
+ if not spans:
678
+ return None
679
+ cands = [c for c in secretconst.suggest(src, f.rel, f.mode)
680
+ if spans is None or any(a <= c.line <= b for a, b in spans)]
681
+ values, names = secretconst.candidate_marks(cands)
682
+ return values, names, spans
683
+
684
+ def secret_table_users(self) -> dict[tuple[str, str], int]:
685
+ """(file, function) -> how many secret-table values it writes as literals (test and debug
686
+ helpers that hard-code table entries): candidates for withholding."""
687
+ files, _ = self.scan()
688
+ marked, table = self._secret_files(files)
689
+ values = {k[0] for k in table}
690
+ out: dict[tuple[str, str], int] = {}
691
+ if not values:
692
+ return out
693
+ for f, src, fs in marked:
694
+ arrays = [(s.start, s.end) for s in fs.sites if s.kind == "array"]
695
+ toks = secretconst._tokens_with_offsets(src, f.mode)
696
+ hits = [pos for t, pos, _ in toks if t.kind == "number" and secretconst.num_value(t.text) in values
697
+ and not any(a <= pos < b for a, b in arrays)]
698
+ for fn in ledger.functions(src, f.mode):
699
+ n = sum(fn.body_start <= p < fn.body_end for p in hits) if fn.body_end else 0
700
+ if n:
701
+ out[(f.rel, fn.symbol)] = n
702
+ return out
703
+
704
+ def reverse_translator(self) -> Translator:
705
+ """Inverse of every mapping ever issued (so old names the AI still uses are restored too)."""
706
+ words = self.vault.words
707
+ fwd = Translator(dict(words), set(self.vault.data["stems"]), dict(self.vault.dirs),
708
+ comment_store=self.vault.data.setdefault("comments", {}),
709
+ string_store=self.vault.data.setdefault("strings", {}))
710
+ rtr = fwd.reversed()
711
+ rtr.words.update({a: s["literal"] for a, s in self.vault.data.get("secrets", {}).items()})
712
+ return rtr
713
+
714
+ # -- twin scanning ---------------------------------------------------
715
+ # -- the twin is written by the AI agent: treat its structure as untrusted ----
716
+ def _inside_twin(self, path: Path) -> bool:
717
+ """True when ``path`` really is inside the twin: no symlink or junction leads out of it."""
718
+ twin_real = os.path.normcase(os.path.realpath(self.twin))
719
+ real = os.path.normcase(os.path.realpath(path))
720
+ return real == twin_real or real.startswith(twin_real.rstrip(os.sep) + os.sep)
721
+
722
+ def _check_twin_dest(self, dest: Path) -> None:
723
+ if dest.is_symlink() or not self._inside_twin(dest.parent if not dest.exists() else dest):
724
+ raise DoppelError(f"refusing to write {dest}: the twin contains a symlink or junction that leads "
725
+ "outside the twin folder (it may have been planted there). Remove it first.")
726
+
727
+ def _twin_files(self) -> dict[str, Path]:
728
+ twin = self.twin
729
+ out: dict[str, Path] = {}
730
+ self.twin_unsafe: list[str] = []
731
+ if not twin.is_dir():
732
+ return out
733
+ data_files = (set(self.vault.data.get("data_twin", [])) | set(self.vault.data.get("notes_twin", []))
734
+ | set(self.vault.data.get("twin_only", {})))
735
+ data_dirs = [d + "/" for d in self.vault.data.get("data_dirs_twin", [])]
736
+ for path in sorted(twin.rglob("*")):
737
+ if path.is_symlink() or (path.exists() and not self._inside_twin(path)):
738
+ self.twin_unsafe.append(path.relative_to(twin).as_posix())
739
+ continue # never read through a link: it could point at any file on the PC
740
+ if path.is_file():
741
+ rel = path.relative_to(twin).as_posix()
742
+ if rel in data_files or any(rel.startswith(d) for d in data_dirs):
743
+ continue # data files and program output in data folders are not code
744
+ if not path_matches(rel, self.cfg["twin_ignore"]):
745
+ out[rel] = path
746
+ return out
747
+
748
+ def pending_twin_changes(self) -> list[str]:
749
+ """Twin files changed/added/deleted since the last export or import."""
750
+ baseline = self.vault.baseline
751
+ by_twin = {b["twin"]: o for o, b in baseline.items()}
752
+ current = self._twin_files()
753
+ pending = []
754
+ for rel, path in current.items():
755
+ orig = by_twin.get(rel)
756
+ if orig is None:
757
+ pending.append(f"new {rel}")
758
+ elif sha(path.read_bytes()) != baseline[orig]["twin_sha"]:
759
+ pending.append(f"changed {rel}")
760
+ for rel in by_twin:
761
+ if rel not in current:
762
+ pending.append(f"deleted {rel}")
763
+ return pending
764
+
765
+ # -- export ----------------------------------------------------------
766
+ def forward(self, tr: Translator, f: SourceFile) -> tuple[str, bytes]:
767
+ if f.excluded or f.mode == VERBATIM_MODE:
768
+ return f.rel, f.data
769
+ text = decode(f.data)
770
+ if is_code(f.mode):
771
+ plan = getattr(tr, "secret_plan", None)
772
+ sites = plan.files.get(f.rel) if plan else None
773
+ held = getattr(tr, "withheld", None)
774
+ spans = held.files.get(f.rel) if held else None
775
+ tr.secret_spans = plan.local_small.get(f.rel) if plan else None
776
+ if spans: # a withheld body hides the secrets inside it too
777
+ merged = {a: v for a, v in (sites or {}).items()
778
+ if not any(s <= a < e for s, (e, _) in spans.items())}
779
+ # a stub's return type uses the twin's names: `return (T_0001){0};`
780
+ merged.update({a: (e, withhold.translate_stub(s, tr.word)) for a, (e, s) in spans.items()})
781
+ out = tr.code_source(text, f.mode, merged)
782
+ else:
783
+ out = tr.code_source(text, f.mode, sites)
784
+ tr.secret_spans = None
785
+ if plan and f.mode == "python":
786
+ # the table aliases, and the aliases of secret numbers in f-string code
787
+ # only the aliases this file's twin code uses: a secret inside a withheld body is not listed
788
+ dummies = plan.dummies.get("python", {})
789
+ aliases = {a for a in secretconst.SECRET_ALIAS_RE.findall(out) if a in dummies}
790
+ if aliases:
791
+ line = plan.imports[f.rel][0] if f.rel in plan.imports else plan.import_lines.get(f.rel, 0)
792
+ out = secretconst.insert_after_line(out, line, secretconst.python_import_line(aliases))
793
+ elif sites:
794
+ line, _ = plan.imports[f.rel]
795
+ out = secretconst.insert_after_line(out, line, secretconst.c_include_line(tr.path(f.rel)))
796
+ elif self._has_hash_comments(f.rel):
797
+ out = tr.build_text(self._hide_abs_paths(text), self._is_cmake(f.rel))
798
+ elif self._is_packaging(f.rel):
799
+ out = tr.path_text(self._hide_abs_paths(text))
800
+ else:
801
+ out = tr.text(self._hide_abs_paths(text))
802
+ return tr.path(f.rel), encode(out)
803
+
804
+ def _hide_abs_paths(self, text: str) -> str:
805
+ """Absolute paths in build and text files (toolchain folders, the source checkout with the user's
806
+ name) -> $(DOPPEL_PATH_0001); import puts them back. The twin is not built from these paths."""
807
+ store: dict[str, str] = self.vault.data.setdefault("abs_paths", {})
808
+ ids = {v: k for k, v in store.items()}
809
+
810
+ def hide(m: re.Match) -> str:
811
+ path = m.group(0)
812
+ pid = ids.get(path)
813
+ if pid is None:
814
+ pid = f"DOPPEL_PATH_{len(store) + 1:04d}"
815
+ store[pid] = path
816
+ ids[path] = pid
817
+ return f"$({pid})"
818
+ return ABS_PATH_RE.sub(hide, text)
819
+
820
+ def _has_hash_comments(self, rel: str) -> bool:
821
+ """Makefile / CMake files: '#' line comments, hidden like code comments."""
822
+ name = rel.rsplit("/", 1)[-1]
823
+ return name in ("Makefile", "makefile", "GNUmakefile", "CMakeLists.txt", "Makefile.inc") or name.lower().endswith(
824
+ (".mk", ".cmake", ".cmake.in", ".am", ".mk.in"))
825
+
826
+ @staticmethod
827
+ def _is_packaging(rel: str) -> bool:
828
+ """pyproject.toml, setup.cfg, MANIFEST.in, requirements*.txt: the tool's keys ([build-system],
829
+ requires-python) stay; only the project's package, module and folder names change (librosa)."""
830
+ name = rel.rsplit("/", 1)[-1]
831
+ return name in ("pyproject.toml", "setup.cfg", "MANIFEST.in") or (
832
+ name.startswith("requirements") and name.endswith(".txt"))
833
+
834
+ @staticmethod
835
+ def _is_cmake(rel: str) -> bool:
836
+ name = rel.rsplit("/", 1)[-1].lower()
837
+ return name == "cmakelists.txt" or name.endswith((".cmake", ".cmake.in"))
838
+
839
+ def export(self, force: bool = False, allow_over_budget: bool = False) -> ExportReport:
840
+ """``allow_over_budget``: export even when a folder goes over its exposure budget (logged)."""
841
+ twin = self.twin
842
+ twin_fresh = not (twin.is_dir() and any(twin.iterdir())) or os.path.normcase(
843
+ str(self.vault.data.get("twin") or "")) != os.path.normcase(str(twin))
844
+ if self.vault.exists and twin.exists():
845
+ pending = self.pending_twin_changes()
846
+ if pending and not force:
847
+ raise DoppelError("the twin has changes that were not imported yet (run 'import' first, "
848
+ "or 'export --force' to discard them):\n " + "\n ".join(pending))
849
+ files, skipped = self.scan()
850
+ unresolved = [r for r in skipped if r.endswith((".doppel-merge", ".doppel-incoming", ".cobf-merge",
851
+ ".cobf-incoming"))]
852
+ if unresolved and not force:
853
+ raise DoppelError("unresolved AI changes from the last import - merge them into the original and "
854
+ "delete these files first (export would drop the AI change from the twin):\n "
855
+ + "\n ".join(unresolved))
856
+ if (twin.is_dir() and any(twin.iterdir()) and not force
857
+ and os.path.normcase(str(self.vault.data.get("twin") or "")) != os.path.normcase(str(twin))):
858
+ raise DoppelError(f"the twin folder {twin} is not empty and was not created by DoppelCode for this project. "
859
+ "Choose an empty or new folder (or use --force to write into it anyway).")
860
+ report = ExportReport(twin=twin, skipped=skipped)
861
+ events, over = self._exposure_events(files, twin_fresh)
862
+ if over and not allow_over_budget:
863
+ raise DoppelError("this export would put folders over their exposure budget:\n " + "\n ".join(over)
864
+ + "\n(raise exposure_budget in .doppel/config.json, or export with --allow-over-budget; "
865
+ "the override is recorded in the ledger)")
866
+ tr = self.build_mapping(files, report, skipped)
867
+
868
+ outputs: dict[str, tuple[SourceFile, bytes]] = {}
869
+ for f in files:
870
+ twin_rel, data = self.forward(tr, f)
871
+ if twin_rel in outputs:
872
+ raise DoppelError(f"two files map to the same twin path {twin_rel}: "
873
+ f"{outputs[twin_rel][0].rel}, {f.rel}")
874
+ outputs[twin_rel] = (f, data)
875
+
876
+ # Remove files this tool wrote earlier that are no longer produced.
877
+ for b in self.vault.baseline.values():
878
+ if b["twin"] not in outputs:
879
+ stale = twin / b["twin"]
880
+ if stale.is_file() and not stale.is_symlink() and self._inside_twin(stale):
881
+ stale.unlink()
882
+ new_baseline = {}
883
+ twin_idents: set[str] = set()
884
+ twin.mkdir(parents=True, exist_ok=True)
885
+ for twin_rel, (f, data) in outputs.items():
886
+ dest = twin / twin_rel
887
+ self._check_twin_dest(dest)
888
+ dest.parent.mkdir(parents=True, exist_ok=True)
889
+ if not dest.exists() or dest.read_bytes() != data:
890
+ dest.write_bytes(data)
891
+ new_baseline[f.rel] = {"twin": twin_rel, "mode": "excluded" if f.excluded else f.mode,
892
+ "orig_sha": sha(f.data), "twin_sha": sha(data)}
893
+ if is_code(f.mode):
894
+ twin_idents.update(t.text for t in lexer.tokenize(decode(data), f.mode)
895
+ if t.kind == lexer.IDENT)
896
+ report.files.append((f.rel, twin_rel))
897
+ self._copy_data(tr, skipped, report)
898
+ plan = tr.secret_plan
899
+ twin_only: dict[str, str] = {}
900
+ # The dummy files list only aliases the twin's code uses: secrets used only inside withheld bodies would
901
+ # otherwise tell how many constants the hidden functions need (pilot round 4).
902
+ used: dict[str, set[str]] = {"python": set(), "c": set()}
903
+ for f, data in outputs.values():
904
+ if f.mode in ("python", "c", "cpp"):
905
+ used["python" if f.mode == "python" else "c"] |= set(
906
+ secretconst.SECRET_ALIAS_RE.findall(decode(data)))
907
+ for family in ("python", "c"):
908
+ if family in plan.dummies:
909
+ plan.dummies[family] = {a: d for a, d in plan.dummies[family].items() if a in used[family]}
910
+ self.vault.data["secret_written"] = {k: sorted(v & set(plan.dummies.get(k, {}))) for k, v in used.items()}
911
+ if plan.dummies.get("python"):
912
+ name = secretconst.PY_MODULE + ".py"
913
+ if name in outputs:
914
+ raise DoppelError(f"the project has its own {name}; DoppelCode needs that name for secret constants")
915
+ data = encode(secretconst.python_twin_module(plan.dummies["python"]))
916
+ self._check_twin_dest(twin / name)
917
+ (twin / name).write_bytes(data)
918
+ twin_only[name] = sha(data)
919
+ if plan.dummies.get("c"):
920
+ name = secretconst.C_HEADER
921
+ if name in outputs:
922
+ raise DoppelError(f"the project has its own {name}; DoppelCode needs that name for secret constants")
923
+ data = encode(secretconst.c_twin_header(plan.dummies["c"]))
924
+ self._check_twin_dest(twin / name)
925
+ (twin / name).write_bytes(data)
926
+ twin_only[name] = sha(data)
927
+ for old in set(self.vault.data.get("twin_only", {})) - set(twin_only):
928
+ p = twin / old
929
+ if p.is_file() and not p.is_symlink() and self._inside_twin(p):
930
+ p.unlink()
931
+ self.vault.data["twin_only"] = twin_only
932
+ report.secrets = len({a for m in plan.files.values() for _, a in m.values()})
933
+ report.withheld = tr.withheld.count
934
+ for name in AGENT_NOTE_FILES:
935
+ if name in outputs:
936
+ continue # the project has its own file of that name: leave it alone
937
+ dest = twin / name
938
+ self._check_twin_dest(dest)
939
+ dest.write_text(AGENT_NOTES + (SECRET_NOTE if plan.active else "")
940
+ + (WITHHELD_NOTE + self._purpose_note(tr) if tr.withheld.count else ""),
941
+ encoding="utf-8")
942
+ report.agent_notes.append(name)
943
+ self.vault.data["notes_twin"] = report.agent_notes
944
+ _remove_empty_dirs(twin, self._inside_twin)
945
+ if self.base_dir.exists():
946
+ shutil.rmtree(self.base_dir)
947
+ for f in files:
948
+ self._write_base(f.rel, f.data)
949
+ if self.twin_base_dir.exists():
950
+ shutil.rmtree(self.twin_base_dir)
951
+ for twin_rel, (f, data) in outputs.items():
952
+ if is_code(f.mode):
953
+ self._write_twin_base(twin_rel, data)
954
+
955
+ self.vault.data["twin"] = str(twin)
956
+ self.vault.data["baseline"] = new_baseline
957
+ self.vault.data["twin_idents"] = sorted(twin_idents)
958
+ session = self.vault.new_name("s_", set())
959
+ logged = {e.get("symbol") for e in ledger.read(self.state_dir) if e.get("kind") == "secret"}
960
+ for alias in sorted({a for m in plan.files.values() for _, a in m.values()} - logged):
961
+ meta = self.vault.data["secrets"].get(alias, {})
962
+ events.append({"event": "export", "file": meta.get("file", ""), "symbol": alias, "kind": "secret"})
963
+ stamp = ledger.now()
964
+ for e in events:
965
+ e.update(time=stamp, session=session)
966
+ events += [{"time": stamp, "event": "override", "session": session, "folder": o} for o in over]
967
+ report.released = list(self.vault.data.get("withheld_release", []))
968
+ self.vault.data["withheld_release"] = [] # one session: the next export withholds them again
969
+ self.vault.save()
970
+ ledger.append(self.state_dir, events)
971
+ report.session = session
972
+ report.bodies_logged = sum(e.get("kind") == "body" for e in events)
973
+ report.over_budget = over
974
+ return report
975
+
976
+ @property
977
+ def state_dir(self) -> Path:
978
+ return self.root / state_dir_name(self.root)
979
+
980
+ def _functions(self, files: list[SourceFile]) -> dict[tuple[str, str], str]:
981
+ """(file, symbol) -> body hash, for every function of the code files the twin gets."""
982
+ out: dict[tuple[str, str], str] = {}
983
+ for f in files:
984
+ if f.excluded or not is_code(f.mode):
985
+ continue
986
+ for fn in ledger.functions(decode(f.data), f.mode):
987
+ out[(f.rel, fn.symbol)] = fn.sha
988
+ return out
989
+
990
+ def _exposure_events(self, files: list[SourceFile], twin_fresh: bool) -> tuple[list[dict], list[str]]:
991
+ """Ledger events for this export (bodies that are new or changed, or re-sent to a new twin) and the
992
+ folders it would put over their exposure budget."""
993
+ funcs = self._functions(files)
994
+ held = self._withheld_keys(files, funcs)
995
+ old = ledger.read(self.state_dir)
996
+ last = ledger.last_sent(old)
997
+ declared = {(e.get("file", ""), e.get("symbol", "")) for e in old if e.get("kind") == "declaration"}
998
+ in_twin = set(self.vault.baseline)
999
+ events = []
1000
+ for (rel, sym), digest in sorted(funcs.items()):
1001
+ if (rel, sym) in held: # only the signature goes to the twin
1002
+ if (rel, sym) not in declared or twin_fresh or rel not in in_twin:
1003
+ events.append({"event": "export", "file": rel, "symbol": sym, "kind": "declaration"})
1004
+ continue
1005
+ prev = last.get((rel, sym))
1006
+ released = f"{rel}::{sym}" in self.vault.data.get("withheld_release", [])
1007
+ if prev is None or prev.get("sha") != digest or released:
1008
+ events.append({"event": "export", "file": rel, "symbol": sym, "kind": "body", "sha": digest,
1009
+ **({"released": True} if released else {})})
1010
+ elif twin_fresh or rel not in in_twin:
1011
+ events.append({"event": "export", "file": rel, "symbol": sym, "kind": "body", "sha": digest,
1012
+ "repeat": True})
1013
+ over = []
1014
+ for folder, limit in sorted(self.cfg["exposure_budget"].items()):
1015
+ prefix = folder.rstrip("/") + "/" if folder not in ("", ".", "./") else ""
1016
+ mine = [k for k in funcs if k[0].startswith(prefix)]
1017
+ if mine:
1018
+ sent = {k for k in mine if k in last or k not in held} # ever sent, or sent by this export
1019
+ share = len(sent) / len(mine)
1020
+ if share > float(limit) + 1e-9:
1021
+ over.append(f"{folder}: {len(sent)} of {len(mine)} function bodies, {share:.0%} > budget "
1022
+ f"{float(limit):.0%}")
1023
+ return events, over
1024
+
1025
+ def _withheld_keys(self, files: list[SourceFile], funcs: dict) -> set[tuple[str, str]]:
1026
+ modes = {f.rel: f.mode for f in files}
1027
+ released = set(self.vault.data.get("withheld_release", []))
1028
+ return {k for k in funcs if modes.get(k[0]) in withhold.LANGS and withhold.chosen(k[0], k[1], self.cfg)
1029
+ and f"{k[0]}::{k[1]}" not in released}
1030
+
1031
+ def _purpose_note(self, tr: Translator) -> str:
1032
+ """The owner's one-line purposes of the functions withheld in this export (opt-in, config
1033
+ "withheld_purpose"), with names and secret values translated like any other twin text."""
1034
+ purposes = self.cfg.get("withheld_purpose") or {}
1035
+ lines = []
1036
+ for rel, symbols in tr.withheld.symbols.items():
1037
+ for sym in symbols:
1038
+ text = " ".join(str(purposes.get(f"{rel}::{sym}", "")).split())
1039
+ if text:
1040
+ lines.append((tr.withheld.ids[f"{rel}::{sym}"], tr.text(text)))
1041
+ if not lines:
1042
+ return ""
1043
+ return ("\nWhat the withheld functions do, in the owner's words:\n\n"
1044
+ + "".join(f"- `{bid}`: {text}\n" for bid, text in sorted(lines)))
1045
+
1046
+ def set_withheld_purpose(self, bid: str, text: str) -> str:
1047
+ """Set (or with empty text remove) the purpose line of withheld function `bid`; returns its key."""
1048
+ key = {b: k for k, b in self.vault.data.get("withheld_ids", {}).items()}.get(bid)
1049
+ if key is None:
1050
+ raise DoppelError(f"not a withheld function: {bid} (see 'doppel withhold list')")
1051
+ purposes = dict(self.cfg.get("withheld_purpose") or {})
1052
+ text = " ".join(text.split())
1053
+ if text:
1054
+ purposes[key] = text
1055
+ else:
1056
+ purposes.pop(key, None)
1057
+ set_config_value(self.root, "withheld_purpose", purposes)
1058
+ self.cfg["withheld_purpose"] = purposes
1059
+ return key
1060
+
1061
+ def withheld_list(self) -> list[dict]:
1062
+ """`doppel withhold list`: id, file, symbol, purpose, and whether it is released for the next export."""
1063
+ ids = self.vault.data.get("withheld_ids", {})
1064
+ purposes = self.cfg.get("withheld_purpose") or {}
1065
+ released = set(self.vault.data.get("withheld_release", []))
1066
+ files, _ = self.scan()
1067
+ current = self._withheld_keys(files, self._functions(files)) | {
1068
+ tuple(k.split("::", 1)) for k in released}
1069
+ out = []
1070
+ for key, bid in sorted(ids.items(), key=lambda kv: kv[1]):
1071
+ rel, sym = key.split("::", 1)
1072
+ if (rel, sym) in current:
1073
+ out.append({"id": bid, "file": rel, "symbol": sym, "released": key in released,
1074
+ "purpose": purposes.get(key, "")})
1075
+ return out
1076
+
1077
+ def release_withheld(self, ids: list[str], reason: str = "") -> list[str]:
1078
+ """Send these withheld bodies with the next export only (a core edit the AI has to make). The
1079
+ release is logged in the ledger now; the body is logged as sent by that export; the export after
1080
+ it withholds the function again."""
1081
+ by_id = {bid: key for key, bid in self.vault.data.get("withheld_ids", {}).items()}
1082
+ unknown = [b for b in ids if b not in by_id]
1083
+ if unknown:
1084
+ raise DoppelError(f"not a withheld function: {', '.join(unknown)} (see 'doppel withhold list')")
1085
+ pending = self.vault.data.setdefault("withheld_release", [])
1086
+ stamp = ledger.now()
1087
+ events = []
1088
+ for bid in ids:
1089
+ key = by_id[bid]
1090
+ if key not in pending:
1091
+ pending.append(key)
1092
+ rel, sym = key.split("::", 1)
1093
+ events.append({"time": stamp, "event": "override", "kind": "release", "id": bid, "file": rel,
1094
+ "symbol": sym, **({"reason": reason} if reason else {})})
1095
+ self.vault.save()
1096
+ ledger.append(self.state_dir, events)
1097
+ return [by_id[b] for b in ids]
1098
+
1099
+ def outline(self) -> list[dict]:
1100
+ """Every function the twin gets, for the desktop app's outline: file, symbol, language, line,
1101
+ whether it is withheld now and whether it can be (Python, C, C++)."""
1102
+ files, _ = self.scan()
1103
+ users = self.secret_table_users()
1104
+ out = []
1105
+ for f in files:
1106
+ if f.excluded or not is_code(f.mode):
1107
+ continue
1108
+ for fn in ledger.functions(decode(f.data), f.mode):
1109
+ out.append({"file": f.rel, "symbol": fn.symbol, "lang": f.mode, "line": fn.start_line,
1110
+ "supported": f.mode in withhold.LANGS,
1111
+ "secret_table_values": users.get((f.rel, fn.symbol), 0),
1112
+ "withheld": f.mode in withhold.LANGS and withhold.chosen(f.rel, fn.symbol, self.cfg)})
1113
+ return out
1114
+
1115
+ def exposure_report(self, by: str = "folder", since: str | None = None) -> list[dict]:
1116
+ """Rows for `doppel report`: what was made available to an AI (not what it read)."""
1117
+ files, _ = self.scan()
1118
+ funcs = self._functions(files)
1119
+ held = self._withheld_keys(files, funcs)
1120
+ events = [e for e in ledger.read(self.state_dir) if not since or e.get("time", "") >= since]
1121
+ sent: dict[tuple[str, str], list[dict]] = {}
1122
+ for e in events:
1123
+ if e.get("kind") == "body":
1124
+ sent.setdefault((e.get("file", ""), e.get("symbol", "")), []).append(e)
1125
+ current = set(self.vault.data.get("secret_sites", {}).values())
1126
+ secret_files = [self.vault.data.get("secrets", {}).get(a, {}).get("file", "") for a in current]
1127
+ if by == "function":
1128
+ rows = []
1129
+ for key in sorted(funcs):
1130
+ ev = sent.get(key, [])
1131
+ rows.append({"file": key[0], "function": key[1], "sends": len(ev), "withheld": key in held,
1132
+ "first": ev[0]["time"] if ev else "", "last": ev[-1]["time"] if ev else "",
1133
+ "via": ",".join(sorted({e.get("event", "") for e in ev}))})
1134
+ return rows
1135
+ group = ledger.folder_of if by == "folder" else (lambda rel: rel)
1136
+ rows: dict[str, dict] = {}
1137
+ for key in funcs:
1138
+ r = rows.setdefault(group(key[0]), {by: group(key[0]), "functions": 0, "sent": 0, "secrets": 0,
1139
+ "withheld": 0})
1140
+ r["functions"] += 1
1141
+ r["sent"] += bool(sent.get(key))
1142
+ r["withheld"] += key in held
1143
+ for rel in secret_files:
1144
+ if rel:
1145
+ r = rows.setdefault(group(rel), {by: group(rel), "functions": 0, "sent": 0, "secrets": 0,
1146
+ "withheld": 0})
1147
+ r["secrets"] += 1
1148
+ for r in rows.values():
1149
+ r["share"] = r["sent"] / r["functions"] if r["functions"] else 0.0
1150
+ return [rows[k] for k in sorted(rows)]
1151
+
1152
+ def _data_twin_rel(self, tr: Translator, rel: str) -> str:
1153
+ parts = rel.split("/")
1154
+ stem, dot, ext = parts[-1].rpartition(".")
1155
+ if not dot:
1156
+ stem, ext = parts[-1], ""
1157
+ name = tr.words.get(stem, stem) + (dot + ext if dot else "")
1158
+ return "/".join([tr.words.get(d, d) for d in parts[:-1]] + [name])
1159
+
1160
+ def _copy_data(self, tr: Translator, skipped: list[str], report: ExportReport) -> None:
1161
+ """data_files = "copy": data files in folders the code names (or named themselves) go into
1162
+ the twin under their aliases; folders the code names are created even when empty."""
1163
+ twin = self.twin
1164
+ old = set(self.vault.data.get("data_twin", []))
1165
+ new_files: list[str] = []
1166
+ dirs_twin: set[str] = set()
1167
+ if self.cfg["data_files"] == "copy":
1168
+ for rel in skipped:
1169
+ if rel.endswith((".doppel-merge", ".doppel-incoming", ".cobf-merge", ".cobf-incoming")):
1170
+ continue
1171
+ parts = rel.split("/")
1172
+ stem = parts[-1].rsplit(".", 1)[0]
1173
+ # a package resource (librosa/core/intervals.msgpack, read with importlib.resources): it
1174
+ # sits in a Python package and goes where the package goes in the twin
1175
+ resource = len(parts) > 1 and (self.root / rel).parent.joinpath("__init__.py").is_file()
1176
+ # every folder on the way must be one the code names (relative to the project root),
1177
+ # so a same-named folder somewhere else in the project is never copied
1178
+ if not resource and (not all(d in self.data_dirs for d in parts[:-1]) or (
1179
+ len(parts) == 1 and stem not in self.data_stems)):
1180
+ continue
1181
+ twin_rel = tr.path(rel) if resource else self._data_twin_rel(tr, rel)
1182
+ src, dest = self.root / rel, twin / twin_rel
1183
+ self._check_twin_dest(dest)
1184
+ dest.parent.mkdir(parents=True, exist_ok=True)
1185
+ st = src.stat()
1186
+ if not dest.exists() or dest.stat().st_size != st.st_size or dest.stat().st_mtime < st.st_mtime:
1187
+ shutil.copy2(src, dest)
1188
+ new_files.append(twin_rel)
1189
+ if len(parts) > 1 and not resource: # a package folder holds code: not a data folder
1190
+ dirs_twin.add(twin_rel.rsplit("/", 1)[0])
1191
+ for d in self.data_dirs:
1192
+ p = self.root / d
1193
+ if p.is_dir() and not p.is_symlink():
1194
+ tdir = tr.words.get(d, d)
1195
+ self._check_twin_dest(twin / tdir / ".keep")
1196
+ (twin / tdir).mkdir(parents=True, exist_ok=True)
1197
+ (twin / tdir / ".keep").touch()
1198
+ dirs_twin.add(tdir)
1199
+ for stale in old - set(new_files):
1200
+ p = twin / stale
1201
+ if p.is_file() and not p.is_symlink() and self._inside_twin(p):
1202
+ p.unlink()
1203
+ self.vault.data["data_twin"] = sorted(new_files)
1204
+ self.vault.data["data_dirs_twin"] = sorted(dirs_twin)
1205
+ report.data_files = len(new_files)
1206
+ report.data_dirs = sorted(dirs_twin)
1207
+
1208
+ # -- base snapshots (original-equivalent of the twin at last sync) -----
1209
+ @property
1210
+ def base_dir(self) -> Path:
1211
+ return self.state_dir / "base"
1212
+
1213
+ def _read_base(self, orig_rel: str) -> bytes | None:
1214
+ p = self.base_dir / orig_rel
1215
+ return p.read_bytes() if p.is_file() else None
1216
+
1217
+ def _write_base(self, orig_rel: str, data: bytes) -> None:
1218
+ p = self.base_dir / orig_rel
1219
+ p.parent.mkdir(parents=True, exist_ok=True)
1220
+ p.write_bytes(data)
1221
+
1222
+ # -- twin snapshots (the twin file as DoppelCode last wrote or accepted it) ---
1223
+ @property
1224
+ def twin_base_dir(self) -> Path:
1225
+ return self.state_dir / "twin_base"
1226
+
1227
+ def _write_twin_base(self, twin_rel: str, data: bytes) -> None:
1228
+ p = self.twin_base_dir / twin_rel
1229
+ p.parent.mkdir(parents=True, exist_ok=True)
1230
+ p.write_bytes(data)
1231
+
1232
+ def _old_twin_text(self, orig_rel: str | None, twin_rel: str, mode: str) -> str | None:
1233
+ """The twin file before the AI edited it: the snapshot, or (vaults from before snapshots) the base
1234
+ translated forward again. None for a new file."""
1235
+ p = self.twin_base_dir / twin_rel
1236
+ if p.is_file():
1237
+ return decode(p.read_bytes())
1238
+ base = self._read_base(orig_rel) if orig_rel else None
1239
+ if base is None:
1240
+ return None
1241
+ cfg = self.cfg
1242
+
1243
+ def no_new_ids() -> str:
1244
+ raise LookupError("not in the vault")
1245
+
1246
+ tr = Translator(dict(self.vault.words), set(self.vault.data["stems"]), dict(self.vault.dirs),
1247
+ scrub_comments=cfg["comments"] in ("scrub", "hide"),
1248
+ scrub_strings=cfg["strings"] in ("scrub", "hide"), hide_strings=cfg["strings"] == "hide",
1249
+ string_store=self.vault.data.setdefault("strings", {}), string_alloc=no_new_ids,
1250
+ hide_comments=cfg["comments"] == "hide",
1251
+ comment_store=self.vault.data.setdefault("comments", {}), comment_alloc=no_new_ids)
1252
+ try:
1253
+ return tr.code_source(decode(base), mode)
1254
+ except (LookupError, ValueError):
1255
+ return None
1256
+
1257
+ def _rename_aliases(self, text: str, old: str | None, mode: str, found: list, renames: dict[str, str],
1258
+ aliases: dict[str, str]) -> str:
1259
+ """Apply --rename OLD=new to the AI's twin text. The new real name gets an alias in the vault (an
1260
+ unknown alias the AI coined simply becomes the alias of the new name), and the twin text is
1261
+ rewritten with that alias, so twin, vault and original agree from now on."""
1262
+ used = {f.token: f for f in found if f.token in renames}
1263
+ if not used:
1264
+ return text
1265
+ forbidden = set(self.vault.words)
1266
+ mapping: dict[str, str] = {}
1267
+ for tok, f in used.items():
1268
+ new = renames[tok]
1269
+ kind = aliascheck.KIND_OF_PREFIX.get(tok.split("_")[0], "word")
1270
+ if f.kind == "secret":
1271
+ if new == "@keep": # put the secret back where the AI wrote a literal
1272
+ text = aliascheck.replace_number(text, mode, f.line, f.value, tok)
1273
+ elif new == "@secret": # take the literal, and hide it from the next export on
1274
+ values = list(self.cfg["secret_values"])
1275
+ if f.value not in values:
1276
+ values.append(f.value)
1277
+ self.cfg["secret_values"] = values
1278
+ set_config_value(self.root, "secret_values", values)
1279
+ else:
1280
+ raise DoppelError(f"{tok} is a secret constant: use --rename {tok}=@keep, "
1281
+ f"--rename {tok}=@secret or --accept {tok}")
1282
+ continue
1283
+ if f.kind == "string":
1284
+ if self.cfg["strings"] == "hide":
1285
+ sid = self.vault.new_name(STRING_PREFIX, forbidden)
1286
+ self.vault.data.setdefault("strings", {})[sid] = f'"{new}"'
1287
+ mapping[tok] = sid + strhide.skeleton(new)
1288
+ else:
1289
+ mapping[tok] = new
1290
+ elif new in self.vault.words:
1291
+ mapping[tok] = self.vault.words[new]
1292
+ elif f.kind == "unknown":
1293
+ self.vault.words[new] = tok
1294
+ self.vault.data["kinds"][new] = kind
1295
+ aliases[tok] = new
1296
+ else:
1297
+ alias = self.vault.assign(new, "word" if kind in ("file", "dir", "data") else kind,
1298
+ self.cfg["naming"], forbidden)
1299
+ mapping[tok] = alias
1300
+ aliases[alias] = new
1301
+ if not mapping:
1302
+ return text
1303
+ return aliascheck.apply_renames(text, mode, aliascheck.changed_lines(old, text), mapping)
1304
+
1305
+ def _secret_requests(self) -> list[str]:
1306
+ """The AI edited a twin-only dummy file: report the aliases whose value it wanted to change."""
1307
+ out = []
1308
+ for name, want in self.vault.data.get("twin_only", {}).items():
1309
+ p = self.twin / name
1310
+ if not p.is_file() or p.is_symlink() or sha(p.read_bytes()) == want:
1311
+ continue
1312
+ family = "python" if name.endswith(".py") else "c"
1313
+ rx = r"^(K_\d{4,})\s*=\s*(.+?)\s*$" if family == "python" else r"^#define (K_\d{4,}) (.+?)\s*$"
1314
+ expected = (secretconst.python_twin_module(self._last_dummies(family)) if family == "python"
1315
+ else secretconst.c_twin_header(self._last_dummies(family)))
1316
+ got = dict(re.findall(rx, decode(p.read_bytes()), re.M))
1317
+ plan_dummies = dict(re.findall(rx, expected, re.M))
1318
+ changed = sorted(a for a in set(got) | set(plan_dummies) if got.get(a) != plan_dummies.get(a))
1319
+ out += [f"secret value change requested: {a} (in {name}; ignored - the real value is in the vault)"
1320
+ for a in changed] or [f"{name} was edited (ignored)"]
1321
+ return out
1322
+
1323
+ def _last_dummies(self, family: str) -> dict[str, str]:
1324
+ """alias -> dummy, as the last export wrote them (rebuilt from the vault entries)."""
1325
+ out = {}
1326
+ current = set(self.vault.data.get("secret_sites", {}).values())
1327
+ written = self.vault.data.get("secret_written", {}).get(family)
1328
+ for a, meta in self.vault.data.get("secrets", {}).items():
1329
+ if meta.get("lang") != family or meta.get("type") == "text" or a not in current:
1330
+ continue
1331
+ if written is not None and a not in written:
1332
+ continue
1333
+ site = secretconst.Site(0, 0, meta["literal"], "array" if meta["type"] == "array" else "scalar", 0,
1334
+ count=meta.get("count", 1), is_float=meta["type"] == "float")
1335
+ out[a] = secretconst.python_dummy(site) if family == "python" else secretconst.c_dummy(site)
1336
+ return out
1337
+
1338
+ def _write_alias_review(self, report: "ImportReport") -> Path:
1339
+ path = self.state_dir / "import_review.txt"
1340
+ lines = ["doppel import: these files were NOT merged. The AI wrote names in DoppelCode's alias style that",
1341
+ "would be restored as the wrong real names (or strings). Decide for each one, then run",
1342
+ "import again:", "",
1343
+ " --rename OLD=new give it a real name, e.g. --rename v_0048=nonce",
1344
+ " or for a string: --rename \"str_0013=Decrypt failed\"",
1345
+ " --accept OLD ... keep it as it is (a known alias keeps its vault meaning)",
1346
+ " --accept accept every finding", "",
1347
+ "Files: " + ", ".join(report.refused), ""]
1348
+ lines += report.alias_open
1349
+ path.write_text("\n".join(lines) + "\n", encoding="utf-8")
1350
+ return path
1351
+
1352
+ # -- import ----------------------------------------------------------
1353
+ _RESERVED = {"con", "prn", "aux", "nul", *(f"com{i}" for i in range(1, 10)), *(f"lpt{i}" for i in range(1, 10))}
1354
+
1355
+ def _new_file_risk(self, rel: str) -> str:
1356
+ """Why a file the AI created must not be imported ('' = fine). Only C sources and known text
1357
+ files are accepted; scripts, executables and anything in hidden folders (.github, .vscode,
1358
+ .git, ...) could run on this PC when you build, open the folder or push."""
1359
+ parts = rel.split("/")
1360
+ if rel.startswith(("/", "\\")) or ":" in parts[0] or ".." in parts:
1361
+ return "path leaves the project"
1362
+ if any(p.startswith(".") for p in parts):
1363
+ return "hidden file or folder (tool / CI configuration)"
1364
+ if parts[-1].split(".")[0].lower() in self._RESERVED:
1365
+ return "reserved Windows device name"
1366
+ if parts[-1].lower().endswith(SCRIPT_EXTENSIONS):
1367
+ return "a script (scripts the AI writes are never imported; existing ones are copied for the build)"
1368
+ mode = self._mode_for(rel)
1369
+ if mode is None:
1370
+ return "not a source or known text file (scripts and binaries are never imported)"
1371
+ if is_code(mode) and mode not in {b["mode"] for b in self.vault.baseline.values()}:
1372
+ return f"a {LANGUAGES[mode].title} file, but the project has no {LANGUAGES[mode].title} sources"
1373
+ return ""
1374
+
1375
+ def _is_build_file(self, rel: str) -> bool:
1376
+ """Changes the AI made to these are listed for review: they run when you build."""
1377
+ name = rel.rsplit("/", 1)[-1]
1378
+ if "." not in name and (self.root / rel).is_file() and (self.root / rel).read_bytes()[:2] == b"#!":
1379
+ return True # a script without an extension
1380
+ return name in self.cfg["text_filenames"] or name.lower().endswith(
1381
+ (".mk", ".cmake", ".ld", ".json", ".yml", ".yaml", ".cfg", ".ini", ".in", ".am", ".ac", ".inc",
1382
+ ".toml") + SCRIPT_EXTENSIONS)
1383
+
1384
+ def _restore(self, rtr: Translator, mode: str, data: bytes, rel: str = "") -> bytes:
1385
+ if mode == "excluded":
1386
+ return data
1387
+ if is_code(mode):
1388
+ text = decode(data)
1389
+ if mode == "python":
1390
+ text = secretconst.strip_python_import(text)
1391
+ elif mode in ("c", "cpp"):
1392
+ text = secretconst.strip_c_include(text)
1393
+ out = rtr.code_source(text, mode)
1394
+ if mode in withhold.LANGS:
1395
+ out = withhold.restore(out, self.vault.data.get("withheld", {}))
1396
+ return encode(out)
1397
+ try:
1398
+ text = data.decode("utf-8")
1399
+ except UnicodeDecodeError:
1400
+ return data
1401
+ store = self.vault.data.get("abs_paths", {})
1402
+ # build files: '-DM_0001' is the flag form of the macro M_0001 (-D / -U), restored like the code
1403
+ if rel and self._has_hash_comments(rel):
1404
+ restored = rtr.build_text(text)
1405
+ elif rel and self._is_packaging(rel):
1406
+ restored = rtr.path_text(text)
1407
+ else:
1408
+ restored = rtr.text(text)
1409
+ out = rtr.restore_build_comments(restored)
1410
+ if store:
1411
+ out = ABS_PATH_ID_RE.sub(lambda m: store.get(m.group(1), m.group(0)), out)
1412
+ return encode(out)
1413
+
1414
+ def _preview_folder(self, folder: Path) -> Path:
1415
+ """The folder for ``import --preview``: outside the project and the twin, and empty or an earlier
1416
+ preview (recognised by its manifest), which is cleared."""
1417
+ dest = Path(folder).resolve()
1418
+ for name, other in (("project", self.root), ("twin", self.twin.resolve())):
1419
+ if dest == other or other in dest.parents or dest in other.parents:
1420
+ raise DoppelError(f"the preview folder must be outside the {name} folder: {dest}")
1421
+ if Path(folder).is_symlink():
1422
+ raise DoppelError(f"the preview folder is a link: {folder}")
1423
+ if dest.exists():
1424
+ if not dest.is_dir():
1425
+ raise DoppelError(f"the preview folder is a file: {dest}")
1426
+ if any(dest.iterdir()):
1427
+ if not (dest / PREVIEW_MANIFEST).is_file():
1428
+ raise DoppelError(f"the preview folder is not empty and holds no earlier preview: {dest}")
1429
+ shutil.rmtree(dest)
1430
+ dest.mkdir(parents=True, exist_ok=True)
1431
+ return dest
1432
+
1433
+ def import_changes(self, to: Path | None = None, dry_run: bool = False, apply_deletes: bool = False,
1434
+ renames: dict[str, str] | None = None, accept: bool | list[str] = False,
1435
+ preview: Path | None = None, only: set[str] | None = None) -> ImportReport:
1436
+ """``renames`` / ``accept`` resolve alias findings (see aliascheck); accept=True accepts all.
1437
+
1438
+ ``preview``: write what the import would write (the merged files, and ``<file>.doppel-merge`` /
1439
+ ``.doppel-incoming`` for conflicts) to this folder, at the same relative paths, plus a manifest
1440
+ (PREVIEW_MANIFEST) for ``apply_preview``. Nothing in the project, the twin or the vault changes.
1441
+ ``only``: import only these original files (paths relative to the project)."""
1442
+ if not self.vault.exists:
1443
+ raise DoppelError("no vault found - run 'export' first")
1444
+ twin = self.twin
1445
+ if not twin.is_dir():
1446
+ raise DoppelError(f"twin folder not found: {twin}")
1447
+ if preview is not None:
1448
+ if to is not None or dry_run or apply_deletes:
1449
+ raise DoppelError("--preview cannot be combined with --to, --dry-run or --apply-deletes")
1450
+ if any(v == "@secret" for v in (renames or {}).values()):
1451
+ raise DoppelError("--rename OLD=@secret changes .doppel/config.json: not possible with --preview")
1452
+ preview = self._preview_folder(preview)
1453
+ writes = to is None and not dry_run and preview is None # the project, the twin and the vault
1454
+ rtr = self.reverse_translator()
1455
+ baseline = self.vault.baseline
1456
+ by_twin = {b["twin"]: o for o, b in baseline.items()}
1457
+ known_idents = set(self.vault.data["twin_idents"])
1458
+ generated = set(self.vault.words.values())
1459
+ dest_root = Path(to).resolve() if to else self.root
1460
+ report = ImportReport()
1461
+ if preview is not None:
1462
+ report.preview_dir = str(preview)
1463
+ current = self._twin_files()
1464
+ renames = dict(renames or {})
1465
+ accepted = set() if accept is True or not accept else set(accept)
1466
+ aliases = {a: o for o, a in self.vault.words.items()}
1467
+ aliases.update({a: o for o, a in self.vault.dirs.items()})
1468
+ secret_store = self.vault.data.get("secrets", {})
1469
+ aliases.update({a: s["literal"] for a, s in secret_store.items()})
1470
+ strings_store = self.vault.data.setdefault("strings", {})
1471
+ vault_changed = False
1472
+ report.secret_requests = self._secret_requests()
1473
+
1474
+ report.unsafe = list(self.twin_unsafe)
1475
+ for twin_rel, path in current.items():
1476
+ data = path.read_bytes()
1477
+ twin_sha = disk_sha = sha(data)
1478
+ orig_rel = by_twin.get(twin_rel)
1479
+ if orig_rel is not None and baseline[orig_rel]["twin_sha"] == twin_sha:
1480
+ continue
1481
+ if only is not None and (orig_rel if orig_rel is not None else rtr.path(twin_rel)) not in only:
1482
+ continue
1483
+ if orig_rel is None:
1484
+ orig_rel = rtr.path(twin_rel)
1485
+ why = self._new_file_risk(orig_rel)
1486
+ if why:
1487
+ report.blocked.append(f"{orig_rel} ({why})")
1488
+ continue
1489
+ mode = self._mode_for(orig_rel)
1490
+ is_new = True
1491
+ else:
1492
+ mode = baseline[orig_rel]["mode"]
1493
+ is_new = False
1494
+ if is_code(mode):
1495
+ # Alias-shaped names the AI coined itself would be restored as the wrong real names.
1496
+ text = decode(data)
1497
+ old = None if is_new else self._old_twin_text(orig_rel, twin_rel, mode)
1498
+ found = aliascheck.find(twin_rel, old, text, mode, aliases, strings_store, set(secret_store))
1499
+ report.alias_warnings += aliascheck.reused_in_new_functions(twin_rel, old, text, mode, aliases)
1500
+ if old is not None and mode in withhold.LANGS:
1501
+ held = self.vault.data.get("withheld", {})
1502
+ for bid in sorted(withhold.stub_ids(old) - withhold.stub_ids(text)):
1503
+ line = next((i for i, l in enumerate(old.splitlines(), 1) if bid in l), 1)
1504
+ found.append(aliascheck.Finding(twin_rel, line, bid, "withheld",
1505
+ held.get(bid, {}).get("symbol", "?")))
1506
+ still_open = [] if accept is True else [f for f in found
1507
+ if f.token not in renames and f.token not in accepted]
1508
+ if still_open:
1509
+ report.alias_open += [f.describe() for f in still_open]
1510
+ report.refused.append(orig_rel)
1511
+ continue
1512
+ report.alias_resolved += [f.describe() + (f" -> renamed to {renames[f.token]}"
1513
+ if f.token in renames else " -> accepted")
1514
+ for f in found]
1515
+ new_text = self._rename_aliases(text, old, mode, found, renames, aliases)
1516
+ # comments the AI dropped while returning whole functions come back (cmt_ placeholders)
1517
+ new_text, kept = commentkeep.keep(old, new_text)
1518
+ if kept:
1519
+ report.comments_kept.append(f"{orig_rel}: {kept} comment(s)")
1520
+ if any(f.token in renames for f in found):
1521
+ vault_changed = True
1522
+ rtr = self.reverse_translator()
1523
+ if new_text != text:
1524
+ data = encode(new_text)
1525
+ twin_sha = sha(data)
1526
+ report.twin_updated.append(twin_rel)
1527
+ if writes:
1528
+ self._check_twin_dest(path)
1529
+ path.write_bytes(data)
1530
+ (report.new if is_new else report.changed).append(orig_rel)
1531
+ if self._is_build_file(orig_rel):
1532
+ report.review.append(orig_rel)
1533
+ if is_code(mode):
1534
+ for t in lexer.tokenize(decode(data), mode):
1535
+ if t.kind == lexer.IDENT and t.text not in known_idents and t.text not in generated \
1536
+ and not _language_word(t.text, mode):
1537
+ report.new_identifiers.add(rtr.word(t.text))
1538
+ restored = self._restore(rtr, mode, data, orig_rel)
1539
+ if not is_new:
1540
+ # the AI's editor saved a non-UTF-8 file as UTF-8: untouched lines keep the original's bytes
1541
+ fix = encodingfix.repair(restored, self._read_base(orig_rel))
1542
+ if fix.lines:
1543
+ restored = fix.data
1544
+ note = f"{orig_rel}: {fix.lines} unchanged line(s) kept in the original's encoding"
1545
+ if fix.encoding:
1546
+ note += f" ({fix.encoding}" + (f", {fix.reencoded} changed line(s) written in it"
1547
+ if fix.reencoded else "") + ")"
1548
+ if fix.left_utf8:
1549
+ note += f"; {fix.left_utf8} changed line(s) left in UTF-8 (characters it does not have)"
1550
+ report.encoding_kept.append(note)
1551
+ if to is not None: # review folder: just write the AI version
1552
+ if not dry_run:
1553
+ dest = dest_root / orig_rel
1554
+ dest.parent.mkdir(parents=True, exist_ok=True)
1555
+ dest.write_bytes(restored)
1556
+ continue
1557
+
1558
+ # Apply the AI's change to the original as a 3-way merge:
1559
+ # base = original-equivalent of the twin at last sync, theirs = AI version, ours = original now.
1560
+ dest = self.root / orig_rel
1561
+ ours = dest.read_bytes() if dest.exists() else None
1562
+ base = self._read_base(orig_rel)
1563
+ if ours is None:
1564
+ result, merged = ("theirs", restored) if base is None else ("nomerge", restored)
1565
+ else:
1566
+ result, merged = merge.merge3(ours, base, restored, label=orig_rel)
1567
+ if result == "merged":
1568
+ report.merged.append(orig_rel)
1569
+ elif result in ("conflict", "nomerge"):
1570
+ report.conflicts.append(orig_rel)
1571
+ if dry_run:
1572
+ continue
1573
+ if preview is not None:
1574
+ self._write_preview(preview, report, orig_rel, twin_rel, result, merged, disk_sha,
1575
+ sha(ours) if ours is not None else "", is_new)
1576
+ continue
1577
+
1578
+ if result in ("theirs", "merged"):
1579
+ dest.parent.mkdir(parents=True, exist_ok=True)
1580
+ dest.write_bytes(merged)
1581
+ elif result in ("conflict", "nomerge"):
1582
+ # Original stays untouched; the merge (with markers) or AI version goes next to it.
1583
+ suffix = ".doppel-merge" if result == "conflict" else ".doppel-incoming"
1584
+ dest.with_name(dest.name + suffix).write_bytes(merged)
1585
+ self._write_base(orig_rel, restored)
1586
+ self._write_twin_base(twin_rel, data)
1587
+ entry = baseline.setdefault(orig_rel, {"twin": twin_rel, "mode": mode})
1588
+ entry["twin_sha"] = twin_sha
1589
+ entry["orig_sha"] = sha(dest.read_bytes()) if dest.exists() else ""
1590
+ if is_code(mode):
1591
+ known_idents.update(t.text for t in lexer.tokenize(decode(data), mode)
1592
+ if t.kind == lexer.IDENT)
1593
+
1594
+ for twin_rel, orig_rel in by_twin.items():
1595
+ if twin_rel in current or (only is not None and orig_rel not in only):
1596
+ continue
1597
+ report.deleted.append(orig_rel)
1598
+ if apply_deletes and writes:
1599
+ dest = self.root / orig_rel
1600
+ if dest.exists() and sha(dest.read_bytes()) == baseline[orig_rel]["orig_sha"]:
1601
+ dest.unlink()
1602
+ report.removed.append(orig_rel)
1603
+ del baseline[orig_rel]
1604
+
1605
+ if preview is not None:
1606
+ manifest = {"version": 1, "project": str(self.root), "twin": str(twin),
1607
+ "renames": renames, "accept": True if accept is True else sorted(accepted),
1608
+ "files": report.preview_files, "refused": report.refused, "deleted": report.deleted,
1609
+ "blocked": report.blocked}
1610
+ (preview / PREVIEW_MANIFEST).write_text(json.dumps(manifest, indent=1), encoding="utf-8")
1611
+ return report
1612
+ if report.refused and not dry_run:
1613
+ report.review_file = str(self._write_alias_review(report))
1614
+ if writes:
1615
+ self.vault.data["twin_idents"] = sorted(known_idents)
1616
+ self.vault.save()
1617
+ elif vault_changed and not dry_run:
1618
+ self.vault.save() # review folder: the new names must still be known next time
1619
+ return report
1620
+
1621
+ def _write_preview(self, folder: Path, report: ImportReport, orig_rel: str, twin_rel: str, result: str,
1622
+ merged: bytes, twin_sha: str, orig_sha: str, is_new: bool) -> None:
1623
+ """One file of ``import --preview``: what the import would write, at the same relative path."""
1624
+ name = orig_rel + {"conflict": ".doppel-merge", "nomerge": ".doppel-incoming"}.get(result, "")
1625
+ dest = (folder / name).resolve()
1626
+ if folder not in dest.parents:
1627
+ raise DoppelError(f"refusing to write {name}: outside the preview folder")
1628
+ dest.parent.mkdir(parents=True, exist_ok=True)
1629
+ dest.write_bytes(merged)
1630
+ status = ("conflict" if result in ("conflict", "nomerge") else "merged" if result == "merged"
1631
+ else "new" if is_new else "changed")
1632
+ report.preview_files.append({"file": orig_rel, "twin": twin_rel, "status": status, "preview": name,
1633
+ "twin_sha": twin_sha, "orig_sha": orig_sha})
1634
+
1635
+ def apply_preview(self, folder: Path, only: list[str] | None = None) -> ImportReport:
1636
+ """Import exactly what ``import --preview`` showed: the files of its manifest (or ``only`` some), with
1637
+ its --rename / --accept. Refuses when a twin file or an original changed since the preview."""
1638
+ folder = Path(folder).resolve()
1639
+ try:
1640
+ manifest = json.loads((folder / PREVIEW_MANIFEST).read_text(encoding="utf-8"))
1641
+ except (OSError, ValueError) as e:
1642
+ raise DoppelError(f"no preview in {folder} ({e.__class__.__name__}): run 'import --preview' first")
1643
+ if Path(manifest.get("project", "")).resolve() != self.root:
1644
+ raise DoppelError(f"the preview in {folder} is for another project: {manifest.get('project')}")
1645
+ entries = {e["file"]: e for e in manifest.get("files", [])}
1646
+ wanted = list(entries) if not only else list(dict.fromkeys(only))
1647
+ unknown = [f for f in wanted if f not in entries]
1648
+ if unknown:
1649
+ raise DoppelError("not in the preview (already applied, or not changed): " + ", ".join(unknown))
1650
+ if not wanted:
1651
+ raise DoppelError("the preview has no files left to apply")
1652
+ stale = []
1653
+ for f in wanted:
1654
+ e = entries[f]
1655
+ t, o = self.twin / e["twin"], self.root / f
1656
+ if (sha(t.read_bytes()) if t.is_file() else "") != e["twin_sha"] or \
1657
+ (sha(o.read_bytes()) if o.is_file() else "") != e["orig_sha"]:
1658
+ stale.append(f)
1659
+ if stale:
1660
+ raise DoppelError("changed since the preview (in the twin or in the original): " + ", ".join(stale)
1661
+ + ". Run the preview again.")
1662
+ rep = self.import_changes(renames=manifest.get("renames") or {}, accept=manifest.get("accept") or False,
1663
+ only=set(wanted))
1664
+ manifest["files"] = [e for f, e in entries.items() if f not in wanted]
1665
+ (folder / PREVIEW_MANIFEST).write_text(json.dumps(manifest, indent=1), encoding="utf-8")
1666
+ return rep
1667
+
1668
+ # -- check -----------------------------------------------------------
1669
+ def check(self, compile_check: bool = True, objects: bool = False) -> CheckReport:
1670
+ rep = CheckReport()
1671
+ if not self.vault.exists or not self.twin.is_dir():
1672
+ raise DoppelError("no twin yet - run 'export' first")
1673
+ files, skipped = self.scan()
1674
+ tr = self.build_mapping(files, other_files=skipped) # does not change existing names
1675
+ rtr = self.reverse_translator()
1676
+
1677
+ # 1. Round trip of the current original through forward + reverse.
1678
+ for f in files:
1679
+ twin_rel, data = self.forward(tr, f)
1680
+ back = self._restore(rtr, "excluded" if f.excluded else f.mode, data, f.rel)
1681
+ if back != f.data or rtr.path(twin_rel) != f.rel:
1682
+ rep.roundtrip_failures.append(f.rel)
1683
+
1684
+ # 2. Leak scan of the twin as it is now: renamed names, sensitive terms, and - always - the
1685
+ # project folder name, the Windows user name and absolute paths (they reveal people and repos).
1686
+ allow = {w.lower() for w in self.cfg.get("leak_allow") or []}
1687
+ renamed = {w for w in tr.words if len(w) >= 4 and w.lower() not in allow}
1688
+ terms = [t for t in [t.lower() for t in self.cfg["sensitive_terms"]] + (
1689
+ [self.root.name.lower()] if len(self.root.name) >= 4 else []) if t not in allow]
1690
+ # The Windows user name only as a path segment, an e-mail or a handle (a user "root" or "eli" must
1691
+ # not flag "rooted" or "delimiter").
1692
+ user_re = None
1693
+ with __import__("contextlib").suppress(Exception):
1694
+ user = getpass.getuser()
1695
+ if len(user) >= 3:
1696
+ u = re.escape(user)
1697
+ user_re = re.compile(rf"(?i)(?:(?<=[\\/])|(?<=@)){u}(?=[\\/]|$|[\s\"'])|(?<![\w.]){u}@[\w-]")
1698
+ # Prose that spells a renamed name out ("goertzel detect", "Detect-Symbol"): a hint, not a failure.
1699
+ phrases = {tuple(ps): w for w in tr.words if kinds_ok(self.vault.data["kinds"].get(w))
1700
+ for ps in [_name_words(w)] if len(ps) >= 2 and sum(map(len, ps)) >= 8}
1701
+ excluded_twin = {b["twin"] for b in self.vault.baseline.values() if b["mode"] == "excluded"}
1702
+ # strings: scrub keeps user-facing text, which can tell what protected code does (pilot round 2:
1703
+ # "ACCURATE REAL-TIME GENDER VOICE DETECTOR"): one warning, with the longest such string as example
1704
+ scrub_warning = self.cfg["strings"] == "scrub" and any(self.cfg.get(k) for k in PROTECTION_KEYS)
1705
+ example, example_words = "", 0
1706
+ # Build files are also scanned for parts of renamed names ("falcon" in TARGET := falcon_selftest).
1707
+ kinds = self.vault.data["kinds"]
1708
+ parts = name_parts(w for w in tr.words if kinds.get(w) in CODE_KINDS) - allow
1709
+ orig_of = {b["twin"]: o for o, b in self.vault.baseline.items()}
1710
+ items_of: dict[tuple[str, int], set[tuple[str, str]]] = {}
1711
+ for rel, path in self._twin_files().items():
1712
+ build = self._has_hash_comments(orig_of.get(rel, rel))
1713
+ hits = [rel] if any(t in rel.lower() for t in terms) else []
1714
+ if rel in excluded_twin:
1715
+ continue
1716
+ mode = self.vault.baseline.get(orig_of.get(rel, ""), {}).get("mode")
1717
+ for lineno, line in enumerate(decode(path.read_bytes()).splitlines(), 1):
1718
+ low = line.lower()
1719
+ # C / C++: '#endif', '#include "config.h"' are not names, even when a Python file of the
1720
+ # project has a variable 'endif' that got renamed (libopus: 2,236 false leak lines)
1721
+ words = WORD_RE.findall(_PP_DIRECTIVE_RE.sub("", line) if mode in ("c", "cpp") else line)
1722
+ if build: # 'endif()', 'set(' are the build language's words
1723
+ keep = build_language_words(line, self._is_cmake(orig_of.get(rel, rel)))
1724
+ words = [m.group(0) for m in WORD_RE.finditer(line) if m.start() not in keep]
1725
+ found = ({("file name" if tr.words[w].startswith(("file_", "dir_")) else "renamed name", w)
1726
+ for w in words if w in renamed}
1727
+ | ({("name part", f"name part '{p}' in {w}") for w in words for p in word_parts(w) & parts}
1728
+ if build else set())
1729
+ | {("sensitive term", t) for t in terms if t in low}
1730
+ | ({("user name", "user name")} if user_re and user_re.search(line) else set())
1731
+ | {("absolute path", "absolute path " + m.group(0)[:60]) for m in ABS_PATH_RE.finditer(line)})
1732
+ if found:
1733
+ items_of.setdefault((rel, lineno), set()).update(found)
1734
+ if phrases:
1735
+ seq = [p for w in words for p in _name_words(w)]
1736
+ for n in {len(k) for k in phrases}:
1737
+ for i in range(len(seq) - n + 1):
1738
+ name = phrases.get(tuple(seq[i:i + n]))
1739
+ if name:
1740
+ rep.hints.append(f"{rel}:{lineno}: '{' '.join(seq[i:i + n])}' spells out "
1741
+ f"the name {name} ({tr.words[name]})")
1742
+ for h in hits:
1743
+ items_of.setdefault((h, 0), set()).add(("sensitive term", "file name contains a sensitive term"))
1744
+ mode = self.vault.baseline.get(orig_of.get(rel, ""), {}).get("mode")
1745
+ if scrub_warning and mode and is_code(mode):
1746
+ for t in lexer.tokenize(decode(path.read_bytes()), mode):
1747
+ words = re.findall(r"[^\W\d_]{3,}", t.text) if t.kind == lexer.STRING else []
1748
+ if len(words) >= 3 and not STRING_ID_RE.search(t.text) and len(words) > example_words:
1749
+ example, example_words = t.text, len(words)
1750
+ if tr.secret_plan.active:
1751
+ mode = self.vault.baseline.get(orig_of.get(rel, ""), {}).get("mode")
1752
+ lang = mode if mode and is_code(mode) else None
1753
+ for line, value in secretconst.leak_hits(decode(path.read_bytes()), lang, tr.secret_plan.scalars,
1754
+ tr.secret_plan.arrays, tr.secret_plan.table_values):
1755
+ items_of.setdefault((rel, line), set()).add(("secret value", f"secret value {value}"))
1756
+ rank = {k: i for i, k in enumerate(LEAK_KINDS)}
1757
+ for (rel, lineno), found in sorted(items_of.items(), key=lambda kv: (
1758
+ min(rank[k] for k, _ in kv[1]), kv[0][0], kv[0][1])):
1759
+ ordered = sorted(found, key=lambda kt: (rank[kt[0]], kt[1]))
1760
+ rep.leak_items.append((rel, lineno, ordered))
1761
+ rep.leaks.append(f"{rel}{f':{lineno}' if lineno else ''}: {', '.join(t for _, t in ordered)}")
1762
+ # the full list next to the vault: the console shows a summary (doppel check --leaks-all for all)
1763
+ with __import__("contextlib").suppress(OSError):
1764
+ out = self.state_dir / "leaks.txt"
1765
+ out.write_text("".join(f"{l}\n" for l in rep.leaks)
1766
+ + ("\n# hints: names spelled out in prose\n" + "".join(f"{h}\n" for h in rep.hints)
1767
+ if rep.hints else ""), encoding="utf-8")
1768
+ rep.leaks_file = str(out)
1769
+
1770
+ # A build file that builds a source path from a variable (CMake: ${FEATURE}.c) cannot find the renamed
1771
+ # file in the twin (libopus: c_feature_check(VLA) -> vla.c, but the twin has mod_0069.c)
1772
+ if self.cfg["rename_files"]:
1773
+ computed = sorted(rel for rel in self.vault.baseline if self._has_hash_comments(rel)
1774
+ and _COMPUTED_PATH_RE.search(decode((self.root / rel).read_bytes())))
1775
+ if computed:
1776
+ rep.warnings.append(
1777
+ f"{len(computed)} build file(s) build a file name from a variable "
1778
+ f"({', '.join(computed[:5])}{', ...' if len(computed) > 5 else ''}): the twin's renamed files "
1779
+ 'will not be found by the project\'s own build. Set "rename_files": false in .doppel/config.json '
1780
+ "to keep file and folder names (identifiers are still renamed).")
1781
+ if scrub_warning:
1782
+ shown = example.encode("ascii", "backslashreplace").decode("ascii")
1783
+ shown = shown if len(shown) <= 70 else shown[:67] + "..."
1784
+ rep.warnings.append("strings: scrub with protected code - user-facing strings stay readable and can tell "
1785
+ f"what the protected code does{f' (e.g. {shown})' if example else ''}. "
1786
+ 'Set "strings": "hide" in .doppel/config.json.')
1787
+
1788
+ # 3. Compile check (original vs twin).
1789
+ if compile_check:
1790
+ compiler = headers.find_compiler(self.cfg["compiler"])
1791
+ rep.compiler = compiler
1792
+ rep.c_files = sum(b["mode"] in ("c", "cpp") for b in self.vault.baseline.values())
1793
+ if compiler:
1794
+ self._compile_compare(compiler, rep, objects, tr, files)
1795
+ # 4. Python: the twin must parse and be the same syntax tree once names are mapped back.
1796
+ self._python_compare(rtr, rep)
1797
+ # 5. Java, C#, JavaScript / TypeScript: the twin must build wherever the original builds.
1798
+ self._toolchain_compare(rep)
1799
+ return rep
1800
+
1801
+ def _toolchain_compare(self, rep: CheckReport) -> None:
1802
+ groups: dict[str, list[tuple[str, Path, Path]]] = {}
1803
+ for orig_rel, b in sorted(self.vault.baseline.items()):
1804
+ key = {"java": "java", "csharp": "csharp", "javascript": "js", "typescript": "js"}.get(b["mode"])
1805
+ o_path, t_path = self.root / orig_rel, self.twin / b["twin"]
1806
+ if key and o_path.is_file() and t_path.is_file() and self._inside_twin(t_path):
1807
+ groups.setdefault(key, []).append((orig_rel, o_path, t_path))
1808
+ if not groups:
1809
+ return
1810
+ with tempfile.TemporaryDirectory(prefix="doppel_build_") as tmp:
1811
+ tmp = Path(tmp)
1812
+ for key, items in groups.items():
1813
+ try:
1814
+ self._build_group(key, items, tmp / key, rep)
1815
+ except (OSError, RuntimeError, subprocess.SubprocessError) as e:
1816
+ rep.not_checked += [f"{rel}: the {key} check failed to run ({e})" for rel, _, _ in items]
1817
+
1818
+ def _build_group(self, key: str, items: list, work: Path, rep: CheckReport) -> None:
1819
+ work.mkdir(parents=True)
1820
+ origs, twins = [o for _, o, _ in items], [t for _, _, t in items]
1821
+ rels = [rel for rel, _, _ in items]
1822
+ if key == "js":
1823
+ tool = toolchains.find_node(self.cfg["node"])
1824
+ if not tool:
1825
+ rep.not_checked += [f"{r}: no Node.js found (install Node or VS Code)" for r in rels]
1826
+ return
1827
+ o_res = toolchains.node_syntax(tool, origs, work)
1828
+ t_res = toolchains.node_syntax(tool, twins, work)
1829
+ checked = 0
1830
+ for rel, o, t in items:
1831
+ if o_res.get(str(o)):
1832
+ rep.not_checked.append(f"{rel}: the original does not compile with {tool.name} "
1833
+ f"({o_res[str(o)][:120]})")
1834
+ elif t_res.get(str(t)):
1835
+ rep.compile_errors.append(f"{self._twin_rel(t)}: {t_res[str(t)]}")
1836
+ else:
1837
+ checked += 1
1838
+ rep.builds.append(f"js/ts: {checked} file(s) compiled (syntax; the code is not run) [{tool.name}]")
1839
+ return
1840
+ if key == "java":
1841
+ tool = toolchains.find_javac(self.cfg["javac"])
1842
+ if not tool:
1843
+ rep.not_checked += [f"{r}: no Java compiler found (install a JDK or set \"javac\")" for r in rels]
1844
+ return
1845
+ ok, errs = toolchains.javac(tool, origs, work / "orig")
1846
+ target = ""
1847
+ else:
1848
+ tool = toolchains.find_csc(self.cfg["csc"])
1849
+ if not tool:
1850
+ rep.not_checked += [f"{r}: no C# compiler found (install the .NET SDK or set \"csc\")" for r in rels]
1851
+ return
1852
+ ok, errs, target = toolchains.csc(tool, origs, work / "orig")
1853
+ if not ok:
1854
+ why = self._short(errs[0], self.root)[:160] if errs else "errors"
1855
+ hint = " - install the .NET SDK for newer C#" if tool.kind == "framework" else ""
1856
+ rep.not_checked += [f"{r}: the original does not compile with {tool.name}{hint} ({why})" for r in rels]
1857
+ return
1858
+ if key == "java":
1859
+ t_ok, t_errs = toolchains.javac(tool, twins, work / "twin")
1860
+ else:
1861
+ t_ok, t_errs, _ = toolchains.csc(tool, twins, work / "twin", target)
1862
+ rep.compile_errors += [self._short(e, self.twin) for e in t_errs]
1863
+ if not t_ok and not t_errs:
1864
+ rep.compile_errors.append(f"{key}: the twin does not compile")
1865
+ label = "java: " if key == "java" else "c#: "
1866
+ rep.builds.append(f"{label} {len(items)} file(s) compiled, "
1867
+ f"{'twin OK' if t_ok else 'twin FAILS'} [{tool.name.splitlines()[0]}]")
1868
+
1869
+ @staticmethod
1870
+ def _short(msg: str, base: Path) -> str:
1871
+ """Compiler message with the folder prefix removed (the paths are long and reveal the location)."""
1872
+ for form in (str(base), str(base).replace("\\", "/")):
1873
+ for variant in (form, form[:1].lower() + form[1:], form[:1].upper() + form[1:]):
1874
+ msg = msg.replace(variant + "\\", "").replace(variant + "/", "")
1875
+ return msg
1876
+
1877
+ def _twin_rel(self, path: Path) -> str:
1878
+ try:
1879
+ return path.relative_to(self.twin).as_posix()
1880
+ except ValueError:
1881
+ return str(path)
1882
+
1883
+ def _python_compare(self, rtr: Translator, rep: CheckReport) -> None:
1884
+ hide_strings = self.cfg["strings"] == "hide"
1885
+ for orig_rel, b in self.vault.baseline.items():
1886
+ if b["mode"] != "python":
1887
+ continue
1888
+ o_path, t_path = self.root / orig_rel, self.twin / b["twin"]
1889
+ if not (o_path.is_file() and t_path.is_file()) or not self._inside_twin(t_path):
1890
+ continue
1891
+ try:
1892
+ o_tree = pyparse.parse(decode(o_path.read_bytes()))
1893
+ except SyntaxError as e:
1894
+ rep.not_checked.append(f"{orig_rel}: the original does not parse ({e.msg}, line {e.lineno})")
1895
+ continue
1896
+ try:
1897
+ t_tree = pyparse.parse(decode(t_path.read_bytes()))
1898
+ except SyntaxError as e:
1899
+ rep.python_differ.append(f"{b['twin']}: syntax error in the twin ({e.msg}, line {e.lineno})")
1900
+ continue
1901
+ t_tree = _python_secrets_back(t_tree, self.vault.data.get("secrets", {}))
1902
+ held = {m["symbol"] for b, m in self.vault.data.get("withheld", {}).items()
1903
+ if m.get("file") == orig_rel and b in withhold.stub_ids(decode(t_path.read_bytes()))}
1904
+ if held:
1905
+ _python_withheld_bodies(o_tree, held)
1906
+ _python_twin_stubs(t_tree)
1907
+ _python_names_back(t_tree, rtr)
1908
+ if hide_strings:
1909
+ for tree in (o_tree, t_tree):
1910
+ for node in ast.walk(tree):
1911
+ if isinstance(node, ast.Constant) and isinstance(node.value, (str, bytes)):
1912
+ node.value = type(node.value)() # b"..." is hidden like "..."
1913
+ elif isinstance(node, ast.JoinedStr):
1914
+ # f"Pitch: {p:.1f} Hz" -> f"str_0005 {p:.1f}": the text pieces differ in number,
1915
+ # the fields (and their format specs) must not
1916
+ node.values = [v for v in node.values if not isinstance(v, ast.Constant)]
1917
+ rep.python_checked += 1
1918
+ if ast.dump(o_tree) != ast.dump(t_tree):
1919
+ rep.python_differ.append(f"{orig_rel}: the twin's syntax tree differs from the original")
1920
+
1921
+ def _compile_compare(self, compiler: str, rep: CheckReport, objects: bool,
1922
+ tr: Translator | None = None, files: list | None = None) -> None:
1923
+ # The twin is AI-written: an #include of "\\\\server\\share\\x.h" makes Windows connect to that
1924
+ # server (and offer the user's login hash); an absolute include reads local files into errors.
1925
+ # '..' is fine while it stays inside the twin (celt/arm/x.c: #include "../y.h"), checked against the
1926
+ # twin's real files; a symlink inside the twin does not count as a file.
1927
+ twin_files = {r for r, p in self._twin_files().items() if p.is_file() and not p.is_symlink()}
1928
+ header_ext = (".h", ".hpp", ".hh", ".hxx", ".h++", ".inl", ".ipp", ".tpp")
1929
+ inc_dirs = sorted({b["twin"].rsplit("/", 1)[0] if "/" in b["twin"] else ""
1930
+ for b in self.vault.baseline.values() if b["twin"].lower().endswith(header_ext)})
1931
+ for b in self.vault.baseline.values():
1932
+ p = self.twin / b["twin"]
1933
+ if b["mode"] in ("c", "cpp") and p.is_file() and not p.is_symlink():
1934
+ for target in unsafe_includes(decode(p.read_bytes()), b["twin"].count("/"), b["twin"],
1935
+ twin_files.__contains__, inc_dirs):
1936
+ rep.unsafe_includes.append(f"{b['twin']}: #include {target}")
1937
+ for rel in self._twin_files():
1938
+ if rel not in {b["twin"] for b in self.vault.baseline.values()} and \
1939
+ languages.for_path(rel) in ("c", "cpp"):
1940
+ for target in unsafe_includes(decode((self.twin / rel).read_bytes()), rel.count("/"), rel,
1941
+ twin_files.__contains__, inc_dirs):
1942
+ rep.unsafe_includes.append(f"{rel}: #include {target}")
1943
+ if rep.unsafe_includes:
1944
+ return # do not run the compiler on this twin at all
1945
+ env = headers.compiler_env(compiler)
1946
+ flags = list(self.cfg["compile_flags"])
1947
+ source_ext = (".c", ".cpp", ".cc", ".cxx", ".c++")
1948
+ pairs = [(o, b["twin"]) for o, b in self.vault.baseline.items()
1949
+ if b["mode"] in ("c", "cpp") and o.lower().endswith(source_ext)]
1950
+ cxx = headers.find_cxx_compiler(self.cfg["cxx_compiler"], compiler)
1951
+
1952
+ def inc_flags(base: Path, rels: list[str]) -> list[str]:
1953
+ dirs = sorted({str((base / r).parent) for r in rels
1954
+ if r.lower().endswith((".h", ".hpp", ".hh", ".hxx", ".h++", ".inl", ".ipp", ".tpp"))})
1955
+ return [f"-I{d}" for d in dirs]
1956
+
1957
+ orig_inc = inc_flags(self.root, list(self.vault.baseline))
1958
+ twin_inc = inc_flags(self.twin, [b["twin"] for b in self.vault.baseline.values()])
1959
+
1960
+ def run(args: list[str]) -> subprocess.CompletedProcess:
1961
+ return subprocess.run(args, capture_output=True, text=True, env=env, timeout=120,
1962
+ creationflags=getattr(subprocess, "CREATE_NO_WINDOW", 0))
1963
+
1964
+ objcopy = Path(compiler).with_name("objcopy.exe" if compiler.lower().endswith(".exe") else "objcopy")
1965
+ with tempfile.TemporaryDirectory() as tmp:
1966
+ # Machine code is compared against a names-only twin (strings and comments untouched), so the
1967
+ # comparison proves exactly "renaming changed no code", whatever the string policy is.
1968
+ alt_root = Path(tmp) / "names_only"
1969
+ if objects and tr is not None:
1970
+ ntr = tr.names_only()
1971
+ for f in files or []:
1972
+ if f.mode in ("c", "cpp") and not f.excluded:
1973
+ dest = alt_root / tr.path(f.rel)
1974
+ dest.parent.mkdir(parents=True, exist_ok=True)
1975
+ dest.write_bytes(encode(ntr.code_source(decode(f.data), f.mode)))
1976
+ alt_inc = inc_flags(alt_root, [b["twin"] for b in self.vault.baseline.values()])
1977
+ for orig_rel, twin_rel in pairs:
1978
+ cc = compiler
1979
+ if self.vault.baseline[orig_rel]["mode"] == "cpp":
1980
+ if not cxx:
1981
+ rep.not_checked.append(f"{orig_rel}: no C++ compiler (g++ / clang++) found")
1982
+ continue
1983
+ cc = cxx
1984
+ o = run([cc, "-fsyntax-only", *flags, *orig_inc, str(self.root / orig_rel)])
1985
+ t = run([cc, "-fsyntax-only", *flags, *twin_inc, str(self.twin / twin_rel)])
1986
+ rep.compiled += 1
1987
+ if o.returncode != 0:
1988
+ # the ORIGINAL does not compile with these flags: nothing to compare against
1989
+ first = next((ln for ln in o.stderr.splitlines() if "error" in ln), o.stderr.strip()[:200])
1990
+ rep.not_checked.append(f"{orig_rel}: the original does not compile with the check's flags "
1991
+ f"({' '.join(flags) or 'compiler default'}) - {first.strip()}")
1992
+ continue
1993
+ if t.returncode != 0:
1994
+ rep.compile_errors.append(f"{twin_rel}:\n{t.stderr.strip()}")
1995
+ continue
1996
+ if not objects:
1997
+ continue
1998
+ if not objcopy.exists():
1999
+ rep.not_checked.append(f"{orig_rel}: machine code not compared ({objcopy.name} not found "
2000
+ "next to the compiler)")
2001
+ continue
2002
+ if not (alt_root / twin_rel).is_file():
2003
+ rep.not_checked.append(f"{orig_rel}: machine code not compared (no names-only twin)")
2004
+ continue
2005
+ code = []
2006
+ for tag, base, rel, inc in (("o", self.root, orig_rel, orig_inc), ("t", alt_root, twin_rel, alt_inc)):
2007
+ obj = Path(tmp) / f"{tag}.o"
2008
+ binf = Path(tmp) / f"{tag}.bin"
2009
+ run([cc, "-c", "-O2", *flags, *inc, str(base / rel), "-o", str(obj)])
2010
+ run([str(objcopy), "-O", "binary", "--only-section=.text", str(obj), str(binf)])
2011
+ code.append(binf.read_bytes() if binf.exists() else b"")
2012
+ rep.objects_compared += 1
2013
+ if code[0] != code[1]:
2014
+ rep.objects_differ.append(orig_rel)
2015
+
2016
+
2017
+ def _python_secrets_back(tree: ast.AST, store: dict[str, dict]) -> ast.AST:
2018
+ """Twin tree with every K_ alias replaced by its real literal and the doppel_secrets import removed."""
2019
+ class Back(ast.NodeTransformer):
2020
+ def visit_Name(self, node):
2021
+ if node.id in store:
2022
+ return pyparse.parse(store[node.id]["literal"].strip(), mode="eval").body
2023
+ return node
2024
+
2025
+ def visit_ImportFrom(self, node):
2026
+ return None if node.module in (secretconst.PY_MODULE, secretconst.LEGACY_PY_MODULE) else node
2027
+
2028
+ return Back().visit(tree) if store else tree
2029
+
2030
+
2031
+ _KEY_RE = re.compile(r"[A-Za-z_]\w*")
2032
+ _KEY_METHODS = {"get", "pop", "setdefault", "__getitem__", "__contains__"}
2033
+ _ITER_BUILTINS = {"enumerate", "zip", "sorted", "reversed", "list", "tuple", "iter", "filter", "dict"}
2034
+
2035
+
2036
+ def python_dict_keys(src: str) -> set[str]:
2037
+ """Identifier-shaped string keys: d['k'], {'k': v}, d.get('k'), 'k' in d, dict(k=...) is code already."""
2038
+ try:
2039
+ tree = pyparse.parse(src)
2040
+ except SyntaxError:
2041
+ return set()
2042
+ out: set[str] = set()
2043
+
2044
+ def add(node) -> None:
2045
+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and _KEY_RE.fullmatch(node.value):
2046
+ out.add(node.value)
2047
+ for node in ast.walk(tree):
2048
+ if isinstance(node, ast.Dict):
2049
+ for k in node.keys:
2050
+ add(k)
2051
+ elif isinstance(node, ast.Subscript):
2052
+ add(node.slice)
2053
+ elif (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute)
2054
+ and node.func.attr in _KEY_METHODS and node.args):
2055
+ add(node.args[0])
2056
+ elif isinstance(node, ast.Compare) and any(isinstance(o, (ast.In, ast.NotIn)) for o in node.ops):
2057
+ add(node.left)
2058
+ return out
2059
+
2060
+
2061
+ def _root_name(node) -> str | None:
2062
+ """`os.environ.get` -> "os", `np.load(p)["x"]` -> "np"; None for anything else."""
2063
+ while True:
2064
+ if isinstance(node, ast.Name):
2065
+ return node.id
2066
+ if isinstance(node, (ast.Attribute, ast.Subscript)):
2067
+ node = node.value
2068
+ elif isinstance(node, ast.Call):
2069
+ node = node.func
2070
+ else:
2071
+ return None
2072
+
2073
+
2074
+ def python_library_keys(src: str, library_names: set[str]) -> set[str]:
2075
+ """Identifier-shaped keys of dicts that belong to a library: subscripts and get/pop on a value reached
2076
+ from an imported name (os.environ['PATH']), and dict literals handed to a call of an imported name
2077
+ (requests.post(json={'user': u})). These keys must keep their spelling for the twin to run."""
2078
+ try:
2079
+ tree = pyparse.parse(src)
2080
+ except SyntaxError:
2081
+ return set()
2082
+ out: set[str] = set()
2083
+
2084
+ def add(node) -> None:
2085
+ if isinstance(node, ast.Constant) and isinstance(node.value, str) and _KEY_RE.fullmatch(node.value):
2086
+ out.add(node.value)
2087
+
2088
+ # Names that hold library values: `devices = sd.query_devices()`, and loop targets over them
2089
+ # (`for i, d in enumerate(devices)`): d['max_input_channels'] is the library's key.
2090
+ library_names = set(library_names)
2091
+
2092
+ def from_library(expr) -> bool:
2093
+ if (isinstance(expr, ast.Call) and isinstance(expr.func, ast.Name) and expr.func.id in _ITER_BUILTINS
2094
+ and expr.args):
2095
+ return any(from_library(a) for a in expr.args)
2096
+ return _root_name(expr) in library_names
2097
+
2098
+ def targets(node) -> set[str]:
2099
+ return {n.id for n in ast.walk(node) if isinstance(n, ast.Name)}
2100
+ while True:
2101
+ before = len(library_names)
2102
+ for node in ast.walk(tree):
2103
+ if isinstance(node, (ast.Assign, ast.AnnAssign)) and node.value is not None and from_library(node.value):
2104
+ for t in (node.targets if isinstance(node, ast.Assign) else [node.target]):
2105
+ if isinstance(t, (ast.Name, ast.Tuple, ast.List)):
2106
+ library_names |= targets(t)
2107
+ elif isinstance(node, (ast.For, ast.comprehension)) and from_library(node.iter):
2108
+ library_names |= targets(node.target)
2109
+ elif isinstance(node, ast.withitem) and node.optional_vars is not None \
2110
+ and from_library(node.context_expr):
2111
+ library_names |= targets(node.optional_vars)
2112
+ if len(library_names) == before:
2113
+ break
2114
+ for node in ast.walk(tree):
2115
+ if isinstance(node, ast.Subscript) and _root_name(node.value) in library_names:
2116
+ add(node.slice)
2117
+ elif isinstance(node, ast.Call):
2118
+ func = node.func
2119
+ if (isinstance(func, ast.Attribute) and func.attr in _KEY_METHODS and node.args
2120
+ and _root_name(func.value) in library_names):
2121
+ add(node.args[0])
2122
+ if _root_name(func) in library_names:
2123
+ for arg in [*node.args, *(k.value for k in node.keywords)]:
2124
+ if isinstance(arg, ast.Dict):
2125
+ for k in arg.keys:
2126
+ add(k)
2127
+ return out
2128
+
2129
+
2130
+ # pytest finds these by name: built-in fixtures, hook arguments, the conftest module
2131
+ PYTEST_NAMES = frozenset({
2132
+ "conftest", "config", "request", "tmp_path", "tmp_path_factory", "tmpdir", "tmpdir_factory", "monkeypatch",
2133
+ "capsys", "capsysbinary", "capfd", "capfdbinary", "caplog", "recwarn", "pytestconfig", "record_property",
2134
+ "record_xml_attribute", "record_testsuite_property", "cache", "doctest_namespace", "pytester", "testdir",
2135
+ "subtests", "item", "items", "session", "parser", "metafunc", "report", "call", "exitstatus",
2136
+ "terminalreporter", "collector", "fixturedef", "nextitem", "early_config", "pluginmanager", "excinfo",
2137
+ })
2138
+
2139
+
2140
+ def _uses_pytest(files) -> bool:
2141
+ for f in files:
2142
+ name = f.rel.rsplit("/", 1)[-1]
2143
+ if name in ("conftest.py", "pytest.ini"):
2144
+ return True
2145
+ if (name in ("pyproject.toml", "setup.cfg", "tox.ini") or (name.startswith("requirements")
2146
+ and name.endswith(".txt"))) \
2147
+ and b"pytest" in f.data:
2148
+ return True
2149
+ return False
2150
+
2151
+
2152
+ # scripts: copied into the twin (the build runs them), never imported as new files, changes reviewed
2153
+ SCRIPT_EXTENSIONS = (".sh", ".bash", ".bat", ".cmd", ".ps1", ".pl", ".pm", ".awk", ".py.in")
2154
+ _CMAKE_TARGET_RE = re.compile(r"\badd_(?:library|executable)\s*\(\s*([A-Za-z_][\w.+\-]*)", re.I)
2155
+ _COMPUTED_PATH_RE = re.compile(r"\$\{[A-Za-z_]\w*\}[\w.-]*\.(?:c|cc|cpp|cxx|h|hpp|hh|in|cmake|py)\b"
2156
+ r"|\$\([A-Za-z_]\w*\)[\w.-]*\.(?:c|cc|cpp|cxx|h|hpp)\b")
2157
+ _PASTE_DEFINE_RE = re.compile(r"^[ \t]*#[ \t]*define[ \t]+\w+\(([^)]*)\)((?:[^\n]*\\\r?\n)*[^\n]*)", re.M)
2158
+ _PASTE_CHAIN_RE = re.compile(r"\w+(?:[ \t]*##[ \t]*\w+)+")
2159
+
2160
+
2161
+ def _pasted_aliases(files, active: dict[str, str]) -> dict[str, str]:
2162
+ """Renamed C / C++ names that a function-like macro builds with ## from literal parts and parameters:
2163
+ name -> the concatenation of the parts' aliases (a literal part and the argument keep their own alias)."""
2164
+ chains: list[list[tuple[bool, str]]] = []
2165
+ idents: set[str] = set()
2166
+ for f in files:
2167
+ if f.mode not in ("c", "cpp") or f.excluded:
2168
+ continue
2169
+ src = decode(f.data)
2170
+ idents |= set(re.findall(r"[A-Za-z_]\w*", src)) # arguments are written in any file
2171
+ if "##" not in src:
2172
+ continue
2173
+ for m in _PASTE_DEFINE_RE.finditer(src):
2174
+ params = {x.strip() for x in m.group(1).split(",")}
2175
+ for c in _PASTE_CHAIN_RE.finditer(m.group(2)):
2176
+ slots = [(x in params, x) for x in re.split(r"[ \t]*##[ \t]*", c.group(0))]
2177
+ if any(is_p for is_p, _ in slots) and not all(is_p for is_p, _ in slots):
2178
+ chains.append(slots)
2179
+ if not chains:
2180
+ return {}
2181
+ patterns = [(re.compile("".join(r"([A-Za-z_]\w*?)" if is_p else re.escape(x) for is_p, x in slots) + r"\Z"),
2182
+ slots) for slots in chains]
2183
+ out: dict[str, str] = {}
2184
+ for name in sorted(active):
2185
+ if name in out or not re.fullmatch(r"[A-Za-z_]\w*", name):
2186
+ continue
2187
+ for rx, slots in patterns:
2188
+ m = rx.match(name)
2189
+ if not m:
2190
+ continue
2191
+ args = iter(m.groups())
2192
+ parts = []
2193
+ for is_p, x in slots:
2194
+ part = next(args) if is_p else x
2195
+ if is_p and part not in idents:
2196
+ break # the argument must be a name the code writes
2197
+ parts.append(active.get(part, part))
2198
+ else:
2199
+ out[name] = "".join(parts)
2200
+ break
2201
+ return out
2202
+
2203
+
2204
+ def _python_twin_stubs(tree: ast.AST) -> None:
2205
+ """Twin side of the comparison: a stub body (`raise NotImplementedError("doppel: body withheld
2206
+ (B_0001)")`, or 0.5.0's `...`) becomes `...`, like the withheld bodies of the original."""
2207
+ for node in ast.walk(tree):
2208
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)) and len(node.body) == 1:
2209
+ st = node.body[0]
2210
+ if (isinstance(st, ast.Raise) and isinstance(st.exc, ast.Call) and st.exc.args
2211
+ and isinstance(st.exc.args[0], ast.Constant)
2212
+ and str(st.exc.args[0].value).startswith(("doppel: body withheld (",
2213
+ "cobf: body withheld ("))):
2214
+ node.body = [ast.Expr(ast.Constant(Ellipsis))]
2215
+
2216
+
2217
+ def _python_withheld_bodies(tree: ast.AST, symbols: set[str]) -> None:
2218
+ """Replace the bodies of these functions (qualified names) by `...`, as the twin has them."""
2219
+ def visit(node, prefix: str) -> None:
2220
+ for child in ast.iter_child_nodes(node):
2221
+ if isinstance(child, (ast.FunctionDef, ast.AsyncFunctionDef)):
2222
+ name = prefix + child.name
2223
+ if name in symbols:
2224
+ child.body = [ast.Expr(ast.Constant(Ellipsis))]
2225
+ else:
2226
+ visit(child, name + ".")
2227
+ elif isinstance(child, ast.ClassDef):
2228
+ visit(child, prefix + child.name + ".")
2229
+ else:
2230
+ visit(child, prefix)
2231
+ visit(tree, "")
2232
+
2233
+
2234
+ def _python_names_back(tree: ast.AST, rtr: Translator) -> None:
2235
+ """Map every name in a twin syntax tree back to the original (identifiers, attributes, imports,
2236
+ parameters, keyword arguments) and restore names inside string constants (scrub mode)."""
2237
+ def back(name: str) -> str:
2238
+ return ".".join(rtr.word(p) for p in name.split("."))
2239
+
2240
+ for node in ast.walk(tree):
2241
+ for attr in ("id", "attr", "name", "arg", "asname", "module", "rest"):
2242
+ value = getattr(node, attr, None)
2243
+ if isinstance(value, str):
2244
+ setattr(node, attr, back(value))
2245
+ for attr in ("names", "kwd_attrs"):
2246
+ value = getattr(node, attr, None)
2247
+ if isinstance(value, list) and value and all(isinstance(v, str) for v in value):
2248
+ setattr(node, attr, [back(v) for v in value])
2249
+ if isinstance(node, ast.Constant) and isinstance(node.value, str):
2250
+ node.value = rtr.text(node.value)
2251
+
2252
+
2253
+ def _language_word(name: str, mode: str) -> bool:
2254
+ """Keywords and builtins (continue, is, getattr, printf): never a 'new name introduced'."""
2255
+ lang = languages.LANGUAGES.get(mode)
2256
+ return name in ALWAYS_KEEP or (lang is not None and (name in lang.keywords or name in lang.keep))
2257
+
2258
+
2259
+ def _name_words(name: str) -> list[str]:
2260
+ """detect_symbol / detectSymbol / DetectSymbol / "detect symbol" -> ["detect", "symbol"]."""
2261
+ return [p.lower() for p in re.findall(r"[A-Z]+(?![a-z])|[A-Z]?[a-z]+", name)]
2262
+
2263
+
2264
+ def kinds_ok(kind: str | None) -> bool:
2265
+ return kind in CODE_KINDS
2266
+
2267
+
2268
+ ABS_PATH_ID_RE = re.compile(r"\$\(((?:DOPPEL|COBF)_PATH_\d{4,})\)")
2269
+ ABS_PATH_RE = re.compile(r"(?<![\w%])[A-Za-z]:(?:\\\\|\\|/)[^\s\"'<>|]+" # C:\x, C:\\x, C:/x; not "%s://"
2270
+ # \\host\share; a host starts with a letter or digit ("\\$\\(" is a CMake regex)
2271
+ r"|(?<![\w\\])\\{2}(?:\\{2})?[A-Za-z0-9][A-Za-z0-9._$-]*\\{1,2}[^\s\"'<>|]+"
2272
+ r"|(?<![\w.])/(?:home|Users|mnt|media)/[^\s\"'<>|]+") # /home/user
2273
+ _PP_DIRECTIVE_RE = re.compile(r'^[ \t]*#[ \t]*\w+(?:[ \t]*(?:<[^>\n]*>|"[^"\n]*"))?')
2274
+ _INCLUDE_RE = re.compile(r'^[ \t]*#[ \t]*(?:include|include_next|import|embed)[ \t]*([<"][^>"\n]+[>"])', re.M)
2275
+
2276
+
2277
+ def _inside_after(start: list[str], parts: list[str]) -> list[str] | None:
2278
+ """Walk `parts` ('..', '.', names) from folder `start` (path from the twin root); None if it leaves the root."""
2279
+ cur = list(start)
2280
+ for part in parts:
2281
+ if part in ("", "."):
2282
+ continue
2283
+ if part == "..":
2284
+ if not cur:
2285
+ return None
2286
+ cur.pop()
2287
+ else:
2288
+ cur.append(part)
2289
+ return cur
2290
+
2291
+
2292
+ def unsafe_includes(text: str, depth: int | None = None, rel: str | None = None,
2293
+ exists=None, inc_dirs: list[str] | None = None) -> list[str]:
2294
+ """#include targets that leave the twin: absolute, drive, UNC (\\\\host\\share) paths, and '..' paths that
2295
+ go above the twin root. ``rel`` (the including file, from the twin root) enables '..' inside the twin:
2296
+ the compiler tries the including file's folder first, so "../x.h" is safe when that resolves inside the
2297
+ twin and ``exists(path)``; otherwise it would be searched in every -I folder (``inc_dirs``, from the twin
2298
+ root), so it must stay inside from each of them. Without ``rel`` every '..' is refused, except DoppelCode's own
2299
+ `#include "../doppel_secrets.h" /* doppel */` (``depth`` = folders between the twin root and the file)."""
2300
+ out = []
2301
+ folder = rel.split("/")[:-1] if rel is not None else None
2302
+ for m in _INCLUDE_RE.finditer(text):
2303
+ target = m.group(1)[1:-1].strip()
2304
+ if depth is not None and target in ("../" * depth + secretconst.C_HEADER,
2305
+ "../" * depth + secretconst.LEGACY_C_HEADER):
2306
+ continue
2307
+ parts = re.split(r"[\\/]+", target)
2308
+ if target.startswith(("/", "\\")) or re.match(r"[A-Za-z]:", target) or ":" in target:
2309
+ out.append(m.group(1))
2310
+ continue
2311
+ if ".." not in parts:
2312
+ continue
2313
+ if folder is None:
2314
+ out.append(m.group(1))
2315
+ continue
2316
+ here = _inside_after(folder, parts)
2317
+ if here is not None and m.group(1).startswith('"') and exists is not None and exists("/".join(here)):
2318
+ continue # found next to the including file: used first
2319
+ if here is None or any(_inside_after(d.split("/") if d else [], parts) is None for d in inc_dirs or []):
2320
+ out.append(m.group(1))
2321
+ return out
2322
+
2323
+
2324
+ def _remove_empty_dirs(root: Path, inside=None) -> None:
2325
+ for d in sorted((p for p in root.rglob("*") if p.is_dir()), key=lambda p: len(p.parts), reverse=True):
2326
+ if d.is_symlink() or (inside is not None and not inside(d)):
2327
+ continue
2328
+ try:
2329
+ d.rmdir()
2330
+ except OSError:
2331
+ pass
2332
+
2333
+
2334
+ def lookup(project: Project, name: str) -> list[str]:
2335
+ words = project.vault.words
2336
+ out = []
2337
+ if name in words:
2338
+ out.append(f"{name} -> {words[name]} ({project.vault.data['kinds'].get(name, '?')})")
2339
+ for o, g in words.items():
2340
+ if g == name:
2341
+ out.append(f"{name} <- {o} ({project.vault.data['kinds'].get(o, '?')})")
2342
+ return out
2343
+