detectkit 0.66.2__tar.gz → 0.66.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (173) hide show
  1. {detectkit-0.66.2/detectkit.egg-info → detectkit-0.66.3}/PKG-INFO +1 -1
  2. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/__init__.py +1 -1
  3. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/cli.md +6 -4
  4. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/detectors.md +5 -3
  5. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/skills/dtk-tune/SKILL.md +11 -10
  6. detectkit-0.66.3/detectkit/tuning/assets/tune.js +187 -0
  7. {detectkit-0.66.2 → detectkit-0.66.3/detectkit.egg-info}/PKG-INFO +1 -1
  8. detectkit-0.66.2/detectkit/tuning/assets/tune.js +0 -187
  9. {detectkit-0.66.2 → detectkit-0.66.3}/LICENSE +0 -0
  10. {detectkit-0.66.2 → detectkit-0.66.3}/MANIFEST.in +0 -0
  11. {detectkit-0.66.2 → detectkit-0.66.3}/README.md +0 -0
  12. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/__init__.py +0 -0
  13. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/__init__.py +0 -0
  14. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/base.py +0 -0
  15. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/branding.py +0 -0
  16. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/discord.py +0 -0
  17. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/email.py +0 -0
  18. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/factory.py +0 -0
  19. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/googlechat.py +0 -0
  20. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/mattermost.py +0 -0
  21. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/ntfy.py +0 -0
  22. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/slack.py +0 -0
  23. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/teams.py +0 -0
  24. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/telegram.py +0 -0
  25. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/channels/webhook.py +0 -0
  26. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/__init__.py +0 -0
  27. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_base.py +0 -0
  28. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_cooldown.py +0 -0
  29. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_decision.py +0 -0
  30. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_dispatch.py +0 -0
  31. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_recovery.py +0 -0
  32. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_replay.py +0 -0
  33. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/_types.py +0 -0
  34. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/alerting/orchestrator/orchestrator.py +0 -0
  35. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/__init__.py +0 -0
  36. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/_base.py +0 -0
  37. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/_types.py +0 -0
  38. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/autotuner.py +0 -0
  39. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/axis_spec.py +0 -0
  40. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/config_emitter.py +0 -0
  41. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/crossval.py +0 -0
  42. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/detector_select.py +0 -0
  43. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/distribution.py +0 -0
  44. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/grid_search.py +0 -0
  45. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/labels.py +0 -0
  46. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/result.py +0 -0
  47. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/runner.py +0 -0
  48. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/scoring.py +0 -0
  49. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/seasonality_search.py +0 -0
  50. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/settings.py +0 -0
  51. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/autotune/window_select.py +0 -0
  52. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/__init__.py +0 -0
  53. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/_output.py +0 -0
  54. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/CLAUDE.section.md +0 -0
  55. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/alerting.md +0 -0
  56. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/autotune.md +0 -0
  57. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/metrics.md +0 -0
  58. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/overview.md +0 -0
  59. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/rules/project.md +0 -0
  60. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/skills/dtk-autotune/SKILL.md +0 -0
  61. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/skills/dtk-feedback/SKILL.md +0 -0
  62. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/skills/dtk-new-metric/SKILL.md +0 -0
  63. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/assets/claude/skills/dtk-setup-project/SKILL.md +0 -0
  64. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/__init__.py +0 -0
  65. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/autotune.py +0 -0
  66. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/clean.py +0 -0
  67. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/init.py +0 -0
  68. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/init_claude.py +0 -0
  69. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/mcp.py +0 -0
  70. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/osi.py +0 -0
  71. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/run.py +0 -0
  72. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/test_alert.py +0 -0
  73. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/tune.py +0 -0
  74. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/ui.py +0 -0
  75. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/commands/unlock.py +0 -0
  76. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/cli/main.py +0 -0
  77. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/__init__.py +0 -0
  78. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/metric_config.py +0 -0
  79. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/metric_io.py +0 -0
  80. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/profile.py +0 -0
  81. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/project_config.py +0 -0
  82. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/config/validator.py +0 -0
  83. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/core/__init__.py +0 -0
  84. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/core/interval.py +0 -0
  85. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/core/models.py +0 -0
  86. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/__init__.py +0 -0
  87. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/_sql_manager.py +0 -0
  88. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/bigquery_manager.py +0 -0
  89. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/clickhouse_manager.py +0 -0
  90. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/duckdb_manager.py +0 -0
  91. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/__init__.py +0 -0
  92. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_alert_states.py +0 -0
  93. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_autotune_runs.py +0 -0
  94. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_base.py +0 -0
  95. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_datapoints.py +0 -0
  96. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_detections.py +0 -0
  97. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_maintenance.py +0 -0
  98. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_metrics.py +0 -0
  99. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_schema.py +0 -0
  100. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/_tasks.py +0 -0
  101. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/internal_tables/manager.py +0 -0
  102. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/manager.py +0 -0
  103. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/mysql_manager.py +0 -0
  104. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/postgres_manager.py +0 -0
  105. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/snowflake_manager.py +0 -0
  106. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/source_manager.py +0 -0
  107. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/database/tables.py +0 -0
  108. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/__init__.py +0 -0
  109. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/base.py +0 -0
  110. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/factory.py +0 -0
  111. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/seasonality.py +0 -0
  112. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/__init__.py +0 -0
  113. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/_windowed.py +0 -0
  114. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/autoreg.py +0 -0
  115. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/iqr.py +0 -0
  116. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/mad.py +0 -0
  117. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/manual_bounds.py +0 -0
  118. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/detectors/statistical/zscore.py +0 -0
  119. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/loaders/__init__.py +0 -0
  120. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/loaders/errors.py +0 -0
  121. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/loaders/metric_loader.py +0 -0
  122. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/loaders/query_template.py +0 -0
  123. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/__init__.py +0 -0
  124. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/context.py +0 -0
  125. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/errors.py +0 -0
  126. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/serialize.py +0 -0
  127. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/server.py +0 -0
  128. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/mcp/tools.py +0 -0
  129. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/__init__.py +0 -0
  130. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/error_dispatch.py +0 -0
  131. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/__init__.py +0 -0
  132. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/_alert_step.py +0 -0
  133. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/_base.py +0 -0
  134. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/_detect_step.py +0 -0
  135. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/_load_step.py +0 -0
  136. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/_types.py +0 -0
  137. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/orchestration/task_manager/manager.py +0 -0
  138. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/reporting/__init__.py +0 -0
  139. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/reporting/assets/report.js +0 -0
  140. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/reporting/builder.py +0 -0
  141. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/reporting/html_report.py +0 -0
  142. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/__init__.py +0 -0
  143. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/errors.py +0 -0
  144. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/exporter.py +0 -0
  145. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/importer.py +0 -0
  146. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/osi_model.py +0 -0
  147. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/semantic/query_gen.py +0 -0
  148. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/tuning/__init__.py +0 -0
  149. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/tuning/config_writer.py +0 -0
  150. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/tuning/html.py +0 -0
  151. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/tuning/payload.py +0 -0
  152. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/tuning/server.py +0 -0
  153. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/__init__.py +0 -0
  154. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/assets/ui.js +0 -0
  155. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/html.py +0 -0
  156. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/jobs.py +0 -0
  157. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/metric_files.py +0 -0
  158. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/overview.py +0 -0
  159. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/ui/server.py +0 -0
  160. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/utils/__init__.py +0 -0
  161. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/utils/datetime_utils.py +0 -0
  162. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/utils/env_interpolation.py +0 -0
  163. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/utils/json_utils.py +0 -0
  164. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit/utils/stats.py +0 -0
  165. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit.egg-info/SOURCES.txt +0 -0
  166. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit.egg-info/dependency_links.txt +0 -0
  167. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit.egg-info/entry_points.txt +0 -0
  168. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit.egg-info/requires.txt +0 -0
  169. {detectkit-0.66.2 → detectkit-0.66.3}/detectkit.egg-info/top_level.txt +0 -0
  170. {detectkit-0.66.2 → detectkit-0.66.3}/pyproject.toml +0 -0
  171. {detectkit-0.66.2 → detectkit-0.66.3}/requirements.txt +0 -0
  172. {detectkit-0.66.2 → detectkit-0.66.3}/setup.cfg +0 -0
  173. {detectkit-0.66.2 → detectkit-0.66.3}/setup.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: detectkit
3
- Version: 0.66.2
3
+ Version: 0.66.3
4
4
  Summary: Metric monitoring with automatic anomaly detection
5
5
  Author: detectkit team
6
6
  License: MIT
@@ -4,7 +4,7 @@ detectk - Anomaly Detection for Time-Series Metrics
4
4
  A Python library for data analysts and engineers to monitor metrics with automatic anomaly detection.
5
5
  """
6
6
 
7
- __version__ = "0.66.2"
7
+ __version__ = "0.66.3"
8
8
 
9
9
  from detectkit.core.interval import Interval
10
10
  from detectkit.core.models import ColumnDefinition, TableModel
@@ -124,10 +124,12 @@ the **Points shown** data window, the alert rule (**direction** + **consecutive
124
124
  anomalies** + the **anomaly_window**/**min_anomaly_share** pair) and the
125
125
  **y = 0** toggle — stay visible in every mode. The chart is
126
126
  **zoomable** (scroll/drag + navigator strip) with a **"Points shown"** trim slider.
127
- Trim it below what the detector needs to warm up (stabilization roughly doubles
128
- it — Autoreg needs `2·window_size + lags`) and the chart dims completely with an
129
- explanation plus an inline warning naming the shortfall and the fixes (raise
130
- Points shown / lower window size / disable stabilization).
127
+ The band is drawn wherever the detector scores (the same band the pipeline
128
+ persists), only lightly dimming the cold-start lead-in — so a long autoreg warm-up
129
+ (`2·window_size + lags`) no longer blanks the chart. The chart dims completely with
130
+ an explanation only when the detector scored **nothing** (window below
131
+ `min_samples`, Points shown too low, or a view full of gaps), naming the fixes
132
+ (raise Window size / Points shown, lower Lags / `min_samples`, disable stabilization).
131
133
  Clicking **Apply** writes the chosen
132
134
  config back into the metric YAML **in place** (autotune, by contrast, writes a new
133
135
  `__tuned_<id>.yml` and never edits the original). Apply **merges** — it rewrites
@@ -236,9 +236,11 @@ recency weighting gives an ongoing incident's points more weight), `detrend`,
236
236
  `smoothing`, `input_type` and seasonality groups, and is near-neutral on clean
237
237
  series. Enabling it is a hashed change — it produces a new `detector_id` and
238
238
  recomputes on the next run; existing configs that don't set it keep their ids.
239
- It also adds one extra `window_size` of warm-up context (`mad`/`zscore`/`iqr`
240
- and `autoreg` alike) — the `dtk tune` cockpit's visible band respects this,
241
- so with `clamp` on the band starts one window later than without it.
239
+ It also adds one extra `window_size` of warm-up *context* (`mad`/`zscore`/`iqr`
240
+ and `autoreg` alike) — this is how much trailing history the pipeline loads, not
241
+ where a band appears: the `dtk tune` cockpit draws the band wherever the detector
242
+ actually scores (as the pipeline persists it), only lightly dimming the cold-start
243
+ lead-in, so `clamp` no longer blanks the cockpit chart on a short view.
242
244
 
243
245
  ## Feature compatibility
244
246
 
@@ -95,16 +95,17 @@ alerts): **Points shown**, the alert rule (**direction** + **consecutive
95
95
  anomalies** + the **anomaly_window**/**min_anomaly_share** fraction pair), and
96
96
  the **y = 0** reference-line toggle.
97
97
 
98
- **Warm-up matters when Points shown is trimmed low.** The band and anomaly
99
- dots only appear once the detector has enough trailing history to warm up —
100
- if you trim **Points shown** below that, the whole chart dims with an
101
- explanation ("all shown points are detector warm-up — nothing to score yet")
102
- and an inline warning names the exact point count still needed, with three
103
- fixes: raise **Points shown**, lower **Window size**, or turn
104
- **Stabilization** off. **Stabilization** roughly doubles the requirement —
105
- Autoreg needs close to `2 · window_size + lags` points at its defaults (over
106
- 400) — so watch for this especially right after switching to Autoreg or
107
- turning stabilization on with a short **Points shown**.
98
+ **The band shows wherever the detector scores** — the same band the pipeline
99
+ persists and a dashboard displays — so the cockpit no longer hides it over the
100
+ long autoreg warm-up (an earlier version blanked the chart whenever the shown
101
+ window was shorter than `2 · window_size + lags`, which for an hourly metric with
102
+ a 20-day window is 40 days — nothing to do with seasonality, which autoreg
103
+ ignores). The cold-start lead-in is only lightly dimmed with a "detection at
104
+ full power →" divider. You'll see a real "no band" warning **only** when the
105
+ detector scored *nothing at all* — its **Window size** is below `min_samples`,
106
+ **Points shown** is trimmed too low, or the shown window is full of gaps — and it
107
+ names the fixes (raise **Window size** / **Points shown**, lower **Lags** /
108
+ `min_samples`, or turn **Stabilization** off).
108
109
 
109
110
  ## Step 3 — The four modes (autotune is one of them)
110
111
 
@@ -0,0 +1,187 @@
1
+ "use strict";(()=>{var jo={"--term-bg":"#211e1a","--clay":"#d15b36","--st-anomaly":"#d63232","--st-recovery":"#36a64f","--st-nodata":"#f0ad4e","--st-error":"#5a7a8c","--faint":"#9a9384","--muted":"#6e675b","--border":"#332f29","--term-border":"#332f29"};function K(n){return getComputedStyle(document.documentElement).getPropertyValue(n).trim()||jo[n]||"#888"}function Uo(n){let i=n.replace("#","").trim();i.length===3&&(i=i[0]+i[0]+i[1]+i[1]+i[2]+i[2]);let f=parseInt(i,16);return i.length!==6||Number.isNaN(f)?[209,91,54]:[f>>16&255,f>>8&255,f&255]}function F(n,i){let[f,t,v]=Uo(n);return`rgba(${f},${t},${v},${i})`}function bo(n){let i=Math.max(1,window.devicePixelRatio||1),f=n.clientWidth||n.offsetWidth||0,t=n.clientHeight||n.offsetHeight||0;return n.width=Math.round(f*i),n.height=Math.round(t*i),i}var Gn=Number.isFinite;function Yn(n,i,f,t,v,y,S,g,k,D,A,I){let ee=i.length,ne=Math.max(1,Math.round(S)),de=v-t||1,Y=0;for(let U=0;U<ee;U++){let a=f[U];!Gn(a)||i[U]<t||i[U]>v||Y++}if(n.strokeStyle=D,n.lineWidth=A*I,n.lineJoin="round",n.beginPath(),Y<=ne){let U=!1;for(let a=0;a<ee;a++){let w=f[a],N=i[a];if(!Gn(w)||N<t||N>v){U=!1;continue}let te=g(N),be=k(w);U?n.lineTo(te,be):(n.moveTo(te,be),U=!0)}}else{let U=new Array(ne).fill(null),a=new Array(ne).fill(null);for(let N=0;N<ee;N++){let te=f[N],be=i[N];if(!Gn(te)||be<t||be>v)continue;let $=Math.floor((be-t)/de*(ne-1));$=$<0?0:$>ne-1?ne-1:$,(U[$]===null||te<U[$])&&(U[$]=te),(a[$]===null||te>a[$])&&(a[$]=te)}let w=!1;for(let N=0;N<ne;N++){if(a[N]===null){w=!1;continue}let te=y+N,be=k(a[N]),$=k(U[N]);w?n.lineTo(te,be):(n.moveTo(te,be),w=!0),n.lineTo(te,$)}}n.stroke()}function go(n){let i=Math.abs(n);return i>=1e3?n.toFixed(0):i>=10?n.toFixed(1):i>=1?n.toFixed(2):n.toFixed(3)}function vo(n,i){let f=new Date(n).toISOString();return i<2*864e5?f.slice(5,16).replace("T"," "):f.slice(5,10)}function Kn(n,i,f){return{left:i.l*f,top:i.t*f,right:n.width-i.r*f,bottom:n.height-i.b*f}}function yo(n,i,f,t,v,y,S){let g=Kn(i,f,t),k=Math.max(g.left,Math.min(v(y),g.right));k<=g.left+.5||(n.save(),n.fillStyle="rgba(17,15,13,0.42)",n.fillRect(g.left,g.top,k-g.left,g.bottom-g.top),n.strokeStyle=F(K("--faint"),.7),n.lineWidth=1*t,n.setLineDash([4*t,4*t]),n.beginPath(),n.moveTo(k,g.top),n.lineTo(k,g.bottom),n.stroke(),n.setLineDash([]),n.fillStyle=F(K("--faint"),.95),n.font=`${10*t}px ui-monospace, monospace`,n.textAlign="left",n.textBaseline="top",n.fillText(S,k+6*t,g.top+5*t),n.restore())}function wo(n,i,f,t,v){let y=Kn(i,f,t);if(y.right<=y.left||y.bottom<=y.top)return;n.save(),n.fillStyle="rgba(17,15,13,0.42)",n.fillRect(y.left,y.top,y.right-y.left,y.bottom-y.top),n.fillStyle=F(K("--faint"),.95),n.font=`${10*t}px ui-monospace, monospace`,n.textAlign="center",n.textBaseline="middle";let S=y.right-y.left-12*t;S>0&&n.fillText(v,(y.left+y.right)/2,y.top+(y.bottom-y.top)*.3,S),n.restore()}function xo(n,i,f,t,v,y,S){let g=Kn(i,f,t),k=5*t;n.save();for(let D=0;D<y.length;D++){let A=y[D],I=v(A.t);if(I<g.left-1||I>g.right+1)continue;let ee=S(A.kind);n.strokeStyle=F(ee,.45),n.lineWidth=1*t,n.beginPath(),n.moveTo(I,g.top),n.lineTo(I,g.bottom),n.stroke(),n.fillStyle=ee,n.beginPath(),n.moveTo(I-k,g.top),n.lineTo(I+k,g.top),n.lineTo(I,g.top+k*1.4),n.closePath(),n.fill()}n.restore()}var Vo={mad:1,zscore:2,iqr:4};function Go(n,i){let f=n.seasonalityData;if(!f||f.length===0)return 0;let t=0;for(let v of i){let y=new Set;for(let S of f)y.add(v.map(g=>{var k;return String((k=S==null?void 0:S[g])!=null?k:"")}).join("|"));t=Math.max(t,y.size)}return t}function Yo(n,i){var v;if(i.type==="manual_bounds")return i.inputType!=="values"?1:0;if(i.type==="autoreg"){let y=Math.max(1,Math.round((v=i.lags)!=null?v:5)),S=i.windowSize+y;return i.inputType!=="values"&&(S+=1),i.stabilization==="clamp"&&(S+=i.windowSize),S}let f=Math.max(i.minSamples,Vo[i.type]);if(i.smoothing==="sma"&&(f=Math.max(f,i.smoothingWindow-1)),i.smoothing==="ema"&&(f=Math.max(f,Math.ceil(5/i.smoothingAlpha))),i.inputType!=="values"&&(f=Math.max(f,1)),i.seasonalityComponents!==null&&i.seasonalityComponents.length>0&&Array.isArray(n.seasonalityData)&&n.seasonalityData.length>0){let y=Go(n,i.seasonalityComponents);if(y>0){let S=i.minSamplesPerGroup*y;i.windowSize>=S&&(f=Math.max(f,S))}}return i.stabilization==="clamp"&&(f+=i.windowSize),f}function ko(n,i){return Math.min(Yo(n,i),n.timestamps.length)}var R={l:52,r:14,t:14,b:26},qn=46,Ko=10,qo=13,_e=Number.isFinite,_t=1e3,Dt=60*_t,Pt=60*Dt,Te=24*Pt,Xn=[_t,2*_t,5*_t,10*_t,15*_t,30*_t,Dt,2*Dt,5*Dt,10*Dt,15*Dt,30*Dt,Pt,2*Pt,3*Pt,6*Pt,12*Pt,Te,2*Te,3*Te,5*Te,7*Te,14*Te];function So(n,i,f){let t=Math.max(i-n,1);if(t>f*14*Te){let g=[1,2,3,6,12,24,36,60,120,240],k=g[g.length-1];for(let de of g)if(t/(de*30.44*Te)<=f){k=de;break}let D=new Date(n),A=D.getUTCFullYear(),I=D.getUTCMonth();if(k>=12){let de=k/12;A=Math.floor(A/de)*de,I=0}else I=Math.floor(I/k)*k;let ee=[],ne=Date.UTC(A,I,1);for(;ne<=i;)ne>=n&&ee.push(ne),I+=k,A+=Math.floor(I/12),I%=12,ne=Date.UTC(A,I,1);return{ticks:ee,step:k*30*Te}}let v=Xn[Xn.length-1];for(let g of Xn)if(t/g<=f){v=g;break}let y;if(v%Te===0){let g=new Date(n);y=Date.UTC(g.getUTCFullYear(),g.getUTCMonth(),g.getUTCDate());let k=v/Te,D=Math.round(y/Te);y+=(k-D%k)%k*Te}else y=Math.ceil(n/v)*v;let S=[];for(let g=y;g<=i;g+=v)g>=n&&S.push(g);return{ticks:S,step:v}}function Jn(n,i){let f=new Date(n).toISOString();return i>=320*Te?f.slice(0,4):i>=26*Te?f.slice(0,7):i>=Te?f.slice(5,10):i>=Pt?f.slice(5,16).replace("T"," "):f.slice(5,19).replace("T"," ")}function Mo(n,i={}){var Vt;let f=n.getContext("2d");if(!f)throw new Error("chart: 2D context unavailable");let t=f,v=!!i.navigable,y=v&&i.showNavigator!==!1,S=i.yFit==="data",g=!!i.labeling,k=(Vt=i.mode)!=null?Vt:"tune",D=()=>g?k:"tune",A=()=>D()!=="label",I=()=>D()==="review"?.3:1,ee=()=>D()==="tune"?1:D()==="review"?.3:.85,ne=()=>g&&D()==="label",de=()=>D()==="label"?1:.55,Y=()=>D()==="tune",U=()=>g&&(D()==="tune"||D()==="review"),a=1,w=null,N=-1,te=0,be=!!i.showZeroLine,$=[],oe=null,Qe=-1,C=null,ce=!1,De=!1,at="above",Ue=0,re=null,Le=null,ue=null,ge=null,Ae=null,J=!1,X=null,V=0,G=1,xe=0,ve=1,ie=0,me=1,qt="";function Xt(){a=bo(n)}let Ve=()=>y?(Ko+qn)*a:0,Oe=()=>n.width-(R.l+R.r)*a,He=()=>n.height-(R.t+R.b)*a-Ve(),Ze=()=>v?ie:V,Et=()=>v?me:G,Ge=()=>Et()-Ze()||1,Pe=()=>G-V||1,O=o=>R.l*a+(o-Ze())/Ge()*Oe(),ke=o=>n.height-R.b*a-Ve()-(o-xe)/(ve-xe||1)*He(),et=()=>n.height-qn*a,Se=()=>(qn-qo)*a,lt=()=>n.width-(R.l+R.r)*a,Re=o=>R.l*a+(o-V)/Pe()*lt(),En=o=>et()+Se()-(o-xe)/(ve-xe||1)*Se(),Jt=(o,r,c)=>{let l=new Array(o.length).fill(!1);if(o.length===0)return l;let d=t.measureText(Jn(o[0],c)).width+16*a,u=-1/0;for(let h=0;h<o.length;h++){let M=r(o[h]);M-u>=d&&(l[h]=!0,u=M)}return l},se=(o,r,c)=>Math.max(r,Math.min(c,o)),$e=()=>{let o=w==null?void 0:w.series,r=o?o.timestamps.length:0,c=r>1?Pe()/(r-1):1e3;return Math.max(c*8,1e3)};function Ne(o,r){var d;let c=r-o,l=$e();if(c<l){let u=(o+r)/2;o=u-l/2,r=u+l/2,c=l}c>=Pe()&&(o=V,r=G),o<V&&(r+=V-o,o=V),r>G&&(o-=r-G,r=G),ie=se(o,V,G),me=se(r,V,G),ce||(d=i.onViewChange)==null||d.call(i,ie,me),De&&fe(),B()}function bt(o,r){v&&(ce=!0,Ne(o,r),ce=!1)}let ze=o=>{let r=(o-R.l*a)/(Oe()||1);return Ze()+se(r,0,1)*Ge()},dt=o=>{let r=(o-R.l*a)/(lt()||1);return V+se(r,0,1)*Pe()},gt=o=>{let r=n.height-R.b*a-Ve(),c=se((r-o)/(He()||1),0,1);return xe+c*(ve-xe)};function $t(o){let r=w==null?void 0:w.series;if(!r||r.timestamps.length===0)return-1;let c=(o-R.l*a)/(Oe()||1),l=Ze()+c*Ge(),d=r.timestamps,u=0,h=d.length-1;for(;u<h;){let M=u+h>>1;d[M]<l?u=M+1:h=M}return u>0&&l-d[u-1]<d[u]-l&&(u-=1),u}function vt(o,r){let c=o.timestamps;if(V=c[0],G=c[c.length-1],v){let h=`${c.length}:${V}:${G}`;h!==qt?(qt=h,ie=V,me=G):(ie=se(ie,V,G),me=se(Math.max(me,ie+$e()),V,G))}let l=1/0,d=-1/0;for(let h of o.values)_e(h)&&(h<l&&(l=h),h>d&&(d=h));if(!S)for(let h of r)h.scored&&(_e(h.lower)&&h.lower<l&&(l=h.lower),_e(h.upper)&&h.upper>d&&(d=h.upper));(!_e(l)||!_e(d))&&(l=0,d=1),be&&(l>0&&(l=0),d<0&&(d=0)),d<=l&&(d=l+1);let u=(d-l)*.06;xe=l-u,ve=d+u}function zt(o,r,c){let l=w.series.timestamps;Yn(t,l,o,Ze(),Et(),R.l*a,Oe(),O,ke,r,c,a)}function pe(o,r){let c=[],l=-1;for(let d=Math.max(0,r);d<o.length;d++){let u=o[d];u.scored&&_e(u.lower)&&_e(u.upper)?l===-1&&(l=d):l!==-1&&(c.push([l,d-1]),l=-1)}return l!==-1&&c.push([l,o.length-1]),c}function Wt(){if(te=0,!w||n.width===0||n.height===0)return;let{series:o,scored:r,params:c,alerts:l}=w;if(o.timestamps.length===0){t.fillStyle=K("--term-bg"),t.fillRect(0,0,n.width,n.height);return}let d=K("--clay"),u=K("--st-anomaly"),h=K("--faint"),M=K("--muted");t.fillStyle=K("--term-bg"),t.fillRect(0,0,n.width,n.height),t.font=`${11*a}px ui-monospace, 'JetBrains Mono', monospace`,t.textBaseline="middle";for(let T=0;T<=4;T++){let j=xe+(ve-xe)*T/4,W=ke(j);t.strokeStyle=F(h,.1),t.lineWidth=1*a,t.beginPath(),t.moveTo(R.l*a,W),t.lineTo(n.width-R.r*a,W),t.stroke(),t.fillStyle=M,t.textAlign="right",t.fillText(go(j),(R.l-8)*a,W)}if(be&&xe<=0&&ve>=0){let T=ke(0);t.strokeStyle=F(M,.6),t.lineWidth=1.25*a,t.beginPath(),t.moveTo(R.l*a,T),t.lineTo(n.width-R.r*a,T),t.stroke(),t.fillStyle=M,t.textAlign="right",t.fillText("0",(R.l-8)*a,T)}t.textBaseline="top";let E=n.height-R.b*a-Ve();if(v){let T=So(Ze(),Et(),7),j=Jt(T.ticks,O,T.step);for(let W=0;W<T.ticks.length;W++){let Z=T.ticks[W],we=O(Z);t.strokeStyle=F(h,.1),t.lineWidth=1*a,t.beginPath(),t.moveTo(we,R.t*a),t.lineTo(we,E),t.stroke(),j[W]&&(t.fillStyle=M,t.textAlign=we<(R.l+24)*a?"left":we>n.width-(R.r+24)*a?"right":"center",t.fillText(Jn(Z,T.step),we,E+7*a))}}else{let T=Ge();for(let j=0;j<=5;j++){let W=V+T*j/5,Z=O(W);t.fillStyle=M,t.textAlign=j===0?"left":j===5?"right":"center",t.fillText(vo(W,T),Z,E+7*a)}}t.save(),t.beginPath(),t.rect(R.l*a,R.t*a,Oe(),He()),t.clip(),We(),en();let _=r.length,z=Math.min(ko(o,c),_),H=z<_?o.timestamps[z]:void 0,Q=I(),Me=A()?pe(r,0):[];t.fillStyle=F(d,.13*Q);for(let[T,j]of Me){t.beginPath(),t.moveTo(O(r[T].timestamp),ke(r[T].upper));for(let W=T+1;W<=j;W++)t.lineTo(O(r[W].timestamp),ke(r[W].upper));for(let W=j;W>=T;W--)t.lineTo(O(r[W].timestamp),ke(r[W].lower));t.closePath(),t.fill()}t.strokeStyle=F(d,.4*Q),t.lineWidth=1*a;for(let[T,j]of Me)for(let W of["upper","lower"]){t.beginPath();for(let Z=T;Z<=j;Z++){let we=O(r[Z].timestamp),it=ke(r[Z][W]);Z===T?t.moveTo(we,it):t.lineTo(we,it)}t.stroke()}t.strokeStyle=F(h,.55*Q),t.lineWidth=1*a,t.setLineDash([3*a,3*a]);for(let[T,j]of Me){t.beginPath();for(let W=T;W<=j;W++){let Z=r[W].center;if(!_e(Z))continue;let we=O(r[W].timestamp),it=ke(Z);W===T?t.moveTo(we,it):t.lineTo(we,it)}t.stroke()}if(t.setLineDash([]),c.type!=="autoreg"&&c.type!=="manual_bounds"&&c.smoothing!=="none"&&(!g||D()==="tune")){zt(o.values,F(d,.28),1.25);let T=r.map(j=>j.processedValue);zt(T,d,1.6)}else zt(o.values,d,1.5);let Ce=ee();for(let T=0;T<_;T++){let j=r[T];if(!j.scored||!_e(j.value))continue;let W=O(j.timestamp),Z=ke(j.value);j.isAnomaly?(t.fillStyle=F(u,.18*Ce),t.beginPath(),t.arc(W,Z,6*a,0,Math.PI*2),t.fill(),t.fillStyle=F(u,Ce),t.beginPath(),t.arc(W,Z,3*a,0,Math.PI*2),t.fill()):o.truthAnomaly[T]&&(t.strokeStyle=F(M,.7),t.lineWidth=1.25*a,t.beginPath(),t.arc(W,Z,3.5*a,0,Math.PI*2),t.stroke())}if(!g||D()==="tune"){let T=Me.length>0;_>0&&!T?wo(t,n,R,a,"no band here \u2014 the detector scored nothing (window below min_samples, or gaps)"):H!==void 0&&yo(t,n,R,a,O,H,"detection at full power \u2192")}N>=0&&N<r.length&&Y()&&tt(N,c.windowSize,r,o,h),l&&l.length&&xo(t,n,R,a,O,l,T=>T==="anomaly"?K("--st-anomaly"):T==="anomaly-validated"?K("--st-recovery"):T==="anomaly-false"?K("--st-error"):T==="recovery"?K("--st-recovery"):K("--st-nodata")),xt(),nt(r,0,_),t.restore(),y&&ct(o,l,d,h,M)}function ct(o,r,c,l,d){let u=et(),h=u+Se(),M=R.l*a,E=n.width-R.r*a,_=So(V,G,5);t.save(),t.beginPath(),t.rect(M,u,lt(),Se()),t.clip(),t.strokeStyle=F(l,.1),t.lineWidth=1*a;for(let ae of _.ticks){let Ce=Re(ae);t.beginPath(),t.moveTo(Ce,u),t.lineTo(Ce,h),t.stroke()}Yn(t,o.timestamps,o.values,V,G,M,lt(),Re,En,F(c,.7),1.1,a),t.restore();let z=Re(ie),H=Re(me);if(t.fillStyle="rgba(27,25,22,0.55)",t.fillRect(M,u,z-M,Se()),t.fillRect(H,u,E-H,Se()),$.length){let ae=K("--st-anomaly");t.fillStyle=F(ae,.28);for(let Ce of $){let T=Re(Ce.start),j=Math.max(Re(Ce.end)-T,2*a);t.fillRect(T,u,j,Se())}}if(r&&r.length){let ae=K("--st-anomaly");t.fillStyle=F(ae,.85);for(let Ce of r){let T=Re(Ce.t);t.fillRect(T-1*a,u,2*a,Se())}}t.fillStyle="rgba(245,241,232,0.06)",t.fillRect(z,u,H-z,Se()),t.strokeStyle=c,t.lineWidth=1.5*a,t.strokeRect(z,u+1,H-z,Se()-2),t.fillStyle=c;let Q=u+Se()/2-8*a;t.fillRect(z-2*a,Q,4*a,16*a),t.fillRect(H-2*a,Q,4*a,16*a),t.font=`${10*a}px ui-monospace, monospace`,t.textBaseline="top",t.fillStyle=d;let Me=Jt(_.ticks,Re,_.step);for(let ae=0;ae<_.ticks.length;ae++){let Ce=_.ticks[ae],T=Re(Ce);t.strokeStyle=F(l,.25),t.lineWidth=1*a,t.beginPath(),t.moveTo(T,h),t.lineTo(T,h+3*a),t.stroke(),Me[ae]&&(t.textAlign=T<(R.l+26)*a?"left":T>n.width-(R.r+26)*a?"right":"center",t.fillText(Jn(Ce,_.step),T,h+5*a))}}function tt(o,r,c,l,d){let u=l.timestamps,h=Math.max(0,o-r),M=o-1,E=R.t*a,_=He();if(M>=h){let Q=l.intervalSeconds*1e3/Ge()*Oe()*.5,Me=O(u[h])-Q,ae=O(u[M])+Q;t.fillStyle="rgba(255,255,255,0.05)",t.fillRect(Me,E,ae-Me,_),t.strokeStyle=F(d,.5),t.lineWidth=1*a,t.beginPath(),t.moveTo(Me,E),t.lineTo(Me,E+_),t.moveTo(ae,E),t.lineTo(ae,E+_),t.stroke()}let z=O(u[o]);t.strokeStyle=F(d,.85),t.lineWidth=1*a,t.setLineDash([2*a,2*a]),t.beginPath(),t.moveTo(z,E),t.lineTo(z,E+_),t.stroke(),t.setLineDash([]);let H=c[o];if(H.scored&&_e(H.lower)&&_e(H.upper)){let Q=5*a;t.strokeStyle=F(K("--clay"),.85),t.lineWidth=1.5*a;for(let Me of[H.lower,H.upper]){let ae=ke(Me);t.beginPath(),t.moveTo(z-Q,ae),t.lineTo(z+Q,ae),t.stroke()}}if(_e(H.value)){let Q=ke(H.value);t.fillStyle=K("--term-bg"),t.beginPath(),t.arc(z,Q,4*a,0,Math.PI*2),t.fill(),t.strokeStyle=H.isAnomaly?K("--st-anomaly"):K("--clay"),t.lineWidth=2*a,t.beginPath(),t.arc(z,Q,4*a,0,Math.PI*2),t.stroke()}}function ut(o,r,c,l,d){t.beginPath(),t.moveTo(o+d,r),t.arcTo(o+c,r,o+c,r+l,d),t.arcTo(o+c,r+l,o,r+l,d),t.arcTo(o,r+l,o,r,d),t.arcTo(o,r,o+c,r,d),t.closePath()}function yt(o,r){let c=K("--st-anomaly"),l=14*a,d=3*a,u=o-l-d,h=R.t*a+d;t.fillStyle=r?F(c,.95):"rgba(27,25,22,0.82)",t.strokeStyle=F(c,.9),t.lineWidth=1*a,ut(u,h,l,l,3*a),t.fill(),t.stroke(),t.strokeStyle=r?"#fff":c,t.lineWidth=1.5*a;let M=4*a;t.beginPath(),t.moveTo(u+M,h+M),t.lineTo(u+l-M,h+l-M),t.moveTo(u+l-M,h+M),t.lineTo(u+M,h+l-M),t.stroke()}let Fe=()=>re!=null?re:Le,It=()=>{let o=Ae||ue;return o?[Math.min(o.a,o.b),Math.max(o.a,o.b)]:[Ze(),Et()]};function wt(){let o=[],r=Fe();if(r==null||!w)return o;let c=w.series.timestamps,l=w.series.values,[d,u]=It(),h=-1,M=-1,E=0;for(let _=0;_<c.length;_++){if(c[_]<d||c[_]>u)continue;let z=l[_];_e(z)&&(at==="above"?z>r:z<r)?(h===-1&&(h=c[_]),M=c[_],E=0):h!==-1&&(E++,E>Ue&&(o.push([h,M]),h=-1,E=0))}return h!==-1&&o.push([h,M]),o}function fe(){if(!i.onThresholdChange)return;let[o,r]=It(),c=Ae||ue;i.onThresholdChange({value:Fe(),locked:re!=null,runs:wt().length,window:c?{start:Math.min(c.a,c.b),end:Math.max(c.a,c.b)}:null,committed:ue!=null,windowMs:r-o})}function Qt(o,r){let c=null;for(let l=$.length-1;l>=0;l--){let d=$[l];o<=d.end&&r>=d.start&&(c===null?(d.start=Math.min(d.start,o),d.end=Math.max(d.end,r),c=d):(c.start=Math.min(c.start,d.start),c.end=Math.max(c.end,d.end),oe===d&&(oe=c),$.splice(l,1)))}c===null&&$.push({start:o,end:r,label:""})}function We(){if(!De||Fe()==null)return;let r=R.t*a,c=He(),l=K("--st-nodata");for(let[d,u]of wt()){let h=O(d),M=Math.max(O(u)-h,2*a);t.fillStyle=F(l,.22),t.fillRect(h,r,M,c),t.strokeStyle=F(l,.6),t.lineWidth=1*a,t.strokeRect(h,r,M,c)}}function xt(){if(!De)return;let o=R.t*a,r=n.height-R.b*a-Ve(),c=R.l*a,l=n.width-R.r*a,d=K("--st-nodata"),[u,h]=It(),M=!!(Ae||ue),E=se(O(u),c,l),_=se(O(h),c,l);M&&(t.fillStyle=F(K("--ink"),.5),t.fillRect(c,o,Math.max(0,E-c),He()),t.fillRect(_,o,Math.max(0,l-_),He()),t.strokeStyle=F(d,.7),t.lineWidth=1*a,t.setLineDash([3*a,3*a]),t.beginPath(),t.moveTo(E,o),t.lineTo(E,r),t.moveTo(_,o),t.lineTo(_,r),t.stroke(),t.setLineDash([]));let z=Fe();if(z!=null&&z>=xe&&z<=ve){let H=ke(z);t.strokeStyle=d,t.lineWidth=1.5*a,t.setLineDash([6*a,4*a]),t.beginPath(),t.moveTo(E,H),t.lineTo(_,H),t.stroke(),t.setLineDash([])}}let Zt=()=>w?w.series.intervalSeconds*1e3:1e3;function mt(o,r,c){let l=!1;for(let d=0,u=c.length-1;d<c.length;u=d++){let h=c[d].x,M=c[d].y,E=c[u].x,_=c[u].y;M>r!=_>r&&o<(E-h)*(r-M)/(_-M||1e-9)+h&&(l=!l)}return l}function Ot(o,r,c){let l=[];if(!X||X.length<3)return l;for(let d=Math.max(0,r);d<c;d++){let u=o[d];!u.scored||!u.isAnomaly||!_e(u.value)||mt(O(u.timestamp),ke(u.value),X)&&l.push(d)}return l}function Ht(o,r){var _;if(!r.length)return[];let c=Zt(),d=(Math.max(1,(_=w==null?void 0:w.params.consecutiveAnomalies)!=null?_:1)+1)*c,u=c/2,h=[],M=r[0],E=r[0];for(let z=1;z<r.length;z++){let H=r[z];o[H].timestamp-o[E].timestamp>d&&(h.push([o[M].timestamp-u,o[E].timestamp+u]),M=H),E=H}return h.push([o[M].timestamp-u,o[E].timestamp+u]),h}function Zn(o,r,c){if(!i.onLassoChange)return;let l=J&&X?Ot(o,r,c):[];i.onLassoChange({active:!!X,anomalies:l.length,incidents:Ht(o,l).length})}function un(){if(!w||!X)return;let{scored:o}=w,r=o.length,c=Ht(o,Ot(o,0,r));for(let[l,d]of c)Qt(l,d);c.length&&Be()}function nt(o,r,c){if(!J||!X||X.length<2)return;let l=K("--clay"),d=K("--st-anomaly");t.beginPath(),t.moveTo(X[0].x,X[0].y);for(let u=1;u<X.length;u++)t.lineTo(X[u].x,X[u].y);t.closePath(),t.fillStyle=F(l,.08),t.fill(),t.strokeStyle=F(l,.9),t.lineWidth=1.5*a,t.setLineDash([5*a,4*a]),t.stroke(),t.setLineDash([]);for(let u of Ot(o,r,c)){let h=O(o[u].timestamp),M=ke(o[u].value);t.strokeStyle=d,t.lineWidth=2*a,t.beginPath(),t.arc(h,M,7*a,0,Math.PI*2),t.stroke()}}function en(){let o=R.t*a,r=He(),c=K("--st-anomaly"),l=R.l*a,d=n.width-R.r*a,u=ne(),h=de();for(let M=0;M<$.length;M++){let E=$[M],_=O(E.start),z=O(E.end);if(z<l-1||_>d+1)continue;let H=Math.max(z-_,2*a),Q=u&&E===oe;t.fillStyle=F(c,(Q?.3:.16)*h),t.fillRect(_,o,H,r),t.strokeStyle=F(c,(Q?.95:.5)*h),t.lineWidth=(Q?2:1)*a,t.strokeRect(_,o,H,r),u&&(t.fillStyle=F(c,.95),t.fillRect(_-1.5*a,o,3*a,r),t.fillRect(z-1.5*a,o,3*a,r),(z-_>=22*a||Q)&&yt(z,Q||M===Qe))}if(u&&C&&C.mode==="new"){let M=O(C.a),E=O(C.b);t.fillStyle=F(K("--st-nodata"),.28),t.fillRect(Math.min(M,E),o,Math.abs(E-M),r)}}function Ye(o,r){if(!w||!w.alerts||!w.alerts.length||r>(R.t+22)*a)return-1;let c=-1,l=9*a;for(let d=0;d<w.alerts.length;d++){let u=Math.abs(o-O(w.alerts[d].t));u<=l&&(l=u,c=d)}return c}function $n(o){var l;if(!w||!w.alerts)return;let r=w.alerts[o].kind,c=r==="anomaly"?"valid":r==="anomaly-validated"?"false":"unreviewed";(l=i.onAlertReviewChange)==null||l.call(i,w.alerts[o].t,c)}function Be(o){var r;(r=i.onIncidentsChange)==null||r.call(i,$,o)}function mn(o){let r=$.indexOf(o);r<0||($.splice(r,1),oe===o&&(oe=null),Qe=-1,Be(o),B())}function pn(o,r){let c=R.t*a,l=6*a;for(let d=0;d<$.length;d++){let u=O($[d].end);if(u-O($[d].start)>=22*a||$[d]===oe){let h=14*a,M=3*a,E=u-h-M,_=c+M;if(o>=E&&o<=E+h&&r>=_&&r<=_+h)return{i:d,edge:"del"}}}for(let d=0;d<$.length;d++){let u=O($[d].start),h=O($[d].end);if(Math.abs(o-u)<=l)return{i:d,edge:"a"};if(Math.abs(o-h)<=l)return{i:d,edge:"b"}}for(let d=0;d<$.length;d++){let u=O($[d].start),h=O($[d].end);if(o>u+l&&o<h-l)return{i:d,edge:"move"}}return null}let kt=()=>{let o=w==null?void 0:w.series,r=o?o.timestamps.length:0;return r>1?Math.max(Pe()/(r-1),1):1e3};function B(){te===0&&(te=requestAnimationFrame(Wt))}function Ke(){if(!w)return;let o=w.scored.length;Zn(w.scored,0,o)}function q(){var c;if(!i.onHover||!w)return;if(N<0){i.onHover(null);return}let o=(c=w.scored[N])!=null?c:null,r={index:N,point:o,windowStart:Math.max(0,N-w.params.windowSize),windowEnd:N-1};i.onHover(r)}let ye=null,le=null,ot=o=>{let r=n.getBoundingClientRect();return{x:(o.clientX-r.left)*a,y:(o.clientY-r.top)*a}},St=o=>y&&o>=et(),pt=o=>{let r=Re(ie),c=Re(me),l=8*a;return Math.abs(o-r)<=l?"l":Math.abs(o-c)<=l?"r":o>r&&o<c?"move":"out"};function Ee(o){if(!w)return;let{x:r,y:c}=ot(o);if(ye||le||C)return;if(St(c)){N!==-1&&(N=-1,q(),B());let u=pt(r);n.style.cursor=u==="l"||u==="r"?"ew-resize":u==="move"?"grab":"pointer";return}let l=D();if(g&&l==="label"&&J){N!==-1&&(N=-1,q()),n.style.cursor="crosshair";return}if(g&&l==="label"&&De){N!==-1&&(N=-1,q()),re==null&&!ge&&(Le=gt(c),fe(),B()),n.style.cursor="crosshair";return}if(g&&l==="label"){N!==-1&&(N=-1,q());let u=pn(r,c),h=u&&u.edge==="del"?u.i:-1;h!==Qe&&(Qe=h,B()),n.style.cursor=u?u.edge==="del"?"pointer":u.edge==="move"?"grab":"ew-resize":"crosshair";return}if(g&&l==="review"){N!==-1&&(N=-1,q()),n.style.cursor=Ye(r,c)>=0?"pointer":"grab";return}v&&(n.style.cursor=g&&Ye(r,c)>=0?"pointer":"grab");let d=$t(r);d!==N&&(N=d,q(),B())}function Mt(){N!==-1&&(N=-1,q(),B())}function qe(o){if(!v||!w)return;let{x:r,y:c}=ot(o);if(y&&c>=et()){let l=pt(r);if(l==="l")le={type:"l",grab:0,vMin:ie,vMax:me};else if(l==="r")le={type:"r",grab:0,vMin:ie,vMax:me};else if(l==="move")le={type:"move",grab:dt(r),vMin:ie,vMax:me};else{let d=dt(r),u=Ge();Ne(d-u/2,d+u/2),le={type:"move",grab:d,vMin:ie,vMax:me}}n.style.cursor="grabbing",o.preventDefault();return}if(c>R.t*a&&c<n.height-R.b*a-Ve()){let l=D();if(U()){let d=Ye(r,c);if(d>=0){$n(d),o.preventDefault();return}}if(g&&l==="label"&&J){X=[{x:r,y:c}],Ke(),n.style.cursor="crosshair",B(),o.preventDefault();return}if(g&&l==="label"&&De){ge={x:r,ts:ze(r)},re==null&&(Le=gt(c)),fe(),B(),o.preventDefault();return}if(g&&l==="label"){let d=ze(r),u=pn(r,c);if(u&&u.edge==="del"){mn($[u.i]),o.preventDefault();return}if(u&&u.edge==="move"){let h=$[u.i];oe=h,C={mode:"move",iv:h,grab:d,a0:h.start,b0:h.end,moved:!1}}else if(u){let h=$[u.i];oe=h,C={mode:"edge",iv:h,edge:u.edge,moved:!1}}else oe=null,C={mode:"new",a:d,b:d,moved:!1};n.style.cursor="crosshair",B(),o.preventDefault();return}ye={x:r,vMin:ie,vMax:me},n.style.cursor="grabbing",o.preventDefault()}}function Xe(o){if(!w)return;let{x:r,y:c}=ot(o);if(J&&X){X.push({x:r,y:c}),Ke(),B();return}if(De&&ge){Math.abs(r-ge.x)>6*a?Ae={a:ge.ts,b:ze(r)}:(Ae=null,re==null&&(Le=gt(c))),fe(),B();return}if(C){let l=ze(r);if(C.mode==="new")C.b=l,Math.abs(O(C.b)-O(C.a))>4*a&&(C.moved=!0);else if(C.mode==="edge"){let d=C.iv,u=kt();C.edge==="a"?d.start=se(Math.min(l,d.end-u),V,G):d.end=se(Math.max(l,d.start+u),V,G),C.moved=!0}else{let d=C.iv,u=C.a0+(l-C.grab),h=C.b0+(l-C.grab);u<V&&(h+=V-u,u=V),h>G&&(u-=h-G,h=G),d.start=se(u,V,G),d.end=se(h,V,G),C.moved=!0}B();return}if(ye){let l=(r-ye.x)*(ye.vMax-ye.vMin)/(Oe()||1);Ne(ye.vMin-l,ye.vMax-l)}else if(le){let l=dt(r);le.type==="l"?Ne(Math.min(l,me-$e()),me):le.type==="r"?Ne(ie,Math.max(l,ie+$e())):Ne(le.vMin+(l-le.grab),le.vMax+(l-le.grab))}}function tn(o){if(J&&X){un(),X=null,Ke(),B();return}if(De&&ge){let{x:r,y:c}=ot(o);if(Math.abs(r-ge.x)>6*a){let l=ge.ts,d=ze(r);ue={a:Math.min(l,d),b:Math.max(l,d)}}else re=gt(c);ge=null,Ae=null,fe(),B();return}if(C){let r=C;if(r.mode==="new")if(r.moved){let c=se(Math.min(r.a,r.b),V,G),l=se(Math.max(r.a,r.b),V,G),d={start:c,end:l,label:""};$.push(d),oe=d}else oe=null;else if(r.iv.start>r.iv.end){let c=r.iv.start;r.iv.start=r.iv.end,r.iv.end=c}C=null,n.style.cursor="crosshair",r.moved&&Be(),B();return}(ye||le)&&(ye=null,le=null,n.style.cursor="grab")}function ft(o){let r=o.target,c=!!r&&(r.tagName==="INPUT"||r.tagName==="TEXTAREA"||r.isContentEditable);if(J){o.key==="Escape"&&X&&(X=null,Ke(),B());return}De||c||!oe||(o.key==="Delete"||o.key==="Backspace"?(o.preventDefault(),mn(oe)):o.key==="Escape"&&(oe=null,B()))}function rt(o){if(!v||!w)return;if(J&&X){o.preventDefault();return}o.preventDefault();let{x:r,y:c}=ot(o),l=se(Ge()*Math.pow(1.0015,o.deltaY),$e(),Pe());if(c>=et()){let d=dt(r);Ne(d-l/2,d+l/2)}else{let d=ze(r),u=(d-ie)/(Ge()||1);Ne(d-u*l,d-u*l+l)}}function Ft(){v&&Ne(V,G)}n.addEventListener("mousemove",Ee),n.addEventListener("mouseleave",Mt),v&&(n.addEventListener("mousedown",qe),n.addEventListener("wheel",rt,{passive:!1}),n.addEventListener("dblclick",Ft),window.addEventListener("mousemove",Xe),window.addEventListener("mouseup",tn)),g&&(window.addEventListener("keydown",ft),n.style.cursor=k==="tune"?"grab":"crosshair");function nn(o){w=o,!g&&o.incidents&&($=o.incidents),vt(o.series,o.scored),N>=o.series.timestamps.length&&(N=-1),B()}function Ct(o){be!==o&&(be=o,w&&vt(w.series,w.scored),B())}function fn(o){$=o,oe=null,Qe=-1,B()}function on(o){g&&(De=o,o?(oe=null,J=!1,X=null,Ke()):(Le=null,ge=null,Ae=null),n.style.cursor="crosshair",fe(),B())}function Bt(o){g&&(J=o,o?(De=!1,ge=null,Ae=null,Le=null,oe=null,fe()):X=null,n.style.cursor="crosshair",Ke(),B())}function rn(o){!g||k===o||(k=o,o!=="label"&&(De=!1,ge=null,Ae=null,Le=null,J=!1,X=null,oe=null,Qe=-1,fe(),Ke()),N=-1,n.style.cursor=o==="tune"?"grab":"crosshair",w&&vt(w.series,w.scored),B())}function sn(o){at=o,fe(),B()}function zn(o){Ue=Math.max(0,Math.floor(o)||0),fe(),B()}function hn(o){re=o!=null&&_e(o)?o:null,fe(),B()}function jt(){let o=wt(),r=Zt()/2;for(let[c,l]of o)Qt(c-r,l+r);return o.length&&Be(),fe(),B(),o.length}function Ut(){ue=null,Ae=null,fe(),B()}function an(){return ue?{start:Math.min(ue.a,ue.b),end:Math.max(ue.a,ue.b)}:null}function Tt(o){ue=o?{a:o.start,b:o.end}:null,fe(),B()}function At(){Xt(),w&&(vt(w.series,w.scored),B())}function bn(){n.removeEventListener("mousemove",Ee),n.removeEventListener("mouseleave",Mt),v&&(n.removeEventListener("mousedown",qe),n.removeEventListener("wheel",rt),n.removeEventListener("dblclick",Ft),window.removeEventListener("mousemove",Xe),window.removeEventListener("mouseup",tn)),g&&window.removeEventListener("keydown",ft),te!==0&&cancelAnimationFrame(te),te=0,w=null}return Xt(),{render:nn,resize:At,setMode:rn,setZeroLine:Ct,setViewWindow:bt,setIncidents:fn,setThresholdMode:on,setThresholdDirection:sn,setThresholdGap:zn,setThresholdValue:hn,applyThreshold:jt,setLassoMode:Bt,clearCaptureWindow:Ut,getCaptureWindow:an,setCaptureWindow:Tt,destroy:bn}}function Rn(n){var f;if(n.type==="manual_bounds"){let t={};return n.lowerBound!=null&&(t.lower_bound=n.lowerBound),n.upperBound!=null&&(t.upper_bound=n.upperBound),n.inputType!=="values"&&(t.input_type=n.inputType),t}if(n.type==="autoreg"){let t=Math.max(1,Math.round((f=n.lags)!=null?f:5)),v={lags:t,threshold:n.threshold,window_size:n.windowSize,min_samples:Math.min(Math.max(n.minSamples,t+2),n.windowSize)};return n.stabilization!=="clamp"&&(v.stabilization=null),n.inputType!=="values"&&(v.input_type=n.inputType),v}let i={threshold:n.threshold,window_size:n.windowSize};return n.windowWeights!=="none"&&(i.window_weights=n.windowWeights,n.windowWeights==="exponential"&&n.halfLife!=null&&(i.half_life=n.halfLife)),n.detrend!=="none"&&(i.detrend=n.detrend),n.stabilization&&n.stabilization!=="none"&&(i.stabilization=n.stabilization),n.smoothing!=="none"&&(i.smoothing=n.smoothing),n.inputType!=="values"&&(i.input_type=n.inputType),n.seasonalityComponents&&n.seasonalityComponents.length&&(i.seasonality_components=n.seasonalityComponents,i.min_samples_per_group=n.minSamplesPerGroup),i}function Co(n,i,f,t){let v=Rn(n),y=[`type: ${n.type}`];for(let[S,g]of Object.entries(v))y.push(`${S}=${typeof g=="object"?JSON.stringify(g):g}`);return n.direction&&n.direction!=="any"&&y.push(`direction=${n.direction}`),y.push(`consecutive_anomalies=${i}`),f!=null&&t!=null&&(y.push(`anomaly_window=${f}p`),y.push(`min_anomaly_share=${t}`)),y.join(" \xB7 ")}function m(n,i,f){let t=document.createElement(n);return i&&(t.className=i),f!=null&&(t.textContent=f),t}function Lt(n,i){let f=m("label","dtk-ctl-label",n);if(i){f.title=i;let t=m("span","dtk-ctl-info","\u24D8");t.title=i,f.appendChild(document.createTextNode(" ")),f.appendChild(t)}return f}function Rt(n,i,f,t,v){let y=m("div","dtk-ctl");y.appendChild(Lt(n,v));let S=m("div","dtk-seg"),g=f,k=[],D=()=>{k.forEach(A=>A.classList.toggle("on",A.dataset.v===g))};return i.forEach(A=>{let I=m("button","dtk-seg-btn",A.label);I.type="button",I.dataset.v=A.value,I.onclick=()=>{g=A.value,D(),t(g)},k.push(I),S.appendChild(I)}),D(),y.appendChild(S),{row:y,get:()=>g,set:A=>{g=A,D()}}}function je(n,i,f){var D;let t=m("div","dtk-ctl"),v=m("div","dtk-ctl-head"),y=Lt(n,i.hint),S=m("span","dtk-ctl-val"),g=(D=i.fmt)!=null?D:(A=>String(A));v.appendChild(y),v.appendChild(S),t.appendChild(v);let k=m("input","dtk-range");return k.type="range",k.min=String(i.min),k.max=String(i.max),k.step=String(i.step),k.value=String(i.value),S.textContent=g(i.value),k.oninput=()=>{S.textContent=g(Number(k.value))},k.onchange=()=>{let A=Number(k.value);S.textContent=g(A),f(A)},t.appendChild(k),{row:t,get:()=>Number(k.value),set:A=>{k.value=String(A),S.textContent=g(Number(k.value))},setMax:A=>{k.max=String(A),Number(k.value)>A&&(k.value=String(A),S.textContent=g(A))},setMin:A=>{k.min=String(A),Number(k.value)<A&&(k.value=String(A),S.textContent=g(A))}}}function Kt(n){if(!Number.isFinite(n))return"\u2014";let i=Math.abs(n);return i!==0&&(i<.01||i>=1e6)?n.toExponential(2):Number(n.toFixed(i<1?4:2)).toString()}function Nn(n){return new Date(n).toISOString().slice(0,16).replace("T"," ")}function Nt(n){let i=Math.round(n/6e4);if(i<60)return`${i}m`;let f=Math.floor(i/60);if(f<24)return`${f}h`;let t=Math.floor(f/24),v=f%24;return v?`${t}d ${v}h`:`${t}d`}function To(n){return n%86400===0?`${n/86400}d`:n%3600===0?`${n/3600}h`:n%60===0?`${n/60}min`:`${n}s`}function Ao(n,i){let f=i.tol,t=i.timestamps,v=(t.length?t[0]:0)-f,y=(t.length?t[t.length-1]:0)+f,S=a=>a.end>=v&&a.start<=y,g=(a,w)=>a.end>=w.start-f&&a.start<=w.end+f,k=i.incidents.filter(S),D=i.validatedSpans.filter(S).filter(a=>!k.some(w=>g(a,w))),A=[...k,...D],I=(a,w)=>a[1]>=w.start-f&&a[0]<=w.end+f,ee=0,ne=0,de=0;for(let a of n){let w=i.reviewFor(a[0],a[1]);w&&de++,w==="valid"&&ne++,(w==="valid"||w!=="false"&&A.some(N=>I(a,N)))&&ee++}let Y=0;for(let a of A)n.some(w=>I(w,a))&&Y++;let U=n.length;return{realIncidents:A.length,caught:Y,recall:A.length?Y/A.length:NaN,totalAlerts:U,correctAlerts:ee,falseAlerts:U-ee,fdr:U?(U-ee)/U:NaN,validated:ne,reviewed:de}}function Qn(n){return Number.isFinite(n)?`${Math.round(n*100)}%`:"\u2014"}function cn(n,i,f,t,v){return`<span class="dtk-m-chip${v!=null&&v.cls?" "+v.cls:""}"${v!=null&&v.title?` title="${v.title}"`:""}><span class="dtk-m-dot" style="background:${t}"></span><span class="dtk-m-v">${n}</span><span class="dtk-m-l">${i}</span>`+(f?`<span class="dtk-m-sub">${f}</span>`:"")+"</span>"}function _o(n,i,f){let t=i.realIncidents>0,v=f!=null?`${Math.round(f*100)}%`:"",y=t&&i.totalAlerts>0&&f!=null&&Number.isFinite(i.fdr)&&i.fdr>f,S;if(!t)S="mark incidents to measure";else if(i.totalAlerts===0)S="no alerts";else if(i.falseAlerts===0)S=`${Qn(i.fdr)} \xB7 all correct`;else{let D=i.totalAlerts/i.falseAlerts,A=D>=9.5?String(Math.round(D)):String(Math.round(D*10)/10);S=`${Qn(i.fdr)} \xB7 \u22481 in ${A} false`}y&&(S+=` \xB7 \u25B2 over ${v} budget`);let g=i.totalAlerts===0?"no alerts":`${i.validated} valid${i.totalAlerts>i.reviewed?` \xB7 ${i.totalAlerts-i.reviewed} left`:" \xB7 all reviewed"}`,k=f?`Budget: at most ${v} of fired alerts false (false-alert rate / FDR). Set per metric or project via false_alert_budget. Labeling is optional \u2014 this just flags when you exceed the budget.`:"";n.innerHTML=cn(String(i.realIncidents),"real incidents","","var(--c)")+cn(t?`${i.caught}/${i.realIncidents}`:"\u2014","caught",t?`recall ${Qn(i.recall)}`:"mark or confirm","var(--green)")+cn(String(i.totalAlerts),"alerts","","var(--c)")+cn(t?String(i.falseAlerts):"\u2014","false alerts",S,"var(--anom)",{cls:y?"over":"",title:k})+cn(`${i.reviewed}/${i.totalAlerts}`,"reviewed",g,"var(--green)")}var Do=!1;function Po(){if(Do)return;Do=!0;let n=`
2
+ .dtk-tune{--c:#d15b36;--c7:#b4471f;--ink:#1b1916;--muted:#6e675b;--faint:#9a9384;
3
+ --paper:#f5f1e8;--surface:#fbf9f3;--border:#e6e0d4;--green:#2e9e73;--anom:#d63232;
4
+ --mono:'JetBrains Mono',ui-monospace,Menlo,monospace;
5
+ --sans:'Schibsted Grotesk',system-ui,-apple-system,Segoe UI,Roboto,sans-serif;}
6
+ .dtk-tune-root{max-width:1680px;margin:0 auto;padding:12px 16px;font-family:var(--sans);color:var(--ink);
7
+ height:100dvh;display:flex;flex-direction:column;gap:10px;overflow:hidden;}
8
+ .dtk-tune-header{flex:0 0 auto;}
9
+ .dtk-tune-titlerow{display:flex;align-items:baseline;gap:10px;flex-wrap:wrap;}
10
+ .dtk-tune-title{font-size:19px;margin:0;font-weight:700;}
11
+ .dtk-tune-badge{font-family:var(--mono);font-size:10px;text-transform:uppercase;letter-spacing:.06em;
12
+ color:#fff;background:var(--c);border-radius:999px;padding:3px 9px;}
13
+ .dtk-tune-sub{color:var(--muted);font-size:12px;margin-top:2px;font-family:var(--mono);}
14
+ .dtk-tune-desc{color:var(--muted);font-size:12px;margin-top:3px;white-space:pre-wrap;max-height:2.6em;overflow:auto;}
15
+ /* cockpit: chart-windshield (stage) + always-visible mode-aware control rail */
16
+ .dtk-tune-cockpit{display:flex;gap:12px;flex:1;min-height:0;}
17
+ .dtk-tune-stage{position:relative;display:flex;flex-direction:column;gap:8px;flex:1;min-width:0;min-height:0;}
18
+ .dtk-tune-hud{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;flex:0 0 auto;}
19
+ .dtk-tune-stagefoot{flex:0 0 auto;display:flex;flex-direction:column;gap:6px;}
20
+ .dtk-tune-rail{flex:0 0 340px;display:flex;flex-direction:column;min-height:0;background:var(--surface);
21
+ border:1px solid var(--border);border-radius:12px;overflow:hidden;}
22
+ .dtk-tune-railhead{flex:0 0 auto;display:flex;align-items:center;justify-content:space-between;gap:8px;
23
+ padding:9px 12px;border-bottom:1px solid var(--border);}
24
+ .dtk-rail-title{font-family:var(--mono);font-size:11px;color:var(--muted);text-transform:uppercase;
25
+ letter-spacing:.06em;flex:1 1 auto;}
26
+ .dtk-tune-railfoot{flex:0 0 auto;display:flex;flex-direction:column;gap:8px;padding:11px 12px;
27
+ border-top:1px solid var(--border);background:var(--paper);}
28
+ .dtk-rail-open{position:absolute;top:50%;right:6px;transform:translateY(-50%);z-index:6;
29
+ border:1px solid var(--border);background:var(--surface);color:var(--ink);border-radius:8px;
30
+ padding:13px 7px;font-size:15px;cursor:pointer;box-shadow:0 1px 6px rgba(27,25,22,.14);}
31
+ .dtk-rail-open:hover{border-color:var(--c);color:var(--c7);}
32
+ .dtk-dock-toggle{flex:0 0 auto;border:1px solid var(--border);background:var(--surface);color:var(--muted);
33
+ border-radius:7px;padding:4px 10px;font-family:var(--sans);font-size:13px;font-weight:700;cursor:pointer;line-height:1;}
34
+ .dtk-dock-toggle:hover{border-color:var(--c);color:var(--c7);}
35
+ .dtk-tune-controls{flex:1;min-height:0;overflow-y:auto;display:flex;flex-direction:column;gap:14px;padding:14px;}
36
+ .dtk-rail-group{display:flex;flex-direction:column;gap:14px;}
37
+ .dtk-ctl{display:flex;flex-direction:column;gap:6px;}
38
+ .dtk-ctl-head{display:flex;justify-content:space-between;align-items:baseline;}
39
+ .dtk-ctl-label{font-size:12px;font-weight:600;color:var(--ink);}
40
+ .dtk-ctl-val{font-family:var(--mono);font-size:12px;color:var(--c7);}
41
+ .dtk-seg{display:flex;gap:4px;background:var(--paper);border:1px solid var(--border);border-radius:8px;padding:3px;}
42
+ .dtk-seg.dtk-wrap{flex-wrap:wrap;}
43
+ .dtk-seg-btn{flex:1 1 auto;border:0;background:transparent;color:var(--muted);font-family:var(--sans);
44
+ font-size:12px;padding:5px 8px;border-radius:6px;cursor:pointer;white-space:nowrap;}
45
+ .dtk-seg-btn:hover{color:var(--ink);}
46
+ .dtk-seg-btn.on{background:var(--c);color:#fff;font-weight:600;}
47
+ .dtk-range{width:100%;accent-color:var(--c);cursor:pointer;}
48
+ .dtk-check{display:flex;align-items:center;gap:6px;font-size:12px;color:var(--muted);margin-top:2px;cursor:pointer;}
49
+ .dtk-tune-chart{position:relative;width:100%;flex:1;min-height:220px;background:var(--surface);
50
+ border:1px solid var(--border);border-radius:12px;overflow:hidden;}
51
+ .dtk-tune-chart canvas{width:100%;height:100%;display:block;}
52
+ .dtk-tune-readout{font-family:var(--mono);font-size:12px;color:var(--muted);min-height:18px;}
53
+ .dtk-tune-stat{font-family:var(--mono);font-size:12px;color:var(--ink);}
54
+ .dtk-tune-warn{font-family:var(--mono);font-size:12px;line-height:1.5;color:var(--c7);
55
+ background:rgba(240,173,78,0.13);border:1px solid rgba(240,173,78,0.5);border-radius:8px;padding:8px 11px;}
56
+ .dtk-tune-cfg{background:var(--ink);color:#c9c2b4;border-radius:8px;padding:8px 11px;font-family:var(--mono);
57
+ font-size:12px;overflow-x:auto;}
58
+ .dtk-tune-cfg-k{display:flex;width:100%;border:0;background:transparent;color:var(--faint);
59
+ font-family:var(--mono);font-size:11.5px;cursor:pointer;padding:0;text-align:left;}
60
+ .dtk-tune-cfg-k:hover{color:#e6e0d4;}
61
+ .dtk-tune-cfg-v{display:block;color:#e6e0d4;white-space:pre-wrap;word-break:break-word;margin-top:6px;}
62
+ .dtk-tune-apply{display:flex;align-items:center;gap:10px;flex-wrap:wrap;}
63
+ .dtk-apply-btn{background:var(--c);color:#fff;border:0;border-radius:8px;padding:10px 18px;font-family:var(--sans);
64
+ font-size:14px;font-weight:600;cursor:pointer;}
65
+ .dtk-apply-btn:hover{background:var(--c7);}
66
+ .dtk-apply-btn:disabled{opacity:.55;cursor:default;}
67
+ .dtk-apply-msg{font-size:13px;}
68
+ .dtk-apply-msg.ok{color:var(--green);}
69
+ .dtk-apply-msg.err{color:var(--anom);}
70
+ .dtk-apply-msg.info{color:var(--muted);}
71
+ .dtk-tune-note{font-size:13px;color:var(--muted);background:var(--surface);border:1px dashed var(--border);
72
+ border-radius:8px;padding:10px 12px;}
73
+ .dtk-ctl-info{color:var(--faint);font-size:10px;cursor:help;vertical-align:super;}
74
+ .dtk-tune-trim{display:flex;flex-direction:column;gap:6px;background:var(--surface);
75
+ border:1px solid var(--border);border-radius:10px;padding:9px 12px;}
76
+ .dtk-tune-trim-head{display:flex;justify-content:space-between;align-items:baseline;}
77
+ .dtk-tune-trim-val{font-family:var(--mono);font-size:12px;color:var(--c7);}
78
+ .dtk-tune-spin{position:absolute;top:10px;right:12px;display:none;align-items:center;gap:7px;
79
+ background:rgba(27,25,22,0.78);color:#e6e0d4;border:1px solid #332f29;border-radius:999px;
80
+ padding:4px 11px 4px 8px;font-family:var(--mono);font-size:11px;pointer-events:none;}
81
+ .dtk-tune-spin.on{display:inline-flex;}
82
+ .dtk-spin-ring{width:12px;height:12px;border-radius:50%;border:2px solid rgba(245,241,232,0.25);
83
+ border-top-color:var(--c);animation:dtk-spin .7s linear infinite;}
84
+ @keyframes dtk-spin{to{transform:rotate(360deg);}}
85
+ .dtk-tune-legend{flex:0 0 auto;display:flex;align-items:center;flex-wrap:wrap;gap:8px 16px;font-size:12px;
86
+ color:var(--muted);padding:6px 12px;background:var(--surface);border:1px solid var(--border);border-radius:9px;}
87
+ .dtk-leg-item{display:inline-flex;align-items:center;gap:6px;cursor:help;}
88
+ .dtk-leg-sw{display:inline-block;flex:0 0 auto;}
89
+ .dtk-leg-sw.line{width:16px;height:3px;background:var(--c);border-radius:2px;}
90
+ .dtk-leg-sw.band{width:16px;height:11px;background:rgba(209,91,54,0.18);
91
+ border:1px solid rgba(209,91,54,0.5);border-radius:2px;}
92
+ .dtk-leg-sw.center{width:16px;height:2px;
93
+ background:repeating-linear-gradient(90deg,var(--faint) 0 4px,transparent 4px 7px);}
94
+ .dtk-leg-sw.dot{width:9px;height:9px;border-radius:50%;background:var(--anom);}
95
+ .dtk-leg-sw.alert{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;
96
+ border-top:7px solid var(--anom);}
97
+ .dtk-leg-sw.alert-ok{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;
98
+ border-top:7px solid var(--green);}
99
+ .dtk-leg-sw.alert-no{width:0;height:0;border-left:5px solid transparent;border-right:5px solid transparent;
100
+ border-top:7px solid #5a7a8c;}
101
+ .dtk-leg-txt{white-space:nowrap;}
102
+ .dtk-season-row{display:flex;align-items:center;justify-content:space-between;gap:8px;}
103
+ .dtk-season-col{font-family:var(--mono);font-size:11.5px;color:var(--muted);
104
+ overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}
105
+ .dtk-season-seg{flex:0 0 auto;padding:2px;}
106
+ .dtk-season-seg .dtk-seg-btn{flex:0 0 auto;padding:3px 7px;font-family:var(--mono);font-size:11px;}
107
+ .dtk-tune-metrics{display:flex;flex-wrap:wrap;gap:8px;margin:0;flex:0 1 auto;}
108
+ .dtk-m-chip{display:inline-flex;align-items:center;gap:7px;padding:7px 13px;background:var(--surface);
109
+ border:1px solid var(--border);border-radius:10px;font-size:13px;}
110
+ .dtk-m-dot{width:9px;height:9px;border-radius:50%;flex:0 0 auto;}
111
+ .dtk-m-v{font-family:var(--mono);font-weight:700;font-size:15px;color:var(--ink);}
112
+ .dtk-m-l{color:var(--faint);font-family:var(--mono);font-size:11px;text-transform:uppercase;letter-spacing:.05em;}
113
+ .dtk-m-sub{color:var(--muted);font-family:var(--mono);font-size:11.5px;}
114
+ .dtk-m-chip.over{border-color:var(--anom);box-shadow:inset 0 0 0 1px rgba(214,50,50,.5);}
115
+ .dtk-m-chip.over .dtk-m-sub{color:var(--anom);font-weight:600;}
116
+ .dtk-tune-modes{display:inline-flex;gap:4px;background:var(--ink);border-radius:9px;padding:4px;margin:0;flex:0 0 auto;}
117
+ .dtk-mode-btn{border:0;background:transparent;color:#c9c2b4;font-family:var(--sans);font-size:13px;font-weight:600;
118
+ padding:7px 16px;border-radius:6px;cursor:pointer;transition:background .12s,color .12s;}
119
+ .dtk-mode-btn:hover{color:#fff;}
120
+ .dtk-mode-btn.on{background:var(--c);color:#fff;}
121
+ .dtk-tune-reviewbar{align-items:center;}
122
+ .dtk-tune-reviewbar .dtk-apply-btn{background:var(--green);}
123
+ .dtk-tune-reviewbar .dtk-apply-btn:hover{background:#27815d;}
124
+ .dtk-at-result{display:flex;flex-direction:column;gap:7px;background:var(--surface);
125
+ border:1px solid var(--border);border-radius:10px;padding:11px 13px;}
126
+ .dtk-at-head{display:flex;flex-wrap:wrap;align-items:baseline;justify-content:space-between;gap:8px;}
127
+ .dtk-at-winner{font-family:var(--mono);font-size:12.5px;font-weight:700;color:var(--ink);}
128
+ .dtk-at-score{font-family:var(--mono);font-size:11.5px;color:var(--c7);}
129
+ .dtk-at-meta{font-family:var(--mono);font-size:11px;color:var(--muted);word-break:break-word;}
130
+ .dtk-at-log{display:flex;flex-direction:column;gap:5px;max-height:240px;overflow:auto;margin-top:4px;}
131
+ .dtk-at-logline{display:flex;gap:8px;align-items:baseline;}
132
+ .dtk-at-stage{flex:0 0 auto;font-family:var(--mono);font-size:9.5px;text-transform:uppercase;
133
+ letter-spacing:.05em;color:#fff;background:var(--c);border-radius:4px;padding:1px 6px;}
134
+ .dtk-at-msg{font-family:var(--mono);font-size:11px;color:var(--ink);}
135
+ .dtk-th{display:flex;flex-direction:column;gap:8px;margin:2px 0 6px;}
136
+ .dtk-th-toggles{display:flex;gap:8px;flex-wrap:wrap;}
137
+ .dtk-th-toggle{align-self:flex-start;border:1px solid var(--border);background:var(--surface);
138
+ color:var(--muted);border-radius:8px;padding:6px 12px;font-family:var(--sans);font-size:12.5px;cursor:pointer;}
139
+ .dtk-th-toggle:hover{border-color:var(--c);color:var(--c7);}
140
+ .dtk-th-toggle.on{background:var(--c);border-color:var(--c);color:#fff;}
141
+ .dtk-th-bar{display:flex;flex-wrap:wrap;align-items:flex-end;gap:10px 14px;padding:11px 13px;
142
+ background:var(--surface);border:1px solid var(--border);border-radius:10px;}
143
+ .dtk-th-grp{display:flex;flex-direction:column;gap:3px;}
144
+ .dtk-th-lbl{font-family:var(--mono);font-size:10.5px;color:var(--faint);text-transform:uppercase;letter-spacing:.05em;}
145
+ .dtk-th-num,.dtk-th-sel{background:var(--paper);color:var(--ink);border:1px solid var(--border);
146
+ border-radius:6px;padding:5px 8px;font-family:var(--mono);font-size:12px;}
147
+ .dtk-th-num{width:96px;}
148
+ .dtk-th-num:focus,.dtk-th-sel:focus{outline:none;border-color:var(--c);}
149
+ .dtk-th-scope{font-family:var(--mono);font-size:11px;color:var(--muted);align-self:center;flex:1 1 160px;}
150
+ .dtk-th-add{padding:7px 14px;}
151
+ .dtk-th-add:disabled{opacity:.5;cursor:default;}
152
+ .dtk-incidents{gap:8px;}
153
+ .dtk-inc-list{display:flex;flex-direction:column;gap:6px;max-height:240px;overflow:auto;}
154
+ .dtk-inc-empty{font-size:12px;color:var(--faint);font-style:italic;}
155
+ .dtk-inc-row{display:flex;align-items:center;gap:6px;flex-wrap:wrap;background:var(--paper);
156
+ border:1px solid var(--border);border-radius:7px;padding:6px 8px;}
157
+ .dtk-inc-span{font-family:var(--mono);font-size:10.5px;color:var(--ink);}
158
+ .dtk-inc-dur{font-family:var(--mono);font-size:10.5px;color:var(--muted);}
159
+ .dtk-inc-label{flex:1 1 90px;min-width:70px;background:var(--surface);color:var(--ink);
160
+ border:1px solid var(--border);border-radius:5px;padding:4px 7px;font-family:var(--sans);font-size:11.5px;}
161
+ .dtk-inc-label:focus{outline:none;border-color:var(--c);}
162
+ .dtk-inc-btn{border:1px solid var(--border);background:var(--surface);color:var(--muted);border-radius:6px;
163
+ padding:3px 8px;font-size:11px;cursor:pointer;font-family:var(--sans);}
164
+ .dtk-inc-btn:hover{border-color:var(--c);color:var(--c7);}
165
+ .dtk-inc-del{color:var(--anom);}
166
+ .dtk-inc-fromalert{border-color:rgba(46,158,115,.5);background:rgba(46,158,115,.08);}
167
+ .dtk-inc-badge{flex:1 1 90px;min-width:70px;font-family:var(--mono);font-size:10.5px;color:var(--green);
168
+ display:inline-flex;align-items:center;font-weight:600;}
169
+ .dtk-setname{background:var(--surface);color:var(--ink);border:1px solid var(--border);border-radius:8px;
170
+ padding:9px 11px;font-family:var(--sans);font-size:13px;min-width:180px;}
171
+ .dtk-setname::placeholder{color:var(--faint);}
172
+ .dtk-setname:focus{outline:none;border-color:var(--c);}
173
+ .dtk-labels-btn{background:var(--surface);color:var(--ink);border:1px solid var(--border);}
174
+ .dtk-labels-btn:hover{background:var(--paper);border-color:var(--c);color:var(--c7);}
175
+ /* Narrow viewports: drop the cockpit to a scrolling stack (chart over rail). */
176
+ @media (max-width:900px){
177
+ .dtk-tune-root{height:auto;overflow:visible;}
178
+ .dtk-tune-cockpit{flex-direction:column;}
179
+ .dtk-tune-rail{flex:0 0 auto;width:100%;}
180
+ .dtk-tune-controls{overflow:visible;}
181
+ .dtk-tune-chart{flex:0 0 auto;height:54vh;min-height:320px;}
182
+ .dtk-rail-open{display:none!important;}
183
+ }
184
+ `,i=document.createElement("style");i.textContent=n,document.head.appendChild(i)}var Lo={mad:3,zscore:3,iqr:1.5,autoreg:3},Ro={mad:10,zscore:3,iqr:4},No={mad:1,zscore:1,iqr:4},Eo="dtk-tune";function $o(n){let i=URL.createObjectURL(new Blob([n.src],{type:"text/javascript"})),f=n.series,t,v=0,y=!1,S=null,g=0,k=Y=>{let U=Y.data;U.type!=="result"||U.id!==v||!S||(y=!1,n.onResult(U,S))},D=()=>{y=!1,n.onError()};function A(){t=new Worker(i),t.onmessage=k,t.onerror=D,t.postMessage({type:"series",series:f})}A();let I=()=>{S=n.getParams(),n.onDispatch(S),v+=1,y&&(t.terminate(),A()),y=!0;let Y=n.getShare();t.postMessage({type:"run",id:v,params:S,anomalyWindowPoints:Y.windowPoints,minAnomalyShare:Y.share})};return{postSeries:Y=>{f=Y,t.postMessage({type:"series",series:f})},recompute:()=>{g&&window.clearTimeout(g),g=window.setTimeout(I,130)},runNow:I,destroy:()=>{g&&window.clearTimeout(g),t.terminate(),URL.revokeObjectURL(i)}}}function Xo(n,i,f){var lo,co,uo,mo,po,fo,ho;Po(),i.classList.add(Eo),i.innerHTML="";let t=m("div","dtk-tune-root");i.appendChild(t);let v=n.points.length,y={timestamps:n.points.map(e=>e.t),values:n.points.map(e=>e.v==null?NaN:e.v),intervalSeconds:n.interval_seconds,truthAnomaly:new Array(v).fill(!1),seasonalityData:n.seasonality_columns.length?n.seasonality:void 0,seasonalityColumns:n.seasonality_columns.length?n.seasonality_columns:void 0},S=y,g=e=>{let s=Math.max(0,v-e);return s<=0?y:{timestamps:y.timestamps.slice(s),values:y.values.slice(s),intervalSeconds:y.intervalSeconds,truthAnomaly:y.truthAnomaly.slice(s),seasonalityData:y.seasonalityData?y.seasonalityData.slice(s):void 0,seasonalityColumns:y.seasonalityColumns}},k=e=>Date.parse(e.replace(" ","T")+"Z"),D=(n.incidents||[]).map(e=>({start:k(e.start),end:k(e.end),label:e.label||""})).filter(e=>Number.isFinite(e.start)&&Number.isFinite(e.end)).map(e=>({start:Math.min(e.start,e.end),end:Math.max(e.start,e.end),label:e.label})),A=(()=>{let e=(n.capture_windows||[])[0];if(!e)return null;let s=k(e.start),p=k(e.end);return!Number.isFinite(s)||!Number.isFinite(p)?null:{start:Math.min(s,p),end:Math.max(s,p)}})(),I=[],ee=[],ne=[],de=[],Y=(n.alert_reviews||[]).map(e=>({start:k(e.start),end:k(e.end),verdict:e.verdict==="false"?"false":"valid"})).filter(e=>Number.isFinite(e.start)&&Number.isFinite(e.end)),U=()=>n.interval_seconds*1e3/2,a=(e,s)=>{let p=U();for(let x of Y)if(s>=x.start-p&&e<=x.end+p)return x.verdict;return null},w=(e,s,p)=>{let x=U();for(let P=Y.length-1;P>=0;P--){let b=Y[P];s>=b.start-x&&e<=b.end+x&&Y.splice(P,1)}p&&Y.push({start:e,end:s,verdict:p})},N=(e,s)=>{let p=U();return e.end>=s.start-p&&e.start<=s.end+p},te=()=>Y.filter(e=>e.verdict==="valid").map(e=>({start:e.start,end:e.end,label:"confirmed alert"})),be=()=>te().filter(e=>!D.some(s=>N(e,s))),$=()=>[...D,...be()],oe=e=>{let s=!1;for(let p=Y.length-1;p>=0;p--)Y[p].verdict==="valid"&&N(Y[p],e)&&(Y.splice(p,1),s=!0);return s},Qe=()=>I.map((e,s)=>{var P;let p=(P=ee[s])!=null?P:[e,e],x=a(p[0],p[1]);return{t:e,kind:x==="valid"?"anomaly-validated":x==="false"?"anomaly-false":"anomaly"}}),C=n.detector,ce=null,De=e=>{var s;return(s=Ro[e])!=null?s:10},at=e=>{var s;return(s=No[e])!=null?s:1},Ue=n.consecutive_anomalies,re=(lo=n.anomaly_window_points)!=null?lo:0,Le=(co=n.min_anomaly_share)!=null?co:.3,ue=()=>re>=2?re:null,ge=()=>re>=2?Le:null,Ae=n.detectors||[],J=typeof n.detector_index=="number"?n.detector_index:null,X=J,V=new Set,G=new Map,xe=()=>{J!=null&&V.add(J)},ve=y.values.filter(e=>Number.isFinite(e)).sort((e,s)=>e-s),ie=ve.length?ve[0]:0,me=ve.length?ve[ve.length-1]:1,qt=e=>ve.length?ve[Math.min(ve.length-1,Math.max(0,Math.round(e*(ve.length-1))))]:0,Xt=Math.max((me-ie)*.05,1e-9),Ve=ie-Xt,Oe=me+Xt,He=Math.max((Oe-Ve)/400,1e-9),Ze=C.lowerBound!=null?C.lowerBound:qt(.05),Et=C.upperBound!=null?C.upperBound:qt(.95),Ge=(uo=C.seasonalityComponents)!=null?uo:[],Pe=new Map;Ge.forEach((e,s)=>e.forEach(p=>Pe.set(p,s+1)));let O=()=>{let e=0;Pe.forEach(p=>{p>e&&(e=p)});let s=[];for(let p=1;p<=e;p++){let x=n.seasonality_columns.filter(P=>Pe.get(P)===p);x.length&&s.push(x)}return s.length?s:null},ke=e=>{if(!e||!n.seasonality.length)return 0;let s=0;for(let p of e){let x=new Set;for(let P of n.seasonality)x.add(p.map(b=>{var L;return String((L=P==null?void 0:P[b])!=null?L:"")}).join("|"));s=Math.max(s,x.size)}return s},et=()=>{var e;return{type:E.get(),threshold:H.get(),windowSize:j.get(),minSamples:C.minSamples,inputType:C.inputType,smoothing:wn.get(),smoothingAlpha:C.smoothingAlpha,smoothingWindow:C.smoothingWindow,windowWeights:Z.get(),halfLife:Z.get()==="exponential"?we.get():null,detrend:vn.get(),stabilization:yn.get(),seasonalityComponents:O(),minSamplesPerGroup:ce?Math.round(ce.get()):(e=C.minSamplesPerGroup)!=null?e:De(E.get()),consecutiveAnomalies:Ue,direction:to.get(),lowerBound:_.get(),upperBound:z.get(),lags:W.get()}},Se=m("div","dtk-tune-header"),lt=m("div","dtk-tune-titlerow");lt.appendChild(m("h1","dtk-tune-title",n.metric));let Re=m("span","dtk-tune-badge",n.save_url?"manual tuning":"preview");lt.appendChild(Re),Se.appendChild(lt);let En=n.project?`${n.project} \xB7 `:"";Se.appendChild(m("div","dtk-tune-sub",`${En}${v} points \xB7 ${To(n.interval_seconds)} grid`)),n.description&&Se.appendChild(m("div","dtk-tune-desc",n.description)),t.appendChild(Se);let Jt=m("div","dtk-tune-metrics"),se=m("div","dtk-tune-cockpit");t.appendChild(se);let $e=m("div","dtk-tune-stage");se.appendChild($e);let Ne=m("div","dtk-tune-hud");Ne.appendChild(Jt),$e.appendChild(Ne);let bt=m("div","dtk-tune-stagefoot"),ze=m("div","dtk-tune-rail");se.appendChild(ze);let dt=m("div","dtk-tune-railhead"),gt=m("span","dtk-rail-title","Tune \xB7 controls"),$t=m("button","dtk-dock-toggle","\u27E9");$t.type="button",$t.title="Collapse the control rail to give the chart the whole width.",dt.appendChild(gt),dt.appendChild($t),ze.appendChild(dt);let vt=m("div","dtk-tune-controls");ze.appendChild(vt);let zt=m("div","dtk-rail-group"),pe=m("div","dtk-rail-group"),Wt=m("div","dtk-rail-group"),ct=m("div","dtk-rail-group"),tt=m("div","dtk-rail-group"),ut=m("div","dtk-rail-group");Wt.style.display="none",ct.style.display="none",tt.style.display="none",vt.append(zt,pe,Wt,ct,tt,ut);let yt=m("div","dtk-tune-railfoot");ze.appendChild(yt);let Fe=m("button","dtk-rail-open","\u2699");Fe.type="button",Fe.title="Show the control rail",Fe.style.display="none",$e.appendChild(Fe);let It=e=>{ze.style.display=e?"":"none",Fe.style.display=e?"none":""};$t.onclick=()=>It(!1),Fe.onclick=()=>It(!0);let wt=m("div","dtk-tune-trim"),fe=m("div","dtk-tune-trim-head");fe.appendChild(Lt("Points shown","Trim the active sample to the most-recent N points. Fewer points recompute faster (cost grows with points \xD7 window) and make a shorter period easier to read \u2014 handy once you can see a smaller window/period is enough."));let Qt=m("span","dtk-tune-trim-val");fe.appendChild(Qt),wt.appendChild(fe);let We=m("input","dtk-range");We.type="range",We.min=String(Math.min(v,200)),We.max=String(v),We.step=String(Math.max(1,Math.round(v/200))),We.value=String(v),wt.appendChild(We),zt.appendChild(wt);let xt=m("div","dtk-tune-chart"),Zt=m("canvas");xt.appendChild(Zt);let mt=m("div","dtk-tune-spin");mt.appendChild(m("span","dtk-spin-ring")),mt.appendChild(m("span","dtk-spin-txt","computing\u2026")),xt.appendChild(mt),$e.appendChild(xt),$e.appendChild(bt);let Ot=m("div","dtk-tune-modes"),Ht={};[{v:"tune",label:"Tune",hint:"Steer the band \u2014 the confidence corridor leads; incidents recede to read-only context. Hover a point for its window."},{v:"review",label:"Review alerts",hint:"Confirm the fired alerts \u2014 click a marker to cycle un-reviewed \u2192 valid (green) \u2192 false (slate). The band ghosts so the alerts lead."},{v:"label",label:"Label incidents",hint:"Mark real incidents \u2014 drag a span, lasso the anomaly cloud, or threshold-capture. The band hides so incidents lead."},{v:"autotune",label:"Autotune",hint:"Let the autotune engine search for the best detector server-side, using your marked incidents as ground truth, then re-seed the knobs with the winner. Review the band, then Apply."}].forEach(e=>{let s=m("button","dtk-mode-btn",e.label);s.type="button",s.title=e.hint,s.dataset.v=e.v,s.onclick=()=>hn(e.v),Ht[e.v]=s,Ot.appendChild(s)}),Ne.appendChild(Ot);let un=m("div","dtk-tune-legend"),nt=(e,s,p)=>{let x=m("span","dtk-leg-item");x.title=p,x.appendChild(m("span",`dtk-leg-sw ${e}`)),x.appendChild(m("span","dtk-leg-txt",s)),un.appendChild(x)};nt("alert","alert","A fired alert, not yet reviewed \u2014 enough consecutive anomalies to meet the rule."),nt("alert-ok","valid alert","An alert you confirmed is real (click a marker in Review mode). Counts toward recall."),nt("alert-no","false alarm","An alert you marked a false positive. Stays in the false-alert rate."),nt("dot","anomaly","A point the detector flagged as anomalous (outside the band)."),nt("line","metric","The metric value over time."),nt("band","expected range","The detector's confidence band \u2014 values inside it read as normal."),nt("center","band center","The expected value at the middle of the band."),$e.insertBefore(un,xt);let en=m("div","dtk-tune-readout");bt.appendChild(en);let Ye=m("div","dtk-tune-warn");Ye.style.display="none",bt.appendChild(Ye);let $n=e=>{if(e.type==="autoreg"||e.type==="manual_bounds"){Ye.style.display="none";return}let s=e.seasonalityComponents,p=ke(s),x=e.minSamplesPerGroup*p;s&&p>0&&e.windowSize<x?(Ye.textContent=`\u26A0 Seasonality inactive at this window: ${e.windowSize} < ${x} (min_samples_per_group ${e.minSamplesPerGroup} \xD7 ${p} key${p===1?"":"s"}). Each point keeps only ~${Math.floor(e.windowSize/p)} same-key point(s), so the band falls back to global statistics (seasonality has no effect) \u2014 this, not the smaller window itself, is why the band widened. Raise the window to \u2265 ${x}, or lower \u201CMin samples per group\u201D.`,Ye.style.display=""):Ye.style.display="none"},Be=m("div","dtk-tune-warn");Be.style.display="none",bt.appendChild(Be);let mn=(e,s)=>{var x;if(S.timestamps.length===0||e>0){Be.style.display="none";return}if(s.type==="autoreg"){let P=Math.max(1,Math.round((x=s.lags)!=null?x:5)),b=Math.max(s.minSamples,P+2),L=["raise Window size / Points shown",`lower Lags (${P}) or min_samples (${s.minSamples})`];s.stabilization==="clamp"&&L.push("turn Stabilization off"),Be.textContent=`\u26A0 No band drawn: autoreg scored 0 points in the shown window. It needs ${b} gap-free fit rows of ${P+1} consecutive points each, and the ${s.windowSize}-point window can't collect them here (too small, too little shown history, or gaps in view). To get a band: ${L.join(", or ")}.`}else Be.textContent=`\u26A0 No band drawn: the detector scored 0 points in the shown window \u2014 the ${s.windowSize}-point window holds fewer than min_samples (${s.minSamples}) valid points here. To get a band: raise Window size / Points shown, or lower min_samples.`;Be.style.display=""},pn=typeof n.false_alert_budget=="number"&&n.false_alert_budget>0?n.false_alert_budget:null;function kt(){let e=Ao(ee,{timestamps:S.timestamps,tol:U(),incidents:D,validatedSpans:te(),reviewFor:a});_o(Jt,e,pn)}let B=()=>{},Ke=()=>{},q=Mo(Zt,{navigable:!0,labeling:!0,mode:"tune",yFit:"data",onHover:e=>{if(!e||!e.point||!e.point.scored){en.textContent="";return}let s=e.point;en.textContent=`t=${Nn(s.timestamp)} value=${Kt(s.value)} band=[${Kt(s.lower)}, ${Kt(s.upper)}]`+(s.isAnomaly?` \u26A0 ${s.direction} (sev ${s.severity.toFixed(2)})`:"")},onIncidentsChange:(e,s)=>{(s?oe(s):!1)?ye():(Cn(),kt())},onThresholdChange:e=>B(e),onLassoChange:e=>Ke(e),onAlertReviewChange:(e,s)=>{let p=I.indexOf(e),x=p>=0?ee[p]:[e,e];w(x[0],x[1],s==="unreviewed"?null:s),ye()}});q.setIncidents(D),A&&q.setCaptureWindow(A);let ye=()=>{de=Qe(),Vt&&q.render({series:S,scored:ne,params:Vt,alerts:de,incidents:D}),kt(),Cn()},le=m("div","dtk-th"),ot=m("div","dtk-th-toggles"),St=m("button","dtk-th-toggle","Threshold capture");St.type="button",St.title="Mark incidents fast: set a horizontal line and grab every contiguous span above (or below) it. Click the chart to set the line, drag across it to limit the capture to a time window.",ot.appendChild(St);let pt=m("button","dtk-th-toggle","Lasso anomalies");pt.type="button",pt.title="Draw a freeform loop around a cloud of anomaly dots on the chart below \u2014 each run of consecutive anomalies (small gaps bridged) becomes one incident span. The ideal way to turn what the detector already flags into ground-truth incidents.",ot.appendChild(pt),le.appendChild(ot);let Ee=m("div","dtk-th-bar"),Mt=m("select","dtk-th-sel");for(let[e,s]of[["above","above the line"],["below","below the line"]]){let p=m("option");p.value=e,p.textContent=s,Mt.appendChild(p)}let qe=m("input","dtk-th-num");qe.type="number",qe.step="any",qe.placeholder="hover chart";let Xe=m("input","dtk-th-num");Xe.type="number",Xe.min="0",Xe.step="1",Xe.value="0";let tn=m("span","dtk-th-scope"),ft=m("button","dtk-inc-btn","\u21BA whole view");ft.type="button",ft.style.display="none";let rt=m("button","dtk-apply-btn dtk-th-add","Add 0 spans");rt.type="button",rt.disabled=!0;let Ft=m("button","dtk-inc-btn","Done");Ft.type="button";let nn=(e,s)=>{let p=m("label","dtk-th-grp");return p.appendChild(m("span","dtk-th-lbl",e)),p.appendChild(s),p};Ee.appendChild(nn("grab points",Mt)),Ee.appendChild(nn("line value",qe)),Ee.appendChild(nn("bridge gaps \u2264",Xe)),Ee.appendChild(tn),Ee.appendChild(ft),Ee.appendChild(rt),Ee.appendChild(Ft),Ee.style.display="none",le.appendChild(Ee);let Ct=m("div","dtk-th-bar"),fn=m("span","dtk-th-scope","draw a loop around the anomaly dots on the chart below"),on=m("button","dtk-inc-btn","Done");on.type="button",Ct.appendChild(fn),Ct.appendChild(on),Ct.style.display="none",le.appendChild(Ct),ct.appendChild(le);let Bt=m("div","dtk-th-bar dtk-tune-reviewbar");Bt.appendChild(m("span","dtk-th-scope","Click a red alert marker to confirm it valid (green) or mark it a false alarm \u2014 cycle un-reviewed \u2192 valid \u2192 false."));let rn=m("button","dtk-apply-btn dtk-th-add","Confirm all unreviewed valid");rn.type="button",rn.onclick=()=>{for(let[e,s]of ee)a(e,s)||w(e,s,"valid");ye()};let sn=m("button","dtk-inc-btn","Clear verdicts");sn.type="button",sn.onclick=()=>{Y.length=0,ye()},Bt.appendChild(rn),Bt.appendChild(sn),Wt.appendChild(Bt);let zn={tune:"Tune \xB7 controls",review:"Review \xB7 verdicts",label:"Label \xB7 incidents",autotune:"Autotune \xB7 search"};function hn(e){q.setMode(e==="autotune"?"tune":e),Object.keys(Ht).forEach(s=>{var p;return(p=Ht[s])==null?void 0:p.classList.toggle("on",s===e)}),e!=="label"&&(Tt(!1),At(!1)),pe.style.display=e==="tune"?"":"none",Wt.style.display=e==="review"?"":"none",ct.style.display=e==="label"?"":"none",tt.style.display=e==="autotune"?"":"none",yt.style.display=e==="tune"||e==="autotune"?"":"none",gt.textContent=zn[e]}let jt=!1,Ut=!1,an=!1,Tt=e=>{jt=e,St.classList.toggle("on",e),Ee.style.display=e?"flex":"none",q.setThresholdMode(e),e&&Ut&&At(!1)},At=e=>{Ut=e,pt.classList.toggle("on",e),Ct.style.display=e?"flex":"none",q.setLassoMode(e),e&&jt&&Tt(!1)};St.onclick=()=>Tt(!jt),Ft.onclick=()=>Tt(!1),pt.onclick=()=>At(!Ut),on.onclick=()=>At(!1),Mt.onchange=()=>q.setThresholdDirection(Mt.value),qe.oninput=()=>{let e=qe.value.trim();an=!0,q.setThresholdValue(e!==""&&!isNaN(Number(e))?Number(e):null),an=!1},Xe.oninput=()=>q.setThresholdGap(Number(Xe.value)||0),ft.onclick=()=>q.clearCaptureWindow(),rt.onclick=()=>{q.applyThreshold()};let bn=e=>{e.key==="Escape"&&(jt?Tt(!1):Ut&&At(!1))};window.addEventListener("keydown",bn),Ke=e=>{fn.textContent=e.active?`${e.anomalies} anomal${e.anomalies===1?"y":"ies"} \u2192 ${e.incidents} incident${e.incidents===1?"":"s"} \u2014 release to add`:"draw a loop around the anomaly dots on the chart below"},B=e=>{rt.textContent=`Add ${e.runs} span${e.runs===1?"":"s"}`,rt.disabled=e.runs===0,e.locked&&e.value!=null&&!an&&(qe.value=String(Math.round(e.value*1e3)/1e3)),ft.style.display=e.committed?"":"none",tn.textContent=e.window?`scope: ${Nt(e.windowMs)} painted`:"scope: current view \u2014 drag the chart to limit it"};let Vt=null,o=$o({src:`"use strict";(()=>{var re={mad:1,zscore:2,iqr:4};function H(n){let e=0;for(let t of n)e+=t;return e}function le(n){let e=n.map((t,i)=>i);return e.sort((t,i)=>n[t]<n[i]?-1:n[t]>n[i]?1:t-i),e}function ce(n,e,t){let i=e.length;if(i===0)return NaN;if(n<=e[0])return t[0];if(n>=e[i-1])return t[i-1];for(let r=1;r<i;r++)if(n<=e[r]){let o=e[r-1],u=e[r],s=t[r-1],l=t[r];if(u===o)return s;let a=(n-o)/(u-o);return s+a*(l-s)}return t[i-1]}function $(n,e,t){let i=le(n),r=i.map(c=>n[c]),o=i.map(c=>e[c]),u=H(o),s=new Array(o.length),l=0;for(let c=0;c<o.length;c++)l+=o[c],s[c]=(l-.5*o[c])/u;let a=t/100;return ce(a,s,r)}function V(n,e){return $(n,e,50)}function ae(n,e,t){let i=t===void 0?V(n,e):t,r=n.map(o=>Math.abs(o-i));return V(r,e)}function fe(n,e){let t=H(e),i=0;for(let r=0;r<n.length;r++)i+=n[r]*(e[r]/t);return i}function me(n,e,t,i=0){let r=H(e),o=e.map(l=>l/r),u=t===void 0?H(n.map((l,a)=>l*o[a])):t,s=0;for(let l=0;l<n.length;l++)s+=o[l]*(n[l]-u)**2;if(i===1){let l=1-H(o.map(a=>a*a));l>1e-12&&(s/=l)}return Math.sqrt(s)}function de(n,e){return e.smoothing==="none"?n.slice():e.smoothing==="ema"?be(n,e.smoothingAlpha):pe(n,e.smoothingWindow)}function be(n,e){let t=n.length,i=new Array(t).fill(NaN);if(t===0)return i;let r=-1;for(let o=0;o<t;o++)if(!Number.isNaN(n[o])){r=o;break}if(r===-1)return i;i[r]=n[r];for(let o=r+1;o<t;o++)Number.isNaN(n[o])?i[o]=i[o-1]:i[o]=e*n[o]+(1-e)*i[o-1];return i}function pe(n,e){let t=n.length,i=new Array(t).fill(NaN);for(let r=0;r<t;r++){let o=Math.max(0,r-e+1),u=0,s=0;for(let l=o;l<=r;l++)Number.isNaN(n[l])||(u+=n[l],s+=1);i[r]=s>0?u/s:NaN}return i}function ee(n,e){let t=n.length;if(e.inputType==="values")return n.slice();let i=new Array(t).fill(NaN);for(let r=1;r<t;r++){let o=n[r-1],u=n[r];e.inputType==="changes"?i[r]=(u-o)/o:e.inputType==="absolute_changes"?i[r]=u-o:i[r]=Math.log(u+1)-Math.log(o+1)}return i}function he(n,e){return n.halfLife!==null?n.halfLife:Math.max(n.windowSize/20,e/2,1)}function ye(n,e){if(n.windowWeights==="none")return null;let t=n.windowSize,i=new Array(t);if(n.windowWeights==="exponential"){let r=he(n,e);for(let o=1;o<=t;o++){let u=Math.min(o/r,1e3);i[o-1]=Math.pow(.5,u)}return i}for(let r=1;r<=t;r++)i[r-1]=(t+1-r)/t;return i}function ne(n,e){return e===null?n.map(()=>1):n.map(t=>e[t-1])}function ge(n){let e=n[0];for(let t of n)t>e&&(e=t);return e}function we(n){let e=n[0];for(let t of n)t<e&&(e=t);return e}function Se(n,e,t){if(n.length<4)return 0;let i=(ge(e)+we(e))/2,r=e.map(y=>y>i),o=r.map(y=>!y),u=0,s=0;for(let y=0;y<e.length;y++)r[y]?u++:s++;if(u<2||s<2)return 0;let l=(y,_)=>_.filter((N,z)=>y[z]),a=l(o,n),c=l(r,n),w=l(o,e),p=l(r,e),v=l(o,t),d=l(r,t),A=V(a,v),f=V(c,d),k=V(w,v),h=V(p,d);return h===k?0:(A-f)/(h-k)}var Me={mad:[["median","center"],["mad","spread"]],zscore:[["mean","center"],["std","spread"]],iqr:[["q1","center"],["q3","center"],["iqr","spread"]]};function te(n,e,t){if(n==="mad"){let o=V(e,t);return{median:o,mad:ae(e,t,o)}}if(n==="zscore"){let o=fe(e,t);return{mean:o,std:me(e,t,o,1)}}let i=$(e,t,25),r=$(e,t,75);return{q1:i,q3:r,iqr:r-i}}function Ae(n,e,t){if(n==="mad"){if(e.mad===0)return[e.median-1e-10,e.median+1e-10];let i=t*1.4826*e.mad;return[e.median-i,e.median+i]}return n==="zscore"?e.std===0?[e.mean-1e-10,e.mean+1e-10]:[e.mean-t*e.std,e.mean+t*e.std]:e.iqr===0?[e.q1-1e-10,e.q3+1e-10]:[e.q1-t*e.iqr,e.q3+t*e.iqr]}function Ne(n,e,t){if(n==="mad"){let i=1.4826*e.mad;return i>0?t/i:1/0}return n==="zscore"?e.std>0?t/e.std:1/0:e.iqr>0?t/e.iqr:1/0}function ke(n,e){return n==="mad"?e.median:n==="zscore"?e.mean:(e.q1+e.q3)/2}function J(n,e,t,i,r){return{index:n,timestamp:e,value:t,processedValue:i,scored:!1,isAnomaly:!1,lower:NaN,upper:NaN,center:NaN,direction:null,severity:0,reason:r}}function xe(n,e){var a,c,w;let{timestamps:t,values:i}=n,r=t.length,o=ee(i,e),u=(a=e.lowerBound)!=null?a:null,s=(c=e.upperBound)!=null?c:null,l=[];for(let p=0;p<r;p++){let v=i[p],d=o[p],A=t[p];if(Number.isNaN(d)){l.push(J(p,A,v,d,"missing_data"));continue}let f=!1,k=null,h=0;u!==null&&d<u&&(f=!0,k="below",h=u-d),s!==null&&d>s&&(f=!0,k="above",h=d-s);let y=0;if(f)if(u!==null&&s!==null){let x=s-u;y=x>0?h/x:1/0}else y=h;let _=u!=null?u:-1/0,N=s!=null?s:1/0,z=u!==null&&s!==null?(u+s)/2:(w=u!=null?u:s)!=null?w:NaN;l.push({index:p,timestamp:A,value:v,processedValue:d,scored:!0,isAnomaly:f,lower:_,upper:N,center:z,direction:k,severity:y,reason:"ok"})}return l}function De(n,e){let t=e.length;for(let r=0;r<t;r++){let o=r;for(let s=r+1;s<t;s++)Math.abs(n[s][r])>Math.abs(n[o][r])&&(o=s);o!==r&&([n[r],n[o]]=[n[o],n[r]],[e[r],e[o]]=[e[o],e[r]]);let u=n[r][r];if(u!==0)for(let s=r+1;s<t;s++){let l=n[s][r]/u;if(l!==0){for(let a=r;a<t;a++)n[s][a]-=l*n[r][a];e[s]-=l*e[r]}}}let i=new Array(t).fill(0);for(let r=t-1;r>=0;r--){let o=e[r];for(let u=r+1;u<t;u++)o-=n[r][u]*i[u];i[r]=n[r][r]!==0?o/n[r][r]:0}return i}function ve(n,e){let t=n[0].length,i=Array.from({length:t},()=>new Array(t).fill(0)),r=new Array(t).fill(0);for(let s=0;s<n.length;s++){let l=n[s];for(let a=0;a<t;a++){r[a]+=l[a]*e[s];for(let c=a;c<t;c++)i[a][c]+=l[a]*l[c]}}for(let s=0;s<t;s++)for(let l=0;l<s;l++)i[s][l]=i[l][s];let o=0;for(let s=0;s<t;s++)o+=i[s][s];let u=1e-8*(o/t);for(let s=0;s<t;s++)i[s][s]+=u;return De(i,r)}function Pe(n,e){var v;let{timestamps:t,values:i}=n,r=t.length,o=Math.max(1,Math.round((v=e.lags)!=null?v:5)),u=e.windowSize,s=e.threshold,l=Math.max(e.minSamples,o+2),a=e.stabilization==="clamp",c=ee(i,e),w=a?c.slice():c,p=[];for(let d=0;d<r;d++){let A=i[d],f=c[d],k=t[d];if(Number.isNaN(f)){p.push(J(d,k,A,f,"missing_data"));continue}let h=d>=o;if(h){for(let m=d-o;m<d;m++)if(!Number.isFinite(w[m])){h=!1;break}}if(!h){p.push(J(d,k,A,f,"missing_lags"));continue}let y=Math.max(o,d-u),_=y-o,N=[],z=[];for(let m=y;m<d;m++){let S=w[m];if(!Number.isFinite(S))continue;let g=!0,D=new Array(o);for(let R=0;R<o;R++){let Y=w[m-o+R];if(!Number.isFinite(Y)){g=!1;break}D[R]=Y}g&&(N.push(S),z.push(D))}let x=N.length;if(x<l){p.push(J(d,k,A,f,"insufficient_data"));continue}let P=H(N)/x,O=0;for(let m of N)O+=(m-P)*(m-P);let T=Math.sqrt(O/x);Number.isFinite(P)||(P=0),(!Number.isFinite(T)||T<=0)&&(T=1);let j=new Array(x),I=new Array(x);for(let m=0;m<x;m++){let S=new Array(o+1);S[0]=1;for(let g=0;g<o;g++)S[g+1]=(z[m][g]-P)/T;j[m]=S,I[m]=(N[m]-P)/T}let Q=ve(j,I),U=0;for(let m=0;m<x;m++){let S=0;for(let D=0;D<=o;D++)S+=j[m][D]*Q[D];let g=I[m]-S;U+=g*g}let C=Math.sqrt(U/Math.max(x-(o+1),1))*T,q=Q[0];for(let m=0;m<o;m++)q+=(w[d-o+m]-P)/T*Q[m+1];let F=q*T+P,W=F-s*C,L=F+s*C,E=f<W||f>L;if(a&&E){let m=f<W?W:L,S=1/0,g=-1/0;for(let D=_;D<d;D++){let R=c[D];Number.isFinite(R)&&(R<S&&(S=R),R>g&&(g=R))}S<=g&&(m=Math.min(Math.max(m,S),g)),w[d]=m}let X=null,b=0;if(E){let m;f<W?(X="below",m=W-f):(X="above",m=f-L),b=C>0?m/C:1/0}p.push({index:d,timestamp:k,value:A,processedValue:f,scored:!0,isAnomaly:E,lower:W,upper:L,center:F,direction:X,severity:b,reason:"ok"})}return p}function oe(n,e){if(e.type==="manual_bounds")return xe(n,e);if(e.type==="autoreg")return Pe(n,e);let t=e.type,i=Math.max(e.minSamples,re[t]),r=Me[t],{timestamps:o,values:u}=n,s=o.length,l=de(u,e),a=ee(l,e),c=e.stabilization==="clamp",w=c?a.slice():a,p=e.seasonalityComponents!==null&&e.seasonalityComponents.length>0&&Array.isArray(n.seasonalityData)&&n.seasonalityData.length>0,v=n.seasonalityData,d=ye(e,i),A=[];for(let f=0;f<s;f++){let k=u[f],h=a[f],y=o[f];if(Number.isNaN(h)){A.push(J(f,y,k,h,"missing_data"));continue}let _=Math.max(0,f-e.windowSize),N=f-_,z=w.slice(_,f),x=z.map(b=>!Number.isNaN(b)),P=[];for(let b=0;b<z.length;b++)x[b]&&P.push(z[b]);if(P.length<i){A.push(J(f,y,k,h,"insufficient_data"));continue}let O=new Array(N);for(let b=0;b<N;b++)O[b]=N-b;let T=[];for(let b=0;b<N;b++)x[b]&&T.push(O[b]);let j=ne(T,d),I=0;e.detrend==="linear"&&(I=Se(P,T,j));let Q=I!==0?P.map((b,m)=>b+I*T[m]):P,U=te(t,Q,j),C={...U};if(p&&v){let b=v[f];for(let m of e.seasonalityComponents){let S=new Array(N).fill(!0);for(let M=0;M<N;M++){let B=v[_+M],G=!0;for(let Z of m)if(!B||B[Z]!==(b==null?void 0:b[Z])){G=!1;break}S[M]=G}let g=[],D=[];for(let M=0;M<N;M++)x[M]&&S[M]&&(g.push(z[M]),D.push(O[M]));if(g.length<e.minSamplesPerGroup)continue;let R=ne(D,d),Y=I!==0?g.map((M,B)=>M+I*D[B]):g,se=te(t,Y,R);for(let[M,B]of r){let G=U[M],ue=(B==="spread"?G>0:G!==0)?se[M]/G:1;C[M]*=ue}}}let[q,F]=Ae(t,C,e.threshold);q>F&&([q,F]=[F,q]);let W=h<q||h>F,L=null,E=0;if(W){let b;h<q?(L="below",b=q-h):(L="above",b=h-F),E=Ne(t,C,b)}c&&W&&(w[f]=h<q?q:F);let X=ke(t,C);A.push({index:f,timestamp:y,value:k,processedValue:h,scored:!0,isAnomaly:W,lower:q,upper:F,center:X,direction:L,severity:E,reason:"ok"})}return A}function Te(n,e){let t=n.seasonalityData;if(!t||t.length===0)return 0;let i=0;for(let r of e){let o=new Set;for(let u of t)o.add(r.map(s=>{var l;return String((l=u==null?void 0:u[s])!=null?l:"")}).join("|"));i=Math.max(i,o.size)}return i}function ie(n,e){var r;if(e.type==="manual_bounds")return e.inputType!=="values"?1:0;if(e.type==="autoreg"){let o=Math.max(1,Math.round((r=e.lags)!=null?r:5)),u=e.windowSize+o;return e.inputType!=="values"&&(u+=1),e.stabilization==="clamp"&&(u+=e.windowSize),u}let t=Math.max(e.minSamples,re[e.type]);if(e.smoothing==="sma"&&(t=Math.max(t,e.smoothingWindow-1)),e.smoothing==="ema"&&(t=Math.max(t,Math.ceil(5/e.smoothingAlpha))),e.inputType!=="values"&&(t=Math.max(t,1)),e.seasonalityComponents!==null&&e.seasonalityComponents.length>0&&Array.isArray(n.seasonalityData)&&n.seasonalityData.length>0){let o=Te(n,e.seasonalityComponents);if(o>0){let u=e.minSamplesPerGroup*o;e.windowSize>=u&&(t=Math.max(t,u))}}return e.stabilization==="clamp"&&(t+=e.windowSize),t}var K=null;function qe(n,e){if(!e||e==="any")return;let t=e==="up"?"above":"below";for(let i of n)i.isAnomaly&&i.direction!==t&&(i.isAnomaly=!1)}function Re(n,e,t){let i=[],r=n.length,o=0;for(;o<r;){if(!(n[o].scored&&n[o].isAnomaly)){o++;continue}let u=o;for(;u+1<r&&n[u+1].scored&&n[u+1].isAnomaly&&n[u+1].timestamp-n[u].timestamp===e;)u++;u-o+1>=t&&i.push({fire:o+t-1,startTs:n[o].timestamp,endTs:n[u].timestamp}),o=u+1}return i}function ze(n,e,t){let i=n.length,r=new Array(i);for(let c=0;c<i;c++)r[c]=n[c].scored&&n[c].isAnomaly;let o=t*e,u=[],s=null,l=-1/0,a=0;for(let c=0;c<i;c++)if(r[c]&&a++,c-e>=0&&r[c-e]&&a--,!(!r[c]||a<o)){if(s&&c-l<=e)s.endTs=n[c].timestamp;else{s&&u.push(s);let w=c;for(let p=Math.max(0,c-e+1);p<=c;p++)if(r[p]){w=p;break}s={fire:c,startTs:n[w].timestamp,endTs:n[c].timestamp}}l=c}return s&&u.push(s),u}function Fe(n,e){let t=new Set(n.map(r=>r.fire)),i=n.slice();for(let r of e)t.has(r.fire)||i.push(r);return i.sort((r,o)=>r.fire-o.fire),i}self.onmessage=n=>{var t,i;let e=n.data;if(e.type==="series"){K=e.series;return}if(e.type==="run"&&K){let r=e.params,o=oe(K,r);qe(o,r.direction);let u=K.intervalSeconds*1e3,s=Re(o,u,r.consecutiveAnomalies),l=(t=e.anomalyWindowPoints)!=null?t:null,a=(i=e.minAnomalyShare)!=null?i:null;l!==null&&a!==null&&l>=2&&a>0&&(s=Fe(s,ze(o,l,a)));let c=s.map(f=>f.fire),w=s.map(f=>[f.startTs,f.endTs]),p=ie(K,r),v=Math.min(p,K.timestamps.length),d=0;for(let f of o)f.scored&&f.isAnomaly&&d++;let A={type:"result",id:e.id,scored:o,fires:c,fireSpans:w,eff:v,need:p,flagged:d};self.postMessage(A)}};})();
185
+ `,series:S,getParams:et,getShare:()=>({windowPoints:ue(),share:ge()}),onDispatch:e=>{var s;Vt=e,J!=null&&G.set(J,e),mt.classList.add("on"),(s=f==null?void 0:f.onState)==null||s.call(f,{params:e,windowPoints:ue(),share:ge()})},onResult:(e,s)=>{mt.classList.remove("on"),ne=e.scored,I=e.fires.map(x=>S.timestamps[x]),ee=e.fireSpans,de=Qe(),q.render({series:S,scored:e.scored,params:s,alerts:de,incidents:D}),kt();let p=e.scored.reduce((x,P)=>x+(P.scored?1:0),0);Bn.textContent=`${e.flagged} flagged \xB7 ${e.fires.length} alert${e.fires.length===1?"":"s"} \xB7 warm-up ${e.need} pts`,$n(s),mn(p,s),Un.textContent=Co(s,Ue,ue(),ge())},onError:()=>{mt.classList.remove("on"),Bn.textContent="recompute failed \u2014 see the browser console"}}),r=o.recompute,c=e=>e>1?Nt(y.timestamps[v-1]-y.timestamps[v-e]):"\u2014",l=e=>{Qt.textContent=e>=v?`${v} pts \xB7 full (${c(v)})`:`${e} pts \xB7 ${c(e)}`};l(v);function d(e){S=g(e),o.postSeries(S),gn(),r()}We.oninput=()=>{l(Number(We.value))},We.onchange=()=>{d(Number(We.value))};let u=()=>{xe(),gn(),r()},h=Ae.filter(e=>e.tunable),M=Ae.filter(e=>!e.tunable);if(Ae.length>1){let e=m("div","dtk-ctl dtk-tune-detpick");if(e.appendChild(Lt("Tuning detector","This metric has several detectors. Pick which one to tune here; every other detector is preserved unchanged when you Apply \u2014 so a manual_bounds floor or a min_detectors\u22652 quorum keeps working.")),h.length>1){let p=m("div","dtk-seg dtk-detpick-seg"),x=[],P=()=>x.forEach(b=>b.classList.toggle("on",Number(b.dataset.v)===J));h.forEach(b=>{let L=m("button","dtk-seg-btn",`#${b.index+1} ${b.type}`);L.type="button",L.dataset.v=String(b.index),L.title=b.summary,L.onclick=()=>{Ho(b.index),P()},x.push(L),p.appendChild(L)}),P(),e.appendChild(p)}let s=[];M.length&&s.push(`Preserved (not tunable here): ${M.map(p=>p.summary).join("; ")}.`),s.push("Apply rewrites only the detector(s) you tune and keeps the rest verbatim."),e.appendChild(m("div","dtk-tune-note",s.join(" "))),pe.appendChild(e)}let E=Rt("Detector",[{label:"MAD",value:"mad"},{label:"Z-Score",value:"zscore"},{label:"IQR",value:"iqr"},{label:"Autoreg",value:"autoreg"},{label:"Manual",value:"manual_bounds"}],C.type,e=>{var s;if(ae((s=Lo[e])!=null?s:3),ce){let p=e;ce.setMin(at(p)),ce.set(De(p))}xe(),Tn(),gn(),r()},"The statistic for the band: MAD (robust median, default), Z-Score (mean/std) or IQR (quartiles) \u2014 all windowed \u2014 Autoreg (predicts each point from its previous values and flags dynamics breaks) or Manual (fixed lower/upper thresholds, no window/history).");pe.appendChild(E.row);let _=je("Lower bound",{min:Ve,max:Oe,step:He,value:Ze,fmt:e=>Kt(e),hint:"Manual bounds: values below this read as anomalous. Drag in from the data range to see how many points fall outside (and how many alerts that yields)."},u);pe.appendChild(_.row);let z=je("Upper bound",{min:Ve,max:Oe,step:He,value:Et,fmt:e=>Kt(e),hint:"Manual bounds: values above this read as anomalous."},u);pe.appendChild(z.row);let H=je("Threshold (\u03C3-equivalent)",{min:.5,max:10,step:.1,value:C.threshold,fmt:e=>e.toFixed(1),hint:"Band half-width in \u03C3-equivalents. Lower = tighter band = more flags; higher = wider band = fewer flags."},u);pe.appendChild(H.row);let Q=H.row.querySelector("input"),Me=H.row.querySelector(".dtk-ctl-val"),ae=e=>{Q&&(Q.value=String(e)),Me&&(Me.textContent=e.toFixed(1))},Ce=e=>Math.max(50,Math.min(2e3,Math.floor(e/2))),T=Math.max(Ce(v),C.windowSize),j=je("Window size (points)",{min:Math.max(1,Math.min(10,C.windowSize)),max:T,step:1,value:C.windowSize,fmt:e=>`${e} \xB7 ${Nt(e*n.interval_seconds*1e3)}`,hint:"How many trailing points form the baseline window for each scored point. Larger = steadier baseline (more history); smaller = adapts faster to shifts."},u);pe.appendChild(j.row);let W=je("Lags (AR order)",{min:1,max:24,step:1,value:Math.max(1,Math.round((mo=C.lags)!=null?mo:5)),fmt:e=>String(e),hint:"Autoreg: how many immediately-preceding values predict the current one. More lags capture longer short-range patterns but need more history per fit."},u);pe.appendChild(W.row);let Z=Rt("Recency weighting",[{label:"none",value:"none"},{label:"exponential",value:"exponential"},{label:"linear",value:"linear"}],C.windowWeights,()=>{xe(),Tn(),r()},"Weight recent points in the window more heavily: none (flat), exponential (half-life decay) or linear. Helps the baseline track a drifting level.");pe.appendChild(Z.row);let we=je("Half-life (points)",{min:1,max:T,step:1,value:(po=C.halfLife)!=null?po:Math.max(5,Math.round(C.windowSize/20)),fmt:e=>`${e} \xB7 ${Nt(e*n.interval_seconds*1e3)}`,hint:"Exponential weighting only: the age (in points) at which a point counts half as much as the newest. Smaller = faster decay = fresher baseline."},u),it=we.row;it.style.display=C.windowWeights==="exponential"?"":"none",pe.appendChild(it);let gn=()=>{var s;let e=Math.max(Ce(S.timestamps.length),C.windowSize,j.get());j.setMax(e),we.setMax(Math.max(e,(s=C.halfLife)!=null?s:0,we.get()))},vn=Rt("Detrend",[{label:"none",value:"none"},{label:"linear",value:"linear"}],C.detrend,u,"Remove a robust linear trend from each window before computing the band, so a steadily rising/falling metric is not flagged for the trend itself.");pe.appendChild(vn.row);let yn=Rt("Stabilization",[{label:"none",value:"none"},{label:"clamp",value:"clamp"}],(fo=C.stabilization)!=null?fo:"none",u,"Anomaly-robust baseline: flagged points enter later windows clamped to the bound they violated, so a long incident cannot inflate the band and mask itself mid-incident.");pe.appendChild(yn.row);let wn=Rt("Smoothing",[{label:"none",value:"none"},{label:"EMA",value:"ema"},{label:"SMA",value:"sma"}],C.smoothing,u,"Smooth the series before detection (EMA or SMA) so single-point jitter does not flag. The detector judges the smoothed line; the raw values show as a faint ghost.");pe.appendChild(wn.row);let Wn=null,eo=()=>{};if(n.seasonality_columns.length){let e=n.seasonality_columns,s=m("div","dtk-ctl");Wn=s,s.appendChild(Lt("Seasonality groups","Condition the band on seasonal keys. Pick a group per column: columns in the SAME group are combined into one key (e.g. dow\xD7hour); separate groups each apply their own correction. Off = ignore that column."));let p=e.length,x=[{label:"\u2014",value:"0"}];for(let b=1;b<=p;b++)x.push({label:`G${b}`,value:String(b)});let P=[];e.forEach(b=>{let L=m("div","dtk-season-row");L.appendChild(m("span","dtk-season-col",b));let Ie=m("div","dtk-seg dtk-season-seg"),ht=[],Ln=()=>{var he;return(he=Pe.get(b))!=null?he:0},Yt=()=>ht.forEach(he=>he.classList.toggle("on",Number(he.dataset.v)===Ln()));P.push(Yt),x.forEach(he=>{let Je=m("button","dtk-seg-btn",he.label);Je.type="button",Je.dataset.v=he.value,Je.title=he.value==="0"?`ignore ${b}`:`put ${b} in group ${he.value}`,Je.onclick=()=>{Pe.set(b,Number(he.value)),Yt(),u()},ht.push(Je),Ie.appendChild(Je)}),Yt(),L.appendChild(Ie),s.appendChild(L)}),pe.appendChild(s),eo=b=>{Pe.clear(),b.forEach((L,Ie)=>L.forEach(ht=>Pe.set(ht,Ie+1))),P.forEach(L=>L())},ce=je("Min samples per group",{min:at(C.type),max:Math.max(50,C.minSamplesPerGroup),step:1,value:Math.max(at(C.type),C.minSamplesPerGroup),fmt:b=>String(b),hint:"Per-seasonal-key minimum: a seasonality group only gets its own band once the window holds this many points sharing the current key \u2014 below it the group falls back to the global band (the seasonality has no effect). Lower it to keep seasonality active on a smaller window; raise it for steadier per-key statistics."},u),pe.appendChild(ce.row)}let to=Rt("Direction",[{label:"both",value:"any"},{label:"up",value:"up"},{label:"down",value:"down"}],(ho=n.direction)!=null?ho:"any",r,"Which anomalies to show and count toward alerts: both directions, only spikes ABOVE the band (up) or only drops BELOW it (down). A preview filter mirroring the alert direction policy \u2014 it never changes the band itself.");ut.appendChild(to.row);let no=je("Alert: consecutive anomalies",{min:1,max:10,step:1,value:Ue,fmt:e=>String(e),hint:"How many anomalies in a row are required before an alert fires. Higher = fewer, more-confident alerts (the \u25BC markers on the chart)."},e=>{Ue=e,r()});ut.appendChild(no.row);let xn=je("Alert: anomaly window (points)",{min:0,max:Math.max(96,re),step:1,value:re,fmt:e=>e>=2?`${e} \xB7 ${Nt(e*n.interval_seconds*1e3)}`:"off",hint:"Fraction rule (OR-ed with the consecutive rule): also fire when at least the share below of the trailing window is anomalous AND the latest point is anomalous. Set to off (< 2) for the classic consecutive-only alert."},e=>{re=e,On(),r()});ut.appendChild(xn.row);let In=je("Alert: min share in window",{min:.05,max:1,step:.05,value:Le,fmt:e=>`${Math.round(e*100)}%`,hint:"Fraction rule: the share of the anomaly window that must be flagged for the alert to fire. Missing points count against the share (an outage never makes it easier)."},e=>{Le=e,r()});ut.appendChild(In.row);let On=()=>{In.row.style.display=re>=2?"":"none"};On();let oo=m("div","dtk-ctl"),kn=m("label","dtk-check"),Sn=m("input");Sn.type="checkbox",Sn.onchange=()=>{q.setZeroLine(Sn.checked)},kn.title="Draw a horizontal line at y = 0 and include zero in the scale \u2014 for real-valued metrics best read relative to zero.",kn.appendChild(Sn),kn.appendChild(document.createTextNode(" Show y = 0 line")),oo.appendChild(kn),ut.appendChild(oo);let Hn=m("div","dtk-ctl dtk-incidents");Hn.appendChild(Lt("Marked incidents","The real incidents you marked (in Label mode). Edit a label, focus to zoom the chart to it, or remove it. Save the set below to incidents/<metric>/ \u2014 the same store dtk autotune reads."));let Mn=m("div","dtk-inc-list");Hn.appendChild(Mn),ct.appendChild(Hn);function zo(e){let s=Math.max((e.end-e.start)*.5,n.interval_seconds*1e3*5);q.setViewWindow(e.start-s,e.end+s)}function Wo(e){let s=D.indexOf(e);s>=0&&D.splice(s,1);let p=oe(e);q.setIncidents(D),p?ye():(Cn(),kt())}function Io(e){w(e.start,e.end,null),q.setIncidents(D),ye()}function Cn(){Mn.innerHTML="";let e=[...D.map(s=>({iv:s,kind:"manual"})),...be().map(s=>({iv:s,kind:"alert"}))].sort((s,p)=>s.iv.start-p.iv.start);if(!e.length){Mn.appendChild(m("div","dtk-inc-empty","None yet \u2014 switch to Label mode and drag across the chart, or confirm alerts in Review mode."));return}for(let{iv:s,kind:p}of e){let x=m("div","dtk-inc-row"+(p==="alert"?" dtk-inc-fromalert":""));if(x.appendChild(m("span","dtk-inc-span",`${Nn(s.start)} \u2192 ${Nn(s.end)}`)),x.appendChild(m("span","dtk-inc-dur",Nt(Math.max(0,s.end-s.start)))),p==="alert"){let L=m("span","dtk-inc-badge","\u2713 confirmed alert");L.title="A fired alert you confirmed valid (in Review mode). It counts as a real incident \u2014 remove it here to un-confirm the alert.",x.appendChild(L)}else{let L=m("input","dtk-inc-label");L.type="text",L.value=s.label||"",L.placeholder="label (optional)",L.oninput=()=>{s.label=L.value},x.appendChild(L)}let P=m("button","dtk-inc-btn","focus");P.type="button",P.onclick=()=>zo(s),x.appendChild(P);let b=m("button","dtk-inc-btn dtk-inc-del","\u2715");b.type="button",b.title=p==="alert"?"un-confirm this alert":"remove this incident",b.onclick=()=>p==="alert"?Io(s):Wo(s),x.appendChild(b),Mn.appendChild(x)}}let Oo=[H.row,j.row,yn.row],Fn=[Z.row,vn.row,wn.row];Wn&&Fn.push(Wn),ce&&Fn.push(ce.row);function Tn(){let e=E.get(),s=e==="manual_bounds",p=e==="autoreg";for(let x of Oo)x.style.display=s?"none":"";for(let x of Fn)x.style.display=s||p?"none":"";W.row.style.display=p?"":"none",_.row.style.display=s?"":"none",z.row.style.display=s?"":"none",it.style.display=!s&&!p&&Z.get()==="exponential"?"":"none"}Tn();function ro(e){var s,p;C=e,E.set(e.type),H.set(e.threshold),gn(),j.set(e.windowSize),Z.set(e.windowWeights),e.windowWeights==="exponential"&&e.halfLife!=null&&we.set(e.halfLife),vn.set(e.detrend),yn.set((s=e.stabilization)!=null?s:"none"),wn.set(e.smoothing),eo(e.seasonalityComponents||[]),ce&&(ce.setMin(at(e.type)),ce.setMax(Math.max(50,e.minSamplesPerGroup,ce.get())),ce.set(Math.max(at(e.type),e.minSamplesPerGroup))),e.lowerBound!=null&&_.set(e.lowerBound),e.upperBound!=null&&z.set(e.upperBound),(e.lags!=null||e.type==="autoreg")&&W.set(Math.max(1,Math.round((p=e.lags)!=null?p:5))),Tn()}function Ho(e){var p;if(e===J)return;let s=Ae.find(x=>x.index===e);!s||!s.tunable||!s.seed||(J!=null&&G.set(J,et()),J=e,ro((p=G.get(e))!=null?p:s.seed),r())}let Bn=m("div","dtk-tune-stat");bt.appendChild(Bn);let jn=m("div","dtk-tune-cfg"),ln=m("button","dtk-tune-cfg-k");ln.type="button",ln.title="Show or hide the exact config that will be written on Apply.";let Un=m("code","dtk-tune-cfg-v"),io=!1,so=e=>{io=e,Un.style.display=e?"":"none",ln.textContent=`${e?"\u25BE":"\u25B8"} // effective config`};if(ln.onclick=()=>so(!io),jn.appendChild(ln),jn.appendChild(Un),so(!1),yt.appendChild(jn),n.save_url){let e=m("div","dtk-tune-apply"),s=m("button","dtk-apply-btn","Apply to metric");s.type="button",s.title="Write this detector config back into the metric YAML (the previous version is archived under metrics/.history/). Trimming the sample does not change what is written.";let p=m("span","dtk-apply-msg");s.onclick=()=>{let x=et();J!=null&&G.set(J,x);let P=[];if(X!=null)for(let b of new Set([X,...V])){let L=G.get(b);L&&P.push({index:b,type:L.type,params:Rn(L)})}else P.push({index:null,type:x.type,params:Rn(x)});s.disabled=!0,p.className="dtk-apply-msg info",p.textContent="Applying\u2026",fetch(n.save_url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({detectors:P,consecutive_anomalies:Ue,anomaly_window:ue()?`${ue()*n.interval_seconds}s`:null,min_anomaly_share:ge()})}).then(b=>b.ok?b.json():b.text().then(L=>{throw new Error(L||`HTTP ${b.status}`)})).then(b=>{var Ie;p.className="dtk-apply-msg ok";let L=b.preserved&&b.preserved.length?` Kept: ${b.preserved.join(", ")}.`:"";p.textContent=`Applied \u2192 ${(Ie=b.saved)!=null?Ie:"metric"} (previous archived).${L} You can close this tab.`}).catch(b=>{s.disabled=!1,p.className="dtk-apply-msg err",p.textContent=`Apply failed: ${b.message}`})},e.appendChild(s),e.appendChild(p),yt.appendChild(e)}else yt.appendChild(m("div","dtk-tune-note","Static preview \u2014 sliders recompute live, but there is no write-back. Run `dtk tune` (without --no-serve) to apply a config."));let Fo=e=>'"'+e.replace(/\\/g,"\\\\").replace(/"/g,'\\"')+'"',Gt=e=>new Date(e).toISOString().slice(0,19).replace("T"," "),ao=()=>{let e=[`metric: ${n.metric}`,"timezone: UTC"],s=new Set,p=$().sort((P,b)=>P.start-b.start).filter(P=>{let b=`${Math.round(P.start)}:${Math.round(P.end)}`;return s.has(b)?!1:(s.add(b),!0)});if(!p.length)e.push("incidents: []");else{e.push("incidents:");for(let P of p){let b=P.label?`, label: ${Fo(P.label)}`:"";e.push(` - {start: "${Gt(P.start)}", end: "${Gt(P.end)}"${b}}`)}}let x=q.getCaptureWindow();if(x&&(e.push("capture_windows:"),e.push(` - {start: "${Gt(x.start)}", end: "${Gt(x.end)}"}`)),Y.length){e.push("alert_reviews:");for(let P of[...Y].sort((b,L)=>b.start-L.start))e.push(` - {start: "${Gt(P.start)}", end: "${Gt(P.end)}", verdict: ${P.verdict}}`)}return e.join(`
186
+ `)+`
187
+ `},An=m("div","dtk-tune-apply"),_n=m("input","dtk-setname");_n.type="text",_n.placeholder="name this set (optional)";let Dn=m("button","dtk-apply-btn dtk-labels-btn",n.labels_save_url?"Save incidents":"Download incidents");Dn.type="button",Dn.title="Write the marked incidents to incidents/<metric>/ (versioned) so they also feed the next `dtk autotune`. Saving labels does not end tuning \u2014 keep adjusting and apply the detector when ready.";let st=m("span","dtk-apply-msg");Dn.onclick=()=>{let e=ao();if(!n.labels_save_url){let s=new Blob([e],{type:"text/yaml"}),p=m("a");p.href=URL.createObjectURL(s),p.download=`${n.metric}.yml`,p.click(),URL.revokeObjectURL(p.href),st.className="dtk-apply-msg ok",st.textContent=`Downloaded \u2014 drop it into incidents/${n.metric}/`;return}st.className="dtk-apply-msg info",st.textContent="Saving\u2026",fetch(n.labels_save_url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({name:_n.value,yaml:e})}).then(s=>s.ok?s.json():s.text().then(p=>{throw new Error(p||`HTTP ${s.status}`)})).then(s=>{var p;st.className="dtk-apply-msg ok",st.textContent=`Saved \u2192 ${(p=s.saved)!=null?p:"incidents"} (keep tuning, or Apply the detector)`}).catch(s=>{st.className="dtk-apply-msg err",st.textContent=`Save failed: ${s.message}`})},An.appendChild(_n),An.appendChild(Dn),An.appendChild(st),ct.appendChild(An);function Bo(e){ro(e.detector),xe(),e.consecutive_anomalies!=null&&(Ue=e.consecutive_anomalies,no.set(Ue)),e.anomaly_window_points!=null&&e.min_anomaly_share!=null?(re=e.anomaly_window_points,Le=e.min_anomaly_share,xn.setMax(Math.max(96,re)),xn.set(re),In.set(Le)):(re=0,xn.set(0)),On(),r()}if(tt.appendChild(m("div","dtk-tune-note","Run the full autotune engine server-side over the window shown (the \u2018Points shown\u2019 trim \u2014 the same series you see and score here), using the incidents you\u2019ve marked (and confirmed alerts) as ground truth. It re-seeds the knobs with the winning detector \u2014 review the band, then Apply (here or in Tune). Nothing is written until you Apply; the next `dtk run` is the source of truth.")),n.autotune_url){let e=m("div","dtk-tune-apply"),s=m("button","dtk-apply-btn","Run autotune");s.type="button",s.title="Search for the best detector over the window shown (the \u2018Points shown\u2019 trim). Uses your marked incidents as ground truth when present (supervised), else an unsupervised objective. Can take a few seconds on a long window.";let p=m("span","dtk-apply-msg");e.appendChild(s),e.appendChild(p),tt.appendChild(e);let x=m("div","dtk-at-result");x.style.display="none",tt.appendChild(x);let P=b=>{x.innerHTML="",x.style.display="";let L=m("div","dtk-at-head");L.appendChild(m("span","dtk-at-winner",b.winner)),L.appendChild(m("span","dtk-at-score",`${b.scoring_metric} ${Number.isFinite(b.score)?b.score.toFixed(3):"\u2014"} \xB7 ${b.mode}`)),x.appendChild(L),x.appendChild(m("div","dtk-at-meta",`${b.n_candidates} candidate${b.n_candidates===1?"":"s"} \xB7 ${b.n_points} pts`+(b.consecutive_anomalies!=null?` \xB7 consecutive ${b.consecutive_anomalies}`:"")+(b.anomaly_window_points!=null&&b.min_anomaly_share!=null?` \xB7 window ${b.anomaly_window_points}p \xD7 ${b.min_anomaly_share}`:"")+(b.seasonality&&b.seasonality.length?` \xB7 seasonality ${JSON.stringify(b.seasonality)}`:" \xB7 no seasonality")));let Ie=m("button","dtk-tune-cfg-k");Ie.type="button";let ht=m("div","dtk-at-log"),Ln=!1,Yt=he=>{Ln=he,ht.style.display=he?"":"none",Ie.textContent=`${he?"\u25BE":"\u25B8"} decision log (${b.decision_log.length})`};Ie.onclick=()=>Yt(!Ln);for(let he of b.decision_log){let Je=m("div","dtk-at-logline");Je.appendChild(m("span","dtk-at-stage",he.stage)),Je.appendChild(m("span","dtk-at-msg",he.message)),ht.appendChild(Je)}Yt(!1),x.appendChild(Ie),x.appendChild(ht)};s.onclick=()=>{s.disabled=!0,p.className="dtk-apply-msg info",p.textContent="Autotuning over the shown window\u2026 this can take a moment.",fetch(n.autotune_url,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({yaml:ao(),window:S.timestamps.length?{start:S.timestamps[0],end:S.timestamps[S.timestamps.length-1]}:null})}).then(b=>b.ok?b.json():b.text().then(L=>{throw new Error(L||`HTTP ${b.status}`)})).then(b=>{s.disabled=!1,Bo(b),P(b);let L=b.mode==="supervised"?" \u2014 supervised by your incidents":" \u2014 unsupervised (mark incidents for a supervised tune)";p.className="dtk-apply-msg ok",p.textContent=`Tuned${L}. Knobs updated; review the band, then Apply.`}).catch(b=>{s.disabled=!1,p.className="dtk-apply-msg err",p.textContent=`Autotune failed: ${b.message}`})}}else tt.appendChild(m("div","dtk-tune-note","Autotune needs the live server \u2014 run `dtk tune` without --no-serve."));hn("tune"),Cn(),o.runNow(),kt();let dn=0,Vn=()=>{dn&&cancelAnimationFrame(dn),dn=requestAnimationFrame(()=>q.resize())},Pn=null;return typeof ResizeObserver!="undefined"?(Pn=new ResizeObserver(Vn),Pn.observe(xt)):window.addEventListener("resize",Vn),{destroy:()=>{o.destroy(),window.removeEventListener("keydown",bn),Pn?Pn.disconnect():window.removeEventListener("resize",Vn),dn&&cancelAnimationFrame(dn),q.destroy()},resize:()=>q.resize()}}window.__DTK_TUNE__={render:Xo};})();
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: detectkit
3
- Version: 0.66.2
3
+ Version: 0.66.3
4
4
  Summary: Metric monitoring with automatic anomaly detection
5
5
  Author: detectkit team
6
6
  License: MIT