template-press 3.3.0__tar.gz → 3.4.0__tar.gz

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.
Files changed (26) hide show
  1. {template_press-3.3.0 → template_press-3.4.0}/PKG-INFO +1 -1
  2. {template_press-3.3.0 → template_press-3.4.0}/pyproject.toml +1 -1
  3. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/press_cli.py +8 -5
  4. template_press-3.4.0/src/template_press/rebrand/check_tools.py +61 -0
  5. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/cli.py +152 -45
  6. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/engine.py +109 -22
  7. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/receipt.py +45 -1
  8. template_press-3.4.0/src/template_press/rebrand/regen.py +668 -0
  9. template_press-3.4.0/src/template_press/rebrand/reset.py +317 -0
  10. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/rules.py +252 -14
  11. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/safety.py +19 -18
  12. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/verifier.py +3 -1
  13. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/verify_cli.py +47 -2
  14. {template_press-3.3.0 → template_press-3.4.0}/README.md +0 -0
  15. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/__init__.py +0 -0
  16. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/py.typed +0 -0
  17. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/__init__.py +0 -0
  18. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/config.py +0 -0
  19. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/discovery.py +0 -0
  20. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/doctor.py +0 -0
  21. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/identity.py +0 -0
  22. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/ignores.py +0 -0
  23. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/matcher.py +0 -0
  24. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/sandbox.py +0 -0
  25. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/synthesize.py +0 -0
  26. {template_press-3.3.0 → template_press-3.4.0}/src/template_press/rebrand/verify_config.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: template_press
3
- Version: 3.3.0
3
+ Version: 3.4.0
4
4
  Summary: Standalone rebrand utility — press a new identity onto an external target repo
5
5
  Author: Steve Morin
6
6
  Author-email: Steve Morin <steve.morin@gmail.com>
@@ -20,7 +20,7 @@
20
20
  [project]
21
21
  name = "template_press"
22
22
  # ITM-070 — static version (ADR-06 cutover). release-please bumps this.
23
- version = "3.3.0"
23
+ version = "3.4.0"
24
24
  description = "Standalone rebrand utility — press a new identity onto an external target repo"
25
25
  readme = "README.md"
26
26
  requires-python = ">=3.12"
@@ -10,8 +10,8 @@ from __future__ import annotations
10
10
  import sys
11
11
 
12
12
  from template_press import __version__
13
+ from template_press.rebrand import check_tools, verify_cli
13
14
  from template_press.rebrand import cli as rebrand_cli
14
- from template_press.rebrand import verify_cli
15
15
 
16
16
  _RESERVED = {"provision", "status"}
17
17
 
@@ -19,10 +19,11 @@ _USAGE = """\
19
19
  usage: press <command> [options]
20
20
 
21
21
  commands:
22
- rebrand press an identity onto a target repo (press rebrand --help)
23
- verify check that a template presses cleanly (press verify --help)
24
- provision configure a target's features (coming in M6)
25
- status report a target's provisioned state (coming in M6)
22
+ rebrand press an identity onto a target repo (press rebrand --help)
23
+ verify check that a template presses cleanly (press verify --help)
24
+ check-tools report whether declared commands resolve (press check-tools --help)
25
+ provision configure a target's features (coming in M6)
26
+ status report a target's provisioned state (coming in M6)
26
27
  """
27
28
 
28
29
 
@@ -39,6 +40,8 @@ def main(argv: list[str] | None = None) -> int:
39
40
  return rebrand_cli.main(rest)
40
41
  if verb == "verify":
41
42
  return verify_cli.verify_command(rest)
43
+ if verb == "check-tools":
44
+ return check_tools.check_tools_command(rest)
42
45
  if verb in _RESERVED:
43
46
  print(
44
47
  f"error: '{verb}' is part of the Provision phase and is not "
@@ -0,0 +1,61 @@
1
+ """press check-tools — declared-tool availability report (P04 D4).
2
+
3
+ Resolves ``argv[0]`` of every declared ``[[regenerate]]`` command plus
4
+ ``git`` — the only tool press itself contributes after D1 — exactly as
5
+ execution would (D2): path-qualified names against the TARGET root, bare
6
+ names on the deny-by-default effective PATH. Reads config, writes
7
+ nothing, executes nothing. Exit 0 all found, 1 any missing, 2
8
+ config/usage error.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import argparse
14
+ import sys
15
+ import tomllib
16
+ from pathlib import Path
17
+
18
+ from template_press.rebrand.regen import command_env, resolve_executable
19
+ from template_press.rebrand.rules import ValidationError, load_rules
20
+
21
+
22
+ def check_tools_command(argv: list[str] | None = None) -> int:
23
+ parser = argparse.ArgumentParser(prog="press check-tools", description=__doc__)
24
+ parser.add_argument("--target", type=Path, required=True)
25
+ args = parser.parse_args(argv)
26
+
27
+ target = args.target.resolve()
28
+ if not target.is_dir():
29
+ print(f"error: target {target} is not a directory", file=sys.stderr)
30
+ return 2
31
+ try:
32
+ rules = load_rules(target)
33
+ except (
34
+ ValidationError,
35
+ tomllib.TOMLDecodeError,
36
+ UnicodeDecodeError,
37
+ OSError,
38
+ ) as exc:
39
+ # The same configuration exception set the rebrand and verify entry
40
+ # points normalize to exit 2 — never a traceback.
41
+ print(f"error: {exc}", file=sys.stderr)
42
+ return 2
43
+
44
+ missing = 0
45
+ reports: list[str] = []
46
+ git = resolve_executable(target, "git", command_env(()))
47
+ if git is None:
48
+ missing += 1
49
+ reports.append("git — missing (press itself needs it)")
50
+ else:
51
+ reports.append(f"git — {git}")
52
+ for rule in rules.regenerate:
53
+ argv0 = rule.command[0]
54
+ found = resolve_executable(target, argv0, command_env(rule.env))
55
+ if found is None:
56
+ missing += 1
57
+ reports.append(f"{argv0} — missing (declared to regenerate {rule.file})")
58
+ else:
59
+ reports.append(f"{argv0} — {found} (regenerates {rule.file})")
60
+ print("\n".join(reports))
61
+ return 1 if missing else 0
@@ -24,7 +24,6 @@ from template_press.rebrand.config import (
24
24
  from template_press.rebrand.discovery import discover, mismatches
25
25
  from template_press.rebrand.doctor import find_leaks, render_leak_report
26
26
  from template_press.rebrand.engine import (
27
- ApplyReport,
28
27
  apply,
29
28
  build_plan,
30
29
  rendered_replace_rules,
@@ -37,13 +36,34 @@ from template_press.rebrand.identity import (
37
36
  display_forms,
38
37
  token_occurs,
39
38
  )
40
- from template_press.rebrand.receipt import read_receipt, write_receipt
41
- from template_press.rebrand.rules import DEFAULT_RULES, Rules, load_rules
39
+ from template_press.rebrand.receipt import (
40
+ RECEIPT_REL,
41
+ invalidate_receipt,
42
+ read_receipt,
43
+ write_receipt,
44
+ )
45
+ from template_press.rebrand.regen import (
46
+ RegenerationPlan,
47
+ execute_regenerations,
48
+ final_validation_pass,
49
+ plan_regenerate_commands,
50
+ preflight_excluded_files,
51
+ preflight_regenerate_outputs,
52
+ render_regenerate_plan,
53
+ restore_control_files,
54
+ snapshot_control_files,
55
+ validate_control_files,
56
+ )
57
+ from template_press.rebrand.reset import (
58
+ apply_resets,
59
+ preflight_reset_targets,
60
+ render_reset_plan,
61
+ )
62
+ from template_press.rebrand.rules import DEFAULT_RULES, ResetRule, Rules, load_rules
42
63
  from template_press.rebrand.safety import (
43
64
  SafetyError,
44
65
  git_hardening_args,
45
66
  scrubbed_git_env,
46
- scrubbed_uv_env,
47
67
  write_control,
48
68
  )
49
69
 
@@ -231,6 +251,11 @@ def main(argv: list[str] | None = None) -> int:
231
251
  parser.add_argument("--dry-run", action="store_true")
232
252
  parser.add_argument("--force", action="store_true")
233
253
  parser.add_argument("--allow-dirty", action="store_true")
254
+ parser.add_argument(
255
+ "--verbose",
256
+ action="store_true",
257
+ help="show the bounded reset content excerpts in the plan",
258
+ )
234
259
  args = parser.parse_args(argv)
235
260
 
236
261
  target = args.target.resolve()
@@ -285,7 +310,35 @@ def main(argv: list[str] | None = None) -> int:
285
310
  return 2
286
311
 
287
312
  plan = build_plan(target, source, dest, rules)
313
+ # Plan-time gates for both declared mechanisms (P04 D1/D2/D5, P05
314
+ # D5): output/target state, stale path-bearing argv against THIS
315
+ # plan's rename set, executable resolution under the deny-by-default
316
+ # env, stub scans, and the translated reset-path identity scan — all
317
+ # before any write, under the exit-2-nothing-written contract
318
+ # (dry-run included).
319
+ gate_problems = preflight_excluded_files(target, rules)
320
+ gate_problems += preflight_regenerate_outputs(target, rules)
321
+ regen_plans, plan_problems = plan_regenerate_commands(
322
+ target, rules.regenerate, renamed=frozenset(plan.renames)
323
+ )
324
+ gate_problems += plan_problems
325
+ reset_previews, reset_problems = preflight_reset_targets(
326
+ target, rules, source=source, dest=dest, renames=plan.renames
327
+ )
328
+ gate_problems += reset_problems
329
+ if gate_problems:
330
+ print(
331
+ "error: declared regeneration/reset cannot run — nothing written:",
332
+ file=sys.stderr,
333
+ )
334
+ for problem in gate_problems:
335
+ print(f" {problem}", file=sys.stderr)
336
+ return 2
288
337
  print(plan.render())
338
+ if regen_plans:
339
+ print(render_regenerate_plan(regen_plans))
340
+ if reset_previews:
341
+ print(render_reset_plan(reset_previews, verbose=args.verbose))
289
342
  strays = stray_press_dirs(target)
290
343
  if strays:
291
344
  print(
@@ -304,6 +357,10 @@ def main(argv: list[str] | None = None) -> int:
304
357
  # LAST gate before apply: every exit-2 path (rules/plan included) is
305
358
  # behind us, so the deferred source-config write can no longer be
306
359
  # followed by a "no writes" exit code.
360
+ if args.force and invalidate_receipt(target):
361
+ # Before the first mutation (P04-T16): a failed forced re-press
362
+ # must not leave the old receipt advertising a verified press.
363
+ print(f"prior receipt invalidated ({RECEIPT_REL})")
307
364
  if write_pending:
308
365
  write_control(target, SOURCE_CONFIG_REL, render_source_config(source))
309
366
  print(f"wrote {SOURCE_CONFIG_REL} from discovery")
@@ -315,47 +372,17 @@ def main(argv: list[str] | None = None) -> int:
315
372
  SafetyError,
316
373
  ) as exc:
317
374
  return _fail(str(exc))
318
- outcome = _press(target, source, dest, rules)
375
+ outcome = _press(
376
+ target,
377
+ source,
378
+ dest,
379
+ rules,
380
+ regen_plans,
381
+ [(preview.rule, preview.stub_text) for preview in reset_previews],
382
+ )
319
383
  return 1 if (outcome.env_error is not None or outcome.leaked) else 0
320
384
 
321
385
 
322
- def _regenerate_lockfiles(target: Path, rules: Rules, report: ApplyReport) -> list[str]:
323
- """Regenerate listed lockfiles; return the ones that FAILED to regenerate.
324
-
325
- A lockfile is excluded from both rewriting and the doctor scan, so a
326
- failed regeneration would leave source-identity content behind invisibly.
327
- Callers must treat failures as verification failures (no receipt).
328
- """
329
- failed: list[str] = []
330
- for lockfile in rules.regenerate:
331
- lockpath = target / lockfile
332
- if lockpath.is_symlink(): # lstat-based, no-follow — check first
333
- report.skipped.append(
334
- f"regenerate {lockfile} (symlink — refusing to write through)"
335
- )
336
- failed.append(lockfile)
337
- continue
338
- if not lockpath.is_file():
339
- continue
340
- if lockfile == "uv.lock":
341
- result = subprocess.run( # nosec B603 B607
342
- ["uv", "lock"], # noqa: S607
343
- cwd=target,
344
- capture_output=True,
345
- text=True,
346
- env=scrubbed_uv_env(), # G5: no UV_* override can steer the write
347
- )
348
- if result.returncode == 0:
349
- report.regenerated.append(lockfile)
350
- else:
351
- report.skipped.append(f"regenerate {lockfile} (uv lock failed)")
352
- failed.append(lockfile)
353
- else:
354
- report.skipped.append(f"regenerate {lockfile} (no regenerator)")
355
- failed.append(lockfile)
356
- return failed
357
-
358
-
359
386
  @dataclass
360
387
  class PressOutcome:
361
388
  """Structurally distinguishes an env/tool failure from a doctor leak.
@@ -371,13 +398,41 @@ class PressOutcome:
371
398
 
372
399
 
373
400
  def _press(
374
- target: Path, source: Identity, dest: Identity, rules: Rules
401
+ target: Path,
402
+ source: Identity,
403
+ dest: Identity,
404
+ rules: Rules,
405
+ regen_plans: list[RegenerationPlan],
406
+ resets: list[tuple[ResetRule, str]],
375
407
  ) -> PressOutcome:
376
408
  report = None
377
409
  try:
410
+ # Reset takes position ZERO (P05 D5): declared paths are consumed in
411
+ # SOURCE coordinates before the rename pass moves anything. A raise
412
+ # here aborts the press (no receipt) — git is the undo button.
413
+ reset_done = apply_resets(target, resets)
378
414
  report = apply(target, source, dest, rules)
379
- failed_locks = _regenerate_lockfiles(target, rules, report)
415
+ report.reset.extend(reset_done)
416
+ # Declared commands run against the FINAL tree: declared paths are
417
+ # translated through the apply-time rename report (P04 D1). The
418
+ # press-owned control files are snapshotted before the first
419
+ # command and revalidated after the last (D1 reservation is not
420
+ # protection — a command can mutate arbitrary files).
421
+ control_snapshot = snapshot_control_files(target) if regen_plans else {}
422
+ failed_locks = execute_regenerations(
423
+ target,
424
+ regen_plans,
425
+ dict(report.renamed),
426
+ report,
427
+ source=source,
428
+ dest=dest,
429
+ rules=rules,
430
+ )
380
431
  if failed_locks:
432
+ # A failed command must not leave a tampered/planted control
433
+ # file behind (codex 3654736777) — restore the snapshot before
434
+ # reporting; {} when no commands ran.
435
+ restore_control_files(target, control_snapshot)
381
436
  print(
382
437
  f"error: lockfile regeneration failed for "
383
438
  f"{', '.join(failed_locks)} — the lockfile still carries the old "
@@ -393,6 +448,35 @@ def _press(
393
448
  report.regenerated,
394
449
  env_error=f"lockfile regeneration failed for {', '.join(failed_locks)}",
395
450
  )
451
+ if regen_plans:
452
+ # Final validation pass (D3): outputs, reset stubs, and the
453
+ # control-file snapshot — a later command corrupting an earlier
454
+ # result is invisible to every downstream inventory.
455
+ post_problems = final_validation_pass(
456
+ target,
457
+ regen_plans,
458
+ resets,
459
+ dict(report.renamed),
460
+ source=source,
461
+ dest=dest,
462
+ rules=rules,
463
+ )
464
+ post_problems += validate_control_files(target, control_snapshot)
465
+ if post_problems:
466
+ restore_control_files(target, control_snapshot)
467
+ print(
468
+ "error: post-regeneration validation failed — no receipt written:",
469
+ file=sys.stderr,
470
+ )
471
+ for problem in post_problems:
472
+ print(f" {problem}", file=sys.stderr)
473
+ print(report.render(), file=sys.stderr)
474
+ return PressOutcome(
475
+ False,
476
+ report.renamed,
477
+ report.regenerated,
478
+ env_error="post-regeneration validation failed",
479
+ )
396
480
  # Verification never honors target-side REWRITE exclusions (EMP-01):
397
481
  # neither extra_exclude_files nor extra_exclude_dirs can hide content
398
482
  # from the doctor. The only sanctioned exemption is the explicit,
@@ -419,7 +503,30 @@ def _press(
419
503
  return PressOutcome(
420
504
  True, report.renamed, report.regenerated, env_error=None
421
505
  )
422
- receipt_path = write_receipt(target, source, dest, report)
506
+ receipt_path = write_receipt(
507
+ target,
508
+ source,
509
+ dest,
510
+ report,
511
+ regenerations=[
512
+ (plan.rule.file, (plan.executable, *plan.rule.command[1:]))
513
+ for plan in regen_plans
514
+ ],
515
+ exempt=[
516
+ *(
517
+ (
518
+ rel,
519
+ "regenerated by declared command; validated by the "
520
+ "press's post-command scan (hermetic verify skips it)",
521
+ )
522
+ for rel in report.regenerated
523
+ ),
524
+ *(
525
+ (rel, "reset to the declared stub (scanned at plan time)")
526
+ for rel in report.reset
527
+ ),
528
+ ],
529
+ )
423
530
  write_control(target, SOURCE_CONFIG_REL, render_source_config(dest))
424
531
  print(report.render())
425
532
  if report.skipped:
@@ -9,8 +9,9 @@ TARGET is the undo button (`git checkout . && git clean -fd`).
9
9
  from __future__ import annotations
10
10
 
11
11
  import os
12
+ import stat
12
13
  import subprocess # nosec B404 — git ls-files enumerates the target
13
- from collections.abc import Collection
14
+ from collections.abc import Collection, Mapping
14
15
  from dataclasses import dataclass, field
15
16
  from pathlib import Path
16
17
 
@@ -24,7 +25,6 @@ from template_press.rebrand.identity import (
24
25
  token_occurs,
25
26
  )
26
27
  from template_press.rebrand.rules import (
27
- DEFAULT_RULES,
28
28
  ReplaceRule,
29
29
  Rules,
30
30
  render_replace_pattern,
@@ -35,6 +35,7 @@ from template_press.rebrand.safety import (
35
35
  SafetyError,
36
36
  assert_ancestors_real,
37
37
  assert_under_root,
38
+ chmod_nofollow,
38
39
  git_hardening_args,
39
40
  safe_write,
40
41
  scrubbed_git_env,
@@ -71,6 +72,13 @@ ROOT_CONTROL: frozenset[str] = frozenset(
71
72
  }
72
73
  )
73
74
 
75
+ # The tool-side cap on scan-exemptible regeneration outputs (P04 D3): a
76
+ # target's declaration is necessary but not sufficient — the filename must
77
+ # also be on this explicit list. Its own constant, NEVER derived from
78
+ # ``exclude_files`` (which would wrongly exempt CHANGELOG.md-class artifacts)
79
+ # nor from a rules default (removed with P04 D1).
80
+ REGENERATE_EXEMPTIBLE: frozenset[str] = frozenset({"uv.lock", "bun.lock"})
81
+
74
82
 
75
83
  @dataclass(frozen=True)
76
84
  class PathEntry:
@@ -97,6 +105,11 @@ class PlanItem:
97
105
  @dataclass
98
106
  class Plan:
99
107
  items: list[PlanItem] = field(default_factory=list)
108
+ # The shallowest-prefix rename map (source → destination POSIX rel
109
+ # paths) this plan implies — structured data for plan-time consumers
110
+ # (stale-argv membership, reset-path translation), so nothing parses it
111
+ # back out of rendered PlanItem strings.
112
+ renames: dict[str, str] = field(default_factory=dict)
100
113
 
101
114
  def render(self) -> str:
102
115
  if not self.items:
@@ -319,33 +332,64 @@ def rewrite_paths(target: Path, rules: Rules) -> list[Path]:
319
332
  return iter_target_files(target, rules)
320
333
 
321
334
 
322
- def scan_paths(target: Path, rules: Rules) -> list[PathEntry]:
335
+ def exempt_regenerated_paths(
336
+ rules: Rules, renamed: Mapping[str, str] | Collection[tuple[str, str]] = ()
337
+ ) -> list[tuple[str, str]]:
338
+ """(translated_path, reason) for every declared output the hermetic
339
+ scan may exempt (P04 D3): basename on the explicit tool cap AND a
340
+ target declaration for that exact path, translated through the renames
341
+ (the sandbox tree has moved by scan time). The exemption is a coverage
342
+ gap — callers must LIST these as not-verified, never omit them.
343
+ """
344
+ renames = dict(renamed)
345
+ out: list[tuple[str, str]] = []
346
+ for rule in rules.regenerate:
347
+ translated = translate_path(rule.file, renames)
348
+ if translated.rsplit("/", 1)[-1] in REGENERATE_EXEMPTIBLE:
349
+ out.append(
350
+ (
351
+ translated,
352
+ "declared regeneration — rebuilt and scanned by the real "
353
+ "press's post-command check; the hermetic sandbox never "
354
+ "runs commands, so verify cannot certify it",
355
+ )
356
+ )
357
+ return out
358
+
359
+
360
+ def scan_paths(
361
+ target: Path,
362
+ rules: Rules,
363
+ renamed: Mapping[str, str] | Collection[tuple[str, str]] = (),
364
+ ) -> list[PathEntry]:
323
365
  """``copy_paths`` minus ``ROOT_CONTROL``, regenerable lockfiles, and
324
366
  ``verify_ignore`` dirs — the no-leak scan's candidate set.
325
367
 
326
368
  A lockfile is scan-exempt only when it is regenerated FRESH after apply,
327
369
  which requires it to be in BOTH:
328
370
 
329
- - the TARGET's effective ``rules.regenerate`` — press actually regenerates
330
- it for THIS target (so ``regenerate = []`` re-includes uv.lock: press
331
- neither rewrites it, since it is in ``exclude_files``, nor regenerates
332
- it, so a stale token must be scanned — keying on ``DEFAULT_RULES`` ALONE
333
- would FALSE-CLEAN it); AND
334
- - the tool's OWN ``DEFAULT_RULES.regenerate`` ∩ ``DEFAULT_RULES.exclude_files``
335
- — the tool has a real regenerator for it (EMP-01/F5: a target's
336
- ``press-rules.toml`` must not be able to hide content from the scan by
337
- declaring ``regenerate = ["bun.lock"]`` for a lockfile press never
338
- regenerates).
339
-
340
- Everything else stays: non-regenerable lockfiles (``bun.lock``,
341
- ``package-lock.json``), a force-added gitignored file, and symlink/
342
- gitlink entries (type-tagged, for Task 7).
371
+ - the TARGET's effective ``rules.regenerate`` declarations — press
372
+ actually regenerates it for THIS target (no declaration → no rebuild →
373
+ a stale token must be scanned; keying on a tool-side list ALONE would
374
+ FALSE-CLEAN it); AND
375
+ - the tool's OWN ``REGENERATE_EXEMPTIBLE`` constant — the explicit cap on
376
+ what a target can exempt (EMP-01/F5: a target's ``press-rules.toml``
377
+ must not be able to hide arbitrary content from the scan by declaring a
378
+ regeneration for it). Deliberately its own constant, never derived
379
+ from ``exclude_files`` — that would wrongly exempt ``CHANGELOG.md``-
380
+ class artifacts (P04 D3).
381
+
382
+ Everything else stays: non-exemptible lockfiles (``package-lock.json``),
383
+ a force-added gitignored file, and symlink/gitlink entries (type-tagged,
384
+ for Task 7).
385
+
386
+ ``renamed`` (the press's rename map/report) translates declared
387
+ source-coordinate outputs to their post-rename locations before the
388
+ exact-path comparison — basename alone matches a nested
389
+ ``packages/demo_widget/bun.lock``, but the path half would fail forever
390
+ without the translation (P04 D3).
343
391
  """
344
- exempt_lockfiles = (
345
- set(rules.regenerate)
346
- & set(DEFAULT_RULES.regenerate)
347
- & DEFAULT_RULES.exclude_files
348
- )
392
+ exempt_lockfiles = {p for p, _ in exempt_regenerated_paths(rules, renamed)}
349
393
  out: list[PathEntry] = []
350
394
  for entry in copy_paths(target):
351
395
  posix = entry.rel.as_posix()
@@ -700,20 +744,58 @@ def build_plan(target: Path, source: Identity, dest: Identity, rules: Rules) ->
700
744
  break
701
745
  for old, new in sorted(rename_map.items()):
702
746
  plan.items.append(PlanItem("rename", old, f"→ {new}"))
747
+ plan.renames.update(rename_map)
703
748
  return plan
704
749
 
705
750
 
751
+ def translate_path(posix: str, renames: Mapping[str, str]) -> str:
752
+ """Map a SOURCE-coordinate rel path through a shallowest-prefix rename
753
+ map to its post-rename location; unrenamed paths pass through.
754
+
755
+ Declared paths (regeneration outputs, reset targets) are written in
756
+ source coordinates, but checks that model the POST-rename tree must
757
+ address the moved location — validating the declared path would report
758
+ a validly moved file as missing (P04 D1/D3).
759
+
760
+ ``_apply_renames`` runs MULTIPLE shallowest-prefix passes, so a
761
+ later-pass pair's old side is in INTERMEDIATE (already-partly-renamed)
762
+ coordinates — translation must chain to a fixpoint, longest matching
763
+ prefix per step, mirroring ``ignores.build_forward_map``'s reverse
764
+ fixpoint. Convergence is guaranteed for real maps (the collision gate
765
+ forbids dest identities embedding source tokens); the bound raises
766
+ rather than hangs on a pathological cycle.
767
+ """
768
+ current = posix
769
+ for _ in range(len(renames) + 1):
770
+ best: tuple[int, str, str] | None = None
771
+ for old, new in renames.items():
772
+ if current == old or current.startswith(old + "/"):
773
+ depth = old.count("/")
774
+ if best is None or depth > best[0]:
775
+ best = (depth, old, new)
776
+ if best is None:
777
+ return current
778
+ _, old, new = best
779
+ current = new if current == old else new + current[len(old) :]
780
+ raise ValidationError(
781
+ f"path translation did not converge for {posix!r} after "
782
+ f"{len(renames) + 1} passes (rename map: {dict(renames)!r})"
783
+ )
784
+
785
+
706
786
  @dataclass
707
787
  class ApplyReport:
708
788
  replaced: list[str] = field(default_factory=list)
709
789
  renamed: list[tuple[str, str]] = field(default_factory=list)
710
790
  skipped: list[str] = field(default_factory=list)
711
791
  regenerated: list[str] = field(default_factory=list)
792
+ reset: list[str] = field(default_factory=list) # declared stubs written
712
793
 
713
794
  def render(self) -> str:
714
795
  return (
715
796
  f"Applied: {len(self.replaced)} replaced, "
716
797
  f"{len(self.renamed)} renamed, "
798
+ f"{len(self.reset)} reset, "
717
799
  f"{len(self.regenerated)} regenerated, "
718
800
  f"{len(self.skipped)} skipped."
719
801
  )
@@ -756,7 +838,12 @@ def _apply_replacements(
756
838
  # atomicity already protects an external hardlink WITHOUT falsely
757
839
  # refusing a legitimate in-repo hardlinked file. A symlink LEAF
758
840
  # never reaches here — _read_text returns None for it upstream.
841
+ # The fresh inode starts from mkstemp's 0600, so the original
842
+ # permission bits are restored afterwards — a rewritten 0755
843
+ # helper must not come out non-executable (P04 D1).
844
+ mode = stat.S_IMODE(os.lstat(path).st_mode)
759
845
  safe_write(target, rel, new_text, refuse_hardlink=False)
846
+ chmod_nofollow(path, mode)
760
847
  report.replaced.append(rel)
761
848
 
762
849
 
@@ -7,6 +7,7 @@ answered. Its presence also guards re-runs (require --force).
7
7
 
8
8
  from __future__ import annotations
9
9
 
10
+ from collections.abc import Sequence
10
11
  from datetime import UTC, datetime
11
12
  from pathlib import Path
12
13
 
@@ -25,6 +26,23 @@ def read_receipt(target: Path) -> str | None:
25
26
  return path.read_text(encoding="utf-8")
26
27
 
27
28
 
29
+ def invalidate_receipt(target: Path) -> bool:
30
+ """Remove the prior receipt, if any; True when one was removed.
31
+
32
+ A forced re-press consumes its predecessor's receipt after the plan
33
+ gates pass and BEFORE the first mutation (P04-T16): a failed forced
34
+ re-press must not leave the old receipt advertising a verified press.
35
+ No-follow — a symlinked press dir or receipt is left alone (the press
36
+ refuses such a layout at write time anyway).
37
+ """
38
+ press_dir = target / RECEIPT_REL.parent
39
+ path = target / RECEIPT_REL
40
+ if press_dir.is_symlink() or path.is_symlink() or not path.is_file():
41
+ return False
42
+ path.unlink()
43
+ return True
44
+
45
+
28
46
  def _identity_table(name: str, identity: Identity) -> list[str]:
29
47
  lines = [f"[press.{name}]"]
30
48
  lines += [f"{k} = {toml_string(v)}" for k, v in identity.as_dict_prompted().items()]
@@ -32,7 +50,12 @@ def _identity_table(name: str, identity: Identity) -> list[str]:
32
50
 
33
51
 
34
52
  def write_receipt(
35
- target: Path, source: Identity, dest: Identity, report: ApplyReport
53
+ target: Path,
54
+ source: Identity,
55
+ dest: Identity,
56
+ report: ApplyReport,
57
+ regenerations: Sequence[tuple[str, Sequence[str]]] = (),
58
+ exempt: Sequence[tuple[str, str]] = (),
36
59
  ) -> Path:
37
60
  stamp = datetime.now(UTC).isoformat(timespec="seconds")
38
61
  lines = [
@@ -50,7 +73,28 @@ def write_receipt(
50
73
  "[press.counts]",
51
74
  f"replaced = {len(report.replaced)}",
52
75
  f"renamed = {len(report.renamed)}",
76
+ f"reset = {len(report.reset)}",
53
77
  f"regenerated = {len(report.regenerated)}",
54
78
  f"skipped = {len(report.skipped)}",
55
79
  ]
80
+ # Each regeneration's RESOLVED argv (P04 D5 revision): under plan→apply
81
+ # nothing stops a config change between two runs, so the receipt is the
82
+ # only artifact recording what actually ran.
83
+ for file, argv in regenerations:
84
+ lines += [
85
+ "",
86
+ "[[press.regenerate]]",
87
+ f"file = {toml_string(file)}",
88
+ "argv = [" + ", ".join(toml_string(a) for a in argv) + "]",
89
+ ]
90
+ # Machine-readable coverage record (P04 D3): every file the ordinary
91
+ # doctor/verify inventories skip, with the mechanism that covered it —
92
+ # the gap stays visible and deliberate, never an unchecked free pass.
93
+ for file, reason in exempt:
94
+ lines += [
95
+ "",
96
+ "[[press.exempt]]",
97
+ f"file = {toml_string(file)}",
98
+ f"reason = {toml_string(reason)}",
99
+ ]
56
100
  return write_control(target, RECEIPT_REL, "\n".join(lines) + "\n")