:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(aio): add scorer passing rules and unified editor (#110056)
Radu Raicea7a80e7804342
diff --git a/docs/internal/ai-offline-evaluation-reporting.md b/docs/internal/ai-offline-evaluation-reporting.mdindex b2067bd9f7b4..7c3192f9e908 100644--- a/docs/internal/ai-offline-evaluation-reporting.md+++ b/docs/internal/ai-offline-evaluation-reporting.md@@ -186,6 +186,15 @@ Retrieve a specific version at the same path followed by `{version_id}/`.These operations use the existing scorer read permissions and include historical versions without recent results.Archived scorers remain addressable, including their versions and offline history, while default scorer selection excludes them.Creating another version with an unchanged configuration remains supported.+Scorer configurations can optionally define which values pass:++- Boolean `true_is_failure: false` makes true pass; `true_is_failure: true` makes false pass. Omitted or null polarity defaults to true passing.+- Categorical `passing_rule` contains `categories`, a list of configured category keys. Every selected category must be included for a result to pass. Single-select rules require at least one passing category; a multi-select rule may have an empty list, making all accepted results fail. Offline results still require a nonempty selection. Omit the rule or set it to null for neutral scores.+- Numeric `passing_rule` contains `operator: "gte"` (at or above) or `operator: "lte"` (at or below), and a finite `threshold` within the scorer's configured bounds. Omit the rule or set it to null for neutral scores. Thresholds need not align with the input step.++Passing rules classify accepted scores; a failing score still has execution status `ok`.+Each immutable version keeps its own polarity and rule. Changing a scorer creates a new configuration version without reinterpreting historical offline results or saved manual review snapshots.+Numeric scorers without a passing rule remain neutral. The editor always offers a passing value for boolean scorers and persists the default polarity when saving a configuration.Experiment summaries and scorer history use the same aggregation rules over all matching results, independently of item pagination or payload availability.Different scorer versions remain separate, even when their configurations match.@@ -196,12 +205,17 @@ Different scorer versions remain separate, even when their configurations match.| Boolean | True and false counts, with the true rate among successful results. || Categorical | Counts and rates per key from the pinned version, including keys with no observations. |+Boolean scorers and numeric or categorical scorers with a passing rule also return `pass_count`, `fail_count`, and `pass_rate`.+The rate divides passing results by successful results, excluding errors, skipped, not-applicable, and missing results.+Numeric pass counts evaluate each result against the threshold, independently of the mean.+Without successful results, boolean scorers and numeric or categorical scorers with a passing rule return zero pass/fail counts and a null rate. Numeric and categorical scorers without a rule return null for all three fields.+Multiple-selection category rates divide by the successful result count and can add up to more than 100%.Error, skipped, and not-applicable outcomes are counted separately and excluded from value summaries.No successful results produces a null mean or rate.Missing results among observed items are reported separately and do not indicate how many entirely absent items were intended.Each repeated trial contributes one item; summaries also expose case and trial coverage without applying per-case weighting.-Numeric increases and boolean true do not imply better quality unless that meaning is established by the scorer.+Numeric increases do not imply better quality unless that meaning is established by the pinned scorer configuration. Boolean true passes by default unless the pinned version sets `true_is_failure: true`.## Reading payload availability@@ -235,7 +249,12 @@ Different scorer versions retain their pinned configurations and are not averageOverview cards show one version at a time, with arrows to browse versions that have results in the selected period.The card summary aggregates the loaded experiments in the selected period for the displayed scorer version, using the same history points as the chart.Numeric means are weighted by successful result counts; boolean and category rates pool their counts across successful results.-The card count shows distinct experiments, including experiments without successful scores. History is limited to 100 experiment/version results, so incomplete-history summaries cover only the loaded results.+Boolean charts show the passing rate, with true passing by default when polarity is omitted.+Numeric charts keep the mean as their primary metric and show the configured threshold with faint passing and failing regions. Series retain their identity colors.+Summaries and tooltips show actual passing and failing counts separately from numeric means. Pooled passing rates divide total passing results by total passing plus failing results.+Long score summaries truncate to fit their container, with the full value available on hover.+Percentage displays use at most two decimal places across summaries, charts, and tooltips. Numeric scores and means normally use six significant digits, retaining more precision when rounding would change their passing verdict. Numeric tooltips and threshold labels show the exact value.+Below the passing and failing counts, each card shows distinct experiments with the scored item count in parentheses. The item count equals passing plus failing results when a passing rule applies; otherwise it counts successful results. The experiment count includes experiments without successful scores. History is limited to 100 experiment/version results, so incomplete-history summaries cover only the loaded results.Output types sit beside scorer titles, and neighboring charts use different colors from the theme palette.Points are connected chronologically with smooth curves within each version and metric. Click a scorer title to open its history.Hovering over an overview chart shows a shared vertical guide at the same execution time across the other score charts.@@ -247,6 +266,7 @@ Short date ranges show time-of-day labels, and short period comparisons show elaAn experiment shows whole-run scorer summaries and an item table with every observed scorer version.Scroll horizontally to reach additional scorer columns.Open an item or score cell for input, output, expected output, reasoning, and payload availability.+Boolean score cells and numeric or categorical cells with a passing rule retain their raw values or custom labels, with a success/check or danger/cross treatment based on the pinned version's rule. Execution errors use a separate warning treatment; skipped, not-applicable, missing, and numeric or categorical results without a passing rule remain neutral.The inspector separates payload fields into collapsible labeled panels. Metadata and long text or large JSON start collapsed; each field can be expanded independently. Result details show the selected scorer and score above its reasoning.These larger payloads load only when the inspector requests them.Upload completion is separate from score quality. **Mark as completed** checks declared expected counts on the server; it cannot force a mismatched upload to complete.@@ -254,12 +274,16 @@ Upload completion is separate from score quality. **Mark as completed** checks dManage scorer definitions and versions under **Evaluations → Scorers**.The previous Human reviews Scorers entry and bookmarked scorer URLs redirect there.Scorer management remains available for manual reviews when offline evaluations are disabled.+Scorer names open the full-page editor at `/ai-evals/evaluations/scorers/{scorer_id}`; `/ai-evals/evaluations/scorers/new` creates a scorer.+The editor combines metadata and score configuration in one form. Passing settings are shown only when offline evaluations are enabled; hiding those controls preserves existing rules. **Save** patches metadata when configuration is unchanged; configuration changes save metadata and a new immutable version together. Saving edits to a boolean scorer with omitted or null polarity also creates a version that explicitly records the default.+Saving a new configuration checks the version observed when editing started. A concurrent version change returns 409 without saving either the draft metadata or configuration.+The **More → Create new version** action can create an unchanged configuration version after confirmation. Save or discard a dirty draft before using this action.+The **Offline evals history** button in the editor opens a scorer's experiment timeline.With the offline feature enabled, a scorer timeline offers upload state, source, date range, comparison, and exact version filters.Its experiment table keeps names and coverage on one line, shows execution time in its own column, and opens run details with the arrow beside each name.Compare against a previous or custom period.Custom comparison periods ending now retain that end when their URL is shared or reloaded.Equal-length periods can share elapsed-time axes; unequal periods keep their actual date axes.-Version creation copies the current stored configuration unchanged and requires refreshing after a concurrent version change.The `ai-observability-offline-evaluations` flag controls all new offline views and related scorer wording and links.The legacy `llm-analytics-offline-evals` flag does not enable them. Keep rollout disabled until producer upload-to-display verification is complete.diff --git a/frontend/snapshots.yml b/frontend/snapshots.ymlindex 44e9ac7db6f5..1cdb31fe6a2f 100644--- a/frontend/snapshots.yml+++ b/frontend/snapshots.yml@@ -8,6 +8,62 @@ snapshots:hash: v1.k794b7964.af0ce5703adcc074ea6c3afc8715d537a646698123a78625e6ec847123b26ae2.ypACU5Xagre6WeI4z7UlQ6w7oY0ieM1C-GnZs93KDkYai-observability-create-prompt-experiment-modal--default--light:hash: v1.k794b7964.1f2df3488ddd83339f1b456d5754cc2914c96b636f3b42d2ec790d9d88cb4b7a.eEMgBC90LXIRJdk4qJWBJVarHjNmZb38tIjLxTV73_E+ ai-observability-offline-experiments-result-tag--boolean-detector--dark:+ hash: v1.k794b7964.11a932279dc111ed5e7890dd994d5acf12f56c57fad7a5723edc85dcc5903cc4.AnI8xHzHRsCXoTRyL39973fLR6H-GyJ7SU8QkOC3WQk+ ai-observability-offline-experiments-result-tag--boolean-detector--light:+ hash: v1.k794b7964.8520d922339633f50f9a4cdf31b1cbd81895357247ea0831ea2efabe31617964.4N8LNOKWooVasw2Rxlr15wwHuR8xe4xnyf2C5qzf3Co+ ai-observability-offline-experiments-result-tag--categorical-mixed--dark:+ hash: v1.k794b7964.dc723c8b74382a1304a729feb68ad3d5619a388645cec41fe647a8d4cea06144.n6T9DDAK13F_8-gtK0hkBM0K822andqeqf15u3_Gpq0+ ai-observability-offline-experiments-result-tag--categorical-mixed--light:+ hash: v1.k794b7964.e23e622ab9d3fc16b926a10bbfc4a80bf56a54bbac1788fca8e52028f6cecb26.efJ-NZCrBNlgLwq4ZLTfIRoYv0hLg_HFajf78cy2Y0A+ ai-observability-offline-experiments-result-tag--error--dark:+ hash: v1.k794b7964.6c563861613d877e2f71e45a885b4fa0a5e449980f224695f637dfe5b712328f.GO8Z9OS7Vg9KuviF8LMJ5mGeHDRYovGI7vAJagqUViI+ ai-observability-offline-experiments-result-tag--error--light:+ hash: v1.k794b7964.221aa6a6372b8187bf6482c280b91158db73e9ed2a1a1f331d2c96af5da66bbe.v-2Odp6LrM0VYqWaUDkRnbXBEltNff5bzSfLiQPLsqs+ ai-observability-offline-experiments-result-tag--near-threshold--dark:+ hash: v1.k794b7964.4e22f2817eeafa67bd17d16c929dbefb72a044a454ac286dbb3f71485233f7b8.Ki4k__1IAvJGCNNkDon-SXyrcWvfwopLSXwlrKwcM3A+ ai-observability-offline-experiments-result-tag--near-threshold--light:+ hash: v1.k794b7964.0afb3b2d8f134394023b035c9decd0cf69080b870d6eefc42b8f3c6dc0096df6.ADP6BxCYK7YMW0sw3LIunIxQd8ApgjJBqgQ3Zb_Uef8+ ai-observability-offline-experiments-result-tag--numeric-failure--dark:+ hash: v1.k794b7964.0f7b6822222fa7665f16f8514d19dc2622593788be887b4a8fb780ff08b05553.izKvmd8nh53o2A8EmAjIQ3QkIUMwk6QV5P2HzMRFcbw+ ai-observability-offline-experiments-result-tag--numeric-failure--light:+ hash: v1.k794b7964.dfb38dd9834421cc7876b9af2bbc5cf1928f2cee07fe8c5c83329638e76ab68b.sa0y0oAzw_IUecvdQl8SbMxBMq3FEP5EaLK2FNyLUXM+ ai-observability-offline-experiments-result-tag--numeric-pass--dark:+ hash: v1.k794b7964.78f2ef974036787906954361f056531cfd17c3ee8f7b2f847bd8faec33c3a34f.HsrDL-YyizN-c44kX70UXwGi8TH-Riu-rZw6XlsVk-8+ ai-observability-offline-experiments-result-tag--numeric-pass--light:+ hash: v1.k794b7964.a6fa90f2030db0b518d230a029c669e7e7902fb6e9433ce20c1414418a9b0280.iJ5w7WfCW8wBofaUjbxVGbbSCKQ6JTFm2xt1gsJbGzA+ ai-observability-offline-experiments-result-tag--skipped--dark:+ hash: v1.k794b7964.8ee9a8a4a723276c565747cf0805ac90ecd8da5d6a3b8cc81a30e2b0e395bf72.5dT5GfMxbHTkbXgQkq9nGtWz2T5r7VEnkyiWNKXXBAE+ ai-observability-offline-experiments-result-tag--skipped--light:+ hash: v1.k794b7964.3fdac3797f59baaf8ff0eb01d1d3d0475600a127bcd13ec7bf3d83f083a2b93b.imjS_0jGQR_PDEo4ULMbJdixQmrtTHN_F2HTHcNPHnc+ ai-observability-offline-experiments-result-tag--unconfigured-boolean--dark:+ hash: v1.k794b7964.002cefa7c5e4bdcb452a68407be79532ad5aa622c222c90c56b242bdcb854dd5.7nhqCwxlkstqb8CJ5xNuwxoceLo7aRheipEvXLJj5d4+ ai-observability-offline-experiments-result-tag--unconfigured-boolean--light:+ hash: v1.k794b7964.5a519c1183c38357019d4c47a1da6ff2381923bdff3e903a6b3784f7bdbbc330.Rd4ACjp75W4rt_rcPXViKPi3tz9TtkyzaRM3EvKmBgs+ ai-observability-offline-experiments-score-summary--boolean--dark:+ hash: v1.k794b7964.07fa36baaa5937fdd68912650698b26d7f0f92eae54d57923c6b8ad74cf7a50e.9vMcA18-6JllK97Y_AmBeWLbv15dY4Ea8pU5U_VwVXw+ ai-observability-offline-experiments-score-summary--boolean--light:+ hash: v1.k794b7964.a8a127b78870257e85878c912351ac21bdda7b5793eb122bf1551b082e816133.9Bymwo9n4k-2Gqva4GeHqv1i7RlgNZPqqeGiX6h-8MQ+ ai-observability-offline-experiments-score-summary--categorical--dark:+ hash: v1.k794b7964.a558dfd4fda58f50bb74b35738f5f9670d8d2b2ba9b1c55182e43a584a64024f.x1PUHdh0HYr6weMmqbsrcrPSkwVle97HlvR2zM45igY+ ai-observability-offline-experiments-score-summary--categorical--light:+ hash: v1.k794b7964.49b5984d52282635d87784aaa577897eb6956f883635a04527d55efe3c8223f3.Rajrcc7N3hWWI17IhCjmPEygrSojxiCsYZMnNo66Pro+ ai-observability-offline-experiments-score-summary--near-threshold--dark:+ hash: v1.k794b7964.1741e4cbc3b4e705be6959a87031e9ad569b9529af5d2f2faff0970b576b5cb7.MwOyiIMkaCm6MvJO4RSAzAJEpeAP9iT9INyxvC62wAw+ ai-observability-offline-experiments-score-summary--near-threshold--light:+ hash: v1.k794b7964.5e732cf4e833a2b92dbdc5c622363501da8f0bbf11f42591a0dc11953e74bb53.ylG_qyQMjMMOOUGXBF-BUy5Sgbf0BuxgVPhwqlEBEE4+ ai-observability-offline-experiments-score-summary--numeric--dark:+ hash: v1.k794b7964.3408f29f99a0788147869b8487bb8f1c9490510f2375c5ede5b26c76e2b14a99.QIEC7ibEjXfY7VRTFBwPQUCE4Yg9cI_il6CvZuxY0yA+ ai-observability-offline-experiments-score-summary--numeric--light:+ hash: v1.k794b7964.cc0b513e978caeaeae3b1f26ce436ec16a2984cc4c60e0ebc5f3b318b648f1b5.wHhY51Uh0Zf2N3bvhlWlJSduP3jQ6ESyKkwIydDvroE+ ai-observability-offline-experiments-score-summary--unconfigured--dark:+ hash: v1.k794b7964.1ec8a1cb515acb88e11a9d31a29547f457a8e7f181512a9eb98a969ad760b399.wwd7V4R2djRPMVGIHBmy1b4sm5y7vIE6k-tGdjmCLJY+ ai-observability-offline-experiments-score-summary--unconfigured--light:+ hash: v1.k794b7964.0fdb7387443d1d089a109e3ba5a3c1cca7757c898ad586257d77501ef53ae9c0.a00gYLzZpm_vUAAR90quMWo8GdgjuqyBFwhk_0YlGDc+ ai-observability-offline-experiments-score-trends--boolean-detector--dark:+ hash: v1.k794b7964.4674ac414495409b6e1b8851d3ca806b673128a81dc796435eec1479d1546a19.7j1RcXXPvpBnEcmOYxuxxgWl2eJyDtvHgMXGMZKK5zw+ ai-observability-offline-experiments-score-trends--boolean-detector--light:+ hash: v1.k794b7964.a4ba6fba82b34194ac2b13f82da0240d7571feed1f40b29e672c480d047f1c94.yRg7chP_zplC523i9i3FdEEyPu4SdZTbDB3sIc7jbKQai-observability-offline-experiments-score-trends--categorical--dark:hash: v1.k794b7964.86b3ece3386ec3cfa56db6cc1670009f3c9bc3017de0ee360fb336254be1fbec.OodE3hlwcB8NBOMhiPQ91Ew1a_M8oEkVvUpaciEGW_cai-observability-offline-experiments-score-trends--categorical--light:@@ -28,6 +84,10 @@ snapshots:hash: v1.k794b7964.01df770a61a8c8727570da3e29cb07273035a552a93ee74cb500bf557cb8662c.jKDH6eSzj4mI1cQ9rBC_DaupozsqoxM9BDQN2ll5K_Yai-observability-offline-experiments-score-trends--last-hour-comparison--light:hash: v1.k794b7964.b2af5cb508b4578a8b76d93fdd339a955dd1d7be36be22f01ff28213bd0496ea.bH70AtGXauXohMhd8q-jzApTkJFkkDGx6ck01_x4GnM+ ai-observability-offline-experiments-score-trends--lower-is-better--dark:+ hash: v1.k794b7964.9a6be40567c017900e570d1118856537b38a03d17b1a9ee59f7b735377f00b4d.PmpPeMq_ajFUeeqtynQP9f0nr6qxrftIlotyMfQyqF8+ ai-observability-offline-experiments-score-trends--lower-is-better--light:+ hash: v1.k794b7964.a880aed226e69fe87fbc26cdc67521fe70f055b6db772102f62665e01db22def.4NXCOaqVA3wW-MYJVqKSgJkwlBCefVr4wD-ehW4XYboai-observability-offline-experiments-score-trends--missing-successful-results--dark:hash: v1.k794b7964.5327540df7942f296f6f06da136f22631e5920a870d56be7fe6fbac38210ea4e.SPKS0M5m7cnRtPSyJKXsyE1I-SP8sW08KaxvfGB3wXUai-observability-offline-experiments-score-trends--missing-successful-results--light:@@ -40,22 +100,82 @@ snapshots:hash: v1.k794b7964.bc315640e7baa6b3b5e579dc28639c383692147d559b7d92ddea2be076d08a32.ljrtVtpsvi_MTMF88ThsB2kK_tHaWJjUcXGWSO6HhUkai-observability-offline-experiments-score-trends--narrow--light:hash: v1.k794b7964.2556c62d0a4268f67526a7bae0860eed45a28d3ff2b53512ff95f9c626e6dacb.zcZcAfaCtF4WCTgClG7Ph702y921g_2H1J_jb81_z3g+ ai-observability-offline-experiments-score-trends--narrow-passing-rule--dark:+ hash: v1.k794b7964.76dbca1f9336b415587cbfdc30dadb2b733a8f226f567023fb3d1cacdc641eac.sYZAKofxqz1ny4XsoupT3SLSQ7fSxdU4Ob2SgVlFY0Y+ ai-observability-offline-experiments-score-trends--narrow-passing-rule--light:+ hash: v1.k794b7964.b0514679f0b0fdf5057844a992d9f482eab4aea61c32c1a076fd5f2d79f7c73e.suJXhRcv6-QZ0WB9ceqrgLGnUNhFbX4YIWAsszStP3kai-observability-offline-experiments-score-trends--numeric--dark:hash: v1.k794b7964.115ef4b115e1348ff0998a32b1ba4578670a539b019cd8d3aef659f4c28ee8c1.pyx5vlANYTY4TgHMpt42B9xJGIgThBFnaKl7SY-DLb4ai-observability-offline-experiments-score-trends--numeric--light:hash: v1.k794b7964.2f8dd277ca680cf00d42c641c6b3a1baadd0894f229ab8d89350205c22f4cf56.5QWWNrDgkj3_CFzilem1eU_pTd37tV6_kFqcItEmmfA+ ai-observability-offline-experiments-score-trends--numeric-passing-rule--dark:+ hash: v1.k794b7964.8a81c7499b66c577891776c38f25e0f8c4fc9d3fb81b899aa6f8743cc9b0d153.hrgMctH8xP0hZOX1e6RgHNj_P0qVWUH_5gudyvSbjI8+ ai-observability-offline-experiments-score-trends--numeric-passing-rule--light:+ hash: v1.k794b7964.e5367e5503e0e7a14586290abedd1f8f25d9a938013d330a9b3783a9377e32cf.2SZhg6Ri2BlDEHtHrLx7RAbuPEUQFdP-D1FP3_tOPNIai-observability-offline-experiments-scorer-history--default--dark:- hash: v1.k794b7964.48fa2f9bfba031021ccac1550db39716828016e5d006aad891c1f477f88ebfad.vQrfes2luhQOd7obTfmgii5N2CSLi0KZzbpcDAesXso+ hash: v1.k794b7964.c816b9439c7de3e2dc8dbdf53b7c0651a3336707e1c8761bb5af0033904ea804.Gs0zlg6uRuw_0gaJi4rXDpWigJ8eYcWlILeaZ6Vf1OMai-observability-offline-experiments-scorer-history--default--light:- hash: v1.k794b7964.f01b1a0e1dcc86f4ad0be7b75ee36d96a35e88d189dcbca7fa4a54b3bb386d59.w9mzVHAHrxXX5sEu9svBOzrCTz4n9tovOQ2pAWBeDM8+ hash: v1.k794b7964.4e537160d18eacf43f87d4b3b9c2ec4ef78cfbc90c34885ad9b6d1f0c1c1b917.oIGbUXPQG4hu1-CMEXy7DhYMOkNq-QEG3atRit7UEFIai-observability-offline-experiments-scorer-history--empty-history--dark:- hash: v1.k794b7964.9d8870713883ba96bd1f1486a2455f95ca66f2b8019e316d2aabc9693c7f7417.-UrQOFm_QWgRwhKZXlp2cbXRkMlrYCNRutDm2QCvxvQ+ hash: v1.k794b7964.90a96ba426f8f452cd947b1e985db2e193ac035767c7c2fcedb55fa53e4ed631.fVY6egjOgoHGNegbNwQ6RKEXoVz3kYwP6nlkxDVgzk0ai-observability-offline-experiments-scorer-history--empty-history--light:- hash: v1.k794b7964.f1a86e8e92926e538e2e7ece56df8c98bb1594c3671db14fa00510e087f44963.7nFc1M7yJE-TUdPuUYZ-FTXCRS6z4oequYrFuFYSqcY+ hash: v1.k794b7964.19bdb239c205431da7017633b52d6d2c8829f4772316cfe267836d82cd4a9901.2MqfY2PaAGOKab9dEghItbVrBQXVAbVJgSph757S144ai-observability-offline-experiments-scorer-history--narrow--dark:- hash: v1.k794b7964.59b22b2274cdee36ebf213c1bc8e6fb3580a6984843407bba1c73dec8ef5779d.Jys6gUWRbll0ARaOgG2XWTD38iAS3CuxfZl1ABadXGs+ hash: v1.k794b7964.98526d40673a0779b784bd7845a2446fc970b299ba2de327e321481079d5f7da.3zf-H0cmGrmEj8yHtdglR_meMHnbEtNpLVc7OaLCoGgai-observability-offline-experiments-scorer-history--narrow--light:- hash: v1.k794b7964.12f960869285a003874135cd985066e93ed34c4803b9aed9a542ba10e141638c.r-OJgh696ONabvP0T6850blw9mpXRGbsN-QbvnmQz3I+ hash: v1.k794b7964.af8bef523d5117ff2d93ab7a27e8e93bf3a5b9fb905151e8c80f0bb1b2a226bd.w6xWigQoWCxRYBqldCxfIaom49tZxgBy0dWTLb0tWvU+ ai-observability-scorer-editor--boolean-detector--dark:+ hash: v1.k794b7964.841ab07e56ee68448ba1df160d2365beed4eec6db48856b984488836ad4ce85f.91iF4r5RJZ81eQDCcoFWZ5N1JTo-dznWBBKCzTSJ-mM+ ai-observability-scorer-editor--boolean-detector--light:+ hash: v1.k794b7964.59661b0cff4ffa3256ba4ad9718fef1ee91a69020755c7f65d058d792456d6d4.euNebFHbsx9MWKKQVZb6FSuIkB2v_HMBCDeODOMVuSY+ ai-observability-scorer-editor--legacy-boolean--dark:+ hash: v1.k794b7964.589593f3b43eaab4211e68f705c4f1e8e58402cf72c48660d3b6e85b12ca7f4e.4iTnDz5cGsuxeZ8ip-NPJFtSPynhPmhnn0d4Q1SQsQ8+ ai-observability-scorer-editor--legacy-boolean--light:+ hash: v1.k794b7964.a94659d37c973f53d579471300a61e0c09c50867c38865f1e3d74739f415ac03.BR5-bEASo9aFk-ArydSTfywdvww_4yO4qGOhPsQtRhU+ ai-observability-scorer-editor--load-error--dark:+ hash: v1.k794b7964.0f8cb6804577e15ea4422940b536fb357fbabb29eacf26afbd87468ec28c90f6.Ly9Rb5gH25bFKYuYUmcSrfPs0DA2Uv-qF6q3gs3n5Bw+ ai-observability-scorer-editor--load-error--light:+ hash: v1.k794b7964.0d15a6abe82416de58c525f70d9bc94874d3039b026c30a14c8bb192b2d661cc.a0uei1Wg5xJeyTqmlHUUfxDgQp86PJs8UXAVYVsvvxo+ ai-observability-scorer-editor--narrow--dark:+ hash: v1.k794b7964.ebce9a1a02bd2d41471f7c199d3673d7bafca24abb717f64baf05548fa140fff.DUTL_KGeO-KPWyLyFnob-GLWt0z2Dn2x8KzRw7TbyBM+ ai-observability-scorer-editor--narrow--light:+ hash: v1.k794b7964.172e67c64e21a0c4104ff35eaaef9a440dbfefa859e53b27e7db09e60b9bc9f4.UiC0GZW1jjTKYBDeKg66KN1yfmpiycjhzw6eZywIKJY+ ai-observability-scorer-editor--new-scorer--dark:+ hash: v1.k794b7964.0adbbb66244d361aad28b60dedc3d1664eeed713b385b0d179d016ec65e30f5f.9DiorxJuO21bW-diNrOFoyRjB-S81Tl9BPJi_1y8DGw+ ai-observability-scorer-editor--new-scorer--light:+ hash: v1.k794b7964.05e69e8cbf5a269adecfe7ae4b7bbc35f0529f20d4c3da7b1e7fe81df4992740.pybjXPj0fuu7rAV5lPqdRXFlz28ZiuYrSqvrQkhvcFc+ ai-observability-scorer-editor--numeric--dark:+ hash: v1.k794b7964.90b0b440870f4a039c4ab8dc6e78f96b6ad72c30e831a0a3ceb4217509eae46c.t9VTtIqyYW9WaiYD1UfyuUqeOri63YNad8Nr3ELMk6k+ ai-observability-scorer-editor--numeric--light:+ hash: v1.k794b7964.1422448358f0f0e1c593d6321a90881d7a478e28a219ef782dbd4c3b83521d1d.cZhIHoCNgA6vM5Vn64UY0gmqwvXBNbzQqfAvaSw1r0o+ ai-observability-scorer-form--boolean-detector--dark:+ hash: v1.k794b7964.6a1b98222f1fba6d4c3fdde6156df44c35ec487e83d0d76da7e712fbd56d3d58.pewGEfZSlIaH1aWMKghO0BqRdpfk2sBTz_kB9ZITvrQ+ ai-observability-scorer-form--boolean-detector--light:+ hash: v1.k794b7964.fb38726711fb17b0fa6942f6a0fb059242655b3330a4533ac51dacf912b74432.8dfTh2m0gn9-XfXqxhOo8IeqogXWQGN5jiJaiKmjglk+ ai-observability-scorer-form--categorical--dark:+ hash: v1.k794b7964.04d3da604f06dd1ccb47841a3b47eae1f75306494679130c39507005568aba9f.x9dfhvETwi5MIoWT5ZYpevdY5xRb5qn3agTKLbeCTb4+ ai-observability-scorer-form--categorical--light:+ hash: v1.k794b7964.cd03b79d9a3af57bfd028822546d869b973873e23090d8afa5b7f037d929ee44.RB5Hko-bMw0gv6oZOyIqBVj3wXhzTgxUoGFycz-gMa0+ ai-observability-scorer-form--categorical-narrow--dark:+ hash: v1.k794b7964.2c87624a84ca9a3c5ca06a165e812fd6b8935e8e8a8558c5d9d397fcb3964947.9ypznBCGhMMzwXsCgC3BARS2wb71r0Pq5airJcY19Ec+ ai-observability-scorer-form--categorical-narrow--light:+ hash: v1.k794b7964.2268634695c9fc0feb52c4b39b35c47adbf9b9506791b7f5fd9f8a657bd72b1c.1RT_WHWdRV9h60t6Zk3EkZNfOG3v9Hht67ghARoQ9BE+ ai-observability-scorer-form--narrow--dark:+ hash: v1.k794b7964.b9ab06356a6dfe363ddb32dfc2593919ab8b92b0e85a9fb21a62f5e9ccc25c67.ZeH7cshPLmd_wTh-L6v_J5QqEpydtgd3Drm9igiGHWo+ ai-observability-scorer-form--narrow--light:+ hash: v1.k794b7964.041db37e5229c59717c8ab44092cf686c1fbb7de4fcf1fcd56e66dbd359a3d93.KHYQLy9Od2uZZFPNvN42h9SNDfl2G7f9zxW8DYfkey4+ ai-observability-scorer-form--new-scorer--dark:+ hash: v1.k794b7964.5b6ff3f06fa0ca76614e5c68ce0a428a56c97b47c24ea6ce234f7cede16d694d.cFt5UUeLhEXacFnJJHuVSZyzUY8xuyE32szF68aURvY+ ai-observability-scorer-form--new-scorer--light:+ hash: v1.k794b7964.59be9a6a45462b7250fa36e4453d605a6d3468103ebec066fcb9b72425be5651.AwuILo4ym2pWUSlyUSfWcsCWmVmvzxMv7D4HnmfYq48+ ai-observability-scorer-form--numeric--dark:+ hash: v1.k794b7964.52f6c3a3ad754e436b7c8df02397ff9c87f2fc4b54499ddff3d2f708e1b45219.cpMjcuayuECAfm8Yl7SGQlRn-Kmj7tqOpLeMTB9yX2c+ ai-observability-scorer-form--numeric--light:+ hash: v1.k794b7964.18a44cf74dae3bf5133e83407a6b07f379d485ff45096ff965babade020b625b.eEuDBN5MRJv8evVoqoiOpH-Ax35PBgPxD99F3_iGmVI+ ai-observability-scorer-form--offline-disabled--dark:+ hash: v1.k794b7964.da97aa78c23020a365ab4eab3ed818e5f8993c46239c1e92977e8a8b28bfe362.M5pd-RjArDI2eiqfGBewTmK8Fbg01zE6uvPXSSJ0RR8+ ai-observability-scorer-form--offline-disabled--light:+ hash: v1.k794b7964.2dc03d1322685e9016f63454a0a2966ae96614bf08802aa725ebc955af65feaf.J8cmghXsSZoVxurLs2npYwulIcvOVgODD2EKNauo1F4ai-observability-scorers--default--dark:hash: v1.k794b7964.040c57a323aca5a3d73ef242bf808c27b6072bfbf504390cb3fd158cf7b0443c.a0G1txCKyiAVTJfCzuRZWBlu7zGDQDM6AXuKQHsJYh8ai-observability-scorers--default--light:@@ -7987,37 +8107,37 @@ snapshots:scenes-app-ai-observability-instrumentation-checklist-card--warnings-with-a-dismissal--light:hash: v1.k794b7964.b0e06944ee7afe4af8cb39363280135111e71ba215aab56a3e410c79de62238b.WtW8suUOWanaTrvjxhV2Z_ANVDRmEW3bqHpTrTe5GoIscenes-app-ai-observability-offline-experiments-experiment--all-scorers--dark:- hash: v1.k794b7964.32789846efca0bdb8996e424742d3b058e116357b8fc11b47f2be819d5045c49.2V2wD8ImBeE55nMWyQtyWkaqXsr1HH3YZRPH7A-kIgM+ hash: v1.k794b7964.77b8eeb6a6bb9e85a4028d13148b4fe4bcfd18960aa499749bbade387d2dffc2.MTL9sKGqzrSi8kpPYs3haq3i1XgxRiC6yXqFUnKvlzMscenes-app-ai-observability-offline-experiments-experiment--all-scorers--light:- hash: v1.k794b7964.ebaa06a75b001cfd02f178b94f05743da264003fde11f1ae969de21a9c9152d6.iwD14_qqLdFFxw9OG0It9i8H8j9N98xFfnt9QHRoLlU+ hash: v1.k794b7964.012426a295152daa24de8516ce67a5ecade2be33a299dc738fc60fc15b6399df.pNBFQGCUrKAgPWtFABTOcNZp7osXurRr3vLfHePiHY0scenes-app-ai-observability-offline-experiments-experiment--detailed-result--dark:- hash: v1.k794b7964.61008324f7380ab4268b0759c5065ec13e71ef1c5777ed33150faf1b3f4e80d4.IgIqkrlEbDe8IAZBiUhT6NA0LOy2rgSSjkKPAHd_4PY+ hash: v1.k794b7964.be36d278ad6c590ede1e5869eadba71cba2fbf4612a0b23a05aceff58c340136.TOcMfeHss0Chw1S7KTVU7eu2GLXiKIQU3euYoRAPUFIscenes-app-ai-observability-offline-experiments-experiment--detailed-result--light:- hash: v1.k794b7964.69ba6863583f191df28d21eea7961a967fd42ebc305e95b9b5561b62f940e277.tDaa6TDG_uTEQomDZXlbzaBkxGAWlzHmgeNjNJfYFPk+ hash: v1.k794b7964.a32a2ad4884811a0ccf32daf02105b3f3855c3659af63ed73b8e254d2d634253.c1e7-OzuQpuVjev-V5p1sJ-QBz7C1MlFjqr3Ldlo_Ucscenes-app-ai-observability-offline-experiments-experiment--expired-payload--dark:- hash: v1.k794b7964.174a812a08ceec355f1b1918cadced89b1647afd84249f97f72210ec81bc7629.YMozNvSURuG0qZvspImmSK07l7fqtLAsy9W0ga-rW2Y+ hash: v1.k794b7964.c633f35059e0407de1e21d6956c58353eaea244f0c36782fef503fb4ae1923ff.fVT2Wg77WeGufjZ8aUIYqWrfwl9LOuFH4DBsYqnYgRIscenes-app-ai-observability-offline-experiments-experiment--expired-payload--light:- hash: v1.k794b7964.170f6e09cac04aa438979722639754058ec97a3a39ec8763ec806fb6f3094bac.gji50mmjWmPYYvMQ-2AkehP1nNBUT3bdVj4F6sZrO0s+ hash: v1.k794b7964.46c8848f0b6a455131a29a604fc4471ea9fbfcc566f496e397e9c3c918919834.zBG2TIsD7pcyVy8v4RbpMtwEfYM1p7jx2dYK9H4Cpqkscenes-app-ai-observability-offline-experiments-experiment--item-inspector--dark:- hash: v1.k794b7964.c0cd2f0aad2c8172a41a492cee1c4371a81ef63c12722eeced503284c4a04035.PEf5a6JIuQvJag56r3YGf0uK-16UD6B-TiqwYUpNRyY+ hash: v1.k794b7964.b1b4a2f32a4c865129064a3fd82fd6168c817e548767aed7057669cf56807b75.KY-u4TZeExWe1qyxBFNQIV00GV5Vyj6EMw4IMtX8Z8Yscenes-app-ai-observability-offline-experiments-experiment--item-inspector--light:- hash: v1.k794b7964.4bd472f80807bda60df30119603fe9cf794e17d8e7284698cb65d61fa0a768e1.x622KHkVx5CY6lKsK25cGqYWHXR9usO1HhSxbXr_ieI+ hash: v1.k794b7964.d5b5031d997fe898f08b76cdbcf9e8cba8c64f95eed1c7cc6e9d07659e3f53d2.MThIVEaUuPRk8atrUxCM-MIndrdmV0NqfZzxQ5hx6LEscenes-app-ai-observability-offline-experiments-experiment--narrow--dark:- hash: v1.k794b7964.00616a9c7b0a913a1e7f7f011a1a1929c2bcd9249c1a9d59e5b39606cefac617.M9I43DUOxOilv2k1VV8PO03NPo_9y9rENkzFGBp56KY+ hash: v1.k794b7964.5673d38bbf3a6d707143df672800761a7a7a5451ddeea6e22cf1be23cbfcf4f3.PQJedGD6_fF2MJ688vh6jNYOLPeyEvNzXSRoEbvYQX8scenes-app-ai-observability-offline-experiments-experiment--narrow--light:- hash: v1.k794b7964.bc344ea5eaffc827bb13ee04d7f84e5fd805365338891c37cc7ff77c1ace29d9.junv5qtguPsE-4geR4AIhcifDhKKgTaQTo5zqjZUKoE+ hash: v1.k794b7964.f8f31513b5dc7d6a8f39040052961a4bacaa6e906b9f3a3f601f7f55d601c731.gfmC4IiX-mi4Edik_p63tKftOIXkyB1fMfhDhLIrv1Mscenes-app-ai-observability-offline-experiments-experiment--request-failure--dark:hash: v1.k794b7964.501bc38da197ae45e045d236336316a18cb78d533ee3008c678c25afe6f3624a.It6rPCGENocYlEoHpN4OPbTNCP4EOKtWe3DmtpiP8CMscenes-app-ai-observability-offline-experiments-experiment--request-failure--light:hash: v1.k794b7964.a31d57c72b94117a24a7a8948a68c6959b4fd00cde6d24aa3cdd206e1ca12eb7.392D8AhKK3JzKggndN4ojaEVt_vsHWraj2vVAWxz5NIscenes-app-ai-observability-offline-experiments-overview--all-time-synchronized-hover--dark:- hash: v1.k794b7964.a03f4980199f19ff3c6ea957d435772df07b87ebbfa1a354b46922805c96d339.rjOvxM5XokdmBhCq3viSd0REEdA-q1F0VzJ0pbL7tHQ+ hash: v1.k794b7964.92f06a25cb40491b184d27fee0afc40fc2915d0e528bf5ba04545bd055fb9e21.zKPFHsgLXM4_6Wm2MneUKlP9VCq9SgLs4rfVKtPsmKwscenes-app-ai-observability-offline-experiments-overview--all-time-synchronized-hover--light:- hash: v1.k794b7964.b372d694596032c2f494dd51521a1c2e0e72cfce985fdd88776b7a2c55c6ca2e.OG35H-RIyyIYRjFKwgDfT_O9BpJGT_RGuFsbualKUiY+ hash: v1.k794b7964.8757d6babacf8e430dd08287fa04166d68213a90a0eb7e4748ce592c690a71ed.5Idjj-crX1d8J5Ttk6W50nDtwJSp2DerTerhHJo8tbYscenes-app-ai-observability-offline-experiments-overview--default-scorers--dark:- hash: v1.k794b7964.c88b633fa1ed25f0dc2ee044f27322ddc73ad0fe6c7b70d5504223a4b42c048f.u3X-bJCxMX7hG7R3h0-dJpcMGb3pcaTNGmBN7_7dNcc+ hash: v1.k794b7964.ee63dbc8b0d27c8084ff93dfafec4aab4ce01024877bae9433583c6577b34724.5PqZDtVDR6Y5Gl8MTCL8hz8PTzJ9KQh9Sjm736u1Y8oscenes-app-ai-observability-offline-experiments-overview--default-scorers--light:- hash: v1.k794b7964.fc0f04c10b4dd322ceafa92efda22e5becc2de02a660dcae4151bb2750466420.IhWKXwq59Ut2EQfm_ubiMRXIjNHLctf81BXe0TT8DZc+ hash: v1.k794b7964.b6b01f620dec845e18cc92f29499ce8387693ad36be054815bc8c6ef4b3c97c4.jyFHo8suG9CUGwZ32OEqLDMLwdTYdNfxAx8CJOb0ZIIscenes-app-ai-observability-offline-experiments-overview--empty--dark:hash: v1.k794b7964.977ade824abb5791ed84c5b6d125bc9589d0787b69daea3efeb6d0fe91f45f70.czJW_b0HTFrXWZGbmMZfAs1UD-NkCfVNLy36XZiTH7Yscenes-app-ai-observability-offline-experiments-overview--empty--light:@@ -8027,53 +8147,53 @@ snapshots:scenes-app-ai-observability-offline-experiments-overview--empty-narrow--light:hash: v1.k794b7964.754079aa9ab7ee416590c9bc8f94fa93f59b7769e98d4e63400883bf4d23ffae.hLRMtJxEnlm36ceer7qs_5s0s0euWyZB0BAqWPZz8c0scenes-app-ai-observability-offline-experiments-overview--filtered-trends--dark:- hash: v1.k794b7964.cd1aaeb31f3a787b340186d7278fb08f3985b1b6c279394317cede408feea814.Ya6XJJJIImryVcQfNqXDjCo-mof3qcyOAhgIkwI_U8Q+ hash: v1.k794b7964.9fdf5042009d4bbae22d40350dced0b1327691d6248e4819675b7a98472bff21.ZWre7Qs9GGu9PcvZQ9oM0acYc-4FRX7E_G5xD4NuYtAscenes-app-ai-observability-offline-experiments-overview--filtered-trends--light:- hash: v1.k794b7964.1430a0ad6ed27526ebd4355303cf3d9bfc995c90d4867dc1ddc236c9218d5e36.pUivlKv47O0lgfH5yQt0tZ2ru_vHccnyGYrKo7m6RbU+ hash: v1.k794b7964.e1fc7f7f745aa51c00658c280d976dc43a025cab66047e863420a12078ffaef5.aeD9daJ8qZwsazp4axiLYwZbot3aBeRtJG-6AVKGhlwscenes-app-ai-observability-offline-experiments-overview--list-error--dark:- hash: v1.k794b7964.c29c63388f030ee51e77954b49e36c1198ec86b55f639131d854afcb3fedb531.yIqviwG5UB668Mm7BLC-OfHMPTMLh5ZwoWD4zcU-gOE+ hash: v1.k794b7964.5c3c9c05034641362b5481f98a2da78a9415a0fdc49c5dcf6a4dba369b690ff0.PaaBerh2sH4kpLWTzjnSFshCOpO-MoAZWNkKHcMpKe4scenes-app-ai-observability-offline-experiments-overview--list-error--light:- hash: v1.k794b7964.32b8c7aadee3875ae5db7a21ef9317e1a78790fd4bcdfcc71613fa0ea8cffbfe.hZzViDroTI1ubjjTqhEG9jqG0of-rIzZ96saW1n3XYs+ hash: v1.k794b7964.313d0039a600be146f2f62147db1fdb4d1202ea2cec5a95ef96dca12ed58b5bb.7Tolzb0JdrUiGuzLnZcHzOb1JMM4T4AvlYSxaK6IBCsscenes-app-ai-observability-offline-experiments-overview--multiple-versions--dark:- hash: v1.k794b7964.04247b88bf1223234ed6e7ef52725d96a180a26163e7a299c67a12050ca5e310.kr71rlsT3I0Dn8EwalxXE5gkeHpvXNLpheF1DRT-nmE+ hash: v1.k794b7964.707dcaf2b4c280e86c780d4d25ebe33a80dc8dd1001eb700fa872267959e1794.QloqqJZKRgf6Fapk4FzWUW0GN5pD_1kHyQq83ssvd0Escenes-app-ai-observability-offline-experiments-overview--multiple-versions--light:- hash: v1.k794b7964.2ceb152a6795c5403ea30bc989b713b55d4e201dfd20670bd2bd8a8e07eb5b86.8n6D7o5Zsu6BFIYdsnI87ChxhVB1-Bz7vIIMMsjvVaU+ hash: v1.k794b7964.cfa522a15b5d22f644d50565e09e4d82608aeb5cf4c8d9b1ad9353a15d546797.AqqssDnJ4x6Yj8UrgQwQre64knWgONZ2qqn8pI6jn98scenes-app-ai-observability-offline-experiments-overview--multiple-versions-narrow--dark:- hash: v1.k794b7964.57f08f48710b95b356c617d395788075b8f1599371d8460c8e8e1257d5a0c953.Fb3RH_djyQbH_gyiR9jxcQAhNMGpt3PoT7XGW5mOyks+ hash: v1.k794b7964.80b2c606c2311f207052f68086d754183d178fa7563c7ec062da2e92d74b6ad2.WdDwFWHk_b3h1MAp5By5r_dDWg0vaABrUGRJlbZ1Qhsscenes-app-ai-observability-offline-experiments-overview--multiple-versions-narrow--light:- hash: v1.k794b7964.dea03bc59d5f7c93ddef52a44b8539ce88415cf95c1f8711dde22714f0a64a4f.16XkFwxL401Y-yzqn3NTCqvN0laEIHM5RNsRiZXEe5E+ hash: v1.k794b7964.882f49bc6e7f051aa0058dbebd8054a3c9bec03aded0de0b37523c16afec8669.uLdpnV_0CSUwFU4n850od6M-_vy9-9trUPbYXsjZj0Ascenes-app-ai-observability-offline-experiments-overview--narrow--dark:- hash: v1.k794b7964.761c02a0bd337ae2511e1622a9aeaa255b8769d7efc055843e4d663a895c4642.LOMsQsY_cWgIriE0cikq-ykS-IHNrE3g0iQHTcZ7MBQ+ hash: v1.k794b7964.5b3d669178447f62d9afec6ac9b41feb5ba6a5c3dbb5fe8e4764ad5519360103.EYJ0U2DpeX5n33IHgAFmS3rRwvviWWy46sSH8_JJz-0scenes-app-ai-observability-offline-experiments-overview--narrow--light:- hash: v1.k794b7964.2aea08b0a80a1283969954929c16ab5b650fecdd914e92e32707ed38e1a3672a.w4iW_1rbm7m34tF4nAUSzpGoC6z6VeXg6VwZj6elyRI+ hash: v1.k794b7964.50dfb823442d39234049daab3d16a32383393dbdf40aec0ebbc80e86c52e8afc.yK1xI2vx15ecjCVGMzAjzITQ_aOLjj0DBbcJk1QYL2oscenes-app-ai-observability-offline-experiments-overview--no-matching-experiments--dark:- hash: v1.k794b7964.6ff04c46798f39b4afc78a0d95860fea4ba441266f01c05ea4a60242b6318a42.iG0HDfCmosp8IliPxVrBPSnrAAWAUlGrjeS7CKrcCo8+ hash: v1.k794b7964.ed9c69d2469f4935e24472b326aca74dd0587cf009ebc3f735c5c5d1f8aebc58.PBd6kunvt27jc5KNGTiCDN1j--9DMXwNAkT1leVPpREscenes-app-ai-observability-offline-experiments-overview--no-matching-experiments--light:- hash: v1.k794b7964.0ce017509182301847a8b099c0239dfe54dd512991457651769717af071d279b.QN2MK_TOy09r1eNdkKqzC8cBKxNU1YBQYaaYbahXsHY+ hash: v1.k794b7964.43f9340ab47a3e1dd95385ea668c669b3c1d30831a29852bd1f9df53352ac204.sn0Iwtyz0Egiroy8pjaZWAjFHTk4B37xYNQsbmqU1s0scenes-app-ai-observability-offline-experiments-overview--partial-history--dark:- hash: v1.k794b7964.e40f15c4a697125c7f78ec016dc7f51e793d0f46961367ec8d2b4cec4b265ac1.WSnQvoeibf9SjcEhK3mUlmEFSxRRCLs1rIIZAX25e_Y+ hash: v1.k794b7964.336cc60c578ae22261f59ab862fac40f3a4cd5e98a73575eb32d0da83e28df91.8J8-T8RZ6qnFjQ7xgOm4hbhSQ3t94mH-5sPFT_nh0x0scenes-app-ai-observability-offline-experiments-overview--partial-history--light:- hash: v1.k794b7964.10dde4f93ce85bdcd5a2f205edc3d12256573b1d0dc61da7618f427f53dc65df.D8p0D5y1rBNGPEHa14yoAMEcKRmo7BldffUVQJNIhl8+ hash: v1.k794b7964.b05de17a4fefb705c6462276808132444d4b4b5b3d68e9a778f040e29db6b595.29qN9vo2gGrGE4cey2Bb1SqSItdXAC6Eci1-P91MP1Escenes-app-ai-observability-offline-experiments-overview--partial-history-narrow--dark:- hash: v1.k794b7964.4af6b1ecf1be5501afd8ebfb83b95645a28883e08093d50e125793e9c278facf.ZfUst-u8ppD4Ft1b0mhTGJ3epZrQDaLH6AO_n7VgzMQ+ hash: v1.k794b7964.c7b6a60ce676beaa13fb20dce5551fb5b374cb894aae7e07233d728c136b2cfd.cehwuLDOUC6wXsXXL1Alv0rBqduTfpYEuR9To6nLKd0scenes-app-ai-observability-offline-experiments-overview--partial-history-narrow--light:- hash: v1.k794b7964.0162bdc938f44a3ef0170fa3e147c1673942aa2a1c63014e8dd749c29bbf10bf.k4cT855FrsOBgeAI0wXn83gJmTFd-pFzQtP6lr0dP24+ hash: v1.k794b7964.73d8a66caeb291d286623491bf61429e46b3ffa49917b71480c4142de59fbb13.LTES5OwKaeAIGROLlqpZhWYZwMJAj1a0dYRO1LdEDIMscenes-app-ai-observability-offline-experiments-overview--recent-experiments--dark:- hash: v1.k794b7964.c88b633fa1ed25f0dc2ee044f27322ddc73ad0fe6c7b70d5504223a4b42c048f.JqyUTpvl8cJhe0k61gaTXdRSc4DvaIKETOu7FwkWlNM+ hash: v1.k794b7964.ee63dbc8b0d27c8084ff93dfafec4aab4ce01024877bae9433583c6577b34724.E6QgEhRXHbaZyoRJxWMMhAOGh00612-nFazNWy8MKiUscenes-app-ai-observability-offline-experiments-overview--recent-experiments--light:- hash: v1.k794b7964.fc0f04c10b4dd322ceafa92efda22e5becc2de02a660dcae4151bb2750466420.tiuGqnMD_NtZuttJzcHSlG5O7KPewDyVFToRR4bnL_Y+ hash: v1.k794b7964.b6b01f620dec845e18cc92f29499ce8387693ad36be054815bc8c6ef4b3c97c4.iRdJ_Xc3oGA3aFBXMzDND_HhyGYAO2EHfEhlsGRn23Uscenes-app-ai-observability-offline-experiments-overview--score-error--dark:hash: v1.k794b7964.6a4ab392e3a9c61aa09a4d2ba700804bfc2a4ba68f0d3ed07a6aeda5a7597444.KnwGA0BS-xPs1Ygs5ms3tKdEAre7XuonWgDudR9BfSgscenes-app-ai-observability-offline-experiments-overview--score-error--light:hash: v1.k794b7964.6e2a098cad6a7be399125ffa6bc75fde41f03d2b4580bea9b155e3c08fa4fd0f.DFDBkI_xNCpSdcaq7GKy95om_ZeTo6RPcecCQ5mMhEwscenes-app-ai-observability-offline-experiments-overview--synchronized-hover--dark:- hash: v1.k794b7964.f83defe0708f343a36cf75a9fde429a3dbc2984e13444bd6de6fd82333a66154.FnxJxcvdk9DuqR9Miam6a4EGhtyhqH5c9pOmdsIwtQ8+ hash: v1.k794b7964.4e7e59cb53943db43d607476e5cf402622f4c208d2586ef11c7bec93fa8cc692.H71gAMQYhCsLXHFbRxl6T0_DjQHlDv5HzVS-I1l5ESgscenes-app-ai-observability-offline-experiments-overview--synchronized-hover--light:- hash: v1.k794b7964.b8747231caa822889c48e2b48309a9eb263114be27851efa36bae4f28ead7490.cfE3-rfFH5fDvux1yHx6xkyYtUAZresVqcbJs8FOD30+ hash: v1.k794b7964.e7722555def758dcfe89e5fe4faab28bcdaf2f255ca0166ead7e2a5e22621e36.3mQphMP7VB56T0FApQMk7wdOcXAmN4B8T5voa7guvo8scenes-app-ai-observability-offline-experiments-overview--synchronized-hover-narrow--dark:- hash: v1.k794b7964.b02173129c1c7fdd635477ae58ce77df5a8dad1c34ede2e104e1127243da3c63.msSqTNOoZfHYvnsJuofXbxOU-YriY_4wKXPAtIR7Yn8+ hash: v1.k794b7964.d86019a71240cb20abd2be302b86ab7644454cddb313d28e32f024bf16ea0a98.qOBSQo5Kpy9wuofEh1A2EzW3exYk2BwHgshxDvdyWAgscenes-app-ai-observability-offline-experiments-overview--synchronized-hover-narrow--light:- hash: v1.k794b7964.8b5e44455d36debf3afc3601d5b6be0efe939b521e91e8b7b95c3819ee17ebcb.nfCQ6ZYg7LT-ZLpZAEX19LBLd51n6YbPSrAFnONoVVA+ hash: v1.k794b7964.d672d469c8481c6526936d0d84c58766a7e51fe6072b3e7b59953fa59eb6c6e8.ZHsxFC2MG9W76b-V6dSOzYEMhGYHT9FezLpgiYHH3VIscenes-app-ai-observability-promptreferencetags--label-and-version-references--dark:hash: v1.k794b7964.4cc699d7489063a64cf4ec1f930d11fc062eb0d9c9e46150f939503945bb8841.jKmH2ZmjZex98fImM00HE_xBBayalWKHtqXbVlhE_VMscenes-app-ai-observability-promptreferencetags--label-and-version-references--light:diff --git a/frontend/src/productScenes.tsx b/frontend/src/productScenes.tsxindex cf5b5b28814e..598b8ff41c8b 100644--- a/frontend/src/productScenes.tsx+++ b/frontend/src/productScenes.tsx@@ -25,6 +25,8 @@ export const productScenes: Record<string, () => Promise<any>> = {AIObservabilityEvaluations: () => import('../../products/ai_observability/frontend/evaluations/EvaluationsScene'),AIObservabilityScorers: () =>import('../../products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorersScene'),+ AIObservabilityScorer: () =>+ import('../../products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene'),AIObservabilityOfflineExperiments: () =>import('../../products/ai_observability/frontend/offline-evaluations/OfflineExperimentsScene'),AIObservabilityOfflineExperiment: () =>diff --git a/frontend/src/products.tsx b/frontend/src/products.tsxindex 1f8863d98fa1..343b487e4c25 100644--- a/frontend/src/products.tsx+++ b/frontend/src/products.tsx@@ -100,6 +100,7 @@ export const productRoutes: Record<string, [string, string]> = {'AIObservabilityOfflineScorerHistory','aiObservabilityOfflineScorerHistory',],+ '/ai-evals/evaluations/scorers/:scorerId': ['AIObservabilityScorer', 'aiObservabilityScorer'],'/ai-evals/evaluations/templates': ['AIObservabilityEvaluationTemplates', 'aiObservabilityEvaluationTemplates'],'/ai-evals/evaluations/:id': ['AIObservabilityEvaluation', 'aiObservabilityEvaluation'],'/prompt-management/prompts': ['AIObservabilityPrompts', 'aiObservabilityPrompts'],@@ -567,6 +568,7 @@ export const productConfiguration: Record<string, any> = {layout: 'app-container',iconType: 'llm_evaluations',},+ AIObservabilityScorer: { projectBased: true, name: 'Scorer', layout: 'app-container', iconType: 'llm_evaluations' },AIObservabilityOfflineExperiments: {projectBased: true,name: 'Offline evals',@@ -1290,6 +1292,12 @@ export const productUrls = {aiObservabilityTag: (id: string): string => `/ai-evals/taggers/${id}`,aiObservabilityEvaluations: (): string => '/ai-evals/evaluations',aiObservabilityScorers: (): string => '/ai-evals/evaluations/scorers',+ aiObservabilityScorer: (+ scorerId: string,+ params?: {+ duplicate?: string+ }+ ): string => combineUrl(`/ai-evals/evaluations/scorers/${encodeURIComponent(scorerId)}`, params).url,aiObservabilityOfflineScorerHistory: (scorerId: string, encode: boolean = true): string =>`/ai-evals/evaluations/scorers/${encode ? encodeURIComponent(scorerId) : scorerId}/offline`,aiObservabilityOfflineEvaluations: (): string => '/ai-evals/evaluations/offline/experiments',@@ -2265,6 +2273,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2376,6 +2385,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2484,6 +2494,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2579,6 +2590,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2712,6 +2724,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2770,6 +2783,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',@@ -2885,6 +2899,7 @@ export const getTreeItemsProducts = (): FileSystemImport[] => ['AIObservabilityDataset','AIObservabilityEvaluations','AIObservabilityScorers',+ 'AIObservabilityScorer','AIObservabilityOfflineExperiments','AIObservabilityOfflineExperiment','AIObservabilityOfflineScorerHistory',diff --git a/frontend/src/scenes/sceneTypes.ts b/frontend/src/scenes/sceneTypes.tsindex 817e7dc5be67..1c27205c11d0 100644--- a/frontend/src/scenes/sceneTypes.ts+++ b/frontend/src/scenes/sceneTypes.ts@@ -233,6 +233,7 @@ export enum Scene {AIObservabilityEvaluation = 'AIObservabilityEvaluation',AIObservabilityEvaluations = 'AIObservabilityEvaluations',AIObservabilityScorers = 'AIObservabilityScorers',+ AIObservabilityScorer = 'AIObservabilityScorer',AIObservabilityOfflineExperiments = 'AIObservabilityOfflineExperiments',AIObservabilityOfflineExperiment = 'AIObservabilityOfflineExperiment',AIObservabilityOfflineScorerHistory = 'AIObservabilityOfflineScorerHistory',@@ -481,6 +482,7 @@ export const sceneToAccessControlResourceType: Partial<[Scene.AIObservabilityEvaluation]: AccessControlResourceType.Evaluation,[Scene.AIObservabilityEvaluations]: [AccessControlResourceType.Evaluation, AccessControlResourceType.LlmAnalytics],[Scene.AIObservabilityScorers]: AccessControlResourceType.LlmAnalytics,+ [Scene.AIObservabilityScorer]: AccessControlResourceType.LlmAnalytics,[Scene.AIObservabilityOfflineExperiments]: AccessControlResourceType.Evaluation,[Scene.AIObservabilityOfflineExperiment]: AccessControlResourceType.Evaluation,[Scene.AIObservabilityOfflineScorerHistory]: AccessControlResourceType.Evaluation,diff --git a/products/ai_observability/backend/api/offline_experiment_read_serializers.py b/products/ai_observability/backend/api/offline_experiment_read_serializers.pyindex dafecc4c3e2f..dc8836d34792 100644--- a/products/ai_observability/backend/api/offline_experiment_read_serializers.py+++ b/products/ai_observability/backend/api/offline_experiment_read_serializers.py@@ -377,6 +377,18 @@ class OfflineScorerSummarySerializer(serializers.Serializer):true_rate = serializers.FloatField(allow_null=True, help_text="Boolean true fraction among successes; null with no successes or for other kinds.")+ pass_count = serializers.IntegerField(+ allow_null=True,+ help_text="Successful results passing the pinned rule. Boolean scores default to true passing; null for unconfigured numeric or categorical scorers.",+ )+ fail_count = serializers.IntegerField(+ allow_null=True,+ help_text="Successful results failing the pinned rule; null for unconfigured numeric or categorical scorers.",+ )+ pass_rate = serializers.FloatField(+ allow_null=True,+ help_text="Passing fraction among successful results; null without successful results or an applicable rule. Boolean scores default to true passing. Excludes errors, skipped, not-applicable, and missing results.",+ )categories = OfflineCategorySummarySerializer(many=True, help_text="Pinned categorical distribution; multiselect rates may sum above one.")diff --git a/products/ai_observability/backend/api/score_definitions.py b/products/ai_observability/backend/api/score_definitions.pyindex 76a1c863664f..8f9905a27236 100644--- a/products/ai_observability/backend/api/score_definitions.py+++ b/products/ai_observability/backend/api/score_definitions.py@@ -186,6 +186,15 @@ class ScoreDefinitionMetadataSerializer(serializers.Serializer):class ScoreDefinitionNewVersionSerializer(serializers.Serializer):+ name = serializers.CharField(+ max_length=255, required=False, help_text="Updated scorer name, saved with this version."+ )+ description = serializers.CharField(+ required=False,+ allow_blank=True,+ allow_null=True,+ help_text="Updated scorer description, saved with this version.",+ )config = ScoreDefinitionConfigField(help_text="Next immutable scorer configuration.")base_version = serializers.IntegerField(required=False,@@ -197,6 +206,12 @@ class ScoreDefinitionNewVersionSerializer(serializers.Serializer):),)+ def validate_name(self, value: str) -> str:+ normalized_value = value.strip()+ if not normalized_value:+ raise serializers.ValidationError("`name` cannot be blank.")+ return normalized_value+class ScoreDefinitionFilter(django_filters.FilterSet):search = django_filters.CharFilter(@@ -296,7 +311,7 @@ class ScoreDefinitionViewSet(definition.create_new_version(config=config, created_by=cast(User, self.request.user))return definition- def _update_definition_metadata(self, definition: ScoreDefinition, validated_data: dict[str, Any]) -> list[str]:+ def _update_definition_metadata(self, definition: ScoreDefinition, validated_data: dict[str, Any]) -> None:definition_data = dict(validated_data)changed_fields: list[str] = []@@ -308,11 +323,28 @@ class ScoreDefinitionViewSet(setattr(definition, field, value)changed_fields.append(field)- if changed_fields:- definition.save(update_fields=[*changed_fields, "updated_at"])+ if not changed_fields:+ return++ definition.save(update_fields=[*changed_fields, "updated_at"])+ event_properties: dict[str, str | bool | int | list[str]] = {+ **self._event_properties(definition),+ "changed_fields": changed_fields,+ }+ if "archived" in changed_fields:+ event_properties["archived_new_value"] = definition.archived- return changed_fields+ transaction.on_commit(+ lambda: report_user_action(+ self.request.user,+ "llma scorer updated",+ event_properties,+ team=self.team,+ request=self.request,+ )+ )+ @transaction.atomicdef _create_definition_version(self, definition: ScoreDefinition, validated_data: dict[str, Any]) -> ScoreDefinition:@@ -321,7 +353,11 @@ class ScoreDefinitionViewSet(created_by=cast(User, self.request.user),base_version=validated_data.get("base_version"),)- definition.refresh_from_db(fields=["current_version", "updated_at"])+ # create_new_version holds the row lock until commit. Reload so the metadata comparison sees writes made after get_object().+ definition.refresh_from_db()+ self._update_definition_metadata(+ definition, {field: validated_data[field] for field in ("name", "description") if field in validated_data}+ )return definition@extend_schema(@@ -378,24 +414,7 @@ class ScoreDefinitionViewSet()def partial_update(self, request: ValidatedRequest, *args: Any, **kwargs: Any) -> Response:definition = self.get_object()- changed_fields = self._update_definition_metadata(definition, dict(request.validated_data))-- if changed_fields:- event_properties: dict[str, Any] = {- **self._event_properties(definition),- "changed_fields": changed_fields,- }-- if "archived" in changed_fields:- event_properties["archived_new_value"] = definition.archived-- report_user_action(- request.user,- "llma scorer updated",- event_properties,- team=self.team,- request=request,- )+ self._update_definition_metadata(definition, dict(request.validated_data))return Response(self.get_serializer(definition).data, status=status.HTTP_200_OK)diff --git a/products/ai_observability/backend/api/test/test_score_definitions.py b/products/ai_observability/backend/api/test/test_score_definitions.pyindex c976da33f445..2443f81dc9e0 100644--- a/products/ai_observability/backend/api/test/test_score_definitions.py+++ b/products/ai_observability/backend/api/test/test_score_definitions.py@@ -1,7 +1,7 @@from uuid import uuid4from posthog.test.base import APIBaseTest-from unittest.mock import ANY, patch+from unittest.mock import ANY, Mock, call, patchfrom django.http import QueryDictfrom django.test import SimpleTestCase@@ -13,7 +13,10 @@ from posthog.constants import AvailableFeaturefrom posthog.models import OrganizationMembership, Userfrom products.access_control.backend.models.access_control import AccessControl-from products.ai_observability.backend.api.score_definitions import ScoreDefinitionVersionQuerySerializer+from products.ai_observability.backend.api.score_definitions import (+ ScoreDefinitionVersionQuerySerializer,+ ScoreDefinitionViewSet,+)from products.ai_observability.backend.models.score_definitions import (ScoreDefinition,ScoreDefinitionVersion,@@ -60,6 +63,7 @@ class TestScoreDefinitionsApi(APIBaseTest):"selection_mode": "multiple","min_selections": 1,"max_selections": 2,+ "passing_rule": {"categories": ["accurate", "helpful"]},},},),@@ -68,7 +72,7 @@ class TestScoreDefinitionsApi(APIBaseTest):{"name": "Score","kind": "numeric",- "config": {"min": 0, "max": 5, "step": 1},+ "config": {"min": 0, "max": 5, "step": 1, "passing_rule": {"operator": "gte", "threshold": 3}},},),(@@ -76,7 +80,7 @@ class TestScoreDefinitionsApi(APIBaseTest):{"name": "Resolved","kind": "boolean",- "config": {"true_label": "Yes", "false_label": "No"},+ "config": {"true_label": "Yes", "false_label": "No", "true_is_failure": False},},),]@@ -234,6 +238,9 @@ class TestScoreDefinitionsApi(APIBaseTest):response = self.client.post(f"{self._endpoint()}{definition.id}/new_version/",{+ "name": "Updated scorer",+ "description": "Updated description",+ "base_version": 1,"config": {"options": [{"key": "pass", "label": "Pass"},@@ -243,7 +250,7 @@ class TestScoreDefinitionsApi(APIBaseTest):"selection_mode": "multiple","min_selections": 1,"max_selections": 2,- }+ },},format="json",)@@ -252,6 +259,7 @@ class TestScoreDefinitionsApi(APIBaseTest):definition.refresh_from_db()current_version = self._current_version(definition)self.assertEqual(current_version.version, 2)+ self.assertEqual((definition.name, definition.description), ("Updated scorer", "Updated description"))self.assertEqual(definition.versions.count(), 2)self.assertEqual(definition.versions.get(version=1).config, original_config)self.assertEqual(@@ -399,6 +407,8 @@ class TestScoreDefinitionsApi(APIBaseTest):def test_new_version_with_stale_base_version_returns_409(self):definition = self._create_definition()+ original_name = definition.name+ original_description = definition.description# Someone else bumps the scorer to v2 first.definition.create_new_version(config={"options": [{"key": "intermediate", "label": "Intermediate"}]},@@ -409,6 +419,8 @@ class TestScoreDefinitionsApi(APIBaseTest):f"{self._endpoint()}{definition.id}/new_version/",{"base_version": 1,+ "name": "Stale name",+ "description": "Stale description","config": {"options": [{"key": "stale", "label": "Stale"},@@ -423,6 +435,58 @@ class TestScoreDefinitionsApi(APIBaseTest):definition.refresh_from_db()# Scorer still at v2 — the stale request did not bump it.self.assertEqual(self._current_version(definition).version, 2)+ self.assertEqual((definition.name, definition.description), (original_name, original_description))++ def test_new_version_rolls_back_when_metadata_persistence_fails(self) -> None:+ definition = self._create_definition()+ original_version_id = definition.current_version_id+ original_metadata = (definition.name, definition.description)+ original_count = ScoreDefinitionVersion.objects.filter(definition=definition).count()+ save = ScoreDefinition.save++ def save_then_fail(instance: ScoreDefinition, *, update_fields: list[str]) -> None:+ save(instance, update_fields=update_fields)+ if "name" in update_fields:+ raise RuntimeError("Metadata persistence failed")++ with patch.object(ScoreDefinition, "save", save_then_fail):+ response = self.client.post(+ f"{self._endpoint()}{definition.id}/new_version/",+ {+ "name": "Updated name",+ "description": "Updated description",+ "config": self._current_version(definition).config,+ },+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_500_INTERNAL_SERVER_ERROR)+ definition.refresh_from_db()+ self.assertEqual(definition.current_version_id, original_version_id)+ self.assertEqual((definition.name, definition.description), original_metadata)+ self.assertEqual(ScoreDefinitionVersion.objects.filter(definition=definition).count(), original_count)++ def test_new_version_applies_metadata_written_concurrently_before_the_lock(self):+ definition = self._create_definition()+ original_name = definition.name+ get_object = ScoreDefinitionViewSet.get_object++ def get_object_then_rename_elsewhere(view: ScoreDefinitionViewSet) -> ScoreDefinition:+ loaded = get_object(view)+ ScoreDefinition.objects.filter(pk=loaded.pk).update(name="Renamed elsewhere")+ return loaded++ with patch.object(ScoreDefinitionViewSet, "get_object", get_object_then_rename_elsewhere):+ response = self.client.post(+ f"{self._endpoint()}{definition.id}/new_version/",+ {"base_version": 1, "name": original_name, "config": self._current_version(definition).config},+ format="json",+ )++ self.assertEqual(response.status_code, status.HTTP_200_OK)+ definition.refresh_from_db()+ self.assertEqual(definition.name, original_name)+ self.assertEqual(response.data["name"], original_name)@parameterized.expand([@@ -541,15 +605,16 @@ class TestScoreDefinitionsApi(APIBaseTest):self.assertNotIn(str(active.id), [result["id"] for result in response.data["results"]])@patch("products.ai_observability.backend.api.score_definitions.report_user_action")- def test_patch_reports_user_action(self, mock_report_user_action):+ def test_patch_reports_user_action(self, mock_report_user_action: Mock) -> None:definition = self._create_definition()mock_report_user_action.reset_mock()- response = self.client.patch(- f"{self._endpoint()}{definition.id}/",- {"name": "Updated quality", "description": "Updated description", "archived": True},- format="json",- )+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.patch(+ f"{self._endpoint()}{definition.id}/",+ {"name": "Updated quality", "description": "Updated description", "archived": True},+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)definition.refresh_from_db()@@ -571,41 +636,53 @@ class TestScoreDefinitionsApi(APIBaseTest):request=ANY,)+ @parameterized.expand([("configuration_only", False), ("with_metadata", True)])@patch("products.ai_observability.backend.api.score_definitions.report_user_action")- def test_new_version_reports_user_action(self, mock_report_user_action):+ def test_new_version_reports_user_action(+ self, _name: str, update_metadata: bool, mock_report_user_action: Mock+ ) -> None:definition = self._create_definition()mock_report_user_action.reset_mock()- response = self.client.post(- f"{self._endpoint()}{definition.id}/new_version/",- {- "config": {- "options": [- {"key": "pass", "label": "Pass"},- {"key": "fail", "label": "Fail"},- ]- }- },- format="json",- )+ metadata = {"name": "Updated quality", "description": "Updated description"} if update_metadata else {}+ with self.captureOnCommitCallbacks(execute=True):+ response = self.client.post(+ f"{self._endpoint()}{definition.id}/new_version/",+ {+ **metadata,+ "config": {+ "options": [+ {"key": "pass", "label": "Pass"},+ {"key": "fail", "label": "Fail"},+ ]+ },+ },+ format="json",+ )self.assertEqual(response.status_code, status.HTTP_200_OK)definition.refresh_from_db()- mock_report_user_action.assert_called_once_with(- self.user,- "llma scorer version created",- {- "scorer_id": str(definition.id),- "scorer_name": definition.name,- "scorer_kind": definition.kind,- "has_description": False,- "archived": False,- "version": 2,- },- team=self.team,- request=ANY,- )+ properties = {+ "scorer_id": str(definition.id),+ "scorer_name": definition.name,+ "scorer_kind": definition.kind,+ "has_description": update_metadata,+ "archived": False,+ "version": 2,+ }+ expected_calls = [call(self.user, "llma scorer version created", properties, team=self.team, request=ANY)]+ if update_metadata:+ expected_calls.append(+ call(+ self.user,+ "llma scorer updated",+ {**properties, "changed_fields": ["name", "description"]},+ team=self.team,+ request=ANY,+ )+ )+ self.assertCountEqual(mock_report_user_action.call_args_list, expected_calls)def _default_config_for_kind(self, kind: str) -> dict:if kind == "categorical":diff --git a/products/ai_observability/backend/api/test/test_trace_reviews.py b/products/ai_observability/backend/api/test/test_trace_reviews.pyindex 4f4aa2463baa..39cc83cacd3c 100644--- a/products/ai_observability/backend/api/test/test_trace_reviews.py+++ b/products/ai_observability/backend/api/test/test_trace_reviews.py@@ -174,12 +174,12 @@ class TestTraceReviewsApi(APIBaseTest):resolved = self._create_definition(name="Resolved",kind="boolean",- config={"true_label": "Yes", "false_label": "No"},+ config={"true_label": "Yes", "false_label": "No", "true_is_failure": True},)confidence = self._create_definition(name="Confidence",kind="numeric",- config={"min": 0, "max": 5, "step": 0.5},+ config={"min": 0, "max": 5, "step": 0.5, "passing_rule": {"operator": "gte", "threshold": 5}},)response = self.client.post(@@ -213,6 +213,8 @@ class TestTraceReviewsApi(APIBaseTest):self.assertEqual(themes_score.definition_config, themes_version.config)self.assertEqual(themes_score.categorical_values, ["helpful", "accurate"])self.assertEqual(resolved_score.boolean_value, True)+ self.assertEqual(resolved_score.definition_config, self._current_version(resolved).config)+ self.assertEqual(confidence_score.definition_config, self._current_version(confidence).config)self.assertEqual(str(confidence_score.numeric_value), "4.500000")def test_can_create_review_with_an_explicit_definition_version(self):diff --git a/products/ai_observability/backend/offline_evaluation_read_service.py b/products/ai_observability/backend/offline_evaluation_read_service.pyindex 4f1a4b9c4709..fd97fd6817dc 100644--- a/products/ai_observability/backend/offline_evaluation_read_service.py+++ b/products/ai_observability/backend/offline_evaluation_read_service.py@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, castfrom uuid import UUIDfrom django.db import connections-from django.db.models import Count, Exists, F, OuterRef, Q+from django.db.models import Case, Count, Exists, F, OuterRef, Q, Whenfrom posthog.dataclasses import frozen@@ -73,6 +73,7 @@ class _Aggregate:mean: float | Nonetrue_count: intfalse_count: int+ pass_count: int | Nonecoverage: _ItemCoveragecategories: dict[str, int]@@ -510,17 +511,56 @@ class OfflineEvaluationReadService:data=payload.data if payload is not None else None,)- def _aggregates(self, identities: list[_SummaryIdentity]) -> dict[_SummaryIdentity, _Aggregate]:+ @staticmethod+ def _passing_condition(version: ScoreDefinitionVersion) -> Q | None:+ if version.definition.kind == "boolean":+ return Q(boolean_value=version.config.get("true_is_failure") is not True)+ elif version.definition.kind == "numeric":+ rule = version.config.get("passing_rule")+ if isinstance(rule, dict):+ if rule.get("operator") == "gte":+ return Q(numeric_value__gte=rule["threshold"])+ if rule.get("operator") == "lte":+ return Q(numeric_value__lte=rule["threshold"])+ elif version.definition.kind == "categorical":+ rule = version.config.get("passing_rule")+ if isinstance(rule, dict):+ categories = rule["categories"]+ return (+ Q(categorical_values__contained_by=categories) & ~Q(categorical_values=[])+ if categories+ else Q(categorical_values=[])+ )+ return None++ def _aggregates(+ self, identities: list[_SummaryIdentity], *, versions: dict[UUID, ScoreDefinitionVersion]+ ) -> dict[_SummaryIdentity, _Aggregate]:selected = Q(pk__in=[])for identity in identities:selected |= Q(item__experiment_id=identity.experiment_id, scorer_version_id=identity.version_id)+ passing = Q(pk__in=[])+ configured_versions = set()+ for version_id, version in versions.items():+ condition = self._passing_condition(version)+ if condition is not None:+ configured_versions.add(version_id)+ passing |= Q(scorer_version_id=version_id) & conditionresults = (self._results().filter(selected).order_by()- .annotate(experiment_id=F("item__experiment_id"))+ .annotate(+ experiment_id=F("item__experiment_id"), score_passes=Case(When(passing, then=True), default=False)+ ).values(- "experiment_id", "scorer_version_id", "status", "numeric_value", "boolean_value", "categorical_values"+ "experiment_id",+ "scorer_version_id",+ "status",+ "numeric_value",+ "boolean_value",+ "categorical_values",+ "score_passes",))sql, params = results.query.sql_with_params()@@ -537,7 +577,8 @@ class OfflineEvaluationReadService:count(*) FILTER (WHERE status = 'not_applicable') AS not_applicable_count,avg(numeric_value::text::numeric) FILTER (WHERE status = 'ok') AS mean,count(*) FILTER (WHERE status = 'ok' AND boolean_value IS TRUE) AS true_count,- count(*) FILTER (WHERE status = 'ok' AND boolean_value IS FALSE) AS false_count+ count(*) FILTER (WHERE status = 'ok' AND boolean_value IS FALSE) AS false_count,+ count(*) FILTER (WHERE status = 'ok' AND score_passes) AS pass_countFROM selected GROUP BY experiment_id, scorer_version_id), category_counts AS (SELECT experiment_id, scorer_version_id, category, count(*) AS selected_count@@ -564,7 +605,7 @@ class OfflineEvaluationReadService:a.skipped_count, a.not_applicable_count, a.mean, a.true_count, a.false_count,c.observed_item_count, c.distinct_case_count, c.items_with_case_key_count,c.items_without_case_key_count, c.trial_item_count, c.distinct_trial_count,- categories.keys, categories.counts+ categories.keys, categories.counts, a.pass_countFROM aggregates a JOIN coverage c USING (experiment_id)LEFT JOIN categories USING (experiment_id, scorer_version_id)"""@@ -586,6 +627,7 @@ class OfflineEvaluationReadService:mean=float(row[7]) if row[7] is not None else None,true_count=row[8],false_count=row[9],+ pass_count=row[18] if row[1] in configured_versions else None,coverage=_ItemCoverage(observed_item_count=row[10],distinct_case_count=row[11],@@ -608,7 +650,7 @@ class OfflineEvaluationReadService:.filter(id__in=[identity.version_id for identity in identities]).select_related("definition")}- aggregates = self._aggregates(identities)+ aggregates = self._aggregates(identities, versions=versions)summaries = {}for identity in identities:version = versions.get(identity.version_id)@@ -649,6 +691,13 @@ class OfflineEvaluationReadService:true_rate=aggregate.true_count / aggregate.status_counts.okif scorer.kind == "boolean" and aggregate.status_counts.okelse None,+ pass_count=aggregate.pass_count,+ fail_count=aggregate.status_counts.ok - aggregate.pass_count+ if aggregate.pass_count is not None+ else None,+ pass_rate=aggregate.pass_count / aggregate.status_counts.ok+ if aggregate.pass_count is not None and aggregate.status_counts.ok+ else None,categories=categories,)return summariesdiff --git a/products/ai_observability/backend/offline_evaluation_read_types.py b/products/ai_observability/backend/offline_evaluation_read_types.pyindex 7f2ebaef6539..bd03f4bf9a23 100644--- a/products/ai_observability/backend/offline_evaluation_read_types.py+++ b/products/ai_observability/backend/offline_evaluation_read_types.py@@ -181,6 +181,9 @@ class OfflineScorerSummary:true_count: int | Nonefalse_count: int | Nonetrue_rate: float | None+ pass_count: int | None+ fail_count: int | None+ pass_rate: float | Nonecategories: list[OfflineCategorySummary]diff --git a/products/ai_observability/backend/score_definition_configs.py b/products/ai_observability/backend/score_definition_configs.pyindex e217bc0490e1..086e2abda4be 100644--- a/products/ai_observability/backend/score_definition_configs.py+++ b/products/ai_observability/backend/score_definition_configs.py@@ -1,6 +1,9 @@import re+import mathfrom typing import Any+from django.db import models+from drf_spectacular.utils import PolymorphicProxySerializer, extend_schema_fieldfrom rest_framework import serializers@@ -32,6 +35,25 @@ class CategoricalScoreOptionSerializer(serializers.Serializer):return normalize_score_definition_key(value, field_name="key")+class CategoricalScorePassingRuleSerializer(serializers.Serializer):+ categories = serializers.ListField(+ child=serializers.CharField(max_length=128),+ help_text="Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.",+ )++ def to_internal_value(self, data: object) -> dict[str, list[str]]:+ if isinstance(data, dict) and set(data) - self.fields.keys():+ raise serializers.ValidationError(+ {"non_field_errors": "Only category keys may be configured in this rule."}+ )+ return super().to_internal_value(data)++ def validate_categories(self, value: list[str]) -> list[str]:+ if len(set(value)) != len(value):+ raise serializers.ValidationError("Select each passing category only once.")+ return sorted(value)++class CategoricalScoreDefinitionConfigSerializer(serializers.Serializer):options = CategoricalScoreOptionSerializer(many=True,@@ -54,6 +76,11 @@ class CategoricalScoreDefinitionConfigSerializer(serializers.Serializer):min_value=1,help_text="Optional maximum number of options that can be selected when `selection_mode` is `multiple`.",)+ passing_rule = CategoricalScorePassingRuleSerializer(+ required=False,+ allow_null=True,+ help_text="Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule.",+ )def validate_options(self, value: list[dict[str, str]]) -> list[dict[str, str]]:if len(value) == 0:@@ -71,6 +98,15 @@ class CategoricalScoreDefinitionConfigSerializer(serializers.Serializer):maximum = attrs.get("max_selections")option_count = len(attrs.get("options", []))+ rule = attrs.get("passing_rule")+ if rule is not None:+ if selection_mode == "single" and not rule["categories"]:+ raise serializers.ValidationError({"passing_rule": "Choose at least one passing category."})+ if not set(rule["categories"]) <= {option["key"] for option in attrs.get("options", [])}:+ raise serializers.ValidationError(+ {"passing_rule": "Choose passing categories from the configured options."}+ )+if selection_mode == "single":if minimum is not None:raise serializers.ValidationError(@@ -100,6 +136,41 @@ class CategoricalScoreDefinitionConfigSerializer(serializers.Serializer):return attrs+class NumericScorePassingRuleSerializer(serializers.Serializer):+ class Operator(models.TextChoices):+ GTE = "gte", "At or above"+ LTE = "lte", "At or below"++ operator = serializers.ChoiceField(+ choices=Operator.choices,+ help_text="Pass at or above (gte), or at or below (lte), the threshold.",+ )+ threshold = serializers.FloatField(help_text="Finite passing threshold within any configured score bounds.")++ def to_internal_value(self, data: Any) -> dict[str, Any]:+ if isinstance(data, dict):+ unknown_keys = sorted(set(data) - self.fields.keys())+ if unknown_keys:+ raise serializers.ValidationError(+ {"non_field_errors": f"Unsupported passing rule keys: {unknown_keys}."}+ )+ if "threshold" in data and (+ isinstance(data["threshold"], bool) or not isinstance(data["threshold"], int | float)+ ):+ raise serializers.ValidationError({"threshold": "Provide a finite number."})+ if isinstance(data.get("threshold"), int):+ try:+ float(data["threshold"])+ except OverflowError as error:+ raise serializers.ValidationError({"threshold": "Provide a finite number."}) from error+ return super().to_internal_value(data)++ def validate_threshold(self, value: float) -> float:+ if not math.isfinite(value):+ raise serializers.ValidationError("Provide a finite number.")+ return value++class NumericScoreDefinitionConfigSerializer(serializers.Serializer):min = serializers.FloatField(required=False,@@ -116,6 +187,11 @@ class NumericScoreDefinitionConfigSerializer(serializers.Serializer):allow_null=True,help_text="Optional increment step for numeric input, for example 1 or 0.5.",)+ passing_rule = NumericScorePassingRuleSerializer(+ required=False,+ allow_null=True,+ help_text="Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule.",+ )def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:minimum = attrs.get("min")@@ -128,10 +204,23 @@ class NumericScoreDefinitionConfigSerializer(serializers.Serializer):if step is not None and step <= 0:raise serializers.ValidationError({"step": "Ensure `step` is greater than 0."})+ passing_rule = attrs.get("passing_rule")+ if passing_rule is not None:+ threshold = passing_rule["threshold"]+ if minimum is not None and threshold < minimum:+ raise serializers.ValidationError({"passing_rule": "The passing threshold must be at least `min`."})+ if maximum is not None and threshold > maximum:+ raise serializers.ValidationError({"passing_rule": "The passing threshold must be at most `max`."})+return attrsclass BooleanScoreDefinitionConfigSerializer(serializers.Serializer):+ true_is_failure = serializers.BooleanField(+ required=False,+ allow_null=True,+ help_text="Whether true means failure. False, omitted, or null means true passes in offline evaluations.",+ )true_label = serializers.CharField(required=False,allow_blank=False,diff --git a/products/ai_observability/backend/test/test_offline_evaluation_reads.py b/products/ai_observability/backend/test/test_offline_evaluation_reads.pyindex 0683e4df059d..f0e249b9cf14 100644--- a/products/ai_observability/backend/test/test_offline_evaluation_reads.py+++ b/products/ai_observability/backend/test/test_offline_evaluation_reads.py@@ -183,6 +183,10 @@ class TestOfflineEvaluationReads(TestCase):self.assertIsNone(summaries[self.numeric_v2.id].mean)boolean = summaries[self.boolean.id]self.assertEqual((boolean.true_count, boolean.false_count, boolean.true_rate), (1, 1, 0.5))+ self.assertEqual((boolean.pass_count, boolean.fail_count, boolean.pass_rate), (1, 1, 0.5))+ for summary in summaries.values():+ if summary.scorer.kind != "boolean":+ self.assertEqual((summary.pass_count, summary.fail_count, summary.pass_rate), (None, None, None))self.assertEqual([(category.key, category.count, category.rate) for category in summaries[self.categorical.id].categories],[("a", 2, 1.0), ("b", 1, 0.5), ("c", 0, 0.0)],@@ -198,6 +202,90 @@ class TestOfflineEvaluationReads(TestCase):).results[0]self.assertEqual(summary, numeric)+ @parameterized.expand(+ [+ (+ "numeric",+ [+ {"passing_rule": {"operator": "gte", "threshold": 5}},+ {"passing_rule": {"operator": "lte", "threshold": 5}},+ ],+ [0.0, 5.0, 10.0, 10.0],+ [3, 2],+ ),+ (+ "categorical",+ [+ {+ "options": [{"key": "a", "label": "A"}, {"key": "b", "label": "B"}],+ "selection_mode": "multiple",+ "passing_rule": {"categories": ["a"]},+ },+ {+ "options": [{"key": "a", "label": "A"}, {"key": "b", "label": "B"}],+ "selection_mode": "multiple",+ "passing_rule": {"categories": ["a", "b"]},+ },+ {+ "options": [{"key": "a", "label": "A"}, {"key": "b", "label": "B"}],+ "selection_mode": "multiple",+ "passing_rule": {"categories": []},+ },+ ],+ [["a"], ["b"], ["a", "b"], ["a"]],+ [2, 4, 0],+ ),+ (+ "boolean",+ [{"true_is_failure": False}, {"true_is_failure": True}],+ [True, False, False, False],+ [1, 3],+ ),+ ]+ )+ def test_passing_summaries_use_pinned_rules_and_exclude_non_scores(+ self, kind: str, configs: list[dict[str, JSONValue]], values: list[ResultValue], pass_counts: list[int]+ ) -> None:+ definition = ScoreDefinition.objects.create(team=self.team, name="Configured scorer", kind=kind)+ versions = [definition.create_new_version(config=config, created_by=None) for config in configs]+ empty_version = definition.create_new_version(config=configs[0], created_by=None)+ unconfigured_version = definition.create_new_version(+ config={"true_is_failure": None} if kind == "boolean" else {**configs[0], "passing_rule": None},+ created_by=None,+ )+ experiment = self._experiment()+ items = [self._item(experiment) for _ in range(8)]+ for version in versions:+ for item, value in zip(items, values):+ self._result(item, version, value)+ for item, status in zip(items[4:7], ("error", "skipped", "not_applicable")):+ self._result(item, version, status=status)+ self._result(items[0], empty_version, status="error")+ self._result(items[0], unconfigured_version, values[0])++ summaries = {+ summary.scorer.id: summary+ for summary in self.service.list_summaries(experiment.id, OfflineReadQuery()).results+ }+ for version, pass_count in zip(versions, pass_counts):+ summary = summaries[version.id]+ self.assertEqual(+ (summary.pass_count, summary.fail_count, summary.pass_rate),+ (pass_count, 4 - pass_count, pass_count / 4),+ )+ self.assertEqual(summary.status_counts, OfflineStatusCounts(ok=4, error=1, skipped=1, not_applicable=1))+ self.assertEqual(summary.missing_result_count, 1)+ empty = summaries[empty_version.id]+ self.assertEqual((empty.pass_count, empty.fail_count, empty.pass_rate), (0, 0, None))+ unconfigured = summaries[unconfigured_version.id]+ self.assertEqual(+ (unconfigured.pass_count, unconfigured.fail_count, unconfigured.pass_rate),+ (1, 0, 1.0) if kind == "boolean" else (None, None, None),+ )+ history = self.service.scorer_history(definition.id, OfflineReadQuery())+ for point in history.results:+ self.assertEqual(point.summary, summaries[point.summary.scorer.id])+@parameterized.expand([(1e308, 1e308, 1e308),diff --git a/products/ai_observability/backend/test/test_score_definition_configs.py b/products/ai_observability/backend/test/test_score_definition_configs.pyindex be84a80b6b05..c48053a8f357 100644--- a/products/ai_observability/backend/test/test_score_definition_configs.py+++ b/products/ai_observability/backend/test/test_score_definition_configs.py@@ -7,6 +7,26 @@ from products.ai_observability.backend.score_definition_configs import build_scoclass TestScoreDefinitionConfigValidation(unittest.TestCase):+ @parameterized.expand(+ [+ ("unknown_category", {"categories": ["missing"]}),+ ("duplicate_category", {"categories": ["good", "good"]}),+ ("empty_single", {"categories": []}),+ ("missing_categories", {}),+ ("unknown_key", {"categories": ["good"], "operator": "any"}),+ ]+ )+ def test_rejects_invalid_categorical_passing_rules(self, _name: str, rule: dict[str, list[str] | str]) -> None:+ serializer = build_score_definition_config_serializer(+ "categorical",+ data={+ "options": [{"key": "good", "label": "Good"}],+ "passing_rule": rule,+ },+ )+ self.assertFalse(serializer.is_valid())+ self.assertIn("passing_rule", serializer.errors)+@parameterized.expand([(@@ -115,10 +135,62 @@ class TestScoreDefinitionConfigValidation(unittest.TestCase):"max_selections": 2,},),+ (+ "categorical_passing",+ "categorical",+ {"options": [{"key": "good", "label": "Good"}], "passing_rule": {"categories": ["good"]}},+ ),+ (+ "categorical_neutral",+ "categorical",+ {"options": [{"key": "good", "label": "Good"}], "passing_rule": None},+ ),+ (+ "categorical_no_passing_categories",+ "categorical",+ {+ "options": [{"key": "good", "label": "Good"}],+ "selection_mode": "multiple",+ "passing_rule": {"categories": []},+ },+ ),("numeric", "numeric", {"min": 0, "max": 5, "step": 1}),+ (+ "numeric_passing",+ "numeric",+ {"min": 0, "max": 5, "step": 1, "passing_rule": {"operator": "gte", "threshold": 2.5}},+ ),+ ("numeric_neutral", "numeric", {"passing_rule": None}),("boolean", "boolean", {"true_label": "Yes", "false_label": "No"}),+ ("boolean_true_passes", "boolean", {"true_is_failure": False}),+ ("boolean_true_fails", "boolean", {"true_is_failure": True}),+ ("boolean_default_polarity", "boolean", {"true_is_failure": None}),+ ("boolean_legacy", "boolean", {}),])def test_valid_configs_pass_validation(self, _name: str, kind: str, payload: dict) -> None:serializer = build_score_definition_config_serializer(kind, data=payload)self.assertTrue(serializer.is_valid(), serializer.errors)+ self.assertEqual(serializer.validated_data, payload)++ @parameterized.expand(+ [+ ("below_minimum", {"operator": "gte", "threshold": -1}),+ ("above_maximum", {"operator": "lte", "threshold": 6}),+ ("unknown_operator", {"operator": "gt", "threshold": 3}),+ ("missing_threshold", {"operator": "gte"}),+ ("missing_operator", {"threshold": 3}),+ ("unknown_key", {"operator": "gte", "threshold": 3, "unexpected": True}),+ ("boolean_threshold", {"operator": "gte", "threshold": True}),+ ("string_threshold", {"operator": "gte", "threshold": "3"}),+ ("nan_threshold", {"operator": "gte", "threshold": float("nan")}),+ ("infinite_threshold", {"operator": "gte", "threshold": float("inf")}),+ ("overflowing_threshold", {"operator": "gte", "threshold": 10**400}),+ ]+ )+ def test_rejects_invalid_numeric_passing_rule(self, _name: str, rule: dict[str, object]) -> None:+ serializer = build_score_definition_config_serializer(+ "numeric", data={"min": 0, "max": 5, "passing_rule": rule}+ )+ self.assertFalse(serializer.is_valid())+ self.assertIn("passing_rule", serializer.errors)diff --git a/products/ai_observability/frontend/generated/api.schemas.ts b/products/ai_observability/frontend/generated/api.schemas.tsindex 8c74aa767118..d5ffb7051c7b 100644--- a/products/ai_observability/frontend/generated/api.schemas.ts+++ b/products/ai_observability/frontend/generated/api.schemas.ts@@ -752,6 +752,14 @@ export const SelectionModeEnumApi = {Multiple: 'multiple',} as const+export interface CategoricalScorePassingRuleApi {+ /**+ * Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.+ * @items.maxLength 128+ */+ categories: string[]+}+export interface CategoricalScoreDefinitionConfigApi {/** Ordered categorical options available to the scorer. */options: CategoricalScoreOptionApi[]@@ -772,6 +780,30 @@ export interface CategoricalScoreDefinitionConfigApi {* @nullable*/max_selections?: number | null+ /** Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule. */+ passing_rule?: CategoricalScorePassingRuleApi | null+}++/**+ * * `gte` - At or above+ * * `lte` - At or below+ */+export type NumericScorePassingRuleSerializerOperatorEnumApi =+ (typeof NumericScorePassingRuleSerializerOperatorEnumApi)[keyof typeof NumericScorePassingRuleSerializerOperatorEnumApi]++export const NumericScorePassingRuleSerializerOperatorEnumApi = {+ Gte: 'gte',+ Lte: 'lte',+} as const++export interface NumericScorePassingRuleApi {+ /** Pass at or above (gte), or at or below (lte), the threshold.+ *+ * * `gte` - At or above+ * * `lte` - At or below */+ operator: NumericScorePassingRuleSerializerOperatorEnumApi+ /** Finite passing threshold within any configured score bounds. */+ threshold: number}export interface NumericScoreDefinitionConfigApi {@@ -790,9 +822,16 @@ export interface NumericScoreDefinitionConfigApi {* @nullable*/step?: number | null+ /** Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule. */+ passing_rule?: NumericScorePassingRuleApi | null}export interface BooleanScoreDefinitionConfigApi {+ /**+ * Whether true means failure. False, omitted, or null means true passes in offline evaluations.+ * @nullable+ */+ true_is_failure?: boolean | null/** Optional label for a true value. */true_label?: string/** Optional label for a false value. */@@ -1063,6 +1102,21 @@ export interface OfflineScorerSummaryApi {* @nullable*/true_rate: number | null+ /**+ * Successful results passing the pinned rule. Boolean scores default to true passing; null for unconfigured numeric or categorical scorers.+ * @nullable+ */+ pass_count: number | null+ /**+ * Successful results failing the pinned rule; null for unconfigured numeric or categorical scorers.+ * @nullable+ */+ fail_count: number | null+ /**+ * Passing fraction among successful results; null without successful results or an applicable rule. Boolean scores default to true passing. Excludes errors, skipped, not-applicable, and missing results.+ * @nullable+ */+ pass_rate: number | null/** Pinned categorical distribution; multiselect rates may sum above one. */categories: OfflineCategorySummaryApi[]}@@ -3672,6 +3726,16 @@ export interface PatchedScoreDefinitionMetadataApi {}export interface ScoreDefinitionNewVersionApi {+ /**+ * Updated scorer name, saved with this version.+ * @maxLength 255+ */+ name?: string+ /**+ * Updated scorer description, saved with this version.+ * @nullable+ */+ description?: string | null/** Next immutable scorer configuration. */config: ScoreDefinitionConfigApi/**diff --git a/products/ai_observability/frontend/generated/api.zod.ts b/products/ai_observability/frontend/generated/api.zod.tsindex 935466c7dbe0..d42dddd360ee 100644--- a/products/ai_observability/frontend/generated/api.zod.ts+++ b/products/ai_observability/frontend/generated/api.zod.ts@@ -2336,6 +2336,8 @@ export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemKeyMaxexport const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemLabelMax = 256+export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax = 128+export const LlmAnalyticsScoreDefinitionsCreateBody = /* @__PURE__ */ zod.object({name: zod.string().max(llmAnalyticsScoreDefinitionsCreateBodyNameMax).describe('Human-readable scorer name.'),description: zod.string().nullish().describe('Optional human-readable description.'),@@ -2389,6 +2391,27 @@ export const LlmAnalyticsScoreDefinitionsCreateBody = /* @__PURE__ */ zod.object.describe('Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'),+ passing_rule: zod+ .union([+ zod.object({+ categories: zod+ .array(+ zod+ .string()+ .max(+ llmAnalyticsScoreDefinitionsCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax+ )+ )+ .describe(+ 'Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({min: zod.number().nullish().describe('Optional inclusive minimum score.'),@@ -2397,8 +2420,33 @@ export const LlmAnalyticsScoreDefinitionsCreateBody = /* @__PURE__ */ zod.object.number().nullish().describe('Optional increment step for numeric input, for example 1 or 0.5.'),+ passing_rule: zod+ .union([+ zod.object({+ operator: zod+ .enum(['gte', 'lte'])+ .describe('\* `gte` - At or above\n\* `lte` - At or below')+ .describe(+ 'Pass at or above (gte), or at or below (lte), the threshold.\n\n\* `gte` - At or above\n\* `lte` - At or below'+ ),+ threshold: zod+ .number()+ .describe('Finite passing threshold within any configured score bounds.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({+ true_is_failure: zod+ .boolean()+ .nullish()+ .describe(+ 'Whether true means failure. False, omitted, or null means true passes in offline evaluations.'+ ),true_label: zod.string().optional().describe('Optional label for a true value.'),false_label: zod.string().optional().describe('Optional label for a false value.'),}),@@ -2418,11 +2466,21 @@ export const LlmAnalyticsScoreDefinitionsPartialUpdateBody = /* @__PURE__ */ zodarchived: zod.boolean().optional().describe('Whether the scorer is archived.'),})+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyNameMax = 255+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemKeyMax = 128export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemLabelMax = 256+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax = 128+export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */ zod.object({+ name: zod+ .string()+ .max(llmAnalyticsScoreDefinitionsNewVersionCreateBodyNameMax)+ .optional()+ .describe('Updated scorer name, saved with this version.'),+ description: zod.string().nullish().describe('Updated scorer description, saved with this version.'),config: zod.union([zod.object({@@ -2463,6 +2521,27 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */.describe('Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'),+ passing_rule: zod+ .union([+ zod.object({+ categories: zod+ .array(+ zod+ .string()+ .max(+ llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax+ )+ )+ .describe(+ 'Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({min: zod.number().nullish().describe('Optional inclusive minimum score.'),@@ -2471,8 +2550,33 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = /* @__PURE__ */.number().nullish().describe('Optional increment step for numeric input, for example 1 or 0.5.'),+ passing_rule: zod+ .union([+ zod.object({+ operator: zod+ .enum(['gte', 'lte'])+ .describe('\* `gte` - At or above\n\* `lte` - At or below')+ .describe(+ 'Pass at or above (gte), or at or below (lte), the threshold.\n\n\* `gte` - At or above\n\* `lte` - At or below'+ ),+ threshold: zod+ .number()+ .describe('Finite passing threshold within any configured score bounds.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({+ true_is_failure: zod+ .boolean()+ .nullish()+ .describe(+ 'Whether true means failure. False, omitted, or null means true passes in offline evaluations.'+ ),true_label: zod.string().optional().describe('Optional label for a true value.'),false_label: zod.string().optional().describe('Optional label for a false value.'),}),diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsxindex 439ce55ed357..724297449d9f 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineExperimentContent.tsx@@ -17,7 +17,7 @@ import { OfflineItemInspector } from './OfflineItemInspector'import { OfflineItemMatrix } from './OfflineItemMatrix'import { offlineRunSourceLabel } from './offlineOverviewState'import { offlineScorerHistoryUrl } from './offlineScorerHistoryLogic'-import { formatOfflineScore } from './offlineScoreTrends'+import { OfflineScoreSummaryDisplay } from './OfflineScoreSummaryDisplay'export function OfflineExperimentContent(props: OfflineExperimentLogicProps): JSX.Element {const logic = offlineExperimentLogic(props)@@ -187,9 +187,7 @@ export function OfflineExperimentContent(props: OfflineExperimentLogicProps): JS{title: 'Summary',render: (_, summary: OfflineScorerSummaryApi) => (- <span className="break-words" translate="no">- {formatOfflineScore(summary)}- </span>+ <OfflineScoreSummaryDisplay summary={summary} />),},{diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsxindex 95bda1f6b0d7..23216a3675f4 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineItemInspector.tsx@@ -1,15 +1,6 @@import { useActions, useValues } from 'kea'-import {- LemonBanner,- LemonButton,- LemonCard,- LemonModal,- LemonSkeleton,- LemonTable,- LemonTag,- Link,-} from '@posthog/lemon-ui'+import { LemonBanner, LemonButton, LemonCard, LemonModal, LemonSkeleton, LemonTable, Link } from '@posthog/lemon-ui'import { TZLabel } from 'lib/components/TZLabel'import { LemonModalContent, LemonModalFooter, LemonModalHeader } from 'lib/lemon-ui/LemonModal/LemonModal'@@ -18,7 +9,8 @@ import { urls } from 'scenes/urls'import type { OfflineResultReadApi } from '../generated/api.schemas'import { OfflineItemInspectorLogicProps, offlineItemInspectorLogic } from './offlineItemInspectorLogic'import { OfflinePayload } from './OfflinePayload'-import { offlineResultLabel } from './offlineResultPresentation'+import { OfflineResultTag } from './OfflineResultTag'+import { offlineScorePassingRuleLabel } from './offlineScoreTrends'export function OfflineItemInspector({onClose,@@ -109,16 +101,16 @@ export function OfflineItemInspector({</div><span className="text-xs text-muted">{`Version ${selectedResult.scorer.version}`}</span></div>- <LemonTag- type={selectedResult.status === 'error' ? 'danger' : 'default'}- size="medium"- wrap- >- <span className="text-lg font-semibold break-words" translate="no">- {offlineResultLabel(selectedResult, selectedResult.scorer)}- </span>- </LemonTag>+ <OfflineResultTag+ result={selectedResult}+ scorer={selectedResult.scorer}+ /></div>+ {offlineScorePassingRuleLabel(selectedResult.scorer) && (+ <p className="text-xs text-muted mb-0">+ {offlineScorePassingRuleLabel(selectedResult.scorer)}+ </p>+ )}{selectedResult.error_code && (<LemonBanner type="warning">{`Evaluator error: ${selectedResult.error_code}`}</LemonBanner>)}@@ -231,18 +223,7 @@ export function OfflineItemInspector({{title: 'Score',render: (_, result: OfflineResultReadApi) => (- <span- className={- result.status === 'error'- ? 'text-danger'- : result.status === 'ok'- ? undefined- : 'text-muted'- }- translate="no"- >- {offlineResultLabel(result, result.scorer)}- </span>+ <OfflineResultTag result={result} scorer={result.scorer} />),},]}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineItemMatrix.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineItemMatrix.tsxindex 7209c1b18a65..04466e3342cd 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineItemMatrix.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineItemMatrix.tsx@@ -12,7 +12,7 @@ import {OFFLINE_SCORER_BATCH_SIZE,OFFLINE_SCORER_COLUMN_WIDTH,} from './offlineItemMatrixConstants'-import { offlineResultLabel } from './offlineResultPresentation'+import { OfflineResultTag } from './OfflineResultTag'export function OfflineItemMatrix(props: OfflineExperimentLogicProps): JSX.Element {const logic = offlineExperimentLogic(props)@@ -118,18 +118,7 @@ export function OfflineItemMatrix(props: OfflineExperimentLogicProps): JSX.ElemeclassName="justify-start"tooltip={result.error_code || undefined}>- <span- className={- result.status === 'error'- ? 'truncate text-danger'- : result.status === 'ok'- ? 'truncate'- : 'truncate text-muted'- }- translate="no"- >- {offlineResultLabel(result, scorer)}- </span>+ <OfflineResultTag result={result} scorer={scorer} /></LemonButton>) : (<span className="text-muted text-xs">No result</span>diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsxindex 243b9092a9cc..9b6aa4b68ff1 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.test.tsx@@ -45,7 +45,8 @@ describe('OfflineOverviewTrend', () => {await screen.findByText(scorer.name)expect(screen.getByText('0.851667')).toBeInTheDocument()- expect(screen.getByText('Mean score · 6 experiments')).toBeInTheDocument()+ expect(screen.getByText('6 experiments (570 items)')).toBeInTheDocument()+ expect(screen.getByText('Mean score')).toBeInTheDocument()if (partial) {expect(screen.getByText(/6 of 200 experiment\/version results.*Partial history/)).toBeInTheDocument()expect(screen.getByText('Earlier experiments and scorer versions may not be shown.')).toBeInTheDocument()diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.tsxindex 73cdccfe64b3..4817958b7a8f 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineOverviewTrend.tsx@@ -8,8 +8,9 @@ import { urls } from 'scenes/urls'import type { offlineExperimentsLogicType } from './offlineExperimentsLogic'import { offlineOverviewTrendLogic, type OfflineOverviewTrendLogicProps } from './offlineOverviewTrendLogic'+import { OfflineScoreSummaryDisplay } from './OfflineScoreSummaryDisplay'import { OfflineScoreTrendChart } from './OfflineScoreTrendChart'-import { formatOfflineScore, getOfflineHistoryCoverage, offlineScoreMetricLabel } from './offlineScoreTrends'+import { getOfflineHistoryCoverage } from './offlineScoreTrends'export function OfflineOverviewTrend(props: OfflineOverviewTrendLogicProps & {@@ -25,6 +26,11 @@ export function OfflineOverviewTrend(const { loadOfflineOverviewTrend, selectVersion } = useActions(logic)const versionIndex = versions.findIndex((version) => version.id === activeVersion?.id)const hasPartialHistory = !!trend && trend.page.count > trend.page.results.length+ const scoredItemCount = periodSummary+ ? periodSummary.pass_count != null && periodSummary.fail_count != null+ ? periodSummary.pass_count + periodSummary.fail_count+ : periodSummary.status_counts.ok+ : 0return (<LemonCard hoverEffect={false} className="min-w-0 flex flex-col gap-3">@@ -92,9 +98,9 @@ export function OfflineOverviewTrend()}</div>{periodSummary && (- <div className="flex flex-wrap items-baseline gap-x-2 gap-y-1">- <strong>{formatOfflineScore(periodSummary)}</strong>- <span className="text-muted text-xs">{`${offlineScoreMetricLabel(periodSummary.scorer)} · ${periodSummary.experimentCount} ${periodSummary.experimentCount === 1 ? 'experiment' : 'experiments'}`}</span>+ <div className="flex flex-col gap-1">+ <OfflineScoreSummaryDisplay summary={periodSummary} />+ <div className="text-muted text-xs">{`${periodSummary.experimentCount} ${periodSummary.experimentCount === 1 ? 'experiment' : 'experiments'} (${scoredItemCount} ${scoredItemCount === 1 ? 'item' : 'items'})`}</div></div>)}{hasPartialHistory && (@@ -106,6 +112,7 @@ export function OfflineOverviewTrend({versionPoints.length ? (<OfflineScoreTrendChartheightClassName="h-36"+ showHeading={false}hoverLogic={overviewLogic}xDomain={props.xDomain}colorOffset={props.colorOffset}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.stories.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.stories.tsxnew file mode 100644index 000000000000..3402abc7bf56--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.stories.tsx@@ -0,0 +1,55 @@+import type { Meta, StoryObj } from '@storybook/react'++import { detailItems, offlineDetailItemResults } from './offlineDetailFixtures'+import { OfflineResultTag } from './OfflineResultTag'++const result = offlineDetailItemResults(detailItems[0].id)[0]+const meta: Meta<typeof OfflineResultTag> = {+ title: 'AI observability/Offline experiments/Result tag',+ component: OfflineResultTag,+ parameters: { layout: 'padded' },+ args: { result, scorer: result.scorer },+}+export default meta+type Story = StoryObj<typeof OfflineResultTag>++export const NumericFailure: Story = {}+export const NumericPass: Story = { args: { result: { ...result, value: 0.9 } } }+export const BooleanDetector: Story = {+ args: {+ result: { ...result, value: true },+ scorer: { ...result.scorer, kind: 'boolean', config: { true_is_failure: true } },+ },+}+export const UnconfiguredBoolean: Story = {+ args: {+ result: { ...result, value: true },+ scorer: { ...result.scorer, kind: 'boolean', config: {} },+ },+}+export const Skipped: Story = { args: { result: { ...result, status: 'skipped', value: null } } }+export const Error: Story = { args: { result: { ...result, status: 'error', value: null } } }++export const NearThreshold: Story = {+ args: {+ result: { ...result, value: 0.9999999 },+ scorer: { ...result.scorer, kind: 'numeric', config: { passing_rule: { operator: 'gte', threshold: 1 } } },+ },+}+export const CategoricalMixed: Story = {+ args: {+ result: { ...result, value: ['good', 'bad'] },+ scorer: {+ ...result.scorer,+ kind: 'categorical',+ config: {+ options: [+ { key: 'good', label: 'Good' },+ { key: 'bad', label: 'Bad' },+ ],+ selection_mode: 'multiple',+ passing_rule: { categories: ['good'] },+ },+ },+ },+}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.test.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.test.tsxnew file mode 100644index 000000000000..b9bfd67c0f18--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.test.tsx@@ -0,0 +1,49 @@+import '@testing-library/jest-dom'++import { cleanup, render, screen } from '@testing-library/react'++import { detailItems, offlineDetailItemResults } from './offlineDetailFixtures'+import { OfflineResultTag } from './OfflineResultTag'++describe('OfflineResultTag', () => {+ afterEach(cleanup)++ it.each([+ [0.9999999, 'gte', '0.9999999', 'Fail'],+ [1.0000001, 'lte', '1.0000001', 'Fail'],+ [1.23456789, 'gte', '1.23457', 'Pass'],+ ] as const)('shows an accurate verdict and exact tooltip for %s with %s', (value, operator, label, verdict) => {+ const result = offlineDetailItemResults(detailItems[0].id)[0]+ render(+ <OfflineResultTag+ result={{ ...result, status: 'ok', value }}+ scorer={{ ...result.scorer, kind: 'numeric', config: { passing_rule: { operator, threshold: 1 } } }}+ />+ )+ expect(screen.getByText(label)).toBeInTheDocument()+ expect(screen.getByTitle(`${verdict}: ${value}`)).toHaveClass(+ `LemonTag--${verdict === 'Pass' ? 'success' : 'danger'}`+ )+ })++ it.each([+ ['ok', 'Fail: Detected', 'Detected', 'danger'],+ ['error', 'Error', 'Error', 'danger'],+ ['skipped', 'Skipped', 'Skipped', 'muted'],+ ['not_applicable', 'Not applicable', 'Not applicable', 'muted'],+ ] as const)('keeps a %s result distinct from the boolean verdict', (status, title, label, type) => {+ const result = offlineDetailItemResults(detailItems[0].id)[0]+ render(+ <OfflineResultTag+ result={{ ...result, status, value: true }}+ scorer={{+ ...result.scorer,+ kind: 'boolean',+ config: { true_label: 'Detected', true_is_failure: true },+ }}+ />+ )+ expect(screen.getByText(label)).toBeInTheDocument()+ expect(screen.getByTitle(title)).toHaveClass(`LemonTag--${type}`)+ })+})diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.tsxnew file mode 100644index 000000000000..4acb7d8fb604--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/OfflineResultTag.tsx@@ -0,0 +1,33 @@+import { IconCheck, IconMinus, IconWarning, IconX } from '@posthog/icons'+import { LemonTag } from '@posthog/lemon-ui'++import type { OfflineResultCellApi, OfflineResultReadApi, OfflineScorerVersionReadApi } from '../generated/api.schemas'+import { offlineResultLabel } from './offlineResultPresentation'+import { offlineScorePasses } from './offlineScoreInterpretation'++export function OfflineResultTag({+ result,+ scorer,+}: {+ result: OfflineResultCellApi | OfflineResultReadApi+ scorer: OfflineScorerVersionReadApi+}): JSX.Element {+ const passed = result.status === 'ok' ? offlineScorePasses(result.value, scorer) : null+ const error = result.status === 'error'+ const label = offlineResultLabel(result, scorer)+ const fullLabel = result.status === 'ok' && typeof result.value === 'number' ? String(result.value) : label+ return (+ <LemonTag+ type={error || passed === false ? 'danger' : passed === true ? 'success' : 'muted'}+ icon={+ error ? <IconWarning /> : passed === true ? <IconCheck /> : passed === false ? <IconX /> : <IconMinus />+ }+ title={passed === null ? fullLabel : `${passed ? 'Pass' : 'Fail'}: ${fullLabel}`}+ className="max-w-full"+ >+ <span className="truncate" translate="no">+ {label}+ </span>+ </LemonTag>+ )+}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.stories.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.stories.tsxnew file mode 100644index 000000000000..be6c2d6cb453--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.stories.tsx@@ -0,0 +1,64 @@+import type { Meta, StoryObj } from '@storybook/react'++import { detailSummaries } from './offlineDetailFixtures'+import { OfflineScoreSummaryDisplay } from './OfflineScoreSummaryDisplay'++const meta: Meta<typeof OfflineScoreSummaryDisplay> = {+ title: 'AI observability/Offline experiments/Score summary',+ component: OfflineScoreSummaryDisplay,+ parameters: { layout: 'padded' },+ args: { summary: detailSummaries[0] },+}+export default meta+type Story = StoryObj<typeof OfflineScoreSummaryDisplay>++export const Numeric: Story = {}+export const Boolean: Story = { args: { summary: detailSummaries[1] } }+export const Unconfigured: Story = {+ args: {+ summary: {+ ...detailSummaries[0],+ scorer: { ...detailSummaries[0].scorer, config: {} },+ pass_count: null,+ fail_count: null,+ pass_rate: null,+ },+ },+}++export const NearThreshold: Story = {+ args: {+ summary: {+ ...detailSummaries[0],+ mean: 0.9999999,+ scorer: { ...detailSummaries[0].scorer, config: { passing_rule: { operator: 'gte', threshold: 1 } } },+ },+ },+}+export const Categorical: Story = {+ args: {+ summary: {+ ...detailSummaries[0],+ mean: null,+ scorer: {+ ...detailSummaries[0].scorer,+ kind: 'categorical',+ config: {+ options: [+ { key: 'good', label: 'Good' },+ { key: 'bad', label: 'Bad' },+ ],+ passing_rule: { categories: ['good'] },+ },+ },+ categories: [+ { key: 'good', label: 'Good', count: 3, rate: 0.75 },+ { key: 'bad', label: 'Bad', count: 1, rate: 0.25 },+ ],+ pass_count: 3,+ fail_count: 1,+ pass_rate: 0.75,+ status_counts: { ok: 4 },+ },+ },+}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.tsxnew file mode 100644index 000000000000..5b63b44f2c99--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScoreSummaryDisplay.tsx@@ -0,0 +1,59 @@+import { IconCheck, IconX } from '@posthog/icons'+import { LemonTag, Tooltip } from '@posthog/lemon-ui'++import { offlineScorePasses } from './offlineScoreInterpretation'+import {+ formatOfflinePercentage,+ formatOfflineScore,+ offlineScoreMetricLabel,+ type OfflineScoreSummary,+} from './offlineScoreTrends'++export function OfflineScoreSummaryDisplay({ summary }: { summary: OfflineScoreSummary }): JSX.Element {+ const meanPassed = summary.scorer.kind === 'numeric' ? offlineScorePasses(summary.mean, summary.scorer) : null+ const score = formatOfflineScore(summary)+ const fullScore = summary.scorer.kind === 'numeric' && summary.mean !== null ? String(summary.mean) : score+ return (+ <div className="min-w-0 flex flex-col gap-1">+ <div className="flex flex-wrap items-baseline gap-1">+ {meanPassed === null ? (+ <Tooltip title={fullScore}>+ <strong className="min-w-0 max-w-full truncate tabular-nums" translate="no">+ {score}+ </strong>+ </Tooltip>+ ) : (+ <Tooltip+ title={`${fullScore}: ${meanPassed ? 'Mean meets the passing rule' : 'Mean does not meet the passing rule'}`}+ >+ <LemonTag+ type={meanPassed ? 'success' : 'danger'}+ icon={meanPassed ? <IconCheck /> : <IconX />}+ className="max-w-full"+ >+ <span className="truncate" translate="no">+ {score}+ </span>+ </LemonTag>+ </Tooltip>+ )}+ <span className="text-xs text-muted">{offlineScoreMetricLabel(summary.scorer)}</span>+ </div>+ {summary.pass_count != null && summary.fail_count != null && (+ <div className="flex flex-wrap items-center gap-x-2 gap-y-1 text-xs tabular-nums">+ {summary.scorer.kind !== 'boolean' && summary.pass_rate != null && (+ <span>{`${formatOfflinePercentage(summary.pass_rate)} pass rate`}</span>+ )}+ <span className="text-success flex items-center gap-0.5">+ <IconCheck />+ <span>{`${summary.pass_count} passed`}</span>+ </span>+ <span className="text-danger flex items-center gap-0.5">+ <IconX />+ <span>{`${summary.fail_count} failed`}</span>+ </span>+ </div>+ )}+ </div>+ )+}diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.stories.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.stories.tsxindex 3abc2484e8e7..8a0fb7c3cfa6 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.stories.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.stories.tsx@@ -23,6 +23,86 @@ const meta: Meta<typeof OfflineScoreTrendChart> = {export default metatype Story = StoryObj<typeof OfflineScoreTrendChart>export const Numeric: Story = {}+export const NumericPassingRule: Story = {+ args: {+ periods: [+ {+ ...meta.args!.periods![0],+ points: OFFLINE_STORY_POINTS.map((point, index) => ({+ ...point,+ summary: {+ ...point.summary,+ scorer: {+ ...point.summary.scorer,+ config: { min: 0, max: 5, passing_rule: { operator: 'gte', threshold: 4 } },+ },+ pass_count: 60 + index,+ fail_count: 32 - index,+ pass_rate: (60 + index) / 92,+ },+ })),+ },+ ],+ },+}+export const LowerIsBetter: Story = {+ args: {+ periods: [+ {+ ...NumericPassingRule.args!.periods![0],+ points: NumericPassingRule.args!.periods![0].points.map((point) => ({+ ...point,+ summary: {+ ...point.summary,+ scorer: {+ ...point.summary.scorer,+ name: 'Response time',+ config: { min: 0, max: 5, passing_rule: { operator: 'lte', threshold: 3.5 } },+ },+ },+ })),+ },+ ],+ },+}+export const BooleanDetector: Story = {+ args: {+ periods: [+ {+ ...meta.args!.periods![0],+ points: OFFLINE_STORY_POINTS.map((point, index) => ({+ ...point,+ summary: {+ ...point.summary,+ scorer: {+ ...point.summary.scorer,+ name: 'Hallucination detected',+ kind: 'boolean',+ config: { true_is_failure: true },+ },+ mean: null,+ true_count: 12 - index,+ false_count: 80 + index,+ true_rate: (12 - index) / 92,+ pass_count: 80 + index,+ fail_count: 12 - index,+ pass_rate: (80 + index) / 92,+ },+ })),+ },+ ],+ },+}+export const NarrowPassingRule: Story = {+ ...NumericPassingRule,+ decorators: [+ (Story) => (+ <div className="w-[520px]">+ <Story />+ </div>+ ),+ ],+}export const Narrow: Story = {decorators: [(Story) => (diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.tsxindex 4287e3446eaa..83fa050eb874 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScoreTrendChart.tsx@@ -1,7 +1,7 @@import type { BuiltLogic } from 'kea'import { useMemo } from 'react'-import { ScatterChart, TooltipFooter, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'+import { ReferenceLine, ScatterChart, TooltipFooter, TooltipSurface, TooltipSwatch } from '@posthog/quill-charts'import { useChartTheme } from 'lib/charts/hooks'import { dayjs } from 'lib/dayjs'@@ -12,7 +12,13 @@ import type { offlineExperimentsLogicType } from './offlineExperimentsLogic'import { createOfflineScoreTrendTickFormatter } from './offlineScoreTrendAxis'import { OfflineScoreTrendCrosshair } from './OfflineScoreTrendCrosshair'import { OfflineScoreTrendLines } from './OfflineScoreTrendLines'-import { buildOfflineTrendPanels, formatOfflineNumericScore, type OfflineTrendPeriod } from './offlineScoreTrends'+import {+ buildOfflineTrendPanels,+ formatOfflineNumericScore,+ formatOfflinePercentage,+ offlineScorePassingRuleLabel,+ type OfflineTrendPeriod,+} from './offlineScoreTrends'export interface OfflineScoreTrendChartProps {periods: OfflineTrendPeriod[]@@ -22,6 +28,7 @@ export interface OfflineScoreTrendChartProps {colorOffset?: numberhoverLogic?: BuiltLogic<offlineExperimentsLogicType>xDomain?: [number, number]+ showHeading?: boolean}export function OfflineScoreTrendChart({@@ -32,6 +39,7 @@ export function OfflineScoreTrendChart({colorOffset = 0,hoverLogic,xDomain,+ showHeading = true,}: OfflineScoreTrendChartProps): JSX.Element {const baseTheme = useChartTheme()const theme = useMemo(@@ -64,7 +72,14 @@ export function OfflineScoreTrendChart({<div className="space-y-4 min-w-0">{panels.map((panel) => (<div key={panel.key} className="min-w-0">- <div className="text-xs text-muted mb-2">{panel.label}</div>+ {showHeading && (+ <div className="text-xs text-muted mb-2 flex flex-wrap gap-x-2 gap-y-1">+ <span>{panel.label}</span>+ {panel.passingRule && (+ <span>{`Score passes ${panel.passingRule.operator === 'gte' ? 'at or above' : 'at or below'} ${panel.passingRule.threshold}`}</span>+ )}+ </div>+ )}{panel.series.some((series) => series.points.length > 0) ? (<div className={cn(heightClassName, 'min-w-0 flex flex-col')}><ScatterChart@@ -81,7 +96,7 @@ export function OfflineScoreTrendChart({domain: panel.yDomain,tickFormatter: (value) =>panel.percentage- ? `${(value * 100).toFixed(0)}%`+ ? formatOfflinePercentage(value): formatOfflineNumericScore(value),},legend: { show: true },@@ -109,11 +124,25 @@ export function OfflineScoreTrendChart({<span className="opacity-70">{meta.metric}</span><strong className="text-lg tabular-nums">{meta.percentage- ? `${formatOfflineNumericScore(point.y * 100)}%`- : formatOfflineNumericScore(point.y)}+ ? formatOfflinePercentage(point.y)+ : String(point.y)}</strong></div>{periods.length > 1 && <div className="opacity-70">{meta.period}</div>}+ {offlineScorePassingRuleLabel(summary.scorer) && (+ <div className="opacity-70 mt-1">+ {offlineScorePassingRuleLabel(summary.scorer)}+ </div>+ )}+ {summary.pass_count != null && summary.fail_count != null && (+ <div className="mt-1">+ {summary.pass_rate != null &&+ summary.scorer.kind !== 'boolean' && (+ <div>{`${formatOfflinePercentage(summary.pass_rate)} pass rate`}</div>+ )}+ <div>{`${summary.pass_count} passed · ${summary.fail_count} failed`}</div>+ </div>+ )}</div><div className="mt-2 pt-2 border-t border-current/25"><div className="font-medium mb-1">Result coverage</div>@@ -158,6 +187,31 @@ export function OfflineScoreTrendChart({)}}>+ {panel.passingRule && (+ <>+ <ReferenceLine+ value={panel.passingRule.threshold}+ fillSide={panel.passingRule.operator === 'gte' ? 'below' : 'above'}+ style={{+ width: 0,+ fillColor: 'var(--color-text-error)',+ fillOpacity: 0.035,+ }}+ showValueOnHover={false}+ />+ <ReferenceLine+ value={panel.passingRule.threshold}+ label={`${panel.passingRule.operator === 'gte' ? '≥' : '≤'} ${panel.passingRule.threshold}`}+ fillSide={panel.passingRule.operator === 'gte' ? 'above' : 'below'}+ style={{+ color: 'var(--color-text-success)',+ width: 1,+ fillOpacity: 0.035,+ }}+ showValueOnHover={false}+ />+ </>+ )}<OfflineScoreTrendLines />{hoverLogic && panel.xDomain && (<OfflineScoreTrendCrosshair logic={hoverLogic} xDomain={panel.xDomain} />diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistory.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistory.tsxindex 46d9ee217c69..74b05aaabbb3 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistory.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistory.tsx@@ -4,14 +4,16 @@ import { useState } from 'react'import { LemonBanner, LemonButton, LemonCard, LemonLabel, LemonSelect, LemonTag, Spinner } from '@posthog/lemon-ui'+import { AccessControlAction } from 'lib/components/AccessControlAction'import { DateFilter } from 'lib/components/DateFilter/DateFilter'import { TZLabel } from 'lib/components/TZLabel'+import { urls } from 'scenes/urls'import { SceneContent } from '~/layout/scenes/components/SceneContent'import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { AccessControlLevel, AccessControlResourceType } from '~/types'import { EvaluationsTabs } from '../evaluations/EvaluationsTabs'-import { ScoreDefinitionVersionButton } from '../scoreDefinitions/ScoreDefinitionVersionButton'import { offlineExperimentUrl } from './offlineExperimentPresentation'import { offlineScorerHistoryLogic, type OfflineScorerHistoryProps } from './offlineScorerHistoryLogic'import { OfflineScorerHistoryTable } from './OfflineScorerHistoryTable'@@ -54,7 +56,6 @@ export function OfflineScorerHistory(props: OfflineScorerHistoryProps): JSX.ElemchangePage,loadOfflineHistoryPrimaryPage,loadOfflineHistoryComparisonPage,- reloadOfflineHistoryDefinition,} = useActions(logic)const toggleRun = (key: string): void => {@@ -92,10 +93,18 @@ export function OfflineScorerHistory(props: OfflineScorerHistoryProps): JSX.Elem{definition.archived && <LemonTag type="warning">Archived</LemonTag>}<span className="text-muted">{definition.description}</span></div>- <ScoreDefinitionVersionButton- definition={definition}- onSuccess={reloadOfflineHistoryDefinition}- />+ <AccessControlAction+ resourceType={AccessControlResourceType.LlmAnalytics}+ minAccessLevel={AccessControlLevel.Editor}+ >+ <LemonButton+ size="small"+ to={urls.aiObservabilityScorer(definition.id)}+ data-attr="offline-history-edit-scorer"+ >+ Edit scorer+ </LemonButton>+ </AccessControlAction></div><div className="flex flex-wrap gap-2 items-end"><div>diff --git a/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistoryTable.tsx b/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistoryTable.tsxindex d87fbb2b59af..6e428d31c67b 100644--- a/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistoryTable.tsx+++ b/products/ai_observability/frontend/offline-evaluations/OfflineScorerHistoryTable.tsx@@ -6,7 +6,7 @@ import { TZLabel } from 'lib/components/TZLabel'import type { OfflineHistoryPageApi, OfflineHistoryPointApi } from '../generated/api.schemas'import { offlineExperimentUrl } from './offlineExperimentPresentation'import { OfflineScorerHistoryRunDetails } from './OfflineScorerHistoryRunDetails'-import { formatOfflineScore } from './offlineScoreTrends'+import { OfflineScoreSummaryDisplay } from './OfflineScoreSummaryDisplay'export function OfflineScorerHistoryTable({periodKey,@@ -72,11 +72,7 @@ export function OfflineScorerHistoryTable({title: 'Score',key: 'score',width: '16%',- render: (_, point) => (- <Tooltip title={formatOfflineScore(point.summary)}>- <span className="block tabular-nums truncate">{formatOfflineScore(point.summary)}</span>- </Tooltip>- ),+ render: (_, point) => <OfflineScoreSummaryDisplay summary={point.summary} />,},{title: 'Coverage',diff --git a/products/ai_observability/frontend/offline-evaluations/offlineDetailFixtures.ts b/products/ai_observability/frontend/offline-evaluations/offlineDetailFixtures.tsindex d2d364ed64cd..7cd07e61d5b1 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineDetailFixtures.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineDetailFixtures.ts@@ -26,6 +26,9 @@ export function makeOfflineDetailSummaries(count: number): OfflineScorerSummaryAobserved_item_count: 8,result_count: 8,status_counts: { ok: 7, error: 1, skipped: 0, not_applicable: 0 },+ pass_count: 5,+ fail_count: 2,+ pass_rate: 5 / 7,missing_result_count: 0,scorer: {...base.scorer,@@ -77,7 +80,9 @@ export function makeOfflineDetailCells(itemIds: string[], versionIds: string[]):? null: scorer.kind === 'boolean'? itemIndex % 3 !== 0- : 0.7 + itemIndex / 100,+ : 'max' in scorer.config && scorer.config.max! > 1+ ? 1400 + itemIndex * 150+ : 0.65 + itemIndex * 0.05,error_code: itemIndex === 3 && scorer.id === detailSummaries[0].scorer.id ? 'evaluator_timeout' : null,evaluator_trace_id: null,evaluated_at: null,diff --git a/products/ai_observability/frontend/offline-evaluations/offlineOverviewFixtures.ts b/products/ai_observability/frontend/offline-evaluations/offlineOverviewFixtures.tsindex 2dc32abe1e7e..c6f9962c2c15 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineOverviewFixtures.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineOverviewFixtures.ts@@ -11,8 +11,12 @@ export const overviewScorers: ScoreDefinitionApi[] = ['Answer quality', 'Groundecurrent_version_id: `22222222-2222-4222-8222-${String(index + 1).padStart(12, '0')}`,config:index === 1- ? { true_label: 'Grounded', false_label: 'Ungrounded' }- : { min: 0, max: index === 2 ? 5000 : 1 },+ ? { true_label: 'Grounded', false_label: 'Ungrounded', true_is_failure: false }+ : {+ min: 0,+ max: index === 2 ? 5000 : 1,+ passing_rule: { operator: index === 2 ? 'lte' : 'gte', threshold: index === 2 ? 1800 : 0.8 },+ },created_by: null,created_at: '2026-09-01T12:00:00Z',updated_at: '2026-09-20T12:00:00Z',@@ -79,6 +83,9 @@ export function overviewHistory(scorer: ScoreDefinitionApi): OfflineHistoryPointtrue_count: scorer.kind === 'boolean' ? 90 - index : null,false_count: scorer.kind === 'boolean' ? 5 + index : null,true_rate: scorer.kind === 'boolean' ? (90 - index) / 95 : null,+ pass_count: scorer.kind === 'boolean' ? 90 - index : 65 + index * 5,+ fail_count: scorer.kind === 'boolean' ? 5 + index : 30 - index * 5,+ pass_rate: (scorer.kind === 'boolean' ? 90 - index : 65 + index * 5) / 95,categories: [],},}))diff --git a/products/ai_observability/frontend/offline-evaluations/offlineResultPresentation.ts b/products/ai_observability/frontend/offline-evaluations/offlineResultPresentation.tsindex 50235b7ef39b..bdc3b3d9526c 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineResultPresentation.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineResultPresentation.ts@@ -7,6 +7,7 @@ import type {OfflineScorerVersionReadApi,} from '../generated/api.schemas'import { getBooleanConfig, getCategoricalConfig } from '../scoreDefinitions/scoreDefinitionConfigUtils'+import { offlineNumericPassingRule } from './offlineScoreInterpretation'import { formatOfflineNumericScore } from './offlineScoreTrends'export function offlineResultLabel(@@ -17,7 +18,7 @@ export function offlineResultLabel(return { error: 'Error', skipped: 'Skipped', not_applicable: 'Not applicable' }[result.status]}if (typeof result.value === 'number') {- return formatOfflineNumericScore(result.value)+ return formatOfflineNumericScore(result.value, offlineNumericPassingRule(scorer))}if (typeof result.value === 'boolean') {const config = getBooleanConfig(scorer.config)diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.test.tsnew file mode 100644index 000000000000..285936a88e1e--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.test.ts@@ -0,0 +1,41 @@+import { offlineScorePasses } from './offlineScoreInterpretation'++describe('offline score interpretation', () => {+ it.each<[Parameters<typeof offlineScorePasses>[1], unknown, boolean | null]>([+ [{ kind: 'boolean', config: {} }, true, true],+ [{ kind: 'boolean', config: { true_is_failure: null } }, false, false],+ [{ kind: 'boolean', config: { true_is_failure: false } }, true, true],+ [{ kind: 'boolean', config: { true_is_failure: false } }, false, false],+ [{ kind: 'boolean', config: { true_is_failure: true } }, true, false],+ [{ kind: 'boolean', config: { true_is_failure: true } }, false, true],+ [{ kind: 'boolean', config: { true_is_failure: false } }, 1, null],+ [{ kind: 'numeric', config: {} }, 1, null],+ [{ kind: 'categorical', config: { options: [] } }, ['good'], null],+ [+ { kind: 'categorical', config: { options: [], passing_rule: { categories: ['good', 'clear'] } } },+ ['good'],+ true,+ ],+ [+ { kind: 'categorical', config: { options: [], passing_rule: { categories: ['good', 'clear'] } } },+ ['good', 'clear'],+ true,+ ],+ [+ { kind: 'categorical', config: { options: [], passing_rule: { categories: ['good'] } } },+ ['good', 'bad'],+ false,+ ],+ [{ kind: 'categorical', config: { options: [], passing_rule: { categories: [] } } }, ['good'], false],++ [{ kind: 'numeric', config: { passing_rule: { operator: 'gte', threshold: 0 } } }, 0, true],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'gte', threshold: 0 } } }, -1, false],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: 0 } } }, 0, true],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: 0 } } }, 1, false],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: 0 } } }, null, null],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: 0 } } }, NaN, null],+ [{ kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: Infinity } } }, 1, null],+ ])('interprets %j and value %p as %p', (scorer, value, expected) => {+ expect(offlineScorePasses(value, scorer)).toBe(expected)+ })+})diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.ts b/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.tsnew file mode 100644index 000000000000..6b18334df3ae--- /dev/null+++ b/products/ai_observability/frontend/offline-evaluations/offlineScoreInterpretation.ts@@ -0,0 +1,51 @@+import type { OfflineScorerVersionReadApi, NumericScoreDefinitionConfigApi } from '../generated/api.schemas'+import {+ getBooleanConfig,+ getCategoricalConfig,+ getNumericConfig,+} from '../scoreDefinitions/scoreDefinitionConfigUtils'++type OfflineScorerConfig = Pick<OfflineScorerVersionReadApi, 'kind' | 'config'>++export function offlineBooleanPolarity(scorer: OfflineScorerConfig): boolean | null {+ return scorer.kind === 'boolean' ? getBooleanConfig(scorer.config).true_is_failure === true : null+}++export function offlineNumericPassingRule(+ scorer: OfflineScorerConfig+): NumericScoreDefinitionConfigApi['passing_rule'] | null {+ const rule = scorer.kind === 'numeric' ? getNumericConfig(scorer.config).passing_rule : null+ return rule && Number.isFinite(rule.threshold) && (rule.operator === 'gte' || rule.operator === 'lte') ? rule : null+}++export function offlineScoreHasPassingRule(scorer: OfflineScorerConfig): boolean {+ return (+ offlineBooleanPolarity(scorer) !== null ||+ offlineNumericPassingRule(scorer) !== null ||+ offlineCategoricalPassingRule(scorer) !== null+ )+}++export function offlineCategoricalPassingRule(scorer: OfflineScorerConfig): string[] | null {+ return scorer.kind === 'categorical' ? (getCategoricalConfig(scorer.config).passing_rule?.categories ?? null) : null+}++export function offlineScorePasses(value: unknown, scorer: OfflineScorerConfig): boolean | null {+ if (scorer.kind === 'boolean' && typeof value === 'boolean') {+ const polarity = offlineBooleanPolarity(scorer)+ return polarity === null ? null : value !== polarity+ }+ if (scorer.kind === 'numeric' && typeof value === 'number' && Number.isFinite(value)) {+ const rule = offlineNumericPassingRule(scorer)+ return rule ? (rule.operator === 'gte' ? value >= rule.threshold : value <= rule.threshold) : null+ }+ if (scorer.kind === 'categorical' && Array.isArray(value)) {+ const categories = offlineCategoricalPassingRule(scorer)+ return categories === null+ ? null+ : value.length === 0+ ? categories.length === 0+ : value.every((key) => categories.includes(key))+ }+ return null+}diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.fixtures.ts b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.fixtures.tsindex 3e1462f6392e..5f0fa6ed912c 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.fixtures.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.fixtures.ts@@ -75,6 +75,9 @@ export function makeOfflineHistoryPoint(index: number, mean: number | null = 4.2true_count: null,false_count: null,true_rate: null,+ pass_count: null,+ fail_count: null,+ pass_rate: null,categories: [],},}diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.test.ts b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.test.tsindex b62828a0147e..9e7a175989f5 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.test.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.test.ts@@ -5,10 +5,23 @@ import {formatOfflineScore,previousOfflinePeriod,resolveOfflineDateRange,+ offlineScoreMetricLabel,} from './offlineScoreTrends'import { makeOfflineHistoryPoint } from './offlineScoreTrends.fixtures'describe('offline score trends', () => {+ it.each([+ ['gte', 0.9999999, 1, '0.9999999'],+ ['lte', 1.0000001, 1, '1.0000001'],+ ['gte', 1.0000001, 1.0000001, '1.0000001'],+ ['lte', -0.9999999, -1, '-0.9999999'],+ ['gte', 1.23456789, 1, '1.23457'],+ ] as const)('keeps the displayed mean consistent with %s for %s at %s', (operator, value, threshold, label) => {+ const point = makeOfflineHistoryPoint(1, value)+ point.summary.scorer.config = { passing_rule: { operator, threshold } }+ expect(formatOfflineScore(point.summary)).toBe(label)+ })+it.each([{label: 'unequal weights and unsuccessful experiments',@@ -57,16 +70,69 @@ describe('offline score trends', () => {point.summary.true_count = index === 0 ? 0 : 6point.summary.false_count = 2point.summary.true_rate = index === 0 ? 0 : 0.75+ point.summary.pass_count = point.summary.true_count+ point.summary.fail_count = point.summary.false_count+ point.summary.pass_rate = point.summary.true_rate}const summary = aggregateOfflineScoreHistory(points)!expect(summary.true_rate).toBe(0.6)+ expect(summary.pass_rate).toBe(0.6)expect(summary.status_counts.ok).toBe(10)expect(formatOfflineScore(summary)).toBe('60%')})- it('aggregates category counts by key while preserving unselected options and multiple-selection rates', () => {+ it.each([false, true])('plots and aggregates actual boolean pass counts for polarity %s', (trueIsFailure) => {+ const points = [makeOfflineHistoryPoint(1), makeOfflineHistoryPoint(2)]+ for (const [index, point] of points.entries()) {+ point.summary.scorer = {+ ...point.summary.scorer,+ kind: 'boolean',+ config: { true_is_failure: trueIsFailure },+ }+ point.summary.status_counts = { ok: index === 0 ? 2 : 8, error: 5, skipped: 1, not_applicable: 1 }+ point.summary.true_count = index === 0 ? 0 : 6+ point.summary.false_count = 2+ point.summary.true_rate = index === 0 ? 0 : 0.75+ point.summary.pass_count = trueIsFailure ? 2 : point.summary.true_count+ point.summary.fail_count = trueIsFailure ? point.summary.true_count : 2+ point.summary.pass_rate = point.summary.pass_count / point.summary.status_counts.ok+ }+ const summary = aggregateOfflineScoreHistory(points)!+ expect(summary.pass_count).toBe(trueIsFailure ? 4 : 6)+ expect(summary.fail_count).toBe(trueIsFailure ? 6 : 4)+ expect(summary.pass_rate).toBe(trueIsFailure ? 0.4 : 0.6)+ expect(summary.true_rate).toBe(0.6)+ expect(formatOfflineScore(summary)).toBe(trueIsFailure ? '40%' : '60%')+ expect(offlineScoreMetricLabel(summary.scorer)).toBe('Pass rate')+ const [panel] = buildOfflineTrendPanels([{ key: 'current', label: 'Current', points }])+ expect(panel.series[0].points.map((point) => point.y)).toEqual(trueIsFailure ? [1, 0.25] : [0, 0.75])+ })++ it('keeps version thresholds separate and includes off-scale thresholds without treating mean as pass rate', () => {+ const points = [makeOfflineHistoryPoint(1, 4), makeOfflineHistoryPoint(2, 4)]+ for (const [index, point] of points.entries()) {+ point.summary.scorer = {+ ...point.summary.scorer,+ id: `version-${index}`,+ config: { min: 0, max: 5, passing_rule: { operator: index === 0 ? 'gte' : 'lte', threshold: 1 } },+ }+ point.summary.pass_count = 23+ point.summary.fail_count = 69+ point.summary.pass_rate = 0.25+ }+ const panels = buildOfflineTrendPanels([{ key: 'current', label: 'Current', points }])+ expect(panels).toHaveLength(2)+ expect(panels.map((panel) => panel.passingRule?.operator)).toEqual(['gte', 'lte'])+ expect(panels.every((panel) => panel.yDomain![0] < 1 && panel.yDomain![1] > 4)).toBe(true)+ expect(panels.map((panel) => panel.series[0].points[0].y)).toEqual([4, 4])+ const summary = aggregateOfflineScoreHistory([points[0]])!+ expect(formatOfflineScore(summary)).toBe('4')+ expect(summary.pass_rate).toBe(0.25)+ })++ it.each([false, true])('aggregates category counts and passing rules (graded: %s)', (graded) => {const points = [makeOfflineHistoryPoint(1), makeOfflineHistoryPoint(2)]for (const [index, point] of points.entries()) {point.summary.scorer = {@@ -74,6 +140,7 @@ describe('offline score trends', () => {kind: 'categorical',config: {selection_mode: 'multiple',+ ...(graded ? { passing_rule: { categories: ['complete'] } } : {}),options: [{ key: 'complete', label: 'Complete' },{ key: 'clear', label: 'Clear' },@@ -89,10 +156,19 @@ describe('offline score trends', () => {{ key: 'other', label: 'Other', count: 0, rate: 0 },]}+ if (graded) {+ points[0].summary.pass_count = 0+ points[0].summary.fail_count = 2+ points[1].summary.pass_count = 4+ points[1].summary.fail_count = 4+ }points[1].summary.categories.reverse()const summary = aggregateOfflineScoreHistory(points)!+ expect([summary.pass_count, summary.fail_count, summary.pass_rate]).toEqual(+ graded ? [4, 6, 0.4] : [null, null, null]+ )expect(summary.categories).toEqual([{ key: 'complete', label: 'Complete', count: 10, rate: 1 },{ key: 'clear', label: 'Clear', count: 6, rate: 0.6 },@@ -135,6 +211,9 @@ describe('offline score trends', () => {}point.summary.mean = nullpoint.summary.true_rate = 0+ point.summary.pass_count = kind === 'boolean' ? 0 : null+ point.summary.fail_count = kind === 'boolean' ? point.summary.status_counts.ok : null+ point.summary.pass_rate = kind === 'boolean' ? 0 : nullpoint.summary.categories = [{ key: 'clear', label: 'Clear', count: 69, rate: 0.75 },{ key: 'complete', label: 'Complete', count: 69, rate: 0.75 },diff --git a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.ts b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.tsindex 2c66fa3c0fc0..293ff5652cc9 100644--- a/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.ts+++ b/products/ai_observability/frontend/offline-evaluations/offlineScoreTrends.ts@@ -9,6 +9,12 @@ import type {OfflineScorerSummaryApi,OfflineScorerVersionReadApi,} from '../generated/api.schemas'+import {+ offlineBooleanPolarity,+ offlineCategoricalPassingRule,+ offlineNumericPassingRule,+ offlineScoreHasPassingRule,+} from './offlineScoreInterpretation'export interface OfflineDateRange {dateFrom?: string@@ -38,9 +44,13 @@ export interface OfflineTrendPanel {elapsed: booleanxDomain?: [number, number]yDomain?: [number, number]+ passingRule: ReturnType<typeof offlineNumericPassingRule>}-export type OfflineScoreSummary = Pick<OfflineScorerSummaryApi, 'scorer' | 'mean' | 'true_rate' | 'categories'> & {+export type OfflineScoreSummary = Pick<+ OfflineScorerSummaryApi,+ 'scorer' | 'mean' | 'true_rate' | 'categories' | 'pass_count' | 'fail_count' | 'pass_rate'+> & {status_counts: Pick<OfflineScorerSummaryApi['status_counts'], 'ok'>}@@ -100,7 +110,7 @@ export function offlineScoreMetricLabel(scorer: OfflineScorerVersionReadApi): streturn 'Mean score'}if (scorer.kind === 'boolean') {- return `${'true_label' in scorer.config ? scorer.config.true_label || 'True' : 'True'} rate`+ return 'Pass rate'}return 'Category rates'}@@ -125,10 +135,18 @@ export function aggregateOfflineScoreHistory(points: OfflineHistoryPointApi[]):}const successful = points.map(({ summary }) => summary).filter((summary) => summary.status_counts.ok > 0)const count = successful.reduce((total, summary) => total + summary.status_counts.ok, 0)+ const graded = offlineScoreHasPassingRule(first.scorer)+ ? successful.filter((summary) => summary.pass_count != null && summary.fail_count != null)+ : []+ const passCount = graded.reduce((total, summary) => total + (summary.pass_count ?? 0), 0)+ const failCount = graded.reduce((total, summary) => total + (summary.fail_count ?? 0), 0)return {scorer: first.scorer,experimentCount: new Set(points.map(({ experiment }) => experiment.id)).size,status_counts: { ok: count },+ pass_count: offlineScoreHasPassingRule(first.scorer) ? passCount : null,+ fail_count: offlineScoreHasPassingRule(first.scorer) ? failCount : null,+ pass_rate: passCount + failCount > 0 ? passCount / (passCount + failCount) : null,mean: first.scorer.kind === 'numeric' && count > 0 ? weightedOfflineNumericMean(successful, count) : null,true_rate:first.scorer.kind === 'boolean' && count > 0@@ -149,36 +167,70 @@ export function formatOfflineScore(summary: OfflineScoreSummary): string {return 'No successful results'}if (summary.scorer.kind === 'numeric') {- return summary.mean === null ? 'No score' : formatOfflineNumericScore(summary.mean)+ return summary.mean === null+ ? 'No score'+ : formatOfflineNumericScore(summary.mean, offlineNumericPassingRule(summary.scorer))}if (summary.scorer.kind === 'boolean') {- return summary.true_rate === null ? 'No score' : `${formatOfflineNumericScore(summary.true_rate * 100)}%`+ return summary.pass_rate == null ? 'No score' : formatOfflinePercentage(summary.pass_rate)}return summary.categories- .map(- ({ label, rate }) => `${label}: ${rate === null ? 'No score' : `${formatOfflineNumericScore(rate * 100)}%`}`- )+ .map(({ label, rate }) => `${label}: ${rate === null ? 'No score' : formatOfflinePercentage(rate)}`).join(', ')}-export function formatOfflineNumericScore(value: number): string {- return value.toLocaleString(undefined, { maximumSignificantDigits: 6 })+export function formatOfflineNumericScore(+ value: number,+ rule: ReturnType<typeof offlineNumericPassingRule> = null+): string {+ let precision = 6+ if (rule) {+ const passes = (score: number): boolean =>+ rule.operator === 'gte' ? score >= rule.threshold : score <= rule.threshold+ while (precision < 17 && passes(Number(value.toPrecision(precision))) !== passes(value)) {+ precision+++ }+ }+ return value.toLocaleString(undefined, { maximumSignificantDigits: precision })+}++export function formatOfflinePercentage(rate: number): string {+ return rate.toLocaleString(undefined, { style: 'percent', maximumFractionDigits: 2 })}export function offlineScoreConfigurationLabel(scorer: Pick<OfflineScorerVersionReadApi, 'kind' | 'config'>): string {const { config } = scorer+ const passingRule = offlineScorePassingRuleLabel(scorer)if (scorer.kind === 'numeric') {- return `Minimum: ${'min' in config && config.min !== null && config.min !== undefined ? formatOfflineNumericScore(config.min) : 'Unbounded'} · Maximum: ${'max' in config && config.max !== null && config.max !== undefined ? formatOfflineNumericScore(config.max) : 'Unbounded'}${'step' in config && config.step != null ? ` · Step: ${formatOfflineNumericScore(config.step)}` : ''}`+ return `Minimum: ${'min' in config && config.min !== null && config.min !== undefined ? formatOfflineNumericScore(config.min) : 'Unbounded'} · Maximum: ${'max' in config && config.max !== null && config.max !== undefined ? formatOfflineNumericScore(config.max) : 'Unbounded'}${'step' in config && config.step != null ? ` · Step: ${formatOfflineNumericScore(config.step)}` : ''} · ${passingRule ?? 'No passing rule'}`}if (scorer.kind === 'boolean') {- return `True: ${'true_label' in config ? config.true_label || 'True' : 'True'} · False: ${'false_label' in config ? config.false_label || 'False' : 'False'}`+ return `True: ${'true_label' in config ? config.true_label || 'True' : 'True'} · False: ${'false_label' in config ? config.false_label || 'False' : 'False'} · ${passingRule ?? 'No passing rule'}`}if ('options' in config) {- return `${config.selection_mode === 'multiple' ? 'Multiple selections' : 'Single selection'} · ${config.options.map(({ label, key }) => `${label} (${key})`).join(', ')}`+ return `${config.selection_mode === 'multiple' ? 'Multiple selections' : 'Single selection'} · ${config.options.map(({ label, key }) => `${label} (${key})`).join(', ')}${passingRule ? ` · ${passingRule}` : ''}`}return ''}+export function offlineScorePassingRuleLabel(+ scorer: Pick<OfflineScorerVersionReadApi, 'kind' | 'config'>+): string | null {+ const polarity = offlineBooleanPolarity(scorer)+ if (polarity !== null) {+ return `${polarity ? 'False' : 'True'} counts as a pass`+ }+ const rule = offlineNumericPassingRule(scorer)+ const categories = offlineCategoricalPassingRule(scorer)+ if (categories !== null) {+ const options = 'options' in scorer.config ? scorer.config.options : []+ return categories.length+ ? `Pass when every selected category is one of: ${categories.map((key) => options.find((option) => option.key === key)?.label || key).join(', ')}`+ : 'No selected categories count as a pass'+ }+ return rule ? `Pass when score ${rule.operator === 'gte' ? '≥' : '≤'} ${rule.threshold}` : null+}+export function getOfflineHistoryCoverage(page: OfflineHistoryPageApi, timezone: string = 'UTC'): string {const dates = page.results.map(({ experiment }) => experiment.started_at).sort()const span = dates.length@@ -210,6 +262,7 @@ export function buildOfflineTrendPanels(periods: OfflineTrendPeriod[]): OfflineTlabel: `${periods.length > 1 && !elapsed ? `${period.label} · ` : ''}${offlineScoreMetricLabel(scorer)}`,series: [],percentage: scorer.kind !== 'numeric',+ passingRule: offlineNumericPassingRule(scorer),elapsed,xDomain:period.dateFrom && period.dateTo@@ -231,7 +284,7 @@ export function buildOfflineTrendPanels(periods: OfflineTrendPeriod[]): OfflineT{key: 'score',label: offlineScoreMetricLabel(scorer),- value: scorer.kind === 'numeric' ? summary.mean : summary.true_rate,+ value: scorer.kind === 'numeric' ? summary.mean : summary.pass_rate,},]for (const metric of metrics) {@@ -246,7 +299,7 @@ export function buildOfflineTrendPanels(periods: OfflineTrendPeriod[]): OfflineT}panel.series.push(series)}- if (metric.value === null || !Number.isFinite(metric.value)) {+ if (metric.value == null || !Number.isFinite(metric.value)) {continue}series.points.push({@@ -269,7 +322,10 @@ export function buildOfflineTrendPanels(periods: OfflineTrendPeriod[]): OfflineT}}const configuration = key.slice(0, key.lastIndexOf(':'))- const values = domains.get(configuration) || []+ const values = [+ ...(domains.get(configuration) || []),+ ...(panel.passingRule ? [panel.passingRule.threshold] : []),+ ]if (panel.percentage) {panel.yDomain = [0, 1]} else if (values.length) {diff --git a/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScoreDefinitions.tsx b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScoreDefinitions.tsxindex 69fa4c0ceb63..415ac9785816 100644--- a/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScoreDefinitions.tsx+++ b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScoreDefinitions.tsx@@ -4,20 +4,17 @@ import {LemonBanner,LemonButton,LemonInput,- LemonModal,LemonSelect,LemonTable,LemonTableColumn,LemonTableColumns,LemonTag,Link,- LemonTextArea,} from '@posthog/lemon-ui'import { AccessControlAction } from 'lib/components/AccessControlAction'import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'import { FEATURE_FLAGS } from 'lib/constants'-import { LemonModalContent, LemonModalFooter, LemonModalHeader } from 'lib/lemon-ui/LemonModal/LemonModal'import { featureFlagLogic } from 'lib/logic/featureFlagLogic'import { getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'import { Scene } from 'scenes/sceneTypes'@@ -35,16 +32,7 @@ import {SCORE_DEFINITIONS_PER_PAGE,} from './aiObservabilityScoreDefinitionsLogic'import { ScoreDefinitionActions } from './ScoreDefinitionActions'-import { scoreDefinitionModalLogic } from './scoreDefinitionModalLogic'-import {- CATEGORICAL_SELECTION_MODE_OPTIONS,- formatKindLabel,- formatNumericInputValue,- getIntegerInputValue,- getNumericInputValue,- type CategoricalSelectionMode,- type ScoreDefinitionModalMode,-} from './scoreDefinitionModalUtils'+import { formatKindLabel } from './scoreDefinitionModalUtils'const KIND_OPTIONS: { label: string; value: ScoreDefinitionKind | '' }[] = [{ label: 'All kinds', value: '' },@@ -61,7 +49,7 @@ const ARCHIVED_OPTIONS: { label: string; value: '' | 'false' | 'true' }[] = [export function AIObservabilityScoreDefinitions(): JSX.Element {const logic = useMountedLogic(aiObservabilityScoreDefinitionsLogic())- const { setFilters, openModal, closeModal, toggleArchive, loadScoreDefinitions } = useActions(logic)+ const { setFilters, toggleArchive, loadScoreDefinitions } = useActions(logic)const { featureFlags } = useValues(featureFlagLogic)const showHistory =!!featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS] &&@@ -74,18 +62,8 @@ export function AIObservabilityScoreDefinitions(): JSX.Element {pagination,filters,scoreDefinitionCountLabel,- modalMode,- selectedDefinition,isArchivingDefinition,} = useValues(logic)- const modalProps =- modalMode === null || (modalMode !== 'create' && selectedDefinition === null)- ? null- : {- mode: modalMode,- scoreDefinition: selectedDefinition,- }-const columns: LemonTableColumns<ScoreDefinition> = [{title: 'Name',@@ -96,13 +74,7 @@ export function AIObservabilityScoreDefinitions(): JSX.Element {return (<div className="space-y-1"><div className="font-semibold max-w-64 @max-[50rem]/scorers:max-w-32 truncate">- {showHistory ? (- <Link to={urls.aiObservabilityOfflineScorerHistory(scoreDefinition.id)}>- {scoreDefinition.name}- </Link>- ) : (- scoreDefinition.name- )}+ <Link to={urls.aiObservabilityScorer(scoreDefinition.id)}>{scoreDefinition.name}</Link></div>{scoreDefinition.description ? (<div className="max-w-64 @max-[50rem]/scorers:max-w-32 truncate text-muted-alt">@@ -167,9 +139,8 @@ export function AIObservabilityScoreDefinitions(): JSX.Element {<ScoreDefinitionActionsdefinition={scoreDefinition}archiving={isArchivingDefinition(scoreDefinition.id)}- openModal={openModal}+ showHistory={showHistory}toggleArchive={toggleArchive}- onVersionCreated={() => loadScoreDefinitions(false)}/>)},@@ -211,7 +182,7 @@ export function AIObservabilityScoreDefinitions(): JSX.Element {<LemonButtontype="primary"size="small"- onClick={() => openModal('create')}+ to={urls.aiObservabilityScorer('new')}data-attr="llma-scorers-create-button">New scorer@@ -248,250 +219,6 @@ export function AIObservabilityScoreDefinitions(): JSX.Element {nouns={['scorer', 'scorers']}/>)}-- {modalProps && (- <ScoreDefinitionModal- mode={modalProps.mode}- scoreDefinition={modalProps.scoreDefinition}- onClose={closeModal}- />- )}</div>)}--function ScoreDefinitionModal({- mode,- scoreDefinition,- onClose,-}: {- mode: ScoreDefinitionModalMode- scoreDefinition: ScoreDefinition | null- onClose: () => void-}): JSX.Element {- const logic = useMountedLogic(scoreDefinitionModalLogic({ mode, scoreDefinition }))- const { submit, setDraftField, updateOptionLabel, addOption, removeOption } = useActions(logic)- const { draft, isCreateMode, isMetadataMode, isConfigMode, title, submitting } = useValues(logic)-- return (- <LemonModal isOpen onClose={onClose} simple maxWidth="42rem">- <LemonModalHeader>- <h3>{title}</h3>- </LemonModalHeader>-- <LemonModalContent className="space-y-4">- {isConfigMode && scoreDefinition ? (- <LemonBanner type="info">- Saving these config changes creates version v{scoreDefinition.current_version + 1}. Previous- versions remain preserved.- </LemonBanner>- ) : null}-- {!isConfigMode ? (- <>- <div className="space-y-1">- <label className="text-sm font-medium">Name</label>- <LemonInput- value={draft.name}- onChange={(value) => setDraftField('name', value)}- data-attr="llma-scorer-name-input"- />- </div>-- {isCreateMode ? (- <>- <div className="space-y-1">- <label className="text-sm font-medium">Kind</label>- <LemonSelect<ScoreDefinitionKind>- value={draft.kind}- onChange={(value) =>- setDraftField('kind', (value as ScoreDefinitionKind) || 'categorical')- }- options={- KIND_OPTIONS.filter((option) => option.value !== '') as {- label: string- value: ScoreDefinitionKind- }[]- }- data-attr="llma-scorer-kind-select"- />- </div>- </>- ) : scoreDefinition ? (- <div className="space-y-1">- <div className="text-sm font-medium">Kind</div>- <div>{formatKindLabel(scoreDefinition.kind)}</div>- </div>- ) : null}-- <div className="space-y-1">- <label className="text-sm font-medium">Description</label>- <LemonTextArea- value={draft.description}- onChange={(value) => setDraftField('description', value)}- data-attr="llma-scorer-description-input"- />- </div>- </>- ) : null}-- {!isMetadataMode ? (- <>- {draft.kind === 'categorical' ? (- <div className="space-y-3">- <div className="grid gap-4 sm:grid-cols-3">- <div className="space-y-1">- <label className="text-sm font-medium">Selection mode</label>- <LemonSelect<CategoricalSelectionMode>- value={draft.selectionMode}- onChange={(value) =>- setDraftField(- 'selectionMode',- (value as CategoricalSelectionMode) || 'single'- )- }- options={CATEGORICAL_SELECTION_MODE_OPTIONS}- data-attr="llma-scorer-selection-mode"- />- </div>-- {draft.selectionMode === 'multiple' ? (- <>- <div className="space-y-1">- <label className="text-sm font-medium">Min selections</label>- <LemonInput- type="number"- value={getIntegerInputValue(draft.categoricalMinSelections)}- onChange={(value) =>- setDraftField(- 'categoricalMinSelections',- formatNumericInputValue(value)- )- }- />- </div>- <div className="space-y-1">- <label className="text-sm font-medium">Max selections</label>- <LemonInput- type="number"- value={getIntegerInputValue(draft.categoricalMaxSelections)}- onChange={(value) =>- setDraftField(- 'categoricalMaxSelections',- formatNumericInputValue(value)- )- }- />- </div>- </>- ) : null}- </div>- <div className="flex items-center justify-between">- <div className="text-sm font-medium">Options</div>- <LemonButton- type="secondary"- size="small"- onClick={addOption}- data-attr="llma-scorer-add-option"- >- Add option- </LemonButton>- </div>- <div className="text-xs text-muted-alt">- Enter the labels people should choose from. Internal option IDs are generated- automatically.- </div>- {draft.options.map((option, index) => (- <div key={`${index}-${option.key}`} className="grid gap-2 sm:grid-cols-[1fr,auto]">- <LemonInput- placeholder="Option label"- value={option.label}- onChange={(value) => updateOptionLabel(index, value)}- />- <LemonButton- type="secondary"- status="danger"- onClick={() => removeOption(index)}- disabledReason={- draft.options.length <= 1 ? 'Keep at least one option' : undefined- }- data-attr="llma-scorer-remove-option"- >- Remove- </LemonButton>- </div>- ))}- </div>- ) : null}-- {draft.kind === 'numeric' ? (- <div className="grid gap-4 sm:grid-cols-3">- <div className="space-y-1">- <label className="text-sm font-medium">Min</label>- <LemonInput- type="number"- value={getNumericInputValue(draft.numericMin)}- onChange={(value) =>- setDraftField('numericMin', formatNumericInputValue(value))- }- />- </div>- <div className="space-y-1">- <label className="text-sm font-medium">Max</label>- <LemonInput- type="number"- value={getNumericInputValue(draft.numericMax)}- onChange={(value) =>- setDraftField('numericMax', formatNumericInputValue(value))- }- />- </div>- <div className="space-y-1">- <label className="text-sm font-medium">Increment</label>- <LemonInput- type="number"- value={getNumericInputValue(draft.numericStep)}- onChange={(value) =>- setDraftField('numericStep', formatNumericInputValue(value))- }- />- <div className="text-xs text-muted-alt">- Optional amount the score should increase by, for example 1 or 0.5.- </div>- </div>- </div>- ) : null}-- {draft.kind === 'boolean' ? (- <div className="grid gap-4 sm:grid-cols-2">- <div className="space-y-1">- <label className="text-sm font-medium">True label</label>- <LemonInput- value={draft.trueLabel}- onChange={(value) => setDraftField('trueLabel', value)}- />- </div>- <div className="space-y-1">- <label className="text-sm font-medium">False label</label>- <LemonInput- value={draft.falseLabel}- onChange={(value) => setDraftField('falseLabel', value)}- />- </div>- </div>- ) : null}- </>- ) : null}- </LemonModalContent>-- <LemonModalFooter>- <LemonButton type="secondary" onClick={onClose} data-attr="llma-scorer-cancel">- Cancel- </LemonButton>- <LemonButton type="primary" onClick={() => submit()} loading={submitting} data-attr="llma-scorer-save">- {isConfigMode ? 'Create version' : 'Save'}- </LemonButton>- </LemonModalFooter>- </LemonModal>- )-}diff --git a/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.stories.tsx b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.stories.tsxnew file mode 100644index 000000000000..9fbe5ae03b2e--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.stories.tsx@@ -0,0 +1,106 @@+import type { Meta, StoryObj } from '@storybook/react'++import { FEATURE_FLAGS } from 'lib/constants'+import { urls } from 'scenes/urls'++import { mswDecorator } from '~/mocks/browser'++import type { ScoreDefinitionApi } from '../generated/api.schemas'+import { AIObservabilityScorerScene } from './AIObservabilityScorerScene'++const definition: ScoreDefinitionApi = {+ id: 'b4f331fe-7d3b-4bbe-9f88-52e1b0a8b000',+ name: 'Answer quality',+ description: 'How well the response answers the question, scored from 0 to 1.',+ kind: 'numeric',+ archived: false,+ current_version: 3,+ current_version_id: 'b4f331fe-7d3b-4bbe-9f88-52e1b0a8b003',+ config: { min: 0, max: 1, passing_rule: { operator: 'gte', threshold: 0.8 } },+ created_by: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-02T00:00:00Z',+ team: 997,+}++const meta: Meta<typeof AIObservabilityScorerScene> = {+ title: 'AI observability/Scorer editor',+ component: AIObservabilityScorerScene,+ args: { scorerId: definition.id },+ parameters: {+ pageUrl: urls.aiObservabilityScorer(definition.id),+ featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS],+ },+ decorators: [+ mswDecorator({+ get: { '/api/projects/:team/llm_analytics/score_definitions/:id/': definition },+ patch: {+ '/api/projects/:team/llm_analytics/score_definitions/:id/': async ({ request }) => ({+ ...definition,+ ...((await request.json()) as object),+ }),+ },+ post: {+ '/api/projects/:team/llm_analytics/score_definitions/': async ({ request }) => ({+ ...definition,+ ...((await request.json()) as object),+ current_version: 1,+ }),+ '/api/projects/:team/llm_analytics/score_definitions/:id/new_version/': async ({ request }) => ({+ ...definition,+ ...((await request.json()) as object),+ current_version: 4,+ }),+ },+ }),+ ],+}+export default meta+type Story = StoryObj<typeof AIObservabilityScorerScene>++export const Numeric: Story = {}+export const NewScorer: Story = {+ args: { scorerId: 'new' },+ parameters: { pageUrl: urls.aiObservabilityScorer('new') },+}+export const BooleanDetector: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team/llm_analytics/score_definitions/:id/': {+ ...definition,+ name: 'Hallucination detected',+ description: 'Flags responses that contain unsupported claims.',+ kind: 'boolean',+ config: { true_is_failure: true, true_label: 'Detected', false_label: 'Not detected' },+ },+ },+ }),+ ],+}+export const LegacyBoolean: Story = {+ decorators: [+ mswDecorator({+ get: {+ '/api/projects/:team/llm_analytics/score_definitions/:id/': {+ ...definition,+ name: 'Review outcome',+ kind: 'boolean',+ config: { true_label: 'Yes', false_label: 'No' },+ },+ },+ }),+ ],+}+export const Narrow: Story = {+ decorators: [+ (Story) => (+ <div className="w-[520px]">+ <Story />+ </div>+ ),+ ],+}+export const LoadError: Story = {+ decorators: [mswDecorator({ get: { '/api/projects/:team/llm_analytics/score_definitions/:id/': [500, {}] } })],+}diff --git a/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.tsx b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.tsxnew file mode 100644index 000000000000..4769b26a1d8d--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/AIObservabilityScorerScene.tsx@@ -0,0 +1,227 @@+import { useActions, useValues } from 'kea'++import { IconEllipsis } from '@posthog/icons'+import { LemonBanner, LemonButton, LemonMenu, LemonTag } from '@posthog/lemon-ui'++import { CopyToClipboardInline } from 'lib/components/CopyToClipboard'+import { FEATURE_FLAGS } from 'lib/constants'+import { LemonDialog } from 'lib/lemon-ui/LemonDialog'+import { LemonSkeleton } from 'lib/lemon-ui/LemonSkeleton'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'+import { getAccessControlDisabledReason, getProductAccessDisabledReason } from 'lib/utils/accessControlUtils'+import { Scene, SceneExport } from 'scenes/sceneTypes'+import { urls } from 'scenes/urls'++import { SceneContent } from '~/layout/scenes/components/SceneContent'+import { SceneTitleSection } from '~/layout/scenes/components/SceneTitleSection'+import { ProductKey } from '~/queries/schema/schema-general'+import { AccessControlLevel, AccessControlResourceType } from '~/types'++import { ScoreDefinitionForm } from './ScoreDefinitionForm'+import { formatKindLabel } from './scoreDefinitionModalUtils'+import { ScorerLogicProps, scorerLogic } from './scorerLogic'++export const scene: SceneExport<ScorerLogicProps> = {+ component: AIObservabilityScorerScene,+ logic: scorerLogic,+ productKey: ProductKey.AI_OBSERVABILITY,+ paramsToProps: ({ params, searchParams }) => ({+ scorerId: params.scorerId || 'new',+ duplicateFrom:+ params.scorerId === 'new' && typeof searchParams.duplicate === 'string'+ ? searchParams.duplicate+ : undefined,+ }),+}++export function AIObservabilityScorerScene(props: ScorerLogicProps): JSX.Element {+ const logic = scorerLogic(props)+ const { definition, definitionLoading, draft, isNew, hasChanges, willCreateVersion, saving, error, loadError } =+ useValues(logic)+ const {+ loadDefinition,+ save,+ createVersion,+ toggleArchive,+ setDraftField,+ updateOptionLabel,+ addOption,+ removeOption,+ } = useActions(logic)+ const { featureFlags } = useValues(featureFlagLogic)+ const editDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.LlmAnalytics,+ AccessControlLevel.Editor+ )+ const showHistory =+ !!featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS] &&+ !getProductAccessDisabledReason({ sceneKey: Scene.AIObservabilityOfflineScorerHistory })++ if (definitionLoading || (!isNew && !definition && !loadError)) {+ return (+ <SceneContent>+ <LemonSkeleton className="h-8 w-64" />+ <LemonSkeleton className="h-96 w-full max-w-3xl" />+ </SceneContent>+ )+ }+ if (loadError) {+ return (+ <SceneContent>+ <LemonBanner type="error" action={{ children: 'Try again', onClick: loadDefinition }}>+ {loadError}+ </LemonBanner>+ <LemonButton to={urls.aiObservabilityScorers()}>Back to scorers</LemonButton>+ </SceneContent>+ )+ }++ return (+ <SceneContent>+ <SceneTitleSection+ name={isNew ? 'New scorer' : definition?.name || 'Scorer'}+ description="Define the scores used in manual reviews and offline evaluations."+ resourceType={{ type: 'llm_evaluations' }}+ actions={+ <div className="flex flex-wrap items-center gap-2">+ {!isNew && definition && (+ <LemonMenu+ items={[+ {+ label: 'Duplicate',+ to: urls.aiObservabilityScorer('new', { duplicate: definition.id }),+ disabledReason: editDisabledReason || (saving ? 'Saving scorer' : undefined),+ 'data-attr': 'llma-scorer-duplicate',+ },+ {+ label: 'Create new version',+ disabledReason:+ editDisabledReason ||+ (saving+ ? 'Saving scorer'+ : hasChanges+ ? 'Save your changes first'+ : undefined),+ onClick: () =>+ LemonDialog.open({+ title: 'Create a new scorer version?',+ content: `Version ${definition.current_version + 1} will keep the current configuration. Use this when your external evaluator changes.`,+ primaryButton: { children: 'Create version', onClick: createVersion },+ secondaryButton: { children: 'Cancel' },+ }),+ 'data-attr': 'llma-scorer-new-version',+ },+ {+ label: definition.archived ? 'Unarchive' : 'Archive',+ status: definition.archived ? 'default' : 'danger',+ disabledReason:+ editDisabledReason ||+ (saving+ ? 'Saving scorer'+ : hasChanges+ ? 'Save your changes first'+ : undefined),+ onClick: toggleArchive,+ 'data-attr': 'llma-scorer-archive-toggle',+ },+ ]}+ >+ <LemonButton icon={<IconEllipsis />} aria-label="Scorer actions" type="secondary" />+ </LemonMenu>+ )}+ <LemonButton+ to={urls.aiObservabilityScorers()}+ type="secondary"+ disabledReason={saving ? 'Saving scorer' : undefined}+ data-attr="llma-scorer-cancel"+ >+ {hasChanges || isNew ? 'Cancel' : 'Back to scorers'}+ </LemonButton>+ <LemonButton+ type="primary"+ htmlType="submit"+ form="scorer-form"+ loading={saving}+ disabledReason={editDisabledReason || (!hasChanges ? 'No unsaved changes' : undefined)}+ data-attr="llma-scorer-save"+ >+ {isNew ? 'Create scorer' : 'Save changes'}+ </LemonButton>+ </div>+ }+ />+ <form+ id="scorer-form"+ className="max-w-3xl w-full space-y-6 pb-8"+ onSubmit={(event) => {+ event.preventDefault()+ save()+ }}+ >+ {!isNew && definition && (+ <div className="flex flex-wrap gap-2 items-center justify-between border-b pb-4">+ <div className="flex items-center flex-wrap gap-2">+ <LemonTag>{formatKindLabel(definition.kind)}</LemonTag>+ <span className="text-muted text-sm">{`Version ${definition.current_version}`}</span>+ {definition.archived && <LemonTag type="muted">Archived</LemonTag>}+ {definition.current_version_id && (+ <CopyToClipboardInline+ explicitValue={definition.current_version_id}+ description="Scorer version ID"+ >+ <span className="text-xs">Copy version ID</span>+ </CopyToClipboardInline>+ )}+ </div>+ {showHistory && (+ <LemonButton+ to={urls.aiObservabilityOfflineScorerHistory(definition.id)}+ type="secondary"+ size="small"+ disabledReason={saving ? 'Saving scorer' : undefined}+ data-attr="scorer-offline-history"+ >+ Offline evals history+ </LemonButton>+ )}+ </div>+ )}+ {error && (+ <LemonBanner+ type="error"+ action={+ isNew+ ? undefined+ : {+ children: 'Reload scorer',+ onClick: () =>+ LemonDialog.open({+ title: 'Discard unsaved changes?',+ content: 'Reloading replaces this form with the latest saved scorer.',+ primaryButton: { children: 'Reload scorer', onClick: loadDefinition },+ secondaryButton: { children: 'Keep editing' },+ }),+ }+ }+ >+ {error}+ </LemonBanner>+ )}+ {willCreateVersion && definition && (+ <LemonBanner type="info">+ {`Saving these scoring rules creates version ${definition.current_version + 1}. Existing reviews and experiments keep their original configuration.`}+ </LemonBanner>+ )}+ <ScoreDefinitionForm+ draft={draft}+ isNew={isNew}+ disabled={saving || !!editDisabledReason}+ setDraftField={setDraftField}+ updateOptionLabel={updateOptionLabel}+ addOption={addOption}+ removeOption={removeOption}+ />+ </form>+ </SceneContent>+ )+}diff --git a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionActions.tsx b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionActions.tsxindex 675a75cd0918..ae1a422c94c8 100644--- a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionActions.tsx+++ b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionActions.tsx@@ -1,89 +1,60 @@-import { useActions, useValues } from 'kea'-import { useId } from 'react'-import { IconEllipsis } from '@posthog/icons'import { LemonButton, LemonMenu } from '@posthog/lemon-ui'-import { AccessControlAction } from 'lib/components/AccessControlAction'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { urls } from 'scenes/urls'import { AccessControlLevel, AccessControlResourceType } from '~/types'import type { ScoreDefinitionApi } from '../generated/api.schemas'-import type { ScoreDefinitionModalMode } from './scoreDefinitionModalUtils'-import { ScoreDefinitionVersionModal } from './ScoreDefinitionVersionModal'-import { scoreDefinitionVersionModalLogic } from './scoreDefinitionVersionModalLogic'export function ScoreDefinitionActions({definition,archiving,- openModal,+ showHistory,toggleArchive,- onVersionCreated,}: {definition: ScoreDefinitionApiarchiving: boolean- openModal: (mode: ScoreDefinitionModalMode, definition: ScoreDefinitionApi) => void+ showHistory: booleantoggleArchive: (definition: ScoreDefinitionApi) => void- onVersionCreated: () => void}): JSX.Element {- const instanceKey = useId()- const versionModalLogic = scoreDefinitionVersionModalLogic({ instanceKey })- const { isOpen: versionModalOpen } = useValues(versionModalLogic)- const { openModal: openVersionModal, closeModal: closeVersionModal } = useActions(versionModalLogic)-+ const editDisabledReason = getAccessControlDisabledReason(+ AccessControlResourceType.LlmAnalytics,+ AccessControlLevel.Editor+ )return (- <>- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonMenu- items={[- {- label: 'Edit metadata',- onClick: () => openModal('metadata', definition),- 'data-attr': 'llma-scorer-edit-metadata',- },- {- label: 'Edit config',- onClick: () => openModal('config', definition),- 'data-attr': 'llma-scorer-edit-config',- },- {- label: 'Create new version',- onClick: openVersionModal,- 'data-attr': 'llma-scorer-new-version',- },- {- label: 'Duplicate',- onClick: () => openModal('duplicate', definition),- 'data-attr': 'llma-scorer-duplicate',- },- {- label: definition.archived ? 'Unarchive' : 'Archive',- onClick: () => toggleArchive(definition),- disabledReason: archiving ? 'Updating scorer' : undefined,- status: definition.archived ? 'default' : 'danger',- 'data-attr': 'llma-scorer-archive-toggle',- },- ]}- >- <LemonButton- icon={<IconEllipsis />}- size="small"- aria-label={`Actions for ${definition.name}`}- loading={archiving}- />- </LemonMenu>- </AccessControlAction>- {versionModalOpen && (- <ScoreDefinitionVersionModal- teamId={String(definition.team)}- scorerId={definition.id}- onClose={closeVersionModal}- onSuccess={onVersionCreated}- />- )}- </>+ <LemonMenu+ items={[+ {+ label: 'Edit scorer',+ to: urls.aiObservabilityScorer(definition.id),+ 'data-attr': 'llma-scorer-edit-config',+ },+ ...(showHistory+ ? [{ label: 'Offline history', to: urls.aiObservabilityOfflineScorerHistory(definition.id) }]+ : []),+ {+ label: 'Duplicate',+ to: urls.aiObservabilityScorer('new', { duplicate: definition.id }),+ disabledReason: editDisabledReason,+ 'data-attr': 'llma-scorer-duplicate',+ },+ {+ label: definition.archived ? 'Unarchive' : 'Archive',+ onClick: () => toggleArchive(definition),+ disabledReason: editDisabledReason || (archiving ? 'Updating scorer' : undefined),+ status: definition.archived ? 'default' : 'danger',+ 'data-attr': 'llma-scorer-archive-toggle',+ },+ ]}+ >+ <LemonButton+ icon={<IconEllipsis />}+ size="small"+ aria-label={`Actions for ${definition.name}`}+ loading={archiving}+ />+ </LemonMenu>)}diff --git a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.stories.tsx b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.stories.tsxnew file mode 100644index 000000000000..92ebe7c6e2c6--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.stories.tsx@@ -0,0 +1,98 @@+import type { Meta, StoryObj } from '@storybook/react'+import { useState } from 'react'++import { FEATURE_FLAGS } from 'lib/constants'++import { ScoreDefinitionForm, type ScoreDefinitionFormProps } from './ScoreDefinitionForm'+import { createDraft } from './scoreDefinitionModalUtils'++const meta: Meta<typeof ScoreDefinitionForm> = {+ title: 'AI observability/Scorer form',+ component: ScoreDefinitionForm,+ parameters: { layout: 'padded', featureFlags: [FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS] },+ args: {+ isNew: false,+ disabled: false,+ draft: {+ ...createDraft('create'),+ name: 'Answer quality',+ kind: 'numeric',+ numericMin: '0',+ numericMax: '10',+ numericPassingEnabled: true,+ numericPassingThreshold: '7',+ },+ },+ render: function Render(args): JSX.Element {+ const [draft, setDraft] = useState(args.draft)+ return (+ <div className="w-[768px] max-w-full">+ <ScoreDefinitionForm+ {...args}+ draft={draft}+ setDraftField={(field, value) => setDraft((current) => ({ ...current, [field]: value }))}+ updateOptionLabel={(index, label) =>+ setDraft((current) => ({+ ...current,+ options: current.options.map((option, i) => (i === index ? { ...option, label } : option)),+ }))+ }+ addOption={() =>+ setDraft((current) => ({ ...current, options: [...current.options, { key: '', label: '' }] }))+ }+ removeOption={(index) =>+ setDraft((current) => ({+ ...current,+ options: current.options.filter((_, i) => i !== index),+ }))+ }+ />+ </div>+ )+ },+}++export default meta+type Story = StoryObj<ScoreDefinitionFormProps>++export const Numeric: Story = {}+export const NewScorer: Story = { args: { isNew: true, draft: createDraft('create') } }+export const BooleanDetector: Story = {+ args: {+ draft: {+ ...createDraft('create'),+ name: 'Hallucination',+ kind: 'boolean',+ trueLabel: 'Flagged',+ falseLabel: 'Clear',+ booleanPassing: 'false',+ },+ },+}+export const Narrow: Story = {+ decorators: [+ (Story) => (+ <div className="w-[520px]">+ <Story />+ </div>+ ),+ ],+}++export const Categorical: Story = {+ args: {+ draft: {+ ...createDraft('create'),+ name: 'Response quality',+ selectionMode: 'multiple',+ categoricalMinSelections: '1',+ categoricalMaxSelections: '2',+ categoricalPassingEnabled: true,+ categoricalPassingCategories: ['good'],+ },+ },+}+export const OfflineDisabled: Story = {+ parameters: { featureFlags: { [FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS]: false } },+}+export const CategoricalNarrow: Story = { ...Categorical, decorators: Narrow.decorators }diff --git a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.tsx b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.tsxnew file mode 100644index 000000000000..c973a2e07bb5--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionForm.tsx@@ -0,0 +1,399 @@+import { useValues } from 'kea'+import { useId } from 'react'++import { IconCheck, IconX } from '@posthog/icons'+import {+ LemonButton,+ LemonCheckbox,+ LemonDivider,+ LemonInput,+ LemonSelect,+ LemonSwitch,+ LemonTag,+ LemonTextArea,+} from '@posthog/lemon-ui'++import { FEATURE_FLAGS } from 'lib/constants'+import { LemonField } from 'lib/lemon-ui/LemonField'+import { featureFlagLogic } from 'lib/logic/featureFlagLogic'++import {+ CATEGORICAL_SELECTION_MODE_OPTIONS,+ formatKindLabel,+ formatNumericInputValue,+ getIntegerInputValue,+ getNumericInputValue,+ getScoreDefinitionOptionKey,+ type ScoreDefinitionDraft,+} from './scoreDefinitionModalUtils'++export interface ScoreDefinitionFormProps {+ draft: ScoreDefinitionDraft+ isNew: boolean+ disabled: boolean+ setDraftField: (field: keyof ScoreDefinitionDraft, value: ScoreDefinitionDraft[keyof ScoreDefinitionDraft]) => void+ updateOptionLabel: (index: number, value: string) => void+ addOption: () => void+ removeOption: (index: number) => void+}++export function ScoreDefinitionForm({+ draft,+ isNew,+ disabled,+ setDraftField,+ updateOptionLabel,+ addOption,+ removeOption,+}: ScoreDefinitionFormProps): JSX.Element {+ const id = useId()+ const { featureFlags } = useValues(featureFlagLogic)+ const disabledReason = disabled ? 'Editing is unavailable right now' : undefined+ const threshold = getNumericInputValue(draft.numericPassingThreshold)++ return (+ <div className="space-y-6 @container/scorer-form">+ <section className="space-y-4" aria-labelledby={`${id}-details`}>+ <h3 id={`${id}-details`} className="mb-0">+ Details+ </h3>+ <LemonField.Pure label="Name" htmlFor={`${id}-name`}>+ <LemonInput+ id={`${id}-name`}+ value={draft.name}+ onChange={(value) => setDraftField('name', value)}+ disabled={disabled}+ placeholder="e.g. Answer quality"+ data-attr="llma-scorer-name-input"+ />+ </LemonField.Pure>+ <LemonField.Pure label="Description (optional)" htmlFor={`${id}-description`}>+ <LemonTextArea+ id={`${id}-description`}+ value={draft.description}+ onChange={(value) => setDraftField('description', value)}+ disabled={disabled}+ placeholder="What does this scorer measure?"+ data-attr="llma-scorer-description-input"+ />+ </LemonField.Pure>+ </section>++ <LemonDivider />++ <section className="space-y-4" aria-labelledby={`${id}-format`}>+ <h3 id={`${id}-format`} className="mb-0">+ Score format+ </h3>+ <LemonField.Pure+ label="Kind"+ htmlFor={isNew ? `${id}-kind` : undefined}+ help={isNew ? undefined : 'The kind stays the same across scorer versions.'}+ >+ {isNew ? (+ <LemonSelect+ id={`${id}-kind`}+ value={draft.kind}+ onChange={(value) => setDraftField('kind', value)}+ options={[+ { label: 'Categorical', value: 'categorical' },+ { label: 'Numeric', value: 'numeric' },+ { label: 'Boolean', value: 'boolean' },+ ]}+ disabledReason={disabledReason}+ data-attr="llma-scorer-kind-select"+ />+ ) : (+ <LemonTag type="muted" className="self-start">+ {formatKindLabel(draft.kind)}+ </LemonTag>+ )}+ </LemonField.Pure>++ {draft.kind === 'numeric' && (+ <>+ <div className="grid gap-4 @min-[36rem]/scorer-form:grid-cols-3">+ {(+ [+ ['numericMin', 'Minimum (optional)'],+ ['numericMax', 'Maximum (optional)'],+ ['numericStep', 'Increment (optional)'],+ ] as const+ ).map(([field, label]) => (+ <LemonField.Pure key={field} label={label} htmlFor={`${id}-${field}`}>+ <LemonInput+ id={`${id}-${field}`}+ type="number"+ value={getNumericInputValue(draft[field])}+ onChange={(value) => setDraftField(field, formatNumericInputValue(value))}+ disabled={disabled}+ placeholder="Not set"+ step="any"+ />+ </LemonField.Pure>+ ))}+ </div>+ <p className="text-sm text-muted mb-0">+ Bounds are inclusive. The increment guides manual scoring, for example 1 or 0.5.+ </p>+ </>+ )}++ {draft.kind === 'boolean' && (+ <div className="grid gap-4 @min-[30rem]/scorer-form:grid-cols-2">+ {(+ [+ ['trueLabel', 'True label (optional)', 'True'],+ ['falseLabel', 'False label (optional)', 'False'],+ ] as const+ ).map(([field, label, placeholder]) => (+ <LemonField.Pure key={field} label={label} htmlFor={`${id}-${field}`}>+ <LemonInput+ id={`${id}-${field}`}+ value={draft[field]}+ onChange={(value) => setDraftField(field, value)}+ placeholder={placeholder}+ disabled={disabled}+ />+ </LemonField.Pure>+ ))}+ </div>+ )}++ {draft.kind === 'categorical' && (+ <>+ <div className="grid gap-4 @min-[36rem]/scorer-form:grid-cols-3">+ <LemonField.Pure label="Selection mode" htmlFor={`${id}-selection-mode`}>+ <LemonSelect+ id={`${id}-selection-mode`}+ value={draft.selectionMode}+ onChange={(value) => setDraftField('selectionMode', value)}+ options={CATEGORICAL_SELECTION_MODE_OPTIONS}+ disabledReason={disabledReason}+ data-attr="llma-scorer-selection-mode"+ />+ </LemonField.Pure>+ {draft.selectionMode === 'multiple' &&+ (+ [+ ['categoricalMinSelections', 'Minimum selections'],+ ['categoricalMaxSelections', 'Maximum selections'],+ ] as const+ ).map(([field, label]) => (+ <LemonField.Pure key={field} label={label} htmlFor={`${id}-${field}`}>+ <LemonInput+ id={`${id}-${field}`}+ type="number"+ value={getIntegerInputValue(draft[field])}+ onChange={(value) => setDraftField(field, formatNumericInputValue(value))}+ min={1}+ max={draft.options.length}+ step={1}+ placeholder="Not set"+ disabled={disabled}+ />+ </LemonField.Pure>+ ))}+ </div>+ <div className="space-y-3">+ {draft.options.map((option, index) => (+ <LemonField.Pure+ key={`${index}-${option.key}`}+ label={`Option ${index + 1}`}+ htmlFor={`${id}-option-${index}`}+ >+ <div className="flex items-start gap-2">+ <LemonInput+ id={`${id}-option-${index}`}+ className="flex-1 min-w-0"+ placeholder="Option label"+ value={option.label}+ onChange={(value) => updateOptionLabel(index, value)}+ disabled={disabled}+ />+ <LemonButton+ type="secondary"+ status="danger"+ onClick={() => removeOption(index)}+ disabledReason={+ disabledReason ||+ (draft.options.length <= 1 ? 'Keep at least one option' : undefined)+ }+ data-attr="llma-scorer-remove-option"+ >+ Remove+ </LemonButton>+ </div>+ </LemonField.Pure>+ ))}+ <LemonButton+ type="secondary"+ size="small"+ onClick={addOption}+ disabledReason={disabledReason}+ data-attr="llma-scorer-add-option"+ >+ Add option+ </LemonButton>+ </div>+ </>+ )}+ </section>++ {featureFlags[FEATURE_FLAGS.AI_OBSERVABILITY_OFFLINE_EVALUATIONS] && (+ <>+ <LemonDivider />+ <section className="space-y-4" aria-labelledby={`${id}-passing`}>+ <div className="space-y-1">+ <h3 id={`${id}-passing`} className="mb-0">+ Passing rule+ </h3>+ <p className="text-sm text-muted mb-0">+ Choose which results count as passes in offline evaluations. The stored scores stay the+ same.+ </p>+ </div>+ {draft.kind === 'boolean' ? (+ <>+ <LemonField.Pure label="Passing value" htmlFor={`${id}-boolean-passing`}>+ <LemonSelect+ id={`${id}-boolean-passing`}+ value={draft.booleanPassing}+ onChange={(value) => setDraftField('booleanPassing', value)}+ options={[+ { value: 'true', label: 'True means pass' },+ { value: 'false', label: 'False means pass' },+ ]}+ disabledReason={disabledReason}+ data-attr="llma-scorer-boolean-passing"+ />+ </LemonField.Pure>+ <div className="flex flex-wrap gap-2" aria-label="Result preview">+ {(['true', 'false'] as const).map((value) => {+ const passing = draft.booleanPassing === value+ const label =+ value === 'true'+ ? draft.trueLabel.trim() || 'True'+ : draft.falseLabel.trim() || 'False'+ return (+ <LemonTag+ key={value}+ type={passing ? 'success' : 'danger'}+ icon={passing ? <IconCheck /> : <IconX />}+ wrap+ >+ {`${label}${passing ? ' · Pass' : ' · Fail'}`}+ </LemonTag>+ )+ })}+ </div>+ </>+ ) : draft.kind === 'categorical' ? (+ <>+ <LemonSwitch+ label="Set a passing rule"+ checked={draft.categoricalPassingEnabled}+ onChange={(value) => setDraftField('categoricalPassingEnabled', value)}+ disabledReason={disabledReason}+ data-attr="llma-scorer-categorical-passing-rule"+ />+ {draft.categoricalPassingEnabled && (+ <LemonField.Pure label="Passing categories">+ <div className="flex flex-col gap-2">+ {draft.options.map((option, index) => {+ const key = getScoreDefinitionOptionKey(option)+ return (+ <LemonCheckbox+ key={index}+ label={option.label || 'Unnamed category'}+ checked={draft.categoricalPassingCategories.includes(key)}+ disabled={disabled || !key}+ onChange={(checked) =>+ setDraftField(+ 'categoricalPassingCategories',+ checked+ ? [...draft.categoricalPassingCategories, key]+ : draft.categoricalPassingCategories.filter(+ (category) => category !== key+ )+ )+ }+ />+ )+ })}+ </div>+ <p className="text-sm text-muted mb-0">+ Every selected category must be marked as passing. Existing results keep+ their scorer version's rule.+ </p>+ </LemonField.Pure>+ )}+ </>+ ) : (+ <>+ <LemonSwitch+ label="Set a passing rule"+ checked={draft.numericPassingEnabled}+ onChange={(value) => setDraftField('numericPassingEnabled', value)}+ disabledReason={disabledReason}+ data-attr="llma-scorer-numeric-passing-rule"+ />+ {draft.numericPassingEnabled && (+ <>+ <div className="grid gap-4 @min-[30rem]/scorer-form:grid-cols-2">+ <LemonField.Pure label="Pass when score is" htmlFor={`${id}-operator`}>+ <LemonSelect+ id={`${id}-operator`}+ value={draft.numericPassingOperator}+ options={[+ { value: 'gte', label: 'At least (≥)' },+ { value: 'lte', label: 'At most (≤)' },+ ]}+ onChange={(value) => setDraftField('numericPassingOperator', value)}+ disabledReason={disabledReason}+ data-attr="llma-scorer-numeric-operator"+ />+ </LemonField.Pure>+ <LemonField.Pure label="Threshold" htmlFor={`${id}-threshold`}>+ <LemonInput+ id={`${id}-threshold`}+ type="number"+ value={threshold}+ onChange={(value) =>+ setDraftField(+ 'numericPassingThreshold',+ formatNumericInputValue(value)+ )+ }+ min={getNumericInputValue(draft.numericMin)}+ max={getNumericInputValue(draft.numericMax)}+ step="any"+ placeholder="Enter a threshold"+ disabled={disabled}+ data-attr="llma-scorer-numeric-threshold"+ />+ </LemonField.Pure>+ </div>+ {threshold !== undefined && (+ <div className="flex flex-wrap gap-2" aria-label="Result preview">+ <LemonTag type="success" icon={<IconCheck />}>+ {`${draft.numericPassingOperator === 'gte' ? '≥' : '≤'} ${threshold} · Pass`}+ </LemonTag>+ <LemonTag type="danger" icon={<IconX />}>+ {`${draft.numericPassingOperator === 'gte' ? '<' : '>'} ${threshold} · Fail`}+ </LemonTag>+ </div>+ )}+ </>+ )}+ </>+ )}+ {draft.kind === 'numeric' && !draft.numericPassingEnabled && (+ <p className="text-sm text-muted mb-0">Scores stay neutral without a passing rule.</p>+ )}+ </section>+ </>+ )}+ </div>+ )+}diff --git a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionButton.tsx b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionButton.tsxdeleted file mode 100644index 8dd11362cf45..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionButton.tsx+++ /dev/null@@ -1,46 +0,0 @@-import { useActions, useValues } from 'kea'-import { useId } from 'react'--import { LemonButton } from '@posthog/lemon-ui'--import { AccessControlAction } from 'lib/components/AccessControlAction'--import { AccessControlLevel, AccessControlResourceType } from '~/types'--import type { ScoreDefinitionApi } from '../generated/api.schemas'-import { ScoreDefinitionVersionModal } from './ScoreDefinitionVersionModal'-import { scoreDefinitionVersionModalLogic } from './scoreDefinitionVersionModalLogic'--export function ScoreDefinitionVersionButton({- definition,- onSuccess,-}: {- definition: ScoreDefinitionApi- onSuccess?: (definition: ScoreDefinitionApi) => void-}): JSX.Element {- const instanceKey = useId()- const logic = scoreDefinitionVersionModalLogic({ instanceKey })- const { isOpen } = useValues(logic)- const { openModal, closeModal } = useActions(logic)-- return (- <>- <AccessControlAction- resourceType={AccessControlResourceType.LlmAnalytics}- minAccessLevel={AccessControlLevel.Editor}- >- <LemonButton size="small" onClick={openModal}>- Create new version- </LemonButton>- </AccessControlAction>- {isOpen && (- <ScoreDefinitionVersionModal- teamId={String(definition.team)}- scorerId={definition.id}- onClose={closeModal}- onSuccess={onSuccess}- />- )}- </>- )-}diff --git a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionModal.tsx b/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionModal.tsxdeleted file mode 100644index d7cff9b0711e..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/ScoreDefinitionVersionModal.tsx+++ /dev/null@@ -1,63 +0,0 @@-import { useActions, useMountedLogic, useValues } from 'kea'--import { LemonBanner, LemonButton, LemonModal, Spinner } from '@posthog/lemon-ui'--import { ScoreDefinitionVersionLogicProps, scoreDefinitionVersionLogic } from './scoreDefinitionVersionLogic'--export function ScoreDefinitionVersionModal(props: ScoreDefinitionVersionLogicProps): JSX.Element {- const logic = useMountedLogic(scoreDefinitionVersionLogic(props))- const { currentDefinition, currentDefinitionLoading, submitting, error } = useValues(logic)- const { submit, loadCurrentDefinition } = useActions(logic)-- return (- <LemonModal- isOpen- title="Create new scorer version"- onClose={props.onClose}- closable={!submitting}- maxWidth="32rem"- footer={- <>- <LemonButton- type="secondary"- onClick={props.onClose}- disabledReason={submitting ? 'Creating a version' : undefined}- >- Cancel- </LemonButton>- <LemonButton- type="primary"- onClick={submit}- loading={submitting}- disabledReason={- currentDefinitionLoading || !currentDefinition- ? 'Load the current version first'- : undefined- }- >- Create new version- </LemonButton>- </>- }- >- <div className="space-y-3">- <p>- Record a change to your external evaluator while keeping the scorer configuration exactly the same.- Use the new version ID for subsequent results.- </p>- {currentDefinitionLoading ? (- <Spinner />- ) : currentDefinition ? (- <p>- <strong>{currentDefinition.name}</strong>- <span> will use the configuration from version {currentDefinition.current_version}.</span>- </p>- ) : null}- {error && <LemonBanner type="error">{error}</LemonBanner>}- {!currentDefinition && !currentDefinitionLoading && (- <LemonButton onClick={() => loadCurrentDefinition()}>Try again</LemonButton>- )}- </div>- </LemonModal>- )-}diff --git a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.test.ts b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.test.tsindex d2fe03cbcba5..cece289f2934 100644--- a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.test.ts+++ b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.test.ts@@ -141,23 +141,6 @@ describe('aiObservabilityScoreDefinitionsLogic', () => {expect(logic.values.scoreDefinitionCountLabel).toBe('0 scorers')})- it('stores modal context in logic', async () => {- const logic = aiObservabilityScoreDefinitionsLogic()- logic.mount()-- await expectLogic(logic, () => {- logic.actions.openModal('metadata', mockScoreDefinition)- }).toFinishAllListeners()-- expect(logic.values.modalMode).toBe('metadata')- expect(logic.values.selectedDefinition).toEqual(mockScoreDefinition)-- logic.actions.closeModal()-- expect(logic.values.modalMode).toBeNull()- expect(logic.values.selectedDefinition).toBeNull()- })-it('archives through logic and reloads the list', async () => {const logic = aiObservabilityScoreDefinitionsLogic()logic.mount()diff --git a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.tsindex 9ef74ac72b72..15d94979f138 100644--- a/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts+++ b/products/ai_observability/frontend/scoreDefinitions/aiObservabilityScoreDefinitionsLogic.ts@@ -23,7 +23,7 @@ import type {PaginatedScoreDefinitionListApi,ScoreDefinitionApi,} from '../generated/api.schemas'-import { getApiErrorDetail, getCurrentProjectId, type ScoreDefinitionModalMode } from './scoreDefinitionModalUtils'+import { getApiErrorDetail, getCurrentProjectId } from './scoreDefinitionModalUtils'export const SCORE_DEFINITIONS_PER_PAGE = 30@@ -93,22 +93,17 @@ export interface aiObservabilityScoreDefinitionsLogicValues {count: numberfilters: ScoreDefinitionFiltersisArchivingDefinition: (definitionId: string) => boolean- modalMode: ScoreDefinitionModalMode | nullpagination: PaginationManualrawFilters: Partial<ScoreDefinitionFilters> | nullscoreDefinitionCountLabel: stringscoreDefinitions: PaginatedScoreDefinitionListApiscoreDefinitionsError: booleanscoreDefinitionsLoading: boolean- selectedDefinition: ScoreDefinitionApi | nullsorting: Sorting | null}// Generated by kea-typegen. Update if you're an agent, ignore if you're human.export interface aiObservabilityScoreDefinitionsLogicActions {- closeModal: () => {- value: true- }loadScoreDefinitions: (debounce?: boolean) => {debounce: boolean}@@ -130,13 +125,7 @@ export interface aiObservabilityScoreDefinitionsLogicActions {debounce: boolean}}- openModal: (- mode: ScoreDefinitionModalMode,- scoreDefinition?: ScoreDefinitionApi | null- ) => {- mode: ScoreDefinitionModalMode- scoreDefinition: ScoreDefinitionApi | null- }+resetForTeam: () => {value: true}@@ -197,11 +186,6 @@ export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefidebounce,}),loadScoreDefinitions: (debounce: boolean = true) => ({ debounce }),- openModal: (mode: ScoreDefinitionModalMode, scoreDefinition: ScoreDefinitionApi | null = null) => ({- mode,- scoreDefinition,- }),- closeModal: true,resetForTeam: true,toggleArchive: (scoreDefinition: ScoreDefinitionApi) => ({ scoreDefinition }),toggleArchiveSuccess: (definitionId: string) => ({ definitionId }),@@ -225,20 +209,6 @@ export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefi}),},],- modalMode: [- null as ScoreDefinitionModalMode | null,- {- openModal: (_, { mode }) => mode,- closeModal: () => null,- },- ],- selectedDefinition: [- null as ScoreDefinitionApi | null,- {- openModal: (_, { scoreDefinition }) => scoreDefinition,- closeModal: () => null,- },- ],archivingDefinitionIds: [new Set<string>(),{@@ -412,7 +382,6 @@ export const aiObservabilityScoreDefinitionsLogic = kea<aiObservabilityScoreDefi// initial load waits for bootstrap instead of throwing "Team ID is not known.".subscriptions(({ actions }) => ({currentTeamId: (currentTeamId: number | null) => {- actions.closeModal()actions.resetForTeam()if (currentTeamId) {actions.loadScoreDefinitions(false)diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionConfigUtils.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionConfigUtils.tsindex 6acd25513ef3..a641b89da79a 100644--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionConfigUtils.ts+++ b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionConfigUtils.ts@@ -25,9 +25,15 @@ export function getCategoricalConfig(config: ScoreDefinitionConfig): Categorical}export function getNumericConfig(config: ScoreDefinitionConfig): NumericScoreDefinitionConfig {- return isRecord(config) && ('min' in config || 'max' in config || 'step' in config) ? config : {}+ return isRecord(config) &&+ !isCategoricalConfig(config) &&+ ('min' in config || 'max' in config || 'step' in config || 'passing_rule' in config)+ ? config+ : {}}export function getBooleanConfig(config: ScoreDefinitionConfig): BooleanScoreDefinitionConfig {- return isRecord(config) && ('true_label' in config || 'false_label' in config) ? config : {}+ return isRecord(config) && ('true_label' in config || 'false_label' in config || 'true_is_failure' in config)+ ? config+ : {}}diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.tsdeleted file mode 100644index eb06bc6f0e2c..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.test.ts+++ /dev/null@@ -1,145 +0,0 @@-import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'--import { expectLogic } from 'kea-test-utils'--import { initKeaTests } from '~/test/init'--import {- llmAnalyticsScoreDefinitionsCreate as aiObservabilityScoreDefinitionsCreate,- llmAnalyticsScoreDefinitionsList as aiObservabilityScoreDefinitionsList,-} from '../generated/api'-import type { ScoreDefinitionApi as ScoreDefinition } from '../generated/api.schemas'-import { aiObservabilityScoreDefinitionsLogic } from './aiObservabilityScoreDefinitionsLogic'-import { scoreDefinitionModalLogic } from './scoreDefinitionModalLogic'-jest.mock('../generated/api', () => ({- llmAnalyticsScoreDefinitionsList: jest.fn(),- llmAnalyticsScoreDefinitionsCreate: jest.fn(),- llmAnalyticsScoreDefinitionsNewVersionCreate: jest.fn(),- llmAnalyticsScoreDefinitionsPartialUpdate: jest.fn(),-}))--const mockAIObservabilityScoreDefinitionsList = aiObservabilityScoreDefinitionsList as jest.MockedFunction<- typeof aiObservabilityScoreDefinitionsList->-const mockAIObservabilityScoreDefinitionsCreate = aiObservabilityScoreDefinitionsCreate as jest.MockedFunction<- typeof aiObservabilityScoreDefinitionsCreate->--const mockScoreDefinition: ScoreDefinition = {- id: 'score_def_1',- name: 'Quality',- description: 'Reusable quality scorer',- kind: 'categorical',- archived: false,- current_version: 2,- current_version_id: null,- config: {- options: [- { key: 'good', label: 'Good' },- { key: 'bad', label: 'Bad' },- ],- },- created_by: null,- created_at: '2026-03-11T00:00:00Z',- updated_at: '2026-03-11T00:00:00Z',- team: MOCK_DEFAULT_TEAM.id,-}--describe('scoreDefinitionModalLogic', () => {- beforeEach(() => {- initKeaTests()- jest.resetAllMocks()- mockAIObservabilityScoreDefinitionsList.mockResolvedValue({- results: [mockScoreDefinition],- count: 1,- next: null,- previous: null,- })- mockAIObservabilityScoreDefinitionsCreate.mockResolvedValue(mockScoreDefinition)- })-- it('submits a create flow and closes the modal via the parent logic', async () => {- const listLogic = aiObservabilityScoreDefinitionsLogic()- listLogic.mount()-- await expectLogic(listLogic).toFinishAllListeners()-- listLogic.actions.openModal('create')-- const modalLogic = scoreDefinitionModalLogic({- mode: 'create',- scoreDefinition: null,- })- modalLogic.mount()-- modalLogic.actions.setDraftField('name', 'New quality scorer')-- await expectLogic(modalLogic, () => {- modalLogic.actions.submit()- }).toFinishAllListeners()-- expect(mockAIObservabilityScoreDefinitionsCreate).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {- name: 'New quality scorer',- description: '',- kind: 'categorical',- config: {- options: [- { key: 'good', label: 'Good' },- { key: 'bad', label: 'Bad' },- ],- },- })- expect(mockAIObservabilityScoreDefinitionsList).toHaveBeenCalledTimes(2)- expect(listLogic.values.modalMode).toBeNull()- expect(modalLogic.values.submitting).toBe(false)- })-- it('stores the modal draft in logic', async () => {- const modalLogic = scoreDefinitionModalLogic({- mode: 'create',- scoreDefinition: null,- })- modalLogic.mount()-- modalLogic.actions.setDraftField('name', 'Hallucination')- modalLogic.actions.setDraftField('kind', 'boolean')- modalLogic.actions.setDraftField('trueLabel', 'Hallucinated')- modalLogic.actions.addOption()- modalLogic.actions.updateOptionLabel(0, 'Helpful')- modalLogic.actions.removeOption(2)-- expect(modalLogic.values.draft.name).toBe('Hallucination')- expect(modalLogic.values.draft.kind).toBe('boolean')- expect(modalLogic.values.draft.trueLabel).toBe('Hallucinated')- expect(modalLogic.values.draft.options).toEqual([- { key: 'good', label: 'Helpful' },- { key: 'bad', label: 'Bad' },- ])- })-- it('initializes edit config from the saved scorer config', () => {- const customOptions = [- { key: 'animals', label: 'Animals' },- { key: 'finance', label: 'Finance' },- { key: 'science', label: 'Science' },- ]- const modalLogic = scoreDefinitionModalLogic({- mode: 'config',- scoreDefinition: {- ...mockScoreDefinition,- config: {- options: customOptions,- selection_mode: 'multiple',- min_selections: 1,- max_selections: 2,- },- },- })- modalLogic.mount()-- expect(modalLogic.values.draft.options).toEqual(customOptions)- expect(modalLogic.values.draft.selectionMode).toBe('multiple')- expect(modalLogic.values.draft.categoricalMinSelections).toBe('1')- expect(modalLogic.values.draft.categoricalMaxSelections).toBe('2')- })-})diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.tsdeleted file mode 100644index a4f2b7b96c76..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalLogic.ts+++ /dev/null@@ -1,223 +0,0 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'--import { lemonToast } from '~/lib/lemon-ui/LemonToast/LemonToast'--import {- llmAnalyticsScoreDefinitionsCreate as aiObservabilityScoreDefinitionsCreate,- llmAnalyticsScoreDefinitionsNewVersionCreate as aiObservabilityScoreDefinitionsNewVersionCreate,- llmAnalyticsScoreDefinitionsPartialUpdate as aiObservabilityScoreDefinitionsPartialUpdate,-} from '../generated/api'-import type { ScoreDefinitionApi } from '../generated/api.schemas'-import type { CategoricalScoreOptionApi } from '../generated/api.schemas'-import { aiObservabilityScoreDefinitionsLogic } from './aiObservabilityScoreDefinitionsLogic'-import {- createDraft,- buildConfigFromDraft,- getApiErrorDetail,- getCurrentProjectId,- getModalTitle,- type ScoreDefinitionDraft,- type ScoreDefinitionModalMode,- validateDraft,-} from './scoreDefinitionModalUtils'--export interface ScoreDefinitionModalLogicProps {- mode: ScoreDefinitionModalMode- scoreDefinition: ScoreDefinitionApi | null-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionModalLogicValues {- draft: ScoreDefinitionDraft- isConfigMode: boolean- isCreateMode: boolean- isMetadataMode: boolean- submitting: boolean- title: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionModalLogicActions {- addOption: () => {- value: true- }- beginSubmit: () => {- value: true- }- initializeDraft: (draft: ScoreDefinitionDraft) => {- draft: ScoreDefinitionDraft- }- removeOption: (index: number) => {- index: number- }- setDraftField: (- field: keyof ScoreDefinitionDraft,- value: ScoreDefinitionDraft[keyof ScoreDefinitionDraft]- ) => {- field: keyof ScoreDefinitionDraft- value: string | CategoricalScoreOptionApi[]- }- submit: () => {- value: true- }- submitFailure: () => {- value: true- }- submitSuccess: () => {- value: true- }- updateOptionLabel: (- index: number,- value: string- ) => {- index: number- value: string- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionModalLogicMeta {- key: string- __keaTypeGenInternalSelectorTypes: {- isCreateMode: (arg: any) => boolean- isMetadataMode: (arg: any) => boolean- isConfigMode: (arg: any) => boolean- title: (arg: any) => string- }-}--export type scoreDefinitionModalLogicType = MakeLogicType<- scoreDefinitionModalLogicValues,- scoreDefinitionModalLogicActions,- ScoreDefinitionModalLogicProps,- scoreDefinitionModalLogicMeta->--export const scoreDefinitionModalLogic = kea<scoreDefinitionModalLogicType>([- path(['products', 'ai_observability', 'frontend', 'scoreDefinitions', 'scoreDefinitionModalLogic']),- props({} as ScoreDefinitionModalLogicProps),- key((props) => `${props.mode}-${props.scoreDefinition?.id ?? 'new'}`),-- actions({- submit: true,- beginSubmit: true,- submitSuccess: true,- submitFailure: true,- initializeDraft: (draft: ScoreDefinitionDraft) => ({ draft }),- setDraftField: (- field: keyof ScoreDefinitionDraft,- value: ScoreDefinitionDraft[keyof ScoreDefinitionDraft]- ) => ({- field,- value,- }),- updateOptionLabel: (index: number, value: string) => ({ index, value }),- addOption: true,- removeOption: (index: number) => ({ index }),- }),-- reducers({- draft: [- ({ mode, scoreDefinition }: ScoreDefinitionModalLogicProps) => createDraft(mode, scoreDefinition),- {- initializeDraft: (_, { draft }) => draft,- setDraftField: (state, { field, value }) => ({- ...state,- [field]: value,- }),- updateOptionLabel: (state, { index, value }) => ({- ...state,- options: state.options.map((option, optionIndex) =>- optionIndex === index ? { ...option, label: value } : option- ),- }),- addOption: (state) => ({- ...state,- options: [...state.options, { key: '', label: '' }],- }),- removeOption: (state, { index }) => ({- ...state,- options: state.options.filter((_, optionIndex) => optionIndex !== index),- }),- },- ],- submitting: [- false,- {- beginSubmit: () => true,- submitSuccess: () => false,- submitFailure: () => false,- },- ],- }),-- selectors({- isCreateMode: [() => [(_, props) => props.mode], (mode): boolean => mode === 'create' || mode === 'duplicate'],- isMetadataMode: [() => [(_, props) => props.mode], (mode): boolean => mode === 'metadata'],- isConfigMode: [() => [(_, props) => props.mode], (mode): boolean => mode === 'config'],- title: [() => [(_, props) => props.mode], (mode): string => getModalTitle(mode)],- }),-- afterMount(({ actions, props }) => {- actions.initializeDraft(createDraft(props.mode, props.scoreDefinition))- }),-- listeners(({ actions, values, props }) => ({- submit: async () => {- const draft = values.draft- const validationError = validateDraft(props.mode, draft)- if (validationError) {- lemonToast.error(validationError)- actions.submitFailure()- return- }-- actions.beginSubmit()-- try {- const config = buildConfigFromDraft(draft)-- if (values.isCreateMode) {- await aiObservabilityScoreDefinitionsCreate(getCurrentProjectId(), {- name: draft.name.trim(),- description: draft.description.trim(),- kind: draft.kind,- config,- })- lemonToast.success(props.mode === 'duplicate' ? 'Scorer duplicated.' : 'Scorer created.')- } else if (values.isMetadataMode && props.scoreDefinition) {- await aiObservabilityScoreDefinitionsPartialUpdate(- getCurrentProjectId(),- props.scoreDefinition.id,- {- name: draft.name.trim(),- description: draft.description.trim(),- }- )- lemonToast.success('Scorer metadata updated.')- } else if (values.isConfigMode && props.scoreDefinition) {- await aiObservabilityScoreDefinitionsNewVersionCreate(- getCurrentProjectId(),- props.scoreDefinition.id,- {- config,- }- )- lemonToast.success('Scorer version created.')- } else {- lemonToast.error('Failed to save scorer.')- actions.submitFailure()- return- }-- actions.submitSuccess()- const listLogic = aiObservabilityScoreDefinitionsLogic()- listLogic.actions.loadScoreDefinitions(false)- listLogic.actions.closeModal()- } catch (error) {- lemonToast.error(getApiErrorDetail(error) || 'Failed to save scorer.')- actions.submitFailure()- }- },- })),-])diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.test.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.test.tsnew file mode 100644index 000000000000..6616dcd06d57--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.test.ts@@ -0,0 +1,123 @@+import type { ScoreDefinitionApi, ScoreDefinitionConfigApi } from '../generated/api.schemas'+import { buildConfigFromDraft, createDraft, validateDraft } from './scoreDefinitionModalUtils'++const definition: ScoreDefinitionApi = {+ id: 'scorer-example',+ name: 'Answer quality',+ description: '',+ kind: 'boolean',+ config: {},+ archived: false,+ current_version: 1,+ current_version_id: 'version-example',+ team: 1,+ created_by: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: '2026-01-01T00:00:00Z',+}++describe('scorer form configuration', () => {+ it.each([+ ['single', [], 'Choose at least one passing category.'],+ ['single', ['missing'], 'Choose passing categories from the configured options.'],+ ['single', ['good'], undefined],+ ['multiple', [], undefined],+ ] as const)('validates categorical passing rules for %s with %j', (selectionMode, categories, error) => {+ const draft = {+ ...createDraft('create'),+ name: 'Quality',+ selectionMode,+ categoricalPassingEnabled: true,+ categoricalPassingCategories: [...categories],+ }+ expect(validateDraft('create', draft)).toBe(error)+ expect(buildConfigFromDraft({ ...draft, categoricalPassingEnabled: false })).not.toHaveProperty('passing_rule')+ })++ it.each<{ kind: ScoreDefinitionApi['kind']; config: ScoreDefinitionConfigApi }>([+ {+ kind: 'categorical',+ config: { options: [{ key: 'good', label: 'Good' }], passing_rule: { categories: ['good'] } },+ },+ { kind: 'boolean', config: { true_is_failure: false } },+ { kind: 'boolean', config: { true_is_failure: true } },+ { kind: 'boolean', config: { true_label: 'Flagged', false_label: 'Clear', true_is_failure: true } },+ { kind: 'numeric', config: { passing_rule: { operator: 'gte', threshold: 0 } } },+ { kind: 'numeric', config: { passing_rule: { operator: 'lte', threshold: -1 } } },+ ])('preserves $kind configuration on edit and duplication: $config', ({ kind, config }) => {+ for (const mode of ['config', 'duplicate'] as const) {+ expect(buildConfigFromDraft(createDraft(mode, { ...definition, kind, config }))).toEqual(config)+ }+ })++ it.each([{}, { true_is_failure: null }])('defaults legacy boolean polarity to true passing: %j', (config) => {+ for (const mode of ['config', 'duplicate'] as const) {+ const existing = createDraft(mode, { ...definition, config })+ expect(existing.booleanPassing).toBe('true')+ expect(buildConfigFromDraft(existing)).toEqual({ true_is_failure: false })+ }++ const created = { ...createDraft('create'), kind: 'boolean' as const }+ expect(buildConfigFromDraft(created)).toEqual({+ true_label: 'True',+ false_label: 'False',+ true_is_failure: false,+ })+ })++ it.each([+ { numericPassingThreshold: '', error: 'Enter a valid number for the passing threshold.' },+ { numericPassingThreshold: 'Infinity', error: 'Enter a valid number for the passing threshold.' },+ { numericPassingThreshold: '-1', error: 'Set the passing threshold within the score bounds.' },+ { numericPassingThreshold: '11', error: 'Set the passing threshold within the score bounds.' },+ { numericPassingThreshold: '0', error: undefined },+ { numericPassingThreshold: '10', error: undefined },+ ])('validates enabled passing threshold $numericPassingThreshold', ({ numericPassingThreshold, error }) => {+ const draft = {+ ...createDraft('config', definition),+ kind: 'numeric' as const,+ numericMin: '0',+ numericMax: '10',+ numericPassingEnabled: true,+ numericPassingThreshold,+ }+ expect(validateDraft('config', draft)).toBe(error)+ expect(validateDraft('config', { ...draft, numericPassingEnabled: false })).toBeUndefined()+ expect(buildConfigFromDraft({ ...draft, numericPassingEnabled: false })).toEqual({ min: 0, max: 10 })+ })++ it.each([+ {+ categoricalMinSelections: '0',+ categoricalMaxSelections: '',+ error: 'Minimum selections must be at least 1.',+ },+ {+ categoricalMinSelections: '',+ categoricalMaxSelections: '0',+ error: 'Maximum selections must be at least 1.',+ },+ { categoricalMinSelections: '1', categoricalMaxSelections: '1', error: undefined },+ { categoricalMinSelections: '', categoricalMaxSelections: '', error: undefined },+ ])(+ 'validates multiple selection bounds min=$categoricalMinSelections max=$categoricalMaxSelections',+ ({ categoricalMinSelections, categoricalMaxSelections, error }) => {+ const draft = {+ ...createDraft('config', {+ ...definition,+ kind: 'categorical',+ config: {+ options: [+ { key: 'good', label: 'Good' },+ { key: 'bad', label: 'Bad' },+ ],+ },+ }),+ selectionMode: 'multiple' as const,+ categoricalMinSelections,+ categoricalMaxSelections,+ }+ expect(validateDraft('config', draft)).toBe(error)+ }+ )+})diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.tsindex 0f5969e95c36..0b2d218d2bf3 100644--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.ts+++ b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionModalUtils.ts@@ -22,11 +22,17 @@ export interface ScoreDefinitionDraft {selectionMode: CategoricalSelectionModecategoricalMinSelections: stringcategoricalMaxSelections: string+ categoricalPassingEnabled: boolean+ categoricalPassingCategories: string[]numericMin: stringnumericMax: stringnumericStep: string+ numericPassingEnabled: boolean+ numericPassingOperator: 'gte' | 'lte'+ numericPassingThreshold: stringtrueLabel: stringfalseLabel: string+ booleanPassing: 'true' | 'false'}export const CATEGORICAL_SELECTION_MODE_OPTIONS: { label: string; value: CategoricalSelectionMode }[] = [@@ -34,8 +40,8 @@ export const CATEGORICAL_SELECTION_MODE_OPTIONS: { label: string; value: Categor{ label: 'Multi-select', value: 'multiple' },]-const DEFAULT_BOOLEAN_TRUE_LABEL = 'Good'-const DEFAULT_BOOLEAN_FALSE_LABEL = 'Bad'+const DEFAULT_BOOLEAN_TRUE_LABEL = 'True'+const DEFAULT_BOOLEAN_FALSE_LABEL = 'False'export function formatKindLabel(kind: ScoreDefinitionKind): string {if (kind === 'categorical') {@@ -65,6 +71,10 @@ function suggestKey(value: string): string {.replace(/^_+|_+$/g, '')}+export function getScoreDefinitionOptionKey(option: ScoreDefinitionOption): string {+ return option.key.trim() || suggestKey(option.label)+}+export function getCurrentProjectId(): string {return String(ApiConfig.getCurrentTeamId())}@@ -150,6 +160,8 @@ export function createDraft(kind,options: defaultOptions,selectionMode: categoricalConfig.selection_mode || 'single',+ categoricalPassingEnabled: categoricalConfig.passing_rule != null,+ categoricalPassingCategories: categoricalConfig.passing_rule?.categories ?? [],categoricalMinSelections:categoricalConfig.min_selections === undefined || categoricalConfig.min_selections === null? ''@@ -161,8 +173,12 @@ export function createDraft(numericMin: numericConfig.min === undefined || numericConfig.min === null ? '' : String(numericConfig.min),numericMax: numericConfig.max === undefined || numericConfig.max === null ? '' : String(numericConfig.max),numericStep: numericConfig.step === undefined || numericConfig.step === null ? '' : String(numericConfig.step),- trueLabel: booleanConfig.true_label || DEFAULT_BOOLEAN_TRUE_LABEL,- falseLabel: booleanConfig.false_label || DEFAULT_BOOLEAN_FALSE_LABEL,+ numericPassingEnabled: numericConfig.passing_rule != null,+ numericPassingOperator: numericConfig.passing_rule?.operator ?? 'gte',+ numericPassingThreshold: numericConfig.passing_rule == null ? '' : String(numericConfig.passing_rule.threshold),+ trueLabel: booleanConfig.true_label ?? (baseDefinition ? '' : DEFAULT_BOOLEAN_TRUE_LABEL),+ falseLabel: booleanConfig.false_label ?? (baseDefinition ? '' : DEFAULT_BOOLEAN_FALSE_LABEL),+ booleanPassing: booleanConfig.true_is_failure ? 'false' : 'true',}}@@ -170,7 +186,7 @@ export function buildConfigFromDraft(draft: ScoreDefinitionDraft): ScoreDefinitiif (draft.kind === 'categorical') {const categoricalConfig: CategoricalScoreDefinitionConfig = {options: draft.options.map((option) => ({- key: option.key.trim() || suggestKey(option.label),+ key: getScoreDefinitionOptionKey(option),label: option.label.trim(),})),}@@ -190,6 +206,9 @@ export function buildConfigFromDraft(draft: ScoreDefinitionDraft): ScoreDefiniti}}+ if (draft.categoricalPassingEnabled) {+ categoricalConfig.passing_rule = { categories: [...draft.categoricalPassingCategories].sort() }+ }return categoricalConfig}@@ -208,6 +227,12 @@ export function buildConfigFromDraft(draft: ScoreDefinitionDraft): ScoreDefinitiif (step !== null) {numericConfig.step = step}+ if (draft.numericPassingEnabled) {+ numericConfig.passing_rule = {+ operator: draft.numericPassingOperator,+ threshold: parseOptionalNumber(draft.numericPassingThreshold) ?? NaN,+ }+ }return numericConfig}@@ -219,6 +244,7 @@ export function buildConfigFromDraft(draft: ScoreDefinitionDraft): ScoreDefinitiif (draft.falseLabel.trim()) {booleanConfig.false_label = draft.falseLabel.trim()}+ booleanConfig.true_is_failure = draft.booleanPassing === 'false'return booleanConfig}@@ -255,6 +281,15 @@ export function validateDraft(mode: ScoreDefinitionModalMode, draft: ScoreDefinioptionKeys.add(normalizedKey)}+ if (draft.categoricalPassingEnabled) {+ if (draft.selectionMode === 'single' && draft.categoricalPassingCategories.length === 0) {+ return 'Choose at least one passing category.'+ }+ if (draft.categoricalPassingCategories.some((key) => !optionKeys.has(key))) {+ return 'Choose passing categories from the configured options.'+ }+ }+if (draft.selectionMode === 'multiple') {const selectionValues = [draft.categoricalMinSelections, draft.categoricalMaxSelections]if (selectionValues.some((value) => value.trim() && Number.isNaN(parseOptionalInteger(value)))) {@@ -264,6 +299,14 @@ export function validateDraft(mode: ScoreDefinitionModalMode, draft: ScoreDefiniconst minimum = parseOptionalInteger(draft.categoricalMinSelections)const maximum = parseOptionalInteger(draft.categoricalMaxSelections)+ if (minimum !== null && minimum < 1) {+ return 'Minimum selections must be at least 1.'+ }++ if (maximum !== null && maximum < 1) {+ return 'Maximum selections must be at least 1.'+ }+if (minimum !== null && minimum > draft.options.length) {return 'Minimum selections cannot exceed the number of options.'}@@ -289,6 +332,19 @@ export function validateDraft(mode: ScoreDefinitionModalMode, draft: ScoreDefiniif (minimum !== null && maximum !== null && minimum > maximum) {return 'Numeric max must be greater than or equal to min.'}+ const step = parseOptionalNumber(draft.numericStep)+ if (step !== null && step <= 0) {+ return 'Set the increment to a number greater than zero.'+ }+ if (draft.numericPassingEnabled) {+ const threshold = parseOptionalNumber(draft.numericPassingThreshold)+ if (threshold === null || !Number.isFinite(threshold)) {+ return 'Enter a valid number for the passing threshold.'+ }+ if ((minimum !== null && threshold < minimum) || (maximum !== null && threshold > maximum)) {+ return 'Set the passing threshold within the score bounds.'+ }+ }}return undefineddiff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.test.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.test.tsdeleted file mode 100644index da122c1a0d96..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.test.ts+++ /dev/null@@ -1,120 +0,0 @@-import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'--import { expectLogic } from 'kea-test-utils'--import { initKeaTests } from '~/test/init'--import { llmAnalyticsScoreDefinitionsNewVersionCreate, llmAnalyticsScoreDefinitionsRetrieve } from '../generated/api'-import type { ScoreDefinitionApi, ScoreDefinitionConfigApi } from '../generated/api.schemas'-import { scoreDefinitionVersionLogic } from './scoreDefinitionVersionLogic'--jest.mock('../generated/api', () => ({- llmAnalyticsScoreDefinitionsRetrieve: jest.fn(),- llmAnalyticsScoreDefinitionsNewVersionCreate: jest.fn(),-}))--const retrieve = jest.mocked(llmAnalyticsScoreDefinitionsRetrieve)-const createVersion = jest.mocked(llmAnalyticsScoreDefinitionsNewVersionCreate)-const definition: ScoreDefinitionApi = {- id: 'scorer-1',- name: 'Quality',- description: '',- kind: 'numeric',- archived: false,- current_version: 2,- current_version_id: 'version-2',- config: {},- created_by: null,- created_at: '2026-01-01T00:00:00Z',- updated_at: null,- team: MOCK_DEFAULT_TEAM.id,-}--describe('scoreDefinitionVersionLogic', () => {- beforeEach(() => {- initKeaTests()- jest.resetAllMocks()- })-- it.each<ScoreDefinitionConfigApi>([- { min: 0, max: null },- { true_label: '', false_label: 'Needs work' },- { options: [{ key: 'ok', label: 'Acceptable' }], selection_mode: 'multiple', min_selections: 0 },- ])('preserves exact configuration when creating a version: %j', async (config) => {- retrieve.mockResolvedValue({ ...definition, config })- createVersion.mockResolvedValue({ ...definition, config, current_version: 3 })- const onClose = jest.fn()- const onSuccess = jest.fn()- const logic = scoreDefinitionVersionLogic({- teamId: String(MOCK_DEFAULT_TEAM.id),- scorerId: definition.id,- onClose,- onSuccess,- })- logic.mount()- await expectLogic(logic).toFinishAllListeners()-- await expectLogic(logic, () => logic.actions.submit()).toFinishAllListeners()-- expect(createVersion).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {- config,- base_version: 2,- })- expect(onSuccess).toHaveBeenCalledWith(expect.objectContaining({ current_version: 3 }))- expect(onClose).toHaveBeenCalledTimes(1)- })-- it('requires another confirmation after a concurrent version change', async () => {- retrieve- .mockResolvedValueOnce(definition)- .mockResolvedValueOnce({ ...definition, current_version: 3, config: { min: 0, max: 5 } })- createVersion.mockRejectedValueOnce({ status: 409 })- const onClose = jest.fn()- const logic = scoreDefinitionVersionLogic({- teamId: String(MOCK_DEFAULT_TEAM.id),- scorerId: definition.id,- onClose,- })- logic.mount()- await expectLogic(logic).toFinishAllListeners()-- await expectLogic(logic, () => logic.actions.submit()).toFinishAllListeners()-- expect(createVersion).toHaveBeenCalledTimes(1)- expect(onClose).not.toHaveBeenCalled()- expect(logic.values.currentDefinition?.current_version).toBe(3)- expect(logic.values.error).toContain('confirm again')- expect(logic.values.submitting).toBe(false)-- createVersion.mockResolvedValue({ ...definition, current_version: 4 })- await expectLogic(logic, () => logic.actions.submit()).toFinishAllListeners()- expect(createVersion).toHaveBeenLastCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {- config: { min: 0, max: 5 },- base_version: 3,- })- })-- it('ignores a second confirmation while the first request is pending', async () => {- retrieve.mockResolvedValue(definition)- let resolve: (value: ScoreDefinitionApi) => void = () => {}- createVersion.mockImplementation(- () =>- new Promise((done) => {- resolve = done- })- )- const logic = scoreDefinitionVersionLogic({- teamId: String(MOCK_DEFAULT_TEAM.id),- scorerId: definition.id,- onClose: jest.fn(),- })- logic.mount()- await expectLogic(logic).toFinishAllListeners()- logic.actions.submit()- logic.actions.submit()- expect(createVersion).toHaveBeenCalledTimes(1)- resolve({ ...definition, current_version: 3 })- await expectLogic(logic).toFinishAllListeners()- expect(logic.values.submitting).toBe(false)- })-})diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.tsdeleted file mode 100644index 9ba423bcedfd..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionLogic.ts+++ /dev/null@@ -1,149 +0,0 @@-import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers } from 'kea'-import { loaders } from 'kea-loaders'--import { lemonToast } from 'lib/lemon-ui/LemonToast'--import { llmAnalyticsScoreDefinitionsNewVersionCreate, llmAnalyticsScoreDefinitionsRetrieve } from '../generated/api'-import type { ScoreDefinitionApi } from '../generated/api.schemas'-import { getApiErrorDetail, getCurrentProjectId } from './scoreDefinitionModalUtils'--export interface ScoreDefinitionVersionLogicProps {- teamId: string- scorerId: string- onClose: () => void- onSuccess?: (definition: ScoreDefinitionApi) => void-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionLogicValues {- currentDefinition: ScoreDefinitionApi | null- currentDefinitionLoading: boolean- error: string | null- submitting: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionLogicActions {- beginSubmit: () => {- value: true- }- finishSubmit: () => {- value: true- }- loadCurrentDefinition: () => {- value: true- }- loadCurrentDefinitionFailure: (- error: string,- errorObject?: any- ) => {- error: string- errorObject?: any- }- loadCurrentDefinitionSuccess: (- currentDefinition: ScoreDefinitionApi | null,- payload?: {- value: true- }- ) => {- currentDefinition: ScoreDefinitionApi | null- payload?: {- value: true- }- }- setError: (error: string | null) => {- error: string | null- }- submit: () => {- value: true- }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionLogicMeta {- key: string-}--export type scoreDefinitionVersionLogicType = MakeLogicType<- scoreDefinitionVersionLogicValues,- scoreDefinitionVersionLogicActions,- ScoreDefinitionVersionLogicProps,- scoreDefinitionVersionLogicMeta->--export const scoreDefinitionVersionLogic = kea<scoreDefinitionVersionLogicType>([- path(['products', 'ai_observability', 'frontend', 'scoreDefinitions', 'scoreDefinitionVersionLogic']),- props({} as ScoreDefinitionVersionLogicProps),- key((props: ScoreDefinitionVersionLogicProps) => `${props.teamId}-${props.scorerId}`),- actions({- loadCurrentDefinition: true,- submit: true,- beginSubmit: true,- finishSubmit: true,- setError: (error: string | null) => ({ error }),- }),- loaders(({ props }) => ({- currentDefinition: [- null as ScoreDefinitionApi | null,- {- loadCurrentDefinition: async (_, breakpoint): Promise<ScoreDefinitionApi | null> => {- const definition = await llmAnalyticsScoreDefinitionsRetrieve(props.teamId, props.scorerId)- breakpoint()- return props.teamId === getCurrentProjectId() ? definition : null- },- },- ],- })),- reducers({- currentDefinition: [null as ScoreDefinitionApi | null, { loadCurrentDefinition: () => null }],- submitting: [false, { beginSubmit: () => true, finishSubmit: () => false }],- error: [- null as string | null,- {- setError: (_, { error }) => error,- loadCurrentDefinition: () => null,- loadCurrentDefinitionFailure: () => 'Could not load the current scorer version. Try again.',- },- ],- }),- listeners(({ actions, asyncActions, props, values }) => ({- submit: async (_, breakpoint) => {- if (- values.submitting ||- values.currentDefinitionLoading ||- !values.currentDefinition ||- props.teamId !== getCurrentProjectId()- ) {- return- }- const definition = values.currentDefinition- const teamId = props.teamId- actions.beginSubmit()- actions.setError(null)- try {- const updated = await llmAnalyticsScoreDefinitionsNewVersionCreate(teamId, props.scorerId, {- config: definition.config,- base_version: definition.current_version,- })- breakpoint()- if (getCurrentProjectId() !== teamId) {- return- }- lemonToast.success(`Created scorer version ${updated.current_version}.`)- props.onSuccess?.(updated)- props.onClose()- } catch (error) {- breakpoint()- if (typeof error === 'object' && error !== null && 'status' in error && error.status === 409) {- await asyncActions.loadCurrentDefinition()- actions.setError('The current version changed. Review the new source version and confirm again.')- } else {- actions.setError(getApiErrorDetail(error) || 'Could not create a new version. Try again.')- }- } finally {- actions.finishSubmit()- }- },- })),- afterMount(({ actions }) => actions.loadCurrentDefinition()),-])diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.test.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.test.tsdeleted file mode 100644index 87960e26ca60..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.test.ts+++ /dev/null@@ -1,31 +0,0 @@-import { initKeaTests } from '~/test/init'--import { scoreDefinitionVersionModalLogic } from './scoreDefinitionVersionModalLogic'--describe('scoreDefinitionVersionModalLogic', () => {- beforeEach(() => initKeaTests())-- it('keeps launchers independent and closes the modal when its launcher unmounts', () => {- const first = scoreDefinitionVersionModalLogic({ instanceKey: 'list-row' })- const second = scoreDefinitionVersionModalLogic({ instanceKey: 'history-button' })- const unmountFirst = first.mount()- const unmountSecond = second.mount()-- first.actions.openModal()- expect(first.values.isOpen).toBe(true)- expect(second.values.isOpen).toBe(false)-- second.actions.openModal()- first.actions.closeModal()- expect(first.values.isOpen).toBe(false)- expect(second.values.isOpen).toBe(true)-- unmountSecond()- const remounted = scoreDefinitionVersionModalLogic({ instanceKey: 'history-button' })- const unmountRemounted = remounted.mount()- expect(remounted.values.isOpen).toBe(false)-- unmountFirst()- unmountRemounted()- })-})diff --git a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.ts b/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.tsdeleted file mode 100644index abd238e226a1..000000000000--- a/products/ai_observability/frontend/scoreDefinitions/scoreDefinitionVersionModalLogic.ts+++ /dev/null@@ -1,49 +0,0 @@-import { LogicWrapper, MakeLogicType, actions, kea, key, path, props, reducers } from 'kea'--export interface ScoreDefinitionVersionModalLogicProps {- instanceKey: string-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionModalLogicValues {- isOpen: boolean-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionModalLogicActions {- closeModal: () => { value: true }- openModal: () => { value: true }-}--// Generated by kea-typegen. Update if you're an agent, ignore if you're human.-export interface scoreDefinitionVersionModalLogicMeta {- key: string-}--export type scoreDefinitionVersionModalLogicType = MakeLogicType<- scoreDefinitionVersionModalLogicValues,- scoreDefinitionVersionModalLogicActions,- ScoreDefinitionVersionModalLogicProps,- scoreDefinitionVersionModalLogicMeta->--export const scoreDefinitionVersionModalLogic: LogicWrapper<scoreDefinitionVersionModalLogicType> =- kea<scoreDefinitionVersionModalLogicType>([- props({} as ScoreDefinitionVersionModalLogicProps),- key(({ instanceKey }) => instanceKey),- path((key) => [- 'products',- 'ai_observability',- 'frontend',- 'scoreDefinitions',- 'scoreDefinitionVersionModalLogic',- key,- ]),- actions({- openModal: true,- closeModal: true,- }),- reducers({- isOpen: [false, { openModal: () => true, closeModal: () => false }],- }),- ])diff --git a/products/ai_observability/frontend/scoreDefinitions/scorerLogic.test.ts b/products/ai_observability/frontend/scoreDefinitions/scorerLogic.test.tsnew file mode 100644index 000000000000..f5bc2132a3fc--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/scorerLogic.test.ts@@ -0,0 +1,320 @@+import { MOCK_DEFAULT_TEAM } from '~/lib/api.mock'++import { router } from 'kea-router'+import { expectLogic } from 'kea-test-utils'++import { urls } from 'scenes/urls'++import { initKeaTests } from '~/test/init'+import { AccessControlLevel } from '~/types'++import {+ llmAnalyticsScoreDefinitionsCreate,+ llmAnalyticsScoreDefinitionsNewVersionCreate,+ llmAnalyticsScoreDefinitionsPartialUpdate,+ llmAnalyticsScoreDefinitionsRetrieve,+} from '../generated/api'+import type { ScoreDefinitionApi, ScoreDefinitionConfigApi } from '../generated/api.schemas'+import { scorerLogic } from './scorerLogic'++jest.mock('../generated/api', () => ({+ llmAnalyticsScoreDefinitionsCreate: jest.fn(),+ llmAnalyticsScoreDefinitionsNewVersionCreate: jest.fn(),+ llmAnalyticsScoreDefinitionsPartialUpdate: jest.fn(),+ llmAnalyticsScoreDefinitionsRetrieve: jest.fn(),+}))++const retrieve = jest.mocked(llmAnalyticsScoreDefinitionsRetrieve)+const create = jest.mocked(llmAnalyticsScoreDefinitionsCreate)+const createVersion = jest.mocked(llmAnalyticsScoreDefinitionsNewVersionCreate)+const update = jest.mocked(llmAnalyticsScoreDefinitionsPartialUpdate)+const definition: ScoreDefinitionApi = {+ id: 'scorer-example',+ name: 'Answer quality',+ description: '',+ kind: 'numeric',+ config: {},+ archived: false,+ current_version: 2,+ current_version_id: 'version-example',+ team: MOCK_DEFAULT_TEAM.id,+ created_by: null,+ created_at: '2026-01-01T00:00:00Z',+ updated_at: null,+}++describe('scorer editor', () => {+ beforeEach(() => {+ initKeaTests()+ window.POSTHOG_APP_CONTEXT!.resource_access_control = {+ ...window.POSTHOG_APP_CONTEXT!.resource_access_control,+ llm_analytics: AccessControlLevel.Editor,+ }+ jest.resetAllMocks()+ retrieve.mockResolvedValue(definition)+ })++ it.each<{ kind: ScoreDefinitionApi['kind']; config: ScoreDefinitionConfigApi; duplicateFrom?: string }>([+ {+ kind: 'categorical',+ config: { options: [{ key: 'good', label: 'Good' }], passing_rule: { categories: ['good'] } },+ },+ { kind: 'numeric', config: { min: 0, max: null, passing_rule: null } },+ { kind: 'numeric', config: {}, duplicateFrom: 'another-scorer' },+ { kind: 'boolean', config: { true_label: '', false_label: 'Needs work', true_is_failure: false } },+ { kind: 'categorical', config: { options: [{ key: 'good', label: 'Good' }], selection_mode: 'single' } },+ ])(+ 'saves only metadata when an existing $kind configuration is untouched',+ async ({ kind, config, duplicateFrom }) => {+ const existing = { ...definition, kind, config }+ retrieve.mockResolvedValue(existing)+ update.mockResolvedValue({ ...existing, name: 'Renamed scorer' })+ const logic = scorerLogic({ scorerId: definition.id, duplicateFrom })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(retrieve).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id)+ expect(logic.values.draft.name).toBe(existing.name)+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ expect(logic.values.willCreateVersion).toBe(false)+ logic.actions.setDraftField('name', 'Renamed scorer')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ expect(logic.values.willCreateVersion).toBe(false)+ logic.actions.setDraftField('name', existing.name)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ logic.actions.setDraftField('name', 'Renamed scorer')+ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()++ expect(update).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {+ name: 'Renamed scorer',+ description: '',+ })+ expect(createVersion).not.toHaveBeenCalled()+ expect(logic.values.definition?.config).toEqual(config)+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ }+ )++ it('keeps categorical passing selections valid while editing unsaved options', () => {+ const logic = scorerLogic({ scorerId: 'new' })+ logic.mount()+ logic.actions.addOption()+ logic.actions.updateOptionLabel(2, 'Helpful')+ logic.actions.setDraftField('categoricalPassingCategories', ['helpful'])+ logic.actions.updateOptionLabel(2, 'Accurate')+ expect(logic.values.draft.categoricalPassingCategories).toEqual(['accurate'])+ logic.actions.removeOption(2)+ expect(logic.values.draft.categoricalPassingCategories).toEqual([])+ })++ it('saves metadata and passing rules together in a version guarded by the original version number', async () => {+ createVersion.mockResolvedValue({+ ...definition,+ name: 'Updated quality',+ current_version: 3,+ config: { passing_rule: { operator: 'gte', threshold: 7 } },+ })+ const logic = scorerLogic({ scorerId: definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setDraftField('name', 'Updated quality')+ logic.actions.setDraftField('numericPassingEnabled', true)+ logic.actions.setDraftField('numericPassingThreshold', '7')+ expect(logic.values.willCreateVersion).toBe(true)++ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()++ expect(createVersion).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {+ name: 'Updated quality',+ description: '',+ config: { passing_rule: { operator: 'gte', threshold: 7 } },+ base_version: 2,+ })+ expect(update).not.toHaveBeenCalled()+ expect(logic.values.definition?.current_version).toBe(3)+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.willCreateVersion).toBe(false)+ })++ it.each([{}, { true_is_failure: null }])(+ 'persists the default boolean polarity on metadata save without marking the initial draft dirty: %j',+ async (polarityConfig) => {+ const existing: ScoreDefinitionApi = {+ ...definition,+ kind: 'boolean',+ config: { true_label: '', false_label: 'Needs work', ...polarityConfig },+ }+ const saved = {+ ...existing,+ name: 'Renamed scorer',+ current_version: 3,+ config: { false_label: 'Needs work', true_is_failure: false },+ }+ retrieve.mockResolvedValue(existing)+ createVersion.mockResolvedValue(saved)+ const logic = scorerLogic({ scorerId: definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.draft.booleanPassing).toBe('true')+ expect(logic.values.configChanged).toBe(false)+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ expect(logic.values.willCreateVersion).toBe(false)+ expect(createVersion).not.toHaveBeenCalled()+ logic.actions.setDraftField('name', 'Renamed scorer')+ expect(logic.values.willCreateVersion).toBe(true)+ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()++ expect(createVersion).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {+ name: 'Renamed scorer',+ description: '',+ config: saved.config,+ base_version: 2,+ })+ expect(update).not.toHaveBeenCalled()+ expect(logic.values.hasChanges).toBe(false)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ expect(logic.values.willCreateVersion).toBe(false)+ }+ )++ it('duplicates a scorer with its boolean polarity without updating the source', async () => {+ const existing: ScoreDefinitionApi = {+ ...definition,+ kind: 'boolean',+ config: { true_label: 'Flagged', false_label: 'Clear', true_is_failure: true },+ }+ retrieve.mockResolvedValue(existing)+ create.mockResolvedValue({+ ...existing,+ id: 'duplicate-example',+ name: 'Answer quality copy',+ current_version: 1,+ })+ const logic = scorerLogic({ scorerId: 'new', duplicateFrom: definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ expect(logic.values.hasUnsavedChanges).toBe(false)+ logic.actions.setDraftField('description', 'Changed description')+ expect(logic.values.hasUnsavedChanges).toBe(true)+ logic.actions.setDraftField('description', '')+ expect(logic.values.hasUnsavedChanges).toBe(false)+ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()++ expect(create).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), {+ name: 'Answer quality copy',+ description: '',+ kind: 'boolean',+ config: existing.config,+ })+ expect(update).not.toHaveBeenCalled()+ expect(createVersion).not.toHaveBeenCalled()+ })++ it.each([+ ['save', false],+ ['save', true],+ ['createVersion', false],+ ['toggleArchive', false],+ ] as const)(+ 'applies the response when %s is repeated while its request is pending (new: %s)',+ async (action, isNew) => {+ let resolve: (value: ScoreDefinitionApi) => void = () => {}+ const request = isNew ? create : action === 'toggleArchive' ? update : createVersion+ request.mockImplementation(+ () =>+ new Promise((done) => {+ resolve = done+ })+ )+ const logic = scorerLogic({ scorerId: isNew ? 'new' : definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ if (action === 'save') {+ logic.actions.setDraftField('kind', 'numeric')+ logic.actions.setDraftField('name', definition.name)+ logic.actions.setDraftField('numericMax', '10')+ }++ logic.actions[action]()+ logic.actions[action]()++ expect(request).toHaveBeenCalledTimes(1)+ expect(logic.values.saving).toBe(true)+ const saved =+ action === 'toggleArchive'+ ? { ...definition, archived: true }+ : { ...definition, config: { max: 10 }, current_version: 3 }+ resolve(saved)+ await expectLogic(logic).toFinishAllListeners()+ expect(logic.values.saving).toBe(false)+ if (isNew) {+ expect(router.values.location.pathname).toBe(+ `/project/${MOCK_DEFAULT_TEAM.id}${urls.aiObservabilityScorer(saved.id)}`+ )+ } else {+ expect(logic.values.definition).toEqual(saved)+ expect(logic.values.hasUnsavedChanges).toBe(false)+ }+ }+ )++ it('keeps edits after a version conflict without retrying against a newer version', async () => {+ createVersion.mockRejectedValue({ status: 409 })+ const logic = scorerLogic({ scorerId: definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()+ logic.actions.setDraftField('numericMax', '10')++ await expectLogic(logic, () => logic.actions.save()).toFinishAllListeners()++ expect(createVersion).toHaveBeenCalledTimes(1)+ expect(logic.values.error).toContain('newer version')+ expect(logic.values.draft.numericMax).toBe('10')+ expect(logic.values.definition?.current_version).toBe(2)+ expect(logic.values.hasChanges).toBe(true)+ expect(logic.values.hasUnsavedChanges).toBe(true)+ expect(logic.values.saving).toBe(false)+ })++ it.each<{+ kind: ScoreDefinitionApi['kind']+ config: ScoreDefinitionConfigApi+ expectedConfig: ScoreDefinitionConfigApi+ }>([+ {+ kind: 'numeric',+ config: { min: 0, max: null, passing_rule: null },+ expectedConfig: { min: 0, max: null, passing_rule: null },+ },+ { kind: 'boolean', config: {}, expectedConfig: { true_is_failure: false } },+ {+ kind: 'boolean',+ config: { true_label: '', false_label: 'Needs work', true_is_failure: null },+ expectedConfig: { false_label: 'Needs work', true_is_failure: false },+ },+ {+ kind: 'boolean',+ config: { true_label: 'Detected', false_label: ' ', true_is_failure: true },+ expectedConfig: { true_label: 'Detected', true_is_failure: true },+ },+ ])('creates an unchanged $kind version with explicit defaults', async ({ kind, config, expectedConfig }) => {+ retrieve.mockResolvedValue({ ...definition, kind, config })+ createVersion.mockResolvedValue({ ...definition, kind, config: expectedConfig, current_version: 3 })+ const logic = scorerLogic({ scorerId: definition.id })+ logic.mount()+ await expectLogic(logic).toFinishAllListeners()++ await expectLogic(logic, () => logic.actions.createVersion()).toFinishAllListeners()++ expect(createVersion).toHaveBeenCalledWith(String(MOCK_DEFAULT_TEAM.id), definition.id, {+ config: expectedConfig,+ base_version: 2,+ })+ expect(logic.values.hasChanges).toBe(false)+ })+})diff --git a/products/ai_observability/frontend/scoreDefinitions/scorerLogic.ts b/products/ai_observability/frontend/scoreDefinitions/scorerLogic.tsnew file mode 100644index 000000000000..21b80685dd8d--- /dev/null+++ b/products/ai_observability/frontend/scoreDefinitions/scorerLogic.ts@@ -0,0 +1,450 @@+import { MakeLogicType, actions, afterMount, kea, key, listeners, path, props, reducers, selectors } from 'kea'+import { loaders } from 'kea-loaders'+import { beforeUnload, router } from 'kea-router'+import posthog from 'posthog-js'++import { lemonToast } from 'lib/lemon-ui/LemonToast'+import { getAccessControlDisabledReason } from 'lib/utils/accessControlUtils'+import { urls } from 'scenes/urls'++import { AccessControlLevel, AccessControlResourceType, Breadcrumb } from '~/types'++import {+ llmAnalyticsScoreDefinitionsCreate,+ llmAnalyticsScoreDefinitionsNewVersionCreate,+ llmAnalyticsScoreDefinitionsPartialUpdate,+ llmAnalyticsScoreDefinitionsRetrieve,+} from '../generated/api'+import type { ScoreDefinitionApi } from '../generated/api.schemas'+import type { CategoricalScoreOptionApi } from '../generated/api.schemas'+import { getBooleanConfig } from './scoreDefinitionConfigUtils'+import {+ buildConfigFromDraft,+ createDraft,+ getApiErrorDetail,+ getCurrentProjectId,+ getScoreDefinitionOptionKey,+ type ScoreDefinitionDraft,+ validateDraft,+} from './scoreDefinitionModalUtils'++export interface ScorerLogicProps {+ scorerId: string+ duplicateFrom?: string+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scorerLogicValues {+ breadcrumbs: Breadcrumb[]+ configChanged: boolean+ definition: ScoreDefinitionApi | null+ definitionLoading: boolean+ draft: ScoreDefinitionDraft+ error: string | null+ hasChanges: boolean+ hasUnsavedChanges: boolean+ isNew: boolean+ loadError: string | null+ saving: boolean+ willCreateVersion: boolean+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scorerLogicActions {+ addOption: () => {+ value: true+ }+ createVersion: () => {+ value: true+ }+ initialize: (definition: ScoreDefinitionApi | null) => {+ definition: ScoreDefinitionApi | null+ }+ loadDefinition: () => {+ value: true+ }+ loadDefinitionFailure: (+ error: string,+ errorObject?: any+ ) => {+ error: string+ errorObject?: any+ }+ loadDefinitionSuccess: (+ definition: ScoreDefinitionApi | null,+ payload?: {+ value: true+ }+ ) => {+ definition: ScoreDefinitionApi | null+ payload?: {+ value: true+ }+ }+ performCreateVersion: () => {+ value: true+ }+ performSave: () => {+ value: true+ }+ performToggleArchive: () => {+ value: true+ }+ removeOption: (index: number) => {+ index: number+ }+ save: () => {+ value: true+ }+ setDraftField: (+ field: keyof ScoreDefinitionDraft,+ value: ScoreDefinitionDraft[keyof ScoreDefinitionDraft]+ ) => {+ field: keyof ScoreDefinitionDraft+ value: boolean | string | string[] | CategoricalScoreOptionApi[]+ }+ setError: (error: string | null) => {+ error: string | null+ }+ setSaving: (saving: boolean) => {+ saving: boolean+ }+ toggleArchive: () => {+ value: true+ }+ updateOptionLabel: (+ index: number,+ value: string+ ) => {+ index: number+ value: string+ }+}++// Generated by kea-typegen. Update if you're an agent, ignore if you're human.+export interface scorerLogicMeta {+ key: string+ __keaTypeGenInternalSelectorTypes: {+ isNew: (arg: any) => boolean+ configChanged: (draft: ScoreDefinitionDraft, definition: ScoreDefinitionApi | null) => boolean+ hasChanges: (+ isNew: boolean,+ configChanged: boolean,+ draft: ScoreDefinitionDraft,+ definition: ScoreDefinitionApi | null+ ) => boolean+ willCreateVersion: (+ isNew: boolean,+ hasChanges: boolean,+ configChanged: boolean,+ definition: ScoreDefinitionApi | null+ ) => boolean+ hasUnsavedChanges: (draft: ScoreDefinitionDraft, definition: ScoreDefinitionApi | null, arg: any) => boolean+ breadcrumbs: (isNew: boolean, definition: ScoreDefinitionApi | null) => Breadcrumb[]+ }+}++export type scorerLogicType = MakeLogicType<scorerLogicValues, scorerLogicActions, ScorerLogicProps, scorerLogicMeta>++export const scorerLogic = kea<scorerLogicType>([+ props({} as ScorerLogicProps),+ key(({ scorerId, duplicateFrom }) => `${getCurrentProjectId()}-${scorerId}-${duplicateFrom || ''}`),+ path((key) => ['products', 'ai_observability', 'frontend', 'scoreDefinitions', 'scorerLogic', key]),+ actions({+ loadDefinition: true,+ initialize: (definition: ScoreDefinitionApi | null) => ({ definition }),+ setDraftField: (+ field: keyof ScoreDefinitionDraft,+ value: ScoreDefinitionDraft[keyof ScoreDefinitionDraft]+ ) => ({+ field,+ value,+ }),+ updateOptionLabel: (index: number, value: string) => ({ index, value }),+ addOption: true,+ removeOption: (index: number) => ({ index }),+ save: true,+ performSave: true,+ createVersion: true,+ performCreateVersion: true,+ toggleArchive: true,+ performToggleArchive: true,+ setSaving: (saving: boolean) => ({ saving }),+ setError: (error: string | null) => ({ error }),+ }),+ loaders(({ props }) => ({+ definition: [+ null as ScoreDefinitionApi | null,+ {+ loadDefinition: async (_, breakpoint) => {+ const teamId = getCurrentProjectId()+ const definition = await llmAnalyticsScoreDefinitionsRetrieve(+ teamId,+ (props.scorerId === 'new' && props.duplicateFrom) || props.scorerId+ )+ breakpoint()+ return teamId === getCurrentProjectId() ? definition : null+ },+ },+ ],+ })),+ reducers(({ props }) => ({+ definition: [null as ScoreDefinitionApi | null, { initialize: (_, { definition }) => definition }],+ draft: [+ createDraft('create'),+ {+ initialize: (_, { definition }) =>+ createDraft(+ props.scorerId === 'new' && props.duplicateFrom+ ? 'duplicate'+ : definition+ ? 'metadata'+ : 'create',+ definition+ ),+ setDraftField: (state, { field, value }) => ({ ...state, [field]: value }),+ updateOptionLabel: (state, { index, value }) => {+ const oldKey = getScoreDefinitionOptionKey(state.options[index])+ const newKey = getScoreDefinitionOptionKey({ ...state.options[index], label: value })+ return {+ ...state,+ options: state.options.map((option, optionIndex) =>+ optionIndex === index ? { ...option, label: value } : option+ ),+ categoricalPassingCategories: state.categoricalPassingCategories+ .map((key) => (key === oldKey ? newKey : key))+ .filter(Boolean),+ }+ },+ addOption: (state) => ({ ...state, options: [...state.options, { key: '', label: '' }] }),+ removeOption: (state, { index }) => ({+ ...state,+ options: state.options.filter((_, optionIndex) => optionIndex !== index),+ categoricalPassingCategories: state.categoricalPassingCategories.filter(+ (key) => key !== getScoreDefinitionOptionKey(state.options[index])+ ),+ }),+ },+ ],+ saving: [false, { setSaving: (_, { saving }) => saving }],+ error: [null as string | null, { setError: (_, { error }) => error, initialize: () => null }],+ loadError: [+ null as string | null,+ {+ loadDefinition: () => null,+ loadDefinitionSuccess: () => null,+ loadDefinitionFailure: () => 'Could not load this scorer. Try again.',+ },+ ],+ })),+ selectors({+ isNew: [() => [(_, props) => props.scorerId], (scorerId) => scorerId === 'new'],+ configChanged: [+ (s) => [s.draft, s.definition],+ (draft: ScoreDefinitionDraft, definition: ScoreDefinitionApi | null) =>+ !!definition &&+ JSON.stringify(buildConfigFromDraft(draft)) !==+ JSON.stringify(buildConfigFromDraft(createDraft('metadata', definition))),+ ],+ hasChanges: [+ (s) => [s.isNew, s.configChanged, s.draft, s.definition],+ (+ isNew: boolean,+ configChanged: boolean,+ draft: ScoreDefinitionDraft,+ definition: ScoreDefinitionApi | null+ ): boolean =>+ isNew ||+ configChanged ||+ draft.name.trim() !== definition?.name ||+ draft.description.trim() !== definition?.description,+ ],+ willCreateVersion: [+ (s) => [s.isNew, s.hasChanges, s.configChanged, s.definition],+ (+ isNew: boolean,+ hasChanges: boolean,+ configChanged: boolean,+ definition: ScoreDefinitionApi | null+ ): boolean =>+ !isNew &&+ hasChanges &&+ (configChanged ||+ (definition?.kind === 'boolean' && getBooleanConfig(definition.config).true_is_failure == null)),+ ],+ hasUnsavedChanges: [+ (s) => [s.draft, s.definition, (_, props) => props],+ (draft: ScoreDefinitionDraft, definition: ScoreDefinitionApi | null, props: ScorerLogicProps) =>+ JSON.stringify(draft) !==+ JSON.stringify(+ createDraft(+ props.scorerId === 'new' && props.duplicateFrom+ ? 'duplicate'+ : definition+ ? 'metadata'+ : 'create',+ definition+ )+ ),+ ],+ breadcrumbs: [+ (s) => [s.isNew, s.definition],+ (isNew: boolean, definition: ScoreDefinitionApi | null): Breadcrumb[] => [+ { name: 'Scorers', path: urls.aiObservabilityScorers(), key: 'AIObservabilityScorers' },+ { name: isNew ? 'New scorer' : definition?.name || 'Scorer', key: 'AIObservabilityScorer' },+ ],+ ],+ }),+ listeners(({ actions, values, props }) => ({+ loadDefinitionSuccess: ({ definition }) => actions.initialize(definition),+ save: () => {+ if (+ values.saving ||+ values.definitionLoading ||+ !values.hasChanges ||+ (!values.isNew && !values.definition) ||+ getAccessControlDisabledReason(AccessControlResourceType.LlmAnalytics, AccessControlLevel.Editor)+ ) {+ return+ }+ const validationError = validateDraft('create', values.draft)+ if (validationError) {+ actions.setError(validationError)+ return+ }+ actions.setSaving(true)+ actions.performSave()+ },+ performSave: async (_, breakpoint) => {+ const teamId = getCurrentProjectId()+ const { draft, definition, isNew, willCreateVersion } = values+ const metadata = { name: draft.name.trim(), description: draft.description.trim() }+ const operation = isNew ? 'create' : willCreateVersion ? 'version' : 'metadata'+ actions.setError(null)+ posthog.capture('llma scorer save started', { operation, kind: draft.kind })+ try {+ const saved = isNew+ ? await llmAnalyticsScoreDefinitionsCreate(teamId, {+ ...metadata,+ kind: draft.kind,+ config: buildConfigFromDraft(draft),+ })+ : willCreateVersion+ ? await llmAnalyticsScoreDefinitionsNewVersionCreate(teamId, props.scorerId, {+ ...metadata,+ config: buildConfigFromDraft(draft),+ base_version: definition!.current_version,+ })+ : await llmAnalyticsScoreDefinitionsPartialUpdate(teamId, props.scorerId, metadata)+ breakpoint()+ if (teamId !== getCurrentProjectId()) {+ return+ }+ if (!isNew) {+ actions.initialize(saved)+ }+ posthog.capture('llma scorer saved', { operation, kind: saved.kind })+ lemonToast.success(isNew ? 'Scorer created.' : 'Scorer saved.')+ if (isNew) {+ router.actions.replace(urls.aiObservabilityScorer(saved.id))+ }+ } catch (error) {+ breakpoint()+ const stale = typeof error === 'object' && error !== null && 'status' in error && error.status === 409+ actions.setError(+ stale+ ? 'This scorer has a newer version. Reload the scorer and review your changes before saving.'+ : getApiErrorDetail(error) || 'Could not save this scorer. Try again.'+ )+ posthog.capture('llma scorer save failed', { operation, kind: draft.kind })+ } finally {+ actions.setSaving(false)+ }+ },+ createVersion: () => {+ if (+ values.saving ||+ values.definitionLoading ||+ !values.definition ||+ values.hasChanges ||+ getAccessControlDisabledReason(AccessControlResourceType.LlmAnalytics, AccessControlLevel.Editor)+ ) {+ return+ }+ actions.setSaving(true)+ actions.performCreateVersion()+ },+ performCreateVersion: async (_, breakpoint) => {+ const definition = values.definition!+ const teamId = getCurrentProjectId()+ actions.setError(null)+ try {+ const saved = await llmAnalyticsScoreDefinitionsNewVersionCreate(teamId, definition.id, {+ config:+ definition.kind === 'boolean'+ ? buildConfigFromDraft(createDraft('config', definition))+ : definition.config,+ base_version: definition.current_version,+ })+ breakpoint()+ if (teamId === getCurrentProjectId()) {+ actions.initialize(saved)+ lemonToast.success(`Created version ${saved.current_version}.`)+ }+ } catch (error) {+ breakpoint()+ actions.setError(+ getApiErrorDetail(error) || 'Could not create a version. Reload this scorer and try again.'+ )+ } finally {+ actions.setSaving(false)+ }+ },+ toggleArchive: () => {+ if (+ values.saving ||+ values.definitionLoading ||+ !values.definition ||+ values.hasChanges ||+ getAccessControlDisabledReason(AccessControlResourceType.LlmAnalytics, AccessControlLevel.Editor)+ ) {+ return+ }+ actions.setSaving(true)+ actions.performToggleArchive()+ },+ performToggleArchive: async (_, breakpoint) => {+ const definition = values.definition!+ const teamId = getCurrentProjectId()+ actions.setError(null)+ try {+ const saved = await llmAnalyticsScoreDefinitionsPartialUpdate(teamId, definition.id, {+ archived: !definition.archived,+ })+ breakpoint()+ if (teamId === getCurrentProjectId()) {+ actions.initialize(saved)+ posthog.capture('llma scorer archive changed', { archived: saved.archived })+ }+ } catch (error) {+ breakpoint()+ actions.setError(getApiErrorDetail(error) || 'Could not update this scorer. Try again.')+ } finally {+ actions.setSaving(false)+ }+ },+ })),+ beforeUnload(({ values }) => ({+ enabled: () => values.hasUnsavedChanges && !values.saving,+ message: 'Leave this scorer? Your unsaved changes will be discarded.',+ })),+ afterMount(({ actions, props }) => {+ posthog.capture('llma scorer editor opened', {+ creating: props.scorerId === 'new',+ duplicating: !!props.duplicateFrom,+ })+ if (props.scorerId !== 'new' || props.duplicateFrom) {+ actions.loadDefinition()+ }+ }),+])diff --git a/products/ai_observability/manifest.tsx b/products/ai_observability/manifest.tsxindex d7ebbbbbf54f..514cfa277bc6 100644--- a/products/ai_observability/manifest.tsx+++ b/products/ai_observability/manifest.tsx@@ -81,6 +81,13 @@ export const manifest: ProductManifest = {layout: 'app-container',iconType: 'llm_evaluations',},+ AIObservabilityScorer: {+ import: () => import('./frontend/scoreDefinitions/AIObservabilityScorerScene'),+ projectBased: true,+ name: 'Scorer',+ layout: 'app-container',+ iconType: 'llm_evaluations',+ },AIObservabilityOfflineExperiments: {import: () => import('./frontend/offline-evaluations/OfflineExperimentsScene'),projectBased: true,@@ -204,6 +211,7 @@ export const manifest: ProductManifest = {'AIObservabilityOfflineScorerHistory','aiObservabilityOfflineScorerHistory',],+ '/ai-evals/evaluations/scorers/:scorerId': ['AIObservabilityScorer', 'aiObservabilityScorer'],'/ai-evals/evaluations/templates': ['AIObservabilityEvaluationTemplates', 'aiObservabilityEvaluationTemplates'],'/ai-evals/evaluations/:id': ['AIObservabilityEvaluation', 'aiObservabilityEvaluation'],'/prompt-management/prompts': ['AIObservabilityPrompts', 'aiObservabilityPrompts'],@@ -404,6 +412,8 @@ export const manifest: ProductManifest = {aiObservabilityTag: (id: string): string => `/ai-evals/taggers/${id}`,aiObservabilityEvaluations: (): string => '/ai-evals/evaluations',aiObservabilityScorers: (): string => '/ai-evals/evaluations/scorers',+ aiObservabilityScorer: (scorerId: string, params?: { duplicate?: string }): string =>+ combineUrl(`/ai-evals/evaluations/scorers/${encodeURIComponent(scorerId)}`, params).url,aiObservabilityOfflineScorerHistory: (scorerId: string, encode: boolean = true): string =>`/ai-evals/evaluations/scorers/${encode ? encodeURIComponent(scorerId) : scorerId}/offline`,aiObservabilityOfflineEvaluations: (): string => '/ai-evals/evaluations/offline/experiments',diff --git a/products/ai_observability/mcp/tools.yaml b/products/ai_observability/mcp/tools.yamlindex a436e0d0ed6b..875967a118e9 100644--- a/products/ai_observability/mcp/tools.yaml+++ b/products/ai_observability/mcp/tools.yaml@@ -1380,8 +1380,11 @@ tools:`numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categoricalscorers need an `options` array with unique keys and optional`selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`,- `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived)- and at version 1.+ `step`, and an optional `passing_rule` with `operator` (`gte`/`lte`) and a finite `threshold` within those+ bounds. Boolean scorers can override `true_label`/`false_label` and set `true_is_failure` (`false`: true+ passes; `true`: false passes). Omitted or null boolean polarity defaults to true passing in offline+ evaluations. Numeric scores without a passing rule remain neutral. Scorers always start active (not+ archived) and at version 1.param_overrides:config:input_schema: ScoreDefinitionConfigSchema@@ -1425,11 +1428,12 @@ tools:title: Bump scorer to a new versiondescription: >Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change- (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep- their snapshot of the previous version, so historical scores remain stable. The `config` shape must match- the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number- you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already- advanced the scorer.+ (add/remove categorical options, tweak numeric bounds or passing rules, change boolean polarity or labels).+ Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The+ `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass+ `base_version` (the version number you observed before bumping) for optimistic concurrency — the request+ returns 409 if another writer already advanced the scorer. Optional `name` and `description` updates are+ saved atomically with the version.param_overrides:config:input_schema: ScoreDefinitionConfigSchemadiff --git a/services/mcp/schema/generated-tool-definitions.json b/services/mcp/schema/generated-tool-definitions.jsonindex b5bd08a3f0ab..c830e34ff9fd 100644--- a/services/mcp/schema/generated-tool-definitions.json+++ b/services/mcp/schema/generated-tool-definitions.json@@ -8102,7 +8102,7 @@}},"llma-score-definition-create": {- "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived) and at version 1.",+ "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`, and an optional `passing_rule` with `operator` (`gte`/`lte`) and a finite `threshold` within those bounds. Boolean scorers can override `true_label`/`false_label` and set `true_is_failure` (`false`: true passes; `true`: false passes). Omitted or null boolean polarity defaults to true passing in offline evaluations. Numeric scores without a passing rule remain neutral. Scorers always start active (not archived) and at version 1.","category": "AI observability","feature": "llm_analytics","summary": "Create scorer",@@ -8144,7 +8144,7 @@}},"llma-score-definition-new-version": {- "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer.",+ "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds or passing rules, change boolean polarity or labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer. Optional `name` and `description` updates are saved atomically with the version.","category": "AI observability","feature": "llm_analytics","summary": "Bump scorer to a new version",diff --git a/services/mcp/schema/tool-definitions-all.json b/services/mcp/schema/tool-definitions-all.jsonindex ba9de21aa012..523e749a6de1 100644--- a/services/mcp/schema/tool-definitions-all.json+++ b/services/mcp/schema/tool-definitions-all.json@@ -8341,7 +8341,7 @@}},"llma-score-definition-create": {- "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`. Boolean scorers can override `true_label`/`false_label`. Scorers always start active (not archived) and at version 1.",+ "description": "Create a new scorer (a.k.a. score definition) used by trace reviews. Pass `name`, `kind` (`categorical`, `numeric`, or `boolean`), and `config` matching the kind. `kind` is immutable after creation. Categorical scorers need an `options` array with unique keys and optional `selection_mode`/`min_selections`/`max_selections` (for `multiple`). Numeric scorers can set `min`, `max`, `step`, and an optional `passing_rule` with `operator` (`gte`/`lte`) and a finite `threshold` within those bounds. Boolean scorers can override `true_label`/`false_label` and set `true_is_failure` (`false`: true passes; `true`: false passes). Omitted or null boolean polarity defaults to true passing in offline evaluations. Numeric scores without a passing rule remain neutral. Scorers always start active (not archived) and at version 1.","category": "AI observability","feature": "llm_analytics","summary": "Create scorer",@@ -8383,7 +8383,7 @@}},"llma-score-definition-new-version": {- "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds, rename boolean labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer.",+ "description": "Publish a new immutable `config` version for an existing scorer. Use this whenever the scoring rules change (add/remove categorical options, tweak numeric bounds or passing rules, change boolean polarity or labels). Existing trace reviews keep their snapshot of the previous version, so historical scores remain stable. The `config` shape must match the scorer's `kind`. Each call increments `current_version` by one. Pass `base_version` (the version number you observed before bumping) for optimistic concurrency — the request returns 409 if another writer already advanced the scorer. Optional `name` and `description` updates are saved atomically with the version.","category": "AI observability","feature": "llm_analytics","summary": "Bump scorer to a new version",diff --git a/services/mcp/schema/tool-inputs.json b/services/mcp/schema/tool-inputs.jsonindex 0936c9f79f5c..bb04e340eaf7 100644--- a/services/mcp/schema/tool-inputs.json+++ b/services/mcp/schema/tool-inputs.json@@ -1277,6 +1277,29 @@"type": "integer","minimum": 1,"maximum": 9007199254740991+ },+ "passing_rule": {+ "description": "Optional passing categories. Omit or set null for neutral scores. Each version keeps its own rule.",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "categories": {+ "type": "array",+ "items": {+ "type": "string",+ "maxLength": 128+ },+ "description": "Passing category keys. Every returned category must be included."+ }+ },+ "required": ["categories"],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]}},"required": ["options"],@@ -1298,6 +1321,30 @@"description": "Optional increment step for numeric input, e.g. 1 or 0.5.","type": "number","exclusiveMinimum": 0+ },+ "passing_rule": {+ "description": "Optional passing rule. Omit or set null for neutral scores. Each version keeps its own rule.",+ "anyOf": [+ {+ "type": "object",+ "properties": {+ "operator": {+ "type": "string",+ "enum": ["gte", "lte"],+ "description": "Pass at or above (gte), or at or below (lte), the threshold."+ },+ "threshold": {+ "type": "number",+ "description": "Finite passing threshold within any configured score bounds."+ }+ },+ "required": ["operator", "threshold"],+ "additionalProperties": false+ },+ {+ "type": "null"+ }+ ]}},"additionalProperties": false,@@ -1315,13 +1362,24 @@"description": "Optional label shown for the false branch (e.g. \"No\").","type": "string","minLength": 1+ },+ "true_is_failure": {+ "description": "Whether true means failure. False, omitted, or null means true passes in offline evaluations.",+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ]}},"additionalProperties": false,"description": "Config shape used when kind is \"boolean\"."}],- "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode + optional passing_rule.categories), numeric (min/max/step + optional passing_rule), or boolean (true_label/false_label + optional true_is_failure). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."},"TaskAgentCreateSchema": {"type": "object",diff --git a/services/mcp/src/api/generated.ts b/services/mcp/src/api/generated.tsindex 5d560f842ecd..7a8d6adee9ee 100644--- a/services/mcp/src/api/generated.ts+++ b/services/mcp/src/api/generated.ts@@ -17758,6 +17758,11 @@ export namespace Schemas {} as const;export interface BooleanScoreDefinitionConfig {+ /**+ * Whether true means failure. False, omitted, or null means true passes in offline evaluations.+ * @nullable+ */+ true_is_failure?: boolean | null;/** Optional label for a true value. */true_label?: string;/** Optional label for a false value. */@@ -21265,6 +21270,14 @@ export namespace Schemas {Multiple: 'multiple',} as const;+ export interface CategoricalScorePassingRule {+ /**+ * Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.+ * @items.maxLength 128+ */+ categories: string[];+ }+export interface CategoricalScoreDefinitionConfig {/** Ordered categorical options available to the scorer. */options: CategoricalScoreOption[];@@ -21285,6 +21298,8 @@ export namespace Schemas {* @nullable*/max_selections?: number | null;+ /** Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule. */+ passing_rule?: CategoricalScorePassingRule | null;}export interface CdcEnableResponse {@@ -64191,6 +64206,28 @@ export namespace Schemas {change: WoWChange | null;}+ /**+ * * `gte` - At or above+ * * `lte` - At or below+ */+ export type NumericScorePassingRuleSerializerOperatorEnum = typeof NumericScorePassingRuleSerializerOperatorEnum[keyof typeof NumericScorePassingRuleSerializerOperatorEnum];+++ export const NumericScorePassingRuleSerializerOperatorEnum = {+ Gte: 'gte',+ Lte: 'lte',+ } as const;++ export interface NumericScorePassingRule {+ /** Pass at or above (gte), or at or below (lte), the threshold.+ *+ * * `gte` - At or above+ * * `lte` - At or below */+ operator: NumericScorePassingRuleSerializerOperatorEnum;+ /** Finite passing threshold within any configured score bounds. */+ threshold: number;+ }+export interface NumericScoreDefinitionConfig {/*** Optional inclusive minimum score.@@ -64207,6 +64244,8 @@ export namespace Schemas {* @nullable*/step?: number | null;+ /** Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule. */+ passing_rule?: NumericScorePassingRule | null;}export interface OAuthRedirectResponse {@@ -65021,6 +65060,21 @@ export namespace Schemas {* @nullable*/true_rate: number | null;+ /**+ * Successful results passing the pinned rule. Boolean scores default to true passing; null for unconfigured numeric or categorical scorers.+ * @nullable+ */+ pass_count: number | null;+ /**+ * Successful results failing the pinned rule; null for unconfigured numeric or categorical scorers.+ * @nullable+ */+ fail_count: number | null;+ /**+ * Passing fraction among successful results; null without successful results or an applicable rule. Boolean scores default to true passing. Excludes errors, skipped, not-applicable, and missing results.+ * @nullable+ */+ pass_rate: number | null;/** Pinned categorical distribution; multiselect rates may sum above one. */categories: OfflineCategorySummary[];}@@ -92991,6 +93045,16 @@ export namespace Schemas {}export interface ScoreDefinitionNewVersion {+ /**+ * Updated scorer name, saved with this version.+ * @maxLength 255+ */+ name?: string;+ /**+ * Updated scorer description, saved with this version.+ * @nullable+ */+ description?: string | null;/** Next immutable scorer configuration. */config: ScoreDefinitionConfig;/**diff --git a/services/mcp/src/generated/ai_observability/api.ts b/services/mcp/src/generated/ai_observability/api.tsindex 0f812496e53e..01a0c0c4cb3a 100644--- a/services/mcp/src/generated/ai_observability/api.ts+++ b/services/mcp/src/generated/ai_observability/api.ts@@ -2094,6 +2094,8 @@ export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemKeyMaxexport const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOneOptionsItemLabelMax = 256+export const llmAnalyticsScoreDefinitionsCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax = 128+export const LlmAnalyticsScoreDefinitionsCreateBody = () => zod.object({name: zod.string().max(llmAnalyticsScoreDefinitionsCreateBodyNameMax).describe('Human-readable scorer name.'),description: zod.string().nullish().describe('Optional human-readable description.'),@@ -2147,6 +2149,27 @@ export const LlmAnalyticsScoreDefinitionsCreateBody = () => zod.object({.describe('Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'),+ passing_rule: zod+ .union([+ zod.object({+ categories: zod+ .array(+ zod+ .string()+ .max(+ llmAnalyticsScoreDefinitionsCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax+ )+ )+ .describe(+ 'Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({min: zod.number().nullish().describe('Optional inclusive minimum score.'),@@ -2155,8 +2178,33 @@ export const LlmAnalyticsScoreDefinitionsCreateBody = () => zod.object({.number().nullish().describe('Optional increment step for numeric input, for example 1 or 0.5.'),+ passing_rule: zod+ .union([+ zod.object({+ operator: zod+ .enum(['gte', 'lte'])+ .describe('\* `gte` - At or above\n\* `lte` - At or below')+ .describe(+ 'Pass at or above (gte), or at or below (lte), the threshold.\n\n\* `gte` - At or above\n\* `lte` - At or below'+ ),+ threshold: zod+ .number()+ .describe('Finite passing threshold within any configured score bounds.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({+ true_is_failure: zod+ .boolean()+ .nullish()+ .describe(+ 'Whether true means failure. False, omitted, or null means true passes in offline evaluations.'+ ),true_label: zod.string().optional().describe('Optional label for a true value.'),false_label: zod.string().optional().describe('Optional label for a false value.'),}),@@ -2203,11 +2251,21 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateParams = () => zod.obje),})+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyNameMax = 255+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemKeyMax = 128export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOneOptionsItemLabelMax = 256+export const llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax = 128+export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = () => zod.object({+ name: zod+ .string()+ .max(llmAnalyticsScoreDefinitionsNewVersionCreateBodyNameMax)+ .optional()+ .describe('Updated scorer name, saved with this version.'),+ description: zod.string().nullish().describe('Updated scorer description, saved with this version.'),config: zod.union([zod.object({@@ -2248,6 +2306,27 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = () => zod.object.describe('Optional maximum number of options that can be selected when `selection_mode` is `multiple`.'),+ passing_rule: zod+ .union([+ zod.object({+ categories: zod+ .array(+ zod+ .string()+ .max(+ llmAnalyticsScoreDefinitionsNewVersionCreateBodyConfigOneOnePassingRuleOneCategoriesItemMax+ )+ )+ .describe(+ 'Passing category keys. Every returned category must be included. An empty list makes all accepted offline results fail.'+ ),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing categories. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({min: zod.number().nullish().describe('Optional inclusive minimum score.'),@@ -2256,8 +2335,33 @@ export const LlmAnalyticsScoreDefinitionsNewVersionCreateBody = () => zod.object.number().nullish().describe('Optional increment step for numeric input, for example 1 or 0.5.'),+ passing_rule: zod+ .union([+ zod.object({+ operator: zod+ .enum(['gte', 'lte'])+ .describe('\* `gte` - At or above\n\* `lte` - At or below')+ .describe(+ 'Pass at or above (gte), or at or below (lte), the threshold.\n\n\* `gte` - At or above\n\* `lte` - At or below'+ ),+ threshold: zod+ .number()+ .describe('Finite passing threshold within any configured score bounds.'),+ }),+ zod.null(),+ ])+ .optional()+ .describe(+ 'Optional passing rule. Omit or set null for neutral scores. Each scorer version keeps its own rule.'+ ),}),zod.object({+ true_is_failure: zod+ .boolean()+ .nullish()+ .describe(+ 'Whether true means failure. False, omitted, or null means true passes in offline evaluations.'+ ),true_label: zod.string().optional().describe('Optional label for a true value.'),false_label: zod.string().optional().describe('Optional label for a false value.'),}),diff --git a/services/mcp/src/schema/tool-inputs.ts b/services/mcp/src/schema/tool-inputs.tsindex 6c55c8940d1b..42ef53dca2b1 100644--- a/services/mcp/src/schema/tool-inputs.ts+++ b/services/mcp/src/schema/tool-inputs.ts@@ -220,6 +220,18 @@ const CategoricalScoreDefinitionConfigSchema = z.min(1).optional().describe('Maximum selections allowed. Only valid when selection_mode is "multiple".'),+ passing_rule: z+ .object({+ categories: z+ .array(z.string().max(128))+ .describe('Passing category keys. Every returned category must be included.'),+ })+ .strict()+ .nullable()+ .optional()+ .describe(+ 'Optional passing categories. Omit or set null for neutral scores. Each version keeps its own rule.'+ ),}).strict().describe('Config shape used when kind is "categorical".')@@ -229,6 +241,17 @@ const NumericScoreDefinitionConfigSchema = zmin: z.number().optional().describe('Optional inclusive minimum score.'),max: z.number().optional().describe('Optional inclusive maximum score (must be ≥ min).'),step: z.number().positive().optional().describe('Optional increment step for numeric input, e.g. 1 or 0.5.'),+ passing_rule: z+ .object({+ operator: z+ .enum(['gte', 'lte'])+ .describe('Pass at or above (gte), or at or below (lte), the threshold.'),+ threshold: z.number().describe('Finite passing threshold within any configured score bounds.'),+ })+ .strict()+ .nullable()+ .optional()+ .describe('Optional passing rule. Omit or set null for neutral scores. Each version keeps its own rule.'),}).strict().describe('Config shape used when kind is "numeric".')@@ -237,6 +260,11 @@ const BooleanScoreDefinitionConfigSchema = z.object({true_label: z.string().min(1).optional().describe('Optional label shown for the true branch (e.g. "Yes").'),false_label: z.string().min(1).optional().describe('Optional label shown for the false branch (e.g. "No").'),+ true_is_failure: z+ .boolean()+ .nullable()+ .optional()+ .describe('Whether true means failure. False, omitted, or null means true passes in offline evaluations.'),}).strict().describe('Config shape used when kind is "boolean".')@@ -248,7 +276,7 @@ export const ScoreDefinitionConfigSchema = zBooleanScoreDefinitionConfigSchema,]).describe(- 'Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch.'+ 'Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode + optional passing_rule.categories), numeric (min/max/step + optional passing_rule), or boolean (true_label/false_label + optional true_is_failure). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch.')export const PromptListInputSchema = z.object({diff --git a/services/mcp/src/tools/generated/ai_observability.ts b/services/mcp/src/tools/generated/ai_observability.tsindex 2f55d2ff217e..46ed68aacc58 100644--- a/services/mcp/src/tools/generated/ai_observability.ts+++ b/services/mcp/src/tools/generated/ai_observability.ts@@ -2176,6 +2176,12 @@ const llmaScoreDefinitionNewVersion = (): ToolBase<handler: async (context: Context, params: z.infer<ReturnType<typeof LlmaScoreDefinitionNewVersionSchema>>) => {const projectId = await context.stateManager.getProjectId()const body: Record<string, unknown> = {}+ if (params.name !== undefined) {+ body['name'] = params.name+ }+ if (params.description !== undefined) {+ body['description'] = params.description+ }if (params.config !== undefined) {body['config'] = params.config}diff --git a/services/mcp/src/tools/links/app-url-manifest.json b/services/mcp/src/tools/links/app-url-manifest.jsonindex c8eaed94daea..1fa37516abdc 100644--- a/services/mcp/src/tools/links/app-url-manifest.json+++ b/services/mcp/src/tools/links/app-url-manifest.json@@ -144,6 +144,11 @@"params": [],"scope": "project"},+ "aiObservabilityScorer": {+ "template": "/ai-evals/evaluations/scorers/{scorerId}",+ "params": ["scorerId"],+ "scope": "project"+ },"aiObservabilityScorers": {"template": "/ai-evals/evaluations/scorers","params": [],diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.jsonindex 1c7818a5a215..09ee7e7b3a0b 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/generate-app-url.json@@ -13,7 +13,7 @@"type": "object"},"url": {- "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/views\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}",+ "description": "A path template copied verbatim from the catalog below (e.g. `/persons/{uuid}`). Its `{placeholders}` are filled from `params`. These slugs come from PostHog's canonical route table, so they are always correct — never pass a path that is not in this list.\n\n/account-connected/{kind}\n/account/credential-review\n/account/social-connected\n/activity-logs\n/activity/{tab}\n/agentic/account-mismatch\n/agentic/authorize\n/ai\n/ai-enrichment\n/ai-evals/datasets\n/ai-evals/datasets/{id}\n/ai-evals/evaluations\n/ai-evals/evaluations/offline/experiments\n/ai-evals/evaluations/offline/experiments/{experimentId}\n/ai-evals/evaluations/scorers\n/ai-evals/evaluations/scorers/{scorerId}\n/ai-evals/evaluations/scorers/{scorerId}/offline\n/ai-evals/evaluations/templates\n/ai-evals/evaluations/{id}\n/ai-evals/taggers\n/ai-evals/taggers/{id}\n/ai-gateway\n/ai-observability/clusters\n/ai-observability/clusters/{runId}/{clusterId}\n/ai-observability/dashboard\n/ai-observability/errors\n/ai-observability/generations\n/ai-observability/playground\n/ai-observability/reviews\n/ai-observability/self-driving\n/ai-observability/sentiment\n/ai-observability/sessions\n/ai-observability/sessions/{id}\n/ai-observability/tools\n/ai-observability/traces\n/ai-observability/traces/{id}\n/ai-observability/users\n/ai/history\n/alerts\n/approvals/{id}\n/autoresearch\n/autoresearch/new\n/autoresearch/{id}\n/billing/authorization_status\n/broadcasts\n/broadcasts/new\n/broadcasts/{id}\n/business-knowledge\n/business-knowledge/playground\n/business-knowledge/settings\n/business-knowledge/{id}\n/canvas\n/canvases/new\n/canvases/{id}\n/cli/authorize\n/cli/live\n/code-review\n/code/canvas/{channelId}/{dashboardId}\n/code/channel/{channelId}\n/code/loop/{loopId}\n/code/task/{taskId}\n/cohorts\n/cohorts/{id}\n/cohorts/{id}/calculation-history\n/connect/vercel/link\n/coupons/{campaign}\n/create-organization\n/customer_analytics\n/customer_analytics/accounts\n/customer_analytics/accounts/by-external-id/{externalId}\n/customer_analytics/accounts/{accountId}\n/customer_analytics/announcements\n/customer_analytics/configuration\n/customer_analytics/dashboard\n/customer_analytics/feature-requests\n/customer_analytics/feed\n/customer_analytics/journeys\n/customer_analytics/journeys/new\n/customer_analytics/journeys/templates\n/customer_analytics/journeys/{id}/edit\n/customer_analytics/notes\n/customer_analytics/tasks\n/dashboard\n/dashboard/templates/{templateId}/copy-to-project\n/dashboard/{id}\n/dashboard/{id}/sharing\n/dashboard/{id}/subscriptions\n/dashboard/{id}/subscriptions/{subscriptionId}\n/dashboard/{id}/tiles/{tileId}\n/data-catalog\n/data-catalog/metrics/{name}\n/data-management/actions\n/data-management/actions/new\n/data-management/actions/new/\n/data-management/actions/{id}\n/data-management/annotations\n/data-management/annotations/{id}\n/data-management/core-events\n/data-management/database\n/data-management/destinations\n/data-management/event-filtering\n/data-management/events\n/data-management/events/{id}\n/data-management/events/{id}/edit\n/data-management/history\n/data-management/ingestion-warnings\n/data-management/ingestion-warnings-v2\n/data-management/managed-viewsets\n/data-management/materialized-columns\n/data-management/properties\n/data-management/properties/{id}\n/data-management/properties/{id}/edit\n/data-management/revenue\n/data-management/schema\n/data-management/sources\n/data-management/sources/{id}/schemas\n/data-management/sources/{sourceId}/schemas/{schemaId}\n/data-management/transformations\n/data-management/variables\n/data-management/variables/{id}\n/data-management/variables/{id}/edit\n/data-management/warehouse-destinations\n/data-management/warehouse-properties\n/data-ops\n/data-warehouse/connect\n/data-warehouse/new-source\n/debug\n/debug/hog\n/debug/precompute\n/early_access_features\n/early_access_features/{id}\n/embedded/{token}\n/endpoints\n/endpoints/{name}\n/engineering-analytics/authors\n/engineering-analytics/authors/{handle}\n/engineering-analytics/deploys\n/engineering-analytics/overview\n/engineering-analytics/pull-requests\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/runs/{runId}\n/engineering-analytics/repos/{repoOwner}/{repoName}/actions/workflows/{workflowName}\n/engineering-analytics/repos/{repoOwner}/{repoName}/pull-requests/{number}\n/engineering-analytics/teams\n/engineering-analytics/teams/{ownerTeam}\n/engineering-analytics/tests\n/engineering-analytics/workflows\n/error_tracking\n/error_tracking/alerts/new/{templateId}\n/error_tracking/alerts/{id}\n/error_tracking/fingerprint/{fingerprint}\n/error_tracking/{id}\n/etl\n/events/{id}/{timestamp}\n/experiments\n/experiments/shared-metrics\n/experiments/shared-metrics/{id}\n/experiments/staff\n/experiments/{id}\n/exports\n/feature_flags\n/feature_flags/new\n/feature_flags/staff\n/feature_flags/staff/cohorts\n/feature_flags/templates\n/feature_flags/{id}\n/files\n/functions/new/{templateId}\n/functions/{id}\n/games/368hedgehogs\n/games/flappyhog\n/games/shipit\n/groups/{groupTypeIndex}\n/groups/{groupTypeIndex}/new\n/groups/{groupTypeIndex}/{groupKey}\n/health\n/health/alerts\n/health/pipeline-status\n/health/sdk-health\n/health/{category}\n/heatmaps\n/heatmaps/new\n/heatmaps/recording\n/heatmaps/{id}\n/home\n/identity-matching\n/inbox\n/inbox/reports/triage\n/inbox/scouts/findings\n/inbox/scouts/runs\n/inbox/scouts/scratchpad\n/inbox/scouts/{skillName}\n/inbox/{tab}/{reportId}\n/insights\n/insights/new\n/insights/quick-start\n/insights/{id}\n/insights/{id}/edit\n/insights/{id}/sharing\n/insights/{id}/subscriptions\n/insights/{id}/subscriptions/{subscriptionId}\n/insights/{insightShortId}/alerts\n/instance/async_migrations\n/instance/async_migrations/future\n/instance/async_migrations/settings\n/instance/dead_letter_queue\n/instance/kafka_inspector\n/instance/metrics\n/instance/settings\n/instance/staff_users\n/instance/status\n/integrations/stripe/confirm-install\n/integrations/vercel/link-error\n/integrations/{kind}/callback\n/integrations/{slug}\n/legal\n/legal/new/{type}\n/link/{id}\n/links\n/live-debugger\n/login\n/login/2fa\n/login/2fa_setup\n/logs\n/logs/alerts/{alertId}/notifications/{hogFunctionId}\n/logs/alerts/{id}\n/logs/drop-rules/new\n/logs/drop-rules/{id}\n/logs/retention-rules/new\n/logs/retention-rules/{id}\n/managed_migrations\n/managed_migrations/new\n/marketing\n/mcp-analytics\n/mcp-analytics/activity\n/mcp-analytics/dashboard\n/mcp-analytics/intent-clustering\n/mcp-analytics/missing-capabilities\n/mcp-analytics/notifications\n/mcp-analytics/sessions\n/mcp-analytics/tool-quality\n/mcp-analytics/tool-quality/{toolName}\n/mcp-registry\n/mcp-servers\n/mcp-servers/agent/{id}\n/mcp-servers/member/{id}\n/mcp-servers/server/{id}\n/mcp-servers/{tab}\n/metrics\n/models\n/models/{id}\n/move-to-cloud\n/my-tickets\n/notebooks\n/notebooks/widgets/{widgetId}\n/notebooks/{shortId}\n/oauth/authorize\n/onboarding\n/organization-deactivated\n/organization-pending-deletion\n/organization/billing\n/organization/billing/overview\n/organization/billing/real-time-usage\n/organization/confirm-creation\n/organization/create-project\n/person/{id}\n/persons\n/persons/{uuid}\n/pipeline/batch-exports/new/{service}\n/pipeline/batch-exports/{id}\n/pipeline/new/\n/pipeline/plugins/{id}\n/preflight\n/product_tours\n/product_tours/{id}\n/project-pending-deletion\n/prompt-management/prompts\n/prompt-management/prompts/{name}\n/pulse\n/replay-vision\n/replay-vision/new/template\n/replay-vision/observations/{observationId}\n/replay-vision/{id}/budget\n/replay-vision/{id}/configure\n/replay-vision/{id}/details\n/replay-vision/{id}/overview\n/replay-vision/{id}/self-driving\n/replay-vision/{id}/template\n/replay-vision/{id}/triggers\n/replay/file-playback\n/replay/home\n/replay/kiosk\n/replay/playlists/{id}\n/replay/settings\n/replay/{id}\n/reset\n/reset/{userUuid}/{token}\n/reset_2fa/{userUuid}/{token}\n/resource-transfer/{resourceKind}/{resourceId}\n/sessions/{id}\n/settings/environment-approvals\n/settings/organization-authentication/{feature}/{configId}\n/settings/project\n/settings/user-feature-previews\n/shared/{token}\n/shared_dashboard/{shareToken}\n/signup\n/signup/{id}\n/site/{url}\n/skills\n/skills/community\n/skills/{categoryTab}\n/skills/{name}\n/slack-task-context\n/spaces\n/spaces/{id}\n/spaces/{id}/canvases\n/spaces/{id}/settings\n/sql\n/stamphog\n/stamphog/digests\n/stamphog/install/callback\n/stamphog/runs\n/startups\n/streamlit-apps\n/streamlit-apps/new\n/streamlit-apps/{id}\n/streamlit-apps/{id}/edit\n/subscriptions\n/subscriptions/new\n/subscriptions/{id}\n/subscriptions/{id}/edit\n/support\n/support/settings\n/support/tickets\n/support/tickets/{ticketId}\n/surveys\n/surveys/form/new\n/surveys/guided/new\n/surveys/{id}\n/tasks\n/tasks/new\n/tasks/{taskId}\n/terminal\n/themes/custom-css\n/toolbar\n/tracing\n/tracing/retention-rules/new\n/tracing/retention-rules/{id}\n/unsubscribe\n/user_research\n/user_research/{id}\n/user_research/{topicId}/response/{responseId}\n/verify_email\n/views\n/visual_review\n/visual_review/repos/{repoId}/flakiness\n/visual_review/repos/{repoId}/runs\n/visual_review/repos/{repoId}/snapshots\n/visual_review/repos/{repoId}/{runType}/snapshots/{identifier}\n/visual_review/runs/{runId}\n/visual_review/settings\n/web\n/web-scripts\n/web-scripts/new\n/web/agents\n/web/bots\n/web/content-autopilot\n/web/health\n/web/live\n/web/marketing\n/web/page-performance\n/web/page-reports\n/web/recap\n/web/session-attribution-explorer\n/web/web-vitals\n/wizard/runs\n/workflows\n/workflows/library/messages/{id}\n/workflows/library/templates/new\n/workflows/library/templates/{id}\n/workflows/new/workflow\n/workflows/{id}/{tab}","type": "string"}},diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-create.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-create.jsonindex a772e298cea5..2c96d32705ca 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-create.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-create.json@@ -47,6 +47,29 @@"minItems": 1,"type": "array"},+ "passing_rule": {+ "anyOf": [+ {+ "additionalProperties": false,+ "properties": {+ "categories": {+ "description": "Passing category keys. Every returned category must be included.",+ "items": {+ "maxLength": 128,+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["categories"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional passing categories. Omit or set null for neutral scores. Each version keeps its own rule."+ },"selection_mode": {"description": "Whether reviewers select one option or many. Defaults to \"single\".","enum": ["single", "multiple"],@@ -68,6 +91,30 @@"description": "Optional inclusive minimum score.","type": "number"},+ "passing_rule": {+ "anyOf": [+ {+ "additionalProperties": false,+ "properties": {+ "operator": {+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",+ "enum": ["gte", "lte"],+ "type": "string"+ },+ "threshold": {+ "description": "Finite passing threshold within any configured score bounds.",+ "type": "number"+ }+ },+ "required": ["operator", "threshold"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional passing rule. Omit or set null for neutral scores. Each version keeps its own rule."+ },"step": {"description": "Optional increment step for numeric input, e.g. 1 or 0.5.","exclusiveMinimum": 0,@@ -85,6 +132,17 @@"minLength": 1,"type": "string"},+ "true_is_failure": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether true means failure. False, omitted, or null means true passes in offline evaluations."+ },"true_label": {"description": "Optional label shown for the true branch (e.g. \"Yes\").","minLength": 1,@@ -94,7 +152,7 @@"type": "object"}],- "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode + optional passing_rule.categories), numeric (min/max/step + optional passing_rule), or boolean (true_label/false_label + optional true_is_failure). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."},"description": {"anyOf": [diff --git a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-new-version.json b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-new-version.jsonindex c7ceef1d22d3..24dd2f4839bc 100644--- a/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-new-version.json+++ b/services/mcp/tests/unit/__snapshots__/tool-schemas/llma-score-definition-new-version.json@@ -47,6 +47,29 @@"minItems": 1,"type": "array"},+ "passing_rule": {+ "anyOf": [+ {+ "additionalProperties": false,+ "properties": {+ "categories": {+ "description": "Passing category keys. Every returned category must be included.",+ "items": {+ "maxLength": 128,+ "type": "string"+ },+ "type": "array"+ }+ },+ "required": ["categories"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional passing categories. Omit or set null for neutral scores. Each version keeps its own rule."+ },"selection_mode": {"description": "Whether reviewers select one option or many. Defaults to \"single\".","enum": ["single", "multiple"],@@ -68,6 +91,30 @@"description": "Optional inclusive minimum score.","type": "number"},+ "passing_rule": {+ "anyOf": [+ {+ "additionalProperties": false,+ "properties": {+ "operator": {+ "description": "Pass at or above (gte), or at or below (lte), the threshold.",+ "enum": ["gte", "lte"],+ "type": "string"+ },+ "threshold": {+ "description": "Finite passing threshold within any configured score bounds.",+ "type": "number"+ }+ },+ "required": ["operator", "threshold"],+ "type": "object"+ },+ {+ "type": "null"+ }+ ],+ "description": "Optional passing rule. Omit or set null for neutral scores. Each version keeps its own rule."+ },"step": {"description": "Optional increment step for numeric input, e.g. 1 or 0.5.","exclusiveMinimum": 0,@@ -85,6 +132,17 @@"minLength": 1,"type": "string"},+ "true_is_failure": {+ "anyOf": [+ {+ "type": "boolean"+ },+ {+ "type": "null"+ }+ ],+ "description": "Whether true means failure. False, omitted, or null means true passes in offline evaluations."+ },"true_label": {"description": "Optional label shown for the true branch (e.g. \"Yes\").","minLength": 1,@@ -94,11 +152,27 @@"type": "object"}],- "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode), numeric (min/max/step), or boolean (true_label/false_label). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."+ "description": "Immutable scorer configuration. Pick the shape matching the scorer kind: categorical (options + selection_mode + optional passing_rule.categories), numeric (min/max/step + optional passing_rule), or boolean (true_label/false_label + optional true_is_failure). The server validates the shape against the kind on the parent scorer and returns 400 on a mismatch."+ },+ "description": {+ "anyOf": [+ {+ "type": "string"+ },+ {+ "type": "null"+ }+ ],+ "description": "Updated scorer description, saved with this version."},"id": {"description": "A UUID string identifying this score definition.","type": "string"+ },+ "name": {+ "description": "Updated scorer name, saved with this version.",+ "maxLength": 255,+ "type": "string"}},"required": ["id", "config"],diff --git a/services/mcp/tests/unit/score-definition-config.test.ts b/services/mcp/tests/unit/score-definition-config.test.tsnew file mode 100644index 000000000000..fed453b4a037--- /dev/null+++ b/services/mcp/tests/unit/score-definition-config.test.ts@@ -0,0 +1,29 @@+import { describe, expect, it } from 'vitest'++import { ScoreDefinitionConfigSchema } from '@/schema/tool-inputs'++describe('Scorer passing configuration', () => {+ it.each([+ { options: [{ key: 'good', label: 'Good' }], passing_rule: { categories: ['good'] } },+ {},+ { true_is_failure: null },+ { true_is_failure: false },+ { true_is_failure: true, true_label: 'Defect', false_label: 'Clear' },+ { passing_rule: null },+ { min: 0, max: 5, passing_rule: { operator: 'gte', threshold: 3 } },+ { passing_rule: { operator: 'lte', threshold: 0.5 } },+ ])('preserves explicit rules and omitted polarity: %j', (config) => {+ expect(ScoreDefinitionConfigSchema.parse(config)).toEqual(config)+ })++ it.each([+ { passing_rule: { operator: 'gt', threshold: 3 } },+ { passing_rule: { operator: 'gte' } },+ { passing_rule: { operator: 'gte', threshold: true } },+ { passing_rule: { operator: 'gte', threshold: Infinity } },+ { passing_rule: { operator: 'gte', threshold: 3, unexpected: true } },+ { true_is_failure: false, passing_rule: { operator: 'gte', threshold: 3 } },+ ])('rejects malformed or mixed scorer configuration: %j', (config) => {+ expect(ScoreDefinitionConfigSchema.safeParse(config).success).toBe(false)+ })+})