From 96b30368bc74a287a4edeb054f59981dc373bfdc Mon Sep 17 00:00:00 2001
From: nala
Date: Sun, 29 Nov 2026 19:49:19 +0200
Subject: [PATCH] commit compras5 2911
---
.../Controllers/GoodsReceiptController.php | 3 +-
.../OrderCancellationController.php | 2 +
.../Controllers/SupplyPlanningController.php | 3 +-
app/Services/AgreementOrderLimits.php | 8 +
app/Services/DeadlineTaskGuiAction.php | 65 +++++
app/Services/InventoryConversionRuntime.php | 101 ++++++++
.../OrderCancellationPolicyWorkflow.php | 1 +
app/Services/OrderCancellationRuntime.php | 78 ++++++
app/Services/OrderCancellationWorkflow.php | 10 +-
app/Services/ReceiptQuantityConversion.php | 6 +-
app/Services/ReceiptStockMovement.php | 22 +-
app/Services/ReplenishmentTaskDefinition.php | 67 +++++
app/Services/SupplyCoordination.php | 2 +-
config/inventory_conversion.php | 8 +-
config/order_cancellation.php | 6 +-
docs/desenvolvimento.md | 14 ++
docs/matriz-sgc-reconciliada.md | 16 +-
docs/operacao-reposicao.md | 2 +
docs/orientacoes-continuidade.md | 12 +
...ytics-print-publication-authorization.json | 7 +
.../analytics-print-publication-http.json | 9 +
.../analytics-print-publication-proposal.json | 230 ++++++++++++++++++
docs/proofs/analytics-print-publication.json | 19 ++
.../approval-deadlines-task-gui-repair.json | 27 ++
...ras-standalone-pilot-activation-check.json | 2 +-
.../compras-standalone-pilot-profiles.json | 42 +++-
...-conversion-operational-authorization.json | 8 +
...tory-conversion-operational-candidate.json | 61 +++++
...ntory-conversion-operational-proposal.json | 57 +++++
...entory-conversion-pilot-authorization.json | 8 +
...entory-conversion-pilot-current-check.json | 15 ++
...ventory-conversion-pilot-installation.json | 19 ++
...entory-conversion-pilot-native-review.json | 42 ++++
.../inventory-conversion-pilot-postcheck.json | 15 ++
.../inventory-conversion-pilot-preflight.json | 14 ++
.../inventory-conversion-pilot-proposal.json | 41 ++++
...rder-cancellation-pilot-authorization.json | 9 +
...order-cancellation-pilot-installation.json | 19 ++
...rder-cancellation-pilot-native-review.json | 39 +++
.../order-cancellation-pilot-postcheck.json | 10 +
.../order-cancellation-pilot-preflight.json | 10 +
.../order-cancellation-pilot-proposal.json | 29 +++
docs/proofs/pilot-operations-current.json | 72 ++++++
docs/proofs/procurement-analytics-qa.json | 42 +++-
docs/proofs/product-review-20261122.json | 46 +++-
.../replenishment-task-authorization.json | 8 +
.../replenishment-task-definition-fix.json | 15 ++
.../replenishment-task-installation.json | 39 +++
docs/proofs/replenishment-task-preflight.json | 18 ++
docs/proofs/replenishment-task-proposal.json | 36 +++
docs/proofs/replenishment-task-recovery.json | 8 +
.../releases/0.2.0-rc.1/bootstrap.php | 3 +
.../releases/0.2.0-rc.1/manifest.json | 11 +
.../0.2.0-rc.1/src/QuantityConversion.php | 35 +++
.../0.2.0-rc.1/src/ReceiptMovementWriter.php | 94 +++++++
packages/order-cancellation/README.md | 4 +-
.../releases/0.2.0-rc.1/manifest.json | 9 +
.../0.2.0-rc.1/src/CommitmentReversal.php | 65 +++++
resources/css/app.css | 27 ++
.../procurement-payment-insights.tsx | 9 +-
resources/js/lib/procurement-navigation.ts | 9 +
resources/js/pages/reports/procurement.tsx | 2 +-
.../activate-inventory-conversion-pilot.php | 127 ++++++++++
scripts/activate-order-cancellation-pilot.php | 111 +++++++++
.../build-inventory-conversion-artifact.php | 45 ++++
scripts/check-analytics-preview.php | 51 ++++
scripts/check-inventory-conversion-pilot.php | 84 +++++++
scripts/check-order-cancellation-pilot.php | 52 ++++
scripts/check-pilot-operations.php | 77 ++++++
scripts/check-standalone-pilot-activation.php | 41 +++-
scripts/check-standalone-pilot-profiles.php | 3 +-
scripts/check-standalone-published-assets.mjs | 27 +-
scripts/install-replenishment-task.php | 136 +++++++++++
scripts/order-cancellation-http.mjs | 37 ++-
scripts/order-cancellation-pilot-check.php | 43 +---
scripts/publish-analytics-print.php | 62 +++++
scripts/repair-approval-deadlines-gui.php | 74 ++++++
scripts/replenishment-pilot-task.php | 58 +++++
scripts/requisition-ledger-qa-check.mjs | 86 ++++++-
scripts/standalone-inventory-preview.mjs | 64 +++++
scripts/verify-replenishment-task-backup.php | 70 ++++++
.../replenishment-command-status.json | 8 +
storage/framework/replenishment-command.lock | 0
tests/Concurrency/unit-conversion-worker.php | 84 ++++++-
.../ReceiptQuantityConversionTest.php | 58 ++++-
tests/Feature/ReceiptStockTest.php | 9 +
.../StandaloneBusinessCompositionTest.php | 37 +++
.../IssuedOrderCancellationFixture.php | 17 +-
.../Support/StandaloneCompositionFixture.php | 33 +++
.../standalone-inventory-http-router.php | 34 +++
.../standalone-inventory-recovery-worker.php | 118 +++++++++
tests/Unit/DeadlineTaskGuiActionTest.php | 28 +++
.../Unit/InventoryConversionArtifactTest.php | 53 ++++
.../Unit/ReplenishmentTaskDefinitionTest.php | 13 +
.../frontend/procurement-menu-search.test.tsx | 37 +++
.../procurement-payment-insights.test.tsx | 21 ++
96 files changed, 3397 insertions(+), 111 deletions(-)
create mode 100644 app/Services/DeadlineTaskGuiAction.php
create mode 100644 app/Services/InventoryConversionRuntime.php
create mode 100644 app/Services/OrderCancellationRuntime.php
create mode 100644 app/Services/ReplenishmentTaskDefinition.php
create mode 100644 docs/proofs/analytics-print-publication-authorization.json
create mode 100644 docs/proofs/analytics-print-publication-http.json
create mode 100644 docs/proofs/analytics-print-publication-proposal.json
create mode 100644 docs/proofs/analytics-print-publication.json
create mode 100644 docs/proofs/approval-deadlines-task-gui-repair.json
create mode 100644 docs/proofs/inventory-conversion-operational-authorization.json
create mode 100644 docs/proofs/inventory-conversion-operational-candidate.json
create mode 100644 docs/proofs/inventory-conversion-operational-proposal.json
create mode 100644 docs/proofs/inventory-conversion-pilot-authorization.json
create mode 100644 docs/proofs/inventory-conversion-pilot-current-check.json
create mode 100644 docs/proofs/inventory-conversion-pilot-installation.json
create mode 100644 docs/proofs/inventory-conversion-pilot-native-review.json
create mode 100644 docs/proofs/inventory-conversion-pilot-postcheck.json
create mode 100644 docs/proofs/inventory-conversion-pilot-preflight.json
create mode 100644 docs/proofs/inventory-conversion-pilot-proposal.json
create mode 100644 docs/proofs/order-cancellation-pilot-authorization.json
create mode 100644 docs/proofs/order-cancellation-pilot-installation.json
create mode 100644 docs/proofs/order-cancellation-pilot-native-review.json
create mode 100644 docs/proofs/order-cancellation-pilot-postcheck.json
create mode 100644 docs/proofs/order-cancellation-pilot-preflight.json
create mode 100644 docs/proofs/order-cancellation-pilot-proposal.json
create mode 100644 docs/proofs/pilot-operations-current.json
create mode 100644 docs/proofs/replenishment-task-authorization.json
create mode 100644 docs/proofs/replenishment-task-definition-fix.json
create mode 100644 docs/proofs/replenishment-task-installation.json
create mode 100644 docs/proofs/replenishment-task-preflight.json
create mode 100644 docs/proofs/replenishment-task-proposal.json
create mode 100644 docs/proofs/replenishment-task-recovery.json
create mode 100644 packages/inventory-write/releases/0.2.0-rc.1/bootstrap.php
create mode 100644 packages/inventory-write/releases/0.2.0-rc.1/manifest.json
create mode 100644 packages/inventory-write/releases/0.2.0-rc.1/src/QuantityConversion.php
create mode 100644 packages/inventory-write/releases/0.2.0-rc.1/src/ReceiptMovementWriter.php
create mode 100644 packages/order-cancellation/releases/0.2.0-rc.1/manifest.json
create mode 100644 packages/order-cancellation/releases/0.2.0-rc.1/src/CommitmentReversal.php
create mode 100644 scripts/activate-inventory-conversion-pilot.php
create mode 100644 scripts/activate-order-cancellation-pilot.php
create mode 100644 scripts/build-inventory-conversion-artifact.php
create mode 100644 scripts/check-analytics-preview.php
create mode 100644 scripts/check-inventory-conversion-pilot.php
create mode 100644 scripts/check-order-cancellation-pilot.php
create mode 100644 scripts/check-pilot-operations.php
create mode 100644 scripts/install-replenishment-task.php
create mode 100644 scripts/publish-analytics-print.php
create mode 100644 scripts/repair-approval-deadlines-gui.php
create mode 100644 scripts/replenishment-pilot-task.php
create mode 100644 scripts/standalone-inventory-preview.mjs
create mode 100644 scripts/verify-replenishment-task-backup.php
create mode 100644 storage/framework/replenishment-command-status.json
create mode 100644 storage/framework/replenishment-command.lock
create mode 100644 tests/Support/StandaloneCompositionFixture.php
create mode 100644 tests/Support/standalone-inventory-http-router.php
create mode 100644 tests/Support/standalone-inventory-recovery-worker.php
create mode 100644 tests/Unit/DeadlineTaskGuiActionTest.php
create mode 100644 tests/Unit/InventoryConversionArtifactTest.php
create mode 100644 tests/Unit/ReplenishmentTaskDefinitionTest.php
diff --git a/app/Http/Controllers/GoodsReceiptController.php b/app/Http/Controllers/GoodsReceiptController.php
index 0cadc7d..0c6dca3 100644
--- a/app/Http/Controllers/GoodsReceiptController.php
+++ b/app/Http/Controllers/GoodsReceiptController.php
@@ -12,6 +12,7 @@ use App\Models\StockItem;
use App\Models\StockMovement;
use App\Models\User;
use App\Models\Warehouse;
+use App\Services\InventoryConversionRuntime;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
use App\Services\ReceiptDocuments;
@@ -72,7 +73,7 @@ class GoodsReceiptController extends Controller
'receipts' => GoodsReceipt::query()->where('purchase_order_id', $order->id)->latest('id')->get(),
'warehouses' => Warehouse::query()->orderBy('code')->get(['id', 'code', 'name']),
'stockItems' => StockItem::query()->orderBy('code')->get(['id', 'code', 'name', 'unit']),
- 'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
+ 'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
'canConfirm' => $actor->can('create', [GoodsReceipt::class, $order]),
'lotScopes' => Schema::hasTable('inventory_lot_allocations')
? app(InventoryLots::class)->activeSetups()->get()->map(fn ($r) => ['stock_item_id' => $r->stock_item_id, 'warehouse_id' => $r->warehouse_id, 'quarantine_on_receipt' => $r->data['quarantine_on_receipt'] ?? true])->values()->all() : [],
diff --git a/app/Http/Controllers/OrderCancellationController.php b/app/Http/Controllers/OrderCancellationController.php
index 60cc559..448597f 100644
--- a/app/Http/Controllers/OrderCancellationController.php
+++ b/app/Http/Controllers/OrderCancellationController.php
@@ -8,6 +8,7 @@ use App\Models\PurchaseOrder;
use App\Models\Requisition;
use App\Models\User;
use App\Services\OrderCancellationPolicyWorkflow;
+use App\Services\OrderCancellationRuntime;
use App\Services\OrderCancellationWorkflow;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
@@ -22,6 +23,7 @@ class OrderCancellationController extends Controller
$actor = $request->user('web');
abort_unless($actor instanceof User, 403);
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
+ app(OrderCancellationRuntime::class)->assertReady();
return $actor;
}
diff --git a/app/Http/Controllers/SupplyPlanningController.php b/app/Http/Controllers/SupplyPlanningController.php
index f4bbfd5..e0e4c04 100644
--- a/app/Http/Controllers/SupplyPlanningController.php
+++ b/app/Http/Controllers/SupplyPlanningController.php
@@ -17,6 +17,7 @@ use App\Models\Warehouse;
use App\Services\AgreementOrderLimits;
use App\Services\ImportDossier;
use App\Services\ImportLandedCosts;
+use App\Services\InventoryConversionRuntime;
use App\Services\InventoryReversals;
use App\Services\OrganizationAccess;
use App\Services\ReceiptWorkflow;
@@ -370,7 +371,7 @@ class SupplyPlanningController extends Controller
}
return Inertia::render('supply/coordination', ['kind' => $kind, 'ready' => $ready,
- 'conversionQaEnabled' => app()->environment('testing') && config('inventory_conversion.qa_enabled') === true,
+ 'conversionQaEnabled' => app(InventoryConversionRuntime::class)->available(),
'recordFilters' => ['record_search' => trim($filters['record_search'] ?? ''), 'record_state' => $filters['record_state'] ?? ''],
'recordPagination' => $page === null ? null : ['current_page' => $page->currentPage(), 'last_page' => $page->lastPage(), 'total' => $page->total(),
'prev_page_url' => $page->previousPageUrl(), 'next_page_url' => $page->nextPageUrl()],
diff --git a/app/Services/AgreementOrderLimits.php b/app/Services/AgreementOrderLimits.php
index b184876..8f91a8a 100644
--- a/app/Services/AgreementOrderLimits.php
+++ b/app/Services/AgreementOrderLimits.php
@@ -260,6 +260,11 @@ final class AgreementOrderLimits
private function loadArithmetic(): void
{
+ if (app(InventoryConversionRuntime::class)->enabled()) {
+ app(ReceiptStockMovement::class)->load();
+
+ return;
+ }
$root = base_path('packages/inventory-write/development');
$bytes = file_get_contents($root.'/manifest.json');
if ($bytes === false || ! hash_equals('90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38', hash('sha256', $bytes))) {
@@ -271,6 +276,9 @@ final class AgreementOrderLimits
if (! is_string($hash) || ! hash_equals($manifest['files']['src/QuantityConversion.php'], $hash)) {
throw new \LogicException('Aritmética alterada.');
}
+ if (class_exists(QuantityConversion::class, false) && realpath((new \ReflectionClass(QuantityConversion::class))->getFileName() ?: '') !== realpath($file)) {
+ throw new \LogicException('COMPRAS_INVENTORY_ARITHMETIC_VERSION');
+ }
require_once $file;
}
diff --git a/app/Services/DeadlineTaskGuiAction.php b/app/Services/DeadlineTaskGuiAction.php
new file mode 100644
index 0000000..8db5948
--- /dev/null
+++ b/app/Services/DeadlineTaskGuiAction.php
@@ -0,0 +1,65 @@
+registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
+ $nodes = $xpath->query('/t:Task/t:Actions/t:Exec/t:Command');
+ $actions = $xpath->query('/t:Task/t:Actions/*');
+ $command = $nodes === false ? null : $nodes->item(0);
+ if ($actions === false || $nodes === false || $actions->length !== 1 || $nodes->length !== 1
+ || ! $command instanceof DOMElement || $command->textContent !== $old) {
+ throw new LogicException('DEADLINE_TASK_GUI_ACTION_MISMATCH');
+ }
+ $command->nodeValue = $new;
+ $output = $document->saveXML();
+ if (! is_string($output)) {
+ throw new LogicException('DEADLINE_TASK_GUI_XML');
+ }
+
+ return $output;
+ }
+
+ public static function assertConserved(string $before, string $after, string $old, string $new): void
+ {
+ if (self::canonical(self::replacement($before, $old, $new)) !== self::canonical($after)) {
+ throw new LogicException('DEADLINE_TASK_GUI_UNRELATED_DEFINITION_CHANGE');
+ }
+ }
+
+ public static function canonical(string $xml): string
+ {
+ $document = WindowsTaskXml::parse($xml);
+ $xpath = new DOMXPath($document);
+ $blanks = $xpath->query('//text()[normalize-space(.)=""]');
+ if ($blanks === false) {
+ throw new LogicException('DEADLINE_TASK_GUI_XML');
+ }
+ foreach ($blanks as $blank) {
+ if ($blank instanceof DOMText && $blank->parentNode !== null) {
+ $blank->parentNode->removeChild($blank);
+ }
+ }
+ $canonical = $document->documentElement->C14N();
+ if (! is_string($canonical)) {
+ throw new LogicException('DEADLINE_TASK_GUI_XML');
+ }
+
+ return $canonical;
+ }
+}
diff --git a/app/Services/InventoryConversionRuntime.php b/app/Services/InventoryConversionRuntime.php
new file mode 100644
index 0000000..2ca0608
--- /dev/null
+++ b/app/Services/InventoryConversionRuntime.php
@@ -0,0 +1,101 @@
+enabled()) {
+ $this->root();
+
+ return true;
+ }
+
+ return config('inventory_conversion.qa_enabled') === true && app()->environment('testing');
+ }
+
+ public function root(): string
+ {
+ if (! $this->enabled() || config('inventory_conversion.qa_enabled') === true) {
+ throw new LogicException('COMPRAS_INVENTORY_CONFIGURATION');
+ }
+ $runtime = app(StandaloneRuntime::class);
+ if (! $runtime->enabled()) {
+ throw new LogicException('COMPRAS_INVENTORY_INSTALLATION_REQUIRED');
+ }
+ $runtime->assertInstallation(DB::connection());
+ $runtime->assertLoadedPackages();
+ $root = config('inventory_conversion.root');
+ if (! is_string($root)) {
+ throw new LogicException('COMPRAS_INVENTORY_ROOT');
+ }
+ self::verifyArtifact($root);
+ foreach ([
+ 'goods_receipt_items' => ['id', 'tenant_id', 'goods_receipt_id', 'stock_item_id', 'received_milli', 'accepted_milli', 'rejected_milli', 'quality_status', 'notes', 'snapshot'],
+ 'goods_receipts' => ['id', 'tenant_id', 'purchase_order_id', 'received_by', 'warehouse_id', 'delivery_note', 'received_on', 'confirmed_at', 'snapshot'],
+ 'stock_movements' => ['id', 'tenant_id', 'goods_receipt_item_id', 'stock_item_id', 'warehouse_id', 'moved_by', 'quantity_milli', 'movement_type', 'moved_at', 'equipment_id', 'spare_part_id', 'snapshot'],
+ ] as $table => $columns) {
+ if (! DB::getSchemaBuilder()->hasColumns($table, $columns)) {
+ throw new LogicException('COMPRAS_INVENTORY_SCHEMA');
+ }
+ }
+
+ return $root;
+ }
+
+ /** No PHP from the component is executed during verification. */
+ public static function verifyArtifact(string $root): void
+ {
+ $boundary = realpath($root);
+ $manifest = $root.'/manifest.json';
+ $bytes = is_file($manifest) ? file_get_contents($manifest) : false;
+ if ($boundary === false || is_link($root) || is_link($manifest) || ! is_file($manifest)
+ || ! is_string($bytes) || ! hash_equals(self::MANIFEST_SHA256, hash('sha256', $bytes))) {
+ throw new LogicException('COMPRAS_INVENTORY_MANIFEST');
+ }
+ $data = json_decode($bytes, true, 512, JSON_THROW_ON_ERROR);
+ foreach ($data['files'] as $file => $hash) {
+ $path = $root.'/'.$file;
+ $actual = is_file($path) ? hash_file('sha256', $path) : false;
+ if (is_link($path) || ! is_file($path) || ! str_starts_with(realpath($path) ?: '', $boundary.DIRECTORY_SEPARATOR)
+ || ! is_string($actual) || ! hash_equals($hash, $actual)) {
+ throw new LogicException('COMPRAS_INVENTORY_FILE:'.$file);
+ }
+ }
+ }
+
+ public static function assertArchiveEntries(\ZipArchive $archive): void
+ {
+ $expected = ['manifest.json', 'bootstrap.php', 'src/QuantityConversion.php', 'src/ReceiptMovementWriter.php'];
+ $actual = [];
+ for ($i = 0; $i < $archive->numFiles; $i++) {
+ $actual[] = $archive->getNameIndex($i);
+ }
+ sort($actual, SORT_STRING);
+ sort($expected, SORT_STRING);
+ if ($actual !== $expected) {
+ throw new LogicException('COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
+ }
+ }
+
+ /** Disabling the component cannot silently select a writer unable to read frozen conversions. */
+ public function assertLegacyCompatible(): void
+ {
+ if (DB::table('goods_receipt_items')->whereNotNull('snapshot->quantity_conversion')->exists()
+ || DB::table('supply_records')->whereNotNull('data->conversion_basis')->exists()) {
+ throw new LogicException('COMPRAS_INVENTORY_DOWNGRADE_REFUSED');
+ }
+ }
+}
diff --git a/app/Services/OrderCancellationPolicyWorkflow.php b/app/Services/OrderCancellationPolicyWorkflow.php
index c961c4c..d865126 100644
--- a/app/Services/OrderCancellationPolicyWorkflow.php
+++ b/app/Services/OrderCancellationPolicyWorkflow.php
@@ -43,6 +43,7 @@ class OrderCancellationPolicyWorkflow extends PurchaseControlPolicyWorkflow
private function enabled(): void
{
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellation_policies'), 503, 'Cancelamento de ordens não activado.');
+ app(OrderCancellationRuntime::class)->assertReady();
}
public function propose(User $user, array $data): PurchaseControlPolicy
diff --git a/app/Services/OrderCancellationRuntime.php b/app/Services/OrderCancellationRuntime.php
new file mode 100644
index 0000000..fe20df6
--- /dev/null
+++ b/app/Services/OrderCancellationRuntime.php
@@ -0,0 +1,78 @@
+enabled()) {
+ return;
+ }
+ $runtime->assertInstallation(DB::connection());
+ $runtime->assertLoadedPackages();
+ if (! property_exists(BudgetContext::class, 'requisitionCycles')) {
+ throw new LogicException('COMPRAS_CANCELLATION_CYCLE_CONTEXT');
+ }
+ foreach (['order_cancellations' => ['operation_key', 'basis_hash', 'status'],
+ 'order_cancellation_policies' => ['revision', 'status'], 'order_cancellation_policy_reviews' => ['reviewed_by'],
+ 'budget_entries' => ['requisition_cycle'], 'budget_requisition_cycles' => ['cycle', 'state']] as $table => $columns) {
+ if (! DB::getSchemaBuilder()->hasColumns($table, $columns)) {
+ throw new LogicException('COMPRAS_CANCELLATION_SCHEMA');
+ }
+ }
+ $root = config('order_cancellation.root');
+ if (! is_string($root)) {
+ throw new LogicException('COMPRAS_CANCELLATION_ROOT');
+ }
+ self::verifyArtifact($root);
+ }
+
+ public static function verifyArtifact(string $root): void
+ {
+ $bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
+ $path = $root.'/src/CommitmentReversal.php';
+ $hash = is_file($path) ? hash_file('sha256', $path) : false;
+ if (! is_string($bytes) || ! hash_equals(self::MANIFEST_SHA256, hash('sha256', $bytes))
+ || is_link($root) || is_link($root.'/manifest.json') || is_link($path)
+ || ! str_starts_with(realpath($path) ?: '', (realpath($root) ?: '').DIRECTORY_SEPARATOR)) {
+ throw new LogicException('COMPRAS_CANCELLATION_MANIFEST');
+ }
+ $manifest = json_decode($bytes, true, 32, JSON_THROW_ON_ERROR);
+ if (! is_string($hash) || ! hash_equals($manifest['files']['src/CommitmentReversal.php'], $hash)) {
+ throw new LogicException('COMPRAS_CANCELLATION_FILE');
+ }
+ }
+
+ /** Returns whether the writer requires the explicit cycle map in its financial context. */
+ public function load(int $origin): bool
+ {
+ $operational = app(StandaloneRuntime::class)->enabled();
+ if ($operational) {
+ $this->assertReady();
+ $path = config('order_cancellation.root').'/src/CommitmentReversal.php';
+ } else {
+ abort_if(DB::getSchemaBuilder()->hasColumn('budget_entries', 'requisition_cycle')
+ && DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '>', 1)->exists(), 503,
+ 'Preserve o componente compatível com os ciclos antes de cancelar esta ordem.');
+ $path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
+ abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
+ }
+ if (class_exists(CommitmentReversal::class, false)
+ && realpath((new \ReflectionClass(CommitmentReversal::class))->getFileName() ?: '') !== realpath($path)) {
+ throw new LogicException('COMPRAS_CANCELLATION_CLASS_LOCATION');
+ }
+ require_once $path;
+
+ return $operational;
+ }
+}
diff --git a/app/Services/OrderCancellationWorkflow.php b/app/Services/OrderCancellationWorkflow.php
index 317b118..8d3af34 100644
--- a/app/Services/OrderCancellationWorkflow.php
+++ b/app/Services/OrderCancellationWorkflow.php
@@ -82,6 +82,7 @@ class OrderCancellationWorkflow
private function enabled(): void
{
abort_unless(config('order_cancellation.enabled') && Schema::hasTable('order_cancellations'), 503, 'Cancelamento de ordens não activado.');
+ app(OrderCancellationRuntime::class)->assertReady();
}
public function state(PurchaseOrder $order): string
@@ -198,11 +199,12 @@ class OrderCancellationWorkflow
if (! empty($order->snapshot['budget_control']) && ! DB::table('budget_entries')->where('tenant_id', $actor->tenant_id)->where('requisition_id', $request->id)->exists()) {
throw ValidationException::withMessages(['budget' => 'A ordem indica controlo orçamental, mas o compromisso não está disponível.']);
}
- $path = base_path('packages/order-cancellation/src/CommitmentReversal.php');
- abort_unless(is_file($path) && hash_file('sha256', $path) === config('order_cancellation.reversal_sha256'), 503, 'Capacidade de reversão indisponível.');
- require_once $path;
+ $cycles = app(OrderCancellationRuntime::class)->load($request->id);
+ $context = $cycles
+ ? (new \ReflectionClass(BudgetContext::class))->newInstanceArgs([$actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN', RequisitionExpiry::orderCycles($order)])
+ : new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN');
try {
- $entry = (new CommitmentReversal)->reverse(DB::connection(), new BudgetContext($actor->id, ['tenant_id' => (int) $actor->tenant_id], (int) now()->year, 'MZN'), $request->id, $order->id);
+ $entry = (new CommitmentReversal)->reverse(DB::connection(), $context, $request->id, $order->id);
} catch (\LogicException $error) {
throw ValidationException::withMessages(['budget' => 'O compromisso não está integralmente disponível para reversão ou a sua base é inconsistente. Reveja o controlo orçamental.']);
}
diff --git a/app/Services/ReceiptQuantityConversion.php b/app/Services/ReceiptQuantityConversion.php
index f059712..bfff98f 100644
--- a/app/Services/ReceiptQuantityConversion.php
+++ b/app/Services/ReceiptQuantityConversion.php
@@ -32,8 +32,8 @@ final class ReceiptQuantityConversion
return null;
}
- if (config('inventory_conversion.qa_enabled') !== true || ! app()->environment('testing')) {
- throw ValidationException::withMessages(['items' => 'A conversão de unidades está preparada apenas para QA.']);
+ if (! app(InventoryConversionRuntime::class)->available()) {
+ throw ValidationException::withMessages(['items' => 'A conversão de unidades não está instalada e activada.']);
}
$v = Validator::make($input ?? [], [
'numerator' => ['required', 'string', 'regex:/^[1-9]\d{0,8}$/D'],
@@ -75,7 +75,7 @@ final class ReceiptQuantityConversion
if ($basis === null) {
return $physical;
}
- abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Conversão ainda não instalada.');
+ abort_unless(app(InventoryConversionRuntime::class)->available(), 503, 'Conversão ainda não instalada.');
app(ReceiptStockMovement::class)->load();
try {
return (int) QuantityConversion::fromBase((string) $physical, $basis['numerator'], $basis['denominator']);
diff --git a/app/Services/ReceiptStockMovement.php b/app/Services/ReceiptStockMovement.php
index 6068441..5581973 100644
--- a/app/Services/ReceiptStockMovement.php
+++ b/app/Services/ReceiptStockMovement.php
@@ -15,7 +15,12 @@ final class ReceiptStockMovement
$root = base_path('packages/inventory-write/releases/0.1.0');
$pin = 'f0b99e591f9a4df135e685f64ceffad77bed259222debe0f34c20f95e3cad800';
$files = ['bootstrap.php', 'src/ReceiptMovementWriter.php'];
- if (config('inventory_conversion.qa_enabled') === true) {
+ $conversion = app(InventoryConversionRuntime::class);
+ if ($conversion->enabled()) {
+ $root = $conversion->root();
+ $pin = InventoryConversionRuntime::MANIFEST_SHA256;
+ $files[] = 'src/QuantityConversion.php';
+ } elseif (config('inventory_conversion.qa_enabled') === true) {
abort_unless(app()->environment('testing'), 503, 'Extensão de conversão limitada a QA.');
$connection = DB::connection();
abort_unless(($connection->getDriverName() === 'sqlite' && $connection->getDatabaseName() === ':memory:')
@@ -23,6 +28,8 @@ final class ReceiptStockMovement
$root = base_path('packages/inventory-write/development');
$pin = '90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38';
$files[] = 'src/QuantityConversion.php';
+ } else {
+ $conversion->assertLegacyCompatible();
}
$bytes = is_file($root.'/manifest.json') ? file_get_contents($root.'/manifest.json') : false;
if (! is_string($bytes) || ! hash_equals($pin, hash('sha256', $bytes))) {
@@ -35,9 +42,16 @@ final class ReceiptStockMovement
throw new \LogicException('Pacote de recepção alterado.');
}
}
- if (class_exists(ReceiptMovementWriter::class, false)) {
- $loaded = (new \ReflectionClass(ReceiptMovementWriter::class))->getFileName();
- if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/ReceiptMovementWriter.php')) {
+ foreach (['ReceiptMovementWriter', 'QuantityConversion'] as $class) {
+ if ($class === 'QuantityConversion' && ! in_array('src/QuantityConversion.php', $files, true)) {
+ continue;
+ }
+ $name = 'Tempo\\Inventory\\'.$class;
+ if (! class_exists($name, false)) {
+ continue;
+ }
+ $loaded = (new \ReflectionClass($name))->getFileName();
+ if (! is_string($loaded) || realpath($loaded) !== realpath($root.'/src/'.$class.'.php')) {
throw new \LogicException('Escritor já carregado de outra versão; use um kernel QA separado.');
}
}
diff --git a/app/Services/ReplenishmentTaskDefinition.php b/app/Services/ReplenishmentTaskDefinition.php
new file mode 100644
index 0000000..ed0ecac
--- /dev/null
+++ b/app/Services/ReplenishmentTaskDefinition.php
@@ -0,0 +1,67 @@
+registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
+ $actions = $view->query('//t:Exec');
+ $principals = $view->query('//t:Principal');
+ $triggers = $view->query('//t:Triggers/*');
+ if ($actions === false || $principals === false || $triggers === false
+ || $actions->length !== 1 || $principals->length !== 1 || $triggers->length !== 2) {
+ throw new LogicException('REPLENISHMENT_TASK_STRUCTURE_DIFFERS');
+ }
+ $views[] = $view;
+ }
+ foreach (['Command', 'Arguments', 'WorkingDirectory', 'LogonType', 'RunLevel', 'MultipleInstancesPolicy', 'ExecutionTimeLimit',
+ 'TimeTrigger/StartBoundary', 'TimeTrigger/Repetition/Interval', 'LogonTrigger/UserId', 'Principal/UserId',
+ 'DisallowStartIfOnBatteries', 'StopIfGoingOnBatteries', 'AllowHardTerminate', 'StartWhenAvailable', 'Hidden'] as $path) {
+ $query = 'string(//t:'.str_replace('/', '/t:', $path).')';
+ $expected = $views[0]->evaluate($query);
+ $actual = $views[1]->evaluate($query);
+ if (in_array($path, ['LogonTrigger/UserId', 'Principal/UserId'], true) && is_string($actual) && is_string($expected)) {
+ $actual = self::currentIdentity($actual);
+ $expected = self::currentIdentity($expected);
+ }
+ // Task Scheduler exports the native Limited/0 default without a RunLevel element.
+ $levels = $views[1]->query('//t:RunLevel');
+ if ($path === 'RunLevel' && $actual === '' && $levels !== false && $levels->length === 0) {
+ $actual = 'LeastPrivilege';
+ }
+ $termination = $views[1]->query('//t:AllowHardTerminate');
+ if ($path === 'AllowHardTerminate' && $actual === '' && $termination !== false && $termination->length === 0) {
+ $actual = 'true';
+ }
+ if ($actual !== $expected) {
+ throw new LogicException('REPLENISHMENT_TASK_DEFINITION_DIFFERS:'.$path);
+ }
+ }
+ }
+
+ private static function currentIdentity(string $identity): string
+ {
+ if (preg_match('/^S-1-\d+(?:-\d+)+$/D', $identity)) {
+ return $identity;
+ }
+ // Native export can resolve the current SID to its account name in the logon trigger.
+ $process = new Process([getenv('SystemRoot').'/System32/whoami.exe', '/user', '/fo', 'csv', '/nh'], timeout: 10);
+ $process->run();
+ $record = str_getcsv(trim($process->getOutput()), escape: '');
+ if (! $process->isSuccessful() || count($record) !== 2 || strcasecmp($identity, $record[0]) !== 0
+ || ! preg_match('/^S-1-\d+(?:-\d+)+$/D', $record[1])) {
+ throw new LogicException('REPLENISHMENT_TASK_CURRENT_IDENTITY_DIFFERS');
+ }
+
+ return $record[1];
+ }
+}
diff --git a/app/Services/SupplyCoordination.php b/app/Services/SupplyCoordination.php
index b3a1552..91c2757 100644
--- a/app/Services/SupplyCoordination.php
+++ b/app/Services/SupplyCoordination.php
@@ -261,7 +261,7 @@ class SupplyCoordination
if ($basis === null) {
return $remaining;
}
- abort_unless(config('inventory_conversion.qa_enabled') === true, 503, 'Conversão ainda não instalada.');
+ abort_unless(app(InventoryConversionRuntime::class)->available(), 503, 'Conversão ainda não instalada.');
app(ReceiptStockMovement::class)->load();
return (int) QuantityConversion::toBase((string) $remaining, $basis['numerator'], $basis['denominator']);
diff --git a/config/inventory_conversion.php b/config/inventory_conversion.php
index 7640ba1..7fcdeb7 100644
--- a/config/inventory_conversion.php
+++ b/config/inventory_conversion.php
@@ -1,4 +1,8 @@
false];
+// Installation is explicit. Shipping a candidate does not activate it in the pilot.
+return [
+ 'qa_enabled' => false,
+ 'enabled' => env('COMPRAS_INVENTORY_CONVERSION_ENABLED', false),
+ 'root' => env('COMPRAS_INVENTORY_ROOT', base_path('packages/inventory-write/releases/0.2.0-rc.1')),
+];
diff --git a/config/order_cancellation.php b/config/order_cancellation.php
index e28f200..bed5f84 100644
--- a/config/order_cancellation.php
+++ b/config/order_cancellation.php
@@ -1,3 +1,7 @@
false, 'reversal_sha256' => '5471d9f826f47012415bf9a7086d4d7316ab8550b58e497f7432b94514a18bfa'];
+return [
+ 'enabled' => env('COMPRAS_ORDER_CANCELLATION_ENABLED', false),
+ 'root' => env('COMPRAS_ORDER_CANCELLATION_ROOT', base_path('packages/order-cancellation/releases/0.2.0-rc.1')),
+ 'reversal_sha256' => '5471d9f826f47012415bf9a7086d4d7316ab8550b58e497f7432b94514a18bfa',
+];
diff --git a/docs/desenvolvimento.md b/docs/desenvolvimento.md
index b252841..bc3905a 100644
--- a/docs/desenvolvimento.md
+++ b/docs/desenvolvimento.md
@@ -1,5 +1,19 @@
# Desenvolvimento do SGC
+29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
+
+29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
+
+29/11/2026 — reposição recorrente do piloto instalada/activa sob a autorização dos componentes necessários: `Compras-Pilot-Replenishment`, utilizador actual com sessão iniciada, privilégios limitados, php-win, minuto técnico/logon, não sobreposição e limite60s. Reutiliza exclusivamente `sgc:replenishment-tick`, exclusão nativa/recuperação durável/heartbeat da instalação; sem renovar regras ou criar parâmetros. Passagens automáticas e solicitada terminaram com0;149tabelas intactas, apenas acompanhamento de `replenishment_work` alterado. Nenhuma nova requisição, decisão, política, concessão ou movimento. Salvaguarda privada restaurada com150tabelas idênticas e base/role temporárias removidas. Diagnóstico integrado actual passou em PostgreSQL só leitura.19testes/132asserções e regressão XML1/5, PHPStan0/Pint aprovados. Correcção própria: exportação nativa omite defaults limitados e resolve SID em alias; comparação conserva identidade/privilégios/frequência sem re-registar tarefa. Tentativa inicial recusada por pin antes do arranque da aplicação; provas distinguem essa recusa das passagens finais aprovadas. Provas `replenishment-task-installation.json`, `replenishment-task-definition-fix.json`, `replenishment-task-recovery.json` e `pilot-operations-current.json`. Conferência actual de inventário conserva150tabelas durante a consulta, sem exigir que a fila operacional permaneça eternamente no estado da instalação; prova de instalação original preservada, nova prova `inventory-conversion-pilot-current-check.json`. Não repetir instalação. Reinício/logoff real e serviço de produção sem sessão continuam separados; aplicação integral continua aberta.
+
+29/11/2026 — C2 integrado nos ciclos de aprovação e instalado/activo no piloto por autorização dos componentes necessários. Escritor versionado52df7927 estorna apenas o ciclo actual aberto, preservando o anterior; regressão PostgreSQL14/258 e legada12/91, PHPStan0/Pint aprovados. Activação alterou apenas duas chaves, conservou150tabelas e recibo financeiro de quatro pacotes;56GETs por quatro perfis passaram. Edge confirmou consulta no piloto sem gravação, login normal emQA, cancelamento sintético aprovado ligado à ordem original cancelada, móvel390×526/100% e impressão de uma folha sem cortes observados; impressão cancelada e separador/ferramentas próprios fechados, três separadores anteriores preservados. A decisão manual anteriormente aceite não foi repetida. Restauro conservou154tabelas, recusou vinculação antiga e repetiu exactamente um cancelamento do ciclo2 após reassociação explícita, sem novo estorno; bases/roles original/restaurada removidos, runner0. Provas `order-cancellation-pilot-installation.json`, `order-cancellation-pilot-postcheck.json` e `order-cancellation-pilot-native-review.json`. Não repetir instalação/autorização. Pendências anteriores de móvel/impressão C2 abaixo são históricas. Nenhuma política empresarial/concessão/operação criada no piloto; aplicação integral continua aberta.
+
+29/11/2026 — instalação e activação de inventário autorizadas e executadas no piloto8005: componente privado `inventory-8608e6551dea6448`, salvaguarda da configuração e apenas duas chaves alteradas; nenhuma migração, concessão ou operação de stock. As150tabelas ficaram idênticas na activação e após revisão nativa;52GETs por perfis passaram novamente. Conferência só leitura integrou o componente com o runtime financeiro80483320/24capacidades,185assets e.env preservados. Correcção própria do instalador: validar nomes exactos das quatro entradas ZIP sem depender da ordem; regressão2/11. Edge abriu recepção/ordem anterior completa e entregas vazias; baseQA própria, login normal e sem atalhos de autenticação demonstraram selecção do artigo, campos de conversão e apresentação390×526/100%; formulário não submetido, aviso de saída observado, ferramentas/separador próprios fechados e base/role/servidor removidos. Provas `inventory-conversion-pilot-installation.json`, `inventory-conversion-pilot-postcheck.json` e `inventory-conversion-pilot-native-review.json`. Não pedir novamente a autorização de instalação/activação recebida; o proprietário autorizou os componentes necessários a esta actividade no piloto, conservando limites de dados/permissões/produção.
+
+Correcção operacional da tarefa de prazos: executável de consola abriu uma janela durante a revisão. Substituído somente por `php-win.exe` da mesma instalação, depois de passagem directa aprovada; script/pin originais, argumentos, pasta, actor, triggers, privilégios, frequência, não sobreposição e limite preservados por comparação XML integral normalizada. Definição anterior salvaguardada; passagem nativa inicial e periódica terminaram com0, sem faltas e sem alteração de políticas/acessos. Regressão2/11 e PHPStan0/Pint aprovados. Prova `approval-deadlines-task-gui-repair.json`; instalação original e prova de encoding permanecem históricas e intactas. A aplicação integral continua aberta.
+
+29/11/2026 — conversão física promovida por autorização expressa para candidata operacional e integrada em QA com o núcleo financeiro próprio. Componente `inventory-write/releases/0.2.0-rc.1`, manifesto `8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd`, ZIP privado de quatro entradas; versão0.1.0, QA congelada e contrato financeiro de quatro pacotes preservados. Selecção explícita verifica instalação, schema, bytes e classes; acordos reutilizam a aritmética seleccionada. Desligar depois de conversões congeladas recusa o escritor antigo. Recepção conserva quantidades/valores comerciais; stock, lotes, devolução, estorno e pendente mantêm equivalência exacta. PostgreSQL15/110, duas corridas reais fora de `testing`, arquivo extraído e modo QA desligado; restauro conserva154tabelas de negócio e história da instalação, recusa a vinculação antiga e repete exactamente dois movimentos após reassociação explícita. Bases/roles original/restaurada removidos. Regressão legada148/2001; delta final de recepção/artefacto34/214 sobreposto, sem somar contagens. PHPStan sem erros, Pint/diff aprovados. Pré-conferência do piloto com PostgreSQL só leitura aprovada: nenhuma linha recebida convertida, configuração/assets intactos. Instalação/activação ainda não autorizadas por esta promoção; proposta concreta `proofs/inventory-conversion-pilot-proposal.json`. Prova `proofs/inventory-conversion-operational-candidate.json`. Aplicação integral continua aberta.
+
29/11/2026 — tarefa de prazos autorizada, instalada e verificada: `Compras-Pilot-Approval-Deadlines`, utilizador actual, sessão Windows iniciada, privilégios limitados, minuto técnico, não sobreposição e limite60s. Passagem inicial e passagens automáticas terminaram com0; contenção real no lock fez o segundo processo sair sem processar ou alterar estado. Definição instalada/actor/comando/logon conferidos, sem guardar password, alterar política PowerShell, substituir tarefas ou reiniciarWindows. Corrigido erro próprio de transporteXML UTF-8→UTF-16, conteúdo canónico idêntico e validação nativa antes do registo;3testes/11asserções de regressão e PHPStan/Pint aprovados. Proposta/autorização originais preservadas e correcção técnica rastreada. QA isolada final11testes/246asserções: lembrete único, devolução do mesmo pedido, reserva libertada, aprovação anterior intacta e nova submissão com aprovações/reserva novas; base/role removidos. Piloto tem0pedidos pendentes com política congelada, sem gravar parâmetros/exemplos;149tabelas e auditoria anterior preservadas. Não repetir a instalação. Provas `approval-deadlines-task-installation.json` e `approval-deadlines-task-encoding-fix.json`. Execução após logon/reinício real deWindows não foi ensaiada; serviço de produção sem sessão e outras operações recorrentes mantêm âmbito separado. Aplicação integral e aceitação empresarial não declaradas concluídas.
Preparação da operação de prazos: `php scripts/approval-deadlines-evaluation.php --check` apenas confere composição/pedidos elegíveis com PostgreSQL só leitura. `php scripts/install-approval-deadlines-task.php` gera a pré-visualização/XML privados sem registar tarefa. `--once` e `--apply-authorized` exigem autorização própria com hash da proposta `proofs/approval-deadlines-task-proposal.json`. O instalador usa a ferramenta nativa `schtasks.exe`, sem alterar a política de execução PowerShell, sem substituir tarefas existentes ou guardar credenciais. Não foi instalada/iniciada tarefa nesta preparação; as passagens reais só poderão ser verificadas após a autorização. A tarefa proposta só funciona com a sessão Windows iniciada.
diff --git a/docs/matriz-sgc-reconciliada.md b/docs/matriz-sgc-reconciliada.md
index dadfa6a..482d456 100644
--- a/docs/matriz-sgc-reconciliada.md
+++ b/docs/matriz-sgc-reconciliada.md
@@ -1,5 +1,13 @@
# Matriz reconciliada do SGC — 03/11/2026
+29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
+
+29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
+
+29/11/2026 — reposição recorrente do piloto instalada/activa sob a autorização dos componentes necessários: `Compras-Pilot-Replenishment`, utilizador actual com sessão iniciada, privilégios limitados, php-win, minuto técnico/logon, não sobreposição e limite60s. Reutiliza exclusivamente `sgc:replenishment-tick`, exclusão nativa/recuperação durável/heartbeat da instalação; sem renovar regras ou criar parâmetros. Passagens automáticas e solicitada terminaram com0;149tabelas intactas, apenas acompanhamento de `replenishment_work` alterado. Nenhuma nova requisição, decisão, política, concessão ou movimento. Salvaguarda privada restaurada com150tabelas idênticas e base/role temporárias removidas. Diagnóstico integrado actual passou em PostgreSQL só leitura.19testes/132asserções e regressão XML1/5, PHPStan0/Pint aprovados. Correcção própria: exportação nativa omite defaults limitados e resolve SID em alias; comparação conserva identidade/privilégios/frequência sem re-registar tarefa. Tentativa inicial recusada por pin antes do arranque da aplicação; provas distinguem essa recusa das passagens finais aprovadas. Provas `replenishment-task-installation.json`, `replenishment-task-definition-fix.json`, `replenishment-task-recovery.json` e `pilot-operations-current.json`. Conferência actual de inventário conserva150tabelas durante a consulta, sem exigir que a fila operacional permaneça eternamente no estado da instalação; prova de instalação original preservada, nova prova `inventory-conversion-pilot-current-check.json`. Não repetir instalação. Reinício/logoff real e serviço de produção sem sessão continuam separados; aplicação integral continua aberta.
+
+29/11/2026 — C2 integrado nos ciclos de aprovação e instalado/activo no piloto por autorização dos componentes necessários. Escritor versionado52df7927 estorna apenas o ciclo actual aberto, preservando o anterior; regressão PostgreSQL14/258 e legada12/91, PHPStan0/Pint aprovados. Activação alterou apenas duas chaves, conservou150tabelas e recibo financeiro de quatro pacotes;56GETs por quatro perfis passaram. Edge confirmou consulta no piloto sem gravação, login normal emQA, cancelamento sintético aprovado ligado à ordem original cancelada, móvel390×526/100% e impressão de uma folha sem cortes observados; impressão cancelada e separador/ferramentas próprios fechados, três separadores anteriores preservados. A decisão manual anteriormente aceite não foi repetida. Restauro conservou154tabelas, recusou vinculação antiga e repetiu exactamente um cancelamento do ciclo2 após reassociação explícita, sem novo estorno; bases/roles original/restaurada removidos, runner0. Provas `order-cancellation-pilot-installation.json`, `order-cancellation-pilot-postcheck.json` e `order-cancellation-pilot-native-review.json`. Não repetir instalação/autorização. Pendências anteriores de móvel/impressão C2 abaixo são históricas. Nenhuma política empresarial/concessão/operação criada no piloto; aplicação integral continua aberta.
+
29/11/2026 — tarefa de prazos autorizada, instalada e verificada: `Compras-Pilot-Approval-Deadlines`, utilizador actual, sessão Windows iniciada, privilégios limitados, minuto técnico, não sobreposição e limite60s. Passagem inicial e passagens automáticas terminaram com0; contenção real no lock fez o segundo processo sair sem processar ou alterar estado. Definição instalada/actor/comando/logon conferidos, sem guardar password, alterar política PowerShell, substituir tarefas ou reiniciarWindows. Corrigido erro próprio de transporteXML UTF-8→UTF-16, conteúdo canónico idêntico e validação nativa antes do registo;3testes/11asserções de regressão e PHPStan/Pint aprovados. Proposta/autorização originais preservadas e correcção técnica rastreada. QA isolada final11testes/246asserções: lembrete único, devolução do mesmo pedido, reserva libertada, aprovação anterior intacta e nova submissão com aprovações/reserva novas; base/role removidos. Piloto tem0pedidos pendentes com política congelada, sem gravar parâmetros/exemplos;149tabelas e auditoria anterior preservadas. Não repetir a instalação. Provas `approval-deadlines-task-installation.json` e `approval-deadlines-task-encoding-fix.json`. Execução após logon/reinício real deWindows não foi ensaiada; serviço de produção sem sessão e outras operações recorrentes mantêm âmbito separado. Aplicação integral e aceitação empresarial não declaradas concluídas.
29/11/2026 — activação expressamente autorizada e executada no piloto:24capacidades ligadas,185assets publicados sob manifesto8653c147 e runtime80483320 preservado em pasta privada. Configuração/manifesto anteriores salvaguardados; outras chaves, origem financeira e.env público preservados. As150tabelas ficaram idênticas na activação;52GETs por4perfis existentes passaram com guarda prévia de SQL de escrita e nova comparação integral, sem novas concessões/utilizadores. PostgreSQL só leitura confirmou independentemente o arranque das24capacidades;185respostasHTTP/hash conferidas e domínio público entrega o novo entry sem expor navegação financeira privada ao anónimo. Revisão Edge real: cadastro financeiro, contextoCompras, menus/ordens operacionais/projectos-imobilizado;390×526/100% e salto ao formulário legíveis. Após entrada/contexto,149tabelas intactas e história anterior da auditoria conservada; apenas1evaluation.entered e1work_context.selected acrescentados. Não foram gravados parâmetros, contas ou operações empresariais. Piloto deixado aberto no dashboard, ferramentas fechadas, separador público original preservado. Não repetir instalação/activação. Provas compras-standalone-pilot-activation[-check].json, compras-standalone-pilot-profiles.json, compras-standalone-published-assets.json e compras-standalone-pilot-native-review.json. Parametrização/aceitação empresarial, percursos visuais/impressão restantes e operação recorrente conservam as pendências próprias; esta entrega não instala tarefa/serviçoWindows nem declara toda a aplicação concluída.
@@ -360,6 +368,10 @@ Pedido expresso implementado com 40 guias e cobertura testada das 87 páginas op
### Actualização — conversões de inventário, 21/11/2026
+**Instalação/activação posterior de29/11 autorizada e concluída no piloto:** componente privado8608e655, apenas duas chaves,150tabelas e configuração financeira/assets/env conservados.52GETs por perfis passaram. Edge demonstrou os percursos existentes; QA com autenticação normal mostrou selecção de artigo, campos e fórmula de conversão em desktop/390×526, sem submeter o formulário. Bases/roles/servidor próprios removidos. Correcção de ordem de entradas ZIP coberta por2testes/11asserções; PHPStan/Pint aprovados. Provas `proofs/inventory-conversion-pilot-installation.json`, `proofs/inventory-conversion-pilot-postcheck.json` e `proofs/inventory-conversion-pilot-native-review.json`. A indicação de activação pendente no delta anterior abaixo é histórica; restantes lacunas e aceitação integral continuam abertas.
+
+**Delta autorizado de29/11:** candidata operacional integrada em QA com a composição autónoma de24capacidades, através de componente opcional próprio e sem alterar o recibo financeiro de quatro pacotes. Manifesto `8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd`;15testes/110asserções PostgreSQL, duas corridas reais em `standalone-qa` sem modo de conversão QA, restauro de154tabelas conservadas e repetição exacta após reassociação explícita. Regressão legada148/2001 e delta sobreposto34/214 aprovados; PHPStan/Pint/diff aprovados. Pré-conferência só leitura do piloto aprovada, sem mudar configuração ou dados. Promoção concluída neste âmbito; instalação/activação no piloto e revisão visual seguinte continuam pendentes da autorização própria. Provas `proofs/inventory-conversion-operational-candidate.json` e proposta `proofs/inventory-conversion-pilot-proposal.json`. O estado QA de21/11 abaixo é histórico; não declara conclusão integral.
+
Preparação de contrato expressamente autorizada em QA. Fonte única em `sgf-tempo/packages/inventory-write/src`; artefacto de desenvolvimento verificado em `packages/inventory-write/development`, sem alterar ou publicar a versão 0.1.0. Adaptação em `ReceiptQuantityConversion`, escritor e recepção; lotes recebem quantidade física, devoluções conservam equivalência documental, saldo da ordem/facturação conservam unidade comercial. Factor, artigo, unidades, fonte e versão congelados na primeira recepção aceite da linha. Não há câmbio de preços nem arredondamento de quantidades.
Prova sintética: 2 caixas × 100 MZN = 200 MZN documentais, 24 unidades físicas; parcelas 1,5 + 0,5 caixas, repetição única, devolução de 6 unidades = 0,5 caixa, lotes de 24 unidades em quarentena e recusa de lote documental de 2 caixas. Confirmação de entrega reutilizada na recepção e projecção pendente em unidades-base; estorno físico de 24 unidades repõe 2 caixas pendentes. Vinte testes/85 asserções SQLite, dez/67 PostgreSQL e duas corridas com contenção real; regressões antigas, 95 frontend, tipos, PHPStan global e compilação privada aprovados. Arquivo antigo e configuração do piloto preservados. Estado: preparação QA, não instalação/activação ou aceitação comercial. Provas finais em `docs/desenvolvimento.md`.
@@ -390,7 +402,7 @@ O âmbito é o SGC autónomo em `C:/laragon/www/compras`, com o piloto sintétic
| Fornecedores | `SupplierParticipation`, `SupplierBankWorkflow`, `SupplierEvaluationWorkflow`; provas históricas e actualização de 21/11 abaixo | Cadastro, validação, avaliação qualitativa, contraditório e tarefas preservados. Múltiplas contas independentes implementadas e verificadas em QA em 21/11, com migração ainda não instalada no piloto. Verificação bancária externa não é inferida do cadastro. |
| Cotações | `QuotationController`, `QuotationPricing`, `QuotationExchange`; actualização de 21/11 acima | Preços/descontos reutilizam núcleo comum. Multimoeda implementada e verificada em QA com moeda original e taxa explícita para MZN, data/fonte congeladas, conforme aprovação do proprietário. Migração ainda não instalada no piloto; não confundir esta entrega com taxa automática, câmbio bancário ou autorização de propostas reais. |
| Conflitos RF-AF-01 | `ConflictGuard`, `ConflictReleases`; `compatibilidade.md` | Levantamento por autorização da direcção decidido em 28/11 e implementado em QA, com competência própria configurável, fundamento, autoria, fonte congelada e histórico imutável. Sem herança automática de Admin/Finanças, caducidade ou retirada pela declaração de ausência. Correcções da mesma declaração partilham a decisão; outra declaração continua a bloquear. SQLite e PostgreSQL: 46 testes/418 asserções em cada motor; frontend 5 testes, tipos/PHPStan/check/Pint/build privado aprovados. Migração e capacidade desligadas no piloto. Periodicidade/validade e aceitação operacional mantêm cobertura própria. |
-| Adjudicação e ordens | `PurchaseAwardOrderTest`; `cancelamento-ordens-emitidas.md`; `proofs/issued-order-cancellation.json` | C2 autorizado para desenvolvimento,implementado com política própria e decisão independente de Finanças,sem recepção/factura/pagamento. Original imutável,reversão canónica auditada única e revisão ligada. Desligado e sem migração/políticas/cancelamentos no piloto;antes da emissão e estornos físicos mantêm circuitos separados. |
+| Adjudicação e ordens | `PurchaseAwardOrderTest`; `cancelamento-ordens-emitidas.md`; `proofs/order-cancellation-pilot-native-review.json` | C2 instalado e activo no piloto em29/11, com política própria e decisão independente de Finanças, sem recepção/factura/pagamento. Estorno canónico do ciclo actual, original e ciclos anteriores preservados. PostgreSQL14/258, legado12/91, restauro154tabelas, ligação à origem, móvel390×526 e impressão conferidos. Nenhuma política empresarial ou cancelamento criado pela activação. Antes da emissão e estornos físicos mantêm circuitos separados. |
| Recepção | `ReceiptWorkflow`; provas de recepção e `proofs/inventory-corrections.json`; `recepcao-documental.md` | Recepção e correcções físicas implementadas; anexos privados R1 instalados com autorização, backup/restauro e consulta por perfis confirmados (`proofs/receipt-block-installation.json`). R2 acrescenta reprodução imprimível com referências dos estornos e anexos. Substituições e aceitação operacional integral mantêm cobertura própria; correcção física não equivale a nota de crédito. |
| Stock | `StockWorkflow`, `InventoryLots`, `InventoryReversals`, `InventoryDispositions`, `ReceiptQuantityConversion`; `proofs/inventory-task-integration.json`; actualização de conversões de 21/11 acima | Lotes, qualidade, correcções e tarefas já existem; «estornos ausentes» seria uma conclusão incorrecta para stock. Conversão documental/física, parcelas, lotes, devolução e estorno têm entrega QA própria; fonte/factor/versão congelados, sem arredondamento de quantidades. A guarda actual exige configuração explícita e ambiente testing. Instalação, activação e revisão visual continuam separadas. |
| Requisições internas | `WarehouseRequests`, `WarehouseReservations`, `WarehouseFulfilment`; `proofs/warehouse-task-pilot-status-http.json` | Autorização, reserva e entrega usam a requisição como documento de saída, sem factura. Venda a terceiros pertence à composição SGF; não desenvolver facturação paralela no SGC. |
@@ -402,7 +414,7 @@ O âmbito é o SGC autónomo em `C:/laragon/www/compras`, com o piloto sintétic
| Pessoas e contratações | `PeopleHiring`, `PeopleRegistry`, `PeopleReportController`; `reutilizacao-dados.md` e `PeopleHiringTest` | Cadastro reutilizável, relatórios e caixa de tarefas são distintos dos de Compras. Uma referência antiga a «sem relatórios» não descreve o código actual. Aceitação visual e cobertura empresarial continuam separadas. |
| Navegação e relatórios | Páginas `workflow/tasks`, `workflow/notices`, `supply/coordination`; `proofs/task-deadlines.json`, `proofs/notice-consultation.json`, `proofs/coordination-export.json` | Filtros, prazos e CSV de acompanhamento entregues. Isto não encerra revisão visual, impressão ou todos os relatórios exigidos pelo produto. |
| Auditoria | `AuditLog`, auditoria nativa e `PrivateAuditExporter` | 28/11/2026 — exportação privada de auditoria implementada em QA para Compras, stock, finanças e configuração, conforme decisão expressa. Quatro competências próprias independentes, sem herança de Admin/Finanças/metadados; bancos completos e Pessoas separados. ZIP privado imutável com manifesto, fontes/contagens/colunas ausentes, NDJSON integral e originais verificados; snapshot readonly, UUID idempotente, hashes, descarga autenticada dos bytes conferidos e limpeza só de ficheiros próprios. SQLite15/493, PG15/493 (base removida), frontend24/2ficheiros, tipos/PHPStan0/check/Pint/build aprovados. HTTP nativo270/quatro sessões/20assets,138tabelas intactas no intervalo de consultas; geração/repetição/ZIP conferidos após esse intervalo, recursos removidos. Manifesto fa87e37a3626ef75d22b5248dce9a0af2bad68c967e6f99bb64bc426a68f6aaf,183entradas. Consulta/CSV de metadados e retenção integral sem eliminação automática preservados. Prova `audit-export-scope-proposal.json`; sem concessões reais, activação ou aceitação visual/integral. |
-| Reposição periódica | `AutomaticPurchases`, `ReplenishmentQueue`, `ReplenishmentProcessLock`; `proofs/replenishment-process-lock.json`, `operacao-reposicao.md` | Recuperação durável, reavaliação temporal e exclusão local existem. A pendência deixou de ser «implementar reposição»: é instalar/conferir operação comercial após reinício e validar capacidade. O bloqueio local não prova exclusão distribuída. |
+| Reposição periódica | `AutomaticPurchases`, `ReplenishmentQueue`, `ReplenishmentProcessLock`; `proofs/replenishment-task-installation.json`, `operacao-reposicao.md` | Tarefa do piloto instalada/activa em29/11 para utilizador actual com sessão, privilégios limitados e passagens periódicas0. Restauro150tabelas e conservação149tabelas verificadas; só a fila técnica avançou. Recuperação durável e exclusão local preservadas. Operação comercial sem sessão, reinício e capacidade continuam separados; o bloqueio local não prova exclusão distribuída. |
## Lacuna escolhida nesta revisão
diff --git a/docs/operacao-reposicao.md b/docs/operacao-reposicao.md
index ef19a58..a16b928 100644
--- a/docs/operacao-reposicao.md
+++ b/docs/operacao-reposicao.md
@@ -1,5 +1,7 @@
# Operação da reposição periódica do SGC
+29/11/2026 — reposição recorrente do piloto instalada/activa sob a autorização dos componentes necessários: `Compras-Pilot-Replenishment`, utilizador actual com sessão iniciada, privilégios limitados, php-win, minuto técnico/logon, não sobreposição e limite60s. Reutiliza exclusivamente `sgc:replenishment-tick`, exclusão nativa/recuperação durável/heartbeat da instalação; sem renovar regras ou criar parâmetros. Passagens automáticas e solicitada terminaram com0;149tabelas intactas, apenas acompanhamento de `replenishment_work` alterado. Nenhuma nova requisição, decisão, política, concessão ou movimento. Salvaguarda privada restaurada com150tabelas idênticas e base/role temporárias removidas. Diagnóstico integrado actual passou em PostgreSQL só leitura.19testes/132asserções e regressão XML1/5, PHPStan0/Pint aprovados. Correcção própria: exportação nativa omite defaults limitados e resolve SID em alias; comparação conserva identidade/privilégios/frequência sem re-registar tarefa. Tentativa inicial recusada por pin antes do arranque da aplicação; provas distinguem essa recusa das passagens finais aprovadas. Provas `replenishment-task-installation.json`, `replenishment-task-definition-fix.json`, `replenishment-task-recovery.json` e `pilot-operations-current.json`. Conferência actual de inventário conserva150tabelas durante a consulta, sem exigir que a fila operacional permaneça eternamente no estado da instalação; prova de instalação original preservada, nova prova `inventory-conversion-pilot-current-check.json`. Não repetir instalação. Reinício/logoff real e serviço de produção sem sessão continuam separados; aplicação integral continua aberta.
+
## Estado desta entrega
O comando, a recuperação durável, o diagnóstico e a exclusão de execuções locais estão implementados. Este documento não instala uma tarefa Windows nem comprova arranque após reinício. A configuração do cliente e o ensaio de reinício continuam a fazer parte da instalação.
diff --git a/docs/orientacoes-continuidade.md b/docs/orientacoes-continuidade.md
index 6b1ae14..b1bd18f 100644
--- a/docs/orientacoes-continuidade.md
+++ b/docs/orientacoes-continuidade.md
@@ -1,5 +1,17 @@
# Continuidade do desenvolvimento do SGC
+29/11/2026 — análise de despesa demonstrada emQA autónoma com login normal: pagamento/afectação preparados pelos serviços nativos; soma39MZN recusada conservando valores,15MZN Material+25MZN Serviços gravados por Finanças como versão1. Relatório conserva40MZN e ambas categorias;153tabelas protegidas intactas, uma imputação/uma auditoria, sem alterar fontes financeiras.390×526/100% legível em formulário/tabelas; impressão de seis folhas mantém título/explicação/categorias juntos na página3 após correcção de quebra. Contexto da afectação passa a Finanças apenas com entrada já autorizada, contagem singular corrigida.37testes/7ficheiros, tipos/lint/formatação/build aprovados. Manifestoc3ac2c64/185assets publicado no piloto por autorização específica, manifesto/chunks anteriores salvaguardados;24capacidades/56GETs e185respostas/hash aprovados, settings/env intactos. Publicação pública autorizada mas NÃO executada: domínio serve instalação distinta, entrada anterior e404para novosassets. Corrigida a suposição anterior de actualização partilhada automática; ligação administrativa existente solicitada, sem repetir tentativasSSH anteriores sem mudança de condição. Provas `procurement-analytics-qa.json`, `analytics-print-publication[-http].json`. Base/roleQA removidos, três separadores anteriores preservados. Aplicação integral continua aberta.
+
+29/11/2026 — revisão nativa de `/ordens/1/imprimir` e `/recepcoes/1/imprimir` no piloto: ordem antiga OC-TEST-wKzfEhxT9Y conserva aviso de original incompleto e totais10000+1600=11600MZN; recepçãoREC-2026-000001 conserva recebido/aceite1,000 e rejeitado0,000, origem e referências disponíveis. Cada pré-visualização coube numa folha, sem cortes observados; ambas canceladas, sem impressão física.390×526/100% confirmou totais da ordem e tabela/referências da recepção; cabeçalhos da tabela quebram nas colunas. Ferramentas/separador próprios fechados e três separadores anteriores preservados. Sem gravações de negócio; conferência PostgreSQL só leitura conserva149tabelas e apenas a fila técnica avança pela tarefa autorizada. Prova `product-review-20261122.json#native_pilot_order_receipt_print_20261129`. Não representa impressão de documentos com anexos, estornos ou confirmação integral dos restantes relatórios.
+
+29/11/2026 — reposição recorrente do piloto instalada/activa sob a autorização dos componentes necessários: `Compras-Pilot-Replenishment`, utilizador actual com sessão iniciada, privilégios limitados, php-win, minuto técnico/logon, não sobreposição e limite60s. Reutiliza exclusivamente `sgc:replenishment-tick`, exclusão nativa/recuperação durável/heartbeat da instalação; sem renovar regras ou criar parâmetros. Passagens automáticas e solicitada terminaram com0;149tabelas intactas, apenas acompanhamento de `replenishment_work` alterado. Nenhuma nova requisição, decisão, política, concessão ou movimento. Salvaguarda privada restaurada com150tabelas idênticas e base/role temporárias removidas. Diagnóstico integrado actual passou em PostgreSQL só leitura.19testes/132asserções e regressão XML1/5, PHPStan0/Pint aprovados. Correcção própria: exportação nativa omite defaults limitados e resolve SID em alias; comparação conserva identidade/privilégios/frequência sem re-registar tarefa. Tentativa inicial recusada por pin antes do arranque da aplicação; provas distinguem essa recusa das passagens finais aprovadas. Provas `replenishment-task-installation.json`, `replenishment-task-definition-fix.json`, `replenishment-task-recovery.json` e `pilot-operations-current.json`. Conferência actual de inventário conserva150tabelas durante a consulta, sem exigir que a fila operacional permaneça eternamente no estado da instalação; prova de instalação original preservada, nova prova `inventory-conversion-pilot-current-check.json`. Não repetir instalação. Reinício/logoff real e serviço de produção sem sessão continuam separados; aplicação integral continua aberta.
+
+29/11/2026 — C2 integrado nos ciclos de aprovação e instalado/activo no piloto por autorização dos componentes necessários. Escritor versionado52df7927 estorna apenas o ciclo actual aberto, preservando o anterior; regressão PostgreSQL14/258 e legada12/91, PHPStan0/Pint aprovados. Activação alterou apenas duas chaves, conservou150tabelas e recibo financeiro de quatro pacotes;56GETs por quatro perfis passaram. Edge confirmou consulta no piloto sem gravação, login normal emQA, cancelamento sintético aprovado ligado à ordem original cancelada, móvel390×526/100% e impressão de uma folha sem cortes observados; impressão cancelada e separador/ferramentas próprios fechados, três separadores anteriores preservados. A decisão manual anteriormente aceite não foi repetida. Restauro conservou154tabelas, recusou vinculação antiga e repetiu exactamente um cancelamento do ciclo2 após reassociação explícita, sem novo estorno; bases/roles original/restaurada removidos, runner0. Provas `order-cancellation-pilot-installation.json`, `order-cancellation-pilot-postcheck.json` e `order-cancellation-pilot-native-review.json`. Não repetir instalação/autorização. Pendências anteriores de móvel/impressão C2 abaixo são históricas. Nenhuma política empresarial/concessão/operação criada no piloto; aplicação integral continua aberta.
+
+29/11/2026 — inventário já instalado/activo no piloto sob autorização posterior do proprietário («autorizo a instalar e activa todos os componentes necessarios para a conclusão da actividade»). Não repetir pedido ou instalação. Provas `inventory-conversion-pilot-installation.json`/`-postcheck.json`/`-native-review.json`: duas chaves,150tabelas conservadas,52GETs por perfis, desktop/móvel390×526 emQA autenticada normalmente, ambientes descartáveis removidos. Estado anterior de activação pendente abaixo é histórico. O verificador financeiro reconhece exclusivamente este delta aprovado e conserva as24capacidades/185assets. Tarefa de prazos corrigida apenas para `php-win.exe` da mesma instalação, mantendo helper/pin/argumentos/triggers/actor/privilégios/frequência/limite; inicial/periódica0 e regressão2/11/PHPStan0. Prova `approval-deadlines-task-gui-repair.json`; não repetir a correcção. Continuar lacunas da matriz, sem declarar aplicação integral concluída ou executar operações empresariais no piloto.
+
+29/11/2026 — promoção de conversão de inventário autorizada e integrada em QA; não pedir novamente essa promoção. Prova `proofs/inventory-conversion-operational-candidate.json`, componente0.2.0-rc.1/manifesto8608e6551dea6448.15/110 PostgreSQL, duas corridas reais em ambiente não-testing, restauro154tabelas conservadas e duas repetições exactas; original/restaurada removidas. Configuração explícita permanece desligada no piloto: a autorização exclui instalação/activação. Proposta concreta `proofs/inventory-conversion-pilot-proposal.json` limita o passo seguinte ao novo componente privado e duas chaves, sem migrações, concessões, operações de negócio ou assets. Pré-conferência PostgreSQL só leitura passou. Não regressar ao escritor antigo após conversões congeladas; preservar os artefactos anteriores e o recibo financeiro de quatro pacotes. A aplicação integral continua aberta.
+
29/11/2026 — tarefa de prazos autorizada, instalada e verificada: `Compras-Pilot-Approval-Deadlines`, utilizador actual, sessão Windows iniciada, privilégios limitados, minuto técnico, não sobreposição e limite60s. Passagem inicial e passagens automáticas terminaram com0; contenção real no lock fez o segundo processo sair sem processar ou alterar estado. Definição instalada/actor/comando/logon conferidos, sem guardar password, alterar política PowerShell, substituir tarefas ou reiniciarWindows. Corrigido erro próprio de transporteXML UTF-8→UTF-16, conteúdo canónico idêntico e validação nativa antes do registo;3testes/11asserções de regressão e PHPStan/Pint aprovados. Proposta/autorização originais preservadas e correcção técnica rastreada. QA isolada final11testes/246asserções: lembrete único, devolução do mesmo pedido, reserva libertada, aprovação anterior intacta e nova submissão com aprovações/reserva novas; base/role removidos. Piloto tem0pedidos pendentes com política congelada, sem gravar parâmetros/exemplos;149tabelas e auditoria anterior preservadas. Não repetir a instalação. Provas `approval-deadlines-task-installation.json` e `approval-deadlines-task-encoding-fix.json`. Execução após logon/reinício real deWindows não foi ensaiada; serviço de produção sem sessão e outras operações recorrentes mantêm âmbito separado. Aplicação integral e aceitação empresarial não declaradas concluídas.
29/11/2026 — próxima frente operacional delimitada: tarefa `Compras-Pilot-Approval-Deadlines` preparada em `approval-deadlines-task-proposal.json`, ainda NÃO autorizada/instalada/iniciada. O helper nativo existente de reposição não chama o comando de prazos; não o alterar ou duplicar. Novo helper usa apenas `sgc:approval-deadlines-tick`, mesmas políticas congeladas, sem definir prazos/actores/grants; `--check` passou com PostgreSQL só leitura e zero pedidos pendentes abrangidos, `--once` recusado antes do arranque por faltar autorização. Instalador PHP gera XML privado e usa `schtasks.exe`, nunca substitui tarefa existente; a política PowerShell bloqueou a primeira alternativa e ficou intacta. Pré-visualização passou, mas registo/execução nativos continuam por verificar depois da decisão. Sessão Windows iniciada, utilizador actual, privilégios limitados, sem password guardada, minuto técnico, não sobreposição e limite de60s; não constitui serviço de produção sem sessão. Não activar por inferência da autorização anterior de capacidades/assets. Sintaxe/Pint/PHPStan passaram; decisão concreta ainda necessária.
diff --git a/docs/proofs/analytics-print-publication-authorization.json b/docs/proofs/analytics-print-publication-authorization.json
new file mode 100644
index 0000000..5295e58
--- /dev/null
+++ b/docs/proofs/analytics-print-publication-authorization.json
@@ -0,0 +1,7 @@
+{
+ "date": "2026-11-29",
+ "state": "approved",
+ "scope": "analytics_print_and_attribution_menu_shared_frontend_delta",
+ "owner_response": "Autorizar a publica\u00e7\u00e3o desta candidata",
+ "proposal_sha256": "39d4bd6577ecffa7cf4f05779fb1a435fb2e5afa02c19c90bea11fdc0346f53d"
+}
diff --git a/docs/proofs/analytics-print-publication-http.json b/docs/proofs/analytics-print-publication-http.json
new file mode 100644
index 0000000..b505dc9
--- /dev/null
+++ b/docs/proofs/analytics-print-publication-http.json
@@ -0,0 +1,9 @@
+{
+ "date": "2026-11-29T17:10:07.239Z",
+ "state": "pilot_passed_public_installation_pending",
+ "pilot_asset_responses_and_hashes": 185,
+ "public_domain_html_delivers_new_entry": false,
+ "public_anonymous_identity_preserved": true,
+ "private_finance_navigation_not_exposed_publicly": true,
+ "new_grants_or_business_operations": false
+}
diff --git a/docs/proofs/analytics-print-publication-proposal.json b/docs/proofs/analytics-print-publication-proposal.json
new file mode 100644
index 0000000..bc35aea
--- /dev/null
+++ b/docs/proofs/analytics-print-publication-proposal.json
@@ -0,0 +1,230 @@
+{
+ "date": "2026-11-29",
+ "state": "prepared_and_verified_pending_shared_frontend_publication",
+ "scope": "analytics_print_and_attribution_menu_shared_frontend_delta",
+ "target": "http://127.0.0.1:8005",
+ "shared_domain": "https://compras.tempo.co.mz",
+ "candidate_root": "storage/framework/testing/sgc-analytics-print-qa-20261129",
+ "manifest_sha256": "c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022",
+ "previous_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
+ "entries": 185,
+ "files": {
+ "assets/Combination-Cf-uZSDM.js": "cb6de0edf2a5bc431766866135d9c8868a5671cd0bcc7894cfd8d425db1ea41d",
+ "assets/access-BQhnsq4e.js": "bdd88260846eb19ce44076292aeadfd5be9cf9e30256b5610320246d4d7aedf5",
+ "assets/access-THFOLUif.js": "bd3755fbd52bb6e7d25ca9aa43078e3e28850e40a7931cc0274215958727c6a6",
+ "assets/accounts-B0nvuErD.js": "c68b4f5f19c6eb4547e5920e5a841c4283c7a81e29ce2dbf9a82f5423b2e2c9c",
+ "assets/administrative-location-DTzxnE32.js": "a22bbd8b15d24721db135b3b29a5649a6bcddb5a2e8bdcc54756778b9a157763",
+ "assets/admission-BK3Betl-.js": "3b434e5a8d170c1d0f7a35b4c059ac8cb4eb1aded58d24bc0ef8b614c75ac938",
+ "assets/admission-CqB7KN-S.js": "fcfa3f88c3c323df6f2fc27292e91e1cbb398730dcc6dd4b5b991956f23117b2",
+ "assets/admission-policy-PAUfg4JR.js": "52664d024c5d03888253924167906d22c3a113e1ff2bd52d67dab6a6ab5169d4",
+ "assets/agreement-followup-Blw2gvq6.js": "51b15ff44bb35a8d7b681995d54acdcfd737423b66889ceb1845189e40c1a034",
+ "assets/agreement-order-bindings-k2CZlpCN.js": "044f4219c334662b6f78612e85d7859def9627d3a7cfc3676ef3de066c4fba52",
+ "assets/ai-preparation-preview-BqvzxR5v.js": "4321c2b38b8810d1a78b41d158d8dfa67612c8bbef14033fe9809d5db6420fb8",
+ "assets/app-BK4iX8j9.js": "1202fd7a03d7d3aae652e789d0770d2fd79a9d82b06232ed76f4800c948eb028",
+ "assets/app-CGdhSI_j.css": "5c0a3680dd0ddb8ae5f4df0b36526c381555b177745535b426384e874046c3ab",
+ "assets/appearance-B-znlKzk.js": "914948bdf3071c1dcd7e966a8db82aad442890aac26d7bb35b133fc4f6335053",
+ "assets/approval-timeouts-D5ga-uhk.js": "bedc0d17fa4d233727dbb49a5f6f042c6688e8ccc810240c80f69714c6b36e64",
+ "assets/arrow-right-jQM5Ljhm.js": "460657b89c0a22dd8c648c59408ab9b5d89cda0a2f77fdb5aafb5d4cd81ee047",
+ "assets/availability-_oQqJuYb.js": "f65ddc9195c6767f4d0b473e0f8dc80693ccce9d6ad7db0aea2bf399857a2bcf",
+ "assets/award-CJxxTMC0.js": "2dddfa5a5e83120d9a224a4730aab83d30e66e0aad51c2f9666846df4abb2e01",
+ "assets/bank-DTJinB_B.js": "2f190e09c0f796320c9138453a5261dd946784c201a10f0584e9ad6ddd408060",
+ "assets/budget-distribution-fields-C_WMk6hA.js": "2975460f13a415b0dccf3db2be561ba8fb7d99faa7a61ef98f6ef18f1b21b52b",
+ "assets/budgets-COD9DW3e.js": "48b4734d2cca2124626ba6b08b475313bf873ed585ee9fd34ad646fa840c83b1",
+ "assets/button-CSyysFhi.js": "a0c7c2d62ff1c139a6b5e6ff2e4c7cc778682337a935a3eee0e2df5ac36607b9",
+ "assets/candidate-availability-BBYAjwDY.js": "848c1b093b9016d4dbbc7795f44c281eb3776bfebf82b2a84ca943c70f5df1aa",
+ "assets/candidate-documents-DzSJVuya.js": "3f5131f76ab32a1477614e2318e09a5fbe736f5b6fc75fe306fdba5802f28482",
+ "assets/candidate-portal-C_bXRf4T.js": "0bd851358d2a8d178a768e7c9f9be4b3788d86183211b5d00615c4d910f261af",
+ "assets/capital-assignments-DwJuZW7b.js": "6140b680220b4bd912fe74c67e041c43a7a93c4f82725f8fe9a63efda61837af",
+ "assets/capital-register-ClvUi9ZL.js": "da43906990512fdbf2002169a58b427c54e5d4df75db5071353a4119a9538cfa",
+ "assets/catalogue-D5E2S2Ty.js": "7718a4241ff9e7306423d3de23e4e94bda87b46662a45d04e82bc1310a306e6d",
+ "assets/check-B0y1oDcN.js": "2b0f7b1e72a08a1106cae81a5910d88a308d1bc92c729def81b0c38b743c7c59",
+ "assets/clock-3-Cy_zSYUr.js": "b8bf146f2a287cd2bf356687ab0dfdcb0bef6f0213bfda494985dd98d97d20a0",
+ "assets/company-CkKlvups.js": "c0b25a0e2bf4963259b673cc1bc526c3b92ab3206ba400f54142ea51c1e5e9fc",
+ "assets/comparison-policy-summary-C80JsjfA.js": "13b64488a4166adec1678d172588b46cf6834382c575b87054c49ba587b69fa8",
+ "assets/confirm-password-Cvvp-hk9.js": "7bfe17c3bad01260d90629439fc78e59ce4aa326f8dd75c07e4003401b7be2e9",
+ "assets/conflict-BelUpYxR.js": "19efa315d126114e8d34439393364583a3fc1b735b3afc41f401c3da8aaf33b4",
+ "assets/conflicts-DgPGWmDV.js": "3d76564f70d671080bde9c3564ac219a559667c90d5332206e276ea887f464d5",
+ "assets/coordination-CeDUgNF7.js": "313a83bf15c0ec40669f3222ccd1a8c7c9eef7f99beeb01d288d1d17226fd9b8",
+ "assets/correction-source-search-CGto9NnP.js": "1ece74e0f8e500a9eed7d9d3abde20e28d453d0a496830574d656d547f56f943",
+ "assets/createLucideIcon-Bl2ij0Zm.js": "88026a98f925baf2a85f5c6091f3dce5d35689ec432417ba87ac3fba450aa326",
+ "assets/dashboard-0dx6aAbu.js": "940e59decd6e1c76a978aac81c1b19c1cd247a13bcd1da6ed456cdae1f2add84",
+ "assets/dispositions-Ce1SuEqV.js": "04824c6dbe3ae2dfe45a126661ac73d5df3ec768cb57b70bc79f857238a4aba1",
+ "assets/dist-Bm7wFECT.js": "ec7a8f48099bdb15bd706858c566dff3c664ea77420b2973463f9482c5c66aa0",
+ "assets/dist-Cxy2kTRX.js": "7884e24de234f6d592ec16f228c0eaba69ee5adf28fcbedb0d59383d184958c8",
+ "assets/dist-DSfJglKD.js": "7e5239388df8e9e9251bc5d432701c3a1798b8940371f88e42683e6426f0c6f2",
+ "assets/distribution-amendment-DZsLTfT0.js": "be1980bd2de5f42270f5ba026c3358866f69a3425269b130d69366deff48e62f",
+ "assets/distributions-CY85EQWK.js": "acd190872dc8e8e472951e7ce79009697562a6fab1ba98cee4cadffb76f86770",
+ "assets/download-d-ik75sA.js": "ac23d0b10fe748b8664965a4ebb479336cbc75e4d08e570577e5f70519bfde1c",
+ "assets/edit-ur-EjaWY.js": "3af5b81c72b25c29f60fc77bf23d7e0427e8d5693a9e722bc52094212829ac74",
+ "assets/entry-BMPBipqO.js": "86a0237e6384bc820631072f41db18c02afbf3a6e05a097e0b6c8e63a1ad5507",
+ "assets/equipment-BzLWUYhw.js": "bfeac74c0c9c54b908b5c9cc278c1d78689d686afe6508928198a78975e98e33",
+ "assets/evaluation-Dt9RWejE.js": "7d02ad3b2aec11b6eb203c890a25614be91c29434ac35f12ae9e4b25064568ba",
+ "assets/evaluations-lM3tp1Xd.js": "ba99599c48387d03f832add36fe1b49e7ce7e49a84900989c60a183d5b7277aa",
+ "assets/expense-allocation-BCkbb7o5.js": "6a187f4f01b69566a3ed18de7146ae24d89b7333a11f5476dabc3819ac5d743a",
+ "assets/expiry-2csqUijE.js": "bb09bd1dbab3f9503388560f867fccd479ef6511bef03ddf616a3e1062623d92",
+ "assets/eye-BcFYyvf-.js": "eccd97f0bfeab1e54e9d1abdcd96184794449a6b6277d096598489f52f61e9cf",
+ "assets/file-text-BMumQ0Wt.js": "9af4fdf5c0527694f24719af17256ac1ebb7061ddd738e5135fdd411f5b3a3ac",
+ "assets/finance-BHfZdnmL.js": "b6201b84b3433d1c68311ea7e3d36bd99a4e33690d0497a91a37dd21b0e5df8e",
+ "assets/fonts-C9MNnjVw.css": "3846a9bb60bfad92960eadcccaf0b4e129d74b11d48791506c8d1a827a385cc8",
+ "assets/forgot-password-BsfTSa-y.js": "1a4a7bc44107c0f575ba5243d83b000644e40875f61ddebee1a4230ebd842983",
+ "assets/form-BBTX1RA3.js": "0917e170d17c333662e3aef529b65327ad16699c5424d208be450bf015195bac",
+ "assets/geography-review-BaQz9Uws.js": "5cd6071fdf5bc98a5bcd675f04fd3382980602c986571bc8cef1b11f206de112",
+ "assets/history-q9dKfKPI.js": "2408f093e1e6b44cba93ebf4e287ca0be330fd37b83ff3913b97c87d8ae8fb00",
+ "assets/home-BZMGz2tD.js": "f06c278668de3a052636ee84d57b7f9fe0eb592090bfad191957a6645550677f",
+ "assets/import-bank-support-BEzXwj3b.js": "e90e2c33e982789a41e54a5d62c2b297ed21dfb827e959f3beaa42bdfc18b18b",
+ "assets/import-costs-BBG7x1FC.js": "dabdc50b18fbc8ec780c348c6ce72306d3ebf54c4392adca2e354b44303728d3",
+ "assets/import-dossier-miS1Jj9N.js": "847c61aa408725c245a78f0e293925ee306e0dc52943a928126c397ecbe6a826",
+ "assets/import-estimate-D1VF2cSU.js": "d5c8bf4c1d23170f01e6de13bd4afee4db070883e3d32cc958a95e9640c2b2bf",
+ "assets/import-estimate-money-C8In-mMc.js": "a55799be92061737217e27d9d22baf042cd085b35da5c49f64ef8abb819205a5",
+ "assets/import-legal-DCy0Ab82.js": "9d05b61e940bd226cce6d39e930a33f36f45fe4187f494d291876ebd74a8f2ed",
+ "assets/import-readiness-CZGfjTTQ.js": "726814eb99bf30b95609bc62eff1b974fedb702e28b02d938373245851836e4a",
+ "assets/import-tariff-summary-CmUfJ-Nk.js": "830c0192461fe81d1ea8e66e8ab0c152ee312a4fc46d19377429605def0e7a04",
+ "assets/import-tariffs-D40k8bOP.js": "cb4dbc328965f0d78791c6ce8eb0439b8cc8b5359d49181bc843579e5137ff89",
+ "assets/input-error-B1DjHZT7.js": "00286fd9e30543b59027b37606d63c96944efdf4f58339aba7afd0cd08629ace",
+ "assets/instrument-sans-400-normal-D1W7dsQl.woff": "797bd3eaa70edbd4757650ab44dad75fbfbfdf18bacedb4b71022c04621d30ad",
+ "assets/instrument-sans-400-normal-DRC__1Mx.woff2": "9a91efaa3599a6ef01b2f49e9ec670e3a2f39baeef09c73198f1052cf3bb0850",
+ "assets/instrument-sans-500-normal-Dk9ku72i.woff2": "9d3547da16d950d12a677c772a3ff9b69846e60e7dcd1b5efd540993f7286532",
+ "assets/instrument-sans-500-normal-Z6ESRlEs.woff": "bd6a8dc8b0dc0cced0c32d3eda93f0e0e82c58ddefea8b53b3307b0c48da3089",
+ "assets/instrument-sans-600-normal-B7fBEWYG.woff2": "efb770916eda95a0e31d80cccde9651d4e8617010b21220e9f227c4820d675da",
+ "assets/instrument-sans-600-normal-B9e8oLYv.woff": "9b4ce1f2b26be7cb087fd87d6f99a202136292ec820af75bd38ab9e53895cf28",
+ "assets/inventory-B5h3Ukug.js": "4e5464e66e4f4436f82f06de10587dbde46c3b7c92d964b09eaa31e6d9f4fb2e",
+ "assets/inventory-BF2HrsoH.js": "fa3e4a56bae767f93e7f7d0202c4efecc8d08583c0ca6761db8560acda64ddc9",
+ "assets/inventory-correction-filters-DzRPHsHm.js": "b0d51c92d5601bee5c0597fd4f552816e1a6741f060009756094447149471b3e",
+ "assets/inventory-demo-iBmoWnSu.js": "d3e2c56b8b88848e9a054657e8a97099d3cd240dde67e874f8ca1f1349a8405d",
+ "assets/inventory-event-actions-DAGSBTeF.js": "c1aff5105ee3969c681c6797a27ce03fb3cad25b06dc9f178d0476442211c8d7",
+ "assets/investment-PLV9V02t.js": "6447fd49732cbbd659f4a28a80914aa4a74af6d183008c63080ac48e82fe3f52",
+ "assets/invoices-BoAM7WOz.js": "199f60d0df5cc510d136b84e0cbd21096dff6d386f46b8d2710c57b3fe41f429",
+ "assets/jsx-runtime-Cjjuc_0N.js": "239501f6701a312b0fbef99c9067ea0d62f11aeeb3a8b388ec4c7528b0493500",
+ "assets/label-Dn4U5SHB.js": "d273f9faf668fc6fc998709fa86dbb3d424a23271725cc48a9b88a8b2d8e399c",
+ "assets/loader-circle-YS2_4W2r.js": "4648de3680be9df8d38d808bb954b6cee541cf3b376321926a10c3edddb96345",
+ "assets/login-CKWAWSgk.js": "a09503f00104dd2a371daf3f7094a67d1edc38b425ccf855cb491f9ec4bbf5fa",
+ "assets/lots-DtbJwhmY.js": "57479a4c4b61b11c94e6265fba17a80e7cb6909cdfcba13a87bfab485991e60f",
+ "assets/metadata-BX49ROpI.js": "6ccd6ce969db9b783eb96505efc17f4c9e5cb2ead80bdf0c2a88bf100a9146c5",
+ "assets/notices-CXfiAX-g.js": "7c6201ead19bb45827f72a6687ea498cb549abbc63e24614c496d9729021ad38",
+ "assets/opening-qfxU3l3z.js": "6257130574b0c9b7dd911cff7484004c9b7010f15518692002ccb70e83e228b8",
+ "assets/operational-orders-D-6WxvEd.js": "5e3e6a1cb9240884a8b0452e9d07e80fd33d09c37752ed013aa1feff63a53262",
+ "assets/operations-D4ZSfTHZ.js": "5df47a9a341054034a02445171312e74a590f04cd8e2003eab1163a87865e6bb",
+ "assets/opportunity-DOit69Zz.js": "8569286358e62aa0895f16480ae0a05ebec0087c5096a83629234f419b2a3ec8",
+ "assets/order-B2XacqK_.js": "528d8905353b71fd74cf0d3b1c08a0d29e5a31f0bd0782e872c41edde849ee63",
+ "assets/order-document-links-CY7gGohw.js": "a94c6e359ec9ab4cb143177522e2822c9aaacc462f636ab5fccfe09c45cdc43c",
+ "assets/order-parts-CW5t2gcS.js": "4bf1d746291eded17bfeceaedcfbab1f4daf5fe0f384739196110a8f98b5db9b",
+ "assets/order-parts-amendment-CYgAI637.js": "305f9cf1f083e91f4eea6aa556f920cec6614b0d729de588a3de237e9e75cc33",
+ "assets/orders-ZLx2ht-j.js": "c24107c0eaed39a0284ff6bc4c70e0008fffce81144ad8e4a592b21ccffb010f",
+ "assets/package-check--ZYjz2oi.js": "ce6074fe092e03473ff914cfe088a47acd57852fe4faef54f239fd04ccd6ab83",
+ "assets/parameters-CFCFFhX1.js": "aebf9777d80f8655462799a09e8c06c67f8b7f7c067dce04fc11d41e52bcd58b",
+ "assets/parts-CVebyMsC.js": "a450d0869a112b4dfec410b0468dd68c2c1e871afbba5b2a673b7172f1b31683",
+ "assets/password-DSVT9zkL.js": "e9f8a7ef9b436a3e046d49f9ab56bdb4ca736bc98f69fc89efe36ec0a9bd08aa",
+ "assets/password-input-CGkicVvZ.js": "52fbcc502527e3e1a11048d63192887eb6ba391649b99c87154d4e0aa58a8fe3",
+ "assets/payments-DRZKh6_G.js": "08bcc95a0b8a06679eda982b05e26a761bac6b007e197cc128bd098572f4a5b6",
+ "assets/pencil--NTa5x5n.js": "ffc5e9c22501ed8196d21f31e016d351f91796821392ec9942716d7a70b9c022",
+ "assets/people-hiring-0ebERuf_.js": "443ff16989484ecbb7576eb060a5339fccd2fc720015d72a2af828e91d12461c",
+ "assets/people-vc9vxDEm.js": "519ba8f2426e1164b737a2383fe624470434caebec146f7b55fdc2ec9d5e0c4e",
+ "assets/pilot-QE42BjXb.js": "03979934dd7d58b36b280db02ac60b228b10c137e4053e9d7271e39b57ae35d8",
+ "assets/planning-CxTCxAAg.js": "e87e388094710ddd37a1a96770458b686c3a3f82c38db6e17f621e0aaf13fde0",
+ "assets/preview-2Baf6red.js": "715ce59aa68b984f8acbbfbf05ba167cb25b9d04a90321950f817603448ed36f",
+ "assets/principal-B2cvvX38.js": "d58223279fd6562b38f8dee50f6b4197e3b14afd87e80f19da561cb1a893c456",
+ "assets/printer-D0Qc0KdJ.js": "6a29144df3944867ae389bb8e8194205099314ffa04c41f0fb054226f27b3566",
+ "assets/private-B4HtjIoy.js": "650e4e263e7aa6167d7fcc301bcf3f66a28772ddfefa2ba3223caed3ff729d77",
+ "assets/process-aYHhc60z.js": "7d79edef1b0f80b19b5216a92713641c653e22bb275aca0ff7604f38d75d1f8c",
+ "assets/procurement-Cvdj8oIj.js": "deb9b91818d092d48f280a9bb16608b77e12e28896b09206b1dac349e538fa95",
+ "assets/procurement-DzkUQnll.js": "6d21cdd22f6506858d82f71ccfd6ef470bb39efd88f72164c2444a0edaf86fb8",
+ "assets/procurement-KYYgYNux.js": "17a0bbcaf372d3db92680dc1b09b3c394790889ebc7f336592262bc766973be5",
+ "assets/procurement-payable-insights-CDEq7c2P.js": "e3a905b3f290d650b74b4ba3cf2ad608cb47f68cfe996188437ea007cc1bb929",
+ "assets/profile-D54hbdmC.js": "b8cd4ce6a1c55ea13e4867d2068b8d4dd3a95647b6a62b8cf18add21456e8b1b",
+ "assets/profile-DPUTcZoy.js": "d72165a92b5044658bbbcbcf48a5aa283d902fef968e89d522b46e6831d1040f",
+ "assets/purchase-controls-ewuBPhyL.js": "2770f80ba3d186212f42274fad2a7bef7eb9ad61a6f9256f7a8f7e182d969e49",
+ "assets/purchases-Ca_KpCmN.js": "126bc431c98a1bfc7b78900240dcfed6b92e62fde375a51d456d8adda479ed2f",
+ "assets/qualification-BXtQGBTt.js": "897d0fd2f8486eb54a9f0a3561407e09a07bb666fee406720344ccffbec972ed",
+ "assets/qualification-Du1Xe6ov.js": "6abaaa89ee76d8f4a8e87f225d59a5649cc6c42dfdb308cd54a596b1191e86b8",
+ "assets/quotation-exchange-panel-Bb-FpBDN.js": "202e9e095b8927a3e456e4cb88ad384bddd1cd614a788a43821d7f6a81a04ddc",
+ "assets/quotations-D9cysYJU.js": "fdcced03e5dfde210cbec687eab13f8b071bd542a15398e52e72858007c6f213",
+ "assets/receipt-CX6COlya.js": "a20578c41e007f6000ff25baf9e53e7c39312d6541432b98edaa66d2355461d8",
+ "assets/receipt-conversion-D0IUpbhy.js": "e3833dd9a81a5f6c6de4e76d1f498948937181d175891538ddf4d63f17d74538",
+ "assets/receipts-D6YB4_Jx.js": "cfe113e2ccc6abb7aa4d3a7aff6da5f3697d67b104c09b92b3d710809c5fc7e0",
+ "assets/recommendation-CmaM4HJV.js": "4ba79527141dc9cc690b6485c1ed7cfb22d4b661d4bbc45edd1d442359fd6984",
+ "assets/recommendation-X13fITXf.js": "f7c0cacb2c4d8bbf4f8c36a9a5fc6edbbb120a667e61aa6f2b2cb8bb2ab7f9d2",
+ "assets/recommendation-policy-B9djca3O.js": "4e168e3dc0a5444cde07bf1e7e0d3d4200b48a9664d67be3fe285bb1808b0666",
+ "assets/register-DV1Dn1KF.js": "64660bd305301ebaa0fd1a6029ea053ce67b78e2bb22861c0d24e9411a4427d8",
+ "assets/registry-D3ehlRXP.js": "8f57cda121e959743a96a4ed39ceedfbc1f10fae75d6eb704f227259335f9824",
+ "assets/replenishment-BSPA8hsB.js": "b7758a61c7dcb8a7e37b197524094f9326f36e24604e05b5188f9855d2d55448",
+ "assets/reports-BP0rIua-.js": "847c370c3d1a7409f4bf19c6a6fe8b183df96b37024d077f7dbafaf737b47641",
+ "assets/request-C9zi9kze.js": "e29430960e7cfebee39ce8e368707b064b89aa55ed3b0da90eff7da2e444b49e",
+ "assets/requests-BqKmjm25.js": "715a80e2e88a8662558fb248eed8647889f71e380d556016340ceb296f835eb4",
+ "assets/requisition-category-fields-BSaNVKfc.js": "6b4144fb8fcd88e53184371fb7840883a50f4db5a982ca1b3b336486f0d2c926",
+ "assets/requisition-history-Dsahm4kA.js": "cd35dcf01ae95f608899009f3795ba78255ef294566e97ca24b70204ff2fa033",
+ "assets/requisitions-C1hewAoT.js": "09766fa54551207c610797ef71c59c04d8294efbc31244bb8a97ff3283fc8ad9",
+ "assets/reset-password-UF8No2x4.js": "05dc0e458ac976b947f12e497de942ad554555c268b8ac7a608701abc27edda2",
+ "assets/returns-CsSg5aR6.js": "80d184c4f18440fc5ac4f09705a915ea9e5c28478dd238417be5b1198df14927",
+ "assets/reversals-BiwrSQxc.js": "833d51a38d2cdd36449e590d99e8413bc7bbe6e948e2d87f5a29f2d08309898a",
+ "assets/review-report-BgIasIw6.js": "86e0e497376c393c45a8451b2391fb20e0928b2256d7765084117ac9ed3b1c0d",
+ "assets/rolldown-runtime-WkwZ5CU-.js": "2629f2ad3cb75a57d98de697127f5af7d777ef572bbcdfa6e3ce8f438cd4527e",
+ "assets/security-CMJB8gNH.js": "0080ae8230f76e4596d00d0898c37b737e2c717c45df3534fd578a65f2d04e5c",
+ "assets/setup-L_WTWruE.js": "3711d34ade26f36f31cf5da6aea22b451e6b210668428c5abb481f1c3ac24056",
+ "assets/show-BGOJEIoW.js": "f7e70c5338287ed6cd0aac4781da59ecb1a9aed02483f54dd6309bfce96766f0",
+ "assets/show-C0nRf4-W.js": "d30e3d51055f421ed475aef23134fec4a0a1d78120eca02ced09dfd63c1e3cd9",
+ "assets/show-CXFekrSj.js": "1a82ecbb42626ad0f770875b3770787775ff864c76cde6e9bc3bc739c5a1473e",
+ "assets/show-CcmBMSeG.js": "060510346f38976ea8aae1b6a1fda384194b7030b9b13b5470b7b9b5025dc71d",
+ "assets/show-CxCJm8Fm.js": "fa5e743e94a78d0bb7b38d92809998e03405995331cd402a39822610ef8ff3cf",
+ "assets/show-D8yGExlC.js": "e190c585949c8000175272d696d0c040448c21e4d0bca6c868751e153ef9c85d",
+ "assets/show-H7UuHhmQ.js": "9e13ca339fb23c6dc8efdea29ef82640b4d1e2bff48259160124d25c453a82f3",
+ "assets/show-LY6kjTcD.js": "748ffa92cf43810d46d5e8d403d8e5c376fd85cb2950adf9c649149854e65886",
+ "assets/spinner-CpJAdIKb.js": "9c8f8fb08c631cae61ecdf41cd766fbc3e777fd184fa707b6351c3d460eef059",
+ "assets/stock-BbWMSwce.js": "fd44071b804bff18a850cd7ac59b4a9857c4ce91445806eb7eec13800907d5c3",
+ "assets/submission-forms-B2rMm0PR.js": "2ffe61bfd2c33ba1aa28c66c706286baf3528411fe1993582bfc8b0b6f18ba64",
+ "assets/submissions-3_zgF6hO.js": "0bdbd940d72b58b3a63cdcf498d32e72da2f05355598047c608ed5f390cb7c1e",
+ "assets/suggestions-D3N9P-9j.js": "41fe46b76540cddcc8a729fc8a0b0be0682a0a2d149108617a951536ddb7ae48",
+ "assets/supplier-DbZ754P4.js": "5617827f9283736a34edb62fe4ea4e6c8df48961c617dd66f416fb054dd92ab4",
+ "assets/supplier-evaluation-fields-CVaumKo3.js": "b3bf770155496cb949573a08741f4962568a0f9b16d983197fa34a8ab7af3a9a",
+ "assets/supplier-improvements-BeE5tDqG.js": "aa7f5e25200fa2f7474d2748b5e3aa6a570b2a969c0ccf5137de95d53cbd8185",
+ "assets/suppliers-BfMwBo4L.js": "02c895b64f9664e825a03b08c4f0a1e60e2134667b38f27b3906fff8fe29b749",
+ "assets/supply-BbIkSZzF.js": "98862093982d5ed521983abad8d4de9a16e1b3b00c5e88af4727b6bc81c48031",
+ "assets/supply-pagination-CnzjlbVc.js": "8537e2e4e48a836f41a2b2176f635ced2b1c62734485d1109bc4469168a1cb28",
+ "assets/tasks-CU4M7rtv.js": "4c0191661c6ab53599dd032c054a3b61f7fedf628fcfe4610c677b52f48361ee",
+ "assets/territorial-filter-DEH8-GF_.js": "20fc0ebc42d3e7e6280072a46f16c5c863750f5380fc752a9dfc0f5968bd6c53",
+ "assets/text-link-CydDNIng.js": "9ddf76c1a4d33cb5d25315e38395f2893250091a23c156adc582bbb2bcad85b9",
+ "assets/two-factor-challenge-B82fyAle.js": "67a32b22c24504210ab2b8a1e6b89d103132b2cbc44b947092c8960052e85b96",
+ "assets/urgent-review-BACi5kh1.js": "de91aa6c6f07f44534bbefa21b7084d73381794144bf27de6bc3d68d817eb6ce",
+ "assets/urgent-review-policy-CAYqVJOH.js": "2d6d6ae185657c2670df87b08e0317b4f398702bfabec45c70ffc7f15c45e6fa",
+ "assets/urgent-reviews-tbM20Twf.js": "f5d776b9e5e9d5ce0cea9cce341725d522a9abf58aec48a7248294b0e13fe3cf",
+ "assets/urgent-stock-CzCK2Tcq.js": "1d8137dfe215f3af36580b20fff6eb11342925bfef58cf4cd3d7dcebcf162411",
+ "assets/use-inventory-preparation-identity-DcCfUMXu.js": "43e5cb96c4ef1bd19574442166c972db05be7d25e5f5ba76a8a0086646eaa0f8",
+ "assets/use-preparation-dirty-DymVzALS.js": "205f865b1fa5fe2550bfcd1ee4d7f280f74065e40c30039cc0cdc6e49dd2a851",
+ "assets/use-procurement-preparation-identity-NZ7gcqOB.js": "09315e79db9d28ab8e584c1e6978ee3da38a849f1be28c0499301e1b3f98d115",
+ "assets/utils-DJPu_GY6.js": "7b162681baff9e9a115823fd6070404fcaddf53d058b311edbe98be7f2662ef4",
+ "assets/wayfinder-Dp7PqxvV.js": "3d4c90228fda731e37f541f3087fdf5387d9d59433e35b267b64a97196f70781",
+ "assets/welcome-BrJd9VRZ.js": "141ecdb30924a8bb99e9c2aa062e5ee614bb5b3ea5e908f67baaf155d7c73240",
+ "assets/work-context-Bhs3Erdk.js": "264da10231ba35dd6e9f7d29c11be4e1d7e9f1383415aee679575d455649efc0"
+ },
+ "changes": [
+ "Keep report titles and descriptions with following content in printing; category title and table observed together on page3.",
+ "Use existing supplier-settlement menu context for the common allocation category page only when that menu entry is already authorized.",
+ "Use singular text for one confirmed payment."
+ ],
+ "verified": {
+ "frontend_tests": 37,
+ "files": 7,
+ "types": true,
+ "scoped_lint_and_format": true,
+ "private_build": true,
+ "native_normal_login_and_error_correction": true,
+ "mobile_390x526_100_percent": true,
+ "print_preview_pages": 6,
+ "category_heading_and_table_same_page": true,
+ "protected_synthetic_tables_unchanged": 153,
+ "one_explicit_attribution_one_audit": true,
+ "synthetic_preview_database_role_removed": true
+ },
+ "procedure": [
+ "Verify old manifest and every candidate file hash; refuse any conflicting existing chunk.",
+ "Save the current manifest privately; add only new or byte-identical assets.",
+ "Atomically select the reviewed manifest, conserving previous chunks for recovery.",
+ "Verify pilot assets and anonymous public page entry; do not activate public runtime or capabilities."
+ ],
+ "recovery": "Restore the previous private manifest only after checking it has not been edited concurrently; retain both sets of immutable assets. No database restoration or downgrade.",
+ "not_included": [
+ "Database writes, migrations, grants, policies, new business operations",
+ "Public runtime or feature activation",
+ "SGF changes"
+ ],
+ "authorization_reason": "AGENTS.md section6 and the earlier concrete shared-publication approval pinned the previous8653c147 manifest. This new shared manifest also changes the frontend served by the public domain."
+}
diff --git a/docs/proofs/analytics-print-publication.json b/docs/proofs/analytics-print-publication.json
new file mode 100644
index 0000000..0490f55
--- /dev/null
+++ b/docs/proofs/analytics-print-publication.json
@@ -0,0 +1,19 @@
+{
+ "date": "2026-11-29T17:07:03+00:00",
+ "state": "partially_published",
+ "authorization": "analytics-print-publication-authorization.json",
+ "manifest_sha256": "c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022",
+ "previous_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
+ "backup_directory": "C:/laragon/data/compras/backups/analytics-print-20261129-170700-a62c6586f9fa",
+ "assets_verified": 185,
+ "old_assets_preserved": true,
+ "database_commands_or_settings_changes": false,
+ "public_runtime_activation": false,
+ "application_complete": false,
+ "pilot_state": "passed",
+ "public_state": "pending_existing_administrative_connection",
+ "public_html_still_previous_entry": true,
+ "public_new_assets_status": 404,
+ "public_installation_distinct_from_local_pilot": true,
+ "previous_shared_installation_assumption_corrected": true
+}
diff --git a/docs/proofs/approval-deadlines-task-gui-repair.json b/docs/proofs/approval-deadlines-task-gui-repair.json
new file mode 100644
index 0000000..32cf48f
--- /dev/null
+++ b/docs/proofs/approval-deadlines-task-gui-repair.json
@@ -0,0 +1,27 @@
+{
+ "date": "2026-11-29T16:20:49+00:00",
+ "state": "passed",
+ "task_name": "Compras-Pilot-Approval-Deadlines",
+ "authority": [
+ "approval-deadlines-task-authorization.json",
+ "inventory-conversion-pilot-authorization.json"
+ ],
+ "private_backup": "C:/laragon/data/compras/tasks/deadline-gui-20261129-162044-cff0de2edac3",
+ "old_executable": "C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe",
+ "new_executable": "C:/Users/macbook/.config/investmoz/php-8.5.11/php-win.exe",
+ "gui_binary_sha256": "ddaed8c0f5fce59a4a92405fe41ab3a9dd3217e65629a1fbb334c43ab72021dc",
+ "only_executable_changed": true,
+ "helper_sha256": "a0aca6a8101b992007efda0920a2cc0336ff84f2a17b3150387605cd35ffca38",
+ "arguments_working_directory_triggers_principal_privileges_overlap_and_limit_preserved": true,
+ "powershell_execution_policy_changed": false,
+ "business_policy_or_grants_changed": false,
+ "reference": "https://www.php.net/manual/en/features.commandline.php",
+ "native_initial_exit_code": 0,
+ "automatic_periodic_exit_code": 0,
+ "missed_runs": 0,
+ "helper_status": "passed",
+ "original_task_definition_and_history_preserved": true,
+ "regression_tests": 2,
+ "regression_assertions": 11,
+ "phpstan_errors": 0
+}
diff --git a/docs/proofs/compras-standalone-pilot-activation-check.json b/docs/proofs/compras-standalone-pilot-activation-check.json
index a83cdf8..2616306 100644
--- a/docs/proofs/compras-standalone-pilot-activation-check.json
+++ b/docs/proofs/compras-standalone-pilot-activation-check.json
@@ -1,5 +1,5 @@
{
- "date": "2026-11-29T14:05:50+00:00",
+ "date": "2026-11-29T17:10:05+00:00",
"state": "passed",
"database_enforced_read_only": true,
"all_24_capabilities_start_with_pinned_installed_packages": true,
diff --git a/docs/proofs/compras-standalone-pilot-profiles.json b/docs/proofs/compras-standalone-pilot-profiles.json
index 3388b3e..7cb17b2 100644
--- a/docs/proofs/compras-standalone-pilot-profiles.json
+++ b/docs/proofs/compras-standalone-pilot-profiles.json
@@ -1,5 +1,5 @@
{
- "date": "2026-11-29T14:03:27+00:00",
+ "date": "2026-11-29T17:07:52+00:00",
"state": "passed",
"mode": "in_process_gets_existing_actors_array_sessions",
"sql_writes_refused_before_execution": true,
@@ -126,6 +126,16 @@
"configuration": true
}
},
+ {
+ "role": "admin",
+ "path": "\/ordens\/cancelamentos",
+ "status": 200,
+ "finance_navigation": {
+ "payments": false,
+ "ledger": false,
+ "configuration": true
+ }
+ },
{
"role": "procurement",
"path": "\/dashboard",
@@ -232,6 +242,16 @@
"configuration": false
}
},
+ {
+ "role": "procurement",
+ "path": "\/ordens\/cancelamentos",
+ "status": 200,
+ "finance_navigation": {
+ "payments": false,
+ "ledger": false,
+ "configuration": false
+ }
+ },
{
"role": "finance",
"path": "\/dashboard",
@@ -334,6 +354,16 @@
"configuration": false
}
},
+ {
+ "role": "finance",
+ "path": "\/ordens\/cancelamentos",
+ "status": 200,
+ "finance_navigation": {
+ "payments": false,
+ "ledger": false,
+ "configuration": false
+ }
+ },
{
"role": "warehouse",
"path": "\/dashboard",
@@ -435,6 +465,16 @@
"ledger": false,
"configuration": false
}
+ },
+ {
+ "role": "warehouse",
+ "path": "\/ordens\/cancelamentos",
+ "status": 200,
+ "finance_navigation": {
+ "payments": false,
+ "ledger": false,
+ "configuration": false
+ }
}
]
}
diff --git a/docs/proofs/inventory-conversion-operational-authorization.json b/docs/proofs/inventory-conversion-operational-authorization.json
new file mode 100644
index 0000000..ecac413
--- /dev/null
+++ b/docs/proofs/inventory-conversion-operational-authorization.json
@@ -0,0 +1,8 @@
+{
+ "date": "2026-11-29",
+ "state": "authorized",
+ "owner_response": "autorizo",
+ "proposal": "docs/proofs/inventory-conversion-operational-proposal.json",
+ "proposal_sha256": "4b90352892dfdb2f6d48f7fea678027877beced01d2d31f69325803126ee61a8",
+ "scope": "Operational candidate and local integration; isolated QA only. Pilot and production installation or activation excluded."
+}
diff --git a/docs/proofs/inventory-conversion-operational-candidate.json b/docs/proofs/inventory-conversion-operational-candidate.json
new file mode 100644
index 0000000..45873df
--- /dev/null
+++ b/docs/proofs/inventory-conversion-operational-candidate.json
@@ -0,0 +1,61 @@
+{
+ "date": "2026-11-29",
+ "state": "candidate_integrated_and_verified_in_isolated_qa",
+ "application_complete": false,
+ "authorization": "inventory-conversion-operational-authorization.json",
+ "artifact": {
+ "root": "packages/inventory-write/releases/0.2.0-rc.1",
+ "contract": "COMPRAS-INVENTORY-CONVERSION-v1",
+ "manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "archive": "storage/framework/testing/compras-inventory-8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd.zip",
+ "archive_sha256": "dbb7e3d172f2ce5168f678993b96d9d94ce2e0c1737b581743cf2bbb6d4d00b8",
+ "entries": 4,
+ "canonical_source_bytes_preserved": true,
+ "legacy_and_qa_artifacts_preserved": true,
+ "financial_four_package_contract_unchanged": true,
+ "archive_rebuild_identical": true
+ },
+ "integration": [
+ "Verify own standalone installation receipt, financial package identity, inventory schema, manifest and bytes before use.",
+ "Single receipt writer; agreement arithmetic uses the selected component; existing receipt and delivery interfaces receive verified availability.",
+ "Exact physical quantities across partial receipts, lots, returns, reversals and pending deliveries; commercial quantities and amounts preserved.",
+ "Disabled component refuses legacy fallback after frozen receipt or delivery conversion; mixed component locations refused. Arithmetic-only loading remains compatible with ordinary legacy receipts."
+ ],
+ "verification": {
+ "operational_postgresql": {
+ "command": "node scripts/requisition-ledger-qa-check.mjs --standalone-conversion-only",
+ "tests": 15,
+ "assertions": 110,
+ "result": "passed",
+ "archive_extracted": true,
+ "real_contention_scenarios": 2,
+ "same_input_statuses": [200, 200],
+ "conflicting_factor_statuses": [200, 422],
+ "one_receipt_movement_audit_per_scenario": true,
+ "write_workers_environment": "standalone-qa",
+ "qa_conversion_enabled": false,
+ "backup_restore": "passed",
+ "old_binding_rejected_and_explicit_rebind_verified": true,
+ "business_tables_preserved": 154,
+ "converted_movements_recovered": 2,
+ "exact_replays_after_recovery": 2,
+ "business_rows_unchanged_by_replay": true,
+ "original_installation_history_preserved": true,
+ "source_and_restored_qa_databases_and_roles_removed": true
+ },
+ "legacy_focused_regression": {"tests": 148, "assertions": 2001, "result": "passed"},
+ "final_receipt_and_artifact_delta": {"tests": 34, "assertions": 214, "result": "passed", "overlaps_legacy_suite": true},
+ "phpstan": {"errors": 0, "result": "passed"},
+ "pint": "passed",
+ "diff_check": "passed",
+ "pilot_prospective_read_only": "inventory-conversion-pilot-preflight.json",
+ "counts_are_not_additive": true
+ },
+ "corrected_issues": [
+ "Agreement arithmetic selected QA classes beside the candidate; selection now covers the whole path.",
+ "Legacy writer must tolerate arithmetic-only loading; regression added.",
+ "Recovery checker establishes the actor before tenant-scoped reads; no application access control weakened."
+ ],
+ "pending": ["Separate pilot installation and activation authorization", "Pilot visual review after activation", "Remaining application matrix and owner acceptance"],
+ "active_data_permissions_settings_assets_or_sgf_changes": false
+}
diff --git a/docs/proofs/inventory-conversion-operational-proposal.json b/docs/proofs/inventory-conversion-operational-proposal.json
new file mode 100644
index 0000000..dabb56f
--- /dev/null
+++ b/docs/proofs/inventory-conversion-operational-proposal.json
@@ -0,0 +1,57 @@
+{
+ "date": "2026-11-29",
+ "state": "awaiting_owner_authorization_not_application_completion",
+ "decision_requested": "Autorizar a promoção da conversão física de inventário já preparada em QA para uma candidata operacional distribuível de Compras e a sua integração local, exclusivamente com validação em bases isoladas.",
+ "authority_boundary": {
+ "existing_authority": "Preparação de contrato expressamente autorizada em QA, registada na matriz em 21/11/2026.",
+ "reference": "docs/matriz-sgc-reconciliada.md, Actualização — conversões de inventário, 21/11/2026",
+ "existing_financial_promotion": "docs/proofs/compras-operational-candidate-proposal.json",
+ "gap": "A composição financeira promovida e activada contém quatro pacotes e 24 capacidades; não inclui inventory-write. O carregador de conversão continua a exigir testing e base QA."
+ },
+ "reviewed_inputs": {
+ "current_qa_manifest": "packages/inventory-write/development/manifest.json",
+ "manifest_sha256": "90cf565537e7fd48eb54a87bcfd6d585cf53239f075764910047838b3b8b4c38",
+ "published_legacy_release": "packages/inventory-write/releases/0.1.0",
+ "host_components": [
+ "app/Services/ReceiptStockMovement.php",
+ "app/Services/ReceiptQuantityConversion.php",
+ "app/Services/SupplyCoordination.php",
+ "app/Http/Controllers/GoodsReceiptController.php",
+ "app/Http/Controllers/SupplyPlanningController.php",
+ "config/inventory_conversion.php"
+ ]
+ },
+ "scope": [
+ "Preparar um novo artefacto versionado e verificável do escritor comum de inventário, preservando a versão 0.1.0 e o artefacto QA congelado.",
+ "Integrar a selecção explícita do artefacto compatível numa instalação própria de Compras, desligada por defeito, sem dependência operacional de uma pasta ou base SGF.",
+ "Usar o mesmo escritor para recepções ordinárias e convertidas; não criar outro motor ou duplicar movimentos.",
+ "Propagar a disponibilidade configurada pelos percursos existentes de recepção e abastecimento; preservar factor racional exacto, unidades, artigo, fonte, versão e equivalências documentais.",
+ "Verificar instalação, manifesto, integridade e compatibilidade antes de efeitos; recusar mistura de versões e regressão incompatível após movimentos convertidos.",
+ "Ensaiar instalação, integração, recuperação e conservação exclusivamente em QA isolado, com dados sintéticos; actualizar a matriz existente com os resultados efectivos."
+ ],
+ "acceptance": [
+ "Duas caixas documentais correspondem exactamente a 24 unidades físicas quando o factor explícito é 12:1; os valores financeiros continuam na unidade comercial.",
+ "Entregas parciais, repetição, devolução, quarentena, lotes, estorno e projecção pendente mantêm equivalência exacta e um único efeito de stock.",
+ "Ausência de factor/fonte, quantidade não representável, versão alterada, instalação incompleta, adulteração e acesso de outra empresa são recusados sem efeitos.",
+ "Recepções sem conversão mantêm o hash e a repetição legados; configurações desligadas conservam o comportamento anterior.",
+ "Integração demonstrada com o artefacto distribuível e núcleo financeiro próprio; testes focados, PostgreSQL, concorrência aplicável, análise estática e revisão dos percursos afectados aprovados."
+ ],
+ "prior_evidence": {
+ "reference": "docs/desenvolvimento.md e docs/matriz-sgc-reconciliada.md, conversões de inventário de 21/11/2026",
+ "sqlite": "20 testes / 85 asserções",
+ "postgresql": "10 testes / 67 asserções e duas corridas com contenção real",
+ "qualification": "Evidência anterior de preparação QA; não demonstra a futura candidata operacional nem aceitação integral. Não foram repetidos estes testes nesta conferência documental."
+ },
+ "recovery": [
+ "Novo artefacto em destino próprio; nenhuma substituição dos artefactos congelados.",
+ "Configuração operacional inicialmente desligada; recuperar apenas bases QA descartáveis nos ensaios.",
+ "Depois de efeitos convertidos não efectuar downgrade para o escritor antigo; preservar o leitor compatível e ensaiar recuperação completa."
+ ],
+ "excluded": [
+ "Instalação ou activação no piloto, domínio público ou produção.",
+ "Operações de compra, recepção, devolução ou stock com dados reais.",
+ "Alterações operacionais no SGF, novas permissões ou factores de conversão inventados.",
+ "Alteração implícita do contrato e recibos imutáveis da composição financeira de quatro pacotes.",
+ "Declaração de conclusão integral da aplicação."
+ ]
+}
diff --git a/docs/proofs/inventory-conversion-pilot-authorization.json b/docs/proofs/inventory-conversion-pilot-authorization.json
new file mode 100644
index 0000000..4caf344
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-authorization.json
@@ -0,0 +1,8 @@
+{
+ "date": "2026-11-29",
+ "state": "approved",
+ "proposal": "docs/proofs/inventory-conversion-pilot-proposal.json",
+ "proposal_sha256": "211101d74d5ce22126c6bf28933e22e6226dadabfb0df636368b263e5f0df18f",
+ "owner_response": "autorizo a instalar e activa todos os componentes necessarios para a conclusão da actividade",
+ "scope": "Install and activate the reviewed inventory conversion component and necessary pilot components for this activity; preserve proposal exclusions on business operations, grants, public production and SGF."
+}
diff --git a/docs/proofs/inventory-conversion-pilot-current-check.json b/docs/proofs/inventory-conversion-pilot-current-check.json
new file mode 100644
index 0000000..079fdb0
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-current-check.json
@@ -0,0 +1,15 @@
+{
+ "date": "2026-11-29T16:48:25+00:00",
+ "state": "passed",
+ "mode": "installed_read_only_postcheck",
+ "database_enforced_read_only": true,
+ "candidate_available_with_installed_financial_runtime": true,
+ "inventory_manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "active_settings_sha256": "b787bd02938381419cbe2803163de2c04331076eff3483af62fd2c0b71ffc820",
+ "public_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
+ "existing_converted_receipt_lines": 0,
+ "active_settings_changed": false,
+ "database_tables_preserved_during_readonly_check": 150,
+ "inventory_component_installed_or_activated": true,
+ "migrations_or_business_commands": false
+}
diff --git a/docs/proofs/inventory-conversion-pilot-installation.json b/docs/proofs/inventory-conversion-pilot-installation.json
new file mode 100644
index 0000000..f0f04fb
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-installation.json
@@ -0,0 +1,19 @@
+{
+ "date": "2026-11-29T16:11:49+00:00",
+ "state": "passed",
+ "authorization": "inventory-conversion-pilot-authorization.json",
+ "target": "http:\/\/127.0.0.1:8005",
+ "backup_directory": "C:\/laragon\/data\/compras\/backups\/inventory-activation-20261129-161148-e12d75b8e063",
+ "inventory_directory": "C:\/laragon\/data\/compras\/runtime\/inventory-8608e6551dea6448",
+ "inventory_manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "settings_before_sha256": "5a2f3eba25b5c040c5cc8827dcd7368be71faf8bd55e80caad4bf233c428b433",
+ "settings_after_sha256": "290b340184e590e5c47e98f6fd929a4fb1d640a5df3459926eb2885b6e9ad048",
+ "changed_keys": [
+ "COMPRAS_INVENTORY_CONVERSION_ENABLED",
+ "COMPRAS_INVENTORY_ROOT"
+ ],
+ "all_database_tables_preserved": 150,
+ "unrelated_settings_env_frontend_and_financial_receipt_preserved": true,
+ "new_permissions_users_migrations_or_business_commands": false,
+ "application_complete": false
+}
diff --git a/docs/proofs/inventory-conversion-pilot-native-review.json b/docs/proofs/inventory-conversion-pilot-native-review.json
new file mode 100644
index 0000000..31a4253
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-native-review.json
@@ -0,0 +1,42 @@
+{
+ "date": "2026-11-29",
+ "state": "installed_component_and_visual_delta_verified",
+ "application_complete": false,
+ "installation": "inventory-conversion-pilot-installation.json",
+ "postcheck": "inventory-conversion-pilot-postcheck.json",
+ "pilot": {
+ "normal_existing_session": true,
+ "receipt_index_and_existing_order_opened": true,
+ "existing_order_already_fully_received": true,
+ "existing_delivery_list_empty_state_and_menu_search_verified": true,
+ "new_business_submissions": false,
+ "all_150_database_tables_preserved_after_native_review": true,
+ "existing_user_tabs_restored": true,
+ "profile_get_checks": 52,
+ "new_permissions_or_users": false
+ },
+ "synthetic_preview": {
+ "command": "node scripts/requisition-ledger-qa-check.mjs --standalone-conversion-preview",
+ "environment": "standalone-qa",
+ "qa_conversion_enabled": false,
+ "pinned_archive_extracted": true,
+ "normal_application_login": true,
+ "login_shortcuts_or_disabled_middleware": false,
+ "synthetic_warehouse_identity": true,
+ "password_not_saved_in_browser": true,
+ "desktop": "Receipt inclusion and stock item selection exposed conversion from cx to un, numerator, denominator, source, source version and exact quantity explanation.",
+ "mobile": "390 x 526 at 100%; conversion fields and explanation fit in one column; quantity table scroll remains contained.",
+ "form_not_submitted": true,
+ "dirty_exit_warning_observed": true,
+ "devtools_and_owned_preview_tab_closed": true,
+ "owned_database_role_server_and_files_removed": true
+ },
+ "installer_regression": {
+ "cause": "Archive entry insertion order differed from the installer's assumed order; initial attempt stopped before settings selection.",
+ "fix": "Require exactly the four reviewed entry names independently of insertion order; reject missing and unexpected entries.",
+ "tests": 2,
+ "assertions": 11,
+ "result": "passed"
+ },
+ "remaining": "Whole application acceptance and unrelated matrix gaps remain open. No live converted receipt was submitted to demonstrate installation."
+}
diff --git a/docs/proofs/inventory-conversion-pilot-postcheck.json b/docs/proofs/inventory-conversion-pilot-postcheck.json
new file mode 100644
index 0000000..b624805
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-postcheck.json
@@ -0,0 +1,15 @@
+{
+ "date": "2026-11-29T16:32:57+00:00",
+ "state": "passed",
+ "mode": "installed_read_only_postcheck",
+ "database_enforced_read_only": true,
+ "candidate_available_with_installed_financial_runtime": true,
+ "inventory_manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "active_settings_sha256": "b787bd02938381419cbe2803163de2c04331076eff3483af62fd2c0b71ffc820",
+ "public_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
+ "existing_converted_receipt_lines": 0,
+ "active_settings_changed": false,
+ "database_tables_preserved_since_activation": 150,
+ "inventory_component_installed_or_activated": true,
+ "migrations_or_business_commands": false
+}
diff --git a/docs/proofs/inventory-conversion-pilot-preflight.json b/docs/proofs/inventory-conversion-pilot-preflight.json
new file mode 100644
index 0000000..511f543
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-preflight.json
@@ -0,0 +1,14 @@
+{
+ "date": "2026-11-29T16:11:48+00:00",
+ "state": "passed",
+ "mode": "prospective_read_only_preflight",
+ "database_enforced_read_only": true,
+ "candidate_available_with_installed_financial_runtime": true,
+ "inventory_manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "active_settings_sha256": "5a2f3eba25b5c040c5cc8827dcd7368be71faf8bd55e80caad4bf233c428b433",
+ "public_manifest_sha256": "8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b",
+ "existing_converted_receipt_lines": 0,
+ "active_settings_changed": false,
+ "inventory_component_installed_or_activated": false,
+ "migrations_or_business_commands": false
+}
diff --git a/docs/proofs/inventory-conversion-pilot-proposal.json b/docs/proofs/inventory-conversion-pilot-proposal.json
new file mode 100644
index 0000000..927f3e6
--- /dev/null
+++ b/docs/proofs/inventory-conversion-pilot-proposal.json
@@ -0,0 +1,41 @@
+{
+ "date": "2026-11-29",
+ "state": "prepared_not_authorized_or_executed",
+ "decision": "Autorizar instalar e activar o componente de conversão física de inventário no piloto local http://127.0.0.1:8005, com salvaguarda da configuração e alteração exclusiva de duas chaves. Não executar operações de negócio.",
+ "why_required": "A autorização inventory-conversion-operational-authorization.json exclui expressamente instalação e activação no piloto ou produção; AGENTS.md secção 6 mantém esta separação.",
+ "candidate_proof": "inventory-conversion-operational-candidate.json",
+ "read_only_preflight": "inventory-conversion-pilot-preflight.json",
+ "target": {
+ "settings": "C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json",
+ "settings_before_sha256": "5a2f3eba25b5c040c5cc8827dcd7368be71faf8bd55e80caad4bf233c428b433",
+ "financial_installation_id": "0602a856-0413-480f-9ef3-1a1f3238bb90",
+ "financial_manifest_sha256": "80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7",
+ "inventory_directory": "C:/laragon/data/compras/runtime/inventory-8608e6551dea6448",
+ "inventory_manifest_sha256": "8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd",
+ "inventory_archive_sha256": "dbb7e3d172f2ce5168f678993b96d9d94ce2e0c1737b581743cf2bbb6d4d00b8"
+ },
+ "proposed_settings_only": {
+ "COMPRAS_INVENTORY_CONVERSION_ENABLED": "true",
+ "COMPRAS_INVENTORY_ROOT": "C:/laragon/data/compras/runtime/inventory-8608e6551dea6448"
+ },
+ "procedure": [
+ "Reverificar identidade do piloto, recibo financeiro, hashes, schema e configuração; recusar deriva ou outro destino.",
+ "Salvaguardar a configuração privada anterior; extrair quatro entradas para o novo destino privado e verificar integralmente antes de seleccionar o componente. Preservar os artefactos anteriores.",
+ "Alterar apenas as duas chaves propostas, conservando a origem financeira, os 24 opt-ins, classificação sintética de novas operações de ensaio e todas as outras chaves.",
+ "Conferir arranque e conservação das tabelas com PostgreSQL só leitura. Não são necessárias migrações ou comandos de stock para instalar o componente.",
+ "Rever os ecrãs existentes de recepção e abastecimento com os acessos existentes, sem submeter operações. Registar evidência e continuar as pendências autorizadas."
+ ],
+ "observable_effect": "Disponibilizar factor explícito, fonte e versão quando as unidades comercial e de stock diferem. A activação não cria factores, documentos, permissões ou movimentos.",
+ "recovery": [
+ "Antes de efeitos convertidos, repor apenas as duas chaves anteriores após conferir ausência de edição concorrente; conservar artefactos e histórico.",
+ "Após recepções ou entregas com conversão congelada, manter o componente compatível e diagnosticar; não seleccionar o escritor antigo. A aplicação recusa esse fallback.",
+ "Não substituir a base activa ou apagar registos para permitir regressão. Restauro completo com movimentos convertidos já ensaiado em PostgreSQL isolado."
+ ],
+ "excluded": [
+ "Instalação ou activação no domínio público, produção ou SGF",
+ "Migrações, dados/permissões, novos utilizadores, concessões ou parâmetros empresariais",
+ "Operações reais ou sintéticas de recepção, devolução, estorno ou compra no piloto",
+ "Publicação de assets, alteração de .env ou dos recibos financeiros imutáveis",
+ "Declaração de conclusão integral da aplicação"
+ ]
+}
diff --git a/docs/proofs/order-cancellation-pilot-authorization.json b/docs/proofs/order-cancellation-pilot-authorization.json
new file mode 100644
index 0000000..66de75e
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-authorization.json
@@ -0,0 +1,9 @@
+{
+ "date": "2026-11-29",
+ "state": "approved",
+ "proposal": "docs/proofs/order-cancellation-pilot-proposal.json",
+ "proposal_sha256": "8ed08b456aab5fd1d5606f7e40d820e1394b0cebcf2a0ab0a9ad66b7fc85c888",
+ "owner_response": "autorizo a instalar e activa todos os componentes necessarios para a conclusão da actividade",
+ "authority_source": "inventory-conversion-pilot-authorization.json",
+ "scope": "Necessary existing C2 component, cycle integration and local pilot installation/activation; no business policies, grants or cancellations."
+}
diff --git a/docs/proofs/order-cancellation-pilot-installation.json b/docs/proofs/order-cancellation-pilot-installation.json
new file mode 100644
index 0000000..5184a34
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-installation.json
@@ -0,0 +1,19 @@
+{
+ "date": "2026-11-29T16:32:41+00:00",
+ "state": "passed",
+ "target": "http:\/\/127.0.0.1:8005",
+ "authorization": "order-cancellation-pilot-authorization.json",
+ "backup_directory": "C:\/laragon\/data\/compras\/backups\/cancellation-activation-20261129-163240-a0e9d6c53d2e",
+ "component_directory": "C:\/laragon\/data\/compras\/runtime\/order-cancellation-52df7927aa268959",
+ "manifest_sha256": "52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f",
+ "changed_keys": [
+ "COMPRAS_ORDER_CANCELLATION_ENABLED",
+ "COMPRAS_ORDER_CANCELLATION_ROOT"
+ ],
+ "settings_before_sha256": "290b340184e590e5c47e98f6fd929a4fb1d640a5df3459926eb2885b6e9ad048",
+ "settings_after_sha256": "b787bd02938381419cbe2803163de2c04331076eff3483af62fd2c0b71ffc820",
+ "all_database_tables_preserved": 150,
+ "unrelated_settings_financial_receipt_env_and_frontend_preserved": true,
+ "policies_grants_migrations_or_business_commands": false,
+ "application_complete": false
+}
diff --git a/docs/proofs/order-cancellation-pilot-native-review.json b/docs/proofs/order-cancellation-pilot-native-review.json
new file mode 100644
index 0000000..fcae5d4
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-native-review.json
@@ -0,0 +1,39 @@
+{
+ "date": "2026-11-29",
+ "state": "passed",
+ "installation": "order-cancellation-pilot-installation.json",
+ "pilot_native_read": {
+ "url": "http://127.0.0.1:8005/ordens/cancelamentos",
+ "page_loaded": true,
+ "no_visible_requests": true,
+ "policy_form_not_submitted": true
+ },
+ "isolated_native_review": {
+ "normal_login": true,
+ "synthetic_data_only": true,
+ "approved_record": "OC-TEST-58RhJVhBrR",
+ "source_cycle": 2,
+ "decision_prepared_by_native_services_before_ui_review": true,
+ "new_manual_approval_claimed": false,
+ "source_link_opened_preserved_cancelled_order": true,
+ "mobile": {"width": 390, "height": 526, "zoom_percent": 100, "details_legible_without_lateral_clipping": true},
+ "print_preview": {"pages": 1, "decision_and_source_link_visible": true, "printing_cancelled": true},
+ "owned_tab_and_devtools_closed": true,
+ "existing_user_tabs_preserved": true,
+ "browser_password_not_saved": true
+ },
+ "postgresql_regression": {"tests": 14, "assertions": 258, "passed": true},
+ "legacy_regression": {"tests": 12, "assertions": 91, "passed": true},
+ "recovery": {
+ "backup_restored": true,
+ "incompatible_binding_rejected": true,
+ "explicit_rebind": true,
+ "preserved_business_tables": 154,
+ "recovered_cancellations": 1,
+ "source_cycle": 2,
+ "exact_replays": 1,
+ "original_and_restored_database_and_role_removed": true,
+ "runner_exit_code": 0
+ },
+ "application_complete": false
+}
diff --git a/docs/proofs/order-cancellation-pilot-postcheck.json b/docs/proofs/order-cancellation-pilot-postcheck.json
new file mode 100644
index 0000000..3279a94
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-postcheck.json
@@ -0,0 +1,10 @@
+{
+ "date": "2026-11-29T16:40:25+00:00",
+ "state": "passed",
+ "installed": true,
+ "database_enforced_read_only": true,
+ "manifest_sha256": "52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f",
+ "existing_cancellation_records": 0,
+ "existing_approved_policies": 0,
+ "new_policies_grants_business_commands_or_settings_changes": false
+}
diff --git a/docs/proofs/order-cancellation-pilot-preflight.json b/docs/proofs/order-cancellation-pilot-preflight.json
new file mode 100644
index 0000000..4fb7a02
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-preflight.json
@@ -0,0 +1,10 @@
+{
+ "date": "2026-11-29T16:32:40+00:00",
+ "state": "passed",
+ "installed": false,
+ "database_enforced_read_only": true,
+ "manifest_sha256": "52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f",
+ "existing_cancellation_records": 0,
+ "existing_approved_policies": 0,
+ "new_policies_grants_business_commands_or_settings_changes": false
+}
diff --git a/docs/proofs/order-cancellation-pilot-proposal.json b/docs/proofs/order-cancellation-pilot-proposal.json
new file mode 100644
index 0000000..b78e3b9
--- /dev/null
+++ b/docs/proofs/order-cancellation-pilot-proposal.json
@@ -0,0 +1,29 @@
+{
+ "date": "2026-11-29",
+ "state": "authorized_as_necessary_component_of_current_activity",
+ "authority": "Owner: autorizo a instalar e activa todos os componentes necessarios para a conclusão da actividade; original implementation scope in issued-order-cancellation-authorization.json retained.",
+ "scope": "Install and enable the existing C2 module in the local pilot with its cycle-aware reversal component; no policies, grants or business cancellations.",
+ "settings_before_sha256": "290b340184e590e5c47e98f6fd929a4fb1d640a5df3459926eb2885b6e9ad048",
+ "manifest_sha256": "52df7927aa2689598ce1be92de1483694347a696245704abb9e3925db7abfc0f",
+ "candidate_root": "packages/order-cancellation/releases/0.2.0-rc.1",
+ "target_root": "C:/laragon/data/compras/runtime/order-cancellation-52df7927aa268959",
+ "proposed_settings_only": {
+ "COMPRAS_ORDER_CANCELLATION_ENABLED": "true",
+ "COMPRAS_ORDER_CANCELLATION_ROOT": "C:/laragon/data/compras/runtime/order-cancellation-52df7927aa268959"
+ },
+ "observed_bug": "Isolated integration originally appended a cycle-1 reversal for a cycle-2 order. Regression reproduced 1 instead of 2; original closed reservation history must remain immutable.",
+ "implementation": "Versioned correction of the existing additive reversal writer: explicit current-cycle map and open head checked, entries selected and reversal appended within that cycle. Original source and financial four-package receipt preserved.",
+ "pre_install_verification": {
+ "standalone_financial_business": {"tests": 14, "assertions": 258, "result": "passed"},
+ "legacy_cancellation": {"tests": 12, "assertions": 91, "result": "passed"},
+ "phpstan": "passed"
+ },
+ "procedure": [
+ "Verify pilot identity, installed financial receipt, complete cancellation/cycle schema, source settings hash and component bytes in read-only mode.",
+ "Save previous settings privately and copy only the new manifest and reversal file into the new private runtime directory.",
+ "Select only the two proposed settings; compare all pilot tables, unrelated settings, environment and frontend manifest before and after.",
+ "Verify actual installed composition and existing profiles without writing database rows; continue synthetic visual/recovery tests separately."
+ ],
+ "recovery": "Preserve prior settings and component files. Before new decisions, restore only the two keys after excluding concurrent edits. After cycle-aware decisions, preserve the compatible writer; never overwrite the database or remove history to downgrade.",
+ "excluded": ["Publishing business policies", "New users or grants", "Cancelling pilot orders or creating business records", "Migrations", "Public production or SGF changes", "Frontend publication", "Claiming full application completion"]
+}
diff --git a/docs/proofs/pilot-operations-current.json b/docs/proofs/pilot-operations-current.json
new file mode 100644
index 0000000..1e8351d
--- /dev/null
+++ b/docs/proofs/pilot-operations-current.json
@@ -0,0 +1,72 @@
+{
+ "date": "2026-11-29T16:52:47+00:00",
+ "database_enforced_read_only": true,
+ "business_commands": false,
+ "replenishment_task_verification": {
+ "native_definition_verified": true,
+ "installation_conservation_requested": true,
+ "baseline_tables": 150,
+ "unchanged_tables": 149,
+ "changed_native_replenishment_tables": [
+ "replenishment_work"
+ ],
+ "new_policies_or_grants": false
+ },
+ "result": {
+ "schema_version": 1,
+ "started_at": "2026-11-29T16:52:46+00:00",
+ "checked_at": "2026-11-29T16:52:46+00:00",
+ "ok": true,
+ "complete": true,
+ "checks": {
+ "replenishment": {
+ "status": "passed",
+ "result": {
+ "checked_at": "2026-11-29T16:52:46+00:00",
+ "ok": true,
+ "reasons": [],
+ "recovery_ready": true,
+ "scheduler_recent": true,
+ "last_result": "passed",
+ "last_finished_at": "2026-11-29T16:51:47+00:00",
+ "work": {
+ "total": 1,
+ "pending": 0,
+ "failed": 0
+ }
+ }
+ },
+ "import_cost_documents": {
+ "status": "passed",
+ "result": {
+ "checked_at": "2026-11-29T16:52:46+00:00",
+ "ok": true,
+ "complete": true,
+ "documents_checked": 0,
+ "files_checked": 0,
+ "missing": 0,
+ "altered": 0,
+ "invalid_reference": 0,
+ "unreferenced": 0,
+ "reasons": []
+ }
+ },
+ "receipt_documents": {
+ "status": "passed",
+ "result": {
+ "checked_at": "2026-11-29T16:52:46+00:00",
+ "ok": true,
+ "complete": true,
+ "reasons": [],
+ "documents_checked": 0,
+ "files_checked": 0,
+ "missing": 0,
+ "invalid_reference": 0,
+ "altered": 0,
+ "unreferenced_recent": 0,
+ "unreferenced_older": 0
+ }
+ }
+ }
+ }
+}
diff --git a/docs/proofs/procurement-analytics-qa.json b/docs/proofs/procurement-analytics-qa.json
index f9403fd..61a402e 100644
--- a/docs/proofs/procurement-analytics-qa.json
+++ b/docs/proofs/procurement-analytics-qa.json
@@ -158,5 +158,45 @@
"Native visual/mobile/print review of new analytical tables and attribution form",
"Operational activation within its concrete authorised scope",
"Other application requirements in the existing matrix"
- ]
+ ],
+ "native_standalone_review_20261129": {
+ "state": "verified_and_published_in_local_pilot_public_installation_pending_connection",
+ "normal_authentication": true,
+ "payment_and_allocation_prepared_with_native_services": true,
+ "synthetic_only": true,
+ "amount_minor": 4000,
+ "rejected_sum_minor": 3900,
+ "error_message_and_input_conservation": true,
+ "native_explicit_attribution": [
+ {
+ "category": "Material",
+ "amount_minor": 1500
+ },
+ {
+ "category": "Serviços",
+ "amount_minor": 2500
+ }
+ ],
+ "version": 1,
+ "history_visible": true,
+ "report_total_minor": 4000,
+ "report_categories_match": true,
+ "protected_tables_preserved": 153,
+ "one_attribution_one_audit": true,
+ "mobile_390x526_100_percent": true,
+ "finance_context_and_form_legible": true,
+ "report_tables_no_lateral_clipping_observed": true,
+ "print_preview_pages": 6,
+ "category_heading_and_table_same_page_after_correction": 3,
+ "preview_cancelled": true,
+ "owned_tab_devtools_closed": true,
+ "original_three_tabs_preserved": true,
+ "database_role_removed": true,
+ "ui_tests": 37,
+ "ui_files": 7,
+ "types_lint_format_build": true,
+ "candidate_manifest": "c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022",
+ "publication": "analytics-print-publication.json",
+ "public_publication_authorized_but_no_administrative_connection": true
+ }
}
diff --git a/docs/proofs/product-review-20261122.json b/docs/proofs/product-review-20261122.json
index e5df017..693b960 100644
--- a/docs/proofs/product-review-20261122.json
+++ b/docs/proofs/product-review-20261122.json
@@ -699,7 +699,7 @@
"adapted_drawer_closes_after_navigation": true,
"agreements_to_contracts_link_followed": true,
"header_links_separated_and_wrapped": true,
- "new_label": "Novo contrato com v\u00e1rios artigos",
+ "new_label": "Novo contrato com vários artigos",
"document_title": "Contrato QA-VISUAL-CONTRACT",
"readable_without_horizontal_page_overflow": true
},
@@ -916,5 +916,49 @@
"synthetic_only": true
},
"remaining": "Native mobile/print delta not verified; source-link input stopped after two geometry-unavailable attempts. No failed confirmation repeated."
+ },
+ "native_cancellation_mobile_print_delta_20261129": {
+ "state": "verified",
+ "proof": "order-cancellation-pilot-native-review.json",
+ "source_link_and_cancelled_order": true,
+ "mobile_390x526_100_percent": true,
+ "single_page_print_preview": true,
+ "printing_cancelled": true,
+ "owned_tab_closed_existing_three_preserved": true,
+ "earlier_manual_decision_not_repeated": true
+ },
+ "native_pilot_order_receipt_print_20261129": {
+ "state": "verified",
+ "environment": "http://127.0.0.1:8005",
+ "order": "OC-TEST-wKzfEhxT9Y",
+ "receipt": "REC-2026-000001",
+ "read_only_existing_documents": true,
+ "order_original_incomplete_notice_preserved": true,
+ "order_totals_mzn": {
+ "subtotal": "10000.00",
+ "vat": "1600.00",
+ "total": "11600.00"
+ },
+ "receipt_original_quantities": {
+ "received": "1.000",
+ "accepted": "1.000",
+ "rejected": "0.000"
+ },
+ "order_print_preview_pages": 1,
+ "receipt_print_preview_pages": 1,
+ "both_print_previews_cancelled": true,
+ "mobile": {
+ "width": 390,
+ "height": 526,
+ "zoom_percent": 100,
+ "order_totals_and_receipt_references_legible": true,
+ "no_lateral_clipping_observed": true,
+ "receipt_headers_wrap_inside_columns": true
+ },
+ "owned_devtools_and_tab_closed": true,
+ "original_three_tabs_preserved": true,
+ "no_business_submission_or_data_edits": true,
+ "input_focus_correction": "An address paste reached focused DevTools and its paste protection refused it. No console code or paste-protection override was executed; navigation resumed through the observed address field.",
+ "application_complete": false
}
}
diff --git a/docs/proofs/replenishment-task-authorization.json b/docs/proofs/replenishment-task-authorization.json
new file mode 100644
index 0000000..4a268c5
--- /dev/null
+++ b/docs/proofs/replenishment-task-authorization.json
@@ -0,0 +1,8 @@
+{
+ "date": "2026-11-29",
+ "state": "approved",
+ "scope": "existing_pilot_replenishment_task",
+ "owner_response": "autorizo a instalar e activa todos os componentes necessarios para a conclus\u00e3o da actividade",
+ "proposal_sha256": "7190730c925bcec4af31355f33ca357e9921f98f5d71ba404fd007c6aa8c39c0",
+ "basis": "Existing owner authorization to install and activate necessary pilot components, applied to native replenishment already approved in the pilot. Existing corporate rules and business decision exclusions remain unchanged."
+}
diff --git a/docs/proofs/replenishment-task-definition-fix.json b/docs/proofs/replenishment-task-definition-fix.json
new file mode 100644
index 0000000..7513da0
--- /dev/null
+++ b/docs/proofs/replenishment-task-definition-fix.json
@@ -0,0 +1,15 @@
+{
+ "date": "2026-11-29",
+ "cause": "Native Task Scheduler omits explicit LeastPrivilege in exported XML while the native principal remains Limited/0. Original strict comparison refused before requesting the initial pass. The automatic pass refused a changed installer pin before application boot.",
+ "original_proposal_sha256": "11a05bc035ef3b2b5a1a7b31330b03fcb614595d1b11df5f0dad1eb71a102817",
+ "corrected_proposal_sha256": "7190730c925bcec4af31355f33ca357e9921f98f5d71ba404fd007c6aa8c39c0",
+ "scope_changed": false,
+ "native_task_reregistered": false,
+ "regression": {
+ "tests": 1,
+ "assertions": 5,
+ "passed": true
+ },
+ "phpstan_errors": 0,
+ "additional_native_equivalence": "Current user SID exported as its account alias; native default AllowHardTerminate=true omitted. Exact current identity resolved with whoami; different identities, elevation, interval and explicit false termination remain refused."
+}
diff --git a/docs/proofs/replenishment-task-installation.json b/docs/proofs/replenishment-task-installation.json
new file mode 100644
index 0000000..f06c474
--- /dev/null
+++ b/docs/proofs/replenishment-task-installation.json
@@ -0,0 +1,39 @@
+{
+ "date": "2026-11-29T16:44:06+00:00",
+ "state": "passed",
+ "task_name": "Compras-Pilot-Replenishment",
+ "current_user_only": true,
+ "credentials_stored": false,
+ "run_level": "Limited",
+ "poll_interval": "PT1M",
+ "overlap": "IgnoreNew",
+ "time_limit": "PT1M",
+ "private_definition": "C:\\laragon\\data\\compras\\tasks\\replenishment-20261129-164444-37535bb23650\\task.private.xml",
+ "xml_sha256": "d6b5c94a81451de449ad1ba7abf34ccb05b63038215bf8f3a6db71b007ef1432",
+ "pilot_ready": true,
+ "eligible_requests": 0,
+ "native_command": "sgc:replenishment-tick",
+ "task_installed_or_started": true,
+ "powershell_execution_policy_changed": false,
+ "private_backup_directory": "C:\\laragon\\data\\compras\\tasks\\replenishment-20261129-164444-37535bb23650",
+ "database_backup_sha256": "5377a99f7105a94b190076dae2d36bd9729bb1bd5ce35b6bc6f1bb8bd957af12",
+ "baseline_tables": 150,
+ "native_definition_verified": true,
+ "initial_and_automatic_passages_exit_code": 0,
+ "first_guarded_attempt_refused_before_application_boot": true,
+ "regression_tests": 19,
+ "regression_assertions": 132,
+ "definition_regression_tests": 1,
+ "definition_regression_assertions": 5,
+ "phpstan_errors": 0,
+ "unchanged_database_tables": 149,
+ "changed_tables": [
+ "replenishment_work"
+ ],
+ "new_requisitions_policies_grants_stock_or_decisions": false,
+ "private_recovery_proof": "replenishment-task-recovery.json",
+ "operational_check": "pilot-operations-current.json",
+ "restart_or_logoff_not_tested": true,
+ "production_service_installed": false,
+ "application_complete": false
+}
diff --git a/docs/proofs/replenishment-task-preflight.json b/docs/proofs/replenishment-task-preflight.json
new file mode 100644
index 0000000..d008561
--- /dev/null
+++ b/docs/proofs/replenishment-task-preflight.json
@@ -0,0 +1,18 @@
+{
+ "date": "2026-11-29T16:44:06+00:00",
+ "state": "preview",
+ "task_name": "Compras-Pilot-Replenishment",
+ "current_user_only": true,
+ "credentials_stored": false,
+ "run_level": "Limited",
+ "poll_interval": "PT1M",
+ "overlap": "IgnoreNew",
+ "time_limit": "PT1M",
+ "private_definition": "C:\/laragon\/data\/compras\/tasks\/replenishment-20261129-164406-2100fa2b566a\/task.private.xml",
+ "xml_sha256": "72702027134421f59c6c59d6a7286ef9abacb8012d34ef910d6faba66ea60f79",
+ "pilot_ready": true,
+ "eligible_requests": 0,
+ "native_command": "sgc:replenishment-tick",
+ "task_installed_or_started": false,
+ "powershell_execution_policy_changed": false
+}
diff --git a/docs/proofs/replenishment-task-proposal.json b/docs/proofs/replenishment-task-proposal.json
new file mode 100644
index 0000000..2f8f429
--- /dev/null
+++ b/docs/proofs/replenishment-task-proposal.json
@@ -0,0 +1,36 @@
+{
+ "date": "2026-11-29",
+ "scope": "existing_pilot_replenishment_task",
+ "task_name": "Compras-Pilot-Replenishment",
+ "installation_id": "0602a856-0413-480f-9ef3-1a1f3238bb90",
+ "source_sha256": {
+ "scripts/replenishment-pilot-task.php": "38b697fbb7c49c13ec67f536aca597862743acd0457ebc2afcf1bc88c3368d9e",
+ "app/Console/Commands/ReplenishmentTick.php": "aa28d463377c75ca80dc6d5696d08059252555f91bbc68f2372f2008becd3b9f",
+ "app/Services/ReplenishmentQueue.php": "abc91afef22a35589dc18984eb8ef2d1d82a55267c4d6ea50172b65c8efbabc8",
+ "app/Services/ReplenishmentHeartbeat.php": "2426211df0e3fe8a0043f7b4e0d9f61663bd4177d6b63524242ec33472e09636",
+ "app/Services/ReplenishmentProcessLock.php": "a48a3de6f7015502204f23072244ab71cdd9bc2994ab605f0bff62f303734c73",
+ "app/Services/AutomaticPurchases.php": "dbb973d7620f8a99bdc4752d975d58c5a684ffe5404b974884c812bff5d47149",
+ "scripts/install-replenishment-task.php": "8587d8e292f51afc3610277e153b406106b71e7463962fde8d9baf23be8921a4",
+ "app/Services/ReplenishmentTaskDefinition.php": "48ad8ccb921a2ddcc7c8119dccf4a407735980b4f9a127ce0ec9e868e48c752c"
+ },
+ "php_executable": "C:/Users/macbook/.config/investmoz/php-8.5.11/php-win.exe",
+ "php_sha256": "ddaed8c0f5fce59a4a92405fe41ab3a9dd3217e65629a1fbb334c43ab72021dc",
+ "target": "http://127.0.0.1:8005",
+ "triggers": [
+ "minute technical poll",
+ "current user logon"
+ ],
+ "principal": "current Windows user, InteractiveToken, LeastPrivilege",
+ "overlap": "IgnoreNew",
+ "time_limit": "PT1M",
+ "command": "sgc:replenishment-tick",
+ "business_scope": "Only existing published replenishment policies and native durable recovery. Do not renew expired rules, change parameters, submit or approve purchases, select suppliers, issue orders or move stock.",
+ "recovery": "Private database backup and task XML before initial passage; disable the newly installed task to stop future passages. Never restore old business rows automatically.",
+ "exclusions": [
+ "production service without interactive session",
+ "reboot or logoff",
+ "new users, grants or credentials",
+ "SGF",
+ "policy renewal"
+ ]
+}
diff --git a/docs/proofs/replenishment-task-recovery.json b/docs/proofs/replenishment-task-recovery.json
new file mode 100644
index 0000000..713d86d
--- /dev/null
+++ b/docs/proofs/replenishment-task-recovery.json
@@ -0,0 +1,8 @@
+{
+ "date": "2026-11-29T16:48:58+00:00",
+ "state": "passed",
+ "restored_tables_identical": 150,
+ "source_database_or_settings_changed": false,
+ "business_commands": false,
+ "temporary_database_and_role_removed": true
+}
diff --git a/packages/inventory-write/releases/0.2.0-rc.1/bootstrap.php b/packages/inventory-write/releases/0.2.0-rc.1/bootstrap.php
new file mode 100644
index 0000000..43aa300
--- /dev/null
+++ b/packages/inventory-write/releases/0.2.0-rc.1/bootstrap.php
@@ -0,0 +1,3 @@
+isZero() || $bottom->isZero() || $quantity->isGreaterThan(PHP_INT_MAX)) {
+ throw new InvalidArgumentException('Factor positivo e quantidade inteira suportada obrigatórios.');
+ }
+ [$converted, $remainder] = $quantity->multipliedBy($top)->quotientAndRemainder($bottom);
+ if (!$remainder->isZero() || $converted->isGreaterThan(PHP_INT_MAX)) {
+ throw new InvalidArgumentException('Quantidade física não representável em milésimos sem arredondamento.');
+ }
+ return (string)$converted;
+ }
+
+ public static function fromBase(string $quantityMilli, string $numerator, string $denominator): string
+ {
+ return self::toBase($quantityMilli, $denominator, $numerator);
+ }
+}
diff --git a/packages/inventory-write/releases/0.2.0-rc.1/src/ReceiptMovementWriter.php b/packages/inventory-write/releases/0.2.0-rc.1/src/ReceiptMovementWriter.php
new file mode 100644
index 0000000..b8e3261
--- /dev/null
+++ b/packages/inventory-write/releases/0.2.0-rc.1/src/ReceiptMovementWriter.php
@@ -0,0 +1,94 @@
+checkHost();$facts=$this->facts($lineId,false);
+ return ['source_hash'=>$this->hash($facts),'receipt_item_id'=>$lineId,'accepted_milli'=>(string)$facts['accepted_milli'],
+ 'stock_item_id'=>(int)$facts['stock_item_id'],'warehouse_id'=>(int)$facts['warehouse_id']];
+ }
+
+ public function write(int $lineId, string $expectedHash): array
+ {
+ $this->checkHost();$facts=$this->facts($lineId,true);$hash=$this->hash($facts);
+ abort_unless(hash_equals($hash,$expectedHash),409,'A origem da recepção mudou. Faça nova conferência.');
+ $existing=$this->db->table($this->schema.'.stock_movements')->where(['tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId])->first();
+ $stockQuantity=$this->stockQuantity($facts);
+ if($existing){
+ $snapshot=json_decode($existing->snapshot,true,512,JSON_THROW_ON_ERROR);
+ abort_unless(($snapshot['inventory_source_hash']??null)===$hash && (string)$existing->quantity_milli===$stockQuantity
+ && (int)$existing->stock_item_id===(int)$facts['stock_item_id'] && (int)$existing->warehouse_id===(int)$facts['warehouse_id'],409,'A origem já tem movimento incompatível ou histórico não reconciliado.');
+ return ['movement_id'=>(int)$existing->id,'source_hash'=>$hash,'replayed'=>true];
+ }
+ $lineSnapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
+ $receiptSnapshot=json_decode($facts['receipt_snapshot'],true,512,JSON_THROW_ON_ERROR);
+ $snapshot=[...$lineSnapshot,'receipt_id'=>(int)$facts['receipt_id'],'order_number'=>$receiptSnapshot['order']['number']??null,
+ 'delivery_note'=>$facts['delivery_note'],'reference'=>$facts['delivery_note'],'inventory_source_hash'=>$hash];
+ $id=$this->db->table($this->schema.'.stock_movements')->insertGetId([
+ 'tenant_id'=>$this->tenant,'goods_receipt_item_id'=>$lineId,'stock_item_id'=>$facts['stock_item_id'],'warehouse_id'=>$facts['warehouse_id'],
+ 'moved_by'=>$this->actor,'quantity_milli'=>$stockQuantity,'movement_type'=>'receipt_in','moved_at'=>now(),
+ 'equipment_id'=>$lineSnapshot['equipment_id']??null,'spare_part_id'=>$lineSnapshot['spare_part_id']??null,
+ 'snapshot'=>json_encode($snapshot,JSON_THROW_ON_ERROR),
+ ]);
+ return ['movement_id'=>(int)$id,'source_hash'=>$hash,'replayed'=>false];
+ }
+
+ /** Legacy facts/hash are unchanged. Converted facts carry their entire frozen basis in line_snapshot. */
+ private function stockQuantity(array $facts): string
+ {
+ $snapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
+ if(!array_key_exists('quantity_conversion',$snapshot))return (string)$facts['accepted_milli'];
+ $basis=$snapshot['quantity_conversion'];
+ abort_unless(is_array($basis) && ($basis['schema']??null)==='inventory.quantity.v1'
+ && ($basis['stock_item_id']??null)===(int)$facts['stock_item_id']
+ && ($basis['document_unit']??null)===($snapshot['order_item']['unit']??null)
+ && ($basis['stock_unit']??null)===($snapshot['stock_item']['unit']??null)
+ && is_string($basis['numerator']??null) && is_string($basis['denominator']??null)
+ && is_string($basis['source']??null) && trim($basis['source'])!==''
+ && is_string($basis['version']??null) && trim($basis['version'])!=='',409,'Base de conversão incompleta ou incompatível.');
+ $converted=QuantityConversion::toBase((string)$facts['accepted_milli'],$basis['numerator'],$basis['denominator']);
+ abort_unless(($basis['accepted_document_milli']??null)===(string)$facts['accepted_milli']
+ && ($basis['accepted_stock_milli']??null)===$converted,409,'Quantidade física divergente da conversão congelada.');
+ return $converted;
+ }
+
+ private function checkHost(): void
+ {
+ if($this->db->transactionLevel()<1)throw new \LogicException('Receipt movement requires the host atomic transaction');
+ ($this->authorize)();
+ }
+
+ private function facts(int $lineId,bool $lock): array
+ {
+ $q=$this->db->table($this->schema.'.goods_receipt_items AS l')
+ ->join($this->schema.'.goods_receipts AS r',fn($j)=>$j->on('r.id','=','l.goods_receipt_id')->on('r.tenant_id','=','l.tenant_id'))
+ ->where('l.tenant_id',$this->tenant)->where('l.id',$lineId)
+ ->select(['l.id','l.tenant_id','l.stock_item_id','l.received_milli','l.accepted_milli','l.rejected_milli','l.quality_status','l.notes',
+ 'l.snapshot AS line_snapshot','r.id AS receipt_id','r.purchase_order_id','r.received_by','r.warehouse_id','r.delivery_note','r.received_on','r.confirmed_at','r.snapshot AS receipt_snapshot']);
+ if($lock)$q->lockForUpdate();
+ $row=$q->first();abort_unless($row,403,'Origem fora do âmbito autorizado.');$facts=(array)$row;
+ $snapshot=json_decode($facts['line_snapshot'],true,512,JSON_THROW_ON_ERROR);
+ abort_unless((int)$facts['received_by']===$this->actor,403,'A origem não pertence ao recebedor desta confirmação.');
+ abort_unless($facts['confirmed_at']!==null && ($snapshot['physical']??false)===true && (int)$facts['accepted_milli']>0
+ && $facts['stock_item_id']!==null && $facts['warehouse_id']!==null,409,'A origem não comprova quantidade física aceite.');
+ return $facts;
+ }
+
+ private function hash(array $facts): string
+ {
+ // Parent status/number are intentionally absent: finalisation occurs later in the same transaction.
+ return hash('sha256',json_encode($facts,JSON_THROW_ON_ERROR));
+ }
+}
diff --git a/packages/order-cancellation/README.md b/packages/order-cancellation/README.md
index 4d8c12b..6a8e782 100644
--- a/packages/order-cancellation/README.md
+++ b/packages/order-cancellation/README.md
@@ -4,4 +4,6 @@ Additive local development capability for integral issued-order cancellation. Do
The host must hold its company lock, authenticate an independent finance actor, validate the published policy, confirm absence of receipts/invoices/payments and open the encompassing transaction. The writer appends a reversal of the original wholly available commitment in the canonical budget_entries ledger. The host binds the reversal entry to its decision in the same transaction and audit.
-MZN only. Verify source SHA-256 against config/order_cancellation.php before execution. No transport, bank operations, invoice cancellation, partial cancellation, activation or grants. The capability is disabled in the local pilot; validation uses disposable databases.
+MZN only. The frozen legacy writer remains in `src`. The cycle-aware writer is versioned in `releases/0.2.0-rc.1`; `OrderCancellationRuntime` verifies its manifest, installation, schema and loaded class location before use. It reverses only the current open requisition cycle and preserves earlier cycles.
+
+The versioned component is installed and explicitly enabled in the Compras local pilot under the owner's installation authorization of 29/11/2026. The original four-package financial installation is unchanged. No company cancellation policy, grant or business cancellation was created by installation. Native review and recovery use disposable synthetic databases. See `docs/proofs/order-cancellation-pilot-installation.json` and `order-cancellation-pilot-native-review.json`. No SGF installation, transport, bank operations or invoice cancellation is included.
diff --git a/packages/order-cancellation/releases/0.2.0-rc.1/manifest.json b/packages/order-cancellation/releases/0.2.0-rc.1/manifest.json
new file mode 100644
index 0000000..0bab601
--- /dev/null
+++ b/packages/order-cancellation/releases/0.2.0-rc.1/manifest.json
@@ -0,0 +1,9 @@
+{
+ "id": "tempo-order-cancellation",
+ "version": "0.2.0-rc.1",
+ "contract": "COMPRAS-ORDER-CANCELLATION-CYCLES-v1",
+ "legacy_source_sha256": "5471d9f826f47012415bf9a7086d4d7316ab8550b58e497f7432b94514a18bfa",
+ "files": {
+ "src/CommitmentReversal.php": "ecf0028a57b0280cf3a889da29a6e528c7eaa6a876e700b32ff59ac3b3eeb069"
+ }
+}
diff --git a/packages/order-cancellation/releases/0.2.0-rc.1/src/CommitmentReversal.php b/packages/order-cancellation/releases/0.2.0-rc.1/src/CommitmentReversal.php
new file mode 100644
index 0000000..2562e0b
--- /dev/null
+++ b/packages/order-cancellation/releases/0.2.0-rc.1/src/CommitmentReversal.php
@@ -0,0 +1,65 @@
+transactionLevel() < 1) {
+ throw new LogicException('Reversal requires the host transaction and company lock.');
+ }
+ $hasCycles = $db->getSchemaBuilder()->hasTable('budget_requisition_cycles');
+ if ($hasCycles !== $db->getSchemaBuilder()->hasColumn('budget_entries', 'requisition_cycle')) {
+ throw new LogicException('Incomplete budget cycle schema.');
+ }
+ $cycle = $context->requisitionCycles[$origin] ?? null;
+ if ($hasCycles) {
+ if ($cycle === null) {
+ throw new LogicException('Explicit order source cycle required.');
+ }
+ $head = $db->table('budget_requisition_cycles')->where($context->scope)->where('requisition_id', $origin)
+ ->orderByDesc('cycle')->lockForUpdate()->first();
+ if (($head === null && $cycle !== 1) || ($head !== null && ((int) $head->cycle !== $cycle || $head->state !== 'open'))) {
+ throw new LogicException('Only the current open order source cycle can be reversed.');
+ }
+ } elseif (($cycle ?? 1) !== 1) {
+ throw new LogicException('Budget cycle schema required for resubmitted orders.');
+ }
+ $entries = $db->table('budget_entries')->where($context->scope)->where('requisition_id', $origin)
+ ->when($hasCycles, fn ($query) => $query->where('requisition_cycle', $cycle))->orderBy('id')->lockForUpdate()->get();
+ if ($entries->isEmpty()) {
+ return null;
+ }
+ $commit = $entries->where('kind', 'commit');
+ if ($commit->count() !== 1) {
+ throw new LogicException('Exactly one original commitment required.');
+ }
+ $source = $commit->first();
+ $amount = BigDecimal::of((string) $source->committed_minor)->toInt();
+ $kind = 'order-cancel-'.$order;
+ $old = $entries->firstWhere('kind', $kind);
+ if ($old) {
+ if ((int) $old->committed_minor !== -$amount || (int) $old->reserved_minor !== 0 || $old->budget_id !== $source->budget_id) {
+ throw new LogicException('Invalid prior reversal.');
+ }
+
+ return (int) $old->id;
+ }
+ $budget = $db->table('budgets')->where($context->scope)->where('id', $source->budget_id)->lockForUpdate()->first();
+ if (! $budget || ! $budget->approved_by || $amount <= 0 || $entries->contains(fn ($e) => $e->budget_id !== $source->budget_id)
+ || BigDecimal::of((string) $entries->sum('reserved_minor'))->toInt() !== 0
+ || BigDecimal::of((string) $entries->sum('committed_minor'))->toInt() !== $amount) {
+ throw new LogicException('Commitment is not wholly available for reversal.');
+ }
+
+ return $db->table('budget_entries')->insertGetId([...$context->scope, ...($hasCycles ? ['requisition_cycle' => $cycle] : []), 'budget_id' => $source->budget_id, 'requisition_id' => $origin,
+ 'created_by' => $context->actorId, 'kind' => $kind, 'reserved_minor' => 0, 'committed_minor' => -$amount, 'created_at' => now()]);
+ }
+}
diff --git a/resources/css/app.css b/resources/css/app.css
index d51f5e9..c2fce10 100644
--- a/resources/css/app.css
+++ b/resources/css/app.css
@@ -230,4 +230,31 @@
.sgc-wide-report nav {
display: none;
}
+
+ .sgc-procurement-report {
+ font-size: 10pt;
+ line-height: 1.35;
+ }
+
+ .sgc-procurement-report .sgc-panel {
+ padding: 8pt;
+ }
+
+ .sgc-procurement-report .sgc-panel > div {
+ margin-top: 6pt;
+ }
+
+ .sgc-procurement-report :is(h2, h3) {
+ break-after: avoid;
+ }
+
+ .sgc-procurement-report :is(h2, h3) + p {
+ break-before: avoid;
+ break-after: avoid;
+ }
+
+ .sgc-procurement-report p {
+ orphans: 3;
+ widows: 3;
+ }
}
diff --git a/resources/js/components/procurement-payment-insights.tsx b/resources/js/components/procurement-payment-insights.tsx
index ea69f59..a1ecc80 100644
--- a/resources/js/components/procurement-payment-insights.tsx
+++ b/resources/js/components/procurement-payment-insights.tsx
@@ -52,7 +52,11 @@ export function ProcurementPaymentInsights({
{data.from ?? 'Desde o início'} —{' '}
{data.to ?? 'Até à data actual'}.{' '}
- {data.coverage.confirmed_payments} pagamentos confirmados.
+ {data.coverage.confirmed_payments}{' '}
+ {data.coverage.confirmed_payments === 1
+ ? 'pagamento confirmado'
+ : 'pagamentos confirmados'}
+ .
Cada factura é considerada uma única vez, mesmo quando a ordem
@@ -71,7 +75,8 @@ export function ProcurementPaymentInsights({
return (
{digits.slice(0, -2)},{digits.slice(-2)} {row.currency}{' '}
- · {row.count} pagamentos
+ · {row.count}{' '}
+ {row.count === 1 ? 'pagamento' : 'pagamentos'}
);
})}
diff --git a/resources/js/lib/procurement-navigation.ts b/resources/js/lib/procurement-navigation.ts
index e52e3dd..e78b6da 100644
--- a/resources/js/lib/procurement-navigation.ts
+++ b/resources/js/lib/procurement-navigation.ts
@@ -677,6 +677,15 @@ export function activeProcurementEntry(
url: string,
): string | undefined {
const current = new URL(url, 'http://local');
+ if (
+ /^\/afectacoes-fornecedores\/\d+\/imputacao(?:\/|$)/.test(
+ current.pathname,
+ ) &&
+ groups.some((group) =>
+ group.entries.some((entry) => entry.id === 'supplier_settlements'),
+ )
+ )
+ return 'supplier_settlements';
if (
(current.pathname === '/compras/acordos/vigencia' ||
(current.pathname === '/compras/fornecimento' &&
diff --git a/resources/js/pages/reports/procurement.tsx b/resources/js/pages/reports/procurement.tsx
index 1d760e9..6c6258f 100644
--- a/resources/js/pages/reports/procurement.tsx
+++ b/resources/js/pages/reports/procurement.tsx
@@ -110,7 +110,7 @@ export default function ProcurementReports({
return (
<>
-
+
'true', 'COMPRAS_INVENTORY_ROOT' => $destination];
+if ($changes !== $plan['proposed_settings_only']) {
+ throw new LogicException('Unreviewed settings changes refused.');
+}
+$after = [...$settings, ...$changes];
+$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
+$preflight = new Process([PHP_BINARY, 'scripts/check-inventory-conversion-pilot.php', '--read-only'], $root, timeout: 30);
+$preflight->mustRun();
+$check = json_decode($preflight->getOutput(), true, 32, JSON_THROW_ON_ERROR);
+if ($check['state'] !== 'passed' || $check['active_settings_changed'] !== false) {
+ throw new LogicException('Read-only installation preflight failed.');
+}
+if ($argv[1] === '--preview') {
+ echo json_encode(['state' => 'preview', 'verified_archive' => true, 'read_only_preflight' => true,
+ 'changed_keys' => array_keys($changes), 'settings_or_database_written' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+ exit;
+}
+if (file_exists($destination)) {
+ throw new LogicException('Existing inventory destination refused; preserve and inspect it.');
+}
+$backup = 'C:/laragon/data/compras/backups/inventory-activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
+if (! mkdir($backup, 0700, true) || file_put_contents($backup.'/settings.before.private.json', $before, LOCK_EX) !== strlen($before)
+ || ! hash_equals(hash('sha256', $before), hash_file('sha256', $backup.'/settings.before.private.json'))) {
+ throw new LogicException('Verified private settings backup required.');
+}
+$db = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+$db->exec('SET default_transaction_read_only=on');
+$frames = static function () use ($db): array {
+ $db->beginTransaction();
+ try {
+ $db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+ $out = [];
+ foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
+ $quoted = '"'.str_replace('"', '""', $table).'"';
+ $rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
+ $out[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
+ }
+ $db->commit();
+
+ return $out;
+ } finally {
+ if ($db->inTransaction()) {
+ $db->rollBack();
+ }
+ }
+};
+$baseline = $frames();
+file_put_contents($backup.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
+$protected = ['env' => hash_file('sha256', $root.'/.env'), 'frontend' => hash_file('sha256', $root.'/public/build/manifest.json')];
+$zip = new ZipArchive;
+if ($zip->open($archive) !== true || $zip->numFiles !== 4) {
+ throw new LogicException('Reviewed archive required.');
+}
+InventoryConversionRuntime::assertArchiveEntries($zip);
+if (! mkdir($destination, 0700) || ! $zip->extractTo($destination) || ! $zip->close()) {
+ throw new LogicException('Inventory extraction failed; settings not changed.');
+}
+InventoryConversionRuntime::verifyArtifact($destination);
+$temporary = $settingsPath.'.inventory-'.bin2hex(random_bytes(6)).'.tmp';
+try {
+ if (file_put_contents($temporary, $encoded, LOCK_EX) !== strlen($encoded)
+ || ! hash_equals(hash('sha256', $before), hash_file('sha256', $settingsPath)) || ! rename($temporary, $settingsPath)) {
+ throw new LogicException('Atomic settings selection failed.');
+ }
+ $postcheck = new Process([PHP_BINARY, 'scripts/check-inventory-conversion-pilot.php', '--installed-read-only'], $root, timeout: 30);
+ $postcheck->mustRun();
+ $verified = json_decode($postcheck->getOutput(), true, 32, JSON_THROW_ON_ERROR);
+ if ($verified['state'] !== 'passed' || ! $verified['inventory_component_installed_or_activated'] || $frames() !== $baseline
+ || hash_file('sha256', $root.'/.env') !== $protected['env'] || hash_file('sha256', $root.'/public/build/manifest.json') !== $protected['frontend']
+ || json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
+ throw new LogicException('Installed component conservation failed.');
+ }
+ $result = ['date' => gmdate('c'), 'state' => 'passed', 'authorization' => 'inventory-conversion-pilot-authorization.json',
+ 'target' => 'http://127.0.0.1:8005', 'backup_directory' => $backup, 'inventory_directory' => $destination,
+ 'inventory_manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256,
+ 'settings_before_sha256' => hash('sha256', $before), 'settings_after_sha256' => hash('sha256', $encoded),
+ 'changed_keys' => array_keys($changes), 'all_database_tables_preserved' => count($baseline),
+ 'unrelated_settings_env_frontend_and_financial_receipt_preserved' => true,
+ 'new_permissions_users_migrations_or_business_commands' => false, 'application_complete' => false];
+ file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+ echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
+} catch (Throwable $error) {
+ // No blind downgrade after possible converted effects or concurrent business edits.
+ file_put_contents($backup.'/failure.private.json', json_encode(['state' => 'requires_inspection_before_configuration_recovery', 'error_class' => $error::class], JSON_THROW_ON_ERROR));
+ throw $error;
+} finally {
+ if (is_file($temporary)) {
+ unlink($temporary);
+ }
+}
diff --git a/scripts/activate-order-cancellation-pilot.php b/scripts/activate-order-cancellation-pilot.php
new file mode 100644
index 0000000..263adeb
--- /dev/null
+++ b/scripts/activate-order-cancellation-pilot.php
@@ -0,0 +1,111 @@
+ 'true', 'COMPRAS_ORDER_CANCELLATION_ROOT' => $destination];
+if ($changes !== $plan['proposed_settings_only']) {
+ throw new LogicException('Unreviewed cancellation configuration refused.');
+}
+$candidate = $root.'/'.$plan['candidate_root'];
+OrderCancellationRuntime::verifyArtifact($candidate);
+$preflight = new Process([PHP_BINARY, 'scripts/check-order-cancellation-pilot.php', '--read-only'], $root, timeout: 30);
+$preflight->mustRun();
+if (json_decode($preflight->getOutput(), true, 32, JSON_THROW_ON_ERROR)['state'] !== 'passed') {
+ throw new LogicException('Cancellation read-only preflight failed.');
+}
+if ($argv[1] === '--preview') {
+ echo json_encode(['state' => 'preview', 'changed_keys' => array_keys($changes), 'database_writes' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+ exit;
+}
+if (file_exists($destination)) {
+ throw new LogicException('Preserve existing cancellation component directory.');
+}
+$backup = 'C:/laragon/data/compras/backups/cancellation-activation-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
+if (! mkdir($backup, 0700, true) || file_put_contents($backup.'/settings.before.private.json', $before, LOCK_EX) !== strlen($before)
+ || ! hash_equals(hash('sha256', $before), hash_file('sha256', $backup.'/settings.before.private.json'))) {
+ throw new LogicException('Cancellation configuration backup failed.');
+}
+$db = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+$db->exec('SET default_transaction_read_only=on');
+$frames = static function () use ($db): array {
+ $db->beginTransaction();
+ try {
+ $db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+ $out = [];
+ foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
+ $quoted = '"'.str_replace('"', '""', $table).'"';
+ $rows = $db->query('SELECT row_to_json(t)::text FROM '.$quoted.' t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
+ $out[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
+ }
+ $db->commit();
+
+ return $out;
+ } finally {
+ if ($db->inTransaction()) {
+ $db->rollBack();
+ }
+ }
+};
+$baseline = $frames();
+file_put_contents($backup.'/table-hashes.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
+$envHash = hash_file('sha256', $root.'/.env');
+$assetsHash = hash_file('sha256', $root.'/public/build/manifest.json');
+if (! mkdir($destination, 0700) || ! mkdir($destination.'/src', 0700)) {
+ throw new LogicException('Cancellation private destination unavailable.');
+}
+foreach (['manifest.json', 'src/CommitmentReversal.php'] as $file) {
+ if (! copy($candidate.'/'.$file, $destination.'/'.$file)) {
+ throw new LogicException('Cancellation component copy failed before activation.');
+ }
+}
+OrderCancellationRuntime::verifyArtifact($destination);
+$after = [...$settings, ...$changes];
+$encoded = json_encode($after, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_THROW_ON_ERROR).PHP_EOL;
+$temporary = $sourcePath.'.cancellation-'.bin2hex(random_bytes(6)).'.tmp';
+try {
+ if (file_put_contents($temporary, $encoded, LOCK_EX) !== strlen($encoded)
+ || ! hash_equals(hash('sha256', $before), hash_file('sha256', $sourcePath)) || ! rename($temporary, $sourcePath)) {
+ throw new LogicException('Cancellation atomic configuration selection failed.');
+ }
+ $check = new Process([PHP_BINARY, 'scripts/check-order-cancellation-pilot.php', '--installed-read-only'], $root, timeout: 30);
+ $check->mustRun();
+ if (json_decode($check->getOutput(), true, 32, JSON_THROW_ON_ERROR)['state'] !== 'passed'
+ || $frames() !== $baseline || hash_file('sha256', $root.'/.env') !== $envHash
+ || hash_file('sha256', $root.'/public/build/manifest.json') !== $assetsHash
+ || json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR) !== $after) {
+ throw new LogicException('Cancellation installation conservation failed; inspect without reverting business rows.');
+ }
+ $report = ['date' => gmdate('c'), 'state' => 'passed', 'target' => 'http://127.0.0.1:8005',
+ 'authorization' => 'order-cancellation-pilot-authorization.json', 'backup_directory' => $backup, 'component_directory' => $destination,
+ 'manifest_sha256' => OrderCancellationRuntime::MANIFEST_SHA256, 'changed_keys' => array_keys($changes),
+ 'settings_before_sha256' => hash('sha256', $before), 'settings_after_sha256' => hash('sha256', $encoded),
+ 'all_database_tables_preserved' => count($baseline), 'unrelated_settings_financial_receipt_env_and_frontend_preserved' => true,
+ 'policies_grants_migrations_or_business_commands' => false, 'application_complete' => false];
+ file_put_contents($resultPath, json_encode($report, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+ echo json_encode($report, JSON_THROW_ON_ERROR).PHP_EOL;
+} finally {
+ if (is_file($temporary)) {
+ unlink($temporary);
+ }
+}
diff --git a/scripts/build-inventory-conversion-artifact.php b/scripts/build-inventory-conversion-artifact.php
new file mode 100644
index 0000000..edc7145
--- /dev/null
+++ b/scripts/build-inventory-conversion-artifact.php
@@ -0,0 +1,45 @@
+open($temporary, ZipArchive::CREATE | ZipArchive::EXCL) !== true) {
+ throw new LogicException('Private archive creation failed.');
+ }
+ foreach (['manifest.json', ...array_keys($manifest['files'])] as $file) {
+ if (! $zip->addFile($root.'/'.$file, $file) || ! $zip->setMtimeName($file, 1795910400)
+ || ! $zip->setExternalAttributesName($file, ZipArchive::OPSYS_UNIX, 0100644 << 16)) {
+ throw new LogicException('Private archive entry failed.');
+ }
+ }
+ if (! $zip->close()) {
+ throw new LogicException('Private archive close failed.');
+ }
+ $hash = hash_file('sha256', $temporary);
+ if (is_file($target)) {
+ if (is_link($target) || ! hash_equals($hash, hash_file('sha256', $target))) {
+ throw new LogicException('Existing archive differs; replacement refused.');
+ }
+ } elseif (! rename($temporary, $target)) {
+ throw new LogicException('Private archive publication failed.');
+ }
+ echo json_encode(['state' => 'private_candidate_only', 'archive' => $target, 'entries' => 4,
+ 'manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256, 'archive_sha256' => $hash,
+ 'pilot_or_production_changes' => false], JSON_THROW_ON_ERROR | JSON_PRETTY_PRINT).PHP_EOL;
+} finally {
+ if (is_file($temporary)) {
+ unlink($temporary);
+ }
+}
diff --git a/scripts/check-analytics-preview.php b/scripts/check-analytics-preview.php
new file mode 100644
index 0000000..46cf95c
--- /dev/null
+++ b/scripts/check-analytics-preview.php
@@ -0,0 +1,51 @@
+ PDO::ERRMODE_EXCEPTION]);
+$db->beginTransaction();
+$db->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+if ($db->query("select current_setting('cluster_name')")->fetchColumn() !== 'sgf_modular_regression_'.$match[1]) {
+ throw new LogicException('Wrong analytical verification cluster.');
+}
+$frames = [];
+foreach ($db->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
+ if (in_array($table, ['supply_records', 'audit_logs'], true)) {
+ continue;
+ }
+ // Normal authentication may rehash a synthetic password or rotate a remember token.
+ $query = $table === 'users' ? 'SELECT id,tenant_id,department_id,purchasing_role,name,email,created_at FROM users'
+ : 'SELECT * FROM "'.str_replace('"', '""', $table).'"';
+ $rows = $db->query('SELECT row_to_json(t)::text FROM ('.$query.') t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
+ $frames[$table] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
+}
+$file = $root.'/analytics-baseline.private.json';
+if ($mode === '--capture') {
+ if (is_file($file) || (int) $db->query("SELECT count(*) FROM supply_records WHERE kind='expense_allocation'")->fetchColumn() !== 0) {
+ throw new LogicException('Fresh analytical baseline required.');
+ }
+ file_put_contents($file, json_encode($frames, JSON_THROW_ON_ERROR));
+ echo json_encode(['state' => 'captured', 'protected_tables' => count($frames), 'database_read_only' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+} else {
+ if ($frames !== json_decode(file_get_contents($file), true, 32, JSON_THROW_ON_ERROR)) {
+ throw new LogicException('Native analytical review changed protected source data.');
+ }
+ $records = $db->query("SELECT data FROM supply_records WHERE kind='expense_allocation' ORDER BY id")->fetchAll(PDO::FETCH_COLUMN);
+ $data = count($records) === 1 ? json_decode($records[0], true, 32, JSON_THROW_ON_ERROR) : [];
+ if (($data['source_type'] ?? null) !== 'common_allocation' || ($data['allocations'] ?? []) !== [
+ ['category' => 'Material', 'amount_minor' => '1500'], ['category' => 'Serviços', 'amount_minor' => '2500']]
+ || (int) $db->query("SELECT count(*) FROM audit_logs WHERE action='expense.allocation_recorded'")->fetchColumn() !== 1) {
+ throw new LogicException('One exact explicit analytical attribution and audit required.');
+ }
+ echo json_encode(['state' => 'passed', 'protected_tables' => count($frames), 'database_read_only' => true,
+ 'explicit_category_total_minor' => 4000, 'one_attribution_one_audit' => true, 'no_financial_source_mutation' => true], JSON_THROW_ON_ERROR).PHP_EOL;
+}
+$db->commit();
diff --git a/scripts/check-inventory-conversion-pilot.php b/scripts/check-inventory-conversion-pilot.php
new file mode 100644
index 0000000..777e388
--- /dev/null
+++ b/scripts/check-inventory-conversion-pilot.php
@@ -0,0 +1,84 @@
+ 'pilot-readonly', 'APP_DEBUG' => 'false',
+ 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
+ 'COMPRAS_INVENTORY_CONVERSION_ENABLED' => 'true', 'COMPRAS_INVENTORY_ROOT' => $candidate,
+ 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
+ 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-inventory-readonly-config.php', 'LOG_CHANNEL' => 'stderr'];
+foreach ($environment as $key => $value) {
+ putenv($key.'='.$value);
+ $_ENV[$key] = $_SERVER[$key] = $value;
+}
+$app = require $root.'/bootstrap/app.php';
+$app->make(Kernel::class)->bootstrap();
+if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
+ throw new LogicException('Database read-only enforcement required.');
+}
+// Conservation belongs to this inspection. Installation-time conservation remains
+// in the immutable installation proof; an operating application may advance its queue.
+DB::beginTransaction();
+DB::statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+$frames = static function (): array {
+ $result = [];
+ foreach (DB::select("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename") as $table) {
+ $quoted = '"'.str_replace('"', '""', $table->tablename).'"';
+ $rows = DB::select('SELECT row_to_json(t)::text AS row FROM '.$quoted.' t ORDER BY row_to_json(t)::text');
+ $result[$table->tablename] = hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR));
+ }
+
+ return $result;
+};
+$baseline = $frames();
+if (! app(InventoryConversionRuntime::class)->available()) {
+ throw new LogicException('Candidate unavailable with prospective configuration.');
+}
+app(ReceiptStockMovement::class)->load();
+$converted = DB::table('goods_receipt_items')->whereNotNull('snapshot->quantity_conversion')->count();
+if ($frames() !== $baseline) {
+ throw new LogicException('Inventory inspection changed pilot data.');
+}
+$preserved = count($baseline);
+DB::commit();
+if (! hash_equals($sourceHash, hash_file('sha256', $sourcePath))
+ || ! hash_equals($publicHash, hash_file('sha256', $root.'/public/build/manifest.json'))) {
+ throw new LogicException('Concurrent pilot settings or frontend change.');
+}
+$result = ['date' => gmdate('c'), 'state' => 'passed', 'mode' => $installed ? 'installed_read_only_postcheck' : 'prospective_read_only_preflight',
+ 'database_enforced_read_only' => true, 'candidate_available_with_installed_financial_runtime' => true,
+ 'inventory_manifest_sha256' => InventoryConversionRuntime::MANIFEST_SHA256,
+ 'active_settings_sha256' => $sourceHash, 'public_manifest_sha256' => $publicHash,
+ 'existing_converted_receipt_lines' => $converted, 'active_settings_changed' => false,
+ 'database_tables_preserved_during_readonly_check' => $preserved,
+ 'inventory_component_installed_or_activated' => $installed, 'migrations_or_business_commands' => false];
+file_put_contents($root.'/docs/proofs/inventory-conversion-pilot-'.($installed ? 'current-check' : 'preflight').'.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/scripts/check-order-cancellation-pilot.php b/scripts/check-order-cancellation-pilot.php
new file mode 100644
index 0000000..104efdd
--- /dev/null
+++ b/scripts/check-order-cancellation-pilot.php
@@ -0,0 +1,52 @@
+ 'pilot-readonly', 'APP_DEBUG' => 'false', 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '',
+ 'PGOPTIONS' => '-c default_transaction_read_only=on', 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array',
+ 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array', 'LOG_CHANNEL' => 'stderr',
+ 'COMPRAS_ORDER_CANCELLATION_ENABLED' => 'true',
+ 'COMPRAS_ORDER_CANCELLATION_ROOT' => $installed ? $plan['target_root'] : $root.'/'.$plan['candidate_root'],
+ 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-cancellation-readonly-config.php'];
+foreach ($environment as $key => $value) {
+ putenv($key.'='.$value);
+ $_ENV[$key] = $_SERVER[$key] = $value;
+}
+$app = require $root.'/bootstrap/app.php';
+$app->make(Kernel::class)->bootstrap();
+if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
+ throw new LogicException('Enforced read-only database required.');
+}
+app(OrderCancellationRuntime::class)->assertReady();
+app(OrderCancellationRuntime::class)->load(0); // Byte-checked class loading only, no reversal command.
+if (! hash_equals(hash('sha256', $before), hash_file('sha256', $sourcePath))) {
+ throw new LogicException('Concurrent cancellation configuration edit.');
+}
+$result = ['date' => gmdate('c'), 'state' => 'passed', 'installed' => $installed, 'database_enforced_read_only' => true,
+ 'manifest_sha256' => OrderCancellationRuntime::MANIFEST_SHA256,
+ 'existing_cancellation_records' => DB::table('order_cancellations')->count(),
+ 'existing_approved_policies' => DB::table('order_cancellation_policies')->where('status', 'approved')->count(),
+ 'new_policies_grants_business_commands_or_settings_changes' => false];
+file_put_contents($root.'/docs/proofs/order-cancellation-pilot-'.($installed ? 'postcheck' : 'preflight').'.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/scripts/check-pilot-operations.php b/scripts/check-pilot-operations.php
new file mode 100644
index 0000000..a818706
--- /dev/null
+++ b/scripts/check-pilot-operations.php
@@ -0,0 +1,77 @@
+ 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => '-c default_transaction_read_only=on',
+ 'CACHE_STORE' => 'array', 'SESSION_DRIVER' => 'array', 'QUEUE_CONNECTION' => 'null', 'MAIL_MAILER' => 'array',
+ 'LOG_CHANNEL' => 'stderr', 'APP_DEBUG' => 'false', 'APP_CONFIG_CACHE' => $root.'/storage/framework/absent-operations-check.php'] as $key => $value) {
+ putenv($key.'='.$value);
+ $_ENV[$key] = $_SERVER[$key] = $value;
+}
+$app = require $root.'/bootstrap/app.php';
+$app->make(Kernel::class)->bootstrap();
+if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
+ throw new LogicException('Enforced database read-only mode required.');
+}
+app(StandaloneRuntime::class)->assertLoadedPackages();
+$result = app(OperationalHealth::class)->inspect();
+$taskProof = $root.'/docs/proofs/replenishment-task-installation.json';
+$taskVerification = null;
+if (is_file($taskProof)) {
+ $task = json_decode(file_get_contents($taskProof), true, 32, JSON_THROW_ON_ERROR);
+ $directory = str_replace('\\', '/', $task['private_backup_directory']);
+ if (! preg_match('~^C:/laragon/data/compras/tasks/replenishment-[0-9]{8}-[0-9]{6}-[a-f0-9]{12}$~D', $directory)
+ || $task['task_name'] !== 'Compras-Pilot-Replenishment') {
+ throw new LogicException('Owned replenishment task backup required.');
+ }
+ $native = new Process([getenv('SystemRoot').'/System32/schtasks.exe', '/Query', '/TN', $task['task_name'], '/XML'], $root, timeout: 15);
+ $native->run();
+ if (! $native->isSuccessful()) {
+ throw new LogicException('Native replenishment task unavailable.');
+ }
+ ReplenishmentTaskDefinition::assertMatches(file_get_contents($directory.'/task.private.xml'), $native->getOutput());
+ $baseline = count($argv) === 3
+ ? json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR) : [];
+ $changed = [];
+ foreach ($baseline as $table => $before) {
+ $rows = DB::select('SELECT row_to_json(t)::text AS row FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text');
+ $same = hash_equals($before['sha256'], hash('sha256', json_encode(array_column($rows, 'row'), JSON_THROW_ON_ERROR)));
+ if (! $same) {
+ $changed[] = $table;
+ if (! in_array($table, ['replenishment_work', 'supply_records', 'audit_logs'], true)) {
+ throw new LogicException('Protected pilot table changed during replenishment verification.');
+ }
+ }
+ }
+ $taskVerification = ['native_definition_verified' => true, 'installation_conservation_requested' => count($argv) === 3, 'baseline_tables' => count($baseline),
+ 'unchanged_tables' => count($baseline) - count($changed), 'changed_native_replenishment_tables' => $changed,
+ 'new_policies_or_grants' => false];
+}
+if (! hash_equals(hash('sha256', $bytes), hash_file('sha256', $path))) {
+ throw new LogicException('Pilot settings changed during inspection.');
+}
+$proof = ['date' => gmdate('c'), 'database_enforced_read_only' => true, 'business_commands' => false,
+ 'replenishment_task_verification' => $taskVerification, 'result' => $result];
+file_put_contents($root.'/docs/proofs/pilot-operations-current.json', json_encode($proof, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($proof, JSON_THROW_ON_ERROR).PHP_EOL;
+exit($result['ok'] ? 0 : 1);
diff --git a/scripts/check-standalone-pilot-activation.php b/scripts/check-standalone-pilot-activation.php
index 1ceb29d..23f219e 100644
--- a/scripts/check-standalone-pilot-activation.php
+++ b/scripts/check-standalone-pilot-activation.php
@@ -15,14 +15,45 @@ $sourcePath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
$source = json_decode(file_get_contents($sourcePath), true, 32, JSON_THROW_ON_ERROR);
$expectedSettings = $plan['active_settings_sha256'];
$expectedManifest = $plan['frontend']['previous_manifest_sha256'];
+$frontend = $plan['frontend'];
if ($installed) {
$activation = json_decode(file_get_contents($root.'/docs/proofs/compras-standalone-pilot-activation.json'), true, 32, JSON_THROW_ON_ERROR);
$previous = json_decode(file_get_contents($activation['backup_directory'].'/settings.before.private.json'), true, 32, JSON_THROW_ON_ERROR);
- if ($activation['state'] !== 'passed' || $source !== [...$previous, ...$plan['proposed_runtime_settings']]) {
+ $component = [];
+ foreach (['inventory-conversion', 'order-cancellation'] as $componentName) {
+ if (! is_file($root.'/docs/proofs/'.$componentName.'-pilot-installation.json')) {
+ continue;
+ }
+ $inventory = json_decode(file_get_contents($root.'/docs/proofs/'.$componentName.'-pilot-installation.json'), true, 32, JSON_THROW_ON_ERROR);
+ $inventoryPlanPath = $root.'/docs/proofs/'.$componentName.'-pilot-proposal.json';
+ $inventoryPlan = json_decode(file_get_contents($inventoryPlanPath), true, 32, JSON_THROW_ON_ERROR);
+ $inventoryApproval = json_decode(file_get_contents($root.'/docs/proofs/'.$componentName.'-pilot-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
+ if ($inventory['state'] !== 'passed' || $inventoryApproval['state'] !== 'approved'
+ || ! hash_equals($inventoryApproval['proposal_sha256'], hash_file('sha256', $inventoryPlanPath))) {
+ throw new LogicException('ACTIVATION_POSTCHECK_COMPONENT_AUTHORIZATION');
+ }
+ $component = [...$component, ...$inventoryPlan['proposed_settings_only']];
+ }
+ if ($activation['state'] !== 'passed' || $source !== [...$previous, ...$plan['proposed_runtime_settings'], ...$component]) {
throw new LogicException('ACTIVATION_POSTCHECK_SETTINGS_DIFFER');
}
$expectedSettings = hash_file('sha256', $sourcePath);
$expectedManifest = $plan['frontend']['manifest_sha256'];
+ $interfacePlanPath = $root.'/docs/proofs/analytics-print-publication-proposal.json';
+ if (is_file($root.'/docs/proofs/analytics-print-publication.json')) {
+ $interfacePlan = json_decode(file_get_contents($interfacePlanPath), true, 512, JSON_THROW_ON_ERROR);
+ $interfaceApproval = json_decode(file_get_contents($root.'/docs/proofs/analytics-print-publication-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
+ $interfaceResult = json_decode(file_get_contents($root.'/docs/proofs/analytics-print-publication.json'), true, 32, JSON_THROW_ON_ERROR);
+ if ($interfaceApproval['state'] !== 'approved' || ($interfaceResult['pilot_state'] ?? $interfaceResult['state']) !== 'passed'
+ || $interfaceApproval['scope'] !== 'analytics_print_and_attribution_menu_shared_frontend_delta'
+ || ! hash_equals($interfaceApproval['proposal_sha256'], hash_file('sha256', $interfacePlanPath))
+ || $interfacePlan['previous_manifest_sha256'] !== $expectedManifest
+ || $interfaceResult['manifest_sha256'] !== $interfacePlan['manifest_sha256']) {
+ throw new LogicException('ACTIVATION_POSTCHECK_INTERFACE_AUTHORIZATION');
+ }
+ $frontend = $interfacePlan;
+ $expectedManifest = $interfacePlan['manifest_sha256'];
+ }
}
if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))
|| $source['APP_ENV'] !== 'payable-testing' || $source['DB_HOST'] !== '127.0.0.1'
@@ -32,12 +63,12 @@ if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))
|| trim($source['PAYABLE_SOURCE_INSTANCE'] ?? '') === '') {
throw new LogicException('ACTIVATION_PREFLIGHT_SOURCE_CHANGED');
}
-$assets = $root.'/'.$plan['frontend']['candidate_root'];
-if (! hash_equals($plan['frontend']['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
+$assets = $root.'/'.$frontend['candidate_root'];
+if (! hash_equals($frontend['manifest_sha256'], hash_file('sha256', $assets.'/manifest.json'))
|| ! hash_equals($expectedManifest, hash_file('sha256', $root.'/public/build/manifest.json'))) {
throw new LogicException('ACTIVATION_PREFLIGHT_MANIFEST_CHANGED');
}
-foreach ($plan['frontend']['files'] as $file => $hash) {
+foreach ($frontend['files'] as $file => $hash) {
if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $assets.'/'.$file))
|| (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
throw new LogicException('ACTIVATION_PREFLIGHT_ASSET_MISMATCH');
@@ -68,7 +99,7 @@ if (! hash_equals($expectedSettings, hash_file('sha256', $sourcePath))) {
}
$result = ['date' => gmdate('c'), 'state' => 'passed', 'database_enforced_read_only' => true,
'all_24_capabilities_start_with_pinned_installed_packages' => true, 'source_instance_preserved' => true,
- 'frontend_assets_verified' => count($plan['frontend']['files']), 'active_settings_changed' => false,
+ 'frontend_assets_verified' => count($frontend['files']), 'active_settings_changed' => false,
'mode' => $installed ? 'installed_configuration_read_only_postcheck' : 'prospective_read_only_preflight',
'assets_published' => $installed, 'new_grants_or_business_commands' => false];
file_put_contents($root.'/docs/proofs/'.($installed ? 'compras-standalone-pilot-activation-check.json' : 'compras-standalone-pilot-activation-preflight.json'), json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
diff --git a/scripts/check-standalone-pilot-profiles.php b/scripts/check-standalone-pilot-profiles.php
index 8f6805c..574b2c3 100644
--- a/scripts/check-standalone-pilot-profiles.php
+++ b/scripts/check-standalone-pilot-profiles.php
@@ -65,11 +65,12 @@ $frames = static function (): array {
$before = $frames();
app(StandaloneRuntime::class)->assertLoadedPackages();
$results = [];
+$extraPaths = config('order_cancellation.enabled') === true ? ['/ordens/cancelamentos'] : [];
foreach (['admin', 'procurement', 'finance', 'warehouse'] as $role) {
$actor = User::query()->where('email', 'avaliacao-'.$role.'@example.test')->firstOrFail();
foreach (['/dashboard', '/requisicoes', '/projectos-imobilizado', '/ordens-operacionais', '/administracao/financeiro',
'/administracao/prazos-aprovacao', '/administracao/revisao-urgencias', '/requisicoes/urgencias/revisoes',
- '/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa'] as $path) {
+ '/conflitos', '/auditoria/privada', '/supplier-payments', '/general-ledger/cycle', '/compras/pesquisa', ...$extraPaths] as $path) {
$app->forgetScopedInstances();
$request = Request::create('http://127.0.0.1:8005'.$path, 'GET', server: ['REMOTE_ADDR' => '127.0.0.1',
'HTTP_ACCEPT' => 'application/json', 'HTTP_X_INERTIA' => 'true']);
diff --git a/scripts/check-standalone-published-assets.mjs b/scripts/check-standalone-published-assets.mjs
index 3b062bf..84da5aa 100644
--- a/scripts/check-standalone-published-assets.mjs
+++ b/scripts/check-standalone-published-assets.mjs
@@ -2,7 +2,23 @@ import fs from 'node:fs/promises';
import crypto from 'node:crypto';
import assert from 'node:assert/strict';
-const plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8'));
+let plan = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation-proposal.json', 'utf8'));
+let interfaceDelta = false;
+try {
+ const result = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication.json', 'utf8'));
+ const bytes = await fs.readFile('docs/proofs/analytics-print-publication-proposal.json');
+ const proposal = JSON.parse(bytes);
+ const approval = JSON.parse(await fs.readFile('docs/proofs/analytics-print-publication-authorization.json', 'utf8'));
+ assert.equal(result.pilot_state ?? result.state, 'passed');
+ assert.equal(approval.state, 'approved');
+ assert.equal(approval.proposal_sha256, crypto.createHash('sha256').update(bytes).digest('hex'));
+ assert.equal(result.manifest_sha256, proposal.manifest_sha256);
+ assert.equal(proposal.previous_manifest_sha256, plan.frontend.manifest_sha256);
+ plan = { ...plan, frontend: proposal };
+ interfaceDelta = true;
+} catch (error) {
+ if (error.code !== 'ENOENT') throw error;
+}
const activation = JSON.parse(await fs.readFile('docs/proofs/compras-standalone-pilot-activation.json', 'utf8'));
assert.equal(activation.state, 'passed');
assert.equal(plan.target, 'http://127.0.0.1:8005');
@@ -29,9 +45,10 @@ const page = JSON.parse(bootstrap[1]);
assert.equal(page.props.auth.user, null);
assert.deepEqual(page.props.commonFinanceNavigation, { payments: false, ledger: false, configuration: false });
const manifest = JSON.parse(await fs.readFile('public/build/manifest.json', 'utf8'));
-assert.ok(html.includes(manifest['resources/js/app.tsx'].file));
-const proof = { date: new Date().toISOString(), state: 'passed', pilot_asset_responses_and_hashes: verified,
- public_domain_html_delivers_new_entry: true, public_anonymous_identity_preserved: true,
+const publicCurrent = html.includes(manifest['resources/js/app.tsx'].file);
+const proof = { date: new Date().toISOString(), state: publicCurrent ? 'passed' : 'pilot_passed_public_installation_pending', pilot_asset_responses_and_hashes: verified,
+ public_domain_html_delivers_new_entry: publicCurrent, public_anonymous_identity_preserved: true,
private_finance_navigation_not_exposed_publicly: true, new_grants_or_business_operations: false };
-await fs.writeFile('docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n');
+await fs.writeFile(interfaceDelta ? 'docs/proofs/analytics-print-publication-http.json' : 'docs/proofs/compras-standalone-published-assets.json', JSON.stringify(proof, null, 2) + '\n');
console.log(JSON.stringify(proof));
+if (!publicCurrent) process.exitCode = 1;
diff --git a/scripts/install-replenishment-task.php b/scripts/install-replenishment-task.php
new file mode 100644
index 0000000..6860d8f
--- /dev/null
+++ b/scripts/install-replenishment-task.php
@@ -0,0 +1,136 @@
+ $hash) {
+ if (! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
+ throw new LogicException('REPLENISHMENT_TASK_SOURCE_CHANGED');
+ }
+}
+if (! hash_equals($plan['php_sha256'], hash_file('sha256', $plan['php_executable']))) {
+ throw new LogicException('REPLENISHMENT_GUI_EXECUTABLE_CHANGED');
+}
+$run = static function (array $command, int $timeout = 15) use ($root): string {
+ $process = new Process($command, $root, timeout: $timeout);
+ $process->run();
+ if (! $process->isSuccessful()) {
+ throw new RuntimeException('REPLENISHMENT_TASK_NATIVE_COMMAND_FAILED');
+ }
+
+ return $process->getOutput();
+};
+$scheduler = getenv('SystemRoot').'/System32/schtasks.exe';
+$tasks = $run([$scheduler, '/Query', '/FO', 'CSV', '/NH']);
+foreach (preg_split('/\r?\n/', trim($tasks)) as $row) {
+ $name = str_getcsv($row, escape: '')[0] ?? '';
+ if ($name === '\\'.$plan['task_name']) {
+ throw new LogicException('REPLENISHMENT_TASK_ALREADY_EXISTS_NEVER_OVERWRITE');
+ }
+}
+$health = json_decode(trim($run([PHP_BINARY, 'scripts/replenishment-pilot-task.php', '--check'])), true, 32, JSON_THROW_ON_ERROR);
+if ($health['state'] !== 'ready' || $health['database_enforced_read_only'] !== true) {
+ throw new LogicException('REPLENISHMENT_TASK_PILOT_NOT_READY');
+}
+$identity = str_getcsv(trim($run([getenv('SystemRoot').'/System32/whoami.exe', '/user', '/fo', 'csv', '/nh'])), escape: '');
+$sid = $identity[1] ?? '';
+if (! preg_match('/^S-1-\d+(?:-\d+)+$/D', $sid)) {
+ throw new LogicException('REPLENISHMENT_TASK_CURRENT_USER_UNAVAILABLE');
+}
+$escape = static fn (string $value) => htmlspecialchars($value, ENT_XML1 | ENT_QUOTES, 'UTF-8');
+$start = (new DateTimeImmutable('now', new DateTimeZone('Africa/Johannesburg')))->modify('+1 minute')->format('c');
+$php = $escape($plan['php_executable']);
+$arguments = $escape('"'.$root.'/scripts/replenishment-pilot-task.php" --once');
+$directory = 'C:/laragon/data/compras/tasks/replenishment-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
+if (! mkdir($directory, 0700, true)) {
+ throw new LogicException('REPLENISHMENT_TASK_PRIVATE_STORAGE');
+}
+$settingsPath = 'C:/laragon/data/sgf-tempo/secrets/payables-demo-compras.json';
+$settings = json_decode(file_get_contents($settingsPath), true, 32, JSON_THROW_ON_ERROR);
+if ($apply) {
+ // Private recovery material; no settings, credentials or business rows are published.
+ copy($settingsPath, $directory.'/settings.private.json');
+ $dump = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_dump.exe', '--format=custom', '--file='.$directory.'/before.dump',
+ '--dbname='.$settings['DB_DATABASE']], $root, ['PGHOST' => $settings['DB_HOST'], 'PGPORT' => $settings['DB_PORT'],
+ 'PGUSER' => $settings['DB_USERNAME'], 'PGPASSWORD' => $settings['DB_PASSWORD']], timeout: 120);
+ $dump->run();
+ if (! $dump->isSuccessful() || ! is_file($directory.'/before.dump')) {
+ throw new LogicException('REPLENISHMENT_PRIVATE_BACKUP_FAILED');
+ }
+ $connection = new PDO('pgsql:host=127.0.0.1;port=5432;dbname='.$settings['DB_DATABASE'], $settings['DB_USERNAME'], $settings['DB_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+ $connection->beginTransaction();
+ $connection->exec('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
+ $baseline = [];
+ foreach ($connection->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN) as $table) {
+ $rows = $connection->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
+ $baseline[$table] = ['rows' => count($rows), 'sha256' => hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR))];
+ }
+ $connection->commit();
+ file_put_contents($directory.'/baseline.private.json', json_encode($baseline, JSON_THROW_ON_ERROR));
+}
+$working = $escape($root);
+$xml = ''.
+ ''.
+ 'Compras pilot: native replenishment under existing approved policies only.'.
+ ''.$start.'truePT1Mfalse'.
+ 'true'.$sid.''.
+ ''.$sid.'InteractiveTokenLeastPrivilege'.
+ 'IgnoreNewfalsefalsetruetruetruetruePT1M'.
+ ''.$php.''.$arguments.''.$working.'';
+$document = WindowsTaskXml::parse($xml);
+$xpath = new DOMXPath($document);
+$xpath->registerNamespace('t', 'http://schemas.microsoft.com/windows/2004/02/mit/task');
+if ($xpath->query('//t:Exec')->length !== 1 || $xpath->evaluate('string(//t:LogonType)') !== 'InteractiveToken'
+ || $xpath->evaluate('string(//t:RunLevel)') !== 'LeastPrivilege' || $xpath->query('//t:Triggers/*')->length !== 2) {
+ throw new LogicException('REPLENISHMENT_TASK_XML_SCOPE');
+}
+$xmlPath = $directory.'/task.private.xml';
+$fileBytes = WindowsTaskXml::encode($xml);
+file_put_contents($xmlPath, $fileBytes);
+$record = ['date' => gmdate('c'), 'state' => 'preview', 'task_name' => $plan['task_name'], 'current_user_only' => true,
+ 'credentials_stored' => false, 'run_level' => 'Limited', 'poll_interval' => 'PT1M', 'overlap' => 'IgnoreNew', 'time_limit' => 'PT1M',
+ 'private_definition' => $xmlPath, 'xml_sha256' => hash('sha256', $fileBytes), 'pilot_ready' => true,
+ 'eligible_requests' => $health['health']['work']['pending'], 'native_command' => $plan['command'],
+ 'task_installed_or_started' => false, 'powershell_execution_policy_changed' => false];
+if ($apply) {
+ $record['private_backup_directory'] = $directory;
+ $record['database_backup_sha256'] = hash_file('sha256', $directory.'/before.dump');
+ $record['baseline_tables'] = count($baseline);
+}
+if (! $apply) {
+ file_put_contents($root.'/docs/proofs/replenishment-task-preflight.json', json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+ echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
+ exit;
+}
+$approvalPath = $root.'/docs/proofs/replenishment-task-authorization.json';
+$approval = is_file($approvalPath) ? json_decode(file_get_contents($approvalPath), true, 32, JSON_THROW_ON_ERROR) : [];
+if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== $plan['scope']
+ || ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))) {
+ throw new LogicException('REPLENISHMENT_TASK_NOT_AUTHORIZED');
+}
+$resultPath = $root.'/docs/proofs/replenishment-task-installation.json';
+if (is_file($resultPath)) {
+ throw new LogicException('REPLENISHMENT_TASK_PREVIOUS_RESULT');
+}
+$run([$scheduler, '/Create', '/TN', $plan['task_name'], '/XML', $xmlPath]); // No /F: never replace another task.
+$installed = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
+file_put_contents($directory.'/installed.private.xml', $installed);
+ReplenishmentTaskDefinition::assertMatches($xml, $installed);
+$record['state'] = 'installed';
+$record['task_installed_or_started'] = true;
+file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+$run([$scheduler, '/Run', '/TN', $plan['task_name']]);
+$record['initial_pass_requested'] = true;
+$record['state'] = 'awaiting_passage_verification';
+file_put_contents($resultPath, json_encode($record, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($record, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/scripts/order-cancellation-http.mjs b/scripts/order-cancellation-http.mjs
index afaf68f..ceefc16 100644
--- a/scripts/order-cancellation-http.mjs
+++ b/scripts/order-cancellation-http.mjs
@@ -1,23 +1,14 @@
-import fs from 'node:fs/promises';
-import assert from 'node:assert/strict';
-const source = await fs.readFile('scripts/supplier-evaluation-check.mjs', 'utf8');
-const common = source.slice(source.indexOf('const base ='), source.indexOf('const author ='));
-await new Function('fs', 'assert', 'return (async()=>{' + common + `
- const records=[];
- for(const role of ['admin','procurement','finance']) {
- const viewer=client(); await viewer.enter(role);
- assert.equal((await viewer.request('/contexto','POST',{area:'procurement',option:'procurement.internal'})).status,302);
- assert.equal((await viewer.request('/ordens/cancelamentos','GET',undefined,false)).status,503);
- const orders=await viewer.request('/ordens'); assert.equal(orders.status,200);
- let checked=0;
- for(const order of orders.page.props.orders.data.slice(0,1)) {
- const detail=await viewer.request('/ordens/'+order.id); assert.equal(detail.status,200);
- assert.equal(detail.page.props.orderCancellation.enabled,false);
- assert.equal(detail.page.props.orderCancellation.canRequest,false);
- assert.equal(detail.page.props.orderCancellationAvailable,false); checked++;
- }
- records.push({role,disabledStatus:503,ordersChecked:checked});
- }
- await fs.writeFile('docs/proofs/issued-order-cancellation-http.json',JSON.stringify({checked_at:new Date().toISOString(),environment:base,result:'passed',records,business_commands:false,policy_commands:false,cancellation_commands:false,visual_review:false},null,2));
- console.log('Circuito desligado no piloto; ordens existentes consultadas sem comandos de cancelamento.');
-` + '})()')(fs, assert);
+// Compatibility entry point: no evaluation login or HTTP mutation is performed.
+// Historical issued-order-cancellation-http.json is deliberately preserved.
+import { spawnSync } from 'node:child_process';
+import { fileURLToPath } from 'node:url';
+
+if (process.argv.length !== 3 || process.argv[2] !== '--read-only') {
+ throw new Error('Use --read-only for in-process GET checks with existing pilot actors.');
+}
+const root = fileURLToPath(new URL('../', import.meta.url));
+const result = spawnSync('php', ['scripts/check-standalone-pilot-profiles.php', '--read-only'], {
+ cwd: root, stdio: 'inherit', windowsHide: true,
+});
+if (result.error) throw result.error;
+process.exitCode = result.status ?? 1;
diff --git a/scripts/order-cancellation-pilot-check.php b/scripts/order-cancellation-pilot-check.php
index 8bf520d..f625fe6 100644
--- a/scripts/order-cancellation-pilot-check.php
+++ b/scripts/order-cancellation-pilot-check.php
@@ -1,42 +1,7 @@
make(Kernel::class)->bootstrap();
-$base = DB::connection('pgsql')->getConfig();
-unset($base['name']);
-config(['database.connections.cancel_pilot_read' => [...$base, 'url' => null, 'host' => $settings['DB_HOST'], 'port' => $settings['DB_PORT'],
- 'database' => $settings['DB_DATABASE'], 'username' => $settings['DB_USERNAME'], 'password' => $settings['DB_PASSWORD']]]);
-$db = DB::connection('cancel_pilot_read');
-$result = $db->transaction(function () use ($db, $settings) {
- $db->statement('SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY');
- $identity = $db->selectOne('select current_database() as db, current_user as role');
- if ($identity->db !== $settings['DB_DATABASE'] || $identity->role !== $settings['DB_USERNAME']) {
- throw new LogicException('Identity mismatch.');
- }
- $schema = Schema::connection('cancel_pilot_read');
- $installed = $schema->hasTable('order_cancellations');
-
- return ['checked_at' => gmdate('c'), 'environment' => 'http://127.0.0.1:8005', 'result' => 'passed',
- 'schema_installed' => $installed, 'migration_applied' => $db->table('migrations')->where('migration', '2026_11_03_000003_create_order_cancellations')->exists(),
- 'cancellations' => $installed ? $db->table('order_cancellations')->count() : 0,
- 'policies' => $schema->hasTable('order_cancellation_policies') ? $db->table('order_cancellation_policies')->count() : 0,
- 'mfa_accounts_enrolled' => $db->table('users')->where(fn ($q) => $q->whereNotNull('two_factor_secret')->orWhereNotNull('two_factor_recovery_codes')->orWhereNotNull('two_factor_confirmed_at'))->count(),
- 'audit_permission_profiles' => $db->table('organization_profiles')->whereJsonContains('permissions', 'audit_metadata_read')->count(),
- 'access_version' => (int) $db->table('organization_access')->where('tenant_id', 1)->value('version'), 'business_commands' => false];
-});
-if ($result['schema_installed'] || $result['migration_applied'] || $result['cancellations'] || $result['policies'] || $result['mfa_accounts_enrolled'] || $result['audit_permission_profiles']) {
- throw new LogicException('Pilot state differs from the authorized disabled scope.');
-}
-file_put_contents($root.'/docs/proofs/issued-order-cancellation-pilot.json', json_encode($result, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES).PHP_EOL);
-echo 'Pilot inspected read-only: circuit uninstalled and disabled; no policies, cancellations or MFA enrollments.'.PHP_EOL;
+require __DIR__.'/check-order-cancellation-pilot.php';
diff --git a/scripts/publish-analytics-print.php b/scripts/publish-analytics-print.php
new file mode 100644
index 0000000..8eb806f
--- /dev/null
+++ b/scripts/publish-analytics-print.php
@@ -0,0 +1,62 @@
+ hash_file('sha256', $file), $protected);
+foreach ($plan['files'] as $file => $hash) {
+ if (! str_starts_with($file, 'assets/') || str_contains($file, '..') || ! hash_equals($hash, hash_file('sha256', $candidate.'/'.$file))
+ || (is_file($root.'/public/build/'.$file) && ! hash_equals($hash, hash_file('sha256', $root.'/public/build/'.$file)))) {
+ throw new LogicException('Interface candidate missing or existing immutable asset differs.');
+ }
+}
+$backup = 'C:/laragon/data/compras/backups/analytics-print-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
+if (! mkdir($backup, 0700, true) || ! copy($manifestPath, $backup.'/manifest.before.json')
+ || ! hash_equals($plan['previous_manifest_sha256'], hash_file('sha256', $backup.'/manifest.before.json'))) {
+ throw new LogicException('Interface manifest recovery copy failed.');
+}
+foreach ($plan['files'] as $file => $hash) {
+ $target = $root.'/public/build/'.$file;
+ if (! is_file($target) && ! copy($candidate.'/'.$file, $target)) {
+ throw new LogicException('Interface asset copy failed before manifest selection.');
+ }
+ if (! hash_equals($hash, hash_file('sha256', $target))) {
+ throw new LogicException('Published asset bytes differ.');
+ }
+}
+$temporary = $manifestPath.'.analytics-'.bin2hex(random_bytes(6)).'.tmp';
+if (! copy($candidate.'/manifest.json', $temporary)
+ || ! hash_equals($plan['manifest_sha256'], hash_file('sha256', $temporary))
+ || ! hash_equals($plan['previous_manifest_sha256'], hash_file('sha256', $manifestPath))
+ || ! rename($temporary, $manifestPath)) {
+ throw new LogicException('Atomic interface manifest selection failed.');
+}
+if ($hashes !== array_map(static fn ($file) => hash_file('sha256', $file), $protected)) {
+ throw new LogicException('Protected configuration changed; inspect without overwriting concurrent edits.');
+}
+$result = ['date' => gmdate('c'), 'state' => 'passed', 'authorization' => 'analytics-print-publication-authorization.json',
+ 'manifest_sha256' => $plan['manifest_sha256'], 'previous_manifest_sha256' => $plan['previous_manifest_sha256'],
+ 'backup_directory' => $backup, 'assets_verified' => count($plan['files']), 'old_assets_preserved' => true,
+ 'database_commands_or_settings_changes' => false, 'public_runtime_activation' => false, 'application_complete' => false];
+file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/scripts/repair-approval-deadlines-gui.php b/scripts/repair-approval-deadlines-gui.php
new file mode 100644
index 0000000..5946145
--- /dev/null
+++ b/scripts/repair-approval-deadlines-gui.php
@@ -0,0 +1,74 @@
+mustRun();
+
+ return $process->getOutput();
+};
+$scheduler = getenv('SystemRoot').'/System32/schtasks.exe';
+$before = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
+$installation = json_decode(file_get_contents($root.'/docs/proofs/approval-deadlines-task-installation.json'), true, 32, JSON_THROW_ON_ERROR);
+$original = file_get_contents($installation['private_definition']);
+if (! hash_equals($installation['private_installed_xml_sha256'], hash('sha256', $original))
+ || DeadlineTaskGuiAction::canonical($original) !== DeadlineTaskGuiAction::canonical($before)) {
+ throw new LogicException('Installed task differs from its original verified definition.');
+}
+DeadlineTaskGuiAction::replacement($before, $old, $new);
+if ($argv[1] === '--preview') {
+ echo json_encode(['state' => 'preview', 'same_task_script_and_policy' => true, 'task_changed' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+ exit;
+}
+$directory = 'C:/laragon/data/compras/tasks/deadline-gui-'.gmdate('Ymd-His').'-'.bin2hex(random_bytes(6));
+if (! mkdir($directory, 0700, true) || file_put_contents($directory.'/before.private.xml', WindowsTaskXml::encode($before)) === false) {
+ throw new LogicException('Private original task backup required.');
+}
+// Native cmdlet changes the action only; no script file or execution-policy override.
+$command = <<<'POWERSHELL'
+$ErrorActionPreference='Stop'
+$task=Get-ScheduledTask -TaskName 'Compras-Pilot-Approval-Deadlines' -TaskPath '\'
+if($task.Actions.Count -ne 1 -or $task.Actions[0].Execute -ne 'C:/Users/macbook/.config/investmoz/php-8.5.11/php.exe'){throw 'Task action changed'}
+$action=New-ScheduledTaskAction -Execute 'C:/Users/macbook/.config/investmoz/php-8.5.11/php-win.exe' -Argument $task.Actions[0].Arguments -WorkingDirectory $task.Actions[0].WorkingDirectory
+Set-ScheduledTask -TaskName 'Compras-Pilot-Approval-Deadlines' -TaskPath '\' -Action $action | Out-Null
+POWERSHELL;
+$run([getenv('SystemRoot').'/System32/WindowsPowerShell/v1.0/powershell.exe', '-NoProfile', '-NonInteractive', '-Command', $command]);
+$after = $run([$scheduler, '/Query', '/TN', $plan['task_name'], '/XML']);
+DeadlineTaskGuiAction::assertConserved($before, $after, $old, $new);
+file_put_contents($directory.'/after.private.xml', WindowsTaskXml::encode($after));
+$run([$scheduler, '/Run', '/TN', $plan['task_name']]);
+$result = ['date' => gmdate('c'), 'state' => 'definition_verified_awaiting_passage', 'task_name' => $plan['task_name'],
+ 'authority' => ['approval-deadlines-task-authorization.json', 'inventory-conversion-pilot-authorization.json'],
+ 'private_backup' => $directory, 'old_executable' => $old, 'new_executable' => $new, 'gui_binary_sha256' => hash_file('sha256', $new),
+ 'only_executable_changed' => true, 'helper_sha256' => hash_file('sha256', $root.'/'.$plan['action_script']),
+ 'arguments_working_directory_triggers_principal_privileges_overlap_and_limit_preserved' => true,
+ 'powershell_execution_policy_changed' => false, 'business_policy_or_grants_changed' => false,
+ 'reference' => 'https://www.php.net/manual/en/features.commandline.php'];
+file_put_contents($resultPath, json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/scripts/replenishment-pilot-task.php b/scripts/replenishment-pilot-task.php
new file mode 100644
index 0000000..099920b
--- /dev/null
+++ b/scripts/replenishment-pilot-task.php
@@ -0,0 +1,58 @@
+ $hash) {
+ if (! hash_equals($hash, hash_file('sha256', $root.'/'.$file))) {
+ throw new LogicException('Reviewed replenishment task source changed.');
+ }
+}
+if (! $check) {
+ $approval = json_decode(file_get_contents($root.'/docs/proofs/replenishment-task-authorization.json'), true, 32, JSON_THROW_ON_ERROR);
+ if (($approval['state'] ?? null) !== 'approved' || ($approval['scope'] ?? null) !== 'existing_pilot_replenishment_task'
+ || ! hash_equals($approval['proposal_sha256'], hash_file('sha256', $planPath))) {
+ throw new LogicException('Replenishment passage not authorized.');
+ }
+}
+foreach ([...$settings, 'DB_CONNECTION' => 'pgsql', 'DB_URL' => '', 'PGOPTIONS' => $check ? '-c default_transaction_read_only=on' : '',
+ 'CACHE_STORE' => $check ? 'array' : ($settings['CACHE_STORE'] ?? 'file'), 'LOG_CHANNEL' => 'stderr'] as $key => $value) {
+ putenv($key.'='.$value);
+ $_ENV[$key] = $_SERVER[$key] = $value;
+}
+$app = require $root.'/bootstrap/app.php';
+$app->make(Kernel::class)->bootstrap();
+app(StandaloneRuntime::class)->assertLoadedPackages();
+if (! app(ReplenishmentQueue::class)->ready()) {
+ throw new LogicException('Native replenishment capability unavailable.');
+}
+if ($check) {
+ if (DB::selectOne('SHOW default_transaction_read_only')->default_transaction_read_only !== 'on') {
+ throw new LogicException('Read-only task preflight required.');
+ }
+ echo json_encode(['state' => 'ready', 'database_enforced_read_only' => true,
+ 'health' => app(ReplenishmentQueue::class)->health(), 'task_started' => false], JSON_THROW_ON_ERROR).PHP_EOL;
+ exit;
+}
+// The native command owns process exclusion, durable recovery and bound heartbeat.
+exit(Artisan::call('sgc:replenishment-tick'));
diff --git a/scripts/requisition-ledger-qa-check.mjs b/scripts/requisition-ledger-qa-check.mjs
index c9dc855..34a7d23 100644
--- a/scripts/requisition-ledger-qa-check.mjs
+++ b/scripts/requisition-ledger-qa-check.mjs
@@ -14,9 +14,13 @@ const componentProfile = process.argv.includes('--standalone-component-profile')
if (componentProfile && (!standaloneOnly || financePreview)) throw Error('Component profile requires its own standalone invocation');
if (financePreview && !standaloneOnly) throw Error('Finance preview requires the isolated standalone runtime');
const standaloneUpgrade = process.argv.includes('--standalone-upgrade-only');
-const standaloneBusiness = process.argv.includes('--standalone-business-only') || standaloneUpgrade;
+const standaloneAnalyticsPreview = process.argv.includes('--standalone-analytics-preview');
+const standaloneCancellationPreview = process.argv.includes('--standalone-cancellation-preview');
+const standaloneConversionPreview = process.argv.includes('--standalone-conversion-preview') || standaloneCancellationPreview || standaloneAnalyticsPreview;
+const standaloneConversion = process.argv.includes('--standalone-conversion-only') || standaloneConversionPreview;
+const standaloneBusiness = process.argv.includes('--standalone-business-only') || standaloneUpgrade || standaloneConversion;
if (standaloneOnly && process.argv.slice(2).some(flag => !['--standalone-runtime-only', '--standalone-finance-preview', '--standalone-component-profile'].includes(flag))) throw Error('Standalone composition requires its own isolated invocation');
-if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== (standaloneUpgrade ? '--standalone-upgrade-only' : '--standalone-business-only'))) throw Error('Standalone business regression requires its own isolated invocation');
+if (standaloneBusiness && process.argv.slice(2).some(flag => flag !== (standaloneAnalyticsPreview ? '--standalone-analytics-preview' : standaloneCancellationPreview ? '--standalone-cancellation-preview' : standaloneConversionPreview ? '--standalone-conversion-preview' : standaloneConversion ? '--standalone-conversion-only' : standaloneUpgrade ? '--standalone-upgrade-only' : '--standalone-business-only'))) throw Error('Standalone business regression requires its own isolated invocation');
const standaloneRoot = path.join(workspace, 'storage/framework/testing/compras-standalone-80483320a54af6f1');
const standalonePin = '80483320a54af6f123498e43c1435a20922455f65860be88bd259e90efcbc0b7';
const standaloneArchivePin = 'bbc1d953061d5a297d4336a3cb746a11af5d6930c6fc7d0b5d64b5bff3046e76';
@@ -132,6 +136,18 @@ try {
createdDatabase = true;
sql(`REVOKE ALL ON DATABASE ${database} FROM PUBLIC;`);
let activeStandaloneRoot = standaloneRoot;
+ let inventoryRoot = null;
+ if (standaloneConversion) {
+ const pin = '8608e6551dea6448983ead401ba900b440ffdeb1446ce52de6509d5eba0e87bd';
+ const archive = path.join(privateParent, `compras-inventory-${pin}.zip`);
+ if (fs.lstatSync(archive).isSymbolicLink() || crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== 'dbb7e3d172f2ce5168f678993b96d9d94ce2e0c1737b581743cf2bbb6d4d00b8') throw Error('Pinned inventory archive mismatch');
+ inventoryRoot = path.join(root, 'inventory-runtime');
+ fs.mkdirSync(inventoryRoot);
+ const code = '$z=new ZipArchive; if($z->open($argv[1])!==true||$z->numFiles!==4||!$z->extractTo($argv[2]))throw new LogicException("Owned inventory extraction failed");$z->close();';
+ const extracted = spawnSync('php', ['-r', code, archive, inventoryRoot], { windowsHide: true, encoding: 'utf8' });
+ if (extracted.status !== 0) throw Error('Owned inventory extraction failed');
+ verifyPrivateRuntime(inventoryRoot, pin, 3);
+ }
if (standaloneOnly) {
const archive = standaloneRoot+'.zip';
if (fs.lstatSync(archive).isSymbolicLink() || crypto.createHash('sha256').update(fs.readFileSync(archive)).digest('hex') !== standaloneArchivePin) throw Error('Pinned standalone archive mismatch');
@@ -180,6 +196,8 @@ try {
environment.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
environment.COMPRAS_STANDALONE_BUSINESS_QA = standaloneBusiness ? '1' : '0';
environment.COMPRAS_STANDALONE_UPGRADE_QA = standaloneUpgrade ? '1' : '0';
+ environment.COMPRAS_STANDALONE_CONVERSION_QA = standaloneConversion ? '1' : '0';
+ if (inventoryRoot !== null) environment.COMPRAS_INVENTORY_ROOT = inventoryRoot;
}
if (frozenRuntime) {
environment.COMMON_FINANCE_BUNDLE_ROOT = financeRoot;
@@ -234,13 +252,75 @@ try {
if (setupOnly || !frozenRuntime || !process.argv.includes('--integrated-schema')) throw Error('Expiry history regression requires the complete pinned isolated composition');
args.splice(0, args.length, 'vendor/bin/pest', '--compact', 'tests/Feature/RequisitionBudgetCyclesTest.php', '--filter=native expiry returns the same request');
}
- if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', standaloneUpgrade ? 'tests/Feature/StandaloneComponentUpgradeTest.php' : 'tests/Feature/StandaloneBusinessCompositionTest.php');
+ if (standaloneBusiness) args.splice(0, args.length, 'vendor/bin/pest', '--compact', standaloneConversion ? 'tests/Conversion/ReceiptQuantityConversionTest.php' : standaloneUpgrade ? 'tests/Feature/StandaloneComponentUpgradeTest.php' : 'tests/Feature/StandaloneBusinessCompositionTest.php');
+ if (standaloneConversionPreview) args.splice(0, args.length, 'artisan', 'migrate', '--force', '--no-interaction', '--quiet');
const result = spawnSync('php', args, {
cwd: process.cwd(), windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: environment,
});
if (!setupOnly || result.status !== 0) process.stdout.write((result.stdout || '').replaceAll(password, '[private]'));
process.stderr.write((result.stderr || '').replaceAll(password, '[private]'));
process.exitCode = result.status === 0 ? 0 : 1;
+ if (result.status === 0 && standaloneConversion) {
+ const prepared = spawnSync('php', ['tests/Concurrency/unit-conversion-worker.php', database, 'prepare-runtime'], {
+ cwd: workspace, windowsHide: true, encoding: 'utf8', env: environment,
+ });
+ if (prepared.status !== 0 || prepared.stdout !== 'synthetic_standalone_inventory_prepared') throw Error('Inventory runtime preparation failed: '+(prepared.stderr || prepared.stdout || ''));
+ const operationalEnvironment = { ...environment, APP_ENV: 'standalone-qa', COMPRAS_RUNTIME_ENABLED: 'true',
+ COMPRAS_RUNTIME_PREPARE_ONLY: 'false', COMPRAS_INVENTORY_CONVERSION_ENABLED: 'true' };
+ for (const match of fs.readFileSync(path.join(workspace, 'config/standalone-runtime.php'), 'utf8').matchAll(/env\('(COMPRAS_[A-Z_]+_ENABLED)'/g)) operationalEnvironment[match[1]] = 'true';
+ if (standaloneConversionPreview) {
+ if (standaloneCancellationPreview) operationalEnvironment.COMPRAS_ORDER_CANCELLATION_ENABLED = 'true';
+ const { reviewStandaloneInventory } = await import('./standalone-inventory-preview.mjs');
+ await reviewStandaloneInventory({ workspace, root, database, environment: operationalEnvironment, cancellation: standaloneCancellationPreview, analytics: standaloneAnalyticsPreview });
+ } else {
+ const raced = spawnSync('php', ['tests/Concurrency/unit-conversion-worker.php', database, 'race'], {
+ cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env: operationalEnvironment,
+ });
+ process.stdout.write((raced.stdout || '').replaceAll(password, '[private]'));
+ process.stderr.write((raced.stderr || '').replaceAll(password, '[private]'));
+ if (raced.status !== 0) throw Error('Operational inventory contention failed');
+ console.log(JSON.stringify({ inventory_archive_extracted: true, operational_environment: 'standalone-qa', qa_conversion_disabled: true, operational_changes: false }));
+ }
+ if (!standaloneConversionPreview || standaloneCancellationPreview) {
+ operationalEnvironment.SGC_STANDALONE_QA_ROOT = root;
+ operationalEnvironment.COMPRAS_QA_ORIGINAL_INSTALLATION_ID = environment.COMPRAS_RUNTIME_INSTALLATION_ID;
+ const inspectInventory = (mode, env) => {
+ const check = spawnSync('php', ['tests/Support/standalone-inventory-recovery-worker.php', env.DB_DATABASE, mode], {
+ cwd: workspace, windowsHide: true, encoding: 'utf8', maxBuffer: 1024 * 1024, env,
+ });
+ if (check.status !== 0) throw Error('Isolated inventory recovery check failed: '+(check.stderr || check.stdout || '').replaceAll(env.DB_PASSWORD, '[private]'));
+ try { return JSON.parse(check.stdout); }
+ catch { throw Error('Inventory recovery returned an invalid receipt: '+(check.stdout || '').replaceAll(env.DB_PASSWORD, '[private]').slice(0, 2000)); }
+ };
+ const readMode = standaloneCancellationPreview ? 'read-cancellation' : 'read';
+ const original = inspectInventory(readMode, operationalEnvironment);
+ const pgInventory = (binary, args, env) => {
+ const check = spawnSync(path.join(pg, binary), args, { windowsHide: true, encoding: 'utf8',
+ env: { ...process.env, PGHOST: '127.0.0.1', PGPORT: '55439', PGUSER: env.DB_USERNAME, PGPASSWORD: env.DB_PASSWORD } });
+ if (check.status !== 0) throw Error('Synthetic inventory backup/restore failed');
+ };
+ const dump = path.join(root, 'inventory-recovery.dump');
+ pgInventory('pg_dump.exe', ['--format=custom', '--no-owner', '--no-acl', '--file='+dump, '--dbname='+database], operationalEnvironment);
+ const restoredPassword = crypto.randomBytes(30).toString('hex');
+ restoreRole = role+'_restored';
+ sql(`CREATE ROLE ${restoreRole} LOGIN PASSWORD '${restoredPassword}' NOSUPERUSER NOCREATEDB NOCREATEROLE NOREPLICATION NOBYPASSRLS;`);
+ restoreDatabase = database+'_restored';
+ sql(`CREATE DATABASE ${restoreDatabase} OWNER ${restoreRole}; REVOKE ALL ON DATABASE ${restoreDatabase} FROM PUBLIC;`);
+ const restored = { ...operationalEnvironment, DB_DATABASE: restoreDatabase, DB_USERNAME: restoreRole, DB_PASSWORD: restoredPassword };
+ pgInventory('pg_restore.exe', ['--no-owner', '--no-acl', '--exit-on-error', '--dbname='+restoreDatabase, dump], restored);
+ const rejected = inspectInventory('reject-restore', restored);
+ if (rejected.rejected !== true) throw Error('Restored inventory binding was not refused');
+ restored.COMPRAS_RUNTIME_INSTALLATION_ID = crypto.randomUUID();
+ const rebound = inspectInventory('rebind', { ...restored, COMPRAS_RUNTIME_ENABLED: 'false', COMPRAS_RUNTIME_PREPARE_ONLY: 'true' });
+ if (rebound.state !== 'rebound') throw Error('Inventory recovery binding not recorded');
+ const recovered = inspectInventory(readMode, restored);
+ if (JSON.stringify(original) !== JSON.stringify(recovered)) throw Error('Recovered inventory business data or legacy installation changed');
+ console.log(JSON.stringify({ inventory_backup_restored: !standaloneCancellationPreview, cancellation_backup_restored: standaloneCancellationPreview,
+ incompatible_binding_rejected: true, explicit_rebind: true, preserved_business_tables: recovered.business_tables,
+ recovered_converted_movements: recovered.converted_movements, recovered_cancellations: recovered.approved_cancellations,
+ source_cycle: recovered.source_cycle, exact_replays: recovered.exact_replays }));
+ }
+ }
if (result.status === 0 && componentProfile) {
const profile = spawnSync('php', ['tests/Support/standalone-runtime-worker.php', database, 'prepare-component-profile'], {
cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'standalone-qa', SGC_STANDALONE_QA_ROOT: root },
diff --git a/scripts/standalone-inventory-preview.mjs b/scripts/standalone-inventory-preview.mjs
new file mode 100644
index 0000000..d685c6e
--- /dev/null
+++ b/scripts/standalone-inventory-preview.mjs
@@ -0,0 +1,64 @@
+// Synthetic loopback preview, normal application authentication, no installed login shortcut.
+import fs from 'node:fs';
+import path from 'node:path';
+import crypto from 'node:crypto';
+import { spawn, spawnSync } from 'node:child_process';
+import { createServer } from 'node:net';
+
+export async function reviewStandaloneInventory({ workspace, root, database, environment, cancellation = false, analytics = false }) {
+ const parent = fs.realpathSync(path.join(workspace, 'storage/framework/testing'));
+ const match = /^compras_receipts_test_([a-f0-9]{12})$/.exec(database);
+ if (!match || path.dirname(fs.realpathSync(root)) !== parent || path.basename(root) !== `rq01-ledger-qa-${match[1]}`
+ || environment.DB_USERNAME !== `payable_history_native_${match[1]}` || environment.DB_HOST !== '127.0.0.1'
+ || environment.DB_PORT !== '55439' || environment.COMPRAS_RUNTIME_SYNTHETIC_ONLY !== 'true') throw Error('Owned inventory preview required');
+ if (cancellation) environment = { ...environment, COMPRAS_ORDER_CANCELLATION_ENABLED: 'true' };
+ const prepared = spawnSync('php', ['tests/Concurrency/unit-conversion-worker.php', database, analytics ? 'prepare-analytics-preview' : cancellation ? 'prepare-cancellation-preview' : 'prepare-preview'], {
+ cwd: workspace, windowsHide: true, encoding: 'utf8', env: { ...environment, APP_ENV: 'testing' },
+ });
+ if (prepared.status !== 0) throw Error('Synthetic inventory preview fixture failed');
+ const fixture = JSON.parse(prepared.stdout);
+ for (const relative of ['public', 'storage/framework/sessions', 'storage/framework/views', 'storage/framework/cache/data', 'storage/logs', 'storage/app/private']) fs.mkdirSync(path.join(root, relative), { recursive: true });
+ const assets = path.join(workspace, 'storage/framework/testing', analytics ? 'sgc-analytics-print-qa-20261129' : 'sgc-standalone-finance-help-qa-20261129');
+ const manifest = fs.readFileSync(path.join(assets, 'manifest.json'));
+ if (crypto.createHash('sha256').update(manifest).digest('hex') !== (analytics ? 'c3ac2c6443d73c228a3a8e8e96f2f32bb130fa5e5b03b2b284b02007c5502022' : '8653c147ab863447b523ddc03111265e3e6510bdddc31341777d6a3bdc46ce5b')) throw Error('Pinned UI build required');
+ fs.cpSync(assets, path.join(root, 'public/build'), { recursive: true, errorOnExist: true });
+ const verifyAnalytics = (mode) => {
+ const check = spawnSync('php', ['scripts/check-analytics-preview.php', root, mode], { cwd: workspace, windowsHide: true, encoding: 'utf8' });
+ if (check.status !== 0) throw Error('Synthetic analytical conservation failed');
+ return JSON.parse(check.stdout);
+ };
+ if (analytics) verifyAnalytics('--capture');
+ for (const file of ['favicon.ico', 'favicon.svg', 'apple-touch-icon.png']) fs.copyFileSync(path.join(workspace, 'public', file), path.join(root, 'public', file));
+ const port = await new Promise((resolve, reject) => {
+ const socket = createServer(); socket.on('error', reject);
+ socket.listen(0, '127.0.0.1', () => { const address = socket.address(); socket.close(() => resolve(address.port)); });
+ });
+ const url = `http://localhost:${port}`;
+ const server = spawn('php', ['-S', `127.0.0.1:${port}`, '-t', path.join(root, 'public'), 'tests/Support/standalone-inventory-http-router.php'], {
+ cwd: workspace, windowsHide: true, stdio: ['ignore', 'ignore', 'ignore'],
+ env: { ...environment, APP_URL: url, ASSET_URL: url, SGC_STANDALONE_QA_ROOT: root, SGC_STANDALONE_QA_PORT: String(port),
+ SESSION_DRIVER: 'file', SESSION_COOKIE: `sgc_inventory_qa_${match[1]}`, SESSION_DOMAIN: '', SESSION_SECURE_COOKIE: 'false',
+ SGC_PRODUCT_ENTITLEMENTS: JSON.stringify({ [fixture.tenant_id]: ['procurement.internal'] }) },
+ });
+ try {
+ let ready = false;
+ for (let attempt = 0; attempt < 30 && !ready; attempt++) {
+ try { const response = await fetch(url+'/login'); ready = response.status === 200; await response.arrayBuffer(); } catch {}
+ if (!ready) await new Promise(resolve => setTimeout(resolve, 200));
+ }
+ if (!ready) throw Error('Inventory preview did not start');
+ const stop = path.join(root, 'stop-inventory-review');
+ console.log(JSON.stringify({ inventory_preview: !cancellation && !analytics, cancellation_preview: cancellation, analytics_preview: analytics, url, stop_file: stop, ...fixture, normal_authentication_required: true }));
+ const until = Date.now()+20*60*1000;
+ while (!fs.existsSync(stop) && Date.now() < until) {
+ if (server.exitCode !== null) throw Error('Inventory preview stopped unexpectedly');
+ await new Promise(resolve => setTimeout(resolve, 200));
+ }
+ if (analytics) console.log(JSON.stringify({ analytical_conservation: verifyAnalytics('--verify') }));
+ } finally {
+ if (server.exitCode === null) {
+ const closed = new Promise(resolve => server.once('exit', resolve));
+ server.kill(); await closed;
+ }
+ }
+}
diff --git a/scripts/verify-replenishment-task-backup.php b/scripts/verify-replenishment-task-backup.php
new file mode 100644
index 0000000..e08d470
--- /dev/null
+++ b/scripts/verify-replenishment-task-backup.php
@@ -0,0 +1,70 @@
+ new PDO('pgsql:host=127.0.0.1;port='.(int) $source['DB_PORT'].';dbname='.$database,
+ $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
+$admin = $connect('postgres', $settings['DB_USERNAME'], $settings['DB_PASSWORD']);
+$id = bin2hex(random_bytes(6));
+$role = 'compras_replenish_app_'.$id;
+$database = 'compras_replenish_restore_'.$id;
+$password = bin2hex(random_bytes(32));
+$createdRole = $createdDatabase = false;
+$copy = null;
+try {
+ $admin->exec('CREATE ROLE "'.$role.'" LOGIN NOSUPERUSER NOCREATEDB NOCREATEROLE NOINHERIT NOREPLICATION NOBYPASSRLS PASSWORD '.$admin->quote($password));
+ $createdRole = true;
+ $admin->exec('CREATE DATABASE "'.$database.'" OWNER "'.$role.'"');
+ $createdDatabase = true;
+ $process = new Process(['C:/Program Files/PostgreSQL/17/bin/pg_restore.exe', '--no-owner', '--no-acl', '--exit-on-error',
+ '--dbname='.$database, $directory.'/before.dump'], $root, ['PGHOST' => '127.0.0.1', 'PGPORT' => $source['DB_PORT'],
+ 'PGUSER' => $role, 'PGPASSWORD' => $password], timeout: 120);
+ $process->run();
+ if (! $process->isSuccessful()) {
+ throw new LogicException('Private replenishment backup restore failed.');
+ }
+ $copy = $connect($database, $role, $password);
+ $copy->exec('SET default_transaction_read_only=on');
+ $baseline = json_decode(file_get_contents($directory.'/baseline.private.json'), true, 32, JSON_THROW_ON_ERROR);
+ $tables = $copy->query("SELECT tablename FROM pg_tables WHERE schemaname='public' ORDER BY tablename")->fetchAll(PDO::FETCH_COLUMN);
+ if ($tables !== array_keys($baseline)) {
+ throw new LogicException('Restored table inventory differs.');
+ }
+ foreach ($baseline as $table => $before) {
+ $rows = $copy->query('SELECT row_to_json(t)::text FROM "'.str_replace('"', '""', $table).'" t ORDER BY row_to_json(t)::text')->fetchAll(PDO::FETCH_COLUMN);
+ if (count($rows) !== $before['rows'] || ! hash_equals($before['sha256'], hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR)))) {
+ throw new LogicException('Restored replenishment backup data differs.');
+ }
+ }
+ $result = ['date' => gmdate('c'), 'state' => 'passed', 'restored_tables_identical' => count($baseline),
+ 'source_database_or_settings_changed' => false, 'business_commands' => false];
+} finally {
+ $copy = null;
+ if ($createdDatabase) {
+ $admin->exec('DROP DATABASE "'.$database.'" WITH (FORCE)');
+ }
+ if ($createdRole) {
+ $admin->exec('DROP ROLE "'.$role.'"');
+ }
+}
+$result['temporary_database_and_role_removed'] = true;
+file_put_contents($root.'/docs/proofs/replenishment-task-recovery.json', json_encode($result, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR).PHP_EOL);
+echo json_encode($result, JSON_THROW_ON_ERROR).PHP_EOL;
diff --git a/storage/framework/replenishment-command-status.json b/storage/framework/replenishment-command-status.json
new file mode 100644
index 0000000..0068023
--- /dev/null
+++ b/storage/framework/replenishment-command-status.json
@@ -0,0 +1,8 @@
+{
+ "started_at": "2026-11-29T17:48:46+00:00",
+ "finished_at": "2026-11-29T17:48:47+00:00",
+ "scope": "SGC replenishment command",
+ "result": "passed",
+ "exit_code": 0,
+ "installation": "03883b15704bdf2be59fcb1a6110242f6d441a2cd9765a469141d5ca71f71c83"
+}
\ No newline at end of file
diff --git a/storage/framework/replenishment-command.lock b/storage/framework/replenishment-command.lock
new file mode 100644
index 0000000..e69de29
diff --git a/tests/Concurrency/unit-conversion-worker.php b/tests/Concurrency/unit-conversion-worker.php
index f5580d6..b09a2f7 100644
--- a/tests/Concurrency/unit-conversion-worker.php
+++ b/tests/Concurrency/unit-conversion-worker.php
@@ -2,25 +2,101 @@
use App\Models\PurchaseOrder;
use App\Models\User;
+use App\Services\OrderCancellationWorkflow;
use App\Services\ReceiptWorkflow;
+use App\Services\SupplierPayables;
use Illuminate\Contracts\Console\Kernel;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Symfony\Component\Process\Process;
require __DIR__.'/../../vendor/autoload.php';
$database = $argv[1] ?? '';
+$operational = getenv('COMPRAS_STANDALONE_CONVERSION_QA') === '1';
$app = require __DIR__.'/../../bootstrap/app.php';
$app->make(Kernel::class)->bootstrap();
-if (! $app->environment('testing') || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
+if (! $app->environment($operational ? ['testing', 'standalone-qa'] : ['testing']) || DB::getDriverName() !== 'pgsql' || DB::connection()->getDatabaseName() !== $database
|| ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', $database)) {
throw new LogicException('Worker de conversão fora de QA.');
}
-config(['inventory_conversion.qa_enabled' => true]);
-if (($argv[2] ?? '') === 'prepare') {
+if ($operational && (DB::connection()->getConfig('host') !== '127.0.0.1' || (string) DB::connection()->getConfig('port') !== '55439'
+ || DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.substr($database, -12))) {
+ throw new LogicException('Owned standalone conversion cluster required.');
+}
+if (($argv[2] ?? '') === 'prepare-runtime' && $operational) {
+ require __DIR__.'/../Support/StandaloneCompositionFixture.php';
+ prepareSyntheticStandaloneRuntime();
+ echo 'synthetic_standalone_inventory_prepared';
+ exit;
+}
+config(['inventory_conversion.qa_enabled' => ! $operational, 'inventory_conversion.enabled' => $operational]);
+if (($argv[2] ?? '') === 'prepare-analytics-preview' && $operational) {
+ require __DIR__.'/../Support/PaymentFixture.php';
+ $f = paymentFixture(['Material', 'Serviços']);
+ $payables = app(SupplierPayables::class);
+ foreach ([$f['author'], $f['validator']] as $actor) {
+ foreach (['view', 'prepare', 'validate', 'payments_view', 'payment_prepare', 'payment_confirm', 'allocation_prepare', 'allocation_confirm'] as $action) {
+ DB::table('pa_access')->insert(['tenant_id' => $actor->tenant_id, 'company_id' => 0, 'unit_id' => 0,
+ 'user_id' => $actor->id, 'person' => 'synthetic-analytics-finance-'.$actor->id, 'action' => $action]);
+ }
+ }
+ auth()->guard()->setUser($f['author']);
+ $proposal = $payables->engine($f['author'])->command('prepare', $f['invoice']->id, 'Synthetic analytics invoice', (string) Str::uuid());
+ auth()->guard()->setUser($f['validator']);
+ $recognised = $payables->engine($f['validator'])->command('validate', $proposal['proposal_id'], 'Independent synthetic invoice recognition', (string) Str::uuid());
+ $run = static function (User $actor, string $action, array $data) use ($payables): array {
+ auth()->guard()->setUser($actor);
+
+ return $payables->settlements($actor)->command($action, $data, (string) Str::uuid());
+ };
+ $payment = $run($f['author'], 'payment-prepare', ['obligation_id' => $recognised['obligation_id'],
+ 'source_revision' => $recognised['source_revision'], 'amount' => '40.00', 'currency' => 'MZN', 'paid_on' => today()->toDateString(),
+ 'fact_reference' => 'DOC-ANALYTICS-SYNTHETIC', 'evidence_reference' => 'DOC-ANALYTICS-EVIDENCE', 'reason' => 'Explicit synthetic payment fact for analytical review']);
+ $run($f['validator'], 'payment-decide', ['payment_id' => $payment['payment_id'], 'decision' => 'confirmed',
+ 'evidence_reference' => 'DOC-ANALYTICS-CONFIRMED', 'reason' => 'Independent synthetic payment confirmation']);
+ $allocation = $run($f['author'], 'allocation-prepare', ['payment_id' => $payment['payment_id'], 'reference' => 'DOC-ANALYTICS-ALLOCATION',
+ 'allocations' => [['obligation_id' => $recognised['obligation_id'], 'source_revision' => $recognised['source_revision'], 'amount' => '40.00']],
+ 'reason' => 'Explicit synthetic invoice allocation']);
+ $run($f['validator'], 'allocation-decide', ['proposal_id' => $allocation['proposal_id'], 'decision' => 'confirmed',
+ 'reason' => 'Independent synthetic allocation confirmation']);
+ $allocationId = (int) DB::table('ps_allocations')->where('payment_id', $payment['payment_id'])->value('id');
+ $f['validator']->update(['email' => 'analytics-finance@example.test', 'name' => 'Finance synthetic analytics review']);
+ echo json_encode(['actor_email' => $f['validator']->email, 'tenant_id' => $f['tenant']->id,
+ 'order_id' => $f['order']->id, 'allocation_id' => $allocationId, 'payment_amount_minor' => 4000,
+ 'attribution_route' => '/afectacoes-fornecedores/'.$allocationId.'/imputacao', 'report_route' => '/relatorios'], JSON_THROW_ON_ERROR);
+ exit;
+}
+if (($argv[2] ?? '') === 'prepare-cancellation-preview' && $operational) {
+ require __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
+ config(['order_cancellation.enabled' => true]);
+ $fixture = new class extends stdClass
+ {
+ public function actingAs(User $actor): void
+ {
+ auth()->guard()->setUser($actor);
+ }
+ };
+ issuedOrderCancellationFixture($fixture, 2);
+ $workflow = app(OrderCancellationWorkflow::class);
+ $fixture->actingAs($fixture->buyer);
+ $record = $workflow->request($fixture->buyer, $fixture->f['order'], $fixture->data);
+ $fixture->actingAs($fixture->finance);
+ $workflow->decide($fixture->finance, $record, 'approved', 'Independent synthetic cycle-aware cancellation preview');
+ $fixture->finance->update(['email' => 'cancellation-finance@example.test', 'name' => 'Finance synthetic cancellation review']);
+ echo json_encode(['actor_email' => $fixture->finance->email, 'tenant_id' => $fixture->f['tenant']->id,
+ 'order_id' => $fixture->f['order']->id, 'cancellation_id' => $record->id, 'source_cycle' => 2, 'state' => 'approved'], JSON_THROW_ON_ERROR);
+ exit;
+}
+if (in_array($argv[2] ?? '', ['prepare', 'prepare-preview'], true)) {
require __DIR__.'/../Support/ReceiptFixture.php';
$f = receiptFixture();
$f['stock']->update(['unit' => 'un']);
+ if (($argv[2] ?? '') === 'prepare-preview' && $operational) {
+ $f['receiver']->update(['email' => 'conversion-warehouse@example.test', 'name' => 'Warehouse synthetic conversion review']);
+ echo json_encode(['actor_email' => $f['receiver']->email, 'tenant_id' => $f['tenant']->id, 'order_id' => $f['order']->id], JSON_THROW_ON_ERROR);
+ exit;
+ }
$body = receiptPayload($f, '1.000');
$body['items'][0]['conversion'] = ['numerator' => '12', 'denominator' => '1', 'source' => 'Embalagem sintética de corrida', 'version' => 'QA-RACE-1'];
echo json_encode(['tenant' => $f['tenant']->id, 'actor' => $f['receiver']->id, 'order' => $f['order']->id, 'body' => $body], JSON_THROW_ON_ERROR);
@@ -43,7 +119,7 @@ if (($argv[2] ?? '') !== 'race') {
throw new InvalidArgumentException('Modo de worker inválido.');
}
foreach (['same_body', 'conflicting_body'] as $scenario) {
- $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), timeout: 30);
+ $prepare = new Process([PHP_BINARY, __FILE__, $database, 'prepare'], dirname(__DIR__, 2), $operational ? ['APP_ENV' => 'testing'] : null, timeout: 30);
$prepare->mustRun();
$input = json_decode($prepare->getOutput(), true, 32, JSON_THROW_ON_ERROR);
$workers = [];
diff --git a/tests/Conversion/ReceiptQuantityConversionTest.php b/tests/Conversion/ReceiptQuantityConversionTest.php
index c6b56a7..185c4f6 100644
--- a/tests/Conversion/ReceiptQuantityConversionTest.php
+++ b/tests/Conversion/ReceiptQuantityConversionTest.php
@@ -10,6 +10,7 @@ use App\Models\StockMovement;
use App\Models\User;
use App\Services\AgreementOrderLimits;
use App\Services\ConflictGuard;
+use App\Services\InventoryConversionRuntime;
use App\Services\InventoryDispositions;
use App\Services\InventoryLots;
use App\Services\InventoryReversals;
@@ -17,17 +18,27 @@ use App\Services\InvoiceWorkflow;
use App\Services\ReceiptStockMovement;
use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
+use App\Services\StandaloneArtifact;
+use App\Services\StandaloneRuntime;
use App\Services\StockWorkflow;
use App\Services\SupplyCoordination;
use App\Services\SupplyPlanning;
use Illuminate\Support\Facades\DB;
+use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
+use Inertia\Testing\AssertableInertia as Assert;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/SupplyFixture.php';
+require_once __DIR__.'/../Support/StandaloneCompositionFixture.php';
beforeEach(function () {
- config(['inventory_conversion.qa_enabled' => true]);
+ $this->operationalConversion = getenv('COMPRAS_STANDALONE_CONVERSION_QA') === '1';
+ if ($this->operationalConversion) {
+ prepareSyntheticStandaloneRuntime();
+ }
+ config(['inventory_conversion.qa_enabled' => ! $this->operationalConversion,
+ 'inventory_conversion.enabled' => $this->operationalConversion]);
$this->f = receiptFixture();
// New consistent synthetic process: 2 boxes x 100 MZN = 200 MZN. Original fixture is untouched.
$request = $this->f['r']->replicate();
@@ -55,6 +66,7 @@ beforeEach(function () {
});
test('two boxes retain two documentary units and 200 MZN while crediting exactly 24 physical units once', function () {
+ $this->get($this->url)->assertOk()->assertInertia(fn (Assert $page) => $page->component('receipts/order')->where('conversionQaEnabled', true));
$id = $this->postJson($this->url, $this->body)->assertCreated()->json('id');
$this->postJson($this->url, $this->body)->assertOk()->assertJsonPath('id', $id);
$line = GoodsReceipt::query()->findOrFail($id)->items()->sole();
@@ -112,11 +124,53 @@ test('missing source factor and nonrepresentable physical quantities never creat
});
test('conversion is not enabled by its presence in a request and cannot escape the QA guard', function () {
- config(['inventory_conversion.qa_enabled' => false]);
+ config(['inventory_conversion.qa_enabled' => false, 'inventory_conversion.enabled' => false]);
$this->postJson($this->url, $this->body)->assertUnprocessable();
expect(StockMovement::query()->count())->toBe(0);
});
+test('a frozen conversion refuses fallback to the legacy inventory writer when the component is disabled', function () {
+ $this->postJson($this->url, $this->body)->assertCreated();
+ config(['inventory_conversion.qa_enabled' => false, 'inventory_conversion.enabled' => false]);
+ expect(fn () => app(ReceiptStockMovement::class)->load())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_DOWNGRADE_REFUSED');
+ expect(StockMovement::query()->sole()->quantity_milli)->toBe(24000);
+});
+
+test('an interrupted outer transaction rolls back the converted receipt and retries once with the same physical quantity', function () {
+ expect(fn () => DB::transaction(function () {
+ app(ReceiptWorkflow::class)->confirm($this->f['receiver'], $this->f['order'], $this->body);
+ throw new RuntimeException('synthetic interruption after movement');
+ }))->toThrow(RuntimeException::class, 'synthetic interruption after movement');
+ expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
+ $this->postJson($this->url, $this->body)->assertCreated();
+ $this->postJson($this->url, $this->body)->assertOk();
+ expect(StockMovement::query()->sole()->quantity_milli)->toBe(24000);
+});
+
+test('operational conversion refuses an unbound installation and mixed QA configuration before stock effects', function () {
+ if (! $this->operationalConversion) {
+ $this->markTestSkipped('Operational installation checks run with the owned PostgreSQL standalone runner.');
+ }
+ $runtime = app(InventoryConversionRuntime::class);
+ config(['inventory_conversion.qa_enabled' => true]);
+ expect(fn () => $runtime->root())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_CONFIGURATION');
+ config(['inventory_conversion.qa_enabled' => false]);
+ $settings = config('standalone-runtime');
+ $settings['installation_id'] = (string) Str::uuid();
+ app()->instance(StandaloneRuntime::class, new StandaloneRuntime($settings, new StandaloneArtifact));
+ expect(fn () => $runtime->root())->toThrow(LogicException::class, 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH');
+ expect(StockMovement::query()->count())->toBe(0)->and(GoodsReceipt::query()->count())->toBe(0);
+});
+
+test('operational conversion refuses an incomplete inventory schema before loading a writer', function () {
+ if (! $this->operationalConversion) {
+ $this->markTestSkipped('Operational schema checks run with the owned PostgreSQL standalone runner.');
+ }
+ DB::statement('ALTER TABLE goods_receipt_items DROP COLUMN notes');
+ expect(fn () => app(InventoryConversionRuntime::class)->root())->toThrow(LogicException::class, 'COMPRAS_INVENTORY_SCHEMA');
+ expect(StockMovement::query()->count())->toBe(0);
+});
+
test('legacy receipt facts retain the exact v1 hash and compatible replay without a conversion basis', function () {
$this->f['stock']->update(['unit' => 'cx']);
$body = $this->body;
diff --git a/tests/Feature/ReceiptStockTest.php b/tests/Feature/ReceiptStockTest.php
index 7e08a62..0eb471a 100644
--- a/tests/Feature/ReceiptStockTest.php
+++ b/tests/Feature/ReceiptStockTest.php
@@ -12,6 +12,7 @@ use App\Services\ReceiptWorkflow;
use App\Services\RequisitionWorkflow;
use Illuminate\Support\Str;
use Inertia\Testing\AssertableInertia as Assert;
+use Tempo\Inventory\ReceiptMovementWriter;
require_once __DIR__.'/../Support/ReceiptFixture.php';
@@ -28,6 +29,14 @@ test('receipt preparation uses encrypted history without registering a receipt o
expect(GoodsReceipt::query()->count())->toBe(0)->and(StockMovement::query()->count())->toBe(0);
});
+test('legacy receipts remain usable after agreement conversion arithmetic is loaded without selecting another stock writer', function () {
+ require_once base_path('packages/inventory-write/development/src/QuantityConversion.php');
+ $this->postJson($this->url, $this->payload)->assertCreated();
+ expect(StockMovement::query()->sole()->quantity_milli)->toBe(600);
+ $writer = new ReflectionClass(ReceiptMovementWriter::class);
+ expect(realpath($writer->getFileName()))->toBe(realpath(base_path('packages/inventory-write/releases/0.1.0/src/ReceiptMovementWriter.php')));
+});
+
test('partial then total receipts preserve pending quantities and credit only accepted stock', function () {
$this->postJson($this->url, receiptPayload($this->f, '0.400'))->assertCreated()->assertJsonPath('status', 'partial');
$first = GoodsReceipt::query()->firstOrFail();
diff --git a/tests/Feature/StandaloneBusinessCompositionTest.php b/tests/Feature/StandaloneBusinessCompositionTest.php
index 69a22fd..8ec9875 100644
--- a/tests/Feature/StandaloneBusinessCompositionTest.php
+++ b/tests/Feature/StandaloneBusinessCompositionTest.php
@@ -12,6 +12,8 @@ use App\Services\CommonPaymentFacts;
use App\Services\ExpenseAllocations;
use App\Services\GeneralLedger;
use App\Services\InvoiceWorkflow;
+use App\Services\OrderCancellationRuntime;
+use App\Services\OrderCancellationWorkflow;
use App\Services\ProcurementPaymentInsights;
use App\Services\RequisitionAccountAssignments;
use App\Services\RequisitionExpiry;
@@ -27,10 +29,13 @@ use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
+use Tempo\Finance\Budget\BudgetContext;
use Tempo\Finance\Budget\BudgetFailure;
+use Tempo\Finance\OrderCancellation\CommitmentReversal;
require_once __DIR__.'/../Support/ReceiptFixture.php';
require_once __DIR__.'/../Support/PaymentFixture.php';
+require_once __DIR__.'/../Support/IssuedOrderCancellationFixture.php';
beforeEach(function () {
if (getenv('COMPRAS_STANDALONE_BUSINESS_QA') !== '1') {
@@ -84,6 +89,38 @@ test('standalone candidate preserves explicit line account attribution without a
expect(DB::table('supply_records')->where('kind', 'req_account')->count())->toBe(1);
});
+test('issued order cancellation reverses the current resubmission cycle and preserves the closed reservation history', function (int $cycle) {
+ issuedOrderCancellationFixture($this, $cycle);
+ $origin = $this->f['r']->id;
+ $first = DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '<', $cycle)->orderBy('id')->get()->toJson();
+ $workflow = app(OrderCancellationWorkflow::class);
+ $this->actingAs($this->buyer);
+ $record = $workflow->request($this->buyer, $this->f['order'], $this->data);
+ $this->actingAs($this->finance);
+ $workflow->decide($this->finance, $record, 'approved', 'Independent synthetic cancellation after request resubmission');
+ $workflow->decide($this->finance, $record, 'approved', 'Independent synthetic cancellation after request resubmission');
+ $reversal = DB::table('budget_entries')->where('requisition_id', $origin)->where('kind', 'order-cancel-'.$this->f['order']->id)->sole();
+ expect((int) $reversal->requisition_cycle)->toBe($cycle)
+ ->and(DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', '<', $cycle)->orderBy('id')->get()->toJson())->toBe($first)
+ ->and((int) DB::table('budget_entries')->where('requisition_id', $origin)->where('requisition_cycle', $cycle)->sum('committed_minor'))->toBe(0)
+ ->and($this->f['r']->fresh()->status)->toBe('cancelled');
+})->with([1, 2]);
+
+test('cycle-aware cancellation refuses a stale or missing cycle map without appending a reversal', function () {
+ issuedOrderCancellationFixture($this, 2);
+ $origin = $this->f['r']->id;
+ $before = DB::table('budget_entries')->orderBy('id')->get()->toJson();
+ app(OrderCancellationRuntime::class)->load($origin);
+ foreach ([[], [$origin => 1]] as $cycles) {
+ $context = (new ReflectionClass(BudgetContext::class))->newInstanceArgs([
+ $this->finance->id, ['tenant_id' => $this->finance->tenant_id], (int) now()->year, 'MZN', $cycles,
+ ]);
+ expect(fn () => DB::transaction(fn () => (new CommitmentReversal)->reverse(DB::connection(), $context, $origin, $this->f['order']->id)))->toThrow(LogicException::class);
+ }
+ expect(DB::table('budget_entries')->orderBy('id')->get()->toJson())->toBe($before)
+ ->and($this->f['r']->fresh()->status)->toBe('approved');
+});
+
test('standalone candidate closes an old reservation cycle and reserves a revised amount once without rewriting history', function () {
$finance = User::factory()->create(['tenant_id' => $this->f['tenant']->id, 'department_id' => $this->f['department']->id,
'purchasing_role' => PurchasingRole::Finance]);
diff --git a/tests/Support/IssuedOrderCancellationFixture.php b/tests/Support/IssuedOrderCancellationFixture.php
index a0027e3..1eb15c1 100644
--- a/tests/Support/IssuedOrderCancellationFixture.php
+++ b/tests/Support/IssuedOrderCancellationFixture.php
@@ -4,13 +4,14 @@ use App\Enums\PurchasingRole;
use App\Models\Budget;
use App\Models\User;
use App\Services\BudgetWorkflow;
+use App\Services\CommonBudget;
use App\Services\OrderCancellationPolicyWorkflow;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
require_once __DIR__.'/../Support/ReceiptFixture.php';
-function issuedOrderCancellationFixture(object $test): void
+function issuedOrderCancellationFixture(object $test, int $cycle = 1): void
{
config(['order_cancellation.enabled' => true]);
$test->f = receiptFixture();
@@ -33,7 +34,19 @@ function issuedOrderCancellationFixture(object $test): void
$test->budget = Budget::query()->create(['tenant_id' => $test->f['tenant']->id, 'cost_center_id' => $test->f['r']->cost_center_id, 'year' => now()->year,
'amount_minor' => 20000, 'includes_tax' => true, 'reason' => 'Dotação fictícia para ensaio da reversão.', 'created_by' => $test->finance->id,
'approved_by' => $test->admins[0]->id, 'approved_at' => now()]);
- DB::transaction(function () use ($test) {
+ DB::transaction(function () use ($test, $cycle) {
+ if ($cycle === 2) {
+ $origin = $test->f['r']->id;
+ $adapter = app(CommonBudget::class);
+ $first = $adapter->for($test->finance, [$origin => 1]);
+ $first->beginRequisitionCycle($origin, 1, (string) Str::uuid());
+ $first->record($origin, $test->f['r']->cost_center_id, 'operating', 'reserve', 10000, 10000);
+ $first->record($origin, $test->f['r']->cost_center_id, 'operating', 'release');
+ $first->closeRequisitionCycle($origin, 1, (string) Str::uuid());
+ $second = $adapter->for($test->finance, [$origin => 2]);
+ $second->beginRequisitionCycle($origin, 2, (string) Str::uuid());
+ $test->f['r']->forceFill(['approval_cycle' => 2])->save();
+ }
foreach (['reserve', 'award', 'commit'] as $kind) {
app(BudgetWorkflow::class)->record($test->finance, $test->f['r'], $kind, 10000, 10000);
}
diff --git a/tests/Support/StandaloneCompositionFixture.php b/tests/Support/StandaloneCompositionFixture.php
new file mode 100644
index 0000000..81953fb
--- /dev/null
+++ b/tests/Support/StandaloneCompositionFixture.php
@@ -0,0 +1,33 @@
+environment('testing') || DB::getDriverName() !== 'pgsql'
+ || DB::connection()->getConfig('host') !== '127.0.0.1'
+ || ! preg_match('/^compras_receipts_test_[a-f0-9]{12}$/D', DB::connection()->getDatabaseName())) {
+ throw new LogicException('Synthetic standalone business database required.');
+ }
+ $settings = config('standalone-runtime');
+ $settings['enabled'] = true;
+ $settings['prepare_only'] = false;
+ $settings['features'] = array_fill_keys(StandaloneRuntime::FEATURES, true);
+ config(['standalone-runtime' => [...$settings, 'enabled' => false], 'common-payables.source_instance' => 'standalone-business-synthetic']);
+ $runtime = new StandaloneRuntime($settings, new StandaloneArtifact);
+ $runtime->artifact();
+ (require base_path('database/standalone-migrations/2026_11_29_000001_create_runtime_installations.php'))->up();
+ DB::table('compras_runtime_installations')->insert(['id' => $settings['installation_id'], 'product' => 'compras',
+ 'contract' => StandaloneArtifact::CONTRACT, 'manifest_sha256' => $settings['manifest_sha256'],
+ 'database_binding_sha256' => StandaloneRuntime::databaseBinding(DB::connection()),
+ 'recorded_by' => 'Synthetic standalone business regression', 'reason' => 'Authorised isolated candidate verification', 'installed_at' => now()]);
+ (require base_path('database/standalone-migrations/2026_11_29_000002_install_standalone_extensions.php'))->up();
+ config(['standalone-runtime' => $settings]);
+ app()->instance(StandaloneRuntime::class, $runtime);
+ $paths = $runtime->configure(DB::connection());
+ config(['general-ledger.path' => $paths['general-ledger']]);
+ $runtime->assertLoadedPackages();
+}
diff --git a/tests/Support/standalone-inventory-http-router.php b/tests/Support/standalone-inventory-http-router.php
new file mode 100644
index 0000000..66d15f3
--- /dev/null
+++ b/tests/Support/standalone-inventory-http-router.php
@@ -0,0 +1,34 @@
+ 'text/javascript', 'css' => 'text/css', 'svg' => 'image/svg+xml', 'png' => 'image/png', 'ico' => 'image/x-icon', 'woff' => 'font/woff', 'woff2' => 'font/woff2'];
+if ($asset !== false && is_file($asset) && str_starts_with(str_replace('\\', '/', $asset), str_replace('\\', '/', $public).'/')
+ && isset($types[pathinfo($asset, PATHINFO_EXTENSION)])) {
+ header('Content-Type: '.$types[pathinfo($asset, PATHINFO_EXTENSION)]);
+ readfile($asset);
+ exit;
+}
+$app = require __DIR__.'/../../bootstrap/app.php';
+$app->useStoragePath($root.'/storage');
+$app->usePublicPath($public);
+$app->handleRequest(Request::capture());
diff --git a/tests/Support/standalone-inventory-recovery-worker.php b/tests/Support/standalone-inventory-recovery-worker.php
new file mode 100644
index 0000000..2b25816
--- /dev/null
+++ b/tests/Support/standalone-inventory-recovery-worker.php
@@ -0,0 +1,118 @@
+useStoragePath($root.'/recovery-storage');
+try {
+ $app->make(Kernel::class)->bootstrap();
+} catch (LogicException $e) {
+ if ($mode !== 'reject-restore' || $e->getMessage() !== 'COMPRAS_RUNTIME_INSTALLATION_MISMATCH') {
+ throw $e;
+ }
+ echo json_encode(['rejected' => true, 'reason' => $e->getMessage()], JSON_THROW_ON_ERROR);
+ exit;
+}
+if ($mode === 'reject-restore') {
+ throw new LogicException('Restored database started with the original binding.');
+}
+if (DB::selectOne("select current_setting('cluster_name') as name")->name !== 'sgf_modular_regression_'.$match[1]) {
+ throw new LogicException('Owned recovery cluster required.');
+}
+if ($mode === 'rebind') {
+ $result = app(StandaloneInstallation::class)->prepare($database, getenv('DB_USERNAME'), 'Synthetic inventory recovery',
+ 'Authorised isolated backup restoration', apply: true, rebind: true);
+ if ($result['state'] !== 'rebound') {
+ throw new LogicException('Recovery binding not recorded.');
+ }
+ echo json_encode(['state' => 'rebound'], JSON_THROW_ON_ERROR);
+ exit;
+}
+if (! app(InventoryConversionRuntime::class)->available() || config('inventory_conversion.qa_enabled') !== false) {
+ throw new LogicException('Operational inventory component required.');
+}
+$frames = static function (): array {
+ $hashes = [];
+ foreach (DB::select("select tablename from pg_tables where schemaname='public' order by tablename") as $table) {
+ if ($table->tablename === 'compras_runtime_installations') {
+ continue;
+ }
+ $rows = DB::table($table->tablename)->get()->map(fn ($row) => json_encode($row, JSON_THROW_ON_ERROR))->all();
+ sort($rows, SORT_STRING);
+ $hashes[$table->tablename] = hash('sha256', json_encode($rows, JSON_THROW_ON_ERROR));
+ }
+
+ return $hashes;
+};
+$hashes = $frames();
+$cancellation = $mode === 'read-cancellation';
+if ($cancellation) {
+ app(OrderCancellationRuntime::class)->assertReady();
+ $record = DB::table('order_cancellations')->sole();
+ $actor = User::query()->findOrFail($record->reviewed_by);
+ auth()->guard()->setUser($actor);
+ $model = OrderCancellation::query()->findOrFail($record->id);
+ app(OrderCancellationWorkflow::class)->decide($actor, $model, 'approved', $record->review_reason);
+ $order = DB::table('purchase_orders')->where('id', $record->purchase_order_id)->firstOrFail();
+ $reversal = DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('kind', 'order-cancel-'.$order->id)->sole();
+ if ((int) $reversal->requisition_cycle !== 2 || $record->status !== 'approved'
+ || (int) DB::table('budget_entries')->where('requisition_id', $order->requisition_id)->where('requisition_cycle', 2)->sum('committed_minor') !== 0) {
+ throw new LogicException('Recovered cancellation cycle or balance changed.');
+ }
+} else {
+ $movements = DB::table('stock_movements')->whereNotNull('snapshot->quantity_conversion')->get();
+ if ($movements->count() !== 2) {
+ throw new LogicException('Both synthetic contention scenarios must survive recovery.');
+ }
+ foreach ($movements as $movement) {
+ $snapshot = json_decode($movement->snapshot, true, 512, JSON_THROW_ON_ERROR);
+ $actor = User::query()->findOrFail($movement->moved_by);
+ auth()->guard()->setUser($actor);
+ $line = GoodsReceiptItem::query()->findOrFail($movement->goods_receipt_item_id);
+ if (app(ReceiptQuantityConversion::class)->documentary($line, (int) $movement->quantity_milli) !== 1000) {
+ throw new LogicException('Restored documentary equivalence changed.');
+ }
+ $result = DB::transaction(function () use ($actor, $movement, $snapshot) {
+ app(ConflictGuard::class)->lockCompany($actor);
+
+ return app(ReceiptStockMovement::class)->for($actor)->write($movement->goods_receipt_item_id, $snapshot['inventory_source_hash']);
+ });
+ if ($result['replayed'] !== true || (int) $result['movement_id'] !== (int) $movement->id) {
+ throw new LogicException('Restored movement was not replayed exactly.');
+ }
+ }
+}
+$original = DB::table('compras_runtime_installations')->where('id', getenv('COMPRAS_QA_ORIGINAL_INSTALLATION_ID'))->first();
+if ($original === null) {
+ throw new LogicException('Original immutable installation history lost.');
+}
+if ($frames() !== $hashes) {
+ throw new LogicException('Replay changed synthetic business data.');
+}
+echo json_encode(['business_tables' => count($hashes), 'business_sha256' => hash('sha256', json_encode($hashes, JSON_THROW_ON_ERROR)),
+ 'original_installation_sha256' => hash('sha256', json_encode($original, JSON_THROW_ON_ERROR)),
+ ...($cancellation ? ['approved_cancellations' => 1, 'source_cycle' => 2, 'exact_replays' => 1]
+ : ['converted_movements' => 2, 'exact_replays' => 2])], JSON_THROW_ON_ERROR);
diff --git a/tests/Unit/DeadlineTaskGuiActionTest.php b/tests/Unit/DeadlineTaskGuiActionTest.php
new file mode 100644
index 0000000..a6ad4ad
--- /dev/null
+++ b/tests/Unit/DeadlineTaskGuiActionTest.php
@@ -0,0 +1,28 @@
+IgnoreNew'
+ .'PT1MC:/synthetic/php.exe'
+ .'"C:/synthetic/deadlines.php" --onceC:/synthetic';
+}
+
+test('silent deadline correction preserves arguments working directory overlap and limits', function () {
+ $xml = syntheticDeadlineGuiXml();
+ $after = DeadlineTaskGuiAction::replacement($xml, 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
+ expect($after)->toContain('php-win.exe')->toContain('"C:/synthetic/deadlines.php" --once')->toContain('IgnoreNew')->toContain('PT1M');
+ DeadlineTaskGuiAction::assertConserved($xml, $after, 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
+ DeadlineTaskGuiAction::assertConserved($xml, str_replace('><', ">\r\n <", $after), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe');
+ expect(DeadlineTaskGuiAction::canonical(str_replace('><', ">\r\n <", $xml)))->toBe(DeadlineTaskGuiAction::canonical($xml));
+ expect(fn () => DeadlineTaskGuiAction::assertConserved($xml, str_replace('PT1M', 'PT5M', $after), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe'))
+ ->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_UNRELATED_DEFINITION_CHANGE');
+});
+
+test('silent deadline correction refuses another executable directory or multiple actions', function () {
+ $xml = syntheticDeadlineGuiXml();
+ expect(fn () => DeadlineTaskGuiAction::replacement($xml, 'C:/synthetic/php.exe', 'C:/other/php-win.exe'))->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_EXECUTABLE_PAIR');
+ expect(fn () => DeadlineTaskGuiAction::replacement(str_replace('', 'other', $xml), 'C:/synthetic/php.exe', 'C:/synthetic/php-win.exe'))
+ ->toThrow(LogicException::class, 'DEADLINE_TASK_GUI_ACTION_MISMATCH');
+});
diff --git a/tests/Unit/InventoryConversionArtifactTest.php b/tests/Unit/InventoryConversionArtifactTest.php
new file mode 100644
index 0000000..769844a
--- /dev/null
+++ b/tests/Unit/InventoryConversionArtifactTest.php
@@ -0,0 +1,53 @@
+open($path, ZipArchive::CREATE | ZipArchive::EXCL))->toBeTrue();
+ foreach (['src/ReceiptMovementWriter.php', 'src/QuantityConversion.php', 'bootstrap.php', 'manifest.json'] as $name) {
+ $zip->addFromString($name, 'synthetic archive entry');
+ }
+ $zip->close();
+ $zip->open($path);
+ InventoryConversionRuntime::assertArchiveEntries($zip);
+ expect($zip->numFiles)->toBe(4);
+ $zip->addFromString('../unexpected.php', 'synthetic forbidden entry');
+ expect(fn () => InventoryConversionRuntime::assertArchiveEntries($zip))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
+ $zip->deleteName('../unexpected.php');
+ $zip->deleteName('bootstrap.php');
+ expect(fn () => InventoryConversionRuntime::assertArchiveEntries($zip))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_ARCHIVE_ENTRIES');
+ } finally {
+ $zip->close();
+ if (is_file($path)) {
+ unlink($path);
+ }
+ }
+});
+
+test('inventory candidate rejects changed component bytes and manifests before loading PHP', function () {
+ $source = dirname(__DIR__, 2).'/packages/inventory-write/releases/0.2.0-rc.1';
+ $root = sys_get_temp_dir().'/compras-inventory-artifact-'.bin2hex(random_bytes(8));
+ mkdir($root.'/src', 0700, true);
+ $files = ['manifest.json', 'bootstrap.php', 'src/QuantityConversion.php', 'src/ReceiptMovementWriter.php'];
+ try {
+ foreach ($files as $file) {
+ copy($source.'/'.$file, $root.'/'.$file);
+ }
+ InventoryConversionRuntime::verifyArtifact($root);
+ expect(hash_file('sha256', $root.'/manifest.json'))->toBe(InventoryConversionRuntime::MANIFEST_SHA256);
+ file_put_contents($root.'/src/QuantityConversion.php', "\n// altered", FILE_APPEND);
+ expect(fn () => InventoryConversionRuntime::verifyArtifact($root))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_FILE:src/QuantityConversion.php');
+ copy($source.'/src/QuantityConversion.php', $root.'/src/QuantityConversion.php');
+ file_put_contents($root.'/manifest.json', "\n", FILE_APPEND);
+ expect(fn () => InventoryConversionRuntime::verifyArtifact($root))->toThrow(LogicException::class, 'COMPRAS_INVENTORY_MANIFEST');
+ } finally {
+ foreach ($files as $file) {
+ unlink($root.'/'.$file);
+ }
+ rmdir($root.'/src');
+ rmdir($root);
+ }
+});
diff --git a/tests/Unit/ReplenishmentTaskDefinitionTest.php b/tests/Unit/ReplenishmentTaskDefinitionTest.php
new file mode 100644
index 0000000..ef51b6a
--- /dev/null
+++ b/tests/Unit/ReplenishmentTaskDefinitionTest.php
@@ -0,0 +1,13 @@
+PT1MS-1-5-21-1S-1-5-21-1InteractiveTokenLeastPrivilegeC:/synthetic/php-win.exe';
+ $xml = str_replace('', 'true', $xml);
+ ReplenishmentTaskDefinition::assertMatches($xml, str_replace(['LeastPrivilege', 'true'], '', $xml));
+ expect(true)->toBeTrue();
+ foreach ([str_replace('LeastPrivilege', 'HighestAvailable', $xml), str_replace('PT1M', 'PT5M', $xml), str_replace('S-1-5-21-1', 'S-1-5-18', $xml), str_replace('true', 'false', $xml)] as $changed) {
+ expect(fn () => ReplenishmentTaskDefinition::assertMatches($xml, $changed))->toThrow(LogicException::class);
+ }
+});
diff --git a/tests/frontend/procurement-menu-search.test.tsx b/tests/frontend/procurement-menu-search.test.tsx
index 0947b2a..067737b 100644
--- a/tests/frontend/procurement-menu-search.test.tsx
+++ b/tests/frontend/procurement-menu-search.test.tsx
@@ -12,6 +12,43 @@ import {
searchProcurementMenu,
} from '@/lib/procurement-menu-search';
+test('common payment attribution retains its existing authorised finance menu entry', () => {
+ const path = '/afectacoes-fornecedores/12/imputacao';
+ expect(
+ activeProcurementEntry(
+ procurementNavigation(
+ ['finance'],
+ true,
+ undefined,
+ false,
+ false,
+ false,
+ false,
+ { payments: true },
+ ),
+ path,
+ ),
+ ).toBe('supplier_settlements');
+ expect(
+ activeProcurementEntry(procurementNavigation(['finance'], true), path),
+ ).toBeUndefined();
+ expect(
+ activeProcurementEntry(
+ procurementNavigation(
+ ['requester'],
+ false,
+ undefined,
+ false,
+ false,
+ false,
+ false,
+ { payments: true },
+ ),
+ path,
+ ),
+ ).toBeUndefined();
+});
+
test.each([
'/compras/fornecimento',
'/compras/fornecimento?view=agreements&record_id=12',
diff --git a/tests/frontend/procurement-payment-insights.test.tsx b/tests/frontend/procurement-payment-insights.test.tsx
index 56ecab3..1f046db 100644
--- a/tests/frontend/procurement-payment-insights.test.tsx
+++ b/tests/frontend/procurement-payment-insights.test.tsx
@@ -3,6 +3,27 @@ import { describe, expect, it } from 'vitest';
import { ProcurementPaymentInsights } from '../../resources/js/components/procurement-payment-insights';
describe('confirmed payment expense', () => {
+ it('describes one confirmed payment in the singular without changing the exact amount', () => {
+ const html = renderToStaticMarkup(
+ ,
+ );
+ expect(html).toContain('1 pagamento confirmado.');
+ expect(html).toContain('40,00 MZN');
+ expect(html).not.toContain('1 pagamentos');
+ });
it('shows supplier identity with exact totals and preserves filters in its independent pagination', () => {
const html = renderToStaticMarkup(