From 2617c3221cab80e02eb9ab694ee0a80d32a1ab33 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 18:45:13 +0000 Subject: [PATCH] docs: add the XR environment audit (102 findings, seven area reports) Seven parallel audits of the XR part (panels, launch pipeline, chart containment, project evolution, dependency graph, historical comparison, mode lifecycle). Each finding has file:line evidence, a failure scenario, its confidence level and a proposed fix. Basis for the XR review epic. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKtAtQus8TVjhG9bhytC --- .claude/docs/INDEX.md | 1 + docs/xr-audit/README.md | 94 +++++++++ docs/xr-audit/charts.md | 370 ++++++++++++++++++++++++++++++++++++ docs/xr-audit/depgraph.md | 266 ++++++++++++++++++++++++++ docs/xr-audit/evolution.md | 326 +++++++++++++++++++++++++++++++ docs/xr-audit/historical.md | 250 ++++++++++++++++++++++++ docs/xr-audit/launcher.md | 324 +++++++++++++++++++++++++++++++ docs/xr-audit/lifecycle.md | 245 ++++++++++++++++++++++++ docs/xr-audit/panels.md | 219 +++++++++++++++++++++ 9 files changed, 2095 insertions(+) create mode 100644 docs/xr-audit/README.md create mode 100644 docs/xr-audit/charts.md create mode 100644 docs/xr-audit/depgraph.md create mode 100644 docs/xr-audit/evolution.md create mode 100644 docs/xr-audit/historical.md create mode 100644 docs/xr-audit/launcher.md create mode 100644 docs/xr-audit/lifecycle.md create mode 100644 docs/xr-audit/panels.md diff --git a/.claude/docs/INDEX.md b/.claude/docs/INDEX.md index 5c575933..6623a6d7 100644 --- a/.claude/docs/INDEX.md +++ b/.claude/docs/INDEX.md @@ -58,6 +58,7 @@ | `docs/cleanup/feature-baseline.md` | EN | Inventory of everything the extension contributes and does (pinned by `test/baseline/`), with the §10 verification checklist | | `docs/cleanup/src-layout.md`, `src-move-map.json` | EN | Story #55: the feature-first `src/` layout and the old → new path map | | `docs/cleanup/{host-boundary,modernization,sweep-outside-src,w2-revalidation}.md` | EN | Layering, idiom modernization, the sweep outside `src/`, the W2 re-validation | +| `docs/xr-audit/README.md` (repository root) | EN | **XR environment audit (2026-11-25)**: 102 findings across panels, launcher, charts/containment, project evolution, dependency graph, historical comparison and mode lifecycle, each with evidence, repro status and proposed fix; per-area reports beside it. Read before fixing anything in the XR epic | ## Task → reading list diff --git a/docs/xr-audit/README.md b/docs/xr-audit/README.md new file mode 100644 index 00000000..2bbcc0d7 --- /dev/null +++ b/docs/xr-audit/README.md @@ -0,0 +1,94 @@ +# XR environment audit (v1.2.1 baseline) + +Date: 2026-11-25. Baseline: `v1.2.1` @ `d89e08d4`, right after the cleanup epic #26. + +This is a bug audit of everything in the extended-reality part of Code-XR: the XR scene templates, the +browser runtimes under `apps/vscode-extension/templates/components/`, how the four in-scene analyses +(classic/single, dependency graph, historical comparison, project evolution) are launched and switched, +and the host-side orchestration that serves them. It was run as seven parallel audits, one per area. +Each area report is in this folder and holds the evidence (file:line), the failure scenario, the +confidence level and a proposed fix for every finding. + +| Area | Report | Findings | Blocker | Major | +|---|---|---|---|---| +| In-scene panels (cards, guide, virtual screens) | [panels.md](panels.md) | 9 | 1 | 3 | +| Host-side launch, servers, sessions | [launcher.md](launcher.md) | 18 | 0 | 10 | +| Chart build, rebuild and containment | [charts.md](charts.md) | 18 | 2 | 9 | +| Project evolution | [evolution.md](evolution.md) | 20 | 1 | 9 | +| Dependency graph | [depgraph.md](depgraph.md) | 12 | 0 | 5 | +| Historical comparison | [historical.md](historical.md) | 13 | 0 | 7 | +| Mode switching and lifecycle | [lifecycle.md](lifecycle.md) | 12 | 2 | 4 | +| **Total** | | **102** | **6** | **47** | + +Some findings appear in two areas under different ids (for example the live-reload reconnect is +CHARTS-10 and LIFECYCLE-10). The epic groups them into one story each. + +## How the findings were verified + +- **CONFIRMED** means the bug was reproduced: with the real compiled host modules under Node, with real + Git repositories built for the purpose, or with the real assembled runtimes on real A-Frame 1.7.1 and + BabiaXR 1.3.4 in headless Chromium (WebGL through SwiftShader). About two thirds of the findings are + confirmed this way. **LIKELY** means traced in code. **SUSPECTED** means it needs a platform we could + not run. +- Nothing here was checked in VS Code itself, in a headset, on Windows or on macOS. Windows-only findings + were reproduced by emulating the Windows behaviour (cp1252 pipes, drive-letter paths) on Linux. + Each report has a "needs the maintainer's eyes" list. +- Baseline before the audit: `npm run test:unit` 1064/1064, and the four Playwright harnesses pass. None of + the existing tests catches any of the findings: most are source-text checks or happy paths, and the + mode-cycle harness loads its page over `file://`, where every data fetch is blocked. + +## The six blockers + +1. **PANELS-1, the "read-through" panels.** Info and legend cards are drawn with `depthTest: false` + (`templates/components/common/codexrCommonRuntime.js`), and A-Frame 1.7.1 does not sort transparent + objects by distance, so screens behind a card are painted over it in DOM order and their text + interleaves with the card's. Removing `depthTest: false` and making the backings opaque fixes it in + the headless reproduction. +2. **CHARTS-1, charts settle off the table.** BabiaXR's axis lines never shrink under A-Frame 1.7.1, and + generated scenes first build from all rows before switching to the row-budgeted slice. Bar, cylinder + and map charts end 1.25 to 2.6 m off the table while containment reports "ok" (see also CHARTS-2). +3. **CHARTS-10 / LIFECYCLE-10, live reload dies after one network error.** The XR SSE client reconnects + with a new `EventSource` that has no handlers, so the scene silently stops updating until a reload. +4. **LIFECYCLE-1, one hung mode freezes the analysis switcher.** Mode transitions run in series with no + timeout or cancel; a dataset fetch that never settles blocks every later switch for the session. +5. **LIFECYCLE-4, project evolution cannot be re-entered after a half-built frame.** +6. **EVO-1, a failed movie generation leaves the client "generating"**, and leaving the mode then deletes + the previous good movie for the whole room. + +## Cross-cutting causes + +Most findings come from six missing shared mechanisms. The epic is organised around them. + +1. **No job model on the host.** Git and Python work (evolution frames, comparison snapshots, dependency + scans, the launch itself) has no job id, no timeout, no cancel and no kill of child processes. A hung + job keeps a "busy" flag forever, Cancel is implemented as Clear, and races pass check-then-act guards. +2. **No lifecycle contract in the scene.** `activate()` can hang or half-fail, errors land in hidden + status lines, the server is never told, and late messages bounce users back to the selector. +3. **No single chart pipeline.** Six paths build or change a chart (generated scene, live switch, remap, + live reload, evolution frames, comparison clones), each with its own order of slice, build and fit. + Containment measures stale geometry and never checks position. +4. **No panel policy.** Every panel picks its own material, opacity, depth settings and position, and + only drag and look-at go through collision. +5. **No launch registry.** Sessions, servers, the SSE file map and watchers are keyed by raw path strings + in four places, the port is chosen twice, and stop/close paths leak listeners or stop the wrong server. +6. **Weak automated coverage of real scenes.** See the test story in the epic. + +## Design proposals + +Each report ends with architecture recommendations. The three that answer the maintainer's explicit asks: + +- **Unified, modular launcher**: [launcher.md §4](launcher.md) (a `LaunchKind` per surface and an + `AnalysisTypeDescriptor` per in-scene analysis, one `LaunchRegistry`, seven behaviour-preserving + migration steps), paired with the scene-side contract in [lifecycle.md §3](lifecycle.md) and the job + runner recommendations at the end of [evolution.md](evolution.md). +- **Unified chart (re)build that keeps charts on the table**: [charts.md §3](charts.md) + (`CodeXRChartPipeline.request()`: slice first, hidden until fitted, Babia animation off, wait for a real + "built" signal, fit once with fresh bounds plus a position check, then reveal and validate). +- **Panel layering and placement policy**: end of [panels.md](panels.md). + +## Reproduction material + +The repro scripts and harnesses are not part of the repository (they are audit tools). They live in the +project's shared files under `xr-audit/repro/`. Running them in a sandbox with no CDN access needs the +Playwright preload `xr-audit/repro/cdn-route.cjs`, which serves A-Frame, BabiaXR and aframe-extras from +`npm pack` tarballs. diff --git a/docs/xr-audit/charts.md b/docs/xr-audit/charts.md new file mode 100644 index 00000000..cf4b59af --- /dev/null +++ b/docs/xr-audit/charts.md @@ -0,0 +1,370 @@ +# Charts audit: build, rebuild and containment of BabiaXR charts on the analysis table + +All paths below are relative to `apps/vscode-extension/` unless stated otherwise. `T/` = `templates/components/codexr/`. +The scripts and screenshots behind every number are in `/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/charts/`. `gen-scene.cjs` builds a REAL directory scene with the compiled `out/` TemplateProcessor and the real runtime assets. `lib.cjs` serves it, with a controllable `/events` SSE channel, and runs it with real A-Frame 1.7.1 and BabiaXR 1.3.4 in headless Chromium (SwiftShader). Its `__probe()` measures the world bounds of what is actually visible under `#chart` against the physical tabletop (6.514 x 4.118 m) and the containment target zone (5.614 x 3.218 m, centred at 0, 1, -18). + +## 1. How the area works (summary) + +1. **Initial generation.** `src/core/charts/templateCharts.ts` and `processing/placeholders/createChart.ts` + `createStructure.ts` emit one ``. That entity carries a `babia-*` component reading `from: data` (the raw producer). It also gets the profile's rotation and `initialScale`, and `#codexr-chart-base-config` (CHART_PRESENTATION_PROFILES from `chartPresentation.ts`). +2. **Row-budget slice.** At runtime the xr-chart-mapping-ui `chartDataSlice.js` creates a `codexrChartDataSlice__` babia-queryjson entity (ranked, deduped top-N rows) and re-points the chart's `from` at it, polling every 400 ms for up to 25 attempts. +3. **Mapping UI.** `mappingProfiles.js` changes chart type (`applyChartTypeToEntity`: strip components and children, marker, rotation, `initialScale`, new component, orphan sweeps) and remaps fields (`applyMappingToCharts`). It keeps its own mirror of the presentation profiles. `pendingValidation.js` validates and confirms or reverts the change. +4. **Containment.** `codexr-chart-containment` (analysis-table runtime) measures three bound sets (full / primary content / containment), scales by size against a limit and anchors the PRIMARY bounds on the tabletop. It is driven by throttled `requestRenormalize`, retries, a steady controller and timer bursts. +5. **Paths that rebuild the chart outside the mapping UI:** + - SSE re-analysis (`templates/xr/sse/live_sse_fileXR.js`): cache-busts queryjson URLs, restores UI state, fires fixed timers. + - Project evolution (`declarativePipeline.js buildEvolutionChart`, frame swaps with data transitions). + - Historical comparison (`comparisonCharts.js createChartFromTemplate` clones). +6. **Two builders, five drivers.** There are two chart builders (the generator and `buildDeclarativeChartEntity`) and five drivers, each with its own timers. None of them waits on a deterministic "Babia finished building" signal. render-budget does not touch Babia charts at all. + +## 2. Findings + +### CHARTS-1: Babia axis lines never shrink, so row charts settle off the table (and containment reports "ok") +- **Severity:** blocker +- **Type:** bug +- **Evidence:** + - BabiaXR 1.3.4 axis components animate `line__xaxis.end` through A-Frame's `animation` component. Under A-Frame 1.7.1 that animation is a no-op on the line component's `end` property. `animtest.cjs` proved it: both an object `to` and a string `to` leave `end` at its first value (x = 50) forever. The axis is drawn once at its first length and never shrinks. + - The generated chart builds first from the raw producer, `src/core/charts/templateCharts.ts:113,157,203`: `componentBody: \`from: data;` (all rows). It is re-pointed to the 20/30-row slice later, so the axis is first sized for ALL rows. +- **Measured (final, settled state, `run-initial.cjs`, `initial.log`):** + + | chart | rows | axis local length vs needed | final world bounds vs tabletop | status | + |---|---|---|---|---| + | bars | 40 | 50 vs 25 | 1.35 m off table on x | settled, ok | + | bars | 400 | huge | 20 bars squeezed into a sliver; scale 0.0094; 4.7 m width is mostly empty axis | settled, ok | + | cyls | 40 | | 1.25 m off | settled, ok | + | barsmap | 400 | | 2.60 m off | settled, ok | + | cylsmap | 400 | | 2.59 m off | settled, ok | + + The same stale axis appears on every shrink: + - SSE re-analysis 40 → 5 rows: 2.48 m off (`run-reanalysis.cjs`, `re-bars.log`). + - Remap x_axis → language (5 distinct): 1.42 m off (`run-remap.cjs`). + - Evolution frame 160 rows → 3 rows: 1.51 m off (`run-evo.cjs`, `shots/evo-bars-frame3(3 rows).png`). + - Screenshots: `shots/initial-bars-40.png`, `shots/initial-bars-400.png`. +- **Failure scenario:** any directory with more than 20 files opens a bars/cyls/barsmap/cylsmap scene whose axis hangs over the table edge, or whose bars are a thin sliver at one end of a long empty axis. Every later shrink makes it worse. +- **Confidence:** CONFIRMED. Real scenes, real Babia, measured per frame. `axisfix.cjs` showed that forcing `axis.updateLine` with animation off brings the vertices to 25 (correct). +- **Proposed fix:** + - (a) Add a CodeXR Babia-compat shim, loaded right after the Babia bundle. It wraps `AFRAME.components['babia-axis-x'|'babia-axis-y'|'babia-axis-z'].Component.prototype.init/update` so that `this.axis.anim = false` and the line is rewritten directly. + - (b) Generate the chart reading from the slice (see CHARTS-6), so the first build already has the budgeted row count. +- **Test:** a Playwright harness scenario (template: `run-initial.cjs`) for bars/cyls/barsmap/cylsmap at n = 3/40/400. Assert that the x-axis line vertex extent equals the bar count times the spacing, and that `overGeo.offTableX/Z === 0` after settle. Also add a unit test that the shim sets `anim=false`. + +### CHARTS-2: Containment checks size, never position, so the chart is "ok" while hanging off the table +- **Severity:** major +- **Type:** bug +- **Evidence:** + - `T/analysis-table/analysisTableRuntime/containmentLimits.js:98-` `computePlanarAxisTargetScale(primarySize, containmentSize, currentScale, containmentLimitSize, ...)`: `var ratio = primarySize / containmentLimitSize;`. Only sizes go in. The limit is targetWidth + tableTopPadding (0.9) − 2 × edgeMargin (0.18) = 6.154 m, which is wider than the 5.614 m zone. + - `diagnosticsAndPid.js:248` `computeAnchorOffset` centres the PRIMARY bounds. The primary set excludes `axis|tick|grid|label|legend|title` (`zonesAndProfiles.js:267-268`), so axes and labels that extend to one side are never centred or clamped. + - The steady controller's settled watch (`steadyController.js:440-500`) compares sizes only. `waitForChartsStable` and `pendingValidation.js evaluatePendingMapping` accept these states. +- **Failure scenario:** with bars n = 3, the bars are centred but the axis/labels extend to one side: 0.33 m off the TABLE and 0.78 m off the zone, at 6.098 m wide, while `getChartStatus()` returns `ready/valid/stabilized, reason ok`. All of CHARTS-1 passes validation for the same reason. +- **Confidence:** CONFIRMED (`run-initial.cjs`, probe vs `getChartStatus()`). +- **Proposed fix:** + - The fit computes the world AABB of the containment bounds and checks `min/max` against the zone rectangle. + - The anchor centres the containment bounds when they are offset from the primary bounds (or clamps the offset so that `[min, max]` stays inside). + - Expose `offZoneX/Z` in `getChartStatus()`. Make `valid` false when either value exceeds the tolerance. +- **Test:** + - Unit test in `test/analysis/*` on `computeAnchorOffset`/limits, with an asymmetric containment box. + - Harness assertion: `status.valid === true` implies `overAll.offZoneX/Z <= 0.02`. + +### CHARTS-3: Containment measures with a stale cached `geometry.boundingBox` +- **Severity:** major +- **Type:** bug +- **Evidence:** `T/analysis-table/analysisTableRuntime/geometryUtils.js:365-366` + ```js + if (!node.geometry.boundingBox && typeof node.geometry.computeBoundingBox === 'function') { + node.geometry.computeBoundingBox(); + ``` + Babia and A-Frame's `line` component rewrite positions in place, so the cached box is never invalidated. +- **Failure scenario:** after an axis update, the line vertices span 25 but the measured bbox still spans 50 (`axisfix.cjs`). Containment fits the old geometry, so the chart either shrinks for nothing or misses an overflow. Any in-place geometry update (axis, line, text re-layout) is affected. +- **Confidence:** CONFIRMED (`axisfix.cjs`: verts 25, bbox 50, before the probe was changed to always recompute). +- **Proposed fix:** + - Always call `computeBoundingBox()` during a measurement pass. The cost is trivial at Babia mesh counts. + - Or compare `geometry.attributes.position.version` against a cached version. +- **Test:** a unit test with a fake geometry whose positions change after the first measure. Assert that the second measure reflects the change. + +### CHARTS-4: Chart switch renders a giant unfitted chart for up to 1.6 s, then animates from it +- **Severity:** major +- **Type:** bug / ux +- **Evidence:** + - `mappingProfiles.js:257-261` (and the presentation profile): `initialScale: '1.5 1.5 1.5'` is applied by `applyChartTypeToEntity` before Babia builds. + - `diagnosticsAndPid.js:22` `shouldAnimateContainmentTransform`: any reason other than `init`/`bootstrap-visible`/`hard-height-guard` (i.e. mapping, componentchanged, analysis-updated) animates 650 ms from the CURRENT (unfitted) transform. + - `containmentComponentCore.js` `requestRenormalize` is a 280 ms leading-edge throttle that drops the trailing request. +- **Measured** with a renderer hook recording the world bounds of every drawn frame (`frames-switch.cjs`, `switch40.log`), on a switch from boats with 40 rows: + + | target chart | worst drawn frame | how long | + |---|---|---| + | cylsmap | 75 x 15 x 17 m | | + | bubbles | 65 x 12 x 29 m | | + | bars | 38 m wide, over 1.8 m tall | up to 1.6 s | + + Sampled worst off-table: 34–72 m. +- **Failure scenario:** in a headset every chart switch flashes a building-sized chart around the user for about a second before it shrinks onto the table. This is the "floating chart after a switch" symptom. +- **Confidence:** CONFIRMED in the headless renderer. Needs the maintainer's eyes in a headset to judge the perceived severity; frame timing differs on a Quest. +- **Proposed fix:** + - Hide the chart (`object3D.visible = false`) from component install until the first fit after the "built" signal, then reveal it. + - Never animate from a transform that was never fitted: only animate between two fitted transforms. + - Make the throttle trailing-edge, so the last request always runs. +- **Test:** harness scenario `frames-switch.cjs` (8 chart types x 3 sizes). Assert that no drawn frame has `overGeo` off the table by more than 0.05 m or a height above the band. + +### CHARTS-5: Initial build is fitted mid-growth, which draws towers 25–36 m tall for about 3 s +- **Severity:** major +- **Type:** bug / ux +- **Evidence:** + - BabiaXR row charts default `animation: true`, `dur: 2000` (bars grow from 0). + - Containment fits while the heights grow, so the y scale reaches 2.49. When growth finishes, the drawn height overshoots until the next pass. + - `chartPresentation.ts` `baseAttributes` for bars/cyls/barsmap/cylsmap do not set `animation: false`. +- **Measured** (`frames-initial.cjs`): + - bars, 3 rows: 10 of 53 drawn frames over the table; worst drawn height 36.2 m at 1.9 s; last over-table frame at 3.19 s. + - cyls, 40 rows: first over-table frame 96.8 m wide; worst height 29 m; last over-table frame at 3.28 s. + - SSE re-analysis to 5 rows: 26.5 m tower (`re-bars.log`). + - Remap: 12.5 m tower. +- **Failure scenario:** the first seconds of every scene and every re-analysis show a tower through the ceiling. +- **Confidence:** CONFIRMED (headless). Needs a headset check for perceived impact. +- **Proposed fix:** + - Set `animation: false` in `baseAttributes` for all row charts (both the TS profile and the runtime mirror). + - Alternatively, keep Babia's animation but treat "animation finished" as part of the built signal and keep the chart hidden until then. +- **Test:** same per-frame harness on the initial load, n = 3/40/400 for every chart type. + +### CHARTS-6: Generated scenes build from raw data first and are re-pointed to the slice later +- **Severity:** major +- **Type:** architecture / bug +- **Evidence:** + - `src/core/charts/templateCharts.ts:113,157,203`: `from: data;`. + - `T/xr-chart-mapping-ui/xrChartMappingUiRuntime/chartDataSlice.js` `scheduleChartDataSliceSync` (400 ms x 25 attempts) creates `codexrChartDataSlice__data` and rewrites `from` afterwards. +- **Failure scenario:** every scene does two Babia builds. The first is over all N rows (400 bars, the oversized axis of CHARTS-1, the containment fit on the wrong geometry), and the second runs over the slice. If the mapping-ui runtime fails to load or errors, the chart stays unbudgeted forever. +- **Confidence:** CONFIRMED (probe `from` changes from `data` to `codexrChartDataSlice__data` during the first seconds; the axis length stays at the raw-row value). +- **Proposed fix:** emit the slice entity in the generated HTML (or compute the slice in TS at generation time into a second producer) and generate the chart with `from: codexrChartDataSlice__data`. +- **Test:** + - TS unit test: the generated HTML for each chart id contains the slice producer and `from: codexrChartDataSlice__`. + - Harness: `from` never equals `data` in any probe sample. + +### CHARTS-7: Remap leaves ghost bars (the component is updated before the slice) +- **Severity:** major +- **Type:** bug +- **Evidence:** `T/xr-chart-mapping-ui/xrChartMappingUiRuntime/mappingProfiles.js:196-225`. `setDeclarativeAttribute(chartEntity, componentName, ...)` runs for every entity first. `refreshChartDataSlicesForMapping(...)` runs only after the loop. Babia therefore rebuilds once on the OLD slice with the NEW key field. + - In that rebuild, babia-bars reuses elements keyed by `babia-name`. Its `currentBars` map is built before the loop, so duplicate keys create elements that are never tracked or removed. +- **Measured** (`ghost.cjs`, `shots/remap-bars-40-x_axis-language.png`): + - Remap x_axis fileName → language: 20 bar elements with 5 distinct names while the slice has 5 rows. 15 ghosts persist after the mapping is confirmed. + - Real-world variant (`dup.cjs`, `DUP=8`, `shots/dup-bars-dup-120.png`): a 120-file project whose basenames repeat (`index.ts`, `__init__.py`) renders 120 bar elements against an 8-row slice, a wall of bars. +- **Confidence:** CONFIRMED. +- **Proposed fix:** + - Recompute the slice BEFORE writing the component (producer → slice → chart order). + - Clear the chart's children when the key field changes. + - In the slice, dedupe on the effective key (already partially done by `keyBy`), and for the initial raw build, see CHARTS-6. +- **Test:** harness remap scenario. Assert that the count of `[babia-name]` children equals the slice length, and that the names are unique. + +### CHARTS-8: Evolution flat charts bypass the slice, which gives walls of bars and about 3.8 s of frozen, oversized frames +- **Severity:** major +- **Type:** bug / architecture +- **Evidence:** + - `T/project-evolution/projectEvolutionRuntime/declarativePipeline.js:3,129,184`: `EVOLUTION_DATA_ID = 'codexrProjectEvolutionData'`, passed as `sourceId` for non-boats charts. + - `buildDeclarativeChartComponentData` keeps `ordered.from = existingData.from` (raw). + - `declarativePipeline.js:465,480`: `if (component.animation === true)` … `(!sawAnimation || component.animation !== true)`. `animation` is a static schema flag, not "animating now", so the wait never ends early and each frame waits duration + 1800 ms. + - Data transitions freeze containment for that whole wait. + - `test/analysis/projectEvolutionRuntime.test.cjs:265` pins the raw source: `circular.getAttribute('babia-doughnut') === 'from: codexrProjectEvolutionData'`. + - `test/runners/run-project-evolution-harness.cjs` asserts `from: codexrProjectEvolutionData`. + - `.claude/docs/XR_COMPONENTS.md` claims slices flow through evolution frames, which is wrong. +- **Measured** (`run-evo.cjs`, `shots/evo-bars-frame2(160 rows).png`): + - A 160-row frame gives 138 bar elements (duplicate-key collisions), scale 0.0236, depth 2.4 cm. + - Frame 1→2: the chart was 129.9 m wide from 176 to 3988 ms; 24 of 30 samples were over the table. + - Frame to 3 rows: stale axis, 1.51 m off (CHARTS-1). +- **Failure scenario:** playing the evolution movie on a real repository shows unreadable walls of bars and building-sized transients on every frame. +- **Confidence:** CONFIRMED (headless). The movie timing should be judged by the maintainer in a headset. +- **Proposed fix:** + - Route evolution through the same slice (`codexrChartDataSlice__codexrProjectEvolutionData`). + - Replace the animation-flag wait with the built signal of the unified pipeline. + - Keep the chart hidden or at its last fitted transform during the transition. + - Update the two tests to assert the slice source, and fix the doc. +- **Test:** the unit test asserts the slice id. The harness plays 3 frames (160/40/3 rows) and asserts the per-frame bounds. + +### CHARTS-9: Comparison clones bypass the slice and use a hardcoded scale +- **Severity:** major +- **Type:** bug / architecture +- **Evidence:** `T/historical-comparison/historicalComparisonRuntime/comparisonCharts.js:165,170`. + ```js + chartData.from = sourceId; // codexrComparisonDataLeft (raw) + clone.setAttribute('scale', '0.01 0.05 0.01'); // for every chart type + ``` +- **Failure scenario:** for a 400-file revision each side renders 400 bars with no budget, dedupe or value filter, and with duplicate-key collisions (CHARTS-7). The fixed non-uniform scale is wrong for pie/donut/bubbles (it distorts round charts) and ignores the presentation profile. +- **Confidence:** + - CONFIRMED for the source and scale (`clone-check.cjs` ran the real `createChartFromTemplate` in a vm: `from: codexrComparisonDataLeft`, scale `0.01 0.05 0.01` for bars). + - Visual overflow not measured, because the harness comparison run produced no clones (`cmp.cjs` abandoned). Needs the maintainer's eyes on a real comparison. +- **Proposed fix:** build clones through the unified pipeline, with a per-side slice and a per-side containment zone (half table). +- **Test:** extend `historicalComparison.test.cjs` (next to `:1044`, the rotation test) to assert the slice source and the profile scale. Add a harness scenario with two revisions of 400 rows. + +### CHARTS-10: SSE reconnect creates an orphan EventSource, so live updates die until the page reloads +- **Severity:** blocker +- **Type:** bug +- **Evidence:** `templates/xr/sse/live_sse_fileXR.js:144-152`. + ```js + setTimeout(() => { + ... + eventSource.close(); + new EventSource('/events'); + }, 3000); + ``` + The new EventSource is not assigned and has no handlers. Closing the original also disables the browser's built-in auto-reconnect. +- **Failure scenario:** the extension's server restarts, or the network blips (Wi-Fi on a headset). The page reconnects (server `clientCount` back to 1), but `analysis-updated` is ignored from then on and the scene silently stops updating. +- **Confidence:** CONFIRMED (`run-reanalysis.cjs`: after `dropClients()`, the orphan connected; a pushed `analysis-updated` changed neither the data URL nor the refresh count). +- **Proposed fix:** delete the custom reconnect and let the native EventSource retry. Or wrap creation in `connect()`, which re-attaches every handler and reassigns `eventSource`. +- **Test:** a harness scenario that drops clients, pushes `analysis-updated` and asserts a refresh. This file is shared by every XR scene, so it also needs a unit test with a fake EventSource. + +### CHARTS-11: SSE cache-bust rewrites the slice entity's URL and drops query parameters +- **Severity:** major +- **Type:** bug +- **Evidence:** `templates/xr/sse/live_sse_fileXR.js:185-194`. Every `[babia-queryjson]` gets `url = urlStr.split('?')[0] + '?t=' + timestamp;`. + - Slice entities have an empty URL (inline `data`), so they become `?t=…`, which fetches `index.html` as JSON and produces an unhandled rejection. + - Comparison producers lose their `?revision=` parameter. +- **Failure scenario:** after a re-analysis, the slice producer briefly holds HTML-parse garbage or errors. The comparison sides reload the wrong revision (the default). +- **Confidence:** + - CONFIRMED for the slice (observed `sliceUrl = '?t=…'` in `run-reanalysis.cjs`). + - LIKELY for the comparison (from code). +- **Proposed fix:** cache-bust only entities with a non-empty URL and no `data-codexr-slice` marker, and preserve existing params (`URL` + `searchParams.set('t', …)`). Better, let the unified pipeline own re-analysis: refetch the producer, then recompute the slices. +- **Test:** a unit test of the cache-bust helper over three URL shapes (empty, plain, with query). + +### CHARTS-12: SSE `restoreState` silently reverts a pending mapping, and fixed timers race the rebuild +- **Severity:** minor +- **Type:** robustness +- **Evidence:** + - `live_sse_fileXR.js:112-113`: `mappingUiRuntime.restoreState(mappingUiState)` re-applies `lastKnownGoodMapping`. + - The fixed delays (renormalize at 240/260 ms, boats at 900 ms, `completeNormalRefresh` at 300 ms, then `waitForChartsStable` with an 8 s timeout) are not tied to Babia completion. + - Observed: the first `codexr-normal-analysis-refreshed` event had not fired within 7–8 s. +- **Failure scenario:** the user is mid-remap when a file save triggers re-analysis. The remap is silently undone. On a slow headset, the timers fire before the rebuild and containment fits the old geometry. +- **Confidence:** + - LIKELY for the revert (code). + - CONFIRMED for the event delay. +- **Proposed fix:** re-analysis calls `pipeline.rebuild({reason: 'analysis-updated'})` with the CURRENT (pending or confirmed) mapping. Remove the timers. +- **Test:** a harness test that starts a remap, pushes `analysis-updated` and asserts the remap survives. + +### CHARTS-13: Empty re-analysis gives a misleading error or a stuck "rebuilding" state +- **Severity:** minor +- **Type:** ux +- **Evidence and measurements** (`run-reanalysis.cjs` with `[]`): + - bars: `status.reason = invalid-axis-length` ("The selected mapping generated invalid axis values"), and the stale axis remains. + - boats: stuck in `waiting-geometry` ("still rebuilding") indefinitely. + - Both recover when data returns. +- **Failure scenario:** a directory whose files all get filtered out (or a parse failure) shows an error that blames the mapping, or a spinner that never ends. +- **Confidence:** CONFIRMED. +- **Proposed fix:** the pipeline detects zero slice rows before installing the component, clears the chart and shows an explicit "No data for this mapping" state. Containment treats empty as valid, with nothing to contain. +- **Test:** harness: push `[]` and assert the empty-state marker and `status.valid`. + +### CHARTS-14: Bubbles are anchored on the smallest bubble, so the axes sink below the tabletop +- **Severity:** minor +- **Type:** bug / ux +- **Evidence:** `chartPresentation.ts` bubbles profile: `fit: uniform`, `surfaceLift: 0.03`. The primary bounds exclude the axes, so the anchor puts the primary geometry's lowest point on the table. +- **Measured:** n = 40 and n = 400, the axes sit 0.38–0.60 m BELOW the tabletop (`below` in `bsm1ndph5.output`), visible under the table (`shots/initial-bubbles-400.png`). They also stick out of the zone by 0.37–0.38 m on x. +- **Confidence:** CONFIRMED. +- **Proposed fix:** for charts with a y axis, anchor `min(containmentBounds.y)` to the surface, or set the Babia axis origin at y = 0 for bubbles. +- **Test:** harness: `overAll.below === 0` for every chart type. + +### CHARTS-15: Pie and donut are tiny on the table +- **Severity:** minor +- **Type:** ux +- **Evidence:** a uniform fit limited by the height band (0.38–0.72 x 1.8 m) for a disc standing at `rotation 90 0 0`. +- **Measured:** about 1.27 m diameter on a 5.6 m table. +- **Confidence:** CONFIRMED. +- **Proposed fix:** exempt standing discs from the height band, or lay them flat with a slight tilt. This is a design call for the maintainer, in a headset. + +### CHARTS-16: Babia pie hover legend throws `removeChild` during a rebuild +- **Severity:** minor +- **Type:** robustness +- **Evidence:** babia-pie `processData` removes all of the entity's children, while its hover legend lives in an implicit global. A rebuild during hover gives `[pageerror] ... removeChild` (observed in the switch logs). +- **Confidence:** CONFIRMED (page error seen); the user-visible effect is minor. +- **Proposed fix:** the compat shim guards the legend removal (`if (legend && legend.parentNode)`). + +### CHARTS-17: The transaction and evolution mapping paths drop or mis-route changes +- **Severity:** minor +- **Type:** robustness +- **Evidence:** + - `frameApplication.js:228`: `if (state.applyingMapping) { return; }`. A second mapping change made while the first applies is dropped, not queued. + - `mappingProfiles.js getChartFromSource` returns `'data'` for any source that is not tree and not Comparison. Evolution's `resolveChartDataSourceId` call therefore updates the MAIN slice record as a side effect. + - `pendingValidation.js`: `scheduleChartSwitchValidation` reverts only on invalid geometry, yet CHARTS-2 makes off-table geometry "valid". The validation bursts fire from 650 ms to 18 s, and the 26 s timeout reverts a valid but not stabilized chart. +- **Confidence:** LIKELY (code reading; not reproduced end-to-end). +- **Proposed fix:** a single queued transaction per chart entity in the unified pipeline (latest request wins after the current one settles). Source ids resolve explicitly per producer. + +### CHARTS-18: Smaller robustness issues +- **Severity:** minor +- **Type:** robustness / test-gap +- **Issues:** + - `geometryUtils.js` `buildFilteredBounds` checks `node.visible` on the node only, so meshes under an invisible ancestor are counted. Use `traverseVisible`. (SUSPECTED) + - The chart title is interpolated unescaped into the component string in `templateCharts.ts`. A `;` or `:` in the folder name would break the attribute parse. (LIKELY) + - render-budget covers only the logo, the dependency graph and debug. Babia charts (400-element comparisons, evolution walls) have no budget. (CONFIRMED by grep) + - There is no test asserting world bounds against the table for any chart type. All existing harness checks read `getChartStatus()`, which CHARTS-2 shows can say "ok" while the chart is off the table. (test-gap) + +## 3. Architecture recommendations + +### Problem +- The chart is built by two builders: the generator, and `buildDeclarativeChartEntity`/`applyChartTypeToEntity`. +- Five drivers call those builders: bootstrap, switch, remap, SSE, evolution and comparison clones. +- Each driver decides on its own: + - which data source to read (raw or slice); + - when the build is "done" (timers from 240 ms to 26 s, the animation-flag wait); + - whether containment animates or freezes. +- Containment is a feedback loop running on stale, size-only measurements. Nearly every finding above is one of these choices made differently, or too early. + +### Design: one pipeline, `CodeXRChartPipeline` +A browser runtime under `T/analysis-table/` (or a new `T/chart-pipeline/`), loaded before the mapping-ui, evolution and comparison runtimes. + +```js +CodeXRChartPipeline.request({ + entity, // or entityId + chartId, // registry id; profile resolved from #codexr-chart-base-config only + sourceId, // the PRODUCER id (data | codexrProjectEvolutionData | codexrComparisonDataLeft ...) + mapping, // dimension -> field + zone, // containment zone (full table, or left/right half for comparison) + reason // 'bootstrap' | 'switch' | 'remap' | 'analysis-updated' | 'evolution-frame' | 'comparison' +}) -> Promise<{ status: 'ready'|'empty'|'invalid', bounds, transactionId }> +``` + +One serialized queue per entity. A newer request supersedes a queued one, never a running one. Steps: + +1. **Resolve the profile** from the single TS source (`chartPresentation.ts` → `#codexr-chart-base-config`). Delete the `mappingProfiles.js` mirror. +2. **Slice first.** Ensure `codexrChartDataSlice__`, recompute it for `(chartId, mapping)` (budget, rank, dedupe on the effective key), and get the row count. If there are 0 rows, clear the chart, set the empty state and return `'empty'` (CHARTS-13). +3. **Begin transition.** Hide the chart: `object3D.visible = false`, or keep the last fitted transform frozen. Freeze containment. +4. **Apply the presentation**: marker, rotation, and a provisional scale computed from the row count and profile (not a fixed 1.5). +5. **Install or update the Babia component** with `from: ` and `animation: false`, under the compat shim (axis `anim=false`, pie legend guard). Clear the children if the chart id or key field changed. +6. **Wait for a deterministic built signal:** the component's NotiBuffer update has been processed, AND the child count plus the summed position-attribute versions have been unchanged for two consecutive frames. No wall-clock timers; one safety timeout that reports `invalid`, never a silent revert. +7. **Fit once:** recompute every bbox (CHARTS-3). Scale by size, then anchor on containment bounds with a positional check against the zone (CHARTS-2), and lift so `min.y` sits on the surface (CHARTS-14). +8. **Reveal:** animate only if both transforms are fitted (CHARTS-4). +9. **Validate.** `valid` means inside the zone (position included). The transaction confirms or reverts on that, and emits `codexr-chart-ready` with bounds. SSE, evolution and tests wait on this event instead of timers. + +Containment keeps its steady controller only to react to external changes (table moved, window resize) through the same `request({reason: 'relayout'})`. + +### Migration steps (each step shippable on its own) +1. **Compat shim and measurement fixes** (CHARTS-1, CHARTS-3, CHARTS-5, CHARTS-16): + - the shim; + - `animation:false` in `baseAttributes`; + - always `computeBoundingBox`. + + Low risk, and it removes the largest symptoms. +2. **Positional containment** (CHARTS-2, CHARTS-14): update `computeAnchorOffset` and the status; harness assertions on world bounds. +3. **SSE fixes** (CHARTS-10, CHARTS-11): the reconnect, and a cache-bust that skips slices and keeps params. These are independent of the pipeline and are blockers. +4. **Introduce `CodeXRChartPipeline`**, implemented with the existing helpers, and route `applyChartTypeToEntity`/`applyMappingToCharts`/`panelUi.selectChart` through it, slice first (CHARTS-4, CHARTS-7, CHARTS-17). +5. **Generator:** emit the slice producer and `from: codexrChartDataSlice__data`. Bootstrap calls `request({reason:'bootstrap'})` (CHARTS-6). +6. **Evolution:** `buildEvolutionChart` and frame swaps call `request({reason:'evolution-frame'})`. Delete `waitForEvolutionChartAnimation`. Update `projectEvolutionRuntime.test.cjs:265`, the evolution harness assertion and `.claude/docs/XR_COMPONENTS.md` (CHARTS-8). +7. **Comparison:** `createChartFromTemplate` calls `request({zone: half, reason:'comparison'})`; drop the hardcoded scale (CHARTS-9). +8. **SSE re-analysis** calls `request({reason:'analysis-updated'})` with the current mapping. Delete the fixed timers and `restoreState`'s mapping re-apply (CHARTS-12). +9. **Delete the dead per-path machinery:** + - the orphan sweeps at 400/1500 ms; + - the validation bursts; + - `scheduleChartDataSliceSync` polling; + - the profile mirror. + + Wire render-budget to the slice budget, so comparison and evolution respect a device-tier row cap. + +### Test plan +- **Unit** (`test/analysis/*.test.cjs`, node runner): + - the shim; + - `computeAnchorOffset` with asymmetric bounds; + - slice-before-component ordering (spy order); + - the cache-bust helper; + - the SSE reconnect with a fake EventSource; + - evolution and comparison source ids. +- **Harness** (Playwright, the scripts in the scratch folder are ready templates): a matrix of 8 chart types x {3, 40, 400 rows, duplicate basenames} x {initial, switch from each type, remap, re-analysis grow/shrink/empty, evolution 3 frames, comparison}. Per drawn frame, assert: + - no visible geometry off the table by more than 0.05 m; + - height inside the band; + - nothing below the tabletop; + - after `codexr-chart-ready`, bounds inside the zone and child count equal to the slice length. + +### Needs the maintainer's eyes +I could not run VS Code or a headset. These need checking there: +- the perceived severity of the transients on a Quest (CHARTS-4, CHARTS-5, CHARTS-8); +- the pie/donut size decision (CHARTS-15); +- a real historical comparison (CHARTS-9 visual); +- SSE reconnect behaviour through the real extension server and Cloudflare tunnel (CHARTS-10). diff --git a/docs/xr-audit/depgraph.md b/docs/xr-audit/depgraph.md new file mode 100644 index 00000000..db4b9a21 --- /dev/null +++ b/docs/xr-audit/depgraph.md @@ -0,0 +1,266 @@ +# Dependency-graph XR analysis: audit (area "depgraph") + +Repo: /home/user/Code-XR @ d89e08d4 (v1.2.1). All paths are relative to the repo root unless they start with `/tmp`. +Scratch harness, scripts and datasets: `/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/depgraph/` +(`run.cjs`, `run5.cjs` = Playwright scenarios on the real assembled runtime; `build.cjs` = harness builder; `run_dep.py`, `cmp.py`, `resolve_check.py` = Python engine probes; `venv/` = backend venv with the pinned lizard + tree-sitter-language-pack). + +Tests run: +- `node --test test/analysis/dependencyGraph.test.cjs test/analysis/dependencyFileScope.test.cjs test/analysis/dependencyGraphBridge.test.cjs`: 55/55 pass. +- `CODEXR_PYTHON=/bin/python npm run test:python`: 73/73 pass. This needed a venv built from `backend/requirements.txt`, because the system python has no lizard. +- None of these tests covers any finding below. + +## 1. How the area works + +- **Entry.** The scene's mode option `dependency-graph` is registered by `CodeXRDependencyGraphRuntime` (`apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/viewLifecycle.js`). + - `selectDependencyMode()` activates the mode at once when the shared entity `dependency-graph/main` is already `ready`. + - Otherwise `start()` hops the local mode runtime to `selection` and sends `dependency-graph-start` over the collaboration WebSocket. +- **Host.** `DependencyGraphBridge.handleDependencyGraphStartMessage` (`apps/vscode-extension/src/core/server/analysis/dependencyGraphBridge.ts`) does three things: + - It refuses when the service is busy. + - It switches the authoritative `analysis-view` to `dependency-graph`. + - It upserts the entity (`analyzing`, or `ready` when a dataset URL is cached), then asks `analysisRefreshCoordinator.requestRefresh(...,'dependency-graph')`. +- **Refresh.** The coordinator calls `refreshDependencyGraph(batch)`, which calls `DependencyGraphService.analyze()` (`apps/vscode-extension/src/core/dependencies/dependencyGraphService.ts`). The service spawns `backend/src/main.py --mode dependencies`. The engine is `backend/src/utils/dependency_analysis_engine.py`, with no timeout and no cancel. + - The service writes `dependencies/dependency-graph-.json` plus `dependency-graph.json`. + - The bridge upserts `{status:'ready', datasetUrl, revision}`. + - Drilling into a file goes through `dependency-file-scope-request` → `analyzeFileScope` → `dependencies/dependency-scope-.json`, and the entity's `datasetUrl` becomes that file. + - Navigation and filters (`dependency-graph-settings`) only merge `scope/layout/filters/mapping` into the entity. They never touch `datasetUrl`. +- **Browser.** + - `applySharedState(snapshot)` fetches `datasetUrl` and stores it as `state.projectDataset` (directory) or `state.fileDatasets[path]` (file). + - `filteredDataset()` projects it with `projectDirectoryScope` / `projectFileScope` (`datasetProjection.js`). This aggregates child directories by summing per-file metrics, and replaces external nodes with one summary node unless `showExternal`. + - `renderGraph()` mounts the `codexr-dependency-graph` A-Frame component. `setGraph()` posts the nodes to an inline Blob Web Worker (`createLayoutWorker`, `scalesAndControls.js:471`). `applyPositions` reconciles the nodes and edges (InstancedMesh edges, one entity per node). + - Leaving the mode runs `deactivate → disposeView → removeGraph`, which removes the entity, and A-Frame `remove()` terminates the worker. +- **Panel.** The detail card (`tooltipsAndSelection.js`) shows `nodeDetailModel` metrics. Its action button calls `openDirectory` / `openFile` / `publishState({showExternal:true})`. + +## 2. Findings + +### DEPGRAPH-1: Directory/parent card metrics are sums of per-file metrics: Fan-out, Degree, Relations, Cycle and Instab. are wrong for folders +- Severity: major - Type: bug +- Evidence: + - `apps/vscode-extension/templates/components/codexr/dependency-graph/dependencyGraphRuntime/datasetProjection.js:271-275`. `addNodeMetrics` adds every per-file metric key, including `fanIn`, `fanOut`, `degree`, `relationCount` and `cycleSize`, into the aggregate: `target.metrics[metric] += Number(source?.metrics?.[metric] || 0);` + - It is used for child directories (`:328`) and for the `..` parent, which receives the whole rest of the project (`:333-334`). + - `scalesAndControls.js:171-186` computes `Instab.` from those sums. + - Per file, Python defines `fanIn=len(incoming)`, `fanOut=len(outgoing)` (distinct neighbours), `degree=len(incoming|outgoing)` and `relationCount` = edge records touching the file (`backend/src/utils/dependency_analysis_engine.py:343-375`). +- What the screenshot's numbers mean: + - Fan-in 46 / Fan-out 1773 / Degree 1819 / Relations 1997 is internally consistent as a sum. Degree = 46+1773 because no file has a neighbour in both directions. Relations > Degree because one neighbour can be reached by several relation kinds (import + call), and each kind is an edge record. + - But the numbers do not describe the folder: + - Fan-in/fan-out count edges between files *inside* the folder. + - The same external package is counted once per file. + - They include `call` relations, which are hidden by default (DEPGRAPH-2 explains why those dominate). + - They count once more on top of the external summary that the table shows. + - `Cycle` is the sum of SCC sizes, which is meaningless for a folder. +- Reproduced on this repo's `apps/vscode-extension/src` (291 files, real engine, `run_dep.py` + script in the scratch dir): + + | folder | card Fan-in / Fan-out / Degree / Relations / **Cycle** / Instab. | real folder-level distinct out / in neighbours (no calls) | + |---|---|---| + | `app` (7 files) | 9 / 150 / 159 / 183 / **416** / 94% | out 7 / in 1 | + | `core` (157) | 585 / 4072 / 4652 / 5175 / **5516** / 87% | out 109 / in 3 | + | `features` (114) | 246 / 2334 / 2580 / 2922 / **4784** / 90% | out 65 / in 3 | + +- Failure scenario: open any folder card. The user reads "Cycle 416" for a 7-file folder, and Fan-out/Instab. values that do not match the edges drawn to that box. +- Confidence: CONFIRMED (numbers computed from the real engine output with the runtime's own summation rule). +- Proposed fix: + - In `projectDirectoryScope` (and `projectFileScope`'s "Other project files" node), stop summing graph metrics. Derive the aggregate's `fanIn`/`fanOut`/`degree`/`relationCount` from the projected boundary edges (`aggregateProjectedEdges` already builds them): count distinct source/target aggregates, respecting `relationFilters` and `showExternal`. + - Keep `totalLines` as a sum and add a `files` count. + - For `cycleSize`, use the largest SCC touching the folder, or "files in cycles", and label it as such. + - Recompute after `filteredDataset()` applies the filters, so a card matches what is on screen. + - Test: a unit test in `test/analysis/dependencyGraph.test.cjs` on `__testing.projectDirectoryScope` with a 3-file fixture: 2 files in `a/` importing each other plus one external. Assert that the folder node reports fanOut = 1 (external), not 3, and a cycle value of 2 at most. + +### DEPGRAPH-2: Unresolved call references become "external packages": `this`, `constructor`, `async`, `super`, built-ins and the file's own function names +- Severity: major - Type: bug +- Evidence: + - `backend/src/utils/dependency_analysis_engine.py:816-836`. `_resolve_edge_counts` treats every relation the same way: `if not target_id: target_id = _ensure_external_node(reference, external_nodes, nodes)`. + - The file-scope variant correctly drops unresolved calls (`:536-541`: `if not target_id: continue`). + - `CALL_PATTERN = r'\b([A-Za-z_][\w.]*)\s*\('` with `CALL_KEYWORDS` (`:60-64`) also matches definitions (`def f(`, `function foo(`, `constructor(`). +- On `apps/vscode-extension/src`: + - 2,450 external nodes for 291 files. + - 5,190 of the 5,846 external edges are `call/ambiguous`. + - The top "packages" are `this` (145), `getLogger` (138), `constructor` (137), `String`, `error`, `Date`, `Array`, `map`, `JSON`, `async`, `super`... +- A Python fixture `pkg2/views.py` with `def f(): ...` produces `views.py -> EXT:f call ambiguous`. +- Consequences: + - fanOut/degree/instability of every file is inflated, and DEPGRAPH-1 multiplies that for folders. This is the main reason for "Fan-out 1773". + - The hidden-external summary card reports "2450 hidden packages". + - `External: shown` puts thousands of junk nodes on the table (DEPGRAPH-5). + - Calls are filtered *off* by default (`DEFAULT_RELATION_FILTERS.call=false`), but the metrics still count them. +- Confidence: CONFIRMED (engine output, `cmp.py` / inline scripts in the scratch dir). +- Proposed fix: + - In `_resolve_edge_counts`, drop a `call` whose reference does not resolve to an internal file, the same way file mode does. At least do not create external nodes for calls. + - Skip definition sites in the lexical call extractor (preceded by `def|function|func|fn|fun|sub` or a method-declaration context), and add `this|super|constructor|async|await|new|typeof|...` to `CALL_KEYWORDS`. + - Consider computing the stored `fanIn`/`fanOut` without `call`/ambiguous relations, or exposing both. + - Test: + - `backend/tests/dependencies/test_dependency_analysis.py`: a TS + Python fixture with `constructor(`, `this.x(`, `def f(`. Assert no external node with those labels. + - Update `test_dependency_golden.py`. + +### DEPGRAPH-3: Import resolution ignores the importing file's directory and depends on PYTHONHASHSEED. Wrong edges are marked `exact`, and edges flip between runs +- Severity: major - Type: bug +- Evidence: + - `backend/src/utils/dependency_analysis_engine.py:625-636`. `_normalize_reference` returns `list({value, without_suffix, dotted, stem})`, a **set**, so the key order follows hash randomisation. + - `_first_match` (`:378-380`) returns the first key found. + - `lookup.setdefault(key, node_id)` (`:893-894`) maps every stem (`util`, `index`, `types`, `models`) to the alphabetically first file with that stem in the whole project. + - Relative specifiers (`./util`, `../x/util`, Python `.models`) are never joined with the importer's directory. + - `ExecutePython` sets no `PYTHONHASHSEED` (grep finds none), and every refresh is a new process. +- Reproduced: + - Fixture `fixture-stem/`: `a/util.ts`, `b/util.ts`, `c/util.ts`, `c/main.ts: import {z} from './util'`, `c/alias.ts: import {y} from 'b/util'`. + - Seeds 0-7: `c/main.ts -> a/util.ts` every time, which is the wrong file, marked `import exact`. + - `c/alias.ts -> a/util.ts` for seeds 0,1,2,6,7 and `-> b/util.ts` for seeds 3,4,5, so the result depends on the seed. + - `c/typed.ts: import type {T} from './types'` produces a bogus external package `type`. On this repo, `type` is the 6th most common "package" with 24 edges. + - Python `from .models import X` becomes external package `.models` (fixture `fixture-py/`). + - On this repo's `src` the stems happen to be unique, so 1,040/1,040 relative imports resolved correctly. Projects with `index.ts`, `utils.*`, `types.*` or `__init__.py` in several folders get wrong, cross-folder edges. That creates false cycles (feeding DEPGRAPH-1's Cycle value) and false fan-in on whichever file sorts first. +- Failure scenario: + - A user analyses a typical TS/JS/Python project: the graph shows `src/feature/x.ts → src/aaa/index.ts` instead of its sibling `index.ts`. + - After each save (incremental refresh = new Python process), some edges can jump to another target. Edge ids are hashes of source/target/kind (`_build_edges`), so the reconciliation animates edges disappearing and appearing with no code change. +- Confidence: CONFIRMED (fixtures above; `PYTHONHASHSEED=0..7 venv/bin/python run_dep.py fixture-stem f$s.json`). +- Proposed fix (`dependency_analysis_engine.py`): + 1. Make `_normalize_reference` order-stable (`list(dict.fromkeys([...]))`) with explicit priority: full path, then without suffix, then dotted, then stem last. + 2. Resolve relative specifiers first against `posixpath.dirname(importer)`, trying the language's extensions and `index.*` / `__init__.py`. Only fall back to the global stem lookup when that fails, and downgrade the confidence to `probable`. + 3. Strip the `type` modifier in TS `import type`/`export type` before resolution. + 4. Pass `PYTHONHASHSEED=0` in the spawn env (`executePython.ts` `spawnAndCollect`) as a belt-and-braces measure. + - Tests: a golden fixture with duplicate stems, run under two `PYTHONHASHSEED` values in `backend/tests/dependencies/` with `subprocess`, asserting byte-identical edge lists and the sibling target. + - This resolves the REPORT §9 item "edge target picked from a set". **It is user-facing, not just a quirk.** + +### DEPGRAPH-4: The entity's `datasetUrl` and `scope` drift apart, so a reload, a late joiner or a collaborator gets an empty table with no error +- Severity: major - Type: bug +- Evidence: + - `dependencyGraphBridge.ts:208-231`. A file-scope request sets `datasetUrl: /dependencies/dependency-scope-.json` with **no** `projectDatasetUrl`. + - `handleDependencyGraphSettingsMessage` (`:179-205`) changes `scope` but never `datasetUrl`. + - In the browser, `openFile` reuses a locally cached dataset and only publishes `scope` (`scalesAndControls.js:8-14`). + - `filteredDataset()` (`datasetProjection.js:383-387`) returns `{nodes:[],edges:[]}` when the dataset type does not match the scope. + - The only escape is the refresh path, which does add `projectDatasetUrl` (`dependencyGraphBridge.ts:363-376`). +- Reproduced in the real runtime (harness `run.cjs s1`, `run5.cjs`): + - Directory scope + project dataset: 7 nodes. `openFile('core/dependencies/dependencyGraphService.ts')`: 14 nodes. "Go to parent" (`openDirectory('core/dependencies')`): 4 nodes. The server entity is now `{datasetUrl:'/s/scope-file.json', scope:{kind:'directory',relativePath:'core/dependencies'}}`. + - Reloading the page with that entity: **0 nodes**, `state.dataset.targetType=file`, `projectDataset=false`, breadcrumb "Folder: core/dependencies", no error. + - The reverse case: entity `scope=file`, `datasetUrl=project` (what a cached `openFile` publishes after a refresh) also gives **0 nodes**. + - `start()` does not help: the cached-URL "restoring" path republishes the same `datasetUrl`. Only "Re-analyze" (forceFull) recovers. +- Failure scenario: + - Drill into a file, go back up, then reload the browser tab, enter VR on another device, or have a colleague join: the dependency table is empty. + - In collaboration, participant A opens a file it had cached. Participant B (no cache) shows an empty table, because B never fetches the file dataset. +- Confidence: CONFIRMED (Playwright harness with the real assembled `dependencyGraphRuntime.js`; the fake server mirrors the bridge's merge rules). +- Proposed fix: + - Keep **both** URLs in the entity at all times: `projectDatasetUrl` (set by every directory analysis, and kept by the file-scope request) and `fileDatasetUrls[path]` or `fileDatasetUrl` for the active file scope. + - Have `applySharedState` fetch the dataset that matches `snapshot.scope`. Fall back to `projectDatasetUrl`, and when a file dataset is missing, send `dependency-file-scope-request` instead of rendering empty. + - In `filteredDataset`, if the selected dataset is missing, show a status ("Loading file symbols...") and request it. Never render an empty graph silently. + - Server side: `handleDependencyGraphSettingsMessage` should not accept `scope.kind:'file'` unless that file's dataset exists, or should trigger `analyzeFileScope` itself. + - Test: extend `test/runners/run-xr-mode-cycle-harness.cjs` with the S1c and S6 scenarios (entity with mismatched scope/datasetUrl → expect nodes > 0), plus a bridge unit test asserting that `projectDatasetUrl` survives a file-scope request. + +### DEPGRAPH-5: No 600-node / 2,000-edge render budget exists, and the force-3d "layout" piles every node past the 16th onto one circle +- Severity: major - Type: bug / ux (docs mismatch) +- Evidence: + - `apps/vscode-extension/docs/features/DEPENDENCY_GRAPH_XR.md` ("The runtime limits a rendered view to 600 nodes and 2,000 edges. Larger datasets open in group mode") does not match the code. + - No limit exists anywhere in `dependencyGraphRuntime/*`. The only `600` is a density score divisor in `dependency-visual-budget/dependencyVisualBudgetRuntime.js:52`. + - There is no "group mode". + - `setGraph` creates one `a-entity` per node. + - The worker's force-3d branch (`scalesAndControls.js:480`): `radius=Math.min(Math.min(w,d)*.45, .28+ring*.22)` with `ring=floor(sqrt(i))`. That reaches the cap of 1.0575 at ring 4, so every node with index ≥ 16 sits on the same radius-1.06 circle, varied only by 5 y-levels. Edges are ignored, so there is no force at all, and a 2.1-wide disc is used on a 4.7×2.35 table. +- Reproduced (harness `run.cjs s2`, real runtime, this repo's `src` dataset at the project root with `External: shown`, a single click): + - 2,456 node entities, 2,669 DOM entities under the graph root. + - **2,440 nodes on the same ring**. + - Profile `dense`, where edge opacity drops to 0.02-0.06. + - No notice to the user. + - With hidden externals the same root shows 7 nodes. A flat folder with N files shows N nodes, also uncapped. +- Failure scenario: the user clicks the orange external-summary node, then "Show external" (`tooltipsAndSelection.js:120`). The headset has to render thousands of entities in a solid ring, frame time collapses on Quest-class devices, and nothing says the view is degraded. +- Confidence: CONFIRMED (counts and positions read from the component; timing on a headset not measured). +- Proposed fix: + - Enforce the documented budget in `filteredDataset()`. Rank nodes by degree, keep the top 600 and the edges among them, and replace the rest with one aggregate "N more" portal node (reuse `createAggregateNode`). Show a status line "Showing 600 of 2,456 nodes". + - For externals, cap to the top-K packages by occurrences. + - Replace the force-3d placement with a real bounded layout that uses the table's aspect ratio: a few hundred iterations of a simple force simulation in the worker, or at least a Fibonacci spiral whose radius grows with sqrt(i/N) up to the table bounds in x and z separately. + - Tests: a unit test on a `filteredDataset`-level budget function (2,000 synthetic nodes gives ≤ 600 + 1). A harness assertion that the number of distinct radii is > 20 for 300 nodes. + +### DEPGRAPH-6: One Web Worker leaks on every entry into dependency mode +- Severity: minor (accumulates over a session) - Type: bug +- Evidence: + - `viewLifecycle.js:15-18`. `renderGraphWhenReady` calls `component.setGraph` as soon as `refs.graph.components[COMPONENT]` exists, which is **before** A-Frame has run `init`. + - `setGraph` calls `this.ensureWorker()` (`componentCore.js:241`), which creates worker #1 because `this.worker` is undefined. + - Then `init` runs: `this.worker = null; ... this.ensureWorker();` (`componentCore.js:6, 51`) overwrites the reference with worker #2 without terminating #1. + - `remove()` only terminates #2. The pre-init `pendingGraph` is also wiped, so the first layout pass is wasted, and the `componentinitialized` listener renders again. + - Each leaked worker also keeps its Blob URL, which is never revoked (`scalesAndControls.js:483`). +- Reproduced (harness `run3.cjs s3`, Worker constructor instrumented). Three enter/leave cycles give workers `created 2/4/6, terminated 1/2/3`. The stack traces show creation #1 from `setGraph ← renderGraphWhenReady ← applySharedState ← performTransition`, and #2 from `init ← initComponent`. +- Failure scenario: a long session switching between analyses accumulates one idle thread plus its heap per entry. On a standalone headset that adds memory pressure. +- Confidence: CONFIRMED. +- Proposed fix: + - In `init`, terminate any existing worker (`this.worker?.terminate?.()`) instead of nulling it. Better: make `renderGraphWhenReady` require `component.initialized === true` (or `refs.graph.hasLoaded`) before calling `setGraph`, so the retry loop and the `componentinitialized` listener do their job. + - Revoke the Blob URL right after `new Worker(...)`. + - Add `worker.onerror`, which today is absent. A throw in the worker (for example a node without `metrics` in metric-space) leaves `pendingGraph` unresolved and the old graph frozen, with no status. + - Test: a harness assertion that `created - terminated <= 1` after N cycles, and `=== 0` once the graph root is gone. + +### DEPGRAPH-7: Re-entering the mode while a refresh runs strands the user in the selector, and the 20 s watchdog falsely reports "did not respond" +- Severity: minor - Type: ux / robustness +- Evidence: + - `viewLifecycle.js:134-135, 154-201`. `selectDependencyMode` only short-cuts when the snapshot is `ready`. With status `analyzing` it calls `start()`, which hops to `selection` first. + - The server refuses with "A dependency analysis is already running." (`dependencyGraphBridge.ts:315-320`, pinned by the bridge test). + - The later `ready` entity is ignored because the mode is no longer dependency (`applySharedState` early return, `:97-100`). + - Separately, `setTransitionLocked(true)` arms a 20 s watchdog (`datasetProjection.js:93-113`). `dependency-graph-progress` messages do not refresh it, so any first analysis over 20 s shows the red "The dependency analysis did not respond. Try again." while it is progressing. + - While locked, `publishState` (`datasetProjection.js:404`) silently drops every navigation, filter or "Open folder" click. +- Reproduced (harness `run5.cjs` S5, entity `analyzing` + busy server): + - After the click: `mode:selection, nodes:0`, error status. + - After the refresh publishes `ready`: still `mode:selection, nodes:0`. The user must click Dependencies again. + - The watchdog case was traced in code. A full deep scan of `apps/vscode-extension` (550 files, 6,172 nodes) took 38 s wall-clock here under load, so >20 s is realistic. +- Failure scenario: in dependency mode, save a file (refresh starts), switch to Normal and back. The user lands on the analysis selector with an error, although the graph will be ready seconds later. +- Confidence: CONFIRMED (stranding) / LIKELY (watchdog false alarm). +- Proposed fix: + - In `selectDependencyMode`, treat `status:'analyzing'` with a known `datasetUrl` (or any `analyzing`) as "attach": call `activateReadySnapshot`-like logic that enters the mode, shows progress, and renders when `ready` arrives. + - On the server, when busy, answer by activating the view and returning the current entity instead of an error. + - Re-arm or extend the watchdog on every `dependency-graph-progress` and on `analyzing` snapshots. + - Show "Busy: please wait" when `publishState` is dropped. + - Test: a harness scenario S5 asserting final `mode === 'dependency-graph'` and nodes > 0. + +### DEPGRAPH-8: Browser file-scope cache is never invalidated, so re-opening a file after edits shows stale symbols +- Severity: minor - Type: bug +- Evidence: + - `scalesAndControls.js:11-14`. `openFile` publishes the scope without asking the server when `state.fileDatasets[path]` exists. + - `state.fileDatasets` is only ever added to (`viewLifecycle.js:67-70`). It is not cleared on a new project `revision`/`sourceRevision`. + - The server cache keys by content hash (`dependencyGraphService.ts:82-84`), but it is bypassed here. +- Failure scenario: drill into `a.ts`, go up, edit `a.ts` (the directory refresh runs), then open `a.ts` again. The old symbols and calls are shown. This compounds with DEPGRAPH-4 for other participants. +- Confidence: LIKELY (traced; the same code path that S6 exercised). +- Proposed fix: key `fileDatasets` by `(path, project sourceRevision)` or clear it whenever a new directory dataset with a higher `sourceRevision` is stored. Always send `dependency-file-scope-request` (the server answers from its hash cache cheaply). Test: a vm unit test in `dependencyFileScope.test.cjs`. + +### DEPGRAPH-9: Analysis jobs cannot be cancelled or timed out, and dataset revisions accumulate in the served folder and in exports +- Severity: minor - Type: robustness +- Evidence: + - `DependencyGraphService.dispose()` only nulls `activeJob` (`dependencyGraphService.ts:71-74`). `executeDependencyAnalysis` has no timeout (`executePython.ts:85-111`). + - Leaving the mode does not stop Python. A hung parse would keep `isBusy()` true, so every later start answers "already running" until the extension restarts. + - Every refresh writes two pretty-printed copies (`dependency-graph-.json` + `dependency-graph.json`; 6.2 MB for the extension folder) and never deletes older revisions or `dependency-scope-*.json`. With live refresh on every save this grows without bound and is copied into exports (`exportPackageTransaction.ts` only removes the whole folder when the mode is not selected). +- Confidence: LIKELY (traced). +- Proposed fix: + - Pass an AbortSignal/timeout through `executePythonScript` and kill the child on dispose or mode exit if no one waits. + - Keep the last two revisions plus the active scope file and delete older ones after publishing. + - Write compact JSON. + +### DEPGRAPH-10: File node ids collide on case-sensitive filesystems +- Severity: minor - Type: bug +- Evidence: `_node_id("file", relative.lower())` (`dependency_analysis_engine.py:880`). The lookup keys are lower-cased too. +- Reproduced: `Util.ts` and `util.ts` in one folder both get `file:22d7d69277642e62`. Duplicate node ids break the reconciliation keyed by id. +- Confidence: CONFIRMED (`fixture-case/`). +- Proposed fix: hash the exact relative path, and keep case-folding only for resolution keys on case-insensitive platforms. +- On "Windows paths in node ids": not an issue. The engine uses `_portable_relative` (forward slashes), the bridge rewrites `\` to `/`, and the runtime's `normalizeRelativePath` does the same. + +### DEPGRAPH-11: REPORT §9 item "shared-state fetch does not check snapshot identity": low user impact +- Severity: minor - Type: robustness +- Evidence: `viewLifecycle.js:77-88`. `loadProjectDataset` checks only `isLoadCurrent` (load and view generation), not `state.snapshot === snapshot`. +- A newer `ready` snapshot always bumps `datasetLoadGeneration`, so the stale result is discarded. A newer non-ready snapshot (`analyzing`) does not, but then `renderGraph()` refuses to render (`status !== 'ready'`). The worst case is a briefly older `projectDataset` that the next `ready` snapshot overwrites. +- Not a user-facing bug today. Fix it together with DEPGRAPH-4 by adding the identity check. +- Confidence: LIKELY (traced). + +### DEPGRAPH-12: Test gaps +- Severity: minor - Type: test-gap +- No test covers: + - folder card metrics; + - external-node creation from calls; + - relative or duplicate-stem resolution, or determinism across hash seeds; + - scope/datasetUrl consistency after drill-down plus reload; + - worker create/terminate balance; + - any node or edge budget; + - re-entry while busy. +- `dependencyGraph.test.cjs` even pins the missing identity check "as-is". +- The scratch harness (`build.cjs`, `run.cjs`, `run5.cjs`) shows that extending `test/manual/xr-mode-cycle-harness.html` with the following is enough to make S1c, S2, S3, S5 and S6 CI checks: + - a configurable `dependencyState` (`window.__DEP_STATE`); + - a `dependency-graph-settings` / `dependency-file-scope-request` echo; + - a busy flag. + +## 3. Architecture recommendations (for the unified launcher and the unified chart rebuild) + +- **One analysis-session contract per mode.** Dependency mode mixes three channels: the `analysis-view` entity (which mode), its own entity (status + `datasetUrl` + view settings), and local caches (`projectDataset`, `fileDatasets`). + - For the unified launcher, each mode should expose the same lifecycle: `canAttach(snapshot)` → `activate` → `render(dataset)` → `deactivate`, plus a status machine `idle | analyzing | ready | error`. + - Entering a mode while it is `analyzing` should *attach* (DEPGRAPH-7), never restart or refuse. + - The server entity should always carry every URL needed to rebuild the current view from scratch (DEPGRAPH-4). Treat "late joiner / reload reproduces the same view" as an acceptance test for every mode. +- **Budget and containment in the projection step, not the renderer.** `filteredDataset()` is the natural single place for the unified "rebuild inside the table" mechanism: project → filter → **budget (cap + aggregate)** → layout within `{width, depth, height}` from the table runtime → render. + - Pass the table bounds in instead of the hard-coded `GRAPH_WIDTH/DEPTH`, root position `0 1.02 -18` (`tooltipsAndSelection.js:345`) and `rig` reset coordinates (`viewLifecycle.js:40`), so the graph follows the analysis-table component like the other charts. +- **Metrics belong to the projection.** Aggregated nodes need metrics computed from the projected edge set (DEPGRAPH-1). Do the same for "Other project files", the parent node and the external summary, so that the cards always describe what is drawn. +- **Worker ownership.** Create the worker lazily from the projection or render service (one per page, revocable Blob URL, `onerror` → status + unlock) rather than inside a component instance that can be called before `init` (DEPGRAPH-6). +- **Engine determinism as a contract.** Add a golden test that runs the engine twice under different `PYTHONHASHSEED` values and asserts identical output. Edge ids are the reconciliation keys, so instability shows up as visible churn in XR. diff --git a/docs/xr-audit/evolution.md b/docs/xr-audit/evolution.md new file mode 100644 index 00000000..dabeed47 --- /dev/null +++ b/docs/xr-audit/evolution.md @@ -0,0 +1,326 @@ +# XR audit: Project Evolution (area "evolution") + +Auditor scratch dir: `/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/evolution/` +- `hostRepro.test.cjs`: host-side repros A to L. They run the compiled `out/` services under the repo's fake vscode, against real git repos built in the scratch dir. Run them with `node --test --test-name-pattern="^X" hostRepro.test.cjs`. +- `sandbox.cjs`, `repro-generating-stuck.cjs`, `repro-cleared-stuck.cjs`: browser-runtime repros. They load the assembled `projectEvolutionRuntime.js` in a `vm` with a fake collaboration client. + +Baseline (all green): `projectEvolutionRuntime` 17/17, `gitHistoryServices` 24/24, `gitRevisionExporter` 15/15, `gitRevisionExportPhases` 7/7, `gitListReferences` 4/4, `gitMaterializeDirectory` 5/5, `gitExportPreflight` 1/1, `gitRefPickerRuntime` 7/7, `exportPackageTransaction` 3/3, `historicalComparison` 16/16, `gitAnalysisShared` 4/4. `npm run test:project-evolution-harness` with the CDN preload exits 0. The harness writes into `apps/vscode-extension/output/project-evolution-harness/`, a gitignored build-output folder. `gitRevisionExporter.test.cjs`'s formerly Windows-only failure is the decorator test with `C:` roots: `buildBabiaStyleFilePath` now strips the drive letter, and CI was green on Windows (REPORT §1), so it is no longer reproducible here. + +## 1. How it works + +- **Server side.** `AnalysisFeatureHost` (`src/core/server/analysis/analysisFeatureHost.ts:138`) creates one `ProjectEvolutionService` per XR session. `ProjectEvolutionBridge` (`src/core/server/analysis/projectEvolutionBridge.ts`) maps collaboration-room messages to it: + - `project-evolution-references-request` + - `-start`: runs fire-and-forget, broadcasts `-progress`, and finally upserts the shared entity `project-evolution/main`. + - `-apply-frame`: copies `dataN.json` over a shared `data.json`, then broadcasts `-frame-applied`. + - `-clear` +- **Generate** (`projectEvolutionService.ts:147`) has four phases: + 1. Resolve the timeline: `git log --all --reverse --max-count=240` plus the working copy (`buildAutomaticTimeline`), or a range or manual picks. + 2. Filter through `GitAnalysisSourceCatalog`, which uses a `GitTimelineBlobIndex` over persistent `git cat-file --batch` processes. + 3. Sample to 24 frames (`gitTimelineSampler`). + 4. Analyze with 4 async "workers". Each one `materialize()`s the commit to disk (one `git show` per file) and runs the full Python `main.py --mode xr` through `ExecutePython`, via `GitAnalysisSessionContext.analyzeSource`. The results are cached per commit in an unbounded Map. Finally `writeEvolutionArtifacts` writes `evolution/revision-N/data{i}.json`, `data.json` and `manifest.json`. +- **Jobs.** `SingleJobGate` refuses a second job. Cancellation is a counter (`cancellationRevision`) that is checked only between revisions. +- **Export path.** `exportGitRevisionData` → `runGitRevisionExport` → `GitTimelineBlobAnalyzer`. It indexes every selected commit's tree via cat-file and analyzes each distinct blob+extension once in `GitExportPythonWorkerPool` (persistent `git_export_analysis_worker.py` children). It writes `git-revisions/*.json` plus `gitData`, which the browser's `offlineGitData.js` turns into movies offline. +- **Browser.** `projectEvolutionRuntime` has 9 parts: + - It registers a mode lifecycle with `CodeXRAnalysisModeRuntime` (activate, deactivate, capture and restore state) and a Git-gated selector option. + - It builds a selection panel around the shared git-ref picker in `sequence` mode. + - It plays frames through `seek` → `requestBridgeFrame` (server copies the frame to the bridge) → `applyBridgeFrameToChart`. That last step uses one declarative pipeline (`babia-queryjson` → tree builder → chart under `codexrProjectEvolutionRoot`), wrapped in analysis-table containment data transitions, and guarded by `viewGeneration` and `playbackGeneration` counters. +- **Who is "generating".** Each client works out the `generating` flag from the broadcast `-progress` messages. There is no server-authoritative job state. + +## 2. Findings + +### EVO-1: A failed generation leaves the client "generating"; leaving the mode then deletes the previous good movie for the whole room +- Severity: **blocker** | Type: bug +- Evidence: + - `templates/components/codexr/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js:286-302`. `handleProgress` sets `state.generating = payload.state === 'analyzing' && frameCount > 0`. `handleError` stops playback and sets the status, but never resets `generating` or hides the progress bar. + - `frameApplication.js:150-161`. `applyClearedState` does not reset it either. + - `transportAndRegistration.js:152-161`: + ```js + function releaseEvolutionOnLeave() { + invalidateEvolutionView(...); + if (state.generating) { state.generating = false; renderGenerationProgress({state:'idle'}); clearMovie(); } + ``` + `clearMovie()` sends `project-evolution-clear`. The server-side `handleProjectEvolutionClearMessage` (`projectEvolutionBridge.ts:43-83`) deletes `revision-N`, removes the shared entity and broadcasts `-cleared` to everybody. +- Failure scenario: + 1. A movie exists. + 2. The user presses Generate again (another range, for example). The server sends a few `analyzing` progress messages, then fails: insufficient data, a range that is not found, the busy race, a Python error, and so on. + 3. The panel shows the error, but the progress bar stays at "Generating frame k / n". + 4. The user goes back to Single. + 5. The client sends `project-evolution-clear`, and the previously generated movie is deleted for every participant. The same stale flag also follows a `-cleared` broadcast, which leaves the progress bar frozen. +- Confidence: **CONFIRMED** (`repro-generating-stuck.cjs`). After `-error`, `generating = true` and the movie at revision 1 is still loaded. `lifecycle.deactivate()` then sends `['project-evolution-clear']`. `repro-cleared-stuck.cjs` shows that `generating` stays true after `-cleared`. +- Proposed fix: + - Reset `generating` and call `renderGenerationProgress({state:'idle'})` in `handleError`, `applyClearedState` and `applySharedState`. + - Better: see EVO-2. A server-authoritative job state, and leave-mode never sending a destructive clear. +- Test: add a case to `test/analysis/projectEvolutionRuntime.test.cjs` that drives the handlers the way the sandbox does, sending progress then error, and asserts `getState().generating === false` and that deactivate sends nothing. + +### EVO-2: "Cancel" is implemented as "Clear": any participant leaving mid-generation wipes the room's movie, and the server does not actually stop +- Severity: **major** | Type: bug / architecture +- Evidence: + - `transportAndRegistration.js:148-161`. The comment says *"a generation in flight is CANCELLED and everything cleaned (the server aborts its workers on project-evolution-clear…)"*. + - `projectEvolutionService.ts:107-121`. `clearGeneratedMovie` bumps `cancellationRevision` **and** `rm`s the current `revision-N`, which is the old good movie. + - `projectEvolutionService.ts:212-265`. Workers check the counter only after `analyzeSource` returns, so Python and git keep running. + - The first worker to notice throws `project-evolution-cleared`, so `Promise.all` rejects immediately and `SingleJobGate.run`'s `finally` (`gitAnalysisSessionContext.ts:255-268`) frees the gate **while the other workers are still materializing and analyzing**. Those orphans later `cache.set()` into the cache that was just cleared. + - Every client receives the broadcast progress, so every client that is in the mode and leaves triggers the clear, not only the one who pressed Generate. +- Failure scenario A: user A generates, and user B (or A in another tab) switches to Dependency graph. A's generation is aborted, the old movie is deleted, and A sees "Project evolution movie cleared." +- Failure scenario B: Clear, then Generate again immediately. The new job runs alongside orphan Python processes from the old one. Both `rm -rf` and rewrite the same `snapshots/` directory (`gitRepositoryService.ts:208-212`) when they hit the same commit. A partial snapshot can then be analyzed, cached, and even recorded as a *deterministic* exclusion in the shared catalogue (`gitAnalysisSessionContext.ts:204-219`), which hides that commit from both Git pickers until the session ends. +- Confidence: + - Scenario A: **LIKELY**. Code-traced; the client half is confirmed by EVO-1's repro. + - Early gate release: **LIKELY** (code). + - Snapshot-directory race: **SUSPECTED**. Repro G, which picks the same commit as a branch and as a commit in manual mode, did not corrupt it with the timing used. +- Proposed fix: + - Split the protocol into `project-evolution-cancel` (job only, keeps the last good movie, owner-only or explicit button) and `-clear` (files and entity). + - Leaving the mode must not cancel. Let the job finish in the background; the entity is passive anyway. + - Plumb an `AbortSignal` from `generate()` into `GitRepositoryService.runGit*` (`execFile` `signal`) and `ExecutePython.spawnAndCollect` (`child.kill()`). + - Make `analyzeSources` await all workers (`Promise.allSettled`) before releasing the gate. + - Key snapshot directories by `sha + jobId`, or serialize materialization per sha with a `Map`. +- Test: extend `gitHistoryServices.test.cjs` with a stub analyzer that blocks on a deferred. Assert that `isBusy()` stays true until every in-flight analysis settles after clear or cancel, and that a cancel does not delete `revision-N`. + +### EVO-3: No timeout and no kill for per-revision analysis: one slow or hung revision keeps the service "busy" forever, even after Clear +- Severity: **major** | Type: robustness +- Evidence: + - `gitAnalysisSessionContext.ts:133`: `await new ExecutePython(this.extensionContext).executeAnalysis(revisionSession)`. + - `src/core/analysis/python/executePython.ts:438-497`. `spawnAndCollect` has no timeout or kill. + - `gitRepositoryService.ts:528-572`. `execFile` git calls have no timeout. + - `projectEvolutionBridge.ts:137-146` answers `project-evolution-busy` while `isBusy()`. +- Failure scenario: a revision with a pathological file (for example huge minified JS through lizard), or a git process waiting on a lazy fetch (EVO-10). The movie "never finishes". Clear does not help, because the worker that never returns is never re-checked. Every later Generate gets "Another project evolution analysis is already running." until VS Code reloads. This matches the "it always gives trouble / gets stuck" report. +- Confidence: **CONFIRMED** (repro A). After `clearGeneratedMovie()` and a 500 ms wait, `isBusy() === true` and a second `generate()` rejects with `project-evolution-busy`. +- Proposed fix: + - Per-revision watchdog: a timeout scaled to file count, which kills the child and turns the revision into an `analysis-failed` exclusion. + - Plus the AbortSignal from EVO-2. + - Expose a "Cancel generation" button that only cancels. +- Test: unit test with a never-resolving stub analyzer and a fake clock. Assert that the job rejects or excludes after the timeout and `isBusy()` returns to false. + +### EVO-4: Clear landing after the analyses finish is ignored: the movie is written and published after everyone was told it was cleared +- Severity: **major** | Type: bug (race) +- Evidence: + - `projectEvolutionService.ts:163-191`. Cancellation is checked only inside `analyzeSources`. `writeEvolutionArtifacts` (`:269-318`) does `++this.revision`, then `rm`, `mkdir`, 24 × `writeFile` and the manifest, with no check. + - The bridge then unconditionally calls `upsertSharedEntity` and `setSnapshotAvailable(true)` (`projectEvolutionBridge.ts:189-206`). + - Because `this.revision` is bumped synchronously at the start of the write phase, a concurrent `clearGeneratedMovie` `rm`s the directory being written. The next `writeFile` throws ENOENT, which reaches every client as `project-evolution-failed`. +- Failure scenario: a user presses "Clear movie", or leaves the mode (EVO-2), during the last seconds. Every client gets `-cleared` and empties the panel. A moment later the movie entity arrives and the selection panel turns back into a movie; or the room gets an ENOENT error. +- Confidence: **CONFIRMED** (repro B). Clear was issued right after the final "Analyzed N / N" progress, and `generate()` still RESOLVED with revision 1 and 7 frames, with all files on disk. +- Proposed fix: + - Check the token before `++revision`, after the writes, and again in the bridge before `upsertSharedEntity`. On mismatch, `rm` the new directory and throw `project-evolution-cleared`. + - Make Clear await the running job's settlement (or cancel it, as in EVO-2) instead of racing it. +- Test: the repro B pattern, a clear scheduled from the final progress callback. Assert rejection with `project-evolution-cleared` and no `revision-*` left. + +### EVO-5: The shared `data.json` "bridge" races: concurrent frame applies fail with ENOENT or leave the wrong frame's data under the right label, and the error stops playback for the whole room +- Severity: **major** | Type: bug / architecture +- Evidence: + - `projectEvolutionService.ts:123-145` and `:486-490`: + ```ts + const tempPath = `${destinationPath}.${process.pid}.${Date.now()}.tmp`; + await fs.promises.copyFile(sourcePath, tempPath); + await fs.promises.rename(tempPath, destinationPath); + ``` + Two applies in the same millisecond share one temp name, and the renames land in completion order, not request order. + - The browser always reads the bridge URL online. `framePlaybackEngine.js:8-18` uses `bridgeUrl()`; the frame's own `url` is used only offline. + - Errors go out with `messageContext.broadcast` (`projectEvolutionBridge.ts:118-126`). `handleError` (`playbackControlsAndMessages.js:296-302`) rejects every client's pending apply and calls `stop()`. + - The `-start` busy race has the same shape. `isBusy()` is checked synchronously, but `generate()` only starts after `await reconcileSession` (`:178-183`), so a double-click or two users produce a broadcast `project-evolution-busy` error that stops everybody while the first job keeps running. +- Failure scenario: + - Fast Next/Next/Previous, or two participants seeking or playing in the same room, gives intermittent ENOENT errors. Playback stops for everyone. + - Worse, client A requests frame 5, B requests frame 2, and A then fetches `data.json?t=…` after B's copy. A shows frame 2's data titled "Frame 5". This is silent. +- Confidence: **CONFIRMED** (repro F). 200 rounds of 3 concurrent `applyFrameToBridge` gave **380 / 600 rejections with ENOENT**. The data mis-labelling follows from the same ordering race (code). +- Proposed fix: + - Delete the bridge. Point `babia-queryjson` at `frame.url` (`/evolution/revision-N/data{i+1}.json?t=…`), exactly as the offline path already does. The URL changes every frame anyway because of the cache buster. + - `project-evolution-apply-frame` then becomes, at most, a "follow me" broadcast carrying `frameIndex`, with no file I/O. + - Reply to errors with `messageContext.send` (the requester only). Broadcast only room-level state. +- Test: + - A unit test that concurrent applies never reject, or the removal of `applyFrameToBridge`. + - The harness's `/__project_evolution_apply_frame` route should stop copying. + - A Playwright step with a seek storm that asserts the datasource URL's `frame=` matches `runtime.frameIndex`. + +### EVO-6: The timeline is `git log --all`, so stashes, notes, remote and other-branch commits become movie frames, and the movie can travel past HEAD and back +- Severity: **major** | Type: bug +- Evidence: + - `gitRepositoryService.ts:138-145`: `['log','--all','--reverse',…]`. The same applies to `listReferences` (`:69-75`) and the export. + - `--all` includes `refs/stash` (a 2-parent "merge", which `gitTimelineSampler.isMilestone` **prefers**), the stash's "index on …" commit, and `refs/notes/*`. It also includes every local and remote branch. + - `resolveCurrentStateSource` (`projectEvolutionService.ts:418-422`) appends the working copy as the last frame. Frames from other branches that are newer than HEAD therefore come *before* the final HEAD state. +- Failure scenario: + - A stash (`git stash`) shows up as a milestone frame titled "On main: WIP…" containing uncommitted, possibly deleted, work. A `git notes` commit shows up as a frame. + - On a detached or older checkout, or a feature branch, the movie plays the newer `main` commits and then jumps "back" to the live state. +- Confidence: **CONFIRMED**. + - Repro C, suggested frames: `"Notes added by 'git notes add'"`, `"merge On main: WIP never committed"`, `"index on main: …"`, `c2`, `c1`, live. + - Repro J (shallow clone, detached at `HEAD~1`): frames `9610f415, 38206cd5, 36030e9e (merge, newer than HEAD), Detached HEAD 38206cd5 (live)`. +- Proposed fix: + - Live movie: replace `--all` with `HEAD` (first-parent optional), with `--exclude=refs/stash --exclude=refs/notes/*` as a minimum. + - Offer "all branches" only as an explicit option. + - Export: same, or `--branches --tags --remotes` instead of `--all`. +- Test: a `gitListReferences.test.cjs` / `gitHistoryServices` case with a stash plus a note, asserting neither appears in `listTimelineSources`. Also a detached-HEAD case asserting that no frame is newer than HEAD. + +### EVO-7: Only the newest 240 commits exist for the live movie: long histories never start at the beginning, and older tags or branches offered in the picker fail with a raw error +- Severity: **major** | Type: bug / ux +- Evidence: + - `projectEvolutionService.ts:27` sets `TIMELINE_SCAN_LIMIT = 240`. `listTimelineSources(240)` gives `--max-count` (newest 240), then `--reverse`. + - The picker lists every branch and tag (`getReferences` merges `references.sources`). In range mode, `resolveTimelineIndex` returns −1 for a ref outside the window, so `throw new Error('project-evolution-range-not-found')` (`:355-357`). `describeBridgeError` (`analysisBridgeReplies.ts:70-82`) shows the raw code. + - The sampler's doc (`gitTimelineSampler.ts:16-18`) promises that the "first revision [is] always included". + - The export (`all`) covers the full history, so live and offline Auto movies of the same project differ. +- Failure scenario: in a repository with 300+ commits, the Auto movie starts at commit 60 (or 2,500 of 2,789 for the JetUML export repo). The user picks the `v0.1` tag as range start and gets "project-evolution-range-not-found". +- Confidence: **CONFIRMED**. + - Repro D: 300 commits, first suggested frame = `c60`, root not included. + - Repro K: the old tag is offered, and range → `ERROR "project-evolution-range-not-found"`. +- Proposed fix: + - Sample from the full first-parent history using `git rev-list --count` plus `--skip`-based probes, or `git log --format=%H %ct` (cheap, about 50 bytes per commit) without materializing. Then sample 24. + - For range mode, resolve endpoints with `git rev-list A..B` / `merge-base` instead of looking them up in a window. + - Map error codes to sentences. +- Test: repro D / K as assertions in `gitHistoryServices.test.cjs`. + +### EVO-8: The live pipeline is very expensive: one `git show` process per file per revision, a full Python directory analysis per revision, a VS Code toast per revision, and snapshots kept on disk +- Severity: **major** | Type: robustness / performance (the "never finishes" root cause) +- Evidence: + - `gitRepositoryService.ts:359-375` (`copyPlannedFiles` runs `git show :` per file). + - `gitAnalysisSessionContext.ts:133` calls `executeAnalysis(revisionSession)` **without `{silent:true}`**. `executePython.ts:156-167` then wraps each revision in `vscode.window.withProgress({location: Notification, title:'CodeXR Analysis', cancellable:false})`, so up to 24 toasts appear, 4 at a time. + - Snapshots under `storage/project-evolution//snapshots/` are only deleted on `dispose()` (`gitRepositoryService.ts:220-222`). With up to 100 MB per snapshot, that can reach about 2.4 GB for 24 frames. + - The per-commit payload cache (`GitAnalysisSessionContext.cache`) is unbounded across regenerations with different ranges. + - No dedupe: files that are byte-identical across frames are re-analyzed per frame. The export pipeline already solves this with blob-level dedupe (`gitTimelineBlobAnalyzer.ts`). +- Failure scenario: a 1,000-file directory needs about 10 s of git spawning per frame on Linux, about 250 s for a 24-frame movie, before Python runs. On Windows, process spawn is several times slower. Progress only moves between revisions, so the bar sits still for minutes. +- Confidence: **CONFIRMED** for the cost (repro L: 1,000 files materialized in 10.4 s, 10.4 ms/file). The toasts are **LIKELY** (code-traced; they need the maintainer's eyes in VS Code). +- Proposed fix: + - Make live evolution (and historical comparison) consume the export's `GitTimelineBlobAnalyzer` + `GitExportPythonWorkerPool`. It reads from cat-file, keeps no working-tree snapshots, analyzes each unique blob once, already has a cancel token that kills workers, and reports per-file progress. + - Keep a per-session prepared store as the cache. + - Short of that: pass `{silent:true}`, `rm` each snapshot right after its analysis, and bound the cache (LRU by commit). + - Payload parity between per-blob and `main.py` directory analysis must be verified first: compare one commit both ways in a test. +- Test: a `gitHistoryServices` case asserting `fake.progress` (fakeVscode recorder) receives no notification per revision, and that the snapshots dir is empty after generate. + +### EVO-9: Windows: the export Python worker decodes its stdin with the ANSI code page, so any non-ASCII path (for example `C:\Users\Adrián\…`) fails every job +- Severity: **major** (Windows users with non-ASCII profile names; the maintainer's own name qualifies) | Type: bug +- Evidence: + - `src/core/export/gitExportPythonWorkerPool.ts:141-147` writes `JSON.stringify({inputPath, outputPath…})` as UTF-8. JSON.stringify does not escape non-ASCII. The spawn (`:66-74`) sets no `PYTHONUTF8` / `PYTHONIOENCODING`. + - `backend/src/export/git_export_analysis_worker.py:73` uses `for raw_line in sys.stdin:`. On Windows, Python below 3.15 decodes piped stdin with the locale code page (cp1252), so the path becomes mojibake, `os.path.isfile` is false, and the worker returns `worker-input-missing`. + - The paths live under `context.storageUri`, which is inside the user profile. +- Failure scenario: Export Analysis Folder with History or Evolution on Windows, user profile `C:\Users\Adrián`. Every blob job fails twice (retry), every revision is excluded, and the result is "Fewer than two revisions could be analyzed…". The offline Git modes are unavailable. +- Confidence: **CONFIRMED (emulated on Linux)**. The same command fed to the real worker with `PYTHONIOENCODING=utf-8` gives `complete`; with `cp1252` it gives `{"type":"error","error":"worker-input-missing"}`. The maintainer should check on real Windows. +- Also: the worker's `Path.unlink(missing_ok=True)` (`:66`) needs Python 3.8+, but `venvManager.ts:593` still advertises "Python 3.7+". On 3.7 every successful job would raise in `finally` and be reported as failed (LIKELY). +- Proposed fix: + - Spawn with `env: {...process.env, PYTHONUTF8: '1', PYTHONIOENCODING: 'utf-8'}`. + - In the worker: `sys.stdin.reconfigure(encoding='utf-8')`, or read `sys.stdin.buffer` and decode. + - Belt and braces: escape non-ASCII in Node (`\uXXXX`). + - Replace `missing_ok` with try/except `FileNotFoundError`. +- Test: a worker-pool test whose `temporaryRoot` contains `á`, run with `PYTHONIOENCODING=cp1252` in the spawn env to emulate Windows. + +### EVO-10: Partial clones: every Git mode silently fetches from the remote, which violates the no-network-without-consent principle and can hang on credentials +- Severity: **major** (principle) | Type: robustness +- Evidence: + - `gitRepositoryService.ts:519-526` (`cat-file -e`), `:553-572` (`git show`). + - `gitBatchObjectReader.ts:46-50` (`cat-file --batch`, also used by the eligibility catalogue on every references request). + - No `GIT_NO_LAZY_FETCH` / `--no-lazy-fetch` / `GIT_TERMINAL_PROMPT=0` anywhere. +- Failure scenario: a repository cloned with `--filter=blob:none` (common for large repos). Opening the Evolution panel, or generating, makes git fetch each missing blob from `origin` one by one. This is very slow, uses the network without consent, and with an authenticated remote may block on a credential helper or askpass. The job then hangs (EVO-3). +- Confidence: **CONFIRMED** with a local `file://` promisor remote. `git cat-file -e :a.js` succeeded only by lazily fetching (the pack count grew). This was a local remote only; real network behaviour is inferred. +- Proposed fix: + - Run all history git commands with `env GIT_NO_LAZY_FETCH=1` (git 2.44+; also pass `--no-lazy-fetch` when supported) and `GIT_TERMINAL_PROMPT=0`. + - Treat a missing object as a deterministic `analysis-failed` exclusion with a clear reason ("blob not present locally (partial clone)"). + - Detect `remote.*.promisor=true` in `getAvailability()` and say so. + +### EVO-11: Old `evolution/revision-*` folders accumulate; Clear deletes only the newest; the export then ships a stale movie the user had replaced and cleared +- Severity: minor | Type: bug +- Evidence: + - `projectEvolutionService.ts:269-277`: each generate creates `revision-N` and never removes `revision-(N-1)`. + - `:107-121`: clear removes only `revision-${this.revision}`. + - The export copies the whole static folder (`exportPackageTransaction.ts:63`) and `findNewestEvolutionRevision` (`exportManifest.ts:491-503`) picks the highest remaining number. + - `this.revision` restarts at 0 on a new service, so Clear before the first generate does nothing. +- Failure scenario: Generate, Generate again, Clear, then Export with Evolution. The export advertises and ships revision-1, an older movie, as "the movie computed before export". Disk use also grows with every regeneration. +- Confidence: **CONFIRMED** (repro H: after two generations and Clear, `evolution/` = `['revision-1']`). +- Proposed fix: after a successful write of revision N, `rm` every other `revision-*`, and on clear `rm` the whole `evolution/` folder. Seed `this.revision` from the highest existing folder. + +### EVO-12: Export "latest N" is silently clamped to 1000 commits; "all" can overflow git's 16 MB buffer on very large histories +- Severity: minor | Type: bug +- Evidence: + - `gitRepositoryService.ts:135-137`: `Math.min(1000, …)`. + - `gitExportOptions.ts:61-74` (`validateGitRevisionScope`) accepts up to the total count, and the UI (`activeAnalysesCommands.ts:468-490`) asks for any N. + - `runGit` uses `maxBuffer: 16 MB` (`:530-534`), which an unlimited `git log --all --format=…%s` exceeds at roughly 80k+ commits, giving "git timeline could not be listed". +- Confidence: **CONFIRMED** (repro I: 1,100 commits, latest 1,050 requested, 1,000 returned). Overflow: LIKELY (arithmetic). +- Proposed fix: no clamp for explicit export scopes. Stream `git log` (spawn + line reader) instead of `execFile` buffering. `timelineSelection` should report the real count. + +### EVO-13: Manual mode drops picks after 24 without telling the user; online order is click order while offline is chronological +- Severity: minor | Type: ux / inconsistency +- Evidence: + - The client sends `maxFrames: references.maxFrames || 24` (`playbackControlsAndMessages.js:224-227`). The server does `request.sourceIds.slice(0, maxFrames)` (`projectEvolutionService.ts:324-327`). + - `GitRepositoryService.resolveSourcesInChronologicalOrder` (`:190-195`) does **not** sort, despite its name. + - The offline `buildOfflineFrames` sorts chronologically (`offlineGitData.js:89-97`, pinned by the "manual keeps chronological order" test). +- Confidence: **CONFIRMED** (repro E: picks c3, c1, c2 produce frames in the order third, first, second). +- Proposed fix: decide on one order (the docs say "selection order"; the offline code says chronological). Rename or implement accordingly, and show "max 24" in the panel or refuse a 25th pick. + +### EVO-14: The generation progress bar is non-monotonic and never reaches 100 % +- Severity: minor | Type: ux +- Evidence: + - `projectEvolutionService.ts:217-258`. With 4 concurrent workers, each progress message carries the `frameIndex` of the item that just *started* or *finished*, so a later message can carry a lower `frameIndex` than an earlier one. + - `timelineAndSources.js:195-207` renders `index / count` as "Generating frame index+1 / count". The bar jumps backwards (5/24 → 2/24) and stalls for the whole duration of one revision. +- Confidence: LIKELY (code). +- Proposed fix: send `completed` and `total` (and in-flight labels). Render `completed / total`. + +### EVO-15: Playback edge cases: Play at the end does nothing; a room snapshot replay resets the position to frame 1; speed change during a seek can skip a frame +- Severity: minor | Type: ux +- Evidence: + - `framePlaybackEngine.js:226-228,309-321`. On the last frame, `play()` → `scheduleNext` → immediately "Project evolution finished." It does not restart from frame 1. + - `frameApplication.js:65-74`. `applySharedState` sets `frameIndex = 0` even when the same revision is replayed (reconnect), so `hasPreservedFrame` fails and the client re-seeks frame 1. + - `transportAndRegistration.js:70-80`. `setSpeed` starts a new `scheduleNext` without waiting for the in-flight `seek`. If the server answer takes longer than the new countdown, the next `seek(frameIndex+1)` supersedes it and a frame is skipped. +- Confidence: Play at end and replay reset: LIKELY. Skipped frame: SUSPECTED. +- Proposed fix: Play at the end restarts from 0. Keep `frameIndex` when `shared.result.revision` is unchanged. In `setSpeed` only re-arm the countdown when no seek is pending. + +### EVO-16: Containment data transitions are not exception-safe, so the chart can be left un-contained +- Severity: minor | Type: robustness +- Evidence: + - `framePlaybackEngine.js:39-56,90-127` (`beginEvolutionDataTransition` … `finish/cancel` with no `try/finally`). + - `containmentComponentCore.js:405-411`: while `dataTransitionActive`, `tick` returns early and `requestRenormalize` only queues. + - Any throw between begin and finish (for example inside `setDeclarativeAttribute` or the mapping runtime) leaves the chart frozen outside containment ("chart off the table") until the next transition. +- Confidence: SUSPECTED (not reproduced; the harness's happy path passes). +- Proposed fix: wrap every begin…finish in `try { … } catch { cancel…; throw }`. Better still, move the whole "swap dataset under containment" sequence into one shared helper in the analysis-table runtime, used by every mode (see §3). + +### EVO-17: Export worker pool: no per-job timeout, and a 10 s ready timeout with up to 32 cold interpreters +- Severity: minor | Type: robustness +- Evidence: + - `gitExportPythonWorkerPool.ts:124-149`. `analyze()` waits indefinitely for `complete`/`error`; only user cancellation (`:270-272`) kills it. + - `:7`: `WORKER_READY_TIMEOUT_MS = 10_000`. With the Maximum profile (`gitExportOptions.ts:50-52`, up to 32 workers), a cold lizard import under antivirus on Windows can exceed it. The `createWorker` failure then propagates and fails the whole export. +- Confidence: SUSPECTED. +- Proposed fix: per-job timeout (kill, retry once, record failure). Ready-timeout failure should degrade the worker count rather than abort. + +### EVO-18: Shared picker lists the remote HEAD alias as a branch named "origin" +- Severity: minor | Type: bug (shared with historical comparison) +- Evidence: `gitRepositoryService.ts:417` filters `shortName.endsWith('/HEAD')`, but `%(refname:short)` of `refs/remotes/origin/HEAD` is `origin`. +- Confidence: **CONFIRMED** (repro J sources: `'origin|branch'` next to `'origin/main|branch'`). +- Proposed fix: filter on `fullRef.endsWith('/HEAD')`. + +### EVO-19: Docs drift (`apps/vscode-extension/docs/features/PROJECT_EVOLUTION_XR.md`) +- Severity: minor | Type: docs +- Statements that are wrong or incomplete: + - "Large histories are sampled": the live movie never sees anything older than the newest 240 commits (EVO-7). + - "`Clear movie` removes the generated `/evolution/` JSON files": it removes only the current revision (EVO-11). + - "Each frame replaces the active chart datasource": through a shared `data.json` bridge (EVO-5). + - The `--all` source set, the 24-frame cap for range and manual, and the cancel-on-leave behaviour are not mentioned. Neither are the per-revision cost or the Windows and partial-clone caveats. + - The doc names `projectEvolutionRuntime.js` as one file; it is now 9 parts plus a manifest. +- Proposed fix: rewrite after EVO-2, EVO-5 and EVO-7 land. + +### EVO-20: Test gaps +- Severity: minor | Type: test-gap +- The runtime suite is mostly regexes over the source (`projectEvolutionRuntime.test.cjs:38-100`). There is no behavioural test of the error, cleared, leave and generating interplay (EVO-1/2). +- `gitHistoryServices` has no cancellation, clear-during-generate, or concurrency tests (EVO-2/3/4/5), and no stash, notes, detached or partial-clone fixtures (EVO-6/10). +- The Playwright harness (`test/runners/run-project-evolution-harness.cjs`) fakes the apply-frame endpoint with synchronous `copyFileSync`, so it can never see EVO-5. It also never exercises generation, errors or Clear. +- The `sandbox.cjs` pattern from this audit (vm + fake collaboration client + fake mode runtime) is a cheap way to add these tests. + +## 3. Architecture recommendations (for the unified launcher and the unified chart rebuild) + +1. **One analysis-job contract on the server**, shared by evolution, historical comparison and the dependency graph. Replace `SingleJobGate` plus fire-and-forget bridges with a `JobRunner` with: + - `start(kind, request) → jobId`, `cancel(jobId)`; + - an `AbortSignal` plumbed into every child process (git, Python); + - a watchdog timeout; + - `Promise.allSettled` before releasing the slot; + - one **server-authoritative shared entity** `analysis-job/` = `{jobId, state: running|ready|failed|cancelled, completed, total, message, ownerParticipantId}`. + + Clients render from that entity instead of inferring `generating` from broadcast progress. That removes EVO-1, EVO-2, EVO-4 and EVO-14 by construction. The launcher adds a mode by registering `{kind, buildRequest, run(request, signal, progress) → result entity}`. + +2. **Cancel is not Clear, and leaving a mode never mutates server state.** Mode lifecycles (`deactivate`) should only park visuals. Destructive actions are explicit buttons, and errors go to the requester (`send`), not the room (`broadcast`), unless they are room state. + +3. **One Git revision provider.** Promote the export's `GitTimelineBlobIndex` + `GitTimelineBlobAnalyzer` + `GitExportPythonWorkerPool` to the only way any Git mode obtains a revision payload: + - it materializes nothing; + - it analyzes each blob once; + - it can be cancelled and reports progress per file; + - it runs the same code online and offline, so live and exported movies match. + + Give it a single timeline policy object `{refs: HEAD|branches|all, excludeStash, firstParent, maxScan}` used by the live movie, the pickers and the export (EVO-6, EVO-7, EVO-12). Harden every git spawn in one place (`GIT_NO_LAZY_FETCH`, `GIT_TERMINAL_PROMPT=0`, timeouts, streaming output) and every Python spawn (`PYTHONUTF8=1`). + +4. **Frames are immutable URLs.** No shared mutable bridge file: the client loads `revision-N/data{i}.json` directly (EVO-5). The same rule should apply to the historical-compare sides. Each payload file should be written once and only read after that, so multi-client playback needs no server round-trip. + +5. **Unified chart rebuild.** Evolution's `declarativePipeline.js` (datasource → tree → chart under one root, reuse the Babia instance, `begin/finishChartDataTransition`, `waitForChartsStable`) is the closest thing the codebase has to the desired "rebuild contained in the table" primitive. Extract it into the analysis-table runtime as `swapChartDataset(rootId, {url, chartId, mapping}, {viewGeneration})`. That helper should: + - own the containment transition with try/finally (EVO-16); + - own the cache-busting and the `componentinitialized` waits; + - own the generation guard. + + Single, historical (two roots) and evolution would then all call it. The launcher's mode descriptor supplies only `{tableZones, chartRoots, datasetFor(state)}`. diff --git a/docs/xr-audit/historical.md b/docs/xr-audit/historical.md new file mode 100644 index 00000000..4daa7f76 --- /dev/null +++ b/docs/xr-audit/historical.md @@ -0,0 +1,250 @@ +# XR audit: historical comparison (area "historical") + +Paths are relative to `apps/vscode-extension/` unless they start with `backend/` or `docs/`. +Scratch evidence (scripts, harness copies, repos) is in +`/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/historical/`. + +Area tests run, all green: historicalComparison (16), historicalComparisonRuntime (5), livePanelHistorical (10), +gitMaterializeDirectory (5), gitRefPickerRuntime (7), offlineHistoricalDelta (8), gitHistoryServices (24). +None of the bugs below is covered by them. Most of those tests read source text or stub git. + +## 1. How the area works + +- **Host.** `AnalysisFeatureHost` (src/core/server/analysis/analysisFeatureHost.ts) builds one `HistoricalComparisonService` per XR or LivePanel session. That service owns: + - a `GitRepositoryService` with a private snapshot root under `storageUri/historical-comparisons//snapshots`; + - a `GitAnalysisSessionContext`, which holds the payload cache per commit and calls `ExecutePython`; + - a `SingleJobGate`, so only one comparison runs at a time. +- **How a comparison starts.** XR sends the room message `historical-comparison-start` to `HistoricalComparisonBridge.handleHistoricalComparisonStartMessage`. LivePanel uses `POST /api/historical/compare`, which answers 202 and reports progress over SSE. +- **The compare job.** `compare()` runs these steps: + 1. `resolveSource` on both ids. A working-copy id re-lists every reference. + 2. `analyzeSource` on each side. The working copy is read from the live `data.json`. A commit is materialized with `ls-tree` plus one `git show` per file, then analyzed by Python with no timeout. + 3. Each payload is decorated with `filePath` and `comparisonKey` (`decorateDirectoryEntries`). + 4. `buildDelta`, then `staticRoot/comparison/revision-N-{left,right}.json` and `revision-N.json` are written. + 5. The result is upserted as the shared room entity `historical-comparison/main`. +- **Live refresh.** While the active request has a working-copy side, every re-analysis event schedules `refreshHistoricalComparison` (350 ms debounce), which runs the whole comparison again. +- **Browser runtime.** The runtime is `templates/components/codexr/historical-comparison/historicalComparisonRuntime/*`. Its `applySharedState` fetches both datasets, then either: + - calls `refreshLiveSide`, when the sources are the same and one side is live, or + - calls `renderComparison`, which clones the scene chart twice (`createChartFromTemplate`) into the `historical-left` and `historical-right` containment zones. Boats get inline trees with the uid namespaces `codexr-left:` and `codexr-right:`; other charts get `babia-queryjson` sources named `codexrComparisonData{Left,Right}`. +- **Leaving and re-entering.** Leaving the mode preserves and hides the comparison root (`parkComparisonGeometry`). Re-entering restores it in place (`restoreComparisonScene`). +- **Source picker.** It is `templates/components/common/codexrGitRefPickerRuntime.js` in compare mode. It is fed by `getReferences()`, which `GitAnalysisSourceCatalog.filterSources` filters through a blob index. + +## 2. Findings + +### HIST-1: A failed live refresh retries every 350 ms forever and never tells the user +- Severity: major. Type: bug. +- Evidence: + - src/core/server/analysis/analysisFeatureHost.ts:304-307: `catch (error) { logger.error('...Live refresh failed:', error); this.scheduleHistoricalComparisonRefresh(); }`. There is no attempt limit, no backoff, no error broadcast, and the retry does not check the current view mode. The XR subscription checks `view.mode === 'historical-compare'` (lines 131-134) only for the first event. + - `scheduleHistoricalComparisonRefresh` (265-277) re-arms itself while `hasLiveSource()` holds. `activeRequest` is never cleared, because nothing calls `forgetLastRequest()` for this service. + - Each attempt broadcasts `historical-comparison-progress` "Resolving Git references..." to the room (289-294) and spawns about 6 git processes (`listReferences`). +- Failure scenario: compare `feature/x` with the live working copy, merge the branch and delete it, then save a file. Every refresh now throws `unknown-comparison-source`, or `git-command-failed` from `rev-parse --verify` when the old map still has it. + - The server loops at about 3 attempts per second for the rest of the session. + - The room keeps receiving "analyzing" progress, and the XR status text flips to "Resolving Git references..." forever. + - Any compare the user starts in between can hit the `isBusy()` window and get "Another comparison is already being generated." + - Other permanent triggers: HIST-2, and the snapshot limits in HIST-5. A working copy whose `data.json` becomes `[]` gives `GitAnalysisSourceError`, which loops the same way. +- Confidence: CONFIRMED. + - `scratch/historical/hostloop.cjs` loads the real compiled `AnalysisFeatureHost` under `fakeVscode` and injects a service whose refresh rejects. + - One source-change event produced 10 refresh attempts and 10 progress broadcasts in 3.6 s, and 0 error broadcasts. +- Proposed fix (analysisFeatureHost.ts): + - Retry only on `comparison-busy`. + - On any other error, broadcast `historical-comparison-error` to the room and send SSE `historical-progress` with state `error` to LivePanel. + - Stop the live link: add `HistoricalComparisonService.detachLiveRefresh()`, which calls `jobs.forgetLastRequest()`, or a "stale" flag. + - Also skip the refresh when the XR view is not `historical-compare`, and run it again on re-entry. +- Test: a unit test in a new test/analysis/historicalLiveRefresh.test.cjs that uses `withFakeVscode`. Use the hostloop.cjs pattern and assert that `refreshActiveComparison` is called exactly once, with one error broadcast. + +### HIST-2: A commit side becomes unresolvable once it drops out of the 50 most recent commits +- Severity: major. Type: bug. +- Evidence: + - src/core/history/gitRepositoryService.ts:109-116: `if (sourceId === 'working-copy' || this.sourceById.size === 0) { await this.listReferences(); } ... if (!source) throw new Error('unknown-comparison-source')`. + - `listReferences()` clears the map (83) and refills it with `log --all --max-count=50` (69-75). + - Commit ids are `commit-`, so they cannot be resolved without being in that list, even though the SHA is still a valid object. +- Failure scenario: compare the oldest listed commit (#50) with the working copy. Make one commit. + - The first live refresh still resolves the commit from the old map, because `Promise.all` order lets it. + - The second refresh fails with `unknown-comparison-source`, which feeds the endless loop in HIST-1. + - The same happens if any 50 commits land on any branch (`--all`), for example after a fetch, or on a busy remote. + - A collaborator whose picker is older sends ids that also fail. +- Confidence: CONFIRMED. `scratch/historical/svc2.cjs` runs against a real 56-commit repo and prints "refresh 1 ok / refresh 2 ERR unknown-comparison-source". +- Proposed fix: keep a session-scoped resolved-source registry that `listReferences` adds to and never clears. Alternatively, accept `commit:` ids and resolve them with `rev-parse --verify ^{commit}` when they are missing from the latest list. Branch and tag ids are already re-verified. +- Test: the gitHistoryServices or historicalComparison unit test builds a real repo with more than 50 commits, resolves the oldest id, commits once, calls `resolveSource('working-copy')` twice, then resolves the old id again. + +### HIST-3: Switching chart type in comparison mode points both sides at the normal analysis data +- Severity: major. Type: bug. +- Evidence: + - The comparison clones become the mapping targets (comparisonCharts.js:334-341). The Field Mapping chart buttons stay active in `historical.mapping`, and nothing locks them (`mappingControlsLocked` applies to evolution playback only). + - `selectChart` → `applyChartTypeToEntity` → `buildRuntimeChartData` → `getChartFromSource` (xr-chart-mapping-ui runtime, assembled lines 982-996). Two branches go wrong: + - Hierarchical target (boats): `from` becomes `'tree'` unless the old `from` contains "Tree". Inline `data` is dropped. + - Flat target coming from boats (no `from`): `from` falls back to `'data'`. + - The historical runtime does not listen for chart changes, so it never rebuilds its comparison sources. +- Failure scenario: run a comparison with a bars chart, then click "Babia Boats" in Field Mapping. + - Both clones get `babia-boats from: tree`, which is the normal working-copy tree. + - Clicking "Cyls" next gives both clones `from: data`. + - Both halves of the table then show the same working-copy data under the "LEFT: " and "RIGHT: live" nameplates. The comparison is silently meaningless. + - In a real bars scene there is no `tree` entity, so the boats clones never build. Containment then reports "still rebuilding" indefinitely, which is the "stuck chart" symptom. +- Confidence: CONFIRMED. + - Done in a real headless browser with the assembled runtimes (`scratch/historical/scen.cjs switch`, harness `h2.html`). The chart option was clicked through the UI. + - Output after the clicks: `after switch to boats {"left":{"comp":"babia-boats","from":"tree"},"right":{"comp":"babia-boats","from":"tree"}}`, then `cyls ... "from":"data"` on both sides. +- Proposed fix, which is exactly the "unified chart rebuild" need: + - Give each mode a chart-construction hook in the mapping runtime, for example `registerChartTypeDelegate(contextId, fn)`, which evolution already half-has (`delegatedEntityApply`). + - In historical mode, a chart switch should call `renderComparison(state.result, payloads.left, payloads.right)` with the new chart id. That rebuilds both clones from the comparison payloads: inline trees for boats, `codexrComparisonData*` sources (and slices) for flat charts. + - At minimum, make `getChartFromSource` keep comparison sources and rebuild inline boats data. +- Test: a Playwright scenario, which could be added to `run-xr-mode-cycle-harness.cjs`: Compare → select boats → assert that each clone's data differs and does not use `from: tree`. Then select cyls and assert `from` matches `/Comparison/`. + +### HIST-4: A comparison that changes while the mode is parked is applied only to the live side; updates can also be lost +- Severity: major. Type: bug. +- Evidence: + - liveRefreshAndRegistration.js:183-198 and compareFlowAndMessages.js:268-275. While the mode is not active, `applySharedState` only does `state.result = snapshot.result`. On re-entry, `activate` restores the old geometry and calls `applySharedState(state.result)`. + - Inside it, `previousResult = state.result`, which is already the new result. So `canRefreshLiveSide(result, previousResult)` (liveRefreshAndRegistration.js:8-21) compares the new result with itself: `sameSources` is always true, and only the live side is refreshed. + - Second path: compareFlowAndMessages.js:277-293. If the user leaves while the datasets are being fetched, the generation check returns before `state.result` is assigned. The newer result is dropped, and no later message re-sends the entity. +- Failure scenarios: + - (a) Collaboration: B is in the normal view while A runs a new comparison, working copy vs commit-2 instead of commit-1. B opens History. + - The right chart still reads commit-1's dataset and its nameplate still says "HEAD~1". + - The companion table uses commit-1's payload. + - `getState().result.right` says commit-2. + - (b) Any client: an update arrives during the enter animation and the user leaves within the fetch. On re-entry the client shows revision 1 forever, while the server holds revision 3. +- Confidence: CONFIRMED in the real browser harness (`scen.cjs stale` and `scen.cjs race`). + - stale: `re-entered {"rightSrcUrl":"/test/manual/xr-mode-history-right.json?revision=1","resultRight":"commit-2","nameplates":[...,"HEAD~1 - No commit date"]}`. + - race: on re-entry, `resultRight:"commit-1"` with `revision=1`. +- Proposed fix (liveRefreshAndRegistration.js and compareFlowAndMessages.js): + - Track `refs.renderedResult`, the result whose geometry is mounted, separately from `state.result`. Decide `canRefreshLiveSide(result, refs.renderedResult)`, comparing the source ids of both sides. + - In `applySharedState`, record `state.pendingResult = snapshot.result` before awaiting. On a generation abort, keep it as `state.result`, so the re-entry path re-syncs it. +- Test: add both scenarios to the mode-cycle Playwright runner. The harness already has `CodeXRHarness.apply`. + +### HIST-5: Shallow directory comparisons materialize the whole subtree, which fails on large repositories and is slow +- Severity: major. Type: bug. +- Evidence: + - gitRepositoryService.ts:286-300 always runs `ls-tree -r` and copies every analyzable file recursively. + - The eligibility index honours `recursive` (gitTimelineBlobIndex.ts:229, `if (this.recursive && ...)`), so the picker shows the revision as usable. + - `planDirectorySnapshot` (341-347) then throws `comparison-snapshot-file-limit` or `-size-limit` on files that the shallow Python run would never read. + - `copyPlannedFiles` (359-375) spawns one `git show` per file, one at a time. `GitBatchObjectReader` exists but is not used here. + - The error is not a `GitAnalysisSourceError`, so the client shows the generic "Historical comparison failed. Please try again." (compareFlowAndMessages.js:264). A retry fails the same way. +- Failure scenario: shallowly analyze the root of a large repository (one top-level `.py` file and more than 5,000 nested files), pick a commit, and press Compare. It fails every time. + - With 1,500 nested files it works but spends 8.5 s copying files that are never analyzed. On Windows, process spawns cost about 10 times more. +- Confidence: CONFIRMED with `scratch/historical/svc1.cjs` and `svc2.cjs` on real repos: + - "index shallow eligible files 1" then "materialize ERR comparison-snapshot-file-limit"; + - "1500 nested files materialized for a shallow target in 8501 ms". +- Proposed fix: + - Pass `isDeep` into `GitRepositoryService.materialize`. For shallow runs, list only the top level (`ls-tree` without `-r`, filtering out tree entries). + - Better: materialize from the `GitTimelineBlobIndex` plan the catalogue already built, through `GitBatchObjectReader`, so the eligibility rules and the materialization rules are the same code. + - Map the limit errors to an exclusion, or at least to a specific message. +- Test: in gitMaterializeDirectory.test.cjs, add a case that asserts the shallow materialization writes top-level files only, plus a real-repo test with more than 5,000 nested files that compares successfully. + +### HIST-6: On Windows, a working copy on a drive other than the extension host's cwd drive collapses to basenames +- Severity: major. Type: bug. +- Evidence: + - Python strips drive letters from `filePath` (backend/src/utils/babia_path_utils.py:52-55). + - `decorateDirectoryEntries` passes that drive-less path to `toPortableRelativePath(analyzedTargetPath, ...)` (src/core/history/gitAnalysisShared.ts:304-310), which calls `path.resolve(candidate)`. On win32 that resolves against the cwd drive, usually C: (the VS Code install). + - For a target `D:\work\proj\src` the relative path crosses drives, so `path.relative` returns an absolute path, and the code falls back to `path.basename(candidate)`. +- Failure scenario: the repo is at `D:\projects\app`. Compare `src` (working copy) against a tag. + - The working-copy side keys files as `file:a.ts`, so `core/a.ts` and `ui/a.ts` collide. + - The commit side (snapshot under C: storage) keys them as `file:core/a.ts`. + - Every file counts as removed plus added, duplicate basenames are lost, and the working-copy boats tree is flat. + - Project evolution's working-copy frame and the Git export use the same helper. +- Confidence: LIKELY, reproduced by simulation. `scratch/historical/winpath.cjs` loads the compiled module with `path` set to `path.win32` and cwd set to `C:\...`, and gets `D:` keys `file:a.ts | file:a.ts` against commit keys `file:core/a.ts | file:ui/a.ts`. It needs confirming on a real Windows machine. +- Proposed fix (gitAnalysisShared.ts): normalize both sides to POSIX and drive-less before comparing, using the same rule as `normalize_path_for_babia`. Alternatively, have Python emit a `relativePath` per entry and prefer it. +- Test: a unit test that runs the module under a `path.win32` shim (the winpath.cjs pattern), with D: and C: targets. + +### HIST-7: No timeout and no cancel. A stuck git or Python run keeps the mode busy for the whole session +- Severity: major. Type: robustness. +- Evidence: + - `ExecutePython.spawnAndCollect` (src/core/analysis/python/executePython.ts:438-497) has no timeout and no kill, and `executeAnalysis` uses `withProgress({ cancellable: false })` (161-167). `analyzeSource` does not pass `silent`, so each side shows a non-cancellable notification. + - `runGit` and `runGitBuffer` (gitRepositoryService.ts:528-572) have no timeout either. + - `SingleJobGate` stays busy until the promise settles (gitAnalysisSessionContext.ts:255-268). + - There is no `historical-comparison-cancel` message. The router handles only references and start (analysisMessageRouter.ts:89-92), while evolution has `cancellationRevision`. + - Leaving the mode does not abort the job. +- Failure scenario: a revision with a pathological file makes lizard run for minutes, or `git status` stalls on a huge working tree or network drive (OneDrive, an SMB share). + - XR shows "Analyzing ..." with no way out. + - Every later Compare gets "Another comparison is already being generated." (409 in LivePanel). + - The live refresh polls `isBusy` every 350 ms indefinitely (analysisFeatureHost.ts:284-287). +- Confidence: LIKELY (traced in code, not reproduced). +- Proposed fix: + - Add an `AbortSignal` through `compare` → `analyzeSource` → `ExecutePython` (`child.kill()`) and through git (`execFile` `timeout` and `signal`). + - Add a `historical-comparison-cancel` room message and a LivePanel cancel button. Cancel on mode leave when no result exists yet. + - Add a per-side timeout, for example 5 minutes, reported as a specific error. +- Test: a unit test with a stubbed `ExecutePython` that never resolves. Assert that cancel releases the gate and that the next compare is accepted. + +### HIST-8: Temporary snapshots and comparison artifacts accumulate on disk +- Severity: minor. Type: robustness. +- Evidence: + - Snapshots are deleted only on `dispose()` (gitRepositoryService.ts:220-222), although the payload is cached in memory right after Python returns. Each compared commit keeps up to 100 MiB under storageUri for the whole session. + - Nothing sweeps `historical-comparisons/*` at activation, so a crashed or killed VS Code leaks them permanently. The empty `` parent folder is never removed either. + - Every compare, including every live refresh on save, writes three new full-payload JSON files to `staticRoot/comparison/revision-N*.json` (historicalComparisonService.ts:143-173) and never deletes older revisions. + - On Windows, the `fs.rm` at line 211 has no `maxRetries`. A Defender or indexer lock (EBUSY or EPERM) makes the compare fail. +- Failure scenario: a long session with a live comparison and frequent saves on a large deep analysis grows `comparison/` by MBs per save. Repeated crashes fill the extension storage. +- Confidence: LIKELY. +- Proposed fix: + - Remove the snapshot directory in a `finally` once Python finishes. + - Sweep `historical-comparisons/` and `project-evolution/` for session ids that are no longer live at startup. + - Keep only the current and previous `revision-*` files. + - Use `fs.rm(..., { maxRetries: 5, retryDelay: 100 })`. +- Test: a unit test that asserts the snapshot directory is gone after `analyzeSource` resolves (real repo, stubbed `ExecutePython`). + +### HIST-9: Concurrent starts and the refresh flag set before success +- Severity: minor. Type: bug. +- Evidence: + - historicalComparisonBridge.ts:139-176 checks `isBusy()`, then awaits `reconcileSession` and `refreshMode` before calling `compare()`. Two starts in that window, from two collaborators or a double tap, both pass. The loser throws `comparison-busy`, which is broadcast to every client (199-206), including the user whose job is still running. + - `setRefreshEnabled(...)` (153-157) runs for the new request before it succeeds, so a failed request leaves the refresh flag describing it while `activeRequest` still holds the previous one. +- Confidence: LIKELY. +- Proposed fix: reserve the gate synchronously, for example with `jobs.tryReserve()`. Send the busy error only to the requester (`messageContext.send`). Set the refresh flag after success. + +### HIST-10: Misleading and stale status text +- Severity: minor. Type: ux. +- Evidence: + - `applySharedState` sets "Loading comparison datasets..." (compareFlowAndMessages.js:278) and never clears it on success. In the harness the panel status still said it after a successful render and after re-entry. + - `handleError` (255-265) maps any message containing `git-command-failed` to "History compare requires an analysis inside a local Git repository.", even for a deleted branch (`rev-parse --verify` failure). Every other code, such as the snapshot limits, `unknown-comparison-source` or a Python failure, becomes "Please try again." +- Confidence: CONFIRMED for the stale status (harness output `"status":"Loading comparison datasets..."` after render). LIKELY for the messages. +- Proposed fix: clear the status after the render. Have the server send typed codes (`reference-gone`, `snapshot-limit`, `analysis-timeout`) and give each a specific message. + +### HIST-11: Picker scalability and permanent exclusions after transient failures +- Severity: minor. Type: ux. +- Evidence: + - Only `log --all --max-count=50` commits are offered (gitRepositoryService.ts:69-75). Older history can be reached only through tags or branches. There is no search, and paging is prev/next only. + - The first `getReferences` indexes every branch and tag (gitAnalysisEligibility.ts:161-172). Measured: 451 sources over 300 files took 2.5 s on first open (`scratch/historical/tags.cjs`), with no progress shown beyond "Loading local Git references...". This grows linearly with tags times files. + - `isDeterministicNoDataError` (gitAnalysisEligibility.ts:75-78) also matches "Unable to parse result" or "JSON markers not found", which a crashed, killed or broken-venv Python produces as well. The commit is then removed from both pickers for the rest of the session (`recordDeterministicExclusion`). +- Confidence: CONFIRMED for the timing. LIKELY for the transient exclusion. +- Proposed fix: + - Add a "Load more" or by-SHA entry backed by HIST-2's registry, and a progress message during indexing. + - Classify exclusions only from validated payloads (empty or non-array), not from process failures. + +### HIST-12: The comparison clone copies every attribute of the scene chart, and the harness hides real breakage +- Severity: minor. Type: architecture and test-gap. +- Evidence: + - `createChartFromTemplate` (comparisonCharts.js:131-151) copies all attributes except a blacklist. + - In `test/manual/xr-mode-cycle-harness.html` the normal chart has no `codexrNormalAnalysisRoot` wrapper, unlike the real template (templates/xr/file/xr-visualization.html:88-101). The surface runtime therefore stamps `data-codexr-normal-root`, `data-codexr-analysis-root` and `data-codexr-analysis-mode="single"` on the chart itself, and the clones inherit those markers. + - On re-entry, `mountNormalRoots` and `detachNormalRoots` then treated the clones as normal roots and left both comparison charts `visible=false`. This was traced with a setAttribute spy. + - With the real wrapper (`h2.html`) re-entry is fine. The harness is therefore not representative, and the copy rule is fragile: any marker added to the chart entity in the future leaks into the clones. + - The mode-cycle runner never runs a comparison, never re-enters with one, never switches charts in compare mode and never pushes an update while parked. That is why HIST-3 and HIST-4 are uncaught. +- Proposed fix: + - Build clones from the canonical chart builder (`buildDeclarativeChartEntity` and the chart base config) plus an explicit whitelist, instead of copying attributes. + - Wrap the harness chart like the real template. + - Extend `run-xr-mode-cycle-harness.cjs` with compare, leave and re-enter, compare with a chart switch, and an update while parked. + +### HIST-13: LivePanel waits on SSE alone, and its live-refresh errors are invisible +- Severity: minor. Type: robustness. +- Evidence: + - templates/components/livepanel/historicalPanel.js:122-165. After the 202, completion arrives only through the SSE messages `historical-progress` and `historical-updated`. If the SSE connection drops during a long analysis, or the event is missed on reconnect, the button stays "Comparing..." with no poll or timeout. + - The host's live refresh (analysisFeatureHost.ts:289-303) never calls `notifyLivePanelHistoricalProgress` on failure, so LivePanel live updates stop silently while HIST-1 loops. +- Confidence: LIKELY. +- Proposed fix: add `GET /api/historical/status` (busy, last revision, last error) and poll it after an SSE reconnect. Route refresh errors to SSE. + +### Documentation +- docs/features/HISTORICAL_COMPARISON_XR.md is in English now, not Spanish. +- It claims "Each side keeps the chart type chosen for the original analysis" and that "every client renders the same ... revision". HIST-3 and HIST-4 contradict both. +- The "5,000 files" limit is counted recursively even for shallow analyses (HIST-5). +- It does not mention the 50-commit horizon breaking live comparisons (HIST-2). + +### Checked and not bugs +- Non-Git folders: availability is disabled with a reason. +- Empty repository with no commits: the picker offers only the working copy. +- Detached HEAD: labelled "Detached HEAD (live)". +- Target missing in a revision: excluded from the picker. +- The two zones do not overlap: the centre gap is 0.18, and the zones come from one function used by both the profiles and the fallback. +- Leaving to single restores the normal chart and the mapping with the real wrapper. +- Metric (axis) changes on boats clones keep the inline data (`buildChartComponentUpdate` merges). +- No item in REPORT.md section 9 belongs to this area. + +## 3. Architecture recommendations + +1. **One chart-construction service.** The mapping runtime should own "build or rebuild chart X for context C from dataset D in zone Z", with each mode registering how to supply D. Historical (two zones, inline boats trees), evolution (one frame) and single (data or tree) would then all go through it. That fixes HIST-3 by construction and removes `createChartFromTemplate`'s attribute copying (HIST-12). +2. **Separate the rendered state from the received state in each mode runtime.** Use `rendered` (the geometry mounted) and `latest` (from the server), and reconcile them on activate. Do not overload `state.result` (HIST-4). This belongs in the unified launcher's mode lifecycle contract: `activate` → `reconcile(latest, rendered)`. +3. **The launcher contract should require cancellation and status.** Each analysis type exposes `start(request, signal)`, `cancel()`, `status()` and `onLeave` policy. The host runs a shared job gate with timeout, abort and typed errors. Historical currently has none of these (HIST-7, HIST-9, HIST-13). Evolution has a home-grown revision counter; unify the two. +4. **Live-refresh policy is shared infrastructure.** Use bounded retry with backoff, surface the error, auto-detach when a source is gone, and stay mode-aware (HIST-1). Put it in `analysisRefreshCoordinator`, not in each feature host. +5. **Git sources are content-addressed.** Resolve by SHA through one registry and materialize from the blob index plan with the batch reader, so eligibility, materialization and export share one file-selection rule (HIST-2, HIST-5). Do path identity in one drive-agnostic normalizer shared with Python's rule (HIST-6). diff --git a/docs/xr-audit/launcher.md b/docs/xr-audit/launcher.md new file mode 100644 index 00000000..6b135c27 --- /dev/null +++ b/docs/xr-audit/launcher.md @@ -0,0 +1,324 @@ +# Launcher / servers / session lifecycle audit (area: `launcher`) + +Repo: `/home/user/Code-XR` @ d89e08d4. Paths below are relative to `apps/vscode-extension/` unless they start with `backend/`. +Confirmation scripts (all runnable with `export PATH=/opt/node24/bin:$PATH; node --test `, they use `test/helpers/fakeVscode.cjs` and compiled `out/`): +`/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/launcher/t1…t9*`. + +## 1. How the area works (summary) + +1. **Entry points.** Some 20 commands and tree clicks call `AnalysisOrchestrator.orchestrateAnalysis(path, mode, targetType, ctx, isDeep)` (`src/core/analysis/analysisOrchestrator.ts`). They live in `features/analysis/commands/{file,directory,dom}/*`, `sections/files-by-language`, `sections/project-by-language`, and `projectAnalysisCommands`. Each call site picks the mode (XR / LivePanel / VisualizeDOM) with its own `switch`. +2. **Session creation.** `UnifiedSessionRegistry.createSession` (`core/analysis/session/sessionRegistry.ts`) rejects a duplicate: same path, mode, type and depth, with a status other than closed or error. It then builds `storage/{fileAnalysis|directoryAnalysis}/___`. +3. **Launch.** The orchestrator dispatches on mode × targetType to `LauncherXRAnalysis` / `LauncherLivePanel` / `LauncherVisualizeDOM`. All three feed `executeLaunchPipeline` (`launchers/launchPipeline.ts`), which runs: preValidation → `FileRequirementProcessor` (Python via `ExecutePython`, then the template parsers: `fileXRParser`, `directoryXRParser`, `livePanelParser`, `visualizeDOMParser`) → `SaveFiles` → **watcher** (`SessionWatcherManager`, File/DirectoryWatcherOrchestrator) → **server**. DOM runs server first, then watcher. +4. **Server.** `new SessionServerManager` (one per launch) → `ServerLaunchOrchestrator` → `MultiServerLauncher.launchServer`. That probes the port, then `serverFactory.launchServerByType` → `HttpServer` / `HttpsDefaultServer` / `HttpsCustomServer`, listening on `0.0.0.0`. It then registers in `ActiveServerRegistry` and auto-opens the page. Afterwards `fileToServerMap.registerMapping(targetPath → port)` keys SSE delivery. +5. **Per-server analysis features.** The `HttpServer` constructor builds an `AnalysisFeatureHost`. Driven by `analysisServerCapabilities.ts`, it attaches `DependencyGraphService`, `HistoricalComparisonService`, `ProjectEvolutionService` and `GitAnalysisSourceCatalog`, wires them into `analysisRefreshCoordinator`, and exposes them through: + - REST: `/api/dependency-graph/summary`, `/api/historical/references`, `/api/historical/compare`; + - the collaboration WebSocket `/codexr-room` (`AnalysisMessageRouter`), which is what the in-scene switcher uses; + - SSE `/events`, for classic data refresh and LivePanel pushes. +6. **Refresh.** Watchers call `analysisRefreshCoordinator.publishChanges`. The coordinator runs the handler of the active mode (and of the background modes) and publishes the `analysis-view` entity to the room. The re-analyzers send SSE `dataRefresh` (XR) or `analysis-updated` (others) to every client registered under **`targetPath`**. +7. **Stop.** + - `ServerControl.stopServer` closes the panel, clears the SSE clients and the file map entry found by port, marks the session closed, `stop()`s with a 4 s timeout falling back to `forceStop()`, and unregisters. + - `ServerWatcherIntegration` listens for `serverRemoved` and stops the session watcher of every session whose `port` matches. + - Active Analyses "Close Analysis" runs `triggerManualCleanup`, then `removeSession`. + +## 2. Findings + +### LAUNCHER-1: HTTPS servers listen on a different port from the one registered (LAN/headset URL, tree, session and toast show the wrong port) +- Severity: major - Type: bug +- Evidence: + - `src/core/server/multiServerLauncher.ts:116` `const finalPort = await this.findAvailablePortWithLogging(requestedPort);`. When the default port is busy, this goes through `PortManager.findAvailablePort` → `get-port`, which **locks the returned port for 15–30 s** (`node_modules/get-port/index.js`, `lockedPorts.young`). + - `src/core/server/httpsDefaultServer.ts:32` and `httpsCustomServer.ts:42` `await this.resolveListeningPort();` → `httpsServerBase.ts:161-167` calls `findAvailablePort(this.config.port, …)` again. get-port skips its own locked port, so `this.config.port = availablePort` (+1). + - `multiServerLauncher.ts:167,210` still register and return `port: finalPort`. That value goes into `ActiveServer.port`, `session.port`/`assignedPort`, `fileToServerMap` and the success toast. + - The URL is right (it comes from `server.start()`), but `activeServerItems.ts:172`, `handleServerActions.ts:141` and `serverDetailsFormat.ts:24` build the **LAN URL from `server.port`**. +- Failure scenario: HTTPS mode, which is the headset mode. Launch any second analysis while one server holds 3000. The tree says "localhost:3001" and "Local network address https://192.168.x.x:3001", and the toast says "Server running on port 3001", but the listener is on 3002. The headset typed or copied URL gets connection refused, or another Code-XR server. Once the get-port lock expires, a later launch can be registered on the same port as an earlier one. `findFileByPort` and `ServerWatcherIntegration.handleServerRemoved` (filter `session.port === server.port`) then pick the wrong file, or tear down two sessions (the duplicate-port part is LIKELY, not reproduced). +- Confidence: CONFIRMED. Running `t2_https_port_mismatch.test.cjs` (real `MultiServerLauncher` + real `HttpsDefaultServer`, default port occupied) printed `result.port=7440 url=https://localhost:7441 actual listen port=7441 listening@result.port=false`. +- Proposed fix: resolve the port once. Delete `resolveListeningPort()` from the HTTPS servers, or have it return the bound port. After `start()`, read the real port from `server.address().port` and use it everywhere: launcher result, registry, file map. Also make the inner `HttpServer` config port follow it; it is copied in the `HttpsServerBase` constructor. Test: a variant of t2 inside `test/servers/multiServerLauncher.test.cjs` with the real HTTPS class, asserting `result.port === instance.server.address().port`. + +### LAUNCHER-2: `forceStop()` never closes the listener (HTTP and HTTPS), and the later `stop()` is a no-op +- Severity: major - Type: bug (REPORT §9 deferred item, and it is worse than recorded: it is not HTTPS-only) +- Evidence: `src/core/server/httpServer.ts:230-234` and `httpsServerBase.ts:107-111` only do `closeAllConnections(); isRunning = false;`, with no `server.close()`. `stop()` starts with `if (!this.server || !this.isRunning) return;` (`httpServer.ts:198-201`), so after a force stop nothing can ever close the socket. `serverControl.ts:113` unregisters the entry anyway. +- Failure scenario: a graceful stop rejects or exceeds 4 s, for example a lingering upgraded WebSocket or tunnel socket (`closeAllConnections` does not track upgraded sockets), or a `close()` error. ServerControl warns "Server removed from the list, but its runtime did not shut down cleanly". The port stays bound on `0.0.0.0` with live request handlers and static files, but no tree entry. It is invisible and cannot be stopped until VS Code restarts. This is one way the tree and the OS port list drift apart. +- Confidence: CONFIRMED. Running `t1_server_stop_and_events.test.cjs` printed `connect after forceStop: true after stop(): true getIsRunning: false`. +- Proposed fix: in both `forceStop()`, call `this.server?.close()` (ignore `ERR_SERVER_NOT_RUNNING`), destroy upgraded sockets the server tracks itself (keep a `Set` from `'connection'` and `'upgrade'`), then null `this.server`. Make `stop()` key on `this.server` and not on `isRunning`. Test: t1 case 1, inverted, added to `test/servers/`. + +### LAUNCHER-3: one target served twice (two modes, or XR plus XR-deep) breaks live reload and cross-wires SSE +- Severity: major - Type: bug (REPORT §9 "same target in two modes") +- Evidence: + - `src/core/analysis/session-servers/serverLaunchOrchestrator.ts:83` `fileToServerMap.registerMapping(request.targetPath, …)`; + - `core/server/fileToServerMap.ts:50` `this.fileToServer.set(fileUri, serverInfo)`, which overwrites; + - `httpServer.ts:526-535`, where `/events` does `findFileByPort(this.config.port)` → 404; + - `SSEManager`/`sseClientRegistry` key clients by `targetPath`. `directoryReAnalyzer.ts:268-273` and `reAnalysisManager.ts:55-57` send to `session.targetPath`. +- Failure scenario: XR and LivePanel of `src/` at once, or XR then XR-deep of the same folder (allowed, since `isDeep` differs): + 1. The first page loses live reload. Its `/events` returns 404, and the EventSource gives up or retries forever. + 2. Clients connected before the second launch are now cross-wired. A LivePanel re-analysis sends `analysis-updated` to the XR page, and the XR watcher sends `dataRefresh` to the LivePanel page. Each reloads its own `data.json`, so it double-reloads or reloads stale data. + 3. Stopping the second server runs `removeAllClients(targetPath)` and `unregisterMapping(targetPath)`, which kills the first server's SSE as well. +- Confidence: CONFIRMED for the 404 (`t1` case 2: `A /events before B: 200 A after B: 404 B: 200`). The cross-wiring is LIKELY, traced through the code. +- Proposed fix: key SSE and the server map by **sessionId**, not by target path. `/events` resolves `this.config.analysisSessionId`, which the server already has, and `SSEManager.sendDataRefresh(sessionId)`. Keep a `targetPath → Set` index for watchers. Test: register two sessions on one target, assert both `/events` return 200 and that a refresh of session A reaches only A's clients. + +### LAUNCHER-4: double-click or quick re-trigger bypasses the duplicate-session guard +- Severity: major - Type: bug (race) +- Evidence: `src/core/analysis/session/sessionRegistry.ts:90` runs the duplicate check, then `:99` `await this.hashTargetFile(...)` (file) or `:119` `await this.assertDirectoryTarget(...)` (directory). Only then does `:128` `this.sessions.set(id, session)` happen. Neither the orchestrator nor the commands hold any in-flight lock. +- Failure scenario: double-click "Analyze File (XR)", or run it from the editor menu and the tree in quick succession. Two sessions, two Python runs, two watchers and two servers result for the same target. Both pages then hit LAUNCHER-3, and two browser tabs or panels open. +- Confidence: CONFIRMED. `t3_session_race_and_pipeline.test.cjs` printed `kinds: created created sessions: 2`, and the same for directories. +- Proposed fix: reserve synchronously. Insert the session (status `creating`) before the first `await`, or keep a `Map` of in-flight creations keyed by a normalised key (see LAUNCHER-17). Test: the t3 case 1, asserting the second call returns `duplicate`. + +### LAUNCHER-5: a launch that fails at the server step leaks its watcher and says nothing to the user +- Severity: major - Type: bug +- Evidence: in `src/core/analysis/launchers/launchPipeline.ts:136` the watcher starts before the server (XR and LivePanel). On failure, `:239` `registry.updateSessionStatus(session.id, 'error', undefined, 'Server could not be started')` runs with **no throw and no toast**. `SessionServerManager.startServerForSession` swallows every error into `{isServerActive:false}`. The `catch` at `:147` does not stop the watcher either. The `error` session is never removed, and the duplicate check ignores `error`, so each retry adds another session and watcher. +- Failure scenario: an XR or LivePanel launch whose server cannot start. Causes include HTTPS-custom with a missing certificate, `defaultPort` 8080 busy (LAUNCHER-12), or `EADDRINUSE`. The user sees nothing, or only "Port … busy". The file or directory watcher keeps re-running the Python analysis on every save, for a page that does not exist. With directory sessions, that is a full re-scan. +- Confidence: CONFIRMED. `t3` case 2 printed `status: error watcherId: watcher-1 watcherStarted: 1 messages: []`. +- Proposed fix: give the pipeline a `try/finally` teardown list (watcher stop, server stop, map unregister) that runs on any failure, and always surface the error. Better, start the server before the watcher, as DOM already does. Test: the t3 case 2, asserting `stopWatchingSession` was called and an error toast was shown. + +### LAUNCHER-6: a server whose `start()` fails still wires its analysis services to the session +- Severity: minor - Type: bug / leak +- Evidence: `src/core/server/serverFactory.ts:200` `serverUrl = await server.start();`. The catch returns `{success:false}` and never disposes the instance. Meanwhile the `HttpServer` constructor already built `AnalysisFeatureHost` (`analysis/analysisFeatureHost.ts:59-155`), which: + - registers the `dependency-graph` refresh handler and an `onStateChanged` listener; + - subscribes to `analysisUpdateEvents`; + - for LivePanel, calls `setBackgroundRefresh` + `forceRefreshMode('dependency-graph')`, which starts a Python dependency scan. + + `start()` also runs `attachToNodeServer`, which creates the room and broadcast WebSocket servers. +- Failure scenario: a port race or certificate failure. The session keeps a ghost dependency handler and listeners. A LivePanel launch that failed still burns a full dependency analysis in the background. +- Confidence: CONFIRMED. `t6_failed_start_leak.test.cjs` printed `launch success: false … coordinator handlers left: [ 'dependency-graph' ] listeners: 1`. +- Proposed fix: in `launchServerByType`'s catch, call `server.disposeRuntimeFeatures()` (or `forceStop()`). Better, build the feature host lazily on `'listening'`. Test: t6, asserting no handler is left behind. + +### LAUNCHER-7: "Close Analysis" during analysis leaves an orphan server and watcher, then reports success +- Severity: major - Type: bug (race / teardown) +- Evidence: + - `features/analysis/sections/active-analyses/activeAnalysesCommands.ts:200` offers Close for any non-closed status, including `analyzing`. + - `:270-271` runs `triggerManualCleanup`, then `removeSession`. + - `executeLaunchPipeline` holds the session object and never re-checks the registry. After Python returns it saves, starts the watcher, starts the server, and `onSuccess` toasts. `registerSessionPort` only warns "not found". +- Failure scenario: start a long directory XR analysis, then close it from Active Analyses. A minute later a server opens anyway, with a watcher re-analysing on save. The server's feature host finds no session, so the in-scene switcher reports every analysis unavailable. It is listed in Active Servers but not in Active Analyses. +- Confidence: CONFIRMED. `t4_close_while_analyzing.test.cjs` printed `after removal: watchers started 1 servers started 1 session in registry false toasts [… "Server running on port 3005"]`. +- Proposed fix: give each launch an `AbortController` stored on the session, or in the unified registry (§4). Close or remove aborts it, the pipeline checks `signal.aborted` between steps, and Python is killed through the signal (LAUNCHER-10). Test: the t4 case 1, asserting zero watcher and server starts. + +### LAUNCHER-8: closing an analysis that has no port can stop an unrelated server +- Severity: major - Type: bug +- Evidence: `src/features/analysis/services/serverWatcherIntegration.ts:153-161`. `findAndStopServerForSession` falls back to `servers.find(server => server.customName?.includes('Analysis'))` and stops the first match. Server names are `XR File: `, `XR Directory: `, `LivePanel …`, or user-chosen names for Visualize Data. +- Failure scenario: an analysis still `analyzing`, or one in `error` (no port), is closed. Any running server whose target or visualization name contains "Analysis" is stopped, for example `AnalysisService.ts` or a data visualization called "Sales Analysis". Its session is marked closed and its watcher stopped, through `serverRemoved`. +- Confidence: CONFIRMED. `t4` case 2 printed `stopped: [ 'server-3001-1' ]` for a server named `XR File: AnalysisService.ts` that belonged to another session. +- Proposed fix: delete that fallback and the `htmlFile.includes(outputPath)` heuristic. Stop only by `metadata.sessionId` (always set by `ServerLaunchOrchestrator`). `ServerControl.closeAssociatedAnalysisSession` (`serverControl.ts:249-266`, substring matching both ways) gets the same fix. Test: the t4 case 2, asserting nothing is stopped. + +### LAUNCHER-9: "Stop all" prompt, return value and toasts disagree +- Severity: minor - Type: bug / ux (REPORT §9 "stopAllServers count-as-success" and "Stop all 20 server(s)?") +- Evidence: + - `src/features/active-servers/views/handleServerActions.ts:425,433` prompts with `getAllServers().length` (every status). + - `ServerControl.stopAllServers` (`core/server/serverControl.ts:160-205`) stops only `status==='running'` and returns a **count**. + - `handleServerActions.ts:442-446` reads it as a boolean (`if (success)`), then toasts `Stopped all ${allServers.length} servers`. + - Each `stopServer` adds its own "Server stopped" toast, and ServerControl adds a summary toast of its own. +- Failure scenario: + - One of three fails. The user sees "Stopped 2/3 servers. Some servers may require manual intervention." and then "Stopped all 3 servers". + - A non-running entry inflates the prompt: "Stop all 2 server(s)?" … "All 1 servers stopped successfully" … "Stopped all 2 servers". + - About the 20-vs-13 report: I could not reproduce those exact numbers. Plausible contributors: LAUNCHER-1 (in HTTPS mode the registry ports are not the bound ports, so a comparison against `lsof` or `netstat` cannot match), LAUNCHER-2 (unregistered but still bound), LAUNCHER-4 and LAUNCHER-7 (extra or orphan servers), and the prompt counting all entries. The maintainer should say whether HTTP or HTTPS was in use. +- Confidence: CONFIRMED. `t5_stop_all.test.cjs` reproduced both transcripts. +- Proposed fix: return `{requested, stopped, failed[]}` from `ServerControl.stopAllServers`, with no toasts inside it. The handler prompts with the running count and shows exactly one summary. Pass `{silent:true}` to `stopServer` in bulk. Test: extend `test/servers/serverActionHandlers.test.cjs` goldens. + +### LAUNCHER-10: no timeout or cancellation anywhere on the launch path, and a hung launch blocks every relaunch +- Severity: major - Type: robustness (hang) +- Evidence: + - `src/core/analysis/python/executePython.ts:438-497` `spawnAndCollect` has no timeout, no kill and no `AbortSignal`. stdin stays an open pipe. + - `projectAnalysisCommands.ts` wraps the launch in a `withProgress` with `cancellable: false`. + - `sessionRegistry.ts:57-67` treats `creating`/`analyzing` as duplicates: "Analysis … is already in progress". + - The pipeline awaits `handleAutoOpening` (`multiServerLauncher.ts:197`), which for an HTTPS server in panel mode awaits a non-modal `showWarningMessage` (`serverOpenActions.ts:47`). +- Failure scenario: a Python run that never returns (huge file, a stalled Windows pipe, antivirus blocking the venv). The progress notification spins forever and the session stays `analyzing`. Every new attempt on that target is refused as "already in progress", and the user's only way out is Close Analysis, which leaks (LAUNCHER-7). The scene never loads. +- Confidence: LIKELY (traced; a real hang was not reproduced). +- Proposed fix: thread an `AbortSignal` through `executeLaunchPipeline` → `ExecutePython` (`child.kill()` on abort), plus a configurable launch timeout (for example 10 min, with a "still running…" progress message). Make the progress cancellable. Do not await auto-open inside the launch; fire it after `monitoring`. Test: a unit test with a fake Python that sleeps, asserting rejection within the timeout and the session moving to `error`. + +### LAUNCHER-11: concurrent historical or project-evolution "start": check-then-act race, and the busy error goes to every peer +- Severity: minor (major in a shared room) - Type: bug (race) +- Evidence: + - `src/core/server/analysis/projectEvolutionBridge.ts:137` checks `isBusy()` synchronously, but the job only enters `SingleJobGate` after `await SessionWatcherManager.reconcileSession` (`:180-183`). + - `historicalComparisonBridge.ts:139` behaves the same, with `reconcile` and `refreshMode` before `compare`. + - The losing request's `project-evolution-busy` error is **broadcast** (`:214`). The scene's `handleError` (`templates/…/project-evolution/projectEvolutionRuntime/playbackControlsAndMessages.js:296-302`) stops playback, rejects the pending frame apply and shows "error" on every client while the first job is still running. +- Failure scenario: a double tap on Generate, or two collaborators. All clients flip to the error status mid-generation, and later the movie appears anyway. In historical compare, the second start also flips `setRefreshEnabled` for the first request. +- Confidence: CONFIRMED on the host side. `t8_evolution_double_start.test.cjs` printed `broadcasts: [ 'project-evolution-error:project-evolution-busy' ]` while the first job was running, then `upsert`. +- Proposed fix: take the gate synchronously, before the first `await`, by moving `reconcileSession` inside `jobs.run`. Send busy errors with `messageContext.send` to the requester only. Test: t8, asserting no broadcast error. + +### LAUNCHER-12: `defaultPort` = 8080 (allowed by the UI) fails every launch when 8080 is busy +- Severity: minor - Type: bug +- Evidence: `src/core/server/multiServerLauncher.ts:256` `PortManager.findAvailablePort(requestedPort + 1)` uses the default `endPort` 8080 (`portManager.ts:52-66`), which throws `Invalid end port 8080`. `handleConfigurationClicks.ts:110-118` allows 3000–8080. +- Failure scenario: the user sets the port to 8080, and Tomcat, Jenkins or another dev server holds it. Every analysis fails with "No available ports found starting from 8080". Combined with LAUNCHER-5, XR launches also fail silently and leak a watcher. +- Confidence: CONFIRMED. `t9_port8080.cjs` printed `THROWS: SERVER: Invalid end port 8080. Must be between 8081 and 65535`. The same message appeared in the t2 log. +- Proposed fix: `findAvailablePort(requestedPort + 1, Math.min(65535, requestedPort + 100))`. Test: a PortManager unit test. + +### LAUNCHER-13: the port probe only checks `0.0.0.0` (risk of co-binding with a localhost dev server on macOS and Windows) +- Severity: major if confirmed - Type: cross-platform bug +- Evidence: `src/core/server/portManager.ts:21-41` `isPortAvailable(port, '0.0.0.0')` is the first-choice path. The server then listens on `0.0.0.0` and the page is opened as `http://localhost:`. On macOS (BSD bind semantics with `SO_REUSEADDR`) and on Windows, a wildcard bind can succeed while another process owns `127.0.0.1:3000` or `[::1]:3000`. That is the default for Vite, Next and CRA on port 3000, the Code-XR default. `localhost` then resolves to the other app. +- Failure scenario: macOS, with a React or Next dev server on `localhost:3000`. Code-XR "launches on 3000" and the browser or panel shows the other app. The XR scene never appears, and `/events` and the API return that app's 404s. +- Confidence: SUSPECTED. Linux refuses the co-bind, so this cannot be reproduced here; the maintainer needs to check on macOS and Windows. +- Proposed fix: probe the way get-port does, across `undefined`/`::`, `0.0.0.0` and `127.0.0.1` (get-port already does this; use it for the first port too). Or bind with `exclusive:true` and port 0 retry, and use the bound port from `server.address()` (which also fixes LAUNCHER-1). + +### LAUNCHER-14: startup cleanup deletes a folder nothing writes, so the real analysis folders grow without bound +- Severity: minor - Type: bug +- Evidence: `src/features/analysis/commands/cleanAnalysisCommands.ts:63` cleans `storage/analysis`. Sessions write to `storage/fileAnalysis|directoryAnalysis/<…>` (`sessionRegistry.ts:155-156`, `utils/saveFiles.ts:50`) and `storage/visualizeDOMAnalysis/<…>` (`launcherVisualizeDOM.ts` `folderName`). `ServerLaunchOrchestrator.getTempDirForSession` (`:127-130`) still points at `storage/analysis/`, a dead fallback. +- Failure scenario: every analysis keeps its data, dependency datasets, comparison revisions and evolution frames in workspace storage forever, across reloads, because sessions are in-memory only. The REPORT §10 A.2 check ("stale folders in analysis/ are removed") is vacuously true. +- Confidence: CONFIRMED (traced: the only writers into storage are the two listed; `grep 'analysis'` finds no other writer). +- Proposed fix: point cleanup at the three real roots, skipping folders of sessions alive in this activation, and delete `getTempDirForSession`. Test: create stale folders under `fileAnalysis/` and `directoryAnalysis/`, run `executeStartupCleanup`, assert they are gone. + +### LAUNCHER-15: Windows: the DOM backend writes non-ASCII JSON to a cp1252 pipe and crashes; stdout decoding splits UTF-8 +- Severity: major (Windows only, VisualizeDOM) - Type: cross-platform bug +- Evidence: `backend/src/html/html_dom_parser.py:64` `print(json.dumps(result, ensure_ascii=False, indent=2))`. `src/core/analysis/python/executePython.ts:448-452` spawns with `env: process.env` and no `PYTHONIOENCODING`/`PYTHONUTF8`. On Windows a piped stdout uses the ANSI code page. `:470` `stdout += data.toString()` also decodes each chunk on its own, so a multi-byte character across a 64 KB boundary becomes U+FFFD. That affects every analysis with accented paths, for example a user folder named "Adrián". +- Failure scenario: Windows, "Visualize DOM" on any HTML containing `→`, emoji, CJK and so on gives `UnicodeEncodeError: 'charmap' codec can't encode character '\u2192'`, and the launch fails. Accented Latin characters come back mangled. +- Confidence: CONFIRMED by simulation: `PYTHONIOENCODING=cp1252 python3 backend/src/html/html_dom_parser.py ` printed the traceback and exited 1. The chunk split is LIKELY. +- Proposed fix: spawn with `env: {...process.env, PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1'}`, and use `child.stdout.setEncoding('utf8')` (StringDecoder-safe). Test: a unit test feeding a split multi-byte buffer, plus a Windows CI job for the DOM fixture. + +### LAUNCHER-16: a registrar failure still reports success, and the server leaks (re-check of the deferred item) +- Severity: minor - Type: robustness +- Evidence: `src/core/server/multiServerLauncher.ts:156-202`. A throw inside the `try` (`registerServer` **or `handleAutoOpening`**) is logged as "Failed to register" and the launch returns `success:true` with `activeServerId` undefined. The server is listening, but nothing can find it to stop it. +- User impact: low in practice, since `registerServer` does not throw today and auto-open catches its own errors. If it ever does, the result is an unstoppable server on `0.0.0.0`. It is pinned by the golden test "registration fails: the launch still succeeds". +- Confidence: LIKELY (code plus the existing golden). +- Proposed fix: if registration fails, `stop()` the instance and return `success:false`. Move auto-open out of the try. Update the golden. + +### LAUNCHER-17: session, SSE and server identity are raw path strings +- Severity: minor - Type: cross-platform robustness +- Evidence: `sessionRegistry.ts:62` `session.targetPath === params.targetPath`; `fileToServerMap` keys; `SSEManager` keys. Entry points produce paths differently: `uri.fsPath` (lower-case drive letter on Windows), `path.resolve(workspaceFolder.uri.fsPath, rel)` (`filesByLanguageCommands.ts:94-105`), and Python-supplied paths (project-by-language). +- Failure scenario: on Windows, or on case-insensitive macOS volumes, `C:\proj\a.ts` and `c:\proj\a.ts` are two targets. The duplicate guard is bypassed, which feeds LAUNCHER-3 and LAUNCHER-4. +- Confidence: SUSPECTED (depends on what each producer returns; not verified on Windows). +- Proposed fix: one `normalizeTargetKey(p)` = `path.resolve(p)` plus `toLowerCase()` on win32 (and on darwin when the volume is case-insensitive), used for every identity key. Keep the original string for display and spawning. + +### LAUNCHER-18: `SessionServerManager` is a per-launch throwaway, so its stop and notify paths are dead or wrong +- Severity: minor - Type: architecture / dead code +- Evidence: `launchPipeline.ts` does `new SessionServerManager(context)` per launch, so its `activeSessions` map dies with the launch. `ServerLaunchOrchestrator.stopServerForSession` (`:112-121`) only unregisters the file map and never stops the server. `directoryReAnalyzer.sendSSENotification`'s fallback `notifyAnalysisUpdated` therefore always no-ops. Its `isWatcherActive: true` is a constant ("Asumimos…"). +- Impact: none today, but anyone calling "stop server for session" through it believes it worked. Fold it into the unified launcher (§4). + +### Smaller observations (not separate findings) +- **Doubled toasts.** `projectByLanguageCommands.ts:179-186` toasts "Started … analysis" *after* the awaited launch, including when it was refused as a duplicate or failed. A DOM failure toasts twice: the pipeline's "Failed to start analysis", then a rethrow caught by the command. A session-creation error toasts in the orchestrator and again in the command wrapper. +- **Five copies of mode selection.** The "which mode for this file or directory" `switch` exists in 5 places (`filesByLanguageCommands`, `projectByLanguageCommands` ×2, the command classes), and the XR project command has no progress UI while the LivePanel project command does. +- **Path guard.** `staticAssets.ts:94` uses `startsWith(staticRoot)` without a separator, so a sibling folder sharing the prefix passes. It is low risk because folder names carry nonces; use `path.relative`. +- **Deactivate leaves servers running.** `extension.ts:109-141` deactivate does not stop running servers or watchers. Only `cleanupInactiveServers`, which does nothing to running ones, is called. Process exit hides this on a full shutdown, but not on a host restart while sockets linger in TIME_WAIT. + +## 3. Current launch paths (map) + +### 3a. Host-side launch, per entry + +| Entry | Mode / target | Launcher → pipeline config | Order | Data producer | Scene / page assets | Server features | +|---|---|---|---|---|---|---| +| `analyzeFileXR`, files-by-language (mode XR) | XR / file | `LauncherXRAnalysis.launchFileXRAnalysis` (chart plus mapping validation in `preValidation`) | watcher → server | Python file metrics → `fileXRParser` (writes `outputPath`, `copyToOutput`, `singleFileRuntimeAssets`) | `fileAnalysis.html`/`index.html` plus the single-file runtime list | XR caps: dep, hist, evol | +| `analyzeDirectoryXR[Deep]`, `analyzeProjectXR[Deep]`, project-by-language (XR) | XR / dir | `launchDirectoryXRAnalysis` | watcher → server | Python dir metrics → `directoryXRParser` (hard-coded list of 37 `*_OUTPUT_NAME` runtime assets) | `directoryAnalysis.html` plus about 20 runtimes | XR caps | +| `analyzeFileLivePanel`, files-by-language (LivePanel) | LP / file | `LauncherLivePanel.launchFile…` (hash preValidation, theme) | watcher → server | Python → `livePanelParser` | LivePanel bundle | dep + hist (LP pushes over SSE) | +| `analyzeDirectoryLivePanel[Deep]`, `analyzeProject[Deep]` (withProgress) | LP / dir | `launchDirectory…` | watcher → server | same | same | dep + hist, forced background dep refresh | +| DOM command, files-by-language (HTML) | DOM / file | `LauncherVisualizeDOM` (`rethrowErrors`, `setEndTime`) | **server → watcher** | `html_dom_parser.py` → `visualizeDOMParser` | babia-html page | none | +| Visualize Data, BabiaXR examples, "Launch server" | (no session) | `launchServerWithFile` / `MultiServerLauncher` directly | server only | none, or JSON in place | user or example HTML | none (static plus collaboration) | + +### 3b. The four in-scene XR analyses (same server, switched by the controller) + +| Analysis | Scene → host | Host service | Data delivered via | Refresh | +|---|---|---|---|---| +| classic (`single`) | WS `analysis-mode-activate {mode:'single'}` | none; the watcher re-analysis (`directoryReAnalyzer` / `reAnalysisManager`) | `./data.json`, SSE `/events` `dataRefresh` (keyed by targetPath) | watcher → coordinator `single` handler | +| dependency-graph | WS `analysis-mode-activate`, then `dependency-graph-start`, `-settings`, `dependency-file-scope-request`; LP uses REST `/api/dependency-graph/summary` | `DependencyGraphService` (through `DependencyGraphBridge`) | room entity `dependency-graph{datasetUrl}` → `/dependencies/dependency-graph-.json` written into staticRoot; LP gets SSE `dependency-updated` | coordinator `dependency-graph` handler (registered by `AnalysisFeatureHost`) | +| historical-compare | WS `historical-comparison-references-request`, `-start`; LP uses REST `/api/historical/references`, `/compare` | `HistoricalComparisonService` + `GitAnalysisSourceCatalog` | room entity `historical-comparison{result}` → `./comparison/revision-N.json`; progress broadcast | `analysisUpdateEvents` → `scheduleHistoricalComparisonRefresh` (350 ms debounce) | +| project-evolution | WS `project-evolution-references-request`, `-start`, `-apply-frame`, `-clear` (XR only) | `ProjectEvolutionService` | room entity `project-evolution{result/resultUrl}`; frames applied server-side (`applyFrameToBridge`) | refresh **disabled** at start (`setRefreshEnabled(false)`); a static movie | + +### 3c. Duplication and divergence +- **Two "launch" concepts.** Session-bound launches go through the pipeline. Session-less launches (Visualize Data, examples, the "launch server" command) call `MultiServerLauncher` directly, with their own naming and no teardown hook. +- **Five-plus places choose the mode.** Three ways name a project: `analyzeProject*` (LP) and `analyzeProjectXR*` (XR) via two different classes, plus project-by-language. +- **Step order differs per launcher.** It is watcher → server for XR and LP and server → watcher for DOM, so the failure semantics differ too. XR and LP set `error` silently (LAUNCHER-5); DOM throws and double-toasts. +- **Ports are resolved twice for HTTPS** (LAUNCHER-1), and identity is keyed three ways: sessionId (registry, coordinator), targetPath (file map, SSE, duplicate check) and port (`findFileByPort`, `handleServerRemoved`, `closeAssociatedAnalysisSession`). Most of the bugs above come from these keys disagreeing. +- **Teardown is spread over four places** that partly overlap: `ServerControl.stopServer`, `ServerWatcherIntegration` (an event on `serverRemoved`, matched by port), `activeAnalysesCommands.closeAnalysis` (manual cleanup, then remove), and `AnalysisFeatureHost.dispose` (wipes the coordinator state for the session, including the watcher's handlers). None of them aborts an in-flight launch. +- **Scene-asset lists are hand-maintained twice**: `directoryXRParser` imports 20 assets and `singleFileRuntimeAssets` keeps a second list. Server capabilities sit in a third table, `analysisServerCapabilities.ts`. Adding an analysis type touches about seven files: the parser lists, capabilities, `AnalysisFeatureHost`, `AnalysisMessageRouter`, a new bridge, `SNAPSHOT_PROBE_BY_MODE`, `analysisViewModes`/the coordinator `MODES`, and the runtime option registration. +- **The scene sends without acknowledgement.** The switcher's `client?.sendMessage?.('analysis-mode-activate', …)` (`templates/components/codexr/analysis-mode/analysisModeRuntime/selectorAndPanel.js:130-131`) gets no ack and has no timeout. If the room socket is not connected (an HTTPS certificate not accepted for wss, or a remote guest), the mode switches locally and the host never learns. The scene then waits on an entity that never arrives; this is one source of "stuck loading". + +## 4. Design: one modular launcher and registry + +### 4a. Two descriptors and one lifecycle + +```ts +// core/analysis/launch/targetKey.ts +export function targetKey(p: string): string // path.resolve + win32/darwin case fold (LAUNCHER-17) + +// core/analysis/launch/launchKinds.ts — HOW something is produced and served (XR | LivePanel | VisualizeDOM | future) +export interface LaunchKind { + id: 'XR' | 'LivePanel' | 'VisualizeDOM' | string; + targets: ReadonlyArray<'file' | 'directory'>; + eligibility(target: LaunchTarget, ctx): Promise; // language support, chart+mapping validation, HTML-only… + produce(target, session, signal: AbortSignal): Promise; // Python + parser; returns files + mainHtml + assetManifest + watch?: (session, signal) => Promise; // file/dir watcher; handle.dispose() + capabilities: ReadonlyArray; // which in-scene analyses the server attaches + progress: ProgressPlan; // replaces the per-launcher percentages + folderName: string; // storage root (also feeds startup cleanup, LAUNCHER-14) +} + +// core/analysis/launch/analysisTypes.ts — WHAT an in-scene analysis is (single | dependency-graph | historical-compare | project-evolution | future) +export interface AnalysisTypeDescriptor { + id: AnalysisTypeId; // also the coordinator mode and the room entityKind root + label: string; + available(sessionCtx): Availability; // replaces resolveAnalysisServerCapabilities + getAvailability() + sceneAssets: RuntimeAssetRef[]; // replaces hard-coded lists in directoryXRParser/singleFileRuntimeAssets + createService(sessionCtx): AnalysisService; // DependencyGraphService / HistoricalComparisonService / … + messages: Record; // 'dependency-graph-start' etc., routed by a generic router + rest?: Record; // '/api/historical/compare' … + snapshotProbe?: { entityKind: string; isAvailable(e): boolean; allowsEmptyShell: boolean }; // replaces SNAPSHOT_PROBE_BY_MODE + refresh?: { handler(batch): Promise; background?: boolean; enabledByDefault: boolean }; + controllerView: { default: string; onSnapshot?: string }; // replaces analysisViewModes +} + +interface AnalysisService { isBusy(): boolean; run(req, job: () => Promise): Promise; dispose(): Promise; } +``` + +### 4b. `LaunchRegistry` replaces UnifiedSessionRegistry, SessionServerManager, fileToServerMap and the session parts of ServerControl + +```ts +class LaunchRegistry { + launch(kind, target, opts): Promise // synchronous reservation by key = `${kind}|${targetKey}|${depth}` (LAUNCHER-4) + get(sessionId) / byKey(key) / byServerId(id) // ONE identity: sessionId; port is just an attribute (LAUNCHER-1/3) + close(sessionId, reason): Promise // the only teardown entry point +} +interface LaunchHandle { + session: Session; + abort: AbortController; // Close during analysis aborts (LAUNCHER-7/10) + resources: Disposable[]; // pushed as each step succeeds: watcher, server, sse channel, feature host + state: 'reserved'|'producing'|'serving'|'monitoring'|'failed'|'closed'; +} +``` + +Pipeline (one function, used by every kind): + +``` +reserve(key) -> throws Duplicate synchronously +eligibility() -> fail fast, nothing to undo +produce(signal) [timeout + abort] -> files saved under storage// +server = startServer(session) -> bound port read from server.address(); feature host built AFTER listen +resources.push(server) +watcher = kind.watch?.(signal) -> AFTER the server, so a server failure never leaves a watcher (LAUNCHER-5) +resources.push(watcher) +state = monitoring; openPage() fire-and-forget (not awaited) +on ANY error/abort: dispose resources in reverse; state=failed; ONE toast; keep a failed entry for display only +``` + +Server and SSE changes: +- `/events` and SSE resolve by `config.analysisSessionId`. `SSEManager.send(sessionId, …)`, with an index `targetKey → Set` for the watchers. +- `ServerControl.stopServer(serverId)` becomes `LaunchRegistry.close(sessionId)` whenever the server has a session; plain servers keep the current path. +- `stopAllServers` returns a report (LAUNCHER-9). +- `forceStop` really closes the listener (LAUNCHER-2). + +Router: +- `AnalysisMessageRouter` becomes a table lookup over `AnalysisTypeDescriptor.messages` for the types the session's kind declares. "Not available" replies are automatic. +- The busy gate is taken synchronously in the generic dispatcher (`service.run`). Busy goes back to the requester only (LAUNCHER-11). + +Scene assets: the parsers ask `assetsFor(kind, enabledTypes)` (union of `sceneAssets`) and stop keeping their own lists. + +Adding a fifth analysis type then means one descriptor file, its runtime folder and its service. + +### 4c. Migration steps (behaviour-preserving, each step shippable and testable) +1. **Fix the confirmed bugs that need no redesign**, each with its scratch test promoted into `test/servers/` or `test/analysis/`: LAUNCHER-2, 6, 8, 9, 11, 12, 15, and LAUNCHER-1 (bound port from `server.address()`). +2. **Introduce `targetKey` plus synchronous reservation** in `createSession` (LAUNCHER-4, 17). +3. **Make the pipeline transactional.** Add a `resources` stack and `AbortController` to `executeLaunchPipeline`, switch the order to server → watcher for all kinds, and give Close Analysis the abort (LAUNCHER-5, 7, 10). Existing launcher tests (`launcherClosures.test.cjs`, `analysisOrchestratorDuplicate.test.cjs`) pin the per-kind configs. +4. **Re-key SSE and the file map by sessionId** (LAUNCHER-3). Keep the `fileToServerMap` API as a thin adapter during the transition. `livePanelSse.test.cjs` and the xr-mode harness verify it. +5. **Extract `LaunchKind` descriptors** from the three launchers and the five mode-selection `switch`es. The orchestrator becomes `registry.launch(kinds[mode], target)`. +6. **Extract `AnalysisTypeDescriptor`s** from `analysisServerCapabilities.ts`, `AnalysisFeatureHost` (constructor branches), the three bridges, `SNAPSHOT_PROBE_BY_MODE`, `analysisViewModes` and the parsers' asset lists. Run `analysisMessageRouter.test.cjs`, `analysisServerCapabilities.test.cjs`, `analysisModeMegatest.test.cjs` and the four Playwright harnesses unchanged. +7. **Fold teardown together.** Move `SessionServerManager`/`ServerLaunchOrchestrator`/`ServerWatcherIntegration` port matching into `LaunchRegistry.close`, delete the dead paths (LAUNCHER-14 fallback dir, LAUNCHER-18), and point startup cleanup at the `LaunchKind.folderName`s. + +### 4d. Cross-platform rules for the new code +- Identity: `targetKey()` only; never compare raw `fsPath`. +- Files: `path.join`/`path.relative` and the `!rel.startsWith('..' + sep) && !isAbsolute(rel)` containment check; URLs built with `/` explicitly from `rel.split(path.sep)`. +- Ports: bind once with port 0 retry or exclusive probing across `::`/`0.0.0.0`/`127.0.0.1`, read `server.address().port`, and treat the port as display data only. +- Python: always `PYTHONUTF8=1`/`PYTHONIOENCODING=utf-8`, decode with `setEncoding('utf8')`, and kill the child on abort. Use `taskkill /T` on Windows if the backend ever spawns children. + +## 5. Status of the REPORT §9 deferred items in this area +| Item | Real user-facing bug? | +|---|---| +| Same target in two modes → `/events` 404 | **Yes**, confirmed (LAUNCHER-3). It also happens with XR plus XR-deep and with a double click (LAUNCHER-4), and it cross-wires SSE. | +| "Stop all 20 server(s)?" while 13 ports open | The prompt and count mismatch is confirmed (LAUNCHER-9). The exact numbers are most plausibly HTTPS port drift (LAUNCHER-1) plus orphan or leaked listeners (LAUNCHER-2, 7); the maintainer should say which server mode was in use. | +| `stopAllServers` count-as-success | **Yes**: contradictory toasts (LAUNCHER-9). | +| `forceStop` on HTTPS leaves the listener | **Yes**, and on **HTTP too**. `stop()` cannot recover it afterwards (LAUNCHER-2). | +| Registrar failure reports success | Real but practically unreachable today (LAUNCHER-16). | + +Needs the maintainer's eyes (no VS Code, headset, macOS or Windows here): LAUNCHER-13 (macOS/Windows co-bind), the Windows half of LAUNCHER-15/17, and whether the forceStop path is hit in practice (look for "did not shut down cleanly" in the CodeXR output). diff --git a/docs/xr-audit/lifecycle.md b/docs/xr-audit/lifecycle.md new file mode 100644 index 00000000..a13e1696 --- /dev/null +++ b/docs/xr-audit/lifecycle.md @@ -0,0 +1,245 @@ +# Lifecycle audit: in-scene orchestration of the four XR analyses + +Area: `analysis-mode` runtime (mode registry, transitions, `selection`), its coupling to the analysis-table / controller / logo, the three mode lifecycles (historical, dependency graph, project evolution), the server echo (`analysis-view`), collaboration sync, SSE live reload, and debug APIs. +Abbreviation: `T/` = `apps/vscode-extension/templates/components/codexr/`. + +Scratch harness (does not touch the repo): `/tmp/claude-0/-home-user/af5ccea8-f538-575c-b7b6-8256e5a53df6/scratchpad/audit/lifecycle/` +- `scenarios.cjs`: Playwright scenarios over the real assembled runtimes in `test/manual/xr-mode-cycle-harness.html`, **served over HTTP** (`server.cjs`). Scenarios: `rapidSwitch activateThrows activateHangs datasetFails selectorLateMessage leakCycles`. Env flags: `TREEBUILDER=1` (mock `babia-treebuilder` so project evolution can render), `NO_LISTENERS=1` (turns off listener tracking so the CDP heap counters are honest), `CYCLES=n`. +- `instrument.js` (init script) adds fault injection: `__faults[mode].activate = 'throw'|'reject'|'hang'|ms` wraps any lifecycle registered through the public `register`, and `__fetchFaults` makes a fetch hang, fail or reject. It also counts listeners, intervals and timeouts. +- `pe-scenario.cjs`, `hist-scenario.cjs`, `dep-start.cjs`, `sse-test.cjs`: focused repros. +- `unit/lifecycle-audit.test.cjs`: three `node --test` vm repros that need no browser. All three pass, so each one demonstrates its bug. +- Run any of them with `export PATH=/opt/node24/bin:$PATH; NODE_OPTIONS="--require /vendor/cdn-route.cjs" node