diff --git a/desktop/src-tauri/src/render_audit.rs b/desktop/src-tauri/src/render_audit.rs index efa856a0..4998eb40 100644 --- a/desktop/src-tauri/src/render_audit.rs +++ b/desktop/src-tauri/src/render_audit.rs @@ -5,7 +5,7 @@ use block2::RcBlock; use objc2::runtime::AnyObject; use objc2::{AnyThread, MainThreadMarker}; use objc2_app_kit::{ - NSBitmapImageFileType, NSBitmapImageRep, NSFloatingWindowLevel, NSImage, NSWindow, + NSApplication, NSBitmapImageFileType, NSBitmapImageRep, NSFloatingWindowLevel, NSImage, NSWindow, }; use objc2_foundation::{NSDictionary, NSError, NSSize, NSString}; use objc2_web_kit::{WKSnapshotConfiguration, WKWebView}; @@ -1031,7 +1031,11 @@ const LABEL_GEOMETRY_COLLECT: &str = r#"JSON.stringify((()=>{ if(Math.min(r.right,q.right)-Math.max(r.left,q.left)>.5&&Math.min(r.bottom,q.bottom)-Math.max(r.top,q.top)>.5)overlapPairs++; } } + const hud=document.querySelector('.knowledge-map-caption'),hs=hud?getComputedStyle(hud):null,hr=hud?.getBoundingClientRect(); + const hudVisible=!!hud&&!hud.hidden&&hs.display!=='none'&&hs.visibility!=='hidden'&&hr.width>0&&hr.height>0; + const hudOverlapPairs=hudVisible?visible.filter(r=>Math.min(r.right,hr.right)-Math.max(r.left,hr.left)>.5&&Math.min(r.bottom,hr.bottom)-Math.max(r.top,hr.top)>.5).length:0; return {scope:'audit-only bounded element rectangles; no label text/IDs or physical/font-ink proof', + hudSampled:hudVisible?1:0,hudOverlapPairs,hudBounds:hudVisible?{left:hr.left,top:hr.top,right:hr.right,bottom:hr.bottom}:null, totalLabels:all.length,sampledLabels:boxes.length,truncated:all.length>24,visibleLabels:visible.length, unpositionedLabels:boxes.filter(b=>!b.positioned).length, visibleUnpositionedLabels:visible.filter(b=>!b.positioned).length, @@ -1633,7 +1637,7 @@ fn audit_graph_scope(window: &tauri::WebviewWindow, output: &Output, deadline: I if case==10 {state["qualityComparison"]=audit_quality_comparison(window,output,deadline,size)?;} publish(output,&format!("graph-scope-{size}.json"),&serde_json::to_vec_pretty(&state).map_err(|_|"scope JSON failed")?,deadline)?; eprintln!("Alden scope {case}: {size} files delivered"); - if case==0 {audit_graph_zoom(window,output,deadline,size)?;} + if case==0 || case==3 {audit_graph_zoom(window,output,deadline,size)?;} states.push(state); } Ok(json!({"case":case,"states":states,"scope":"fixed observed projects/filter/next-page, two owned window sizes, read-only"})) @@ -1643,20 +1647,37 @@ fn audit_graph_scope(window: &tauri::WebviewWindow, output: &Output, deadline: I // actual OrbitControls and the product projection path, not physical gestures. fn audit_graph_zoom(window: &tauri::WebviewWindow, output: &Output, deadline: Instant, size: &str) -> Result<(),String> { let mut states=Vec::new(); - for (name,ratio,expected) in [("distant",0.55_f64,0),("context",1.7,2),("detail",2.5,3)] { + for (name,ratio,expected) in [("distant",0.55_f64,0),("context",1.7,2),("detail",2.5,3),("returned",0.55,0)] { collect_script(window,"JSON.stringify((()=>{document.querySelector('#knowledge-camera-reset').click();return {reset:true};})())".into(),deadline)?; - wait_for_audit_state("zoom reset",deadline,||collect_script(window,graph_collect_script(),deadline), + let reset = wait_for_audit_state("zoom reset",deadline,||collect_script(window,graph_collect_script(),deadline), |s|s["motion"]["camera"]==false&&s["motion"]["labelZoomRatio"].as_f64().is_some_and(|r|(r-1.0).abs()<0.02))?; + if reset["labelGeometryObservation"]["visibleLabels"] != 0 { + return Err(format!("passive labels remained at fitted zoom: {reset}")); + } let delta:f64=-ratio.ln()/(-0.95_f64.ln()*0.7*0.01); collect_script(window,format!(r#"JSON.stringify((()=>{{const c=document.querySelector('#knowledge-graph-canvas'),r=c.getBoundingClientRect();c.dispatchEvent(new WheelEvent('wheel',{{deltaY:{delta},deltaMode:0,clientX:r.x+r.width/2,clientY:r.y+r.height/2,bubbles:true,cancelable:true}}));return {{syntheticWheel:true}};}})())"#),deadline)?; let navigation=wait_for_audit_state("zoom labels paint",deadline,||collect_script(window,graph_collect_script(),deadline), |s|s["motion"]["camera"]==false && s["motion"]["labelZoom"]==expected)?; let labels=collect_script(window,LABEL_GEOMETRY_COLLECT.into(),deadline)?; - if labels["overlapPairs"]!=0 || labels["clippedLabels"]!=0 || labels["visibleUnpositionedLabels"]!=0 || labels["truncated"]!=false { + if labels["overlapPairs"]!=0 || labels["clippedLabels"]!=0 || labels["visibleUnpositionedLabels"]!=0 || labels["truncated"]!=false || labels["hudOverlapPairs"]!=0 || labels["hudSampled"]!=1 { return Err(format!("zoom label geometry failed: {labels}")); } - publish(output,&format!("graph-zoom-{size}-{name}.png"),&snapshot(window,deadline)?,deadline)?; - states.push(json!({"level":name,"requestedRatio":ratio,"navigation":navigation,"labels":labels})); + if expected == 0 && (labels["totalLabels"] != 0 || labels["visibleLabels"] != 0) + || expected >= 2 && labels["visibleLabels"].as_u64().unwrap_or(0) == 0 { + return Err(format!("zoom reveal/clear contract failed at {name}: {labels}")); + } + let native = minimized_native_state(window, false, deadline)?; + if native["applicationActive"] != false || native["key"] != false + || native["alpha"] != 0.0 || native["level"] != 0 { + return Err(format!("zoom capture violated background constraints: {native}")); + } + // Keep the existing fixed PNG allowlist. The fourth transition records + // actual native/render state without replacing the first distant image. + if name != "returned" { + publish(output,&format!("graph-zoom-{size}-{name}.png"),&snapshot(window,deadline)?,deadline)?; + } + states.push(json!({"level":name,"requestedRatio":ratio,"navigation":navigation,"labels":labels, + "resetLabels":reset["labelGeometryObservation"],"nativeBackground":native})); } publish(output,&format!("graph-zoom-{size}.json"),&serde_json::to_vec_pretty(&json!({"states":states, "scope":"owned native synthetic wheel input; actual product camera and labels; no physical gesture or FPS proof"})).map_err(|_|"zoom JSON failed")?,deadline)?; @@ -1671,6 +1692,31 @@ fn scoped_blur_preserved(state: &Value) -> bool { }) } +// Audit-only: minimize the actual owned AppKit window without +// injecting visibility events or modifying the production renderer lifecycle. +fn minimized_native_state( + window: &tauri::WebviewWindow, + minimize: bool, + deadline: Instant, +) -> Result { + live(deadline)?; + let target = window.clone(); + let (tx, rx) = mpsc::sync_channel(1); + window.run_on_main_thread(move || { + let result = live(deadline).and_then(|_| { + let mtm = MainThreadMarker::new().ok_or("native state not on main thread")?; + let pointer = target.ns_window().map_err(|_| "native window missing")?; + let native = unsafe { &*pointer.cast::() }; + if minimize { native.miniaturize(None); } + Ok(json!({"visible":native.isVisible(),"minimized":native.isMiniaturized(), + "key":native.isKeyWindow(),"alpha":native.alphaValue(), + "level":native.level(),"applicationActive":NSApplication::sharedApplication(mtm).isActive()})) + }); + let _ = tx.try_send(result); + }).map_err(|_| "native state dispatch failed")?; + receive(rx, deadline) +} + fn audit_settings( app: &tauri::AppHandle, output: &Output, @@ -1682,8 +1728,8 @@ fn audit_settings( let window = app .get_webview_window("settings") .ok_or("settings window missing")?; - // Only this short-lived audit instance: keep its settings renderer - // unoccluded without activating the app or changing the user's key window. + // Graph QA stays transparent and noninteractive in this owned process. + let background_graph = graph_scope.is_some(); live(deadline)?; let target = window.clone(); let (tx, rx) = mpsc::sync_channel(1); @@ -1695,7 +1741,8 @@ fn audit_settings( .map_err(|_| "settings native window missing")?; live(deadline)?; unsafe { - (&*native.cast::()).setLevel(NSFloatingWindowLevel); + (&*native.cast::()).setLevel(if background_graph {0} else {NSFloatingWindowLevel}); + if background_graph { (&*native.cast::()).setAlphaValue(0.0); } // This audit uses fixed JS actions. Physical mouse input // must continue to the user's existing app, not rotate our // floating graph between the saved navigation snapshots. @@ -1716,7 +1763,44 @@ fn audit_settings( ) }, |state| state["mounted"] == true)?; if let Some(case) = graph_scope { - return audit_graph_scope(&window, output, deadline, case); + let target = window.clone(); + let (tx, rx) = mpsc::sync_channel(1); + window.run_on_main_thread(move || { + let result = live(deadline).and_then(|_| { + let mtm = MainThreadMarker::new().ok_or("audit deactivation not on main thread")?; + let app = NSApplication::sharedApplication(mtm); + let was_active = app.isActive(); + app.deactivate(); + Ok(json!({"wasActive":was_active,"afterDeactivateActive":app.isActive()})) + }); + let _ = tx.try_send(result); + drop(target); + }).map_err(|_| "audit deactivation dispatch failed")?; + let deactivation = receive(rx, deadline)?; + let before = minimized_native_state(&window, false, deadline)?; + if before["applicationActive"] != false || before["key"] != false + || before["alpha"] != 0.0 || before["level"] != 0 { + return Err(format!("career zoom diagnostic violated background constraints: native={before}, deactivation={deactivation}")); + } + let mut result = audit_graph_scope(&window, output, deadline, case)?; + let immediate = minimized_native_state(&window, true, deadline)?; + let mut observations = Vec::new(); + for _ in 0..8 { + live(deadline)?; + std::thread::sleep(Duration::from_millis(250)); + let native = minimized_native_state(&window, false, deadline)?; + if native["applicationActive"] != false || native["key"] != false + || native["alpha"] != 0.0 || native["level"] != 0 + || native["minimized"] != true || native["visible"] != false { + return Err("career zoom diagnostic did not remain minimized in background".into()); + } + observations.push(native); + } + result["nativeBackgroundBefore"] = before; + result["nativeOwnedDeactivation"] = deactivation; + result["nativeMinimizeImmediate"] = immediate; + result["nativeMinimizedObservations"] = json!(observations); + return Ok(result); } graph_step(&window, "memory-page", deadline)?; let initial = wait_for_audit_state("initial graph render", deadline, @@ -2750,6 +2834,14 @@ pub fn run(request: Request, mut context: tauri::Context) { // This audit creates one incognito view itself; configured persistent // views must never be created or adopted by the fixture workflow. if request.entity { context.config_mut().app.windows.clear(); } + if request.graph_scope.is_some() { + for window in &mut context.config_mut().app.windows { + window.incognito = true; + window.visible = false; + window.focus = false; + window.always_on_top = false; + } + } let output = Output::open(&request.directory).unwrap_or_else(|error| { eprintln!("Alden render audit: {error}"); std::process::exit(2); diff --git a/desktop/src/__tests__/semantic-overview-placement.test.ts b/desktop/src/__tests__/semantic-overview-placement.test.ts new file mode 100644 index 00000000..b4ae2cfa --- /dev/null +++ b/desktop/src/__tests__/semantic-overview-placement.test.ts @@ -0,0 +1,44 @@ +import {describe,expect,it} from 'vitest'; +import {parseKnowledgeGraph,type KnowledgeView} from '../knowledge/graph-model'; +import {SemanticLayoutEngine} from '../knowledge/semantic-layout'; +import type {LayoutAffinityPair} from '../knowledge/layout-affinity'; + +function scene(star:boolean,duplicateTitles=false):KnowledgeView { + return {...parseKnowledgeGraph({nodes:Array.from({length:256},(_,i)=>({ + id:`n${i.toString().padStart(3,'0')}`,label:duplicateTitles&&(i===1||i===128)?'Same saved title':`Saved topic ${i}`,category:'topic', + })),edges:star?Array.from({length:255},(_,i)=>({source:'n000',target:`n${(i+1).toString().padStart(3,'0')}`,weight:1})):[]}),hops:0,focusId:null}; +} +const affinity=(target:string):LayoutAffinityPair[]=>[{source:'n001',target,cosine:.95}]; +const solve=(view:KnowledgeView,pairs:LayoutAffinityPair[])=>new SemanticLayoutEngine().layout(view,new Map(),pairs,{nowMs:1000}); + +describe('preserve admitted semantic geometry through overview styling',()=>{ + it('lets a different semantic neighbor change the final coordinates of a hub leaf',()=>{ + const view=scene(true),source=JSON.stringify(view); + const first=solve(view,affinity('n128')),second=solve(view,affinity('n129')); + expect(first.diagnostics.affinityPairs).toBe(1);expect(second.diagnostics.affinityPairs).toBe(1); + expect(first.clusterIds.get('n001')).toBe(first.clusterIds.get('n128')); + expect(second.clusterIds.get('n001')).toBe(second.clusterIds.get('n129')); + expect(first.anchors.get('n001')).not.toEqual(second.anchors.get('n001')); + expect(first.anchors.get('n128')).not.toEqual(second.anchors.get('n128')); + expect(JSON.stringify(view)).toBe(source); + }); + + it('does not replace admitted semantic positions with a duplicate-title disk',()=>{ + const view=scene(false,true),source=JSON.stringify(view); + const first=solve(view,affinity('n128')),second=solve(view,affinity('n129')); + expect(first.diagnostics.affinityPairs).toBe(1); + expect(first.anchors.get('n001')).not.toEqual(second.anchors.get('n001')); + expect(JSON.stringify(view)).toBe(source); + }); + + it('keeps structural fallback unchanged for rejected affinity input',()=>{ + const view=scene(true),fallback=solve(view,[]); + for(const pair of [{source:'n001',target:'outside',cosine:.95}, + {source:'n001',target:'n128',cosine:NaN}, + {source:'n001',target:'n128',cosine:0}]){ + const rejected=solve(view,[pair]); + expect(rejected.diagnostics.affinityPairs).toBe(0); + expect(rejected.anchors).toEqual(fallback.anchors); + } + }); +}); diff --git a/desktop/src/knowledge/semantic-layout.ts b/desktop/src/knowledge/semantic-layout.ts index cff1a824..3913715b 100644 --- a/desktop/src/knowledge/semantic-layout.ts +++ b/desktop/src/knowledge/semantic-layout.ts @@ -245,6 +245,7 @@ function placeOverviewStars( edges: ReadonlyArray, pinned: ReadonlySet, nodes: readonly { id?: string; label?: string; category?: string }[], + semanticNodes: ReadonlySet, ): Set { const owned = new Set(); if (ids.length < 256 || pinned.size === 1) return owned; @@ -286,7 +287,7 @@ function placeOverviewStars( const group = members.get(hub) ?? [hub]; const disk = Math.min(.48, .035 * Math.sqrt(group.length)); for (const id of group) { - if (pinned.has(id)) continue; + if (pinned.has(id) || semanticNodes.has(id)) continue; if (id === hub) { anchors.set(id, dest); owned.add(id); continue; } const offset = seed(id), span = Math.hypot(offset.x, offset.y, offset.z) || 1; const reach = .45 + .55 * ((hash(id) % 1000) / 1000); @@ -1008,8 +1009,11 @@ export class SemanticLayoutEngine { const separated = {x:origin.x+v.x*gain,y:origin.y+v.y*gain,z:origin.z+v.z*gain}; anchors.set(id, pinOrigin ? boundNear(separated, pinOrigin) : bound(separated)); }); - const starOwned = placeOverviewStars(ids, anchors, real, pinned, view.nodes); - placeDuplicateLabels(view.nodes, anchors, starOwned, pinned); + // Source hubs and equal titles are fallback geometry. They must not erase + // the positions already solved from admitted content affinities. + const semanticNodes = new Set(semantic.flatMap(([, pair]) => [pair.source, pair.target])); + const starOwned = placeOverviewStars(ids, anchors, real, pinned, view.nodes, semanticNodes); + placeDuplicateLabels(view.nodes, anchors, new Set([...starOwned, ...semanticNodes]), pinned); const dirtyIds = new Set(); for (const id of ids) { const prior = previousPositions.get(id), p = anchors.get(id)!; diff --git a/docs/evaluation/semantic-overview-geometry-20261025.md b/docs/evaluation/semantic-overview-geometry-20261025.md new file mode 100644 index 00000000..e18cd0b7 --- /dev/null +++ b/docs/evaluation/semantic-overview-geometry-20261025.md @@ -0,0 +1,98 @@ +# Preserve semantic coordinates in overview fallback placement + +The engine computed content-affinity coordinates and then replaced them with +hub-star and duplicate-title geometry. On a current1984-node career snapshot, +the final star step moved1689 of1767 nodes incident to an admitted affinity. +On a five-project snapshot it moved492 of586 such nodes. An observer-only copy +of the actual source counted the moves and produced exactly identical final +anchors/clusters to the uninstrumented baseline. This is code/geometry evidence, +not proof that the underlying E5 similarities are semantic truth. + +The final star and duplicate-title steps now act as fallback for nodes without +admitted content affinities. Endpoints retained by the existing bounded affinity +selector keep their already solved coordinates; authoritative pins retain their +existing handling. Rejected/missing affinities retain the structural fallback. +Nodes, memberships, cluster IDs, source relationships/direction, labels, identities, +merge decisions, embedding/profile, edge strengths and budgets are unchanged. + +```mermaid +flowchart LR + A[Current validated input] --> B[Existing bounded force solver] + B --> C{Incident to admitted content affinity?} + C -->|Yes| D[Keep solved coordinates] + C -->|No| E[Existing hub-star or title fallback] + D --> F[Existing renderer] + E --> F +``` + +Two new regressions failed on the baseline: changing an admitted semantic neighbor +did not change a star leaf's final coordinate, and a duplicate-title disk likewise +erased its semantic movement. A third check preserves fallback for malformed or +unavailable affinity input. These three and existing pin/force/budget checks pass; +the final full frontend suite passed1150 checks in103 files and TypeScript/Vite +build passed. Existing large-chunk warnings remain. Those tests are not pixel, +physical gesture, Retina, GPU/FPS, battery or full installed-app evidence. + +Read-only captures came through the installed graph and affinity endpoints, with +exact ordered target/version refs. Five CPU replays per saved input were +deterministic. Same-membership comparison on the1984-node career snapshot reduced +3D point pairs closer than0.025 world units from865 to14; exact coincident pairs +remained0. The fraction inside the declared central ellipsoid threshold changed +0→0.003024. On the1984-node union snapshot, close pairs changed239→113 with0 exact +coincidences and central fraction0 in both. These are world-space diagnostics, +not screen-space overlap or a universally optimal packing result. + +Independent standard-library arithmetic matched the exact SHA-256 of1984 career +and588 union vector blobs to the saved source/vector proofs. In the career case, +1024 admitted-pair median distance changed1.4094→0.2461 world units;278 same-cluster +pairs not directly admitted changed1.4544→0.1841 (median E5 cosine0.9337). +The8192 seeded eligible noncandidate random-pair median changed1.5995→2.0483. +On the union input,790 admitted pairs changed0.4487→0.4403 and307 held-out +within-cluster pairs0.4980→0.3986; its8192 random pairs changed1.4290→0.6753. +The cohorts are separate and not combined into a significance/causality claim. +The original vector space is part of the layout mechanism, so even held-out +cosine checks are not independent human gold, entity equivalence or fact validity. + +The union capture excluded1396 of1984 displayed records from content affinity +(871 empty bodies,518 metadata descriptions,7 source-metadata-only records). +Missing content evidence is not repaired by moving points. Its1396 excluded +records retain fallback geometry; whole messenger/media acquisition remains a +separate gate. Pair sampling remains partial:65,536 comparisons cover about3.33% +of eligible career pairs and52.0% of eligible union pairs. + +A separate read-only experiment used the already supported max_candidates4096 +option while preserving the same source/vector proofs and65,536 comparisons. +It returned2755 pairs, covered1984 rather than1767 candidate endpoints, and changed +career community count989→604. With the old final placement, only89 final positions +changed. This corroborates the overwrite mechanism but is not a promotion of a +larger budget. The product default1024 and all other budgets remain unchanged. + +The protection set adds O(P) work/storage for at most4096 admitted semantic pairs +and a bounded union with existing fallback-owned IDs. It removes no source queries +and changes no solver complexity. Sequential CPU timings from the private +experiments do not establish a speedup. Exact source hashes, raw/probe/setup +failures, geometry/vector reports, canonical build, native render and installed +readback belong under the task output `layout-quality-20261025`; completion of a +later gate is never inferred from this source document. + +This is a scoped defect fix restoring the meaning of an existing force solver. +Current-source external Pro/Gemini/reverse validation remains incomplete under +the preserved upload gate. Local regressions, observer alignment and the flowchart +do not constitute an all-input refinement, safety or liveness proof. + +The first scope3 native capture succeeded, but the reused wrapper wrongly expected +zoom and body-notation outputs that this source had not implemented. Its missing-file +failure is retained; it is not zoom acceptance. The old path also could not attest +transparent/minimized operation. The maintained graph-only audit now creates its +owned windows hidden, unfocused and incognito, sets alpha0 and normal level before +ordering the graph, verifies nonkey/inactive state for each zoom capture, then +minimizes and reads back eight observations. The original primary app is not +adopted or given synthetic input. A minimized-primary physical journey remains +unverified. Actual native pass/failure receipts remain authoritative. + +Scope3 now checks distant/context/detail/returned zoom states at two sizes, +including zero passive labels at fitted and distant zoom, positive labels when +zoomed in, and bounded label/caption rectangles without overlap or clipping. +This is actual product camera/render code with synthetic wheel input, not +physical gestures, font-ink bounds, Retina or performance proof. The audit +changes no product label policy or source data and admits no control writes.