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/cli.py ADDED
@@ -0,0 +1,462 @@
1
+ """Command line: python -m doppelcode <command> <project> ..."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import argparse
6
+ import sys
7
+ from pathlib import Path
8
+
9
+ from .config import (BUILD_NAME_MODES, COMMENT_MODES, DATA_MODES, LEGACY_STATE_DIR, STRING_MODES, set_config_value,
10
+ state_dir_name, write_default_config)
11
+ from .project import DoppelError, Project, lookup
12
+
13
+
14
+ def _cmd_init(args) -> int:
15
+ path = write_default_config(Path(args.project).resolve())
16
+ print(f"config: {path}")
17
+ return 0
18
+
19
+
20
+ def _cmd_export(args) -> int:
21
+ if args.comments:
22
+ set_config_value(Path(args.project).resolve(), "comments", args.comments)
23
+ if args.strings:
24
+ set_config_value(Path(args.project).resolve(), "strings", args.strings)
25
+ if args.data:
26
+ set_config_value(Path(args.project).resolve(), "data_files", args.data)
27
+ if args.build_names:
28
+ set_config_value(Path(args.project).resolve(), "build_names", args.build_names)
29
+ proj = Project(args.project, args.out)
30
+ rep = proj.export(force=args.force, allow_over_budget=args.allow_over_budget)
31
+ print(f"twin: {rep.twin}")
32
+ for note in proj.auto_notes:
33
+ print(f"note: {note}")
34
+ print(f"files: {len(rep.files)} written, {len(rep.skipped)} skipped (not copied)")
35
+ if rep.languages:
36
+ print("languages: " + ", ".join(f"{k} ({v})" for k, v in sorted(rep.languages.items())))
37
+ if rep.unresolved_modules:
38
+ print(f"warning: {len(rep.unresolved_modules)} Python module(s) not found, their names may get renamed"
39
+ + _missing_where(rep, rep.unresolved_modules))
40
+ print(f"names: {rep.renamed} renamed ({rep.new_names} new in vault)")
41
+ print(f"exposure: {rep.bodies_logged} function bod{'y' if rep.bodies_logged == 1 else 'ies'} newly made "
42
+ f"available (ledger session {rep.session}; 'doppel report' for the totals)")
43
+ for item in rep.over_budget:
44
+ print(f"OVER BUDGET {item} (allowed with --allow-over-budget; recorded in the ledger)")
45
+ if rep.withheld:
46
+ print(f"withheld: {rep.withheld} function bod{'y' if rep.withheld == 1 else 'ies'} kept on this PC "
47
+ "(the twin has the signatures)")
48
+ for key in rep.released:
49
+ print(f"released: {key} - its body is in the twin for this session only (logged); the next "
50
+ "export withholds it again")
51
+ if rep.secrets:
52
+ print(f"secrets: {rep.secrets} secret constant site(s) hidden as K_ aliases (dummy values in the twin)")
53
+ unmarked = [c for c, marked in proj.secret_candidates() if not marked]
54
+ if unmarked:
55
+ print(f"note: {len(unmarked)} unmarked secret-constant candidate(s) - see 'doppel secrets suggest'")
56
+ if rep.agent_notes:
57
+ print(f"agents: {', '.join(rep.agent_notes)} written into the twin (asks for plain names for new things)")
58
+ mode = proj.cfg["comments"]
59
+ print(f"comments: {dict(hide='hidden (placeholders, restored on import)', scrub='names replaced', keep='kept as is')[mode]}")
60
+ smode = proj.cfg["strings"]
61
+ if proj.cfg["data_files"] == "build":
62
+ print(f"data: {len(getattr(proj, 'build_inputs', []))} build input(s) copied (text files build files "
63
+ "name)")
64
+ if proj.cfg["data_files"] == "copy":
65
+ print(f"data: {rep.data_files} file(s) copied under their aliases"
66
+ + (f" into {', '.join(rep.data_dirs)}" if rep.data_dirs else ""))
67
+ print(f"strings: {dict(hide='hidden (str_0001 + format skeleton, restored on import)', scrub='names replaced', keep='kept as is')[smode]}"
68
+ + (" - default with withheld functions / secrets; set \"strings\" in .doppel/config.json to change"
69
+ if proj.cfg.get("strings_by_default") else ""))
70
+ print(f"compiler: {rep.compiler or 'not found - only the built-in stdlib list protects library names'}")
71
+ if rep.unresolved_headers:
72
+ print(f"warning: {len(rep.unresolved_headers)} header(s) not found, their names may get renamed"
73
+ + _missing_where(rep, rep.unresolved_headers))
74
+ if args.verbose:
75
+ for o, t in rep.files:
76
+ print(f" {o} -> {t}")
77
+ for s in rep.skipped:
78
+ print(f" skipped {s}")
79
+ print("Point the AI agent at the twin folder. Run 'import' to bring its edits back.")
80
+ return 0
81
+
82
+
83
+ def _parse_renames(items: list[str] | None) -> dict[str, str]:
84
+ out = {}
85
+ for item in items or []:
86
+ old, sep, new = item.partition("=")
87
+ if not sep or not old.strip() or not new:
88
+ raise DoppelError(f"--rename needs OLD=new, got {item!r}")
89
+ out[old.strip()] = new.strip() if not old.strip().startswith("str_") else new
90
+ return out
91
+
92
+
93
+ def _cmd_import(args) -> int:
94
+ proj = Project(args.project)
95
+ accept = True if args.accept == [] else (args.accept or False)
96
+ if args.only and not args.from_preview:
97
+ raise DoppelError("--only needs --from-preview DIR")
98
+ if args.from_preview:
99
+ if args.preview or args.to or args.dry_run or args.apply_deletes or args.rename or args.accept is not None:
100
+ raise DoppelError("--from-preview takes only --only (the preview's --rename / --accept are used)")
101
+ rep = proj.apply_preview(Path(args.from_preview), args.only)
102
+ else:
103
+ rep = proj.import_changes(to=Path(args.to) if args.to else None, dry_run=args.dry_run,
104
+ apply_deletes=args.apply_deletes, renames=_parse_renames(args.rename),
105
+ accept=accept, preview=Path(args.preview) if args.preview else None)
106
+ prefix = "(dry run) " if args.dry_run else "(preview) " if args.preview else ""
107
+ for label, items in (("changed", rep.changed), ("merged", rep.merged), ("new", rep.new),
108
+ ("conflict", rep.conflicts),
109
+ ("deleted in twin", rep.deleted), ("removed", rep.removed)):
110
+ for item in items:
111
+ print(f"{prefix}{label:16} {item}")
112
+ if rep.conflicts:
113
+ print("Conflicts: you and the AI changed the same lines. The original "
114
+ + ("would be" if args.preview else "was") + " left untouched; the merge "
115
+ "with conflict markers is in <file>.doppel-merge (or the AI version in <file>.doppel-incoming)"
116
+ + (" in the preview folder." if args.preview else "."))
117
+ if rep.merged:
118
+ print("Merged: the AI's changes were applied on top of your own edits to the original.")
119
+ if rep.deleted and not args.apply_deletes:
120
+ print("Deleted files are only reported; use --apply-deletes to remove them from the original.")
121
+ if rep.new_identifiers:
122
+ print("New names introduced in the twin (kept as written): " + ", ".join(sorted(rep.new_identifiers)))
123
+ for item in rep.comments_kept:
124
+ print(f"comments: {item} the AI left out of its rewrite, put back")
125
+ for item in rep.encoding_kept:
126
+ print(f"encoding: {item}")
127
+ for item in rep.alias_warnings:
128
+ print(f"warning: {item}")
129
+ for item in rep.blocked:
130
+ print(f"{prefix}{'BLOCKED':16} {item}")
131
+ for item in rep.unsafe:
132
+ print(f"{prefix}{'IGNORED (link)':16} {item} (symlink/junction in the twin - not followed)")
133
+ if rep.blocked:
134
+ print("Blocked files were created by the AI but are not imported: only C sources and known text files "
135
+ "outside hidden folders are accepted. Copy them by hand if you really want them.")
136
+ if rep.review:
137
+ print("Review before building: build / config files changed by the AI: " + ", ".join(rep.review))
138
+ for item in rep.secret_requests:
139
+ print(f"{prefix}{'secret':16} {item}")
140
+ for item in rep.alias_resolved:
141
+ print(f"{prefix}{'alias':16} {item}")
142
+ for item in rep.twin_updated:
143
+ print(f"{prefix}{'twin updated':16} {item} (renamed names now have their own aliases)")
144
+ if rep.refused:
145
+ for item in rep.refused:
146
+ print(f"{prefix}{'NOT MERGED':16} {item}")
147
+ print("The AI wrote names in DoppelCode's alias style that would come back as the wrong real names:")
148
+ for item in rep.alias_open:
149
+ print(f" {item}")
150
+ print("Give each one a real name with --rename OLD=new (e.g. --rename v_0048=nonce), keep it with "
151
+ "--accept OLD, or accept all with --accept, then run import again."
152
+ + (f" Saved to {rep.review_file}" if rep.review_file else ""))
153
+ if rep.preview_dir is not None:
154
+ print(f"preview: {len(rep.preview_files)} file(s) written to {rep.preview_dir} (same relative paths). "
155
+ "Nothing in the project or the twin was changed. Apply with: doppel import <project> "
156
+ "--from-preview <dir> [--only FILE]")
157
+ if not (rep.changed or rep.new or rep.deleted or rep.refused):
158
+ print("Nothing to import.")
159
+ return 1 if rep.conflicts or rep.refused else 0
160
+
161
+
162
+ def _missing_where(rep, names) -> str:
163
+ """': a.h, b.h' for a few, else where the full list is."""
164
+ if len(names) <= 5:
165
+ return ": " + ", ".join(sorted(names))
166
+ return f" (list in {rep.missing_file})" if rep.missing_file else ""
167
+
168
+
169
+ def _print_leaks(rep, args) -> None:
170
+ """Leak summary: counts by kind, the top files, then examples (secret values and absolute paths first);
171
+ the full list is in .doppel/leaks.txt, or printed with --leaks-all."""
172
+ from collections import Counter
173
+ from .project import LEAK_KINDS
174
+ if not rep.leaks:
175
+ print("leaks: none")
176
+ return
177
+ print(f"leaks: {len(rep.leaks)} line(s)" + (f" - full list in {rep.leaks_file}" if rep.leaks_file else ""))
178
+ kinds = Counter(k for _, _, items in rep.leak_items for k in {k for k, _ in items})
179
+ print(" by kind: " + " | ".join(f"{k} {kinds[k]}" for k in LEAK_KINDS if kinds[k]))
180
+ files = Counter(rel for rel, _, _ in rep.leak_items)
181
+ if len(files) > 1:
182
+ top = files.most_common(5)
183
+ print(" top files: " + ", ".join(f"{rel} {n}" for rel, n in top)
184
+ + (f" (+{len(files) - len(top)} more files)" if len(files) > len(top) else ""))
185
+ limit = len(rep.leaks) if args.leaks_all else args.max_leaks
186
+ for leak in rep.leaks[:limit]:
187
+ print(f" {leak}")
188
+ if len(rep.leaks) > limit:
189
+ print(f" ... {len(rep.leaks) - limit} more (--leaks-all, or the file above). Words you accept, such as "
190
+ 'a public project name: "leak_allow" in .doppel/config.json')
191
+
192
+
193
+ def _cmd_check(args) -> int:
194
+ proj = Project(args.project)
195
+ rep = proj.check(compile_check=not args.no_compile, objects=args.objects)
196
+ print(f"round trip: {'OK' if not rep.roundtrip_failures else 'FAILED ' + ', '.join(rep.roundtrip_failures)}")
197
+ _print_leaks(rep, args)
198
+ for warning in rep.warnings:
199
+ print(f"warning: {warning}")
200
+ if rep.hints:
201
+ shown = len(rep.hints) if args.leaks_all else min(len(rep.hints), 5)
202
+ print(f"hints: {len(rep.hints)} line(s) spell a renamed name out in prose (comments / strings "
203
+ f"kept by 'scrub'; 'hide' removes them){'' if shown == len(rep.hints) else ', e.g.:'}")
204
+ for hint in rep.hints[:shown]:
205
+ print(f" {hint}")
206
+ if rep.unsafe_includes:
207
+ print("compile: NOT RUN - the twin includes files outside itself (possible attack, e.g. a network "
208
+ "share that would receive your Windows login):")
209
+ for item in rep.unsafe_includes:
210
+ print(f" {item}")
211
+ elif args.no_compile:
212
+ pass
213
+ elif not rep.compiler and not (rep.builds or rep.python_checked or rep.python_differ or rep.not_checked):
214
+ print("compile: skipped (no compiler found)")
215
+ else:
216
+ if rep.c_files:
217
+ print(f"compile: {rep.compiled} C/C++ file(s), {len(rep.compile_errors)} twin-only error(s) "
218
+ f"[{rep.compiler}]")
219
+ for line in rep.builds:
220
+ print(line)
221
+ for err in rep.compile_errors:
222
+ print(err)
223
+ for item in rep.not_checked:
224
+ print(f" NOT CHECKED {item}")
225
+ if rep.not_checked:
226
+ print(" (set compile_flags / javac / csc / node in .doppel/config.json to match your real build, e.g. "
227
+ '"compile_flags": ["-std=gnu17", "-DMY_DEFINE"])')
228
+ if rep.python_checked or rep.python_differ:
229
+ print(f"python: {rep.python_checked} file(s) compared as syntax trees, "
230
+ + ("identical" if not rep.python_differ else "DIFFER"))
231
+ for item in rep.python_differ:
232
+ print(f" {item}")
233
+ if args.objects and rep.objects_skipped:
234
+ print(f"machine code: not compared ({rep.objects_skipped})")
235
+ elif args.objects and rep.c_files:
236
+ print(f"machine code: {rep.objects_compared} object(s) compared, "
237
+ f"{'identical' if not rep.objects_differ else 'DIFFER: ' + ', '.join(rep.objects_differ)}")
238
+ return 0 if rep.ok else 1
239
+
240
+
241
+ def _cmd_withhold(args) -> int:
242
+ proj = Project(args.project)
243
+ if args.action == "purpose":
244
+ if not args.ids:
245
+ print('error: e.g. doppel withhold purpose PROJECT B_0002 "returns (gender, confidence)" '
246
+ '(no text removes it)', file=sys.stderr)
247
+ return 2
248
+ key = proj.set_withheld_purpose(args.ids[0], " ".join(args.ids[1:]))
249
+ print(f"purpose {'set' if args.ids[1:] else 'removed'}: {args.ids[0]} {key}")
250
+ print("The next export lists it in the twin's AGENTS.md (it tells the AI what the function does).")
251
+ return 0
252
+ if args.action == "release":
253
+ if not args.ids:
254
+ print("error: give the ids to release, e.g. 'doppel withhold release PROJECT B_0001'", file=sys.stderr)
255
+ return 2
256
+ for key in proj.release_withheld(args.ids, args.reason or ""):
257
+ print(f"released for the next export: {key} (logged in the exposure ledger)")
258
+ print("Run 'export': the twin gets these bodies for one session; the export after it withholds them again.")
259
+ return 0
260
+ rows = proj.withheld_list()
261
+ if not rows:
262
+ print("No withheld functions (core_functions / core_modules in .doppel/config.json).")
263
+ return 0
264
+ for r in rows:
265
+ print(f"{r['id']} {r['file']}::{r['symbol']}{' (released for the next export)' if r['released'] else ''}")
266
+ if r["purpose"]:
267
+ print(f" purpose: {r['purpose']}")
268
+ return 0
269
+
270
+
271
+ def _cmd_secrets(args) -> int:
272
+ proj = Project(args.project)
273
+ if args.action == "suggest":
274
+ cands = proj.secret_candidates() # ranked: tables, algorithm constants, thresholds, rest
275
+ if not cands:
276
+ print("No candidates found.")
277
+ return 0
278
+ total = len(cands)
279
+ if not args.all and total > args.top:
280
+ from collections import Counter
281
+ per_file = Counter(c.rel for c, _ in cands)
282
+ print(f"{total} candidates in {len(per_file)} file(s). The top {args.top}, ranked (tables first, then "
283
+ "known algorithm constants, values compared with a variable, the rest); --all for every one.")
284
+ for c, marked in cands[: args.top]:
285
+ fn = f" {c.function}()" if c.function else ""
286
+ print(f" {c.rel}:{c.line}{fn} {c.text} {c.rule}{' [' + c.symbol + ']' if c.symbol else ''}"
287
+ f"{' (marked)' if marked else ''}")
288
+ print("\nCandidates per file:")
289
+ rows = per_file.most_common()
290
+ for rel, n in rows[:20]:
291
+ print(f" {n:>5} {rel}")
292
+ if len(rows) > 20:
293
+ print(f" ... {len(rows) - 20} more files")
294
+ print('\nTo mark a whole file or function: "secret_files": ["dsp/"], "secret_functions": '
295
+ '["src/f.c::func"] in .doppel/config.json; single values: "secret_values" / "secret_symbols".')
296
+ return 0
297
+ where = None
298
+ for c, marked in sorted(cands, key=lambda cm: (cm[0].rel, cm[0].function, cm[0].line)):
299
+ # grouped: file, then function, one line per candidate
300
+ if (c.rel, c.function) != where:
301
+ if where is None or where[0] != c.rel:
302
+ print(f"\n{c.rel}")
303
+ print(f" {c.function + '()' if c.function else '(file scope)'}")
304
+ where = (c.rel, c.function)
305
+ print(f" {c.line:>5}: {c.text:<20} {c.rule}{' [' + c.symbol + ']' if c.symbol else ''}"
306
+ f"{' (marked)' if marked else ''}")
307
+ values = sorted({c.text for c, m in cands if not m and c.rule != "known algorithm constant"
308
+ and not c.text.startswith("table")}, key=lambda t: (len(t), t))
309
+ symbols = sorted({c.symbol for c, m in cands if not m and c.symbol})
310
+ print("\nTo mark them, add to .doppel/config.json (edit the lists first - only what is really secret):")
311
+ print(' "secret_values": [' + ", ".join(f'"{v}"' for v in values) + "],")
312
+ print(' "secret_symbols": [' + ", ".join(f'"{s}"' for s in symbols) + "]")
313
+ users = proj.secret_table_users()
314
+ if users:
315
+ print("\nFunctions that write values of a secret table as literals (hidden in the twin, but the "
316
+ "code around them may still tell; consider withholding them):")
317
+ for (rel, sym), n in sorted(users.items()):
318
+ print(f" {rel}::{sym} ({n} value(s))")
319
+ print(' add to "core_functions" in .doppel/config.json, or tick them in the desktop app\'s '
320
+ "Withheld functions")
321
+ return 0
322
+ rows = proj.secret_list()
323
+ if not rows:
324
+ print("No secret constants (run export after marking them).")
325
+ return 0
326
+ for r in rows:
327
+ value = r["literal"] if args.show_values else "(hidden - use --show-values)"
328
+ where = f"{r.get('file', '')}:{r.get('line', '')}" if r.get("file") else "(in a comment or string)"
329
+ print(f"{r['alias']} {r['type']:<6} {where:<40} {value}")
330
+ return 0
331
+
332
+
333
+ def _cmd_report(args) -> int:
334
+ rows = Project(args.project).exposure_report(by=args.by, since=args.since)
335
+ print("Exposure report - what was made available to an AI (not what it read)"
336
+ + (f", since {args.since}" if args.since else ""))
337
+ if not rows:
338
+ print("No functions found.")
339
+ return 0
340
+ if args.by == "function":
341
+ width = max(len(f"{r['file']}:{r['function']}") for r in rows)
342
+ print(f"{'function':<{width}} sends first last via")
343
+ for r in rows:
344
+ print(f"{r['file'] + ':' + r['function']:<{width}} {r['sends']:>5} {r['first'] or '-':<20} "
345
+ f"{r['last'] or '-':<20} {r['via']}")
346
+ return 0
347
+ width = max([len(r[args.by]) for r in rows] + [len(args.by)])
348
+ print(f"{args.by:<{width}} functions bodies sent share bodies withheld secrets withheld")
349
+ for r in rows:
350
+ print(f"{r[args.by]:<{width}} {r['functions']:>9} {r['sent']:>11} {r['share']:>5.0%} "
351
+ f"{r['withheld']:>15} {r['secrets']:>16}")
352
+ return 0
353
+
354
+
355
+ def _cmd_lookup(args) -> int:
356
+ lines = lookup(Project(args.project), args.name)
357
+ print("\n".join(lines) if lines else f"{args.name}: not in vault")
358
+ return 0 if lines else 1
359
+
360
+
361
+ def main(argv: list[str] | None = None) -> int:
362
+ ap = argparse.ArgumentParser(prog="doppel", description="Create an obfuscated twin of a code project for AI agents, and sync edits back.")
363
+ from . import __version__
364
+ ap.add_argument("--version", action="version", version=f"DoppelCode {__version__}")
365
+ sub = ap.add_subparsers(dest="cmd", required=True)
366
+
367
+ p = sub.add_parser("init", help="write a default .doppel/config.json")
368
+ p.add_argument("project")
369
+ p.set_defaults(func=_cmd_init)
370
+
371
+ p = sub.add_parser("export", help="create or refresh the obfuscated twin")
372
+ p.add_argument("project")
373
+ p.add_argument("--out", help="twin folder (default: remembered, or <parent>/obf_<hash>)")
374
+ p.add_argument("--force", action="store_true", help="overwrite un-imported twin changes")
375
+ p.add_argument("--data", choices=DATA_MODES,
376
+ help="copy: put the data files the code reads (named in strings, or in folders named in "
377
+ "strings) into the twin under their aliases. Saved in .doppel/config.json")
378
+ p.add_argument("--strings", choices=STRING_MODES,
379
+ help="hide: replace string literals by ids, keeping format specifiers; scrub: only names; "
380
+ "keep. Saved in .doppel/config.json")
381
+ p.add_argument("--comments", choices=COMMENT_MODES,
382
+ help="hide: replace whole comments by placeholders; scrub: only names; keep. Saved in "
383
+ ".doppel/config.json")
384
+ p.add_argument("--allow-over-budget", action="store_true",
385
+ help="export even if a folder goes over its exposure_budget (recorded in the ledger)")
386
+ p.add_argument("--build-names", choices=BUILD_NAME_MODES,
387
+ help="rename: also rename words in Makefile / CMake files made of the project's name parts "
388
+ "(TARGET := falcon_selftest -> w_0001; the build then produces a renamed binary). "
389
+ "Default keep. Saved in .doppel/config.json")
390
+ p.add_argument("-v", "--verbose", action="store_true")
391
+ p.set_defaults(func=_cmd_export)
392
+
393
+ p = sub.add_parser("import", help="restore twin edits into the original project")
394
+ p.add_argument("project")
395
+ p.add_argument("--to", help="write restored files to this folder instead of the project")
396
+ p.add_argument("--dry-run", action="store_true")
397
+ p.add_argument("--preview", metavar="DIR",
398
+ help="write the merged files to DIR (same relative paths) and change nothing in the project")
399
+ p.add_argument("--from-preview", metavar="DIR",
400
+ help="apply a preview made with --preview DIR; refused if the twin or the original changed since")
401
+ p.add_argument("--only", action="append", metavar="FILE",
402
+ help="with --from-preview: apply only this file (path in the project; repeat for more)")
403
+ p.add_argument("--apply-deletes", action="store_true", help="delete originals whose twin file was deleted")
404
+ p.add_argument("--rename", action="append", metavar="OLD=new",
405
+ help="give an alias the AI coined a real name (repeatable): --rename v_0048=nonce, "
406
+ "--rename \"str_0013=Decrypt failed\"")
407
+ p.add_argument("--accept", nargs="*", metavar="OLD",
408
+ help="keep these flagged aliases as they are (a known alias keeps its vault meaning); "
409
+ "without names: accept every finding")
410
+ p.set_defaults(func=_cmd_import)
411
+
412
+ p = sub.add_parser("check", help="round trip, leak scan and compile check")
413
+ p.add_argument("project")
414
+ p.add_argument("--no-compile", action="store_true")
415
+ p.add_argument("--objects", action="store_true", help="also compare generated machine code (.text)")
416
+ p.add_argument("--max-leaks", type=int, default=30, help="example leak lines to print (default 30)")
417
+ p.add_argument("--leaks-all", action="store_true", help="print every leak and hint line")
418
+ p.set_defaults(func=_cmd_check)
419
+
420
+ p = sub.add_parser("report", help="exposure report: which function bodies were made available to an AI")
421
+ p.add_argument("project")
422
+ p.add_argument("--by", choices=("folder", "file", "function"), default="folder")
423
+ p.add_argument("--since", help="only events from this date on (YYYY-MM-DD)")
424
+ p.set_defaults(func=_cmd_report)
425
+
426
+ p = sub.add_parser("secrets", help="secret constants: suggest candidates, or list the marked ones")
427
+ p.add_argument("action", choices=("suggest", "list"))
428
+ p.add_argument("project")
429
+ p.add_argument("--show-values", action="store_true", help="list: also print the real values")
430
+ p.add_argument("--all", action="store_true", help="suggest: every candidate, grouped by file and function")
431
+ p.add_argument("--top", type=int, default=50, help="suggest: how many ranked candidates to show (default 50)")
432
+ p.set_defaults(func=_cmd_secrets)
433
+
434
+ p = sub.add_parser("withhold", help="withheld functions: list them, release some for one export, or "
435
+ "give one a purpose line for the AI")
436
+ p.add_argument("action", choices=("list", "release", "purpose"))
437
+ p.add_argument("project")
438
+ p.add_argument("ids", nargs="*", help="release: B_ ids (see 'list'); purpose: one B_ id, then the text")
439
+ p.add_argument("--reason", help="release: why (kept in the exposure ledger)")
440
+ p.set_defaults(func=_cmd_withhold)
441
+
442
+ p = sub.add_parser("lookup", help="translate a name in either direction")
443
+ p.add_argument("project")
444
+ p.add_argument("name")
445
+ p.set_defaults(func=_cmd_lookup)
446
+
447
+ args = ap.parse_args(argv)
448
+ project = getattr(args, "project", None)
449
+ if project and state_dir_name(Path(project).resolve()) == LEGACY_STATE_DIR:
450
+ print("note: this project still uses the .cobf folder from before the rename; DoppelCode reads it as it is. "
451
+ "Rename it to .doppel (same content) when convenient: 'ren .cobf .doppel' (Windows) or "
452
+ "'mv .cobf .doppel'.", file=sys.stderr)
453
+ try:
454
+ return args.func(args)
455
+ except DoppelError as e:
456
+ print(f"error: {e}", file=sys.stderr)
457
+ return 2
458
+
459
+
460
+
461
+ if __name__ == "__main__":
462
+ sys.exit(main())