@actuarial-ts/agents 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +4 -2
  2. package/dist/advisor.d.ts +2 -1
  3. package/dist/advisor.d.ts.map +1 -1
  4. package/dist/advisor.js +3 -1
  5. package/dist/advisor.js.map +1 -1
  6. package/dist/divergence.d.ts +267 -0
  7. package/dist/divergence.d.ts.map +1 -0
  8. package/dist/divergence.js +414 -0
  9. package/dist/divergence.js.map +1 -0
  10. package/dist/errors.d.ts +1 -1
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/errors.js +20 -0
  13. package/dist/errors.js.map +1 -1
  14. package/dist/index.d.ts +4 -0
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +4 -0
  17. package/dist/index.js.map +1 -1
  18. package/dist/judgment.d.ts +26 -0
  19. package/dist/judgment.d.ts.map +1 -1
  20. package/dist/judgment.js +21 -0
  21. package/dist/judgment.js.map +1 -1
  22. package/dist/mcp.d.ts +165 -0
  23. package/dist/mcp.d.ts.map +1 -0
  24. package/dist/mcp.js +155 -0
  25. package/dist/mcp.js.map +1 -0
  26. package/dist/promotion.d.ts +295 -0
  27. package/dist/promotion.d.ts.map +1 -0
  28. package/dist/promotion.js +824 -0
  29. package/dist/promotion.js.map +1 -0
  30. package/dist/remote.d.ts +221 -0
  31. package/dist/remote.d.ts.map +1 -0
  32. package/dist/remote.js +295 -0
  33. package/dist/remote.js.map +1 -0
  34. package/dist/tools.d.ts +87 -6
  35. package/dist/tools.d.ts.map +1 -1
  36. package/dist/tools.js +182 -15
  37. package/dist/tools.js.map +1 -1
  38. package/package.json +11 -4
  39. package/src/advisor.ts +141 -0
  40. package/src/divergence.ts +642 -0
  41. package/src/errors.ts +62 -0
  42. package/src/evals.ts +162 -0
  43. package/src/index.ts +9 -0
  44. package/src/judgment.ts +458 -0
  45. package/src/mcp.ts +274 -0
  46. package/src/promotion.ts +1240 -0
  47. package/src/remote.ts +371 -0
  48. package/src/tools.ts +561 -0
@@ -0,0 +1,824 @@
1
+ /**
2
+ * promoteStudy: notebook study -> governed judgment (interchange spec rev 2.1,
3
+ * Section 6). A four-gate judgment chain built on createJudgmentChain:
4
+ *
5
+ * Gate 1 "study-intake" - schema/integrity validation via interchange
6
+ * parseDocument, ASOP 23 data review on the study's
7
+ * triangles, selection coherence (spec 3.2 rule),
8
+ * segment resolution (v1: one selection per
9
+ * segment), and the tolerance ceiling.
10
+ * Gate 2 "replay-verify" - table-exact intents replayed through
11
+ * interchange/core; approx/value-only targets
12
+ * labeled verified-by-value; supportingResults
13
+ * refereed via crosscheck at the effective
14
+ * tolerance; a "disagree" verdict HARD-BLOCKS.
15
+ * Gate 3 "rationale" - a DRAFT rationale (template-assembled from the
16
+ * study narrative; options.draftRationale is the
17
+ * injection hook for future agent drafting); resume
18
+ * REQUIRES a non-blank rationale AND attestation.
19
+ * Gate 4 "apply" - deps.applySelections per selection,
20
+ * deps.runAnalysis, ledger entries carrying the
21
+ * Gate 3 rationale + attestation verbatim, and
22
+ * deps.persistNote with the trail + ledger JSON.
23
+ *
24
+ * Architecture decisions (each is load-bearing):
25
+ *
26
+ * - EAGER, DETERMINISTIC INTAKE. All Gate 1/2 computation (parse, review,
27
+ * coherence, segment resolution, replay, crosschecks) runs synchronously at
28
+ * chain-CONSTRUCTION time. Everything is a pure function of the study
29
+ * document plus deps.resolveSegment, so a host that reconstructs the chain
30
+ * after a restart (promoteStudy again with the same study) gets IDENTICAL
31
+ * gates and resume schemas - which is what makes the Gate 2 hard-block
32
+ * structural: when any referee verdict is "disagree", the replay-verify
33
+ * resume schema literally only admits { decision: "abort" }. Mastra's own
34
+ * resume validation rejects an accept; no runtime flag to lose across a
35
+ * snapshot rehydration, no advisory check an agent could talk its way past.
36
+ *
37
+ * - STUDY-CONTENT FAILURES SURFACE AS GATE FAILURES. A malformed study
38
+ * (BAD_INTERCHANGE), a tolerance above the host ceiling
39
+ * (TOLERANCE_CEILING_EXCEEDED), an unresolvable or ambiguous segment
40
+ * (SEGMENT_UNRESOLVED / SEGMENT_AMBIGUOUS), an incoherent selection under
41
+ * refuse strictness (INCOHERENT_SELECTION), or an empty study (EMPTY_STUDY)
42
+ * never throws out of promoteStudy itself: the captured error is thrown
43
+ * from Gate 1's gatherEvidence, so the run fails AT the study-intake gate
44
+ * with the named error, where the host's gate UI can render it.
45
+ * promoteStudy throws synchronously only for programmer errors
46
+ * (BAD_PROMOTION_OPTIONS: missing deps, non-positive ceiling, ...).
47
+ *
48
+ * - DATA REVIEW CHOICE (documented per plan task B2): where a segment group
49
+ * contains exactly one paid and one incurred triangle, the full
50
+ * @actuarial-ts/data reviewTriangles pair review runs (it includes the
51
+ * per-triangle monotonicity and interior-missing checks). Every other core
52
+ * loss triangle gets the per-triangle STRUCTURAL subset of those checks
53
+ * (non-decreasing cumulative rows, interior missing cells), reported in the
54
+ * same DataReviewReport shape. Non-core measures (earnedPremium, custom:*)
55
+ * are exposure/reference data, not loss triangles: their review is reported
56
+ * "not-evaluated" rather than silently passed - unless a selection
57
+ * references one, which fails intake (BAD_INTERCHANGE from the converter).
58
+ * Review findings, including fail-status checks, are EVIDENCE for the human
59
+ * intake decision, not automatic blocks; only the named error classes above
60
+ * block mechanically. The recommendation says so when checks fail.
61
+ *
62
+ * - PURITY. This module never reads a clock; options.now supplies every
63
+ * timestamp (envelope createdAt at construction, ledger timestamps at
64
+ * resume). The tenant seam is untouched: deps close over the host's own
65
+ * authenticated context, and nothing model-facing exists here at all.
66
+ *
67
+ * FOOTGUN (inherited from createJudgmentChain): the returned workflow exposes
68
+ * .then(step), making it an ACCIDENTAL THENABLE. Never await promoteStudy's
69
+ * return value and never return it from an async function - assign it
70
+ * synchronously and register it on a Mastra instance.
71
+ */
72
+ import { ReservingError, runChainLadder, } from "@actuarial-ts/core";
73
+ import { CONVENTION_PROFILES, CORE_MEASURES, DETERMINISTIC_CL_PROFILE, crosscheck, docToSelections, docToTriangle, isValueOnlySelection, parseDocument, resultToDoc, verifyIntegrity, } from "@actuarial-ts/interchange";
74
+ import { reviewTriangles, } from "@actuarial-ts/data";
75
+ import { z } from "zod";
76
+ import { AgentsError } from "./errors.js";
77
+ import { createJudgmentChain, } from "./judgment.js";
78
+ /** Collects the study's `witnessed` supporting results (spec 16). */
79
+ function witnessedResultsOf(study) {
80
+ const notices = [];
81
+ for (const doc of study.supportingResults ?? []) {
82
+ const result = doc.result;
83
+ if (result["reproducibility"] !== "witnessed")
84
+ continue;
85
+ const rawStability = result["stability"];
86
+ const stability = rawStability !== null && typeof rawStability === "object"
87
+ ? rawStability
88
+ : null;
89
+ notices.push({
90
+ method: String(result["method"] ?? "(unnamed method)"),
91
+ engine: `${doc.result.engine.name}@${doc.result.engine.version}`,
92
+ seed: typeof result["seed"] === "number" ? result["seed"] : null,
93
+ stability: stability === null
94
+ ? null
95
+ : {
96
+ repeats: Number(stability["repeats"] ?? 0),
97
+ byteIdentical: stability["byteIdentical"] === true,
98
+ maxRelativeDeviation: typeof stability["maxRelativeDeviation"] === "number"
99
+ ? stability["maxRelativeDeviation"]
100
+ : null,
101
+ },
102
+ });
103
+ }
104
+ return notices;
105
+ }
106
+ /** The workflow id promoteStudy builds its chain with. */
107
+ export const PROMOTION_CHAIN_ID = "promote-study";
108
+ const MAX_STRUCTURAL_DETAILS = 20;
109
+ function capDetails(items) {
110
+ return items.length <= MAX_STRUCTURAL_DETAILS
111
+ ? items
112
+ : [...items.slice(0, MAX_STRUCTURAL_DETAILS), `+${items.length - MAX_STRUCTURAL_DETAILS} more`];
113
+ }
114
+ function structuralCheck(id, description, findings) {
115
+ return {
116
+ id,
117
+ description,
118
+ status: findings.length > 0 ? "warning" : "pass",
119
+ details: capDetails(findings),
120
+ };
121
+ }
122
+ /**
123
+ * The per-triangle STRUCTURAL subset of the data package's triangle review
124
+ * (the pair-wise checks need a paid/incurred pair; these do not).
125
+ */
126
+ function structuralReview(tri) {
127
+ const nonDecreasing = [];
128
+ const interiorMissing = [];
129
+ for (let i = 0; i < tri.values.length; i++) {
130
+ const row = tri.values[i];
131
+ let prev = null;
132
+ let prevAge = null;
133
+ for (let j = 0; j < row.length; j++) {
134
+ const v = row[j];
135
+ if (v === null || v === undefined)
136
+ continue;
137
+ const age = tri.ages[j];
138
+ if (prev !== null && v < prev) {
139
+ nonDecreasing.push(`${tri.kind} ${tri.origins[i]} age ${prevAge} -> ${age}: ${prev} -> ${v}`);
140
+ }
141
+ prev = v;
142
+ prevAge = age;
143
+ }
144
+ const observed = row.map((v) => v !== null && v !== undefined);
145
+ const first = observed.indexOf(true);
146
+ const last = observed.lastIndexOf(true);
147
+ if (first === -1)
148
+ continue;
149
+ for (let j = first + 1; j < last; j++) {
150
+ if (!observed[j]) {
151
+ interiorMissing.push(`${tri.kind} ${tri.origins[i]} age ${tri.ages[j]}: interior cell missing`);
152
+ }
153
+ }
154
+ }
155
+ const checks = [
156
+ structuralCheck("negative-incremental", "Cumulative values are non-decreasing along each origin row (salvage/case takedowns can legitimately violate this)", nonDecreasing),
157
+ structuralCheck("interior-missing", "No row has a missing cell between observed cells", interiorMissing),
158
+ ];
159
+ const summary = { pass: 0, warning: 0, fail: 0, notEvaluated: 0 };
160
+ for (const c of checks) {
161
+ if (c.status === "pass")
162
+ summary.pass++;
163
+ else if (c.status === "warning")
164
+ summary.warning++;
165
+ }
166
+ return { checks, summary };
167
+ }
168
+ function notEvaluatedReview(reason) {
169
+ return {
170
+ checks: [
171
+ {
172
+ id: "loss-triangle-review",
173
+ description: "ASOP 23-oriented triangle review",
174
+ status: "not-evaluated",
175
+ details: [`not evaluated: ${reason}`],
176
+ },
177
+ ],
178
+ summary: { pass: 0, warning: 0, fail: 0, notEvaluated: 1 },
179
+ };
180
+ }
181
+ function segmentKeyOf(labels) {
182
+ return JSON.stringify(Object.entries(labels).sort(([a], [b]) => a.localeCompare(b)));
183
+ }
184
+ function labelsOf(triangleDoc) {
185
+ return triangleDoc.triangle.segment?.labels ?? {};
186
+ }
187
+ /**
188
+ * ASOP 23 review over the study's triangles: paired reviewTriangles wherever
189
+ * a segment group holds exactly one paid and one incurred core triangle;
190
+ * structural checks for every other core loss triangle; not-evaluated for
191
+ * non-core measures (see the module doc for the rationale).
192
+ */
193
+ function reviewStudyTriangles(triangles, warnings) {
194
+ const isCore = (doc) => CORE_MEASURES.includes(doc.triangle.measure);
195
+ const bySegment = new Map();
196
+ for (const doc of triangles) {
197
+ if (!isCore(doc))
198
+ continue;
199
+ const key = segmentKeyOf(labelsOf(doc));
200
+ const list = bySegment.get(key);
201
+ if (list)
202
+ list.push(doc);
203
+ else
204
+ bySegment.set(key, [doc]);
205
+ }
206
+ const paired = new Set();
207
+ const evidence = [];
208
+ for (const group of bySegment.values()) {
209
+ const paidDocs = group.filter((d) => d.triangle.measure === "paid");
210
+ const incurredDocs = group.filter((d) => d.triangle.measure === "incurred");
211
+ if (paidDocs.length === 1 && incurredDocs.length === 1) {
212
+ const paidDoc = paidDocs[0];
213
+ const incurredDoc = incurredDocs[0];
214
+ const paidConv = docToTriangle(paidDoc);
215
+ const incurredConv = docToTriangle(incurredDoc);
216
+ warnings.push(...paidConv.warnings, ...incurredConv.warnings);
217
+ evidence.push({
218
+ mode: "paired-asop23",
219
+ triangles: [
220
+ { integrity: paidDoc.integrity, measure: "paid" },
221
+ { integrity: incurredDoc.integrity, measure: "incurred" },
222
+ ],
223
+ report: reviewTriangles(paidConv.triangle, incurredConv.triangle),
224
+ });
225
+ paired.add(paidDoc);
226
+ paired.add(incurredDoc);
227
+ }
228
+ }
229
+ for (const doc of triangles) {
230
+ if (paired.has(doc))
231
+ continue;
232
+ if (!isCore(doc)) {
233
+ evidence.push({
234
+ mode: "not-evaluated",
235
+ triangles: [{ integrity: doc.integrity, measure: doc.triangle.measure }],
236
+ report: notEvaluatedReview(`measure "${doc.triangle.measure}" is exposure/reference data, not a core loss triangle`),
237
+ });
238
+ continue;
239
+ }
240
+ const conv = docToTriangle(doc);
241
+ warnings.push(...conv.warnings);
242
+ evidence.push({
243
+ mode: "structural",
244
+ triangles: [{ integrity: doc.integrity, measure: doc.triangle.measure }],
245
+ report: structuralReview(conv.triangle),
246
+ });
247
+ }
248
+ return evidence;
249
+ }
250
+ /** The shared conventionProfile the 10x flag is measured against. */
251
+ function referenceProfileId(supportingResults) {
252
+ const profiles = new Set();
253
+ for (const doc of supportingResults ?? []) {
254
+ const profile = doc.result.engine.conventionProfile;
255
+ if (typeof profile === "string" && profile in CONVENTION_PROFILES)
256
+ profiles.add(profile);
257
+ }
258
+ return profiles.size === 1 ? [...profiles][0] : DETERMINISTIC_CL_PROFILE.id;
259
+ }
260
+ function targetLabelsOf(coherence) {
261
+ return coherence.findings.map((finding) => {
262
+ const target = finding.target === "tail"
263
+ ? "tail"
264
+ : `${finding.target.fromAgeMonths}-${finding.target.toAgeMonths}`;
265
+ const exact = finding.capability === "exact";
266
+ const label = {
267
+ target,
268
+ capability: finding.capability,
269
+ label: exact ? "replayed-exact" : "verified-by-value",
270
+ };
271
+ if (finding.note !== undefined)
272
+ label.note = finding.note;
273
+ return label;
274
+ });
275
+ }
276
+ function computeIntake(deps, studyInput, options) {
277
+ const strictness = options.strictness ?? "refuse";
278
+ const warnings = [];
279
+ try {
280
+ // 1. Schema + envelope-integrity validation via the interchange parser.
281
+ const parsed = parseDocument(studyInput, { strictness });
282
+ warnings.push(...parsed.warnings);
283
+ if (parsed.doc.kind !== "study") {
284
+ throw new ReservingError("BAD_INTERCHANGE", `promoteStudy needs a document of kind "study"; got kind "${parsed.doc.kind}"`);
285
+ }
286
+ const doc = parsed.doc;
287
+ const study = doc.study;
288
+ if (study.selections.length === 0) {
289
+ throw new AgentsError("EMPTY_STUDY", `Study "${study.title}" contains no selections; the promotion unit must carry at least one`);
290
+ }
291
+ // 2. Nested-document integrity (the study envelope's tag covers the study
292
+ // body, not the embedded documents' own claims).
293
+ const nested = [
294
+ ...study.triangles.map((t) => ({ kind: "triangle", doc: t })),
295
+ ...study.selections.map((s) => ({ kind: "selection", doc: s })),
296
+ ...(study.supportingResults ?? []).map((r) => ({ kind: r.kind, doc: r })),
297
+ ];
298
+ for (const { kind, doc: embedded } of nested) {
299
+ const check = verifyIntegrity(embedded);
300
+ if (!check.ok) {
301
+ const message = `Embedded ${kind} document states integrity ${check.actual ?? "(none)"} but its semantic ` +
302
+ `body hashes to ${check.expected}`;
303
+ if (strictness === "refuse")
304
+ throw new ReservingError("BAD_INTERCHANGE", message);
305
+ warnings.push(message);
306
+ }
307
+ }
308
+ // 3. Tolerance ceiling + the 10x-profile-default flag (spec 6 Gate 1).
309
+ const stated = study.expectations?.replayTolerance ?? null;
310
+ const ceiling = options.toleranceCeiling;
311
+ if (stated !== null && stated > ceiling) {
312
+ throw new AgentsError("TOLERANCE_CEILING_EXCEEDED", `Study replayTolerance ${stated} exceeds the host ceiling ${ceiling}; the host cannot ` +
313
+ "verify at the study's stated tolerance, so the study fails intake (loosen nothing here - " +
314
+ "fix the study upstream or raise the host ceiling deliberately)");
315
+ }
316
+ const profileId = referenceProfileId(study.supportingResults);
317
+ const profileDefault = CONVENTION_PROFILES[profileId].tolerance.central;
318
+ const tolerance = {
319
+ stated,
320
+ profileId,
321
+ profileDefault,
322
+ exceedsTenTimesProfileDefault: stated !== null && stated > 10 * profileDefault,
323
+ ceiling,
324
+ effective: Math.min(stated ?? profileDefault, ceiling),
325
+ };
326
+ // 4. ASOP 23 data review.
327
+ const dataReview = reviewStudyTriangles(study.triangles, warnings);
328
+ // 5. Per selection: triangle linkage, coherence, segment, replay.
329
+ const trianglesByTag = new Map(study.triangles.map((t) => [t.integrity, t]));
330
+ const targetsSeen = new Map(); // target -> selection integrity
331
+ const units = [];
332
+ for (const selectionDoc of study.selections) {
333
+ const tag = selectionDoc.selection.appliesTo.triangleIntegrity;
334
+ const triangleDoc = trianglesByTag.get(tag);
335
+ if (triangleDoc === undefined) {
336
+ throw new ReservingError("BAD_INTERCHANGE", `Selection ${selectionDoc.integrity} applies to triangle ${tag}, which the study does not carry`);
337
+ }
338
+ const replayed = docToSelections(selectionDoc, { triangleDoc, strictness });
339
+ warnings.push(...replayed.warnings);
340
+ const labels = labelsOf(triangleDoc);
341
+ const target = deps.resolveSegment(labels);
342
+ if (target === null) {
343
+ throw new AgentsError("SEGMENT_UNRESOLVED", `No workspace target matches segment labels ${JSON.stringify(labels)} for selection ` +
344
+ `${selectionDoc.integrity} (v1 resolves exact matches only; no fuzzy matching)`);
345
+ }
346
+ const priorSelection = targetsSeen.get(target);
347
+ if (priorSelection !== undefined) {
348
+ throw new AgentsError("SEGMENT_AMBIGUOUS", `Selections ${priorSelection} and ${selectionDoc.integrity} both resolve to workspace ` +
349
+ `target "${target}"; v1 promotes exactly one selection per segment`);
350
+ }
351
+ targetsSeen.set(target, selectionDoc.integrity);
352
+ const replayResult = runChainLadder(docToTriangle(triangleDoc).triangle, replayed.selections);
353
+ warnings.push(...replayResult.warnings);
354
+ const replayDoc = resultToDoc(replayResult, {
355
+ triangleDoc,
356
+ selectionDoc,
357
+ createdAt: options.now(),
358
+ parameters: { replayOf: selectionDoc.integrity, source: "promotion replay-verify" },
359
+ });
360
+ units.push({
361
+ selectionDoc,
362
+ triangleDoc,
363
+ labels,
364
+ target,
365
+ replayed,
366
+ replayDoc,
367
+ replayTotals: {
368
+ ultimate: replayResult.totals.ultimate,
369
+ unpaid: replayResult.totals.unpaid,
370
+ },
371
+ targets: targetLabelsOf(replayed.coherence),
372
+ verifiedByValueOnly: isValueOnlySelection(selectionDoc.selection),
373
+ });
374
+ }
375
+ // 6. Referee each supporting result against its replay (spec 6 Gate 2).
376
+ const crosschecks = [];
377
+ for (const supporting of study.supportingResults ?? []) {
378
+ const engine = {
379
+ name: supporting.result.engine.name,
380
+ version: supporting.result.engine.version,
381
+ };
382
+ if (supporting.kind !== "method-result") {
383
+ crosschecks.push({
384
+ resultIntegrity: supporting.integrity,
385
+ engine,
386
+ verdict: null,
387
+ report: null,
388
+ reason: "stochastic results compare at distribution level only (spec 3.2); not refereed in this phase",
389
+ });
390
+ continue;
391
+ }
392
+ const unit = units.find((u) => u.selectionDoc.integrity === supporting.result.appliesTo.selectionIntegrity &&
393
+ u.triangleDoc.integrity === supporting.result.appliesTo.triangleIntegrity);
394
+ if (unit === undefined) {
395
+ crosschecks.push({
396
+ resultIntegrity: supporting.integrity,
397
+ engine,
398
+ verdict: null,
399
+ report: null,
400
+ reason: "appliesTo tags match no (triangle, selection) pair in the study; nothing to referee against",
401
+ });
402
+ continue;
403
+ }
404
+ const report = crosscheck({
405
+ a: supporting,
406
+ b: unit.replayDoc,
407
+ tolerance: tolerance.effective,
408
+ selection: unit.selectionDoc,
409
+ createdAt: options.now(),
410
+ });
411
+ crosschecks.push({
412
+ resultIntegrity: supporting.integrity,
413
+ engine,
414
+ verdict: report.report.verdict,
415
+ report,
416
+ });
417
+ }
418
+ return {
419
+ ok: true,
420
+ ctx: {
421
+ study,
422
+ studyIntegrity: doc.integrity,
423
+ tolerance,
424
+ dataReview,
425
+ units,
426
+ crosschecks,
427
+ hardBlocked: crosschecks.some((c) => c.verdict === "disagree"),
428
+ warnings,
429
+ },
430
+ };
431
+ }
432
+ catch (err) {
433
+ return { ok: false, error: err instanceof Error ? err : new Error(String(err)) };
434
+ }
435
+ }
436
+ // ---------------------------------------------------------------------------
437
+ // Evidence assembly
438
+ function reviewSummaryText(dataReview) {
439
+ const totals = { pass: 0, warning: 0, fail: 0, notEvaluated: 0 };
440
+ for (const entry of dataReview) {
441
+ totals.pass += entry.report.summary.pass;
442
+ totals.warning += entry.report.summary.warning;
443
+ totals.fail += entry.report.summary.fail;
444
+ totals.notEvaluated += entry.report.summary.notEvaluated;
445
+ }
446
+ return `${totals.pass} pass, ${totals.warning} warning, ${totals.fail} fail, ${totals.notEvaluated} not evaluated`;
447
+ }
448
+ /** See StudyIntakeEvidence.workspaceBindingNote; one constant so every
449
+ * intake states the same scope, verbatim. */
450
+ export const WORKSPACE_BINDING_NOTE = "Scope of verification: coherence, replay, and referee checks verify the study against " +
451
+ "its OWN embedded triangle. Whether that triangle is this workspace's book of business " +
452
+ "is not machine-verified; that binding remains the reviewing actuary's judgment.";
453
+ function intakeEvidenceOf(ctx) {
454
+ return {
455
+ study: {
456
+ title: ctx.study.title,
457
+ analyst: ctx.study.narrative.analyst ?? null,
458
+ sourceRef: ctx.study.narrative.sourceRef ?? null,
459
+ summary: ctx.study.narrative.summary,
460
+ integrity: ctx.studyIntegrity,
461
+ },
462
+ replayTolerance: ctx.tolerance,
463
+ dataReview: ctx.dataReview,
464
+ coherence: ctx.units.map((u) => ({
465
+ selectionIntegrity: u.selectionDoc.integrity,
466
+ triangleIntegrity: u.triangleDoc.integrity,
467
+ coherence: u.replayed.coherence,
468
+ })),
469
+ segments: ctx.units.map((u) => ({
470
+ selectionIntegrity: u.selectionDoc.integrity,
471
+ labels: u.labels,
472
+ target: u.target,
473
+ })),
474
+ warnings: ctx.warnings,
475
+ workspaceBindingNote: WORKSPACE_BINDING_NOTE,
476
+ };
477
+ }
478
+ function replayEvidenceOf(ctx) {
479
+ const refereed = ctx.crosschecks.filter((c) => c.verdict !== null);
480
+ const verification = (ctx.study.supportingResults ?? []).length === 0
481
+ ? "Verification was selection coherence plus replay only: the study carried no " +
482
+ "supportingResults, so no cross-engine referee step ran (spec 6 Gate 2)."
483
+ : `Verification was coherence, replay, and referee: ${refereed.length} supporting ` +
484
+ `result(s) crosschecked against the replay at effective tolerance ${ctx.tolerance.effective}` +
485
+ (refereed.length < ctx.crosschecks.length
486
+ ? `; ${ctx.crosschecks.length - refereed.length} could not be refereed (see reasons)`
487
+ : "") +
488
+ ".";
489
+ return {
490
+ effectiveTolerance: ctx.tolerance.effective,
491
+ replays: ctx.units.map((u) => ({
492
+ selectionIntegrity: u.selectionDoc.integrity,
493
+ triangleIntegrity: u.triangleDoc.integrity,
494
+ segmentTarget: u.target,
495
+ targets: u.targets,
496
+ verifiedByValueOnly: u.verifiedByValueOnly,
497
+ replayTotals: u.replayTotals,
498
+ })),
499
+ crosschecks: ctx.crosschecks,
500
+ hardBlocked: ctx.hardBlocked,
501
+ verification,
502
+ };
503
+ }
504
+ function defaultDraftRationale(ctx) {
505
+ const { study, replay } = ctx;
506
+ const source = study.narrative.sourceRef ?? study.title;
507
+ const analyst = study.narrative.analyst !== undefined ? ` by ${study.narrative.analyst}` : "";
508
+ const verdicts = replay.crosschecks
509
+ .filter((c) => c.verdict !== null)
510
+ .map((c) => `${c.engine.name} ${c.verdict}`)
511
+ .join(", ");
512
+ return (`Adopting the selections of study "${study.title}" (${source})${analyst}. ` +
513
+ `Study summary: ${study.narrative.summary} ` +
514
+ `Replay verification: ${replay.replays.length} selection(s) verified at effective tolerance ` +
515
+ `${replay.effectiveTolerance}${verdicts.length > 0 ? `; referee verdicts: ${verdicts}` : ""}. ` +
516
+ replay.verification);
517
+ }
518
+ // ---------------------------------------------------------------------------
519
+ // Resume-schema building blocks
520
+ const nonBlankString = z
521
+ .string()
522
+ .refine((s) => s.trim() !== "", { message: "must not be blank" });
523
+ const actorField = z.string().min(1).optional();
524
+ /** Maps a free-form actor string onto the compliance ledger's closed enum:
525
+ * exact enum values pass through; anything else (an unattended MCP client,
526
+ * a named service) records as "agent" - disclosure-true for a non-human
527
+ * decider. What is recorded where: every ledger entry's `actor` carries
528
+ * this COARSE enum; the RAW actor string is preserved verbatim inside the
529
+ * attestation entry's value (`value.actor`), so the precise identity
530
+ * survives the enum mapping. */
531
+ function toAssumptionActor(actor) {
532
+ return actor === "default" || actor === "actuary" || actor === "agent" ? actor : "agent";
533
+ }
534
+ /** The gate a promotion was aborted at, or null when it is still live. */
535
+ function abortedStage(decisions) {
536
+ for (const gateId of ["study-intake", "replay-verify", "rationale"]) {
537
+ const decision = decisions[gateId];
538
+ if (decision?.decision === "abort")
539
+ return gateId;
540
+ }
541
+ return null;
542
+ }
543
+ const skipWhenAborted = (ctx) => {
544
+ const stage = abortedStage(ctx.decisions);
545
+ return stage === null ? null : `promotion aborted at the ${stage} gate`;
546
+ };
547
+ // ---------------------------------------------------------------------------
548
+ // The chain factory
549
+ function validateOptions(deps, options) {
550
+ const badOption = (detail) => {
551
+ throw new AgentsError("BAD_PROMOTION_OPTIONS", `promoteStudy: ${detail}`);
552
+ };
553
+ if (typeof deps !== "object" || deps === null)
554
+ badOption("deps must be an object");
555
+ for (const key of ["resolveSegment", "applySelections", "runAnalysis", "persistNote"]) {
556
+ if (typeof deps[key] !== "function")
557
+ badOption(`deps.${key} must be a function`);
558
+ }
559
+ if (!Number.isFinite(options.toleranceCeiling) || options.toleranceCeiling <= 0) {
560
+ badOption(`toleranceCeiling must be a positive finite number; got ${options.toleranceCeiling}`);
561
+ }
562
+ if (typeof options.now !== "function")
563
+ badOption("now must be a function returning an ISO timestamp");
564
+ if (options.strictness !== undefined && options.strictness !== "warn" && options.strictness !== "refuse") {
565
+ badOption(`strictness must be "warn" or "refuse"; got ${JSON.stringify(options.strictness)}`);
566
+ }
567
+ }
568
+ /**
569
+ * Builds the promotion judgment chain for one study. SYNCHRONOUS by design
570
+ * (see the accidental-thenable footgun in the module doc): assign the return
571
+ * value and register it on a Mastra instance, exactly like any
572
+ * createJudgmentChain workflow; then createRun/start/resume drive the gates.
573
+ *
574
+ * Reconstruction contract: promoteStudy(deps, studyDoc, options) is
575
+ * deterministic given the study document and deps.resolveSegment, so a host
576
+ * resuming a snapshot after a restart rebuilds the identical chain.
577
+ */
578
+ export function promoteStudy(deps, studyDoc, options) {
579
+ validateOptions(deps, options);
580
+ const intake = computeIntake(deps, studyDoc, options);
581
+ const ctx = intake.ok ? intake.ctx : null;
582
+ /** Gates 2-4 run only after Gate 1 succeeded, which requires intake.ok. */
583
+ const requireCtx = () => {
584
+ if (ctx === null) {
585
+ throw intake.ok ? new Error("unreachable") : intake.error;
586
+ }
587
+ return ctx;
588
+ };
589
+ const intakeGate = {
590
+ id: "study-intake",
591
+ stage: "study-intake",
592
+ resumeSchema: z.object({
593
+ decision: z.enum(["accept", "abort"]),
594
+ rationale: nonBlankString,
595
+ actor: actorField,
596
+ }),
597
+ gatherEvidence: () => {
598
+ const context = requireCtx(); // intake failures surface HERE, as a gate failure
599
+ const evidence = intakeEvidenceOf(context);
600
+ const tolerance = context.tolerance;
601
+ const flag = tolerance.exceedsTenTimesProfileDefault
602
+ ? ` WARNING: the stated tolerance exceeds 10x the ${tolerance.profileId} profile default (${tolerance.profileDefault}).`
603
+ : "";
604
+ const review = reviewSummaryText(context.dataReview);
605
+ const hasFailures = context.dataReview.some((entry) => entry.report.summary.fail > 0);
606
+ return {
607
+ recommendation: `Replay tolerance: stated ${tolerance.stated ?? "(none)"}, host ceiling ${tolerance.ceiling}, ` +
608
+ `effective ${tolerance.effective}.${flag} Data review: ${review}. ` +
609
+ `${context.units.length} selection(s) resolved to segment target(s) ` +
610
+ `[${context.units.map((u) => u.target).join(", ")}]. ` +
611
+ (hasFailures
612
+ ? "The data review found failing checks; recommend abort unless the findings are explainable."
613
+ : "Intake checks passed; accept to proceed to replay verification."),
614
+ evidence,
615
+ };
616
+ },
617
+ applyDecision: async (_gateCtx, decision) => ({
618
+ summary: decision.decision === "abort"
619
+ ? "promotion aborted at study intake"
620
+ : "study accepted for promotion",
621
+ }),
622
+ };
623
+ // The Gate 2 hard-block is STRUCTURAL: on any "disagree" referee verdict
624
+ // the resume schema admits only { decision: "abort" } - Mastra's own
625
+ // resume validation rejects an accept, and because intake is recomputed
626
+ // deterministically on reconstruction, the block survives restarts.
627
+ const replayDecisionSchema = ctx?.hardBlocked
628
+ ? z.literal("abort")
629
+ : z.enum(["accept", "abort"]);
630
+ const replayGate = {
631
+ id: "replay-verify",
632
+ stage: "replay-verify",
633
+ resumeSchema: z.object({
634
+ decision: replayDecisionSchema,
635
+ rationale: nonBlankString,
636
+ actor: actorField,
637
+ }),
638
+ skipWhen: skipWhenAborted,
639
+ gatherEvidence: () => {
640
+ const context = requireCtx();
641
+ const evidence = replayEvidenceOf(context);
642
+ const valueOnlyCount = evidence.replays.filter((r) => r.verifiedByValueOnly).length;
643
+ return {
644
+ recommendation: evidence.hardBlocked
645
+ ? "UNACCEPTABLE: a supporting result DISAGREES with the replay at the effective " +
646
+ `tolerance ${evidence.effectiveTolerance}. The gate cannot accept this study; abort ` +
647
+ "and fix it upstream (spec 6: tolerance editing is not an escape hatch)."
648
+ : `${evidence.replays.length} selection(s) verified at tolerance ${evidence.effectiveTolerance}` +
649
+ (valueOnlyCount > 0
650
+ ? `; ${valueOnlyCount} verified by value only (no independent recomputation)`
651
+ : "") +
652
+ `. ${evidence.verification} Accept to proceed to the rationale gate.`,
653
+ evidence,
654
+ };
655
+ },
656
+ applyDecision: async (_gateCtx, decision) => ({
657
+ summary: decision.decision === "abort"
658
+ ? "promotion aborted at replay verification"
659
+ : `replay verification accepted (${requireCtx().units.length} selection(s), tolerance ${requireCtx().tolerance.effective})`,
660
+ }),
661
+ };
662
+ const rationaleGate = {
663
+ id: "rationale",
664
+ stage: "rationale",
665
+ resumeSchema: z.object({
666
+ decision: z.enum(["approve", "abort"]),
667
+ rationale: nonBlankString,
668
+ attestation: nonBlankString,
669
+ actor: actorField,
670
+ }),
671
+ skipWhen: skipWhenAborted,
672
+ gatherEvidence: async () => {
673
+ const context = requireCtx();
674
+ const draftCtx = {
675
+ study: context.study,
676
+ studyIntegrity: context.studyIntegrity,
677
+ intake: intakeEvidenceOf(context),
678
+ replay: replayEvidenceOf(context),
679
+ };
680
+ const draft = await (options.draftRationale ?? defaultDraftRationale)(draftCtx);
681
+ const witnessedResults = witnessedResultsOf(context.study);
682
+ const evidence = {
683
+ draftRationale: draft,
684
+ attestationRequired: true,
685
+ study: {
686
+ title: context.study.title,
687
+ sourceRef: context.study.narrative.sourceRef ?? null,
688
+ analyst: context.study.narrative.analyst ?? null,
689
+ },
690
+ witnessedResults,
691
+ };
692
+ // Disclosed, never silently blocked: the actuary decides whether a
693
+ // non-reproducible result is acceptable support, but they must be told
694
+ // it is one before their attestation is written to the ledger.
695
+ const witnessedNotice = witnessedResults.length === 0
696
+ ? ""
697
+ : ` ATTENTION: ${witnessedResults.length} supporting result(s) are WITNESSED, not ` +
698
+ `reproducible — ${witnessedResults
699
+ .map((w) => {
700
+ const drift = w.stability === null
701
+ ? "no stability check was run"
702
+ : w.stability.byteIdentical
703
+ ? `${w.stability.repeats} repeat runs agreed exactly`
704
+ : `repeat runs DIFFERED (max relative deviation ${w.stability.maxRelativeDeviation ?? "unreported"})`;
705
+ return `${w.method} on ${w.engine} (${drift})`;
706
+ })
707
+ .join("; ")}. Re-running these will not reproduce the numbers this study relies on. ` +
708
+ "Your attestation covers relying on them (spec 16).";
709
+ return {
710
+ recommendation: "Review and edit the draft rationale; the final text you resume with is recorded " +
711
+ "verbatim in the assumption ledger. An attestation (who authored/reviewed the " +
712
+ "rationale) is required." +
713
+ witnessedNotice,
714
+ evidence,
715
+ };
716
+ },
717
+ applyDecision: async (_gateCtx, decision) => ({
718
+ summary: decision.decision === "abort"
719
+ ? "promotion aborted at the rationale gate"
720
+ : "rationale approved (attestation on file)",
721
+ }),
722
+ };
723
+ const analysisLabelOf = (context) => `Study promotion - ${context.study.title}`;
724
+ const ledgerSourceOf = (context) => `${context.study.narrative.sourceRef ?? context.study.title} ` +
725
+ `(study ${context.studyIntegrity}, tolerance ${context.tolerance.effective})`;
726
+ const applyGate = {
727
+ id: "apply",
728
+ stage: "apply",
729
+ resumeSchema: z.object({
730
+ decision: z.enum(["apply", "abort"]),
731
+ rationale: nonBlankString,
732
+ actor: actorField,
733
+ }),
734
+ skipWhen: skipWhenAborted,
735
+ gatherEvidence: () => {
736
+ const context = requireCtx();
737
+ const evidence = {
738
+ applications: context.units.map((u) => ({
739
+ segmentTarget: u.target,
740
+ selectionIntegrity: u.selectionDoc.integrity,
741
+ developmentCount: u.selectionDoc.selection.development.length,
742
+ tailFactor: u.selectionDoc.selection.tail?.value ?? 1,
743
+ })),
744
+ analysisLabel: analysisLabelOf(context),
745
+ ledgerSource: ledgerSourceOf(context),
746
+ };
747
+ return {
748
+ recommendation: `Apply ${evidence.applications.length} selection(s) to ` +
749
+ `[${evidence.applications.map((a) => a.segmentTarget).join(", ")}], rerun the analysis, ` +
750
+ "and record the ledger entries. This mutates host state.",
751
+ evidence,
752
+ };
753
+ },
754
+ applyDecision: async (gateCtx, decision) => {
755
+ if (decision.decision === "abort") {
756
+ return { summary: "promotion aborted at the apply gate" };
757
+ }
758
+ const context = requireCtx();
759
+ const approval = gateCtx.decisions["rationale"];
760
+ if (approval === undefined || approval.decision !== "approve") {
761
+ throw new AgentsError("MISSING_RATIONALE", "The apply gate ran without an approved rationale gate decision; the ledger records " +
762
+ "the rationale-gate text verbatim and cannot proceed without it");
763
+ }
764
+ const actor = approval.actor ?? options.actorDefault ?? "actuary";
765
+ const ledgerActor = toAssumptionActor(actor);
766
+ const source = ledgerSourceOf(context);
767
+ for (const unit of context.units) {
768
+ await deps.applySelections(unit.selectionDoc, unit.replayed.selections, unit.target);
769
+ }
770
+ await deps.runAnalysis(analysisLabelOf(context));
771
+ const ledgerEntries = context.units.map((unit) => ({
772
+ field: `selections.${unit.target}`,
773
+ value: {
774
+ development: unit.selectionDoc.selection.development.map((d) => ({
775
+ fromAgeMonths: d.fromAgeMonths,
776
+ toAgeMonths: d.toAgeMonths,
777
+ value: d.value,
778
+ })),
779
+ tailFactor: unit.selectionDoc.selection.tail?.value ?? 1,
780
+ },
781
+ source,
782
+ rationale: approval.rationale, // Gate 3's final text, verbatim
783
+ actor: ledgerActor,
784
+ }));
785
+ // The attestation entry's value carries BOTH strings verbatim: the
786
+ // attestation itself (spec 8: lands in the ledger) and the RAW actor
787
+ // identity, which the entry-level `actor` collapses to the coarse
788
+ // compliance enum (see toAssumptionActor).
789
+ ledgerEntries.push({
790
+ field: "promotion.attestation",
791
+ value: { attestation: approval.attestation, actor },
792
+ source,
793
+ rationale: approval.rationale,
794
+ actor: ledgerActor,
795
+ });
796
+ return {
797
+ summary: `applied ${context.units.length} selection(s) to [${context.units
798
+ .map((u) => u.target)
799
+ .join(", ")}]`,
800
+ ledgerEntries,
801
+ };
802
+ },
803
+ };
804
+ return createJudgmentChain({
805
+ id: PROMOTION_CHAIN_ID,
806
+ gates: [intakeGate, replayGate, rationaleGate, applyGate],
807
+ now: options.now,
808
+ onComplete: async (outcome, chainCtx) => {
809
+ // Persist the trail + ledger JSON exactly like the server's ELR chain,
810
+ // but only when the promotion actually applied (aborted chains complete
811
+ // with their trail and an empty ledger; nothing to persist).
812
+ const applied = chainCtx.decisions["apply"];
813
+ if (applied?.decision !== "apply")
814
+ return;
815
+ const approval = chainCtx.decisions["rationale"];
816
+ const author = approval?.actor ?? options.actorDefault ?? "actuary";
817
+ await deps.persistNote(`Study promotion trail:\n${outcome.trail
818
+ .map((t) => `- ${t.stage}: ${t.decision}${t.rationale ? ` - ${t.rationale}` : ""}`)
819
+ .join("\n")}`, author);
820
+ await deps.persistNote(`Study promotion assumption ledger:\n${JSON.stringify({ entries: outcome.ledger.entries }, null, 2)}`, author);
821
+ },
822
+ });
823
+ }
824
+ //# sourceMappingURL=promotion.js.map