Turbocharge Claude Code, Cursor, Codex, Gemini & every coding agent: faster, cheaper, with contextual understanding specific to your codebase.
TypeScript ai-agentsanthropicclaude-codeclicode-graphcodexcontext-engineeringcursordeveloper-toolsgeminiknowledge-graphllmmcpmcp-serveropen-sourceopenaitree-sitter
feat: add PHP language support (#64)
William Desportesd0ba1e4f0577
diff --git a/package-lock.json b/package-lock.jsonindex 08bc4a43..a237dfa3 100644--- a/package-lock.json+++ b/package-lock.json@@ -18,6 +18,7 @@"tree-sitter": "^0.21.1","tree-sitter-go": "^0.23.4","tree-sitter-java": "^0.23.5",+ "tree-sitter-php": "^0.23.4","tree-sitter-python": "^0.21.0","tree-sitter-typescript": "^0.23.2","tree-sitter-wasm": "^1.1.4",@@ -913,6 +914,25 @@}}},+ "node_modules/tree-sitter-php": {+ "version": "0.23.12",+ "resolved": "https://registry.npmjs.org/tree-sitter-php/-/tree-sitter-php-0.23.12.tgz",+ "integrity": "sha512-VwkBVOahhC2NYXK/Fuqq30NxuL/6c2hmbxEF4jrB7AyR5rLc7nT27mzF3qoi+pqx9Gy2AbXnGezF7h4MeM6YRA==",+ "hasInstallScript": true,+ "license": "MIT",+ "dependencies": {+ "node-addon-api": "^8.2.2",+ "node-gyp-build": "^4.8.2"+ },+ "peerDependencies": {+ "tree-sitter": "^0.21.1"+ },+ "peerDependenciesMeta": {+ "tree-sitter": {+ "optional": true+ }+ }+ },"node_modules/tree-sitter-python": {"version": "0.21.0","resolved": "https://registry.npmjs.org/tree-sitter-python/-/tree-sitter-python-0.21.0.tgz",diff --git a/package.json b/package.jsonindex e0d74203..c54e1eca 100644--- a/package.json+++ b/package.json@@ -63,6 +63,7 @@"tree-sitter": "^0.21.1","tree-sitter-go": "^0.23.4","tree-sitter-java": "^0.23.5",+ "tree-sitter-php": "^0.23.4","tree-sitter-python": "^0.21.0","tree-sitter-typescript": "^0.23.2","tree-sitter-wasm": "^1.1.4",diff --git a/src/graph/bindings.ts b/src/graph/bindings.tsindex 8826ea28..5609247d 100644--- a/src/graph/bindings.ts+++ b/src/graph/bindings.ts@@ -58,6 +58,21 @@ export function defName(node: Parser.SyntaxNode, lang: Language): string | null}return null;}+ if (lang === "php") {+ const phpDefTypes = new Set([+ "class_declaration",+ "interface_declaration",+ "trait_declaration",+ "enum_declaration",+ "method_declaration",+ "function_definition",+ ]);+ if (phpDefTypes.has(node.type)) return node.childForFieldName("name")?.text ?? null;+ // Closures push a scope segment in extract.ts too — mirror it so a typed+ // parameter bound inside a closure is keyed under the same scope path.+ if (node.type === "anonymous_function" || node.type === "arrow_function") return phpClosureName(node);+ return null;+ }const defTypes =lang === "python"? new Set(["class_definition", "function_definition"])@@ -116,6 +131,9 @@ export function resolveRecvType(undefined);}+ // PHP static call `Foo::bar()`: the scope operand is a class name, so it *is*+ // the receiver type. (Member calls pass a `$var` receiver, filtered by the `$`.)+ if (ctx.lang === "php" && !receiver.startsWith("$")) return receiver;return ((ctx.lang === "go" && receiver === ctx.goReceiverVar ? ctx.enclosingClass : undefined) ??ctx.bindings.lookup(ctx.scope, receiver) ??@@ -195,6 +213,7 @@ function visit(if (lang === "python") handlePy(node, scope, classScope, bindings, aliases);else if (lang === "go") handleGo(node, scope, bindings);else if (lang === "java") handleJava(node, scope, classScope, bindings);+ else if (lang === "php") handlePhp(node, scope, bindings);else handleTs(node, scope, classScope, bindings, aliases);const name = defName(node, lang);@@ -232,6 +251,62 @@ function callTypeName(node: Parser.SyntaxNode | null | undefined, aliases: Map<sreturn aliases.get(fn.text) ?? fn.text;}+/** PHP variable->type bindings from the two confident, syntax-local clues:+ * a type-hinted parameter (`function f(Foo $x)`) and a `new` assignment+ * (`$x = new Foo()`). Keyed by the `$var` text (with the `$`) so a+ * `$var->method()` call site resolves through resolveRecvType's bindings+ * lookup, exactly like Python's annotated params and Go's receiver. */+function handlePhp(node: Parser.SyntaxNode, scope: string[], bindings: FileBindings): void {+ if (node.type === "simple_parameter") {+ const type = phpTypeName(node.childForFieldName("type"));+ const name = node.childForFieldName("name");+ if (type && name?.type === "variable_name") bindings.set(scope.join("."), name.text, type);+ return;+ }+ if (node.type === "assignment_expression") {+ const left = node.childForFieldName("left");+ const right = node.childForFieldName("right");+ if (left?.type === "variable_name" && right?.type === "object_creation_expression") {+ const type = phpNewType(right);+ if (type) bindings.set(scope.join("."), left.text, type);+ }+ }+}++/** Closure name, duplicated from extract.ts's `phpClosureName` (this file must+ * not value-import extract.ts) so the two scope stacks agree on the segment a+ * closure pushes. The right-hand-side check compares node `.id` rather than+ * `===` on wrappers for the same reason as extract.ts: wrapper identity is not+ * stable across traversals, so `===` can spuriously fall through to `{closure}`+ * and desync this scope segment from the one extract.ts mints. */+function phpClosureName(node: Parser.SyntaxNode): string {+ const parent = node.parent;+ if (parent?.type === "assignment_expression" && parent.childForFieldName("right")?.id === node.id) {+ const left = parent.childForFieldName("left");+ if (left?.type === "variable_name") return left.text.replace(/^\$/, "");+ }+ return "{closure}";+}++/** A PHP type hint's class name: unwrap `?T` (optional_type) and `named_type`,+ * de-qualify a namespaced name to its trailing segment. Null for primitives,+ * unions, and intersections (no single confident class to bind). */+function phpTypeName(node: Parser.SyntaxNode | null): string | null {+ if (!node) return null;+ if (node.type === "named_type" || node.type === "optional_type") {+ return phpTypeName(node.namedChildren[0] ?? null);+ }+ if (node.type === "name") return node.text;+ if (node.type === "qualified_name") return node.text.replace(/^.*\\/, "");+ return null;+}++/** The class name of a `new Foo()` / `new App\Foo()`, de-qualified. */+function phpNewType(node: Parser.SyntaxNode): string | null {+ const cls = node.namedChildren.find((c) => c.type === "name" || c.type === "qualified_name");+ return cls ? cls.text.replace(/^.*\\/, "") : null;+}+function handlePy(node: Parser.SyntaxNode,scope: string[],diff --git a/src/graph/extract.ts b/src/graph/extract.tsindex af57fa2a..78fa1a09 100644--- a/src/graph/extract.ts+++ b/src/graph/extract.ts@@ -11,12 +11,13 @@ import TypeScript from "tree-sitter-typescript";import Python from "tree-sitter-python";import Go from "tree-sitter-go";import Java from "tree-sitter-java";+import PHP from "tree-sitter-php";import { basename } from "node:path";import { contentHash } from "../util/id.js";import { collectBindings, goReceiverVarOf, resolveRecvType, type FileBindings } from "./bindings.js";import type { Kind, NodeV1, Relation } from "./types.js";-export type Language = "typescript" | "tsx" | "python" | "go" | "java";+export type Language = "typescript" | "tsx" | "python" | "go" | "java" | "php";/*** Extension → the tree-sitter grammar that parses it, and the label a human expects@@ -46,6 +47,7 @@ const EXTENSIONS: ReadonlyArray<{ ext: string; grammar: Language; label: string{ ext: ".py", grammar: "python", label: "python" },{ ext: ".go", grammar: "go", label: "go" },{ ext: ".java", grammar: "java", label: "java" },+ { ext: ".php", grammar: "php", label: "php" },];function entryFor(path: string): (typeof EXTENSIONS)[number] | undefined {@@ -179,12 +181,26 @@ const JAVA_KINDS: Record<string, Kind> = {* which "class"-only logic would miss for a record's or interface's members. */const JAVA_TYPE_KINDS: ReadonlySet<Kind> = new Set<Kind>(["class", "interface", "enum", "struct"]);+// PHP: definition node types are all distinct (no py-style function→method+// promotion needed — a class body uses `method_declaration`, not+// `function_definition`). `trait_declaration` maps to the PHP-only `trait` kind.+const PHP_KINDS: Record<string, Kind> = {+ function_definition: "function",+ method_declaration: "method",+ class_declaration: "class",+ interface_declaration: "interface",+ trait_declaration: "trait",+ enum_declaration: "enum",+};++const KINDS_BY_LANG: Record<Language, Record<string, Kind>> = {typescript: TS_KINDS,tsx: TS_KINDS,python: PY_KINDS,go: GO_KINDS,java: JAVA_KINDS,+ php: PHP_KINDS,};/**@@ -192,7 +208,9 @@ const KINDS_BY_LANG: Record<Language, Record<string, Kind>> = {** Java is the reason this is a set rather than a string: `method_invocation` and* `object_creation_expression` (`new Foo()`) are separate node types, and a Java- * codebase's constructor calls are a large share of its real edges.+ * codebase's constructor calls are a large share of its real edges. PHP is+ * likewise multi-shape: a call is a function / member / nullsafe-member / scoped+ * call, never a single `call_expression`.*/const CALL_TYPES: Record<Language, ReadonlySet<string>> = {typescript: new Set(["call_expression"]),@@ -200,6 +218,12 @@ const CALL_TYPES: Record<Language, ReadonlySet<string>> = {python: new Set(["call"]),go: new Set(["call_expression"]),java: new Set(["method_invocation", "object_creation_expression"]),+ php: new Set([+ "function_call_expression",+ "member_call_expression",+ "nullsafe_member_call_expression",+ "scoped_call_expression",+ ]),};const FUNCTION_VALUE_TYPES = new Set([@@ -216,6 +240,7 @@ const GRAMMARS: Record<Language, unknown> = {python: Python,go: Go,java: Java,+ php: PHP.php,};export interface WalkCtx {@@ -348,7 +373,9 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd? goExported(desc.name): ctx.lang === "java"? javaExported(node)- : tsExported(node),+ : ctx.lang === "php"+ ? phpExported(node)+ : tsExported(node),origin: "ast",body_hash: contentHash(desc.hashNode.text),body_text: searchBody(desc.hashNode.text),@@ -412,6 +439,16 @@ function walk(node: Parser.SyntaxNode, ctx: WalkCtx, out: NodeV1[], edges: RawEd// Imported identifiers are declarations, not uses. The import-binding pass// above already recorded them, so do not descend and emit false references.return;+ } else if (ctx.lang === "php" && node.type === "use_declaration") {+ // Trait composition inside a class body (`use HasFactory, Notifiable;`).+ // Modelled as `implements`: like an interface, a trait is a contract of+ // behaviour the class mixes in (Graft's Relation set has no `uses`).+ for (const t of node.namedChildren) {+ if (t.type === "name" || t.type === "qualified_name") {+ edges.push({ source: ctx.parentId, relation: "implements", name: t.text.replace(/^.*\\/, ""), file: ctx.rel });+ }+ }+ return;} else if (node.type === "identifier" &&!isDirectCallee(node, callTypes) &&@@ -557,6 +594,20 @@ function describe(node: Parser.SyntaxNode, ctx: WalkCtx): DefDescriptor | null {if (ctx.lang === "go") return describeGo(node, ctx);if (ctx.lang === "java") return describeJava(node, ctx);+ // PHP closures: `$h = function () {…}` / `fn() => …`, and bare callbacks+ // (`$routes->get('/x', function () {…})`). Captured as function nodes so a+ // closure-only file (a routing table, a DI container) keeps its structure+ // and the calls inside attribute to the closure, not the file.+ if (ctx.lang === "php" && (node.type === "anonymous_function" || node.type === "arrow_function")) {+ const body = node.childForFieldName("body");+ return {+ name: phpClosureName(node),+ kind: "function",+ headerEnd: body ? body.startIndex : node.endIndex,+ hashNode: node,+ };+ }+const mapped = ctx.kinds[node.type];if (mapped) {const name = node.childForFieldName("name")?.text;@@ -688,6 +739,32 @@ function goExported(name: string): boolean {return first !== first.toLowerCase() && first === first.toUpperCase();}+/** PHP visibility: a class member is "exported" unless it is `private`/`protected`.+ * Top-level functions/classes carry no visibility modifier and are always visible. */+function phpExported(node: Parser.SyntaxNode): boolean {+ const vis = node.namedChildren.find((c) => c.type === "visibility_modifier");+ return vis ? vis.text === "public" : true;+}++/** Name for a PHP closure / arrow-fn: the variable it's assigned to+ * (`$handler = fn(...)` -> `handler`, mirroring how TS names arrow-consts),+ * else the anonymous `{closure}` (deduplicated per file by mintId).+ *+ * The "is this the assignment's right-hand side" check compares tree-sitter node+ * `.id` (a stable per-tree node identity) rather than `===` on the wrapper+ * objects: the binding does not guarantee that two traversals to the same+ * underlying node hand back the same JS wrapper, so `right === node` can be false+ * even when they are the same node — producing a stray `{closure}` name that+ * makes `graft check` report the graph STALE against its own stored output. */+function phpClosureName(node: Parser.SyntaxNode): string {+ const parent = node.parent;+ if (parent?.type === "assignment_expression" && parent.childForFieldName("right")?.id === node.id) {+ const left = parent.childForFieldName("left");+ if (left?.type === "variable_name") return left.text.replace(/^\$/, "");+ }+ return "{closure}";+}+function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx): RawEdge[] {const edges: RawEdge[] = [];if (ctx.lang === "java") {@@ -717,6 +794,21 @@ function heritageEdges(node: Parser.SyntaxNode, classId: string, ctx: WalkCtx):}return edges;}+ if (ctx.lang === "php") {+ // `class C extends B implements I, J` → base_clause (extends) ++ // class_interface_clause (implements); names may be namespace-qualified.+ for (const clause of node.namedChildren) {+ const relation: Relation | null =+ clause.type === "base_clause" ? "extends" : clause.type === "class_interface_clause" ? "implements" : null;+ if (!relation) continue;+ for (const t of clause.namedChildren) {+ if (t.type === "name" || t.type === "qualified_name") {+ edges.push({ source: classId, relation, name: t.text.replace(/^.*\\/, ""), file: ctx.rel });+ }+ }+ }+ return edges;+ }const heritage = node.namedChildren.find((c) => c.type === "class_heritage");for (const clause of heritage?.namedChildren ?? []) {const relation: Relation | null =@@ -774,6 +866,8 @@ function calleeName(return { name: nameNode.text, viaMember: true, receiver: javaReceiver(obj) };}+ if (lang === "php") return phpCallee(node);+const fn = node.childForFieldName("function");if (!fn) return null;if (fn.type === "identifier") return { name: fn.text, viaMember: false };@@ -866,6 +960,54 @@ function pyReceiver(fn: Parser.SyntaxNode): string | undefined {return undefined;}+/**+ * PHP call shapes: `foo()` (function_call_expression), `$obj->m()` /+ * `$obj?->m()` (member/nullsafe_member_call_expression), and `Cls::m()`+ * (scoped_call_expression). The called name is the trailing `name`; the+ * receiver, when locally knowable (`$this`, `self`/`static`/`parent`), feeds+ * receiver-typed resolution the same way Python's `self` and Go's receiver do.+ */+function phpCallee(node: Parser.SyntaxNode): { name: string; viaMember: boolean; receiver?: string } | null {+ if (node.type === "function_call_expression") {+ const fn = node.childForFieldName("function");+ const name = fn ? phpName(fn) : null;+ return name ? { name, viaMember: false } : null;+ }+ const nameNode = node.childForFieldName("name");+ if (!nameNode) return null;+ if (node.type === "scoped_call_expression") {+ return { name: nameNode.text, viaMember: true, receiver: phpScopeReceiver(node.childForFieldName("scope")) };+ }+ // member_call_expression / nullsafe_member_call_expression+ return { name: nameNode.text, viaMember: true, receiver: phpObjReceiver(node.childForFieldName("object")) };+}++/** A PHP callee identifier: bare `name`, or the trailing segment of a+ * `qualified_name` (`\App\helpers\slug` → `slug`). Dynamic calls (`$fn()`) → null. */+function phpName(node: Parser.SyntaxNode): string | null {+ if (node.type === "name") return node.text;+ if (node.type === "qualified_name") return node.text.replace(/^.*\\/, "") || null;+ return null;+}++/** `$obj->m()` receiver: `$this` normalizes to `this` (→ enclosing class); any+ * other variable is returned verbatim for a bindings lookup. */+function phpObjReceiver(obj: Parser.SyntaxNode | null): string | undefined {+ if (obj?.type !== "variable_name") return undefined;+ return obj.text === "$this" ? "this" : obj.text;+}++/** `Cls::m()` receiver: `self`/`static`/`parent` normalize to `self` (→ enclosing+ * class); an explicit class name is the trailing segment of its qualified path. */+function phpScopeReceiver(scope: Parser.SyntaxNode | null): string | undefined {+ if (!scope) return undefined;+ const text = scope.text;+ if (scope.type === "relative_scope" || text === "self" || text === "static" || text === "parent") return "self";+ if (scope.type === "name") return text;+ if (scope.type === "qualified_name") return text.replace(/^.*\\/, "");+ return undefined;+}+/** ts `member_expression` node's receiver text: `this`, `this.x`, or a bare identifier. */function tsReceiver(fn: Parser.SyntaxNode): string | undefined {const obj = fn.childForFieldName("object");@@ -884,10 +1026,18 @@ function isImport(node: Parser.SyntaxNode, lang: Language): boolean {// (`import ( … )`) forms each yield one edge as the walk recurses into the list.if (lang === "go") return node.type === "import_spec";if (lang === "java") return node.type === "import_declaration";+ // PHP: one edge per imported symbol — the clause leaf inside a (possibly+ // grouped) `use A\B, C\D;` / `use A\{B, C};` declaration.+ if (lang === "php") return node.type === "namespace_use_clause";return node.type === "import_statement" || node.type === "import_from_statement";}function importSpecifier(node: Parser.SyntaxNode, lang: Language): string | null {+ if (lang === "php") {+ // namespace_use_clause → its `qualified_name`/`name`, e.g. `App\Models\Animal`.+ const q = node.namedChildren.find((c) => c.type === "qualified_name" || c.type === "name");+ return q ? q.text.replace(/^\\/, "") : null;+ }if (lang === "python") {const m =node.childForFieldName("module_name") ??diff --git a/src/graph/resolve.ts b/src/graph/resolve.tsindex a67eb2a1..21483603 100644--- a/src/graph/resolve.ts+++ b/src/graph/resolve.ts@@ -145,7 +145,9 @@ export function resolveEdges(: resolveImport(e.specifier, e.file, byId);add(e.source, target, "imports", "extracted");} else if (e.relation === "extends" || e.relation === "implements") {- const kinds: Kind[] = e.relation === "implements" ? ["interface"] : ["class", "interface"];+ // `implements` also resolves to a `trait` — PHP models trait composition+ // (`use SomeTrait;`) as an implements edge, and a trait is a valid target.+ const kinds: Kind[] = e.relation === "implements" ? ["interface", "trait"] : ["class", "interface"];const hit = resolveName(e.name!, e.file, kinds, perFileName, globalName);// an unresolved base is usually an external/imported type — keep the name.add(e.source, hit?.id ?? e.name!, e.relation, hit?.confidence ?? "inferred");diff --git a/src/graph/scopes.ts b/src/graph/scopes.tsindex eab0a98c..915aa188 100644--- a/src/graph/scopes.ts+++ b/src/graph/scopes.ts@@ -29,7 +29,7 @@ import { readFollowSubmodules, readIncludeDirs } from "../util/state.js";import type { GraphV1, ScopeV1 } from "./types.js";/** Project-marker files, checked in this order (also the order `markers` is built in). */-const MARKERS = ["package.json", "go.mod", "pyproject.toml", "setup.py", "Cargo.toml", "pom.xml", "build.gradle", "build.gradle.kts"];+const MARKERS = ["package.json", "go.mod", "pyproject.toml", "setup.py", "Cargo.toml", "composer.json", "pom.xml", "build.gradle", "build.gradle.kts"];const CANONICAL_ROOT: ScopeV1[] = [{ prefix: "", label: "", markers: [] }];diff --git a/src/graph/types.ts b/src/graph/types.tsindex 0fb3c653..ff243e15 100644--- a/src/graph/types.ts+++ b/src/graph/types.ts@@ -19,8 +19,9 @@ export type Kind =| "method"| "interface" // TS + Go| "type" // TS + Go (type alias / named type)- | "enum" // TS only+ | "enum" // TS + PHP + Java| "struct" // Go only+ | "trait" // PHP only// The generic (tags.scm) breadth tier also emits these — every tree-sitter// grammar's tags.scm uses the tree-sitter tags @definition.<X> vocabulary, and// module/constant/variable are common across the long tail (Ruby modules,diff --git a/test/graph-invariants.test.ts b/test/graph-invariants.test.tsindex 2a1b058b..980e7c04 100644--- a/test/graph-invariants.test.ts+++ b/test/graph-invariants.test.ts@@ -1,6 +1,6 @@/*** Tier-0 quality gate as a test: build a real graph over a multi-tier fixture- * (TS on the depth extractor, Rust + PHP on the generic breadth tier) and assert+ * (TS + PHP on the depth extractor, Rust on the generic breadth tier) and assert* (a) the structural INVARIANTS hold on the output of BOTH tiers together, and* (b) the build is DETERMINISTIC — two cold builds of the same source produce the* same graph. Both are things every future extraction/resolution change must keep@@ -20,8 +20,9 @@ import { checkGraphInvariants } from "../src/graph/invariants.js";import type { GraphV1 } from "../src/graph/types.js";// A recursion-free fixture spanning both tiers: main→helper (TS, depth),-// load→parse (Rust, breadth), Circle implements Shape (PHP, breadth → a-// `references` edge). No function calls itself, so self-loops must be zero.+// load→parse (Rust, breadth), Circle implements Shape (PHP, depth → an+// `implements` edge; PHP has a depth extractor, so it is not on the breadth+// tier). No function calls itself, so self-loops must be zero.function writeFixture(dir: string): void {mkdirSync(join(dir, "src"), { recursive: true });writeFileSync(@@ -61,12 +62,12 @@ test("Tier-0: a built multi-tier graph satisfies every structural invariant", as// both tiers are actually present, or the fixture isn't testing what it claimsconst origins = new Set(g!.nodes.filter((n) => n.kind !== "file").map((n) => n.origin));- assert.ok(origins.has("ast"), "TS depth-tier nodes present");- assert.ok(origins.has("generic"), "Rust/PHP breadth-tier nodes present");+ assert.ok(origins.has("ast"), "TS/PHP depth-tier nodes present");+ assert.ok(origins.has("generic"), "Rust breadth-tier nodes present");// and that resolution actually produced the edge kinds this gate is meant to guardconst rels = new Set(g!.edges.map((e) => e.relation));assert.ok(rels.has("calls"), "call edges resolved");- assert.ok(rels.has("references"), "a breadth-tier references edge resolved (Circle→Shape)");+ assert.ok(rels.has("implements"), "a PHP depth-tier implements edge resolved (Circle→Shape)");assert.ok(rels.has("contains"), "containment edges present");const { problems, selfLoopCalls } = checkGraphInvariants(g!);diff --git a/test/graph-languages.test.ts b/test/graph-languages.test.tsindex f66ac83f..c81d4ae1 100644--- a/test/graph-languages.test.ts+++ b/test/graph-languages.test.ts@@ -28,6 +28,7 @@ const INDEXED = ["a.py", "a.pyi","a.go","a.java",+ "a.php",];test("a file is labelled exactly when it is indexed", () => {@@ -55,6 +56,7 @@ test("labels name the language, not the grammar that parses it", () => {assert.equal(languageLabelOf("api/main.pyi"), "python");assert.equal(languageLabelOf("cmd/main.go"), "go");assert.equal(languageLabelOf("src/main/java/com/acme/App.java"), "java");+ assert.equal(languageLabelOf("app/Models/User.php"), "php");// The grammar is unchanged — extraction, the extract cache and every `Language`// switch still see exactly what they saw before.diff --git a/test/graph-php.test.ts b/test/graph-php.test.tsnew file mode 100644index 00000000..b208ccc5--- /dev/null+++ b/test/graph-php.test.ts@@ -0,0 +1,296 @@+/**+ * Tests for PHP extraction in the Tier-1 code graph. Builds a small PHP project in+ * a temp dir and asserts the emitted nodes (classes, methods, interface, trait,+ * enum, top-level function) and edges (calls, extends, implements) match the AST+ * walk in extract.ts.+ */+import { test } from "node:test";+import assert from "node:assert/strict";+import { mkdtempSync, writeFileSync, rmSync } from "node:fs";+import { join } from "node:path";+import { tmpdir } from "node:os";+import { buildGraph } from "../src/graph/build.js";+import { checkGraph } from "../src/graph/check.js";+import { extractFile } from "../src/graph/extract.js";+import { readGraph, wiringPath } from "../src/graph/write.js";+import type { GraphV1, NodeV1 } from "../src/graph/types.js";++const APP_PHP = `<?php+namespace App;++use App\\Support\\Base;++class Widget extends Base implements Runnable+{+ use Loggable;++ public function run(): int+ {+ return $this->helper();+ }++ private function helper(): int+ {+ return Base::seed();+ }++ public function act(Base $b): string+ {+ return $b->label();+ }+}++interface Runnable {}++trait Loggable {}++enum Color: string+{+ case Red = 'r';+}++function topLevel(): int+{+ return 1;+}++$make = fn(): int => topLevel();++register(function (): void {+ topLevel();+});+`;++const BASE_PHP = `<?php+namespace App\\Support;++class Base+{+ public static function seed(): int+ {+ return 0;+ }++ public function label(): string+ {+ return 'b';+ }+}+`;++function makeFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "graft-php-"));+ writeFileSync(join(dir, "composer.json"), `{"name": "acme/app"}\n`);+ writeFileSync(join(dir, "app.php"), APP_PHP);+ writeFileSync(join(dir, "base.php"), BASE_PHP);+ return dir;+}++function nodeById(graph: GraphV1, id: string): NodeV1 | undefined {+ return graph.nodes.find((n) => n.id === id);+}++test("PHP extraction: classes, methods, interface, trait, enum, function", async () => {+ const dir = makeFixture();+ try {+ const result = await buildGraph(dir); // $0, Tier-1 only+ assert.ok(result.languages.includes("php"), "languages should include php");++ const graph = readGraph(wiringPath(join(dir, "graft")));+ assert.ok(graph, "wiring graph should be written");++ assert.equal(nodeById(graph!, "app.php#Widget")?.kind, "class");+ assert.equal(nodeById(graph!, "base.php#Base")?.kind, "class");++ // methods — file-scoped under their class; visibility drives `exported`+ const run = nodeById(graph!, "app.php#Widget.run");+ assert.equal(run?.kind, "method");+ assert.equal(run?.exported, true, "public method is exported");+ assert.equal(nodeById(graph!, "app.php#Widget.helper")?.exported, false, "private method is not exported");++ // language-specific kinds+ assert.equal(nodeById(graph!, "app.php#Runnable")?.kind, "interface");+ assert.equal(nodeById(graph!, "app.php#Loggable")?.kind, "trait");+ assert.equal(nodeById(graph!, "app.php#Color")?.kind, "enum");+ assert.equal(nodeById(graph!, "app.php#topLevel")?.kind, "function");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("PHP extraction: call, extends, and implements edges", async () => {+ const dir = makeFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ // `class Widget extends Base` resolves cross-file by class name+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "extends" && e.source === "app.php#Widget" && e.target === "base.php#Base",+ ),+ "Widget should have a resolved extends edge to Base",+ );++ // `implements Runnable` resolves to the same-file interface+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "implements" && e.source === "app.php#Widget" && e.target === "app.php#Runnable",+ ),+ "Widget should have a resolved implements edge to Runnable",+ );++ // `$this->helper()` resolves to the receiver method (self → enclosing class)+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#Widget.run" && e.target === "app.php#Widget.helper",+ ),+ "run should have a resolved calls edge to helper",+ );++ // `Base::seed()` static call resolves to the target class method by name+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#Widget.helper" && e.target === "base.php#Base.seed",+ ),+ "helper should have a resolved calls edge to Base.seed",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("PHP extraction: trait use and typed-parameter receiver binding", async () => {+ const dir = makeFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ // `use Loggable;` inside the class body resolves to the trait (modelled as implements)+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "implements" && e.source === "app.php#Widget" && e.target === "app.php#Loggable",+ ),+ "Widget should have a resolved trait-use (implements) edge to Loggable",+ );++ // `act(Base $b)` -> `$b->label()` resolves via the typed-parameter binding+ // ($b : Base), not by bare method name — Base.label is the only match anyway,+ // but the binding is what makes this correct when several classes share a name.+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#Widget.act" && e.target === "base.php#Base.label",+ ),+ "act should resolve $b->label() to Base.label through the parameter binding",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++// A variable-assigned closure is named after its variable, so its node id is+// `…#<var>`. If that name is recomputed as the anonymous `{closure}` on a later+// pass, the stored id and the recomputed id disagree — the exact drift that made+// `graft check` report STALE on closure-heavy PHP right after a clean build+// (reported against this branch on a ~2k-file Laravel repo). These closures are+// shaped like that report: a top-level `static function … use (…)` and a+// variable-assigned closure nested inside a method.+const CLOSURES_PHP = `<?php+declare(strict_types=1);++$itemGroupCallback = static function ($itemGroup) use ($response) {+ return $itemGroup->id;+};++class Service+{+ public function getItemList(): array+ {+ $mapper = function ($row) {+ return $row->value;+ };+ return array_map($mapper, []);+ }+}+`;++function makeClosureFixture(): string {+ const dir = mkdtempSync(join(tmpdir(), "graft-php-closures-"));+ writeFileSync(join(dir, "composer.json"), `{"name": "acme/closures"}\n`);+ writeFileSync(join(dir, "closures.php"), CLOSURES_PHP);+ return dir;+}++test("PHP closures: variable-assigned closures are named after their variable", () => {+ const { nodes } = extractFile("closures.php", CLOSURES_PHP, "php");+ const ids = nodes.map((n) => n.id);+ // top-level `static function` assigned to $itemGroupCallback, and the closure+ // assigned to $mapper inside the method — both keep the variable name, no {closure}.+ assert.ok(ids.includes("closures.php#itemGroupCallback"), `expected named top-level closure, got: ${ids.join(", ")}`);+ assert.ok(+ ids.includes("closures.php#Service.getItemList.mapper"),+ `expected named nested closure, got: ${ids.join(", ")}`,+ );+ assert.ok(!ids.some((id) => id.includes("{closure}")), `no closure should collapse to {closure}, got: ${ids.join(", ")}`);+});++test("PHP closures: closure names are stable across repeated extraction", () => {+ // The name derives from a tree-sitter node comparison; wrapper identity is not+ // stable across traversals, so the comparison must use node `.id`, not `===`.+ // Re-extracting the same source must yield the identical closure-node id set.+ const first = extractFile("closures.php", CLOSURES_PHP, "php").nodes.map((n) => n.id).sort();+ for (let i = 0; i < 5; i++) {+ const again = extractFile("closures.php", CLOSURES_PHP, "php").nodes.map((n) => n.id).sort();+ assert.deepEqual(again, first, "closure-node ids must be identical on every extraction");+ }+});++test("PHP closures: `graft check` stays fresh after build (no name drift)", async () => {+ const dir = makeClosureFixture();+ try {+ await buildGraph(dir);+ // No source changed between build and check, so the recomputed Tier-1 node set+ // must match the committed graph exactly — in particular the closure ids.+ const result = await checkGraph(dir);+ assert.deepEqual(result.added, [], "check should report no added nodes");+ assert.deepEqual(result.removed, [], "check should report no removed nodes");+ assert.deepEqual(result.changed, [], "check should report no changed nodes");+ assert.equal(result.ok, true, "graph check should be OK immediately after build");+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});++test("PHP extraction: closures become nodes and own the calls inside them", async () => {+ const dir = makeFixture();+ try {+ await buildGraph(dir);+ const graph = readGraph(wiringPath(join(dir, "graft")))!;++ // an assigned arrow-fn is named after its variable (like a TS arrow-const)+ assert.equal(nodeById(graph, "app.php#make")?.kind, "function", "assigned closure `$make` is a function node");++ // a bare callback (`register(function () {…})`) is an anonymous `{closure}` node+ assert.ok(+ graph.nodes.some((n) => n.id === "app.php#{closure}" && n.kind === "function"),+ "anonymous callback becomes a {closure} function node",+ );++ // the call inside each closure attributes to the closure, not the file —+ // this is what keeps a closure-only routing table structured+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#make" && e.target === "app.php#topLevel",+ ),+ "the arrow-fn body's call to topLevel is owned by `make`",+ );+ assert.ok(+ graph.edges.some(+ (e) => e.relation === "calls" && e.source === "app.php#{closure}" && e.target === "app.php#topLevel",+ ),+ "the anonymous callback's call to topLevel is owned by {closure}",+ );+ } finally {+ rmSync(dir, { recursive: true, force: true });+ }+});