@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.
Files changed (119) hide show
  1. package/.antigravity-plugin/plugin.json +20 -0
  2. package/LICENSE +21 -0
  3. package/README.md +195 -2
  4. package/agy-skills/erosiano-review/SKILL.md +17 -0
  5. package/dist/adapters/agy/skills.js +252 -0
  6. package/dist/adapters/cli/check-changed.js +3 -0
  7. package/dist/adapters/cli/main.js +1013 -0
  8. package/dist/adapters/cli/policy-bin.js +10 -0
  9. package/dist/adapters/cli/review-verdict.js +3 -0
  10. package/dist/adapters/omp/extension.js +884 -0
  11. package/dist/adapters/omp/skills.js +130 -0
  12. package/dist/adapters/ui/hud.js +389 -0
  13. package/dist/adapters/ui/tree.js +471 -0
  14. package/dist/core/audit/index.js +2 -0
  15. package/dist/core/audit/log.js +505 -0
  16. package/dist/core/audit/summary.js +188 -0
  17. package/dist/core/changes/changes.js +591 -0
  18. package/dist/core/changes/git.js +266 -0
  19. package/dist/core/changes/plan.js +109 -0
  20. package/dist/core/changes/render.js +356 -0
  21. package/dist/core/engine/build.js +178 -0
  22. package/dist/core/engine/child.js +389 -0
  23. package/dist/core/engine/host.js +206 -0
  24. package/dist/core/engine/lock.js +133 -0
  25. package/dist/core/engine/protocol.js +43 -0
  26. package/dist/core/engine/runtime.js +44 -0
  27. package/dist/core/engine/status.js +452 -0
  28. package/dist/core/engine/typescript.js +194 -0
  29. package/dist/core/engine/workspace.js +72 -0
  30. package/dist/core/graph/graph.js +127 -0
  31. package/dist/core/graph/limits.js +16 -0
  32. package/dist/core/impact/query.js +1292 -0
  33. package/dist/core/impact/render.js +590 -0
  34. package/dist/core/impact/session.js +694 -0
  35. package/dist/core/indexing/declarations.js +455 -0
  36. package/dist/core/indexing/differential.js +345 -0
  37. package/dist/core/indexing/doctor.js +120 -0
  38. package/dist/core/indexing/indexer.js +811 -0
  39. package/dist/core/indexing/keys.js +451 -0
  40. package/dist/core/indexing/lexical.js +212 -0
  41. package/dist/core/indexing/packages.js +57 -0
  42. package/dist/core/indexing/program.js +171 -0
  43. package/dist/core/indexing/resolve.js +1004 -0
  44. package/dist/core/indexing/stamp.js +52 -0
  45. package/dist/core/indexing/surface.js +335 -0
  46. package/dist/core/indexing/ui-progress.js +37 -0
  47. package/dist/core/indexing/verify.js +76 -0
  48. package/dist/core/kernel/config.js +383 -0
  49. package/dist/core/kernel/glob.js +105 -0
  50. package/dist/core/kernel/guards.js +4 -0
  51. package/dist/core/kernel/types.js +3 -0
  52. package/dist/core/kernel/verdict.js +142 -0
  53. package/dist/core/knowledge/anchors.js +139 -0
  54. package/dist/core/knowledge/knowledge.js +95 -0
  55. package/dist/core/knowledge/learning.js +102 -0
  56. package/dist/core/knowledge/render.js +76 -0
  57. package/dist/core/knowledge/store.js +109 -0
  58. package/dist/core/knowledge/yaml.js +87 -0
  59. package/dist/core/search/lexical.js +382 -0
  60. package/dist/core/search/render.js +98 -0
  61. package/dist/core/search/segments.js +118 -0
  62. package/dist/core/verify/parse.js +127 -0
  63. package/dist/core/verify/render.js +67 -0
  64. package/dist/core/verify/report.js +40 -0
  65. package/dist/core/verify/revision.js +79 -0
  66. package/dist/core/verify/run.js +117 -0
  67. package/dist/core/verify/store.js +66 -0
  68. package/dist/core/verify/verify.js +173 -0
  69. package/dist/core/workspace/init.js +267 -0
  70. package/dist/core/workspace/probe.js +56 -0
  71. package/dist/core/workspace/scan.js +420 -0
  72. package/dist/engineering/baseline.js +337 -0
  73. package/dist/engineering/change-scope.js +500 -0
  74. package/dist/engineering/check-changed.js +40 -0
  75. package/dist/engineering/config.js +129 -0
  76. package/dist/engineering/dist/policy.d.ts +17 -0
  77. package/dist/engineering/dist/policy.js +150 -0
  78. package/dist/engineering/dist/runtime.d.ts +40 -0
  79. package/dist/engineering/dist/runtime.js +77 -0
  80. package/dist/engineering/dist/sdlc.d.ts +7 -0
  81. package/dist/engineering/dist/sdlc.js +27 -0
  82. package/dist/engineering/eslint-rules/index.js +107 -0
  83. package/dist/engineering/index.d.ts +7 -0
  84. package/dist/engineering/index.js +319 -0
  85. package/dist/engineering/intelligence.js +44 -0
  86. package/dist/engineering/package.json +36 -0
  87. package/dist/engineering/policy.js +2 -0
  88. package/dist/engineering/practice-tool.js +72 -0
  89. package/dist/engineering/practices.js +283 -0
  90. package/dist/engineering/practices.json +2453 -0
  91. package/dist/engineering/review-verdict.js +262 -0
  92. package/dist/engineering/sdlc.js +2 -0
  93. package/dist/index.js +20 -0
  94. package/dist/storage/records.js +245 -0
  95. package/dist/storage/sqlite.js +314 -0
  96. package/dist/workflow/catalog.js +69 -0
  97. package/dist/workflow/classify.js +55 -0
  98. package/dist/workflow/loader.js +140 -0
  99. package/dist/workflow/packs.js +469 -0
  100. package/dist/workflow/registry.js +359 -0
  101. package/dist/workflow/render.js +61 -0
  102. package/dist/workflow/router.js +141 -0
  103. package/dist/workflow/sources.js +229 -0
  104. package/dist/workflow/types.js +44 -0
  105. package/dist/workflow/updates.js +532 -0
  106. package/engineering.lock.json +94 -0
  107. package/package.json +81 -4
  108. package/rules/engineering.md +20 -0
  109. package/scripts/agy-mcp.mjs +27 -0
  110. package/scripts/mcp/engineering.mjs +91 -0
  111. package/scripts/mcp/stdio.mjs +304 -0
  112. package/scripts/mcp/tools.mjs +491 -0
  113. package/skills/ksd-intelligence/SKILL.md +54 -0
  114. package/skills/matt-sdlc/SKILL.md +42 -0
  115. package/skills/osmani-quality/SKILL.md +38 -0
  116. package/skills/poteto-mode/SKILL.md +40 -0
  117. package/skills/pstack-analysis/SKILL.md +36 -0
  118. package/skills.lock.json +71 -0
  119. package/skills.registry.json +181 -0
@@ -0,0 +1,694 @@
1
+ import { readFileSync, statSync } from 'node:fs';
2
+ import { join } from 'node:path';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { buildIndex } from '../engine/build.js';
5
+ import { isHolderAlive, readLockHolder } from '../engine/lock.js';
6
+ import { impactConfigHash } from '../indexing/stamp.js';
7
+ import { isRecord } from '../kernel/guards.js';
8
+ import { applyRiskZones } from '../kernel/verdict.js';
9
+ import { probe } from '../workspace/probe.js';
10
+ import { FAILURE_FILE, SCHEMA_VERSION, openPublished, readFiles, readMeta, readSchemaVersion, } from '../../storage/sqlite.js';
11
+ import { ImpactQuery } from './query.js';
12
+ function failure(targets, message) {
13
+ return targets.map((input) => ({
14
+ input,
15
+ kind: 'failure',
16
+ code: 'index-failed',
17
+ message: `index-failed: ${message}`,
18
+ retry: true,
19
+ }));
20
+ }
21
+ function building(targets) {
22
+ return targets.map((input) => ({
23
+ input,
24
+ kind: 'guidance',
25
+ code: 'index-building',
26
+ message: 'index-building: index update is still running; retry shortly',
27
+ }));
28
+ }
29
+ function fileOfKey(key) {
30
+ const hash = key.indexOf('#');
31
+ return hash === -1 ? key : key.slice(0, hash);
32
+ }
33
+ function staleResult(value, reason, riskZones) {
34
+ const paths = [
35
+ value.span?.file ?? fileOfKey(value.target),
36
+ ...value.byDepth.flat().map((node) => node.span.file),
37
+ ];
38
+ const verdict = applyRiskZones({
39
+ ...value.verdict,
40
+ basis: [...new Set([...value.verdict.basis, 'stale-index'])],
41
+ }, paths, riskZones, {
42
+ incomplete: true,
43
+ hasFactors: value.factors.length > 0,
44
+ preMatchedZones: value.verdict.zones,
45
+ });
46
+ return {
47
+ ...value,
48
+ completeness: {
49
+ status: 'partial',
50
+ reasons: [...new Set([...value.completeness.reasons, reason])],
51
+ },
52
+ verdict,
53
+ };
54
+ }
55
+ function markStale(answer, reason, riskZones) {
56
+ if (answer.kind !== 'result')
57
+ return answer;
58
+ if ('results' in answer.value) {
59
+ return {
60
+ ...answer,
61
+ value: {
62
+ ...answer.value,
63
+ results: answer.value.results.map((result) => staleResult(result, reason, riskZones)),
64
+ ...(answer.value.aggregate === undefined
65
+ ? {}
66
+ : { aggregate: staleResult(answer.value.aggregate, reason, riskZones) }),
67
+ },
68
+ };
69
+ }
70
+ return { ...answer, value: staleResult(answer.value, reason, riskZones) };
71
+ }
72
+ function updatedFiles(outcome, fallback) {
73
+ if (!outcome.ok || !isRecord(outcome.value.drift))
74
+ return fallback;
75
+ const { added, changed, deleted } = outcome.value.drift;
76
+ if (typeof added !== 'number' || typeof changed !== 'number' || typeof deleted !== 'number') {
77
+ return fallback;
78
+ }
79
+ return added + changed + deleted;
80
+ }
81
+ function lastFailure(cacheDir, builtAt) {
82
+ try {
83
+ const raw = JSON.parse(readFileSync(join(cacheDir, FAILURE_FILE), 'utf8'));
84
+ if (!isRecord(raw) ||
85
+ typeof raw.at !== 'string' ||
86
+ (builtAt !== undefined && builtAt > raw.at)) {
87
+ return null;
88
+ }
89
+ const problems = Array.isArray(raw.problems)
90
+ ? raw.problems.filter((value) => typeof value === 'string')
91
+ : [];
92
+ return (problems.join('; ') ||
93
+ (typeof raw.reason === 'string' ? raw.reason : 'index verification failed'));
94
+ }
95
+ catch {
96
+ return null;
97
+ }
98
+ }
99
+ function driftFingerprint(root, driftedFiles, configHash) {
100
+ const parts = [`config:${configHash}`];
101
+ for (const path of driftedFiles) {
102
+ try {
103
+ const stat = statSync(join(root, path));
104
+ parts.push(`${path}:${stat.size}:${stat.mtimeMs}`);
105
+ }
106
+ catch {
107
+ parts.push(`${path}:missing`);
108
+ }
109
+ }
110
+ return parts.join('\n');
111
+ }
112
+ function staleReasonText(driftedFiles, staleReason, failureMessage) {
113
+ const paths = driftedFiles.slice(0, 10).join(', ');
114
+ const omitted = driftedFiles.length > 10 ? ` (+${driftedFiles.length - 10} more)` : '';
115
+ return `stale-index: ${paths}${omitted}${staleReason ? `; ${staleReason}` : ''}${failureMessage}`;
116
+ }
117
+ const TIMED_OUT = Symbol('build wait expired');
118
+ const ABORTED = Symbol('wait aborted');
119
+ /** One repository's query coordinator. No database is held open between calls. */
120
+ export class ImpactSession {
121
+ workspace;
122
+ activeBuild = null;
123
+ lastFailed = null;
124
+ build;
125
+ waitMs;
126
+ waitAfterExpiry;
127
+ onProgress;
128
+ constructor(workspace, options = {}) {
129
+ this.workspace = workspace;
130
+ this.build = options.build ?? buildIndex;
131
+ this.waitMs = options.waitMs ?? 60_000;
132
+ this.waitAfterExpiry = options.waitAfterExpiry ?? false;
133
+ this.onProgress = options.onProgress;
134
+ }
135
+ ensureBuild() {
136
+ if (this.activeBuild !== null && !this.activeBuild.cancelled) {
137
+ return this.activeBuild;
138
+ }
139
+ const controller = new AbortController();
140
+ const waiters = new Set();
141
+ const progressCallbacks = new Set();
142
+ const onProgress = (message, data) => {
143
+ this.onProgress?.(message, data);
144
+ for (const cb of progressCallbacks)
145
+ cb(message, data);
146
+ };
147
+ const shared = {
148
+ task: Promise.resolve({
149
+ ok: false,
150
+ code: 'index-failed',
151
+ message: 'uninitialized',
152
+ fix: 'retry',
153
+ }),
154
+ controller,
155
+ waiters,
156
+ progressCallbacks,
157
+ hasDetachedWaiter: false,
158
+ cancelled: false,
159
+ };
160
+ const task = Promise.resolve()
161
+ .then(() => this.build(this.workspace, {
162
+ onProgress,
163
+ signal: controller.signal,
164
+ }))
165
+ .catch((error) => ({
166
+ ok: false,
167
+ code: 'index-failed',
168
+ message: error instanceof Error ? error.message : String(error),
169
+ fix: 'retry once: ei index',
170
+ }));
171
+ shared.task = task;
172
+ this.activeBuild = shared;
173
+ void task.then(() => {
174
+ if (this.activeBuild === shared)
175
+ this.activeBuild = null;
176
+ });
177
+ return shared;
178
+ }
179
+ async runBuildWait(deadline, callOptions) {
180
+ // If an earlier cancelled build is still tearing down its child process, wait for teardown
181
+ // before starting a fresh build so we neither join a dying build nor race the lock file.
182
+ while (this.activeBuild !== null && this.activeBuild.cancelled) {
183
+ const cancelling = this.activeBuild;
184
+ const settled = await this.raceWait(cancelling.task, deadline, callOptions.signal);
185
+ if (settled === ABORTED || callOptions.signal?.aborted) {
186
+ return { ok: false, code: 'index-failed', message: 'Cancelled', fix: 'retry' };
187
+ }
188
+ if (settled === TIMED_OUT)
189
+ return TIMED_OUT;
190
+ }
191
+ const shared = this.ensureBuild();
192
+ const waiter = { signal: callOptions.signal };
193
+ shared.waiters.add(waiter);
194
+ if (callOptions.onProgress !== undefined)
195
+ shared.progressCallbacks.add(callOptions.onProgress);
196
+ let settled;
197
+ try {
198
+ settled = await this.raceWait(shared.task, deadline, callOptions.signal);
199
+ if (settled === TIMED_OUT && this.waitAfterExpiry && !callOptions.signal?.aborted) {
200
+ settled = await this.raceWait(shared.task, Number.POSITIVE_INFINITY, callOptions.signal);
201
+ }
202
+ }
203
+ finally {
204
+ shared.waiters.delete(waiter);
205
+ if (callOptions.onProgress !== undefined) {
206
+ shared.progressCallbacks.delete(callOptions.onProgress);
207
+ }
208
+ }
209
+ if (settled === TIMED_OUT && !callOptions.signal?.aborted) {
210
+ shared.hasDetachedWaiter = true;
211
+ return TIMED_OUT;
212
+ }
213
+ if (settled === ABORTED || callOptions.signal?.aborted) {
214
+ const noLiveWaiters = [...shared.waiters].every((w) => w.signal?.aborted === true);
215
+ if (noLiveWaiters && !shared.hasDetachedWaiter && !shared.cancelled) {
216
+ shared.cancelled = true;
217
+ shared.controller.abort();
218
+ }
219
+ if (shared.cancelled)
220
+ await shared.task;
221
+ return { ok: false, code: 'index-failed', message: 'Cancelled', fix: 'retry' };
222
+ }
223
+ return settled;
224
+ }
225
+ raceWait(promise, deadline, signal) {
226
+ if (signal?.aborted)
227
+ return Promise.resolve(ABORTED);
228
+ const competitors = [promise];
229
+ let timer;
230
+ if (Number.isFinite(deadline)) {
231
+ const remaining = Math.max(0, deadline - Date.now());
232
+ competitors.push(new Promise((resolve) => {
233
+ timer = setTimeout(() => resolve(TIMED_OUT), remaining);
234
+ }));
235
+ }
236
+ let onAbort;
237
+ if (signal !== undefined) {
238
+ competitors.push(new Promise((resolve) => {
239
+ onAbort = () => resolve(ABORTED);
240
+ signal.addEventListener('abort', onAbort, { once: true });
241
+ }));
242
+ }
243
+ return Promise.race(competitors).finally(() => {
244
+ if (timer !== undefined)
245
+ clearTimeout(timer);
246
+ if (onAbort !== undefined)
247
+ signal?.removeEventListener('abort', onAbort);
248
+ });
249
+ }
250
+ async untilPublished(previousId, deadline, signal) {
251
+ while (Date.now() < deadline) {
252
+ if (signal?.aborted)
253
+ return 'aborted';
254
+ const db = openPublished(this.workspace.cacheDir);
255
+ try {
256
+ if (db !== null && readMeta(db).build_id !== previousId)
257
+ return 'published';
258
+ }
259
+ finally {
260
+ db?.close();
261
+ }
262
+ const holder = readLockHolder(this.workspace.cacheDir);
263
+ if (holder === null || !isHolderAlive(holder)) {
264
+ const check = openPublished(this.workspace.cacheDir);
265
+ try {
266
+ return check !== null && readMeta(check).build_id !== previousId
267
+ ? 'published'
268
+ : 'released';
269
+ }
270
+ finally {
271
+ check?.close();
272
+ }
273
+ }
274
+ await delay(Math.min(50, Math.max(1, deadline - Date.now())));
275
+ }
276
+ return signal?.aborted ? 'aborted' : 'timed-out';
277
+ }
278
+ answer(targets, depth, db, options) {
279
+ return new ImpactQuery(db, this.workspace.config.impact, {
280
+ ...options,
281
+ riskZones: this.workspace.config.riskZones,
282
+ }).batch(targets, depth);
283
+ }
284
+ async query(targets, depth, callOptions = {}) {
285
+ if (callOptions.signal?.aborted) {
286
+ return {
287
+ answers: failure(targets, 'Cancelled'),
288
+ index: { state: 'stale', updatedFiles: 0, driftedFiles: [] },
289
+ };
290
+ }
291
+ const invalid = targets.length < 1 ||
292
+ targets.length > 5 ||
293
+ targets.some((target) => typeof target !== 'string' || target.length === 0) ||
294
+ (depth !== undefined && (!Number.isInteger(depth) || depth < 1 || depth > 10));
295
+ if (invalid) {
296
+ return {
297
+ answers: targets.length === 0
298
+ ? [
299
+ {
300
+ input: '',
301
+ kind: 'failure',
302
+ code: 'INVALID_INPUT',
303
+ message: 'provide 1–5 targets and depth 1–10',
304
+ },
305
+ ]
306
+ : targets.map((input) => ({
307
+ input,
308
+ kind: 'failure',
309
+ code: 'INVALID_INPUT',
310
+ message: 'provide 1–5 targets and depth 1–10',
311
+ })),
312
+ index: { state: 'fresh', updatedFiles: 0, driftedFiles: [] },
313
+ };
314
+ }
315
+ let db = null;
316
+ let prefetched;
317
+ let driftedFiles = [];
318
+ let fingerprint = '';
319
+ let previousId = null;
320
+ let staleReason = '';
321
+ try {
322
+ const configHash = impactConfigHash(this.workspace.config.impact);
323
+ db = openPublished(this.workspace.cacheDir);
324
+ if (db !== null) {
325
+ if (readSchemaVersion(db) !== SCHEMA_VERSION) {
326
+ staleReason = 'published schema does not match current index';
327
+ db.close();
328
+ db = null;
329
+ }
330
+ else {
331
+ const meta = readMeta(db);
332
+ previousId = meta.build_id ?? null;
333
+ const persistedFailure = lastFailure(this.workspace.cacheDir, meta.built_at);
334
+ if (persistedFailure !== null)
335
+ staleReason = `update failed: ${persistedFailure}`;
336
+ const files = readFiles(db);
337
+ prefetched = { files, meta };
338
+ const drift = await probe(this.workspace.root, this.workspace.config.impact, files, this.workspace.config.impact.freshness);
339
+ driftedFiles = [...new Set([...drift.added, ...drift.changed, ...drift.deleted])].sort();
340
+ if (meta.config_hash !== configHash) {
341
+ staleReason = 'index configuration changed';
342
+ driftedFiles = [...new Set([...driftedFiles, 'ei.config.json'])].sort();
343
+ }
344
+ if (driftedFiles.length === 0 && persistedFailure !== null) {
345
+ this.lastFailed = null;
346
+ const reason = `stale-index: ${staleReason}`;
347
+ return {
348
+ answers: this.answer(targets, depth, db, prefetched).map((answer) => markStale(answer, reason, this.workspace.config.riskZones)),
349
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
350
+ };
351
+ }
352
+ if (driftedFiles.length === 0) {
353
+ this.lastFailed = null;
354
+ const answers = this.answer(targets, depth, db, prefetched);
355
+ return { answers, index: { state: 'fresh', updatedFiles: 0, driftedFiles: [] } };
356
+ }
357
+ fingerprint = driftFingerprint(this.workspace.root, driftedFiles, configHash);
358
+ if (this.lastFailed !== null && this.lastFailed.fingerprint === fingerprint) {
359
+ const reason = staleReasonText(driftedFiles, staleReason, `; update failed: ${this.lastFailed.message}`);
360
+ return {
361
+ answers: this.answer(targets, depth, db, prefetched).map((answer) => markStale(answer, reason, this.workspace.config.riskZones)),
362
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
363
+ };
364
+ }
365
+ }
366
+ }
367
+ const deadline = Date.now() + this.waitMs;
368
+ let outcome = await this.runBuildWait(deadline, callOptions);
369
+ if (callOptions.signal?.aborted) {
370
+ return {
371
+ answers: failure(targets, 'Cancelled'),
372
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
373
+ };
374
+ }
375
+ if (outcome !== TIMED_OUT && !outcome.ok && outcome.code === 'busy') {
376
+ const status = await this.untilPublished(previousId, this.waitAfterExpiry ? Number.POSITIVE_INFINITY : deadline, callOptions.signal);
377
+ if (status === 'aborted' || callOptions.signal?.aborted) {
378
+ return {
379
+ answers: failure(targets, 'Cancelled'),
380
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
381
+ };
382
+ }
383
+ outcome =
384
+ status === 'published'
385
+ ? { ok: true, value: { action: 'update' } }
386
+ : status === 'released' || this.waitAfterExpiry
387
+ ? {
388
+ ok: false,
389
+ code: 'index-failed',
390
+ message: 'another session released the lock without publishing',
391
+ fix: 'run: ei index',
392
+ }
393
+ : TIMED_OUT;
394
+ }
395
+ if (outcome !== TIMED_OUT && outcome.ok && outcome.value.action === 'failed') {
396
+ const problems = outcome.value.problems;
397
+ outcome = {
398
+ ok: false,
399
+ code: 'index-failed',
400
+ message: Array.isArray(problems) ? problems.join('; ') : 'index verification failed',
401
+ fix: 'retry once: ei index',
402
+ };
403
+ }
404
+ if (outcome !== TIMED_OUT && outcome.ok) {
405
+ db?.close();
406
+ db = null;
407
+ db = openPublished(this.workspace.cacheDir);
408
+ if (db === null || readSchemaVersion(db) !== SCHEMA_VERSION) {
409
+ outcome = {
410
+ ok: false,
411
+ code: 'index-failed',
412
+ message: 'build completed without publishing a compatible index',
413
+ fix: 'retry once: ei index',
414
+ };
415
+ }
416
+ else {
417
+ this.lastFailed = null;
418
+ const answers = this.answer(targets, depth, db);
419
+ return {
420
+ answers,
421
+ index: {
422
+ state: 'updated',
423
+ updatedFiles: updatedFiles(outcome, driftedFiles.length),
424
+ driftedFiles,
425
+ },
426
+ };
427
+ }
428
+ }
429
+ if (outcome !== TIMED_OUT && !outcome.ok && fingerprint !== '') {
430
+ this.lastFailed = { fingerprint, message: outcome.message };
431
+ }
432
+ if (db === null) {
433
+ return {
434
+ answers: outcome === TIMED_OUT ? building(targets) : failure(targets, outcome.message),
435
+ index: {
436
+ state: outcome === TIMED_OUT ? 'building' : 'stale',
437
+ updatedFiles: 0,
438
+ driftedFiles,
439
+ },
440
+ };
441
+ }
442
+ const failureMessage = outcome === TIMED_OUT ? '' : `; update failed: ${outcome.message}`;
443
+ const reason = staleReasonText(driftedFiles, staleReason, failureMessage);
444
+ return {
445
+ answers: this.answer(targets, depth, db, prefetched).map((answer) => markStale(answer, reason, this.workspace.config.riskZones)),
446
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
447
+ };
448
+ }
449
+ catch (error) {
450
+ const message = error instanceof Error ? error.message : String(error);
451
+ return {
452
+ answers: failure(targets, message),
453
+ index: { state: 'stale', updatedFiles: 0, driftedFiles },
454
+ };
455
+ }
456
+ finally {
457
+ db?.close();
458
+ }
459
+ }
460
+ getWorkspace() {
461
+ return this.workspace;
462
+ }
463
+ /**
464
+ * Ensure the published index is fresh using a full content hash (`freshness: 'hash'`), never
465
+ * `'stat'`. Caller owns closing the returned `db` when non-null.
466
+ */
467
+ async prepareForChanges(callOptions = {}) {
468
+ return this.prepareSessionDb('hash', callOptions, true);
469
+ }
470
+ /**
471
+ * Ensure the published index is ready for lexical search using configured freshness (`'stat'`
472
+ * by default). Caller owns closing the returned `db` when non-null.
473
+ */
474
+ async prepareForSearch(callOptions = {}) {
475
+ const ctx = await this.prepareSessionDb(this.workspace.config.impact.freshness, callOptions, false);
476
+ return {
477
+ db: ctx.db,
478
+ indexState: ctx.indexState,
479
+ updatedFiles: ctx.updatedFiles,
480
+ driftedFiles: ctx.driftedFiles,
481
+ staleReason: ctx.staleReason,
482
+ failureMessage: ctx.failureMessage,
483
+ ...(ctx.meta !== undefined ? { meta: ctx.meta } : {}),
484
+ ...(ctx.scannedFiles !== undefined ? { scannedFiles: ctx.scannedFiles } : {}),
485
+ };
486
+ }
487
+ async prepareSessionDb(freshness, callOptions = {}, capturePreUpdate = false) {
488
+ if (callOptions.signal?.aborted) {
489
+ return {
490
+ db: null,
491
+ indexState: 'failed',
492
+ updatedFiles: 0,
493
+ driftedFiles: [],
494
+ staleReason: null,
495
+ failureMessage: 'Cancelled',
496
+ preUpdateIndexable: null,
497
+ };
498
+ }
499
+ let db = null;
500
+ let driftedFiles = [];
501
+ let fingerprint = '';
502
+ let previousId = null;
503
+ let staleReason = '';
504
+ let preUpdateIndexable = null;
505
+ let meta;
506
+ let scannedFiles;
507
+ try {
508
+ const configHash = impactConfigHash(this.workspace.config.impact);
509
+ db = openPublished(this.workspace.cacheDir);
510
+ if (db !== null) {
511
+ if (readSchemaVersion(db) !== SCHEMA_VERSION) {
512
+ staleReason = 'published schema does not match current index';
513
+ db.close();
514
+ db = null;
515
+ }
516
+ else {
517
+ meta = readMeta(db);
518
+ previousId = meta.build_id ?? null;
519
+ const persistedFailure = lastFailure(this.workspace.cacheDir, meta.built_at);
520
+ if (persistedFailure !== null)
521
+ staleReason = `update failed: ${persistedFailure}`;
522
+ const files = readFiles(db);
523
+ scannedFiles = files.length;
524
+ if (capturePreUpdate) {
525
+ preUpdateIndexable = new Set(files.filter((f) => f.status === 'indexable').map((f) => f.path));
526
+ }
527
+ const drift = await probe(this.workspace.root, this.workspace.config.impact, files, freshness);
528
+ driftedFiles = [...new Set([...drift.added, ...drift.changed, ...drift.deleted])].sort();
529
+ if (meta.config_hash !== configHash) {
530
+ staleReason = 'index configuration changed';
531
+ driftedFiles = [...new Set([...driftedFiles, 'ei.config.json'])].sort();
532
+ }
533
+ if (driftedFiles.length === 0 && persistedFailure !== null) {
534
+ this.lastFailed = null;
535
+ return {
536
+ db,
537
+ indexState: 'stale',
538
+ updatedFiles: 0,
539
+ driftedFiles,
540
+ staleReason: `stale-index: ${staleReason}`,
541
+ failureMessage: null,
542
+ preUpdateIndexable,
543
+ meta,
544
+ scannedFiles,
545
+ };
546
+ }
547
+ if (driftedFiles.length === 0) {
548
+ this.lastFailed = null;
549
+ return {
550
+ db,
551
+ indexState: 'fresh',
552
+ updatedFiles: 0,
553
+ driftedFiles: [],
554
+ staleReason: null,
555
+ failureMessage: null,
556
+ preUpdateIndexable,
557
+ meta,
558
+ scannedFiles,
559
+ };
560
+ }
561
+ fingerprint = driftFingerprint(this.workspace.root, driftedFiles, configHash);
562
+ if (this.lastFailed !== null && this.lastFailed.fingerprint === fingerprint) {
563
+ return {
564
+ db,
565
+ indexState: 'stale',
566
+ updatedFiles: 0,
567
+ driftedFiles,
568
+ staleReason: staleReasonText(driftedFiles, staleReason, `; update failed: ${this.lastFailed.message}`),
569
+ failureMessage: null,
570
+ preUpdateIndexable,
571
+ meta,
572
+ scannedFiles,
573
+ };
574
+ }
575
+ }
576
+ }
577
+ const deadline = Date.now() + this.waitMs;
578
+ let outcome = await this.runBuildWait(deadline, callOptions);
579
+ if (callOptions.signal?.aborted) {
580
+ db?.close();
581
+ return {
582
+ db: null,
583
+ indexState: 'failed',
584
+ updatedFiles: 0,
585
+ driftedFiles,
586
+ staleReason: null,
587
+ failureMessage: 'Cancelled',
588
+ preUpdateIndexable,
589
+ };
590
+ }
591
+ if (outcome !== TIMED_OUT && !outcome.ok && outcome.code === 'busy') {
592
+ const status = await this.untilPublished(previousId, this.waitAfterExpiry ? Number.POSITIVE_INFINITY : deadline, callOptions.signal);
593
+ if (status === 'aborted' || callOptions.signal?.aborted) {
594
+ db?.close();
595
+ return {
596
+ db: null,
597
+ indexState: 'failed',
598
+ updatedFiles: 0,
599
+ driftedFiles,
600
+ staleReason: null,
601
+ failureMessage: 'Cancelled',
602
+ preUpdateIndexable,
603
+ };
604
+ }
605
+ outcome =
606
+ status === 'published'
607
+ ? { ok: true, value: { action: 'update' } }
608
+ : status === 'released' || this.waitAfterExpiry
609
+ ? {
610
+ ok: false,
611
+ code: 'index-failed',
612
+ message: 'another session released the lock without publishing',
613
+ fix: 'run: ei index',
614
+ }
615
+ : TIMED_OUT;
616
+ }
617
+ if (outcome !== TIMED_OUT && outcome.ok && outcome.value.action === 'failed') {
618
+ const problems = outcome.value.problems;
619
+ outcome = {
620
+ ok: false,
621
+ code: 'index-failed',
622
+ message: Array.isArray(problems) ? problems.join('; ') : 'index verification failed',
623
+ fix: 'retry once: ei index',
624
+ };
625
+ }
626
+ if (outcome !== TIMED_OUT && outcome.ok) {
627
+ db?.close();
628
+ db = openPublished(this.workspace.cacheDir);
629
+ if (db === null || readSchemaVersion(db) !== SCHEMA_VERSION) {
630
+ db?.close();
631
+ db = null;
632
+ outcome = {
633
+ ok: false,
634
+ code: 'index-failed',
635
+ message: 'build completed without publishing a compatible index',
636
+ fix: 'retry once: ei index',
637
+ };
638
+ }
639
+ else {
640
+ this.lastFailed = null;
641
+ return {
642
+ db,
643
+ indexState: 'updated',
644
+ updatedFiles: updatedFiles(outcome, driftedFiles.length),
645
+ driftedFiles,
646
+ staleReason: null,
647
+ failureMessage: null,
648
+ preUpdateIndexable,
649
+ };
650
+ }
651
+ }
652
+ if (outcome !== TIMED_OUT && !outcome.ok && fingerprint !== '') {
653
+ this.lastFailed = { fingerprint, message: outcome.message };
654
+ }
655
+ if (db === null) {
656
+ return {
657
+ db: null,
658
+ indexState: outcome === TIMED_OUT ? 'building' : 'failed',
659
+ updatedFiles: 0,
660
+ driftedFiles,
661
+ staleReason: null,
662
+ failureMessage: outcome === TIMED_OUT
663
+ ? 'index update is still running; retry shortly'
664
+ : outcome.message,
665
+ preUpdateIndexable,
666
+ };
667
+ }
668
+ const failureMessage = outcome === TIMED_OUT ? '' : `; update failed: ${outcome.message}`;
669
+ return {
670
+ db,
671
+ indexState: 'stale',
672
+ updatedFiles: 0,
673
+ driftedFiles,
674
+ staleReason: staleReasonText(driftedFiles, staleReason, failureMessage),
675
+ failureMessage: null,
676
+ preUpdateIndexable,
677
+ ...(meta !== undefined ? { meta } : {}),
678
+ ...(scannedFiles !== undefined ? { scannedFiles } : {}),
679
+ };
680
+ }
681
+ catch (error) {
682
+ db?.close();
683
+ return {
684
+ db: null,
685
+ indexState: 'failed',
686
+ updatedFiles: 0,
687
+ driftedFiles,
688
+ staleReason: null,
689
+ failureMessage: error instanceof Error ? error.message : String(error),
690
+ preUpdateIndexable,
691
+ };
692
+ }
693
+ }
694
+ }