From 61870315c3ed74e470b269be713677a3add3c77e Mon Sep 17 00:00:00 2001 From: Muhammad Fadil Date: Mon, 23 Nov 2026 18:20:21 +0800 Subject: [PATCH 1/3] chore: tidy code comments in detectors, graph, inference, cache and tests Comment-only change. Drops banners, restated code and change-history narration, keeps the reasons behind constraints and thresholds, and translates the remaining Indonesian comments to English. The TypeScript output with comments removed is identical to the previous commit for every touched file. Co-Authored-By: Claude Sonnet 5.5 Claude-Session: https://claude.ai/code/session_01AgTNRaH4ru388em8b5Zhxn --- .../analyzers/detectors/capabilityDetector.ts | 92 ++++---------- .../detectors/clientRouteDetector.ts | 12 -- .../detectors/elysiaRouteDetector.ts | 2 +- .../analyzers/detectors/frameworkDetector.ts | 65 ++++------ .../analyzers/detectors/koaRouteDetector.ts | 1 - .../analyzers/detectors/nestRouteDetector.ts | 13 +- .../src/analyzers/detectors/routeDetector.ts | 57 ++++----- .../cli/src/analyzers/detectors/routeUtils.ts | 2 - .../analyzers/detectors/trpcRouteDetector.ts | 4 +- .../src/analyzers/features/featureMerge.ts | 106 +++-------------- .../cli/src/analyzers/graph/aliasResolver.ts | 5 +- .../cli/src/analyzers/graph/bundlerAliases.ts | 24 ++-- .../src/analyzers/graph/dependencyGraph.ts | 1 - .../cli/src/analyzers/graph/dependencyMap.ts | 30 ++--- .../analyzers/inference/domainInference.ts | 112 ++++-------------- packages/cli/src/cache/agentNavigation.ts | 5 +- packages/cli/test/agent-navigation.test.ts | 8 +- packages/cli/test/analyzer-grounding.test.ts | 16 +-- packages/cli/test/analyzers.test.ts | 10 -- packages/cli/test/audit-regressions.test.ts | 26 ---- 20 files changed, 146 insertions(+), 445 deletions(-) diff --git a/packages/cli/src/analyzers/detectors/capabilityDetector.ts b/packages/cli/src/analyzers/detectors/capabilityDetector.ts index 08f678a..faa0cd8 100644 --- a/packages/cli/src/analyzers/detectors/capabilityDetector.ts +++ b/packages/cli/src/analyzers/detectors/capabilityDetector.ts @@ -9,10 +9,6 @@ import { singularize } from "../analysis/extractors/fallbackExtractor.js"; */ const READ_ONLY_VIEW_RESOURCE = /^(?:stats?|statistics|analytics?|reports?|reporting)$/; -// --------------------------------------------------------------------------- -// Types -// --------------------------------------------------------------------------- - export type CapabilityKind = | "crud" | "sharing" @@ -28,30 +24,22 @@ export type CapabilityKind = export type CapabilityInfo = { kind: CapabilityKind; name: string; - /** Entity yang capability ini beroperasi di atasnya */ + /** Entities the capability operates on. */ entities: string[]; - /** Route files sebagai evidence */ + /** Route files the capability was inferred from. */ evidence: string[]; confidence: "high" | "medium" | "low"; }; -// --------------------------------------------------------------------------- -// Main entry -// --------------------------------------------------------------------------- - /** - * detectCapabilities — derive capabilities dari route patterns + entity graph. - * - * Berbeda dari featureDetector yang detect *library* yang dipakai (Stripe, Redis, dll), - * capabilityDetector detect *perilaku* yang di-expose project via routes. + * Derives capabilities from route patterns, using the entity graph to name entities. * - * Contoh: - * GET+POST+PUT+DELETE /snippets → crud capability pada entity "Snippet" - * POST /snippets/[id]/share → sharing capability - * POST /workspaces/[id]/members → collaboration capability + * Unlike `featureDetector`, which detects libraries the project uses (Stripe, Redis), + * this detects behavior the project exposes through routes: * - * Input: RouteInfo[] + EntityGraph (untuk entity name mapping) - * Output: CapabilityInfo[] + * GET+POST+PUT+DELETE /snippets -> crud on entity "Snippet" + * POST /snippets/[id]/share -> sharing + * POST /workspaces/[id]/members -> collaboration */ export function detectCapabilities( routes: RouteInfo[], @@ -63,24 +51,17 @@ export function detectCapabilities( const apiRoutes = routes.filter((r) => r.kind === "api"); const pageRoutes = routes.filter((r) => r.kind === "page"); - // --- CRUD detection --- const crudCapabilities = detectCrudCapabilities(apiRoutes, entityGraph); capabilities.push(...crudCapabilities); - // --- Behavioral capabilities dari route patterns --- - // Only use API routes for behavioral detection — page routes produce too many - // false positives because page paths often contain domain keywords that - // don't represent actual capabilities (e.g. /search page = UI, not search infra) + // API routes only: page paths often contain domain keywords that are not + // capabilities (a /search page is UI, not search infrastructure). const behavioral = detectBehavioralCapabilities(apiRoutes, entityGraph); capabilities.push(...behavioral); return deduplicateCapabilities(capabilities); } -// --------------------------------------------------------------------------- -// CRUD detection -// --------------------------------------------------------------------------- - function detectCrudCapabilities( apiRoutes: RouteInfo[], entityGraph: EntityGraph @@ -132,25 +113,10 @@ function detectCrudCapabilities( return capabilities; } -// --------------------------------------------------------------------------- -// Behavioral capabilities -// -// Threshold design rationale: -// -// highConfidenceAt = 1 was too aggressive — a single route match on a -// generic path like /search or /stats was enough to create a "high" -// confidence feature, even when that route was just a UI page. -// -// New thresholds: -// - Search: 2 — one /search page is a UI pattern, not a search infrastructure -// - Reporting: 2 — one /stats or /dashboard page doesn't mean reporting infra -// - Social: 3 — needs multiple social signals (likes AND comments, etc.) -// - All others: 1 or 2 depending on signal specificity -// -// Additionally: behavioral detection now only runs on API routes (not page -// routes) to avoid UI pages being confused with backend capabilities. -// --------------------------------------------------------------------------- - +// Thresholds keep a single route on a generic path (/search, /stats) from +// reading as a capability. Search and Reporting need 2 matches for "high", +// Social needs 3 (likes AND comments, ...), the rest 1 or 2 by how specific +// the path is. Search and Social also need several matches to surface at all. const BEHAVIORAL_SIGNALS: Array<{ kind: CapabilityKind; name: string; @@ -160,7 +126,7 @@ const BEHAVIORAL_SIGNALS: Array<{ /** Minimum matches to surface as a capability at all (default: 1) */ minimumMatches?: number; }> = [ - // Sharing — specific enough that 1 match is fine + // Specific enough that 1 match is fine. { kind: "sharing", name: "Content Sharing", @@ -168,7 +134,6 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 2, minimumMatches: 1, }, - // Publishing { kind: "publishing", name: "Content Publishing", @@ -176,7 +141,7 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 1, minimumMatches: 1, }, - // Collaboration — workspace/member/invite are strong signals + // workspace/member/invite are strong signals. { kind: "collaboration", name: "Team Collaboration", @@ -189,7 +154,6 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 2, minimumMatches: 1, }, - // Discovery { kind: "discovery", name: "Public Discovery", @@ -200,8 +164,7 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 1, minimumMatches: 1, }, - // Social — needs multiple signals to avoid false positives - // e.g. a single /comments route could be anything + // A single /comments route could be anything, so several signals are needed. { kind: "social", name: "Social Interactions", @@ -212,9 +175,8 @@ const BEHAVIORAL_SIGNALS: Array<{ /\/(follow|followers|following)(\/|$)/i, ], highConfidenceAt: 3, - minimumMatches: 2, // needs at least 2 distinct social routes to surface + minimumMatches: 2, }, - // File management { kind: "file-management", name: "File Management", @@ -226,7 +188,7 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 1, minimumMatches: 1, }, - // Real-time — transport-level signals only, very specific + // Transport-level signals only. { kind: "real-time", name: "Real-time Features", @@ -238,16 +200,15 @@ const BEHAVIORAL_SIGNALS: Array<{ highConfidenceAt: 1, minimumMatches: 1, }, - // Search — needs at least 2 API routes to surface - // A single /api/search could be a simple filter, not search infrastructure + // A single /api/search could be a simple filter, not search infrastructure. { kind: "search", name: "Search", pathPatterns: [/\/(search|find|query|lookup)(\/|$)/i], highConfidenceAt: 2, - minimumMatches: 2, // must have at least 2 distinct search API routes + minimumMatches: 2, }, - // Reporting — dashboard alone is not enough (many apps have a /dashboard page) + // `dashboard` is left out: many apps have a /dashboard page. { kind: "reporting", name: "Statistics & Reporting", @@ -261,7 +222,6 @@ const BEHAVIORAL_SIGNALS: Array<{ ]; function detectBehavioralCapabilities( - // Only API routes now — page routes removed to cut false positives apiRoutes: RouteInfo[], entityGraph: EntityGraph ): CapabilityInfo[] { @@ -297,10 +257,6 @@ function detectBehavioralCapabilities( return capabilities; } -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - function extractResourceName(path: string): string | null { const segments = path .split("/") @@ -374,12 +330,12 @@ function higherConfidence( return rank[a] >= rank[b] ? a : b; } -// NON_RESOURCE_SEGMENTS — path segments yang bukan nama resource. +// Path segments that never name a resource. const NON_RESOURCE_SEGMENTS = new Set([ "auth", "oauth", "callback", "health", "ping", "status", "public", "internal", "static", "assets", "files", "me", "self", "history", "session", "sessions", - // tambahan: common Next.js/UI page paths yang bukan API resource + // Common Next.js/UI page paths that are not API resources. "dashboard", "settings", "profile", "search", ]); diff --git a/packages/cli/src/analyzers/detectors/clientRouteDetector.ts b/packages/cli/src/analyzers/detectors/clientRouteDetector.ts index 413fdbb..7ada92e 100644 --- a/packages/cli/src/analyzers/detectors/clientRouteDetector.ts +++ b/packages/cli/src/analyzers/detectors/clientRouteDetector.ts @@ -77,8 +77,6 @@ export function detectClientRoutes( }))); } -// ------------------------------------------------------------------- model - type FileModel = { /** Local name → module specifier. */ imports: Map; @@ -140,16 +138,12 @@ function locateComponent( return resolved ?? entry.definedIn; } -// -------------------------------------------------------------- path rules - function composePath(base: string, path: string | undefined, isIndex: boolean): string { if (isIndex || path === undefined || path === "") return base; if (path === "*") return joinRoutePaths(base, "*"); return path.startsWith("/") ? joinRoutePaths(path) : joinRoutePaths(base, path); } -// ---------------------------------------------------- React Router: JSX tree - const WRAPPER_TAG = /(?:Route|Guard|Protected|Auth|Private|Suspense|Provider|Boundary)/; const ROUTE_TAG = /^(?:\w+\.)?\w*Route$/; @@ -267,8 +261,6 @@ function componentFromExpression(expression: ts.Expression): Component | undefin return undefined; } -// -------------------------------- React Router data routers / Vue Router - type RouteObject = { path?: string; isIndex: boolean; @@ -372,8 +364,6 @@ function isChildrenOfRoute(array: ts.ArrayLiteralExpression): boolean { && ts.isArrayLiteralExpression(owner.parent); } -// ------------------------------------------------- TanStack code-based routes - type CodeRoute = { variable: string; path?: string; parent?: string; component: Component; isIndex: boolean }; function readTanStackRoutes(source: ts.SourceFile, definedIn: string, model: FileModel): RouteEntry[] { @@ -452,8 +442,6 @@ function parentOf(value: ts.Expression): string | undefined { return undefined; } -// ------------------------------------------------------- svelte-spa-router - function readSvelteSpaRoutes( source: ts.SourceFile, definedIn: string, diff --git a/packages/cli/src/analyzers/detectors/elysiaRouteDetector.ts b/packages/cli/src/analyzers/detectors/elysiaRouteDetector.ts index 51e7d6d..6aee326 100644 --- a/packages/cli/src/analyzers/detectors/elysiaRouteDetector.ts +++ b/packages/cli/src/analyzers/detectors/elysiaRouteDetector.ts @@ -73,7 +73,7 @@ export function detectElysiaRoutes(files: ScannedFile[], graph?: Record { const detected = new Set(); const sourceFiles = files.filter((file) => isArchitectureSource(file.path)); - // Phase 1: dependency manifest — highest confidence signal. - // package.json is the canonical source of truth for what frameworks are installed. + // package.json dependencies are the highest-confidence signal. for (const manifest of readManifestDependencies(files)) { const dependencies = { ...manifest.runtime, ...manifest.dev }; // A server framework that is only a devDependency is usually test tooling @@ -145,9 +139,9 @@ function collectFrameworks(files: ScannedFile[]): Set { detected.add("react"); } - // Nuxt apps ship App.vue too, so vue must exclude when nuxt is present — - // same mirror of the react-vs-next exclusion. The runtime gate prevents a - // Vue UI library (vue only in peerDependencies) from being labeled an app. + // Nuxt apps ship App.vue too, so vue is excluded when nuxt is present (as react + // is for next). The runtime gate keeps a Vue UI library, which lists vue as a + // peer or dev dependency, from being labeled an app. const hasVueRuntime = "@vitejs/plugin-vue" in dependencies || "@vitejs/plugin-vue2" in dependencies || "@vue/cli-service" in dependencies @@ -162,13 +156,11 @@ function collectFrameworks(files: ScannedFile[]): Set { } } - // Phase 2: file structure heuristics — secondary signal. - // Only used when package.json is absent or incomplete (e.g. monorepo root without deps). + // File-structure signals run in addition to the manifests (a monorepo root may list no deps). // Next.js: next.config.* or App Router / Pages Router file conventions. - // _app and _document are Next.js-unique; a bare src/pages/api/ folder is NOT - // (Astro uses the same folder for endpoints), so it is deliberately excluded - // from the Pages Router signal here. + // _app and _document are Next.js-unique; a bare src/pages/api/ folder is not a + // signal because Astro uses the same folder for endpoints. if ( sourceFiles.some((file) => /(^|\/)next\.config\.[cm]?[jt]s$/.test(file.path)) || sourceFiles.some((file) => @@ -180,63 +172,52 @@ function collectFrameworks(files: ScannedFile[]): Set { detected.add("nextjs"); } - // Express: primarily via package.json dependency (see below for the file-only path). + // The Express and Hono file heuristics below only apply when this is false. const hasReliableManifest = files.some( (file) => file.path.endsWith("package.json") && isArchitectureSource(file.path) && isParseableJson(file.content) ); - // Express: ONLY add via file heuristic if express was already confirmed in package.json, - // OR — narrow fallback — if package.json is missing/unparseable entirely. - // - // Rationale: `server.ts` and `app.ts` are common filenames in Next.js, NestJS, and vanilla - // Node projects. Without the dependency gate, a Next.js project with a custom `app.ts` - // utility file would be misclassified as Express. The dep check is the authoritative signal; - // the filename pattern alone is intentionally never used as a standalone trigger. - // - // When there's no reliable manifest to check at all, that filename ambiguity is still a - // real risk, so instead of trusting the filename we scan file *content* for an actual - // `express()` call or `require("express")`/`from "express"` — evidence specific enough - // that a Next.js app.ts utility file won't produce a false positive. + // A `server.ts` / `app.ts` filename never adds Express by itself: Next.js, NestJS and + // plain Node projects use those names too. With no parseable package.json to check, + // file content is scanned for an `express()` call or an `express` require/import instead. if ( detected.has("express") && sourceFiles.some((file) => /(^|\/)(?:src\/)?(?:server|app)\.[cm]?[jt]s$/.test(file.path) ) ) { - // Already added via deps — this block intentionally left as documentation of the gate. - // The detected.add("express") already happened above; we don't re-add. + // Already detected from dependencies. } else if (!hasReliableManifest && sourceFiles.some((file) => hasExpressCallSite(file.content))) { detected.add("express"); } - // Astro: src/pages/*.astro is specific enough to be safe as a standalone signal. + // src/pages/*.astro is specific enough to stand alone. if (sourceFiles.some((file) => /(^|\/)src\/pages\/.+\.astro$/.test(file.path))) { detected.add("astro"); } - // Nuxt: nuxt.config.* is as specific as next.config.* today. + // nuxt.config.* is specific to Nuxt. if (sourceFiles.some((file) => /(^|\/)nuxt\.config\.[cm]?[jt]s$/.test(file.path))) { detected.add("nuxt"); } - // Vue: App.vue at the project root (or src/) is specific enough to stand alone. + // App.vue at the project root (or src/) is specific enough to stand alone. if (sourceFiles.some((file) => /(^|\/)(?:src\/)?App\.vue$/.test(file.path))) { detected.add("vue"); } - // SvelteKit: +page.svelte under src/routes/ is unique to SvelteKit — the "+" - // prefix is not used by any other framework. svelte.config.js is NOT used as a - // signal because non-SvelteKit Svelte projects have it too. + // +page.svelte under src/routes/ is unique to SvelteKit. svelte.config.js is not a + // signal because plain Svelte projects have it too. if (sourceFiles.some((file) => /(^|\/)src\/routes\/.+\+page\.svelte$/.test(file.path))) { detected.add("sveltekit"); } - // NestJS: nest-cli.json is as specific as next.config.* / nuxt.config.*. + // nest-cli.json is specific to NestJS. if (files.some((file) => /(^|\/)nest-cli\.json$/.test(file.path))) { detected.add("nestjs"); } - // Remix / React Router v7: their config files are specific to each tool. + // The Remix and React Router v7 config files are specific to each tool. if (files.some((file) => /(^|\/)remix\.config\.[cm]?js$/.test(file.path))) { detected.add("remix"); } @@ -279,7 +260,7 @@ const REMIX_PACKAGES = [ const QWIK_PACKAGES = ["@builder.io/qwik-city", "@builder.io/qwik", "@qwik.dev/router", "@qwik.dev/core"]; -// v6 ships `@adonisjs/core`; v4 and v5 ship `@adonisjs/framework` / `@adonisjs/core` too. +// `@adonisjs/core` is v5 and v6; `@adonisjs/framework` is v4. const ADONIS_PACKAGES = ["@adonisjs/core", "@adonisjs/framework"]; const TANSTACK_ROUTER_PACKAGES = [ diff --git a/packages/cli/src/analyzers/detectors/koaRouteDetector.ts b/packages/cli/src/analyzers/detectors/koaRouteDetector.ts index 9d51c82..3d62e03 100644 --- a/packages/cli/src/analyzers/detectors/koaRouteDetector.ts +++ b/packages/cli/src/analyzers/detectors/koaRouteDetector.ts @@ -222,7 +222,6 @@ function optionsPrefix(options: ts.Expression | undefined, module: ModuleInfo, i if (ts.isPropertyAssignment(property) && ts.isIdentifier(property.name) && property.name.text === "prefix") { return index.stringOf(property.initializer, module) ?? ""; } - // `{ prefix }` if (ts.isShorthandPropertyAssignment(property) && property.name.text === "prefix") { return index.stringOf(property.name, module) ?? ""; } diff --git a/packages/cli/src/analyzers/detectors/nestRouteDetector.ts b/packages/cli/src/analyzers/detectors/nestRouteDetector.ts index e0d685d..90e8aa8 100644 --- a/packages/cli/src/analyzers/detectors/nestRouteDetector.ts +++ b/packages/cli/src/analyzers/detectors/nestRouteDetector.ts @@ -17,19 +17,19 @@ const ROUTE_DECORATORS = new Set([ const ALL_HTTP_METHODS = ["GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS", "HEAD"]; /** - * detectNestRoutes — NestJS controllers are decorator + class based, so flat - * per-line regex cannot associate a @Get(':id') with the @Controller('users') - * that scopes it. ts-morph gives per-class/method decorator scope for free. + * NestJS routes are decorator-based, so a per-line regex cannot tie a + * `@Get(':id')` to the `@Controller('users')` that scopes it; ts-morph exposes + * decorators per class and method. * * Paths are read from string literals, no-substitution templates and arrays of * them, for both `@Controller('users')` and `@Controller({ path: 'users' })`. * * Known limitations: * - Paths built from constants or template substitutions are not resolved. - * - app.setGlobalPrefix('api') and `version` are not composed into route paths. + * - `app.setGlobalPrefix('api')` and `version` are not composed into route paths. */ export function detectNestRoutes(files: ScannedFile[]): RouteInfo[] { - // Cheap pre-filter before any ts-morph parse — most scans have no controllers. + // Cheap pre-filter before any ts-morph parse: most scans have no controllers. const candidates = files.filter( (file) => /\.[cm]?[jt]s$/.test(file.path) && file.content.includes("@Controller") ); @@ -66,8 +66,7 @@ export function detectNestRoutes(files: ScannedFile[]): RouteInfo[] { const subPaths = literalPaths(routeDecorator.getArguments()[0]); const decoratorName = routeDecorator.getName().toUpperCase(); - // @All() matches every HTTP method — expand instead of inventing a - // placeholder value. + // @All() matches every HTTP method, so list them all rather than a placeholder. const methods = decoratorName === "ALL" ? ALL_HTTP_METHODS : [decoratorName]; diff --git a/packages/cli/src/analyzers/detectors/routeDetector.ts b/packages/cli/src/analyzers/detectors/routeDetector.ts index cfb2e86..bb486c1 100644 --- a/packages/cli/src/analyzers/detectors/routeDetector.ts +++ b/packages/cli/src/analyzers/detectors/routeDetector.ts @@ -33,16 +33,13 @@ export type RouteInfo = { }; /** - * detectRoutes — run every detector whose framework was detected, then merge - * the results. A project with a Next.js frontend AND an Express backend in a - * single scan now yields routes from BOTH sides instead of first-match-wins. + * Runs every detector whose framework was detected and merges the results, so a + * Next.js frontend with an Express backend yields routes from both sides. + * Detectors filter by their own file patterns, so running several at once does + * not produce duplicates. * - * Each per-framework detector stays isolated (they already filter by their own - * file patterns), so running several at once is safe — they don't collide - * because they look at different files. - * - * `graph` (optional) lets the Express detector resolve routers mounted across - * files so mount prefixes compose with the sub-paths they wrap. + * `graph` lets the detectors that follow mounts across files (Express, Fastify, + * Hono, Angular, ...) compose mount prefixes with the sub-paths they wrap. */ export function detectRoutes( files: ScannedFile[], @@ -118,9 +115,8 @@ function detectNextRoutes(files: ScannedFile[]): RouteInfo[] { const slotFiles = new Set(); for (const file of files.filter((item) => isArchitectureSource(item.path))) { - // App Router — match anywhere in path, not just root. - // Supports: src/app/, app/, apps/web/src/app/, packages/web/src/app/, dll. - // Sebelumnya pakai ^(?:src\/)? yang miss monorepo prefix seperti apps/web/. + // App Router: matched at any depth, not anchored to the root, so monorepo + // prefixes such as apps/web/src/app/ are found. const appMatch = file.path.match( /(?:^|\/)(?:src\/)?app\/(.+\/)?(page|route|sitemap|robots|manifest)\.[jt]sx?$/ ); @@ -151,7 +147,7 @@ function detectNextRoutes(files: ScannedFile[]): RouteInfo[] { continue; } - // Pages Router — sama, ganti ^ ke (?:^|\/) buat monorepo support. + // Pages Router: also matched at any depth for monorepos. const pagesMatch = file.path.match( /(?:^|\/)(?:src\/)?pages\/(.+)\.[jt]sx?$/ ); @@ -178,11 +174,9 @@ function detectNextRoutes(files: ScannedFile[]): RouteInfo[] { } /** - * detectAstroRoutes — pages live under src/pages/ (Astro always uses src/ as - * its source root). Page files are .astro/.md/.mdx; endpoint files are - * .ts/.js exporting GET/POST/etc., the same convention as Next.js route - * handlers. Underscore-prefixed segments and content collections are not - * routes and are skipped. + * Astro pages live under `src/pages/` as .astro/.md/.mdx; endpoints are .ts/.js + * files exporting GET/POST/etc., like Next.js route handlers. Underscore-prefixed + * segments are not routes. */ function detectAstroRoutes(files: ScannedFile[]): RouteInfo[] { const routes: RouteInfo[] = []; @@ -213,10 +207,9 @@ function detectAstroRoutes(files: ScannedFile[]): RouteInfo[] { } /** - * detectNuxtRoutes — Nuxt uses root-level pages/** (not src/pages/ like Astro), - * unless srcDir is customized in nuxt.config — a v1 limitation. Bracket syntax - * for dynamic segments, [...slug] for catch-alls, and index-stripping mirror - * Next.js Pages Router conventions. + * Nuxt pages are `pages/**` at any depth (the folder is not tied to `src/`); + * `srcDir` from nuxt.config is not read. Bracket segments, `[...slug]` + * catch-alls and index stripping follow the Next.js Pages Router conventions. */ function detectNuxtRoutes(files: ScannedFile[]): RouteInfo[] { const routes: RouteInfo[] = []; @@ -266,10 +259,9 @@ function detectNuxtRoutes(files: ScannedFile[]): RouteInfo[] { } /** - * detectSvelteKitRoutes — the route unit is a FOLDER under src/routes/, not a - * file name. Only +page.svelte (page) and +server.[jt]s (api) are routes; the - * "+" prefix is SvelteKit-only, so the escaped literals below are safe. Route - * groups "(group)" are stripped by toRoutePath. + * The route unit is a folder under `src/routes/`, not a file name. Only + * `+page.svelte` (page) and `+server.[jt]s` (api) are routes. Route groups + * `(group)` are stripped by `toRoutePath`. */ function detectSvelteKitRoutes(files: ScannedFile[]): RouteInfo[] { const routes: RouteInfo[] = []; @@ -339,7 +331,6 @@ function detectFastifyRoutes( ); const byPath = new Map(eligibleFiles.map((file) => [file.path, file])); - // First pass: direct routes per file, plus collect plugin registrations. const directRoutes = new Map(); const registers: FastifyRegister[] = []; @@ -362,7 +353,6 @@ function detectFastifyRoutes( } } - // Second pass: resolve registered plugins and compose prefix + sub-path. const mountedFiles = new Set(); for (const register of registers) { const target = resolveRouterTarget( @@ -386,14 +376,14 @@ function detectFastifyRoutes( }); } } - // Unresolvable plugin without routes — it is not a route, so drop it. + // A plugin that cannot be resolved or has no routes is dropped; unlike Express + // there is no USE placeholder for it. } // @fastify/autoload registers every plugin file of a folder with the folder path as its // prefix, so a file's routes are relative to that path, not to "/". const autoloads = findAutoloadRoots(eligibleFiles); - // Emit standalone routes only for files that were not absorbed by a plugin. for (const [path, fileRoutes] of directRoutes) { if (mountedFiles.has(path)) continue; const prefix = autoloadPrefix(path, autoloads); @@ -518,7 +508,6 @@ function detectExpressRoutes( ); const byPath = new Map(eligibleFiles.map((file) => [file.path, file])); - // First pass: direct route methods per file, plus collect mounted routers. const directRoutes = new Map(); const mounts: ExpressMount[] = []; @@ -541,7 +530,6 @@ function detectExpressRoutes( } } - // Second pass: resolve each mount to the router file it points at. const resolvedMounts = mounts.map((mount) => ({ mount, target: resolveRouterTarget( @@ -597,8 +585,8 @@ function detectExpressRoutes( // the full prefix, so a bare USE entry would be noise. mountedFiles.add(target.path); } else { - // Unresolvable or empty router — keep the mount itself as a USE route so - // the middleware prefix stays visible instead of silently disappearing. + // Unresolvable or empty router: keep the mount as a USE route so the + // middleware prefix stays visible. routes.push({ path: base || "/", file: mount.file, @@ -609,7 +597,6 @@ function detectExpressRoutes( } } - // Emit standalone routes only for files that were not absorbed by a mount. for (const [path, fileRoutes] of directRoutes) { if (!mountedFiles.has(path)) { routes.push(...fileRoutes); diff --git a/packages/cli/src/analyzers/detectors/routeUtils.ts b/packages/cli/src/analyzers/detectors/routeUtils.ts index 1c9ca6a..a469565 100644 --- a/packages/cli/src/analyzers/detectors/routeUtils.ts +++ b/packages/cli/src/analyzers/detectors/routeUtils.ts @@ -4,8 +4,6 @@ import { isArchitectureSource } from "../graph/sourceScope.js"; import { matchLocalPath, normalizePath } from "../graph/localPaths.js"; import { compareText } from "../../utils/compare.js"; -// Helpers shared by the per-framework route detectors. - export function resolveRouterTarget( identifier: string, mountFile: string, diff --git a/packages/cli/src/analyzers/detectors/trpcRouteDetector.ts b/packages/cli/src/analyzers/detectors/trpcRouteDetector.ts index f4b479f..c9067cb 100644 --- a/packages/cli/src/analyzers/detectors/trpcRouteDetector.ts +++ b/packages/cli/src/analyzers/detectors/trpcRouteDetector.ts @@ -5,7 +5,7 @@ import { compareText } from "../../utils/compare.js"; type ProcedureKind = "QUERY" | "MUTATION"; -// Known V1 limitations: +// Known limitations: // - Only processes the first router({...}) call per file // - Nested composition resolved max 2 levels (root → sub) @@ -140,7 +140,7 @@ function parseRouterFile( } } - // Extract sub-router references: "subRouter" used as values + // Sub-routers referenced as values, e.g. `users: usersRouter`. const subRouterRefs: string[] = []; const refPattern = /(\w+)\s*:\s*(\w+Router)\b/g; let refMatch = refPattern.exec(routerBody); diff --git a/packages/cli/src/analyzers/features/featureMerge.ts b/packages/cli/src/analyzers/features/featureMerge.ts index 09ebe74..19e0d4c 100644 --- a/packages/cli/src/analyzers/features/featureMerge.ts +++ b/packages/cli/src/analyzers/features/featureMerge.ts @@ -1,22 +1,3 @@ -/** - * featureMerge.ts - * - * Centralized feature merge logic. - * - * Sebelumnya merge tersebar di dua tempat: - * 1. featureDetector.ts → mergeFeature() pakai normalizeFeatureName (string only) - * 2. projectMap.ts → domain feature merge pakai f.name.toLowerCase() equality - * - * Keduanya punya flaw yang sama: bergantung pada nama sebagai identity. - * "Plan Management" dan "Customizable Plans" tidak akan di-merge karena nama berbeda. - * - * Refactor ini: - * - Ganti kedua merge sites dengan satu fungsi: mergeIntoFeatureList() - * - Pakai featureSimilarity.ts sebagai basis comparison - * - Canonical name: first-seen wins (stabil antar-run) - * - Merge enriches data (files, terms, entities) tanpa rename feature - */ - import type { FeatureInfo } from "./featureDetector.js"; import { findSimilarFeature, @@ -25,15 +6,10 @@ import { DEFAULT_SIMILARITY_THRESHOLD, } from "./featureSimilarity.js"; -// --------------------------------------------------------------------------- -// Convert FeatureInfo ke FeatureIdentity untuk similarity comparison -// --------------------------------------------------------------------------- - export function toFeatureIdentity(feature: FeatureInfo): FeatureIdentity { return { name: feature.name, - // Sort arrays deterministically agar fingerprint dan similarity - // comparison konsisten antar-run. + // Sorted so similarity results do not depend on input order. files: [...feature.files].sort(), searchTerms: [...feature.searchTerms].sort(), relatedEntities: extractRelatedEntities(feature).sort(), @@ -41,31 +17,19 @@ export function toFeatureIdentity(feature: FeatureInfo): FeatureIdentity { }; } -/** - * extractRelatedEntities — derive entity names dari feature data. - * - * entityGraphToFeatures() inject entity name + owned/peer names ke searchTerms. - * capabilitiesToFeatures() juga inject entity names via cap.entities. - * - * Filter ketat: hanya entity name dari feature name pattern, bukan asal-asalan - * dari searchTerms (yang bisa berisi generic technical keywords). - * - * entityOverlap di similarity engine tetap dapat sinyal dari searchTerms - * melalui termOverlap — jadi entityOverlap khusus menangkap entity name - * yang eksplisit dari feature name "X Management". - */ +// Deliberately strict: searchTerms also hold generic technical keywords, which must not +// count as entities. Plain searchTerms still reach the similarity score through termOverlap, +// so entityOverlap only captures names stated explicitly. function extractRelatedEntities(feature: FeatureInfo): string[] { const entities: string[] = []; - // Pattern: "X Management" / "X System" / "X Module" → "X" adalah entity + // "X Management" / "X System" / "X Module" names entity "X". const nameMatch = feature.name.match(/^(.+?)\s+(?:Management|System|Module|Feature|Service)$/i); if (nameMatch) { entities.push(nameMatch[1].trim()); } - // Hanya ambil searchTerms yang eksplisit Title Case (entity names). - // searchTerms umumnya lowercase, jadi ini filter natural. - // Terms dari FEATURE_SIGNALS (technical keywords) tidak akan lulus. + // Entity names are the Title Case searchTerms; registry signal terms are lowercase and fail this test. for (const term of feature.searchTerms) { if (/^[A-Z]/.test(term)) { entities.push(term); @@ -75,25 +39,13 @@ function extractRelatedEntities(feature: FeatureInfo): string[] { return [...new Set(entities)]; } -// --------------------------------------------------------------------------- -// Core merge function -// --------------------------------------------------------------------------- - /** - * mergeIntoFeatureList — merge satu feature ke list yang sudah ada. - * - * Algorithm: - * 1. Cari existing feature yang similar (pakai similarity engine) - * 2. Kalau ditemukan → enrich existing (files, terms, entities), jangan rename - * 3. Kalau tidak ditemukan → tambah sebagai feature baru - * - * Canonical name: feature pertama yang masuk MENANG — tidak pernah di-overwrite. - * Ini kunci stabilitas: walaupun AI run ke-2 generate "Customizable Plans", - * kalau "Plan Management" sudah ada di list, namanya tetap "Plan Management". + * Merges `addition` into `features` in place: into the most similar existing feature, + * or appended when none reaches `threshold`. * - * @param features - List feature yang sudah ada (mutated in place) - * @param addition - Feature baru yang ingin di-merge - * @param threshold - Similarity threshold (default: DEFAULT_SIMILARITY_THRESHOLD) + * The first-seen name is canonical and never overwritten, which keeps names stable across + * runs: if "Plan Management" exists, a later AI feature "Customizable Plans" merges into it + * without renaming it. */ export function mergeIntoFeatureList( features: FeatureInfo[], @@ -106,28 +58,19 @@ export function mergeIntoFeatureList( const match = findSimilarFeature(identities, additionIdentity, threshold); if (match === null) { - // Tidak ada yang similar → tambah sebagai feature baru features.push(addition); return; } - // Similar feature ditemukan → enrich tanpa rename const existing = features[match.index]; features[match.index] = mergeFeatureData(existing, addition); } /** - * mergeFeatureData — combine data dari dua feature yang sudah diidentifikasi sama. - * - * Rules: - * - name: existing wins (canonical first-seen) - * - purpose: existing wins KECUALI existing adalah generic fallback - * - files: union (dedup) - * - evidence: union (dedup) - * - searchTerms: union (capped di MAX_SEARCH_TERMS) - * - confidence: ambil yang lebih tinggi (jangan downgrade) - * - entryPoints: union — domain feature bisa bawa entryPoints baru - * - businessFlow: existing wins jika meaningful, fallback ke addition + * Combines two features already judged to be the same one. `existing` keeps its name, + * and keeps its purpose and business flow unless they are generic placeholders. + * List fields are unioned (searchTerms capped at `MAX_SEARCH_TERMS`) and the higher + * confidence wins. */ export function mergeFeatureData(existing: FeatureInfo, addition: FeatureInfo): FeatureInfo { const resolvedPurpose = isGenericPurpose(existing.purpose) && !isGenericPurpose(addition.purpose) @@ -166,20 +109,9 @@ function isPlaceholderBusinessFlow(flow: string[]): boolean { return flow.length === 1 && /^Identify files related to /i.test(flow[0]); } -// --------------------------------------------------------------------------- -// Batch merge — untuk domain features dari AI inference -// --------------------------------------------------------------------------- - /** - * mergeDomainFeatures — merge semua domain features ke static feature list. - * - * Ini menggantikan loop di projectMap.ts yang hanya pakai name.toLowerCase() equality. - * Sekarang pakai similarity engine sehingga "Customizable Plans" tidak duplicate - * "Plan Management" yang sudah ada dari static analysis. - * - * @param features - Static features (mutated) - * @param domainFeatures - AI-inferred features - * @param threshold - Similarity threshold + * Merges AI-inferred features into the static list (mutated). Matching is by similarity, + * not name equality, so "Customizable Plans" folds into an existing "Plan Management". */ export function mergeDomainFeatures( features: FeatureInfo[], @@ -191,10 +123,6 @@ export function mergeDomainFeatures( } } -// --------------------------------------------------------------------------- -// Helpers -// --------------------------------------------------------------------------- - function dedup(arr: T[]): T[] { return [...new Set(arr)]; } diff --git a/packages/cli/src/analyzers/graph/aliasResolver.ts b/packages/cli/src/analyzers/graph/aliasResolver.ts index 326c88b..43bf89f 100644 --- a/packages/cli/src/analyzers/graph/aliasResolver.ts +++ b/packages/cli/src/analyzers/graph/aliasResolver.ts @@ -108,10 +108,7 @@ export function isDeclaredAlias(specifier: string, mappings: AliasMapping[], fro ); } -/** - * Resolve an alias import specifier to a root-relative path using configured - * mappings. Returns null if no mapping matches. - */ +/** Best candidate from `resolveAliasCandidates`, or null when no mapping matches. */ export function resolveAlias( specifier: string, mappings: AliasMapping[], diff --git a/packages/cli/src/analyzers/graph/bundlerAliases.ts b/packages/cli/src/analyzers/graph/bundlerAliases.ts index cb25d23..332e1de 100644 --- a/packages/cli/src/analyzers/graph/bundlerAliases.ts +++ b/packages/cli/src/analyzers/graph/bundlerAliases.ts @@ -3,16 +3,14 @@ import { join, posix, relative, sep } from "node:path"; import { ts } from "ts-morph"; import type { AliasMapping } from "./aliasResolver.js"; -/** - * Aliases that only exist in bundler config: `@` → `src` in vite.config, - * `$components` in svelte.config, `resolve.alias` in webpack.config, `alias` - * in nuxt.config. None of them is in tsconfig, so without this the import - * `@/lib/db` looks like an npm package and the file graph loses the edge. - * - * Configs are code, so they are read from the syntax tree, never run. Anything - * that cannot be worked out statically (an env variable, a function call this - * module does not know) is skipped rather than guessed. - */ +// Aliases that only exist in bundler config (`@` -> `src` in vite.config, +// `$components` in svelte.config, `resolve.alias` in webpack.config, `alias` in +// nuxt.config) are absent from tsconfig, so without this `@/lib/db` looks like +// an npm package and the file graph loses the edge. +// +// Configs are code, so they are read from the syntax tree, never run. Anything +// that cannot be worked out statically (an env variable, an unknown helper +// call) is skipped rather than guessed. const CONFIG_FILE = /^(?:vite(?:st)?|vitest|webpack|rollup|rspack|rsbuild|astro|svelte|nuxt|next|electron\.vite|quasar)(?:\.[\w-]+)?\.config\.[cm]?[jt]s$|^webpack\.[\w.-]+\.[cm]?[jt]s$/; @@ -212,8 +210,6 @@ function toMappings( ]; } -// ---------------------------------------------------------- path evaluation - /** * Fold an expression that builds a path (`path.resolve(__dirname, 'src')`, * `fileURLToPath(new URL('./src', import.meta.url))`, a template string, a @@ -253,7 +249,7 @@ function fold( return value; } - // import.meta.url, import.meta.dirname, process.cwd, import.meta.dirname + // import.meta.url / .filename / .dirname if (ts.isPropertyAccessExpression(node)) { const text = node.getText(); if (text === "import.meta.url" || text === "import.meta.filename") return FILE; @@ -329,8 +325,6 @@ function calleeName(expression: ts.Expression): string | undefined { return undefined; } -// --------------------------------------------------------------------- AST - function collectVariables(node: ts.Node, variables: Map): void { if (ts.isVariableDeclaration(node) && ts.isIdentifier(node.name) && node.initializer) { if (!variables.has(node.name.text)) variables.set(node.name.text, node.initializer); diff --git a/packages/cli/src/analyzers/graph/dependencyGraph.ts b/packages/cli/src/analyzers/graph/dependencyGraph.ts index 1c04909..d60883c 100644 --- a/packages/cli/src/analyzers/graph/dependencyGraph.ts +++ b/packages/cli/src/analyzers/graph/dependencyGraph.ts @@ -66,7 +66,6 @@ export function buildDependencyGraph( } } - // Try alias resolution for non-relative imports const candidates = resolveAliasCandidates(specifier, aliasMappings, file.path); const aliasResolved = candidates.length > 0 ? firstResolved(candidates, localPaths) : null; if (aliasResolved) { diff --git a/packages/cli/src/analyzers/graph/dependencyMap.ts b/packages/cli/src/analyzers/graph/dependencyMap.ts index 9b87142..15e62b7 100644 --- a/packages/cli/src/analyzers/graph/dependencyMap.ts +++ b/packages/cli/src/analyzers/graph/dependencyMap.ts @@ -1,10 +1,6 @@ import type { FileGraph } from "./dependencyGraph.js"; -/** - * buildReverseGraph — invert a forward file-import graph into a - * "who depends on me" graph. `fileGraph` maps a file to the files it - * imports; the reverse maps a file to the files that import it. - */ +/** Inverts a file -> imports graph into file -> importers ("who depends on me"). */ export function buildReverseGraph(fileGraph: FileGraph): FileGraph { const reverse: FileGraph = {}; @@ -30,20 +26,17 @@ export type MapTreeNode = { }; /** - * Default cap on direct children shown per node. Hub files (a shared - * types.ts, utils.ts, a common UI component) can have very high fan-in — - * without a cap, a single "used by" tree (or the mermaid diagram built from - * it) can balloon to hundreds of lines/nodes and become unreadable. Pass - * `maxChildren: Infinity` (wired to the `--all` flag) to bypass this. + * Default cap on direct children shown per node. Hub files (shared types.ts, + * utils.ts, common UI components) have huge fan-in, and a "used by" tree or + * mermaid diagram without a cap grows to hundreds of unreadable nodes. Pass + * `maxChildren: Infinity` (the `--all` flag) to bypass it. */ export const DEFAULT_MAX_CHILDREN = 25; /** - * buildBoundedTree — walk a graph outward from `root` up to `maxDepth` hops, - * stopping (and flagging isCycle) whenever a path revisits a file already on - * the current branch. File dependency graphs commonly have real cycles - * (A imports B imports A), so a naive walk without a visited-per-branch set - * would recurse forever. + * Walks the graph outward from `root` up to `maxDepth` hops. A path that + * revisits a file already on its branch stops and is flagged `isCycle`; import + * cycles (A imports B imports A) are real and would otherwise recurse forever. */ export function buildBoundedTree( graph: FileGraph, @@ -87,12 +80,7 @@ export function buildBoundedTree( }; } -/** - * collectNodesWithinDepth — flat, deduplicated list of every file reachable - * from `root` within `maxDepth` hops (root excluded). Used for feature-level - * "what does this feature touch outside itself" style queries where a flat - * set is more useful than a nested tree. - */ +/** Flat, deduplicated list of files reachable from `root` within `maxDepth` hops, root excluded. */ export function collectNodesWithinDepth( graph: FileGraph, root: string, diff --git a/packages/cli/src/analyzers/inference/domainInference.ts b/packages/cli/src/analyzers/inference/domainInference.ts index f4a18d3..84addc4 100644 --- a/packages/cli/src/analyzers/inference/domainInference.ts +++ b/packages/cli/src/analyzers/inference/domainInference.ts @@ -7,20 +7,16 @@ import { readFile, writeFile, mkdir } from "node:fs/promises"; import { join } from "node:path"; import { z } from "zod"; -// --------------------------------------------------------------------------- -// Types -// --------------------------------------------------------------------------- - export type DomainInferenceResult = { /** e.g. "Code Snippet Manager", "E-Commerce Platform", "LMS" */ domain: string; /** Human-readable summary of what the project does */ summary: string; - /** Domain-specific features AI inferred — tidak hardcode, truly dynamic */ + /** Domain-specific features the model inferred; not drawn from a fixed list. */ domainFeatures: DomainFeature[]; confidence: number; // 0.0 - 1.0 model: string; - /** Total tokens used — buat monitoring cost */ + /** Total tokens used, for cost monitoring. */ tokensUsed: number; }; @@ -33,7 +29,7 @@ export type DomainFeature = { export type DomainInferenceInput = { entityNames: string[]; relations: Array<{ from: string; to: string; kind: string }>; - capabilities: string[]; // capability kinds only — hemat token + capabilities: string[]; // capability kinds only, to save tokens technicalFeatures: string[]; // feature names only routeCount: number; framework: string; @@ -42,20 +38,8 @@ export type DomainInferenceInput = { absentCapabilities: string[]; }; -// --------------------------------------------------------------------------- -// Cache -// -// Domain inference di-cache di .devmap/domain-cache.json berdasarkan hash -// dari DomainInferenceInput. Kalau input tidak berubah (entity names, relations, -// capabilities, framework sama), cached result langsung dipakai tanpa LLM call. -// -// Ini memastikan `devmap analyze` idempotent — hasil feature names tidak -// berubah tiap run selama codebase tidak berubah. -// -// Cache invalidation otomatis: kalau hash input berubah (tambah entity baru, -// ubah relasi, dll), cache di-skip dan LLM dipanggil ulang. -// --------------------------------------------------------------------------- - +// Results are cached in .devmap/domain-cache.json keyed by a hash of the input, so +// `devmap analyze` returns the same feature names on every run until the input changes. type DomainInferenceCache = { inputHash: string; result: DomainInferenceResult; @@ -90,11 +74,11 @@ async function readDomainCache( const raw = await readFile(cachePath, "utf-8"); const cache = JSON.parse(raw) as Partial; - if (cache.inputHash !== inputHash) return null; // input berubah → stale + if (cache.inputHash !== inputHash) return null; // A cached result that no longer passes validation is a miss, not a crash. return sanitizeDomainResult(cache.result, input); } catch { - return null; // file tidak ada atau corrupt → miss + return null; // missing or corrupt cache file is a miss } } @@ -114,45 +98,29 @@ async function writeDomainCache( }; await writeFile(cachePath, JSON.stringify(cache, null, 2) + "\n", "utf-8"); } catch { - // Cache write gagal = non-fatal, lanjut tanpa cache + // A failed cache write only costs a repeat LLM call next run. } } -// --------------------------------------------------------------------------- -// Main entry -// --------------------------------------------------------------------------- - /** - * inferDomain — kirim structured metadata ke AI, dapat domain understanding. - * - * INTENTIONALLY tidak kirim raw source code — hanya metadata terstruktur. - * Ini menjaga token usage minimal (~300-500 token per call) dan - * memastikan AI focus pada domain inference, bukan code analysis. + * Infers the project domain from structured metadata only, never raw source, which + * keeps a call to ~300-500 tokens. Returns null when the input is too thin, the + * model fails or its answer does not validate; the static features stand on their own. * - * Cache: result di-cache di .devmap/domain-cache.json berdasarkan hash input. - * Kalau input tidak berubah, cached result dipakai langsung (no LLM call). - * Ini memastikan analyze idempotent — feature names tidak berubah tiap run. - * - * Dipanggil SETELAH static analysis selesai (Step 1-4) — sebagai enhancement, - * bukan replacement. Kalau AI unavailable, static features tetap ada. - * - * @param input - Structured metadata dari static analysis - * @param callAI - Injected AI caller — decoupled dari provider specifics - * @param projectRoot - Root project path, untuk baca/tulis cache + * With `projectRoot`, an unchanged input is answered from the cache without calling `callAI`. */ export async function inferDomain( input: DomainInferenceInput, callAI: (prompt: string) => Promise, projectRoot?: string ): Promise { - // Skip kalau data terlalu sedikit — AI inference gak akan meaningful + // With neither entities nor capabilities the model has nothing to infer from. if (input.entityNames.length === 0 && input.capabilities.length === 0) { return null; } const inputHash = hashDomainInput(input); - // Cache hit → return langsung, no LLM call if (projectRoot) { const cached = await readDomainCache(projectRoot, inputHash, input); if (cached) return cached; @@ -165,32 +133,18 @@ export async function inferDomain( const result = parseDomainInferenceResponse(raw, input); if (!result) return null; - // Tulis ke cache buat run berikutnya if (projectRoot) { await writeDomainCache(projectRoot, inputHash, result); } return result; } catch { - // AI inference adalah enhancement, bukan blocker - // Kalau gagal, return null — caller tetap punya static features + // Any model or network failure is non-fatal. return null; } } -// --------------------------------------------------------------------------- -// Prompt builder -// --------------------------------------------------------------------------- - -/** - * buildDomainInferencePrompt — build minimal, structured prompt. - * - * Design principles: - * - Compact: hanya kirim yang AI butuhkan - * - Structured: JSON input biar AI gak perlu parse prose - * - Focused: satu task, satu output format - * - Bounded: max_tokens 600 cukup buat domain inference - */ +// The caller caps the completion at 600 tokens (commands/analyze.ts), enough for this JSON shape. function buildDomainInferencePrompt(input: DomainInferenceInput): string { const metadata = JSON.stringify({ framework: input.framework, @@ -230,10 +184,6 @@ Rules: - Entity names alone (e.g. 'Message', 'Room', 'User') are NOT reliable signals of application domain. The same entity name can represent a chat message, an activity log, a personal note, or a comment — depending on ownership pattern, not naming. Use ownershipPattern and absentCapabilities as primary evidence: single_user_isolated strongly suggests a personal/private tool (notes, journal, tracker), not a multi-user communication platform. Only conclude 'chat' or 'messaging' domain if ownershipPattern is shared_access or direct_messaging, or detectedCapabilities includes collaboration/social/real-time.`; } -// --------------------------------------------------------------------------- -// Response parser -// --------------------------------------------------------------------------- - const domainFeatureSchema = z.object({ name: z.string().trim().min(1).max(80), purpose: z.string().trim().min(1).max(300), @@ -250,18 +200,18 @@ const domainResultSchema = z.object({ domainFeatures: z.array(z.unknown()).optional() }); -/** - * Single gate for everything the model (or a stale cache file) hands back. - * Wrong types are rejected instead of crashing later, and a domain feature only - * survives with entities that really exist in the static analysis, because an - * AI feature has no files of its own to be grounded in. - */ // Every app has these; a feature that only touches them is not specific to the domain. const GENERIC_ENTITIES = new Set([ "user", "users", "account", "accounts", "session", "sessions", "verificationtoken", "verification", "token", "role", "roles", "permission", "permissions", "profile" ]); +/** + * Single gate for everything the model (or a stale cache file) hands back. + * Wrong types are rejected instead of crashing later, and a domain feature only + * survives with entities that really exist in the static analysis, because an + * AI feature has no files of its own to be grounded in. + */ function sanitizeDomainResult( value: unknown, input: DomainInferenceInput @@ -306,7 +256,7 @@ function parseDomainInferenceResponse( input: DomainInferenceInput ): DomainInferenceResult | null { try { - // Strip markdown fences kalau ada + // Models wrap JSON in markdown fences despite the prompt. const cleaned = raw .replace(/^```json\s*/i, "") .replace(/^```\s*/i, "") @@ -319,10 +269,6 @@ function parseDomainInferenceResponse( } } -// --------------------------------------------------------------------------- -// Helper — convert DomainFeature ke FeatureInfo buat merge ke snapshot -// --------------------------------------------------------------------------- - export function domainFeaturesToFeatureInfo( domainFeatures: DomainFeature[] ): FeatureInfo[] { @@ -332,24 +278,18 @@ export function domainFeaturesToFeatureInfo( files: [], entryPoints: [], businessFlow: [], - // searchTerms include relatedEntities agar similarity engine dapat - // mencocokkan AI feature dengan static feature via entity overlap. - // Contoh: AI returns relatedEntities: ["Plan", "Subscription"] - // Static feature "Plan Management" punya searchTerms: ["plan", "subscription", ...] - // → entityOverlap / termOverlap tinggi → di-merge, bukan duplicate. + // Entities go into searchTerms so the similarity engine can match an AI feature to a + // static one: relatedEntities ["Plan", "Subscription"] overlaps the searchTerms of + // "Plan Management" and merges instead of duplicating it. searchTerms: [ ...df.relatedEntities.map((e) => e.toLowerCase()), ...df.name.toLowerCase().split(/\s+/).filter(Boolean) ].filter((v, i, arr) => arr.indexOf(v) === i).slice(0, 12), - confidence: "medium" as const, // AI-inferred = medium, bukan high + confidence: "medium" as const, // AI-inferred is never high evidence: [] })); } -// --------------------------------------------------------------------------- -// Helper — build DomainInferenceInput dari projectMap data -// --------------------------------------------------------------------------- - const ALL_CAPABILITY_KINDS: CapabilityKind[] = [ "crud", "sharing", "collaboration", "discovery", "publishing", "social", "file-management", "real-time", "search", "reporting", diff --git a/packages/cli/src/cache/agentNavigation.ts b/packages/cli/src/cache/agentNavigation.ts index 9b490cf..5f7571e 100644 --- a/packages/cli/src/cache/agentNavigation.ts +++ b/packages/cli/src/cache/agentNavigation.ts @@ -163,9 +163,8 @@ function selectIndexCriticalFiles(snapshot: ProjectMap): string[] { } // BFS distance from the nearest entry point over the resolved dependency graph. -// Without this, calculateStartHereScore had no way to prefer "the file the -// entry point calls directly" over "some file three imports deeper" — both -// only differed by generic importance, which doesn't track call-graph order. +// Lets the start-here score prefer a file the entry point imports directly over +// one several imports deeper; generic importance does not track call-graph order. function computeEntryDistance(snapshot: ProjectMap): Map { const distance = new Map(); const queue: string[] = []; diff --git a/packages/cli/test/agent-navigation.test.ts b/packages/cli/test/agent-navigation.test.ts index 3e1b98a..4e4adec 100644 --- a/packages/cli/test/agent-navigation.test.ts +++ b/packages/cli/test/agent-navigation.test.ts @@ -202,12 +202,8 @@ test("agent navigation describes mixed CLI workspaces without misleading agents" }; assert.deepEqual(index.project.projectTypes, ["web-app", "node-cli"]); - // A mixed workspace still surfaces its real, detected framework — agents - // aren't misled because `projectTypes`/`frameworks` sit right alongside - // it in the same object, spelling out "this repo also has a CLI". - // Nulling `framework` here used to hide a correctly-detected Astro app - // behind "unknown" for any monorepo that happens to contain a bin field - // anywhere (e.g. devmap's own repo). See project-metadata.test.ts. + // `framework` must stay the detected one: a `bin` field anywhere in a monorepo + // must not turn it into "unknown". See project-metadata.test.ts. assert.equal(index.project.framework, "astro"); assert.deepEqual(index.project.frameworks, ["astro"]); diff --git a/packages/cli/test/analyzer-grounding.test.ts b/packages/cli/test/analyzer-grounding.test.ts index f51fa9b..0e59de7 100644 --- a/packages/cli/test/analyzer-grounding.test.ts +++ b/packages/cli/test/analyzer-grounding.test.ts @@ -37,10 +37,6 @@ async function withProject(files: Record, run: (root: string) => const PACKAGE = JSON.stringify({ name: "fixture", dependencies: {} }); -// --------------------------------------------------------------------------- -// Project metadata: nothing is reported that the files do not show -// --------------------------------------------------------------------------- - test("a project without TypeScript or JavaScript files reports its own language, never typescript", () => { const files = [ scanned("manage.py", "import os\n"), @@ -126,8 +122,6 @@ test("a runtime dependency on a server framework is enough", () => { assert.deepEqual(detectFrameworks([scanned("package.json", manifest)]), ["fastify"]); }); -// The settings-only pnpm-workspace.yaml (onlyBuiltDependencies, overrides) is what pnpm 10 -// projects commonly have; only a `packages` list declares workspace members. async function metadataOf(files: Record, frameworks: Parameters[3]) { let project: ReturnType | undefined; await withProject(files, async (root) => { @@ -136,6 +130,8 @@ async function metadataOf(files: Record, frameworks: Parameters< return project as ReturnType; } +// pnpm 10 projects commonly have a settings-only pnpm-workspace.yaml (onlyBuiltDependencies, +// overrides); only a `packages` list declares workspace members. test("pnpm-workspace.yaml without a packages list does not make a monorepo", async () => { const project = await metadataOf({ "package.json": JSON.stringify({ name: "app", dependencies: { next: "^15.0.0" } }), @@ -191,10 +187,6 @@ test("declaration files are never entry points, and type-test folders are not pr assert.equal(isArchitectureSource("src/search/query.ts"), true); }); -// --------------------------------------------------------------------------- -// Features: names, ids and search terms stay tied to the project's own evidence -// --------------------------------------------------------------------------- - test("search terms list only the vocabulary the project's files contain", async () => { await withProject({ "package.json": PACKAGE, @@ -267,10 +259,6 @@ test("agent navigation keeps both features when two names slug to the same id", }); }); -// --------------------------------------------------------------------------- -// Domain inference: a bad model answer or a bad cache never breaks analysis -// --------------------------------------------------------------------------- - const DOMAIN_INPUT: DomainInferenceInput = { entityNames: ["Order", "Customer"], relations: [{ from: "Order", to: "Customer", kind: "belongsTo" }], diff --git a/packages/cli/test/analyzers.test.ts b/packages/cli/test/analyzers.test.ts index 5886a64..a12741e 100644 --- a/packages/cli/test/analyzers.test.ts +++ b/packages/cli/test/analyzers.test.ts @@ -449,16 +449,6 @@ test("feature detection keeps documentation and landing UI out of technical feat assert.ok(aiFeature?.files.every((path) => path.startsWith("packages/cli/src/ai/"))); }); -// NOTE: "structural feature flows describe behavior instead of repeating file -// lists" was removed here. It asserted against "Analysis Engine" / "Snapshot -// Engine" features — confirmed via fileRole.ts's own header comment that -// these DevMap-specific roles were deliberately removed in favor of generic -// architectural roles (api-handler, service, middleware, repository, -// ui-component, ai-integration, cli-command). The test was never updated -// after that removal. If you want a regression test for "business flows -// describe behavior, not a file list" against a role that still exists -// (e.g. "CLI Commands"), that's a good follow-up but needs fresh fixture -// data verified against real output first. test("project map summarizes a Next.js fixture", async () => { const projectMap = await createProjectMap(nextFixture); diff --git a/packages/cli/test/audit-regressions.test.ts b/packages/cli/test/audit-regressions.test.ts index 80dd677..1b3fa5f 100644 --- a/packages/cli/test/audit-regressions.test.ts +++ b/packages/cli/test/audit-regressions.test.ts @@ -36,8 +36,6 @@ async function withProject(files: Record, run: (root: string) => } } -// ------------------------------------------------------------ Vue SFC with two script blocks - const TWO_BLOCKS = [ "