import assert from 'node:assert/strict'; import {createHash} from 'node:crypto'; import {existsSync, mkdirSync, readFileSync, readdirSync, realpathSync, statSync, writeFileSync} from 'node:fs'; import {basename, extname, join, relative, resolve} from 'node:path'; export const developmentLabels = Object.freeze({ PLANNED:'PLAN / SINANMADI', LOCAL_VALIDATED:'YEREL DOĞRULAMA', DEVELOPMENT_GUEST_ACCEPTED:'KONUK GELİŞTİRME TESTİ GEÇTİ', PARTIAL_EXTERNAL:'DIŞ DOĞRULAMA BEKLİYOR', PARTIAL_GUEST_PROFILE:'PROFİL EKSİK', }); export const digest = bytes => createHash('sha256').update(bytes).digest('hex'); export function safeArtifact(root, path) { assert.equal(typeof path,'string'); assert.ok(!path.startsWith('/')&&!path.includes('\\')&&!path.split('/').some(p=>p==='..'||p==='.'||p==='')); assert.match(path,/^(reports\/os-implementation\/|kernel\/|bootinfo\/|userspace\/|bootloader\/|\.cargo\/|scripts\/|os-[a-z0-9-]+\/)/); const file=resolve(root,path), actual=realpathSync(file); assert.ok(actual.startsWith(realpathSync(root)+'/'),'artifact escapes project'); assert.ok(statSync(actual).isFile());return file; } export function validateDevelopment(progress, plan) { assert.equal(progress.moves.length,plan.moves.length); const counts={locallyValidated:0,developmentGuestAccepted:0,partialExternal:0,partialGuestProfile:0,notAccepted:0,productAccepted:0}; for(const [i,move] of progress.moves.entries()) { assert.equal(move.id,plan.moves[i].id);assert.ok(move.status in developmentLabels); assert.equal(move.productAccepted,false,'development evidence cannot grant product acceptance'); if(move.status==='PLANNED')assert.equal(move.evidence,null); else {assert.match(move.evidence?.sha256??'',/^[a-f0-9]{64}$/);assert.match(move.evidence?.path??'',/^reports\/os-implementation\/.+\.json$/);} if(move.status==='LOCAL_VALIDATED')counts.locallyValidated++; else if(move.status==='DEVELOPMENT_GUEST_ACCEPTED')counts.developmentGuestAccepted++; else {counts.notAccepted++;if(move.status==='PARTIAL_EXTERNAL')counts.partialExternal++; if(move.status==='PARTIAL_GUEST_PROFILE')counts.partialGuestProfile++;} } assert.deepEqual(progress.counts,counts,'progress counters must match individual evidence states'); const accepted=progress.moves.filter(m=>m.status==='DEVELOPMENT_GUEST_ACCEPTED').at(-1); assert.equal(progress.lastAcceptedGuest,accepted?.id); assert.ok(progress.moves.some(m=>m.id===progress.nextImplementation)); return counts; } const redact=(text,root)=>String(text).replaceAll(root,'').replace(/\/Users\/[^/\s"']+/g,'') .replace(/\/var\/folders\/[^\s"'<>]+/g,''); const textExtensions=new Set(['.rs','.S','.ld','.mjs','.js','.toml','.md','.log','.txt']); function artifacts(value, out=[], depth=0) { if(depth>6||out.length>=400||!value||typeof value!=='object')return out; if(typeof value.path==='string'&&/^[a-f0-9]{64}$/.test(value.sha256??'')){out.push(value);return out;} for(const [key,item] of Object.entries(value))if(!['main','inheritedUserElf','inheritedStatUserElf','inheritedDupUserElf'].includes(key))artifacts(item,out,depth+1); return out; } function testSummary(report) { const tests=report.tests??{}; return Object.fromEntries(Object.entries(tests).filter(([,v])=>['number','boolean','string'].includes(typeof v))); } export function buildDevelopment(root, output, plan) { const progressBytes=readFileSync(join(root,'reports/os-implementation/progress.json')); const progress=JSON.parse(progressBytes);const counts=validateDevelopment(progress,plan); const evidenceDir=join(output,'os-evidence');mkdirSync(evidenceDir,{recursive:true}); const saved=new Map(), reports=new Map(), unavailable=[]; const recoveryPath=join(root,'scripts/os-public-source-archives.json'); const recoveries=existsSync(recoveryPath)?JSON.parse(readFileSync(recoveryPath)):[]; assert.ok(Array.isArray(recoveries)); function sourceBytes(item) { try { const bytes=readFileSync(safeArtifact(root,item.path)); if(digest(bytes)===item.sha256)return {bytes}; } catch {} for(const row of recoveries.filter(row=>row.original===item.path&&row.sha256===item.sha256)) { try { assert.ok(row.path.startsWith('reports/os-implementation/')); const bytes=readFileSync(safeArtifact(root,row.path)); if(digest(bytes)===item.sha256)return {bytes,recoveredFrom:row.path}; } catch {} } throw new Error('source bytes no longer match the recorded hash'); } function exportText(item) { if(!textExtensions.has(extname(item.path)))return null; const key=item.path+':'+item.sha256;if(saved.has(key))return saved.get(key); try { const {bytes,recoveredFrom}=sourceBytes(item); assert.ok(bytes.length<=4*1024*1024,'text exceeds the public excerpt limit'); let decoded,escapedControlBytes=false; if(extname(item.path)==='.log') { try {decoded=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes);} catch {decoded=Array.from(bytes,byte=>byte>=128?'\\x'+byte.toString(16).padStart(2,'0'):String.fromCharCode(byte)).join('');escapedControlBytes=true;} decoded=decoded.replace(/[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]/g,char=>{ escapedControlBytes=true;return '\\x'+char.charCodeAt(0).toString(16).padStart(2,'0'); }); } else { assert.ok(!bytes.includes(0),'binary artifact is not a text download'); decoded=new TextDecoder('utf-8',{fatal:true,ignoreBOM:true}).decode(bytes); } const text=redact(decoded,root),publicHash=digest(text); const href='/os-evidence/'+publicHash+'.txt';writeFileSync(join(output,href.slice(1)),text); const result={name:basename(item.path),source:item.path,originalSha256:item.sha256, href,sha256:publicHash,bytes:Buffer.byteLength(text),redacted:text!==decoded, ...(recoveredFrom?{recoveredFrom}:{}),...(escapedControlBytes?{escapedControlBytes:true}:{})}; saved.set(key,result);return result; } catch(error) { const result={name:basename(item.path),source:item.path,originalSha256:item.sha256,href:null, unavailable:'Kayıttaki hash ile eşleşen, izin verilen boyutta bir metin dosyası bulunamadı.'}; saved.set(key,result);unavailable.push(result);return result; } } const moves=progress.moves.map(move=>({id:move.id,status:move.status,scope:move.scope??null, required:move.required??null,productAccepted:false,evidence:null})); for(const [i,move] of progress.moves.entries()) { if(!move.evidence)continue; const {path,sha256}=move.evidence; if(!reports.has(sha256)) { const file=safeArtifact(root,path),bytes=readFileSync(file); assert.equal(digest(bytes),sha256,`evidence report changed: ${path}`); const report=JSON.parse(bytes),selected=[]; for(const key of ['sources','tests','commands','contract','fixture','journalFixture','harness','mutant','mutations','build']) artifacts(report[key],selected); if(report.candidate?.path&&report.candidate.sha256) { const candidateBytes=readFileSync(safeArtifact(root,report.candidate.path)); assert.equal(digest(candidateBytes),report.candidate.sha256); const candidate=JSON.parse(candidateBytes); artifacts(candidate.sources,selected);artifacts(candidate.build,selected); const nativePrograms=candidate.nativePrograms??[]; assert.ok(Array.isArray(nativePrograms),'native program source list'); for(const [sources,userReport] of [[candidate.nativeUserSources,candidate.segmentUserReport], [candidate.nativeNewUserSources,candidate.segmentNewUserReport], ...nativePrograms.map(program=>[program.sources,program.report])]) { artifacts(sources,selected); if(userReport?.path&&userReport.sha256) { const userBytes=readFileSync(safeArtifact(root,userReport.path)); assert.equal(digest(userBytes),userReport.sha256); const native=JSON.parse(userBytes); artifacts(native.build,selected);artifacts(native.dependencySources,selected);artifacts(native.harness,selected); } } if(move.id===progress.lastAcceptedGuest)artifacts(candidate.sources?.main,selected); } const cases=Array.isArray(report.cases)?report.cases:[]; for(const row of cases.slice(0,100))artifacts(row.serial,selected); const files=[...new Map(selected.map(item=>[item.path+item.sha256,item])).values()].map(exportText).filter(Boolean); const summary={schema:'turkos-public-development-evidence/v1',originalReport:{path,sha256,bytes:bytes.length}, status:report.status??null,scope:redact(report.scope??report.boundary??'Kapsam için bağlı kayıtları inceleyin.',root), productAccepted:false,tests:testSummary(report),caseCount:cases.length, caseSerialsSelected:Math.min(cases.length,100),imageSha256:report.image?.sha256??null, files,moves:[]}; reports.set(sha256,summary); } const summary=reports.get(sha256);summary.moves.push(move.id); moves[i].evidence={href:'/os-evidence/'+sha256+'.json',sha256,recordId:sha256}; } // Explicit completed preparation/component records do not advance roadmap // acceptance. Bind the report and each selected download by its exact hash. const experiments=[]; const experimentsPath=join(root,'scripts/os-development-experiments.json'); const registered=existsSync(experimentsPath)?JSON.parse(readFileSync(experimentsPath)):[]; assert.ok(Array.isArray(registered)&®istered.length<=1000); const experimentIds=new Set(); for(const row of registered) { assert.match(row.id,/^K\d+-[a-z0-9-]+$/);assert.ok(!experimentIds.has(row.id));experimentIds.add(row.id); assert.ok(plan.moves.some(move=>move.id===row.milestone)); assert.equal(typeof row.title,'string');assert.equal(typeof row.scope,'string'); assert.match(row.report?.sha256??'',/^[a-f0-9]{64}$/); const bytes=readFileSync(safeArtifact(root,row.report.path)); assert.equal(digest(bytes),row.report.sha256,'experiment report changed'); const report=JSON.parse(bytes); assert.equal(report.status,row.status);assert.doesNotMatch(row.status,/RUNNING|PENDING/); assert.match(row.status,/(?:PASSED|FAILED|COMPILED|GUEST_RETURNED|CORRECTED_AND_TESTED)/); assert.notEqual(report.guestAccepted,true);assert.notEqual(report.productAccepted,true); assert.ok(Array.isArray(row.files)&&row.files.length<=100); const files=row.files.map(exportText).filter(Boolean); const summary={schema:'turkos-public-development-experiment/v1',id:row.id,milestone:row.milestone, title:redact(row.title,root),scope:redact(row.scope,root),status:report.status, originalReport:{...row.report,bytes:bytes.length},guestAccepted:false,productAccepted:false,files}; const href='/os-evidence/experiment-'+row.report.sha256+'.json'; writeFileSync(join(output,href.slice(1)),JSON.stringify(summary,null,2)+'\n'); experiments.push({...summary,href}); } // Discover completed failed attempts only at known shallow report locations. // Expected mutant failures and deliberate process cuts are not failed runs. const failures=[]; const parent=join(root,'reports/os-implementation'); for(const entry of readdirSync(parent,{withFileTypes:true})) { if(!entry.isDirectory()||!/^K\d/.test(entry.name))continue; const dir=join(parent,entry.name),lifecycle=join(dir,'scoped-lifecycle.json'); let reportPath,report,kind; if(existsSync(lifecycle)) { const value=JSON.parse(readFileSync(lifecycle)); if(value.status==='RUNNER_FAILED'){report=value;reportPath=lifecycle;kind='Sanal makine koşusu başarısız';} } else if(/(?:user-(?:staging|build)|staging-(?:build|test|local)|candidate|compile|preflight|harness-failed)-/.test(entry.name)) { const path=join(dir,'report.json'); if(existsSync(path)&&statSync(path).size<4*1024*1024) { const value=JSON.parse(readFileSync(path)); if(/(?:COMPILE|BUILD)_FAILED|STAGING_BUILD_FAILED/.test(value.status??'')) {report=value;reportPath=path;kind='Derleme başarısız';} else if(/^(?:STAGING_(?:TEST|LOCAL)_FAILED|K\d+_[A-Z0-9_]+_HARNESS_FAILED)$/.test(value.status??'')) {report=value;reportPath=path;kind='Hazırlık testi başarısız';} } } if(!report)continue; const selected=artifacts([report.build,report.log,report.test,report.tests,report.source,report.linker,report.commands,report.sources,report.dependencySources,report.harness,report.nativeUserSources,report.nativeNewUserSources,report.kernelBuildLog]); // A completed failed run can retain a diagnostic serial log at its root. const diagnosticDirs=[dir,...readdirSync(dir,{withFileTypes:true}).filter(f=>f.isDirectory()&&f.name.startsWith('product-')).map(f=>join(dir,f.name))]; for(const diagnosticDir of diagnosticDirs)for(const file of readdirSync(diagnosticDir,{withFileTypes:true})) { if(!file.isFile()||!/(?:failed|failure|stderr|error).*\.(?:log|txt)$/.test(file.name))continue; const path=join(diagnosticDir,file.name); if(statSync(path).size<=4*1024*1024)selected.push({path:relative(root,path),sha256:digest(readFileSync(path))}); } const files=selected.map(exportText).filter(Boolean); const originalReport={path:relative(root,reportPath),sha256:digest(readFileSync(reportPath))}; failures.push({id:entry.name,kind,originalReport,at:report.completedAt??statSync(reportPath).mtime.toISOString(), detail:redact(String(report.failure??report.error??report.cause??'Başarısız deneme arşivlendi; sonraki denemelerin sonucu ayrıca gösterilir.'),root),files}); } failures.sort((a,b)=>b.at.localeCompare(a.at)); const entries=[...reports.values()].sort((a,b)=>Number(b.moves.at(-1).slice(1))-Number(a.moves.at(-1).slice(1))); for(const entry of entries)writeFileSync(join(evidenceDir,entry.originalReport.sha256+'.json'),JSON.stringify(entry,null,2)+'\n'); const snapshot={schema:'turkos-public-development/v1',generatedAt:new Date().toISOString(), progressUpdatedAt:progress.generatedAt,sourceProgressSha256:digest(progressBytes), lastAcceptedGuest:progress.lastAcceptedGuest,nextImplementation:progress.nextImplementation,counts, productAccepted:false,publication:'Snapshot at site build time; ongoing runs are not accepted until their evidence gate completes.', coverage:'Hash-checked progress reports, relevant source/test text and selected guest serial logs. Full VM memory captures, disk images and oversized logs stay in the local archive. Local machine paths are redacted in downloadable text; both hashes are retained.', evidenceReports:entries.length,textDownloads:new Set([...saved.values()].filter(f=>f.href).map(f=>f.href)).size, experimentReports:experiments.length,experiments,unavailable,failures,moves}; writeFileSync(join(output,'K601-K2500-development.json'),JSON.stringify(snapshot,null,2)+'\n'); return {...snapshot,reports:entries}; }