#!/usr/bin/env node
import'./chunk-5TAVYPOV.js';import*as d from'fs';import*as m from'path';import*as _ from'crypto';import {execSync}from'child_process';import u from'chalk';function x(o){return o.split(`
`).map(a=>a.trimEnd()).filter(a=>a.trim().length>0).join(`
`).replace(/\s+/g," ").trim()}function j(o){let a=[],l=/^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@/gm,i;for(;(i=l.exec(o))!==null;)a.push({oldStart:parseInt(i[1],10),oldCount:i[2]!==void 0?parseInt(i[2],10):1,newCount:i[4]!==void 0?parseInt(i[4],10):1});return a}function T(o,a,l,i,c){let h;try{h=execSync(`git diff ${l}..HEAD --unified=0 -- "${a}"`,{cwd:o,encoding:"utf8",timeout:5e3});}catch{return null}if(!h.trim())return null;let p=j(h),s=0;for(let t of p){if(t.oldStart+t.oldCount<=i){s+=t.newCount-t.oldCount;continue}if(t.oldStart<c)return null;break}return s===0?null:{newStart:i+s,newEnd:c+s}}function F(o,a,l,i,c,h,p){let s=m.isAbsolute(a)?a:m.join(o,a);if(!d.existsSync(s))return  false;try{let t=d.readFileSync(s,"utf8"),r=i===c?`${l}:${i}`:`${l}:${i}-${c}`,n=h===p?`${l}:${h}`:`${l}:${h}-${p}`;return t.includes(r)?(d.writeFileSync(s,t.replace(r,n),"utf8"),!0):!1}catch{return  false}}async function W(o){let a=process.cwd(),l=m.join(a,".paradigm","aspect-graph.db");if(!d.existsSync(l)){o.json?console.log(JSON.stringify({driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[]})):console.log(u.gray("No aspect-graph.db found. Run paradigm_aspect_check to initialize."));return}let i=o.autoHeal!==false;try{let c=(await import('sql.js')).default,h=await c(),p=d.readFileSync(l),s=new h.Database(p),t=[];try{let n=s.prepare("SELECT id, aspect_id, file_path, start_line, end_line, content_hash, normalized_hash, materialized_at_commit, drifted FROM anchors"),g=[];for(;n.step();){let e=n.getAsObject();g.push(e);}n.free();for(let e of g){let S=m.isAbsolute(e.file_path)?e.file_path:m.join(a,e.file_path);if(!d.existsSync(S)){t.push({aspectId:e.aspect_id,path:e.file_path,startLine:e.start_line,endLine:e.end_line,status:"missing"});continue}let C=d.readFileSync(S,"utf8").split(`
`),D=Math.max(0,e.start_line-1),R=Math.min(C.length,e.end_line),y=C.slice(D,R).join(`
`),E=_.createHash("sha256").update(y).digest("hex");if(e.content_hash!=null&&E===e.content_hash){e.drifted===1&&s.run("UPDATE anchors SET drifted = 0 WHERE id = ?",[e.id]),t.push({aspectId:e.aspect_id,path:e.file_path,startLine:e.start_line,endLine:e.end_line,status:"clean"});continue}let H=_.createHash("sha256").update(x(y)).digest("hex");if(e.normalized_hash!=null&&H===e.normalized_hash){s.run("UPDATE anchors SET content_hash = ?, drifted = 0 WHERE id = ?",[E,e.id]),t.push({aspectId:e.aspect_id,path:e.file_path,startLine:e.start_line,endLine:e.end_line,status:"cosmetic"});continue}if(e.content_hash==null&&e.normalized_hash==null){s.run("UPDATE anchors SET content_hash = ?, normalized_hash = ?, drifted = 0 WHERE id = ?",[E,H,e.id]),t.push({aspectId:e.aspect_id,path:e.file_path,startLine:e.start_line,endLine:e.end_line,status:"clean"});continue}let $=!1;if(e.materialized_at_commit){let f=T(a,e.file_path,e.materialized_at_commit,e.start_line,e.end_line);if(f){let w=C.slice(Math.max(0,f.newStart-1),Math.min(C.length,f.newEnd)).join(`
`),L=_.createHash("sha256").update(w).digest("hex");if(e.content_hash!=null&&L===e.content_hash||e.normalized_hash!=null&&_.createHash("sha256").update(x(w)).digest("hex")===e.normalized_hash){if(i){let k=_.createHash("sha256").update(w).digest("hex");s.run("UPDATE anchors SET start_line = ?, end_line = ?, content_hash = ?, drifted = 0 WHERE id = ?",[f.newStart,f.newEnd,k,e.id]);let b=s.prepare("SELECT defined_in FROM aspects WHERE id = ?");if(b.bind([e.aspect_id]),b.step()){let z=b.getAsObject();F(a,z.defined_in,e.file_path,e.start_line,e.end_line,f.newStart,f.newEnd);}b.free();}t.push({aspectId:e.aspect_id,path:e.file_path,startLine:i?f.newStart:e.start_line,endLine:i?f.newEnd:e.end_line,status:"shifted",autoHealed:i}),$=!0;}}}$||(s.run("UPDATE anchors SET drifted = 1 WHERE id = ?",[e.id]),t.push({aspectId:e.aspect_id,path:e.file_path,startLine:e.start_line,endLine:e.end_line,status:"modified"}));}let A=s.export();d.writeFileSync(l,Buffer.from(A));}finally{s.close();}let r={driftedCount:t.filter(n=>n.status==="modified").length,healedCount:t.filter(n=>n.status==="shifted"&&n.autoHealed).length,cleanCount:t.filter(n=>n.status==="clean"||n.status==="cosmetic").length,missingCount:t.filter(n=>n.status==="missing").length,details:t};if(o.json)console.log(JSON.stringify(r));else {if(console.log(u.blue(`
Aspect Drift Check
`)),r.healedCount>0&&console.log(u.green(`  Auto-healed: ${r.healedCount} shifted anchor(s)`)),r.cleanCount>0&&console.log(u.green(`  Clean: ${r.cleanCount} anchor(s)`)),r.driftedCount>0){console.log(u.red(`  Drifted: ${r.driftedCount} anchor(s) (content changed)`));for(let n of t.filter(g=>g.status==="modified"))console.log(u.red(`    ${n.aspectId}: ${n.path}:${n.startLine}-${n.endLine}`));}r.missingCount>0&&console.log(u.yellow(`  Missing: ${r.missingCount} anchor file(s) deleted`)),r.driftedCount===0&&r.missingCount===0?console.log(u.green(`
  All anchors are clean.
`)):console.log(u.gray(`
  Run paradigm_aspect_check to review and fix.
`));}}catch(c){o.json?console.log(JSON.stringify({driftedCount:0,healedCount:0,cleanCount:0,missingCount:0,details:[],error:String(c)})):console.log(u.red(`Drift check failed: ${c}`));}}export{W as driftCheckCommand};