@oaksecurity/aitm 0.0.0-stage → 2.3.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 (63) hide show
  1. package/.env.example +11 -0
  2. package/CHANGELOG.md +100 -0
  3. package/LICENSE +21 -0
  4. package/README.md +229 -2
  5. package/SECURITY.md +49 -0
  6. package/SPEC.md +304 -0
  7. package/docs/api.md +332 -0
  8. package/docs/inputs-and-limits.md +78 -0
  9. package/docs/usage.md +351 -0
  10. package/examples/custody-architecture.md +27 -0
  11. package/package.json +67 -4
  12. package/src/api/server.js +591 -0
  13. package/src/api/web.js +38 -0
  14. package/src/application.js +32 -0
  15. package/src/assessments.js +37 -0
  16. package/src/assets/BDOGrotesk-Bold.ttf +0 -0
  17. package/src/assets/BDOGrotesk-Regular.ttf +0 -0
  18. package/src/assets/OFL.txt +93 -0
  19. package/src/assets/README.md +10 -0
  20. package/src/cli.js +224 -0
  21. package/src/client.js +88 -0
  22. package/src/config.js +105 -0
  23. package/src/doctor.js +128 -0
  24. package/src/engine/credentials.js +31 -0
  25. package/src/engine/download.js +135 -0
  26. package/src/engine/engine.js +783 -0
  27. package/src/engine/errors.js +23 -0
  28. package/src/engine/generation.js +121 -0
  29. package/src/engine/ingest.js +444 -0
  30. package/src/engine/pdf-layout.js +204 -0
  31. package/src/engine/pdf-report.js +573 -0
  32. package/src/engine/prompts.js +82 -0
  33. package/src/engine/providers.js +476 -0
  34. package/src/engine/references.js +112 -0
  35. package/src/engine/report.js +200 -0
  36. package/src/engine/schema.js +267 -0
  37. package/src/engine/store.js +115 -0
  38. package/src/engine/validate.js +397 -0
  39. package/src/engine/zip.js +70 -0
  40. package/src/index.js +5 -0
  41. package/src/source-input.js +32 -0
  42. package/src/token.js +59 -0
  43. package/src/tui/app.js +694 -0
  44. package/src/tui/editor.js +34 -0
  45. package/src/tui/file-picker.js +111 -0
  46. package/src/tui/logo.js +8 -0
  47. package/src/tui/progress.js +90 -0
  48. package/src/tui/report-reader.js +105 -0
  49. package/src/tui/select.js +63 -0
  50. package/src/tui/workbench.js +377 -0
  51. package/src/version.js +5 -0
  52. package/src/web/app.js +729 -0
  53. package/src/web/assets/BDOGrotesk-Bold.woff2 +0 -0
  54. package/src/web/assets/BDOGrotesk-Medium.woff2 +0 -0
  55. package/src/web/assets/BDOGrotesk-Regular.woff2 +0 -0
  56. package/src/web/assets/README.md +5 -0
  57. package/src/web/assets/aitm-mark.svg +12 -0
  58. package/src/web/assets/oak-white.svg +166 -0
  59. package/src/web/html.js +32 -0
  60. package/src/web/index.html +26 -0
  61. package/src/web/markdown.js +48 -0
  62. package/src/web/styles.css +1450 -0
  63. package/src/web/views.js +254 -0
@@ -0,0 +1,783 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { EventEmitter } from 'node:events';
3
+ import { z } from 'zod';
4
+ import { Store, now } from './store.js';
5
+ import { AppError, insist, parse } from './errors.js';
6
+ import {
7
+ PHASES,
8
+ CreateProject,
9
+ UpdateProject,
10
+ Review,
11
+ RunInput,
12
+ SourceInput,
13
+ PhaseId,
14
+ Schemas,
15
+ enabledPhases,
16
+ resolveConfig,
17
+ } from './schema.js';
18
+ import { ingest, LIMITS, needsFullSourceRun } from './ingest.js';
19
+ import {
20
+ validateArtifact,
21
+ validateContinuation,
22
+ retainContinuation,
23
+ validateFullTrees,
24
+ resolveEvidence,
25
+ deferEvidence,
26
+ evidenceReviewNotes,
27
+ resolveCoverage,
28
+ } from './validate.js';
29
+ import { promptFor } from './prompts.js';
30
+ import { generationSources, generationSchema } from './generation.js';
31
+ import { resolveReferences } from './references.js';
32
+ import { Providers } from './providers.js';
33
+
34
+ const artifact = (data, runId = null, generation = null) => ({
35
+ data,
36
+ status: 'draft',
37
+ review: null,
38
+ generatedAt: now(),
39
+ runId,
40
+ generation,
41
+ reviewNotes: evidenceReviewNotes(data),
42
+ });
43
+ const terminal = new Set(['completed', 'failed', 'cancelled', 'interrupted', 'awaiting_review']);
44
+
45
+ export class Engine {
46
+ static async open({ dataDir, providers = new Providers() }) {
47
+ return new Engine(await Store.open(dataDir), providers);
48
+ }
49
+ constructor(store, providers) {
50
+ this.store = store;
51
+ this.providers = providers;
52
+ this.events = new EventEmitter();
53
+ this.events.setMaxListeners(100);
54
+ this.active = new Map();
55
+ this.closed = false;
56
+ }
57
+ get(id) {
58
+ return this.store.get(id);
59
+ }
60
+ list() {
61
+ return this.store.list();
62
+ }
63
+ save(p) {
64
+ const saved = this.store.save(JSON.parse(this.providers.redact(JSON.stringify(p))));
65
+ this.events.emit('change', saved.id);
66
+ return saved;
67
+ }
68
+ idle(id) {
69
+ insist(!this.closed, 'Engine is stopping.', 503);
70
+ insist(
71
+ !this.active.has(id),
72
+ 'This project has an operation in progress. Wait or cancel its run before editing.',
73
+ 409,
74
+ 'project_busy',
75
+ );
76
+ }
77
+ revision(project, expected) {
78
+ insist(
79
+ project.revision === expected,
80
+ 'Project changed. Refresh and apply your edit again.',
81
+ 409,
82
+ 'revision_conflict',
83
+ );
84
+ }
85
+ audit(p, action, detail) {
86
+ p.audit.push({ at: now(), action, detail });
87
+ }
88
+ invalidate(p, from) {
89
+ const index = PHASES.findIndex((x) => x.id === from);
90
+ for (const phase of PHASES.slice(index)) delete p.artifacts[phase.id];
91
+ }
92
+ inventory(p) {
93
+ this.invalidate(p, 'scope');
94
+ p.artifacts.scope = artifact({
95
+ scope: p.scope,
96
+ inventory: p.sources.map((s) => ({
97
+ sourceId: s.id,
98
+ label: s.label,
99
+ hash: s.hash,
100
+ files: s.files.length,
101
+ })),
102
+ });
103
+ }
104
+ create(input) {
105
+ insist(!this.closed, 'Engine is stopping.', 503);
106
+ const data = parse(CreateProject, input);
107
+ // Without a provider or model choice, use a provider that has a key.
108
+ const given = input?.config ?? {};
109
+ if (!given.provider && !given.fastModel && !given.deepModel)
110
+ data.config.provider = this.providers.preferred();
111
+ data.config = resolveConfig(data.config);
112
+ const p = {
113
+ schemaVersion: 2,
114
+ id: randomUUID(),
115
+ ...data,
116
+ revision: 0,
117
+ createdAt: now(),
118
+ updatedAt: now(),
119
+ sources: [],
120
+ artifacts: {},
121
+ runs: [],
122
+ audit: [],
123
+ };
124
+ this.inventory(p);
125
+ return this.save(p);
126
+ }
127
+ update(id, raw) {
128
+ this.idle(id);
129
+ const input = parse(UpdateProject, raw),
130
+ p = this.get(id);
131
+ this.revision(p, input.revision);
132
+ if (input.name !== undefined) p.name = input.name;
133
+ if (input.scope !== undefined && p.scope !== input.scope) {
134
+ p.scope = input.scope;
135
+ this.inventory(p);
136
+ }
137
+ if (input.config) {
138
+ const config = resolveConfig(input.config);
139
+ if (Object.entries(config).some(([key, value]) => value !== p.config[key])) {
140
+ p.config = config;
141
+ this.invalidate(p, 'ingest');
142
+ }
143
+ }
144
+ this.audit(p, 'project.updated', 'Project settings or scope updated.');
145
+ return this.save(p);
146
+ }
147
+ remove(id) {
148
+ this.idle(id);
149
+ this.store.remove(id);
150
+ this.events.emit('change', id);
151
+ }
152
+ async addSource(id, input, replaceId = null) {
153
+ this.idle(id);
154
+ const p = this.get(id);
155
+ insist(replaceId || p.sources.length < 100, 'A project supports at most 100 sources.');
156
+ if (replaceId)
157
+ insist(
158
+ p.sources.some((s) => s.id === replaceId),
159
+ 'Source not found.',
160
+ 404,
161
+ );
162
+ const controller = new AbortController();
163
+ const task = (async () => {
164
+ const source = await ingest(input, {
165
+ sourceId: replaceId || randomUUID(),
166
+ signal: controller.signal,
167
+ });
168
+ return this.saveSource(p, source, replaceId);
169
+ })();
170
+ this.active.set(id, { controller, task });
171
+ try {
172
+ return await task;
173
+ } finally {
174
+ this.active.delete(id);
175
+ }
176
+ }
177
+ async addSources(id, raw) {
178
+ this.idle(id);
179
+ const inputs = parse(z.array(SourceInput).min(1).max(100), raw);
180
+ const p = this.get(id);
181
+ insist(p.sources.length + inputs.length <= 100, 'A project supports at most 100 sources.');
182
+ const controller = new AbortController();
183
+ const task = Promise.resolve().then(async () => {
184
+ for (const input of inputs) {
185
+ controller.signal.throwIfAborted();
186
+ const source = await ingest(input, { signal: controller.signal });
187
+ this.prepareSource(p, source, null);
188
+ }
189
+ controller.signal.throwIfAborted();
190
+ return this.save(p);
191
+ });
192
+ this.active.set(id, { controller, task });
193
+ try {
194
+ return await task;
195
+ } finally {
196
+ this.active.delete(id);
197
+ }
198
+ }
199
+ saveSource(p, source, replaceId) {
200
+ return this.save(this.prepareSource(p, source, replaceId));
201
+ }
202
+ prepareSource(p, source, replaceId) {
203
+ const sanitized = JSON.parse(this.providers.redact(JSON.stringify(source)));
204
+ for (const file of sanitized.files) file.lines = file.text.split('\n').length;
205
+ const previous = p.sources.find((s) => s.id === replaceId);
206
+ const unchanged =
207
+ previous?.hash === source.hash &&
208
+ previous.files.every((file, i) => file.text === sanitized.files[i]?.text);
209
+ p.sources = previous
210
+ ? p.sources.map((s) => (s.id === replaceId ? sanitized : s))
211
+ : [...p.sources, sanitized];
212
+ insist(
213
+ p.sources.flatMap((s) => s.files).length <= LIMITS.projectFiles,
214
+ 'Project exceeds the 2000 file limit. Narrow the source scope.',
215
+ );
216
+ insist(
217
+ p.sources.flatMap((s) => s.files).reduce((n, f) => n + f.text.length, 0) <=
218
+ LIMITS.projectChars,
219
+ 'Project evidence exceeds 32 MiB of text. Narrow the source scope.',
220
+ );
221
+ if (!unchanged) this.inventory(p);
222
+ this.audit(p, unchanged ? 'sources.checked' : 'sources.changed', sanitized.label);
223
+ return p;
224
+ }
225
+ async syncSource(id, sourceId) {
226
+ const source = this.get(id).sources.find((s) => s.id === sourceId);
227
+ insist(source, 'Source not found.', 404);
228
+ insist(
229
+ ['local', 'git', 'url'].includes(source.kind),
230
+ 'Replace text or synced-file sources with PUT /sources/:id.',
231
+ );
232
+ return this.addSource(
233
+ id,
234
+ {
235
+ kind: source.kind,
236
+ label: source.label,
237
+ ...(source.kind === 'local' ? { path: source.locator } : { url: source.locator }),
238
+ },
239
+ sourceId,
240
+ );
241
+ }
242
+ removeSource(id, sourceId) {
243
+ this.idle(id);
244
+ const p = this.get(id);
245
+ insist(
246
+ p.sources.some((s) => s.id === sourceId),
247
+ 'Source not found.',
248
+ 404,
249
+ );
250
+ p.sources = p.sources.filter((s) => s.id !== sourceId);
251
+ this.inventory(p);
252
+ this.audit(p, 'sources.removed', sourceId);
253
+ return this.save(p);
254
+ }
255
+ editArtifact(id, phase, input) {
256
+ this.idle(id);
257
+ parse(PhaseId, phase);
258
+ const p = this.get(id);
259
+ const patch = parse(z.strictObject({ revision: z.int(), data: Schemas[phase] }), input);
260
+ this.revision(p, patch.revision);
261
+ insist(phase !== 'scope', 'Edit scope through the project settings.');
262
+ insist(p.artifacts[phase], 'Generate this phase before editing.', 409);
263
+ const data = validateArtifact(phase, patch.data, p);
264
+ this.invalidate(p, phase);
265
+ p.artifacts[phase] = artifact(data);
266
+ this.audit(p, 'artifact.edited', phase);
267
+ return this.save(p);
268
+ }
269
+ approve(id, phase, raw) {
270
+ this.idle(id);
271
+ parse(PhaseId, phase);
272
+ const input = parse(Review, raw),
273
+ p = this.get(id);
274
+ this.revision(p, input.revision);
275
+ insist(
276
+ PHASES.find((x) => x.id === phase).gate,
277
+ 'This step has no review gate. The next gate is the TRACE model.',
278
+ 409,
279
+ 'no_review_gate',
280
+ );
281
+ insist(p.artifacts[phase], 'No artifact exists for this phase.', 409);
282
+ for (const prior of enabledPhases(p)) {
283
+ if (prior.id === phase) break;
284
+ insist(
285
+ p.artifacts[prior.id] && (!prior.gate || p.artifacts[prior.id].status === 'approved'),
286
+ `Review ${prior.title} first.`,
287
+ 409,
288
+ 'review_required',
289
+ );
290
+ }
291
+ p.artifacts[phase].status = 'approved';
292
+ p.artifacts[phase].review = { reviewer: input.reviewer, notes: input.notes, at: now() };
293
+ this.audit(p, 'artifact.approved', { phase, ...p.artifacts[phase].review });
294
+ return this.save(p);
295
+ }
296
+ run(id, raw = {}) {
297
+ this.idle(id);
298
+ insist(!this.closed, 'Engine is stopping.', 503);
299
+ const input = parse(RunInput, raw),
300
+ p = this.get(id);
301
+ insist(
302
+ p.sources.length > 0 && p.scope.trim(),
303
+ 'Define a scope and add at least one source before running.',
304
+ );
305
+ insist(
306
+ !input.phase || !needsFullSourceRun(p),
307
+ 'Run the full pipeline to process the complete source and rebuild prerequisites before regenerating one phase.',
308
+ 409,
309
+ 'source_refresh_required',
310
+ );
311
+ this.providers.assertConfigured(p.config.provider);
312
+ if (input.mode === 'full') {
313
+ let rebuildTrees = !p.config.trees || p.config.treeLimit !== 3 || !p.artifacts.trees;
314
+ if (p.artifacts.trees) {
315
+ try {
316
+ validateFullTrees(p.artifacts.trees.data, p);
317
+ } catch (error) {
318
+ if (!(error instanceof AppError)) throw error;
319
+ rebuildTrees = true;
320
+ }
321
+ }
322
+ if (rebuildTrees) this.invalidate(p, 'trees');
323
+ if (p.config.coordination === 'off') this.invalidate(p, 'coordination');
324
+ p.config = {
325
+ ...p.config,
326
+ trees: true,
327
+ treeLimit: 3,
328
+ coordination: p.config.coordination === 'off' ? 'auto' : p.config.coordination,
329
+ };
330
+ this.audit(p, 'pipeline.full', { treeLimit: 3, coordination: p.config.coordination });
331
+ }
332
+ if (input.phase) {
333
+ insist(
334
+ enabledPhases(p).some((x) => x.id === input.phase),
335
+ 'This phase is disabled.',
336
+ );
337
+ for (const prior of enabledPhases(p)) {
338
+ if (prior.id === input.phase) break;
339
+ insist(p.artifacts[prior.id], `Generate ${prior.title} first.`, 409, 'dependency_missing');
340
+ if (input.mode === 'review' && prior.gate)
341
+ insist(
342
+ p.artifacts[prior.id].status === 'approved',
343
+ `Review ${prior.title} first.`,
344
+ 409,
345
+ 'review_required',
346
+ );
347
+ }
348
+ this.invalidate(p, input.phase);
349
+ } else if (!input.resume) this.invalidate(p, 'ingest');
350
+ const run = {
351
+ id: randomUUID(),
352
+ status: 'queued',
353
+ mode: input.mode,
354
+ phase: null,
355
+ createdAt: now(),
356
+ startedAt: null,
357
+ phaseStartedAt: null,
358
+ finishedAt: null,
359
+ error: null,
360
+ events: [],
361
+ lastEventId: 0,
362
+ usage: { inputTokens: 0, outputTokens: 0 },
363
+ };
364
+ p.runs.push(run);
365
+ this.save(p);
366
+ const controller = new AbortController();
367
+ // Schedule after the active slot is reserved, including synchronous fake providers.
368
+ const task = Promise.resolve()
369
+ .then(() => this.execute(id, run.id, input, controller.signal))
370
+ .finally(() => this.active.delete(id));
371
+ this.active.set(id, { controller, task, runId: run.id });
372
+ return structuredClone(run);
373
+ }
374
+ emit(id, runId, type, phase, message, extra = {}) {
375
+ const p = this.get(id),
376
+ run = p.runs.find((r) => r.id === runId);
377
+ const event = { id: ++run.lastEventId, type, at: now(), phase, message, ...extra };
378
+ run.events.push(event);
379
+ this.save(p);
380
+ this.events.emit(runId, event);
381
+ }
382
+ status(id, runId, status, phase = null, error = null, message = null) {
383
+ const p = this.get(id),
384
+ run = p.runs.find((r) => r.id === runId);
385
+ run.status = status;
386
+ if (status === 'running') {
387
+ run.startedAt ||= now();
388
+ if (phase !== run.phase) run.phaseStartedAt = now();
389
+ }
390
+ run.phase = phase;
391
+ run.error = error;
392
+ if (terminal.has(status)) run.finishedAt = now();
393
+ this.save(p);
394
+ this.emit(id, runId, status, phase, error || message || status.replaceAll('_', ' '));
395
+ }
396
+ async execute(id, runId, input, signal) {
397
+ try {
398
+ this.status(id, runId, 'running');
399
+ const incomplete = this.get(id).sources.filter((source) =>
400
+ source.warnings.some((w) => w.includes('excerpt truncated')),
401
+ );
402
+ for (const source of incomplete) {
403
+ insist(
404
+ ['local', 'git', 'url'].includes(source.kind) && source.locator,
405
+ 'This saved snapshot is incomplete. Replace it with the original full source before running TRACE.',
406
+ 409,
407
+ 'source_refresh_required',
408
+ );
409
+ this.status(id, runId, 'running', 'scope');
410
+ this.emit(
411
+ id,
412
+ runId,
413
+ 'source_refresh',
414
+ 'scope',
415
+ `Reading the complete source: ${source.label}`,
416
+ );
417
+ const complete = await ingest(
418
+ {
419
+ kind: source.kind,
420
+ label: source.label,
421
+ ...(source.kind === 'local' ? { path: source.locator } : { url: source.locator }),
422
+ },
423
+ { sourceId: source.id, signal },
424
+ );
425
+ signal.throwIfAborted();
426
+ this.saveSource(this.get(id), complete, source.id);
427
+ }
428
+ const saved = this.get(id);
429
+ if (needsFullSourceRun(saved)) {
430
+ this.invalidate(saved, 'ingest');
431
+ this.audit(
432
+ saved,
433
+ 'analysis.source_coverage',
434
+ 'Rebuilding analysis made from source excerpts.',
435
+ );
436
+ this.save(saved);
437
+ this.emit(
438
+ id,
439
+ runId,
440
+ 'source_refresh',
441
+ 'scope',
442
+ 'Rebuilding saved analysis to process every source line.',
443
+ );
444
+ }
445
+ for (const phase of PHASES) {
446
+ signal.throwIfAborted();
447
+ let p = this.get(id);
448
+ if (!enabledPhases(p).some((x) => x.id === phase.id)) {
449
+ this.emit(id, runId, 'skipped', phase.id, 'Optional phase disabled or not applicable.');
450
+ continue;
451
+ }
452
+ if (input.phase && phase.id !== input.phase) continue;
453
+ if (!p.artifacts[phase.id]) {
454
+ this.status(id, runId, 'running', phase.id);
455
+ const deep = ['stride', 'coordination'].includes(phase.id);
456
+ const batches = generationSources(phase.id, p);
457
+ const usage = { inputTokens: 0, outputTokens: 0 };
458
+ const passes = [];
459
+ let result, data;
460
+ for (const [batchIndex, sources] of batches.entries()) {
461
+ const prompt = promptFor(phase.id, p, {
462
+ full: input.mode === 'full',
463
+ sources,
464
+ previousDraft: data,
465
+ batch: { number: batchIndex + 1, total: batches.length },
466
+ });
467
+ const context = JSON.parse(prompt.user);
468
+ let evidenceCorrections = [],
469
+ coverageCorrections = [],
470
+ evidenceWarnings = [],
471
+ referenceCorrections = [],
472
+ referenceWarnings = [],
473
+ retainedFindings = [],
474
+ attempts = 0;
475
+ for (; attempts < 2; attempts++) {
476
+ const batchProgress = {
477
+ provider: p.config.provider,
478
+ model: deep ? p.config.deepModel : p.config.fastModel,
479
+ attempt: attempts + 1,
480
+ batch: batchIndex + 1,
481
+ batches: batches.length,
482
+ };
483
+ this.emit(
484
+ id,
485
+ runId,
486
+ 'request',
487
+ phase.id,
488
+ `${phase.id === 'model' ? `Reading source batch ${batchIndex + 1}/${batches.length}` : phase.id === 'ingest' ? 'Classifying source inventory' : 'Analysing completed TRACE artifacts'} · waiting for provider response.`,
489
+ batchProgress,
490
+ );
491
+ result = await this.providers.call({
492
+ provider: p.config.provider,
493
+ model: deep ? p.config.deepModel : p.config.fastModel,
494
+ phase: phase.id,
495
+ schema: generationSchema(phase.id, p),
496
+ effort: p.config.effort,
497
+ ...prompt,
498
+ user: JSON.stringify(context),
499
+ signal,
500
+ onProgress: (progress) =>
501
+ this.emit(id, runId, 'progress', phase.id, `Receiving ${phase.title}`, {
502
+ ...progress,
503
+ ...batchProgress,
504
+ }),
505
+ });
506
+ signal.throwIfAborted();
507
+ p = this.get(id);
508
+ const run = p.runs.find((r) => r.id === runId);
509
+ for (const key of ['inputTokens', 'outputTokens']) {
510
+ usage[key] += result.usage[key];
511
+ run.usage[key] += result.usage[key];
512
+ }
513
+ this.save(p);
514
+ this.emit(
515
+ id,
516
+ runId,
517
+ 'validating',
518
+ phase.id,
519
+ 'Validating evidence and references.',
520
+ batchProgress,
521
+ );
522
+ try {
523
+ const continuation = retainContinuation(context.previousDraft, result.data);
524
+ retainedFindings = continuation.retained;
525
+ const resolved = resolveEvidence(phase.id, continuation.data, p);
526
+ evidenceWarnings = deferEvidence(phase.id, resolved.data, p);
527
+ const references = resolveReferences(phase.id, resolved.data, p);
528
+ referenceCorrections = references.corrections;
529
+ referenceWarnings = references.warnings;
530
+ coverageCorrections =
531
+ phase.id === 'stride' ? resolveCoverage(resolved.data, p) : [];
532
+ data = validateArtifact(phase.id, resolved.data, p);
533
+ if (context.previousDraft) validateContinuation(context.previousDraft, data);
534
+ if (phase.id === 'trees' && input.mode === 'full') validateFullTrees(data, p);
535
+ evidenceCorrections = resolved.corrections;
536
+ break;
537
+ } catch (error) {
538
+ if (attempts || !(error instanceof AppError) || error.status !== 422) throw error;
539
+ context.correction = {
540
+ instruction:
541
+ 'Correct the previous artifact to satisfy the schema and evidence/reference checks. Return the entire corrected artifact.',
542
+ validationError: error.message,
543
+ previousArtifact: result.data,
544
+ };
545
+ this.emit(
546
+ id,
547
+ runId,
548
+ 'validation_retry',
549
+ phase.id,
550
+ 'Repairing the output structure once before continuing.',
551
+ { validationError: this.providers.redact(error.message) },
552
+ );
553
+ }
554
+ }
555
+ passes.push({
556
+ attempts: attempts + 1,
557
+ evidenceCorrections,
558
+ coverageCorrections,
559
+ evidenceWarnings,
560
+ referenceCorrections,
561
+ referenceWarnings,
562
+ retainedFindings,
563
+ });
564
+ this.emit(
565
+ id,
566
+ runId,
567
+ 'batch_complete',
568
+ phase.id,
569
+ `${phase.id === 'model' ? `Source batch ${batchIndex + 1}/${batches.length} analysed` : `${phase.title} analysed`}${retainedFindings.length ? `; retained ${retainedFindings.length} earlier finding(s)` : ''}.`,
570
+ { batch: batchIndex + 1, batches: batches.length, retained: retainedFindings.length },
571
+ );
572
+ }
573
+ signal.throwIfAborted();
574
+ p = this.get(id);
575
+ const evidenceWarnings = passes.flatMap((pass) => pass.evidenceWarnings);
576
+ p.artifacts[phase.id] = artifact(data, runId, {
577
+ provider: result.provider,
578
+ model: result.model,
579
+ usage,
580
+ attempts: passes.reduce((total, pass) => total + pass.attempts, 0),
581
+ evidenceCorrections: passes.flatMap((pass) => pass.evidenceCorrections),
582
+ coverageCorrections: passes.flatMap((pass) => pass.coverageCorrections),
583
+ evidenceWarnings,
584
+ referenceCorrections: passes.flatMap((pass) => pass.referenceCorrections),
585
+ referenceWarnings: passes.flatMap((pass) => pass.referenceWarnings),
586
+ retainedFindings: passes.flatMap((pass) => pass.retainedFindings),
587
+ sourceCoverage:
588
+ phase.id === 'model'
589
+ ? {
590
+ complete: true,
591
+ files: p.sources.flatMap((s) => s.files).length,
592
+ characters: p.sources
593
+ .flatMap((s) => s.files)
594
+ .reduce((n, f) => n + f.text.length, 0),
595
+ batches: batches.length,
596
+ }
597
+ : phase.id === 'ingest'
598
+ ? { fromInventory: true }
599
+ : { fromArtifacts: true },
600
+ });
601
+ this.save(p);
602
+ if (evidenceWarnings.length)
603
+ this.emit(
604
+ id,
605
+ runId,
606
+ 'evidence_review',
607
+ phase.id,
608
+ `${evidenceWarnings.length} claim(s) need source review. Saved as unverified assumptions; continuing TRACE.`,
609
+ { count: evidenceWarnings.length },
610
+ );
611
+ const referenceWarnings = passes.flatMap((pass) => pass.referenceWarnings);
612
+ if (referenceWarnings.length)
613
+ this.emit(
614
+ id,
615
+ runId,
616
+ 'reference_review',
617
+ phase.id,
618
+ `${referenceWarnings.length} model mapping(s) need review. Valid links and findings are saved; continuing TRACE.`,
619
+ { count: referenceWarnings.length },
620
+ );
621
+ this.emit(id, runId, 'artifact', phase.id, `${phase.title} ready for review.`);
622
+ } else this.emit(id, runId, 'reused', phase.id, `Using saved ${phase.title}.`);
623
+ p = this.get(id);
624
+ if (input.mode === 'review' && phase.gate && p.artifacts[phase.id].status !== 'approved') {
625
+ this.status(
626
+ id,
627
+ runId,
628
+ 'awaiting_review',
629
+ phase.id,
630
+ null,
631
+ `${phase.title} is ready. Review and approve it to continue.`,
632
+ );
633
+ return;
634
+ }
635
+ }
636
+ // A single-step run completes without a report; do not announce one.
637
+ this.status(
638
+ id,
639
+ runId,
640
+ 'completed',
641
+ null,
642
+ null,
643
+ input.phase
644
+ ? `${PHASES.find((x) => x.id === input.phase).title} is complete.`
645
+ : 'Pipeline complete. The report is ready.',
646
+ );
647
+ } catch (error) {
648
+ if (signal.aborted) this.status(id, runId, 'cancelled');
649
+ else
650
+ this.status(
651
+ id,
652
+ runId,
653
+ 'failed',
654
+ this.get(id).runs.find((r) => r.id === runId).phase,
655
+ error instanceof AppError
656
+ ? this.providers.redact(error.message)
657
+ : 'Analysis failed unexpectedly. Retry the unfinished phase.',
658
+ );
659
+ }
660
+ }
661
+ getRun(id, runId) {
662
+ const run = this.get(id).runs.find((r) => r.id === runId);
663
+ insist(run, 'Run not found.', 404);
664
+ return run;
665
+ }
666
+ async cancel(id, runId) {
667
+ this.getRun(id, runId);
668
+ const active = this.active.get(id);
669
+ if (active?.runId === runId) {
670
+ active.controller.abort();
671
+ await active.task;
672
+ }
673
+ return this.getRun(id, runId);
674
+ }
675
+ export(id) {
676
+ return { format: 'aitm-project', version: 2, project: this.get(id) };
677
+ }
678
+ import(raw) {
679
+ insist(!this.closed, 'Engine is stopping.', 503);
680
+ const envelope = parse(
681
+ z.strictObject({
682
+ format: z.literal('aitm-project'),
683
+ version: z.literal(2),
684
+ project: z.record(z.string(), z.unknown()),
685
+ }),
686
+ raw,
687
+ );
688
+ const old = envelope.project;
689
+ insist(old.schemaVersion === 2, 'Unsupported project schema version.');
690
+ const input = parse(CreateProject, { name: old.name, scope: old.scope, config: old.config });
691
+ input.config = resolveConfig(input.config);
692
+ const sourceSchema = z.strictObject({
693
+ id: z.uuid(),
694
+ kind: z.enum(['local', 'git', 'url', 'text', 'files']),
695
+ label: z.string().min(1).max(300),
696
+ locator: z.string().nullable(),
697
+ commit: z.string().nullable(),
698
+ hash: z.string(),
699
+ collectedAt: z.iso.datetime(),
700
+ files: z
701
+ .array(
702
+ z.strictObject({
703
+ id: z.string().regex(/^file-[a-f0-9]{20}$/),
704
+ path: z.string().max(500),
705
+ hash: z.string(),
706
+ bytes: z.int().nonnegative(),
707
+ text: z.string().max(LIMITS.fileChars),
708
+ lines: z.int().min(1),
709
+ }),
710
+ )
711
+ .min(1)
712
+ .max(LIMITS.files),
713
+ warnings: z.array(z.string().max(2000)).max(100),
714
+ });
715
+ const sources = parse(z.array(sourceSchema).max(100), old.sources);
716
+ const sourceIds = new Set(),
717
+ fileIds = new Set();
718
+ let chars = 0;
719
+ for (const source of sources) {
720
+ insist(!sourceIds.has(source.id), 'Duplicate source ID.');
721
+ sourceIds.add(source.id);
722
+ // Imported projects are portable snapshots; syncing a local path requires re-adding it explicitly.
723
+ source.kind = 'files';
724
+ source.locator = null;
725
+ for (const file of source.files) {
726
+ insist(!fileIds.has(file.id), 'Duplicate file ID.');
727
+ fileIds.add(file.id);
728
+ chars += file.text.length;
729
+ insist(file.lines === file.text.split('\n').length, 'Incorrect source line count.');
730
+ }
731
+ }
732
+ insist(chars <= LIMITS.projectChars, 'Imported evidence exceeds the project size limit.');
733
+ insist(fileIds.size <= LIMITS.projectFiles, 'Imported evidence exceeds the 2000 file limit.');
734
+ const p = {
735
+ schemaVersion: 2,
736
+ id: randomUUID(),
737
+ ...input,
738
+ sources,
739
+ revision: 0,
740
+ createdAt: now(),
741
+ updatedAt: now(),
742
+ artifacts: {},
743
+ runs: [],
744
+ audit: [],
745
+ };
746
+ this.inventory(p);
747
+ for (const phase of PHASES.slice(1))
748
+ if (old.artifacts?.[phase.id]) {
749
+ insist(
750
+ enabledPhases(p).some((x) => x.id === phase.id),
751
+ 'Imported project contains a disabled phase.',
752
+ );
753
+ const prior = enabledPhases(p).slice(
754
+ 0,
755
+ enabledPhases(p).findIndex((x) => x.id === phase.id),
756
+ );
757
+ insist(
758
+ prior.every((x) => p.artifacts[x.id]),
759
+ 'Imported artifact is missing a dependency.',
760
+ );
761
+ p.artifacts[phase.id] = artifact(
762
+ validateArtifact(phase.id, old.artifacts[phase.id].data, p),
763
+ );
764
+ }
765
+ this.audit(
766
+ p,
767
+ 'project.imported',
768
+ 'Portable snapshot imported; review decisions require fresh approval.',
769
+ );
770
+ const serialized = JSON.stringify(p);
771
+ insist(
772
+ this.providers.redact(serialized) === serialized,
773
+ 'Import contains a configured provider credential.',
774
+ );
775
+ return this.save(p);
776
+ }
777
+ async close() {
778
+ this.closed = true;
779
+ for (const active of this.active.values()) active.controller.abort();
780
+ await Promise.allSettled([...this.active.values()].map((a) => a.task));
781
+ await this.store.close();
782
+ }
783
+ }