@memberjunction/record-set-processor 6.2.0-edge.3 → 6.2.0-edge.5

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 (60) hide show
  1. package/README.md +36 -1
  2. package/dist/RecordProcessExecutor.d.ts +29 -15
  3. package/dist/RecordProcessExecutor.d.ts.map +1 -1
  4. package/dist/RecordProcessExecutor.js +59 -62
  5. package/dist/RecordProcessExecutor.js.map +1 -1
  6. package/dist/RecordSetProcessor.d.ts +9 -0
  7. package/dist/RecordSetProcessor.d.ts.map +1 -1
  8. package/dist/RecordSetProcessor.js +146 -76
  9. package/dist/RecordSetProcessor.js.map +1 -1
  10. package/dist/index.d.ts +0 -4
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +0 -4
  13. package/dist/index.js.map +1 -1
  14. package/dist/operations/RecordProcessControlOperations.d.ts.map +1 -1
  15. package/dist/operations/RecordProcessControlOperations.js +9 -7
  16. package/dist/operations/RecordProcessControlOperations.js.map +1 -1
  17. package/dist/processors/ActionRecordProcessor.js +2 -2
  18. package/dist/processors/AgentRecordProcessor.d.ts.map +1 -1
  19. package/dist/processors/AgentRecordProcessor.js +5 -2
  20. package/dist/processors/AgentRecordProcessor.js.map +1 -1
  21. package/dist/processors/FieldRulesProcessor.d.ts +8 -7
  22. package/dist/processors/FieldRulesProcessor.d.ts.map +1 -1
  23. package/dist/processors/FieldRulesProcessor.js +23 -13
  24. package/dist/processors/FieldRulesProcessor.js.map +1 -1
  25. package/dist/processors/WriteBackProcessor.d.ts +70 -2
  26. package/dist/processors/WriteBackProcessor.d.ts.map +1 -1
  27. package/dist/processors/WriteBackProcessor.js +159 -59
  28. package/dist/processors/WriteBackProcessor.js.map +1 -1
  29. package/dist/trackers/GenericProcessRunTracker.d.ts.map +1 -1
  30. package/dist/trackers/GenericProcessRunTracker.js +5 -0
  31. package/dist/trackers/GenericProcessRunTracker.js.map +1 -1
  32. package/dist/watermark/WatermarkService.d.ts +62 -24
  33. package/dist/watermark/WatermarkService.d.ts.map +1 -1
  34. package/dist/watermark/WatermarkService.js +123 -70
  35. package/dist/watermark/WatermarkService.js.map +1 -1
  36. package/dist/writeBack.d.ts +358 -42
  37. package/dist/writeBack.d.ts.map +1 -1
  38. package/dist/writeBack.js +848 -208
  39. package/dist/writeBack.js.map +1 -1
  40. package/package.json +16 -17
  41. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts +0 -92
  42. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.d.ts.map +0 -1
  43. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js +0 -26
  44. package/dist/feature-pipeline-drivers/BaseFeaturePipelineDriver.js.map +0 -1
  45. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts +0 -79
  46. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.d.ts.map +0 -1
  47. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js +0 -257
  48. package/dist/feature-pipeline-drivers/DecisionFeaturePipelineDriver.js.map +0 -1
  49. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts +0 -23
  50. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.d.ts.map +0 -1
  51. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js +0 -85
  52. package/dist/feature-pipeline-drivers/LLMFeaturePipelineDriver.js.map +0 -1
  53. package/dist/processors/FeaturePipelineEscalation.d.ts +0 -155
  54. package/dist/processors/FeaturePipelineEscalation.d.ts.map +0 -1
  55. package/dist/processors/FeaturePipelineEscalation.js +0 -208
  56. package/dist/processors/FeaturePipelineEscalation.js.map +0 -1
  57. package/dist/processors/InferProcessor.d.ts +0 -306
  58. package/dist/processors/InferProcessor.d.ts.map +0 -1
  59. package/dist/processors/InferProcessor.js +0 -1210
  60. package/dist/processors/InferProcessor.js.map +0 -1
@@ -1,1210 +0,0 @@
1
- /**
2
- * @fileoverview Infer processor — for each record, runs an AI Prompt over the record's data and
3
- * returns the structured result as the record's `ResultPayload`. Write-back is NOT done here: the
4
- * `WriteBackProcessor` wrapper (added by `RecordProcessExecutor` when an OutputMapping is set)
5
- * applies the Record Process's OutputMapping uniformly across Action / Agent / Infer work types.
6
- *
7
- * Supports DataFeatureSpec context (EntityDocumentID template rendering with __Parent context,
8
- * QueryID parameterized execution, Field projections), Layer-1 constraint injection, Layer-2
9
- * constraint validation with OnViolation policies, and lifecycle hooks (P1-6). A Decision pipeline
10
- * whose spec sets `Escalation` re-runs its below-floor records through an LLM pipeline
11
- * (see `FeaturePipelineEscalation`).
12
- *
13
- * @module @memberjunction/record-set-processor
14
- */
15
- import { createHash } from 'node:crypto';
16
- import { LogError, LogStatus, Metadata, RunQuery, RunView } from '@memberjunction/core';
17
- import { MJGlobal, UUIDsEqual, Canonicalize, ComputeContentHashAsync, EscapeSQLString, ResolveMappingRef, SafeJSONParse, resolveMappingRef, resolveValueMapping } from '@memberjunction/global';
18
- import { KnowledgeHubMetadataEngine } from '@memberjunction/core-entities';
19
- import { AIEngine } from '@memberjunction/aiengine';
20
- import { FeatureValueCacheService, ResolveConstraint, BuildEntityFieldValueLookup, IsDecisionPipelineType, IsLLMPipelineType, LLM_PIPELINE_TYPE, renderConstraintBlock, validateMaterializationTargets, validateOutputValue, validateSpec, FindOutputByName, } from '@memberjunction/feature-pipelines';
21
- import { EntityDocumentCache, EntityDocumentTemplateParser } from '@memberjunction/entity-documents';
22
- import { BaseFeaturePipelineDriver, } from '../feature-pipeline-drivers/BaseFeaturePipelineDriver.js';
23
- import { LLMFeaturePipelineDriver } from '../feature-pipeline-drivers/LLMFeaturePipelineDriver.js';
24
- import { DescribeEscalationFailure, FeaturePipelineEscalator, } from './FeaturePipelineEscalation.js';
25
- /** Whether a value is a plain JSON object (not null, not an array). */
26
- function isPlainRecord(value) {
27
- return typeof value === 'object' && value !== null && !Array.isArray(value);
28
- }
29
- /**
30
- * Runs an AI Prompt per record and returns its structured output (write-back is the wrapper's job).
31
- * A pipeline whose spec sets `Escalation` computes a whole batch before recording any of it, so its batch
32
- * path does not call {@link ProcessRecord} once per record: an extension that overrides `ProcessRecord`
33
- * does not see those records.
34
- */
35
- export class InferProcessor {
36
- /**
37
- * @param promptID - The `MJ: AI Prompts` ID to run for each record.
38
- * @param inputMapping - Optional mapping shaping the data passed to the prompt (default: `{ record }`).
39
- * @param spec - Optional DataFeatureSpec defining outputs, constraints, and caching policy.
40
- */
41
- constructor(promptID, inputMapping, spec) {
42
- this.promptID = promptID;
43
- this.inputMapping = inputMapping;
44
- this.spec = spec;
45
- /** How many records this processor has escalated. */
46
- this.escalatedRecordCount = 0;
47
- /**
48
- * Whether this processor writes `MJ: Feature Values` history rows. On for every pipeline run. A
49
- * Decision pipeline turns it off on its escalation target, because it records the final answers of
50
- * the records it escalates itself.
51
- */
52
- this.WritesHistory = true;
53
- }
54
- /**
55
- * Builds the processor for an Infer Feature Pipeline from its `MJ: Record Processes` row: parses and
56
- * validates the DataFeatureSpec in `Configuration` (and its materialization targets), and creates the
57
- * spec's `ProcessorExtensionKey` subclass when it names one. `RecordProcessExecutor` builds every
58
- * Infer pipeline this way, and so does a Decision pipeline's escalation to an LLM pipeline.
59
- *
60
- * @param rp - The pipeline's row (WorkType `Infer`).
61
- * @param provider - The provider whose metadata the materialization targets are checked against (default: the global one).
62
- * @throws Error when the row has no PromptID, its Configuration is not valid JSON, its spec or
63
- * materialization targets are invalid, or its ProcessorExtensionKey is not registered.
64
- */
65
- static FromRecordProcess(rp, provider) {
66
- if (!rp.PromptID) {
67
- throw new Error(`Record Process '${rp.Name}': WorkType=Infer requires PromptID`);
68
- }
69
- const inputMapping = rp.InputMapping ? SafeJSONParse(rp.InputMapping) : undefined;
70
- const spec = InferProcessor.parseSpec(rp, provider);
71
- if (spec?.ProcessorExtensionKey) {
72
- const custom = MJGlobal.Instance.ClassFactory.CreateInstance(InferProcessor, spec.ProcessorExtensionKey, rp.PromptID, inputMapping, spec);
73
- if (custom && custom.constructor !== InferProcessor) {
74
- return custom;
75
- }
76
- else {
77
- throw new Error(`Record Process '${rp.Name}': ProcessorExtensionKey '${spec.ProcessorExtensionKey}' not found in ClassFactory`);
78
- }
79
- }
80
- return new InferProcessor(rp.PromptID, inputMapping, spec);
81
- }
82
- /** Parses and validates the DataFeatureSpec in an Infer pipeline row's `Configuration`; undefined when it has none. */
83
- static parseSpec(rp, provider) {
84
- let spec;
85
- if (rp.Configuration && rp.Configuration.trim().length > 0) {
86
- try {
87
- spec = JSON.parse(rp.Configuration);
88
- }
89
- catch (e) {
90
- throw new Error(`Record Process '${rp.Name}': Configuration is invalid JSON: ${e instanceof Error ? e.message : String(e)}`);
91
- }
92
- const issues = validateSpec(spec);
93
- const errors = issues.filter((i) => i.Severity === 'error');
94
- if (errors.length > 0) {
95
- throw new Error(`Record Process '${rp.Name}': invalid DataFeatureSpec in Configuration: ${errors.map((err) => err.Message).join('; ')}`);
96
- }
97
- const targetProvider = provider ?? Metadata.Provider;
98
- if (targetProvider && rp.EntityID) {
99
- const materializationIssues = validateMaterializationTargets(spec, targetProvider, rp.EntityID);
100
- const matErrors = materializationIssues.filter((i) => i.Severity === 'error');
101
- if (matErrors.length > 0) {
102
- throw new Error(`Record Process '${rp.Name}': invalid materialization targets: ${matErrors.map((err) => `${err.Field ? `[${err.Field}] ` : ''}${err.Message} Fix: ${err.FixRecommendation}`).join('; ')}`);
103
- }
104
- }
105
- }
106
- return spec;
107
- }
108
- /** The pipeline's DataFeatureSpec, when it has one. */
109
- get Spec() {
110
- return this.spec;
111
- }
112
- /** The `MJ: AI Prompts` ID this processor runs for each record. */
113
- get PromptID() {
114
- return this.promptID;
115
- }
116
- /** The hash that versions this pipeline's output constraints, as its Dedup Cache and history record it. */
117
- get ConstraintHash() {
118
- return this.computeConstraintHash(this.spec);
119
- }
120
- /**
121
- * How many records this processor has escalated to its spec's `Escalation` pipeline. A processor
122
- * serves one run, so this is the run's count. It counts every record whose answer was escalated,
123
- * including the records that shared a Dedup Cache key with one, and the escalations that failed.
124
- */
125
- get EscalatedRecordCount() {
126
- return this.escalatedRecordCount;
127
- }
128
- async ProcessRecord(record, context, options) {
129
- await this.ensureRecordsLoaded([record], context);
130
- const run = await this.resolveRunState(context);
131
- if ('ErrorMessage' in run) {
132
- return { Status: 'Failed', ErrorMessage: run.ErrorMessage };
133
- }
134
- const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
135
- let keyInfo;
136
- // P1-7c Dedup Cache lookup
137
- if (run.IsCacheable) {
138
- keyInfo =
139
- options?.keyInfo ??
140
- (await FeatureValueCacheService.Instance.computeCacheKey({
141
- keyFields: this.spec?.Caching?.KeyFields,
142
- recordData: this.recordToPlain(record),
143
- }));
144
- if (!options?.skipLookup) {
145
- const cached = await FeatureValueCacheService.Instance.Lookup({
146
- recordProcessID: context.recordProcessID,
147
- scope: this.spec?.Caching?.Scope,
148
- promptID: prompt.ID,
149
- promptVersionHash,
150
- constraintHash,
151
- keyHash: keyInfo.keyHash,
152
- contextUser: context.contextUser,
153
- provider: context.provider,
154
- });
155
- if (cached) {
156
- let cachedPayload = JSON.parse(cached.OutputsJSON);
157
- if (typeof cachedPayload === 'string') {
158
- try {
159
- cachedPayload = JSON.parse(cachedPayload);
160
- }
161
- catch {
162
- // keep as string
163
- }
164
- }
165
- await this.recordFeatureValuesHistory({
166
- record,
167
- context,
168
- payload: cachedPayload,
169
- reasoning: cached.Reasoning,
170
- promptID: prompt.ID,
171
- promptVersionHash,
172
- constraintHash,
173
- aiPromptRunID: cached.AIPromptRunID,
174
- featureValueCacheID: cached.ID,
175
- });
176
- return {
177
- Status: 'Succeeded',
178
- ResultPayload: cachedPayload,
179
- AIPromptRunID: cached.AIPromptRunID ?? undefined,
180
- PromptVersionHash: promptVersionHash,
181
- FeatureValueCacheID: cached.ID,
182
- };
183
- }
184
- }
185
- }
186
- // The pipeline type's driver turns the record's context into its outputs (for LLM: the prompt run and its hooks)
187
- const sample = await this.computeSample({ keyInfo, records: [record] }, context, run);
188
- // A decision below the escalation floor escalates; any other answer is validated and recorded as it is
189
- const [finalized] = await this.finalizeSamples([sample], context, run);
190
- return finalized.Result;
191
- }
192
- /** Runs the driver on a key group's first record, and notes which outputs, if any, are below the escalation floor. */
193
- async computeSample(group, context, run) {
194
- const sample = group.records[0];
195
- const fieldValues = this.buildFieldValuesLookup(context);
196
- const computed = await run.Driver.ComputeOutputs({
197
- Record: sample,
198
- Context: context,
199
- Prompt: run.Prompt,
200
- Spec: this.spec,
201
- Hooks: this.buildComputeHooks(),
202
- FieldValues: fieldValues,
203
- });
204
- return { Group: group, Sample: sample, Computed: computed, BelowFloor: this.belowFloor(computed) };
205
- }
206
- /**
207
- * Finishes a computed sample: a driver failure fails it, a below-floor decision takes its escalation's
208
- * outcome, and any other answer is validated, cached and recorded.
209
- */
210
- async finalizeSample(sample, outcomes, context, run) {
211
- const computed = sample.Computed;
212
- if ('ErrorMessage' in computed) {
213
- return {
214
- Result: {
215
- Status: 'Failed',
216
- ErrorMessage: computed.ErrorMessage,
217
- AIPromptRunID: computed.AIPromptRunID,
218
- },
219
- };
220
- }
221
- if (sample.BelowFloor.length > 0) {
222
- return this.finalizeEscalated(sample, computed, outcomes.get(sample.Sample.RecordID), context, run);
223
- }
224
- const result = await this.finalizeComputed(sample.Sample, context, run, sample.Group.keyInfo, computed);
225
- return { Result: result, History: this.missFanOutHistory(result, context, run) };
226
- }
227
- /**
228
- * Validates a driver's outputs against the constraints (applying each OnViolation policy), stores
229
- * them in the Dedup Cache, and records their history.
230
- */
231
- async finalizeComputed(record, context, run, keyInfo, computed) {
232
- const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
233
- const aiPromptRunID = computed.AIPromptRunID;
234
- const rawResult = computed.RawResult;
235
- // Layer 2: Validate outputs against constraints and apply OnViolation policy
236
- const validationOutcome = await this.validateOutputs(this.spec?.Outputs ?? [], rawResult, record, context);
237
- if (!validationOutcome.valid) {
238
- return {
239
- Status: 'Failed',
240
- ErrorMessage: validationOutcome.errorMessage ?? 'Constraint violation',
241
- AIPromptRunID: aiPromptRunID,
242
- };
243
- }
244
- const confidence = this.confidenceOfKeptValues(computed.Confidence, validationOutcome.replacedOutputs);
245
- let featureValueCacheID;
246
- const reasoning = typeof rawResult === 'object' && rawResult !== null ? rawResult.reasoning : undefined;
247
- // P1-7c Dedup Cache store
248
- if (run.IsCacheable && keyInfo) {
249
- try {
250
- const stored = await FeatureValueCacheService.Instance.Store({
251
- recordProcessID: context.recordProcessID,
252
- scope: this.spec?.Caching?.Scope,
253
- promptID: prompt.ID,
254
- promptVersionHash,
255
- constraintHash,
256
- keyHash: keyInfo.keyHash,
257
- keyDisplay: keyInfo.keyDisplay,
258
- keyJSON: keyInfo.keyJSON,
259
- outputsJSON: JSON.stringify(validationOutcome.payload),
260
- reasoning: reasoning ?? null,
261
- aiPromptRunID: aiPromptRunID ?? null,
262
- ttlSeconds: this.spec?.Caching?.TTLSeconds,
263
- contextUser: context.contextUser,
264
- provider: context.provider,
265
- });
266
- featureValueCacheID = stored.ID;
267
- }
268
- catch (e) {
269
- LogError(`InferProcessor: failed storing cache entry: ${e instanceof Error ? e.message : String(e)}`);
270
- }
271
- }
272
- // P1-7c History tracking in MJ: Feature Values
273
- await this.recordFeatureValuesHistory({
274
- record,
275
- context,
276
- payload: validationOutcome.payload,
277
- reasoning,
278
- promptID: prompt.ID,
279
- promptVersionHash,
280
- constraintHash,
281
- aiPromptRunID,
282
- featureValueCacheID,
283
- ...(confidence ? { outputConfidence: confidence } : {}),
284
- });
285
- return {
286
- Status: 'Succeeded',
287
- ResultPayload: validationOutcome.payload,
288
- AIPromptRunID: aiPromptRunID,
289
- PromptVersionHash: promptVersionHash,
290
- FeatureValueCacheID: featureValueCacheID,
291
- ...(confidence ? { Confidence: confidence } : {}),
292
- };
293
- }
294
- /**
295
- * Two-phase batch execution (P1-7c). Resolves distinct keys across the batch first,
296
- * checks the dedup cache in one batch query, executes LLM prompts ONCE per distinct key,
297
- * and fans results back across all matching rows.
298
- */
299
- async ProcessBatch(records, context) {
300
- await this.ensureRecordsLoaded(records, context);
301
- const results = new Map();
302
- if (!this.spec?.Caching?.Cacheable || records.length === 0) {
303
- if (this.escalator && records.length > 0) {
304
- return this.processUncachedBatchWithEscalation(records, context);
305
- }
306
- for (const r of records) {
307
- results.set(r.RecordID, await this.ProcessRecord(r, context));
308
- }
309
- return results;
310
- }
311
- // Resolve before the cache phases, so a type that cannot run fails every record rather than serving cache hits
312
- const run = await this.resolveRunState(context);
313
- if ('ErrorMessage' in run) {
314
- return this.failEvery(records, run.ErrorMessage, results);
315
- }
316
- const { Prompt: prompt, PromptVersionHash: promptVersionHash, ConstraintHash: constraintHash } = run;
317
- // Phase 1: Compute distinct cache keys across the batch
318
- const keyGroupMap = new Map();
319
- for (const record of records) {
320
- const recordData = this.recordToPlain(record);
321
- const keyInfo = await FeatureValueCacheService.Instance.computeCacheKey({
322
- keyFields: this.spec.Caching.KeyFields,
323
- recordData,
324
- });
325
- let group = keyGroupMap.get(keyInfo.keyHash);
326
- if (!group) {
327
- group = { keyInfo, records: [] };
328
- keyGroupMap.set(keyInfo.keyHash, group);
329
- }
330
- group.records.push(record);
331
- }
332
- // Phase 2: Batch lookup existing cache entries for all distinct keys
333
- const distinctKeyHashes = Array.from(keyGroupMap.keys());
334
- const cacheMap = await FeatureValueCacheService.Instance.BatchLookup({
335
- recordProcessID: context.recordProcessID,
336
- scope: this.spec.Caching.Scope,
337
- promptID: prompt.ID,
338
- promptVersionHash,
339
- constraintHash,
340
- keyHashes: distinctKeyHashes,
341
- contextUser: context.contextUser,
342
- provider: context.provider,
343
- });
344
- // Phase 3: Fan out hits; execute misses ONCE per distinct key and fan out
345
- const escalatingMisses = [];
346
- for (const [keyHash, group] of keyGroupMap.entries()) {
347
- const cached = cacheMap.get(keyHash);
348
- if (cached) {
349
- // CACHE HIT: fan out immediately to all matching records without calling LLM!
350
- let cachedPayload = JSON.parse(cached.OutputsJSON);
351
- if (typeof cachedPayload === 'string') {
352
- try {
353
- cachedPayload = JSON.parse(cachedPayload);
354
- }
355
- catch {
356
- // keep as string
357
- }
358
- }
359
- for (const rec of group.records) {
360
- await this.recordFeatureValuesHistory({
361
- record: rec,
362
- context,
363
- payload: cachedPayload,
364
- reasoning: cached.Reasoning,
365
- promptID: prompt.ID,
366
- promptVersionHash,
367
- constraintHash,
368
- aiPromptRunID: cached.AIPromptRunID,
369
- featureValueCacheID: cached.ID,
370
- });
371
- results.set(rec.RecordID, {
372
- Status: 'Succeeded',
373
- ResultPayload: cachedPayload,
374
- AIPromptRunID: cached.AIPromptRunID ?? undefined,
375
- PromptVersionHash: promptVersionHash,
376
- FeatureValueCacheID: cached.ID,
377
- });
378
- }
379
- }
380
- else if (this.escalator) {
381
- // CACHE MISS, escalating pipeline: computed together below, so the below-floor records escalate together
382
- escalatingMisses.push(group);
383
- }
384
- else {
385
- // CACHE MISS: Execute prompt ONCE for the distinct key (using the first record in the group)
386
- const sampleRecord = group.records[0];
387
- const singleResult = await this.ProcessRecord(sampleRecord, context, {
388
- skipLookup: true,
389
- keyInfo: group.keyInfo,
390
- });
391
- // Fan out result to all records in this group
392
- await this.fanOutGroupResult(group, sampleRecord, singleResult, this.missFanOutHistory(singleResult, context, run), results);
393
- }
394
- }
395
- await this.computeGroupsWithEscalation(escalatingMisses, context, run, results);
396
- return results;
397
- }
398
- /** Fails every record with one message. */
399
- failEvery(records, errorMessage, results) {
400
- for (const r of records) {
401
- results.set(r.RecordID, { Status: 'Failed', ErrorMessage: errorMessage });
402
- }
403
- return results;
404
- }
405
- /**
406
- * Resolves what one processing pass needs: the prompt, the driver, and the hashes that version the
407
- * pipeline's answers. Returns why the pipeline cannot run instead, when the prompt is missing or the
408
- * driver cannot be resolved.
409
- */
410
- async resolveRunState(context) {
411
- await AIEngine.Instance.Config(false, context.contextUser);
412
- const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
413
- if (!prompt) {
414
- return { ErrorMessage: `AI Prompt '${this.promptID}' not found` };
415
- }
416
- const resolution = await this.resolveDriverOrError(context);
417
- if ('ErrorMessage' in resolution) {
418
- return { ErrorMessage: resolution.ErrorMessage };
419
- }
420
- return {
421
- Prompt: prompt,
422
- Driver: resolution.Driver,
423
- IsCacheable: this.spec?.Caching?.Cacheable === true,
424
- PromptVersionHash: this.computePromptVersionHash(prompt, this.spec),
425
- ConstraintHash: this.computeConstraintHash(this.spec),
426
- };
427
- }
428
- /**
429
- * Gives every record in a key group its sample's result. The other records get a copy of it, and their
430
- * own history row from `history` (which is absent when the sample failed).
431
- */
432
- async fanOutGroupResult(group, sample, result, history, results) {
433
- for (const rec of group.records) {
434
- if (rec.RecordID === sample.RecordID) {
435
- results.set(rec.RecordID, result);
436
- }
437
- else {
438
- if (history) {
439
- await this.recordFeatureValuesHistory({ ...history, record: rec });
440
- }
441
- results.set(rec.RecordID, { ...result });
442
- }
443
- }
444
- }
445
- /** The history a key group's other records get from its sample's computed result: none when it failed. */
446
- missFanOutHistory(result, context, run) {
447
- if (result.Status !== 'Succeeded') {
448
- return undefined;
449
- }
450
- return {
451
- context,
452
- payload: result.ResultPayload,
453
- promptID: run.Prompt.ID,
454
- promptVersionHash: run.PromptVersionHash,
455
- constraintHash: run.ConstraintHash,
456
- aiPromptRunID: result.AIPromptRunID,
457
- featureValueCacheID: result.FeatureValueCacheID,
458
- ...(result.Confidence ? { outputConfidence: result.Confidence } : {}),
459
- };
460
- }
461
- // -------------------------------------------------------------------------------------------------
462
- // Escalation (DataFeatureSpec.Escalation): below-floor decisions re-run through an LLM pipeline
463
- // -------------------------------------------------------------------------------------------------
464
- /**
465
- * The escalation of below-floor decisions, when the spec is a Decision pipeline's and has `Escalation`;
466
- * created once. `ValidateSpec` already refuses `Escalation` on any other type, but a processor built
467
- * directly from a spec skips it, and an LLM pipeline returns no confidence, so every record would escalate.
468
- */
469
- get escalator() {
470
- if (!this.spec?.Escalation || !IsDecisionPipelineType(this.spec.PipelineType)) {
471
- return undefined;
472
- }
473
- this._escalator ??= new FeaturePipelineEscalator(this.spec.Escalation, this.spec.Outputs ?? [], (pipeline, provider) => InferProcessor.FromRecordProcess(pipeline, provider));
474
- return this._escalator;
475
- }
476
- /** A successful decision's outputs below the escalation floor; empty when the pipeline does not escalate. */
477
- belowFloor(computed) {
478
- const escalator = this.escalator;
479
- if (!escalator || 'ErrorMessage' in computed) {
480
- return [];
481
- }
482
- return escalator.BelowFloor(computed.Confidence);
483
- }
484
- /** An uncached batch of a pipeline that escalates: every record is its own group, computed together. */
485
- async processUncachedBatchWithEscalation(records, context) {
486
- const results = new Map();
487
- const run = await this.resolveRunState(context);
488
- if ('ErrorMessage' in run) {
489
- return this.failEvery(records, run.ErrorMessage, results);
490
- }
491
- await this.computeGroupsWithEscalation(records.map((r) => ({ records: [r] })), context, run, results);
492
- return results;
493
- }
494
- /**
495
- * Computes key groups for a pipeline that escalates. The driver answers each group's first record; the
496
- * below-floor answers escalate together, in one pass through the target; then each group's final
497
- * answer is recorded once and fanned out to its records.
498
- */
499
- async computeGroupsWithEscalation(groups, context, run, results) {
500
- const samples = [];
501
- for (const group of groups) {
502
- samples.push(await this.computeSample(group, context, run));
503
- }
504
- const finalized = await this.finalizeSamples(samples, context, run);
505
- for (let i = 0; i < samples.length; i++) {
506
- await this.fanOutGroupResult(samples[i].Group, samples[i].Sample, finalized[i].Result, finalized[i].History, results);
507
- }
508
- }
509
- /**
510
- * Escalates the below-floor samples together, then finalizes every sample, in order. The escalations are
511
- * counted and logged by each escalated sample's final result, so an escalated answer that fails this
512
- * pipeline's own constraints counts as failed.
513
- */
514
- async finalizeSamples(samples, context, run) {
515
- const outcomes = await this.escalateBelowFloor(samples, context);
516
- const finalized = [];
517
- for (const sample of samples) {
518
- finalized.push(await this.finalizeSample(sample, outcomes, context, run));
519
- }
520
- this.countEscalations(samples, finalized);
521
- return finalized;
522
- }
523
- /**
524
- * Escalates, together, the samples whose decision was below the floor. Returns each escalated sample's
525
- * outcome by record ID; empty when none escalated.
526
- */
527
- async escalateBelowFloor(samples, context) {
528
- const escalator = this.escalator;
529
- const escalating = samples.filter((s) => s.BelowFloor.length > 0);
530
- if (!escalator || escalating.length === 0) {
531
- return new Map();
532
- }
533
- return escalator.Escalate(escalating.map((s) => ({ Record: s.Sample, BelowFloor: s.BelowFloor })), context);
534
- }
535
- /**
536
- * Adds a pass's escalated records (each group's records, fan-out included) to the run's count, and logs
537
- * it, counting as failed each escalated group whose final result failed.
538
- */
539
- countEscalations(samples, finalized) {
540
- const escalator = this.escalator;
541
- let escalated = 0;
542
- let failed = 0;
543
- samples.forEach((sample, i) => {
544
- if (sample.BelowFloor.length === 0) {
545
- return;
546
- }
547
- escalated += sample.Group.records.length;
548
- if (finalized[i].Result.Status !== 'Succeeded') {
549
- failed += sample.Group.records.length;
550
- }
551
- });
552
- if (!escalator || escalated === 0) {
553
- return;
554
- }
555
- this.escalatedRecordCount += escalated;
556
- LogStatus(`InferProcessor: escalated ${escalated} record(s) whose decision confidence was below ${escalator.BelowConfidence} ` +
557
- `to Feature Pipeline '${escalator.PipelineID}' (${failed} failed); ${this.escalatedRecordCount} escalated in this run.`);
558
- }
559
- /**
560
- * Finishes a record whose decision was below the escalation floor. A failed escalation fails the record
561
- * with both reasons, and the low-confidence decision is never cached, recorded or returned. A successful
562
- * one replaces the decision: the target's validated payload, in this pipeline's shape, is recorded in
563
- * history under the target's prompt, prompt run, hashes and cache entry, with the escalation note as the
564
- * history row's reasoning, and the record's result names the target's prompt with that prompt run and
565
- * hash, so write-back's `$run` provenance describes one run. It is not written to this pipeline's Dedup
566
- * Cache, which holds only answers the decision model gave with confidence; the target caches its own answers.
567
- *
568
- * The target validated its answer against its own constraints only, and those may be looser than this
569
- * pipeline's (a wider enum, or none). So the answer, in this pipeline's shape, is validated again against
570
- * this pipeline's own output constraints, with each output's OnViolation policy, exactly as a decision's
571
- * answer is: `fail` fails the record with both reasons, `null` and `coerce-to-other` apply. A value
572
- * outside the Decision pipeline's domain is never recorded or written back.
573
- *
574
- * The record paid for two model calls, and `MJ: Feature Values` is what links a prompt run to the process
575
- * run. So before the answer's row, one more history row records the superseded decision: its prompt run,
576
- * prompt, hashes and confidence, with no values (the low-confidence answer is never recorded as a value)
577
- * and a reasoning that says it was superseded. It is written once per decision call: a key group's other
578
- * records get only the answer's row.
579
- */
580
- async finalizeEscalated(sample, decision, outcome, context, run) {
581
- const record = sample.Sample;
582
- const decisionRunID = decision.AIPromptRunID;
583
- if (!outcome) {
584
- const message = `Escalation to Feature Pipeline '${this.spec?.Escalation?.PipelineID}' returned no outcome`;
585
- return { Result: { Status: 'Failed', ErrorMessage: message, AIPromptRunID: decisionRunID } };
586
- }
587
- if ('ErrorMessage' in outcome) {
588
- return { Result: { Status: 'Failed', ErrorMessage: outcome.ErrorMessage, AIPromptRunID: outcome.AIPromptRunID ?? decisionRunID } };
589
- }
590
- const checked = await this.validateOutputs(this.spec?.Outputs ?? [], this.projectEscalatedPayload(outcome), record, context);
591
- if (!checked.valid) {
592
- const reason = `its answer is outside this Decision pipeline's own constraints: ${checked.errorMessage ?? 'Constraint violation'}`;
593
- const message = DescribeEscalationFailure(outcome.EscalationReason, outcome.PipelineName, reason);
594
- return { Result: { Status: 'Failed', ErrorMessage: message, AIPromptRunID: outcome.AIPromptRunID ?? decisionRunID } };
595
- }
596
- const payload = checked.payload;
597
- await this.recordSupersededDecision(record, decision, outcome, context, run);
598
- const history = {
599
- context,
600
- payload,
601
- reasoning: outcome.Note,
602
- promptID: outcome.PromptID,
603
- promptVersionHash: outcome.PromptVersionHash,
604
- constraintHash: outcome.ConstraintHash,
605
- aiPromptRunID: outcome.AIPromptRunID,
606
- featureValueCacheID: outcome.FeatureValueCacheID,
607
- };
608
- await this.recordFeatureValuesHistory({ ...history, record });
609
- return {
610
- Result: {
611
- Status: 'Succeeded',
612
- ResultPayload: payload,
613
- PromptID: outcome.PromptID,
614
- AIPromptRunID: outcome.AIPromptRunID,
615
- PromptVersionHash: outcome.PromptVersionHash,
616
- FeatureValueCacheID: outcome.FeatureValueCacheID,
617
- },
618
- History: history,
619
- };
620
- }
621
- /**
622
- * Records the history row of a decision an escalation superseded: the decision model's prompt run and
623
- * confidence under this pipeline's prompt and hashes, no values, and a reasoning saying it was superseded.
624
- * Nothing is recorded when the decision has no prompt run to link.
625
- */
626
- async recordSupersededDecision(record, decision, outcome, context, run) {
627
- if (!decision.AIPromptRunID) {
628
- return;
629
- }
630
- await this.recordFeatureValuesHistory({
631
- record,
632
- context,
633
- payload: null,
634
- omitValues: true,
635
- reasoning: outcome.SupersededNote,
636
- promptID: run.Prompt.ID,
637
- promptVersionHash: run.PromptVersionHash,
638
- constraintHash: run.ConstraintHash,
639
- aiPromptRunID: decision.AIPromptRunID,
640
- ...(decision.Confidence ? { outputConfidence: decision.Confidence } : {}),
641
- });
642
- }
643
- /**
644
- * The escalated payload in this pipeline's shape: the target's validated payload, with each output's
645
- * value also placed at this pipeline's Ref for it, so write-back and history (which read this
646
- * pipeline's Refs) find the escalated values. When both pipelines use the same Refs, it is the target's
647
- * payload as is.
648
- */
649
- projectEscalatedPayload(outcome) {
650
- let projected = isPlainRecord(outcome.Payload) ? structuredClone(outcome.Payload) : outcome.Payload;
651
- for (const output of this.spec?.Outputs ?? []) {
652
- const source = FindOutputByName(outcome.TargetOutputs, output.Name);
653
- if (!source || source.Ref === output.Ref) {
654
- continue;
655
- }
656
- const value = ResolveMappingRef(source.Ref, { $: outcome.Payload });
657
- if (output.Ref === '$') {
658
- projected = value;
659
- }
660
- else if (output.Ref.startsWith('$.')) {
661
- const target = isPlainRecord(projected) ? projected : {};
662
- SetNestedValue(target, output.Ref.substring(2), value);
663
- projected = target;
664
- }
665
- }
666
- return projected;
667
- }
668
- /**
669
- * Computes a deterministic SHA-256 hash representing the prompt version and constraint instructions.
670
- * A pipeline type other than `LLM` is part of the hash, so switching a pipeline's type never serves
671
- * the old type's cached values. An LLM pipeline's hash is unchanged by the type's introduction.
672
- * So are the `Escalation` settings: the floor decides which decision answers are confident enough to
673
- * keep, so changing it (or the target) invalidates the answers cached under the old settings. A
674
- * pipeline without `Escalation` keeps its hash.
675
- */
676
- computePromptVersionHash(prompt, spec) {
677
- const promptText = prompt.TemplateText ?? prompt.Description ?? prompt.Name ?? '';
678
- const outputsStr = spec?.Outputs ? JSON.stringify(spec.Outputs) : '';
679
- const constraintBlock = spec?.Outputs ? renderConstraintBlock(spec.Outputs) : '';
680
- const hashBasis = `${prompt.ID}::${promptText}::${outputsStr}::${constraintBlock}${this.pipelineTypeHashSuffix(spec)}${this.escalationHashSuffix(spec)}`;
681
- return createHash('sha256').update(hashBasis).digest('hex');
682
- }
683
- /** The pipeline type's part of the prompt version hash: empty when the type is absent or `LLM`. */
684
- pipelineTypeHashSuffix(spec) {
685
- const pipelineType = spec?.PipelineType?.trim();
686
- if (!pipelineType || IsLLMPipelineType(pipelineType)) {
687
- return '';
688
- }
689
- return `::PipelineType=${pipelineType.toLowerCase()}`;
690
- }
691
- /** The escalation settings' part of the prompt version hash: empty without `Escalation`. */
692
- escalationHashSuffix(spec) {
693
- const escalation = spec?.Escalation;
694
- if (!escalation) {
695
- return '';
696
- }
697
- const settings = { PipelineID: escalation.PipelineID?.trim().toLowerCase(), BelowConfidence: escalation.BelowConfidence };
698
- return `::Escalation=${Canonicalize(settings)}`;
699
- }
700
- /** Computes a deterministic SHA-256 hash representing the output constraints. */
701
- computeConstraintHash(spec) {
702
- if (!spec?.Outputs || spec.Outputs.length === 0) {
703
- return 'no-constraints';
704
- }
705
- const constraints = spec.Outputs.map((o) => ({
706
- name: o.Name,
707
- constraint: o.Constraint,
708
- }));
709
- const canonical = Canonicalize(constraints);
710
- return createHash('sha256').update(canonical).digest('hex');
711
- }
712
- /**
713
- * Records historical audit rows in MJ: Feature Values for all outputs on a record.
714
- * `outputConfidence` (from a driver that produces confidence) sets each output's confidence by
715
- * output name, ahead of the single `confidence`. `omitValues` records every output's value as null,
716
- * whatever the payload holds (a superseded decision's row). Records nothing when {@link WritesHistory} is off.
717
- */
718
- async recordFeatureValuesHistory(params) {
719
- if (!this.WritesHistory || !this.spec?.Outputs || this.spec.Outputs.length === 0 || !params.context.recordProcessID || !params.context.entityID) {
720
- return;
721
- }
722
- const outputsList = [];
723
- const rawPayload = params.payload;
724
- const sources = { $: rawPayload };
725
- for (const output of this.spec.Outputs) {
726
- const val = params.omitValues ? null : resolveMappingRef(output.Ref, sources);
727
- outputsList.push({
728
- featureName: output.Name,
729
- value: val !== undefined ? val : null,
730
- reasoning: params.reasoning,
731
- confidence: params.outputConfidence?.[output.Name] ?? params.confidence,
732
- });
733
- }
734
- try {
735
- await FeatureValueCacheService.Instance.RecordFeatureValues({
736
- recordProcessID: params.context.recordProcessID,
737
- entityID: params.context.entityID,
738
- recordID: params.record.RecordID,
739
- outputs: outputsList,
740
- promptID: params.promptID,
741
- promptVersionHash: params.promptVersionHash,
742
- constraintHash: params.constraintHash,
743
- processRunID: params.context.processRunID,
744
- aiPromptRunID: params.aiPromptRunID,
745
- featureValueCacheID: params.featureValueCacheID,
746
- contextUser: params.context.contextUser,
747
- provider: params.context.provider,
748
- });
749
- }
750
- catch (e) {
751
- LogError(`InferProcessor: failed to record FeatureValues history for record '${params.record.RecordID}': ${e instanceof Error ? e.message : String(e)}`);
752
- }
753
- }
754
- /**
755
- * Computes the watermark basis hash for Checksum strategy:
756
- * SHA-256 over canonical { promptData, promptVersionHash }.
757
- */
758
- async ComputeBasisHash(record, context) {
759
- await this.ensureRecordsLoaded([record], context);
760
- await AIEngine.Instance.Config(false, context.contextUser);
761
- const prompt = AIEngine.Instance.Prompts.find((p) => UUIDsEqual(p.ID, this.promptID));
762
- const promptVersionHash = prompt ? this.computePromptVersionHash(prompt, this.spec) : '';
763
- const promptData = await this.buildPromptData(record, context);
764
- return ComputeContentHashAsync({
765
- promptData,
766
- promptVersionHash,
767
- });
768
- }
769
- // -------------------------------------------------------------------------------------------------
770
- // Feature Pipeline driver (resolved from MJ: Feature Pipeline Types by DataFeatureSpec.PipelineType)
771
- // -------------------------------------------------------------------------------------------------
772
- /**
773
- * Resolves the driver for this pipeline's type, once per processor instance.
774
- *
775
- * The type is `DataFeatureSpec.PipelineType`, or `LLM` when absent. It is matched by name
776
- * (case-insensitive, trimmed) against the `MJ: Feature Pipeline Types` catalog cached by
777
- * `KnowledgeHubMetadataEngine`, and its `DriverClass` is created through the ClassFactory. `LLM`
778
- * resolves to {@link LLMFeaturePipelineDriver} when the catalog has no `LLM` row, or cannot be read,
779
- * so a database without the seed row keeps working. The driver's `ValidateOutputs` then runs once.
780
- *
781
- * @throws Error when the type is not in the catalog (and is not `LLM`), is not Active, names a
782
- * DriverClass that is not registered, or cannot produce every output (naming each one).
783
- */
784
- async ResolveDriver(context) {
785
- this.driverResolution ??= this.resolveDriverFromCatalog(context);
786
- return this.driverResolution;
787
- }
788
- /** Runs {@link ResolveDriver}, turning a resolution error into a message the caller fails the record with. */
789
- async resolveDriverOrError(context) {
790
- try {
791
- return { Driver: await this.ResolveDriver(context) };
792
- }
793
- catch (e) {
794
- return { ErrorMessage: e instanceof Error ? e.message : String(e) };
795
- }
796
- }
797
- /** Finds the pipeline's type in the catalog, creates its driver, and checks it can produce every output. */
798
- async resolveDriverFromCatalog(context) {
799
- const typeName = this.spec?.PipelineType ?? LLM_PIPELINE_TYPE;
800
- const pipelineType = await this.findPipelineType(typeName, context);
801
- const driver = pipelineType ? this.createDriver(pipelineType) : this.createDriverWithoutCatalogRow(typeName);
802
- if (this.spec) {
803
- this.assertDriverProducesOutputs(driver, typeName, this.spec, context);
804
- }
805
- return driver;
806
- }
807
- /**
808
- * Looks the type up by name in the catalog. If the catalog cannot be read, `LLM` is treated as not
809
- * found (and so still resolves); any other type fails, because only the catalog names its driver.
810
- */
811
- async findPipelineType(typeName, context) {
812
- try {
813
- await KnowledgeHubMetadataEngine.Instance.Config(false, context.contextUser, context.provider);
814
- const wanted = typeName.trim().toLowerCase();
815
- return KnowledgeHubMetadataEngine.Instance.FeaturePipelineTypes.find((t) => t.Name?.trim().toLowerCase() === wanted);
816
- }
817
- catch (e) {
818
- const reason = e instanceof Error ? e.message : String(e);
819
- if (!IsLLMPipelineType(typeName)) {
820
- throw new Error(`Feature Pipeline type '${typeName}' could not be resolved: MJ: Feature Pipeline Types could not be read: ${reason}`);
821
- }
822
- LogError(`InferProcessor: MJ: Feature Pipeline Types could not be read (${reason}); running as LLM`);
823
- return undefined;
824
- }
825
- }
826
- /** The driver for a type with no catalog row: `LLM` still runs; any other name is an error. */
827
- createDriverWithoutCatalogRow(typeName) {
828
- if (IsLLMPipelineType(typeName)) {
829
- return new LLMFeaturePipelineDriver();
830
- }
831
- throw new Error(`Feature Pipeline type '${typeName}' was not found in MJ: Feature Pipeline Types.`);
832
- }
833
- /** Creates an Active type's driver from its registered `DriverClass`. */
834
- createDriver(pipelineType) {
835
- if (pipelineType.Status !== 'Active') {
836
- throw new Error(`Feature Pipeline type '${pipelineType.Name}' is ${pipelineType.Status}; only an Active type can run.`);
837
- }
838
- const driverClass = pipelineType.DriverClass;
839
- const driver = MJGlobal.Instance.ClassFactory.CreateInstance(BaseFeaturePipelineDriver, driverClass);
840
- if (!driver || driver.constructor === BaseFeaturePipelineDriver) {
841
- throw new Error(`Feature Pipeline type '${pipelineType.Name}' names DriverClass '${driverClass}', which is not registered ` +
842
- `with @RegisterClass(BaseFeaturePipelineDriver, '${driverClass}').`);
843
- }
844
- return driver;
845
- }
846
- /**
847
- * The value lists of the pipeline's own entity (`context.entityID`), for the output check and the
848
- * driver. Consults only that entity's fields, so a same-named field elsewhere is never read; undefined
849
- * when the run names no entity or the provider does not know it.
850
- */
851
- buildFieldValuesLookup(context) {
852
- if (!context.entityID) {
853
- return undefined;
854
- }
855
- const provider = context.provider ?? Metadata.Provider; // global-provider-ok: last-resort fallback for a context built without its provider
856
- return typeof provider?.EntityByID === 'function' ? BuildEntityFieldValueLookup(provider.EntityByID(context.entityID)) : undefined;
857
- }
858
- /** Fails when the driver cannot produce one or more of the spec's outputs, naming every one. */
859
- assertDriverProducesOutputs(driver, typeName, spec, context) {
860
- const fieldValues = this.buildFieldValuesLookup(context);
861
- const messages = driver.ValidateOutputs(spec, fieldValues);
862
- if (messages.length > 0) {
863
- throw new Error(`Feature Pipeline type '${typeName}' cannot produce every output: ${messages.join(' ')}`);
864
- }
865
- }
866
- /** The driver's callbacks into this processor's overridable steps, so extensions keep working. */
867
- buildComputeHooks() {
868
- return {
869
- BuildPromptData: (record, ctx) => this.buildPromptData(record, ctx),
870
- BeforeBuildContext: (record, ctx) => this.beforeBuildContext(record, ctx),
871
- BeforePromptExecute: (params, record, ctx) => this.beforePromptExecute(params, record, ctx),
872
- AfterPromptExecute: (result, record, ctx) => this.afterPromptExecute(result, record, ctx),
873
- };
874
- }
875
- // -------------------------------------------------------------------------------------------------
876
- // P1-6 Lifecycle Hooks (overridable by subclasses registered under DataFeatureSpec.ProcessorExtensionKey)
877
- // -------------------------------------------------------------------------------------------------
878
- /** Lifecycle hook called before prompt data context is constructed. */
879
- async beforeBuildContext(record, ctx) { }
880
- /** Lifecycle hook called immediately before ExecutePrompt is invoked. */
881
- async beforePromptExecute(params, record, ctx) { }
882
- /** Lifecycle hook called after prompt execution returns successfully. Defaults to returning result.result. */
883
- async afterPromptExecute(result, record, ctx) {
884
- return result.result ?? {};
885
- }
886
- /**
887
- * Layer 2 output validation hook. Evaluates outputs against declared constraints, applies OnViolation
888
- * policies (fail, null, coerce-to-other), and builds the processed payload. `replacedOutputs` names
889
- * the outputs whose value a `null` or `coerce-to-other` policy replaced.
890
- */
891
- async validateOutputs(outputs, rawResult, record, ctx) {
892
- if (!outputs || !Array.isArray(outputs) || outputs.length === 0) {
893
- return { valid: true, payload: rawResult };
894
- }
895
- let payloadCopy = typeof rawResult === 'object' && rawResult !== null
896
- ? structuredClone(rawResult)
897
- : rawResult;
898
- const violations = [];
899
- for (const output of outputs) {
900
- if (!output.Constraint) {
901
- continue;
902
- }
903
- const sources = { $: rawResult };
904
- const rawVal = resolveMappingRef(output.Ref, sources);
905
- const target = output.Target;
906
- const field = target.Mode === 'field'
907
- ? ctx.provider?.EntityByID(record.EntityID)?.Fields?.find((f) => f.Name.toLowerCase() === target.EntityFieldName.toLowerCase())
908
- : undefined;
909
- // The resolved constraint carries the field's value list for an enum with FromFieldMetadata;
910
- // without it the check sees only the spec's own Values
911
- const validation = validateOutputValue(rawVal, output.Constraint, {
912
- targetFieldTSType: field?.TSType,
913
- resolved: ResolveConstraint(output, field),
914
- });
915
- if (!validation.valid) {
916
- return {
917
- valid: false,
918
- errorMessage: `Constraint violation for '${output.Name}': ${validation.violationMessage}`,
919
- };
920
- }
921
- if (validation.violationPolicyApplied === 'null' || validation.violationPolicyApplied === 'coerce-to-other') {
922
- violations.push({
923
- outputName: output.Name,
924
- violationMessage: validation.violationMessage ?? 'Constraint violation',
925
- policy: validation.violationPolicyApplied,
926
- });
927
- }
928
- if (validation.coerced || validation.value !== rawVal) {
929
- if (output.Ref === '$') {
930
- payloadCopy = validation.value;
931
- }
932
- else if (typeof payloadCopy === 'object' && payloadCopy !== null && output.Ref.startsWith('$.')) {
933
- const propPath = output.Ref.substring(2);
934
- SetNestedValue(payloadCopy, propPath, validation.value);
935
- }
936
- }
937
- }
938
- if (typeof payloadCopy === 'object' && payloadCopy !== null && violations.length > 0) {
939
- payloadCopy._violations = violations;
940
- }
941
- return { valid: true, payload: payloadCopy, replacedOutputs: violations.map((v) => v.outputName) };
942
- }
943
- /**
944
- * The driver's per-output confidences, less those of outputs whose value the constraint check replaced:
945
- * a confidence belongs to the value the model gave, not to a null or 'Other' written in its place.
946
- * Undefined when none remain.
947
- */
948
- confidenceOfKeptValues(confidence, replacedOutputs) {
949
- if (!confidence) {
950
- return undefined;
951
- }
952
- const replaced = new Set(replacedOutputs ?? []);
953
- const kept = Object.entries(confidence).filter(([outputName]) => !replaced.has(outputName));
954
- return kept.length > 0 ? Object.fromEntries(kept) : undefined;
955
- }
956
- /** Lifecycle hook to resolve a dedup cache key for this record. Default returns null (computed by cache service). */
957
- async resolveCacheKey(record, spec, ctx) {
958
- return null;
959
- }
960
- /** Lifecycle hook called before write-back is executed on this record. */
961
- async beforeWriteBack(// case-violation-ok-legacy-back-compat: a subclass overrides this; a stub preserves CALLING the old name but not OVERRIDING it, and WriteBackProcessor also probes for it by string
962
- mapping, result, record, ctx) { }
963
- // -------------------------------------------------------------------------------------------------
964
- // Context Construction & Helpers
965
- // -------------------------------------------------------------------------------------------------
966
- /**
967
- * Builds the data object passed to the prompt.
968
- * Incorporates spec.Context (EntityDocumentID rendering, QueryID parameterized execution, Field filtering),
969
- * input mapping, and Layer-1 constraint instructions.
970
- */
971
- async buildPromptData(record, ctx) {
972
- let recordData = this.recordToPlain(record);
973
- // Context.Fields projection: filter record fields if explicit fields are listed
974
- if (this.spec?.Context?.Fields && this.spec.Context.Fields.length > 0) {
975
- const allowed = new Set(this.spec.Context.Fields.map((f) => f.toLowerCase()));
976
- const filtered = {};
977
- for (const [key, val] of Object.entries(recordData)) {
978
- if (allowed.has(key.toLowerCase()) || key === 'ID' || key === 'RecordID' || key === 'EntityID') {
979
- filtered[key] = val;
980
- }
981
- }
982
- recordData = filtered;
983
- }
984
- let promptData;
985
- const mappingToUse = this.inputMapping ?? this.spec?.Context?.InputMapping;
986
- if (!mappingToUse) {
987
- promptData = { record: recordData };
988
- }
989
- else {
990
- const mapped = resolveValueMapping(mappingToUse, { record: recordData });
991
- promptData = mapped && typeof mapped === 'object' ? mapped : { record: recordData };
992
- }
993
- // P1-8a: EntityDocument context rendering
994
- if (this.spec?.Context?.EntityDocumentID && ctx) {
995
- try {
996
- await EntityDocumentCache.Instance.Refresh(false, ctx.contextUser);
997
- const doc = EntityDocumentCache.Instance.GetDocument(this.spec.Context.EntityDocumentID);
998
- if (doc) {
999
- const parser = EntityDocumentTemplateParser.CreateInstance();
1000
- if (ctx.provider) {
1001
- parser.ProviderOverride = ctx.provider;
1002
- }
1003
- const templateText = await parser.resolveDocumentTemplateText(doc, ctx.contextUser);
1004
- if (templateText && templateText.trim().length > 0) {
1005
- const rendered = await parser.Parse(templateText, record.EntityID, recordData, ctx.contextUser);
1006
- promptData.context = rendered;
1007
- promptData.RenderedContext = rendered;
1008
- promptData.document = rendered;
1009
- }
1010
- }
1011
- }
1012
- catch (e) {
1013
- LogError(`InferProcessor: failed to render EntityDocument '${this.spec.Context.EntityDocumentID}': ${e instanceof Error ? e.message : String(e)}`);
1014
- }
1015
- }
1016
- // P1-8a / C7: Query context execution
1017
- if (this.spec?.Context?.QueryID && ctx) {
1018
- try {
1019
- const rq = new RunQuery();
1020
- const queryParams = {};
1021
- if (this.spec.Context.QueryParams) {
1022
- for (const [pName, pRef] of Object.entries(this.spec.Context.QueryParams)) {
1023
- queryParams[pName] = resolveMappingRef(pRef, { record: recordData, $: recordData });
1024
- }
1025
- }
1026
- const qResult = await rq.RunQuery({ QueryID: this.spec.Context.QueryID, Parameters: queryParams }, ctx.contextUser);
1027
- if (qResult && qResult.Success) {
1028
- promptData.queryResult = qResult.Results;
1029
- if (!promptData.context) {
1030
- promptData.context = qResult.Results;
1031
- }
1032
- }
1033
- else {
1034
- LogError(`InferProcessor: RunQuery '${this.spec.Context.QueryID}' failed: ${qResult?.ErrorMessage ?? 'unknown error'}`);
1035
- }
1036
- }
1037
- catch (e) {
1038
- LogError(`InferProcessor: failed executing Query '${this.spec.Context.QueryID}': ${e instanceof Error ? e.message : String(e)}`);
1039
- }
1040
- }
1041
- // Layer 1: Inject constraint block if feature spec declares outputs
1042
- if (this.spec?.Outputs && this.spec.Outputs.length > 0) {
1043
- const constraintBlock = renderConstraintBlock(this.spec.Outputs);
1044
- if (constraintBlock && constraintBlock.trim().length > 0) {
1045
- promptData.constraints = constraintBlock;
1046
- promptData.ConstraintBlock = constraintBlock;
1047
- }
1048
- }
1049
- return promptData;
1050
- }
1051
- /** Extracts a plain field map from the record (BaseEntity → GetAll(), plain object → as-is). */
1052
- recordToPlain(record) {
1053
- const r = record.Record;
1054
- if (r && typeof r.GetAll === 'function') {
1055
- return r.GetAll();
1056
- }
1057
- if (r && typeof r === 'object') {
1058
- return r;
1059
- }
1060
- return { RecordID: record.RecordID, EntityID: record.EntityID };
1061
- }
1062
- /**
1063
- * Ensures that every record in the batch has its full field data loaded on `record.Record`.
1064
- * If records only have primary keys (as yielded by source pagination), batch-fetches the
1065
- * full records via RunView in a single query per entity.
1066
- */
1067
- async ensureRecordsLoaded(records, context) {
1068
- const requiredFields = [];
1069
- if (this.spec?.Context?.Fields) {
1070
- requiredFields.push(...this.spec.Context.Fields);
1071
- }
1072
- if (this.spec?.Caching?.KeyFields) {
1073
- requiredFields.push(...this.spec.Caching.KeyFields);
1074
- }
1075
- const needsLoading = records.filter((r) => {
1076
- if (!r.Record || typeof r.Record !== 'object')
1077
- return true;
1078
- if (typeof r.Record.GetAll === 'function')
1079
- return false;
1080
- const rec = r.Record;
1081
- // If explicit fields are required, check if any is missing
1082
- if (requiredFields.length > 0) {
1083
- const recKeysLower = new Set(Object.keys(rec).map((k) => k.toLowerCase()));
1084
- const missing = requiredFields.some((f) => !recKeysLower.has(f.toLowerCase()));
1085
- if (missing)
1086
- return true;
1087
- return false;
1088
- }
1089
- // If no explicit fields, check if record only contains primary/identity keys
1090
- const nonPkKeys = Object.keys(rec).filter((k) => {
1091
- const lower = k.toLowerCase();
1092
- return lower !== 'id' && lower !== 'recordid' && lower !== 'entityid';
1093
- });
1094
- return nonPkKeys.length === 0;
1095
- });
1096
- if (needsLoading.length === 0)
1097
- return;
1098
- const candidateProvider = context.provider ?? Metadata.Provider; // global-provider-ok: fallback to global provider when not in context
1099
- const provider = (candidateProvider && typeof candidateProvider.EntityByID === 'function')
1100
- ? candidateProvider
1101
- : undefined;
1102
- if (!provider)
1103
- return;
1104
- const byEntity = new Map();
1105
- for (const r of needsLoading) {
1106
- const list = byEntity.get(r.EntityID) ?? [];
1107
- list.push(r);
1108
- byEntity.set(r.EntityID, list);
1109
- }
1110
- for (const [entityID, entityRecords] of byEntity) {
1111
- const entity = provider.EntityByID(entityID);
1112
- if (!entity)
1113
- continue;
1114
- const pk = entity.FirstPrimaryKey?.Name ?? 'ID'; // first-pk-ok: batch lookup by PK for entity records
1115
- const chunkSize = 500;
1116
- for (let i = 0; i < entityRecords.length; i += chunkSize) {
1117
- const chunk = entityRecords.slice(i, i + chunkSize);
1118
- const ids = chunk.map((r) => `'${EscapeSQLString(r.RecordID)}'`).join(',');
1119
- const rv = new RunView();
1120
- const result = await rv.RunView({
1121
- EntityName: entity.Name,
1122
- ExtraFilter: `[${pk}] IN (${ids})`,
1123
- ResultType: 'simple',
1124
- MaxRows: chunk.length,
1125
- BypassCache: true,
1126
- }, context.contextUser);
1127
- if (result.Success && result.Results) {
1128
- const rowMap = new Map();
1129
- for (const row of result.Results) {
1130
- const idVal = String(row[pk]);
1131
- rowMap.set(idVal, row);
1132
- }
1133
- for (const r of chunk) {
1134
- const row = rowMap.get(r.RecordID);
1135
- if (row) {
1136
- r.Record = row;
1137
- }
1138
- }
1139
- }
1140
- else {
1141
- const errMsg = result.ErrorMessage || 'Failed to load records from entity view';
1142
- LogError(`[InferProcessor] ensureRecordsLoaded failed for entity '${entity.Name}': ${errMsg}`);
1143
- throw new Error(`[InferProcessor] Failed to load records for entity '${entity.Name}': ${errMsg}`);
1144
- }
1145
- }
1146
- }
1147
- }
1148
- }
1149
- /**
1150
- * Sets a value at a dot-delimited path (e.g. 'a.b' or 'items[0].name') on an object,
1151
- * mutating the object in-place and creating intermediate objects or arrays as needed.
1152
- */
1153
- export function SetNestedValue(obj, path, value) {
1154
- if (!path)
1155
- return;
1156
- const parts = path.split('.');
1157
- let current = obj;
1158
- for (let i = 0; i < parts.length - 1; i++) {
1159
- const part = parts[i];
1160
- if (!part || part === '__proto__' || part === 'constructor' || part === 'prototype') {
1161
- return;
1162
- }
1163
- const arrayMatch = part.match(/^([^[]+)\[(\d+)\]$/);
1164
- if (arrayMatch) {
1165
- const name = arrayMatch[1];
1166
- if (name === '__proto__' || name === 'constructor' || name === 'prototype') {
1167
- return;
1168
- }
1169
- const index = parseInt(arrayMatch[2], 10);
1170
- if (!Array.isArray(current[name])) {
1171
- current[name] = [];
1172
- }
1173
- const arr = current[name];
1174
- if (!arr[index] || typeof arr[index] !== 'object') {
1175
- arr[index] = Object.create(null);
1176
- }
1177
- current = arr[index];
1178
- }
1179
- else {
1180
- if (current[part] === undefined || current[part] === null || typeof current[part] !== 'object') {
1181
- current[part] = Object.create(null);
1182
- }
1183
- current = current[part];
1184
- }
1185
- }
1186
- const lastPart = parts[parts.length - 1];
1187
- if (lastPart === '__proto__' || lastPart === 'constructor' || lastPart === 'prototype') {
1188
- return;
1189
- }
1190
- const arrayMatch = lastPart.match(/^([^[]+)\[(\d+)\]$/);
1191
- if (arrayMatch) {
1192
- const name = arrayMatch[1];
1193
- if (name === '__proto__' || name === 'constructor' || name === 'prototype') {
1194
- return;
1195
- }
1196
- const index = parseInt(arrayMatch[2], 10);
1197
- if (!Array.isArray(current[name])) {
1198
- current[name] = [];
1199
- }
1200
- current[name][index] = value;
1201
- }
1202
- else {
1203
- current[lastPart] = value;
1204
- }
1205
- }
1206
- /** @deprecated Use {@link SetNestedValue}. */
1207
- export function setNestedValue(obj, path, value) {
1208
- return SetNestedValue(obj, path, value);
1209
- }
1210
- //# sourceMappingURL=InferProcessor.js.map