context-pilot-engine 0.2.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/dist/engine.d.ts +29 -64
- package/dist/engine.d.ts.map +1 -1
- package/dist/engine.js +209 -198
- package/dist/engine.js.map +1 -0
- package/dist/graph/graph.js.map +1 -0
- package/dist/history/backtest.d.ts +127 -0
- package/dist/history/backtest.d.ts.map +1 -0
- package/dist/history/backtest.js +290 -0
- package/dist/history/backtest.js.map +1 -0
- package/dist/history/cochange.d.ts +91 -0
- package/dist/history/cochange.d.ts.map +1 -0
- package/dist/history/cochange.js +149 -0
- package/dist/history/cochange.js.map +1 -0
- package/dist/history/diff.d.ts +21 -0
- package/dist/history/diff.d.ts.map +1 -0
- package/dist/history/diff.js +57 -0
- package/dist/history/diff.js.map +1 -0
- package/dist/history/git.d.ts +34 -0
- package/dist/history/git.d.ts.map +1 -0
- package/dist/history/git.js +92 -0
- package/dist/history/git.js.map +1 -0
- package/dist/history/miner.d.ts +9 -0
- package/dist/history/miner.d.ts.map +1 -0
- package/dist/history/miner.js +70 -0
- package/dist/history/miner.js.map +1 -0
- package/dist/impact/impact.d.ts +55 -0
- package/dist/impact/impact.d.ts.map +1 -0
- package/dist/impact/impact.js +139 -0
- package/dist/impact/impact.js.map +1 -0
- package/dist/index.d.ts +18 -2
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +12 -1
- package/dist/index.js.map +1 -0
- package/dist/indexer/chunker.d.ts +9 -6
- package/dist/indexer/chunker.d.ts.map +1 -1
- package/dist/indexer/chunker.js +46 -11
- package/dist/indexer/chunker.js.map +1 -0
- package/dist/indexer/imports.d.ts +24 -0
- package/dist/indexer/imports.d.ts.map +1 -0
- package/dist/indexer/imports.js +138 -0
- package/dist/indexer/imports.js.map +1 -0
- package/dist/indexer/indexer.d.ts +15 -0
- package/dist/indexer/indexer.d.ts.map +1 -1
- package/dist/indexer/indexer.js +101 -86
- package/dist/indexer/indexer.js.map +1 -0
- package/dist/indexer/languages.d.ts +2 -2
- package/dist/indexer/languages.d.ts.map +1 -1
- package/dist/indexer/languages.js +10 -0
- package/dist/indexer/languages.js.map +1 -0
- package/dist/pilot/bench.d.ts +53 -0
- package/dist/pilot/bench.d.ts.map +1 -0
- package/dist/pilot/bench.js +143 -0
- package/dist/pilot/bench.js.map +1 -0
- package/dist/pilot/format.d.ts +4 -0
- package/dist/pilot/format.d.ts.map +1 -0
- package/dist/pilot/format.js +31 -0
- package/dist/pilot/format.js.map +1 -0
- package/dist/pilot/pilot.d.ts +47 -0
- package/dist/pilot/pilot.d.ts.map +1 -0
- package/dist/pilot/pilot.js +102 -0
- package/dist/pilot/pilot.js.map +1 -0
- package/dist/pilot/search.d.ts +25 -0
- package/dist/pilot/search.d.ts.map +1 -0
- package/dist/pilot/search.js +130 -0
- package/dist/pilot/search.js.map +1 -0
- package/dist/storage/schema.d.ts.map +1 -1
- package/dist/storage/schema.js +59 -33
- package/dist/storage/schema.js.map +1 -0
- package/dist/storage/sqlite.d.ts +56 -27
- package/dist/storage/sqlite.d.ts.map +1 -1
- package/dist/storage/sqlite.js +143 -123
- package/dist/storage/sqlite.js.map +1 -0
- package/dist/symbols/extract.d.ts +23 -0
- package/dist/symbols/extract.d.ts.map +1 -0
- package/dist/symbols/extract.js +130 -0
- package/dist/symbols/extract.js.map +1 -0
- package/dist/types.d.ts +142 -97
- package/dist/types.d.ts.map +1 -1
- package/dist/types.js.map +1 -0
- package/package.json +24 -10
- package/dist/embedder/embedder.d.ts +0 -4
- package/dist/embedder/embedder.d.ts.map +0 -1
- package/dist/embedder/embedder.js +0 -37
- package/dist/engine.test.d.ts +0 -2
- package/dist/engine.test.d.ts.map +0 -1
- package/dist/engine.test.js +0 -9
- package/dist/search/search.d.ts +0 -12
- package/dist/search/search.d.ts.map +0 -1
- package/dist/search/search.js +0 -38
- package/src/embedder/embedder.ts +0 -46
- package/src/engine.ts +0 -425
- package/src/graph/graph.ts +0 -136
- package/src/index.ts +0 -15
- package/src/indexer/chunker.ts +0 -115
- package/src/indexer/indexer.ts +0 -297
- package/src/indexer/languages.ts +0 -55
- package/src/search/search.ts +0 -48
- package/src/storage/schema.ts +0 -92
- package/src/storage/sqlite.ts +0 -353
- package/src/types.ts +0 -137
- package/tsconfig.json +0 -19
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Diego Alvarez
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/dist/engine.d.ts
CHANGED
|
@@ -1,8 +1,10 @@
|
|
|
1
|
-
import type { IContextEngine, IndexResult,
|
|
1
|
+
import type { CheckQuery, CheckResponse, FindSymbolResponse, OutlineResponse, PilotQuery, PilotResult, CoChangeQuery, CoChangeResponse, ImpactQuery, ImpactResponse, HistoryResult, IContextEngine, IndexResult, StatusResult, SubgraphResult } from "./types.js";
|
|
2
|
+
export declare const DEFAULT_CHECK_MIN_SCORE = 0.6;
|
|
3
|
+
/** Normalizes a user-supplied path to the project-relative, forward-slash form used in storage. */
|
|
4
|
+
export declare function toProjectPath(projectPath: string, file: string): string;
|
|
2
5
|
export declare class ContextEngine implements IContextEngine {
|
|
3
6
|
private db;
|
|
4
7
|
private _initialized;
|
|
5
|
-
private embeddingsCache;
|
|
6
8
|
private graphCache;
|
|
7
9
|
constructor(dbPath?: string);
|
|
8
10
|
init(): Promise<void>;
|
|
@@ -11,21 +13,32 @@ export declare class ContextEngine implements IContextEngine {
|
|
|
11
13
|
force?: boolean;
|
|
12
14
|
paths?: string[];
|
|
13
15
|
}): Promise<IndexResult>;
|
|
14
|
-
|
|
15
|
-
query: string;
|
|
16
|
+
mineHistory(params: {
|
|
16
17
|
projectPath: string;
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
}): Promise<
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
projectPath: string;
|
|
25
|
-
|
|
26
|
-
}): Promise<
|
|
27
|
-
|
|
28
|
-
|
|
18
|
+
force?: boolean;
|
|
19
|
+
maxCommits?: number;
|
|
20
|
+
}): Promise<HistoryResult>;
|
|
21
|
+
coChanges(params: CoChangeQuery): CoChangeResponse;
|
|
22
|
+
impact(params: ImpactQuery): ImpactResponse;
|
|
23
|
+
checkChange(params: CheckQuery): Promise<CheckResponse>;
|
|
24
|
+
ensureFresh(params: {
|
|
25
|
+
projectPath: string;
|
|
26
|
+
maxAgeMs?: number;
|
|
27
|
+
}): Promise<void>;
|
|
28
|
+
pilot(params: PilotQuery): PilotResult;
|
|
29
|
+
outline(params: {
|
|
30
|
+
projectPath: string;
|
|
31
|
+
file: string;
|
|
32
|
+
}): OutlineResponse;
|
|
33
|
+
findSymbol(params: {
|
|
34
|
+
projectPath: string;
|
|
35
|
+
name: string;
|
|
36
|
+
limit?: number;
|
|
37
|
+
}): FindSymbolResponse;
|
|
38
|
+
indexedFiles(params: {
|
|
39
|
+
projectPath: string;
|
|
40
|
+
}): string[];
|
|
41
|
+
private fileTokens;
|
|
29
42
|
status(params: {
|
|
30
43
|
projectPath: string;
|
|
31
44
|
}): Promise<StatusResult>;
|
|
@@ -35,55 +48,7 @@ export declare class ContextEngine implements IContextEngine {
|
|
|
35
48
|
depth?: number;
|
|
36
49
|
direction?: string;
|
|
37
50
|
}): Promise<SubgraphResult>;
|
|
38
|
-
graphDistances(params: {
|
|
39
|
-
projectPath: string;
|
|
40
|
-
activeChunkId: string;
|
|
41
|
-
candidateIds: string[];
|
|
42
|
-
}): Promise<{
|
|
43
|
-
distances: Record<string, number>;
|
|
44
|
-
}>;
|
|
45
|
-
remember(params: {
|
|
46
|
-
projectPath: string;
|
|
47
|
-
sessionId: string;
|
|
48
|
-
memoryType: "decision" | "pattern" | "todo" | "context_note";
|
|
49
|
-
content: string;
|
|
50
|
-
}): Promise<{
|
|
51
|
-
id: string;
|
|
52
|
-
success: boolean;
|
|
53
|
-
}>;
|
|
54
|
-
getCoEditScores(params: {
|
|
55
|
-
projectPath: string;
|
|
56
|
-
activeFilePath: string;
|
|
57
|
-
candidatePaths: string[];
|
|
58
|
-
}): Record<string, number>;
|
|
59
|
-
getFileGraph(params: {
|
|
60
|
-
projectPath: string;
|
|
61
|
-
}): Promise<{
|
|
62
|
-
nodes: Array<{
|
|
63
|
-
id: string;
|
|
64
|
-
path: string;
|
|
65
|
-
language: string;
|
|
66
|
-
chunkCount: number;
|
|
67
|
-
}>;
|
|
68
|
-
edges: Array<{
|
|
69
|
-
from: string;
|
|
70
|
-
to: string;
|
|
71
|
-
}>;
|
|
72
|
-
}>;
|
|
73
|
-
listMemories(params: {
|
|
74
|
-
projectPath: string;
|
|
75
|
-
}): Promise<{
|
|
76
|
-
memories: import("./types.js").MemoryRecord[];
|
|
77
|
-
}>;
|
|
78
|
-
deleteMemory(params: {
|
|
79
|
-
projectPath: string;
|
|
80
|
-
memoryId: string;
|
|
81
|
-
}): Promise<{
|
|
82
|
-
success: boolean;
|
|
83
|
-
}>;
|
|
84
51
|
close(): void;
|
|
85
|
-
private _getEmbeddings;
|
|
86
52
|
private _getGraph;
|
|
87
|
-
private _embedNewChunks;
|
|
88
53
|
}
|
|
89
54
|
//# sourceMappingURL=engine.d.ts.map
|
package/dist/engine.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,
|
|
1
|
+
{"version":3,"file":"engine.d.ts","sourceRoot":"","sources":["../src/engine.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EACV,UAAU,EACV,aAAa,EACb,kBAAkB,EAClB,eAAe,EACf,UAAU,EACV,WAAW,EACX,aAAa,EACb,gBAAgB,EAChB,WAAW,EACX,cAAc,EACd,aAAa,EACb,cAAc,EACd,WAAW,EACX,YAAY,EACZ,cAAc,EACf,MAAM,YAAY,CAAC;AAoDpB,eAAO,MAAM,uBAAuB,MAAM,CAAC;AAE3C,mGAAmG;AACnG,wBAAgB,aAAa,CAAC,WAAW,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,GAAG,MAAM,CAGvE;AAED,qBAAa,aAAc,YAAW,cAAc;IAClD,OAAO,CAAC,EAAE,CAAe;IACzB,OAAO,CAAC,YAAY,CAAS;IAG7B,OAAO,CAAC,UAAU,CAA8B;gBAEpC,MAAM,CAAC,EAAE,MAAM;IAKrB,IAAI,IAAI,OAAO,CAAC,IAAI,CAAC;IAMrB,KAAK,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,EAAE,CAAA;KAAE,GAAG,OAAO,CAAC,WAAW,CAAC;IA6B/F,WAAW,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,aAAa,CAAC;IAQhH,SAAS,CAAC,MAAM,EAAE,aAAa,GAAG,gBAAgB;IAwBlD,MAAM,CAAC,MAAM,EAAE,WAAW,GAAG,cAAc;IAyBrC,WAAW,CAAC,MAAM,EAAE,UAAU,GAAG,OAAO,CAAC,aAAa,CAAC;IAgCvD,WAAW,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,IAAI,CAAC;IAOpF,KAAK,CAAC,MAAM,EAAE,UAAU,GAAG,WAAW;IA0CtC,OAAO,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG,eAAe;IAWvE,UAAU,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAC;QAAC,IAAI,EAAE,MAAM,CAAC;QAAC,KAAK,CAAC,EAAE,MAAM,CAAA;KAAE,GAAG,kBAAkB;IA0B7F,YAAY,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,MAAM,EAAE;IAIvD,OAAO,CAAC,UAAU;IAQZ,MAAM,CAAC,MAAM,EAAE;QAAE,WAAW,EAAE,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC,YAAY,CAAC;IA6B9D,KAAK,CAAC,MAAM,EAAE;QAClB,MAAM,EAAE,MAAM,CAAC;QACf,WAAW,EAAE,MAAM,CAAC;QACpB,KAAK,CAAC,EAAE,MAAM,CAAC;QACf,SAAS,CAAC,EAAE,MAAM,CAAC;KACpB,GAAG,OAAO,CAAC,cAAc,CAAC;IAoC3B,KAAK,IAAI,IAAI;IAIb,OAAO,CAAC,SAAS;CAsBlB"}
|
package/dist/engine.js
CHANGED
|
@@ -1,19 +1,43 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { existsSync, readFileSync, statSync } from "fs";
|
|
2
2
|
import { homedir } from "os";
|
|
3
|
-
import {
|
|
4
|
-
import { openDatabase,
|
|
5
|
-
import {
|
|
3
|
+
import { isAbsolute, join, relative } from "path";
|
|
4
|
+
import { openDatabase, getProjectStats, getProjectGraphEdges, getCoChangeState, getCoChangeStats, getCoChangeFileStats, getCoChangePartners, getFileImports, getIndexedPaths, getProject, getFileSymbols, getProjectSymbols, findSymbolDefs, findSymbolRefs, } from "./storage/sqlite.js";
|
|
5
|
+
import { searchFiles } from "./pilot/search.js";
|
|
6
|
+
import { DEFAULT_PILOT_BUDGET, pilot } from "./pilot/pilot.js";
|
|
7
|
+
import { computeImpact, DEFAULT_IMPACT_DEPTH } from "./impact/impact.js";
|
|
6
8
|
import { initTreeSitter } from "./indexer/languages.js";
|
|
7
9
|
import { indexProject, indexSpecificFiles, projectId } from "./indexer/indexer.js";
|
|
8
|
-
import { semanticSearch, cosineSimilarity } from "./search/search.js";
|
|
9
10
|
import { DiGraph } from "./graph/graph.js";
|
|
10
|
-
|
|
11
|
-
|
|
11
|
+
import { mineHistory } from "./history/miner.js";
|
|
12
|
+
import { combineCoChanges, defaultIgnore, DEFAULT_MAX_FILES_PER_COMMIT, DEFAULT_MIN_CONFIDENCE, DEFAULT_MIN_SUPPORT, } from "./history/cochange.js";
|
|
13
|
+
import { isGitRepo } from "./history/git.js";
|
|
14
|
+
import { readWorkingChanges } from "./history/diff.js";
|
|
15
|
+
const DEFAULT_COCHANGE_LIMIT = 10;
|
|
16
|
+
const DEFAULT_FRESH_MS = 5 * 60_000;
|
|
17
|
+
const DEFAULT_FIND_LIMIT = 30;
|
|
18
|
+
// Seed files from the text search that get expanded with impact()
|
|
19
|
+
const PILOT_SEEDS = 5;
|
|
20
|
+
const toOutline = (r) => ({
|
|
21
|
+
name: r.name,
|
|
22
|
+
kind: r.kind,
|
|
23
|
+
parent: r.parent,
|
|
24
|
+
startLine: r.start_line,
|
|
25
|
+
endLine: r.end_line,
|
|
26
|
+
signature: r.signature,
|
|
27
|
+
});
|
|
28
|
+
// Co-change candidates fed into impact scoring, before the final limit
|
|
29
|
+
const IMPACT_COCHANGE_POOL = 50;
|
|
30
|
+
// Calibrated with `backtest --with-graph --calibrate` (see CLAUDE.md): ~50-65% of alerts are real
|
|
31
|
+
export const DEFAULT_CHECK_MIN_SCORE = 0.6;
|
|
32
|
+
/** Normalizes a user-supplied path to the project-relative, forward-slash form used in storage. */
|
|
33
|
+
export function toProjectPath(projectPath, file) {
|
|
34
|
+
const rel = isAbsolute(file) ? relative(projectPath, file) : file;
|
|
35
|
+
return rel.replace(/\\/g, "/").replace(/^\.\//, "");
|
|
36
|
+
}
|
|
12
37
|
export class ContextEngine {
|
|
13
38
|
db;
|
|
14
39
|
_initialized = false;
|
|
15
|
-
// Per-project
|
|
16
|
-
embeddingsCache = new Map();
|
|
40
|
+
// Per-project cache, invalidated on re-index
|
|
17
41
|
graphCache = new Map();
|
|
18
42
|
constructor(dbPath) {
|
|
19
43
|
const path = dbPath ?? join(homedir(), ".context-pilot", "db.sqlite");
|
|
@@ -22,46 +46,23 @@ export class ContextEngine {
|
|
|
22
46
|
async init() {
|
|
23
47
|
if (this._initialized)
|
|
24
48
|
return;
|
|
25
|
-
process.stderr.write("[engine] initializing tree-sitter...\n");
|
|
26
49
|
await initTreeSitter();
|
|
27
|
-
process.stderr.write("[engine] loading embedding model (first run may download ~90MB)...\n");
|
|
28
|
-
await initEmbedder();
|
|
29
50
|
this._initialized = true;
|
|
30
|
-
process.stderr.write("[engine] ready\n");
|
|
31
51
|
}
|
|
32
52
|
async index(params) {
|
|
33
53
|
if (!this._initialized)
|
|
34
54
|
await this.init();
|
|
35
55
|
const pid = projectId(params.projectPath);
|
|
36
|
-
// Invalidate caches for this project
|
|
37
|
-
this.embeddingsCache.delete(pid);
|
|
38
56
|
this.graphCache.delete(pid);
|
|
39
57
|
try {
|
|
40
|
-
let filesIndexed;
|
|
41
|
-
let filesSkipped;
|
|
42
|
-
let totalFiles;
|
|
43
58
|
if (params.paths && params.paths.length > 0) {
|
|
44
|
-
// Targeted re-index of specific files (used by watcher)
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const { relative } = await import("path");
|
|
48
|
-
const relPaths = params.paths.map((p) => relative(params.projectPath, p).replace(/\\/g, "/"));
|
|
49
|
-
recordCoEdits(this.db, pid, relPaths);
|
|
50
|
-
}
|
|
51
|
-
else {
|
|
52
|
-
// Full project index
|
|
53
|
-
({ filesIndexed, filesSkipped, totalFiles } = await indexProject(this.db, params.projectPath, params.force ?? false));
|
|
59
|
+
// Targeted re-index of specific files (used by watcher); history only changes on commit
|
|
60
|
+
const counts = await indexSpecificFiles(this.db, params.projectPath, params.paths, params.force ?? false);
|
|
61
|
+
return { success: true, projectId: pid, projectPath: params.projectPath, ...counts };
|
|
54
62
|
}
|
|
55
|
-
|
|
56
|
-
await this.
|
|
57
|
-
return {
|
|
58
|
-
success: true,
|
|
59
|
-
projectId: pid,
|
|
60
|
-
projectPath: params.projectPath,
|
|
61
|
-
filesIndexed,
|
|
62
|
-
filesSkipped,
|
|
63
|
-
totalFiles,
|
|
64
|
-
};
|
|
63
|
+
const counts = await indexProject(this.db, params.projectPath, params.force ?? false);
|
|
64
|
+
const history = await this.mineHistory({ projectPath: params.projectPath, force: params.force });
|
|
65
|
+
return { success: true, projectId: pid, projectPath: params.projectPath, ...counts, history };
|
|
65
66
|
}
|
|
66
67
|
catch (err) {
|
|
67
68
|
return {
|
|
@@ -75,48 +76,174 @@ export class ContextEngine {
|
|
|
75
76
|
};
|
|
76
77
|
}
|
|
77
78
|
}
|
|
78
|
-
async
|
|
79
|
-
|
|
80
|
-
await this.
|
|
79
|
+
async mineHistory(params) {
|
|
80
|
+
try {
|
|
81
|
+
return await mineHistory(this.db, projectId(params.projectPath), params.projectPath, params);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
return { status: "error", commitsProcessed: 0, commitsSkipped: 0, files: 0, pairs: 0, error: String(err) };
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
coChanges(params) {
|
|
81
88
|
const pid = projectId(params.projectPath);
|
|
82
|
-
const
|
|
83
|
-
|
|
84
|
-
|
|
89
|
+
const historyAvailable = getCoChangeState(this.db, pid) !== undefined;
|
|
90
|
+
const sources = [...new Set(params.files.map((f) => toProjectPath(params.projectPath, f)))];
|
|
91
|
+
const stats = getCoChangeFileStats(this.db, pid, sources);
|
|
92
|
+
const unknownFiles = sources.filter((s) => !stats.has(s));
|
|
93
|
+
const sourceSet = new Set(sources);
|
|
94
|
+
const rows = sources
|
|
95
|
+
.flatMap((s) => getCoChangePartners(this.db, pid, s))
|
|
96
|
+
.filter((r) => !sourceSet.has(r.candidate));
|
|
97
|
+
const results = combineCoChanges(rows, stats, {
|
|
98
|
+
minSupport: params.minSupport ?? DEFAULT_MIN_SUPPORT,
|
|
99
|
+
minConfidence: params.minConfidence ?? DEFAULT_MIN_CONFIDENCE,
|
|
100
|
+
})
|
|
101
|
+
// History remembers deleted files; only suggest what still exists
|
|
102
|
+
.filter((r) => existsSync(join(params.projectPath, r.path)))
|
|
103
|
+
.slice(0, params.limit ?? DEFAULT_COCHANGE_LIMIT);
|
|
104
|
+
return { results, unknownFiles, historyAvailable };
|
|
105
|
+
}
|
|
106
|
+
impact(params) {
|
|
107
|
+
const pid = projectId(params.projectPath);
|
|
108
|
+
const co = this.coChanges({ projectPath: params.projectPath, files: params.files, limit: IMPACT_COCHANGE_POOL });
|
|
109
|
+
const imports = getFileImports(this.db, pid);
|
|
110
|
+
const files = getIndexedPaths(this.db, pid);
|
|
111
|
+
const changed = [...new Set(params.files.map((f) => toProjectPath(params.projectPath, f)))];
|
|
112
|
+
const results = computeImpact({
|
|
113
|
+
changed,
|
|
114
|
+
coChanges: co.results,
|
|
115
|
+
imports,
|
|
116
|
+
files,
|
|
117
|
+
maxDepth: params.depth ?? DEFAULT_IMPACT_DEPTH,
|
|
118
|
+
})
|
|
119
|
+
.filter((r) => existsSync(join(params.projectPath, r.path)))
|
|
120
|
+
.slice(0, params.limit ?? DEFAULT_COCHANGE_LIMIT);
|
|
121
|
+
return {
|
|
122
|
+
results,
|
|
123
|
+
unknownFiles: co.unknownFiles,
|
|
124
|
+
historyAvailable: co.historyAvailable,
|
|
125
|
+
graphAvailable: files.length > 0,
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
async checkChange(params) {
|
|
129
|
+
const empty = { changed: [], missing: [], unknownFiles: [], historyAvailable: false, graphAvailable: false };
|
|
130
|
+
if (!(await isGitRepo(params.projectPath)))
|
|
131
|
+
return { ...empty, skipped: "not a git repository" };
|
|
132
|
+
const changed = await readWorkingChanges(params.projectPath, { staged: params.staged, base: params.base });
|
|
133
|
+
// Deleted and renamed-away paths still matter: history knows their partners
|
|
134
|
+
const queried = [...new Set(changed.flatMap((c) => (c.oldPath ? [c.path, c.oldPath] : [c.path])))].filter((p) => !defaultIgnore(p));
|
|
135
|
+
if (queried.length === 0)
|
|
136
|
+
return { ...empty, changed };
|
|
137
|
+
// Same cut-off as mining: a change this large is a bulk edit, its co-changes are noise
|
|
138
|
+
if (queried.length > DEFAULT_MAX_FILES_PER_COMMIT) {
|
|
139
|
+
return { ...empty, changed, skipped: `${queried.length} files changed (bulk change)` };
|
|
85
140
|
}
|
|
86
|
-
const
|
|
87
|
-
const
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
|
|
141
|
+
const minScore = params.minScore ?? DEFAULT_CHECK_MIN_SCORE;
|
|
142
|
+
const impact = this.impact({ projectPath: params.projectPath, files: queried, limit: IMPACT_COCHANGE_POOL });
|
|
143
|
+
const inChange = new Set(queried);
|
|
144
|
+
// Threshold on the strongest single signal: the noisy-OR score saturates when many files change
|
|
145
|
+
const missing = impact.results
|
|
146
|
+
.filter((r) => (r.signals[0]?.weight ?? 0) >= minScore && !inChange.has(r.path))
|
|
147
|
+
.slice(0, params.limit ?? DEFAULT_COCHANGE_LIMIT);
|
|
148
|
+
return {
|
|
149
|
+
changed,
|
|
150
|
+
missing,
|
|
151
|
+
unknownFiles: impact.unknownFiles,
|
|
152
|
+
historyAvailable: impact.historyAvailable,
|
|
153
|
+
graphAvailable: impact.graphAvailable,
|
|
154
|
+
};
|
|
155
|
+
}
|
|
156
|
+
async ensureFresh(params) {
|
|
157
|
+
const project = getProject(this.db, projectId(params.projectPath));
|
|
158
|
+
const age = project?.indexed_at ? Date.now() - project.indexed_at : Infinity;
|
|
159
|
+
if (age > (params.maxAgeMs ?? DEFAULT_FRESH_MS))
|
|
160
|
+
await this.index({ projectPath: params.projectPath });
|
|
161
|
+
else
|
|
162
|
+
await this.mineHistory({ projectPath: params.projectPath });
|
|
163
|
+
}
|
|
164
|
+
pilot(params) {
|
|
165
|
+
const pid = projectId(params.projectPath);
|
|
166
|
+
const files = (params.files ?? []).map((f) => toProjectPath(params.projectPath, f));
|
|
167
|
+
const symbols = getProjectSymbols(this.db, pid).map((s) => ({
|
|
168
|
+
path: s.path,
|
|
169
|
+
name: s.name,
|
|
170
|
+
kind: s.kind,
|
|
171
|
+
startLine: s.start_line,
|
|
93
172
|
}));
|
|
94
|
-
|
|
173
|
+
const hits = searchFiles(params.task, symbols, getIndexedPaths(this.db, pid)).filter((h) => existsSync(join(params.projectPath, h.path)));
|
|
174
|
+
const seeds = [...new Set([...files, ...hits.slice(0, PILOT_SEEDS).filter((h) => h.score >= 0.3).map((h) => h.path)])];
|
|
175
|
+
const impact = seeds.length && params.expand !== false
|
|
176
|
+
? this.impact({ projectPath: params.projectPath, files: seeds, limit: 15 }).results
|
|
177
|
+
: [];
|
|
178
|
+
const sourceLines = new Map();
|
|
179
|
+
const read = (path) => {
|
|
180
|
+
if (!sourceLines.has(path)) {
|
|
181
|
+
try {
|
|
182
|
+
sourceLines.set(path, readFileSync(join(params.projectPath, path), "utf8").split(/\r?\n/));
|
|
183
|
+
}
|
|
184
|
+
catch {
|
|
185
|
+
sourceLines.set(path, null);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
return sourceLines.get(path);
|
|
189
|
+
};
|
|
190
|
+
return pilot({
|
|
191
|
+
task: params.task,
|
|
192
|
+
files,
|
|
193
|
+
hits,
|
|
194
|
+
impact,
|
|
195
|
+
budget: params.budget ?? DEFAULT_PILOT_BUDGET,
|
|
196
|
+
outline: (path) => getFileSymbols(this.db, pid, path).map(toOutline),
|
|
197
|
+
fileTokens: (path) => this.fileTokens(params.projectPath, path),
|
|
198
|
+
lines: (path, start, end) => read(path)?.slice(start - 1, end).join("\n") ?? null,
|
|
199
|
+
});
|
|
95
200
|
}
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
201
|
+
outline(params) {
|
|
202
|
+
const path = toProjectPath(params.projectPath, params.file);
|
|
203
|
+
const pid = projectId(params.projectPath);
|
|
204
|
+
return {
|
|
205
|
+
path,
|
|
206
|
+
symbols: getFileSymbols(this.db, pid, path).map(toOutline),
|
|
207
|
+
fileTokens: this.fileTokens(params.projectPath, path),
|
|
208
|
+
indexed: getIndexedPaths(this.db, pid).includes(path),
|
|
209
|
+
};
|
|
210
|
+
}
|
|
211
|
+
findSymbol(params) {
|
|
99
212
|
const pid = projectId(params.projectPath);
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
213
|
+
// "Class.method" or "module.fn": look up the last part
|
|
214
|
+
const name = params.name.trim().split(/[.:#]/).pop() ?? params.name;
|
|
215
|
+
const definitions = findSymbolDefs(this.db, pid, name).map((r) => ({
|
|
216
|
+
...toOutline(r),
|
|
217
|
+
path: r.path,
|
|
218
|
+
exported: r.exported === 1,
|
|
219
|
+
}));
|
|
220
|
+
const byFile = new Map();
|
|
221
|
+
for (const r of findSymbolRefs(this.db, pid, name)) {
|
|
222
|
+
const lines = byFile.get(r.path) ?? [];
|
|
223
|
+
lines.push(r.line);
|
|
224
|
+
byFile.set(r.path, lines);
|
|
103
225
|
}
|
|
104
|
-
const
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
.map((m) => ({ ...m, score: cosineSimilarity(queryVec, m.vector) }))
|
|
108
|
-
.sort((a, b) => b.score - a.score)
|
|
109
|
-
.slice(0, k);
|
|
226
|
+
const uses = [...byFile.entries()]
|
|
227
|
+
.map(([path, lines]) => ({ path, lines }))
|
|
228
|
+
.sort((a, b) => b.lines.length - a.lines.length);
|
|
110
229
|
return {
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
score: m.score,
|
|
116
|
-
created_at: m.createdAt,
|
|
117
|
-
})),
|
|
230
|
+
name,
|
|
231
|
+
definitions,
|
|
232
|
+
uses: uses.slice(0, params.limit ?? DEFAULT_FIND_LIMIT),
|
|
233
|
+
totalUses: uses.reduce((a, u) => a + u.lines.length, 0),
|
|
118
234
|
};
|
|
119
235
|
}
|
|
236
|
+
indexedFiles(params) {
|
|
237
|
+
return getIndexedPaths(this.db, projectId(params.projectPath));
|
|
238
|
+
}
|
|
239
|
+
fileTokens(projectPath, path) {
|
|
240
|
+
try {
|
|
241
|
+
return Math.ceil(statSync(join(projectPath, path)).size / 4);
|
|
242
|
+
}
|
|
243
|
+
catch {
|
|
244
|
+
return 0;
|
|
245
|
+
}
|
|
246
|
+
}
|
|
120
247
|
async status(params) {
|
|
121
248
|
const pid = projectId(params.projectPath);
|
|
122
249
|
const project = this.db
|
|
@@ -126,6 +253,7 @@ export class ContextEngine {
|
|
|
126
253
|
return { indexed: false, projectPath: params.projectPath };
|
|
127
254
|
}
|
|
128
255
|
const stats = getProjectStats(this.db, pid);
|
|
256
|
+
const state = getCoChangeState(this.db, pid);
|
|
129
257
|
return {
|
|
130
258
|
indexed: project.indexed_at !== null,
|
|
131
259
|
projectId: pid,
|
|
@@ -133,11 +261,18 @@ export class ContextEngine {
|
|
|
133
261
|
files: stats.files,
|
|
134
262
|
chunks: stats.chunks,
|
|
135
263
|
indexedAt: project.indexed_at ?? undefined,
|
|
264
|
+
history: state && {
|
|
265
|
+
headSha: state.head_sha,
|
|
266
|
+
minedAt: state.mined_at,
|
|
267
|
+
commitsProcessed: state.commits_processed,
|
|
268
|
+
commitsSkipped: state.commits_skipped,
|
|
269
|
+
...getCoChangeStats(this.db, pid),
|
|
270
|
+
},
|
|
136
271
|
};
|
|
137
272
|
}
|
|
138
273
|
async graph(params) {
|
|
139
274
|
const pid = projectId(params.projectPath);
|
|
140
|
-
const g =
|
|
275
|
+
const g = this._getGraph(pid);
|
|
141
276
|
// Find root node — match by name or path
|
|
142
277
|
let rootId;
|
|
143
278
|
for (const [id, attrs] of g.allNodes()) {
|
|
@@ -165,102 +300,13 @@ export class ContextEngine {
|
|
|
165
300
|
})),
|
|
166
301
|
};
|
|
167
302
|
}
|
|
168
|
-
async graphDistances(params) {
|
|
169
|
-
const pid = projectId(params.projectPath);
|
|
170
|
-
const g = await this._getGraph(pid);
|
|
171
|
-
const distances = g.shortestPathDistances(params.activeChunkId, params.candidateIds);
|
|
172
|
-
return { distances };
|
|
173
|
-
}
|
|
174
|
-
async remember(params) {
|
|
175
|
-
if (!this._initialized)
|
|
176
|
-
await this.init();
|
|
177
|
-
const pid = projectId(params.projectPath);
|
|
178
|
-
upsertProject(this.db, pid, params.projectPath);
|
|
179
|
-
const id = randomUUID();
|
|
180
|
-
this.db.prepare(`
|
|
181
|
-
INSERT INTO memories (id, project_id, session_id, memory_type, content, relevance_score, created_at)
|
|
182
|
-
VALUES (?, ?, ?, ?, ?, 1.0, ?)
|
|
183
|
-
`).run(id, pid, params.sessionId, params.memoryType, params.content, Date.now());
|
|
184
|
-
// Store embedding so memories are semantically searchable
|
|
185
|
-
try {
|
|
186
|
-
const vector = await embedSingle(params.content);
|
|
187
|
-
upsertMemoryEmbedding(this.db, id, vector, MODEL);
|
|
188
|
-
}
|
|
189
|
-
catch {
|
|
190
|
-
// non-critical — memory is stored even without embedding
|
|
191
|
-
}
|
|
192
|
-
return { id, success: true };
|
|
193
|
-
}
|
|
194
|
-
getCoEditScores(params) {
|
|
195
|
-
const pid = projectId(params.projectPath);
|
|
196
|
-
return getCoEditScores(this.db, pid, params.activeFilePath, params.candidatePaths);
|
|
197
|
-
}
|
|
198
|
-
async getFileGraph(params) {
|
|
199
|
-
const pid = projectId(params.projectPath);
|
|
200
|
-
const files = this.db.prepare(`
|
|
201
|
-
SELECT f.id, f.path, COALESCE(f.language, 'unknown') as language, COUNT(c.id) as chunk_count
|
|
202
|
-
FROM files f
|
|
203
|
-
LEFT JOIN chunks c ON c.file_id = f.id
|
|
204
|
-
WHERE f.project_id = ?
|
|
205
|
-
GROUP BY f.id
|
|
206
|
-
ORDER BY chunk_count DESC
|
|
207
|
-
LIMIT 400
|
|
208
|
-
`).all(pid);
|
|
209
|
-
const edges = this.db.prepare(`
|
|
210
|
-
SELECT DISTINCT f1.id AS from_file, f2.id AS to_file
|
|
211
|
-
FROM graph_edges ge
|
|
212
|
-
JOIN chunks c1 ON c1.id = ge.from_chunk
|
|
213
|
-
JOIN files f1 ON f1.id = c1.file_id
|
|
214
|
-
JOIN chunks c2 ON c2.id = ge.to_chunk
|
|
215
|
-
JOIN files f2 ON f2.id = c2.file_id
|
|
216
|
-
WHERE f1.project_id = ? AND f1.id != f2.id
|
|
217
|
-
`).all(pid);
|
|
218
|
-
// Only include edges where both nodes are in our limited node set
|
|
219
|
-
const nodeIds = new Set(files.map((f) => f.id));
|
|
220
|
-
const filteredEdges = edges.filter((e) => nodeIds.has(e.from_file) && nodeIds.has(e.to_file));
|
|
221
|
-
return {
|
|
222
|
-
nodes: files.map((f) => ({
|
|
223
|
-
id: f.id,
|
|
224
|
-
path: f.path,
|
|
225
|
-
language: f.language,
|
|
226
|
-
chunkCount: f.chunk_count,
|
|
227
|
-
})),
|
|
228
|
-
edges: filteredEdges.map((e) => ({ from: e.from_file, to: e.to_file })),
|
|
229
|
-
};
|
|
230
|
-
}
|
|
231
|
-
async listMemories(params) {
|
|
232
|
-
const pid = projectId(params.projectPath);
|
|
233
|
-
const memories = this.db.prepare(`
|
|
234
|
-
SELECT id, memory_type, content, session_id, relevance_score, created_at
|
|
235
|
-
FROM memories
|
|
236
|
-
WHERE project_id = ?
|
|
237
|
-
ORDER BY created_at DESC
|
|
238
|
-
`).all(pid);
|
|
239
|
-
return { memories };
|
|
240
|
-
}
|
|
241
|
-
async deleteMemory(params) {
|
|
242
|
-
const pid = projectId(params.projectPath);
|
|
243
|
-
const result = this.db
|
|
244
|
-
.prepare(`DELETE FROM memories WHERE id = ? AND project_id = ?`)
|
|
245
|
-
.run(params.memoryId, pid);
|
|
246
|
-
return { success: result.changes > 0 };
|
|
247
|
-
}
|
|
248
303
|
close() {
|
|
249
304
|
this.db.close();
|
|
250
305
|
}
|
|
251
|
-
|
|
252
|
-
async _getEmbeddings(projectId) {
|
|
253
|
-
if (this.embeddingsCache.has(projectId))
|
|
254
|
-
return this.embeddingsCache.get(projectId);
|
|
255
|
-
const candidates = getAllEmbeddings(this.db, projectId);
|
|
256
|
-
this.embeddingsCache.set(projectId, candidates);
|
|
257
|
-
return candidates;
|
|
258
|
-
}
|
|
259
|
-
async _getGraph(projectId) {
|
|
306
|
+
_getGraph(projectId) {
|
|
260
307
|
if (this.graphCache.has(projectId))
|
|
261
308
|
return this.graphCache.get(projectId);
|
|
262
309
|
const g = new DiGraph();
|
|
263
|
-
// Add all chunks as nodes
|
|
264
310
|
const chunks = this.db.prepare(`
|
|
265
311
|
SELECT c.id, c.chunk_type, c.name, f.path
|
|
266
312
|
FROM chunks c JOIN files f ON f.id = c.file_id
|
|
@@ -269,46 +315,11 @@ export class ContextEngine {
|
|
|
269
315
|
for (const c of chunks) {
|
|
270
316
|
g.addNode(c.id, { chunkType: c.chunk_type, name: c.name, path: c.path });
|
|
271
317
|
}
|
|
272
|
-
|
|
273
|
-
const edges = getProjectGraphEdges(this.db, projectId);
|
|
274
|
-
for (const e of edges) {
|
|
318
|
+
for (const e of getProjectGraphEdges(this.db, projectId)) {
|
|
275
319
|
g.addEdge(e.from_chunk, e.to_chunk, { edgeType: e.edge_type, weight: e.weight });
|
|
276
320
|
}
|
|
277
321
|
this.graphCache.set(projectId, g);
|
|
278
322
|
return g;
|
|
279
323
|
}
|
|
280
|
-
async _embedNewChunks(pid) {
|
|
281
|
-
// Find chunks without embeddings
|
|
282
|
-
const unembedded = this.db.prepare(`
|
|
283
|
-
SELECT c.id, c.content
|
|
284
|
-
FROM chunks c
|
|
285
|
-
JOIN files f ON f.id = c.file_id
|
|
286
|
-
WHERE f.project_id = ?
|
|
287
|
-
AND c.id NOT IN (SELECT chunk_id FROM embeddings)
|
|
288
|
-
`).all(pid);
|
|
289
|
-
if (unembedded.length === 0)
|
|
290
|
-
return;
|
|
291
|
-
process.stderr.write(`[engine] embedding ${unembedded.length} new chunks...\n`);
|
|
292
|
-
const texts = unembedded.map((c) => c.content);
|
|
293
|
-
const vectors = await embedTexts(texts);
|
|
294
|
-
const stmt = this.db.prepare(`
|
|
295
|
-
INSERT OR REPLACE INTO embeddings (chunk_id, model, vector, dims, created_at)
|
|
296
|
-
VALUES (?, ?, ?, ?, ?)
|
|
297
|
-
`);
|
|
298
|
-
const { vectorToBlob } = await import("./storage/sqlite.js");
|
|
299
|
-
this.db.exec("BEGIN");
|
|
300
|
-
try {
|
|
301
|
-
for (let i = 0; i < unembedded.length; i++) {
|
|
302
|
-
stmt.run(unembedded[i].id, MODEL, vectorToBlob(vectors[i]), vectors[i].length, Date.now());
|
|
303
|
-
}
|
|
304
|
-
this.db.exec("COMMIT");
|
|
305
|
-
}
|
|
306
|
-
catch (err) {
|
|
307
|
-
this.db.exec("ROLLBACK");
|
|
308
|
-
throw err;
|
|
309
|
-
}
|
|
310
|
-
// Invalidate embeddings cache
|
|
311
|
-
this.embeddingsCache.delete(pid);
|
|
312
|
-
}
|
|
313
324
|
}
|
|
314
325
|
//# sourceMappingURL=engine.js.map
|