@krisada-m/ksd-intelligence 0.0.0-stage → 1.1.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/.antigravity-plugin/plugin.json +20 -0
- package/LICENSE +21 -0
- package/README.md +195 -2
- package/agy-skills/erosiano-review/SKILL.md +17 -0
- package/dist/adapters/agy/skills.js +252 -0
- package/dist/adapters/cli/check-changed.js +3 -0
- package/dist/adapters/cli/main.js +1013 -0
- package/dist/adapters/cli/policy-bin.js +10 -0
- package/dist/adapters/cli/review-verdict.js +3 -0
- package/dist/adapters/omp/extension.js +884 -0
- package/dist/adapters/omp/skills.js +130 -0
- package/dist/adapters/ui/hud.js +389 -0
- package/dist/adapters/ui/tree.js +471 -0
- package/dist/core/audit/index.js +2 -0
- package/dist/core/audit/log.js +505 -0
- package/dist/core/audit/summary.js +188 -0
- package/dist/core/changes/changes.js +591 -0
- package/dist/core/changes/git.js +266 -0
- package/dist/core/changes/plan.js +109 -0
- package/dist/core/changes/render.js +356 -0
- package/dist/core/engine/build.js +178 -0
- package/dist/core/engine/child.js +389 -0
- package/dist/core/engine/host.js +206 -0
- package/dist/core/engine/lock.js +133 -0
- package/dist/core/engine/protocol.js +43 -0
- package/dist/core/engine/runtime.js +44 -0
- package/dist/core/engine/status.js +452 -0
- package/dist/core/engine/typescript.js +194 -0
- package/dist/core/engine/workspace.js +72 -0
- package/dist/core/graph/graph.js +127 -0
- package/dist/core/graph/limits.js +16 -0
- package/dist/core/impact/query.js +1292 -0
- package/dist/core/impact/render.js +590 -0
- package/dist/core/impact/session.js +694 -0
- package/dist/core/indexing/declarations.js +455 -0
- package/dist/core/indexing/differential.js +345 -0
- package/dist/core/indexing/doctor.js +120 -0
- package/dist/core/indexing/indexer.js +811 -0
- package/dist/core/indexing/keys.js +451 -0
- package/dist/core/indexing/lexical.js +212 -0
- package/dist/core/indexing/packages.js +57 -0
- package/dist/core/indexing/program.js +171 -0
- package/dist/core/indexing/resolve.js +1004 -0
- package/dist/core/indexing/stamp.js +52 -0
- package/dist/core/indexing/surface.js +335 -0
- package/dist/core/indexing/ui-progress.js +37 -0
- package/dist/core/indexing/verify.js +76 -0
- package/dist/core/kernel/config.js +383 -0
- package/dist/core/kernel/glob.js +105 -0
- package/dist/core/kernel/guards.js +4 -0
- package/dist/core/kernel/types.js +3 -0
- package/dist/core/kernel/verdict.js +142 -0
- package/dist/core/knowledge/anchors.js +139 -0
- package/dist/core/knowledge/knowledge.js +95 -0
- package/dist/core/knowledge/learning.js +102 -0
- package/dist/core/knowledge/render.js +76 -0
- package/dist/core/knowledge/store.js +109 -0
- package/dist/core/knowledge/yaml.js +87 -0
- package/dist/core/search/lexical.js +382 -0
- package/dist/core/search/render.js +98 -0
- package/dist/core/search/segments.js +118 -0
- package/dist/core/verify/parse.js +127 -0
- package/dist/core/verify/render.js +67 -0
- package/dist/core/verify/report.js +40 -0
- package/dist/core/verify/revision.js +79 -0
- package/dist/core/verify/run.js +117 -0
- package/dist/core/verify/store.js +66 -0
- package/dist/core/verify/verify.js +173 -0
- package/dist/core/workspace/init.js +267 -0
- package/dist/core/workspace/probe.js +56 -0
- package/dist/core/workspace/scan.js +420 -0
- package/dist/engineering/baseline.js +337 -0
- package/dist/engineering/change-scope.js +500 -0
- package/dist/engineering/check-changed.js +40 -0
- package/dist/engineering/config.js +129 -0
- package/dist/engineering/dist/policy.d.ts +17 -0
- package/dist/engineering/dist/policy.js +150 -0
- package/dist/engineering/dist/runtime.d.ts +40 -0
- package/dist/engineering/dist/runtime.js +77 -0
- package/dist/engineering/dist/sdlc.d.ts +7 -0
- package/dist/engineering/dist/sdlc.js +27 -0
- package/dist/engineering/eslint-rules/index.js +107 -0
- package/dist/engineering/index.d.ts +7 -0
- package/dist/engineering/index.js +319 -0
- package/dist/engineering/intelligence.js +44 -0
- package/dist/engineering/package.json +36 -0
- package/dist/engineering/policy.js +2 -0
- package/dist/engineering/practice-tool.js +72 -0
- package/dist/engineering/practices.js +283 -0
- package/dist/engineering/practices.json +2453 -0
- package/dist/engineering/review-verdict.js +262 -0
- package/dist/engineering/sdlc.js +2 -0
- package/dist/index.js +20 -0
- package/dist/storage/records.js +245 -0
- package/dist/storage/sqlite.js +314 -0
- package/dist/workflow/catalog.js +69 -0
- package/dist/workflow/classify.js +55 -0
- package/dist/workflow/loader.js +140 -0
- package/dist/workflow/packs.js +469 -0
- package/dist/workflow/registry.js +359 -0
- package/dist/workflow/render.js +61 -0
- package/dist/workflow/router.js +141 -0
- package/dist/workflow/sources.js +229 -0
- package/dist/workflow/types.js +44 -0
- package/dist/workflow/updates.js +532 -0
- package/engineering.lock.json +94 -0
- package/package.json +81 -4
- package/rules/engineering.md +20 -0
- package/scripts/agy-mcp.mjs +27 -0
- package/scripts/mcp/engineering.mjs +91 -0
- package/scripts/mcp/stdio.mjs +304 -0
- package/scripts/mcp/tools.mjs +491 -0
- package/skills/ksd-intelligence/SKILL.md +54 -0
- package/skills/matt-sdlc/SKILL.md +42 -0
- package/skills/osmani-quality/SKILL.md +38 -0
- package/skills/poteto-mode/SKILL.md +40 -0
- package/skills/pstack-analysis/SKILL.md +36 -0
- package/skills.lock.json +71 -0
- package/skills.registry.json +181 -0
|
@@ -0,0 +1,382 @@
|
|
|
1
|
+
import { engineVersion } from '../engine/typescript.js';
|
|
2
|
+
import { matchAny } from '../kernel/glob.js';
|
|
3
|
+
import { readMeta } from '../../storage/sqlite.js';
|
|
4
|
+
import { tokenizeForQuery } from './segments.js';
|
|
5
|
+
export const DEFAULT_SEARCH_LIMIT = 8;
|
|
6
|
+
export const MIN_SEARCH_LIMIT = 1;
|
|
7
|
+
export const MAX_SEARCH_LIMIT = 20;
|
|
8
|
+
export const MAX_SEARCH_QUERY_CHARS = 200;
|
|
9
|
+
const MAX_FTS_TOKENS = 32;
|
|
10
|
+
const MAX_CANDIDATES = 500;
|
|
11
|
+
const MAX_EXACT_CANDIDATES = 100;
|
|
12
|
+
// Column order in declarations_fts (migration 5):
|
|
13
|
+
// 0: stable_key UNINDEXED, 1: name_tokens, 2: owner_tokens, 3: kind, 4: signature, 5: doc, 6: path_tokens
|
|
14
|
+
const BM25_SQL = '-bm25(declarations_fts, 0.0, 25.0, 10.0, 0.5, 5.0, 3.0, 1.0)';
|
|
15
|
+
export function validateSearchInput(rawQuery, rawLimit) {
|
|
16
|
+
if (typeof rawQuery !== 'string' ||
|
|
17
|
+
rawQuery.includes('\0') ||
|
|
18
|
+
rawQuery.trim().length === 0 ||
|
|
19
|
+
rawQuery.length > MAX_SEARCH_QUERY_CHARS) {
|
|
20
|
+
return {
|
|
21
|
+
ok: false,
|
|
22
|
+
message: 'query must be a non-empty string of 1–200 characters',
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
let limit = DEFAULT_SEARCH_LIMIT;
|
|
26
|
+
if (rawLimit !== undefined) {
|
|
27
|
+
if (typeof rawLimit !== 'number' ||
|
|
28
|
+
!Number.isInteger(rawLimit) ||
|
|
29
|
+
rawLimit < MIN_SEARCH_LIMIT ||
|
|
30
|
+
rawLimit > MAX_SEARCH_LIMIT) {
|
|
31
|
+
return { ok: false, message: 'limit must be an integer 1–20' };
|
|
32
|
+
}
|
|
33
|
+
limit = rawLimit;
|
|
34
|
+
}
|
|
35
|
+
return { ok: true, query: rawQuery.trim(), limit };
|
|
36
|
+
}
|
|
37
|
+
/** Wraps a query term as a double-quoted FTS5 string literal so no operator is ever parsed. */
|
|
38
|
+
export function quoteFtsLiteral(term) {
|
|
39
|
+
return `"${term.replaceAll('\0', '').replaceAll('"', '""')}"`;
|
|
40
|
+
}
|
|
41
|
+
function buildFtsQueryInternal(query) {
|
|
42
|
+
const rawTerms = [];
|
|
43
|
+
const rawSeen = new Set();
|
|
44
|
+
const pushRaw = (term) => {
|
|
45
|
+
if (term === '' || rawSeen.has(term))
|
|
46
|
+
return;
|
|
47
|
+
rawSeen.add(term);
|
|
48
|
+
rawTerms.push(term);
|
|
49
|
+
};
|
|
50
|
+
for (const part of query.trim().split(/\s+/)) {
|
|
51
|
+
if (part === '')
|
|
52
|
+
continue;
|
|
53
|
+
pushRaw(part);
|
|
54
|
+
if (part.endsWith('()') && part.length > 2) {
|
|
55
|
+
pushRaw(part.slice(0, -2));
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const alnumRaw = rawTerms.filter((term) => /\p{L}|\p{N}/u.test(term));
|
|
59
|
+
const splitTokens = tokenizeForQuery(query);
|
|
60
|
+
const ftsTokens = [];
|
|
61
|
+
const ftsSeen = new Set();
|
|
62
|
+
let tokenLimitHit = false;
|
|
63
|
+
for (const token of [...splitTokens, ...alnumRaw.map((term) => term.toLowerCase())]) {
|
|
64
|
+
if (token === '' || ftsSeen.has(token))
|
|
65
|
+
continue;
|
|
66
|
+
if (ftsTokens.length >= MAX_FTS_TOKENS) {
|
|
67
|
+
tokenLimitHit = true;
|
|
68
|
+
break;
|
|
69
|
+
}
|
|
70
|
+
ftsSeen.add(token);
|
|
71
|
+
ftsTokens.push(token);
|
|
72
|
+
}
|
|
73
|
+
const exactClauses = [];
|
|
74
|
+
const exactSeen = new Set();
|
|
75
|
+
const pushExactClause = (term) => {
|
|
76
|
+
const clause = `name_tokens : ${quoteFtsLiteral(term)}`;
|
|
77
|
+
if (exactSeen.has(clause) || exactClauses.length >= MAX_FTS_TOKENS)
|
|
78
|
+
return;
|
|
79
|
+
exactSeen.add(clause);
|
|
80
|
+
exactClauses.push(clause);
|
|
81
|
+
};
|
|
82
|
+
for (const term of alnumRaw) {
|
|
83
|
+
pushExactClause(term);
|
|
84
|
+
const dot = term.lastIndexOf('.');
|
|
85
|
+
if (dot > 0 && dot < term.length - 1) {
|
|
86
|
+
const afterDot = term.slice(dot + 1);
|
|
87
|
+
if (/\p{L}|\p{N}/u.test(afterDot)) {
|
|
88
|
+
pushExactClause(afterDot);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
return {
|
|
93
|
+
matchExpr: ftsTokens.length === 0 ? null : ftsTokens.map(quoteFtsLiteral).join(' OR '),
|
|
94
|
+
exactMatchExpr: exactClauses.length === 0 ? null : exactClauses.join(' OR '),
|
|
95
|
+
rawTerms,
|
|
96
|
+
tokenLimitHit,
|
|
97
|
+
};
|
|
98
|
+
}
|
|
99
|
+
export function buildFtsQuery(query) {
|
|
100
|
+
const { matchExpr, exactMatchExpr, rawTerms } = buildFtsQueryInternal(query);
|
|
101
|
+
return { matchExpr, exactMatchExpr, rawTerms };
|
|
102
|
+
}
|
|
103
|
+
function mapCandidateRow(row) {
|
|
104
|
+
return {
|
|
105
|
+
id: Number(row.id),
|
|
106
|
+
stableKey: String(row.stable_key),
|
|
107
|
+
signature: String(row.signature),
|
|
108
|
+
file: String(row.file),
|
|
109
|
+
name: String(row.name),
|
|
110
|
+
simple: String(row.simple),
|
|
111
|
+
declKind: String(row.decl_kind),
|
|
112
|
+
exported: Number(row.exported),
|
|
113
|
+
startLine: Number(row.start_line),
|
|
114
|
+
endLine: Number(row.end_line),
|
|
115
|
+
bm25Score: Number(row.bm25_score),
|
|
116
|
+
callers: Number(row.callers),
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
function readCandidates(db, matchExpr, candidateLimit) {
|
|
120
|
+
// Select top-N rowids via compact symbols B-tree before hydrating wide FTS/declaration rows and caller counts.
|
|
121
|
+
const rows = db
|
|
122
|
+
.prepare(`WITH top AS (
|
|
123
|
+
SELECT
|
|
124
|
+
f.rowid AS id,
|
|
125
|
+
s.key AS stable_key,
|
|
126
|
+
${BM25_SQL} AS bm25_score
|
|
127
|
+
FROM declarations_fts f
|
|
128
|
+
JOIN symbols s ON s.id = f.rowid
|
|
129
|
+
WHERE declarations_fts MATCH ?
|
|
130
|
+
ORDER BY bm25_score DESC, s.key ASC
|
|
131
|
+
LIMIT ?
|
|
132
|
+
)
|
|
133
|
+
SELECT
|
|
134
|
+
top.id AS id,
|
|
135
|
+
top.stable_key AS stable_key,
|
|
136
|
+
f.signature AS signature,
|
|
137
|
+
d.file AS file,
|
|
138
|
+
d.name AS name,
|
|
139
|
+
d.simple AS simple,
|
|
140
|
+
d.kind AS decl_kind,
|
|
141
|
+
d.exported AS exported,
|
|
142
|
+
d.start_line AS start_line,
|
|
143
|
+
d.end_line AS end_line,
|
|
144
|
+
top.bm25_score AS bm25_score,
|
|
145
|
+
(SELECT COUNT(DISTINCT e.source) FROM edges e WHERE e.target = d.id AND e.kind NOT IN ('IMPORTS', 'TESTS')) AS callers
|
|
146
|
+
FROM top
|
|
147
|
+
JOIN declarations d ON d.id = top.id
|
|
148
|
+
JOIN declarations_fts f ON f.rowid = top.id`)
|
|
149
|
+
.all(matchExpr, candidateLimit);
|
|
150
|
+
return rows.map(mapCandidateRow);
|
|
151
|
+
}
|
|
152
|
+
export function querySearch(db, impact, query, limit, extras) {
|
|
153
|
+
const meta = extras?.meta ?? readMeta(db);
|
|
154
|
+
const engine = {
|
|
155
|
+
version: engineVersion(),
|
|
156
|
+
typescript: meta.typescript_version ?? 'unknown',
|
|
157
|
+
extractor: meta.extractor_stamp ?? 'unknown',
|
|
158
|
+
};
|
|
159
|
+
const scannedFiles = extras?.scannedFiles ??
|
|
160
|
+
Number(db.prepare('SELECT COUNT(*) AS n FROM files').get()?.n ?? 0);
|
|
161
|
+
const indexState = extras?.indexState ?? 'fresh';
|
|
162
|
+
const { matchExpr, exactMatchExpr, rawTerms, tokenLimitHit } = buildFtsQueryInternal(query);
|
|
163
|
+
if (matchExpr === null && exactMatchExpr === null) {
|
|
164
|
+
return {
|
|
165
|
+
query,
|
|
166
|
+
limit,
|
|
167
|
+
totalMatches: 0,
|
|
168
|
+
hits: [],
|
|
169
|
+
indexState,
|
|
170
|
+
...(extras?.updatedFiles !== undefined ? { updatedFiles: extras.updatedFiles } : {}),
|
|
171
|
+
scannedFiles,
|
|
172
|
+
...(extras?.staleReason !== undefined ? { staleReason: extras.staleReason } : {}),
|
|
173
|
+
engine,
|
|
174
|
+
};
|
|
175
|
+
}
|
|
176
|
+
const candidates = new Map();
|
|
177
|
+
const seenIds = new Set();
|
|
178
|
+
let ftsTotal = 0;
|
|
179
|
+
if (matchExpr !== null) {
|
|
180
|
+
const topRows = readCandidates(db, matchExpr, MAX_CANDIDATES);
|
|
181
|
+
for (const row of topRows) {
|
|
182
|
+
candidates.set(row.stableKey, row);
|
|
183
|
+
seenIds.add(row.id);
|
|
184
|
+
}
|
|
185
|
+
if (topRows.length < MAX_CANDIDATES) {
|
|
186
|
+
ftsTotal = topRows.length;
|
|
187
|
+
}
|
|
188
|
+
else {
|
|
189
|
+
const totalRow = db
|
|
190
|
+
.prepare('SELECT COUNT(*) AS total FROM declarations_fts WHERE declarations_fts MATCH ?')
|
|
191
|
+
.get(matchExpr);
|
|
192
|
+
ftsTotal = Number(totalRow?.total ?? 0);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
const exactSet = new Set([...rawTerms, query.trim()]);
|
|
196
|
+
const exactLowerSet = new Set([...exactSet].map((term) => term.toLowerCase()));
|
|
197
|
+
if ((ftsTotal > MAX_CANDIDATES || tokenLimitHit || matchExpr === null) &&
|
|
198
|
+
exactMatchExpr !== null) {
|
|
199
|
+
const exactTerms = [...exactSet].filter((term) => !term.includes('\0') && /\p{L}|\p{N}/u.test(term));
|
|
200
|
+
const hasNonAscii = exactTerms.some((term) => /[^\x00-\x7f]/.test(term));
|
|
201
|
+
const fallbackExact = () => {
|
|
202
|
+
for (const row of readCandidates(db, exactMatchExpr, MAX_EXACT_CANDIDATES)) {
|
|
203
|
+
if (!candidates.has(row.stableKey)) {
|
|
204
|
+
candidates.set(row.stableKey, row);
|
|
205
|
+
seenIds.add(row.id);
|
|
206
|
+
}
|
|
207
|
+
}
|
|
208
|
+
};
|
|
209
|
+
if (hasNonAscii || exactTerms.length === 0 || matchExpr === null) {
|
|
210
|
+
fallbackExact();
|
|
211
|
+
}
|
|
212
|
+
else {
|
|
213
|
+
// IN (...) + UNION avoids SQLite's planner falling back to SCAN d on OR across COLLATE NOCASE predicates.
|
|
214
|
+
const simplePlaceholders = exactTerms.map(() => '?').join(', ');
|
|
215
|
+
const dottedTerms = exactTerms.filter((term) => term.includes('.') || term.includes(' '));
|
|
216
|
+
const exactSql = dottedTerms.length === 0
|
|
217
|
+
? `SELECT d.id AS id
|
|
218
|
+
FROM declarations d
|
|
219
|
+
WHERE d.kind != 'module' AND d.simple COLLATE NOCASE IN (${simplePlaceholders})`
|
|
220
|
+
: `SELECT d.id AS id
|
|
221
|
+
FROM declarations d
|
|
222
|
+
WHERE d.kind != 'module' AND d.simple COLLATE NOCASE IN (${simplePlaceholders})
|
|
223
|
+
UNION
|
|
224
|
+
SELECT d.id AS id
|
|
225
|
+
FROM declarations d
|
|
226
|
+
WHERE d.kind != 'module' AND d.name COLLATE NOCASE IN (${dottedTerms.map(() => '?').join(', ')})`;
|
|
227
|
+
const exactIdRows = db.prepare(exactSql).all(...exactTerms, ...dottedTerms);
|
|
228
|
+
const missingExactIds = [];
|
|
229
|
+
for (const row of exactIdRows) {
|
|
230
|
+
const id = Number(row.id);
|
|
231
|
+
if (!seenIds.has(id))
|
|
232
|
+
missingExactIds.push(id);
|
|
233
|
+
}
|
|
234
|
+
if (missingExactIds.length > MAX_EXACT_CANDIDATES) {
|
|
235
|
+
fallbackExact();
|
|
236
|
+
}
|
|
237
|
+
else if (missingExactIds.length > 0) {
|
|
238
|
+
const placeholders = missingExactIds.map(() => '?').join(', ');
|
|
239
|
+
const missingRows = db
|
|
240
|
+
.prepare(`SELECT
|
|
241
|
+
d.id AS id,
|
|
242
|
+
s.key AS stable_key,
|
|
243
|
+
f.signature AS signature,
|
|
244
|
+
d.file AS file,
|
|
245
|
+
d.name AS name,
|
|
246
|
+
d.simple AS simple,
|
|
247
|
+
d.kind AS decl_kind,
|
|
248
|
+
d.exported AS exported,
|
|
249
|
+
d.start_line AS start_line,
|
|
250
|
+
d.end_line AS end_line,
|
|
251
|
+
0.0 AS bm25_score,
|
|
252
|
+
(SELECT COUNT(DISTINCT e.source) FROM edges e WHERE e.target = d.id AND e.kind NOT IN ('IMPORTS', 'TESTS')) AS callers
|
|
253
|
+
FROM declarations d
|
|
254
|
+
JOIN symbols s ON s.id = d.id
|
|
255
|
+
JOIN declarations_fts f ON f.rowid = d.id
|
|
256
|
+
WHERE d.id IN (${placeholders})`)
|
|
257
|
+
.all(...missingExactIds).map(mapCandidateRow);
|
|
258
|
+
const bm25ById = new Map();
|
|
259
|
+
if (missingExactIds.length > 0 && !tokenLimitHit && matchExpr !== null) {
|
|
260
|
+
// Unary `+` stops SQLite FTS5 from turning 1-element `IN (?)` into `rowid = ?` (`0:=M7`), which ignores the rowid filter.
|
|
261
|
+
const bm25Rows = db
|
|
262
|
+
.prepare(`SELECT f.rowid AS id, ${BM25_SQL} AS bm25_score
|
|
263
|
+
FROM declarations_fts f
|
|
264
|
+
WHERE declarations_fts MATCH ? AND +f.rowid IN (${placeholders})`)
|
|
265
|
+
.all(matchExpr, ...missingExactIds);
|
|
266
|
+
for (const bm of bm25Rows) {
|
|
267
|
+
bm25ById.set(Number(bm.id), Number(bm.bm25_score));
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
for (const row of missingRows) {
|
|
271
|
+
const bm25 = bm25ById.get(row.id);
|
|
272
|
+
if (bm25 !== undefined)
|
|
273
|
+
row.bm25Score = bm25;
|
|
274
|
+
if (!candidates.has(row.stableKey)) {
|
|
275
|
+
candidates.set(row.stableKey, row);
|
|
276
|
+
seenIds.add(row.id);
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
const scored = [...candidates.values()].map((row) => {
|
|
283
|
+
const exactCase = exactSet.has(row.name) || exactSet.has(row.simple);
|
|
284
|
+
const exactLower = !exactCase &&
|
|
285
|
+
(exactLowerSet.has(row.name.toLowerCase()) || exactLowerSet.has(row.simple.toLowerCase()));
|
|
286
|
+
const kind = exactCase || exactLower ? 'exact' : 'lexical';
|
|
287
|
+
const exactBoost = exactCase ? 1000 : exactLower ? 900 : 0;
|
|
288
|
+
const exportedBoost = row.exported === 1 ? 1.5 : 0;
|
|
289
|
+
const callerBoost = Math.log(1 + row.callers) * 0.5;
|
|
290
|
+
const score = row.bm25Score + exactBoost + exportedBoost + callerBoost;
|
|
291
|
+
return { row, kind, score };
|
|
292
|
+
});
|
|
293
|
+
scored.sort((a, b) => {
|
|
294
|
+
if (b.score !== a.score)
|
|
295
|
+
return b.score - a.score;
|
|
296
|
+
return a.row.stableKey < b.row.stableKey ? -1 : a.row.stableKey > b.row.stableKey ? 1 : 0;
|
|
297
|
+
});
|
|
298
|
+
const routeCache = new Map();
|
|
299
|
+
const isRoute = (file) => {
|
|
300
|
+
let cached = routeCache.get(file);
|
|
301
|
+
if (cached === undefined) {
|
|
302
|
+
cached = impact.routes.length > 0 && matchAny(impact.routes, file);
|
|
303
|
+
routeCache.set(file, cached);
|
|
304
|
+
}
|
|
305
|
+
return cached;
|
|
306
|
+
};
|
|
307
|
+
const hits = scored.slice(0, limit).map(({ row, kind, score }) => ({
|
|
308
|
+
kind,
|
|
309
|
+
symbol: row.stableKey,
|
|
310
|
+
declarationKind: row.declKind,
|
|
311
|
+
span: {
|
|
312
|
+
file: row.file,
|
|
313
|
+
startLine: row.startLine,
|
|
314
|
+
endLine: row.endLine,
|
|
315
|
+
},
|
|
316
|
+
signature: row.signature,
|
|
317
|
+
exported: row.exported === 1,
|
|
318
|
+
callers: row.callers,
|
|
319
|
+
route: isRoute(row.file),
|
|
320
|
+
score,
|
|
321
|
+
}));
|
|
322
|
+
return {
|
|
323
|
+
query,
|
|
324
|
+
limit,
|
|
325
|
+
totalMatches: Math.max(ftsTotal, candidates.size),
|
|
326
|
+
hits,
|
|
327
|
+
indexState,
|
|
328
|
+
...(extras?.updatedFiles !== undefined ? { updatedFiles: extras.updatedFiles } : {}),
|
|
329
|
+
scannedFiles,
|
|
330
|
+
...(extras?.staleReason !== undefined ? { staleReason: extras.staleReason } : {}),
|
|
331
|
+
engine,
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
export async function runSearch(session, options) {
|
|
335
|
+
if (options.signal?.aborted) {
|
|
336
|
+
return { kind: 'failure', code: 'index-failed', message: 'Cancelled' };
|
|
337
|
+
}
|
|
338
|
+
const workspace = session.getWorkspace();
|
|
339
|
+
if (workspace.config.search.enabled === false) {
|
|
340
|
+
return {
|
|
341
|
+
kind: 'failure',
|
|
342
|
+
code: 'index-failed',
|
|
343
|
+
message: 'search is disabled in ei.config.json (search.enabled = false)',
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
const valid = validateSearchInput(options.query, options.limit);
|
|
347
|
+
if (!valid.ok) {
|
|
348
|
+
return { kind: 'failure', code: 'INVALID_INPUT', message: valid.message };
|
|
349
|
+
}
|
|
350
|
+
const ctx = await session.prepareForSearch({
|
|
351
|
+
signal: options.signal,
|
|
352
|
+
onProgress: options.onProgress,
|
|
353
|
+
});
|
|
354
|
+
if (ctx.db === null) {
|
|
355
|
+
if (ctx.indexState === 'building') {
|
|
356
|
+
return {
|
|
357
|
+
kind: 'guidance',
|
|
358
|
+
code: 'index-building',
|
|
359
|
+
message: 'INDEX BUILDING — index build still running after 60 s. Call again; the answer will use the finished index.',
|
|
360
|
+
};
|
|
361
|
+
}
|
|
362
|
+
return {
|
|
363
|
+
kind: 'failure',
|
|
364
|
+
code: 'index-failed',
|
|
365
|
+
message: ctx.failureMessage ?? 'index unavailable',
|
|
366
|
+
retry: ctx.failureMessage !== 'Cancelled',
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
try {
|
|
370
|
+
const result = querySearch(ctx.db, workspace.config.impact, valid.query, valid.limit, {
|
|
371
|
+
indexState: ctx.indexState === 'updated' ? 'updated' : ctx.indexState === 'stale' ? 'stale' : 'fresh',
|
|
372
|
+
updatedFiles: ctx.updatedFiles,
|
|
373
|
+
...(ctx.staleReason !== null ? { staleReason: ctx.staleReason } : {}),
|
|
374
|
+
...(ctx.meta !== undefined ? { meta: ctx.meta } : {}),
|
|
375
|
+
...(ctx.scannedFiles !== undefined ? { scannedFiles: ctx.scannedFiles } : {}),
|
|
376
|
+
});
|
|
377
|
+
return { kind: 'result', value: result };
|
|
378
|
+
}
|
|
379
|
+
finally {
|
|
380
|
+
ctx.db.close();
|
|
381
|
+
}
|
|
382
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/** TOOLS.md §7 character budget for `ei_search`. */
|
|
2
|
+
export const SEARCH_BUDGET = 4_000;
|
|
3
|
+
function plural(count, singular, pluralForm) {
|
|
4
|
+
return `${count.toLocaleString('en-US')} ${count === 1 ? singular : pluralForm}`;
|
|
5
|
+
}
|
|
6
|
+
function shortName(symbol) {
|
|
7
|
+
const hash = symbol.indexOf('#');
|
|
8
|
+
return hash === -1 ? symbol : symbol.slice(hash + 1);
|
|
9
|
+
}
|
|
10
|
+
function sanitizeDisplay(text) {
|
|
11
|
+
return text.replace(/[\r\n\t]+/g, ' ');
|
|
12
|
+
}
|
|
13
|
+
function formatHitRow(hit) {
|
|
14
|
+
const kindCol = hit.kind.padEnd(8);
|
|
15
|
+
const loc = `${hit.span.file}:${hit.span.startLine}`;
|
|
16
|
+
const sigRaw = sanitizeDisplay(hit.signature).trim() || shortName(hit.symbol);
|
|
17
|
+
const sig = sigRaw.length > 80 ? `${sigRaw.slice(0, 79)}…` : sigRaw;
|
|
18
|
+
const facts = [];
|
|
19
|
+
if (hit.route)
|
|
20
|
+
facts.push('route');
|
|
21
|
+
if (hit.exported)
|
|
22
|
+
facts.push('exported');
|
|
23
|
+
if (hit.callers > 0)
|
|
24
|
+
facts.push(plural(hit.callers, 'caller', 'callers'));
|
|
25
|
+
const shownFacts = facts.slice(0, 2);
|
|
26
|
+
return ` ${kindCol} ${loc} ${sig}${shownFacts.length > 0 ? ` ${shownFacts.join(' · ')}` : ''}`;
|
|
27
|
+
}
|
|
28
|
+
function formatFooter(result) {
|
|
29
|
+
const state = result.indexState === 'stale'
|
|
30
|
+
? 'STALE INDEX'
|
|
31
|
+
: result.indexState === 'updated'
|
|
32
|
+
? (result.updatedFiles ?? 0) > 0
|
|
33
|
+
? `index updated (${plural(result.updatedFiles ?? 0, 'file', 'files')})`
|
|
34
|
+
: 'index updated'
|
|
35
|
+
: 'index fresh';
|
|
36
|
+
const tsVer = !result.engine.typescript || result.engine.typescript === 'unknown'
|
|
37
|
+
? 'n/a'
|
|
38
|
+
: result.engine.typescript;
|
|
39
|
+
const engVer = !result.engine.version || result.engine.version === 'unknown' ? 'n/a' : result.engine.version;
|
|
40
|
+
return `— ${state} · search: lexical only · ${plural(result.scannedFiles ?? 0, 'file', 'files')} · ts ${tsVer} · engine ${engVer}`;
|
|
41
|
+
}
|
|
42
|
+
export function renderSearch(result, budget = SEARCH_BUDGET) {
|
|
43
|
+
const queryText = sanitizeDisplay(result.query);
|
|
44
|
+
const footer = formatFooter(result);
|
|
45
|
+
if (result.hits.length === 0) {
|
|
46
|
+
const line1 = `SEARCH "${queryText}" — no matches. Try identifiers that would appear in the code.`;
|
|
47
|
+
const out = `${line1}\n${footer}`;
|
|
48
|
+
return out.length <= budget ? out : out.slice(0, budget);
|
|
49
|
+
}
|
|
50
|
+
const next = 'Next: call ei_impact with the symbol you intend to change.';
|
|
51
|
+
const makeHeader = (shown) => `SEARCH "${queryText}" — ${shown.toLocaleString('en-US')} of ${plural(result.totalMatches, 'match', 'matches')}`;
|
|
52
|
+
const hitRows = result.hits.map(formatHitRow);
|
|
53
|
+
const full = [makeHeader(result.hits.length), ...hitRows, next, footer].join('\n');
|
|
54
|
+
if (full.length <= budget)
|
|
55
|
+
return full;
|
|
56
|
+
const chosen = [];
|
|
57
|
+
for (const row of hitRows) {
|
|
58
|
+
const nextShown = chosen.length + 1;
|
|
59
|
+
const remaining = Math.max(0, result.totalMatches - nextShown);
|
|
60
|
+
const candidateLines = [
|
|
61
|
+
makeHeader(nextShown),
|
|
62
|
+
...chosen,
|
|
63
|
+
row,
|
|
64
|
+
...(remaining > 0 ? [` (+${plural(remaining, 'more match', 'more matches')})`] : []),
|
|
65
|
+
next,
|
|
66
|
+
footer,
|
|
67
|
+
];
|
|
68
|
+
if (candidateLines.join('\n').length > budget)
|
|
69
|
+
break;
|
|
70
|
+
chosen.push(row);
|
|
71
|
+
}
|
|
72
|
+
const remaining = Math.max(0, result.totalMatches - chosen.length);
|
|
73
|
+
const out = [
|
|
74
|
+
makeHeader(chosen.length),
|
|
75
|
+
...chosen,
|
|
76
|
+
...(remaining > 0 ? [` (+${plural(remaining, 'more match', 'more matches')})`] : []),
|
|
77
|
+
next,
|
|
78
|
+
footer,
|
|
79
|
+
].join('\n');
|
|
80
|
+
return out.length <= budget ? out : out.slice(0, budget);
|
|
81
|
+
}
|
|
82
|
+
export function renderSearchOutcome(outcome, budget = SEARCH_BUDGET) {
|
|
83
|
+
if (outcome.kind === 'failure') {
|
|
84
|
+
if (outcome.message === 'Cancelled')
|
|
85
|
+
return 'Cancelled';
|
|
86
|
+
if (outcome.code === 'INVALID_INPUT') {
|
|
87
|
+
return `INVALID_INPUT: ${outcome.message}`.slice(0, budget);
|
|
88
|
+
}
|
|
89
|
+
const prefix = outcome.message.startsWith('index-failed:')
|
|
90
|
+
? outcome.message
|
|
91
|
+
: `index-failed: ${outcome.message}`;
|
|
92
|
+
return `${prefix}. Retry once; if it fails again, continue without ei_search and say so in your report.`.slice(0, budget);
|
|
93
|
+
}
|
|
94
|
+
if (outcome.kind === 'guidance') {
|
|
95
|
+
return 'INDEX BUILDING — index build still running after 60 s. Call again; the answer will use the finished index.'.slice(0, budget);
|
|
96
|
+
}
|
|
97
|
+
return renderSearch(outcome.value, budget);
|
|
98
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
/** Maximum length in UTF-16 code units for cached signature and doc fields (RISK §6, D60). */
|
|
2
|
+
export const MAX_SEARCH_FIELD_CHARS = 400;
|
|
3
|
+
/**
|
|
4
|
+
* Splits an identifier or repo-relative path into lowercase search tokens:
|
|
5
|
+
* camelCase, PascalCase, acronyms (`XMLHttpRequest`), letter-digit boundaries (`parseURL2`),
|
|
6
|
+
* snake/kebab/dot/slash/dollar/underscore separators, and Unicode letters.
|
|
7
|
+
*/
|
|
8
|
+
export function splitIdentifier(input) {
|
|
9
|
+
return input
|
|
10
|
+
.replace(/[^\p{L}\p{N}]+/gu, ' ')
|
|
11
|
+
.replace(/([\p{Ll}\p{Lo}])(\p{Lu})/gu, '$1 $2')
|
|
12
|
+
.replace(/(\p{Lu}+)(\p{Lu}\p{Ll})/gu, '$1 $2')
|
|
13
|
+
.replace(/(\p{L})(\p{N})/gu, '$1 $2')
|
|
14
|
+
.replace(/(\p{N})(\p{L})/gu, '$1 $2')
|
|
15
|
+
.replace(/\s+/g, ' ')
|
|
16
|
+
.trim()
|
|
17
|
+
.toLowerCase();
|
|
18
|
+
}
|
|
19
|
+
/** Tokenizes a raw user query using the same rules as indexed identifiers. */
|
|
20
|
+
export function tokenizeForQuery(query) {
|
|
21
|
+
const split = splitIdentifier(query);
|
|
22
|
+
return split === '' ? [] : split.split(' ');
|
|
23
|
+
}
|
|
24
|
+
export function pathTokens(repoRelativePosixPath) {
|
|
25
|
+
return splitIdentifier(repoRelativePosixPath);
|
|
26
|
+
}
|
|
27
|
+
function combineTokens(raw) {
|
|
28
|
+
const trimmed = raw.trim();
|
|
29
|
+
if (trimmed === '')
|
|
30
|
+
return '';
|
|
31
|
+
const split = splitIdentifier(trimmed);
|
|
32
|
+
if (split === '')
|
|
33
|
+
return trimmed;
|
|
34
|
+
if (trimmed.toLowerCase() === split)
|
|
35
|
+
return split;
|
|
36
|
+
return `${trimmed} ${split}`;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Keeps owner tokens separate from simple-name tokens so querying an owner name ranks the
|
|
40
|
+
* owner declaration itself (`name_tokens`) above its members (`owner_tokens`).
|
|
41
|
+
*/
|
|
42
|
+
export function ownerAndNameTokens(name, simple) {
|
|
43
|
+
const dot = name.lastIndexOf('.');
|
|
44
|
+
const rawOwner = dot > 0 ? name.slice(0, dot) : '';
|
|
45
|
+
return {
|
|
46
|
+
nameTokens: combineTokens(simple),
|
|
47
|
+
ownerTokens: rawOwner === '' ? '' : combineTokens(rawOwner),
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
/** Caps text at `max` UTF-16 code units without splitting a surrogate pair. */
|
|
51
|
+
export function capSearchText(text, max = MAX_SEARCH_FIELD_CHARS) {
|
|
52
|
+
if (max <= 0 || text.length === 0)
|
|
53
|
+
return '';
|
|
54
|
+
if (text.length <= max)
|
|
55
|
+
return text;
|
|
56
|
+
const last = text.charCodeAt(max - 1);
|
|
57
|
+
const end = last >= 0xd800 && last <= 0xdbff ? max - 1 : max;
|
|
58
|
+
return text.slice(0, end).trimEnd();
|
|
59
|
+
}
|
|
60
|
+
/** Formats bodyless signature headers for a declaration's AST nodes, capped at 400 chars. */
|
|
61
|
+
export function extractSearchSignature(nodes, signatureOf) {
|
|
62
|
+
const parts = nodes
|
|
63
|
+
.map((node) => signatureOf(node)
|
|
64
|
+
.replace(/\s+/g, ' ')
|
|
65
|
+
.replace(/\s*\{\s*$/, '')
|
|
66
|
+
.trim())
|
|
67
|
+
.filter((part) => part.length > 0);
|
|
68
|
+
return capSearchText(parts.join(' ; '));
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Extracts the first paragraph of the declaration's JSDoc comment (`/** ... *\/`), ignoring
|
|
72
|
+
* subsequent paragraphs, JSDoc tags, and regular `//` or `/* ... *\/` comments.
|
|
73
|
+
*/
|
|
74
|
+
export function extractFirstDocParagraph(ts, nodes) {
|
|
75
|
+
for (const node of nodes) {
|
|
76
|
+
const docs = ts.getJSDocCommentsAndTags(node).filter(ts.isJSDoc);
|
|
77
|
+
const doc = docs.at(-1);
|
|
78
|
+
if (doc === undefined)
|
|
79
|
+
continue;
|
|
80
|
+
const raw = ts.getTextOfJSDocComment(doc.comment) ?? '';
|
|
81
|
+
const normalized = raw.replace(/\r\n/g, '\n').trim();
|
|
82
|
+
if (normalized === '')
|
|
83
|
+
continue;
|
|
84
|
+
const paragraphs = normalized
|
|
85
|
+
.split(/\n\s*\n/)
|
|
86
|
+
.map((p) => p.replace(/\s+/g, ' ').trim())
|
|
87
|
+
.filter((p) => p.length > 0);
|
|
88
|
+
const first = paragraphs[0] ?? '';
|
|
89
|
+
if (first !== '')
|
|
90
|
+
return capSearchText(first);
|
|
91
|
+
}
|
|
92
|
+
return '';
|
|
93
|
+
}
|
|
94
|
+
/**
|
|
95
|
+
* Builds FTS5 search rows for an `ok`-extracted indexable file, skipping the synthetic
|
|
96
|
+
* `<module>` declaration. Callers must never invoke this on `parse-error`, `not-in-program`,
|
|
97
|
+
* `lexical`, or excluded/secret files.
|
|
98
|
+
*/
|
|
99
|
+
export function extractSearchRows(ts, file, declarations, nodesOf, signatureOf) {
|
|
100
|
+
const fileTokens = pathTokens(file);
|
|
101
|
+
const rows = [];
|
|
102
|
+
for (const decl of declarations) {
|
|
103
|
+
if (decl.kind === 'module')
|
|
104
|
+
continue;
|
|
105
|
+
const nodes = nodesOf.get(decl.key) ?? [];
|
|
106
|
+
const { nameTokens, ownerTokens } = ownerAndNameTokens(decl.name, decl.simple);
|
|
107
|
+
rows.push({
|
|
108
|
+
key: decl.key,
|
|
109
|
+
nameTokens,
|
|
110
|
+
ownerTokens,
|
|
111
|
+
kind: decl.kind,
|
|
112
|
+
signature: extractSearchSignature(nodes, signatureOf),
|
|
113
|
+
doc: extractFirstDocParagraph(ts, nodes),
|
|
114
|
+
pathTokens: fileTokens,
|
|
115
|
+
});
|
|
116
|
+
}
|
|
117
|
+
return rows;
|
|
118
|
+
}
|