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
5 changes: 5 additions & 0 deletions app/Commands/ReindexAllCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -112,6 +112,11 @@ public function handle(

$vectorized++;
note(" Vectorized: {$vResult['success']}/{$vResult['total']} ({$vResult['failed']} failed)");

$pruneResult = $codeIndexer->pruneStaleSymbols($indexPath, $repo);
if ($pruneResult['deleted'] > 0) {
note(" Pruned {$pruneResult['deleted']} stale symbols");
}
}

info("Done: {$indexed} indexed, {$vectorized} vectorized, {$errors} errors");
Expand Down
5 changes: 5 additions & 0 deletions app/Commands/VectorizeCodeCommand.php
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,11 @@ function (int $success, int $failed, int $total) use (&$lastReport): void {

info("Done: {$result['success']}/{$result['total']} symbols vectorized, {$result['failed']} failed");

$pruneResult = $codeIndexer->pruneStaleSymbols($indexPath, $repo);
if ($pruneResult['deleted'] > 0) {
note("Pruned {$pruneResult['deleted']} stale symbols ({$pruneResult['total_checked']} checked)");
}

return self::SUCCESS;
}
}
4 changes: 4 additions & 0 deletions app/Mcp/Servers/KnowledgeServer.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,12 @@

use App\Mcp\Tools\ContextTool;
use App\Mcp\Tools\CorrectTool;
use App\Mcp\Tools\FileOutlineTool;
use App\Mcp\Tools\RecallTool;
use App\Mcp\Tools\RememberTool;
use App\Mcp\Tools\SearchCodeTool;
use App\Mcp\Tools\StatsTool;
use App\Mcp\Tools\SymbolLookupTool;
use Laravel\Mcp\Server;
use Laravel\Mcp\Server\Attributes\Instructions;
use Laravel\Mcp\Server\Attributes\Name;
Expand All @@ -27,6 +29,8 @@ class KnowledgeServer extends Server
ContextTool::class,
StatsTool::class,
SearchCodeTool::class,
FileOutlineTool::class,
SymbolLookupTool::class,
];

protected array $resources = [];
Expand Down
55 changes: 55 additions & 0 deletions app/Mcp/Tools/FileOutlineTool.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
<?php

declare(strict_types=1);

namespace App\Mcp\Tools;

use App\Services\SymbolIndexService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;

#[Description('Get the symbol outline of a file — classes, methods, functions with hierarchy.')]
#[IsReadOnly]
#[IsIdempotent]
class FileOutlineTool extends Tool
{
public function __construct(
private readonly SymbolIndexService $symbolIndex,
) {}

public function handle(Request $request): Response
{
$file = $request->get('file');

if (! is_string($file) || $file === '') {
return Response::error('A file path is required.');
}

$repo = is_string($request->get('repo')) ? $request->get('repo') : 'local/knowledge';

$outline = $this->symbolIndex->getFileOutline($file, $repo);

return Response::text(json_encode([
'file' => $file,
'repo' => $repo,
'symbols' => $outline,
'total' => count($outline),
], JSON_THROW_ON_ERROR));
}

public function schema(JsonSchema $schema): array
{
return [
'file' => $schema->string()
->description('Relative file path within the repo (e.g., "app/Services/UserService.php")')
->required(),
'repo' => $schema->string()
->description('Repository identifier (e.g., "local/pstrax-laravel"). Defaults to "local/knowledge".'),
];
}
}
35 changes: 25 additions & 10 deletions app/Mcp/Tools/SearchCodeTool.php
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
namespace App\Mcp\Tools;

use App\Services\CodeIndexerService;
use App\Services\SymbolIndexService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
Expand All @@ -20,6 +21,7 @@ class SearchCodeTool extends Tool
{
public function __construct(
private readonly CodeIndexerService $codeIndexer,
private readonly SymbolIndexService $symbolIndex,
) {}

public function handle(Request $request): Response
Expand Down Expand Up @@ -47,16 +49,29 @@ public function handle(Request $request): Response
], JSON_THROW_ON_ERROR));
}

$formatted = array_map(fn (array $r): array => [
'filepath' => $r['filepath'],
'repo' => $r['repo'],
'language' => $r['language'],
'symbol_name' => $r['symbol_name'] ?? null,
'symbol_kind' => $r['symbol_kind'] ?? null,
'line' => $r['start_line'],
'score' => round($r['score'], 3),
'content' => $r['content'],
], $results);
$formatted = array_map(function (array $r): array {
$source = null;
$symbolName = $r['symbol_name'] ?? null;
if (is_string($symbolName) && $symbolName !== '') {
$source = $this->symbolIndex->getSymbolSourceByNameAndFile(
$symbolName,
$r['filepath'],
$r['repo'],
);
}

return [
'filepath' => $r['filepath'],
'repo' => $r['repo'],
'language' => $r['language'],
'symbol_name' => $symbolName,
'symbol_kind' => $r['symbol_kind'] ?? null,
'line' => $r['start_line'],
'score' => round($r['score'], 3),
'content' => $r['content'],
'source' => $source,
];
}, $results);

return Response::text(json_encode([
'results' => $formatted,
Expand Down
72 changes: 72 additions & 0 deletions app/Mcp/Tools/SymbolLookupTool.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
<?php

declare(strict_types=1);

namespace App\Mcp\Tools;

use App\Services\SymbolIndexService;
use Illuminate\Contracts\JsonSchema\JsonSchema;
use Laravel\Mcp\Request;
use Laravel\Mcp\Response;
use Laravel\Mcp\Server\Attributes\Description;
use Laravel\Mcp\Server\Tool;
use Laravel\Mcp\Server\Tools\Annotations\IsIdempotent;
use Laravel\Mcp\Server\Tools\Annotations\IsReadOnly;

#[Description('Look up a symbol by ID — get metadata and optionally its source code.')]
#[IsReadOnly]
#[IsIdempotent]
class SymbolLookupTool extends Tool
{
public function __construct(
private readonly SymbolIndexService $symbolIndex,
) {}

public function handle(Request $request): Response
{
$symbolId = $request->get('symbol_id');

if (! is_string($symbolId) || $symbolId === '') {
return Response::error('A symbol_id is required.');
}

$repo = is_string($request->get('repo')) ? $request->get('repo') : 'local/knowledge';
$includeSource = $request->get('include_source') !== false;

$symbol = $this->symbolIndex->getSymbol($symbolId, $repo);

if ($symbol === null) {
return Response::error("Symbol '{$symbolId}' not found in {$repo}.");
}

$result = [
'id' => $symbol['id'] ?? $symbolId,
'kind' => $symbol['kind'] ?? '',
'name' => $symbol['name'] ?? '',
'file' => $symbol['file'] ?? '',
'line' => $symbol['line'] ?? 0,
'signature' => $symbol['signature'] ?? '',
'summary' => $symbol['summary'] ?? '',
'docstring' => $symbol['docstring'] ?? '',
];

if ($includeSource) {
$result['source'] = $this->symbolIndex->getSymbolSource($symbolId, $repo);
}

return Response::text(json_encode($result, JSON_THROW_ON_ERROR));
}

public function schema(JsonSchema $schema): array
{
return [
'symbol_id' => $schema->string()
->description('The symbol ID from a search or outline result')
->required(),
'repo' => $schema->string()
->description('Repository identifier (e.g., "local/pstrax-laravel"). Defaults to "local/knowledge".'),
'include_source' => $schema->boolean()
->description('Whether to include the full source code (default: true)'),
];
}
}
77 changes: 76 additions & 1 deletion app/Services/CodeIndexerService.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,9 @@
use App\Contracts\EmbeddingServiceInterface;
use App\Integrations\Qdrant\QdrantConnector;
use App\Integrations\Qdrant\Requests\CreateCollection;
use App\Integrations\Qdrant\Requests\DeletePoints;
use App\Integrations\Qdrant\Requests\GetCollectionInfo;
use App\Integrations\Qdrant\Requests\ScrollPoints;
use App\Integrations\Qdrant\Requests\SearchPoints;
use App\Integrations\Qdrant\Requests\UpsertPoints;
use Symfony\Component\Finder\Finder;
Expand Down Expand Up @@ -171,7 +173,7 @@ public function indexFile(string $filepath, string $repo): array
* Search code semantically.
*
* @param array{repo?: string, language?: string} $filters
* @return array<array{filepath: string, repo: string, language: string, content: string, score: float, functions: array<string>}>
* @return array<array{filepath: string, repo: string, language: string, content: string, score: float, functions: array<string>, symbol_name: string|null, symbol_kind: string|null, signature: string|null, start_line: int, end_line: int}>
*/
public function search(string $query, int $limit = 10, array $filters = []): array
{
Expand Down Expand Up @@ -346,6 +348,79 @@ function (array $s) use ($allowedKinds, $language): bool {
return ['success' => $success, 'failed' => $failed, 'total' => $total];
}

/**
* Remove vectorized symbols that no longer exist in the current index.
*
* @return array{deleted: int, total_checked: int}
*/
public function pruneStaleSymbols(string $indexPath, string $repo): array
{
$content = @file_get_contents($indexPath);
if ($content === false) {
return ['deleted' => 0, 'total_checked' => 0];
}

/** @var array{symbols: array<array<string, mixed>>}|null $index */
$index = json_decode($content, true);
if (! is_array($index) || ! isset($index['symbols'])) {
return ['deleted' => 0, 'total_checked' => 0];
}

// Build set of valid point IDs from the current index
$validIds = [];
foreach ($index['symbols'] as $symbol) {
$id = md5("{$repo}:{$symbol['file']}:{$symbol['name']}:{$symbol['line']}");
$validIds[$id] = true;
}

// Scroll through all points for this repo in Qdrant
$staleIds = [];
$totalChecked = 0;
$offset = null;

do {
$filter = ['must' => [['key' => 'repo', 'match' => ['value' => $repo]]]];
$response = $this->connector->send(
new ScrollPoints(self::COLLECTION_NAME, 100, $filter, $offset)
);

if (! $response->successful()) {
break;
}

$data = $response->json();
$points = $data['result']['points'] ?? [];
$offset = $data['result']['next_page_offset'] ?? null;

foreach ($points as $point) {
// Only check symbol points (they have symbol_name in payload)
if (! isset($point['payload']['symbol_name'])) {
continue;
}

$totalChecked++;
$pointId = $point['id'];

if (! isset($validIds[$pointId])) {
$staleIds[] = $pointId;
}
}
} while ($offset !== null && $points !== []);

// Delete stale points in batches
$deleted = 0;
foreach (array_chunk($staleIds, 100) as $batch) {
$response = $this->connector->send(
new DeletePoints(self::COLLECTION_NAME, $batch)
);
if ($response->successful()) {
$deleted += count($batch);
}
}

return ['deleted' => $deleted, 'total_checked' => $totalChecked];
}

/**
* Build searchable text from a tree-sitter symbol.
*
Expand Down
51 changes: 51 additions & 0 deletions app/Services/SymbolIndexService.php
Original file line number Diff line number Diff line change
Expand Up @@ -302,6 +302,40 @@ private function loadIndex(string $repo): ?array
return $data;
}

/**
* Get symbol source code by name and file path.
*/
public function getSymbolSourceByNameAndFile(string $name, string $filePath, string $repo = 'local/knowledge'): ?string
{
$index = $this->loadIndex($repo);
if ($index === null) {
return null;
}

$symbol = $this->findSymbolByNameAndFile($index, $name, $filePath);
if ($symbol === null) {
return null;
}

$contentPath = $this->contentFilePath($repo, $symbol['file']);
if ($contentPath === null || ! file_exists($contentPath)) {
return null;
}

$handle = fopen($contentPath, 'rb');
// @codeCoverageIgnoreStart
if ($handle === false) {
return null;
}
// @codeCoverageIgnoreEnd

fseek($handle, $symbol['byte_offset']);
$source = fread($handle, $symbol['byte_length']);
fclose($handle);

return $source !== false ? $source : null;
}

/**
* Find a symbol by ID in an index.
*
Expand All @@ -319,6 +353,23 @@ private function findSymbol(array $index, string $symbolId): ?array
return null;
}

/**
* Find a symbol by name and file path in an index.
*
* @param array<string, mixed> $index
* @return array<string, mixed>|null
*/
private function findSymbolByNameAndFile(array $index, string $name, string $filePath): ?array
{
foreach ($index['symbols'] as $symbol) {
if (($symbol['name'] ?? '') === $name && ($symbol['file'] ?? '') === $filePath) {
return $symbol;
}
}

return null;
}

/**
* Calculate weighted search score for a symbol.
*
Expand Down
Loading
Loading