@apex-inc/mcp-server 0.61.1 → 0.63.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.
@@ -4,10 +4,13 @@ import { join } from "node:path";
4
4
  import { apiGet, apiPost, apiPatch, apiDelete, getActiveWorkspace, } from "../api-client.js";
5
5
  import { resolveExperimentHypothesis } from "../experiment-copy.js";
6
6
  import { activationLiveLine, shouldRefuseActivationWiring } from "../activation-wiring.js";
7
+ import { parseFrontDoorRefusal, renderFrontDoorRefusal } from "../belief-front-door.js";
7
8
  import { apexBaseUrl } from "../base-url.js";
8
9
  import { fetchLiveTestHits, formatLiveTestStop, isFileStop, isObjectStop, } from "../live-test-guard.js";
9
10
  import { hasConflictAdvisory, renderConflictAdvisory, } from "../conflict-advisory.js";
10
- import { APEX, controlPctOf, daysRunningOf, findVariant, missingScreenshotLines, formatArmLine, titleCaseEvent, assertTargetUrlForActiveWorkspace, errMsg, resolveCreateSurface, } from "../tool-shared.js";
11
+ import { APEX, controlPctOf, daysRunningOf, predictionLines, findVariant, missingScreenshotLines, formatArmLine, titleCaseEvent, assertTargetUrlForActiveWorkspace, errMsg, resolveCreateSurface, } from "../tool-shared.js";
12
+ const STARTING_CONFIDENCE_HELP = "Leave unset. A new claim with no tests starts at 50% (untested) and moves only when a test concludes. Set it only when you can name the evidence (a past test or measured data), and say what it is.";
13
+ const NEW_BECAUSE_HELP = "Only after Apex returned related beliefs and the user said this is a different claim: one sentence on how it differs. Kept on the record.";
11
14
  const NETWORK_WORD = {
12
15
  meta: "Meta",
13
16
  google: "Google",
@@ -209,43 +212,67 @@ async function createAdHoldout(args) {
209
212
  }
210
213
  export const experimentTools = {
211
214
  plan_experiment: {
212
- description: `${APEX} — PLANNING ONLY, does not create anything. Analyzes a goal against existing beliefs and experiments, then returns structured options for the user to choose from. After calling, you MUST present the returned options as a numbered list or poll and wait for the user to pick before calling any other Apex tools.`,
215
+ description: `${APEX} — PLANNING ONLY, does not create anything. Run this FIRST, before writing any belief or prediction. Pass the claim you expect to test as belief (or just the goal): returns beliefs already on file that make the same or a related claim, with their confidence, evidence and past tests; the most recent beliefs; and tests already run on the target page. After calling, you MUST present the returned options as a numbered list or poll and wait for the user to pick (link an existing belief, or write a new claim) before calling any other Apex tools.`,
213
216
  schema: z.object({
214
217
  goal: z.string().describe("What the user wants to improve or test (e.g. 'improve signup conversion on landing page')"),
215
218
  targetUrl: z.string().optional().describe("URL of the page to test, if known"),
219
+ belief: z.string().optional().describe("The claim you expect to test, if you have one. Matched against beliefs on file far better than the goal alone."),
216
220
  }),
217
- handler: async ({ goal, targetUrl }) => {
218
- const [beliefs, experiments] = await Promise.all([
221
+ handler: async ({ goal, targetUrl, belief }) => {
222
+ const statement = belief?.trim() || goal;
223
+ const [beliefs, experiments, screen] = await Promise.all([
219
224
  apiGet("/api/beliefs"),
220
225
  apiGet("/api/experiments?unified=true"),
226
+ apiGet(`/api/beliefs/similar?statement=${encodeURIComponent(statement)}`).catch(() => ({ data: null })),
221
227
  ]);
222
- const keywords = goal
223
- .toLowerCase()
224
- .replace(/[^a-z0-9\s]/g, "")
225
- .split(/\s+/)
226
- .filter((w) => w.length > 3);
227
- const relatedBeliefs = beliefs.filter((b) => {
228
- const words = b.statement.toLowerCase();
229
- return keywords.some((kw) => words.includes(kw));
230
- });
231
- const relatedExperiments = experiments.filter((e) => {
232
- const words = e.name.toLowerCase();
233
- return keywords.some((kw) => words.includes(kw));
234
- });
228
+ const related = screen.data?.similar ?? [];
229
+ const relatedIds = new Set(related.map((b) => b.id));
230
+ const recentBeliefs = [...beliefs]
231
+ .filter((b) => !relatedIds.has(b.id))
232
+ .sort((a, b) => (b.createdAt ?? "").localeCompare(a.createdAt ?? ""))
233
+ .slice(0, 3);
234
+ const pagePath = (() => {
235
+ try {
236
+ return targetUrl ? new URL(targetUrl).pathname.replace(/\/$/, "") : null;
237
+ }
238
+ catch {
239
+ return null;
240
+ }
241
+ })();
242
+ const testsOnThisPage = pagePath
243
+ ? experiments.filter((e) => {
244
+ try {
245
+ return Boolean(e.targetUrl) && new URL(e.targetUrl).pathname.replace(/\/$/, "") === pagePath;
246
+ }
247
+ catch {
248
+ return false;
249
+ }
250
+ })
251
+ : [];
235
252
  const plan = {
236
253
  _apex: true,
237
254
  goal,
238
255
  targetUrl: targetUrl || null,
239
- relatedBeliefs: relatedBeliefs.slice(0, 5).map((b) => ({
256
+ sameClaimOnFile: screen.data?.duplicate
257
+ ? { id: screen.data.duplicate.id, statement: screen.data.duplicate.statement }
258
+ : null,
259
+ relatedBeliefs: related.map((b) => ({
240
260
  id: b.id,
241
261
  statement: b.statement,
242
262
  confidence: Math.round(b.confidence * 100),
243
- tested: experiments.some((e) => e.beliefId === b.id),
263
+ evidence: b.evidence_count,
264
+ tests: b.tests,
244
265
  })),
245
- relatedExperiments: relatedExperiments.slice(0, 3).map((e) => ({
266
+ recentBeliefs: recentBeliefs.map((b) => ({
267
+ id: b.id,
268
+ statement: b.statement,
269
+ confidence: Math.round(b.confidence * 100),
270
+ })),
271
+ testsOnThisPage: testsOnThisPage.slice(0, 5).map((e) => ({
246
272
  id: e.id,
247
273
  name: e.name,
248
274
  status: e.status,
275
+ beliefId: e.beliefId ?? null,
249
276
  })),
250
277
  suggestedBeliefs: [
251
278
  `Users who see [specific change] will convert at a higher rate`,
@@ -258,18 +285,13 @@ export const experimentTools = {
258
285
  "click_through_rate",
259
286
  "time_on_page",
260
287
  ],
261
- suggestedConfidenceLevels: [
262
- { label: "Low (30%) — Gut feeling, no supporting data yet", value: 30 },
263
- { label: "Medium (55%) — Some signals, but hasn't been tested", value: 55 },
264
- { label: "High (75%) — Strong evidence from past experiments or data", value: 75 },
265
- { label: "Very High (90%) — Near-certain, well-established pattern", value: 90 },
266
- ],
288
+ startingConfidence: "Not a choice. A linked belief keeps the confidence its evidence earned. A new claim with no tests starts at 50% (untested) and moves only when a test concludes.",
267
289
  suggestedTrafficAllocations: [
268
290
  { label: "Adaptive (recommended) — Automatically shifts traffic toward the winning variant", control: 50, variant: 50, adaptive: true },
269
291
  { label: "Balanced 50/50 — Equal split, fastest to reach significance", control: 50, variant: 50, adaptive: false },
270
292
  { label: "Conservative 80/20 — Minimal exposure to variant, lower risk", control: 80, variant: 20, adaptive: false },
271
293
  ],
272
- _instructions: "IMPORTANT: Present each section as a numbered selection the user can pick from. Use a poll or numbered list for beliefs, confidence, metrics, and traffic split. Do NOT auto-fill any values.",
294
+ _instructions: "IMPORTANT: Lead with what is already known. If sameClaimOnFile is set, recommend linking it. Otherwise show relatedBeliefs with their confidence, evidence and tests (a discarded test is not evidence) and testsOnThisPage, and ask the user to link one or write a new claim. Read a past test's prediction with get_results before predicting a new one. Then present metrics and traffic split as numbered selections. Do NOT auto-fill any values.",
273
295
  };
274
296
  return {
275
297
  content: [
@@ -282,7 +304,7 @@ export const experimentTools = {
282
304
  },
283
305
  },
284
306
  start_reasoning: {
285
- description: `${APEX} — Record a belief and hypothesis chain. Only call AFTER the user has picked a belief statement and confidence level from the options you presented.`,
307
+ description: `${APEX} — Record a NEW belief and hypothesis chain. Only call AFTER plan_experiment showed the related beliefs and past tests and the user chose to write a new claim instead of linking one. Apex refuses a claim already on file (link it) and a related one without new_because.`,
286
308
  schema: z.object({
287
309
  decision: z.string().describe("What you want to improve or change"),
288
310
  belief: z.string().describe("The assumption — must be confirmed by the user"),
@@ -290,19 +312,35 @@ export const experimentTools = {
290
312
  .number()
291
313
  .min(0)
292
314
  .max(100)
293
- .describe("How sure the user is about this assumption (0-100%) — must be chosen by the user"),
315
+ .optional()
316
+ .describe(STARTING_CONFIDENCE_HELP),
317
+ newBecause: z
318
+ .string()
319
+ .optional()
320
+ .describe(NEW_BECAUSE_HELP),
294
321
  }),
295
- handler: async ({ decision, belief, confidence }) => {
296
- const b = await apiPost("/api/beliefs", {
297
- statement: belief,
298
- confidence: confidence / 100,
299
- });
322
+ handler: async ({ decision, belief, confidence, newBecause }) => {
323
+ const startingConfidence = (confidence ?? 50) / 100;
324
+ let b;
325
+ try {
326
+ b = await apiPost("/api/beliefs", {
327
+ statement: belief,
328
+ confidence: startingConfidence,
329
+ ...(newBecause ? { new_because: newBecause } : {}),
330
+ });
331
+ }
332
+ catch (err) {
333
+ const refusal = parseFrontDoorRefusal(err);
334
+ if (!refusal)
335
+ throw err;
336
+ return { content: [{ type: "text", text: renderFrontDoorRefusal(refusal, APEX) }], isError: true };
337
+ }
300
338
  const hypothesis = `If we act on "${belief.slice(0, 80)}", then we should see a measurable improvement in our target metric.`;
301
339
  const h = await apiPost("/api/hypotheses", {
302
340
  beliefId: b.id,
303
341
  statement: hypothesis,
304
342
  predictedEffect: `Impact related to: ${decision.slice(0, 60)}`,
305
- confidence: confidence / 100,
343
+ confidence: b.confidence,
306
344
  status: "active",
307
345
  });
308
346
  return {
@@ -328,18 +366,29 @@ export const experimentTools = {
328
366
  },
329
367
  },
330
368
  create_belief: {
331
- description: `${APEX} — Record an assumption your team is making. Confirm the belief statement and confidence with the user before calling.`,
369
+ description: `${APEX} — Record a NEW assumption your team is making. Check list_beliefs (or plan_experiment) first: Apex refuses a claim already on file (link it instead) and a related one unless you pass new_because. Confirm the statement with the user before calling.`,
332
370
  schema: z.object({
333
371
  statement: z.string().describe("The assumption statement"),
334
- confidence: z.number().min(0).max(100).describe("How sure you are (0-100%)"),
372
+ confidence: z.number().min(0).max(100).optional().describe(STARTING_CONFIDENCE_HELP),
335
373
  parentBeliefId: z.string().optional().describe("ID of a parent assumption, if this is a sub-assumption"),
374
+ newBecause: z.string().optional().describe(NEW_BECAUSE_HELP),
336
375
  }),
337
- handler: async ({ statement, confidence, parentBeliefId }) => {
338
- const b = await apiPost("/api/beliefs", {
339
- statement,
340
- confidence: confidence / 100,
341
- parentBeliefId,
342
- });
376
+ handler: async ({ statement, confidence, parentBeliefId, newBecause }) => {
377
+ let b;
378
+ try {
379
+ b = await apiPost("/api/beliefs", {
380
+ statement,
381
+ confidence: (confidence ?? 50) / 100,
382
+ parentBeliefId,
383
+ ...(newBecause ? { new_because: newBecause } : {}),
384
+ });
385
+ }
386
+ catch (err) {
387
+ const refusal = parseFrontDoorRefusal(err);
388
+ if (!refusal)
389
+ throw err;
390
+ return { content: [{ type: "text", text: renderFrontDoorRefusal(refusal, APEX) }], isError: true };
391
+ }
343
392
  return {
344
393
  content: [
345
394
  {
@@ -364,7 +413,8 @@ export const experimentTools = {
364
413
  hypothesisId: z.string().optional().describe("ID of the expected outcome"),
365
414
  predictionId: z.string().optional().describe("ID of the expected impact"),
366
415
  beliefStatement: z.string().optional().describe("If you don't have a beliefId, pass the assumption statement and Apex will create the belief (and a hypothesis) and link them to this experiment."),
367
- beliefConfidence: z.number().min(0).max(100).optional().describe("Confidence (0-100%) for the belief created from beliefStatement. Defaults to 50."),
416
+ beliefConfidence: z.number().min(0).max(100).optional().describe(`For a belief created from beliefStatement. ${STARTING_CONFIDENCE_HELP}`),
417
+ newBecause: z.string().optional().describe(`With beliefStatement. ${NEW_BECAUSE_HELP}`),
368
418
  hypothesisStatement: z.string().optional().describe("Optional hypothesis statement to record alongside a belief created from beliefStatement."),
369
419
  primaryMetricEvent: z.string().optional().describe("Event the experiment optimizes: a standard Apex event (e.g. 'checkout_completed') or any event this workspace receives or defined with define_event (e.g. 'demo_booked'). Checked against this workspace; a name it has never seen is refused with the closest matches. Prefer an OUTCOME event (purchase/signup) over a proxy (email_open) — use list_metrics to see which are DETECTED with volume."),
370
420
  primaryMetricType: z.enum(["rate", "count", "revenue", "duration"]).optional().describe("How the goal is measured. 'rate' (default) = did it happen. 'revenue'/'duration' = a continuous value summed per subject (set primaryMetricValueProperty). Use 'revenue' for Stripe/purchase-value goals."),
@@ -506,6 +556,19 @@ export const experimentTools = {
506
556
  catch {
507
557
  /* conflict check is advisory; never block the preview */
508
558
  }
559
+ // Belief front door, shown before anything is written: the same check
560
+ // the create will enforce, so the user picks link-or-new up front.
561
+ let beliefFrontDoor;
562
+ if (!args.beliefId && args.beliefStatement) {
563
+ try {
564
+ const screen = await apiGet(`/api/beliefs/similar?statement=${encodeURIComponent(args.beliefStatement)}`);
565
+ if (screen.data && (screen.data.duplicate || screen.data.similar.length > 0))
566
+ beliefFrontDoor = screen.data;
567
+ }
568
+ catch {
569
+ /* the create enforces it either way */
570
+ }
571
+ }
509
572
  const recipe = {
510
573
  _apex: true,
511
574
  _type: "experiment_preview",
@@ -526,13 +589,14 @@ export const experimentTools = {
526
589
  beliefId: args.beliefId || null,
527
590
  beliefStatement: args.beliefStatement || null,
528
591
  predictionId: args.predictionId || null,
592
+ ...(beliefFrontDoor ? { _belief_front_door: beliefFrontDoor } : {}),
529
593
  ...(conflictAdvisory ? { _conflict_advisory: conflictAdvisory } : {}),
530
594
  ...(conversionEventSet
531
595
  ? {}
532
596
  : {
533
597
  _conversion_goal_warning: "No conversion event set. The draft will be created, but it CANNOT be started until you set the outcome you're optimizing. Call list_events to see what's firing (prefer a real outcome like signup/purchase over form_submit), then pass primaryMetricEvent. Confirm the goal with the user before creating.",
534
598
  }),
535
- _instructions: `Before proposing variant copy, ground every factual claim in .apex/brand-truth.md (read it; cite the line each claim traces to; if a claim isn't backed there, ask the user instead of inventing it).${conflictAdvisory ? " IMPORTANT: _conflict_advisory is set — show it to the user and resolve the overlap (mutex / variant / sequence) before creating." : ""}${conversionEventSet ? "" : " IMPORTANT: _conversion_goal_warning is set — surface it and set a conversion event (list_events → primaryMetricEvent) before creating, unless the user explicitly wants a draft to fill in later."} Then present this as a summary and ask the user to confirm (1), adjust (2), or cancel (3). Do NOT create the experiment until confirmed.`,
599
+ _instructions: `Before proposing variant copy, ground every factual claim in .apex/brand-truth.md (read it; cite the line each claim traces to; if a claim isn't backed there, ask the user instead of inventing it).${beliefFrontDoor ? ` IMPORTANT: _belief_front_door is set — beliefs already on file make ${beliefFrontDoor.duplicate ? "this exact claim" : "a related claim"}. Show them with their tests and ask the user to link one (pass beliefId instead of beliefStatement; its confidence comes from its evidence)${beliefFrontDoor.duplicate ? "" : " or confirm it is a different claim (pass newBecause with how it differs)"}. Creating without that is refused.` : ""}${conflictAdvisory ? " IMPORTANT: _conflict_advisory is set — show it to the user and resolve the overlap (mutex / variant / sequence) before creating." : ""}${conversionEventSet ? "" : " IMPORTANT: _conversion_goal_warning is set — surface it and set a conversion event (list_events → primaryMetricEvent) before creating, unless the user explicitly wants a draft to fill in later."} Then present this as a summary and ask the user to confirm (1), adjust (2), or cancel (3). Do NOT create the experiment until confirmed.`,
536
600
  };
537
601
  return { content: [{ type: "text", text: JSON.stringify(recipe, null, 2) }] };
538
602
  }
@@ -543,10 +607,23 @@ export const experimentTools = {
543
607
  let hypothesisId = args.hypothesisId;
544
608
  if (!beliefId && args.beliefStatement) {
545
609
  const confidence = args.beliefConfidence != null ? args.beliefConfidence / 100 : 0.5;
546
- const b = await apiPost("/api/beliefs", {
547
- statement: args.beliefStatement,
548
- confidence,
549
- });
610
+ let b;
611
+ try {
612
+ b = await apiPost("/api/beliefs", {
613
+ statement: args.beliefStatement,
614
+ confidence,
615
+ ...(args.newBecause ? { new_because: args.newBecause } : {}),
616
+ });
617
+ }
618
+ catch (err) {
619
+ const refusal = parseFrontDoorRefusal(err);
620
+ if (!refusal)
621
+ throw err;
622
+ return {
623
+ content: [{ type: "text", text: `${renderFrontDoorRefusal(refusal, APEX)}\n\nNo experiment was created.` }],
624
+ isError: true,
625
+ };
626
+ }
550
627
  beliefId = b.id;
551
628
  const hypothesisStatement = args.hypothesisStatement ??
552
629
  `If we act on "${args.beliefStatement.slice(0, 80)}", then we should see a measurable improvement in "${args.name}".`;
@@ -803,9 +880,14 @@ export const experimentTools = {
803
880
  : "NOT SET — required before start (see _instructions)",
804
881
  decisionWindowDays: args.runtimeDays ?? 14,
805
882
  minSamplePerArm: args.minSamplePerArm ?? 50,
806
- beliefId: beliefId || null,
807
- hypothesisId: hypothesisId || null,
808
- predictionId: args.predictionId || null,
883
+ // What the server saved, not what this call sent: the API mints the
884
+ // prediction (and sometimes the hypothesis) on create.
885
+ beliefId: exp.beliefId || beliefId || null,
886
+ hypothesisId: exp.hypothesisId || hypothesisId || null,
887
+ predictionId: exp.predictionId || args.predictionId || null,
888
+ prediction: exp.prediction?.magnitude
889
+ ? { direction: exp.prediction.direction, magnitude: exp.prediction.magnitude }
890
+ : null,
809
891
  sdk: mode === "sdk" ? {
810
892
  ...(isMobile
811
893
  ? {
@@ -1335,8 +1417,32 @@ export const experimentTools = {
1335
1417
  return { content: [{ type: "text", text: JSON.stringify(recipe, null, 2) }] };
1336
1418
  },
1337
1419
  },
1420
+ discard_experiment: {
1421
+ description: `${APEX} — Put away a test that never really ran (a draft, one waiting on deploy, or a paused test where no version reached its sample floor). It is archived with the reason, and NO outcome is recorded and its belief is not touched, because a handful of visitors is noise, not evidence. Use this instead of conclude_experiment when a test is being replaced or was set up wrong before it collected anything. The server refuses (409 discard_not_allowed) while the test is running (pause it first) and once a version reached the floor (end it with conclude_experiment so the result is recorded). Ask the user to confirm before calling.`,
1422
+ schema: z.object({
1423
+ experimentId: z.string().describe("The experiment ID to discard"),
1424
+ reason: z.string().describe("One sentence on why it is being discarded, e.g. 'Restarted on the existing belief'. Kept on the record."),
1425
+ }),
1426
+ handler: async ({ experimentId, reason }) => {
1427
+ const exp = await apiPatch(`/api/experiments/${encodeURIComponent(experimentId)}`, { action: "discard", reason });
1428
+ return {
1429
+ content: [
1430
+ {
1431
+ type: "text",
1432
+ text: [
1433
+ `${APEX} Experiment Discarded`,
1434
+ ``,
1435
+ ` "${exp.name}" was put away without a result.`,
1436
+ ` No outcome was recorded and its belief was not changed.`,
1437
+ ` Reason kept on the record: ${exp.discardReason ?? reason}`,
1438
+ ].join("\n"),
1439
+ },
1440
+ ],
1441
+ };
1442
+ },
1443
+ },
1338
1444
  archive_experiment: {
1339
- description: `${APEX} — Archive an experiment. Removes it from active views but preserves all data, learnings, and belief graph connections. Archived experiments still contribute to intelligence scoring and recommendations. A RUNNING experiment cannot be archived — end it first (conclude_experiment / promote_winner) so its result + belief are captured; the server returns 409 archive_requires_conclusion otherwise. Ask the user to confirm before calling.`,
1445
+ description: `${APEX} — Archive an experiment. Removes it from active views but preserves all data, learnings, and belief graph connections. Archiving does not record a result or update a belief. A RUNNING experiment, or a paused one where a version already reached the sample floor, cannot be archived — end it first (conclude_experiment / promote_winner) so its result + belief are captured; the server returns 409 archive_requires_conclusion otherwise. For a test that never collected enough people to mean anything, use discard_experiment so the record says why. Ask the user to confirm before calling.`,
1340
1446
  schema: z.object({
1341
1447
  experimentId: z.string().describe("The experiment ID to archive"),
1342
1448
  }),
@@ -1418,7 +1524,7 @@ export const experimentTools = {
1418
1524
  },
1419
1525
  },
1420
1526
  get_results: {
1421
- description: `${APEX} — Get the website experiment card: visitors, conversions, and confidence from GET /api/experiments/:id?unified=true. For readiness (collecting / decisive / inconclusive) or a letter Experiment step, use get_experiment_results.`,
1527
+ description: `${APEX} — Get the website experiment card: visitors, conversions, confidence, and the committed prediction, hypothesis and belief (read these back before reasoning about a result) from GET /api/experiments/:id?unified=true. For readiness (collecting / decisive / inconclusive) or a letter Experiment step, use get_experiment_results.`,
1422
1528
  schema: z.object({
1423
1529
  experimentId: z.string().describe("The experiment ID"),
1424
1530
  }),
@@ -1463,7 +1569,8 @@ export const experimentTools = {
1463
1569
  varB
1464
1570
  ? ` ${varB.assigned} visitors | ${varB.converted} conversions | ${cvr(varB)} CVR`
1465
1571
  : " No data yet",
1466
- exp.beliefId ? `\n Linked belief: ${exp.beliefId}` : "",
1572
+ ``,
1573
+ ...predictionLines(exp),
1467
1574
  ``,
1468
1575
  `${"═".repeat(40)}`,
1469
1576
  ``,
@@ -1527,6 +1634,41 @@ export const experimentTools = {
1527
1634
  lines,
1528
1635
  ``,
1529
1636
  `Link one to a new experiment with its id, or generate a fresh belief from your hypothesis.`,
1637
+ `If two of these state the same claim, merge them (merge_beliefs) so their evidence adds up in one place.`,
1638
+ ].join("\n"),
1639
+ },
1640
+ ],
1641
+ };
1642
+ },
1643
+ },
1644
+ merge_beliefs: {
1645
+ description: `${APEX} — Merge a duplicate belief into the one that survives. Use when two beliefs state the same claim, so their evidence is split and neither confidence tells the truth. Moves the duplicate's evidence, hypotheses, predictions, outcomes, decision-log entries, child beliefs and linked tests onto the survivor, writes a decision-log entry naming what moved, and keeps the duplicate as a redirect (old ids still resolve; lists hide it). Not reversible from the tools. Show the user both statements and get their go-ahead before calling.`,
1646
+ schema: z.object({
1647
+ beliefId: z.string().describe("The duplicate belief, folded away"),
1648
+ into: z.string().describe("The belief that survives"),
1649
+ }),
1650
+ handler: async ({ beliefId, into }) => {
1651
+ const body = await apiPost(`/api/beliefs/${encodeURIComponent(beliefId)}/merge`, { into });
1652
+ if (!body.data) {
1653
+ return {
1654
+ content: [{ type: "text", text: `${APEX} Merge refused: ${body.error ?? "unknown error"}` }],
1655
+ isError: true,
1656
+ };
1657
+ }
1658
+ const { survivor, merged, moved } = body.data;
1659
+ return {
1660
+ content: [
1661
+ {
1662
+ type: "text",
1663
+ text: [
1664
+ `${APEX} Beliefs Merged`,
1665
+ ``,
1666
+ ` Folded: [${merged.id}] ${merged.statement}`,
1667
+ ` Into: [${survivor.id}] ${survivor.statement} (${Math.round(survivor.confidence * 100)}% confidence)`,
1668
+ ``,
1669
+ ` Moved: ${moved.evidence} evidence, ${moved.hypotheses} hypotheses, ${moved.predictions} predictions, ${moved.outcomes} outcomes, ${moved.ledgerEntries} decision-log entries, ${moved.childBeliefs} child beliefs.`,
1670
+ ` Tests now linked to the survivor: ${moved.experiments.length > 0 ? moved.experiments.join(", ") : "none"}.`,
1671
+ ` The old id still resolves to the survivor.`,
1530
1672
  ].join("\n"),
1531
1673
  },
1532
1674
  ],