Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.
TypeScript antigravity-skillsbusiness-knowledgeclaude-codeclaude-skillscodebase-analysiscodexcodex-skillsdeveloper-tools-ai-agentgemini-cli-skillskarpathy-llm-wikiknowledge-baseknowledge-graphmemoryopencode-skillspi-agentunderstandcodevibe-coding
feat: add hardened Scala graph support
KumamuKumabcb5a0ddb28d
diff --git a/package.json b/package.jsonindex e7cfefae..c1f805f7 100644--- a/package.json+++ b/package.json@@ -55,6 +55,7 @@"tree-sitter-python","tree-sitter-ruby","tree-sitter-rust",+ "tree-sitter-scala","tree-sitter-typescript"]}diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 4500368b..ab2d85ff 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -99,6 +99,9 @@ importers:tree-sitter-rust:specifier: ^0.24.0version: 0.24.0+ tree-sitter-scala:+ specifier: ^0.24.0+ version: 0.24.0tree-sitter-typescript:specifier: ^0.23.2version: 0.23.2@@ -2915,6 +2918,14 @@ packages:tree-sitter:optional: true+ resolution: {integrity: sha512-vkMuAUrBZ1zZz2XcGDQk18Kz73JkpgaeXzbNVobPke0G35sd9jH32aUxG6OLRKM7et0TbsfqkWf4DeJoGk4K1g==}+ peerDependencies:+ tree-sitter: ^0.21.1+ peerDependenciesMeta:+ tree-sitter:+ optional: true+resolution: {integrity: sha512-e04JUUKxTT53/x3Uq1zIL45DoYKVfHH4CZqwgZhPg5qYROl5nQjV+85ruFzFGZxu+QeFVbRTPDRnqL9UbU4VeA==}peerDependencies:@@ -6304,6 +6315,11 @@ snapshots:node-addon-api: 8.6.0node-gyp-build: 4.8.4+ dependencies:+ node-addon-api: 8.6.0+ node-gyp-build: 4.8.4+dependencies:node-addon-api: 8.6.0diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yamlindex 2ff1c33d..36da254f 100644--- a/pnpm-workspace.yaml+++ b/pnpm-workspace.yaml@@ -16,4 +16,5 @@ allowBuilds:tree-sitter-python: truetree-sitter-ruby: truetree-sitter-rust: true+ tree-sitter-scala: truetree-sitter-typescript: truediff --git a/tests/skill/understand/test_extract_import_map.test.mjs b/tests/skill/understand/test_extract_import_map.test.mjsindex 8e779dae..61b03765 100644--- a/tests/skill/understand/test_extract_import_map.test.mjs+++ b/tests/skill/understand/test_extract_import_map.test.mjs@@ -866,6 +866,153 @@ describe('extract-import-map.mjs — Kotlin resolver', () => {});});+describe('extract-import-map.mjs — Scala resolver', () => {+ let projectRoot;++ afterEach(() => {+ if (projectRoot) {+ rmSync(projectRoot, { recursive: true, force: true });+ projectRoot = null;+ }+ });++ it('resolves plain, selector-list, and package-object imports', () => {+ projectRoot = setupTree({+ 'src/main/scala/com/example/Main.scala':+ `package com.example\n\nimport com.example.foo.Bar\nimport com.example.util.{Helper, Other}\nimport com.example.model._\n\nobject Main\n`,+ 'src/main/scala/com/example/foo/Bar.scala':+ `package com.example.foo\n\nclass Bar\n`,+ 'src/main/scala/com/example/util/Helper.scala':+ `package com.example.util\n\nobject Helper\n`,+ 'src/main/scala/com/example/util/Other.scala':+ `package com.example.util\n\nobject Other\n`,+ 'src/main/scala/com/example/model/package.scala':+ `package com.example\n\npackage object model\n`,+ 'src/main/scala/com/example/model/User.scala':+ `package com.example.model\n\ncase class User(id: Long)\n`,+ 'src/main/scala/com/example/model/Order.scala':+ `package com.example.model\n\ncase class Order(id: Long)\n`,+ });++ const files = [+ { path: 'src/main/scala/com/example/Main.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/foo/Bar.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/util/Helper.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/util/Other.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/model/package.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/model/User.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/model/Order.scala', language: 'scala', fileCategory: 'code' },+ ];++ const result = runScript(projectRoot, { projectRoot, files });++ expect(result.status).toBe(0);+ expect(result.output.importMap['src/main/scala/com/example/Main.scala']).toEqual([+ 'src/main/scala/com/example/foo/Bar.scala',+ 'src/main/scala/com/example/model/Order.scala',+ 'src/main/scala/com/example/model/User.scala',+ 'src/main/scala/com/example/model/package.scala',+ 'src/main/scala/com/example/util/Helper.scala',+ 'src/main/scala/com/example/util/Other.scala',+ ]);+ });++ it('resolves renamed selector imports by original source names', () => {+ projectRoot = setupTree({+ 'src/main/scala/com/example/Main.scala':+ `package com.example\n\nimport com.example.util.{Helper => H, Other as O}\n\nobject Main\n`,+ 'src/main/scala/com/example/util/Helper.scala':+ `package com.example.util\n\nobject Helper\n`,+ 'src/main/scala/com/example/util/Other.scala':+ `package com.example.util\n\nobject Other\n`,+ });++ const result = runScript(projectRoot, {+ projectRoot,+ files: [+ { path: 'src/main/scala/com/example/Main.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/util/Helper.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/util/Other.scala', language: 'scala', fileCategory: 'code' },+ ],+ });++ expect(result.status).toBe(0);+ expect(result.output.importMap['src/main/scala/com/example/Main.scala']).toEqual([+ 'src/main/scala/com/example/util/Helper.scala',+ 'src/main/scala/com/example/util/Other.scala',+ ]);+ });++ it('does not add package.scala when a plain import resolves directly', () => {+ projectRoot = setupTree({+ 'src/main/scala/com/example/Main.scala':+ `package com.example\n\nimport com.example.pkg.Bar\n\nobject Main\n`,+ 'src/main/scala/com/example/pkg/Bar.scala':+ `package com.example.pkg\n\nclass Bar\n`,+ 'src/main/scala/com/example/pkg/package.scala':+ `package com.example\n\npackage object pkg { val defaultTimeout = 30 }\n`,+ });++ const result = runScript(projectRoot, {+ projectRoot,+ files: [+ { path: 'src/main/scala/com/example/Main.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/pkg/Bar.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/pkg/package.scala', language: 'scala', fileCategory: 'code' },+ ],+ });++ expect(result.status).toBe(0);+ expect(result.output.importMap['src/main/scala/com/example/Main.scala']).toEqual([+ 'src/main/scala/com/example/pkg/Bar.scala',+ ]);+ });++ it('resolves imports to .sc Scala script targets', () => {+ projectRoot = setupTree({+ 'src/main/scala/com/example/Main.scala':+ `package com.example\n\nimport com.example.scripts.Task\n\nobject Main\n`,+ 'src/main/scala/com/example/scripts/Task.sc':+ `package com.example.scripts\n\nobject Task\n`,+ });++ const result = runScript(projectRoot, {+ projectRoot,+ files: [+ { path: 'src/main/scala/com/example/Main.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/main/scala/com/example/scripts/Task.sc', language: 'scala', fileCategory: 'code' },+ ],+ });++ expect(result.status).toBe(0);+ expect(result.output.importMap['src/main/scala/com/example/Main.scala']).toEqual([+ 'src/main/scala/com/example/scripts/Task.sc',+ ]);+ });++ it('drops scala external imports (cats.effect, scala.concurrent, etc.)', () => {+ projectRoot = setupTree({+ 'src/app/App.scala':+ `package app\n\nimport cats.effect.IO\nimport scala.concurrent.Future\nimport app.Local\n\nobject App\n`,+ 'src/app/Local.scala':+ `package app\n\nclass Local\n`,+ });++ const result = runScript(projectRoot, {+ projectRoot,+ files: [+ { path: 'src/app/App.scala', language: 'scala', fileCategory: 'code' },+ { path: 'src/app/Local.scala', language: 'scala', fileCategory: 'code' },+ ],+ });++ expect(result.status).toBe(0);+ // cats.effect/scala.concurrent are external (no project file matches);+ // app.Local maps via suffix to src/app/Local.scala.+ expect(result.output.importMap['src/app/App.scala']).toEqual(['src/app/Local.scala']);+ });+});+describe('extract-import-map.mjs — C# resolver', () => {let projectRoot;diff --git a/tests/skill/understand/test_merge_batch_graphs.py b/tests/skill/understand/test_merge_batch_graphs.pyindex 1bda81f9..0c3f5ecd 100644--- a/tests/skill/understand/test_merge_batch_graphs.py+++ b/tests/skill/understand/test_merge_batch_graphs.py@@ -109,6 +109,12 @@ class IsTestPathTests(unittest.TestCase):self.assertTrue(mbg.is_test_path("src/test/kotlin/com/foo/BarTest.kt"))self.assertTrue(mbg.is_test_path("src/test/kotlin/com/foo/BarTests.kt"))+ def test_scala_test_files(self) -> None:+ self.assertTrue(mbg.is_test_path("src/test/scala/com/foo/BarSpec.scala"))+ self.assertTrue(mbg.is_test_path("src/test/scala/com/foo/BarSuite.scala"))+ self.assertTrue(mbg.is_test_path("src/test/scala/com/foo/BarTest.scala"))+ self.assertTrue(mbg.is_test_path("src/test/scala/com/foo/BarTests.scala"))+def test_csharp_test_files(self) -> None:self.assertTrue(mbg.is_test_path("Foo.Tests/BarTests.cs"))self.assertTrue(mbg.is_test_path("Foo.Tests/BarTest.cs"))@@ -206,6 +212,14 @@ class ProductionCandidatesTests(unittest.TestCase):cands = mbg.production_candidates("src/test/kotlin/com/foo/BarTest.kt")self.assertIn("src/main/kotlin/com/foo/Bar.kt", cands)+ def test_scala_sbt_layout(self) -> None:+ cands = mbg.production_candidates("src/test/scala/com/foo/BarSpec.scala")+ self.assertIn("src/main/scala/com/foo/Bar.scala", cands)++ def test_scala_multimodule_sbt_layout(self) -> None:+ cands = mbg.production_candidates("modules/core/src/test/scala/com/foo/BarSpec.scala")+ self.assertIn("modules/core/src/main/scala/com/foo/Bar.scala", cands)+def test_js_ts_test_subdir_walkout(self) -> None:# Some JS/TS projects use `<dir>/test/` or `<dir>/spec/` instead of# the more idiomatic `__tests__/`. Walk out of either.@@ -299,6 +313,54 @@ class LinkTestsTests(unittest.TestCase):# Test node is not tagged with "tested"self.assertNotIn("tested", nodes_by_id["file:src/foo.test.ts"]["tags"])+ def test_scala_sbt_pairing_emits_forward_edge(self) -> None:+ nodes_by_id = {+ "file:src/main/scala/com/foo/Bar.scala": _file_node(+ "src/main/scala/com/foo/Bar.scala",+ ),+ "file:src/test/scala/com/foo/BarSpec.scala": _file_node(+ "src/test/scala/com/foo/BarSpec.scala",+ ),+ }+ edges: list[dict[str, Any]] = []++ added, dropped, tagged, swapped = mbg.link_tests(nodes_by_id, edges)++ self.assertEqual(added, 1)+ self.assertEqual(dropped, 0)+ self.assertEqual(tagged, 1)+ self.assertEqual(swapped, 0)+ self.assertEqual(len(edges), 1)+ self.assertEqual(edges[0]["source"], "file:src/main/scala/com/foo/Bar.scala")+ self.assertEqual(edges[0]["target"], "file:src/test/scala/com/foo/BarSpec.scala")++ def test_scala_multimodule_sbt_pairing_emits_forward_edge(self) -> None:+ nodes_by_id = {+ "file:modules/core/src/main/scala/com/foo/Bar.scala": _file_node(+ "modules/core/src/main/scala/com/foo/Bar.scala",+ ),+ "file:modules/core/src/test/scala/com/foo/BarSpec.scala": _file_node(+ "modules/core/src/test/scala/com/foo/BarSpec.scala",+ ),+ }+ edges: list[dict[str, Any]] = []++ added, dropped, tagged, swapped = mbg.link_tests(nodes_by_id, edges)++ self.assertEqual(added, 1)+ self.assertEqual(dropped, 0)+ self.assertEqual(tagged, 1)+ self.assertEqual(swapped, 0)+ self.assertEqual(len(edges), 1)+ self.assertEqual(+ edges[0]["source"],+ "file:modules/core/src/main/scala/com/foo/Bar.scala",+ )+ self.assertEqual(+ edges[0]["target"],+ "file:modules/core/src/test/scala/com/foo/BarSpec.scala",+ )+def test_no_production_counterpart_no_edge(self) -> None:nodes_by_id = {"file:src/foo.test.ts": _file_node("src/foo.test.ts"),diff --git a/tests/skill/understand/test_scan_project.test.mjs b/tests/skill/understand/test_scan_project.test.mjsindex 9ce7357a..8212d1cb 100644--- a/tests/skill/understand/test_scan_project.test.mjs+++ b/tests/skill/understand/test_scan_project.test.mjs@@ -144,6 +144,21 @@ describe('scan-project.mjs — language detection', () => {expect(byPath(r.output, 'g.swift').language).toBe('swift');});+ it('maps Scala extensions to scala (with .sbt categorized as config)', () => {+ projectRoot = setupTree({+ 'src/main/scala/App.scala': 'object App\n',+ 'scripts/task.sc': 'println(1)\n',+ 'build.sbt': 'name := "demo"\n',+ });+ const r = runScript(projectRoot);+ expect(r.status).toBe(0);+ expect(byPath(r.output, 'src/main/scala/App.scala').language).toBe('scala');+ expect(byPath(r.output, 'src/main/scala/App.scala').fileCategory).toBe('code');+ expect(byPath(r.output, 'scripts/task.sc').language).toBe('scala');+ expect(byPath(r.output, 'build.sbt').language).toBe('scala');+ expect(byPath(r.output, 'build.sbt').fileCategory).toBe('config');+ });+it('maps Ruby, PHP, C, C++ to their language ids', () => {projectRoot = setupTree({'a.rb': 'puts 1\n',diff --git a/understand-anything-plugin/agents/project-scanner.md b/understand-anything-plugin/agents/project-scanner.mdindex 4f066445..d7304cb3 100644--- a/understand-anything-plugin/agents/project-scanner.md+++ b/understand-anything-plugin/agents/project-scanner.md@@ -96,7 +96,7 @@ The script:| `LICENSE` | `code` (exception — not docs) || `Dockerfile`, `Dockerfile.*`, `docker-compose.*`, `compose.yml`/`compose.yaml`, `Makefile`, `Jenkinsfile`, `Procfile`, `Vagrantfile`, `.gitlab-ci.yml`, `.dockerignore`, `.github/workflows/*`, `.circleci/*`, paths in `k8s/` or `kubernetes/`, `*.k8s.yml`/`*.k8s.yaml` | `infra` || `.md`, `.mdx`, `.rst`, `.txt`, `.text` (except `LICENSE`) | `docs` |-| `.yaml`, `.yml`, `.json`, `.jsonc`, `.toml`, `.xml`, `.xsl`, `.xsd`, `.plist`, `.cfg`, `.ini`, `.env`, `.properties`, `.csproj`, `.sln`, `.mod`, `.sum`, `.gradle` | `config` |+| `.yaml`, `.yml`, `.json`, `.jsonc`, `.toml`, `.xml`, `.xsl`, `.xsd`, `.plist`, `.cfg`, `.ini`, `.env`, `.properties`, `.csproj`, `.sln`, `.mod`, `.sum`, `.gradle`, `.sbt` | `config` || `.tf`, `.tfvars` | `infra` || `.sql`, `.graphql`, `.gql`, `.proto`, `.prisma`, `.csv`, `.tsv` | `data` || `.sh`, `.bash`, `.zsh`, `.ps1`, `.psm1`, `.psd1`, `.bat`, `.cmd` | `script` |@@ -157,7 +157,7 @@ Read the output JSON and merge the `importMap` field directly into your final sc**Capture stderr** when you run the bundled script. Any line starting with `Warning:` should be appended to phase warnings — the SKILL.md orchestrator captures these for the final report. The script also writes a one-line summary `extract-import-map: filesScanned=… filesWithImports=… totalEdges=…` on completion; you can ignore that line or surface it as informational.-**Languages supported.** The bundled script natively handles import resolution for: TypeScript, JavaScript (including CJS `require()`), Python (relative + absolute + `__init__.py`), Go (go.mod prefix stripping), Rust (`use crate::`, `use super::`, `use self::`, and `mod x;` declarations), Java, Kotlin, C#, Ruby (`require` + `require_relative`), PHP (composer.json PSR-4 autoload), C, and C++ (`#include` with relative + include/ + src/ probes). Languages outside this set get empty arrays — there is no LLM-based fallback.+**Languages supported.** The bundled script natively handles import resolution for: TypeScript, JavaScript (including CJS `require()`), Python (relative + absolute + `__init__.py`), Go (go.mod prefix stripping), Rust (`use crate::`, `use super::`, `use self::`, and `mod x;` declarations), Java, Kotlin, Scala (dotted FQN + selector lists + package objects), C#, Ruby (`require` + `require_relative`), PHP (composer.json PSR-4 autoload), C, and C++ (`#include` with relative + include/ + src/ probes). Languages outside this set get empty arrays — there is no LLM-based fallback.---@@ -219,7 +219,7 @@ Then assemble the final output JSON:- ALWAYS validate that `totalFiles` matches the actual length of the `files` array.- Trust Step B for file enumeration + language detection + category assignment + line counts + complexity. Trust Step C for `importMap`. Your only synthesis is the `description` field (plus the Step A narrative fields: `name`, `frameworks`, `languages`).- Do NOT re-implement file enumeration, language detection, or category assignment in your discovery script. Use the bundled `scan-project.mjs`. If the table doesn't cover your project type, file an issue rather than ad-hoc handling.-- Do NOT attempt to re-implement import resolution. The bundled `extract-import-map.mjs` handles all 12 supported code languages (TS, JS, Python, Go, Rust, Java, Kotlin, C#, Ruby, PHP, C, C++) deterministically via tree-sitter + per-language resolvers.+- Do NOT attempt to re-implement import resolution. The bundled `extract-import-map.mjs` handles all 13 supported code languages (TS, JS, Python, Go, Rust, Java, Kotlin, Scala, C#, Ruby, PHP, C, C++) deterministically via tree-sitter + per-language resolvers.- Every file MUST have a `fileCategory` field with one of: `code`, `config`, `docs`, `infra`, `data`, `script`, `markup` — `scan-project.mjs` guarantees this; just don't strip it.## Writing Resultsdiff --git a/understand-anything-plugin/package.json b/understand-anything-plugin/package.jsonindex 64df77d1..25e18ce6 100644--- a/understand-anything-plugin/package.json+++ b/understand-anything-plugin/package.json@@ -17,5 +17,23 @@"@types/node": "^22.0.0","typescript": "^5.7.0","vitest": "^3.1.0"+ },+ "pnpm": {+ "onlyBuiltDependencies": [+ "@tree-sitter-grammars/tree-sitter-kotlin",+ "esbuild",+ "tree-sitter-c",+ "tree-sitter-c-sharp",+ "tree-sitter-cpp",+ "tree-sitter-go",+ "tree-sitter-java",+ "tree-sitter-javascript",+ "tree-sitter-php",+ "tree-sitter-python",+ "tree-sitter-ruby",+ "tree-sitter-rust",+ "tree-sitter-scala",+ "tree-sitter-typescript"+ ]}}diff --git a/understand-anything-plugin/packages/core/package.json b/understand-anything-plugin/packages/core/package.jsonindex bc3ac3be..2328da9c 100644--- a/understand-anything-plugin/packages/core/package.json+++ b/understand-anything-plugin/packages/core/package.json@@ -51,6 +51,7 @@"tree-sitter-python": "^0.25.0","tree-sitter-ruby": "^0.23.1","tree-sitter-rust": "^0.24.0",+ "tree-sitter-scala": "^0.24.0","tree-sitter-typescript": "^0.23.2","web-tree-sitter": "^0.26.6","yaml": "^2.8.3",diff --git a/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts b/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.tsindex 7eff12e4..a6606483 100644--- a/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts+++ b/understand-anything-plugin/packages/core/src/__tests__/language-registry.test.ts@@ -49,10 +49,10 @@ describe("LanguageRegistry", () => {});describe("createDefault", () => {- it("registers all 41 built-in language configs", () => {+ it("registers all 42 built-in language configs", () => {const registry = LanguageRegistry.createDefault();const all = registry.getAllLanguages();- expect(all.length).toBe(41);+ expect(all.length).toBe(42);});it("maps all expected extensions", () => {@@ -66,6 +66,7 @@ describe("LanguageRegistry", () => {expect(registry.getByExtension(".php")?.id).toBe("php");expect(registry.getByExtension(".swift")?.id).toBe("swift");expect(registry.getByExtension(".kt")?.id).toBe("kotlin");+ expect(registry.getByExtension(".scala")?.id).toBe("scala");expect(registry.getByExtension(".cs")?.id).toBe("csharp");expect(registry.getByExtension(".cpp")?.id).toBe("cpp");expect(registry.getByExtension(".c")?.id).toBe("c");diff --git a/understand-anything-plugin/packages/core/src/languages/configs/index.ts b/understand-anything-plugin/packages/core/src/languages/configs/index.tsindex 6a949e89..294bfed6 100644--- a/understand-anything-plugin/packages/core/src/languages/configs/index.ts+++ b/understand-anything-plugin/packages/core/src/languages/configs/index.ts@@ -9,6 +9,7 @@ import { rubyConfig } from "./ruby.js";import { phpConfig } from "./php.js";import { swiftConfig } from "./swift.js";import { kotlinConfig } from "./kotlin.js";+import { scalaConfig } from "./scala.js";import { cConfig } from "./c.js";import { cppConfig } from "./cpp.js";import { dartConfig } from "./dart.js";@@ -54,6 +55,7 @@ export const builtinLanguageConfigs: LanguageConfig[] = [phpConfig,swiftConfig,kotlinConfig,+ scalaConfig,luaConfig,cConfig,cppConfig,@@ -100,6 +102,7 @@ export {phpConfig,swiftConfig,kotlinConfig,+ scalaConfig,luaConfig,cConfig,cppConfig,diff --git a/understand-anything-plugin/packages/core/src/languages/configs/scala.ts b/understand-anything-plugin/packages/core/src/languages/configs/scala.tsnew file mode 100644index 00000000..c5f416f4--- /dev/null+++ b/understand-anything-plugin/packages/core/src/languages/configs/scala.ts@@ -0,0 +1,29 @@+import type { LanguageConfig } from "../types.js";++export const scalaConfig = {+ id: "scala",+ displayName: "Scala",+ extensions: [".scala", ".sc"],+ treeSitter: {+ wasmPackage: "tree-sitter-scala",+ wasmFile: "tree-sitter-scala.wasm",+ },+ concepts: [+ "case classes",+ "pattern matching",+ "traits",+ "implicits / given instances",+ "type classes",+ "higher-kinded types",+ "for-comprehensions",+ "effect systems (Cats Effect, ZIO)",+ "companion objects",+ "sealed hierarchies (ADTs)",+ ],+ filePatterns: {+ entryPoints: ["**/Main.scala", "**/App.scala", "**/*Main.scala", "**/*App.scala"],+ barrels: ["**/package.scala"],+ tests: ["*Spec.scala", "*Suite.scala", "*Test.scala", "*Tests.scala"],+ config: ["build.sbt", "build.sc", "build.mill", "project/build.properties"],+ },+} satisfies LanguageConfig;diff --git a/understand-anything-plugin/packages/core/src/plugins/extractors/__tests__/scala-extractor.test.ts b/understand-anything-plugin/packages/core/src/plugins/extractors/__tests__/scala-extractor.test.tsnew file mode 100644index 00000000..a8328317--- /dev/null+++ b/understand-anything-plugin/packages/core/src/plugins/extractors/__tests__/scala-extractor.test.ts@@ -0,0 +1,537 @@+import { describe, it, expect, beforeAll } from "vitest";+import { createRequire } from "node:module";+import { ScalaExtractor } from "../scala-extractor.js";++const require = createRequire(import.meta.url);++let Parser: any;+let Language: any;+let scalaLang: any;++beforeAll(async () => {+ const mod = await import("web-tree-sitter");+ Parser = mod.Parser;+ Language = mod.Language;+ await Parser.init();+ const wasmPath = require.resolve("tree-sitter-scala/tree-sitter-scala.wasm");+ scalaLang = await Language.load(wasmPath);+});++function parse(code: string) {+ const parser = new Parser();+ parser.setLanguage(scalaLang);+ const tree = parser.parse(code);+ const root = tree.rootNode;+ return { tree, parser, root };+}++describe("ScalaExtractor", () => {+ const extractor = new ScalaExtractor();++ it("has correct languageIds", () => {+ expect(extractor.languageIds).toEqual(["scala"]);+ });++ describe("extractStructure - functions", () => {+ it("extracts a Scala 3 top-level function with params and return type", () => {+ const { tree, parser, root } = parse(`def add(a: Int, b: Int): Int = a + b+`);+ const result = extractor.extractStructure(root);++ expect(result.functions).toHaveLength(1);+ expect(result.functions[0].name).toBe("add");+ expect(result.functions[0].params).toEqual(["a", "b"]);+ expect(result.functions[0].returnType).toBe("Int");++ tree.delete();+ parser.delete();+ });++ it("extracts a function with an inferred return type", () => {+ const { tree, parser, root } = parse(`def greet(name: String) = s"hello $name"+`);+ const result = extractor.extractStructure(root);++ expect(result.functions).toHaveLength(1);+ expect(result.functions[0].name).toBe("greet");+ expect(result.functions[0].params).toEqual(["name"]);+ expect(result.functions[0].returnType).toBeUndefined();++ tree.delete();+ parser.delete();+ });++ it("extracts curried and using-clause parameter lists", () => {+ const { tree, parser, root } = parse(+ `def run(a: Int)(b: String)(using ec: scala.concurrent.ExecutionContext): Unit = ()+`,+ );+ const result = extractor.extractStructure(root);++ expect(result.functions).toHaveLength(1);+ expect(result.functions[0].name).toBe("run");+ expect(result.functions[0].params).toContain("a");+ expect(result.functions[0].params).toContain("b");+ expect(result.functions[0].returnType).toBe("Unit");++ tree.delete();+ parser.delete();+ });++ it("extracts an effect-typed function (Cats Effect IO)", () => {+ const { tree, parser, root } = parse(`import cats.effect.IO++def fetchUser(id: Long): IO[Option[String]] = IO.pure(None)+`);+ const result = extractor.extractStructure(root);++ expect(result.functions).toHaveLength(1);+ expect(result.functions[0].name).toBe("fetchUser");+ expect(result.functions[0].returnType).toBe("IO[Option[String]]");++ tree.delete();+ parser.delete();+ });++ it("extracts extension methods as top-level functions", () => {+ const { tree, parser, root } = parse(`extension (s: String)+ def shout: String = s.toUpperCase+`);+ const result = extractor.extractStructure(root);++ expect(result.functions).toHaveLength(1);+ expect(result.functions[0].name).toBe("shout");+ expect(result.functions[0].returnType).toBe("String");++ tree.delete();+ parser.delete();+ });+ });++ describe("extractStructure - classes, traits, objects, enums", () => {+ it("extracts a case class with parameters as properties", () => {+ const { tree, parser, root } = parse(`case class User(id: Long, name: String)+`);+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].name).toBe("User");+ expect(result.classes[0].properties).toEqual(["id", "name"]);+ expect(result.classes[0].methods).toEqual([]);++ tree.delete();+ parser.delete();+ });++ it("treats only val/var constructor params of a regular class as properties", () => {+ const { tree, parser, root } = parse(+ `class Service(val name: String, dep: Int, var counter: Long)+`,+ );+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].properties).toEqual(["name", "counter"]);++ tree.delete();+ parser.delete();+ });++ it("extracts a class with methods and val members", () => {+ const { tree, parser, root } = parse(`class UserService(repo: AnyRef) {+ private val cacheSize: Int = 128++ def getUser(id: Long): Option[String] = None++ private def logAccess(id: Long): Unit = ()+}+`);+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].name).toBe("UserService");+ expect(result.classes[0].methods).toEqual(["getUser", "logAccess"]);+ expect(result.classes[0].properties).toEqual(["cacheSize"]);++ // Methods also land in the top-level functions array+ const names = result.functions.map((f) => f.name);+ expect(names).toEqual(["getUser", "logAccess"]);++ tree.delete();+ parser.delete();+ });++ it("extracts a trait with abstract method declarations", () => {+ const { tree, parser, root } = parse(`trait UserRepo[F[_]] {+ def find(id: Long): F[Option[String]]+}+`);+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].name).toBe("UserRepo");+ expect(result.classes[0].methods).toEqual(["find"]);++ tree.delete();+ parser.delete();+ });++ it("extracts an object and recurses into companion-object ADT members", () => {+ const { tree, parser, root } = parse(`sealed trait Command++object Command {+ final case class Create(name: String) extends Command+ case object Refresh extends Command+}+`);+ const result = extractor.extractStructure(root);++ const names = result.classes.map((c) => c.name);+ expect(names).toContain("Command"); // trait + object entries+ expect(names).toContain("Create");+ expect(names).toContain("Refresh");+ const create = result.classes.find((c) => c.name === "Create")!;+ expect(create.properties).toEqual(["name"]);++ tree.delete();+ parser.delete();+ });++ it("extracts extension methods inside objects", () => {+ const { tree, parser, root } = parse(`object syntax {+ extension (s: String)+ def shout: String = s.toUpperCase+}+`);+ const result = extractor.extractStructure(root);++ const syntax = result.classes.find((c) => c.name === "syntax");+ expect(syntax?.methods).toContain("shout");+ expect(result.functions.map((f) => f.name)).toContain("shout");+ expect(result.exports.map((e) => e.name)).toEqual(+ expect.arrayContaining(["syntax", "shout"]),+ );++ tree.delete();+ parser.delete();+ });++ it("extracts declarations inside braced package clauses", () => {+ const { tree, parser, root } = parse(`package com.example {+ class Foo++ object Bar {+ def run(): Unit = ()+ }+}+`);+ const result = extractor.extractStructure(root);++ expect(result.classes.map((c) => c.name)).toEqual(["Foo", "Bar"]);+ expect(result.functions.map((f) => f.name)).toEqual(["run"]);+ expect(result.exports.map((e) => e.name)).toEqual(+ expect.arrayContaining(["Foo", "run", "Bar"]),+ );++ tree.delete();+ parser.delete();+ });++ it("extracts package objects with their members", () => {+ const { tree, parser, root } = parse(`package com.example++package object syntax {+ val defaultTimeout: Int = 30+ def helper(x: Int): Int = x+}+`);+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].name).toBe("syntax");+ expect(result.classes[0].properties).toEqual(["defaultTimeout"]);+ expect(result.classes[0].methods).toEqual(["helper"]);+ expect(result.functions.map((f) => f.name)).toEqual(["helper"]);+ expect(result.exports.map((e) => e.name)).toEqual(+ expect.arrayContaining(["defaultTimeout", "helper", "syntax"]),+ );++ tree.delete();+ parser.delete();+ });++ it("extracts a Scala 3 enum with its cases as properties", () => {+ const { tree, parser, root } = parse(`enum Color {+ case Red, Green, Blue+}+`);+ const result = extractor.extractStructure(root);++ expect(result.classes).toHaveLength(1);+ expect(result.classes[0].name).toBe("Color");+ expect(result.classes[0].properties).toEqual(["Red", "Green", "Blue"]);++ tree.delete();+ parser.delete();+ });++ });++ describe("extractStructure - imports", () => {+ it("extracts a plain import", () => {+ const { tree, parser, root } = parse(`import cats.effect.IO+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(1);+ expect(result.imports[0].source).toBe("cats.effect.IO");+ expect(result.imports[0].specifiers).toEqual(["IO"]);++ tree.delete();+ parser.delete();+ });++ it("extracts multiple importers from one import declaration", () => {+ const { tree, parser, root } = parse(`import cats.effect.IO, scala.concurrent.Future+import cats.effect.{Resource, ExitCode}, scala.concurrent.duration.*+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(4);+ expect(result.imports.map((i) => i.source)).toEqual([+ "cats.effect.IO",+ "scala.concurrent.Future",+ "cats.effect",+ "scala.concurrent.duration",+ ]);+ expect(result.imports.map((i) => i.specifiers)).toEqual([+ ["IO"],+ ["Future"],+ ["Resource", "ExitCode"],+ ["*"],+ ]);++ tree.delete();+ parser.delete();+ });++ it("extracts a selector-list import", () => {+ const { tree, parser, root } = parse(`import cats.effect.{IO, Resource}+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(1);+ expect(result.imports[0].source).toBe("cats.effect");+ expect(result.imports[0].specifiers).toEqual(["IO", "Resource"]);++ tree.delete();+ parser.delete();+ });++ it("extracts Scala 2 and Scala 3 wildcard imports", () => {+ const { tree, parser, root } = parse(`import cats.syntax.all._+import scala.concurrent.duration.*+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(2);+ expect(result.imports[0].source).toBe("cats.syntax.all");+ expect(result.imports[0].specifiers).toEqual(["*"]);+ expect(result.imports[1].source).toBe("scala.concurrent.duration");+ expect(result.imports[1].specifiers).toEqual(["*"]);++ tree.delete();+ parser.delete();+ });++ it("extracts source names for renamed imports (Scala 2 arrow and Scala 3 as)", () => {+ const { tree, parser, root } = parse(`import cats.effect.{IO => Effect}+import cats.effect.kernel.{Async as AsyncEff}+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(2);+ expect(result.imports[0].specifiers).toEqual(["IO"]);+ expect(result.imports[1].specifiers).toEqual(["Async"]);++ tree.delete();+ parser.delete();+ });++ it("does not treat excluded renamed imports as imported specifiers", () => {+ const { tree, parser, root } = parse(`import cats.effect.{IO, Resource => _, Async as AsyncEff}+`);+ const result = extractor.extractStructure(root);++ expect(result.imports).toHaveLength(1);+ expect(result.imports[0].source).toBe("cats.effect");+ expect(result.imports[0].specifiers).toEqual(["IO", "Async"]);++ tree.delete();+ parser.delete();+ });+ });++ describe("extractStructure - exports and visibility", () => {+ it("treats public declarations as exported and private ones as internal", () => {+ const { tree, parser, root } = parse(`class Api {+ def visible(): Unit = ()+ private def hidden(): Unit = ()+ protected def inherited(): Unit = ()+}++private class Internal+`);+ const result = extractor.extractStructure(root);++ const exported = result.exports.map((e) => e.name);+ expect(exported).toContain("Api");+ expect(exported).toContain("visible");+ expect(exported).toContain("inherited");+ expect(exported).not.toContain("hidden");+ expect(exported).not.toContain("Internal");++ tree.delete();+ parser.delete();+ });++ it("does not export public members inherited from a private outer type", () => {+ const { tree, parser, root } = parse(`private class Internal {+ def leak(): Unit = ()+}+`);+ const result = extractor.extractStructure(root);++ const exported = result.exports.map((e) => e.name);+ expect(exported).not.toContain("Internal");+ expect(exported).not.toContain("leak");++ tree.delete();+ parser.delete();+ });++ it("treats private[scope] as not exported", () => {+ const { tree, parser, root } = parse(`private[service] def helper(): Unit = ()+`);+ const result = extractor.extractStructure(root);++ expect(result.exports.map((e) => e.name)).not.toContain("helper");++ tree.delete();+ parser.delete();+ });++ it("exports Scala 3 top-level vals and given instances", () => {+ const { tree, parser, root } = parse(`val defaultTimeout: Int = 30++given intOrd: Ordering[Int] = Ordering.Int+`);+ const result = extractor.extractStructure(root);++ const exported = result.exports.map((e) => e.name);+ expect(exported).toContain("defaultTimeout");+ expect(exported).toContain("intOrd");++ tree.delete();+ parser.delete();+ });++ it("extracts Scala 3 export declarations", () => {+ const { tree, parser, root } = parse(`export service.{run as start, stop}+export config.defaultTimeout+`);+ const result = extractor.extractStructure(root);++ expect(result.exports.map((e) => e.name)).toEqual([+ "start",+ "stop",+ "defaultTimeout",+ ]);++ tree.delete();+ parser.delete();+ });+ });++ describe("extractCallGraph", () => {+ it("extracts direct and method calls with the enclosing caller", () => {+ const { tree, parser, root } = parse(`object Main {+ def run(args: List[String]): Unit = {+ val svc = helper(args)+ svc.getUser(1L)+ }++ def helper(args: List[String]): AnyRef = null+}+`);+ const entries = extractor.extractCallGraph(root);++ expect(entries).toContainEqual(+ expect.objectContaining({ caller: "run", callee: "helper" }),+ );+ expect(entries).toContainEqual(+ expect.objectContaining({ caller: "run", callee: "getUser" }),+ );++ tree.delete();+ parser.delete();+ });++ it("extracts generic calls and ignores calls outside functions", () => {+ const { tree, parser, root } = parse(`val eager = compute(1)++def caller(): Unit = {+ helper[Int](1)+ IO.pure[String]("x")+}+`);+ const entries = extractor.extractCallGraph(root);++ const callees = entries.map((e) => e.callee);+ expect(callees).toContain("helper");+ expect(callees).toContain("pure");+ // `compute(1)` is not inside a function definition+ expect(callees).not.toContain("compute");++ tree.delete();+ parser.delete();+ });++ it("extracts infix and constructor calls", () => {+ const { tree, parser, root } = parse(`def caller(xs: List[Int]): Unit = {+ xs map println+ val x = new Foo()+}+`);+ const entries = extractor.extractCallGraph(root);++ expect(entries).toContainEqual(+ expect.objectContaining({ caller: "caller", callee: "map" }),+ );+ expect(entries).toContainEqual(+ expect.objectContaining({ caller: "caller", callee: "Foo" }),+ );++ tree.delete();+ parser.delete();+ });++ it("tracks nested for-comprehension style calls (Cats Effect)", () => {+ const { tree, parser, root } = parse(`import cats.effect.IO++def program(): IO[Unit] = {+ IO.println("start").flatMap(_ => IO.println("done"))+}+`);+ const entries = extractor.extractCallGraph(root);++ const callees = entries.map((e) => e.callee);+ expect(callees).toContain("println");+ expect(callees).toContain("flatMap");+ expect(entries.every((e) => e.caller === "program")).toBe(true);++ tree.delete();+ parser.delete();+ });+ });+});diff --git a/understand-anything-plugin/packages/core/src/plugins/extractors/index.ts b/understand-anything-plugin/packages/core/src/plugins/extractors/index.tsindex d4327d7f..ccafe139 100644--- a/understand-anything-plugin/packages/core/src/plugins/extractors/index.ts+++ b/understand-anything-plugin/packages/core/src/plugins/extractors/index.ts@@ -12,6 +12,7 @@ export { CSharpExtractor } from "./csharp-extractor.js";export { DartExtractor } from "./dart-extractor.js";export { KotlinExtractor } from "./kotlin-extractor.js";export { SwiftExtractor } from "./swift-extractor.js";+export { ScalaExtractor } from "./scala-extractor.js";import type { LanguageExtractor } from "./types.js";import { TypeScriptExtractor } from "./typescript-extractor.js";@@ -26,6 +27,7 @@ import { CSharpExtractor } from "./csharp-extractor.js";import { DartExtractor } from "./dart-extractor.js";import { KotlinExtractor } from "./kotlin-extractor.js";import { SwiftExtractor } from "./swift-extractor.js";+import { ScalaExtractor } from "./scala-extractor.js";export const builtinExtractors: LanguageExtractor[] = [new TypeScriptExtractor(),@@ -40,4 +42,5 @@ export const builtinExtractors: LanguageExtractor[] = [new DartExtractor(),new KotlinExtractor(),new SwiftExtractor(),+ new ScalaExtractor(),];diff --git a/understand-anything-plugin/packages/core/src/plugins/extractors/scala-extractor.ts b/understand-anything-plugin/packages/core/src/plugins/extractors/scala-extractor.tsnew file mode 100644index 00000000..4713af63--- /dev/null+++ b/understand-anything-plugin/packages/core/src/plugins/extractors/scala-extractor.ts@@ -0,0 +1,604 @@+import type { StructuralAnalysis, CallGraphEntry } from "../../types.js";+import type { LanguageExtractor, TreeSitterNode } from "./types.js";+import { findChild, findChildren } from "./base-extractor.js";++/** Node types that declare a Scala type (all map to `classes` in the graph). */+const TYPE_DEFINITION_KINDS = new Set([+ "class_definition",+ "trait_definition",+ "object_definition",+ "package_object",+ "enum_definition",+]);++/** Node types that declare a function (with or without a body). */+const FUNCTION_DEFINITION_KINDS = new Set([+ "function_definition",+ "function_declaration",+]);++/** Node types that declare a field/value member. */+const FIELD_DEFINITION_KINDS = new Set([+ "val_definition",+ "var_definition",+ "val_declaration",+ "var_declaration",+]);++/**+ * Extract the access-modifier text (e.g. "private", "private[pkg]") from a+ * declaration's `modifiers` child, or null when no access modifier is present.+ *+ * Scala's default visibility is public, so `null` means the declaration IS+ * exported — callers must treat absence as exported.+ */+function extractAccessModifier(declNode: TreeSitterNode): string | null {+ const modifiers = findChild(declNode, "modifiers");+ if (!modifiers) return null;+ const access = findChild(modifiers, "access_modifier");+ if (!access) return null;+ return access.text;+}++/**+ * Whether a Scala declaration is visible to other files.+ *+ * Default visibility is public, so a declaration with no access modifier+ * counts as exported. Only `private` (including `private[scope]`) opts out;+ * `protected` remains exported in the project-graph sense because it is+ * still resolvable from other files via inheritance.+ */+function isExported(declNode: TreeSitterNode): boolean {+ const access = extractAccessModifier(declNode);+ return access === null || !access.startsWith("private");+}++/**+ * Get the name of a Scala declaration: the first direct `identifier` child+ * (the keyword and optional modifiers precede it, type/value parameters+ * follow it).+ */+function extractDeclarationName(declNode: TreeSitterNode): string | null {+ for (let i = 0; i < declNode.childCount; i++) {+ const child = declNode.child(i);+ if (child && child.type === "identifier") return child.text;+ }+ return null;+}++/**+ * Extract parameter names from a function-like definition. Scala functions+ * may carry several parameter lists (currying / implicit / using clauses):+ * every direct `parameters` child contributes its `parameter` names in order.+ */+function extractParams(declNode: TreeSitterNode): string[] {+ const params: string[] = [];+ for (const paramList of findChildren(declNode, "parameters")) {+ for (const param of findChildren(paramList, "parameter")) {+ const id = findChild(param, "identifier");+ if (id) params.push(id.text);+ }+ }+ return params;+}++/**+ * Extract the declared return type from a function-like definition. The+ * grammar puts the return-type annotation as a direct `:` token followed by+ * a named type node (`def f(x: Int): IO[Unit] = ...`). Returns undefined+ * when the return type is inferred.+ */+function extractReturnType(declNode: TreeSitterNode): string | undefined {+ for (let i = 0; i < declNode.childCount; i++) {+ const child = declNode.child(i);+ if (!child || child.type !== ":") continue;+ for (let j = i + 1; j < declNode.childCount; j++) {+ const next = declNode.child(j);+ if (next && next.isNamed) return next.text;+ }+ }+ return undefined;+}++/**+ * Whether a `class_definition` is a case class (carries a leading `case`+ * keyword token). Case-class parameters are public vals, so they all count+ * as properties.+ */+function isCaseDefinition(declNode: TreeSitterNode): boolean {+ for (let i = 0; i < declNode.childCount; i++) {+ const child = declNode.child(i);+ if (child && child.type === "case") return true;+ if (child && child.type === "identifier") break;+ }+ return false;+}++/**+ * Collect constructor parameters that are properties. For case classes every+ * `class_parameter` is a public val; for regular classes only parameters+ * with an explicit `val` / `var` keyword become fields.+ */+function collectClassParameterProperties(+ declNode: TreeSitterNode,+ properties: string[],+): void {+ const caseClass = isCaseDefinition(declNode);+ for (const paramList of findChildren(declNode, "class_parameters")) {+ for (const param of findChildren(paramList, "class_parameter")) {+ let isProperty = caseClass;+ if (!isProperty) {+ for (let i = 0; i < param.childCount; i++) {+ const child = param.child(i);+ if (child && (child.type === "val" || child.type === "var")) {+ isProperty = true;+ break;+ }+ }+ }+ if (!isProperty) continue;+ const id = findChild(param, "identifier");+ if (id) properties.push(id.text);+ }+ }+}++/**+ * Extract the name of a val/var member. The grammar puts the binding name+ * as a direct `identifier` child (tuple/pattern bindings have no single+ * identifier and are skipped).+ */+function extractFieldName(fieldNode: TreeSitterNode): string | null {+ return extractDeclarationName(fieldNode);+}++/**+ * Scala extractor for tree-sitter structural analysis and call graph+ * extraction. Covers Scala 2 and Scala 3 syntax: classes, case classes,+ * traits, objects, enums, top-level and member functions, extension+ * methods, and the three import shapes (plain, selector list, wildcard).+ */+export class ScalaExtractor implements LanguageExtractor {+ readonly languageIds = ["scala"];++ extractStructure(rootNode: TreeSitterNode): StructuralAnalysis {+ const functions: StructuralAnalysis["functions"] = [];+ const classes: StructuralAnalysis["classes"] = [];+ const imports: StructuralAnalysis["imports"] = [];+ const exports: StructuralAnalysis["exports"] = [];++ this.walkTopLevel(rootNode, functions, classes, imports, exports);++ return { functions, classes, imports, exports };+ }++ extractCallGraph(rootNode: TreeSitterNode): CallGraphEntry[] {+ const entries: CallGraphEntry[] = [];+ const functionStack: string[] = [];++ const walk = (node: TreeSitterNode) => {+ let pushed = false;++ if (node.type === "function_definition") {+ const name = extractDeclarationName(node);+ if (name) {+ functionStack.push(name);+ pushed = true;+ }+ }++ if (functionStack.length > 0) {+ const callee = this.extractCallLikeName(node);+ if (callee) {+ entries.push({+ caller: functionStack[functionStack.length - 1],+ callee,+ lineNumber: node.startPosition.row + 1,+ });+ }+ }++ for (let i = 0; i < node.childCount; i++) {+ const child = node.child(i);+ if (child) walk(child);+ }++ if (pushed) functionStack.pop();+ };++ walk(rootNode);+ return entries;+ }++ // ---- Private helpers ----++ /**+ * Walk the direct children of the compilation unit (or of a braceless+ * `package foo { ... }` / top-level region) and dispatch declarations.+ */+ private walkTopLevel(+ node: TreeSitterNode,+ functions: StructuralAnalysis["functions"],+ classes: StructuralAnalysis["classes"],+ imports: StructuralAnalysis["imports"],+ exports: StructuralAnalysis["exports"],+ ): void {+ for (let i = 0; i < node.childCount; i++) {+ const child = node.child(i);+ if (!child) continue;++ if (child.type === "package_clause") {+ // Package is metadata about this file, not a graph member — but a+ // `package foo { ... }` block nests real declarations underneath.+ this.walkTopLevel(child, functions, classes, imports, exports);+ } else if (child.type === "template_body") {+ // Braced package clauses wrap top-level declarations in a template body.+ this.walkTopLevel(child, functions, classes, imports, exports);+ } else if (child.type === "import_declaration") {+ this.extractImport(child, imports);+ } else if (child.type === "export_declaration") {+ this.extractExportDeclaration(child, exports);+ } else if (FUNCTION_DEFINITION_KINDS.has(child.type)) {+ this.extractFunction(child, functions, exports);+ } else if (TYPE_DEFINITION_KINDS.has(child.type)) {+ this.extractTypeDefinition(child, classes, functions, exports);+ } else if (FIELD_DEFINITION_KINDS.has(child.type)) {+ // Scala 3 top-level val/var+ const name = extractFieldName(child);+ if (name && isExported(child)) {+ exports.push({ name, lineNumber: child.startPosition.row + 1 });+ }+ } else if (child.type === "extension_definition") {+ // Extension methods are surfaced as top-level functions.+ this.extractExtensionDefinition(child, null, functions, exports);+ } else if (child.type === "given_definition") {+ const name = extractDeclarationName(child);+ if (name && isExported(child)) {+ exports.push({ name, lineNumber: child.startPosition.row + 1 });+ }+ }+ }+ }++ private extractFunction(+ declNode: TreeSitterNode,+ functions: StructuralAnalysis["functions"],+ exports: StructuralAnalysis["exports"],+ exportAllowed = true,+ ): void {+ const name = extractDeclarationName(declNode);+ if (!name) return;+ functions.push({+ name,+ lineRange: [declNode.startPosition.row + 1, declNode.endPosition.row + 1],+ params: extractParams(declNode),+ returnType: extractReturnType(declNode),+ });+ if (exportAllowed && isExported(declNode)) {+ exports.push({ name, lineNumber: declNode.startPosition.row + 1 });+ }+ }++ /**+ * Extract a class / trait / object / enum definition. Nested type+ * definitions inside the body (the companion-object ADT idiom:+ * `object Command { case class Create(...) }`) are recursed into and+ * surfaced as their own class entries.+ */+ private extractTypeDefinition(+ declNode: TreeSitterNode,+ classes: StructuralAnalysis["classes"],+ functions: StructuralAnalysis["functions"],+ exports: StructuralAnalysis["exports"],+ exportAllowed = true,+ ): void {+ const name = extractDeclarationName(declNode);+ if (!name) return;++ const properties: string[] = [];+ const methods: string[] = [];+ const memberExportAllowed = exportAllowed && isExported(declNode);++ // 1. Constructor `val`/`var` (and all case-class) parameters.+ collectClassParameterProperties(declNode, properties);++ // 2. Body members, if any (`class Empty` / `case class Point(...)`+ // have no template_body). Enums keep cases in an `enum_body`.+ const body =+ findChild(declNode, "template_body") ?? findChild(declNode, "enum_body");+ if (body) {+ this.collectTemplateBody(+ body,+ methods,+ properties,+ classes,+ functions,+ exports,+ memberExportAllowed,+ );+ }++ classes.push({+ name,+ lineRange: [declNode.startPosition.row + 1, declNode.endPosition.row + 1],+ methods,+ properties,+ });++ if (memberExportAllowed) {+ exports.push({ name, lineNumber: declNode.startPosition.row + 1 });+ }+ }++ /**+ * Walk a `template_body` / `enum_body` and collect member functions and+ * fields. Function entries are added to both the type's `methods` array+ * and the top-level `functions` array (matching the Go / Swift / Kotlin+ * extractor convention).+ */+ private collectTemplateBody(+ body: TreeSitterNode,+ methods: string[],+ properties: string[],+ classes: StructuralAnalysis["classes"],+ functions: StructuralAnalysis["functions"],+ exports: StructuralAnalysis["exports"],+ exportAllowed = true,+ ): void {+ for (let i = 0; i < body.childCount; i++) {+ const member = body.child(i);+ if (!member) continue;++ if (FUNCTION_DEFINITION_KINDS.has(member.type)) {+ const name = extractDeclarationName(member);+ if (!name) continue;+ methods.push(name);+ functions.push({+ name,+ lineRange: [member.startPosition.row + 1, member.endPosition.row + 1],+ params: extractParams(member),+ returnType: extractReturnType(member),+ });+ if (exportAllowed && isExported(member)) {+ exports.push({ name, lineNumber: member.startPosition.row + 1 });+ }+ } else if (FIELD_DEFINITION_KINDS.has(member.type)) {+ const name = extractFieldName(member);+ if (!name) continue;+ properties.push(name);+ if (exportAllowed && isExported(member)) {+ exports.push({ name, lineNumber: member.startPosition.row + 1 });+ }+ } else if (TYPE_DEFINITION_KINDS.has(member.type)) {+ this.extractTypeDefinition(member, classes, functions, exports, exportAllowed);+ } else if (member.type === "extension_definition") {+ this.extractExtensionDefinition(+ member,+ methods,+ functions,+ exports,+ exportAllowed,+ );+ } else if (member.type === "enum_case_definitions") {+ // `case Red, Green` inside an enum body — each case is a property.+ for (let j = 0; j < member.childCount; j++) {+ const enumCase = member.child(j);+ if (!enumCase || !enumCase.isNamed) continue;+ const id = findChild(enumCase, "identifier");+ if (id) properties.push(id.text);+ }+ }+ }+ }++ /**+ * Extract a Scala import. The dotted prefix is a run of direct+ * `identifier` children; the trailing element decides the shape:+ *+ * - `import cats.effect.IO` → source="cats.effect.IO", specifiers=["IO"]+ * - `import cats.effect._` / `.*` → source="cats.effect", specifiers=["*"]+ * - `import a.{B, C => D, E as F}` → source="a", specifiers=["B", "D", "F"]+ */+ private extractImport(+ declNode: TreeSitterNode,+ imports: StructuralAnalysis["imports"],+ ): void {+ const itemChildren: TreeSitterNode[][] = [];+ let current: TreeSitterNode[] = [];++ for (let i = 0; i < declNode.childCount; i++) {+ const child = declNode.child(i);+ if (!child) continue;+ if (child.type === ",") {+ if (current.length > 0) itemChildren.push(current);+ current = [];+ } else if (child.isNamed) {+ current.push(child);+ }+ }+ if (current.length > 0) itemChildren.push(current);++ for (const item of itemChildren) {+ this.extractImportItem(item, declNode.startPosition.row + 1, imports);+ }+ }++ private extractImportItem(+ itemChildren: TreeSitterNode[],+ lineNumber: number,+ imports: StructuralAnalysis["imports"],+ ): void {+ const parts: string[] = [];+ for (const child of itemChildren) {+ if (child.type === "identifier") parts.push(child.text);+ }++ const selectors = itemChildren.find((child) => child.type === "namespace_selectors");+ const wildcard = itemChildren.find((child) => child.type === "namespace_wildcard");++ let source: string;+ let specifiers: string[];++ if (wildcard) {+ if (parts.length === 0) return;+ source = parts.join(".");+ specifiers = ["*"];+ } else if (selectors) {+ if (parts.length === 0) return;+ source = parts.join(".");+ specifiers = this.extractSelectorSpecifiers(selectors);+ if (specifiers.length === 0) specifiers = ["*"];+ } else {+ if (parts.length === 0) return;+ source = parts.join(".");+ specifiers = [parts[parts.length - 1]];+ }++ imports.push({+ source,+ specifiers,+ lineNumber,+ });+ }++ /**+ * Extract the imported names from a `{ ... }` selector list. Renames+ * (`A => B` in Scala 2, `A as B` in Scala 3) surface the source name so+ * file resolution can still probe `A.scala`; excluded `A => _` selectors+ * are skipped. `given` / `*` selectors surface as "*".+ */+ private extractSelectorSpecifiers(selectors: TreeSitterNode): string[] {+ const specifiers: string[] = [];+ for (let i = 0; i < selectors.childCount; i++) {+ const child = selectors.child(i);+ if (!child || !child.isNamed) continue;++ if (child.type === "identifier") {+ specifiers.push(child.text);+ } else if (child.type === "namespace_wildcard") {+ specifiers.push("*");+ } else {+ // Renamed selector (arrow_renamed_identifier / as_renamed_identifier):+ // the source name is the FIRST identifier child.+ if (findChild(child, "wildcard")) continue;+ const ids = findChildren(child, "identifier");+ if (ids.length > 0) specifiers.push(ids[0].text);+ }+ }+ return specifiers;+ }++ private extractExtensionDefinition(+ declNode: TreeSitterNode,+ methods: string[] | null,+ functions: StructuralAnalysis["functions"],+ exports: StructuralAnalysis["exports"],+ exportAllowed = true,+ ): void {+ for (const fn of findChildren(declNode, "function_definition")) {+ const name = extractDeclarationName(fn);+ if (name && methods) methods.push(name);+ this.extractFunction(fn, functions, exports, exportAllowed);+ }+ }++ private extractExportDeclaration(+ declNode: TreeSitterNode,+ exports: StructuralAnalysis["exports"],+ ): void {+ const selectors = findChild(declNode, "namespace_selectors");+ const names = selectors+ ? this.extractExportSelectorNames(selectors)+ : this.extractExportedPathName(declNode);++ for (const name of names) {+ if (name !== "*") {+ exports.push({ name, lineNumber: declNode.startPosition.row + 1 });+ }+ }+ }++ private extractExportSelectorNames(selectors: TreeSitterNode): string[] {+ const names: string[] = [];+ for (let i = 0; i < selectors.childCount; i++) {+ const child = selectors.child(i);+ if (!child || !child.isNamed) continue;++ if (child.type === "identifier") {+ names.push(child.text);+ } else if (child.type === "namespace_wildcard") {+ names.push("*");+ } else if (!findChild(child, "wildcard")) {+ const ids = findChildren(child, "identifier");+ if (ids.length > 0) names.push(ids[ids.length - 1].text);+ }+ }+ return names;+ }++ private extractExportedPathName(declNode: TreeSitterNode): string[] {+ let name: string | null = null;+ for (const id of findChildren(declNode, "identifier")) {+ name = id.text;+ }+ return name ? [name] : [];+ }++ /**+ * Extract the callee name from a Scala `call_expression`. Shapes:+ *+ * foo(...) → identifier "foo"+ * target.method(...) → field_expression whose last identifier is+ * the method name+ * foo[T](...) / x.f[T](…) → generic_function wrapping either shape+ */+ private extractCallLikeName(node: TreeSitterNode): string | null {+ if (node.type === "call_expression") return this.extractCalleeName(node);+ if (node.type === "infix_expression") return this.extractInfixName(node);+ if (node.type === "instance_expression") return this.extractConstructorName(node);+ return null;+ }++ private extractCalleeName(callNode: TreeSitterNode): string | null {+ let target = callNode.child(0);+ if (!target) return null;++ if (target.type === "generic_function") {+ target = target.child(0);+ if (!target) return null;+ }++ if (target.type === "identifier") return target.text;++ if (target.type === "field_expression") {+ let lastIdentifier: string | null = null;+ for (let i = 0; i < target.childCount; i++) {+ const child = target.child(i);+ if (child && child.type === "identifier") {+ lastIdentifier = child.text;+ }+ }+ return lastIdentifier;+ }+ return null;+ }++ private extractInfixName(infixNode: TreeSitterNode): string | null {+ const identifiers: string[] = [];+ for (let i = 0; i < infixNode.childCount; i++) {+ const child = infixNode.child(i);+ if (child && child.type === "identifier") identifiers.push(child.text);+ }+ return identifiers[1] ?? identifiers[0] ?? null;+ }++ private extractConstructorName(instanceNode: TreeSitterNode): string | null {+ for (let i = 0; i < instanceNode.childCount; i++) {+ const child = instanceNode.child(i);+ if (child && (child.type === "type_identifier" || child.type === "identifier")) {+ return child.text;+ }+ }+ return null;+ }+}diff --git a/understand-anything-plugin/packages/core/src/plugins/tree-sitter-plugin.ts b/understand-anything-plugin/packages/core/src/plugins/tree-sitter-plugin.tsindex 65203d25..bfedd7d3 100644--- a/understand-anything-plugin/packages/core/src/plugins/tree-sitter-plugin.ts+++ b/understand-anything-plugin/packages/core/src/plugins/tree-sitter-plugin.ts@@ -23,7 +23,7 @@ type TreeSitterLanguage = import("web-tree-sitter").Language;* and how to load their WASM grammars. Provides deep structural analysis* (functions, classes, imports, exports, call graphs) for all languages* with registered extractors: TypeScript, JavaScript, Python, Go, Rust,- * Java, Ruby, PHP, C/C++, and C#.+ * Java, Ruby, PHP, C/C++, C#, Dart, Kotlin, Swift, and Scala.** Languages without tree-sitter configs are gracefully skipped (the LLM* agent handles analysis for those).diff --git a/understand-anything-plugin/pnpm-lock.yaml b/understand-anything-plugin/pnpm-lock.yamlindex 8cd5f67c..fd4cf753 100644--- a/understand-anything-plugin/pnpm-lock.yaml+++ b/understand-anything-plugin/pnpm-lock.yaml@@ -72,6 +72,9 @@ importers:tree-sitter-rust:specifier: ^0.24.0version: 0.24.0+ tree-sitter-scala:+ specifier: ^0.24.0+ version: 0.24.0tree-sitter-typescript:specifier: ^0.23.2version: 0.23.2@@ -789,6 +792,7 @@ packages:'@ungap/[email protected]':resolution: {integrity: sha512-WmoN8qaIAo7WTYWbAZuG8PYEhn5fkz7dZrqTBZ7dtt//lL2Gwms1IcnQ5yHqjDfX8Ft5j4YzDM23f87zBfDe9g==}+ deprecated: Potential CWE-502 - Update to 1.3.1 or higher'@vitejs/[email protected]':resolution: {integrity: sha512-gUu9hwfWvvEDBBmgtAowQCojwZmJ5mcLn3aufeCsitijs3+f2NsrPtlAWIR6OPiqljl96GVCUbLe0HyqIpVaoA==}@@ -1712,6 +1716,14 @@ packages:tree-sitter:optional: true+ resolution: {integrity: sha512-vkMuAUrBZ1zZz2XcGDQk18Kz73JkpgaeXzbNVobPke0G35sd9jH32aUxG6OLRKM7et0TbsfqkWf4DeJoGk4K1g==}+ peerDependencies:+ tree-sitter: ^0.21.1+ peerDependenciesMeta:+ tree-sitter:+ optional: true+resolution: {integrity: sha512-e04JUUKxTT53/x3Uq1zIL45DoYKVfHH4CZqwgZhPg5qYROl5nQjV+85ruFzFGZxu+QeFVbRTPDRnqL9UbU4VeA==}peerDependencies:@@ -3480,6 +3492,11 @@ snapshots:node-addon-api: 8.7.0node-gyp-build: 4.8.4+ dependencies:+ node-addon-api: 8.7.0+ node-gyp-build: 4.8.4+dependencies:node-addon-api: 8.7.0diff --git a/understand-anything-plugin/pnpm-workspace.yaml b/understand-anything-plugin/pnpm-workspace.yamlindex 19a92f21..fa43b1ad 100644--- a/understand-anything-plugin/pnpm-workspace.yaml+++ b/understand-anything-plugin/pnpm-workspace.yaml@@ -13,4 +13,5 @@ allowBuilds:tree-sitter-python: truetree-sitter-ruby: truetree-sitter-rust: true+ tree-sitter-scala: truetree-sitter-typescript: truediff --git a/understand-anything-plugin/skills/understand/extract-import-map.mjs b/understand-anything-plugin/skills/understand/extract-import-map.mjsindex eda3e0f7..f87f010a 100644--- a/understand-anything-plugin/skills/understand/extract-import-map.mjs+++ b/understand-anything-plugin/skills/understand/extract-import-map.mjs@@ -480,9 +480,12 @@ async function buildResolutionContext(projectRoot, files) {}// Build per-extension suffix indices for dotted-FQN resolvers (Java,- // Kotlin, C#). Indexed once; reused for every import dispatch.+ // Kotlin, Scala, C#). Indexed once; reused for every import dispatch.const javaIndex = buildSuffixIndex(files, p => p.endsWith('.java'));const kotlinIndex = buildSuffixIndex(files, p => p.endsWith('.kt'));+ const scalaFilePredicate = p => p.endsWith('.scala') || p.endsWith('.sc');+ const scalaIndex = buildSuffixIndex(files, scalaFilePredicate);+ const scalaPackageIndex = buildPackageIndex(files, scalaFilePredicate);const csIndex = buildSuffixIndex(files, p => p.endsWith('.cs'));const swiftModuleIndex = buildSwiftModuleIndex(files, swiftResult.targets);@@ -494,6 +497,8 @@ async function buildResolutionContext(projectRoot, files) {goFilesByDir,javaIndex,kotlinIndex,+ scalaIndex,+ scalaPackageIndex,csIndex,swiftModuleIndex,phpAutoloads,@@ -1022,6 +1027,27 @@ function buildSuffixIndex(files, extPredicate) {return idx;}+function buildPackageIndex(files, extPredicate) {+ const idx = new Map();+ for (const f of files) {+ const p = toPosix(f.path);+ if (!extPredicate(p)) continue;+ const dir = dirOf(p);+ if (!dir) continue;++ const parts = dir.split('/');+ for (let i = 0; i < parts.length; i++) {+ const suffix = parts.slice(i).join('/');+ if (!idx.has(suffix)) idx.set(suffix, []);+ idx.get(suffix).push(p);+ }+ }+ for (const arr of idx.values()) {+ arr.sort((a, b) => a.localeCompare(b));+ }+ return idx;+}+const SWIFT_SOURCE_ROOT_DIRS = new Set(['source', 'sources', 'test', 'tests']);const SWIFT_MODULE_CONTAINER_DIRS = new Set(['framework',@@ -1143,6 +1169,84 @@ export function resolveKotlinImport(rawImport, _file, ctx) {return resolveDottedFqn(rawImport, '.kt', ctx.kotlinIndex);}+// ---------------------------------------------------------------------------+// Scala resolver+//+// Scala imports come from the core ScalaExtractor in three shapes:+// - plain: `import com.example.Foo` -> source='com.example.Foo',+// specifiers=['Foo']+// - selector: `import com.example.{A, B}` -> source='com.example',+// specifiers=['A', 'B']+// - wildcard: `import com.example._` / `.*` -> source='com.example',+// specifiers=['*']+//+// The plain source resolves like Java (`com/example/Foo.scala` suffix probe).+// Selector lists probe each specifier under the source package. Scala also+// allows package objects (`com/example/package.scala`) to hold members, so+// the package prefix is additionally probed against `<pkg>/package.scala`.+// Multi-type files (a `model.scala` holding many case classes) can't be+// resolved by name probing — same accepted limitation as Java/Kotlin/C#.+// ---------------------------------------------------------------------------++export function resolveScalaImport(rawImport, specifiers, _file, ctx) {+ const out = new Set();+ const specs = Array.isArray(specifiers) ? specifiers : [];+ const isPlain =+ specs.length === 1 &&+ specs[0] &&+ specs[0] !== '*' &&+ rawImport.endsWith(`.${specs[0]}`);++ if (specs.includes('*')) {+ for (const m of resolveScalaPackage(rawImport, ctx)) out.add(m);+ return [...out].sort((a, b) => a.localeCompare(b));+ }++ if (isPlain) {+ for (const m of resolveScalaDottedFqn(rawImport, ctx)) out.add(m);+ if (out.size === 0) {+ const pkg = rawImport.slice(0, -(specs[0].length + 1));+ for (const m of resolveScalaDottedFqn(`${pkg}.package`, ctx)) out.add(m);+ }+ return [...out].sort((a, b) => a.localeCompare(b));+ }++ let unresolvedSelector = false;+ for (const spec of specs) {+ if (!spec) continue;+ const matches = resolveScalaDottedFqn(`${rawImport}.${spec}`, ctx);+ if (matches.length === 0) unresolvedSelector = true;+ for (const m of matches) out.add(m);+ }++ if (unresolvedSelector) {+ for (const m of resolveScalaDottedFqn(`${rawImport}.package`, ctx)) out.add(m);+ }++ return [...out].sort((a, b) => a.localeCompare(b));+}++function resolveScalaDottedFqn(fqn, ctx) {+ return [+ ...resolveDottedFqn(fqn, '.scala', ctx.scalaIndex),+ ...resolveDottedFqn(fqn, '.sc', ctx.scalaIndex),+ ];+}++function resolveScalaPackage(pkg, ctx) {+ if (!pkg || typeof pkg !== 'string') return [];+ const dirPart = pkg.replace(/\.\*$/, '').replace(/\./g, '/');+ const matches = ctx.scalaPackageIndex.get(dirPart);+ return matches ? [...matches].sort(compareScalaPackageMembers) : [];+}++function compareScalaPackageMembers(a, b) {+ const aPackage = /\/package\.s(?:cala|c)$/.test(a);+ const bPackage = /\/package\.s(?:cala|c)$/.test(b);+ if (dirOf(a) === dirOf(b) && aPackage !== bPackage) return aPackage ? 1 : -1;+ return a.localeCompare(b);+}+// ---------------------------------------------------------------------------// C# resolver//@@ -1639,6 +1743,9 @@ function resolveImport(imp, file, ctx) {if (lang === 'kotlin') {return resolveKotlinImport(src, file, ctx);}+ if (lang === 'scala') {+ return resolveScalaImport(src, imp.specifiers, file, ctx);+ }if (lang === 'csharp') {return resolveCSharpImport(src, file, ctx);}@@ -1803,7 +1910,11 @@ async function main() {}}}- resolved = [...resolvedSet].sort((a, b) => a.localeCompare(b));+ resolved = [...resolvedSet].sort((a, b) =>+ file.language === 'scala'+ ? compareScalaPackageMembers(a, b)+ : a.localeCompare(b),+ );} catch (err) {process.stderr.write(`Warning: extract-import-map: import resolution failed for ${path} ` +diff --git a/understand-anything-plugin/skills/understand/languages/scala.md b/understand-anything-plugin/skills/understand/languages/scala.mdnew file mode 100644index 00000000..8b5ee23f--- /dev/null+++ b/understand-anything-plugin/skills/understand/languages/scala.md@@ -0,0 +1,51 @@+# Scala Language Prompt Snippet++## Key Concepts++- **Case Classes**: Immutable data carriers with auto-generated `equals`, `hashCode`, `copy`, and pattern-matching support+- **Pattern Matching**: `match` expressions destructure ADTs exhaustively; the compiler warns on missing cases for sealed hierarchies+- **Traits**: Interface-plus-implementation mixins; stackable behavior via linearization+- **Implicits / Given Instances**: Scala 2 `implicit` / Scala 3 `given`+`using` provide type-class instances and contextual parameters resolved at compile time+- **Type Classes**: Ad-hoc polymorphism via implicit/given instances (e.g. Cats' `Functor`, `Monad`); look for `F[_]` type parameters+- **Higher-Kinded Types**: Abstraction over type constructors (`F[_]`) — the foundation of tagless-final service definitions+- **For-Comprehensions**: Sugar over `flatMap`/`map` chains; the standard way to sequence effects (`IO`, `Future`, `Either`)+- **Effect Systems**: Cats Effect (`IO`, `Resource`, `Fiber`), ZIO, and FS2 model side effects as composable values run at the "end of the world"+- **Companion Objects**: Singleton paired with a class/trait holding factory methods, type-class instances, and ADT constructors+- **Sealed Hierarchies (ADTs)**: `sealed trait` + case classes/objects model closed sums; enums in Scala 3++## Import Patterns++- `import package.ClassName` — import a specific member+- `import package.{A, B}` — selector list importing several members+- `import package._` (Scala 2) / `import package.*` (Scala 3) — wildcard import+- `import package.{Name => Alias}` (Scala 2) / `import package.Name as Alias` (Scala 3) — rename on import+- `import cats.syntax.all._` — syntax-extension imports that enable extension methods (common in Typelevel code)++## File Patterns++- `build.sbt` — sbt build definition; `project/` holds build support code+- `build.sc` / `build.mill` — Mill build definition+- `Main.scala` / `*App.scala` — entry points (`object ... extends IOApp` for Cats Effect, `extends App`/`@main` otherwise)+- `package.scala` — package object holding package-level members (Scala 2 idiom)+- `src/main/scala/` — main source root following sbt conventions+- `src/test/scala/` — test source root; specs conventionally end in `*Spec.scala` / `*Suite.scala`++## Common Frameworks++- **Cats Effect** — pure functional runtime with `IO`, `Resource`, and fiber-based concurrency+- **ZIO** — effect system with typed errors and environment (`ZIO[R, E, A]`)+- **Akka / Pekko** — actor-based concurrency, streaming, and clustering+- **Play Framework** — full-stack MVC web framework+- **http4s** — pure functional HTTP server/client built on Cats Effect and FS2+- **Spark** — distributed data processing; look for `Dataset`/`DataFrame` transformations++## Example Language Notes++> Defines the service as a tagless-final trait `UserRepo[F[_]]` so the same+> business logic runs against `IO` in production and a state monad in tests.+> Given/implicit instances in the companion object wire the production+> implementation.+>+> Uses a sealed trait `Command` with case-class variants matched exhaustively+> in the interpreter — the compiler flags any unhandled command when a new+> variant is added.diff --git a/understand-anything-plugin/skills/understand/merge-batch-graphs.py b/understand-anything-plugin/skills/understand/merge-batch-graphs.pyindex 2021f9ae..9f99fdd3 100644--- a/understand-anything-plugin/skills/understand/merge-batch-graphs.py+++ b/understand-anything-plugin/skills/understand/merge-batch-graphs.py@@ -99,6 +99,7 @@ _TEST_NAME_PATTERNS: dict[str, tuple[tuple[str, ...], tuple[str, ...]]] = {".py": (("test_",), ("_test",)),".java": ((), ("Test", "Tests", "IT")),".kt": ((), ("Test", "Tests")),+ ".scala": ((), ("Spec", "Suite", "Test", "Tests")),".cs": ((), ("Test", "Tests")),".c": (("test_",), ("_test",)),".cpp": (("test_",), ("_test",)),@@ -445,6 +446,25 @@ def production_candidates(test_path: str) -> list[str]:_add_unique(candidates, _join(dir_path, f"{base_stem}.kt"))break+ # ── Scala ─────────────────────────────────────────────────────────+ elif ext == ".scala":+ for suffix in ("Spec", "Suite", "Tests", "Test"):+ if stem.endswith(suffix):+ base_stem = stem[: -len(suffix)]+ # sbt layout: swap any .../src/test/scala/... segment while+ # preserving a module prefix such as modules/core/.+ for i in range(0, max(len(dir_segs) - 2, 0)):+ if list(dir_segs[i : i + 3]) == ["src", "test", "scala"]:+ new_dir = "/".join(+ list(dir_segs[:i])+ + ["src", "main", "scala"]+ + list(dir_segs[i + 3 :])+ )+ _add_unique(candidates, f"{new_dir}/{base_stem}.scala")+ break+ _add_unique(candidates, _join(dir_path, f"{base_stem}.scala"))+ break+# ── C# ────────────────────────────────────────────────────────────elif ext == ".cs":for suffix in ("Tests", "Test"):diff --git a/understand-anything-plugin/skills/understand/scan-project.mjs b/understand-anything-plugin/skills/understand/scan-project.mjsindex 83ccc7d1..72126fa8 100644--- a/understand-anything-plugin/skills/understand/scan-project.mjs+++ b/understand-anything-plugin/skills/understand/scan-project.mjs@@ -113,12 +113,15 @@ const LANGUAGE_BY_EXT = Object.freeze({// Python'.py': 'python','.pyi': 'python',- // Go / Rust / Java / Kotlin / C# / Swift / Lua+ // Go / Rust / Java / Kotlin / Scala / C# / Swift / Lua'.go': 'go','.rs': 'rust','.java': 'java','.kt': 'kotlin','.kts': 'kotlin',+ '.scala': 'scala',+ '.sc': 'scala',+ '.sbt': 'scala','.cs': 'csharp','.swift': 'swift','.lua': 'lua',@@ -308,6 +311,7 @@ const CATEGORY_BY_EXT = Object.freeze({'.mod': 'config','.sum': 'config','.gradle': 'config',+ '.sbt': 'config',// infra'.tf': 'infra','.tfvars': 'infra',