From c3bcd759c4a96764ae8aaf99d6a65aa8c375b91d Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:12:53 +0700 Subject: [PATCH 1/5] fix(cli,nestjs): honor ignoreFindings in visualize and share the config reader - `archmind visualize` passed no options to explain(), so finding types listed in archmind.json `ignoreFindings` still appeared in the HTML report. It now reads the config and passes `{ ignore }`, like `archmind findings`. - nestjs-parser drops its private copy of loadUserConfig and uses the one in @kidkender/archmind-protocol (same behavior); requires protocol ^0.5.1. --- apps/cli/src/commands/visualize.ts | 13 ++++++++----- package-lock.json | 2 +- packages/nestjs-parser/package.json | 2 +- packages/nestjs-parser/src/adapter.ts | 15 ++------------- 4 files changed, 12 insertions(+), 20 deletions(-) diff --git a/apps/cli/src/commands/visualize.ts b/apps/cli/src/commands/visualize.ts index 6587e26..00778e0 100644 --- a/apps/cli/src/commands/visualize.ts +++ b/apps/cli/src/commands/visualize.ts @@ -2,18 +2,20 @@ import { writeFileSync } from "fs" import { join, resolve } from "path" import { execSync } from "child_process" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" -import { IR_NODE_TYPES, toIRNodeType } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES, toIRNodeType, loadUserConfig } from "@kidkender/archmind-protocol" import { parseProject, requireProject } from "../utils/parse-project.js" // --------------------------------------------------------------------------- // Lazy import explainer (optional dep — visualize still works without findings) // --------------------------------------------------------------------------- -function tryExplain(graph: IntermediateExecutionGraph): Finding[] { +function tryExplain(graph: IntermediateExecutionGraph, ignore?: string[]): Finding[] { try { // eslint-disable-next-line @typescript-eslint/no-require-imports - const { explain } = require("@kidkender/archmind-explainer") as { explain: (g: IntermediateExecutionGraph) => Finding[] } - return explain(graph) + const { explain } = require("@kidkender/archmind-explainer") as { + explain: (g: IntermediateExecutionGraph, query?: string, opts?: { ignore?: string[] }) => Finding[] + } + return explain(graph, undefined, { ignore }) } catch { return [] } @@ -510,11 +512,12 @@ export async function runVisualize(flags: Record): Promise const { graphs, routeCount } = parseProject(projectRoot) console.log(`Parsed ${routeCount} routes`) + const ignore = loadUserConfig(projectRoot)?.ignoreFindings const routes: RouteData[] = [] let criticalTotal = 0 for (const graph of graphs) { - const findings = tryExplain(graph) + const findings = tryExplain(graph, ignore) const route = buildRouteData(graph, findings) routes.push(route) criticalTotal += route.criticalCount diff --git a/package-lock.json b/package-lock.json index cb74b89..a64cd55 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6490,7 +6490,7 @@ "version": "0.7.1", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, diff --git a/packages/nestjs-parser/package.json b/packages/nestjs-parser/package.json index f5a3753..968a782 100644 --- a/packages/nestjs-parser/package.json +++ b/packages/nestjs-parser/package.json @@ -36,7 +36,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "js-yaml": "^4.3.2", "ts-morph": "^23.0.0" }, diff --git a/packages/nestjs-parser/src/adapter.ts b/packages/nestjs-parser/src/adapter.ts index 401437d..48a1667 100644 --- a/packages/nestjs-parser/src/adapter.ts +++ b/packages/nestjs-parser/src/adapter.ts @@ -1,6 +1,5 @@ -import { existsSync, readFileSync } from "fs" -import { join } from "path" -import type { IntermediateExecutionGraph, ArchMindUserConfig } from "@kidkender/archmind-protocol" +import { loadUserConfig } from "@kidkender/archmind-protocol" +import type { IntermediateExecutionGraph } from "@kidkender/archmind-protocol" import type { SemanticAdapter } from "@kidkender/archmind-protocol" import type { Project } from "ts-morph" import { extractRoutes } from "./extractors/route.extractor.js" @@ -13,16 +12,6 @@ import type { NestJSSemanticRoute } from "./types.js" import type { GuardDescriptor } from "./types.js" import type { DTOSchema } from "@kidkender/archmind-protocol" -function loadUserConfig(projectRoot: string): ArchMindUserConfig | undefined { - const configPath = join(projectRoot, "archmind.json") - if (!existsSync(configPath)) return undefined - try { - return JSON.parse(readFileSync(configPath, "utf-8")) as ArchMindUserConfig - } catch { - return undefined - } -} - export class NestJSAdapter implements SemanticAdapter { parseProject(root: string): IntermediateExecutionGraph[] { const userConfig = loadUserConfig(root) From 8a90e63280f53e98e17c911a0d258cbb932587ae Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:12:53 +0700 Subject: [PATCH 2/5] feat(springboot-parser): read archmind.json guards for project annotations The Spring Boot adapter never loaded archmind.json, so `guards` had no effect on Spring Boot projects. It now reads the config through loadUserConfig: annotation names under `guards.auth_gate` emit ir:auth_gate, names under `guards.authz_check` emit ir:auth_gate -> ir:authz_check. The config wins over the built-in rules, so a listed Shiro `@RequiresRoles` is no longer ir:unknown_middleware. A malformed archmind.json is ignored. Requires protocol ^0.5.1. docs: bring next-version-ideas.md in line with v0.9.1 (benchmark CLI, graph diff, CI and lens shipped; modular Laravel partial; new items #10 and #11; reordered priorities). --- docs/next-version-ideas.md | 50 ++++++++--- package-lock.json | 2 +- packages/springboot-parser/README.md | 5 ++ .../__tests__/adapter-user-config.test.ts | 89 +++++++++++++++++++ packages/springboot-parser/package.json | 2 +- packages/springboot-parser/src/adapter.ts | 5 +- .../src/controller-parser.ts | 18 +++- packages/springboot-parser/src/ir-emitter.ts | 1 + packages/springboot-parser/src/types.ts | 4 +- 9 files changed, 159 insertions(+), 17 deletions(-) create mode 100644 packages/springboot-parser/__tests__/adapter-user-config.test.ts diff --git a/docs/next-version-ideas.md b/docs/next-version-ideas.md index 6316fac..88ddb7c 100644 --- a/docs/next-version-ideas.md +++ b/docs/next-version-ideas.md @@ -2,6 +2,7 @@ > Generated: 2026-06-30 > Updated: 2026-07-03 — after v0.5.0 shipped (Spring Boot parser, AQL, Architecture Constraints, AI Context API, `archmind visualize`) +> Updated: 2026-11-10 — statuses checked against the code at v0.9.1 --- @@ -13,6 +14,10 @@ - ✅ **AI Context API** (`@kidkender/archmind-context`) — `buildSemanticContext()`, exposed via `archmind_get_context` MCP tool - ✅ **`archmind visualize`** — Execution Timeline HTML report - ✅ **Framework #4: Go/Gin** (`@kidkender/archmind-go-parser`, v0.8.x) — route, auth-gate (including runtime skip-lists), authz-check, validation-gate, and GORM transaction-boundary detection for Gin projects. Isolation/tenant scoping is not implemented yet. +- ✅ **`@kidkender/archmind-lens`** (v0.9.0–0.9.1) — Go symbol-to-entry-point call graph, exposed as MCP `archmind_symbol_context`. +- ✅ **Benchmark CLI (#2)** — `archmind benchmark` (`apps/cli/src/commands/benchmark.ts`) reads the pain specs and scores node/edge recall. +- ✅ **Graph Diff for PR review (#1)** — `archmind diff --format markdown` plus the sticky-comment workflow in `docs/ci-templates/topology-guard.yml`. +- ✅ **CI** — `.github/workflows/ci.yml` builds and tests on every push and PR to `main`. These shipped features open up new follow-on ideas below (#5, #7) that weren't possible before. @@ -22,7 +27,7 @@ These shipped features open up new follow-on ideas below (#5, #7) that weren't p **Priority:** High impact, feasible **Effort:** Medium -**Status:** Not started +**Status:** ✅ Done — `archmind diff --format markdown` + `docs/ci-templates/topology-guard.yml` (sticky PR comment) Hiện tại CI chỉ fail/pass. Next step là sinh ra **PR comment** mô tả chính xác cái gì thay đổi trong execution graph — không phải diff code mà diff topology. @@ -48,7 +53,7 @@ PR #42 — Execution Graph Changes **Priority:** High value, low effort (corpus đã có) **Effort:** Low -**Status:** Not started +**Status:** ✅ Done — `archmind benchmark` (`apps/cli/src/commands/benchmark.ts`). Still open: running it in CI on every PR. `research/semantic-pains` đã có 4 test cases với format đầy đủ, nhưng `duck benchmark run` chưa implement. Đây là low-hanging fruit để tự validate và publish kết quả công khai. @@ -176,7 +181,7 @@ archmind serve --project . --port 4000 **Priority:** Medium — real gap found via cross-repo benchmarking, not yet scoped into any plan **Effort:** Medium -**Status:** Not started +**Status:** Partial — `route-parser.ts` resolves module-style route namespaces; `project-config.ts` has no `modules/` handling and akaunting has not been re-measured Benchmarked against akaunting (642 routes) as a fresh, previously-unseen repo — archMind parsed cleanly (no crashes) but stayed almost silent (6/58 auth-gate/unknown-middleware nodes, 0 service_call/guard/txn/branch nodes despite 642 routes). Root cause: akaunting is a modular Laravel app (`nwidart/laravel-modules` or similar) — real controllers live under `modules/*/Http/Controllers/`, not `app/Http/Controllers/` as the parser assumes. This is a distinct architecture gap from the 6 gaps already fixed for IR v1.5 (koel/BookStack-driven), confirmed independently on invoiceninja and monica (both generalized cleanly with zero changes). @@ -202,7 +207,29 @@ Every parser module still wraps its `_parser.parse()` call in a bare `catch { re **Remaining deliverable:** - Replace the blanket `catch { return emptyDefaults }` in each parser module with a narrower catch (file-not-found only) so a genuine future parse failure surfaces loudly instead of reading as "no findings" — not done yet; the `maxWorkers` fix removed the trigger but the swallow-everything pattern itself is still there -**Why:** This is very likely *why* there's no CI on this repo at all — a red/green result that changes every run isn't a gate anyone can trust. +**Why:** This is very likely *why* there's no CI on this repo at all — a red/green result that changes every run isn't a gate anyone can trust. (CI now exists: `.github/workflows/ci.yml`.) + +Count at v0.9.1 of bare `catch {` in parser sources (tests excluded): laravel 36, nestjs 18, springboot 13, go 4. Not all of them wrap a parse; the ones that read a file and parse it in one `try` (e.g. `laravel-parser/src/controller-parser.ts`) are the target. + +--- + +## 10. Spring Boot does not read `archmind.json` + +**Priority:** Medium +**Effort:** Low +**Status:** ✅ Done (2026-11-10) — the adapter reads `archmind.json`; `guards.auth_gate` / `guards.authz_check` classify the project's own annotation names. `ownershipSources` stays Go-only. + +`springboot-parser` never loaded the user config, so `guards`, `authorization.ownershipSources` and the other adapter-level settings have no effect on Spring Boot projects (`ignoreFindings` still works, because `analysis`, the CLI and the MCP server apply it). Wire `loadUserConfig` from `@kidkender/archmind-protocol` into the adapter, as the Go and NestJS adapters do. + +--- + +## 11. Gin layouts still missed by go-parser + +**Priority:** Medium +**Effort:** Medium +**Status:** Open + +After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from the 0.8.2 spot-check still not handled: engine held in a struct field and mutated by a receiver method, engine wrapped in a custom type with its own `.GET()`/`.POST()`, functional-options chains, Wire-style DI. Lens limits: embedded interfaces, two types with the same name in different packages. --- @@ -210,12 +237,15 @@ Every parser module still wraps its `_parser.parse()` call in a bare `catch { re | Idea | Impact | Effort | Recommended Order | |------|--------|--------|-------------------| -| Tree-sitter flaky tests (#9) | Critical | Low (one deliverable left) | **1st** — narrow the remaining swallow-catch | -| AQL/Constraints in CI (#5) | High | Low-Medium | **2nd** — reuses shipped engine | -| Benchmark CLI (#2) | High | Low | **3rd** | -| Graph Diff PR Comment (#1) | High | Medium | **4th** | -| Modular Laravel support (#8) | Medium | Medium | **5th** | +| Narrow swallow-catch in parsers (#9) | High | Low-Medium | **1st** | +| Go tenant scoping | Medium | Medium | **3rd** | +| Remaining Gin layouts + lens limits (#11) | Medium | Medium | **4th** | +| Modular Laravel support (#8, partial) | Medium | Medium | **5th** | | Auto-fix Suggestions (#4) | Medium | Medium | **6th** | -| Framework #5 + adapter kit (#3) | High | High | **7th** — next new framework beyond Go | +| Framework #5 + adapter kit (#3) | High | High | **7th** | | Web UI Visualizer (#6) | Medium | High | **8th** | | OTel Runtime Expansion (#7) | High | High | **9th** | +| ~~AQL/Constraints in CI (#5)~~ | | | Done | +| ~~Benchmark CLI (#2)~~ | | | Done | +| ~~Graph Diff PR Comment (#1)~~ | | | Done | +| ~~Spring Boot reads `archmind.json` (#10)~~ | | | Done | diff --git a/package-lock.json b/package-lock.json index a64cd55..89be1e3 100644 --- a/package-lock.json +++ b/package-lock.json @@ -6632,7 +6632,7 @@ "version": "0.4.0", "license": "MIT", "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, diff --git a/packages/springboot-parser/README.md b/packages/springboot-parser/README.md index 12225cd..3839fe2 100644 --- a/packages/springboot-parser/README.md +++ b/packages/springboot-parser/README.md @@ -66,6 +66,11 @@ const methods = parseControllerFile("/path/to/OrderController.java") ### Security - **Per-method annotations:** `@PreAuthorize`, `@Secured`, `@RolesAllowed` +- **Project-specific annotations from `archmind.json`:** names listed under `guards.auth_gate` become `ir:auth_gate`; names under `guards.authz_check` become `ir:auth_gate` → `ir:authz_check`. They take precedence over the built-in rules, so a known-but-unclassified annotation such as Shiro's `@RequiresRoles` stops being `ir:unknown_middleware` once it is listed: + + ```json + { "guards": { "auth_gate": ["RequireLogin"], "authz_check": ["RequiresRoles", "CheckPermission"] } } + ``` - **Global `SecurityFilterChain` rules:** parses `requestMatchers().hasRole()` / `hasAnyRole()` / `permitAll()` / `denyAll()` chains and applies them to matching routes automatically ### Validation diff --git a/packages/springboot-parser/__tests__/adapter-user-config.test.ts b/packages/springboot-parser/__tests__/adapter-user-config.test.ts new file mode 100644 index 0000000..70f18d2 --- /dev/null +++ b/packages/springboot-parser/__tests__/adapter-user-config.test.ts @@ -0,0 +1,89 @@ +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { parseSpringBootProject } from "../src/adapter.js" + +const CONTROLLER = ` + package com.example.web; + import org.springframework.web.bind.annotation.*; + + @RestController + @RequestMapping("/api/orders") + public class OrderController { + @RequireLogin + @GetMapping + public String list() { return "ok"; } + + @RequiresRoles("admin") + @DeleteMapping("/{id}") + public void remove(@PathVariable Long id) { } + + @TeamOnly + @PostMapping + public void create(@RequestBody String body) { } + } +` + +function nodeTypes(graphs: ReturnType, method: string): string[] { + const g = graphs.find((x) => x.method === method) + if (!g) throw new Error(`no graph for ${method}`) + return g.nodes.map((n) => n.type) +} + +describe("parseSpringBootProject — archmind.json guards", () => { + let dir: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-sb-config-")) + writeFileSync(join(dir, "OrderController.java"), CONTROLLER) + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + test("without archmind.json, known-but-unclassified annotations stay ir:unknown_middleware", () => { + const graphs = parseSpringBootProject(dir) + + expect(nodeTypes(graphs, "GET")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + expect(nodeTypes(graphs, "DELETE")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + // @TeamOnly is not a recognised name at all + expect(nodeTypes(graphs, "POST")).not.toContain(IR_NODE_TYPES.AUTH_GATE) + expect(nodeTypes(graphs, "POST")).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + }) + + test("guards.auth_gate and guards.authz_check classify the project's own annotations", () => { + writeFileSync(join(dir, "archmind.json"), JSON.stringify({ + guards: { auth_gate: ["RequireLogin"], authz_check: ["RequiresRoles", "TeamOnly"] }, + })) + + const graphs = parseSpringBootProject(dir) + + const get = nodeTypes(graphs, "GET") + expect(get).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(get).not.toContain(IR_NODE_TYPES.AUTHZ_CHECK) + expect(get).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + + const del = nodeTypes(graphs, "DELETE") + expect(del).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(del).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + expect(del).not.toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + + const post = nodeTypes(graphs, "POST") + expect(post).toContain(IR_NODE_TYPES.AUTH_GATE) + expect(post).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + + const authz = graphs.find((g) => g.method === "DELETE")!.nodes + .find((n) => n.type === IR_NODE_TYPES.AUTHZ_CHECK)! + expect(authz.symbol).toBe(`@RequiresRoles(admin)`) + }) + + test("a malformed archmind.json is ignored", () => { + writeFileSync(join(dir, "archmind.json"), "{ not json") + + const graphs = parseSpringBootProject(dir) + + expect(nodeTypes(graphs, "GET")).toContain(IR_NODE_TYPES.UNKNOWN_MIDDLEWARE) + }) +}) diff --git a/packages/springboot-parser/package.json b/packages/springboot-parser/package.json index 8c6d7f3..bfe0a4f 100644 --- a/packages/springboot-parser/package.json +++ b/packages/springboot-parser/package.json @@ -22,7 +22,7 @@ "test": "node --experimental-vm-modules ../../node_modules/jest/bin/jest.js" }, "dependencies": { - "@kidkender/archmind-protocol": "^0.5.0", + "@kidkender/archmind-protocol": "^0.5.1", "tree-sitter": "^0.21.0", "tree-sitter-java": "^0.23.5" }, diff --git a/packages/springboot-parser/src/adapter.ts b/packages/springboot-parser/src/adapter.ts index 1438c05..c364239 100644 --- a/packages/springboot-parser/src/adapter.ts +++ b/packages/springboot-parser/src/adapter.ts @@ -1,7 +1,7 @@ import { randomUUID } from "crypto" import type { IntermediateExecutionGraph, ExecutionNode, ExecutionEdge } from "@kidkender/archmind-protocol" import type { SemanticAdapter } from "@kidkender/archmind-protocol" -import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION } from "@kidkender/archmind-protocol" +import { IR_NODE_TYPES, IR_EDGE_RELATIONS, IR_VERSION, loadUserConfig } from "@kidkender/archmind-protocol" import { findJavaFiles, isEntrypointFile } from "./scanner.js" import { parseControllerFile } from "./controller-parser.js" import { emitGraph } from "./ir-emitter.js" @@ -11,6 +11,7 @@ import { buildServiceTransactionIndex, type ServiceTransactionIndex } from "./se export class SpringBootAdapter implements SemanticAdapter { parseProject(root: string): IntermediateExecutionGraph[] { + const userConfig = loadUserConfig(root) const allFiles = findJavaFiles(root) const controllerFiles = allFiles.filter(isEntrypointFile) @@ -23,7 +24,7 @@ export class SpringBootAdapter implements SemanticAdapter { for (const file of controllerFiles) { try { - const methods = parseControllerFile(file, baseClassIndex) + const methods = parseControllerFile(file, baseClassIndex, userConfig) const controllerModule = moduleRootOf(file) for (const m of methods) { const graph = emitGraph(m, root) diff --git a/packages/springboot-parser/src/controller-parser.ts b/packages/springboot-parser/src/controller-parser.ts index 819eac9..20eda29 100644 --- a/packages/springboot-parser/src/controller-parser.ts +++ b/packages/springboot-parser/src/controller-parser.ts @@ -2,6 +2,7 @@ import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import type { ArchMindUserConfig } from "@kidkender/archmind-protocol" import { moduleRootOf } from "./security-config-parser.js" import type { SpringControllerMethod, AuthAnnotation, ServiceCall, DataAccessCall, EventPublication, HttpMethod, @@ -55,6 +56,7 @@ const MESSAGING_LISTENER_ANNS: Record = { export function parseControllerFile( filePath: string, baseClassIndex?: Map, + userConfig?: ArchMindUserConfig, ): SpringControllerMethod[] { let source: string try { @@ -131,7 +133,7 @@ export function parseControllerFile( const methodTxn = classTxn || hasAnnotation(mods, new Set(["Transactional"])) const readOnly = isReadOnlyTxn(mods) - const authAnnotations = extractAuthAnnotations(mods) + const authAnnotations = extractAuthAnnotations(mods, userConfig) const { hasValidation, validatedParamTypes } = extractValidationInfo(methodNode) const body = methodNode.childForFieldName("body") ?? @@ -365,13 +367,25 @@ const UNKNOWN_SECURITY_ANN_NAMES = new Set([ "CheckPermission", // common custom naming ]) -function extractAuthAnnotations(modifiers: Parser.SyntaxNode): AuthAnnotation[] { +function extractAuthAnnotations(modifiers: Parser.SyntaxNode, userConfig?: ArchMindUserConfig): AuthAnnotation[] { const out: AuthAnnotation[] = [] + const customAuthGate = userConfig?.guards?.auth_gate + const customAuthzCheck = userConfig?.guards?.authz_check for (const child of modifiers.children) { if (child.type !== "annotation" && child.type !== "marker_annotation") continue const name = getAnnotationName(child) if (!name) continue + // archmind.json `guards` names the project's own security annotations. + // The project knows their meaning, so this wins over the built-in rules. + const isCustomAuthz = customAuthzCheck?.includes(name) ?? false + const isCustomAuth = !isCustomAuthz && (customAuthGate?.includes(name) ?? false) + if (isCustomAuthz || isCustomAuth) { + const expr = getAnnotationStringArg(child) ?? "" + out.push({ kind: "custom", expression: `@${name}${expr ? `(${expr})` : ""}`, isAuthOnly: isCustomAuth }) + continue + } + if (name === "PreAuthorize") { const expr = getAnnotationStringArg(child) ?? "" const isAuthOnly = /^\s*isAuthenticated\(\)\s*$/.test(expr) || diff --git a/packages/springboot-parser/src/ir-emitter.ts b/packages/springboot-parser/src/ir-emitter.ts index ede05ea..015f491 100644 --- a/packages/springboot-parser/src/ir-emitter.ts +++ b/packages/springboot-parser/src/ir-emitter.ts @@ -230,5 +230,6 @@ function formatAuthSymbol(ann: AuthAnnotation): string { case "rolesAllowed": return `@RolesAllowed("${ann.expression}")` // "unknown" is handled earlier (emitted as ir:unknown_middleware) and never reaches here. case "unknown": return ann.expression + case "custom": return ann.expression } } diff --git a/packages/springboot-parser/src/types.ts b/packages/springboot-parser/src/types.ts index 55defc9..0c55f29 100644 --- a/packages/springboot-parser/src/types.ts +++ b/packages/springboot-parser/src/types.ts @@ -11,7 +11,9 @@ export interface AuthAnnotation { // as ir:unknown_middleware instead of a guessed auth_gate/authz_check so the // LLM sees "there IS a security signal here, but I can't tell you its shape" // rather than silently reading it as no-auth. - kind: "preAuthorize" | "secured" | "rolesAllowed" | "unknown" + // "custom" = an annotation the project named in archmind.json `guards` + // (auth_gate → isAuthOnly true, authz_check → isAuthOnly false). + kind: "preAuthorize" | "secured" | "rolesAllowed" | "unknown" | "custom" expression: string // raw annotation value, e.g. "hasRole('ADMIN')" isAuthOnly: boolean // true when the expression only checks isAuthenticated() } From 27a0dde83e76691d8282432c432042590b70c545 Mon Sep 17 00:00:00 2001 From: kidkender Date: Tue, 10 Nov 2026 16:21:19 +0700 Subject: [PATCH 3/5] fix(laravel-parser,springboot-parser): report parse failures and parse files over 32 KiB Every parser wrapped readFileSync and tree-sitter's parse() in one bare `catch { return }`, so a parse failure read as "this file has nothing in it". That also hid a real bug: tree-sitter 0.21 throws "Invalid argument" for input past its default 32 KiB buffer, and only route-parser passed a bufferSize, so controllers and services larger than 32 KiB silently produced no auth, transaction, isolation or guard nodes. All read+parse sites now go through php-source.ts / java-source.ts: - an unreadable file (missing, a directory, no access) yields nothing, as before - the parse buffer is sized to the source - a parse failure is printed on stderr with the file path and the file is skipped Catches around JSON.parse of composer.json / archmind.json and readdirSync are unchanged. The pass-level catches in graph-augmenter.ts are left for later. --- docs/next-version-ideas.md | 4 +- .../src/__tests__/php-source.test.ts | 80 +++++++++++++++++++ .../laravel-parser/src/audit-log-parser.ts | 13 +-- .../laravel-parser/src/bootstrap-parser.ts | 13 +-- .../laravel-parser/src/constant-resolver.ts | 13 +-- .../laravel-parser/src/controller-parser.ts | 35 +++----- .../src/event-listener-mapper.ts | 12 +-- .../laravel-parser/src/guard-clause-parser.ts | 13 +-- .../laravel-parser/src/isolation-parser.ts | 13 +-- packages/laravel-parser/src/kernel-parser.ts | 24 ++---- packages/laravel-parser/src/php-source.ts | 45 +++++++++++ .../laravel-parser/src/queue-job-parser.ts | 17 ++-- .../laravel-parser/src/resource-parser.ts | 13 +-- packages/laravel-parser/src/route-parser.ts | 15 +--- .../src/route-service-provider-parser.ts | 13 +-- .../laravel-parser/src/schedule-parser.ts | 13 +-- .../laravel-parser/src/transaction-parser.ts | 13 +-- .../__tests__/java-source.test.ts | 52 ++++++++++++ .../src/controller-parser.ts | 18 +---- packages/springboot-parser/src/java-source.ts | 45 +++++++++++ .../src/service-transaction-index.ts | 18 ++--- 21 files changed, 299 insertions(+), 183 deletions(-) create mode 100644 packages/laravel-parser/src/__tests__/php-source.test.ts create mode 100644 packages/laravel-parser/src/php-source.ts create mode 100644 packages/springboot-parser/__tests__/java-source.test.ts create mode 100644 packages/springboot-parser/src/java-source.ts diff --git a/docs/next-version-ideas.md b/docs/next-version-ideas.md index 88ddb7c..fa55f74 100644 --- a/docs/next-version-ideas.md +++ b/docs/next-version-ideas.md @@ -198,7 +198,7 @@ Benchmarked against akaunting (642 routes) as a fresh, previously-unseen repo **Priority:** High — undermines trust in the whole test suite and any CI built on top of it **Effort:** Medium -**Status:** Root cause corrected + primary fix shipped 2026-09-03 (branch `fix/retrieval-flaky-tests-ci`); one deliverable still open +**Status:** ✅ Done (2026-11-10) for laravel-parser and springboot-parser — read+parse sites go through `php-source.ts` / `java-source.ts`: an unreadable file yields nothing, a parse failure is printed on stderr with the file path and the file is skipped. This also fixed files over 32 KiB (tree-sitter 0.21 throws "Invalid argument" past its default buffer; only `route-parser.ts` passed `bufferSize`, so every other parser silently returned nothing for large controllers and services). Still open: the broad `catch { /* skip */ }` around whole passes in `graph-augmenter.ts`. Initial hypothesis (below, kept for record) was a `tree-sitter@^0.21.0` / `tree-sitter-php@^0.23.12` ABI skew. **That was wrong** — disproved empirically: a plain-Node script reusing the same `Parser` singleton for 500 heavy parses in a row had zero failures. The real cause: Jest reuses one worker *process* across multiple test files in the same package; each file re-imports that package's module-level `new Parser()` singleton, and repeatedly re-loading the native tree-sitter addon into the same process is what makes `_parser.parse(source)` intermittently throw — not the grammar/core version pairing itself. Confirmed by setting `maxWorkers` high enough (in `laravel-parser`'s and `springboot-parser`'s `jest.config.js`) that every test file always gets its own process: 5/5 and then 3/3 repeated full-suite runs came back completely clean, both isolated and via `npm test`. @@ -237,7 +237,6 @@ After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from t | Idea | Impact | Effort | Recommended Order | |------|--------|--------|-------------------| -| Narrow swallow-catch in parsers (#9) | High | Low-Medium | **1st** | | Go tenant scoping | Medium | Medium | **3rd** | | Remaining Gin layouts + lens limits (#11) | Medium | Medium | **4th** | | Modular Laravel support (#8, partial) | Medium | Medium | **5th** | @@ -249,3 +248,4 @@ After 0.3.0: `gin-vue-admin` ~201/250 routes, `go-admin` 99/109. Patterns from t | ~~Benchmark CLI (#2)~~ | | | Done | | ~~Graph Diff PR Comment (#1)~~ | | | Done | | ~~Spring Boot reads `archmind.json` (#10)~~ | | | Done | +| ~~Narrow swallow-catch in parsers (#9)~~ | | | Done (graph-augmenter pass-level catches remain) | diff --git a/packages/laravel-parser/src/__tests__/php-source.test.ts b/packages/laravel-parser/src/__tests__/php-source.test.ts new file mode 100644 index 0000000..29ea882 --- /dev/null +++ b/packages/laravel-parser/src/__tests__/php-source.test.ts @@ -0,0 +1,80 @@ +import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globals" +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import type Parser from "tree-sitter" +import { parseOptionsFor, parseSource, parsePhpFile } from "../php-source.js" +import { parseTransactions } from "../transaction-parser.js" + +// A controller well past tree-sitter 0.21's default 32 KiB parse buffer: the +// transaction sits after ~40 KB of filler methods. +function largeController(): string { + const filler = Array.from({ length: 400 }, (_, i) => + ` public function helper${i}()\n {\n return ['key${i}' => 'value value value value value value value value value'];\n }\n`, + ).join("\n") + return ` { + let dir: string + let warn: ReturnType + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-php-source-")) + warn = jest.spyOn(console, "warn").mockImplementation(() => {}) + }) + + afterEach(() => { + warn.mockRestore() + rmSync(dir, { recursive: true, force: true }) + }) + + test("sizes the parse buffer only for sources of 32 KiB or more", () => { + expect(parseOptionsFor(" { + const source = largeController() + expect(source.length).toBeGreaterThan(32 * 1024) + const file = join(dir, "BigController.php") + writeFileSync(file, source) + + const result = parseTransactions(file, "store") + + expect(result.hasTransaction).toBe(true) + expect(warn).not.toHaveBeenCalled() + }) + + test("a missing file yields null without a warning", () => { + const fakeParser = { parse: () => { throw new Error("should not be called") } } as unknown as Parser + expect(parsePhpFile(fakeParser, join(dir, "Missing.php"))).toBeNull() + expect(warn).not.toHaveBeenCalled() + }) + + test("a parse failure is reported with the file path and yields null", () => { + const failing = { parse: () => { throw new Error("Invalid argument") } } as unknown as Parser + + expect(parseSource(failing, " - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return [] diff --git a/packages/laravel-parser/src/bootstrap-parser.ts b/packages/laravel-parser/src/bootstrap-parser.ts index 724e3ba..d62b99a 100644 --- a/packages/laravel-parser/src/bootstrap-parser.ts +++ b/packages/laravel-parser/src/bootstrap-parser.ts @@ -1,9 +1,9 @@ -import { readFileSync } from "fs" import { join, relative, normalize } from "path" // @ts-ignore import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { AliasMap } from "./kernel-parser.js" @@ -30,14 +30,9 @@ type AstNode = { type: string; children: AstNode[]; namedChildren: AstNode[]; te * Returns empty aliasMap and routeFiles if the file cannot be read or parsed. */ export function parseBootstrap(filePath: string, projectRoot: string): BootstrapParseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { aliasMap: {}, routeFiles: [], routePrefixes: new Map() } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { aliasMap: {}, routeFiles: [], routePrefixes: new Map() } + const { source, tree } = parsed const root = tree.rootNode as AstNode const aliasMap = extractAliasMap(root) diff --git a/packages/laravel-parser/src/constant-resolver.ts b/packages/laravel-parser/src/constant-resolver.ts index c91d206..4e92d1c 100644 --- a/packages/laravel-parser/src/constant-resolver.ts +++ b/packages/laravel-parser/src/constant-resolver.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php has no bundled types import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" // Resolved PHP class constants: ClassName → { CONST_NAME → "value" } export type ConstantMap = Record> @@ -10,14 +10,9 @@ const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) export function parseConstantClass(filePath: string): ConstantMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const map: ConstantMap = {} walkNode(tree.rootNode, null, map) return map diff --git a/packages/laravel-parser/src/controller-parser.ts b/packages/laravel-parser/src/controller-parser.ts index 9fb9121..eacbcef 100644 --- a/packages/laravel-parser/src/controller-parser.ts +++ b/packages/laravel-parser/src/controller-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import { extractReturnedResources } from "./resource-parser.js" import { classifyDispatch } from "./transaction-parser.js" import { isGuardClauseMethodNode } from "./guard-clause-parser.js" @@ -122,14 +122,9 @@ export function parseControllerMethod( filePath: string, methodName: string ): ControllerL1 | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const useMap = extractUseMap(root) @@ -241,14 +236,9 @@ export function parseControllerMethod( * Returns undefined if the file can't be parsed or has no authorize() method. */ export function parseFormRequestAuthorize(filePath: string): string | undefined { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return undefined - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return undefined + const { source, tree } = parsed const methodNode = findMethod(tree.rootNode, "authorize") if (!methodNode) return undefined @@ -1056,14 +1046,9 @@ export function detectParamDrivenBranch( argPosition: number, requestParamName: string ): ConditionalBranch | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const methodNode = findMethod(root, methodName) if (!methodNode) return null diff --git a/packages/laravel-parser/src/event-listener-mapper.ts b/packages/laravel-parser/src/event-listener-mapper.ts index e48cbe7..55f7664 100644 --- a/packages/laravel-parser/src/event-listener-mapper.ts +++ b/packages/laravel-parser/src/event-listener-mapper.ts @@ -4,6 +4,7 @@ import { join } from "path" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import { extractUseMap } from "./controller-parser.js" import { fqcnToPath } from "./project-config.js" @@ -43,14 +44,9 @@ export function parseEventListeners( const providerPath = join(projectRoot, "app/Providers/EventServiceProvider.php") if (!existsSync(providerPath)) return new Map() - let source: string - let tree: ReturnType - try { - source = readFileSync(providerPath, "utf-8") - tree = _parser.parse(source) - } catch { - return new Map() - } + const parsed = parsePhpFile(_parser, providerPath) + if (!parsed) return new Map() + const { source, tree } = parsed const root = tree.rootNode as AstNode // eslint-disable-next-line @typescript-eslint/no-explicit-any diff --git a/packages/laravel-parser/src/guard-clause-parser.ts b/packages/laravel-parser/src/guard-clause-parser.ts index ae279b2..caac970 100644 --- a/packages/laravel-parser/src/guard-clause-parser.ts +++ b/packages/laravel-parser/src/guard-clause-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -38,14 +38,9 @@ const NO_GUARD: GuardClauseResult = { isGuardClause: false, reason: null, condit * inside the method does not false-positive as a guard clause. */ export function detectGuardClause(filePath: string, methodName: string): GuardClauseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return NO_GUARD - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return NO_GUARD + const { source, tree } = parsed const methodNode = findMethod(tree.rootNode, methodName) if (!methodNode) return NO_GUARD diff --git a/packages/laravel-parser/src/isolation-parser.ts b/packages/laravel-parser/src/isolation-parser.ts index 677c97a..e4958da 100644 --- a/packages/laravel-parser/src/isolation-parser.ts +++ b/packages/laravel-parser/src/isolation-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -65,14 +65,9 @@ export function parseIsolation(filePath: string, opts: IsolationOptions = {}, me const tenantSignals = new Set(opts.tenantSignals ?? DEFAULT_TENANT_SIGNALS) const tenantContainerKeys = opts.tenantContainerKeys ?? DEFAULT_TENANT_CONTAINER_KEYS - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return { modelQueries: [], modelWrites: [], readsTenantFromContainer: false } diff --git a/packages/laravel-parser/src/kernel-parser.ts b/packages/laravel-parser/src/kernel-parser.ts index a423f08..0d34a38 100644 --- a/packages/laravel-parser/src/kernel-parser.ts +++ b/packages/laravel-parser/src/kernel-parser.ts @@ -1,8 +1,8 @@ // @ts-ignore — tree-sitter lacks ambient declarations in this workspace import Parser from "tree-sitter" -import { readFileSync } from "fs" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -20,14 +20,9 @@ export type MiddlewareGroupMap = Record * Returns an empty map if the file cannot be read or no aliases are found. */ export function parseKernel(filePath: string): AliasMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const out: AliasMap = {} findAliasProperty(tree.rootNode, out) return out @@ -38,14 +33,9 @@ export function parseKernel(filePath: string): AliasMap { * Returns an empty map if the file cannot be read or no groups are found. */ export function parseMiddlewareGroups(filePath: string): MiddlewareGroupMap { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return {} - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return {} + const { source, tree } = parsed const out: MiddlewareGroupMap = {} findMiddlewareGroupsProperty(tree.rootNode, out) return out diff --git a/packages/laravel-parser/src/php-source.ts b/packages/laravel-parser/src/php-source.ts new file mode 100644 index 0000000..1e4351a --- /dev/null +++ b/packages/laravel-parser/src/php-source.ts @@ -0,0 +1,45 @@ +import { readFileSync } from "fs" +import type Parser from "tree-sitter" + +/** + * tree-sitter 0.21 parses a string through a fixed-size buffer (32 KiB by + * default) and throws "Invalid argument" for longer input. Size the buffer to + * the source so large files (big controllers, fat services) are parsed instead + * of failing. + */ +export function parseOptionsFor(source: string): { bufferSize: number } | undefined { + return source.length >= 32 * 1024 ? { bufferSize: source.length * 2 } : undefined +} + +/** + * Parses `source` with `parser`. A parse failure is reported on stderr with the + * file path and yields null, so the caller skips the file — it no longer reads + * as "this file has nothing in it". + */ +export function parseSource(parser: Parser, source: string, filePath: string): Parser.Tree | null { + try { + return parser.parse(source, undefined, parseOptionsFor(source)) + } catch (err) { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] laravel-parser: could not parse ${filePath}: ${reason} (file skipped)`) + return null + } +} + +/** Reads a file. A file that cannot be read (missing, a directory, no access) yields null. */ +export function readSource(filePath: string): string | null { + try { + return readFileSync(filePath, "utf-8") + } catch { + return null + } +} + +/** Reads and parses a PHP file; null when it cannot be read or parsed (see parseSource). */ +export function parsePhpFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { + const source = readSource(filePath) + if (source === null) return null + const tree = parseSource(parser, source, filePath) + if (!tree) return null + return { source, tree } +} diff --git a/packages/laravel-parser/src/queue-job-parser.ts b/packages/laravel-parser/src/queue-job-parser.ts index 13a4ea8..9e3fe07 100644 --- a/packages/laravel-parser/src/queue-job-parser.ts +++ b/packages/laravel-parser/src/queue-job-parser.ts @@ -10,6 +10,7 @@ import { join } from "path" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parseSource, readSource } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" @@ -21,21 +22,13 @@ const SKIP_DIRS = new Set(["node_modules", "vendor", "storage", "bootstrap", ".g /** Parse a single file for a ShouldQueue job class. Returns null if not a queued job. */ export function parseQueuedJob(filePath: string): IntermediateExecutionGraph | null { - let source: string - try { - source = readFileSync(filePath, "utf-8") - } catch { - return null - } + const source = readSource(filePath) + if (source === null) return null // Cheap string pre-filter before paying for a tree-sitter parse. if (!source.includes("ShouldQueue")) return null - let tree: ReturnType - try { - tree = _parser.parse(source) - } catch { - return null - } + const tree = parseSource(_parser, source, filePath) + if (!tree) return null const cls = findShouldQueueClass(tree.rootNode) if (!cls) return null diff --git a/packages/laravel-parser/src/resource-parser.ts b/packages/laravel-parser/src/resource-parser.ts index 538ffea..6be1c9d 100644 --- a/packages/laravel-parser/src/resource-parser.ts +++ b/packages/laravel-parser/src/resource-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -36,14 +36,9 @@ const SENSITIVE_PATTERNS = /secret|token|password|passwd|internal|admin_|_admin| * Returns null if the file can't be parsed or has no toArray() method. */ export function parseApiResource(filePath: string): ApiResourceInfo | null { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return null - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return null + const { source, tree } = parsed const root = tree.rootNode const className = extractClassName(root) diff --git a/packages/laravel-parser/src/route-parser.ts b/packages/laravel-parser/src/route-parser.ts index 2a7e249..e1e75b4 100644 --- a/packages/laravel-parser/src/route-parser.ts +++ b/packages/laravel-parser/src/route-parser.ts @@ -1,8 +1,8 @@ -import { readFileSync } from "fs" import { dirname, join } from "path" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode, @@ -80,16 +80,9 @@ function processFile( out: IntermediateExecutionGraph[], opts: ParseOptions ): void { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - // Large files (> 32KB) require a bigger internal parse buffer - const bufferSize = source.length > 32_768 ? 1024 * 1024 : undefined - tree = _parser.parse(source, undefined, bufferSize ? { bufferSize } : undefined) - } catch { - return - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return + const { tree } = parsed const useMap = extractUseMap(tree.rootNode) walkBlock(tree.rootNode, ctx, out, filePath, opts, useMap) } diff --git a/packages/laravel-parser/src/route-service-provider-parser.ts b/packages/laravel-parser/src/route-service-provider-parser.ts index 26846e1..38cfc32 100644 --- a/packages/laravel-parser/src/route-service-provider-parser.ts +++ b/packages/laravel-parser/src/route-service-provider-parser.ts @@ -1,8 +1,8 @@ -import { readFileSync } from "fs" import { dirname, join, normalize, relative } from "path" import Parser from "tree-sitter" // @ts-ignore — tree-sitter lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -67,14 +67,9 @@ function parseProvider( const middleware: RouteWrappingMap = new Map() const namespace: RouteNamespaceMap = new Map() const prefix: RoutePrefixMap = new Map() - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { middleware, namespace, prefix } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { middleware, namespace, prefix } + const { source, tree } = parsed const classNamespaceProperty = findClassNamespaceProperty(tree.rootNode) walk(tree.rootNode, filePath, projectRoot, middleware, namespace, prefix, classNamespaceProperty) return { middleware, namespace, prefix } diff --git a/packages/laravel-parser/src/schedule-parser.ts b/packages/laravel-parser/src/schedule-parser.ts index e3da3b8..450cd7b 100644 --- a/packages/laravel-parser/src/schedule-parser.ts +++ b/packages/laravel-parser/src/schedule-parser.ts @@ -5,10 +5,10 @@ // Mirrors the Spring Boot @Scheduled and NestJS @Cron entrypoint kind so all // three frameworks emit an equivalent EntrypointDescriptor{type:"cron"}. // --------------------------------------------------------------------------- -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" import type { IntermediateExecutionGraph, ExecutionNode } from "@kidkender/archmind-protocol" import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" @@ -50,14 +50,9 @@ export interface ScheduledEntry { } export function parseSchedule(filePath: string): IntermediateExecutionGraph[] { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const scheduleMethod = findScheduleMethod(tree.rootNode) if (!scheduleMethod) return [] diff --git a/packages/laravel-parser/src/transaction-parser.ts b/packages/laravel-parser/src/transaction-parser.ts index 2883356..60c7f15 100644 --- a/packages/laravel-parser/src/transaction-parser.ts +++ b/packages/laravel-parser/src/transaction-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" +import { parsePhpFile } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -69,14 +69,9 @@ export interface TransactionParseResult { * `delete()`'s graph — IR v1.5 Phase 3 fix). */ export function parseTransactions(filePath: string, methodName?: string): TransactionParseResult { - let source: string - let tree: ReturnType - try { - source = readFileSync(filePath, "utf-8") - tree = _parser.parse(source) - } catch { - return { hasTransaction: false, blocks: [] } - } + const parsed = parsePhpFile(_parser, filePath) + if (!parsed) return { hasTransaction: false, blocks: [] } + const { source, tree } = parsed const scanRoot = methodName ? findMethod(tree.rootNode, methodName) : tree.rootNode if (!scanRoot) return { hasTransaction: false, blocks: [] } diff --git a/packages/springboot-parser/__tests__/java-source.test.ts b/packages/springboot-parser/__tests__/java-source.test.ts new file mode 100644 index 0000000..c78c5cd --- /dev/null +++ b/packages/springboot-parser/__tests__/java-source.test.ts @@ -0,0 +1,52 @@ +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { IR_NODE_TYPES } from "@kidkender/archmind-protocol" +import { parseSpringBootProject } from "../src/adapter.js" + +// A controller well past tree-sitter 0.21's default 32 KiB parse buffer; the +// mapped, secured method comes after ~40 KB of filler. +function largeController(): string { + const filler = Array.from({ length: 400 }, (_, i) => + ` private String helper${i}() { return "value value value value value value value value value ${i}"; }`, + ).join("\n") + return ` +package com.example.web; +import org.springframework.web.bind.annotation.*; +import org.springframework.security.access.prepost.PreAuthorize; + +@RestController +@RequestMapping("/api/reports") +public class ReportController { +${filler} + + @PreAuthorize("hasRole('ADMIN')") + @DeleteMapping("/{id}") + public void remove(@PathVariable Long id) { } +} +` +} + +describe("parseSpringBootProject — large source files", () => { + let dir: string + + beforeEach(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-sb-large-")) + }) + + afterEach(() => { + rmSync(dir, { recursive: true, force: true }) + }) + + test("a controller larger than 32 KiB is parsed with its auth annotations", () => { + const source = largeController() + expect(source.length).toBeGreaterThan(32 * 1024) + writeFileSync(join(dir, "ReportController.java"), source) + + const graphs = parseSpringBootProject(dir) + + expect(graphs).toHaveLength(1) + expect(graphs[0]!.path).toContain("/api/reports") + expect(graphs[0]!.nodes.map((n) => n.type)).toContain(IR_NODE_TYPES.AUTHZ_CHECK) + }) +}) diff --git a/packages/springboot-parser/src/controller-parser.ts b/packages/springboot-parser/src/controller-parser.ts index 20eda29..502e1b5 100644 --- a/packages/springboot-parser/src/controller-parser.ts +++ b/packages/springboot-parser/src/controller-parser.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import { parseJavaFile } from "./java-source.js" import type { ArchMindUserConfig } from "@kidkender/archmind-protocol" import { moduleRootOf } from "./security-config-parser.js" import type { @@ -58,19 +58,9 @@ export function parseControllerFile( baseClassIndex?: Map, userConfig?: ArchMindUserConfig, ): SpringControllerMethod[] { - let source: string - try { - source = readFileSync(filePath, "utf-8") - } catch { - return [] - } - - let tree: ReturnType - try { - tree = _parser.parse(source) - } catch { - return [] - } + const parsed = parseJavaFile(_parser, filePath) + if (!parsed) return [] + const { source, tree } = parsed const root = tree.rootNode const out: SpringControllerMethod[] = [] diff --git a/packages/springboot-parser/src/java-source.ts b/packages/springboot-parser/src/java-source.ts new file mode 100644 index 0000000..5d2dc24 --- /dev/null +++ b/packages/springboot-parser/src/java-source.ts @@ -0,0 +1,45 @@ +import { readFileSync } from "fs" +import type Parser from "tree-sitter" + +/** + * tree-sitter 0.21 parses a string through a fixed-size buffer (32 KiB by + * default) and throws "Invalid argument" for longer input. Size the buffer to + * the source so large files (big controllers, generated code) are parsed instead + * of failing. + */ +export function parseOptionsFor(source: string): { bufferSize: number } | undefined { + return source.length >= 32 * 1024 ? { bufferSize: source.length * 2 } : undefined +} + +/** + * Parses `source` with `parser`. A parse failure is reported on stderr with the + * file path and yields null, so the caller skips the file — it no longer reads + * as "this file has nothing in it". + */ +export function parseSource(parser: Parser, source: string, filePath: string): Parser.Tree | null { + try { + return parser.parse(source, undefined, parseOptionsFor(source)) + } catch (err) { + const reason = err instanceof Error ? err.message : String(err) + console.warn(`[archmind] springboot-parser: could not parse ${filePath}: ${reason} (file skipped)`) + return null + } +} + +/** Reads a file. A file that cannot be read (missing, a directory, no access) yields null. */ +export function readSource(filePath: string): string | null { + try { + return readFileSync(filePath, "utf-8") + } catch { + return null + } +} + +/** Reads and parses a Java file; null when it cannot be read or parsed (see parseSource). */ +export function parseJavaFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { + const source = readSource(filePath) + if (source === null) return null + const tree = parseSource(parser, source, filePath) + if (!tree) return null + return { source, tree } +} diff --git a/packages/springboot-parser/src/service-transaction-index.ts b/packages/springboot-parser/src/service-transaction-index.ts index a0c42b3..0c7c470 100644 --- a/packages/springboot-parser/src/service-transaction-index.ts +++ b/packages/springboot-parser/src/service-transaction-index.ts @@ -1,7 +1,7 @@ -import { readFileSync } from "fs" import Parser from "tree-sitter" // @ts-ignore import Java from "tree-sitter-java" +import { parseSource, readSource } from "./java-source.js" import { moduleRootOf } from "./security-config-parser.js" const _parser = new Parser() @@ -39,20 +39,12 @@ export function buildServiceTransactionIndex(javaFiles: string[]): ServiceTransa const interfaceToImpls = new Map() for (const file of javaFiles) { - let source: string - try { - source = readFileSync(file, "utf-8") - } catch { - continue - } + const source = readSource(file) + if (source === null) continue if (!source.includes("@Transactional") && !source.includes("implements")) continue - let tree: Parser.Tree - try { - tree = _parser.parse(source) - } catch { - continue - } + const tree = parseSource(_parser, source, file) + if (!tree) continue const module = moduleRootOf(file) From de354470216dcc202f0711dde292a8c46ccfcdfc Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 15:14:31 +0700 Subject: [PATCH 4/5] perf(laravel-parser): parse each file once per run and stop walking whole trees per lookup MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Parsing files over 32 KiB (previous commit) exposed a cost that small files hid: every module (controller, transaction, isolation, guard clause, audit log) re-parsed the controller or service for every route, and each method lookup walked the whole tree through `.children`, which builds a JS array at every node. On invoiceninja the CLI ran for over 10 minutes and the machine ran out of memory; 19 routes of InvoiceController alone took 6.2 s and 517 MB. - php-source: parsed files are reused while their content is unchanged (up to 32 files, least recently used dropped; an edited file is parsed again). - findMethod is shared by the five modules (their identical private copies are removed) and uses descendantsOfType, with a per-tree name index. - extractUseMap is computed once per tree (callers get a copy). InvoiceController's 19 routes: 261 parses → 20, 6.2 s → 0.8 s, 517 MB → 20 MB, same 196 nodes. Full invoiceninja: completes in 36 s (139 s before the 32 KiB fix, when its large files were skipped). monica and akaunting graphs are identical before and after. --- .../src/__tests__/php-source.test.ts | 40 +++++++++++++- .../laravel-parser/src/audit-log-parser.ts | 20 +------ .../laravel-parser/src/controller-parser.ts | 30 ++++------- .../laravel-parser/src/guard-clause-parser.ts | 20 +------ .../laravel-parser/src/isolation-parser.ts | 20 +------ packages/laravel-parser/src/php-source.ts | 54 ++++++++++++++++++- .../laravel-parser/src/transaction-parser.ts | 20 +------ 7 files changed, 104 insertions(+), 100 deletions(-) diff --git a/packages/laravel-parser/src/__tests__/php-source.test.ts b/packages/laravel-parser/src/__tests__/php-source.test.ts index 29ea882..287a932 100644 --- a/packages/laravel-parser/src/__tests__/php-source.test.ts +++ b/packages/laravel-parser/src/__tests__/php-source.test.ts @@ -2,8 +2,10 @@ import { describe, test, expect, jest, beforeEach, afterEach } from "@jest/globa import { mkdtempSync, writeFileSync, rmSync } from "fs" import { tmpdir } from "os" import { join } from "path" -import type Parser from "tree-sitter" -import { parseOptionsFor, parseSource, parsePhpFile } from "../php-source.js" +import Parser from "tree-sitter" +// @ts-ignore — tree-sitter-php lacks ambient declarations in this workspace +import PHP from "tree-sitter-php" +import { parseOptionsFor, parseSource, parsePhpFile, findMethod } from "../php-source.js" import { parseTransactions } from "../transaction-parser.js" // A controller well past tree-sitter 0.21's default 32 KiB parse buffer: the @@ -77,4 +79,38 @@ describe("php-source", () => { expect(message).toContain("/app/Http/Controllers/X.php") expect(message).toContain("Invalid argument") }) + + test("a file is parsed once while its content is unchanged, and again after it changes", () => { + const real = new Parser() + real.setLanguage((PHP as { php?: unknown }).php ?? PHP) + let parses = 0 + const counting = { parse: (...args: unknown[]) => { parses++; return (real.parse as (...a: unknown[]) => Parser.Tree)(...args) } } as unknown as Parser + const file = join(dir, "Cached.php") + + writeFileSync(file, " { + const file = join(dir, "Methods.php") + writeFileSync(file, `>() + export function extractUseMap(root: Parser.SyntaxNode): Map { + const isRoot = !root.parent + const cached = isRoot ? useMaps.get(root.tree) : undefined + if (cached) return new Map(cached) const map = new Map() gatherUseDecls(root, map) - return map + if (isRoot) useMaps.set(root.tree, map) + return new Map(map) } function registerUseClause(clause: Parser.SyntaxNode, prefix: string, map: Map): void { @@ -310,26 +317,7 @@ function lastSegment(fqcn: string): string { // ---- Method finder ---------------------------------------------------- -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- FormRequest extraction ------------------------------------------- diff --git a/packages/laravel-parser/src/guard-clause-parser.ts b/packages/laravel-parser/src/guard-clause-parser.ts index caac970..6b1b278 100644 --- a/packages/laravel-parser/src/guard-clause-parser.ts +++ b/packages/laravel-parser/src/guard-clause-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -127,22 +127,4 @@ function isGuardIfStatement(stmt: Parser.SyntaxNode): boolean { // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} diff --git a/packages/laravel-parser/src/isolation-parser.ts b/packages/laravel-parser/src/isolation-parser.ts index e4958da..beabe4d 100644 --- a/packages/laravel-parser/src/isolation-parser.ts +++ b/packages/laravel-parser/src/isolation-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -83,25 +83,7 @@ export function parseIsolation(filePath: string, opts: IsolationOptions = {}, me // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- Container read detection ----------------------------------------- diff --git a/packages/laravel-parser/src/php-source.ts b/packages/laravel-parser/src/php-source.ts index 1e4351a..a9d5a88 100644 --- a/packages/laravel-parser/src/php-source.ts +++ b/packages/laravel-parser/src/php-source.ts @@ -35,11 +35,63 @@ export function readSource(filePath: string): string | null { } } +/** + * Parsed files, most recently used last. A route is analysed by several modules + * (controller, transaction, isolation, guard clauses, audit log), each of which + * used to re-parse the same controller or service for every route — hundreds of + * parses of one large file per project. An entry is reused only while the file's + * content is unchanged, so an edited file is parsed again. Trees are only read, + * never edited, so sharing one between modules is safe. + */ +const parsed = new Map() +/** Files kept parsed at once; enough for a route's controller and the services it reaches. */ +const PARSE_CACHE_SIZE = 32 + /** Reads and parses a PHP file; null when it cannot be read or parsed (see parseSource). */ export function parsePhpFile(parser: Parser, filePath: string): { source: string; tree: Parser.Tree } | null { const source = readSource(filePath) if (source === null) return null + const hit = parsed.get(filePath) + if (hit && hit.source === source) { + parsed.delete(filePath) + parsed.set(filePath, hit) + return hit + } const tree = parseSource(parser, source, filePath) if (!tree) return null - return { source, tree } + const entry = { source, tree } + parsed.delete(filePath) + parsed.set(filePath, entry) + if (parsed.size > PARSE_CACHE_SIZE) parsed.delete(parsed.keys().next().value as string) + return entry } + +/** + * The first method named `name` in document order (as the old recursive walks + * found it). `descendantsOfType` walks the tree natively and only wraps the + * matches; walking `.children` recursively built a JS array at every node of + * every method body, which made each lookup on a large file cost a full-tree + * allocation. + */ +export function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { + // from a tree's root, look the method up in that tree's index (built once per tree) + if (!root.parent) { + let index = methodIndex.get(root.tree) + if (!index) { + index = new Map() + for (const method of root.descendantsOfType("method_declaration")) { + const methodName = method.childForFieldName("name")?.text + if (methodName && !index.has(methodName)) index.set(methodName, method) // first in document order + } + methodIndex.set(root.tree, index) + } + return index.get(name) ?? null + } + for (const method of root.descendantsOfType("method_declaration")) { + if (method.childForFieldName("name")?.text === name) return method + } + return null +} + +/** Method name → first method_declaration with that name, per tree. */ +const methodIndex = new WeakMap>() diff --git a/packages/laravel-parser/src/transaction-parser.ts b/packages/laravel-parser/src/transaction-parser.ts index 60c7f15..e743ac8 100644 --- a/packages/laravel-parser/src/transaction-parser.ts +++ b/packages/laravel-parser/src/transaction-parser.ts @@ -1,7 +1,7 @@ import Parser from "tree-sitter" // @ts-ignore import PHP from "tree-sitter-php" -import { parsePhpFile } from "./php-source.js" +import { parsePhpFile, findMethod } from "./php-source.js" const _parser = new Parser() _parser.setLanguage((PHP as { php?: unknown }).php ?? PHP) @@ -84,25 +84,7 @@ export function parseTransactions(filePath: string, methodName?: string): Transa // ---- Method finder ------------------------------------------------------ -function findMethod(root: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - for (const child of root.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} -function findMethodIn(node: Parser.SyntaxNode, name: string): Parser.SyntaxNode | null { - if (node.type === "method_declaration") { - const nameNode = node.childForFieldName("name") - if (nameNode?.text === name) return node - } - for (const child of node.children) { - const found = findMethodIn(child, name) - if (found) return found - } - return null -} // ---- Tree traversal --------------------------------------------------- From ff7a102eb2f08f676c47a55fb4a576957da76edc Mon Sep 17 00:00:00 2001 From: kidkender Date: Thu, 12 Nov 2026 16:42:49 +0700 Subject: [PATCH 5/5] fix(laravel-parser): compare tree-sitter nodes by position, not identity MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit gatherServiceCalls folds a mutating call into the relationship accessor it is chained on ($user->apiTokens()->delete() → one "User::apiTokens()->delete") and skips the accessor when recursing with `child !== objNode`. tree-sitter 0.21 does not always return the same JS object for the same node — it depends on its node cache and on garbage collection — so in some runs the accessor was visited again and emitted as a duplicate service call. That made output vary between identical runs (koel: 1943 / 1946 / 1943 nodes; one koel method gave two different results in 6 of 50 calls) and, with the parse cache of the previous commit, made BookStack consistently wrong (3922 instead of 3917). Nodes are now compared by start/end index and type. Same build, three runs: koel 1933 and BookStack 3917 every time. New test repeats the koel pattern 60 times; it fails on the old comparison. --- .../__tests__/service-call-folding.test.ts | 63 +++++++++++++++++++ .../laravel-parser/src/controller-parser.ts | 10 ++- 2 files changed, 72 insertions(+), 1 deletion(-) create mode 100644 packages/laravel-parser/src/__tests__/service-call-folding.test.ts diff --git a/packages/laravel-parser/src/__tests__/service-call-folding.test.ts b/packages/laravel-parser/src/__tests__/service-call-folding.test.ts new file mode 100644 index 0000000..1586add --- /dev/null +++ b/packages/laravel-parser/src/__tests__/service-call-folding.test.ts @@ -0,0 +1,63 @@ +import { describe, test, expect, beforeAll, afterAll } from "@jest/globals" +import { mkdtempSync, writeFileSync, rmSync } from "fs" +import { tmpdir } from "os" +import { join } from "path" +import { parseControllerMethod } from "../controller-parser.js" + +// A mutating call chained onto a relationship accessor ($folder->playlists()->detach()) +// is folded into one service call; the accessor alone must not be emitted again. +// The skip used to compare tree-sitter nodes with `!==`, and tree-sitter does not +// always hand back the same JS object for the same node, so some runs emitted a +// duplicate "PlaylistFolder::playlists" (seen on koel: 6 of 50 runs). + +const SERVICE = `each(static function (string $playlistId) use ($folder): void { + PlaylistFolder::query() + ->whereHas('playlists', static fn ($q) => $q->whereKey($playlistId)) + ->get() + ->each(static fn (PlaylistFolder $folder) => $folder->playlists()->detach($playlistId)); + }); + $folder->playlists()->attach($playlistIds); + }); + } +} +` + +describe("parseControllerMethod — folded relationship mutations", () => { + let dir: string + let file: string + + beforeAll(() => { + dir = mkdtempSync(join(tmpdir(), "archmind-folding-")) + file = join(dir, "PlaylistFolderService.php") + writeFileSync(file, SERVICE) + }) + + afterAll(() => rmSync(dir, { recursive: true, force: true })) + + test("the accessor is folded into its mutation and not emitted on its own", () => { + const calls = parseControllerMethod(file, "addPlaylistsToFolder")!.serviceCalls.map((s) => `${s.serviceClass}::${s.method}`) + expect(calls).toContain("PlaylistFolder::playlists()->attach") + expect(calls).toContain("PlaylistFolder::playlists()->detach") + expect(calls).not.toContain("PlaylistFolder::playlists") + }) + + test("repeated runs give the same result", () => { + const seen = new Set() + for (let i = 0; i < 60; i++) { + const calls = parseControllerMethod(file, "addPlaylistsToFolder")!.serviceCalls.map((s) => `${s.serviceClass}::${s.method}`) + seen.add(JSON.stringify(calls)) + } + expect(seen.size).toBe(1) + }) +}) diff --git a/packages/laravel-parser/src/controller-parser.ts b/packages/laravel-parser/src/controller-parser.ts index 6291779..625d234 100644 --- a/packages/laravel-parser/src/controller-parser.ts +++ b/packages/laravel-parser/src/controller-parser.ts @@ -869,6 +869,11 @@ function tryExtractBaseServiceCall( return null } +/** Whether two tree-sitter nodes are the same node of the same tree (wrapper objects may differ). */ +function sameNode(a: Parser.SyntaxNode, b: Parser.SyntaxNode): boolean { + return a.startIndex === b.startIndex && a.endIndex === b.endIndex && a.type === b.type +} + function gatherServiceCalls( node: Parser.SyntaxNode, injections: Map, @@ -893,8 +898,11 @@ function gatherServiceCalls( }) // objNode is fully consumed by the combined node above — recurse // into the rest of the chain but skip re-visiting it standalone. + // Compared by position, not `!==`: tree-sitter does not guarantee + // one JS object per node (it depends on its node cache and on GC), + // so identity made the base accessor show up again in some runs. for (const child of node.children as Parser.SyntaxNode[]) { - if (child !== objNode) gatherServiceCalls(child, injections, results, requestParamVars) + if (!sameNode(child, objNode)) gatherServiceCalls(child, injections, results, requestParamVars) } return }