From 66544caea6582cbcb3cad0bde3714df645d1d97a Mon Sep 17 00:00:00 2001 From: kj Date: Sat, 21 Nov 2026 20:41:41 -0300 Subject: [PATCH] fix(cli): repair legacy core ledgers and make --keep-local durable Store canonical core hashes in lock.core, add core.schema and repair legacy ledgers from the registered commit before deciding drift. Skipped --keep-local files remain tracked with the target canonical hash, fail closed when the old core cannot be resolved, and update core reports per-file actions. --- README.org | 23 +- .../src/Toolbox/Commands/AdoptCommand.php | 1 + .../src/Toolbox/Commands/UpdateCommand.php | 14 ++ .../commands/src/Toolbox/CoreProvider.php | 71 ++++++ packages/commands/src/Toolbox/FileSync.php | 71 ++++-- packages/commands/src/Toolbox/Installer.php | 67 +++++- packages/commands/src/Toolbox/Lock.php | 13 +- tests/group3_state_test.php | 24 ++ tests/group7_commands_test.php | 221 ++++++++++++++++++ tests/group9_absorb_test.php | 1 + 10 files changed, 471 insertions(+), 35 deletions(-) diff --git a/README.org b/README.org index e2b1e1b..3b56d05 100644 --- a/README.org +++ b/README.org @@ -123,10 +123,14 @@ se bloquea y pide =--force=, =--backup= o =--keep-local=. #+BEGIN_SRC sh duckbrain update core # sólo el núcleo duckbrain update http # un paquete -duckbrain update # todo: catálogo -> core -> componentes +duckbrain update # componentes instalados duckbrain update --dry-run # muestra el plan sin escribir #+END_SRC +=update core= repara el ledger del core si viene de una versión antigua y +reporta el resultado por archivo (=written=, =overwritten=, =backed_up=, +=skipped=, =removed=, =aborted=) más un resumen. + ** =duckbrain list= / =duckbrain doctor= / =duckbrain catalog= / =duckbrain adopt= - =list=: core y componentes instalados con versión y modo. @@ -174,8 +178,21 @@ Así =crypto/src/Libs/Crypto.php= → =src/Libs/Crypto.php= y - =.duckbrain/lock.json=: lo que *tienes* (core y componentes, con versión, commit del toolbox y hash por archivo). +El hash de cada archivo del core es siempre el *canónico* de la versión +registrada, nunca el del archivo en disco. Así el drift se deriva de una fuente +fiable: =sha256(disco) != lock=. El bloque =core= lleva un =schema= (2 para este +formato) que permite reconocer ledgers heredados. + +Los locks creados antes de v0.2.9 guardaron en algunos casos el hash local en +lugar del canónico. La primera operación de core sobre ese proyecto recomputa +los hashes desde el =commit= registrado y migra el ledger sin tocar archivos. Si +la versión vieja del core no está disponible, la operación se detiene en lugar +de arriesgar una escritura destructiva. + Los hashes permiten detectar ediciones locales. La actualización respeta lo que -editaste y te pregunta antes de pisarlo. +editaste y te pregunta antes de pisarlo. =--keep-local= es durable: el archivo +saltado queda registrado con el canónico de la versión destino y se vuelve a +proteger en las actualizaciones siguientes, no sólo en la primera. * Migrar un proyecto existente @@ -209,7 +226,7 @@ Cómo trata =adopt= cada archivo: |------------------------------+--------------------------------------+-------------| | Coincide con el catálogo | Lo registra como =adopted= | No | | Existe pero difiere | Lo registra con =origin: local= | No | -| Del core (existe en el core) | Registra el hash actual en =lock.core= | No | +| Del core (existe en el core) | Registra el hash canónico en =lock.core= | No | | Ajeno al core/addons | No lo toca | No | Las copias divergentes quedan marcadas como *edición local*: un =update= diff --git a/packages/commands/src/Toolbox/Commands/AdoptCommand.php b/packages/commands/src/Toolbox/Commands/AdoptCommand.php index dc91fcb..db14d51 100644 --- a/packages/commands/src/Toolbox/Commands/AdoptCommand.php +++ b/packages/commands/src/Toolbox/Commands/AdoptCommand.php @@ -152,6 +152,7 @@ final class AdoptCommand extends Command if (!$dryRun) { $lock->setCore([ + 'schema' => 2, 'version' => $provider->version(), 'commit' => $provider->commit(), 'files' => $files, diff --git a/packages/commands/src/Toolbox/Commands/UpdateCommand.php b/packages/commands/src/Toolbox/Commands/UpdateCommand.php index 49b5109..a7e47cb 100644 --- a/packages/commands/src/Toolbox/Commands/UpdateCommand.php +++ b/packages/commands/src/Toolbox/Commands/UpdateCommand.php @@ -24,6 +24,20 @@ final class UpdateCommand extends Command if (($parsed['args'][0] ?? null) === 'core') { $provider = $this->coreProvider($parsed['options']); $result = $installer->updateCore($provider, $options); + + $counts = []; + foreach ($result['actions'] as $file => $action) { + $this->console->out(' ' . $action . ' ' . $file); + $counts[$action] = ($counts[$action] ?? 0) + 1; + } + if ($counts !== []) { + $summary = []; + foreach ($counts as $action => $count) { + $summary[] = $action . '=' . $count; + } + $this->console->out(' resumen: ' . implode(' ', $summary)); + } + $this->console->ok('core ' . ($result['version'] ?? '?')); foreach ($result['aborted'] as $aborted) { $this->console->error('abortado: ' . $aborted); diff --git a/packages/commands/src/Toolbox/CoreProvider.php b/packages/commands/src/Toolbox/CoreProvider.php index 582aab6..bdea358 100644 --- a/packages/commands/src/Toolbox/CoreProvider.php +++ b/packages/commands/src/Toolbox/CoreProvider.php @@ -189,4 +189,75 @@ final class CoreProvider return (string) file_get_contents($path); } + + /** + * Hashes canónicos de un conjunto de rutas en un ref histórico del core. + * Se usa para reparar ledgers heredados que guardaron hashes locales. + * + * Prefiere el commit (identidad inmutable) y cae al tag `v`. + * Devuelve null si el ref o alguna de las rutas no se pueden resolver. + * + * @param list $paths + * @return array|null + */ + public function canonicalAt(?string $commit, ?string $version, array $paths): ?array + { + if (!$this->isGit() || $paths === []) { + return null; + } + + $refs = []; + if ($commit !== null && $commit !== '') { + $refs[] = $commit; + } + if ($version !== null && $version !== '') { + $refs[] = 'v' . ltrim($version, 'vV'); + } + + foreach (array_unique($refs) as $ref) { + exec( + 'git -C ' . escapeshellarg($this->dir) . ' rev-parse --verify --quiet ' . + escapeshellarg($ref . '^{commit}') . ' 2>/dev/null', + $ignored, + $code + ); + if ($code !== 0) { + continue; + } + + $files = []; + $ok = true; + foreach ($paths as $relative) { + $tmp = tempnam(sys_get_temp_dir(), 'dbcore'); + if ($tmp === false) { + $ok = false; + break; + } + + exec( + 'git -C ' . escapeshellarg($this->dir) . ' show ' . + escapeshellarg($ref . ':' . $relative) . + ' > ' . escapeshellarg($tmp) . ' 2>/dev/null', + $ignored, + $exists + ); + if ($exists !== 0) { + @unlink($tmp); + $ok = false; + break; + } + + $content = (string) file_get_contents($tmp); + @unlink($tmp); + + $files[$relative] = 'sha256:' . hash('sha256', $content); + } + + if ($ok) { + return $files; + } + } + + return null; + } } diff --git a/packages/commands/src/Toolbox/FileSync.php b/packages/commands/src/Toolbox/FileSync.php index d5af06a..a2a69da 100644 --- a/packages/commands/src/Toolbox/FileSync.php +++ b/packages/commands/src/Toolbox/FileSync.php @@ -15,14 +15,12 @@ final class FileSync public const ABORTED = 'aborted'; /** + * Decide qué haría `write()` sin tocar el disco. + * * @param array{force?:bool, backup?:bool, keepLocal?:bool} $options */ - public function write(string $path, string $contents, ?string $expected, array $options = []): string + public function plan(string $path, string $contents, ?string $expected, array $options = []): string { - if (!is_dir(dirname($path))) { - mkdir(dirname($path), 0777, true); - } - $existed = is_file($path); $drifted = $existed && Drift::isDrifted($path, $expected); @@ -31,27 +29,17 @@ final class FileSync // heredado) un archivo existente también puede respaldarse. $changed = $existed && (string) file_get_contents($path) !== $contents; if ($changed && ($options['backup'] ?? false)) { - copy($path, $path . '.bak'); - file_put_contents($path, $contents); - return self::BACKED_UP; } - file_put_contents($path, $contents); - return $existed ? self::OVERWRITTEN : self::WRITTEN; } if ($options['force'] ?? false) { - file_put_contents($path, $contents); - return self::OVERWRITTEN; } if ($options['backup'] ?? false) { - copy($path, $path . '.bak'); - file_put_contents($path, $contents); - return self::BACKED_UP; } @@ -65,7 +53,34 @@ final class FileSync /** * @param array{force?:bool, backup?:bool, keepLocal?:bool} $options */ - public function remove(string $path, ?string $expected, array $options = []): string + public function write(string $path, string $contents, ?string $expected, array $options = []): string + { + if (!is_dir(dirname($path))) { + mkdir(dirname($path), 0777, true); + } + + $action = $this->plan($path, $contents, $expected, $options); + + if ($action === self::WRITTEN || $action === self::OVERWRITTEN) { + file_put_contents($path, $contents); + + return $action; + } + + if ($action === self::BACKED_UP) { + copy($path, $path . '.bak'); + file_put_contents($path, $contents); + } + + return $action; + } + + /** + * Decide qué haría `remove()` sin tocar el disco. + * + * @param array{force?:bool, backup?:bool, keepLocal?:bool} $options + */ + public function planRemove(string $path, ?string $expected, array $options = []): string { if (!is_file($path)) { return self::SKIPPED; @@ -79,10 +94,28 @@ final class FileSync } if ($options['backup'] ?? false) { - copy($path, $path . '.bak'); - } else { - return self::ABORTED; + return self::BACKED_UP; } + + return self::ABORTED; + } + + return self::OVERWRITTEN; + } + + /** + * @param array{force?:bool, backup?:bool, keepLocal?:bool} $options + */ + public function remove(string $path, ?string $expected, array $options = []): string + { + $action = $this->planRemove($path, $expected, $options); + + if ($action === self::SKIPPED || $action === self::ABORTED) { + return $action; + } + + if ($action === self::BACKED_UP) { + copy($path, $path . '.bak'); } unlink($path); diff --git a/packages/commands/src/Toolbox/Installer.php b/packages/commands/src/Toolbox/Installer.php index e7a6fbe..c8a48a8 100644 --- a/packages/commands/src/Toolbox/Installer.php +++ b/packages/commands/src/Toolbox/Installer.php @@ -271,8 +271,27 @@ final class Installer private function writeCore(CoreProvider $provider, array $options, bool $removeStale): array { $protected = $this->componentOwnedPaths(); - $expected = $this->lock->core()['files'] ?? []; - $files = $provider->files(); + $core = $this->lock->core(); + $expected = $core['files'] ?? []; + $origin = $core['origin'] ?? null; + + if ($expected !== [] && $this->lock->coreSchema() < 2) { + $canonical = $provider->canonicalAt( + $core['commit'] ?? null, + $core['version'] ?? null, + array_keys($expected) + ); + if ($canonical === null) { + $ref = $core['commit'] ?? $core['version'] ?? '?'; + throw new ToolboxException( + 'No se pudo reparar el lock del core: la versión registrada (' . $ref . ') no está disponible. ' . + 'Actualiza la caché del core o apunta --core-dir a esa versión.' + ); + } + $expected = $canonical; + } + + $files = $provider->files(); $installed = []; $actions = []; @@ -283,15 +302,18 @@ final class Installer continue; } + $contents = $provider->read($relative); $absolute = $this->root . '/' . $relative; + $hash = 'sha256:' . hash('sha256', $contents); if ($options['dryRun'] ?? false) { - $actions[$relative] = 'planned'; - $installed[$relative] = 'sha256:' . hash('sha256', $provider->read($relative)); + $planned = $this->sync->plan($absolute, $contents, $expected[$relative] ?? null, $options); + $actions[$relative] = 'planned-' . $planned; + $installed[$relative] = $hash; continue; } - $action = $this->sync->write($absolute, $provider->read($relative), $expected[$relative] ?? null, $options); + $action = $this->sync->write($absolute, $contents, $expected[$relative] ?? null, $options); $actions[$relative] = $action; if ($action === FileSync::ABORTED) { @@ -299,7 +321,9 @@ final class Installer continue; } - $installed[$relative] = Drift::hash($absolute); + // Ledger canónico: también para archivos saltados con --keep-local, + // de modo que sigan detectándose como drift en el próximo update. + $installed[$relative] = $hash; } if ($removeStale) { @@ -308,22 +332,43 @@ final class Installer continue; } if ($options['dryRun'] ?? false) { - $actions[$relative] = 'remove-planned'; + $planned = $this->sync->planRemove($this->root . '/' . $relative, $hash, $options); + $actions[$relative] = $planned === FileSync::OVERWRITTEN + ? 'planned-removed' + : 'planned-' . $planned; continue; } - $action = $this->sync->remove($this->root . '/' . $relative, $hash, $options); + $absolute = $this->root . '/' . $relative; + $action = $this->sync->remove($absolute, $hash, $options); if ($action === FileSync::ABORTED) { $aborted[] = $relative; + continue; } + if ($action === FileSync::SKIPPED) { + if (is_file($absolute)) { + $actions[$relative] = 'skipped'; + $this->console->warn('obsoleto conservado localmente: ' . $relative . ' (ya no gestionado)'); + } + continue; + } + $actions[$relative] = 'removed'; } } if ($aborted === [] && !($options['dryRun'] ?? false)) { - $this->lock->setCore([ + $newCore = [ + 'schema' => 2, 'version' => $provider->version() ?? $this->coreVersion(), - 'commit' => $provider->commit() ?? ($this->lock->core()['commit'] ?? null), + 'commit' => $provider->commit() ?? ($core['commit'] ?? null), 'files' => $installed, - ]); + ]; + if ($origin !== null) { + $newCore['origin'] = $origin; + } elseif (!$removeStale) { + $newCore['origin'] = 'toolbox'; + } + + $this->lock->setCore($newCore); $this->lock->save($this->root); } diff --git a/packages/commands/src/Toolbox/Lock.php b/packages/commands/src/Toolbox/Lock.php index 52ea330..2cdd54a 100644 --- a/packages/commands/src/Toolbox/Lock.php +++ b/packages/commands/src/Toolbox/Lock.php @@ -58,12 +58,21 @@ final class Lock return new self($data['core'] ?? null, $components); } - /** @return array{version?:string, commit?:string, files?:array}|null */ + /** @return array{schema?:int, version?:string, commit?:string, origin?:string, files?:array}|null */ public function core(): ?array { return $this->core; } + /** + * Esquema del ledger del core: 1 = heredado (hash del disco), 2 = hashes + * canónicos. La ausencia de marca se interpreta como heredado. + */ + public function coreSchema(): int + { + return (int) ($this->core['schema'] ?? 1); + } + /** @return array}> */ public function components(): array { @@ -80,7 +89,7 @@ final class Lock return $this->components[$id] ?? null; } - /** @param array{version?:string, commit?:string, files?:array} $core */ + /** @param array{schema?:int, version?:string, commit?:string, origin?:string, files?:array} $core */ public function setCore(array $core): void { $this->core = $core; diff --git a/tests/group3_state_test.php b/tests/group3_state_test.php index 51b98b2..671eac2 100644 --- a/tests/group3_state_test.php +++ b/tests/group3_state_test.php @@ -46,6 +46,30 @@ Harness::it('lock guarda core y componentes con schema esperado', function () { rrmdir($dir); }); +Harness::it('guardar componentes no asciende el esquema del core', function () { + $dir = tmpdir(); + $lock = Lock::empty(); + $lock->setCore(['schema' => 1, 'version' => '1.0.0', 'commit' => 'abc', 'files' => ['a' => 'sha256:x']]); + $lock->setComponent('p:c', [ + 'package' => 'p', + 'version' => '1.0.0', + 'toolbox_commit' => null, + 'mode' => 'copy', + 'files' => [], + ]); + $lock->save($dir); + + eq(1, Lock::load($dir)->coreSchema(), 'un guardado de componentes preserva el esquema legacy'); + $raw = json_decode((string) file_get_contents(Lock::path($dir)), true); + eq(1, $raw['core']['schema'], 'el JSON conserva schema 1'); + + unset($raw['core']['schema']); + file_put_contents(Lock::path($dir), json_encode($raw)); + eq(1, Lock::load($dir)->coreSchema(), 'sin marca se interpreta como esquema 1'); + + rrmdir($dir); +}); + Harness::it('ownership detecta colisión de rutas', function () { $lock = Lock::empty(); $lock->setCore(['files' => ['src/Libs/X.php' => 'sha256:a']]); diff --git a/tests/group7_commands_test.php b/tests/group7_commands_test.php index 976de01..6695934 100644 --- a/tests/group7_commands_test.php +++ b/tests/group7_commands_test.php @@ -6,6 +6,8 @@ use Toolbox\Commands\ListCommand; use Toolbox\Commands\RemoveCommand; use Toolbox\Commands\UpdateCommand; use Toolbox\Console; +use Toolbox\CoreProvider; +use Toolbox\Drift; use Toolbox\Lock; Harness::suite('group7'); @@ -71,6 +73,82 @@ function g7_console(&$stream): Console return new Console($stream, $stream); } +/** + * Repo del core con dos versiones y una ruta que desaparece en v0.1.1. + * Queda con el working tree en el último tag. + */ +function g7_core_history(): string +{ + $dir = tmpdir('corehist'); + write_file($dir . '/autoload.php', <<<'PHP' + $paths */ +function g7_materialize(string $repo, string $ref, string $root, array $paths): void +{ + foreach ($paths as $path) { + $contents = shell_exec( + 'git -C ' . escapeshellarg($repo) . ' show ' . escapeshellarg($ref . ':' . $path) . ' 2>/dev/null' + ); + write_file($root . '/' . $path, (string) $contents); + } +} + +/** @return array */ +function g7_legacy_lock(string $proj, string $repo): array +{ + $oldCommit = trim((string) shell_exec('git -C ' . escapeshellarg($repo) . ' rev-parse v0.1.0')); + $routerHash = 'sha256:' . hash('sha256', (string) shell_exec( + 'git -C ' . escapeshellarg($repo) . ' show v0.1.0:src/Libs/Router.php' + )); + + $files = [ + 'autoload.php' => Drift::hash($proj . '/autoload.php'), + 'config.php' => Drift::hash($proj . '/config.php'), + 'src/Libs/Router.php' => $routerHash, + 'src/Libs/Legacy.php' => Drift::hash($proj . '/src/Libs/Legacy.php'), + ]; + + write_file($proj . '/.duckbrain/lock.json', json_encode([ + 'core' => ['version' => '0.1.0', 'commit' => $oldCommit, 'files' => $files], + 'components' => [], + ], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES) . "\n"); + + return $files; +} + Harness::it('install descarga el core en un directorio vacío', function () { $proj = tmpdir('proj'); $core = g7_core('0.1.0'); @@ -320,3 +398,146 @@ Harness::it('un comando del proyecto sin describe() no carga (interfaz estricta) rrmdir($proj); }); + +Harness::it('canonicalAt lee un ref viejo y falla cerrado con refs o rutas ausentes', function () { + $repo = g7_core_history(); + $old = trim((string) shell_exec('git -C ' . escapeshellarg($repo) . ' rev-parse v0.1.0')); + $provider = CoreProvider::fromDirectory($repo); + + $hashes = $provider->canonicalAt($old, null, ['src/Libs/Router.php', 'src/Libs/Legacy.php', 'src/Empty/.gitkeep']); + ok(is_array($hashes), 'resuelve el ref viejo'); + $canonicalRouter = 'sha256:' . hash('sha256', (string) shell_exec( + 'git -C ' . escapeshellarg($repo) . ' show v0.1.0:src/Libs/Router.php' + )); + eq($canonicalRouter, $hashes['src/Libs/Router.php'], 'hash canónico histórico'); + eq('sha256:' . hash('sha256', ''), $hashes['src/Empty/.gitkeep'], 'archivo vacío resuelto'); + + eq(null, $provider->canonicalAt('deadbeef', '9.9.9', ['src/Libs/Router.php']), 'ref inexistente'); + eq(null, $provider->canonicalAt($old, null, ['src/Libs/Nope.php']), 'ruta inexistente'); + + rrmdir($repo); +}); + +Harness::it('update core repara un lock heredado y protege keep-local de forma durable', function () { + $repo = g7_core_history(); + $tool = g7_toolbox(); + $proj = tmpdir('proj'); + $paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php']; + + g7_materialize($repo, 'v0.1.0', $proj, $paths); + $config = "run([ + 'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local', + ]); + rewind($stream); + $out = (string) stream_get_contents($stream); + + eq(0, $code, 'el update termina sin abortos'); + eq($config, (string) file_get_contents($proj . '/config.php'), 'config local intacto'); + eq($legacy, (string) file_get_contents($proj . '/src/Libs/Legacy.php'), 'obsoleto local intacto'); + ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v2'), 'Router actualizado'); + ok(str_contains($out, 'skipped config.php'), 'reporta el archivo saltado'); + ok(str_contains($out, 'resumen:'), 'reporta un resumen por archivo'); + ok(str_contains($out, 'obsoleto conservado localmente: src/Libs/Legacy.php'), 'avisa del obsoleto conservado'); + + $lock = Lock::load($proj); + eq(2, $lock->coreSchema(), 'el lock migra a esquema 2'); + eq('0.1.1', $lock->core()['version']); + ok(!isset($lock->core()['files']['src/Libs/Legacy.php']), 'el obsoleto sale del ledger'); + $canonicalConfig = 'sha256:' . hash('sha256', (string) shell_exec( + 'git -C ' . escapeshellarg($repo) . ' show v0.1.1:config.php' + )); + eq($canonicalConfig, $lock->core()['files']['config.php'], 'el ledger guarda el canónico destino, no el hash local'); + + g7_core_tag($repo, '0.1.2', 'router-v3'); + (new UpdateCommand(g7_console($quiet)))->run([ + 'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local', + ]); + eq($config, (string) file_get_contents($proj . '/config.php'), 'keep-local durable: config sigue intacto'); + ok(str_contains((string) file_get_contents($proj . '/src/Libs/Router.php'), 'router-v3'), 'Router sigue actualizándose'); + eq('0.1.2', Lock::load($proj)->core()['version']); + + g7_core_tag($repo, '0.1.3', 'router-v4'); + $rc = (new UpdateCommand(g7_console($quiet2)))->run([ + 'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', + ]); + eq(1, $rc, 'sin --keep-local el drift aborta'); + eq($config, (string) file_get_contents($proj . '/config.php'), 'el aborto no pisa config'); + eq('0.1.2', Lock::load($proj)->core()['version'], 'el lock no avanza con abortos'); + + rrmdir($proj); + rrmdir($tool); + rrmdir($repo); +}); + +Harness::it('update core falla cerrado si no puede reparar el lock heredado', function () { + $repo = g7_core_history(); + $fresh = g7_core('9.9.9', 'router-fresh'); + $tool = g7_toolbox(); + $proj = tmpdir('proj'); + $paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php']; + + g7_materialize($repo, 'v0.1.0', $proj, $paths); + write_file($proj . '/config.php', "run([ + 'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $fresh, '--yes', '--keep-local', + ]); + rewind($stream); + $out = (string) stream_get_contents($stream); + + eq(1, $code, 'falla cerrado'); + eq($lockBefore, (string) file_get_contents(Lock::path($proj)), 'el lock no se reescribe'); + eq($routerBefore, (string) file_get_contents($proj . '/src/Libs/Router.php'), 'no se escribe el core'); + ok(str_contains($out, 'No se pudo reparar el lock del core'), 'explica el bloqueo'); + + rrmdir($proj); + rrmdir($tool); + rrmdir($repo); + rrmdir($fresh); +}); + +Harness::it('update core --dry-run planifica el drift sin escribir', function () { + $repo = g7_core_history(); + $tool = g7_toolbox(); + $proj = tmpdir('proj'); + $paths = ['autoload.php', 'config.php', 'src/Libs/Router.php', 'src/Libs/Legacy.php']; + + g7_materialize($repo, 'v0.1.0', $proj, $paths); + write_file($proj . '/config.php', "run([ + 'core', '--root=' . $proj, '--toolbox=' . $tool, '--core-dir=' . $repo, '--yes', '--keep-local', '--dry-run', + ]); + rewind($stream); + $out = (string) stream_get_contents($stream); + + eq(0, $code, 'dry-run termina bien'); + ok(str_contains($out, 'planned-skipped config.php'), 'planifica el archivo protegido'); + ok(str_contains($out, 'planned-overwritten src/Libs/Router.php'), 'planifica el archivo a actualizar'); + eq($lockBefore, (string) file_get_contents(Lock::path($proj)), 'dry-run no toca el lock'); + eq($routerBefore, (string) file_get_contents($proj . '/src/Libs/Router.php'), 'dry-run no escribe archivos'); + + rrmdir($proj); + rrmdir($tool); + rrmdir($repo); +}); diff --git a/tests/group9_absorb_test.php b/tests/group9_absorb_test.php index ddc4656..ebc01d5 100644 --- a/tests/group9_absorb_test.php +++ b/tests/group9_absorb_test.php @@ -143,6 +143,7 @@ Harness::it('adopt del core registra hash canónico y marca ediciones locales', eq('sha256:' . hash('sha256', $canonicalRouter), $coreHashRouter, 'hash de Router.php = canónico'); eq('sha256:' . hash('sha256', $canonicalConfig), $coreHashConfig, 'hash de config.php = canónico (aunque el local difiera)'); eq('local', $lock->core()['origin'] ?? null, 'origin = local porque hay ediciones locales'); + eq(2, $lock->coreSchema(), 'adopt graba el esquema canónico'); ok(file_get_contents($proj . '/config.php') !== $canonicalConfig, 'la copia local customizada no se tocó');