@resolveio/server-lib 22.3.124 → 22.3.125

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 (34) hide show
  1. package/collections/ai-run.collection.d.ts +3 -0
  2. package/collections/ai-run.collection.js +170 -0
  3. package/collections/ai-run.collection.js.map +1 -0
  4. package/managers/ai-run-evidence.manager.d.ts +36 -0
  5. package/managers/ai-run-evidence.manager.js +377 -0
  6. package/managers/ai-run-evidence.manager.js.map +1 -0
  7. package/managers/openai-usage-ledger.manager.d.ts +1 -0
  8. package/managers/openai-usage-ledger.manager.js +5 -56
  9. package/managers/openai-usage-ledger.manager.js.map +1 -1
  10. package/models/ai-run.model.d.ts +19 -0
  11. package/models/ai-run.model.js +4 -0
  12. package/models/ai-run.model.js.map +1 -0
  13. package/package.json +3 -1
  14. package/public_api.d.ts +7 -0
  15. package/public_api.js +7 -0
  16. package/public_api.js.map +1 -1
  17. package/util/ai-run-evidence-adapters.d.ts +33 -0
  18. package/util/ai-run-evidence-adapters.js +660 -0
  19. package/util/ai-run-evidence-adapters.js.map +1 -0
  20. package/util/ai-run-evidence-dashboard.d.ts +67 -0
  21. package/util/ai-run-evidence-dashboard.js +309 -0
  22. package/util/ai-run-evidence-dashboard.js.map +1 -0
  23. package/util/ai-run-evidence-eval.d.ts +86 -0
  24. package/util/ai-run-evidence-eval.js +854 -0
  25. package/util/ai-run-evidence-eval.js.map +1 -0
  26. package/util/ai-run-evidence.d.ts +212 -0
  27. package/util/ai-run-evidence.js +649 -0
  28. package/util/ai-run-evidence.js.map +1 -0
  29. package/util/ai-runner-qa-tools.d.ts +1 -0
  30. package/util/ai-runner-qa-tools.js +129 -10
  31. package/util/ai-runner-qa-tools.js.map +1 -1
  32. package/util/openai-usage-cost.d.ts +6 -0
  33. package/util/openai-usage-cost.js +92 -0
  34. package/util/openai-usage-cost.js.map +1 -0
@@ -0,0 +1,649 @@
1
+ "use strict";
2
+ var __assign = (this && this.__assign) || function () {
3
+ __assign = Object.assign || function(t) {
4
+ for (var s, i = 1, n = arguments.length; i < n; i++) {
5
+ s = arguments[i];
6
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
7
+ t[p] = s[p];
8
+ }
9
+ return t;
10
+ };
11
+ return __assign.apply(this, arguments);
12
+ };
13
+ var __values = (this && this.__values) || function(o) {
14
+ var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0;
15
+ if (m) return m.call(o);
16
+ if (o && typeof o.length === "number") return {
17
+ next: function () {
18
+ if (o && i >= o.length) o = void 0;
19
+ return { value: o && o[i++], done: !o };
20
+ }
21
+ };
22
+ throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined.");
23
+ };
24
+ var __read = (this && this.__read) || function (o, n) {
25
+ var m = typeof Symbol === "function" && o[Symbol.iterator];
26
+ if (!m) return o;
27
+ var i = m.call(o), r, ar = [], e;
28
+ try {
29
+ while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
30
+ }
31
+ catch (error) { e = { error: error }; }
32
+ finally {
33
+ try {
34
+ if (r && !r.done && (m = i["return"])) m.call(i);
35
+ }
36
+ finally { if (e) throw e.error; }
37
+ }
38
+ return ar;
39
+ };
40
+ var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
41
+ if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
42
+ if (ar || !(i in from)) {
43
+ if (!ar) ar = Array.prototype.slice.call(from, 0, i);
44
+ ar[i] = from[i];
45
+ }
46
+ }
47
+ return to.concat(ar || Array.prototype.slice.call(from));
48
+ };
49
+ Object.defineProperty(exports, "__esModule", { value: true });
50
+ exports.isCumulativeCodexUsageEntry = isCumulativeCodexUsageEntry;
51
+ exports.resolveOpenAIUsageThreadKey = resolveOpenAIUsageThreadKey;
52
+ exports.normalizeOpenAIUsageRowsForCosting = normalizeOpenAIUsageRowsForCosting;
53
+ exports.buildAIQaRun = buildAIQaRun;
54
+ exports.classifyAIRunOutcome = classifyAIRunOutcome;
55
+ exports.buildAIRun = buildAIRun;
56
+ exports.buildAIRunCost = buildAIRunCost;
57
+ exports.redactAIRunTrainingExample = redactAIRunTrainingExample;
58
+ function isoNow(value) {
59
+ if (value instanceof Date) {
60
+ return value.toISOString();
61
+ }
62
+ var parsed = value ? new Date(value) : new Date();
63
+ if (Number.isFinite(parsed.getTime())) {
64
+ return parsed.toISOString();
65
+ }
66
+ return new Date().toISOString();
67
+ }
68
+ function cleanText(value, max) {
69
+ if (max === void 0) { max = 1000; }
70
+ return String(value || '').replace(/\s+/g, ' ').trim().slice(0, max);
71
+ }
72
+ function cleanUsageNumber(value) {
73
+ var parsed = Number(value);
74
+ return Number.isFinite(parsed) ? parsed : 0;
75
+ }
76
+ function cleanUsageDate(value) {
77
+ if (!value) {
78
+ return undefined;
79
+ }
80
+ var date = value instanceof Date ? value : new Date(value);
81
+ return Number.isFinite(date.getTime()) ? date : undefined;
82
+ }
83
+ function isCumulativeCodexUsageEntry(entry) {
84
+ return cleanText(entry === null || entry === void 0 ? void 0 : entry.category, 180).toLowerCase().startsWith('ai-dashboard-codex:');
85
+ }
86
+ function resolveOpenAIUsageThreadKey(entry) {
87
+ var _a, _b;
88
+ var conversationId = cleanText((_a = entry === null || entry === void 0 ? void 0 : entry.id_conversation) !== null && _a !== void 0 ? _a : entry === null || entry === void 0 ? void 0 : entry.idConversation, 240);
89
+ if (conversationId) {
90
+ return conversationId;
91
+ }
92
+ return cleanText((_b = entry === null || entry === void 0 ? void 0 : entry.id_request) !== null && _b !== void 0 ? _b : entry === null || entry === void 0 ? void 0 : entry.idRequest, 240);
93
+ }
94
+ function normalizeOpenAIUsageRowsForCosting(rows) {
95
+ if (rows === void 0) { rows = []; }
96
+ if (!Array.isArray(rows) || !rows.length) {
97
+ return [];
98
+ }
99
+ var sortedRows = rows
100
+ .map(function (row, index) { return (__assign(__assign({}, row), { _sortIndex: index })); })
101
+ .sort(function (a, b) {
102
+ var _a, _b, _c, _d, _e, _f;
103
+ var timeA = ((_a = cleanUsageDate(a.timestamp)) === null || _a === void 0 ? void 0 : _a.getTime()) || 0;
104
+ var timeB = ((_b = cleanUsageDate(b.timestamp)) === null || _b === void 0 ? void 0 : _b.getTime()) || 0;
105
+ if (timeA !== timeB) {
106
+ return timeA - timeB;
107
+ }
108
+ var requestCompare = cleanText((_c = a.id_request) !== null && _c !== void 0 ? _c : a.idRequest, 240)
109
+ .localeCompare(cleanText((_d = b.id_request) !== null && _d !== void 0 ? _d : b.idRequest, 240));
110
+ if (requestCompare) {
111
+ return requestCompare;
112
+ }
113
+ var conversationCompare = cleanText((_e = a.id_conversation) !== null && _e !== void 0 ? _e : a.idConversation, 240)
114
+ .localeCompare(cleanText((_f = b.id_conversation) !== null && _f !== void 0 ? _f : b.idConversation, 240));
115
+ if (conversationCompare) {
116
+ return conversationCompare;
117
+ }
118
+ return cleanUsageNumber(a._sortIndex) - cleanUsageNumber(b._sortIndex);
119
+ });
120
+ var previousByThread = new Map();
121
+ return sortedRows.map(function (row) {
122
+ var _a, _b, _c, _d, _e, _f;
123
+ var inputTokens = cleanUsageNumber((_a = row.input_tokens) !== null && _a !== void 0 ? _a : row.inputTokens);
124
+ var cachedInputTokens = cleanUsageNumber((_b = row.cached_input_tokens) !== null && _b !== void 0 ? _b : row.cachedInputTokens);
125
+ var outputTokens = cleanUsageNumber((_c = row.output_tokens) !== null && _c !== void 0 ? _c : row.outputTokens);
126
+ var totalTokens = cleanUsageNumber((_e = (_d = row.total_tokens) !== null && _d !== void 0 ? _d : row.totalTokens) !== null && _e !== void 0 ? _e : (inputTokens + outputTokens));
127
+ var estimatedUsd = cleanUsageNumber((_f = row.cost_estimate) !== null && _f !== void 0 ? _f : row.estimatedUsd);
128
+ var threadKey = isCumulativeCodexUsageEntry(row) ? resolveOpenAIUsageThreadKey(row) : '';
129
+ var normalizedInputTokens = inputTokens;
130
+ var normalizedCachedInputTokens = cachedInputTokens;
131
+ var normalizedOutputTokens = outputTokens;
132
+ var normalizedTotalTokens = totalTokens;
133
+ var normalizedEstimatedUsd = estimatedUsd;
134
+ if (threadKey) {
135
+ var previous = previousByThread.get(threadKey);
136
+ if (previous
137
+ && inputTokens >= previous.inputTokens
138
+ && cachedInputTokens >= previous.cachedInputTokens
139
+ && outputTokens >= previous.outputTokens
140
+ && totalTokens >= previous.totalTokens
141
+ && estimatedUsd >= previous.estimatedUsd) {
142
+ normalizedInputTokens = Math.max(0, inputTokens - previous.inputTokens);
143
+ normalizedCachedInputTokens = Math.max(0, cachedInputTokens - previous.cachedInputTokens);
144
+ normalizedOutputTokens = Math.max(0, outputTokens - previous.outputTokens);
145
+ normalizedTotalTokens = Math.max(0, totalTokens - previous.totalTokens);
146
+ normalizedEstimatedUsd = Math.max(0, estimatedUsd - previous.estimatedUsd);
147
+ }
148
+ previousByThread.set(threadKey, {
149
+ inputTokens: inputTokens,
150
+ cachedInputTokens: cachedInputTokens,
151
+ outputTokens: outputTokens,
152
+ totalTokens: totalTokens,
153
+ estimatedUsd: estimatedUsd
154
+ });
155
+ }
156
+ var resolvedTotalTokens = normalizedTotalTokens || (normalizedInputTokens + normalizedOutputTokens);
157
+ var resolvedEstimatedUsd = Number(normalizedEstimatedUsd.toFixed(6));
158
+ return __assign(__assign({}, row), { input_tokens: normalizedInputTokens, inputTokens: normalizedInputTokens, cached_input_tokens: normalizedCachedInputTokens, cachedInputTokens: normalizedCachedInputTokens, output_tokens: normalizedOutputTokens, outputTokens: normalizedOutputTokens, total_tokens: resolvedTotalTokens, totalTokens: resolvedTotalTokens, cost_estimate: resolvedEstimatedUsd, estimatedUsd: resolvedEstimatedUsd });
159
+ });
160
+ }
161
+ function cleanList(values, limit, max) {
162
+ var e_1, _a;
163
+ if (limit === void 0) { limit = 20; }
164
+ if (max === void 0) { max = 500; }
165
+ if (!Array.isArray(values)) {
166
+ return [];
167
+ }
168
+ var result = [];
169
+ try {
170
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
171
+ var value = values_1_1.value;
172
+ var normalized = cleanText(value, max);
173
+ if (normalized && !result.includes(normalized)) {
174
+ result.push(normalized);
175
+ }
176
+ if (result.length >= limit) {
177
+ break;
178
+ }
179
+ }
180
+ }
181
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
182
+ finally {
183
+ try {
184
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
185
+ }
186
+ finally { if (e_1) throw e_1.error; }
187
+ }
188
+ return result;
189
+ }
190
+ function normalizeCheckStatus(value) {
191
+ var normalized = cleanText(value, 40).toLowerCase().replace(/[_\s-]+/g, '_');
192
+ if (normalized === 'passed' || normalized === 'ok' || normalized === 'ready') {
193
+ return 'pass';
194
+ }
195
+ if (normalized === 'failed' || normalized === 'error' || normalized === 'fail') {
196
+ return 'fail';
197
+ }
198
+ if (normalized === 'blocked' || normalized === 'dependency_blocked') {
199
+ return 'blocked';
200
+ }
201
+ if (normalized === 'warning') {
202
+ return 'warn';
203
+ }
204
+ if (normalized === 'skipped' || normalized === 'not_applicable') {
205
+ return 'skipped';
206
+ }
207
+ return normalized === 'pass' || normalized === 'warn' ? normalized : 'unknown';
208
+ }
209
+ function normalizeCompileStatus(value) {
210
+ var normalized = cleanText(value, 40).toLowerCase().replace(/[_\s-]+/g, '_');
211
+ if (normalized === 'passed' || normalized === 'ok') {
212
+ return 'pass';
213
+ }
214
+ if (normalized === 'failed' || normalized === 'error') {
215
+ return 'fail';
216
+ }
217
+ if (normalized === 'blocked') {
218
+ return 'blocked';
219
+ }
220
+ if (normalized === 'stale' || normalized === 'stale_evidence') {
221
+ return 'stale';
222
+ }
223
+ if (normalized === 'skipped' || normalized === 'not_applicable') {
224
+ return 'skipped';
225
+ }
226
+ return normalized === 'pass' || normalized === 'fail' ? normalized : 'unknown';
227
+ }
228
+ function makeGate(key, label, status, reason, evidenceRefs, now, metadata) {
229
+ if (evidenceRefs === void 0) { evidenceRefs = []; }
230
+ return __assign({ key: key, label: label, status: status, reason: cleanText(reason, 1400), evidenceRefs: cleanList(evidenceRefs, 20, 500), recordedAt: isoNow(now) }, (metadata ? { metadata: metadata } : {}));
231
+ }
232
+ function failedOrBlocked(status) {
233
+ return status === 'fail' || status === 'blocked';
234
+ }
235
+ function passed(status) {
236
+ return status === 'pass';
237
+ }
238
+ function normalizeInfraChecks(values) {
239
+ return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { name: cleanText(entry === null || entry === void 0 ? void 0 : entry.name, 120) || 'infra_check', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000), path: cleanText(entry === null || entry === void 0 ? void 0 : entry.path, 500) })); });
240
+ }
241
+ function normalizeRouteProbes(values) {
242
+ return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { route: cleanText(entry === null || entry === void 0 ? void 0 : entry.route, 500) || '/', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), screenshot: cleanText(entry === null || entry === void 0 ? void 0 : entry.screenshot, 500), caption: cleanText(entry === null || entry === void 0 ? void 0 : entry.caption, 1000), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000), consoleErrors: cleanList(entry === null || entry === void 0 ? void 0 : entry.consoleErrors, 30, 500), networkErrors: cleanList(entry === null || entry === void 0 ? void 0 : entry.networkErrors, 30, 500) })); });
243
+ }
244
+ function normalizeBusinessAssertions(values) {
245
+ return (Array.isArray(values) ? values : []).map(function (entry) { return (__assign(__assign({}, entry), { assertion: cleanText(entry === null || entry === void 0 ? void 0 : entry.assertion, 1000) || 'business assertion', status: normalizeCheckStatus(entry === null || entry === void 0 ? void 0 : entry.status), workflow: cleanText(entry === null || entry === void 0 ? void 0 : entry.workflow, 400), route: cleanText(entry === null || entry === void 0 ? void 0 : entry.route, 500), action: cleanText(entry === null || entry === void 0 ? void 0 : entry.action, 500), expected: cleanText(entry === null || entry === void 0 ? void 0 : entry.expected, 1000), observed: cleanText(entry === null || entry === void 0 ? void 0 : entry.observed, 1000), dataProof: cleanText(entry === null || entry === void 0 ? void 0 : entry.dataProof, 1400), artifactPaths: cleanList(entry === null || entry === void 0 ? void 0 : entry.artifactPaths, 30, 500), message: cleanText(entry === null || entry === void 0 ? void 0 : entry.message, 1000) })); });
246
+ }
247
+ function collectBusinessAssertionArtifactPaths(assertions) {
248
+ var e_2, _a, e_3, _b;
249
+ var paths = [];
250
+ try {
251
+ for (var assertions_1 = __values(assertions), assertions_1_1 = assertions_1.next(); !assertions_1_1.done; assertions_1_1 = assertions_1.next()) {
252
+ var assertion = assertions_1_1.value;
253
+ try {
254
+ for (var _c = (e_3 = void 0, __values(assertion.artifactPaths || [])), _d = _c.next(); !_d.done; _d = _c.next()) {
255
+ var artifactPath = _d.value;
256
+ if (artifactPath && !paths.includes(artifactPath)) {
257
+ paths.push(artifactPath);
258
+ }
259
+ }
260
+ }
261
+ catch (e_3_1) { e_3 = { error: e_3_1 }; }
262
+ finally {
263
+ try {
264
+ if (_d && !_d.done && (_b = _c.return)) _b.call(_c);
265
+ }
266
+ finally { if (e_3) throw e_3.error; }
267
+ }
268
+ }
269
+ }
270
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
271
+ finally {
272
+ try {
273
+ if (assertions_1_1 && !assertions_1_1.done && (_a = assertions_1.return)) _a.call(assertions_1);
274
+ }
275
+ finally { if (e_2) throw e_2.error; }
276
+ }
277
+ return paths;
278
+ }
279
+ function buildAIQaRun(input) {
280
+ if (input === void 0) { input = {}; }
281
+ var now = isoNow(input.now);
282
+ var infraChecks = normalizeInfraChecks(input.infraChecks);
283
+ var compile = input.compile
284
+ ? __assign(__assign({}, input.compile), { status: normalizeCompileStatus(input.compile.status), command: cleanText(input.compile.command, 500), artifactPath: cleanText(input.compile.artifactPath, 500), message: cleanText(input.compile.message, 1000) }) : undefined;
285
+ var routeProbes = normalizeRouteProbes(input.routeProbes);
286
+ var businessAssertions = normalizeBusinessAssertions(input.businessAssertions);
287
+ var artifacts = Array.isArray(input.artifacts) ? input.artifacts : [];
288
+ var gateResults = [];
289
+ var failedInfra = infraChecks.filter(function (check) { return failedOrBlocked(check.status); });
290
+ if (failedInfra.length) {
291
+ gateResults.push(makeGate('qa_infra', 'QA infrastructure', 'blocked', "QA infrastructure failed before model/business validation: ".concat(failedInfra.map(function (check) { return "".concat(check.name, ": ").concat(check.message || check.status); }).join('; ')), failedInfra.map(function (check) { return check.path || ''; }).filter(Boolean), now, { failed_checks: failedInfra.map(function (check) { return check.name; }) }));
292
+ return { outcome: 'infra_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
293
+ }
294
+ if (infraChecks.length) {
295
+ gateResults.push(makeGate('qa_infra', 'QA infrastructure', 'pass', 'QA infrastructure preflight checks passed.', [], now));
296
+ }
297
+ if (compile && (failedOrBlocked(compile.status) || compile.status === 'stale' || compile.staleEvidence === true)) {
298
+ gateResults.push(makeGate('qa_compile', 'Compile/build', 'fail', compile.status === 'stale' || compile.staleEvidence === true
299
+ ? 'Compile/build evidence is stale and cannot be used for acceptance.'
300
+ : (compile.message || 'Compile/build failed before browser QA.'), compile.artifactPath ? [compile.artifactPath] : [], now, { command: compile.command || '' }));
301
+ return { outcome: 'compile_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
302
+ }
303
+ if (compile && passed(compile.status)) {
304
+ gateResults.push(makeGate('qa_compile', 'Compile/build', 'pass', 'Compile/build evidence passed.', compile.artifactPath ? [compile.artifactPath] : [], now));
305
+ }
306
+ var failedRouteProbes = routeProbes.filter(function (probe) { return failedOrBlocked(probe.status) || probe.shellOnly === true; });
307
+ if (failedRouteProbes.length) {
308
+ gateResults.push(makeGate('qa_route_probe', 'Browser route probe', 'fail', "Browser route probe failed or showed shell-only UI: ".concat(failedRouteProbes.map(function (probe) { return "".concat(probe.route, ": ").concat(probe.message || probe.caption || probe.status); }).join('; ')), failedRouteProbes.map(function (probe) { return probe.screenshot || ''; }).filter(Boolean), now));
309
+ return { outcome: 'route_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
310
+ }
311
+ if (routeProbes.some(function (probe) { return passed(probe.status); })) {
312
+ gateResults.push(makeGate('qa_route_probe', 'Browser route probe', 'pass', 'Browser route reached authenticated application content. This is not business acceptance by itself.', routeProbes.map(function (probe) { return probe.screenshot || ''; }).filter(Boolean), now));
313
+ }
314
+ var failedBusinessAssertions = businessAssertions.filter(function (assertion) { return failedOrBlocked(assertion.status); });
315
+ if (failedBusinessAssertions.length) {
316
+ gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'fail', "Issue-specific workflow assertion failed: ".concat(failedBusinessAssertions.map(function (assertion) { return assertion.message || assertion.observed || assertion.assertion; }).join('; ')), collectBusinessAssertionArtifactPaths(failedBusinessAssertions), now));
317
+ return { outcome: 'business_assertion_failed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
318
+ }
319
+ var passedBusinessAssertions = businessAssertions.filter(function (assertion) { return passed(assertion.status); });
320
+ if (passedBusinessAssertions.length) {
321
+ gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'pass', 'At least one issue-specific workflow/data assertion passed.', collectBusinessAssertionArtifactPaths(passedBusinessAssertions), now, { passed_assertions: passedBusinessAssertions.map(function (assertion) { return assertion.assertion; }) }));
322
+ return { outcome: 'business_assertion_passed', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
323
+ }
324
+ if (routeProbes.some(function (probe) { return passed(probe.status); })) {
325
+ gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'blocked', 'Browser route loaded, but no issue-specific business assertion passed. Route-only proof cannot accept the run.', [], now));
326
+ return { outcome: 'route_only_pass', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
327
+ }
328
+ gateResults.push(makeGate('qa_business_assertion', 'Business assertion', 'blocked', 'No issue-specific QA assertion was recorded.', [], now));
329
+ return { outcome: 'incomplete', infraChecks: infraChecks, compile: compile, routeProbes: routeProbes, businessAssertions: businessAssertions, artifacts: artifacts, gateResults: gateResults, updatedAt: now };
330
+ }
331
+ function normalizeQaRun(input) {
332
+ if (!input) {
333
+ return undefined;
334
+ }
335
+ if (input.outcome && Array.isArray(input.gateResults)) {
336
+ return input;
337
+ }
338
+ return buildAIQaRun(input);
339
+ }
340
+ function statusLooksFailed(value) {
341
+ var normalized = cleanText(value, 120).toLowerCase();
342
+ return !!normalized && /(fail|failed|error|blocked|missing|empty|stale|skipped|not ready|not_ready|could not|cannot)/i.test(normalized);
343
+ }
344
+ function statusLooksPassed(value) {
345
+ var normalized = cleanText(value, 120).toLowerCase();
346
+ return !!normalized && /(pass|passed|success|complete|completed|ready|published|deployed|live|merged)/i.test(normalized);
347
+ }
348
+ function addGateOnce(gates, gate) {
349
+ if (gates.some(function (entry) { return entry.key === gate.key && entry.status === gate.status && entry.reason === gate.reason; })) {
350
+ return;
351
+ }
352
+ gates.push(gate);
353
+ }
354
+ function classifyAIRunOutcome(input) {
355
+ var e_4, _a;
356
+ if (input === void 0) { input = {}; }
357
+ var now = isoNow(input.now);
358
+ var gates = Array.isArray(input.gates) ? __spreadArray([], __read(input.gates), false) : [];
359
+ var warnings = [];
360
+ var qa = normalizeQaRun(input.qa);
361
+ if (qa) {
362
+ try {
363
+ for (var _b = __values(qa.gateResults), _c = _b.next(); !_c.done; _c = _b.next()) {
364
+ var gate = _c.value;
365
+ addGateOnce(gates, gate);
366
+ }
367
+ }
368
+ catch (e_4_1) { e_4 = { error: e_4_1 }; }
369
+ finally {
370
+ try {
371
+ if (_c && !_c.done && (_a = _b.return)) _a.call(_b);
372
+ }
373
+ finally { if (e_4) throw e_4.error; }
374
+ }
375
+ }
376
+ if (input.manualHandoff === true) {
377
+ return {
378
+ outcome: 'manual_handoff',
379
+ reason: 'Run requires manual handoff.',
380
+ nextAction: 'Ask a human operator to resolve the blocked run.',
381
+ gates: gates,
382
+ warnings: warnings,
383
+ recordedAt: now
384
+ };
385
+ }
386
+ if (input.stopped === true || /stop|stopped|cancel|cancelled|paused/i.test("".concat(input.status || '', " ").concat(input.phase || ''))) {
387
+ return {
388
+ outcome: 'stopped',
389
+ reason: 'Run was stopped before accepted evidence was recorded.',
390
+ nextAction: 'Resume or restart only if the request is still active.',
391
+ gates: gates,
392
+ warnings: warnings,
393
+ recordedAt: now
394
+ };
395
+ }
396
+ if (input.rejected === true) {
397
+ return {
398
+ outcome: 'rejected',
399
+ reason: 'Run was explicitly rejected.',
400
+ nextAction: 'Start a repair run from the failing evidence.',
401
+ gates: gates,
402
+ warnings: warnings,
403
+ recordedAt: now
404
+ };
405
+ }
406
+ if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'infra_failed') {
407
+ return {
408
+ outcome: 'qa_infra_failed',
409
+ reason: 'QA infrastructure failed before product validation.',
410
+ nextAction: 'Repair QA harness dependencies, ports, browser, Mongo, or startup before another model repair loop.',
411
+ gates: gates,
412
+ warnings: warnings,
413
+ recordedAt: now
414
+ };
415
+ }
416
+ if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'compile_failed') {
417
+ return {
418
+ outcome: 'build_failed',
419
+ reason: 'Compile/build evidence failed or was stale.',
420
+ nextAction: 'Repair compile/build first, then rerun QA from the same failed step.',
421
+ gates: gates,
422
+ warnings: warnings,
423
+ recordedAt: now
424
+ };
425
+ }
426
+ if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'route_failed') {
427
+ return {
428
+ outcome: 'qa_incomplete',
429
+ reason: 'Browser route probe failed before business proof.',
430
+ nextAction: 'Repair route/auth/startup issue and rerun the same browser route probe.',
431
+ gates: gates,
432
+ warnings: warnings,
433
+ recordedAt: now
434
+ };
435
+ }
436
+ if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'route_only_pass' || (qa === null || qa === void 0 ? void 0 : qa.outcome) === 'incomplete') {
437
+ return {
438
+ outcome: input.scorecardPassed === true ? 'false_pass' : 'qa_incomplete',
439
+ reason: input.scorecardPassed === true
440
+ ? 'Scorecard or workflow status passed without issue-specific business assertion proof.'
441
+ : 'QA has not recorded issue-specific business assertion proof.',
442
+ nextAction: 'Add before/action/after workflow proof with screenshot/data assertions before acceptance.',
443
+ gates: gates,
444
+ warnings: warnings,
445
+ recordedAt: now
446
+ };
447
+ }
448
+ if ((qa === null || qa === void 0 ? void 0 : qa.outcome) === 'business_assertion_failed') {
449
+ return {
450
+ outcome: input.terminal === true ? 'rejected' : 'qa_incomplete',
451
+ reason: 'Issue-specific business assertion failed.',
452
+ nextAction: 'Repair the product/data defect and rerun the failing assertion.',
453
+ gates: gates,
454
+ warnings: warnings,
455
+ recordedAt: now
456
+ };
457
+ }
458
+ var hasBusinessPass = (qa === null || qa === void 0 ? void 0 : qa.outcome) === 'business_assertion_passed';
459
+ var scorecardPassed = input.scorecardPassed === true || statusLooksPassed(input.scorecardStatus);
460
+ var releaseBlockers = [];
461
+ if (statusLooksFailed(input.deployStatus)) {
462
+ releaseBlockers.push("deploy=".concat(cleanText(input.deployStatus, 120)));
463
+ }
464
+ if (statusLooksFailed(input.publishStatus)) {
465
+ releaseBlockers.push("publish=".concat(cleanText(input.publishStatus, 120)));
466
+ }
467
+ if (statusLooksFailed(input.sampleDataStatus)) {
468
+ releaseBlockers.push("sample_data=".concat(cleanText(input.sampleDataStatus, 120)));
469
+ }
470
+ if (releaseBlockers.length && (scorecardPassed || hasBusinessPass)) {
471
+ addGateOnce(gates, makeGate('release', 'Release/deploy', 'fail', "Final acceptance is blocked after QA/scorecard because release gates failed: ".concat(releaseBlockers.join(', '), "."), [], now));
472
+ return {
473
+ outcome: 'release_blocked',
474
+ reason: "Release gates failed after QA/scorecard: ".concat(releaseBlockers.join(', '), "."),
475
+ nextAction: 'Repair deploy/publish/sample-data coverage before marking the run accepted.',
476
+ gates: gates,
477
+ warnings: warnings,
478
+ recordedAt: now
479
+ };
480
+ }
481
+ if (scorecardPassed && !hasBusinessPass) {
482
+ warnings.push('scorecard_pass_without_business_assertion');
483
+ addGateOnce(gates, makeGate('business_assertion_required', 'Business assertion', 'blocked', 'Scorecard passed, but no issue-specific business assertion proof was recorded.', [], now));
484
+ return {
485
+ outcome: 'false_pass',
486
+ reason: 'Scorecard-only proof is not acceptance.',
487
+ nextAction: 'Record issue-specific workflow/data proof, then reclassify the run.',
488
+ gates: gates,
489
+ warnings: warnings,
490
+ recordedAt: now
491
+ };
492
+ }
493
+ var statusPhase = "".concat(input.status || '', " ").concat(input.phase || '');
494
+ if ((input.explicitAccepted === true || statusLooksPassed(statusPhase) || scorecardPassed) && hasBusinessPass) {
495
+ return {
496
+ outcome: 'accepted',
497
+ reason: 'Run has terminal success signal and issue-specific business assertion proof.',
498
+ nextAction: 'No repair action required.',
499
+ gates: gates,
500
+ warnings: warnings,
501
+ recordedAt: now
502
+ };
503
+ }
504
+ if (statusLooksFailed(statusPhase)) {
505
+ return {
506
+ outcome: 'rejected',
507
+ reason: 'Run ended with a failure status and no accepted proof.',
508
+ nextAction: 'Classify the failing gate and rerun the smallest repair step.',
509
+ gates: gates,
510
+ warnings: warnings,
511
+ recordedAt: now
512
+ };
513
+ }
514
+ return {
515
+ outcome: 'unknown',
516
+ reason: 'Run does not have enough normalized evidence for a terminal label.',
517
+ nextAction: 'Ingest QA, deploy, assistant, usage, and commit evidence before using this run for training.',
518
+ gates: gates,
519
+ warnings: warnings,
520
+ recordedAt: now
521
+ };
522
+ }
523
+ function buildAIRun(input) {
524
+ var decision = input.outcome
525
+ ? {
526
+ outcome: input.outcome,
527
+ gates: input.gates || [],
528
+ warnings: input.warnings || [],
529
+ nextAction: input.nextAction || '',
530
+ reason: '',
531
+ recordedAt: isoNow(input.now)
532
+ }
533
+ : classifyAIRunOutcome({
534
+ source: input.source,
535
+ status: input.status,
536
+ phase: input.phase,
537
+ qa: input.qa,
538
+ gates: input.gates,
539
+ scorecardPassed: input.scorecardPassed,
540
+ deployStatus: input.deployStatus,
541
+ publishStatus: input.publishStatus,
542
+ sampleDataStatus: input.sampleDataStatus,
543
+ manualHandoff: input.manualHandoff,
544
+ stopped: input.stopped,
545
+ rejected: input.rejected,
546
+ explicitAccepted: input.explicitAccepted,
547
+ terminal: input.terminal,
548
+ now: input.now
549
+ });
550
+ return {
551
+ id: input.id,
552
+ source: input.source || 'unknown',
553
+ sourceIds: input.sourceIds || {},
554
+ title: input.title,
555
+ status: input.status,
556
+ phase: input.phase,
557
+ startedAt: input.startedAt,
558
+ completedAt: input.completedAt,
559
+ outcome: decision.outcome,
560
+ events: Array.isArray(input.events) ? input.events : [],
561
+ gates: decision.gates,
562
+ qa: normalizeQaRun(input.qa),
563
+ cost: input.cost,
564
+ nextAction: decision.nextAction,
565
+ warnings: decision.warnings,
566
+ metadata: input.metadata
567
+ };
568
+ }
569
+ function buildAIRunCost(entries) {
570
+ var e_5, _a, e_6, _b;
571
+ var _c, _d, _e, _f, _g, _h, _j, _k, _l, _m;
572
+ if (entries === void 0) { entries = []; }
573
+ var cost = {
574
+ inputTokens: 0,
575
+ cachedInputTokens: 0,
576
+ outputTokens: 0,
577
+ totalTokens: 0,
578
+ estimatedUsd: 0,
579
+ models: [],
580
+ categories: {}
581
+ };
582
+ try {
583
+ for (var _o = __values(normalizeOpenAIUsageRowsForCosting(entries)), _p = _o.next(); !_p.done; _p = _o.next()) {
584
+ var entry = _p.value;
585
+ var category = cleanText(entry.category, 120) || 'unknown';
586
+ var model = cleanText(entry.model, 120);
587
+ var inputTokens = Number((_d = (_c = entry.input_tokens) !== null && _c !== void 0 ? _c : entry.inputTokens) !== null && _d !== void 0 ? _d : 0) || 0;
588
+ var cachedInputTokens = Number((_f = (_e = entry.cached_input_tokens) !== null && _e !== void 0 ? _e : entry.cachedInputTokens) !== null && _f !== void 0 ? _f : 0) || 0;
589
+ var outputTokens = Number((_h = (_g = entry.output_tokens) !== null && _g !== void 0 ? _g : entry.outputTokens) !== null && _h !== void 0 ? _h : 0) || 0;
590
+ var totalTokens = Number((_k = (_j = entry.total_tokens) !== null && _j !== void 0 ? _j : entry.totalTokens) !== null && _k !== void 0 ? _k : (inputTokens + outputTokens)) || 0;
591
+ var estimatedUsd = Number((_m = (_l = entry.cost_estimate) !== null && _l !== void 0 ? _l : entry.estimatedUsd) !== null && _m !== void 0 ? _m : 0) || 0;
592
+ cost.inputTokens += inputTokens;
593
+ cost.cachedInputTokens += cachedInputTokens;
594
+ cost.outputTokens += outputTokens;
595
+ cost.totalTokens += totalTokens;
596
+ cost.estimatedUsd += estimatedUsd;
597
+ if (model && !cost.models.includes(model)) {
598
+ cost.models.push(model);
599
+ }
600
+ if (!cost.categories[category]) {
601
+ cost.categories[category] = {
602
+ inputTokens: 0,
603
+ cachedInputTokens: 0,
604
+ outputTokens: 0,
605
+ totalTokens: 0,
606
+ estimatedUsd: 0,
607
+ count: 0
608
+ };
609
+ }
610
+ cost.categories[category].inputTokens += inputTokens;
611
+ cost.categories[category].cachedInputTokens += cachedInputTokens;
612
+ cost.categories[category].outputTokens += outputTokens;
613
+ cost.categories[category].totalTokens += totalTokens;
614
+ cost.categories[category].estimatedUsd += estimatedUsd;
615
+ cost.categories[category].count += 1;
616
+ }
617
+ }
618
+ catch (e_5_1) { e_5 = { error: e_5_1 }; }
619
+ finally {
620
+ try {
621
+ if (_p && !_p.done && (_a = _o.return)) _a.call(_o);
622
+ }
623
+ finally { if (e_5) throw e_5.error; }
624
+ }
625
+ cost.estimatedUsd = Number(cost.estimatedUsd.toFixed(6));
626
+ try {
627
+ for (var _q = __values(Object.keys(cost.categories)), _r = _q.next(); !_r.done; _r = _q.next()) {
628
+ var category = _r.value;
629
+ cost.categories[category].estimatedUsd = Number(cost.categories[category].estimatedUsd.toFixed(6));
630
+ }
631
+ }
632
+ catch (e_6_1) { e_6 = { error: e_6_1 }; }
633
+ finally {
634
+ try {
635
+ if (_r && !_r.done && (_b = _q.return)) _b.call(_q);
636
+ }
637
+ finally { if (e_6) throw e_6.error; }
638
+ }
639
+ return cost;
640
+ }
641
+ function redactAIRunTrainingExample(example) {
642
+ var redact = function (value) { return cleanText(value, 5000)
643
+ .replace(/mongodb(?:\+srv)?:\/\/[^\s"'<>]+/ig, '[redacted-mongo-url]')
644
+ .replace(/\b(?:sk|ghp|xoxb|AKIA)[A-Za-z0-9_\-]{12,}\b/g, '[redacted-secret]')
645
+ .replace(/\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z]{2,}\b/ig, '[redacted-email]'); };
646
+ return __assign(__assign({}, example), { inputSummary: redact(example.inputSummary), actionSummary: redact(example.actionSummary), evidence: cleanList(example.evidence, 80, 5000).map(redact) });
647
+ }
648
+
649
+ //# sourceMappingURL=ai-run-evidence.js.map