Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 8 additions & 5 deletions apps/cli/src/commands/visualize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 []
}
Expand Down Expand Up @@ -510,11 +512,12 @@ export async function runVisualize(flags: Record<string, string>): Promise<void>
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
Expand Down
52 changes: 41 additions & 11 deletions docs/next-version-ideas.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

---

Expand All @@ -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.

Expand All @@ -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.

Expand All @@ -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.

Expand Down Expand Up @@ -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).

Expand All @@ -193,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`.

Expand All @@ -202,20 +207,45 @@ 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.

---

## Summary Table

| 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** |
| 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 |
| ~~Narrow swallow-catch in parsers (#9)~~ | | | Done (graph-augmenter pass-level catches remain) |
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

116 changes: 116 additions & 0 deletions packages/laravel-parser/src/__tests__/php-source.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
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 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
// 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 `<?php
namespace App\\Http\\Controllers;

use Illuminate\\Support\\Facades\\DB;

class BigController extends Controller
{
${filler}
public function store()
{
DB::transaction(function () {
Order::create([]);
});
}
}
`
}

describe("php-source", () => {
let dir: string
let warn: ReturnType<typeof jest.spyOn>

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("<?php echo 1;")).toBeUndefined()
const big = "x".repeat(40_000)
expect(parseOptionsFor(big)!.bufferSize).toBeGreaterThan(big.length)
})

test("a controller larger than 32 KiB is parsed, not silently empty", () => {
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, "<?php", "/app/Http/Controllers/X.php")).toBeNull()
expect(warn).toHaveBeenCalledTimes(1)
const message = String(warn.mock.calls[0]![0])
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, "<?php class A { function one() {} }")
const first = parsePhpFile(counting, file)
const second = parsePhpFile(counting, file)
expect(parses).toBe(1)
expect(second?.tree).toBe(first?.tree)

writeFileSync(file, "<?php class A { function two() {} }")
const third = parsePhpFile(counting, file)
expect(parses).toBe(2)
expect(findMethod(third!.tree.rootNode, "two")).not.toBeNull()
expect(findMethod(third!.tree.rootNode, "one")).toBeNull()
})

test("findMethod returns the first method of that name in document order", () => {
const file = join(dir, "Methods.php")
writeFileSync(file, `<?php
class First { public function handle() { return 1; } }
class Second { public function handle() { return 2; } public function other() {} }`)
const real = new Parser()
real.setLanguage((PHP as { php?: unknown }).php ?? PHP)
const { tree } = parsePhpFile(real, file)!
const handle = findMethod(tree.rootNode, "handle")
expect(handle?.text).toContain("return 1")
expect(findMethod(tree.rootNode, "other")?.startPosition.row).toBe(2)
expect(findMethod(tree.rootNode, "missing")).toBeNull()
})
})
63 changes: 63 additions & 0 deletions packages/laravel-parser/src/__tests__/service-call-folding.test.ts
Original file line number Diff line number Diff line change
@@ -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 = `<?php
namespace App\\Services;

use App\\Models\\PlaylistFolder;
use Illuminate\\Support\\Facades\\DB;

class PlaylistFolderService
{
public function addPlaylistsToFolder(PlaylistFolder $folder, array $playlistIds): void
{
DB::transaction(static function () use ($folder, $playlistIds): void {
collect($playlistIds)->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<string>()
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)
})
})
31 changes: 4 additions & 27 deletions packages/laravel-parser/src/audit-log-parser.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { readFileSync } from "fs"
import Parser from "tree-sitter"
// @ts-ignore
import PHP from "tree-sitter-php"
import { parsePhpFile, findMethod } from "./php-source.js"

const _parser = new Parser()
_parser.setLanguage((PHP as { php?: unknown }).php ?? PHP)
Expand Down Expand Up @@ -41,14 +41,9 @@ export function parseAuditLogCalls(filePath: string, auditSinks: string[], metho
const sinkSet = new Set(auditSinks)
if (sinkSet.size === 0) return []

let source: string
let tree: ReturnType<typeof _parser.parse>
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 []
Expand All @@ -60,25 +55,7 @@ export function parseAuditLogCalls(filePath: string, auditSinks: string[], metho

// ---- 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
}

function gatherAuditLogCalls(
node: Parser.SyntaxNode,
Expand Down
Loading
Loading