@krisada-m/ksd-intelligence 0.0.0-stage → 1.0.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/README.md +167 -2
- package/dist/adapters/agy/skills.js +252 -0
- package/dist/adapters/cli/check-changed.js +3 -0
- package/dist/adapters/cli/main.js +1002 -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 +893 -0
- package/dist/adapters/omp/skills.js +130 -0
- package/dist/adapters/ui/hud.js +318 -0
- package/dist/adapters/ui/tree.js +460 -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 +381 -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 +792 -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/index.js +20 -0
- package/dist/policy/change-scope.js +500 -0
- package/dist/policy/check-changed.js +40 -0
- package/dist/policy/config.js +106 -0
- package/dist/policy/dist/policy.d.ts +17 -0
- package/dist/policy/dist/policy.js +147 -0
- package/dist/policy/dist/runtime.d.ts +40 -0
- package/dist/policy/dist/runtime.js +75 -0
- package/dist/policy/dist/sdlc.d.ts +7 -0
- package/dist/policy/dist/sdlc.js +27 -0
- package/dist/policy/eslint-rules/index.js +107 -0
- package/dist/policy/index.d.ts +2 -0
- package/dist/policy/index.js +241 -0
- package/dist/policy/package.json +33 -0
- package/dist/policy/policy.d.ts +2 -0
- package/dist/policy/policy.js +2 -0
- package/dist/policy/review-verdict.js +262 -0
- package/dist/policy/sdlc.js +2 -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/package.json +74 -4
- package/scripts/agy-mcp.mjs +27 -0
- package/scripts/mcp/stdio.mjs +304 -0
- package/scripts/mcp/tools.mjs +451 -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,389 @@
|
|
|
1
|
+
// Engine child process entry (D45). Reads requests from stdin, answers on stdout, one JSON per line.
|
|
2
|
+
import { setTimeout as delay } from 'node:timers/promises';
|
|
3
|
+
import { pathToFileURL } from 'node:url';
|
|
4
|
+
import { isRecord } from '../kernel/guards.js';
|
|
5
|
+
import { MODULE_NAME, fileDeclarations, } from '../indexing/declarations.js';
|
|
6
|
+
import { doctorDeep } from '../indexing/doctor.js';
|
|
7
|
+
import { Indexer } from '../indexing/indexer.js';
|
|
8
|
+
import { declarationSurfaces } from '../indexing/surface.js';
|
|
9
|
+
import { beginBuild, writeFiles } from '../../storage/sqlite.js';
|
|
10
|
+
import { encode, lineReader, parseMessage } from './protocol.js';
|
|
11
|
+
import { loadWorkspace } from './workspace.js';
|
|
12
|
+
class OpError extends Error {
|
|
13
|
+
code;
|
|
14
|
+
constructor(code, message) {
|
|
15
|
+
super(message);
|
|
16
|
+
this.code = code;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
// stdout is the protocol channel; anything a dependency logs goes to stderr instead.
|
|
20
|
+
console.log = console.error;
|
|
21
|
+
function send(message) {
|
|
22
|
+
process.stdout.write(encode(message));
|
|
23
|
+
}
|
|
24
|
+
function stringArg(args, key) {
|
|
25
|
+
const value = args[key];
|
|
26
|
+
if (typeof value !== 'string' || value === '') {
|
|
27
|
+
throw new OpError('INVALID_INPUT', `${key} must be a non-empty string`);
|
|
28
|
+
}
|
|
29
|
+
return value;
|
|
30
|
+
}
|
|
31
|
+
// D44: TypeScript is always loaded by absolute path; a bare specifier does not resolve here.
|
|
32
|
+
async function importByPath(path) {
|
|
33
|
+
const loaded = await import(pathToFileURL(path).href);
|
|
34
|
+
return isRecord(loaded) && isRecord(loaded.default) ? loaded.default : loaded;
|
|
35
|
+
}
|
|
36
|
+
function isCompiler(value) {
|
|
37
|
+
return (isRecord(value) &&
|
|
38
|
+
typeof value.version === 'string' &&
|
|
39
|
+
typeof value.createProgram === 'function' &&
|
|
40
|
+
typeof value.createSemanticDiagnosticsBuilderProgram === 'function');
|
|
41
|
+
}
|
|
42
|
+
const compilers = new Map();
|
|
43
|
+
async function compilerAt(path) {
|
|
44
|
+
let ts = compilers.get(path);
|
|
45
|
+
if (ts === undefined) {
|
|
46
|
+
const loaded = await importByPath(path);
|
|
47
|
+
if (!isCompiler(loaded)) {
|
|
48
|
+
throw new OpError('typescript-invalid', `${path} is not a TypeScript compiler`);
|
|
49
|
+
}
|
|
50
|
+
ts = loaded;
|
|
51
|
+
compilers.set(path, ts);
|
|
52
|
+
}
|
|
53
|
+
return ts;
|
|
54
|
+
}
|
|
55
|
+
function indexerFor(args, ts) {
|
|
56
|
+
const budget = Number(process.env.EI_MEMORY_LIMIT_MB);
|
|
57
|
+
return new Indexer(ts, stringArg(args, 'root'), stringArg(args, 'cacheDir'), {
|
|
58
|
+
memoryBudgetMb: Number.isFinite(budget) && budget > 0 ? budget : undefined,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
function parseSyntaxOnly(ts, file, text) {
|
|
62
|
+
const sf = ts.createSourceFile(file, text, ts.ScriptTarget.Latest, true);
|
|
63
|
+
let parseError = null;
|
|
64
|
+
const host = {
|
|
65
|
+
getSourceFile: (name) => (name === file ? sf : undefined),
|
|
66
|
+
getDefaultLibFileName: () => 'lib.d.ts',
|
|
67
|
+
writeFile: () => { },
|
|
68
|
+
getCurrentDirectory: () => '',
|
|
69
|
+
getCanonicalFileName: (name) => name,
|
|
70
|
+
useCaseSensitiveFileNames: () => true,
|
|
71
|
+
getNewLine: () => '\n',
|
|
72
|
+
fileExists: (name) => name === file,
|
|
73
|
+
readFile: (name) => (name === file ? text : undefined),
|
|
74
|
+
};
|
|
75
|
+
const program = ts.createProgram([file], { noLib: true, noResolve: true, types: [], allowJs: true, checkJs: false }, host);
|
|
76
|
+
const diag = program.getSyntacticDiagnostics(sf)[0];
|
|
77
|
+
if (diag !== undefined) {
|
|
78
|
+
const pos = diag.start ?? 0;
|
|
79
|
+
const line = sf.getLineAndCharacterOfPosition(pos).line + 1;
|
|
80
|
+
parseError = {
|
|
81
|
+
line,
|
|
82
|
+
detail: ts.flattenDiagnosticMessageText(diag.messageText, ' '),
|
|
83
|
+
};
|
|
84
|
+
}
|
|
85
|
+
const extracted = fileDeclarations(ts, sf, file);
|
|
86
|
+
const surfaces = declarationSurfaces(ts, sf, extracted);
|
|
87
|
+
const declMap = new Map();
|
|
88
|
+
for (const decl of extracted.declarations)
|
|
89
|
+
declMap.set(decl.key, decl);
|
|
90
|
+
return { declarations: declMap, surfaces, parseError };
|
|
91
|
+
}
|
|
92
|
+
function spanOfDecl(decl) {
|
|
93
|
+
return { file: decl.file, startLine: decl.startLine, endLine: decl.endLine };
|
|
94
|
+
}
|
|
95
|
+
// Builds leave a child holding the programs' memory; the host retires it after each (D50).
|
|
96
|
+
const BUILD_OPS = new Set(['index', 'doctor']);
|
|
97
|
+
// A Map, not an object literal: an op name such as `constructor` must not reach a prototype member.
|
|
98
|
+
const ops = new Map([
|
|
99
|
+
[
|
|
100
|
+
'ping',
|
|
101
|
+
() => ({
|
|
102
|
+
pid: process.pid,
|
|
103
|
+
runtime: process.versions.bun === undefined ? 'node' : 'bun',
|
|
104
|
+
version: process.versions.bun ?? process.versions.node,
|
|
105
|
+
rssMb: Math.round(process.memoryUsage().rss / 2 ** 20),
|
|
106
|
+
}),
|
|
107
|
+
],
|
|
108
|
+
[
|
|
109
|
+
'typescript',
|
|
110
|
+
async (args) => {
|
|
111
|
+
const ts = await importByPath(stringArg(args, 'path'));
|
|
112
|
+
if (!isRecord(ts) || typeof ts.version !== 'string') {
|
|
113
|
+
throw new OpError('typescript-invalid', 'module at path has no string `version` export');
|
|
114
|
+
}
|
|
115
|
+
return { version: ts.version };
|
|
116
|
+
},
|
|
117
|
+
],
|
|
118
|
+
[
|
|
119
|
+
'index',
|
|
120
|
+
async (args, progress, hud) => {
|
|
121
|
+
const indexer = indexerFor(args, await compilerAt(stringArg(args, 'typescriptPath')));
|
|
122
|
+
const workspace = await loadWorkspace(indexer.root);
|
|
123
|
+
return indexer.index({
|
|
124
|
+
impact: workspace.config.impact,
|
|
125
|
+
full: args.full === true,
|
|
126
|
+
freshness: args.freshness === 'stat' ? 'stat' : 'hash',
|
|
127
|
+
onProgress: progress,
|
|
128
|
+
onHudProgress: args.hudProgress === true ? hud : undefined,
|
|
129
|
+
});
|
|
130
|
+
},
|
|
131
|
+
],
|
|
132
|
+
[
|
|
133
|
+
'doctor',
|
|
134
|
+
async (args, progress, hud) => {
|
|
135
|
+
const ts = await compilerAt(stringArg(args, 'typescriptPath'));
|
|
136
|
+
const indexer = indexerFor(args, ts);
|
|
137
|
+
const workspace = await loadWorkspace(indexer.root);
|
|
138
|
+
const size = typeof args.differential === 'number' ? args.differential : 0;
|
|
139
|
+
return doctorDeep(ts, indexer, workspace.config.impact, {
|
|
140
|
+
differential: size,
|
|
141
|
+
onProgress: progress,
|
|
142
|
+
onHudProgress: args.hudProgress === true ? hud : undefined,
|
|
143
|
+
});
|
|
144
|
+
},
|
|
145
|
+
],
|
|
146
|
+
[
|
|
147
|
+
'changes-diff',
|
|
148
|
+
async (args) => {
|
|
149
|
+
const ts = await compilerAt(stringArg(args, 'typescriptPath'));
|
|
150
|
+
const rawFiles = Array.isArray(args.files) ? args.files : [];
|
|
151
|
+
const symbols = [];
|
|
152
|
+
const parseErrors = [];
|
|
153
|
+
for (const entry of rawFiles) {
|
|
154
|
+
if (!isRecord(entry) ||
|
|
155
|
+
typeof entry.path !== 'string' ||
|
|
156
|
+
typeof entry.status !== 'string') {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const path = entry.path;
|
|
160
|
+
const status = entry.status;
|
|
161
|
+
const oldPath = typeof entry.oldPath === 'string' ? entry.oldPath : undefined;
|
|
162
|
+
const baseText = typeof entry.baseText === 'string' ? entry.baseText : undefined;
|
|
163
|
+
const workText = typeof entry.workText === 'string' ? entry.workText : undefined;
|
|
164
|
+
if (status === 'A') {
|
|
165
|
+
if (workText === undefined)
|
|
166
|
+
continue;
|
|
167
|
+
const work = parseSyntaxOnly(ts, path, workText);
|
|
168
|
+
if (work.parseError !== null) {
|
|
169
|
+
parseErrors.push({ file: path, ...work.parseError });
|
|
170
|
+
}
|
|
171
|
+
let addedCount = 0;
|
|
172
|
+
for (const [key, decl] of work.declarations) {
|
|
173
|
+
if (decl.name === MODULE_NAME)
|
|
174
|
+
continue;
|
|
175
|
+
symbols.push({ symbol: key, change: 'added', span: spanOfDecl(decl) });
|
|
176
|
+
addedCount++;
|
|
177
|
+
}
|
|
178
|
+
if (addedCount === 0) {
|
|
179
|
+
const mod = work.declarations.get(`${path}#${MODULE_NAME}`);
|
|
180
|
+
symbols.push({
|
|
181
|
+
symbol: `${path}#${MODULE_NAME}`,
|
|
182
|
+
change: 'added',
|
|
183
|
+
...(mod === undefined ? {} : { span: spanOfDecl(mod) }),
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
else if (status === 'D') {
|
|
188
|
+
if (baseText === undefined)
|
|
189
|
+
continue;
|
|
190
|
+
const base = parseSyntaxOnly(ts, path, baseText);
|
|
191
|
+
let removedCount = 0;
|
|
192
|
+
for (const [key, decl] of base.declarations) {
|
|
193
|
+
if (decl.name === MODULE_NAME)
|
|
194
|
+
continue;
|
|
195
|
+
symbols.push({ symbol: key, change: 'removed', span: spanOfDecl(decl) });
|
|
196
|
+
removedCount++;
|
|
197
|
+
}
|
|
198
|
+
if (removedCount === 0) {
|
|
199
|
+
const mod = base.declarations.get(`${path}#${MODULE_NAME}`);
|
|
200
|
+
symbols.push({
|
|
201
|
+
symbol: `${path}#${MODULE_NAME}`,
|
|
202
|
+
change: 'removed',
|
|
203
|
+
...(mod === undefined ? {} : { span: spanOfDecl(mod) }),
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
}
|
|
207
|
+
else if (status === 'R') {
|
|
208
|
+
if (baseText !== undefined) {
|
|
209
|
+
const baseFile = oldPath ?? path;
|
|
210
|
+
const base = parseSyntaxOnly(ts, baseFile, baseText);
|
|
211
|
+
let removedCount = 0;
|
|
212
|
+
for (const [key, decl] of base.declarations) {
|
|
213
|
+
if (decl.name === MODULE_NAME)
|
|
214
|
+
continue;
|
|
215
|
+
symbols.push({ symbol: key, change: 'removed', span: spanOfDecl(decl) });
|
|
216
|
+
removedCount++;
|
|
217
|
+
}
|
|
218
|
+
if (removedCount === 0) {
|
|
219
|
+
const mod = base.declarations.get(`${baseFile}#${MODULE_NAME}`);
|
|
220
|
+
symbols.push({
|
|
221
|
+
symbol: `${baseFile}#${MODULE_NAME}`,
|
|
222
|
+
change: 'removed',
|
|
223
|
+
...(mod === undefined ? {} : { span: spanOfDecl(mod) }),
|
|
224
|
+
});
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
if (workText !== undefined) {
|
|
228
|
+
const work = parseSyntaxOnly(ts, path, workText);
|
|
229
|
+
if (work.parseError !== null) {
|
|
230
|
+
parseErrors.push({ file: path, ...work.parseError });
|
|
231
|
+
}
|
|
232
|
+
let addedCount = 0;
|
|
233
|
+
for (const [key, decl] of work.declarations) {
|
|
234
|
+
if (decl.name === MODULE_NAME)
|
|
235
|
+
continue;
|
|
236
|
+
symbols.push({ symbol: key, change: 'added', span: spanOfDecl(decl) });
|
|
237
|
+
addedCount++;
|
|
238
|
+
}
|
|
239
|
+
if (addedCount === 0) {
|
|
240
|
+
const mod = work.declarations.get(`${path}#${MODULE_NAME}`);
|
|
241
|
+
symbols.push({
|
|
242
|
+
symbol: `${path}#${MODULE_NAME}`,
|
|
243
|
+
change: 'added',
|
|
244
|
+
...(mod === undefined ? {} : { span: spanOfDecl(mod) }),
|
|
245
|
+
});
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
else if (status === 'M') {
|
|
250
|
+
if (baseText === undefined || workText === undefined)
|
|
251
|
+
continue;
|
|
252
|
+
const base = parseSyntaxOnly(ts, path, baseText);
|
|
253
|
+
const work = parseSyntaxOnly(ts, path, workText);
|
|
254
|
+
if (work.parseError !== null) {
|
|
255
|
+
parseErrors.push({ file: path, ...work.parseError });
|
|
256
|
+
}
|
|
257
|
+
// Whitespace/comment-only edit on TS (or non-JSDoc JS) leaves fileTokenHash identical.
|
|
258
|
+
if (base.surfaces.fileTokenHash === work.surfaces.fileTokenHash) {
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const baseSurfaces = base.surfaces.declarations;
|
|
262
|
+
const workSurfaces = work.surfaces.declarations;
|
|
263
|
+
for (const [key, bSurf] of baseSurfaces) {
|
|
264
|
+
const wSurf = workSurfaces.get(key);
|
|
265
|
+
if (wSurf === undefined) {
|
|
266
|
+
const bDecl = base.declarations.get(key);
|
|
267
|
+
symbols.push({
|
|
268
|
+
symbol: key,
|
|
269
|
+
change: 'removed',
|
|
270
|
+
...(bDecl === undefined ? {} : { span: spanOfDecl(bDecl) }),
|
|
271
|
+
});
|
|
272
|
+
}
|
|
273
|
+
else if (bSurf.surfaceHash !== wSurf.surfaceHash) {
|
|
274
|
+
const wDecl = work.declarations.get(key);
|
|
275
|
+
symbols.push({
|
|
276
|
+
symbol: key,
|
|
277
|
+
change: 'signature-changed',
|
|
278
|
+
...(wDecl === undefined ? {} : { span: spanOfDecl(wDecl) }),
|
|
279
|
+
});
|
|
280
|
+
}
|
|
281
|
+
else if (bSurf.bodyHash !== wSurf.bodyHash) {
|
|
282
|
+
const wDecl = work.declarations.get(key);
|
|
283
|
+
symbols.push({
|
|
284
|
+
symbol: key,
|
|
285
|
+
change: 'modified',
|
|
286
|
+
...(wDecl === undefined ? {} : { span: spanOfDecl(wDecl) }),
|
|
287
|
+
});
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
for (const [key] of workSurfaces) {
|
|
291
|
+
if (!baseSurfaces.has(key)) {
|
|
292
|
+
const wDecl = work.declarations.get(key);
|
|
293
|
+
symbols.push({
|
|
294
|
+
symbol: key,
|
|
295
|
+
change: 'added',
|
|
296
|
+
...(wDecl === undefined ? {} : { span: spanOfDecl(wDecl) }),
|
|
297
|
+
});
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
if (base.surfaces.moduleHash !== work.surfaces.moduleHash) {
|
|
301
|
+
const mod = work.declarations.get(`${path}#${MODULE_NAME}`);
|
|
302
|
+
symbols.push({
|
|
303
|
+
symbol: `${path}#${MODULE_NAME}`,
|
|
304
|
+
change: 'modified',
|
|
305
|
+
...(mod === undefined ? {} : { span: spanOfDecl(mod) }),
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
return { symbols, parseErrors };
|
|
311
|
+
},
|
|
312
|
+
],
|
|
313
|
+
]);
|
|
314
|
+
// Test-only ops: memory pressure and a build interrupted mid-write. Read once at start-up from
|
|
315
|
+
// this process's own environment, which only the parent's spawn call sets; requests cannot.
|
|
316
|
+
if (process.env.EI_ENGINE_TEST_OPS === '1') {
|
|
317
|
+
ops.set('allocate', async (_args, progress) => {
|
|
318
|
+
const held = [];
|
|
319
|
+
for (let mb = 1; mb <= 1024; mb++) {
|
|
320
|
+
held.push(new Array(131_072).fill(mb)); // ~1 MB of heap, every page touched
|
|
321
|
+
if (mb % 32 === 0) {
|
|
322
|
+
progress('allocated', { mb });
|
|
323
|
+
await delay(5);
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
return { allocatedMb: held.length };
|
|
327
|
+
});
|
|
328
|
+
ops.set('stage-and-hang', (args, progress) => {
|
|
329
|
+
const db = beginBuild(stringArg(args, 'cacheDir'));
|
|
330
|
+
const records = Array.isArray(args.paths)
|
|
331
|
+
? args.paths.map((path) => ({
|
|
332
|
+
path: String(path),
|
|
333
|
+
size: 0,
|
|
334
|
+
mtimeMs: 0,
|
|
335
|
+
hash: null,
|
|
336
|
+
kind: 'ts',
|
|
337
|
+
package: null,
|
|
338
|
+
tsconfig: null,
|
|
339
|
+
status: 'indexable',
|
|
340
|
+
reason: null,
|
|
341
|
+
}))
|
|
342
|
+
: [];
|
|
343
|
+
writeFiles(db, records);
|
|
344
|
+
progress('staged', { rows: records.length });
|
|
345
|
+
return new Promise(() => undefined); // never publishes; the test kills this process
|
|
346
|
+
});
|
|
347
|
+
}
|
|
348
|
+
async function handle(id, op, args) {
|
|
349
|
+
const run = ops.get(op);
|
|
350
|
+
if (!run) {
|
|
351
|
+
send({ type: 'error', id, code: 'INVALID_INPUT', message: `unknown engine op: ${op}` });
|
|
352
|
+
return;
|
|
353
|
+
}
|
|
354
|
+
const retire = BUILD_OPS.has(op);
|
|
355
|
+
try {
|
|
356
|
+
const input = isRecord(args) ? args : {};
|
|
357
|
+
const value = await run(input, (message, data) => send({ type: 'progress', id, message, data }), (event) => {
|
|
358
|
+
if (input.hudProgress !== true)
|
|
359
|
+
return;
|
|
360
|
+
try {
|
|
361
|
+
send({ type: 'progress', id, message: '__hud_progress__', data: { hudProgress: event } });
|
|
362
|
+
}
|
|
363
|
+
catch {
|
|
364
|
+
// Optional telemetry cannot affect the engine operation.
|
|
365
|
+
}
|
|
366
|
+
});
|
|
367
|
+
send({ type: 'result', id, value, retire });
|
|
368
|
+
}
|
|
369
|
+
catch (error) {
|
|
370
|
+
const code = error instanceof OpError ? error.code : 'index-failed';
|
|
371
|
+
send({
|
|
372
|
+
type: 'error',
|
|
373
|
+
id,
|
|
374
|
+
code,
|
|
375
|
+
message: error instanceof Error ? error.message : String(error),
|
|
376
|
+
retire,
|
|
377
|
+
});
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
process.stdin.on('data', lineReader((line) => {
|
|
381
|
+
const message = parseMessage(line);
|
|
382
|
+
if (typeof message === 'string' || message.type !== 'request') {
|
|
383
|
+
console.error(`engine: ignored line (${typeof message === 'string' ? message : message.type})`);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
void handle(message.id, message.op, message.args);
|
|
387
|
+
}));
|
|
388
|
+
// The parent closes stdin to retire the child, and the pipe closes if the parent dies.
|
|
389
|
+
process.stdin.on('end', () => process.exit(0));
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
import { execFile, spawn } from 'node:child_process';
|
|
2
|
+
import { fileURLToPath } from 'node:url';
|
|
3
|
+
import { promisify } from 'node:util';
|
|
4
|
+
import { encode, lineReader, parseMessage } from './protocol.js';
|
|
5
|
+
import { runtimeArgs } from './runtime.js';
|
|
6
|
+
const run = promisify(execFile);
|
|
7
|
+
const IDLE_MS = 10 * 60_000;
|
|
8
|
+
/** D35: the longest a tool call waits (first build); every request has at least this limit. */
|
|
9
|
+
const REQUEST_MS = 60_000;
|
|
10
|
+
const IDLE_KILL_GRACE_MS = 5_000;
|
|
11
|
+
const STDERR_TAIL = 4_096;
|
|
12
|
+
const NODE_OOM = /heap out of memory|Reached heap limit|Allocation failed - JavaScript heap/i;
|
|
13
|
+
async function rssMb(pid) {
|
|
14
|
+
try {
|
|
15
|
+
const { stdout } = await run('ps', ['-o', 'rss=', '-p', String(pid)]);
|
|
16
|
+
const kb = Number.parseInt(stdout.trim(), 10);
|
|
17
|
+
return Number.isNaN(kb) ? null : kb / 1024;
|
|
18
|
+
}
|
|
19
|
+
catch {
|
|
20
|
+
return null; // process already gone
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Parent side of the engine (D45): one child process, spawned on the first request and again
|
|
25
|
+
* on the first request after it exits, killed above its memory limit, retired after every build
|
|
26
|
+
* or update and, after query ops, when idle.
|
|
27
|
+
*/
|
|
28
|
+
export function createEngineHost(options) {
|
|
29
|
+
const { runtime, memoryLimitMb } = options;
|
|
30
|
+
const idleMs = options.idleMs ?? IDLE_MS;
|
|
31
|
+
const requestMs = options.requestMs ?? REQUEST_MS;
|
|
32
|
+
const watchdog = options.watchdog ?? runtime.kind === 'bun';
|
|
33
|
+
// Test-only child ops need an env the caller passes explicitly; the session's own variables
|
|
34
|
+
// never enable them.
|
|
35
|
+
const inherited = { ...process.env };
|
|
36
|
+
delete inherited.EI_ENGINE_TEST_OPS;
|
|
37
|
+
const base = options.env ?? inherited;
|
|
38
|
+
// Under OMP the runtime is the omp executable, which only acts as plain Bun when asked to.
|
|
39
|
+
// The child sizes its background work to the limit it is killed at.
|
|
40
|
+
const limited = { ...base, EI_MEMORY_LIMIT_MB: String(memoryLimitMb) };
|
|
41
|
+
const env = runtime.kind === 'bun' ? { ...limited, BUN_BE_BUN: '1' } : limited;
|
|
42
|
+
const childScript = fileURLToPath(new URL('./child.js', import.meta.url));
|
|
43
|
+
let current = null;
|
|
44
|
+
let idleTimer;
|
|
45
|
+
let sequence = 0;
|
|
46
|
+
let starts = 0;
|
|
47
|
+
let lastExit = null;
|
|
48
|
+
let retiring = null;
|
|
49
|
+
function kill(child, reason) {
|
|
50
|
+
child.killedFor ??= reason;
|
|
51
|
+
child.proc.kill('SIGKILL');
|
|
52
|
+
}
|
|
53
|
+
function onExit(child, code, signal) {
|
|
54
|
+
clearInterval(child.sampler);
|
|
55
|
+
if (current === child)
|
|
56
|
+
current = null;
|
|
57
|
+
if (retiring === child)
|
|
58
|
+
retiring = null;
|
|
59
|
+
const oom = signal === 'SIGABRT' || code === 134 || NODE_OOM.test(child.stderr);
|
|
60
|
+
const reason = child.killedFor ?? (oom ? 'memory-limit' : 'crashed');
|
|
61
|
+
lastExit = { code, signal, reason };
|
|
62
|
+
const tail = child.stderr.trim().slice(-300);
|
|
63
|
+
const message = reason === 'memory-limit'
|
|
64
|
+
? `engine exceeded its memory limit of ${memoryLimitMb} MB (${runtime.kind})`
|
|
65
|
+
: reason === 'timeout' && child.timedOut !== null
|
|
66
|
+
? `engine did not answer '${child.timedOut.op}' within ${child.timedOut.ms} ms and was killed`
|
|
67
|
+
: `engine child exited (${signal ?? `code ${code}`}, ${reason})${tail ? `: ${tail}` : ''}`;
|
|
68
|
+
for (const pending of child.pending.values()) {
|
|
69
|
+
clearTimeout(pending.timer);
|
|
70
|
+
pending.resolve({ ok: false, code: 'index-failed', message, reason });
|
|
71
|
+
}
|
|
72
|
+
child.pending.clear();
|
|
73
|
+
}
|
|
74
|
+
function onMessage(child, message) {
|
|
75
|
+
const pending = child.pending.get(message.id);
|
|
76
|
+
if (!pending || message.type === 'request')
|
|
77
|
+
return;
|
|
78
|
+
if (message.type === 'progress') {
|
|
79
|
+
const data = typeof message.data === 'object' && message.data !== null
|
|
80
|
+
? { ...message.data, pid: child.proc.pid }
|
|
81
|
+
: { value: message.data, pid: child.proc.pid };
|
|
82
|
+
pending.onProgress?.(message.message, data);
|
|
83
|
+
return;
|
|
84
|
+
}
|
|
85
|
+
clearTimeout(pending.timer);
|
|
86
|
+
child.pending.delete(message.id);
|
|
87
|
+
pending.resolve(message.type === 'result'
|
|
88
|
+
? { ok: true, value: message.value }
|
|
89
|
+
: { ok: false, code: message.code, message: message.message });
|
|
90
|
+
if (message.retire === true)
|
|
91
|
+
child.retireWhenDone = true;
|
|
92
|
+
if (child.pending.size > 0)
|
|
93
|
+
return;
|
|
94
|
+
if (child.retireWhenDone)
|
|
95
|
+
retire(child, 'retired');
|
|
96
|
+
else
|
|
97
|
+
armIdle(child);
|
|
98
|
+
}
|
|
99
|
+
/** Later requests start a fresh child; this one exits when its stdin closes. */
|
|
100
|
+
function retire(child, reason) {
|
|
101
|
+
if (current === child)
|
|
102
|
+
current = null;
|
|
103
|
+
retiring = child;
|
|
104
|
+
child.killedFor ??= reason;
|
|
105
|
+
child.proc.stdin.end();
|
|
106
|
+
setTimeout(() => kill(child, reason), IDLE_KILL_GRACE_MS).unref();
|
|
107
|
+
}
|
|
108
|
+
function armIdle(child) {
|
|
109
|
+
clearTimeout(idleTimer);
|
|
110
|
+
idleTimer = setTimeout(() => {
|
|
111
|
+
if (current === child && child.pending.size === 0)
|
|
112
|
+
retire(child, 'idle');
|
|
113
|
+
}, idleMs);
|
|
114
|
+
idleTimer.unref();
|
|
115
|
+
}
|
|
116
|
+
function startSampler(child) {
|
|
117
|
+
let busy = false;
|
|
118
|
+
child.sampler = setInterval(() => {
|
|
119
|
+
const pid = child.proc.pid;
|
|
120
|
+
if (busy || pid === undefined)
|
|
121
|
+
return;
|
|
122
|
+
busy = true;
|
|
123
|
+
void rssMb(pid).then((mb) => {
|
|
124
|
+
busy = false;
|
|
125
|
+
if (mb !== null && mb > memoryLimitMb)
|
|
126
|
+
kill(child, 'memory-limit');
|
|
127
|
+
});
|
|
128
|
+
}, options.samplerMs ?? 1_000);
|
|
129
|
+
child.sampler.unref();
|
|
130
|
+
}
|
|
131
|
+
function spawnChild() {
|
|
132
|
+
const proc = spawn(runtime.command, [...runtimeArgs(runtime, memoryLimitMb), childScript], {
|
|
133
|
+
env,
|
|
134
|
+
stdio: 'pipe',
|
|
135
|
+
});
|
|
136
|
+
let markExited = () => undefined;
|
|
137
|
+
const child = {
|
|
138
|
+
proc,
|
|
139
|
+
pending: new Map(),
|
|
140
|
+
stderr: '',
|
|
141
|
+
killedFor: null,
|
|
142
|
+
timedOut: null,
|
|
143
|
+
retireWhenDone: false,
|
|
144
|
+
exited: new Promise((resolve) => (markExited = resolve)),
|
|
145
|
+
};
|
|
146
|
+
let done = false;
|
|
147
|
+
const finish = (code, signal) => {
|
|
148
|
+
if (done)
|
|
149
|
+
return;
|
|
150
|
+
done = true;
|
|
151
|
+
onExit(child, code, signal);
|
|
152
|
+
markExited();
|
|
153
|
+
};
|
|
154
|
+
proc.stdout.on('data', lineReader((line) => {
|
|
155
|
+
const message = parseMessage(line);
|
|
156
|
+
if (typeof message === 'string') {
|
|
157
|
+
child.stderr = `${child.stderr}[protocol] ${message}: ${line.slice(0, 200)}\n`.slice(-STDERR_TAIL);
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
onMessage(child, message);
|
|
161
|
+
}));
|
|
162
|
+
proc.stderr.on('data', (chunk) => {
|
|
163
|
+
child.stderr = (child.stderr + chunk.toString()).slice(-STDERR_TAIL);
|
|
164
|
+
});
|
|
165
|
+
// A write to a dying child fails with EPIPE; 'close' then reports the exit to every request.
|
|
166
|
+
proc.stdin.on('error', () => undefined);
|
|
167
|
+
proc.on('error', (error) => {
|
|
168
|
+
child.stderr += error.message;
|
|
169
|
+
if (proc.pid === undefined)
|
|
170
|
+
finish(null, null);
|
|
171
|
+
});
|
|
172
|
+
proc.on('close', finish);
|
|
173
|
+
if (watchdog)
|
|
174
|
+
startSampler(child);
|
|
175
|
+
starts++;
|
|
176
|
+
return child;
|
|
177
|
+
}
|
|
178
|
+
function request(op, args, opts = {}) {
|
|
179
|
+
// A retiring child still holds its memory: start the next one only after it has exited.
|
|
180
|
+
if (retiring !== null)
|
|
181
|
+
return retiring.exited.then(() => request(op, args, opts));
|
|
182
|
+
clearTimeout(idleTimer);
|
|
183
|
+
const child = (current ??= spawnChild());
|
|
184
|
+
const id = String(++sequence);
|
|
185
|
+
const ms = opts.timeoutMs ?? requestMs;
|
|
186
|
+
return new Promise((resolve) => {
|
|
187
|
+
const timer = setTimeout(() => {
|
|
188
|
+
child.timedOut ??= { op, ms };
|
|
189
|
+
kill(child, 'timeout');
|
|
190
|
+
}, ms);
|
|
191
|
+
child.pending.set(id, { resolve, onProgress: opts.onProgress, timer });
|
|
192
|
+
child.proc.stdin.write(encode({ type: 'request', id, op, args }));
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
async function stop() {
|
|
196
|
+
clearTimeout(idleTimer);
|
|
197
|
+
const children = [current, retiring].filter((child) => child !== null);
|
|
198
|
+
for (const child of children)
|
|
199
|
+
kill(child, 'stopped');
|
|
200
|
+
await Promise.all(children.map((child) => child.exited));
|
|
201
|
+
}
|
|
202
|
+
function status() {
|
|
203
|
+
return { runtime, memoryLimitMb, pid: current?.proc.pid ?? null, starts, lastExit };
|
|
204
|
+
}
|
|
205
|
+
return { request, stop, status };
|
|
206
|
+
}
|