Files
SGF/scripts/summarize-native-warehouse-return.mjs
T
2026-11-02 20:29:34 +02:00

78 lines
11 KiB
JavaScript

import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {spawnSync} from 'node:child_process';
const read=p=>JSON.parse(fs.readFileSync(p,'utf8').replace(/^\uFEFF/,''));
const hash=p=>crypto.createHash('sha256').update(fs.readFileSync(p)).digest('hex');
const state=read('C:/laragon/data/sgf-tempo/run/modular-regression-current.json');
if(state.port!==55439||state.id!=='2576427d1939')throw Error('Unexpected isolated cluster');
const privateRoot=path.join(state.root,'private/stock-receipt-115c5b17e171');
const attrs=t=>Object.fromEntries([...t.matchAll(/(\w+)="([^"]*)"/g)].map(m=>[m[1],m[2]]));
const files=['private/stock-receipt-115c5b17e171/return-native-1793639486315-junit.xml',
'private/stock-receipt-115c5b17e171/return-native-1793640514403-junit.xml',
'private/stock-receipt-cc99dcb17e19/return-reversals-junit.xml','stock-read-1793636847404.xml'];
const selected=new Map();
const proofs=files.map(name=>{
const file=path.join(state.root,name),xml=fs.readFileSync(file,'utf8'),suite=attrs(xml.match(/<testsuite\b[^>]*>/)[0]);
if(Number(suite.errors)||Number(suite.failures)||Number(suite.skipped))throw Error('Nonpassing evidence');
const cases=[...xml.matchAll(/<testcase\b[^>]*\/>|<testcase\b[^>]*>[\s\S]*?<\/testcase>/g)].map(m=>attrs(m[0].match(/^<testcase\b[^>]*>/)[0]));
if(cases.length!==Number(suite.tests))throw Error('Wrong case count');
for(const c of cases)selected.set(c.classname+'::'+c.name,{name:c.name,assertions:Number(c.assertions),proof:name});
return {file:name,sha256:hash(file),tests:Number(suite.tests),assertions:Number(suite.assertions),errors:0,failures:0};
});
const artifact='../compras/packages/inventory-return/releases/0.1.0',manifest=read(artifact+'/manifest.json');
const manifestHash='2850a4f5cb678acfe3a9dbc7a7d62eb233bc72722ad0de374681c2679c90557c';
if(hash(artifact+'/manifest.json')!==manifestHash)throw Error('Artifact changed');
for(const [f,sha] of Object.entries(manifest.files))if(hash(artifact+'/'+f)!==sha||hash('packages/inventory-return/'+f)!==sha)throw Error('Writer mismatch');
const observerPath=path.join(state.root,'stock-read-1793636847404.json'),observer=read(observerPath);
const fixturePath=path.join(privateRoot,'return-results-'+observer.native_fixture_sha256+'.json'),fixture=read(fixturePath);
if(hash(fixturePath)!==observer.native_fixture_sha256||fixture.return_movement!==observer.observed_return_movement_id||fixture.physical_milli!==observer.physical_milli)throw Error('Observer provenance mismatch');
for(const k of ['tenant','warehouse','item','return_movement'])if(!Number.isSafeInteger(fixture[k])||fixture[k]<1)throw Error('Invalid fixture identity');
const connection=read(path.join(privateRoot,'source-connection.json'));
if(connection.port!==55439||connection.database!=='compras_receipts_test_115c5b17e171'||connection.username!=='stock_receipt_read_115c5b17e171')throw Error('Wrong reader');
const sql=`BEGIN READ ONLY;
SELECT json_build_object('cluster',current_setting('cluster_name'),'database',current_database(),'role',current_user,'read_only',current_setting('default_transaction_read_only'),
'elevated',(SELECT rolsuper OR rolcreatedb OR rolcreaterole OR rolreplication OR rolbypassrls FROM pg_roles WHERE rolname=current_user),
'select_book',has_table_privilege(current_user,'stock_movements','SELECT'),'can_write_book',has_table_privilege(current_user,'stock_movements','INSERT,UPDATE,DELETE'),
'select_native_operations',has_table_privilege(current_user,'stock_operations','SELECT'),
'movements',(SELECT count(*) FROM stock_movements WHERE tenant_id=${fixture.tenant} AND stock_item_id=${fixture.item} AND warehouse_id=${fixture.warehouse}),
'physical_milli',(SELECT sum(quantity_milli)::text FROM stock_movements WHERE tenant_id=${fixture.tenant} AND stock_item_id=${fixture.item} AND warehouse_id=${fixture.warehouse}),
'same_return',(SELECT count(*)=1 FROM stock_movements WHERE id=${fixture.return_movement} AND tenant_id=${fixture.tenant} AND movement_type='workshop_return_in' AND quantity_milli=3000)); ROLLBACK;`;
const pg=spawnSync('C:/Program Files/PostgreSQL/17/bin/psql.exe',['-h','127.0.0.1','-p','55439','-U',connection.username,'-d',connection.database,'-Atq','-v','ON_ERROR_STOP=1'],{input:sql,encoding:'utf8',windowsHide:true,env:{...process.env,PGPASSWORD:connection.password}});
if(pg.status!==0)throw Error('Read-only provenance postcheck failed');
const book=JSON.parse(pg.stdout.trim());
if(book.cluster!=='sgf_modular_regression_'+state.id||book.read_only!=='on'||book.elevated||book.can_write_book||book.select_native_operations||!book.select_book||book.movements!==3||book.physical_milli!=='8000'||!book.same_return)throw Error('Reader or retained fixture changed');
const previous=read('docs/proofs/module-association-http-lock-summary-20261102.json');
for(const p of [previous.proof,...previous.previous_proofs])if(hash(p.path)!==p.sha256)throw Error('Prior association evidence changed');
const load=read('docs/proofs/stock-read-load-20261102.json');
if(hash('packages/inventory-read/src/InventoryReader.php')!==load.source_sha256)throw Error('Load-tested SQL changed');
const post=spawnSync('C:/laragon/tools/sgf-tempo/php-8.4.27/php.exe',['scripts/workshop-stock-state.php'],{encoding:'utf8',windowsHide:true});
if(post.status!==0)throw Error('SGF temporary rights restoration failed');
const uiPath='docs/proofs/native-return-ui-20261102.json',ui=read(uiPath);
for(const [f,sha] of Object.entries(ui.inputs_sha256))if(hash('../compras/'+f)!==sha)throw Error('UI evidence stale');
const renderPath='docs/proofs/native-return-history-render-20261102.json',render=read(renderPath);
if(render.component_sha256!==hash('../compras/resources/js/pages/stock/operations.tsx')||render.page_sha256!==hash(path.join(privateRoot,'native-stock-history-page.json'))||!render.render_passed)throw Error('Render evidence stale');
const build=read(path.join(privateRoot,'return-private-build.json'));
if(!build.passed||build.manifest_sha256!==hash(path.join(privateRoot,'app/public/build/manifest.json')))throw Error('Private build missing or stale');
const analysis=read(path.join(privateRoot,'return-phpstan.json'));if(analysis.result!=='passed'||analysis.errors!==0)throw Error('PHP analysis failed');
const sourceFiles=['../compras/app/Services/WarehouseReturns.php','../compras/app/Services/WarehouseReturnMovement.php','../compras/app/Http/Controllers/WarehouseReturnController.php','../compras/app/Services/InventoryReversals.php','../compras/app/Services/SupplyHistory.php','../compras/app/Services/OrganizationAccess.php','../compras/config/stock_returns.php','../compras/routes/web.php','../compras/tests/Feature/WarehouseReturnIntegrationTest.php','../compras/tests/Support/warehouse-return-worker.php','resources/js/StockReadWorkspace.jsx','tests/Feature/StockReadTest.php'];
if(!fs.readFileSync('../compras/config/stock_returns.php','utf8').includes("'enabled' => false"))throw Error('Unexpected activation');
const report={date:'2026-11-02',increment:'NATIVE-WAREHOUSE-UNUSED-RETURN-SIM-v1',status:'local_synthetic_implementation',proofs,
totals:{distinct_tests:selected.size,assertions:[...selected.values()].reduce((n,c)=>n+c.assertions,0)},selected_cases:[...selected.values()],
evidence_selection:'18 native cases, one new forecast-boundary case, 16 affected reversal cases, one SGF observer case. Valid overlapping earlier runs are not added. Observer binds an archived retained fixture; subsequent native tests used new isolated tenants.',
scenario:{receipt_milli:'10000',acknowledged_delivery_milli:'5000',physical_after_delivery:'5000',declared_unused_return_milli:'3000',physical_after_return:'8000',movements:3,one_shared_writer:true,native_standalone_requires_sgf:false,sgf_read_only_observes_same_movement:true},
controls:{individual_unused_declaration:true,independent_physical_receipt:true,original_source_snapshots_preserved:true,append_only_decisions:true,versions_context_permissions_revalidated:true,withdrawal_and_rejection_without_stock_effect:true,source_reversal_after_partial_return_refused:true,transaction_failure_recovery:true,package_failure_503_recovery:true,history_metadata_rendered:true,replenishment_signal_once_inside_transaction:true},
concurrency:{real_processes:2,company_row_blocker_observed:true,after_release_same_proposal:'200 replay; one movement',competing_returns:'one confirmed; second 409 after release',withdraw_confirm:'one terminal state in both lock orders',http_lock_timeout:'423 warehouse_return_busy; no effects; explicit retry after release succeeds'},
history:read(path.join(privateRoot,'return-history-metrics.json')),forecast_boundary:read(path.join(privateRoot,'return-forecast-boundary.json')),
package:{manifest_sha256:manifestHash,canonical_matches_native_artifact:true,writer_unchanged:true},observer:{proof_sha256:hash(observerPath),fixture_archive_sha256:hash(fixturePath),...observer},
postchecks:{native_retained_book:book,sgf:JSON.parse(post.stdout)},
ui:{proof:uiPath,sha256:hash(uiPath),...ui},history_render:{proof:renderPath,sha256:hash(renderPath),...render},qualified_private_build:build,php_analysis:analysis,
source_sha256:Object.fromEntries(sourceFiles.map(f=>[f,hash(f)])),
reused_proofs:Object.fromEntries(['docs/proofs/workshop-material-cycle-20261102.json','docs/proofs/stock-read-load-20261102.json','docs/proofs/module-association-http-lock-summary-20261102.json'].map(f=>[f,hash(f)])),
preservation:{six_pending_associations_untouched:true,blocked_cache_untouched:true,demos_and_real_data_untouched:true,no_real_rights_granted:true,native_synthetic_profiles_retained_in_separate_qa_database:true,sgf_temporary_rights_restored:true,regression_not_reset:true,existing_proofs_preserved:true,activation:false,publication:false,checkpoint:false},
limits:['Native unused quantity is an explicit recipient declaration; no SGF technical-consumption register is consulted by the standalone native flow.','Only internal warehouse deliveries; no lots, equipment/spare parts, reservation-bearing articles, quality or quarantine.','No consumed-material compensation or automatic reversal of confirmed returns.','Historical forecast preserves gross issue convention; net return forecasting is not implemented.','SGF observation is isolated QA evidence, not installation of a full operational composition.','No write-load capacity, visual review, browser interaction or deployment validation.','Qualified private asset build omits optional React compiler and font downloading; default optimized build is not validated.'],
visual_review_pending:true,deployment_capacity_validated:false};
fs.writeFileSync('docs/proofs/native-warehouse-return-20261102.json',JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify({totals:report.totals,postchecks:report.postchecks,package:report.package},null,2));