From 3e282b4c6662d4fccb9eab210e1aa68e05252f60 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:08:16 +0000 Subject: [PATCH 01/12] chore(lint): lock the TypeScript idioms already at zero MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 1, TypeScript part. A new ESLint block over src/**/*.ts makes four idioms that are already absent errors, so they stay absent: - no-var var in src/: 0 -> 0 - prefer-rest-params arguments object: 0 -> 0 - @typescript-eslint/no-namespace namespace: 0 -> 0 - @typescript-eslint/no-unsafe-function-type Function type: 0 -> 0 Counts from the A.1 AST script (docs/cleanup/modernization.md appendix). The block is the home of every later lock-in of this story; exceptions are per-file overrides, never eslint-disable comments (suppressions stay 0). lintContract.test.cjs gains one test asserting the four rules are errors over src/**/*.ts. No source file changes; lint 0 errors, 204 warnings (budget unchanged). Gates: npm run lint, npm test 1054/1054 (1053 + the new contract test). Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 12 ++++++++++ .../test/tooling/lintContract.test.cjs | 23 +++++++++++++++++++ 2 files changed, 35 insertions(+) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 9c0c4f4d..eed2a0a8 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -105,6 +105,18 @@ export default [{ "@typescript-eslint/no-floating-promises": ["error", { checkThenables: true }], "@typescript-eslint/no-misused-promises": "warn", }, +}, { + // Modernized idioms (story #56, docs/cleanup/modernization.md §1 and §7). + // Each rule landed in the commit that brought its idiom to zero in src/, so + // the count can only stay there. Exceptions are per-file overrides below, + // never eslint-disable comments (the suppressions guardrail is at 0). + files: ["src/**/*.ts"], + rules: { + "no-var": "error", + "prefer-rest-params": "error", + "@typescript-eslint/no-namespace": "error", + "@typescript-eslint/no-unsafe-function-type": "error", + }, }, { files: NO_CONSOLE_FILES, ignores: CONSOLE_ALLOWLIST, diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index 233442be..0ff621d6 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -197,3 +197,26 @@ test('no-console is an error over all of src/, and the log sink is the only exce assert.deepEqual(block.ignores, ['src/core/logging/sink.ts']); assert.ok(fs.existsSync(path.join(projectRoot, 'src', 'core', 'logging', 'sink.ts')), 'the allowlisted sink exists'); }); + +// Idioms story #56 brought to zero in src/ (docs/cleanup/modernization.md §7). +// Each lock-in landed with the commit that reached zero; one switched off or +// downgraded would let the idiom come back unnoticed. +const MODERNIZED_IDIOM_RULES = [ + 'no-var', + 'prefer-rest-params', + '@typescript-eslint/no-namespace', + '@typescript-eslint/no-unsafe-function-type', +]; + +test('the modernized idioms stay locked over src/', async () => { + const config = await loadEslintConfig(); + const block = config.find((candidate) => candidate.rules + && candidate.rules['no-var'] !== undefined + && Array.isArray(candidate.files) && candidate.files.includes('src/**/*.ts')); + + assert.ok(block, 'one block locks the idioms over src/**/*.ts'); + for (const rule of MODERNIZED_IDIOM_RULES) { + const value = block.rules[rule]; + assert.equal(Array.isArray(value) ? value[0] : value, 'error', `${rule} is an error over src/`); + } +}); From 2308d6c0aed1e19c73eaef42707ed420a21dbc43 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:10:33 +0000 Subject: [PATCH 02/12] refactor(ts): static imports for Node built-ins MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 4. Inline require() of Node built-ins becomes a top-level `import * as … from '…'`: - code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts 4 x require('path').dirname -> path.dirname - servers/runtime/sse/SSEManager.ts require('path').join + require('fs') -> path.join, fs.existsSync/statSync - views/active_servers/items/activeServerItems.ts require('path').basename -> path.basename require (package), A.1 script: 7 in 3 files -> 0. executePython.ts has none left: #35 already removed its 8. The 2 relative lazy requires (directoryReAnalyzer.ts, getVisualizationConfiguration.ts, cycle breakers) and the 8 in ModularTreeDataProvider.ts (load-bearing, skill §4) stay. Lock-in: @typescript-eslint/no-require-imports is an error over src/, with one per-file override block (rule off) for exactly those three files. lintContract.test.cjs asserts the rule and pins the exemption list. Text pins (grep of the basenames in test/ and scripts/): - activeServerItems.ts: remoteAccessImplementation.test.cjs:123,175 reads it and matches TreeItemCollapsibleState.Collapsed, "Local network address", "Connected users", remoteAccess?.status, the participant contextValue ternary - G (behaviour strings); none on the import block or line 516. lanUrl.test.cjs loads it from out/ (behavioural). guardrail-baseline.json lists it in size.filesOver500 (still over 500). - directoryAnalysisLivePanelCommands.ts: no hits. - SSEManager.ts: no text pins (only requireOut loads). Built-ins are already loaded by the host, so hoisting the require changes no evaluation order. The `fs` local that shadowed nothing is gone; the calls are now typed (they were `any`). H2 (CODEXR_NO_SOURCEMAPS=1 npm run package): dist/extension.js b4c1894828cd (1,194,230 B) -> 5446d88cc487 (1,195,032 B, +802 B). The diff touches only the three modules: the hoisted requires renamed the minifier's locals, and SSEManager, which had no namespace import that survived emit before, now carries TypeScript's __importStar helper. No other module changed. Gates: npm run lint (0 errors, 204 warnings, budget unchanged), npm test 1055/1055. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 13 ++++++++++++ .../directoryAnalysisLivePanelCommands.ts | 9 +++++---- .../src/servers/runtime/sse/SSEManager.ts | 5 +++-- .../active_servers/items/activeServerItems.ts | 3 ++- .../test/tooling/lintContract.test.cjs | 20 +++++++++++++++++++ 5 files changed, 43 insertions(+), 7 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index eed2a0a8..07a71a52 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -116,6 +116,19 @@ export default [{ "prefer-rest-params": "error", "@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-unsafe-function-type": "error", + "@typescript-eslint/no-require-imports": "error", + }, +}, { + // The lazy require() calls that stay (modernization.md §4): the eight in + // the tree provider are load-bearing (cleanup skill §4), and the other two + // defer a relative import to break a load-time module cycle. + files: [ + "src/views/ModularTreeDataProvider.ts", + "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", + "src/utils/getVisualizationConfiguration.ts", + ], + rules: { + "@typescript-eslint/no-require-imports": "off", }, }, { files: NO_CONSOLE_FILES, diff --git a/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts b/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts index 8f729cff..9447f4bd 100644 --- a/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts +++ b/apps/vscode-extension/src/code_analysis/commands/directory_analysis/directoryAnalysisLivePanelCommands.ts @@ -3,6 +3,7 @@ * Commands for analyzing directories in LivePanel mode. */ +import * as path from 'path'; import * as vscode from 'vscode'; import { AnalysisOrchestrator } from '../../engine/analysisOrchestrator'; import { CommandRegistration } from '../subsections/analysis_settings/analysis_file_mode'; @@ -47,7 +48,7 @@ export class DirectoryAnalysisLivePanelCommands { if (stat.type === vscode.FileType.Directory) { directoryPath = uri.fsPath; } else { - directoryPath = require('path').dirname(uri.fsPath); + directoryPath = path.dirname(uri.fsPath); } } else if (vscode.workspace.workspaceFolders?.length) { if (vscode.workspace.workspaceFolders.length === 1) { @@ -65,7 +66,7 @@ export class DirectoryAnalysisLivePanelCommands { void vscode.window.showWarningMessage('CodeXR: No directory selected for LivePanel analysis'); return; } - directoryPath = require('path').dirname(activeEditor.document.fileName); + directoryPath = path.dirname(activeEditor.document.fileName); } await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, false); @@ -88,7 +89,7 @@ export class DirectoryAnalysisLivePanelCommands { const stat = await vscode.workspace.fs.stat(uri); directoryPath = stat.type === vscode.FileType.Directory ? uri.fsPath - : require('path').dirname(uri.fsPath); + : path.dirname(uri.fsPath); } else if (vscode.workspace.workspaceFolders?.length) { directoryPath = vscode.workspace.workspaceFolders[0].uri.fsPath; } else { @@ -97,7 +98,7 @@ export class DirectoryAnalysisLivePanelCommands { void vscode.window.showWarningMessage('CodeXR: No directory selected for LivePanel Deep analysis'); return; } - directoryPath = require('path').dirname(activeEditor.document.fileName); + directoryPath = path.dirname(activeEditor.document.fileName); } await AnalysisOrchestrator.orchestrateAnalysis(directoryPath, 'LivePanel', 'directory', this.context, true); diff --git a/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts b/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts index 4003f20f..d3ba36b8 100644 --- a/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts +++ b/apps/vscode-extension/src/servers/runtime/sse/SSEManager.ts @@ -1,3 +1,5 @@ +import * as fs from 'fs'; +import * as path from 'path'; import * as http from 'http'; import { SSEClientRegistry } from './sseClientRegistry'; import { fileToServerMap } from '../../../utils/fileToServerMap'; @@ -89,8 +91,7 @@ export class SSEManager { logger.debug(() => `REQUEST_UPDATE: Found mapping - Port: ${mapping.port}, TempDir: ${mapping.tempDir}`); // Verify data.json exists in the temp directory - const dataJsonPath = require('path').join(mapping.tempDir, 'data.json'); - const fs = require('fs'); + const dataJsonPath = path.join(mapping.tempDir, 'data.json'); try { const exists = fs.existsSync(dataJsonPath); logger.debug(() => `REQUEST_UPDATE: data.json exists at ${dataJsonPath}: ${exists}`); diff --git a/apps/vscode-extension/src/views/active_servers/items/activeServerItems.ts b/apps/vscode-extension/src/views/active_servers/items/activeServerItems.ts index 7f6e329d..8760dd25 100644 --- a/apps/vscode-extension/src/views/active_servers/items/activeServerItems.ts +++ b/apps/vscode-extension/src/views/active_servers/items/activeServerItems.ts @@ -1,3 +1,4 @@ +import * as path from 'path'; import * as vscode from 'vscode'; import { ActiveServer } from '../../../active_servers/model/activeServerModel'; import { COLLABORATION_AVATARS, ConnectedParticipantSummary } from '../../../collaboration'; @@ -513,7 +514,7 @@ Mode: ${mode} Port: ${server.port}`; if (server.htmlFile) { - const fileName = require('path').basename(server.htmlFile); + const fileName = path.basename(server.htmlFile); tooltip += `\nFile: ${fileName}`; } diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index 0ff621d6..075140d4 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -206,6 +206,7 @@ const MODERNIZED_IDIOM_RULES = [ 'prefer-rest-params', '@typescript-eslint/no-namespace', '@typescript-eslint/no-unsafe-function-type', + '@typescript-eslint/no-require-imports', ]; test('the modernized idioms stay locked over src/', async () => { @@ -220,3 +221,22 @@ test('the modernized idioms stay locked over src/', async () => { assert.equal(Array.isArray(value) ? value[0] : value, 'error', `${rule} is an error over src/`); } }); + +test('only the three files with deliberate lazy require() may use it', async () => { + // modernization.md §4: the tree provider's eight lazy requires are + // load-bearing, the other two break load-time cycles. Any other file + // imports statically. + const config = await loadEslintConfig(); + const exemptions = config.filter((block) => block.rules + && block.rules['@typescript-eslint/no-require-imports'] === 'off'); + + assert.equal(exemptions.length, 1, 'one exemption block'); + assert.deepEqual([...exemptions[0].files].sort(), [ + 'src/code_analysis/engine/watchers/directoryReAnalyzer.ts', + 'src/utils/getVisualizationConfiguration.ts', + 'src/views/ModularTreeDataProvider.ts', + ]); + for (const file of exemptions[0].files) { + assert.ok(fs.existsSync(path.join(projectRoot, file)), `${file} exists`); + } +}); From 27bfec86a02999dec0e65d7ede5d3bfaa44422a0 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:12:12 +0000 Subject: [PATCH 03/12] refactor(ts): slice() instead of substr(), lock includes() and slice() MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 5. - servers/runtime/multiServerLauncher.ts generateServerId(): Math.random().toString(36).substr(2, 5) -> .slice(2, 7). Both arguments are non-negative constants, so slice(start, start + length) returns the same characters (both clamp at the end of the string). substr(): 1 -> 0. indexOf compares: the A.1 script reported 5 in 3 files, but re-reading them none is a presence test: the 3 in executePython.ts are `args[args.indexOf('--x') + 1]` (the index is used) and the 2 in gitExportPythonWorkerPool.ts / gitBatchObjectReader.ts are `newline = buf.indexOf('\n')` assignments the script counts as binary expressions. Real `indexOf(...) !== -1` compares: 0 -> 0, so nothing to convert; the typed rule confirms it reports nothing. Lock-in (src/**/*.ts): @typescript-eslint/prefer-includes and no-restricted-properties on `substr`, both errors; lintContract.test.cjs asserts them. Text pins: multiServerLauncher.test.cjs reads only its golden transcript fixture, which normalizes ids with /server_\d+_[a-z0-9]+/ (behavioural, not a source pin). folderDependencies.json mentions the module in prose only. H2: dist/extension.js 5446d88cc487 -> f173adebd8e1 (-1 B); the only changed statement is generateServerId's substr(2,5) -> slice(2,7). Gates: npm run lint (0 errors, 204 warnings), npm test 1055/1055. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 5 +++++ .../src/servers/runtime/multiServerLauncher.ts | 2 +- apps/vscode-extension/test/tooling/lintContract.test.cjs | 2 ++ 3 files changed, 8 insertions(+), 1 deletion(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 07a71a52..15b6f7a0 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -117,6 +117,11 @@ export default [{ "@typescript-eslint/no-namespace": "error", "@typescript-eslint/no-unsafe-function-type": "error", "@typescript-eslint/no-require-imports": "error", + "@typescript-eslint/prefer-includes": "error", + "no-restricted-properties": ["error", { + property: "substr", + message: "Use slice() (substr is Annex B legacy; slice(start, start + length) for non-negative arguments).", + }], }, }, { // The lazy require() calls that stay (modernization.md §4): the eight in diff --git a/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts b/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts index 5a670c92..3f971785 100644 --- a/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts +++ b/apps/vscode-extension/src/servers/runtime/multiServerLauncher.ts @@ -268,7 +268,7 @@ export class MultiServerLauncher { */ private generateServerId(): string { const timestamp = Date.now(); - const random = Math.random().toString(36).substr(2, 5); + const random = Math.random().toString(36).slice(2, 7); return `server_${timestamp}_${random}`; } } diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index 075140d4..7f3401dd 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -207,6 +207,8 @@ const MODERNIZED_IDIOM_RULES = [ '@typescript-eslint/no-namespace', '@typescript-eslint/no-unsafe-function-type', '@typescript-eslint/no-require-imports', + '@typescript-eslint/prefer-includes', + 'no-restricted-properties', ]; test('the modernized idioms stay locked over src/', async () => { From 9e2506eccb89f2af430aa3711c89dcc42d49c655 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:14:59 +0000 Subject: [PATCH 04/12] refactor(ts): optional chaining where it is safe MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 6. Every site the typed @typescript-eslint/prefer-optional-chain reports (10, in 7 files), rewritten by hand and each one reviewed for the one case where `a && a.b` and `a?.b` differ (a falsy, non-nullish `a`): - engine/processors/analysisBootstrap.ts:233 `!content || !content.trim()` -> `!content?.trim()`; content is string | undefined, '' gives true both ways. - services/serverWatcherIntegration.ts:154,158 (in find() predicates) `server.htmlFile && server.htmlFile.includes(x)` -> `server.htmlFile?.includes(x)`, same for customName. Both are `string | undefined` on ActiveServer (activeServerModel.ts:50,53). '' differs only if the needle is '': line 154 runs under `if (... && session.outputPath)`, line 158 searches 'Analysis', so the truthiness is the same. - analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts:76 `!chart || !chart.dimensions` -> `!chart?.dimensions` (object | undefined). - servers/commands/serverCommands.ts:310 and visualize_data/views/interactions/visualizationLauncher.ts:96 `fileUri && fileUri[0]` -> `fileUri?.[0]` (Uri[] | undefined from showOpenDialog). - views/babia_examples/interactions/handleBabiaExampleClicks.ts:83,90,97 `item.babiaExample && item.babiaExample.isValid` -> `item.babiaExample?.isValid`. - visualization_settings/utils/settingsAccessors.ts:82 `legacySettings && legacySettings[field]` -> `legacySettings?.[field]`, in an `if`: for a falsy primitive both are falsy (indexing a primitive does not throw), for null/undefined both short-circuit. All are in boolean contexts. Count: typed rule 10 -> 0 (A.1 script `a && a.b`: 7 -> 1). Left on purpose: - serverWatcherIntegration.ts:151 `server.metadata && server.metadata.sessionId === sessionId`: not equivalent (`undefined === undefined` would match a server without metadata when sessionId is undefined); the rule does not report it either. - sharedChartTypeSettingCore.ts:103 `selectedItem && selectedItem.chart`: not reported by the typed rule; the plan keeps this row rule-driven. Lock-in: @typescript-eslint/prefer-optional-chain is an error over src/; lintContract.test.cjs asserts it. Text pins (basename grep in test/ and scripts/): - analysisBootstrap.ts: reanalysisArchitecture.test.cjs:132/152, directoryAnalysisStartup.test.cjs:29, livePanelDomIntegration.test.cjs:64/78/93/213 match buildTrackedFiles, resolveTrackedSystemPath, executeAnalysis, SHA256Generator, LivePanelParser construction, bootstrapVisualizeDOM - S/G, none on ensureBootstrapFiles' filter. - serverWatcherIntegration.ts: reanalysisArchitecture.test.cjs:16 matches stopWatchingSession - G, untouched. guardrail-baseline.json any.topFiles (count 8, unchanged). - sharedDimensionMappingSettingCore.ts: dimensionMappingShared.test.cjs:20 and xrFieldSchemaIntegration.test.cjs:38 match the class name, getFieldsForDataType, validateMappingsForChart, the mappedValue label, XRFieldSchemaService - G, untouched. - serverCommands.ts: remoteAccessImplementation.test.cjs:239-253 match the stopAll / uninstallManagedBinary ordering - G, untouched; serverCommandsContextGuard.test.cjs mentions it in a comment. - handleBabiaExampleClicks.ts: guardrail-baseline.json any.topFiles only. - settingsAccessors.ts, visualizationLauncher.ts: no text pins. Measurement: complexity.over10 54 -> 53 (fewer `&&`), recorded with guardrails:update. ESLint warnings 204 -> 204. H2: dist/extension.js f173adebd8e1 -> e927daf5a3fd (-78 B); the 9 changed statements are exactly the 10 sites above. Gates: npm run lint, npm test 1055/1055. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 1 + .../code_analysis/engine/processors/analysisBootstrap.ts | 2 +- .../src/code_analysis/services/serverWatcherIntegration.ts | 4 ++-- .../sharedDimensionMappingSettingCore.ts | 2 +- .../vscode-extension/src/servers/commands/serverCommands.ts | 2 +- .../babia_examples/interactions/handleBabiaExampleClicks.ts | 6 +++--- .../src/visualization_settings/utils/settingsAccessors.ts | 2 +- .../views/interactions/visualizationLauncher.ts | 2 +- apps/vscode-extension/test/tooling/guardrail-baseline.json | 4 ++-- apps/vscode-extension/test/tooling/lintContract.test.cjs | 1 + 10 files changed, 14 insertions(+), 12 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 15b6f7a0..af2e8153 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -118,6 +118,7 @@ export default [{ "@typescript-eslint/no-unsafe-function-type": "error", "@typescript-eslint/no-require-imports": "error", "@typescript-eslint/prefer-includes": "error", + "@typescript-eslint/prefer-optional-chain": "error", "no-restricted-properties": ["error", { property: "substr", message: "Use slice() (substr is Annex B legacy; slice(start, start + length) for non-negative arguments).", diff --git a/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts b/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts index c511cd32..d5ec1008 100644 --- a/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts +++ b/apps/vscode-extension/src/code_analysis/engine/processors/analysisBootstrap.ts @@ -230,7 +230,7 @@ export class AnalysisBootstrap { ): void { const missingFiles = requiredFiles.filter((fileName) => { const content = loadedFiles.get(fileName); - return !content || !content.trim(); + return !content?.trim(); }); if (missingFiles.length > 0) { diff --git a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts index 34786872..6a703df5 100644 --- a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts +++ b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts @@ -151,11 +151,11 @@ export class ServerWatcherIntegration { let matchingServer = servers.find((server: any) => server.metadata && server.metadata.sessionId === sessionId); if (!matchingServer && session.outputPath) { - matchingServer = servers.find((server: any) => server.htmlFile && server.htmlFile.includes(session.outputPath)); + matchingServer = servers.find((server: any) => server.htmlFile?.includes(session.outputPath)); } if (!matchingServer) { - matchingServer = servers.find((server: any) => server.customName && server.customName.includes('Analysis')); + matchingServer = servers.find((server: any) => server.customName?.includes('Analysis')); } if (matchingServer) { diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts index 9dbf6b83..e9c9a477 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts @@ -73,7 +73,7 @@ export class SharedDimensionMappingSettingCore { } const chart = this.getChartMetadata(chartType); - if (!chart || !chart.dimensions) { + if (!chart?.dimensions) { return [new CodeAnalysisTreeItem( 'No dimensions available', vscode.TreeItemCollapsibleState.None, diff --git a/apps/vscode-extension/src/servers/commands/serverCommands.ts b/apps/vscode-extension/src/servers/commands/serverCommands.ts index 3fe606cc..6e7ad20d 100644 --- a/apps/vscode-extension/src/servers/commands/serverCommands.ts +++ b/apps/vscode-extension/src/servers/commands/serverCommands.ts @@ -307,7 +307,7 @@ async function promptForHtmlFile(): Promise { const fileUri = await vscode.window.showOpenDialog(options); - if (fileUri && fileUri[0]) { + if (fileUri?.[0]) { const filePath = fileUri[0].fsPath; logger.debug(() => `User selected file: ${filePath}`); diff --git a/apps/vscode-extension/src/views/babia_examples/interactions/handleBabiaExampleClicks.ts b/apps/vscode-extension/src/views/babia_examples/interactions/handleBabiaExampleClicks.ts index 288df393..805a6653 100644 --- a/apps/vscode-extension/src/views/babia_examples/interactions/handleBabiaExampleClicks.ts +++ b/apps/vscode-extension/src/views/babia_examples/interactions/handleBabiaExampleClicks.ts @@ -80,21 +80,21 @@ export class BabiaExampleClickHandler { break; case 'launchExample': - if (item.babiaExample && item.babiaExample.isValid) { + if (item.babiaExample?.isValid) { logger.debug(`Launching example from context menu: ${item.babiaExample.id}`); await this.handleExampleItemClick(item); } break; case 'openInBrowser': - if (item.babiaExample && item.babiaExample.isValid) { + if (item.babiaExample?.isValid) { logger.debug(`Opening example in browser: ${item.babiaExample.id}`); await this.launchExampleInBrowser(item.babiaExample); } break; case 'openInPanel': - if (item.babiaExample && item.babiaExample.isValid) { + if (item.babiaExample?.isValid) { logger.debug(`Opening example in panel: ${item.babiaExample.id}`); await this.launchExampleInPanel(item.babiaExample); } diff --git a/apps/vscode-extension/src/visualization_settings/utils/settingsAccessors.ts b/apps/vscode-extension/src/visualization_settings/utils/settingsAccessors.ts index 672e0894..ca93138f 100644 --- a/apps/vscode-extension/src/visualization_settings/utils/settingsAccessors.ts +++ b/apps/vscode-extension/src/visualization_settings/utils/settingsAccessors.ts @@ -79,7 +79,7 @@ function resolveColor(field: ColorField, fileSettings: StoredVisualizationSettin // Fallback to globalState for backward compatibility if (extensionContext) { const legacySettings = extensionContext.globalState.get(LEGACY_STORAGE_KEY); - if (legacySettings && legacySettings[field]) { + if (legacySettings?.[field]) { return legacySettings[field]; } } diff --git a/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts b/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts index 2743766c..80dced89 100644 --- a/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts +++ b/apps/vscode-extension/src/visualize_data/views/interactions/visualizationLauncher.ts @@ -93,7 +93,7 @@ export class VisualizationLauncher { const fileUri = await vscode.window.showOpenDialog(options); - if (fileUri && fileUri[0]) { + if (fileUri?.[0]) { const filePath = fileUri[0].fsPath; const fileName = path.basename(filePath); diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 24a1299c..cad26230 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -55,7 +55,7 @@ "src/views/active_servers/items/activeServerItems.ts" ], "functions.over80Lines": 36, - "complexity.over10": 54, + "complexity.over10": 53, "complexity.over15": 9, "complexity.over20": 0, "complexity.over30": 0, @@ -70,7 +70,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49505, + "src.lines": 49508, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index 7f3401dd..b29bb22d 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -208,6 +208,7 @@ const MODERNIZED_IDIOM_RULES = [ '@typescript-eslint/no-unsafe-function-type', '@typescript-eslint/no-require-imports', '@typescript-eslint/prefer-includes', + '@typescript-eslint/prefer-optional-chain', 'no-restricted-properties', ]; From bf60a7a174ac9c7de7bf3566c727d3571b4025e8 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:17:29 +0000 Subject: [PATCH 05/12] refactor(ts): template literals instead of string concatenation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 7. Every concatenation that `prefer-template` reports in src/ (8 sites, 6 files) becomes a template literal: - babia_templates/processing/placeholders/createStructure.ts:138 getSSEScriptWithNonce: `scriptContent + '\n' + mainJsScript` -> `${scriptContent}\n${mainJsScript}` (generated scene HTML, done last) - babia_templates/processing/templateHTMLProcessor.ts:104,105 (debug log arguments; `undefined + '...'` and `${undefined}...` are both 'undefined...') - code_analysis/engine/utils/executePython.ts:78 (debug log) - python_env/runtime/venvManager.ts:650 (error message; the first literal line stays a literal, the second absorbs getErrorDetails(error)) - servers/utils/networkUtils.ts:94,95 (debug logs) - utils/jsonFieldAnalyzer.ts:224 (nested `' • ' + sampleText` in an existing template) Every operand is a string (or `string | undefined` in the two log previews), for which `+` and `${}` produce the same text. Byte-identity of the generated HTML: getSSEScriptWithNonce was characterized from out/ (fake vscode, extensionPath = the extension root, nonce fixed) before and after the change, sha256 of its output: xr 12,340 chars f351f1d6919da284 -> f351f1d6919da284 dom 3,682 chars 814d8de268a34f4a -> 814d8de268a34f4a none 0 chars e3b0c44298fc1c14 -> e3b0c44298fc1c14 templateHTMLProcessor.ts changes only log arguments, not the HTML it builds. Counts: prefer-template 8 -> 0. The A.1 script's "string concatenation" row goes 23 -> 18: the 18 left are literal + literal line wraps of long messages (activeAnalysesCommands.ts, remoteAccessManager.ts, collaborationItems.ts, ...), which prefer-template does not flag and which are clearer as they are. Lock-in: prefer-template is an error over src/; lintContract.test.cjs asserts it. Text pins (basename grep in test/ and scripts/): - createStructure.ts: xrDataSource.test.cjs:27 matches the XR_BOATS_TREE_FIELDS ternary and the babia-treebuilder attribute - G, untouched. - templateHTMLProcessor.ts: livePanelDomIntegration.test.cjs:118/137 matches HTML_CONTENT_JSON - G, untouched. - executePython.ts: reanalysisArchitecture.test.cjs:51-52 (silent option), analysisPaths.test.cjs:14 (resolveBackendScriptPath), directoryAnalysisStartup.test.cjs:22 ('--files' absence, coordinator comment), livePanelDomIntegration.test.cjs:150-151 (parsePythonOutput signature, JSON.parse) and featureSurface.cjs:151 (Python entry points) - S/G, none on line 78. - venvManager.ts, networkUtils.ts: loaded from out/ only; no test matches the changed messages ("could not upgrade pip", "For VR/Mobile"). - jsonFieldAnalyzer.ts: no hits. H2: dist/extension.js e927daf5a3fd -> 3838d8e16de4 (+13 B); the changed statements are exactly the 8 sites. Gates: npm run lint, npm test 1055/1055. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 1 + .../processing/placeholders/createStructure.ts | 2 +- .../src/babia_templates/processing/templateHTMLProcessor.ts | 4 ++-- .../src/code_analysis/engine/utils/executePython.ts | 2 +- apps/vscode-extension/src/python_env/runtime/venvManager.ts | 3 +-- apps/vscode-extension/src/servers/utils/networkUtils.ts | 4 ++-- apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts | 2 +- apps/vscode-extension/test/tooling/lintContract.test.cjs | 1 + 8 files changed, 10 insertions(+), 9 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index af2e8153..6dec5ea2 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -119,6 +119,7 @@ export default [{ "@typescript-eslint/no-require-imports": "error", "@typescript-eslint/prefer-includes": "error", "@typescript-eslint/prefer-optional-chain": "error", + "prefer-template": "error", "no-restricted-properties": ["error", { property: "substr", message: "Use slice() (substr is Annex B legacy; slice(start, start + length) for non-negative arguments).", diff --git a/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts b/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts index 958c6223..735b7611 100644 --- a/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts +++ b/apps/vscode-extension/src/babia_templates/processing/placeholders/createStructure.ts @@ -135,7 +135,7 @@ export class CreateStructure { // Add nonce script tag for main.js (standard path for all analyses) const mainJsScript = ``; - return scriptContent + '\n' + mainJsScript; + return `${scriptContent}\n${mainJsScript}`; } catch (error) { logger.error(`Error loading SSE script:`, error); diff --git a/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts b/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts index 37a6b334..be3bc2c6 100644 --- a/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts +++ b/apps/vscode-extension/src/babia_templates/processing/templateHTMLProcessor.ts @@ -101,8 +101,8 @@ export class TemplateHTMLProcessor { jsContentType: typeof returnResult.jsContent }); - logger.debug('DEBUG - indexHtml preview:', returnResult.indexHtml?.substring(0, 100) + '...'); - logger.debug('DEBUG - jsContent preview:', returnResult.jsContent?.substring(0, 100) + '...'); + logger.debug('DEBUG - indexHtml preview:', `${returnResult.indexHtml?.substring(0, 100)}...`); + logger.debug('DEBUG - jsContent preview:', `${returnResult.jsContent?.substring(0, 100)}...`); return returnResult; diff --git a/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts b/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts index 6f6702a5..94e0d8f8 100644 --- a/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts +++ b/apps/vscode-extension/src/code_analysis/engine/utils/executePython.ts @@ -75,7 +75,7 @@ export class ExecutePython { } public async executeXRFieldSchema(targetType: 'file' | 'directory'): Promise { - logger.debug(() => 'Loading XR field schema for ' + targetType); + logger.debug(() => `Loading XR field schema for ${targetType}`); return await this.executePythonScript('main.py', [ '--mode', 'schema', '--type', targetType, diff --git a/apps/vscode-extension/src/python_env/runtime/venvManager.ts b/apps/vscode-extension/src/python_env/runtime/venvManager.ts index 1a3c83d3..ef79bb98 100644 --- a/apps/vscode-extension/src/python_env/runtime/venvManager.ts +++ b/apps/vscode-extension/src/python_env/runtime/venvManager.ts @@ -648,8 +648,7 @@ export class VenvManager { if (!pipStillAvailable) { throw new Error( 'CodeXR could not upgrade pip and the virtual environment pip is no longer usable. ' + - 'The global Python installation was not modified.\n\n' + - this.getErrorDetails(error), + `The global Python installation was not modified.\n\n${this.getErrorDetails(error)}`, ); } diff --git a/apps/vscode-extension/src/servers/utils/networkUtils.ts b/apps/vscode-extension/src/servers/utils/networkUtils.ts index b2a53bbd..18f9ebaa 100644 --- a/apps/vscode-extension/src/servers/utils/networkUtils.ts +++ b/apps/vscode-extension/src/servers/utils/networkUtils.ts @@ -91,8 +91,8 @@ export class NetworkUtils { logger.debug('===================================='); logger.debug(() => `Primary External URL: ${urls.localIP}`); logger.debug(() => `Localhost URL: ${urls.localhost}`); - logger.debug(() => 'For VR/Mobile devices use: ' + urls.localIP); - logger.debug(() => 'For local testing use: ' + urls.localhost); + logger.debug(() => `For VR/Mobile devices use: ${urls.localIP}`); + logger.debug(() => `For local testing use: ${urls.localhost}`); logger.debug('Network Diagnostics:'); logger.debug(() => ` - Server listening on: 0.0.0.0:${port}`); logger.debug(() => ` - Local IP detected: ${this.getLocalIPAddress()}`); diff --git a/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts b/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts index 10334b1d..ed689bc7 100644 --- a/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts +++ b/apps/vscode-extension/src/utils/jsonFieldAnalyzer.ts @@ -221,7 +221,7 @@ export class JsonFieldAnalyzer { return { label: field.name, description: typeInfo, - detail: `${field.valueCount} values${sampleText ? ' • ' + sampleText : ''}` + detail: `${field.valueCount} values${sampleText ? ` • ${sampleText}` : ''}` }; } } diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index b29bb22d..a43e1264 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -209,6 +209,7 @@ const MODERNIZED_IDIOM_RULES = [ '@typescript-eslint/no-require-imports', '@typescript-eslint/prefer-includes', '@typescript-eslint/prefer-optional-chain', + 'prefer-template', 'no-restricted-properties', ]; From 55d5c819ec0cbe1ba983cddef8cd23f8d5122e0d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:21:00 +0000 Subject: [PATCH 06/12] refactor(ts): type the any in code_analysis/views/subsections/active_analyses MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 8, first folder (the biggest offender: 18 of 130). Types only. activeAnalysesDataService.ts (11 -> 0): - ActiveAnalysisItem.session: any -> UnifiedAnalysisSession (what getAllSessions() returns and createAnalysisItem stores). - createAnalysisItem(session: any, ...) -> UnifiedAnalysisSession. - getAnalysisById(): any | null -> UnifiedAnalysisSession | undefined | null (getSession() returns undefined for a miss; the catch returns null). - getSubsectionItem(): any -> CodeAnalysisTreeItem, the type its only caller (AnalysisSectionProvider.getChildren) puts it in; the literal is structurally one (import type, no runtime import). - 7 x `(item as any). =` -> `(item as ActiveAnalysisTreeItem). =`, a local type: vscode.TreeItem plus the ActiveAnalysisItem fields copied onto it for context-menu commands. activeAnalysesCommands.ts (7 -> 0): - the six `arg?: ActiveAnalysisItem | string | any` parameters (showActions, showDetails, closeAnalysis, viewInBrowser, exportFolder, extractSessionId) and resolveSelectedSession's `arg: unknown` take ActiveAnalysisCommandArg: a string id, or an object carrying session.id / sessionId / id, directly or under originalAnalysisItem - exactly the shapes extractSessionId probes. ActiveAnalysisItem fits it structurally, so its now-unused import name is dropped from the import line. - generateDetailsContent(session: any) -> UnifiedAnalysisSession. Lock-in: a named flat-config block "codexr/any-free-folders" makes @typescript-eslint/no-explicit-any an error for this folder. lintContract.test.cjs: the warn-budget check skips that one named block (it can only tighten the rule), and a new test pins the block to that single rule at "error" over existing src/ folder globs. Text pins (basename grep in test/ and scripts/): - activeAnalysesActions.test.cjs:35-229 reads both files and matches command ids, "Left-click to show available actions", the export pipeline calls (beginExportPackageTransaction, pruneExportPackage, ...), user-facing strings ("Close analysis for", "Serve it with any static HTTP server") - G, none on a changed line (the `ActiveAnalysisItem` import name is not matched anywhere in test/). - reanalysisArchitecture.test.cjs:70-121 checks the file has no legacy marker (doesNotMatch) - G, untouched. - activeAnalysesCommands.test.cjs, activeAnalysesPresentation.test.cjs load out/ (behavioural). Measurements: any.total 130 -> 112 (code_analysis 53 -> 35); ESLint warnings 204 -> 186, so the lint budget (--max-warnings, eslint.maxWarnings) goes 204 -> 186 via guardrails:update. Characterization: dist-identical 3838d8e16de4 Gates: npm run typecheck, npm run lint, npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 11 ++++++ apps/vscode-extension/package.json | 2 +- .../commands/activeAnalysesCommands.ts | 34 ++++++++++++++----- .../services/activeAnalysesDataService.ts | 34 +++++++++++++------ .../test/tooling/guardrail-baseline.json | 28 +++++++-------- .../test/tooling/lintContract.test.cjs | 31 +++++++++++++++-- 6 files changed, 103 insertions(+), 37 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 6dec5ea2..0f48dd80 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -137,6 +137,17 @@ export default [{ rules: { "@typescript-eslint/no-require-imports": "off", }, +}, { + // Folders whose `any`s were typed away (story #56, modernization.md §7): + // there no-explicit-any is an error, not a budget warning. A folder joins + // the list in the commit that brings it to zero. + name: "codexr/any-free-folders", + files: [ + "src/code_analysis/views/subsections/active_analyses/**/*.ts", + ], + rules: { + "@typescript-eslint/no-explicit-any": "error", + }, }, { files: NO_CONSOLE_FILES, ignores: CONSOLE_ALLOWLIST, diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 4da2b1dc..ffca4aa2 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 204", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 186", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts index f5bc8c48..42e3e11a 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts @@ -9,7 +9,7 @@ import * as path from 'path'; import { UnifiedAnalysisSession } from '../../../../engine/core/analysisSession'; import { UnifiedSessionRegistry } from '../../../../engine/core/sessionRegistry'; import { ServerWatcherIntegration } from '../../../../services/serverWatcherIntegration'; -import { ActiveAnalysisItem, ActiveAnalysesDataService } from '../services/activeAnalysesDataService'; +import { ActiveAnalysesDataService } from '../services/activeAnalysesDataService'; import { CommandRegistration } from '../../../../commands/subsections/analysis_settings/analysis_file_mode'; import { analysisRefreshCoordinator } from '../../../../refresh/analysisRefreshCoordinator'; import { @@ -49,6 +49,22 @@ import { getLogger } from '../../../../../core/logging/sink'; const logger = getLogger('ACTIVE_ANALYSES_COMMANDS'); +/** The id-bearing fields extractSessionId looks for on a command argument. */ +interface SessionIdCarrier { + session?: { id?: string }; + sessionId?: string; + id?: string; +} + +/** + * What an Active Analyses command receives: a session id, the data item + * (an ActiveAnalysisItem fits SessionIdCarrier), the TreeItem tagged with the + * session fields, or a wrapper holding the data item as originalAnalysisItem. + */ +type ActiveAnalysisCommandArg = + | string + | (SessionIdCarrier & { originalAnalysisItem?: SessionIdCarrier }); + /** The Git steps of the export wizard: a request to run, or the wizard stops. */ type GitExportPrompt = | { kind: 'cancelled' } @@ -146,7 +162,7 @@ export class ActiveAnalysesCommands { return [...this.commands]; } - private async showActions(arg?: ActiveAnalysisItem | string | any): Promise { + private async showActions(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -214,7 +230,7 @@ export class ActiveAnalysesCommands { } } - private async showDetails(arg?: ActiveAnalysisItem | string | any): Promise { + private async showDetails(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -229,7 +245,7 @@ export class ActiveAnalysesCommands { await vscode.window.showTextDocument(doc); } - private async closeAnalysis(arg?: ActiveAnalysisItem | string | any): Promise { + private async closeAnalysis(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -277,7 +293,7 @@ export class ActiveAnalysesCommands { void vscode.window.showErrorMessage('Failed to close the analysis session cleanly'); } - private async viewInBrowser(arg?: ActiveAnalysisItem | string | any): Promise { + private async viewInBrowser(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -298,7 +314,7 @@ export class ActiveAnalysesCommands { await vscode.env.openExternal(vscode.Uri.parse(url)); } - private async exportFolder(arg?: ActiveAnalysisItem | string | any): Promise { + private async exportFolder(arg?: ActiveAnalysisCommandArg): Promise { const selected = this.resolveSelectedSession(arg); if (!selected) { return; @@ -701,7 +717,7 @@ export class ActiveAnalysesCommands { * id, then to a live session, reporting the first step that fails. */ private resolveSelectedSession( - arg: unknown, + arg: ActiveAnalysisCommandArg | undefined, ): { sessionId: string; session: UnifiedAnalysisSession } | undefined { const sessionId = this.extractSessionId(arg); if (!sessionId) { @@ -717,7 +733,7 @@ export class ActiveAnalysesCommands { return { sessionId, session }; } - private extractSessionId(arg?: ActiveAnalysisItem | string | any): string | undefined { + private extractSessionId(arg?: ActiveAnalysisCommandArg): string | undefined { if (typeof arg === 'string') { return arg; } @@ -757,7 +773,7 @@ export class ActiveAnalysesCommands { return undefined; } - private generateDetailsContent(session: any): string { + private generateDetailsContent(session: UnifiedAnalysisSession): string { return `# Analysis Details ## Session Information diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts index df4852ff..f958340a 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts @@ -5,7 +5,9 @@ import * as vscode from 'vscode'; import * as path from 'path'; +import { UnifiedAnalysisSession } from '../../../../engine/core/analysisSession'; import { UnifiedSessionRegistry } from '../../../../engine/core/sessionRegistry'; +import type { CodeAnalysisTreeItem } from '../../../../views/items/analysisItems'; import { getLogger } from '../../../../../core/logging/sink'; const logger = getLogger('ACTIVE_ANALYSES_DATA_SERVICE'); @@ -26,9 +28,19 @@ export interface ActiveAnalysisItem { serverUrl?: string; assignedPort?: number; // Direct session reference for commands - NO MORE COMPLEX TRANSFORMATIONS - session: any; + session: UnifiedAnalysisSession; } +/** + * The session fields copied onto the TreeItem: VS Code passes the TreeItem, + * not the element, to context-menu commands, and they locate the session + * through these. + */ +type ActiveAnalysisTreeItem = vscode.TreeItem & Pick< + ActiveAnalysisItem, + 'sessionId' | 'analysisType' | 'status' | 'targetPath' | 'serverUrl' | 'assignedPort' +>; + /** Icon colour per analysis mode for file targets; legacy mode names included. */ const FILE_ICON_COLORS: Readonly> = { LivePanel: 'charts.green', @@ -144,13 +156,13 @@ export class ActiveAnalysesDataService { // CRITICAL: Add sessionId to the TreeItem so commands can locate the session // VS Code passes the TreeItem object to context menu commands, not the original element - (item as any).sessionId = element.sessionId; - (item as any).id = element.id; - (item as any).analysisType = element.analysisType; - (item as any).status = element.status; - (item as any).targetPath = element.targetPath; - (item as any).serverUrl = element.serverUrl; - (item as any).assignedPort = element.assignedPort; + (item as ActiveAnalysisTreeItem).sessionId = element.sessionId; + (item as ActiveAnalysisTreeItem).id = element.id; + (item as ActiveAnalysisTreeItem).analysisType = element.analysisType; + (item as ActiveAnalysisTreeItem).status = element.status; + (item as ActiveAnalysisTreeItem).targetPath = element.targetPath; + (item as ActiveAnalysisTreeItem).serverUrl = element.serverUrl; + (item as ActiveAnalysisTreeItem).assignedPort = element.assignedPort; logger.debug('Created TreeItem with session info:', { sessionId: element.sessionId, @@ -239,7 +251,7 @@ export class ActiveAnalysesDataService { /** * Create analysis item for tree view */ - private createAnalysisItem(session: any, type: 'file' | 'directory'): ActiveAnalysisItem | null { + private createAnalysisItem(session: UnifiedAnalysisSession, type: 'file' | 'directory'): ActiveAnalysisItem | null { try { if (!session) { logger.warn('Cannot create analysis item - session is null/undefined'); @@ -365,7 +377,7 @@ export class ActiveAnalysesDataService { /** * Get analysis by ID */ - public getAnalysisById(id: string): any | null { + public getAnalysisById(id: string): UnifiedAnalysisSession | undefined | null { try { if (!this.sessionRegistry) { logger.warn('Session registry not initialized'); @@ -439,7 +451,7 @@ export class ActiveAnalysesDataService { /** * Get subsection item for the tree (SIMPLIFIED integration) */ - public getSubsectionItem(): any { + public getSubsectionItem(): CodeAnalysisTreeItem { try { const activeCount = this.getAllActiveAnalyses().length; return { diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index cad26230..931b7a36 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,11 +24,11 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 130, + "any.total": 112, "any.byModule": { "active_servers": 11, "babia_templates": 2, - "code_analysis": 53, + "code_analysis": 35, "commands": 6, "platform": 7, "python_env": 5, @@ -61,7 +61,7 @@ "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 204, + "eslint.maxWarnings": 186, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -70,7 +70,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49508, + "src.lines": 49535, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ @@ -80,10 +80,6 @@ } ], "any.topFiles": [ - { - "file": "src/code_analysis/views/subsections/active_analyses/services/activeAnalysesDataService.ts", - "count": 11 - }, { "file": "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", "count": 9 @@ -92,10 +88,6 @@ "file": "src/code_analysis/services/serverWatcherIntegration.ts", "count": 8 }, - { - "file": "src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts", - "count": 7 - }, { "file": "src/commands/analysis/AnalysisCommands.ts", "count": 5 @@ -139,6 +131,14 @@ { "file": "src/views/babia_examples/interactions/handleBabiaExampleClicks.ts", "count": 3 + }, + { + "file": "src/visualization_settings/storage/settingsStorage.ts", + "count": 3 + }, + { + "file": "src/active_servers/services/serverRegistrar.ts", + "count": 2 } ], "complexity.worst10": [ @@ -206,11 +206,11 @@ "size.largest10": [ { "file": "src/python_env/runtime/venvManager.ts", - "lines": 852 + "lines": 851 }, { "file": "src/code_analysis/views/subsections/active_analyses/commands/activeAnalysesCommands.ts", - "lines": 787 + "lines": 803 }, { "file": "src/code_analysis/export/exportManifest.ts", diff --git a/apps/vscode-extension/test/tooling/lintContract.test.cjs b/apps/vscode-extension/test/tooling/lintContract.test.cjs index a43e1264..085e0b7a 100644 --- a/apps/vscode-extension/test/tooling/lintContract.test.cjs +++ b/apps/vscode-extension/test/tooling/lintContract.test.cjs @@ -30,6 +30,10 @@ const WARN_BUDGET_RULES = [ // Budget rules that reached zero and were promoted to errors (ROADMAP T59). const PROMOTED_RULES = ['@typescript-eslint/no-floating-promises']; +// The flat-config block (by its name) where folders free of `any` make +// no-explicit-any an error (story #56). +const ANY_FREE_BLOCK = 'codexr/any-free-folders'; + async function loadEslintConfig() { const configUrl = pathToFileURL(path.join(projectRoot, 'eslint.config.mjs')).href; return (await import(configUrl)).default; @@ -78,9 +82,13 @@ test('the warn-only budget rules are configured as warnings over src', async () // The type-aware ones live in their own block (they need the TypeScript // program); the merge below follows flat-config order, last block wins. // A budget rule set to "off" would let its count drift while the - // --max-warnings ceiling still looks tight. + // --max-warnings ceiling still looks tight. The any-free folders block is + // the one deliberate exception: it makes no-explicit-any stricter (an + // error) for the folders listed there, never looser. const config = await loadEslintConfig(); - const rules = Object.assign({}, ...config.filter((block) => block.rules).map((block) => block.rules)); + const rules = Object.assign({}, ...config + .filter((block) => block.rules && block.name !== ANY_FREE_BLOCK) + .map((block) => block.rules)); for (const rule of WARN_BUDGET_RULES) { const value = rules[rule]; @@ -244,3 +252,22 @@ test('only the three files with deliberate lazy require() may use it', async () assert.ok(fs.existsSync(path.join(projectRoot, file)), `${file} exists`); } }); + +test('folders typed free of any keep no-explicit-any as an error', async () => { + // Story #56 types the `any`s folder by folder; a folder at zero is locked + // there. The block may only tighten the rule, and every folder it names + // must exist (a moved folder would otherwise drop out of the lock silently). + const config = await loadEslintConfig(); + const blocks = config.filter((block) => block.name === ANY_FREE_BLOCK); + + assert.equal(blocks.length, 1, 'one any-free folders block'); + const [block] = blocks; + assert.deepEqual(Object.keys(block.rules), ['@typescript-eslint/no-explicit-any']); + assert.equal(block.rules['@typescript-eslint/no-explicit-any'], 'error'); + assert.ok(block.files.length > 0); + for (const pattern of block.files) { + assert.match(pattern, /^src\/.+\/\*\*\/\*\.ts$/, `${pattern} is a src/ folder glob`); + const folder = pattern.replace(/\/\*\*\/\*\.ts$/, ''); + assert.ok(fs.statSync(path.join(projectRoot, folder)).isDirectory(), `${folder} exists`); + } +}); From 9c873f6ea7bc8c12705cfbd3d7cb8e565a1fd9b1 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:23:22 +0000 Subject: [PATCH 07/12] refactor(ts): type the any in code_analysis/services MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 8. Types only; the folder's 8 `any`s were all in serverWatcherIntegration.ts: - onRegistryChange((event: any) => ...) -> RegistryEvent (the listener type RegistryChangeEvent already declares). - handleServerRemoved(serverId, server: any) -> ActiveServer (RegistryEvent.server). - getAllSessions().filter((session: any) => ...) -> UnifiedAnalysisSession. - getAllServers().find((server: any) => ...) x3 -> ActiveServer. - findAndStopServerForSession(sessionId, session: any) -> UnifiedAnalysisSession (its caller passes a registry session). - the metadata.sessionId lookup: ActiveServer.metadata does not declare sessionId (the registry stores metadata as given; serverControl.ts reads the same field through `as any`), so a local SessionTaggedServer type adds it as optional for that one predicate instead of widening the model. Both new imports are `import type` (no runtime edge; the active_servers<->code_analysis folder edge already exists). Lock-in: src/code_analysis/services/**/*.ts joins the "codexr/any-free-folders" block (no-explicit-any: error). Text pins: reanalysisArchitecture.test.cjs:16 reads the file and matches stopWatchingSession(sessionId) - G, untouched. guardrail-baseline.json lists it in any.topFiles (removed by guardrails:update). folderDependencies.json mentions the session-closing edge in prose. Measurements: any.total 112 -> 104 (code_analysis 35 -> 27); ESLint warnings and budget 186 -> 178. Characterization: dist-identical 3838d8e16de4 Gates: npm run typecheck, npm run lint, npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 1 + apps/vscode-extension/package.json | 2 +- .../services/serverWatcherIntegration.ts | 27 +++++++++++++------ .../test/tooling/guardrail-baseline.json | 16 +++++------ 4 files changed, 29 insertions(+), 17 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 0f48dd80..ac3ba6c5 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -143,6 +143,7 @@ export default [{ // the list in the commit that brings it to zero. name: "codexr/any-free-folders", files: [ + "src/code_analysis/services/**/*.ts", "src/code_analysis/views/subsections/active_analyses/**/*.ts", ], rules: { diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index ffca4aa2..478001d1 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 186", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 178", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts index 6a703df5..4e80a63f 100644 --- a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts +++ b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts @@ -10,9 +10,20 @@ import { getActiveServerRegistry } from '../../active_servers/registry/activeSer import { ServerControl } from '../../active_servers/runtime/serverControl'; import * as fs from 'fs'; import { getLogger } from '../../core/logging/sink'; +import type { ActiveServer, RegistryEvent } from '../../active_servers/model/activeServerModel'; +import type { UnifiedAnalysisSession } from '../engine/core/analysisSession'; const logger = getLogger('SERVER_WATCHER_INTEGRATION'); +/** + * A server whose registration metadata may name the analysis session it + * serves. The registry stores metadata as given, so the field is read + * optimistically, beyond what ActiveServer declares. + */ +type SessionTaggedServer = ActiveServer & { + metadata?: ActiveServer['metadata'] & { sessionId?: string }; +}; + export class ServerWatcherIntegration { private static instance: ServerWatcherIntegration; private context: vscode.ExtensionContext; @@ -38,7 +49,7 @@ export class ServerWatcherIntegration { private setupServerEventListeners(): void { try { const serverRegistry = getActiveServerRegistry(); - serverRegistry.onRegistryChange((event: any) => { + serverRegistry.onRegistryChange((event: RegistryEvent) => { if (event.type === 'serverRemoved') { void this.handleServerRemoved(event.serverId!, event.server!); } @@ -48,10 +59,10 @@ export class ServerWatcherIntegration { } } - private async handleServerRemoved(serverId: string, server: any): Promise { + private async handleServerRemoved(serverId: string, server: ActiveServer): Promise { try { const sessionRegistry = UnifiedSessionRegistry.getInstance(this.context); - const affectedSessions = sessionRegistry.getAllSessions().filter((session: any) => session.port === server.port); + const affectedSessions = sessionRegistry.getAllSessions().filter((session: UnifiedAnalysisSession) => session.port === server.port); logger.debug(() => `Found ${affectedSessions.length} affected sessions for server ${serverId}`); for (const session of affectedSessions) { @@ -134,7 +145,7 @@ export class ServerWatcherIntegration { private async stopServerByPort(port: number): Promise { try { const serverRegistry = getActiveServerRegistry(); - const serverToStop = serverRegistry.getAllServers().find((server: any) => server.port === port); + const serverToStop = serverRegistry.getAllServers().find((server: ActiveServer) => server.port === port); if (serverToStop) { await ServerControl.stopServer(serverToStop.id); } @@ -143,19 +154,19 @@ export class ServerWatcherIntegration { } } - private async findAndStopServerForSession(sessionId: string, session: any): Promise { + private async findAndStopServerForSession(sessionId: string, session: UnifiedAnalysisSession): Promise { try { const serverRegistry = getActiveServerRegistry(); const servers = serverRegistry.getAllServers(); - let matchingServer = servers.find((server: any) => server.metadata && server.metadata.sessionId === sessionId); + let matchingServer = servers.find((server: SessionTaggedServer) => server.metadata && server.metadata.sessionId === sessionId); if (!matchingServer && session.outputPath) { - matchingServer = servers.find((server: any) => server.htmlFile?.includes(session.outputPath)); + matchingServer = servers.find((server: ActiveServer) => server.htmlFile?.includes(session.outputPath)); } if (!matchingServer) { - matchingServer = servers.find((server: any) => server.customName?.includes('Analysis')); + matchingServer = servers.find((server: ActiveServer) => server.customName?.includes('Analysis')); } if (matchingServer) { diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 931b7a36..6fd62b35 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,11 +24,11 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 112, + "any.total": 104, "any.byModule": { "active_servers": 11, "babia_templates": 2, - "code_analysis": 35, + "code_analysis": 27, "commands": 6, "platform": 7, "python_env": 5, @@ -61,7 +61,7 @@ "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 186, + "eslint.maxWarnings": 178, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -70,7 +70,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49535, + "src.lines": 49546, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ @@ -84,10 +84,6 @@ "file": "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", "count": 9 }, - { - "file": "src/code_analysis/services/serverWatcherIntegration.ts", - "count": 8 - }, { "file": "src/commands/analysis/AnalysisCommands.ts", "count": 5 @@ -139,6 +135,10 @@ { "file": "src/active_servers/services/serverRegistrar.ts", "count": 2 + }, + { + "file": "src/babia_templates/processing/templateProcessor.ts", + "count": 2 } ], "complexity.worst10": [ From d335a1574970472afef52d76d46a2b8c9b9ea3ad Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:25:40 +0000 Subject: [PATCH 08/12] refactor(ts): type the any in code_analysis/engine/watchers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 8. Types only; the folder's 9 `any`s were all in directoryReAnalyzer.ts, and directoryReanalysisData.ts already declares the data.json shapes they stood for: - IncrementalChangeSet.updatedResults, reAnalyzeFiles()'s result, the reanalysisResults / resultsToUpsert locals and applyUpdatedResults' parameter: any[] -> AnalysisFileEntry[] (the entries upsertXRFiles and upsertLivePanelFiles take). - the three `currentData: any` parameters -> a local `AnalysisData = XRAnalysisData | LivePanelAnalysisData`. The helper calls sit in `xrFormat ? xrHelper(...) : livePanelHelper(...)` ternaries that TypeScript cannot narrow through a boolean, so each argument carries an `as XRAnalysisData` / `as LivePanelAnalysisData` matching its branch (8 casts, erased at emit; publishChanges already did the same). - writeJsonAtomically(filePath, data: any) -> data: unknown (it only JSON.stringify's it). AnalysisFileEntry joins the existing import from ./directoryReanalysisData. The lazy require of SSEManager (a cycle breaker, modernization.md §4) stays. Lock-in: src/code_analysis/engine/watchers/**/*.ts joins the "codexr/any-free-folders" block. Text pins: reanalysisArchitecture.test.cjs:31,56-61 reads the file and matches `options: { notifyClients?: boolean } = {}`, `if (options.notifyClients !== false) {`, `fs.promises.readFile(dataJsonPath, 'utf8')`, `writeJsonAtomically(dataJsonPath, currentData)`, `executeFileReanalysis(filesToAnalyze)` and the absence of sync fs - S/G, all still match (none of those lines changed). lintContract.test.cjs pins the file in the no-require-imports exemption (unchanged). directoryReAnalyzer.test.cjs loads out/ (behavioural). Measurements: any.total 104 -> 95 (code_analysis 27 -> 18); ESLint warnings and budget 178 -> 169. Characterization: dist-identical 3838d8e16de4 Gates: npm run typecheck, npm run lint, npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 1 + apps/vscode-extension/package.json | 2 +- .../engine/watchers/directoryReAnalyzer.ts | 36 ++++++++++--------- .../test/tooling/guardrail-baseline.json | 16 ++++----- 4 files changed, 30 insertions(+), 25 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index ac3ba6c5..198b5ce6 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -143,6 +143,7 @@ export default [{ // the list in the commit that brings it to zero. name: "codexr/any-free-folders", files: [ + "src/code_analysis/engine/watchers/**/*.ts", "src/code_analysis/services/**/*.ts", "src/code_analysis/views/subsections/active_analyses/**/*.ts", ], diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 478001d1..1ca191b9 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 178", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 169", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts b/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts index 69e16345..be413b9b 100644 --- a/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts +++ b/apps/vscode-extension/src/code_analysis/engine/watchers/directoryReAnalyzer.ts @@ -12,6 +12,7 @@ import { SessionServerManager } from '../servers/sessionServerManager'; import { SHA256Generator } from '../../../utils/sha256Generator'; import { FileHashTracker } from './fileHashTracker'; import { + AnalysisFileEntry, createEmptyFileEntry, hasMatchingLivePanelFile, hasMatchingXRFile, @@ -29,9 +30,12 @@ import { getLogger } from '../../../core/logging/sink'; const logger = getLogger('DIRECTORY_REANALYZER'); +/** A parsed data.json, in either layout; `xrFormat` says which one. */ +type AnalysisData = XRAnalysisData | LivePanelAnalysisData; + interface IncrementalChangeSet { removedFiles?: string[]; - updatedResults?: any[]; + updatedResults?: AnalysisFileEntry[]; addedFiles?: string[]; } @@ -44,7 +48,7 @@ export class DirectoryReAnalyzer { this.sessionServerManager = new SessionServerManager(context); } - async reAnalyzeFiles(changedFiles: string[]): Promise { + async reAnalyzeFiles(changedFiles: string[]): Promise { try { logger.debug(() => `Re-analyzing ${changedFiles.length} changed files`); const result = await this.executePython.executeFileReanalysis(changedFiles); @@ -151,7 +155,7 @@ export class DirectoryReAnalyzer { } private applyRemovedFiles( - currentData: any, + currentData: AnalysisData, xrFormat: boolean, removedFiles: string[], hashTracker: FileHashTracker, @@ -160,8 +164,8 @@ export class DirectoryReAnalyzer { for (const removedPath of removedFiles) { const removed = xrFormat - ? removeDeletedFileFromXRFormat(currentData, removedPath) - : removeDeletedFileFromLivePanelFormat(currentData, removedPath); + ? removeDeletedFileFromXRFormat(currentData as XRAnalysisData, removedPath) + : removeDeletedFileFromLivePanelFormat(currentData as LivePanelAnalysisData, removedPath); if (removed) { hasChanges = true; @@ -173,18 +177,18 @@ export class DirectoryReAnalyzer { return hasChanges; } - private applyUpdatedResults(currentData: any, xrFormat: boolean, updatedResults: any[]): boolean { + private applyUpdatedResults(currentData: AnalysisData, xrFormat: boolean, updatedResults: AnalysisFileEntry[]): boolean { if (updatedResults.length === 0) { return false; } return xrFormat - ? upsertXRFiles(currentData, updatedResults) - : upsertLivePanelFiles(currentData, updatedResults); + ? upsertXRFiles(currentData as XRAnalysisData, updatedResults) + : upsertLivePanelFiles(currentData as LivePanelAnalysisData, updatedResults); } private async applyAddedFiles( - currentData: any, + currentData: AnalysisData, xrFormat: boolean, session: UnifiedAnalysisSession, addedFiles: string[], @@ -194,8 +198,8 @@ export class DirectoryReAnalyzer { for (const filePath of addedFiles) { const alreadyExists = xrFormat - ? hasMatchingXRFile(currentData, filePath) - : hasMatchingLivePanelFile(currentData, filePath); + ? hasMatchingXRFile(currentData as XRAnalysisData, filePath) + : hasMatchingLivePanelFile(currentData as LivePanelAnalysisData, filePath); if (!alreadyExists) { filesToAnalyze.push(filePath); @@ -206,7 +210,7 @@ export class DirectoryReAnalyzer { return false; } - let reanalysisResults: any[] = []; + let reanalysisResults: AnalysisFileEntry[] = []; try { const results = await this.executePython.executeFileReanalysis(filesToAnalyze); reanalysisResults = Array.isArray(results) ? results : [results]; @@ -214,7 +218,7 @@ export class DirectoryReAnalyzer { logger.error('Error analyzing new files:', error); } - const resultsToUpsert: any[] = []; + const resultsToUpsert: AnalysisFileEntry[] = []; for (const [index, filePath] of filesToAnalyze.entries()) { const result = reanalysisResults[index] && reanalysisResults[index].success !== false ? reanalysisResults[index] @@ -231,9 +235,9 @@ export class DirectoryReAnalyzer { } if (xrFormat) { - upsertXRFiles(currentData, resultsToUpsert); + upsertXRFiles(currentData as XRAnalysisData, resultsToUpsert); } else { - upsertLivePanelFiles(currentData, resultsToUpsert); + upsertLivePanelFiles(currentData as LivePanelAnalysisData, resultsToUpsert); } return true; @@ -248,7 +252,7 @@ export class DirectoryReAnalyzer { } } - private async writeJsonAtomically(filePath: string, data: any): Promise { + private async writeJsonAtomically(filePath: string, data: unknown): Promise { const tempPath = `${filePath}.${process.pid}.${Date.now()}.tmp`; await fs.promises.writeFile(tempPath, JSON.stringify(data, null, 2), 'utf8'); await fs.promises.rename(tempPath, filePath); diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 6fd62b35..52c3dac5 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,11 +24,11 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 104, + "any.total": 95, "any.byModule": { "active_servers": 11, "babia_templates": 2, - "code_analysis": 27, + "code_analysis": 18, "commands": 6, "platform": 7, "python_env": 5, @@ -61,7 +61,7 @@ "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 178, + "eslint.maxWarnings": 169, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -70,7 +70,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49546, + "src.lines": 49550, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ @@ -80,10 +80,6 @@ } ], "any.topFiles": [ - { - "file": "src/code_analysis/engine/watchers/directoryReAnalyzer.ts", - "count": 9 - }, { "file": "src/commands/analysis/AnalysisCommands.ts", "count": 5 @@ -139,6 +135,10 @@ { "file": "src/babia_templates/processing/templateProcessor.ts", "count": 2 + }, + { + "file": "src/code_analysis/engine/parsers/directoryXRParser.ts", + "count": 2 } ], "complexity.worst10": [ From 552825a0d39755ab4c8f7b19bda2e546eb60179d Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:30:44 +0000 Subject: [PATCH 09/12] refactor(ts): type the any in active_servers (model, registry, registrar) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 8. Types only; 9 of the folder's 11 `any`s. The model gains two declarations for what was `any`: - ActiveServerRuntime: the server runtime behind a registration, declared structurally with what the extension calls on it (stop, forceStop, createAuthenticatedBrowserUrl). HttpServer and both HTTPS servers match it (the only producer, multiServerLauncher, passes a ServerInstance). It is structural on purpose: importing ServerInstance from servers/runtime made the model, registry and registrar lose their vscode-free status (dependencyDirection.test.cjs floor 109 -> 105, red), so the model keeps no import at all. - ActiveServerMetadata: the fields read (host, staticRoot, description, sessionId) plus an `unknown` index signature for what the launcher records (serverType, originalPort, portChanged, launcherId, ...). ActiveServer.metadata used to declare only the first three while the registry stored anything. Then: - ActiveServer.serverInstance, registerServer()/registerActiveServer() config.serverInstance, ServerRegistrationConfig.serverInstance: any -> ActiveServerRuntime (4). - the same three configs' metadata: any -> ActiveServerMetadata (3). - serverControl.ts stopInstanceOrForce(serverId, instance: any) -> ActiveServerRuntime; allSessions.forEach((session: any, ...)) -> UnifiedAnalysisSession (import type) (2). - code_analysis/services/serverWatcherIntegration.ts: its local SessionTaggedServer type (added two commits ago because the model lacked sessionId) is now redundant and removed; the predicate takes ActiveServer. Left for the next commit: serverControl.ts's two `(server.metadata as any).sessionId` casts. Typed, `server.metadata && server.metadata.sessionId` is reported by prefer-optional-chain, and `?.` changes the bundle, so it cannot ride in a dist-identical commit. Text pins: no test reads these files as text (activeServerRegistry.test.cjs loads out/); folderDependencies.json mentions serverControl.ts in prose. dependencyDirection.test.cjs (vscode-free floor, folder edges) stays green. Measurements: any.total 95 -> 86 (active_servers 11 -> 2); ESLint warnings and budget 169 -> 160. Characterization: dist-identical 3838d8e16de4 Gates: npm run typecheck, npm run lint, npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/package.json | 2 +- .../active_servers/model/activeServerModel.ts | 33 +++++++++++++++---- .../registry/activeServerRegistry.ts | 10 +++--- .../active_servers/runtime/serverControl.ts | 7 ++-- .../services/serverRegistrar.ts | 6 ++-- .../services/serverWatcherIntegration.ts | 11 +------ .../test/tooling/guardrail-baseline.json | 26 +++++++-------- 7 files changed, 54 insertions(+), 41 deletions(-) diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index 1ca191b9..c4c18457 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 169", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 160", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/active_servers/model/activeServerModel.ts b/apps/vscode-extension/src/active_servers/model/activeServerModel.ts index 51f9a7cf..0e3c2b06 100644 --- a/apps/vscode-extension/src/active_servers/model/activeServerModel.ts +++ b/apps/vscode-extension/src/active_servers/model/activeServerModel.ts @@ -53,14 +53,35 @@ export interface ActiveServer { customName?: string; /** Server instance reference for control operations */ - serverInstance?: any; + serverInstance?: ActiveServerRuntime; /** Additional metadata */ - metadata?: { - host?: string; - staticRoot?: string; - description?: string; - }; + metadata?: ActiveServerMetadata; +} + +/** + * The runtime behind a registered server (HttpServer or one of the HTTPS + * servers). Declared structurally, with only what the extension calls on it, + * so this model stays free of the server runtime and of vscode. + */ +export interface ActiveServerRuntime { + stop(): Promise; + forceStop(): void; + createAuthenticatedBrowserUrl(baseUrl: string): string; +} + +/** + * Registration metadata, stored as given: the fields the extension reads, + * plus whatever the launcher records (serverType, originalPort, portChanged, + * launcherId, ...) and its callers add. + */ +export interface ActiveServerMetadata { + host?: string; + staticRoot?: string; + description?: string; + /** The analysis session the server serves, when the registration names one. */ + sessionId?: string; + [field: string]: unknown; } /** diff --git a/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts b/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts index d7c20f8f..39bb2b54 100644 --- a/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts +++ b/apps/vscode-extension/src/active_servers/registry/activeServerRegistry.ts @@ -1,5 +1,5 @@ import { EventEmitter } from 'events'; -import { ActiveServer, RegistryEvent, RegistryEventType, LaunchMode, CertMode } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, RegistryEvent, RegistryEventType, LaunchMode, CertMode } from '../model/activeServerModel'; import { RemoteAccessState } from '../../remote_access/model/remoteAccessModel'; import { getLogger } from '../../core/logging/sink'; @@ -81,8 +81,8 @@ export class ActiveServerRegistry { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; }): ActiveServer { logger.debug('SERVER: registerServer called with config:', { port: config.port, @@ -343,8 +343,8 @@ export function registerActiveServer(config: { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; }): ActiveServer { return getActiveServerRegistry().registerServer(config); } diff --git a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts index e5aa6de6..401de67b 100644 --- a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts +++ b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts @@ -1,5 +1,6 @@ import * as vscode from 'vscode'; -import { ActiveServer } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerRuntime } from '../model/activeServerModel'; +import type { UnifiedAnalysisSession } from '../../code_analysis/engine/core/analysisSession'; import { getActiveServerRegistry } from '../registry/activeServerRegistry'; import { getPanelManager } from '../services/panelManager'; import { fileToServerMap } from '../../utils/fileToServerMap'; @@ -117,7 +118,7 @@ export class ServerControl { * Await the instance's graceful stop, falling back to a forced socket close * if it hangs or fails. Returns false when the shutdown was not clean. */ - private static async stopInstanceOrForce(serverId: string, instance: any): Promise { + private static async stopInstanceOrForce(serverId: string, instance: ActiveServerRuntime): Promise { let timer: NodeJS.Timeout | undefined; try { await Promise.race([ @@ -220,7 +221,7 @@ export class ServerControl { const allSessions = sessionRegistry.getAllSessions(); logger.debug(() => `DEBUG - Found ${allSessions.length} active analysis sessions`); - allSessions.forEach((session: any, index: number) => { + allSessions.forEach((session: UnifiedAnalysisSession, index: number) => { logger.debug(() => `DEBUG - Session ${index + 1}:`, { id: session.id, targetPath: session.targetPath, diff --git a/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts b/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts index bca0cebd..750586c0 100644 --- a/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts +++ b/apps/vscode-extension/src/active_servers/services/serverRegistrar.ts @@ -1,4 +1,4 @@ -import { ActiveServer, LaunchMode, CertMode } from '../model/activeServerModel'; +import { ActiveServer, ActiveServerMetadata, ActiveServerRuntime, LaunchMode, CertMode } from '../model/activeServerModel'; import { registerActiveServer } from '../registry/activeServerRegistry'; import { getLogger } from '../../core/logging/sink'; @@ -15,8 +15,8 @@ export interface ServerRegistrationConfig { timestamp: number; htmlFile?: string; customName?: string; - serverInstance?: any; - metadata?: any; + serverInstance?: ActiveServerRuntime; + metadata?: ActiveServerMetadata; } /** diff --git a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts index 4e80a63f..24ea4d30 100644 --- a/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts +++ b/apps/vscode-extension/src/code_analysis/services/serverWatcherIntegration.ts @@ -15,15 +15,6 @@ import type { UnifiedAnalysisSession } from '../engine/core/analysisSession'; const logger = getLogger('SERVER_WATCHER_INTEGRATION'); -/** - * A server whose registration metadata may name the analysis session it - * serves. The registry stores metadata as given, so the field is read - * optimistically, beyond what ActiveServer declares. - */ -type SessionTaggedServer = ActiveServer & { - metadata?: ActiveServer['metadata'] & { sessionId?: string }; -}; - export class ServerWatcherIntegration { private static instance: ServerWatcherIntegration; private context: vscode.ExtensionContext; @@ -159,7 +150,7 @@ export class ServerWatcherIntegration { const serverRegistry = getActiveServerRegistry(); const servers = serverRegistry.getAllServers(); - let matchingServer = servers.find((server: SessionTaggedServer) => server.metadata && server.metadata.sessionId === sessionId); + let matchingServer = servers.find((server: ActiveServer) => server.metadata && server.metadata.sessionId === sessionId); if (!matchingServer && session.outputPath) { matchingServer = servers.find((server: ActiveServer) => server.htmlFile?.includes(session.outputPath)); diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 52c3dac5..4735502d 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,9 +24,9 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 95, + "any.total": 86, "any.byModule": { - "active_servers": 11, + "active_servers": 2, "babia_templates": 2, "code_analysis": 18, "commands": 6, @@ -61,7 +61,7 @@ "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 169, + "eslint.maxWarnings": 160, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -70,7 +70,7 @@ }, "informational": { "src.files": 337, - "src.lines": 49550, + "src.lines": 49563, "src.functions": 3338, "src.unreachableLines": 0, "console.topFiles": [ @@ -104,14 +104,6 @@ "file": "src/views/ModularTreeDataProvider.ts", "count": 5 }, - { - "file": "src/active_servers/registry/activeServerRegistry.ts", - "count": 4 - }, - { - "file": "src/active_servers/runtime/serverControl.ts", - "count": 4 - }, { "file": "src/servers/storage/serverSettingsManager.ts", "count": 4 @@ -129,7 +121,7 @@ "count": 3 }, { - "file": "src/active_servers/services/serverRegistrar.ts", + "file": "src/active_servers/runtime/serverControl.ts", "count": 2 }, { @@ -139,6 +131,14 @@ { "file": "src/code_analysis/engine/parsers/directoryXRParser.ts", "count": 2 + }, + { + "file": "src/code_analysis/engine/processors/analysisBootstrap.ts", + "count": 2 + }, + { + "file": "src/code_analysis/engine/servers/serverLaunchOrchestrator.ts", + "count": 2 } ], "complexity.worst10": [ From 12f9599b32726a9c876aa5964f5d18c5f8806af3 Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:32:02 +0000 Subject: [PATCH 10/12] refactor(ts): typed metadata.sessionId lookup in serverControl, lock active_servers MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 rows 8 and 6. The last two `any`s of active_servers: serverControl.ts read the session id through `(server.metadata as any).sessionId`. ActiveServerMetadata (previous commit) declares sessionId, so: if (server.metadata && (server.metadata as any).sessionId) { const sessionId = (server.metadata as any).sessionId; -> if (server.metadata?.sessionId) { const sessionId = server.metadata.sessionId; Once typed, prefer-optional-chain (an error since row 6) reports the `a && a.b` form, so the guard becomes `?.`. metadata is ActiveServerMetadata | undefined (an object or nothing), so in this boolean `if` the two forms take the same branch for every value. H2: dist/extension.js 3838d8e16de4 -> 8a0d706c9537 (-11 B); the only changed statement is that guard (`t.metadata&&t.metadata.sessionId` -> `t.metadata?.sessionId`). Lock-in: src/active_servers/**/*.ts joins the "codexr/any-free-folders" block (no-explicit-any: error). Text pins: none on serverControl.ts (folderDependencies.json prose only). Measurements: any.total 86 -> 84 (active_servers 2 -> 0); complexity.over15 9 -> 8 (ServerControl's session lookup CCN 16 -> 15); ESLint warnings and budget 160 -> 158. Gates: npm run typecheck, npm run lint, npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 1 + apps/vscode-extension/package.json | 2 +- .../active_servers/runtime/serverControl.ts | 4 +-- .../test/tooling/guardrail-baseline.json | 27 +++++++++---------- 4 files changed, 17 insertions(+), 17 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 198b5ce6..3eb37643 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -143,6 +143,7 @@ export default [{ // the list in the commit that brings it to zero. name: "codexr/any-free-folders", files: [ + "src/active_servers/**/*.ts", "src/code_analysis/engine/watchers/**/*.ts", "src/code_analysis/services/**/*.ts", "src/code_analysis/views/subsections/active_analyses/**/*.ts", diff --git a/apps/vscode-extension/package.json b/apps/vscode-extension/package.json index c4c18457..8ba181cb 100644 --- a/apps/vscode-extension/package.json +++ b/apps/vscode-extension/package.json @@ -752,7 +752,7 @@ "typecheck": "node ../../node_modules/typescript/bin/tsc --noEmit --incremental false -p tsconfig.check.json && node ../../node_modules/typescript/bin/tsc --incremental false -p tsconfig.tooling.json", "compile-tests": "node -e \"require('fs').rmSync('out',{recursive:true,force:true})\" && node ../../node_modules/typescript/bin/tsc -p . --outDir out", "watch-tests": "node ../../node_modules/typescript/bin/tsc -p . -w --outDir out", - "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 160", + "lint": "node ../../node_modules/eslint/bin/eslint.js src test scripts templates webpack.config.js eslint.config.mjs --max-warnings 158", "test": "npm run test:basic", "test:basic": "npm run typecheck && npm run lint && npm run compile-tests && npm run test:unit", "test:unit": "node test/runners/run-node-tests.cjs", diff --git a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts index 401de67b..252aebce 100644 --- a/apps/vscode-extension/src/active_servers/runtime/serverControl.ts +++ b/apps/vscode-extension/src/active_servers/runtime/serverControl.ts @@ -234,8 +234,8 @@ export class ServerControl { let associatedSession = null; // Try to find by sessionId in server metadata (when implemented) - if (server.metadata && (server.metadata as any).sessionId) { - const sessionId = (server.metadata as any).sessionId; + if (server.metadata?.sessionId) { + const sessionId = server.metadata.sessionId; logger.debug(() => `DEBUG - Trying to find session by metadata sessionId: ${sessionId}`); associatedSession = sessionRegistry.getSession(sessionId); if (associatedSession) { diff --git a/apps/vscode-extension/test/tooling/guardrail-baseline.json b/apps/vscode-extension/test/tooling/guardrail-baseline.json index 4735502d..7afa2421 100644 --- a/apps/vscode-extension/test/tooling/guardrail-baseline.json +++ b/apps/vscode-extension/test/tooling/guardrail-baseline.json @@ -24,9 +24,8 @@ }, "catch.consoleOnly": 0, "catch.emptyNoComment": 0, - "any.total": 86, + "any.total": 84, "any.byModule": { - "active_servers": 2, "babia_templates": 2, "code_analysis": 18, "commands": 6, @@ -56,12 +55,12 @@ ], "functions.over80Lines": 36, "complexity.over10": 53, - "complexity.over15": 9, + "complexity.over15": 8, "complexity.over20": 0, "complexity.over30": 0, "reachability.unreachable": [], "templates.consoleLog": 31, - "eslint.maxWarnings": 160, + "eslint.maxWarnings": 158, "commands.internalByKind": { "legacy-alias": 2, "programmatic": 2, @@ -120,10 +119,6 @@ "file": "src/visualization_settings/storage/settingsStorage.ts", "count": 3 }, - { - "file": "src/active_servers/runtime/serverControl.ts", - "count": 2 - }, { "file": "src/babia_templates/processing/templateProcessor.ts", "count": 2 @@ -139,6 +134,10 @@ { "file": "src/code_analysis/engine/servers/serverLaunchOrchestrator.ts", "count": 2 + }, + { + "file": "src/code_analysis/engine/utils/executePython.ts", + "count": 2 } ], "complexity.worst10": [ @@ -184,18 +183,18 @@ "function": "updateFromLegacyConfig", "file": "src/servers/storage/serverSettingsManager.ts" }, - { - "ccn": 16, - "lines": 81, - "function": "closeAssociatedAnalysisSession", - "file": "src/active_servers/runtime/serverControl.ts" - }, { "ccn": 16, "lines": 31, "function": "validateConfig", "file": "src/active_servers/services/serverRegistrar.ts" }, + { + "ccn": 15, + "lines": 81, + "function": "closeAssociatedAnalysisSession", + "file": "src/active_servers/runtime/serverControl.ts" + }, { "ccn": 15, "lines": 88, From cd83e65e402e719bfbbbd1d47721386bd08109cb Mon Sep 17 00:00:00 2001 From: Claude Date: Wed, 25 Nov 2026 14:36:05 +0000 Subject: [PATCH 11/12] refactor(ts): ?? for object-typed defaults MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit modernization.md §5 row 9. Report mode first: @typescript-eslint/prefer-nullish-coalescing with ignorePrimitives { string, number, boolean, bigint: true } reports 76 sites in src/. 16 of them are `if (!x) { x = ... }` singleton/lazy-init blocks and one is a `json === undefined ? String(metadata) : json` ternary (whose `??` form would also swallow null); those shapes stay as they are (ignoreIfStatements, ignoreTernaryTests). That leaves 60 `a || b` with an object-typed (object | array | function | Map value) left operand. Converted: 48 of the 60, in 30 files. The proof per line is the type plus the producer: for an object/array/function operand, `||` and `??` differ only when the operand is a falsy non-nullish primitive (0, '', false, NaN), so a conversion is behaviour-neutral when the value can only come from this code: - Map.get / Array.find over values the code itself stored (createChart x2, gitRevisionExportCore x2, gitAnalysisEligibility x2, remoteSessionAuthority x3, screenBroadcastSignalingServer, roomRegistry, roomSharedState x5, sseClientRegistry, fileToServerMap, languageMetadata); - results of the code's own calls typed object | undefined (fileWatcherOrchestrator getStatus(), analysisFeatureHost getAvailability(), httpServer getConnectedParticipants() and onDidChange(), httpsServerBase describeStartError(), ActiveServersSectionProvider, collaborationRoomServer resolveSession(), collaborationSessionApi getConfiguration(), collaborationCommands RemoteAccessManager.getInstance(), projectEvolutionService existingReferences); - optional parameters and fields set by internal callers (analysisCommands refreshCallback, dependencyGraphService request, gitRevisionExportCore options.request, gitAnalysisSessionContext sourceCatalog, autoAnalysisDelay x2, analysisFeatureHost x2, visualizeDataItems state, launcherLivePanel session.filesToHash, exportPackageTransaction manifest sources, remoteAccessManager server.remoteAccess, serverDetailsFormat server.metadata, collaborationRoomServer existingParticipant and peer.session.profile, collaborationSessionApi session.profile, and the three `item.command.arguments || []` in the view click handlers). Not converted (12), each file exempted by a per-file override (rule off): - parsed JSON from a WebSocket client or the analysis bridge, where a malformed 0/''/false must still fall back to `{}`: dependencyGraphBridge.ts:186, projectEvolutionBridge.ts:99,149, collaborationRoomServer.ts:228,231,237,240, roomSharedState.ts:84; - workspace storage / settings updates: visualizeDataState.ts:394, sharedDimensionMappingSettingCore.ts:182 (adapter.getMappings from storage), serverSettingsManager.ts:279; - an S pin: projectEvolutionService.ts:421, where historicalComparison.test.cjs:467 matches /source\.kind === 'workingCopy'\) \|\| null/ verbatim. Relaxing it needs its own characterization commit; left for 1.3.0. Lock-in: @typescript-eslint/prefer-nullish-coalescing is an error over src/ with ignorePrimitives (all), ignoreTernaryTests and ignoreIfStatements, plus the 8-file exemption block; lintContract.test.cjs asserts the rule. Text pins: every converted file was grepped by basename in test/ (16 files read as text by remoteAccessImplementation, virtualScreenRuntime, historicalComparison, livePanelHistorical, dependencyGraph, reanalysisArchitecture, analysisServerCapabilities, xrDataSource, ...); every `\|\|` / `\?\?` regex in those suites was checked against the changed lines: only historicalComparison.test.cjs:467 matched (above, kept). virtualScreenRuntime.test.cjs:414 is an absence check on `room.entities.get(key) || { entityKind, entityId }` (G, still absent). H2: dist/extension.js 8a0d706c9537 -> 983cfe36a26d (+22 B); 43 changed statements carrying the 48 new `??` and nothing else. Gates: npm run typecheck, npm run lint (158 warnings, budget unchanged), npm test 1056/1056, npm run test:analysis (export code touched) green. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- apps/vscode-extension/eslint.config.mjs | 27 +++++++++++++++++++ .../views/interactions/serverDetailsFormat.ts | 2 +- .../processing/placeholders/createChart.ts | 4 +-- .../commands/analysisCommands.ts | 2 +- .../dependencies/dependencyGraphService.ts | 2 +- .../engine/launchers/launcherLivePanel.ts | 2 +- .../watchers/fileWatcherOrchestrator.ts | 2 +- .../export/exportPackageTransaction.ts | 2 +- .../export/gitRevisionExportCore.ts | 6 ++--- .../historical/gitAnalysisEligibility.ts | 4 +-- .../historical/gitAnalysisSessionContext.ts | 2 +- .../historical/projectEvolutionService.ts | 2 +- .../auto_analysis_delay/autoAnalysisDelay.ts | 4 +-- .../collaboration/collaborationCommands.ts | 2 +- .../security/remoteSessionAuthority.ts | 6 ++--- .../services/remoteAccessManager.ts | 2 +- .../runtime/analysis/analysisFeatureHost.ts | 6 ++--- .../screenBroadcastSignalingServer.ts | 2 +- .../collaboration/collaborationRoomServer.ts | 6 ++--- .../collaboration/collaborationSessionApi.ts | 4 +-- .../runtime/collaboration/roomRegistry.ts | 2 +- .../runtime/collaboration/roomSharedState.ts | 10 +++---- .../src/servers/runtime/httpServer.ts | 4 +-- .../src/servers/runtime/httpsServerBase.ts | 2 +- .../servers/runtime/sse/sseClientRegistry.ts | 2 +- .../src/utils/fileToServerMap.ts | 2 +- .../src/utils/languageMetadata.ts | 2 +- .../ActiveServersSectionProvider.ts | 2 +- .../handleVisualizationSettingsClicks.ts | 2 +- .../interactions/handleVisualizeDataClicks.ts | 4 +-- .../items/visualizeDataItems.ts | 2 +- .../test/tooling/lintContract.test.cjs | 1 + 32 files changed, 76 insertions(+), 48 deletions(-) diff --git a/apps/vscode-extension/eslint.config.mjs b/apps/vscode-extension/eslint.config.mjs index 3eb37643..ce5ce528 100644 --- a/apps/vscode-extension/eslint.config.mjs +++ b/apps/vscode-extension/eslint.config.mjs @@ -124,6 +124,33 @@ export default [{ property: "substr", message: "Use slice() (substr is Annex B legacy; slice(start, start + length) for non-negative arguments).", }], + // `??` only where the left operand is object-typed: '' || d and '' ?? d + // differ, and settings or user JSON carry real '', 0 and false values, + // so primitive operands, ternaries and if-assignments are not reported. + "@typescript-eslint/prefer-nullish-coalescing": ["error", { + ignorePrimitives: { string: true, number: true, boolean: true, bigint: true }, + ignoreTernaryTests: true, + ignoreIfStatements: true, + }], + }, +}, { + // Files that keep an object-typed `x || {}` on purpose: the operand is + // parsed JSON from a WebSocket client, the bridge protocol, workspace + // storage or a settings update, where a malformed `0`, `''` or `false` + // must still fall back to the default (modernization.md §7, row 9). + files: [ + // historicalComparison.test.cjs pins `source.kind === 'workingCopy') || null` here (S pin). + "src/code_analysis/historical/projectEvolutionService.ts", + "src/servers/runtime/analysis/dependencyGraphBridge.ts", + "src/servers/runtime/analysis/projectEvolutionBridge.ts", + "src/servers/runtime/collaboration/collaborationRoomServer.ts", + "src/servers/runtime/collaboration/roomSharedState.ts", + "src/servers/storage/serverSettingsManager.ts", + "src/visualize_data/state/visualizeDataState.ts", + "src/code_analysis/views/subsections/analysis_settings/dimension_mapping_shared/sharedDimensionMappingSettingCore.ts", + ], + rules: { + "@typescript-eslint/prefer-nullish-coalescing": "off", }, }, { // The lazy require() calls that stay (modernization.md §4): the eight in diff --git a/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts b/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts index b81193b6..436ae41e 100644 --- a/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts +++ b/apps/vscode-extension/src/active_servers/views/interactions/serverDetailsFormat.ts @@ -18,7 +18,7 @@ export function getServerLabel(server: ActiveServer): string { * Format server details for display */ export function formatServerDetails(server: ActiveServer): string { - const metadata = (server.metadata || {}) as Record; + const metadata = (server.metadata ?? {}) as Record; const remote = server.remoteAccess; const protocol = server.certMode === 'http' ? 'http' : 'https'; const lanUrl = NetworkUtils.getPrimaryExternalUrl(server.port, protocol); diff --git a/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts b/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts index e8c9ca73..8b175898 100644 --- a/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts +++ b/apps/vscode-extension/src/babia_templates/processing/placeholders/createChart.ts @@ -29,7 +29,7 @@ export class CreateChart { // Every chart — boats included — comes from the single canonical // template list; a duplicated boats fallback used to live here and // drifted from the real one. - const chart = chartTemplates.find((candidate) => candidate.id === chartId) || null; + const chart = chartTemplates.find((candidate) => candidate.id === chartId) ?? null; if (!chart) { return { success: false, @@ -216,7 +216,7 @@ export class CreateChart { * Get chart metadata by ID */ public static getChartMetadata(chartId: string): ChartMetadata | null { - return chartTemplates.find(c => c.id === chartId) || null; + return chartTemplates.find(c => c.id === chartId) ?? null; } /** diff --git a/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts b/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts index f4ee7080..0a92587f 100644 --- a/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts +++ b/apps/vscode-extension/src/code_analysis/commands/analysisCommands.ts @@ -37,7 +37,7 @@ export class CodeAnalysisCommands { ): CommandRegistration[] { logger.debug('Collecting all command registrations'); - const defaultRefreshCallback = refreshCallback || (() => { + const defaultRefreshCallback = refreshCallback ?? (() => { logger.debug('Default refresh callback executed'); }); diff --git a/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts b/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts index 7b94da8c..948a7947 100644 --- a/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts +++ b/apps/vscode-extension/src/code_analysis/dependencies/dependencyGraphService.ts @@ -168,7 +168,7 @@ export class DependencyGraphService { onProgress?: (message: string) => void, ): Promise { const session = this.getSession(); - const refreshRequest: DependencyRefreshRequest = request || { + const refreshRequest: DependencyRefreshRequest = request ?? { sourceRevision: 0, changedFiles: [], addedFiles: [], diff --git a/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts b/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts index 63397f20..28251e5d 100644 --- a/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts +++ b/apps/vscode-extension/src/code_analysis/engine/launchers/launcherLivePanel.ts @@ -86,7 +86,7 @@ export class LauncherLivePanel { progress: { process: 20, save: 40, watcherOrServer: 60, serverOrWatcher: 80, done: 100 }, preValidation: async () => { - const files = session.filesToHash || []; + const files = session.filesToHash ?? []; logger.debug(() => `${LOG_PREFIX}: Directory session target path: ${session.targetPath}`); logger.debug(() => `${LOG_PREFIX}: Directory session deep mode: ${session.isDeep ? 'enabled' : 'disabled'}`); logger.debug(() => `${LOG_PREFIX}: Session currently tracks ${files.length} hashed files`); diff --git a/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts b/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts index b83575e1..6095373d 100644 --- a/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts +++ b/apps/vscode-extension/src/code_analysis/engine/watchers/fileWatcherOrchestrator.ts @@ -238,7 +238,7 @@ export class FileWatcherOrchestrator { watcherId: this.watcherId, targetPath: this.session.targetPath, sessionId: this.session.id, - debounceStatus: this.debounceManager?.getStatus() || null, + debounceStatus: this.debounceManager?.getStatus() ?? null, }; } diff --git a/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts b/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts index 9725b657..02e5fa13 100644 --- a/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts +++ b/apps/vscode-extension/src/code_analysis/export/exportPackageTransaction.ts @@ -132,7 +132,7 @@ function collectManifestPayloadUrls(manifest: ExportManifest): Set { } } } - for (const source of manifest.gitData?.references.sources || []) { + for (const source of manifest.gitData?.references.sources ?? []) { urls.add(source.payloadUrl); } if ( diff --git a/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts b/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts index d4258d46..730b7b3a 100644 --- a/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts +++ b/apps/vscode-extension/src/code_analysis/export/gitRevisionExportCore.ts @@ -186,7 +186,7 @@ export async function runGitRevisionExport( options: GitRevisionExportOptions, ): Promise { const { gitService } = deps; - const request: GitRevisionExportRequest = options.request || { + const request: GitRevisionExportRequest = options.request ?? { scope: { kind: 'all' }, performanceProfile: 'balanced', }; @@ -279,7 +279,7 @@ function groupSourcesByCommit( if (source.kind !== 'gitRef' || !source.commitSha) { return; } - const group = bySha.get(source.commitSha) || []; + const group = bySha.get(source.commitSha) ?? []; if (!group.some((existing) => existing.id === source.id)) { group.push(source); } @@ -327,7 +327,7 @@ async function prepareStoreOrCancel( bySha: Map, ): Promise<{ store: PreparedGitRevisionStore } | { outcome: GitExportOutcome }> { try { - const primarySources = Array.from(bySha.keys()).map((sha) => (bySha.get(sha) || [])[0]); + const primarySources = Array.from(bySha.keys()).map((sha) => (bySha.get(sha) ?? [])[0]); return { store: await deps.prepareRevisionStore(primarySources) }; } catch (error) { if (run.options.token?.isCancellationRequested || String(error).includes('git-export-cancelled')) { diff --git a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts index 0a66f88e..da18653b 100644 --- a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts +++ b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisEligibility.ts @@ -153,7 +153,7 @@ export class GitAnalysisSourceCatalog { if (source.kind !== 'gitRef') { continue; } - const group = gitSourcesBySha.get(source.commitSha) || []; + const group = gitSourcesBySha.get(source.commitSha) ?? []; group.push(source); gitSourcesBySha.set(source.commitSha, group); } @@ -178,7 +178,7 @@ export class GitAnalysisSourceCatalog { const cached = source.kind === 'workingCopy' ? workingCopyEligibility : this.deterministicExclusions.get(source.commitSha) - || this.commitEligibility.get(source.commitSha); + ?? this.commitEligibility.get(source.commitSha); if (!cached || cached.usable) { usable.push(source); continue; diff --git a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts index f73596b8..9c14e32f 100644 --- a/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts +++ b/apps/vscode-extension/src/code_analysis/historical/gitAnalysisSessionContext.ts @@ -72,7 +72,7 @@ export class GitAnalysisSessionContext { private readonly policy: GitRevisionAnalysisPolicy, ) { this.ownsSourceCatalog = !sourceCatalog; - this.sourceCatalog = sourceCatalog || new GitAnalysisSourceCatalog( + this.sourceCatalog = sourceCatalog ?? new GitAnalysisSourceCatalog( session.targetType, session.isDeep === true, path.join(session.savedFilesPath || staticRoot, 'data.json'), diff --git a/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts b/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts index 57a0d7ff..e9bf2943 100644 --- a/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts +++ b/apps/vscode-extension/src/code_analysis/historical/projectEvolutionService.ts @@ -395,7 +395,7 @@ export class ProjectEvolutionService { } private async buildAutomaticTimeline(existingReferences?: { sources: ComparisonSource[]; workingTreeDirty: boolean }): Promise { - const references = existingReferences || await this.gitService.listReferences(); + const references = existingReferences ?? await this.gitService.listReferences(); const timeline = await this.gitService.listTimelineSources(TIMELINE_SCAN_LIMIT); const gitTimeline = timeline.length ? timeline diff --git a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts index 5067556d..d6720bf0 100644 --- a/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts +++ b/apps/vscode-extension/src/code_analysis/views/subsections/analysis_settings/auto_analysis_delay/autoAnalysisDelay.ts @@ -61,7 +61,7 @@ export class AutoAnalysisDelaySetting { * Get display text for current delay */ private getDelayDisplayText(delayConfig?: AutoAnalysisDelayConfig): string { - const configToUse = delayConfig || this.currentDelayConfig; + const configToUse = delayConfig ?? this.currentDelayConfig; if (configToUse.type === 'Custom') { const ms = configToUse.customMs || 0; return `Custom: ${ms}ms`; @@ -73,7 +73,7 @@ export class AutoAnalysisDelaySetting { * Get appropriate icon for current delay */ private getDelayIcon(delayConfig?: AutoAnalysisDelayConfig): vscode.ThemeIcon { - const configToUse = delayConfig || this.currentDelayConfig; + const configToUse = delayConfig ?? this.currentDelayConfig; if (configToUse.type === 'RealTime') { return new vscode.ThemeIcon('zap', new vscode.ThemeColor('charts.green')); } else if (configToUse.type === 'Custom') { diff --git a/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts b/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts index ca289cd3..0d37a2d0 100644 --- a/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts +++ b/apps/vscode-extension/src/commands/collaboration/collaborationCommands.ts @@ -29,7 +29,7 @@ export function getCollaborationCommandRegistrations( description: 'Join a remote CodeXR session', handler: async () => { const remoteAccess = RemoteAccessManager.getInstance() - || RemoteAccessManager.initialize(context); + ?? RemoteAccessManager.initialize(context); await remoteAccess.joinInvitation(); }, }, diff --git a/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts b/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts index 1ec2a650..160c894c 100644 --- a/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts +++ b/apps/vscode-extension/src/remote_access/security/remoteSessionAuthority.ts @@ -359,19 +359,19 @@ export class RemoteSessionAuthority { return null; } this.browserTokens.delete(tokenHash); - return this.sessions.get(record.sessionId) || null; + return this.sessions.get(record.sessionId) ?? null; } public resolveCookie(cookieHeader: string | undefined): AuthenticatedCollaborationSession | null { this.cleanup(); const sessionId = this.readCookie(cookieHeader, 'codexr_session'); - return sessionId ? this.sessions.get(sessionId) || null : null; + return sessionId ? this.sessions.get(sessionId) ?? null : null; } public resolveExtensionToken(token: string): AuthenticatedCollaborationSession | null { this.cleanup(); const sessionId = this.extensionTokens.get(this.hash(token)); - return sessionId ? this.sessions.get(sessionId) || null : null; + return sessionId ? this.sessions.get(sessionId) ?? null : null; } public updateExtensionProfile( diff --git a/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts b/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts index b552cf60..ce3041fd 100644 --- a/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts +++ b/apps/vscode-extension/src/remote_access/services/remoteAccessManager.ts @@ -88,7 +88,7 @@ export class RemoteAccessManager implements vscode.Disposable { throw new Error('The active server no longer exists.'); } if (this.shares.has(serverId)) { - return server.remoteAccess || { ...DEFAULT_REMOTE_ACCESS_STATE }; + return server.remoteAccess ?? { ...DEFAULT_REMOTE_ACCESS_STATE }; } const remoteServer = this.asRemoteCapableServer(server); const binaryPath = await this.binaryManager.resolveBinary(true); diff --git a/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts b/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts index ba2e5e31..455c9e4c 100644 --- a/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts +++ b/apps/vscode-extension/src/servers/runtime/analysis/analysisFeatureHost.ts @@ -122,7 +122,7 @@ export class AnalysisFeatureHost { this.config.extensionContext, this.config.analysisSessionId, this.config.staticRoot, - this.gitAnalysisSourceCatalog || undefined, + this.gitAnalysisSourceCatalog ?? undefined, ); this.analysisUpdateSubscription = analysisUpdateEvents.on((event) => { if (event.sessionId !== this.config.analysisSessionId) { @@ -147,7 +147,7 @@ export class AnalysisFeatureHost { this.config.extensionContext, this.config.analysisSessionId, this.config.staticRoot, - this.gitAnalysisSourceCatalog || undefined, + this.gitAnalysisSourceCatalog ?? undefined, ); } @@ -197,7 +197,7 @@ export class AnalysisFeatureHost { enabled: false, reason: 'Project evolution is not available for this server.', }, - dependencyGraph: this.dependencyGraphService?.getAvailability() || { + dependencyGraph: this.dependencyGraphService?.getAvailability() ?? { enabled: false, reason: 'Dependency analysis is not available for this server.', }, diff --git a/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts b/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts index c366f80c..fad13a37 100644 --- a/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts +++ b/apps/vscode-extension/src/servers/runtime/broadcast/screenBroadcastSignalingServer.ts @@ -563,7 +563,7 @@ export class ScreenBroadcastSignalingServer { if (!roomId || !screenId) { return null; } - return this.screens.get(this.getScreenKey(roomId, screenId)) || null; + return this.screens.get(this.getScreenKey(roomId, screenId)) ?? null; } private pruneScreen(roomId: string, screenId: string): void { diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts index 2cd06b78..5a9e1303 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationRoomServer.ts @@ -192,7 +192,7 @@ export class CollaborationRoomServer { const peer: CollaborationPeer = { id: peerId, socket, - session: this.options.resolveSession?.(request) || null, + session: this.options.resolveSession?.(request) ?? null, joinedRoom: false, roomId: null, anonymousDisplayName: '', @@ -329,7 +329,7 @@ export class CollaborationRoomServer { } const role: CollaborationRole = room.participants.size === 0 ? 'host' : 'guest'; - const participant = existingParticipant || { + const participant = existingParticipant ?? { peerId: peer.id, displayName: peer.anonymousDisplayName, identityMode: 'anonymous' as IdentityMode, @@ -344,7 +344,7 @@ export class CollaborationRoomServer { room, peer, participant, - peer.session?.profile || { + peer.session?.profile ?? { identityMode: 'anonymous', customName: '', // A peer with no session (local browser) never chose a colour. diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts index b483f88d..e5f25c0b 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/collaborationSessionApi.ts @@ -85,9 +85,9 @@ export class CollaborationSessionApi { const mapping = fileUri ? fileToServerMap.getServerInfo(fileUri) : null; const activeServerId = mapping?.activeServerId || `port-${this.deps.port}`; const collaborationConfiguration = CollaborationProfileManager.getInstance()?.getConfiguration() - || this.getDefaultCollaborationConfiguration(); + ?? this.getDefaultCollaborationConfiguration(); const session = this.deps.authority.resolveCookie(req.headers.cookie); - const profile = session?.profile || DEFAULT_COLLABORATION_PROFILE; + const profile = session?.profile ?? DEFAULT_COLLABORATION_PROFILE; const { historicalComparison, projectEvolution, dependencyGraph } = await this.deps.getAnalysisAvailability(); diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts b/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts index 4d903d18..b54f5a5f 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/roomRegistry.ts @@ -43,7 +43,7 @@ export class CollaborationRoomRegistry { if (!peer.joinedRoom || !peer.roomId) { return null; } - return this.rooms.get(peer.roomId) || null; + return this.rooms.get(peer.roomId) ?? null; } public broadcast(room: CollaborationRoomState, payload: Record, excludedPeerId?: string): void { diff --git a/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts b/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts index 9163bbd5..dcaccea5 100644 --- a/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts +++ b/apps/vscode-extension/src/servers/runtime/collaboration/roomSharedState.ts @@ -32,7 +32,7 @@ export function upsertAuthoritativeEntity( } const key = getEntityKey(normalized.entityKind, normalized.entityId); const nextEntity = { - ...(room.entities.get(key) || {}), + ...(room.entities.get(key) ?? {}), ...normalized, updatedAt: new Date().toISOString(), }; @@ -88,9 +88,9 @@ export function upsertEntity( } const key = getEntityKey(entity.entityKind, entity.entityId); - const previous = room.entities.get(key) || null; + const previous = room.entities.get(key) ?? null; const nextEntity: SharedEntityState = { - ...(previous || {}), + ...(previous ?? {}), ...entity, entityKind: entity.entityKind, entityId: entity.entityId, @@ -214,9 +214,9 @@ export function updatePresence(context: RoomContext, peer: CollaborationPeer, pa return; } - const previous = room.presence.get(peer.id) || null; + const previous = room.presence.get(peer.id) ?? null; const nextPresence: SharedPresenceState = { - ...(previous || {}), + ...(previous ?? {}), ...payload, ...getParticipantPresence(participant), peerId: peer.id, diff --git a/apps/vscode-extension/src/servers/runtime/httpServer.ts b/apps/vscode-extension/src/servers/runtime/httpServer.ts index f24c28ba..8d4cab99 100644 --- a/apps/vscode-extension/src/servers/runtime/httpServer.ts +++ b/apps/vscode-extension/src/servers/runtime/httpServer.ts @@ -265,7 +265,7 @@ export class HttpServer { } public getConnectedParticipants(): ConnectedParticipantSummary[] { - return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) || []; + return this.collaborationRoomServer?.getConnectedParticipants(this.sessionApi.getCollaborationRoomId()) ?? []; } /** @@ -567,7 +567,7 @@ export class HttpServer { for (const session of sessions) { this.collaborationRoomServer?.updateSessionProfile(session.sessionId, session.profile); } - }) || null; + }) ?? null; this.broadcastSignalingServer = new ScreenBroadcastSignalingServer( server, '/codexr-broadcast', diff --git a/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts b/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts index e5cb98f6..829ddec3 100644 --- a/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts +++ b/apps/vscode-extension/src/servers/runtime/httpsServerBase.ts @@ -214,7 +214,7 @@ export abstract class HttpsServerBase { } else if (error.code === 'EACCES') { reject(new Error(`SERVER: Permission denied. May need to run as administrator for port ${this.config.port}`)); } else { - reject(this.describeStartError(error) || new Error(`SERVER: Failed to start HTTPS server: ${error.message}`)); + reject(this.describeStartError(error) ?? new Error(`SERVER: Failed to start HTTPS server: ${error.message}`)); } } diff --git a/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts b/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts index ea4fd1e0..a150da56 100644 --- a/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts +++ b/apps/vscode-extension/src/servers/runtime/sse/sseClientRegistry.ts @@ -85,7 +85,7 @@ export class SSEClientRegistry { * @returns Array of response objects */ getClients(fileUri: string): http.ServerResponse[] { - return this.clients.get(fileUri) || []; + return this.clients.get(fileUri) ?? []; } /** diff --git a/apps/vscode-extension/src/utils/fileToServerMap.ts b/apps/vscode-extension/src/utils/fileToServerMap.ts index bb3da1d7..c0b225b2 100644 --- a/apps/vscode-extension/src/utils/fileToServerMap.ts +++ b/apps/vscode-extension/src/utils/fileToServerMap.ts @@ -66,7 +66,7 @@ class FileToServerMapping { * @returns ServerInfo or null if not found */ getServerInfo(fileUri: string): ServerInfo | null { - return this.fileToServer.get(fileUri) || null; + return this.fileToServer.get(fileUri) ?? null; } /** diff --git a/apps/vscode-extension/src/utils/languageMetadata.ts b/apps/vscode-extension/src/utils/languageMetadata.ts index cd477fff..9b002e8e 100644 --- a/apps/vscode-extension/src/utils/languageMetadata.ts +++ b/apps/vscode-extension/src/utils/languageMetadata.ts @@ -59,7 +59,7 @@ SupportedLanguages.forEach(lang => { */ export function getLanguageForFile(filePath: string): LanguageInfo | null { const extension = getFileExtension(filePath); - return ExtensionToLanguageMap.get(extension) || null; + return ExtensionToLanguageMap.get(extension) ?? null; } /** diff --git a/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts b/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts index 97bb7efd..7f94985b 100644 --- a/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts +++ b/apps/vscode-extension/src/views/active_servers/ActiveServersSectionProvider.ts @@ -173,7 +173,7 @@ export class ActiveServersSectionProvider implements SectionProvider Date: Wed, 25 Nov 2026 14:38:25 +0000 Subject: [PATCH 12/12] docs(v1.2.1): #56 part B progress and session log MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit docs/cleanup/modernization.md gains §7 "Progress (TypeScript)": before and after per plan row (1, 4-10), the lock-in rule of each, the ESLint budget (204 -> 158) and any.total (130 -> 84) movement, and the remaining `any` offenders for the next pass. It also records that the "left to #35" notes of §1/§4/§5 no longer apply now that #35 has merged. .claude/docs/v1.2.1/sessions/56b-modernize-ts.md: commits, measurements, proofs (H1/H2, byte-identical SSE script output), gates, what was left and why (row 10: no `.then()` qualifies; one S-pinned `|| null`; 11 `||` on external JSON/storage/settings), design notes, quirks and F5 checks. No CHANGELOG line: nothing user-visible. Gates: npm test 1056/1056. Refs #56 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_014FkKt8WKa6XiX4gKgDL8Hu --- .../docs/v1.2.1/sessions/56b-modernize-ts.md | 84 +++++++++++++++++++ docs/cleanup/modernization.md | 19 +++++ 2 files changed, 103 insertions(+) create mode 100644 .claude/docs/v1.2.1/sessions/56b-modernize-ts.md diff --git a/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md b/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md new file mode 100644 index 00000000..9d936154 --- /dev/null +++ b/.claude/docs/v1.2.1/sessions/56b-modernize-ts.md @@ -0,0 +1,84 @@ +# Session log: #56 (part B) — modernize the TypeScript idioms + +Date: 2026-11-25. Branch `claude/project-thread-n2s3q6-modernize-ts`, cut from `origin/v1.2.1` at `a2d92672` (after #35 parts A and B, PRs #61/#63, and #56 part A, PR #62). Story: Code-XR-Project/Code-XR#56 (epic #26). Plan: `docs/cleanup/modernization.md` §5, rows 1 (TypeScript part) and 4–10; the measured before/after table is its §7. Part A (Python and browser runtimes) is `56a-modernize-py-js.md`. + +## Commits + +| Commit | Subject | Plan row | Proof | +|---|---|---|---| +| `3e282b4c` | chore(lint): lock the TypeScript idioms already at zero | 1 | config only | +| `2308d6c0` | refactor(ts): static imports for Node built-ins | 4 | H2 (+802 B: hoisted requires, one `__importStar` helper) | +| `27bfec86` | refactor(ts): slice() instead of substr(), lock includes() and slice() | 5 | H2 (one statement) | +| `9e2506ec` | refactor(ts): optional chaining where it is safe | 6 | H2 (10 sites) | +| `bf60a7a1` | refactor(ts): template literals instead of string concatenation | 7 | H2 (8 sites) + byte-identical SSE script output | +| `55d5c819` | refactor(ts): type the any in code_analysis/views/subsections/active_analyses | 8 | H1 `3838d8e16de4` | +| `9c873f6e` | refactor(ts): type the any in code_analysis/services | 8 | H1 `3838d8e16de4` | +| `d335a157` | refactor(ts): type the any in code_analysis/engine/watchers | 8 | H1 `3838d8e16de4` | +| `552825a0` | refactor(ts): type the any in active_servers (model, registry, registrar) | 8 | H1 `3838d8e16de4` | +| `12f9599b` | refactor(ts): typed metadata.sessionId lookup in serverControl, lock active_servers | 8 + 6 | H2 (one statement) | +| `cd83e65e` | refactor(ts): ?? for object-typed defaults | 9 | H2 (48 `??`, 43 statements) | + +Row 10 has no commit: none of the 24 `.then()` qualifies (see below). + +## Measurements + +| Metric | Before | After | +|---|---:|---:| +| `npm test` | 1053/1053 | 1056/1056 (+3 lint-contract tests) | +| ESLint warning budget (`eslint.maxWarnings`) | 204 | 158 | +| `any.total` (guardrail) | 130 | 84 | +| `complexity.over10` / `over15` | 54 / 9 | 53 / 8 | +| inline `require()` of built-ins | 7 | 0 | +| `substr()` | 1 | 0 | +| typed `prefer-optional-chain` reports | 10 | 0 | +| `prefer-template` reports | 8 | 0 | +| typed `prefer-nullish-coalescing` (`ignorePrimitives` all) | 76 (60 `\|\|`, 15 if-assign, 1 ternary) | 12 `\|\|` kept, in 8 exempted files | +| `dist/extension.js` (production, no source maps) | `b4c1894828cd`, 1,194,230 B | `983cfe36a26d`, 1,194,977 B | + +The bundle grows 747 B in total, all of it from row 4 (the hoisted `require`s rename minifier locals and add TypeScript's `__importStar` helper to `SSEManager`); every other row is neutral or smaller. + +## How the changes were proved + +- **Types-only commits (row 8)**: the production bundle (`CODEXR_NO_SOURCEMAPS=1 npm run package`) is byte-identical to the parent, `3838d8e16de4`, each time. One `any` pair (`serverControl.ts`'s `(server.metadata as any).sessionId`) could not be typed in a dist-identical commit: once typed, `prefer-optional-chain` forces `?.`, so it is its own H2 commit (`12f9599b`). +- **H2 commits**: the minified bundle split on `;` and diffed against the parent; every changed statement is listed in the commit body. +- **Generated HTML (row 7)**: `CreateStructure.getSSEScriptWithNonce` was run from `out/` under the fake vscode, for `xr`, `dom` and `none`, before and after: same length and sha256. +- **`??` (row 9)**: converted only where the left operand is object-typed **and** produced by this code (Map/find over stored objects, internal call results, internal optional parameters). Parsed JSON from WebSocket clients and the analysis bridge, workspace storage and settings updates keep `||`, because a malformed `0`, `''` or `false` must still fall back. +- **Text pins**: every touched file grepped by basename in `test/` and `scripts/`, pins classified in each commit body. Row 9 also checked every `\|\|` / `\?\?` regex of the suites that read the touched files: one S pin found and kept. + +## Gates + +`npm run typecheck`, `npm run lint` and `npm test` after every commit; `npm run test:analysis` after rows 7 (executePython touched) and 9 (export code touched), both green. `guardrails:update` in every commit that moved a metric. + +## Deliberately not done + +- **Row 10 (`await` instead of `.then()`)**: 0 of 24. Every `.then()` is a fire-and-forget user prompt (`void vscode.window.showXMessage(…).then(choice => …)`, 18), the HTTP request handler's `routeRequest(…).then().catch()` (converting needs an async handler, and `HttpServer` is §4 territory), promise caches/queues whose promise is stored, not awaited (`gitTimelineBlobIndex` 2, `gitTimelineBlobAnalyzer` 1, `gitAnalysisEligibility` 2), `void job.then(clear, clear)` in `dependencyGraphService`, or `.then(resolve, reject)` inside a `new Promise` (`cloudflaredBinaryManager`, §4). +- **`projectEvolutionService.ts:421`** keeps `|| null`: `historicalComparison.test.cjs:467` pins `source.kind === 'workingCopy') || null` verbatim (S pin). Relaxing it needs a characterization commit first. +- **The 11 other `||` of row 9** (WebSocket/bridge payloads, storage, settings): not provably free of `''`/`0`/`false` at runtime. +- **The 18 remaining concatenations** of the A.1 row: literal + literal line wraps of long messages; `prefer-template` does not report them and they read better as they are. +- **`a && a.b` left by the script (2)**: `serverWatcherIntegration.ts:151` (`server.metadata && server.metadata.sessionId === sessionId` — not equivalent when `sessionId` is undefined) and `sharedChartTypeSettingCore.ts:103` (not reported by the typed rule). +- **Row 8 beyond 4 folders**: `utils/commandBuilder.ts` (generic `TArgs extends any[]`), `utils/jsonFieldAnalyzer.ts` (`unknown` would need narrowing code, not types), `executePython.ts`'s `PythonPayload = any` and the pinned `parsePythonOutput(…): any` signature, and the rest listed in modernization.md §7. +- §4 items: enums, `new Promise` wrappers, sync `fs` in async functions, `HttpServer.stop()` order, the XR field-schema contract, the 8 lazy requires of the tree provider: untouched. + +## Design notes + +- `ActiveServer.serverInstance` is typed by a structural `ActiveServerRuntime` interface in the model rather than `ServerInstance` from `servers/runtime/serverFactory`: importing the latter (even `import type`) made the model, registry and registrar lose their vscode-free status, and `dependencyDirection.test.cjs`'s floor (109) went red. +- `ActiveServer.metadata` became `ActiveServerMetadata` (the read fields plus `sessionId`, with an `unknown` index signature for what the launcher records). The model used to declare three fields while the registry stored anything. +- The per-folder `no-explicit-any: error` lives in a flat-config block named `codexr/any-free-folders`; the lint contract test excludes that one named block from its "budget rules stay warnings" check and pins it to that single rule over existing `src/` folders. + +## Quirks found (record only, for 1.3.0) + +- `ActiveAnalysesDataService.getSubsectionItem()` returns a plain object where its caller expects a `CodeAnalysisTreeItem`; it type-checks structurally, but it is not an instance. +- `metadata.sessionId` reaches the registry only through the launcher's `additionalMetadata` spread (`serverLaunchOrchestrator.ts` passes `{ sessionId }`), which `ActiveServer.metadata` did not declare until this session; it is now an optional field of `ActiveServerMetadata`. + +## CHANGELOG + +No line: nothing a user can notice. Covered by the existing "Internal improvements" summary. + +## F5 checks for the maintainer + +1. Active Analyses: run a directory analysis (XR and LivePanel); left-click an entry (actions quick pick), Show Details, View in Browser, Export folder, Close Analysis. +2. Stop the analysis server from Active Servers: the analysis is cleaned up and the notification names the port. +3. Edit a file in an analyzed directory: the incremental re-analysis updates the scene/panel (XR and LivePanel), including adding and deleting a file. +4. Active Servers tooltip shows `File: ` for a served HTML file; Open in Browser works on HTTP and HTTPS servers. +5. Collaboration: join a room, transfer host, kick a participant, presenter stop (paths with `?? {}` defaults around them). +6. Visualize Data: pick a chart, a JSON file and map dimensions; the field list shows "N values • Samples: …". diff --git a/docs/cleanup/modernization.md b/docs/cleanup/modernization.md index 3dfc2bf9..47b44431 100644 --- a/docs/cleanup/modernization.md +++ b/docs/cleanup/modernization.md @@ -156,6 +156,25 @@ Landed on `claude/project-thread-n2s3q6-modernize-py-js` (session log `.claude/d Row 2 leaves exactly three places on `typing` generics: `TargetTuple` (a runtime alias, see §3), `utils/xr_field_schema.py` (contract, 9) and `html/html_dom_parser.py` (2), whose `def emit_json_result(result: Dict[str, Any]) -> None:` line `livePanelDomIntegration.test.cjs` pins verbatim (an S pin: relaxing it needs its own characterization commit first, so the file was left whole rather than half-converted). +## 7. Progress (TypeScript) + +Landed on `claude/project-thread-n2s3q6-modernize-ts` (session log `.claude/docs/v1.2.1/sessions/56b-modernize-ts.md`), after #35 merged, so `executePython.ts` and the export files were in scope (the "left to #35" notes in §1, §4 and §5 no longer apply). Counts are from the A.1 script and the typed ESLint rules, on `src/`. Every lock-in lives in one `src/**/*.ts` block of `apps/vscode-extension/eslint.config.mjs`, asserted by `test/tooling/lintContract.test.cjs`; exceptions are per-file overrides there, never `eslint-disable` (suppressions stay 0). + +| Plan row | Idiom × area | Before | After | Lock-in | +|---|---|---:|---:|---| +| 1 (TS part) | `var`, `arguments`, `namespace`, `Function` type | 0 | 0 | `no-var`, `prefer-rest-params`, `@typescript-eslint/no-namespace`, `@typescript-eslint/no-unsafe-function-type` | +| 4 | inline `require()` of Node built-ins | 7 in 3 files (`executePython.ts` had none left after #35) | 0 | `@typescript-eslint/no-require-imports`; off for `ModularTreeDataProvider.ts` (8 lazy, load-bearing) and the two cycle breakers | +| 5 | `substr()` / `indexOf` presence compares | 1 / 0 (the script's 5 "compares" all use the index: `args[indexOf(x) + 1]`, `newline = buf.indexOf('\n')`) | 0 / 0 | `no-restricted-properties` on `substr`, `@typescript-eslint/prefer-includes` | +| 6 | `a && a.b` (typed `prefer-optional-chain`) | 10 in 7 files | 0 | `@typescript-eslint/prefer-optional-chain` | +| 7 | concatenation `prefer-template` reports | 8 in 6 files (script row: 23) | 0 (script row: 18, all literal + literal line wraps) | `prefer-template`. `createStructure.ts`'s SSE script builder checked byte-identical (sha256 of its output for xr/dom/none) | +| 8 | `any` (guardrail `any.total`) | 130 | 84 | `no-explicit-any: error` for the folders at zero (named block `codexr/any-free-folders`): `active_servers`, `code_analysis/engine/watchers`, `code_analysis/services`, `code_analysis/views/subsections/active_analyses` | +| 9 | `x \|\| d` with an object-typed `x` (`prefer-nullish-coalescing`, `ignorePrimitives` all) | 76 reported: 60 `\|\|`, 15 `if (!x) x = …`, 1 ternary | 12 `\|\|` kept on purpose | the rule with `ignorePrimitives` (all), `ignoreTernaryTests`, `ignoreIfStatements`; off for 8 files: parsed WebSocket/bridge JSON (`dependencyGraphBridge`, `projectEvolutionBridge`, `collaborationRoomServer`, `roomSharedState`), storage and settings (`visualizeDataState`, `sharedDimensionMappingSettingCore`, `serverSettingsManager`) and one S pin (`projectEvolutionService.ts:421`, matched by `historicalComparison.test.cjs:467`) | +| 10 | `.then()` where the promise is already returned or awaited | 0 of 24 | 0 | none (no rule without a new plugin). All 24 are fire-and-forget prompts (`void showXMessage(…).then(choice => …)`), the HTTP request handler's `.then().catch()`, promise caches/queues (`gitTimelineBlobIndex`, `gitTimelineBlobAnalyzer`, `gitAnalysisEligibility`), or a resolver inside `new Promise` | + +ESLint warning budget (`eslint.maxWarnings`): 204 → 158, all from `no-explicit-any` warnings that disappeared. `complexity.over10` 54 → 53, `complexity.over15` 9 → 8. + +Row 8 status, for the next pass (re-measure with `npm run guardrails:measure`): the biggest remaining files are `utils/jsonFieldAnalyzer.ts` and `utils/commandBuilder.ts` (5 each; the latter's `TArgs extends any[]` generics need a variance decision, not a rename), `platform/tree/baseInterfaces.ts` 5, `python_env/runtime/venvManager.ts` 5, `views/ModularTreeDataProvider.ts` 5, `commands/analysis/AnalysisCommands.ts` 5, `servers/storage/serverSettingsManager.ts` 4. `executePython.ts` keeps `type PythonPayload = any` and the `parsePythonOutput(…): any` signature that `livePanelDomIntegration.test.cjs` pins verbatim (S pin). + ## Appendix: how to re-run the numbers From the repository root, after `npm ci` (the scripts resolve `typescript` and `acorn` from the workspace). Copy each script to a scratch folder first: they are kept here, not in `scripts/`, because only #56 needs them.