@bitcobblers/wod-wiki-lang 0.61.2259 → 0.62.2261

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.
package/dist/index.cjs CHANGED
@@ -283,14 +283,46 @@ var TIME_LIKE_TYPES = /* @__PURE__ */ new Set([
283
283
  function isTimeLikeMetric(type) {
284
284
  return TIME_LIKE_TYPES.has(type);
285
285
  }
286
+ function dedupePresentedLabels(labels) {
287
+ const deduped = [];
288
+ for (const raw of labels) {
289
+ const label = raw.trim();
290
+ if (!label) continue;
291
+ const lower = label.toLowerCase();
292
+ const prev = deduped[deduped.length - 1]?.toLowerCase();
293
+ if (prev && (prev === lower || prev.endsWith(` ${lower}`))) continue;
294
+ deduped.push(label);
295
+ }
296
+ return deduped;
297
+ }
286
298
  function baseText(metric) {
287
299
  if (metric.image) return metric.image;
288
300
  if (metric.value === void 0 || metric.value === null) return metric.type;
301
+ if (metric.value instanceof Date) {
302
+ return metric.value.toISOString();
303
+ }
304
+ if (Array.isArray(metric.value)) {
305
+ const spans = metric.value.filter(
306
+ (item) => Boolean(item) && typeof item === "object" && "started" in item && typeof item.started === "number"
307
+ );
308
+ if (spans.length > 0 && spans.length === metric.value.length) {
309
+ const totalMs = spans.reduce((acc, s) => acc + Math.max(0, (s.ended ?? s.started) - s.started), 0);
310
+ return formatDurationSmart(totalMs);
311
+ }
312
+ return metric.value.map((item) => String(item)).filter(Boolean).join(", ");
313
+ }
289
314
  if (typeof metric.value === "object") {
290
315
  const v = metric.value;
316
+ if ("amount" in v && "units" in v) {
317
+ return v.amount !== void 0 ? `${v.amount} ${v.units}` : String(v.units);
318
+ }
291
319
  if ("text" in v) return String(v.text);
292
320
  if ("current" in v) return `Round ${v.current}`;
293
- return JSON.stringify(metric.value);
321
+ if ("started" in v && typeof v.started === "number") {
322
+ const ended = typeof v.ended === "number" ? v.ended : v.started;
323
+ return formatDurationSmart(Math.max(0, ended - v.started));
324
+ }
325
+ return computeColumnLabel(metric.type);
294
326
  }
295
327
  return String(metric.value);
296
328
  }
@@ -313,6 +345,24 @@ function formatTooltipValue(metric) {
313
345
  return formatDurationSmart(metric.value);
314
346
  }
315
347
  const val = metric.value;
348
+ if (typeof val === "number" && Number.isFinite(val)) {
349
+ const formatted = Number.isInteger(val) ? String(val) : (Math.round(val * 10) / 10).toFixed(1);
350
+ return metric.unit ? `${formatted} ${metric.unit}` : formatted;
351
+ }
352
+ if (val instanceof Date) {
353
+ return val.toISOString();
354
+ }
355
+ if (Array.isArray(val)) {
356
+ if (metric.image) return metric.image;
357
+ const spans = val.filter(
358
+ (item) => Boolean(item) && typeof item === "object" && "started" in item && typeof item.started === "number"
359
+ );
360
+ if (spans.length > 0 && spans.length === val.length) {
361
+ const totalMs = spans.reduce((acc, s) => acc + Math.max(0, (s.ended ?? s.started) - s.started), 0);
362
+ return formatDurationSmart(totalMs);
363
+ }
364
+ return val.map((item) => String(item)).filter(Boolean).join(", ");
365
+ }
316
366
  if (val !== null && typeof val === "object") {
317
367
  if (metric.image) return metric.image;
318
368
  const obj = val;
@@ -321,11 +371,23 @@ function formatTooltipValue(metric) {
321
371
  }
322
372
  if ("text" in obj) return String(obj.text);
323
373
  if ("current" in obj) return `Round ${obj.current}`;
324
- return JSON.stringify(val);
374
+ if ("started" in obj && typeof obj.started === "number") {
375
+ const ended = typeof obj.ended === "number" ? obj.ended : obj.started;
376
+ return formatDurationSmart(Math.max(0, ended - obj.started));
377
+ }
378
+ return computeColumnLabel(metric.type);
379
+ }
380
+ if (metric.image && metric.unit && typeof val === "string" && !val.includes(metric.unit)) {
381
+ return metric.image;
325
382
  }
326
- return String(val);
383
+ return val !== void 0 && val !== null ? String(val) : metric.image ?? computeColumnLabel(metric.type);
327
384
  }
328
- function buildTooltip(metric) {
385
+ function buildTooltip(metric, surface) {
386
+ if (surface && surface !== "debug") {
387
+ const heading2 = computeColumnLabel(metric.type);
388
+ const valText = formatTooltipValue(metric);
389
+ return valText ? `${heading2}: ${valText}` : heading2;
390
+ }
329
391
  const parts = [];
330
392
  parts.push(`Type: ${metric.type}`);
331
393
  if (metric.value !== void 0) parts.push(`Value: ${formatTooltipValue(metric)}`);
@@ -601,6 +663,18 @@ function createPolicy() {
601
663
  const t2 = metric.type;
602
664
  if ((t2 === wodWikiCore.MetricType.Sound || t2 === "sound") && surface !== "debug") return true;
603
665
  if (t2.startsWith(TAG_MARKER_PREFIX) && surface !== "debug") return true;
666
+ if (surface !== "debug") {
667
+ if (t2 === wodWikiCore.MetricType.SystemTime || t2 === "system-time" || t2 === wodWikiCore.MetricType.Spans || t2 === "spans") {
668
+ return true;
669
+ }
670
+ if (t2 === wodWikiCore.MetricType.Equipment || t2 === "equipment") {
671
+ const refMeta = metric.metadata?.[wodWikiCore.REFERENCE_METADATA_KEY];
672
+ const directMatched = metric.metadata?.matched;
673
+ if (metric.origin === "compiler" || refMeta?.matched === "whole" || directMatched === "whole") {
674
+ return true;
675
+ }
676
+ }
677
+ }
604
678
  if (surface === "review-grid-column") {
605
679
  if (t2 === wodWikiCore.MetricType.Elapsed || t2 === "elapsed" || t2 === wodWikiCore.MetricType.Total || t2 === "total") return true;
606
680
  if (t2 === wodWikiCore.MetricType.System || t2 === "system") return true;
@@ -628,7 +702,7 @@ function createPolicy() {
628
702
  return {
629
703
  metric,
630
704
  label: computeLabel(metric),
631
- tooltip: buildTooltip(metric),
705
+ tooltip: buildTooltip(metric, surface),
632
706
  renderKind,
633
707
  tone: computeTone(metric, rest),
634
708
  iconKey: rest ? "rest" : metric.type,
@@ -1669,6 +1743,7 @@ var DurationMetric = class {
1669
1743
  seconds;
1670
1744
  original;
1671
1745
  type = wodWikiCore.MetricType.Duration;
1746
+ unit = "ms";
1672
1747
  /**
1673
1748
  * Determines the intended timer direction based on value and modifiers.
1674
1749
  * - If forceCountUp is true (^ modifier), always returns 'up'
@@ -1891,6 +1966,24 @@ function classifyStatements(facts, references) {
1891
1966
  }
1892
1967
  function equipmentMeta(resolution, authored, meta2) {
1893
1968
  if (resolution.matched !== "split" || !resolution.remaining) return meta2;
1969
+ if (resolution.equipmentSpan) {
1970
+ const leadingTrim = authored.length - authored.trimStart().length;
1971
+ const start = leadingTrim + resolution.equipmentSpan.start;
1972
+ const end = leadingTrim + resolution.equipmentSpan.end;
1973
+ const raw2 = meta2.raw.slice(start, end);
1974
+ const length2 = raw2.length;
1975
+ if (length2 > 0) {
1976
+ return {
1977
+ ...meta2,
1978
+ startOffset: meta2.startOffset + start,
1979
+ endOffset: meta2.startOffset + end,
1980
+ length: length2,
1981
+ columnStart: meta2.columnStart + start,
1982
+ columnEnd: meta2.columnStart + end,
1983
+ raw: raw2
1984
+ };
1985
+ }
1986
+ }
1894
1987
  const prefixEnd = authored.trimEnd().length - resolution.remaining.length;
1895
1988
  if (prefixEnd <= 0) return meta2;
1896
1989
  const raw = meta2.raw.slice(0, prefixEnd).trimEnd();
@@ -1921,7 +2014,7 @@ function applyReferenceResolution(pairs, fact, references) {
1921
2014
  }
1922
2015
  if (resolution.equipment.length > 0) {
1923
2016
  const eqMeta = equipmentMeta(resolution, authored, meta2);
1924
- const eqSource = resolution.matched === "split" ? eqMeta.raw : resolution.matched === "explicit" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
2017
+ const eqSource = resolution.matched === "split" ? eqMeta.raw : resolution.matched === "explicit" || resolution.matched === "whole" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
1925
2018
  result.push({
1926
2019
  metrics: new EquipmentMetric(
1927
2020
  resolution.equipment.map((ref) => ref.slug),
@@ -1929,7 +2022,8 @@ function applyReferenceResolution(pairs, fact, references) {
1929
2022
  refs: resolution.equipment,
1930
2023
  source: eqSource,
1931
2024
  matched: resolution.matched,
1932
- diagnostics: resolution.diagnostics
2025
+ diagnostics: resolution.diagnostics,
2026
+ ...resolution.matched === "whole" ? { origin: "compiler" } : {}
1933
2027
  }
1934
2028
  ),
1935
2029
  meta: eqMeta
@@ -2047,14 +2141,15 @@ function resolveFusedEffortReferences(statements, references) {
2047
2141
  }
2048
2142
  if (resolution.equipment.length > 0) {
2049
2143
  const eqMeta = meta2 ? equipmentMeta(resolution, authored, meta2) : void 0;
2050
- const eqSource = resolution.matched === "split" && eqMeta ? eqMeta.raw : authored;
2144
+ const eqSource = resolution.matched === "split" && eqMeta ? eqMeta.raw : resolution.matched === "whole" || resolution.matched === "explicit" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
2051
2145
  const eqMetric = new EquipmentMetric(
2052
2146
  resolution.equipment.map((ref) => ref.slug),
2053
2147
  {
2054
2148
  refs: resolution.equipment,
2055
2149
  source: eqSource,
2056
2150
  matched: resolution.matched,
2057
- diagnostics: resolution.diagnostics
2151
+ diagnostics: resolution.diagnostics,
2152
+ ...resolution.matched === "whole" ? { origin: "compiler" } : {}
2058
2153
  }
2059
2154
  );
2060
2155
  nextMetrics.push(eqMetric);
@@ -3566,6 +3661,69 @@ tagHighlighter([
3566
3661
  { tag: tags.invalid, class: "tok-invalid" },
3567
3662
  { tag: tags.punctuation, class: "tok-punctuation" }
3568
3663
  ]);
3664
+
3665
+ // src/effort-registry/fuzzyMatch.ts
3666
+ function levenshteinDistance(a, b) {
3667
+ if (a === b) return 0;
3668
+ if (a.length === 0) return b.length;
3669
+ if (b.length === 0) return a.length;
3670
+ if (a.length > b.length) {
3671
+ const tmp = a;
3672
+ a = b;
3673
+ b = tmp;
3674
+ }
3675
+ const m = a.length;
3676
+ const n = b.length;
3677
+ let prev = new Uint32Array(m + 1);
3678
+ let curr = new Uint32Array(m + 1);
3679
+ for (let i = 0; i <= m; i++) {
3680
+ prev[i] = i;
3681
+ }
3682
+ for (let j = 1; j <= n; j++) {
3683
+ curr[0] = j;
3684
+ const bj = b.charCodeAt(j - 1);
3685
+ for (let i = 1; i <= m; i++) {
3686
+ const cost = a.charCodeAt(i - 1) === bj ? 0 : 1;
3687
+ curr[i] = Math.min(
3688
+ prev[i] + 1,
3689
+ // deletion
3690
+ curr[i - 1] + 1,
3691
+ // insertion
3692
+ prev[i - 1] + cost
3693
+ // substitution
3694
+ );
3695
+ }
3696
+ const swap = prev;
3697
+ prev = curr;
3698
+ curr = swap;
3699
+ }
3700
+ return prev[m];
3701
+ }
3702
+ function normalizeForFuzzy(input) {
3703
+ return input.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").replace(/[-_]+/g, " ").trim().replace(/\s+/g, " ");
3704
+ }
3705
+ function isWithinThreshold(a, b, threshold) {
3706
+ const na = normalizeForFuzzy(a);
3707
+ const nb = normalizeForFuzzy(b);
3708
+ if (na === nb) return true;
3709
+ if (Math.abs(na.length - nb.length) > threshold) return false;
3710
+ return levenshteinDistance(na, nb) <= threshold;
3711
+ }
3712
+ function findBestFuzzyMatch(query, candidates, threshold) {
3713
+ const nq = normalizeForFuzzy(query);
3714
+ let best = null;
3715
+ for (const candidate of candidates) {
3716
+ const nc = normalizeForFuzzy(candidate);
3717
+ if (Math.abs(nq.length - nc.length) > threshold) continue;
3718
+ const distance = levenshteinDistance(nq, nc);
3719
+ if (distance > threshold) continue;
3720
+ if (!best || distance < best.distance) {
3721
+ best = { target: candidate, distance };
3722
+ if (distance === 0) break;
3723
+ }
3724
+ }
3725
+ return best;
3726
+ }
3569
3727
  var whiteboardScriptSnippets = [
3570
3728
  {
3571
3729
  name: "emom",
@@ -3668,6 +3826,8 @@ var STRUCTURE_KEYWORD_DISPLAY = {
3668
3826
  "for time": "FOR TIME",
3669
3827
  rest: "Rest"
3670
3828
  };
3829
+ var COUNT_QUALIFIER_WORDS = /^(reps?|rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
3830
+ var ROUNDS_QUALIFIER_WORDS = /^(rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
3671
3831
  var PRIMARY_UNIT_BOOST = {
3672
3832
  kg: 30,
3673
3833
  lb: 29,
@@ -3678,18 +3838,25 @@ var PRIMARY_UNIT_BOOST = {
3678
3838
  ft: 24,
3679
3839
  kcal: 23
3680
3840
  };
3841
+ function clampBoost(value) {
3842
+ return Math.max(-99, Math.min(99, Math.round(value)));
3843
+ }
3681
3844
  function unitCompletions(units, dimension, preferredSet) {
3682
3845
  return units.toArray().filter((def) => !dimension || def.dimension === dimension).flatMap((def) => {
3683
3846
  const canonicalLower = def.canonical.toLowerCase();
3684
3847
  const canonicalBoost = preferredSet?.has(canonicalLower) ? 40 : PRIMARY_UNIT_BOOST[canonicalLower] ?? 20;
3848
+ const canonicalOption = {
3849
+ label: def.canonical,
3850
+ detail: def.dimension,
3851
+ type: "unit",
3852
+ section: COMPLETION_SECTIONS.units,
3853
+ boost: canonicalBoost
3854
+ };
3855
+ if (def.aliases.length > 0) {
3856
+ completionAliases.set(canonicalOption, def.aliases.map((a) => a.toLowerCase()));
3857
+ }
3685
3858
  return [
3686
- {
3687
- label: def.canonical,
3688
- detail: def.dimension,
3689
- type: "unit",
3690
- section: COMPLETION_SECTIONS.units,
3691
- boost: canonicalBoost
3692
- },
3859
+ canonicalOption,
3693
3860
  ...def.aliases.map((alias) => ({
3694
3861
  label: alias,
3695
3862
  detail: def.dimension,
@@ -3700,6 +3867,33 @@ function unitCompletions(units, dimension, preferredSet) {
3700
3867
  ];
3701
3868
  });
3702
3869
  }
3870
+ function makeCountQualifiers(includeRounds, needsLeadingSpace, ladderDetail) {
3871
+ const space = needsLeadingSpace ? " " : "";
3872
+ const items = [
3873
+ {
3874
+ label: "reps",
3875
+ detail: ladderDetail ?? "count",
3876
+ type: "unit",
3877
+ section: COMPLETION_SECTIONS.units,
3878
+ apply: `${space}reps`,
3879
+ boost: ladderDetail ? 45 : 38
3880
+ }
3881
+ ];
3882
+ completionAliases.set(items[0], ["rep"]);
3883
+ if (includeRounds) {
3884
+ const roundsOpt = {
3885
+ label: "rounds",
3886
+ detail: "rounds",
3887
+ type: "unit",
3888
+ section: COMPLETION_SECTIONS.units,
3889
+ apply: `${space}rounds`,
3890
+ boost: 37
3891
+ };
3892
+ completionAliases.set(roundsOpt, ["round", "rd", "rds", "set", "sets"]);
3893
+ items.push(roundsOpt);
3894
+ }
3895
+ return items;
3896
+ }
3703
3897
  function titleCase(word) {
3704
3898
  return word.toLowerCase().replace(/(^|[\s])([a-z])/g, (_, lead, ch) => lead + ch.toUpperCase());
3705
3899
  }
@@ -3771,7 +3965,7 @@ function toCompletions(values, detail, quoteValues = false) {
3771
3965
  detail: value.detail ?? (value.label && value.label !== value.value ? value.value : detail),
3772
3966
  type: completionType,
3773
3967
  info: value.info,
3774
- ...value.boost !== void 0 ? { boost: value.boost } : {},
3968
+ ...value.boost !== void 0 ? { boost: clampBoost(value.boost) } : {},
3775
3969
  ...resolvedSection ? { section: resolvedSection } : {}
3776
3970
  };
3777
3971
  if (value.aliases?.length) {
@@ -3780,8 +3974,228 @@ function toCompletions(values, detail, quoteValues = false) {
3780
3974
  return item;
3781
3975
  });
3782
3976
  }
3783
- function appendCreateEffortOption(pool, typedPhrase, onCreateEffort) {
3784
- if (!onCreateEffort) return pool;
3977
+ function damerauDistance(a, b) {
3978
+ if (a === b) return 0;
3979
+ const m = a.length;
3980
+ const n = b.length;
3981
+ if (m === 0) return n;
3982
+ if (n === 0) return m;
3983
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
3984
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
3985
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
3986
+ for (let i = 1; i <= m; i++) {
3987
+ for (let j = 1; j <= n; j++) {
3988
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
3989
+ let val = Math.min(
3990
+ dp[i - 1][j] + 1,
3991
+ dp[i][j - 1] + 1,
3992
+ dp[i - 1][j - 1] + cost
3993
+ );
3994
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
3995
+ val = Math.min(val, dp[i - 2][j - 2] + 1);
3996
+ }
3997
+ dp[i][j] = val;
3998
+ }
3999
+ }
4000
+ return dp[m][n];
4001
+ }
4002
+ function isOrderedSubsequence(needle, haystack) {
4003
+ if (needle.length < 3 || haystack.length > 28) return false;
4004
+ if (needle[0] !== haystack[0]) return false;
4005
+ let i = 0;
4006
+ for (let j = 0; j < haystack.length && i < needle.length; j++) {
4007
+ if (needle[i] === haystack[j]) i++;
4008
+ }
4009
+ return i === needle.length;
4010
+ }
4011
+ function dedupeStrings(values) {
4012
+ const seen = /* @__PURE__ */ new Set();
4013
+ const out = [];
4014
+ for (const v of values) {
4015
+ if (!v || seen.has(v)) continue;
4016
+ seen.add(v);
4017
+ out.push(v);
4018
+ }
4019
+ return out;
4020
+ }
4021
+ function buildCatalogIndex(rawEfforts, rawEquipment) {
4022
+ const eqCompletions = toCompletions(rawEquipment, "equipment");
4023
+ const eqTermsBySlug = /* @__PURE__ */ new Map();
4024
+ const equipmentLabelBySlug = /* @__PURE__ */ new Map();
4025
+ const equipment = rawEquipment.map((opt, idx) => {
4026
+ const label = opt.label ?? opt.value;
4027
+ const rawTerms = [label, opt.value, ...opt.aliases ?? []];
4028
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
4029
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
4030
+ const slugLower = opt.value.toLowerCase();
4031
+ eqTermsBySlug.set(slugLower, dedupeStrings([...terms, ...words]));
4032
+ equipmentLabelBySlug.set(slugLower, label);
4033
+ const base = eqCompletions[idx];
4034
+ return {
4035
+ kind: "equipment",
4036
+ option: opt,
4037
+ label,
4038
+ labelLower: label.toLowerCase(),
4039
+ terms,
4040
+ words,
4041
+ equipmentSlugs: [slugLower],
4042
+ equipmentTerms: [],
4043
+ completion: {
4044
+ ...base,
4045
+ section: resolveSection(opt.section) ?? COMPLETION_SECTIONS.equipment
4046
+ }
4047
+ };
4048
+ });
4049
+ const effortCompletions = toCompletions(rawEfforts, "effort");
4050
+ const efforts = rawEfforts.map((opt, idx) => {
4051
+ const label = opt.label ?? opt.value;
4052
+ const rawTerms = [label, opt.value, ...opt.aliases ?? []];
4053
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
4054
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
4055
+ const equipmentSlugs = (opt.equipment ?? []).map((s) => s.toLowerCase());
4056
+ const equipmentTerms = dedupeStrings(
4057
+ equipmentSlugs.flatMap((slug) => eqTermsBySlug.get(slug) ?? [normalizeForFuzzy(slug)])
4058
+ );
4059
+ return {
4060
+ kind: "effort",
4061
+ option: opt,
4062
+ label,
4063
+ labelLower: label.toLowerCase(),
4064
+ terms,
4065
+ words,
4066
+ equipmentSlugs,
4067
+ equipmentTerms,
4068
+ completion: effortCompletions[idx]
4069
+ };
4070
+ });
4071
+ return { efforts, equipment, equipmentLabelBySlug };
4072
+ }
4073
+ function bestTokenScore(qTok, entry) {
4074
+ let best = 0;
4075
+ for (const term of entry.terms) {
4076
+ if (term === qTok) return 100;
4077
+ if (term.startsWith(qTok)) best = Math.max(best, 86);
4078
+ else if (qTok.length >= 2 && term.includes(qTok)) best = Math.max(best, 58);
4079
+ else if (isOrderedSubsequence(qTok, term)) best = Math.max(best, 32);
4080
+ }
4081
+ for (const word of entry.words) {
4082
+ if (word === qTok) best = Math.max(best, 95);
4083
+ else if (word.startsWith(qTok)) best = Math.max(best, 82);
4084
+ else if (qTok.length >= 2 && word.includes(qTok)) best = Math.max(best, 55);
4085
+ else if (qTok.length >= 3) {
4086
+ const maxDist = qTok.length <= 4 ? 1 : 2;
4087
+ if (Math.abs(word.length - qTok.length) <= maxDist) {
4088
+ const dist = damerauDistance(qTok, word);
4089
+ if (dist <= maxDist) best = Math.max(best, 46 - dist * 10);
4090
+ } else if (qTok.length >= 4 && word.length > qTok.length) {
4091
+ const prefix = word.slice(0, qTok.length);
4092
+ const dist = damerauDistance(qTok, prefix);
4093
+ if (dist <= 1) best = Math.max(best, 38);
4094
+ }
4095
+ if (isOrderedSubsequence(qTok, word)) best = Math.max(best, 30);
4096
+ }
4097
+ }
4098
+ for (const eqTerm of entry.equipmentTerms) {
4099
+ if (eqTerm === qTok) best = Math.max(best, 76);
4100
+ else if (qTok.length >= 2 && eqTerm.startsWith(qTok)) best = Math.max(best, 66);
4101
+ else if (qTok.length >= 4 && Math.abs(eqTerm.length - qTok.length) <= 1) {
4102
+ if (damerauDistance(qTok, eqTerm) <= 1) best = Math.max(best, 34);
4103
+ }
4104
+ }
4105
+ return best;
4106
+ }
4107
+ function scoreCatalogEntry(query, entry) {
4108
+ const normQuery = normalizeForFuzzy(query);
4109
+ if (!normQuery) return 1;
4110
+ const qTokens = normQuery.split(" ").filter(Boolean);
4111
+ if (qTokens.length === 0) return 1;
4112
+ let wholeBonus = 0;
4113
+ for (const term of entry.terms) {
4114
+ if (term === normQuery) {
4115
+ wholeBonus = Math.max(wholeBonus, 140);
4116
+ } else if (term.startsWith(normQuery)) {
4117
+ wholeBonus = Math.max(wholeBonus, 115);
4118
+ } else if (normQuery.length >= 2 && term.includes(normQuery)) {
4119
+ wholeBonus = Math.max(wholeBonus, 80);
4120
+ }
4121
+ }
4122
+ let tokenSum = 0;
4123
+ for (const qTok of qTokens) {
4124
+ const tokenScore = bestTokenScore(qTok, entry);
4125
+ if (tokenScore === 0) return null;
4126
+ tokenSum += tokenScore;
4127
+ }
4128
+ const labelWordCount = normalizeForFuzzy(entry.label).split(" ").filter(Boolean).length;
4129
+ const extraWordPenalty = Math.max(0, labelWordCount - qTokens.length) * 3;
4130
+ return wholeBonus + Math.round(tokenSum / qTokens.length) - extraWordPenalty + (entry.option.boost ?? 0);
4131
+ }
4132
+ function scoreCompletionOption(query, option) {
4133
+ const normQuery = normalizeForFuzzy(query);
4134
+ if (!normQuery) return 1;
4135
+ const qTokens = normQuery.split(" ").filter(Boolean);
4136
+ if (qTokens.length === 0) return 1;
4137
+ const aliases = completionAliases.get(option) ?? [];
4138
+ const rawTerms = [
4139
+ option.label,
4140
+ typeof option.apply === "string" ? option.apply : "",
4141
+ ...aliases
4142
+ ].filter(Boolean);
4143
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
4144
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
4145
+ let wholeBonus = 0;
4146
+ for (const term of terms) {
4147
+ if (term === normQuery) wholeBonus = Math.max(wholeBonus, 130);
4148
+ else if (term.startsWith(normQuery)) wholeBonus = Math.max(wholeBonus, 105);
4149
+ else if (normQuery.length >= 2 && term.includes(normQuery)) wholeBonus = Math.max(wholeBonus, 70);
4150
+ }
4151
+ let tokenSum = 0;
4152
+ for (const qTok of qTokens) {
4153
+ let best = 0;
4154
+ for (const term of terms) {
4155
+ if (term === qTok) best = Math.max(best, 100);
4156
+ else if (term.startsWith(qTok)) best = Math.max(best, 85);
4157
+ else if (qTok.length >= 2 && term.includes(qTok)) best = Math.max(best, 55);
4158
+ }
4159
+ for (const word of words) {
4160
+ if (word === qTok) best = Math.max(best, 95);
4161
+ else if (word.startsWith(qTok)) best = Math.max(best, 80);
4162
+ else if (qTok.length >= 3) {
4163
+ const maxDist = qTok.length <= 4 ? 1 : 2;
4164
+ if (Math.abs(word.length - qTok.length) <= maxDist) {
4165
+ const dist = damerauDistance(qTok, word);
4166
+ if (dist <= maxDist) best = Math.max(best, 44 - dist * 10);
4167
+ }
4168
+ }
4169
+ }
4170
+ if (best === 0) return null;
4171
+ tokenSum += best;
4172
+ }
4173
+ return wholeBonus + Math.round(tokenSum / qTokens.length) + (option.boost ?? 0);
4174
+ }
4175
+ function findExactEntry(phrase, entries) {
4176
+ const norm = normalizeForFuzzy(phrase);
4177
+ if (!norm) return void 0;
4178
+ return entries.find((entry) => entry.terms.includes(norm));
4179
+ }
4180
+ function isExactAliasOrTermSplit(phrase, index) {
4181
+ const norm = normalizeForFuzzy(phrase);
4182
+ if (!norm) return false;
4183
+ if (index.efforts.some((e) => e.terms.includes(norm))) return true;
4184
+ const words = norm.split(" ").filter(Boolean);
4185
+ for (let k = 1; k < words.length; k++) {
4186
+ const left = words.slice(0, k).join(" ");
4187
+ const right = words.slice(k).join(" ");
4188
+ const effortLeft = index.efforts.some((e) => e.terms.includes(left));
4189
+ const eqRight = index.equipment.some((e) => e.terms.includes(right));
4190
+ if (effortLeft && eqRight) return true;
4191
+ const eqLeft = index.equipment.some((e) => e.terms.includes(left));
4192
+ const effortRight = index.efforts.some((e) => e.terms.includes(right));
4193
+ if (eqLeft && effortRight) return true;
4194
+ }
4195
+ return false;
4196
+ }
4197
+ function appendCreateEffortOption(pool, typedPhrase, onCreateEffort, suppressCreate = false) {
4198
+ if (!onCreateEffort || suppressCreate) return pool;
3785
4199
  const trimmed = typedPhrase.trim();
3786
4200
  if (trimmed.length < 3 || !/^[A-Za-z][A-Za-z0-9 -]*$/.test(trimmed)) return pool;
3787
4201
  const lower = trimmed.toLowerCase();
@@ -3853,8 +4267,10 @@ function suppliedPropertyKeys(context) {
3853
4267
  }
3854
4268
  return keys;
3855
4269
  }
3856
- function isUnitFragment(context, fragment, units) {
3857
- return fragment.firstChild?.name === "Effort" && units.has(context.state.doc.sliceString(fragment.from, fragment.to));
4270
+ function isUnitOrQualifierFragment(context, fragment, units) {
4271
+ if (fragment.firstChild?.name !== "Effort") return false;
4272
+ const raw = context.state.doc.sliceString(fragment.from, fragment.to).trim();
4273
+ return units.has(raw) || COUNT_QUALIFIER_WORDS.test(raw);
3858
4274
  }
3859
4275
  function trailingEffortRun(context, statement, units) {
3860
4276
  const nodes = statement?.name === "Block" ? statement.getChildren("Fragment") : [];
@@ -3864,9 +4280,154 @@ function trailingEffortRun(context, statement, units) {
3864
4280
  while (start > 0 && nodes[start - 1].firstChild?.name === "Effort") start--;
3865
4281
  const run = nodes.slice(start, end);
3866
4282
  let firstEffort = 0;
3867
- while (firstEffort < run.length - 1 && isUnitFragment(context, run[firstEffort], units)) firstEffort++;
4283
+ while (firstEffort < run.length && isUnitOrQualifierFragment(context, run[firstEffort], units)) firstEffort++;
3868
4284
  return run.slice(firstEffort);
3869
4285
  }
4286
+ function detectRepLadder(context, nodes, qtyIdx) {
4287
+ if (qtyIdx < 2 || nodes[qtyIdx]?.firstChild?.name !== "Quantity") {
4288
+ return { isLadder: false, rungCount: 1 };
4289
+ }
4290
+ const qtyText = context.state.doc.sliceString(nodes[qtyIdx].from, nodes[qtyIdx].to);
4291
+ if (!/^\d+$/.test(qtyText)) return { isLadder: false, rungCount: 1 };
4292
+ let rungCount = 1;
4293
+ let j = qtyIdx;
4294
+ while (j >= 2 && nodes[j - 1].firstChild?.name === "Effort" && context.state.doc.sliceString(nodes[j - 1].from, nodes[j - 1].to) === "-" && nodes[j].from === nodes[j - 1].to && nodes[j - 2].firstChild?.name === "Quantity" && nodes[j - 1].from === nodes[j - 2].to && /^\d+$/.test(context.state.doc.sliceString(nodes[j - 2].from, nodes[j - 2].to))) {
4295
+ rungCount++;
4296
+ j -= 2;
4297
+ }
4298
+ return { isLadder: rungCount >= 2, rungCount };
4299
+ }
4300
+ function analyzeStatementBefore(context, nodes, uptoEnd, index, units) {
4301
+ let hasRounds = false;
4302
+ let hasEffort = false;
4303
+ let hasEquipment = false;
4304
+ const wordChunks = [];
4305
+ for (let i = 0; i < uptoEnd; i++) {
4306
+ const frag = nodes[i];
4307
+ const kind = frag.firstChild?.name;
4308
+ if (kind === "Rounds" || kind === "RoundScheme") {
4309
+ hasRounds = true;
4310
+ continue;
4311
+ }
4312
+ if (kind === "Quantity") {
4313
+ if (detectRepLadder(context, nodes, i).isLadder) hasRounds = true;
4314
+ continue;
4315
+ }
4316
+ if (kind === "Effort") {
4317
+ const raw = context.state.doc.sliceString(frag.from, frag.to).trim();
4318
+ if (raw === "-" || raw === "/" || raw === "|") continue;
4319
+ if (ROUNDS_QUALIFIER_WORDS.test(raw)) {
4320
+ hasRounds = true;
4321
+ continue;
4322
+ }
4323
+ if (COUNT_QUALIFIER_WORDS.test(raw) || units.has(raw)) continue;
4324
+ wordChunks.push(raw);
4325
+ }
4326
+ }
4327
+ if (wordChunks.length > 0) {
4328
+ const phrase = wordChunks.join(" ");
4329
+ const norm = normalizeForFuzzy(phrase);
4330
+ const exactEq = findExactEntry(phrase, index.equipment);
4331
+ const exactEff = findExactEntry(phrase, index.efforts);
4332
+ if (exactEq && !exactEff) {
4333
+ hasEquipment = true;
4334
+ } else if (exactEff) {
4335
+ hasEffort = true;
4336
+ const eqWords = exactEff.equipmentSlugs.some((slug) => {
4337
+ const label = index.equipmentLabelBySlug.get(slug);
4338
+ return label ? norm.includes(normalizeForFuzzy(label)) : false;
4339
+ });
4340
+ if (eqWords) hasEquipment = true;
4341
+ } else if (isExactAliasOrTermSplit(phrase, index)) {
4342
+ hasEffort = true;
4343
+ hasEquipment = true;
4344
+ } else {
4345
+ hasEffort = true;
4346
+ }
4347
+ }
4348
+ return { hasRounds, hasEffort, hasEquipment };
4349
+ }
4350
+ function phraseHasExplicitEquipment(phrase, index) {
4351
+ const norm = normalizeForFuzzy(phrase);
4352
+ if (!norm) return false;
4353
+ const words = norm.split(" ").filter(Boolean);
4354
+ for (let k = 1; k < words.length; k++) {
4355
+ const left = words.slice(0, k).join(" ");
4356
+ const right = words.slice(k).join(" ");
4357
+ if (index.efforts.some((e) => e.terms.includes(left)) && index.equipment.some((e) => e.terms.includes(right))) {
4358
+ return true;
4359
+ }
4360
+ if (index.equipment.some((e) => e.terms.includes(left)) && index.efforts.some((e) => e.terms.includes(right))) {
4361
+ return true;
4362
+ }
4363
+ }
4364
+ const exactEq = findExactEntry(phrase, index.equipment);
4365
+ if (!exactEq) {
4366
+ for (let k = 1; k < words.length; k++) {
4367
+ const left = words.slice(0, k).join(" ");
4368
+ const right = words.slice(k).join(" ");
4369
+ if (index.equipment.some((e) => e.terms.includes(right)) && !index.equipment.some((e) => e.terms.includes(left))) {
4370
+ return true;
4371
+ }
4372
+ }
4373
+ }
4374
+ const exactEff = findExactEntry(phrase, index.efforts);
4375
+ if (!exactEff) return false;
4376
+ return exactEff.equipmentSlugs.some((slug) => {
4377
+ const label = index.equipmentLabelBySlug.get(slug);
4378
+ if (label && norm.includes(normalizeForFuzzy(label))) return true;
4379
+ const eqEntry = index.equipment.find((eq) => eq.equipmentSlugs[0] === slug);
4380
+ return eqEntry ? eqEntry.terms.some((t2) => t2.length >= 2 && words.includes(t2)) : false;
4381
+ });
4382
+ }
4383
+ function specializedEffortsForBase(phrase, index) {
4384
+ const normBase = normalizeForFuzzy(phrase);
4385
+ const baseWords = normBase.split(" ").filter(Boolean);
4386
+ if (baseWords.length === 0) return [];
4387
+ const exactCurrent = findExactEntry(phrase, index.efforts);
4388
+ const results = [];
4389
+ for (const entry of index.efforts) {
4390
+ if (entry.labelLower === phrase.toLowerCase()) continue;
4391
+ if (exactCurrent && entry.labelLower === exactCurrent.labelLower) continue;
4392
+ const matchesAllWords = baseWords.every((w) => entry.words.includes(w) || entry.terms.some((t2) => t2.includes(w)));
4393
+ if (!matchesAllWords) continue;
4394
+ const eqNames = entry.equipmentSlugs.map((slug) => index.equipmentLabelBySlug.get(slug)).filter((name2) => Boolean(name2));
4395
+ const detail = eqNames.length > 0 ? `${entry.completion.detail ?? "effort"} \xB7 ${eqNames.join(", ")}` : entry.completion.detail;
4396
+ results.push({
4397
+ ...entry.completion,
4398
+ detail,
4399
+ boost: clampBoost((entry.option.boost ?? 0) + 18),
4400
+ apply: (view, _completion, from, to) => {
4401
+ view.dispatch({
4402
+ changes: { from, to, insert: entry.label },
4403
+ selection: { anchor: from + entry.label.length },
4404
+ userEvent: "input.complete"
4405
+ });
4406
+ }
4407
+ });
4408
+ }
4409
+ return results;
4410
+ }
4411
+ function specializedEffortsForEquipment(eqEntry, index) {
4412
+ const eqSlug = eqEntry.equipmentSlugs[0];
4413
+ const results = [];
4414
+ for (const entry of index.efforts) {
4415
+ const usesEq = entry.equipmentSlugs.includes(eqSlug) || eqEntry.terms.some((t2) => t2.length >= 2 && entry.words.includes(t2));
4416
+ if (!usesEq) continue;
4417
+ results.push({
4418
+ ...entry.completion,
4419
+ boost: clampBoost((entry.option.boost ?? 0) + 20),
4420
+ apply: (view, _completion, from, to) => {
4421
+ view.dispatch({
4422
+ changes: { from, to, insert: entry.label },
4423
+ selection: { anchor: from + entry.label.length },
4424
+ userEvent: "input.complete"
4425
+ });
4426
+ }
4427
+ });
4428
+ }
4429
+ return results;
4430
+ }
3870
4431
  function inNode(context, names) {
3871
4432
  for (let node = language.syntaxTree(context.state).resolveInner(context.pos, -1); node; node = node.parent) {
3872
4433
  if (names.has(node.name)) return true;
@@ -3875,6 +4436,56 @@ function inNode(context, names) {
3875
4436
  }
3876
4437
  var ALWAYS_SUPPRESSED_NODES = /* @__PURE__ */ new Set(["Text", "textComment", "MetricObject"]);
3877
4438
  var HEADING_NODES = /* @__PURE__ */ new Set(["Heading", "heading"]);
4439
+ function completeParenthesizedRounds(before, pos) {
4440
+ if (!/\([^)\n]*$/.test(before)) return void 0;
4441
+ const openIdx = before.lastIndexOf("(");
4442
+ const inner = before.slice(openIdx + 1);
4443
+ if (inner.includes("-")) return null;
4444
+ const m = /^(\s*)(\d+)([ \t]*)([A-Za-z]*)$/.exec(inner);
4445
+ if (!m) return null;
4446
+ const hasSpace = m[3].length > 0;
4447
+ const typedWord = m[4];
4448
+ const lead = hasSpace ? "" : " ";
4449
+ const wordFrom = pos - typedWord.length;
4450
+ const makeParenApply = (word) => (view, _c, from, to) => {
4451
+ const hasClose = view.state.doc.sliceString(to, to + 1) === ")";
4452
+ const insert = `${lead}${word}${hasClose ? "" : ")"}`;
4453
+ view.dispatch({
4454
+ changes: { from, to, insert },
4455
+ selection: { anchor: from + insert.length + (hasClose ? 1 : 0) },
4456
+ userEvent: "input.complete"
4457
+ });
4458
+ };
4459
+ const options = [
4460
+ {
4461
+ label: "rounds",
4462
+ detail: "rounds",
4463
+ type: "unit",
4464
+ section: COMPLETION_SECTIONS.units,
4465
+ boost: 45,
4466
+ apply: makeParenApply("rounds")
4467
+ },
4468
+ {
4469
+ label: "reps",
4470
+ detail: "count",
4471
+ type: "unit",
4472
+ section: COMPLETION_SECTIONS.units,
4473
+ boost: 40,
4474
+ apply: makeParenApply("reps")
4475
+ }
4476
+ ];
4477
+ completionAliases.set(options[0], ["round", "rd", "rds", "set", "sets"]);
4478
+ completionAliases.set(options[1], ["rep"]);
4479
+ if (typedWord.length > 0) {
4480
+ const scored = options.map((opt) => ({ opt, score: scoreCompletionOption(typedWord, opt) })).filter((x) => x.score !== null).sort((a, b) => b.score - a.score).map((x) => x.opt);
4481
+ return scored.length > 0 ? { from: wordFrom, options: scored, filter: false } : null;
4482
+ }
4483
+ return {
4484
+ from: wordFrom,
4485
+ options,
4486
+ validFor: /^[A-Za-z]*$/
4487
+ };
4488
+ }
3878
4489
  function whiteboardScriptCompletionSource(options = {}) {
3879
4490
  const sportWords = dialectWords(options.sport);
3880
4491
  const keywords = structureKeywords();
@@ -3924,6 +4535,21 @@ function whiteboardScriptCompletionSource(options = {}) {
3924
4535
  });
3925
4536
  }
3926
4537
  }
4538
+ const restTag = /^[A-Za-z0-9-]*/.exec(line.text.slice(pos - line.from))[0];
4539
+ if (restTag.length > 0) {
4540
+ const lower = word.toLowerCase();
4541
+ const filteredTags = tagOptions.filter((opt) => {
4542
+ if (opt.type === "create") return true;
4543
+ const applyLower = typeof opt.apply === "string" ? opt.apply.toLowerCase() : "";
4544
+ return opt.label.toLowerCase().includes(lower) || applyLower.includes(lower);
4545
+ });
4546
+ return filteredTags.length > 0 ? {
4547
+ from: pos - word.length,
4548
+ to: pos + restTag.length,
4549
+ options: filteredTags,
4550
+ filter: false
4551
+ } : null;
4552
+ }
3927
4553
  return {
3928
4554
  from: pos - word.length,
3929
4555
  options: tagOptions,
@@ -3931,6 +4557,8 @@ function whiteboardScriptCompletionSource(options = {}) {
3931
4557
  };
3932
4558
  }
3933
4559
  if (inNode(context, HEADING_NODES)) return null;
4560
+ const parenResult = completeParenthesizedRounds(before, pos);
4561
+ if (parenResult !== void 0) return parenResult;
3934
4562
  const statement = currentStatement(context);
3935
4563
  if (statement?.name === "Property") {
3936
4564
  const keyNode = statement.firstChild;
@@ -3942,17 +4570,12 @@ function whiteboardScriptCompletionSource(options = {}) {
3942
4570
  if (source) return { from: value && !value.type.isError ? value.from : pos, options: toCompletions(await source(), key, true) };
3943
4571
  return null;
3944
4572
  }
3945
- const efforts = options.efforts ? toCompletions(await options.efforts(), "effort") : [];
3946
- const equipmentPrefixes = options.equipment ? (await options.equipment()).map((eq) => ({
3947
- label: eq.label ?? eq.value,
3948
- apply: `${eq.label ?? eq.value} `,
3949
- detail: eq.detail ?? "equipment",
3950
- type: "text",
3951
- section: resolveSection(eq.section) ?? COMPLETION_SECTIONS.equipment,
3952
- ...eq.boost !== void 0 ? { boost: eq.boost } : {}
3953
- })) : [];
3954
- const postQuantityEffortOptions = [...efforts, ...equipmentPrefixes, ...sportWords];
3955
- const effortOptions = [...keywords, ...efforts, ...equipmentPrefixes, ...sportWords];
4573
+ const rawEfforts = options.efforts ? await options.efforts() : [];
4574
+ const rawEquipment = options.equipment ? await options.equipment() : [];
4575
+ const catalog = buildCatalogIndex(rawEfforts, rawEquipment);
4576
+ const efforts = catalog.efforts.map((e) => e.completion);
4577
+ const equipmentOpts = catalog.equipment.map((e) => e.completion);
4578
+ const missingLineElements = [...efforts, ...equipmentOpts, ...sportWords];
3956
4579
  if (/^[ \t]*[A-Za-z][A-Za-z0-9]*$/.test(before)) {
3957
4580
  const supplied = suppliedPropertyKeys(context);
3958
4581
  const propertyOptions = COMPLETION_PROPERTY_KEYS.filter((key) => !supplied.has(key)).map((key) => ({
@@ -3967,24 +4590,38 @@ function whiteboardScriptCompletionSource(options = {}) {
3967
4590
  ...snippets,
3968
4591
  ...startKeywords,
3969
4592
  ...efforts,
4593
+ ...equipmentOpts,
3970
4594
  ...sportWords,
3971
4595
  ...propertyOptions
3972
4596
  ];
3973
4597
  const typedRaw = before.trimStart();
3974
4598
  const typedStart = typedRaw.toLowerCase();
3975
- const hasAliasHit = typedStart.length >= 2 && effortOptions.some((opt) => completionMatchesWord(opt, typedStart) === "alias");
3976
- if (hasAliasHit) {
3977
- const matched = allStartOptions.filter((opt) => completionMatchesWord(opt, typedStart) !== null);
4599
+ const hasSubstringOrPrefix = allStartOptions.some((opt) => {
4600
+ const m = completionMatchesWord(opt, typedStart);
4601
+ return m === "prefix" || m === "word";
4602
+ });
4603
+ const fuzzyEfforts = catalog.efforts.map((e) => ({ opt: e.completion, score: scoreCatalogEntry(typedRaw, e) })).filter((x) => x.score !== null).sort((a, b) => b.score - a.score);
4604
+ const fuzzyEquipment = catalog.equipment.map((e) => ({ opt: e.completion, score: scoreCatalogEntry(typedRaw, e) })).filter((x) => x.score !== null).sort((a, b) => b.score - a.score);
4605
+ const restWord = /^[A-Za-z0-9-]*/.exec(line.text.slice(pos - line.from))[0];
4606
+ const hasAliasOrFuzzyOnly = (fuzzyEfforts.length > 0 || fuzzyEquipment.length > 0) && (!hasSubstringOrPrefix || typedStart.length >= 2 && fuzzyEfforts.some((e) => completionMatchesWord(e.opt, typedStart) === "alias"));
4607
+ if (hasAliasOrFuzzyOnly || restWord.length > 0) {
4608
+ const otherMatched = [...snippets, ...startKeywords, ...sportWords, ...propertyOptions].filter((opt) => scoreCompletionOption(typedRaw, opt) !== null);
4609
+ const matched = [
4610
+ ...otherMatched,
4611
+ ...fuzzyEfforts.map((x) => x.opt),
4612
+ ...fuzzyEquipment.map((x) => x.opt)
4613
+ ];
4614
+ const suppressCreate = isExactAliasOrTermSplit(typedRaw, catalog);
3978
4615
  return {
3979
4616
  from: pos - typedRaw.length,
3980
- options: appendCreateEffortOption(matched, typedRaw, options.onCreateEffort),
3981
- filter: false,
3982
- validFor: /^[A-Za-z]*$/
4617
+ ...restWord.length > 0 ? { to: pos + restWord.length } : {},
4618
+ options: appendCreateEffortOption(matched, typedRaw, options.onCreateEffort, suppressCreate),
4619
+ filter: false
3983
4620
  };
3984
4621
  }
3985
4622
  return {
3986
4623
  from: pos - typedRaw.length,
3987
- options: appendCreateEffortOption(allStartOptions, typedRaw, options.onCreateEffort),
4624
+ options: appendCreateEffortOption(allStartOptions, typedRaw, options.onCreateEffort, isExactAliasOrTermSplit(typedRaw, catalog)),
3988
4625
  validFor: /^[A-Za-z]*$/
3989
4626
  };
3990
4627
  }
@@ -3992,71 +4629,340 @@ function whiteboardScriptCompletionSource(options = {}) {
3992
4629
  let end = nodes.length;
3993
4630
  while (end > 0 && nodes[end - 1].from >= pos) end--;
3994
4631
  const last = nodes[end - 1];
3995
- const completingWord = last?.firstChild?.name === "Effort" && last.to === pos;
3996
- const quantityFragment = completingWord ? nodes[end - 2] : last;
4632
+ const completingWord = last?.firstChild?.name === "Effort" && last.from < pos && pos <= last.to;
4633
+ const qtyIdx = completingWord ? end - 2 : end - 1;
4634
+ const quantityFragment = qtyIdx >= 0 ? nodes[qtyIdx] : void 0;
3997
4635
  const quantity = quantityFragment?.firstChild?.name === "Quantity" ? quantityFragment.firstChild : null;
3998
4636
  const incompleteAction = statement?.name === "Block" && statement.getChildren("Fragment").some(
3999
4637
  (fragment) => fragment.firstChild?.name === "Action" && fragment.from < (quantity?.from ?? pos) && !context.state.doc.sliceString(fragment.from, fragment.to).includes(":")
4000
4638
  );
4001
4639
  if (quantity && !incompleteAction) {
4640
+ const hasAtSign = Boolean(quantity.getChild("AtSign"));
4641
+ const rawQty = context.state.doc.sliceString(quantity.from, quantity.to);
4642
+ const isWholeInteger = !hasAtSign && /^\d+$/.test(rawQty);
4643
+ const isWildcard = !hasAtSign && rawQty === "?";
4644
+ const isGlued = completingWord ? last.from === quantityFragment.to : pos === quantityFragment.to;
4645
+ const hasTrailingSpace = !completingWord && pos > quantityFragment.to && /[ \t]$/.test(before);
4646
+ const ladder = !hasAtSign ? detectRepLadder(context, nodes, qtyIdx) : { isLadder: false, rungCount: 1 };
4647
+ const prefixLine = analyzeStatementBefore(context, nodes, qtyIdx, catalog, units);
4002
4648
  const preferredSet = new Set(
4003
4649
  (options.preferredUnits?.() ?? []).map((u) => u.toLowerCase())
4004
4650
  );
4005
- const unitPool = unitCompletions(
4006
- units,
4007
- quantity.getChild("AtSign") ? "mass" : void 0,
4008
- preferredSet.size > 0 ? preferredSet : void 0
4009
- );
4010
- const wordText = completingWord ? context.state.doc.sliceString(last.from, pos).toLowerCase() : "";
4011
- const hasAliasHit = wordText.length >= 2 && postQuantityEffortOptions.some((opt) => completionMatchesWord(opt, wordText) === "alias");
4012
- const pool = [...unitPool, ...postQuantityEffortOptions];
4013
- if (hasAliasHit && completingWord) {
4014
- const rawPhrase = context.state.doc.sliceString(last.from, pos);
4651
+ if (hasAtSign) {
4652
+ const massPool = unitCompletions(units, "mass", preferredSet.size > 0 ? preferredSet : void 0);
4653
+ const wordText = completingWord ? context.state.doc.sliceString(last.from, pos) : "";
4654
+ if (completingWord && (last.to > pos || wordText.length >= 2)) {
4655
+ const hasAlias = massPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias");
4656
+ if (hasAlias || last.to > pos) {
4657
+ return {
4658
+ from: last.from,
4659
+ ...last.to > pos ? { to: last.to } : {},
4660
+ options: massPool.filter((opt) => scoreCompletionOption(wordText, opt) !== null),
4661
+ filter: false
4662
+ };
4663
+ }
4664
+ }
4015
4665
  return {
4016
- from: last.from,
4017
- options: appendCreateEffortOption(
4018
- pool.filter((opt) => completionMatchesWord(opt, wordText) !== null),
4019
- rawPhrase,
4020
- options.onCreateEffort
4021
- ),
4022
- filter: false,
4666
+ from: completingWord ? last.from : pos,
4667
+ options: massPool,
4023
4668
  validFor: /^[A-Za-z]*$/
4024
4669
  };
4025
4670
  }
4026
- return {
4027
- from: completingWord ? last.from : pos,
4028
- options: completingWord ? appendCreateEffortOption(pool, context.state.doc.sliceString(last.from, pos), options.onCreateEffort) : pool,
4029
- validFor: /^[A-Za-z]*$/
4030
- };
4671
+ if (ladder.isLadder) {
4672
+ const ladderDetail = ladder.rungCount >= 3 ? `rep scheme (${ladder.rungCount} rounds)` : "rep scheme";
4673
+ const ladderReps = makeCountQualifiers(false, isGlued, ladderDetail);
4674
+ if (hasTrailingSpace) {
4675
+ return {
4676
+ from: pos,
4677
+ options: [
4678
+ ...missingLineElements,
4679
+ ...keywords.filter((k) => k.label === "FOR TIME")
4680
+ ]
4681
+ };
4682
+ }
4683
+ if (completingWord) {
4684
+ const wordText = context.state.doc.sliceString(last.from, pos);
4685
+ const pool = isGlued ? ladderReps : [...isGlued ? [] : makeCountQualifiers(false, false, ladderDetail), ...missingLineElements, ...keywords.filter((k) => k.label === "FOR TIME")];
4686
+ const matched = scorePhrasePool(wordText, pool, catalog, options.onCreateEffort, !isGlued);
4687
+ return matched.length > 0 ? {
4688
+ from: last.from,
4689
+ ...last.to > pos ? { to: last.to } : {},
4690
+ options: matched,
4691
+ filter: false
4692
+ } : null;
4693
+ }
4694
+ return {
4695
+ from: pos,
4696
+ options: ladderReps,
4697
+ validFor: /^[A-Za-z]*$/
4698
+ };
4699
+ }
4700
+ if (isGlued) {
4701
+ const countOpts = isWholeInteger || isWildcard ? makeCountQualifiers(isWholeInteger && !prefixLine.hasRounds, true) : [];
4702
+ const unitPool = [
4703
+ ...countOpts,
4704
+ ...unitCompletions(units, void 0, preferredSet.size > 0 ? preferredSet : void 0)
4705
+ ];
4706
+ if (completingWord) {
4707
+ const wordText = context.state.doc.sliceString(last.from, pos);
4708
+ const hasAliasHit = unitPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias");
4709
+ if (hasAliasHit || last.to > pos) {
4710
+ return {
4711
+ from: last.from,
4712
+ ...last.to > pos ? { to: last.to } : {},
4713
+ options: unitPool.filter((opt) => scoreCompletionOption(wordText, opt) !== null),
4714
+ filter: false
4715
+ };
4716
+ }
4717
+ }
4718
+ return {
4719
+ from: completingWord ? last.from : pos,
4720
+ options: unitPool,
4721
+ validFor: /^[A-Za-z]*$/
4722
+ };
4723
+ }
4724
+ if (hasTrailingSpace) {
4725
+ if (!prefixLine.hasEffort) {
4726
+ return missingLineElements.length > 0 ? { from: pos, options: missingLineElements } : null;
4727
+ }
4728
+ if (!prefixLine.hasEquipment) {
4729
+ return equipmentOpts.length > 0 ? { from: pos, options: equipmentOpts } : null;
4730
+ }
4731
+ return null;
4732
+ }
4733
+ if (completingWord) {
4734
+ const wordText = context.state.doc.sliceString(last.from, pos);
4735
+ const unitCandidates = [
4736
+ ...isWholeInteger || isWildcard ? makeCountQualifiers(isWholeInteger && !prefixLine.hasRounds, false) : [],
4737
+ ...unitCompletions(units, void 0, preferredSet.size > 0 ? preferredSet : void 0)
4738
+ ];
4739
+ const matchingUnits = unitCandidates.filter((opt) => {
4740
+ const norm = normalizeForFuzzy(wordText);
4741
+ const labelLower = opt.label.toLowerCase();
4742
+ const aliases = completionAliases.get(opt) ?? [];
4743
+ return labelLower.startsWith(norm) || aliases.some((a) => a.startsWith(norm));
4744
+ });
4745
+ const elementPool = prefixLine.hasEffort && !prefixLine.hasEquipment ? equipmentOpts : prefixLine.hasEffort ? [] : missingLineElements;
4746
+ const effortMatches = scoreCatalogList(wordText, prefixLine.hasEffort ? [] : catalog.efforts);
4747
+ const equipmentMatches = scoreCatalogList(wordText, prefixLine.hasEquipment ? [] : catalog.equipment);
4748
+ const sportMatches = (!prefixLine.hasEffort ? sportWords : []).map((opt) => ({ opt, score: scoreCompletionOption(wordText, opt) })).filter((x) => x.score !== null).sort((a, b) => b.score - a.score).map((x) => x.opt);
4749
+ const combined = [
4750
+ ...matchingUnits,
4751
+ ...effortMatches.map((x) => x.opt),
4752
+ ...equipmentMatches.map((x) => x.opt),
4753
+ ...sportMatches
4754
+ ];
4755
+ const hasAliasHit = elementPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias") || matchingUnits.length > 0 || effortMatches.length + equipmentMatches.length > 0;
4756
+ const suppressCreate = isExactAliasOrTermSplit(wordText, catalog);
4757
+ return hasAliasHit || combined.length > 0 || options.onCreateEffort && !prefixLine.hasEffort ? {
4758
+ from: last.from,
4759
+ ...last.to > pos ? { to: last.to } : {},
4760
+ options: !prefixLine.hasEffort ? appendCreateEffortOption(combined, wordText, options.onCreateEffort, suppressCreate) : combined,
4761
+ filter: false
4762
+ } : null;
4763
+ }
4031
4764
  }
4032
4765
  if (before.trim() === "") {
4033
- return { from: pos, options: [...snippets, ...startKeywords, ...efforts, ...sportWords] };
4766
+ return { from: pos, options: [...snippets, ...startKeywords, ...efforts, ...equipmentOpts, ...sportWords] };
4034
4767
  }
4768
+ const effortRun = trailingEffortRun(context, statement, units);
4035
4769
  if (word.length === 0 && /[ \t]$/.test(before)) {
4036
- const effortRun = trailingEffortRun(context, statement, units);
4037
- const last2 = effortRun[effortRun.length - 1];
4038
- if (last2 && !isUnitFragment(context, last2, units)) return null;
4039
- return { from: pos, options: effortOptions };
4770
+ if (effortRun.length === 0) {
4771
+ return { from: pos, options: [...keywords, ...missingLineElements] };
4772
+ }
4773
+ const runFirst = effortRun[0];
4774
+ const runLast = effortRun[effortRun.length - 1];
4775
+ const phraseFrom = runFirst.from;
4776
+ const phraseText = context.state.doc.sliceString(phraseFrom, runLast.to).trim();
4777
+ if (phraseHasExplicitEquipment(phraseText, catalog)) return null;
4778
+ const exactEq = findExactEntry(phraseText, catalog.equipment);
4779
+ if (exactEq) {
4780
+ const dedicated = specializedEffortsForEquipment(exactEq, catalog);
4781
+ const dedicatedLabels = new Set(dedicated.map((d) => d.label.toLowerCase()));
4782
+ const appendedEfforts = catalog.efforts.filter((e) => !dedicatedLabels.has(e.labelLower)).map((e) => ({
4783
+ ...e.completion,
4784
+ apply: (view, _c, from, to) => {
4785
+ const existing = view.state.doc.sliceString(from, to);
4786
+ const insert = `${existing}${e.label}`;
4787
+ view.dispatch({
4788
+ changes: { from, to, insert },
4789
+ selection: { anchor: from + insert.length },
4790
+ userEvent: "input.complete"
4791
+ });
4792
+ }
4793
+ }));
4794
+ const allEqOptions = [...dedicated, ...appendedEfforts];
4795
+ return allEqOptions.length > 0 ? { from: phraseFrom, options: allEqOptions, filter: false } : null;
4796
+ }
4797
+ const specialized = specializedEffortsForBase(phraseText, catalog);
4798
+ const suffixEquipment = catalog.equipment.map((eq) => ({
4799
+ ...eq.completion,
4800
+ apply: (view, _completion, from, to) => {
4801
+ const existing = view.state.doc.sliceString(from, to);
4802
+ const insert = `${existing}${eq.label}`;
4803
+ view.dispatch({
4804
+ changes: { from, to, insert },
4805
+ selection: { anchor: from + insert.length },
4806
+ userEvent: "input.complete"
4807
+ });
4808
+ }
4809
+ }));
4810
+ const combined = [...specialized, ...suffixEquipment];
4811
+ return combined.length > 0 ? { from: phraseFrom, options: combined, filter: false } : null;
4040
4812
  }
4041
4813
  if (word.length > 0 && /^[A-Za-z][A-Za-z0-9'-]*$/.test(word)) {
4042
- const effortRun = trailingEffortRun(context, statement, units);
4043
- const first = effortRun[0];
4044
- const last2 = effortRun[effortRun.length - 1];
4045
- if (!first || !last2 || last2.to < pos) return null;
4046
- const rawPhrase = context.state.doc.sliceString(first.from, pos);
4047
- const typed = rawPhrase.toLowerCase();
4048
- const compatible = effortOptions.filter((option) => completionMatchesWord(option, typed) !== null);
4049
- const usesAlias = compatible.some((option) => completionMatchesWord(option, typed) === "alias");
4814
+ if (effortRun.length === 0) return null;
4815
+ const phraseFrom = effortRun[0].from;
4816
+ const runLast = effortRun[effortRun.length - 1];
4817
+ if (runLast.to < pos) return null;
4818
+ const rawPhrase = context.state.doc.sliceString(phraseFrom, pos);
4819
+ const isSingleWord = effortRun.length === 1;
4820
+ const scoredOptions = [];
4821
+ const seenOutcome = /* @__PURE__ */ new Set();
4822
+ const pushScored = (option, score, outcomeKey) => {
4823
+ if (seenOutcome.has(outcomeKey)) return;
4824
+ seenOutcome.add(outcomeKey);
4825
+ scoredOptions.push({ option, score });
4826
+ };
4827
+ const strategy1Efforts = scoreCatalogList(rawPhrase, catalog.efforts);
4828
+ for (const { entry, opt, score } of strategy1Efforts) {
4829
+ const eqLabels = entry.equipmentSlugs.map((slug) => catalog.equipmentLabelBySlug.get(slug)).filter((lbl) => Boolean(lbl));
4830
+ const multiTokenUpgrade = !isSingleWord && eqLabels.length > 0;
4831
+ const upgradedDetail = multiTokenUpgrade && !(opt.detail ?? "").toLowerCase().includes(eqLabels[0].toLowerCase()) ? `${opt.detail ?? "effort"} \xB7 includes ${eqLabels.join(", ")}` : opt.detail;
4832
+ pushScored(
4833
+ {
4834
+ ...opt,
4835
+ detail: upgradedDetail,
4836
+ boost: clampBoost(Math.min(75, Math.round(score / 4)) + (multiTokenUpgrade ? 10 : 0)),
4837
+ apply: (view, _completion, from, to) => {
4838
+ view.dispatch({
4839
+ changes: { from, to, insert: entry.label },
4840
+ selection: { anchor: from + entry.label.length },
4841
+ userEvent: "input.complete"
4842
+ });
4843
+ }
4844
+ },
4845
+ score + (multiTokenUpgrade ? 25 : 0),
4846
+ `whole:${entry.labelLower}`
4847
+ );
4848
+ }
4849
+ if (isSingleWord) {
4850
+ for (const { entry, opt, score } of scoreCatalogList(rawPhrase, catalog.equipment)) {
4851
+ pushScored(
4852
+ {
4853
+ ...opt,
4854
+ boost: clampBoost(Math.min(70, Math.round(score / 4))),
4855
+ apply: (view, _completion, from, to) => {
4856
+ view.dispatch({
4857
+ changes: { from, to, insert: entry.label },
4858
+ selection: { anchor: from + entry.label.length },
4859
+ userEvent: "input.complete"
4860
+ });
4861
+ }
4862
+ },
4863
+ score,
4864
+ `eq-whole:${entry.labelLower}`
4865
+ );
4866
+ }
4867
+ for (const kw of [...keywords, ...sportWords]) {
4868
+ const s = scoreCompletionOption(rawPhrase, kw);
4869
+ if (s !== null) pushScored(kw, s, `kw:${kw.label.toLowerCase()}`);
4870
+ }
4871
+ } else {
4872
+ for (let k = 1; k < effortRun.length; k++) {
4873
+ const prefixText = context.state.doc.sliceString(phraseFrom, effortRun[k - 1].to).trim();
4874
+ const suffixFrom = effortRun[k].from;
4875
+ const suffixText = context.state.doc.sliceString(suffixFrom, pos).trim();
4876
+ if (!prefixText || !suffixText) continue;
4877
+ const suffixDelta = suffixFrom - phraseFrom;
4878
+ const prefixIsEq = findExactEntry(prefixText, catalog.equipment);
4879
+ const prefixIsEff = findExactEntry(prefixText, catalog.efforts);
4880
+ if (prefixIsEq) {
4881
+ for (const { entry, opt, score } of scoreCatalogList(suffixText, catalog.efforts)) {
4882
+ if (seenOutcome.has(`whole:${entry.labelLower}`)) continue;
4883
+ if (normalizeForFuzzy(entry.label).includes(normalizeForFuzzy(prefixIsEq.label))) continue;
4884
+ const resultingText = `${prefixText} ${entry.label}`.toLowerCase();
4885
+ if (seenOutcome.has(`whole:${resultingText}`)) continue;
4886
+ const dedicatedEqText = `${prefixIsEq.label} ${entry.label}`.toLowerCase();
4887
+ if (seenOutcome.has(`whole:${dedicatedEqText}`)) continue;
4888
+ pushScored(
4889
+ {
4890
+ ...opt,
4891
+ boost: clampBoost(Math.min(72, Math.round(score / 4))),
4892
+ apply: (view, _completion, from, to) => {
4893
+ view.dispatch({
4894
+ changes: { from: from + suffixDelta, to, insert: entry.label },
4895
+ selection: { anchor: from + suffixDelta + entry.label.length },
4896
+ userEvent: "input.complete"
4897
+ });
4898
+ }
4899
+ },
4900
+ score,
4901
+ `eq-prefix-eff:${entry.labelLower}:${suffixDelta}`
4902
+ );
4903
+ }
4904
+ }
4905
+ const allowEquipmentSuffix = Boolean(prefixIsEff) || !prefixIsEq && suffixText.length >= 2 && (strategy1Efforts.length === 0 || scoreCatalogList(suffixText, catalog.equipment).some((m) => m.score >= 70));
4906
+ if (allowEquipmentSuffix && !prefixIsEq) {
4907
+ for (const { entry, opt, score } of scoreCatalogList(suffixText, catalog.equipment)) {
4908
+ pushScored(
4909
+ {
4910
+ ...opt,
4911
+ detail: opt.detail ?? "Equipment",
4912
+ boost: clampBoost(Math.min(70, Math.round(score / 4))),
4913
+ apply: (view, _completion, from, to) => {
4914
+ view.dispatch({
4915
+ changes: { from: from + suffixDelta, to, insert: entry.label },
4916
+ selection: { anchor: from + suffixDelta + entry.label.length },
4917
+ userEvent: "input.complete"
4918
+ });
4919
+ }
4920
+ },
4921
+ score,
4922
+ `eff-prefix-eq:${entry.labelLower}:${suffixDelta}`
4923
+ );
4924
+ }
4925
+ }
4926
+ }
4927
+ }
4928
+ scoredOptions.sort((a, b) => b.score - a.score);
4929
+ const finalOptions = scoredOptions.map((x) => x.option);
4930
+ const suppressCreate = isExactAliasOrTermSplit(rawPhrase, catalog);
4931
+ const withCreate = appendCreateEffortOption(finalOptions, rawPhrase, options.onCreateEffort, suppressCreate);
4932
+ if (withCreate.length === 0) return null;
4050
4933
  return {
4051
- from: first.from,
4052
- options: appendCreateEffortOption(compatible, rawPhrase, options.onCreateEffort),
4053
- ...usesAlias ? { filter: false } : {},
4054
- validFor: /^[A-Za-z ]*$/
4934
+ from: phraseFrom,
4935
+ ...runLast.to > pos ? { to: runLast.to } : {},
4936
+ options: withCreate,
4937
+ filter: false
4055
4938
  };
4056
4939
  }
4057
4940
  return null;
4058
4941
  };
4059
4942
  }
4943
+ function scoreCatalogList(query, entries) {
4944
+ const scored = [];
4945
+ for (const entry of entries) {
4946
+ const score = scoreCatalogEntry(query, entry);
4947
+ if (score !== null) scored.push({ entry, opt: entry.completion, score });
4948
+ }
4949
+ scored.sort((a, b) => b.score - a.score);
4950
+ return scored;
4951
+ }
4952
+ function scorePhrasePool(query, pool, catalog, onCreateEffort, allowCreate = true) {
4953
+ const scored = [];
4954
+ const effortMap = new Map(catalog.efforts.map((e) => [e.completion, e]));
4955
+ const eqMap = new Map(catalog.equipment.map((e) => [e.completion, e]));
4956
+ for (const opt of pool) {
4957
+ const eff = effortMap.get(opt);
4958
+ const eq = eqMap.get(opt);
4959
+ const score = eff ? scoreCatalogEntry(query, eff) : eq ? scoreCatalogEntry(query, eq) : scoreCompletionOption(query, opt);
4960
+ if (score !== null) scored.push({ opt, score });
4961
+ }
4962
+ scored.sort((a, b) => b.score - a.score);
4963
+ const res = scored.map((x) => x.opt);
4964
+ return allowCreate ? appendCreateEffortOption(res, query, onCreateEffort, isExactAliasOrTermSplit(query, catalog)) : res;
4965
+ }
4060
4966
  function whiteboardScriptCompletion(options = {}) {
4061
4967
  return autocomplete.autocompletion({ override: [whiteboardScriptCompletionSource(options)] });
4062
4968
  }
@@ -4099,6 +5005,196 @@ function whiteboardScript(options) {
4099
5005
  return new language.LanguageSupport(whiteboardScriptLanguage, whiteboardScriptCompletion(options ?? {}));
4100
5006
  }
4101
5007
 
5008
+ // src/parser/indentation.ts
5009
+ var ROUNDS_QUALIFIER_WORDS2 = /^(rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
5010
+ var CONTAINER_KEYWORDS = /* @__PURE__ */ new Set(["amrap", "emom", "tabata"]);
5011
+ function hasAnyErrorNode(node) {
5012
+ let found = false;
5013
+ node.cursor().iterate((cur) => {
5014
+ if (cur.type.isError) {
5015
+ found = true;
5016
+ return false;
5017
+ }
5018
+ return void 0;
5019
+ });
5020
+ return found;
5021
+ }
5022
+ function isRoundsHeaderLine(lineContent) {
5023
+ const trimmed = lineContent.trim();
5024
+ if (!trimmed) return false;
5025
+ const source = `${trimmed}
5026
+ `;
5027
+ const tree = parser.parse(source);
5028
+ if (hasAnyErrorNode(tree.topNode)) return false;
5029
+ const topChildren = [];
5030
+ for (let child = tree.topNode.firstChild; child; child = child.nextSibling) {
5031
+ if (child.name !== "newline") topChildren.push(child);
5032
+ }
5033
+ if (topChildren.length !== 1 || topChildren[0].name !== "Block") return false;
5034
+ const fragments = topChildren[0].getChildren("Fragment");
5035
+ if (fragments.length === 0) return false;
5036
+ let hasRoundsHeader = false;
5037
+ let hasContainerKeyword = false;
5038
+ let hasDuration = false;
5039
+ let hasLeafPayload = false;
5040
+ for (let i = 0; i < fragments.length; i++) {
5041
+ const frag = fragments[i];
5042
+ const kind = frag.firstChild;
5043
+ if (!kind) {
5044
+ hasLeafPayload = true;
5045
+ break;
5046
+ }
5047
+ switch (kind.name) {
5048
+ case "Rounds": {
5049
+ const raw = source.slice(kind.from, kind.to);
5050
+ if (!raw.endsWith(")")) return false;
5051
+ const seq = kind.getChild("Sequence");
5052
+ const idNode = kind.getChild("Identifier");
5053
+ if (!seq) {
5054
+ hasLeafPayload = true;
5055
+ break;
5056
+ }
5057
+ const numbers = seq.getChildren("Number");
5058
+ const idText = idNode ? source.slice(idNode.from, idNode.to) : "";
5059
+ if (numbers.length >= 2 && !idNode) {
5060
+ hasRoundsHeader = true;
5061
+ } else if (numbers.length === 1 && (!idNode || ROUNDS_QUALIFIER_WORDS2.test(idText))) {
5062
+ hasRoundsHeader = true;
5063
+ } else {
5064
+ hasLeafPayload = true;
5065
+ }
5066
+ break;
5067
+ }
5068
+ case "RoundScheme": {
5069
+ hasRoundsHeader = true;
5070
+ break;
5071
+ }
5072
+ case "Duration": {
5073
+ hasDuration = true;
5074
+ break;
5075
+ }
5076
+ case "Quantity": {
5077
+ const hasAtSign = Boolean(kind.getChild("AtSign"));
5078
+ const qtyRaw = source.slice(kind.from, kind.to);
5079
+ const isWholeInt = !hasAtSign && /^\d+$/.test(qtyRaw);
5080
+ if (!isWholeInt) {
5081
+ hasLeafPayload = true;
5082
+ break;
5083
+ }
5084
+ let j = i;
5085
+ let rungCount = 1;
5086
+ while (j + 2 < fragments.length && fragments[j + 1].firstChild?.name === "Effort" && source.slice(fragments[j + 1].from, fragments[j + 1].to) === "-" && fragments[j + 1].from === fragments[j].to && fragments[j + 2].firstChild?.name === "Quantity" && fragments[j + 2].from === fragments[j + 1].to && /^\d+$/.test(source.slice(fragments[j + 2].from, fragments[j + 2].to))) {
5087
+ rungCount++;
5088
+ j += 2;
5089
+ }
5090
+ if (rungCount >= 2) {
5091
+ hasRoundsHeader = true;
5092
+ i = j;
5093
+ if (i + 1 < fragments.length && fragments[i + 1].firstChild?.name === "Effort" && /^reps?$/i.test(source.slice(fragments[i + 1].from, fragments[i + 1].to).trim())) {
5094
+ i++;
5095
+ }
5096
+ break;
5097
+ }
5098
+ if (i + 1 < fragments.length && fragments[i + 1].firstChild?.name === "Effort" && ROUNDS_QUALIFIER_WORDS2.test(source.slice(fragments[i + 1].from, fragments[i + 1].to).trim())) {
5099
+ hasRoundsHeader = true;
5100
+ i++;
5101
+ break;
5102
+ }
5103
+ hasLeafPayload = true;
5104
+ break;
5105
+ }
5106
+ case "Effort": {
5107
+ const raw = source.slice(kind.from, kind.to).trim().toLowerCase();
5108
+ if (raw === "for" && i + 1 < fragments.length && fragments[i + 1].firstChild?.name === "Effort" && source.slice(fragments[i + 1].from, fragments[i + 1].to).trim().toLowerCase() === "time") {
5109
+ hasContainerKeyword = true;
5110
+ i++;
5111
+ break;
5112
+ }
5113
+ if (CONTAINER_KEYWORDS.has(raw)) {
5114
+ hasContainerKeyword = true;
5115
+ break;
5116
+ }
5117
+ if (raw === "work" && (hasRoundsHeader || hasDuration)) {
5118
+ break;
5119
+ }
5120
+ hasLeafPayload = true;
5121
+ break;
5122
+ }
5123
+ case "TagRef":
5124
+ case "Text":
5125
+ break;
5126
+ default:
5127
+ hasLeafPayload = true;
5128
+ break;
5129
+ }
5130
+ if (hasLeafPayload) break;
5131
+ }
5132
+ return (hasRoundsHeader || hasContainerKeyword) && !hasLeafPayload;
5133
+ }
5134
+ function computeWhiteboardEnterAction(lineText, fromCol, toCol = fromCol, unit = " ") {
5135
+ const indent = /^[ \t]*/.exec(lineText)[0];
5136
+ const before = lineText.slice(0, fromCol);
5137
+ const after = lineText.slice(toCol);
5138
+ const isCollapsed = fromCol === toCol;
5139
+ if (lineText.trim() === "") {
5140
+ if (indent.length > 0) {
5141
+ return {
5142
+ replaceFromCol: 0,
5143
+ replaceToCol: lineText.length,
5144
+ insert: "\n",
5145
+ cursorOffset: 1
5146
+ };
5147
+ }
5148
+ return {
5149
+ replaceFromCol: fromCol,
5150
+ replaceToCol: toCol,
5151
+ insert: "\n",
5152
+ cursorOffset: 1
5153
+ };
5154
+ }
5155
+ if (/^([ \t]*)([+-])(?![+-])[ \t]*$/.test(lineText) && fromCol >= indent.length + 1) {
5156
+ return {
5157
+ replaceFromCol: 0,
5158
+ replaceToCol: lineText.length,
5159
+ insert: "\n",
5160
+ cursorOffset: 1
5161
+ };
5162
+ }
5163
+ if (isCollapsed && fromCol <= indent.length && after.trim().length > 0) {
5164
+ const keptIndent = indent.slice(0, fromCol);
5165
+ return {
5166
+ replaceFromCol: 0,
5167
+ replaceToCol: fromCol,
5168
+ insert: `
5169
+ ${keptIndent}`,
5170
+ cursorOffset: 1 + keptIndent.length
5171
+ };
5172
+ }
5173
+ const leadingAfterSpaces = /^[ \t]+/.exec(after)?.[0].length ?? 0;
5174
+ const markerMatch = /^([ \t]*)([+-])(?![+-])([ \t]*)(.*)$/.exec(before);
5175
+ if (markerMatch) {
5176
+ const marker = markerMatch[2];
5177
+ const contentBefore = markerMatch[4].trim();
5178
+ const nextPrefix2 = contentBefore.length > 0 ? isRoundsHeaderLine(contentBefore) ? `${indent}${unit}` : `${indent}${marker} ` : indent;
5179
+ return {
5180
+ replaceFromCol: fromCol,
5181
+ replaceToCol: toCol + leadingAfterSpaces,
5182
+ insert: `
5183
+ ${nextPrefix2}`,
5184
+ cursorOffset: 1 + nextPrefix2.length
5185
+ };
5186
+ }
5187
+ const beforeContent = before.slice(indent.length).trim();
5188
+ const nextPrefix = isRoundsHeaderLine(beforeContent) ? `${indent}${unit}` : indent;
5189
+ return {
5190
+ replaceFromCol: fromCol,
5191
+ replaceToCol: toCol + leadingAfterSpaces,
5192
+ insert: `
5193
+ ${nextPrefix}`,
5194
+ cursorOffset: 1 + nextPrefix.length
5195
+ };
5196
+ }
5197
+
4102
5198
  // src/effort-registry/types.ts
4103
5199
  var EFFORT_REGISTRY_ORIGINS = ["bundled", "user"];
4104
5200
  var SEED_PRECEDENCE_RANK = {
@@ -4787,71 +5883,6 @@ function tagCategoryRecordToDocument(category, record) {
4787
5883
  ...Object.keys(widgets).length > 0 ? { widgets } : {}
4788
5884
  });
4789
5885
  }
4790
-
4791
- // src/effort-registry/fuzzyMatch.ts
4792
- function levenshteinDistance(a, b) {
4793
- if (a === b) return 0;
4794
- if (a.length === 0) return b.length;
4795
- if (b.length === 0) return a.length;
4796
- if (a.length > b.length) {
4797
- const tmp = a;
4798
- a = b;
4799
- b = tmp;
4800
- }
4801
- const m = a.length;
4802
- const n = b.length;
4803
- let prev = new Uint32Array(m + 1);
4804
- let curr = new Uint32Array(m + 1);
4805
- for (let i = 0; i <= m; i++) {
4806
- prev[i] = i;
4807
- }
4808
- for (let j = 1; j <= n; j++) {
4809
- curr[0] = j;
4810
- const bj = b.charCodeAt(j - 1);
4811
- for (let i = 1; i <= m; i++) {
4812
- const cost = a.charCodeAt(i - 1) === bj ? 0 : 1;
4813
- curr[i] = Math.min(
4814
- prev[i] + 1,
4815
- // deletion
4816
- curr[i - 1] + 1,
4817
- // insertion
4818
- prev[i - 1] + cost
4819
- // substitution
4820
- );
4821
- }
4822
- const swap = prev;
4823
- prev = curr;
4824
- curr = swap;
4825
- }
4826
- return prev[m];
4827
- }
4828
- function normalizeForFuzzy(input) {
4829
- return input.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").replace(/[-_]+/g, " ").trim().replace(/\s+/g, " ");
4830
- }
4831
- function isWithinThreshold(a, b, threshold) {
4832
- const na = normalizeForFuzzy(a);
4833
- const nb = normalizeForFuzzy(b);
4834
- if (na === nb) return true;
4835
- if (Math.abs(na.length - nb.length) > threshold) return false;
4836
- return levenshteinDistance(na, nb) <= threshold;
4837
- }
4838
- function findBestFuzzyMatch(query, candidates, threshold) {
4839
- const nq = normalizeForFuzzy(query);
4840
- let best = null;
4841
- for (const candidate of candidates) {
4842
- const nc = normalizeForFuzzy(candidate);
4843
- if (Math.abs(nq.length - nc.length) > threshold) continue;
4844
- const distance = levenshteinDistance(nq, nc);
4845
- if (distance > threshold) continue;
4846
- if (!best || distance < best.distance) {
4847
- best = { target: candidate, distance };
4848
- if (distance === 0) break;
4849
- }
4850
- }
4851
- return best;
4852
- }
4853
-
4854
- // src/effort-registry/EffortResolver.ts
4855
5886
  function normalizeSlug(label) {
4856
5887
  return normalizeForFuzzy(label).replace(/\s+/g, "-");
4857
5888
  }
@@ -5386,6 +6417,14 @@ function buildExactIndex(entities) {
5386
6417
  }
5387
6418
  const topTier = direct.filter((candidate) => resolveEntityRank(candidate) === maxRank);
5388
6419
  if (topTier.length === 1) return { entity: topTier[0], ambiguous: [] };
6420
+ const trimmedLower = key.trim().toLowerCase();
6421
+ const slugified = normalizeForFuzzy(key).replace(/\s+/g, "-");
6422
+ const exactSlugMatches = topTier.filter(
6423
+ (candidate) => candidate.slug.toLowerCase() === trimmedLower || candidate.slug.toLowerCase() === slugified
6424
+ );
6425
+ if (exactSlugMatches.length === 1) {
6426
+ return { entity: exactSlugMatches[0], ambiguous: [] };
6427
+ }
5389
6428
  return { entity: null, ambiguous: topTier };
5390
6429
  }
5391
6430
  };
@@ -5408,7 +6447,7 @@ function createReferenceIndex(catalog, materialize) {
5408
6447
  const dedupedEquipment = dedupeEntitiesByPrecedence(catalog.equipment ?? []);
5409
6448
  const efforts = buildExactIndex(catalog.efforts ?? []);
5410
6449
  const equipment = buildExactIndex(dedupedEquipment);
5411
- const prefixCandidates = dedupedEquipment.flatMap((entity) => [entity.label, ...entity.aliases].filter((name2) => !!name2 && !!name2.trim()).map((name2) => ({ lower: name2.trim().toLowerCase(), entity }))).sort((a, b) => b.lower.length - a.lower.length);
6450
+ const equipmentCandidates = dedupedEquipment.flatMap((entity) => [entity.label, ...entity.aliases].filter((name2) => !!name2 && !!name2.trim()).map((name2) => ({ lower: name2.trim().toLowerCase(), entity }))).sort((a, b) => b.lower.length - a.lower.length);
5412
6451
  const materializer = materialize ?? ((effort) => ({
5413
6452
  effort,
5414
6453
  definition: effort,
@@ -5496,6 +6535,7 @@ function createReferenceIndex(catalog, materialize) {
5496
6535
  let remaining = "";
5497
6536
  let equipmentRefs = [];
5498
6537
  let equipmentAuthored = false;
6538
+ let equipmentSpan;
5499
6539
  const fillEquipment = () => {
5500
6540
  if (equipmentRefs.length > 0 || equipmentAuthored) return;
5501
6541
  if (effortEntity === null) return;
@@ -5608,8 +6648,9 @@ function createReferenceIndex(catalog, materialize) {
5608
6648
  };
5609
6649
  }
5610
6650
  }
6651
+ const wholeFound = resolveEffortExact(source);
5611
6652
  const lowerSource = source.toLowerCase();
5612
- for (const candidate of prefixCandidates) {
6653
+ for (const candidate of equipmentCandidates) {
5613
6654
  if (!lowerSource.startsWith(candidate.lower)) continue;
5614
6655
  const after = source.slice(candidate.lower.length);
5615
6656
  if (after && !/^\s/.test(after)) continue;
@@ -5635,6 +6676,11 @@ function createReferenceIndex(catalog, materialize) {
5635
6676
  }
5636
6677
  if (!equipmentFound.entity) continue;
5637
6678
  const effortFound = resolveEffortExact(candidateRemaining);
6679
+ if (wholeFound.entity && wholeFound.entity.equipment?.includes(equipmentFound.entity.slug) && (effortFound.entity || effortFound.diagnostic?.reason === "ambiguous-effort")) {
6680
+ matched = "whole";
6681
+ effortEntity = wholeFound.entity;
6682
+ break;
6683
+ }
5638
6684
  if (effortFound.entity) {
5639
6685
  matched = "split";
5640
6686
  effortEntity = effortFound.entity;
@@ -5645,9 +6691,10 @@ function createReferenceIndex(catalog, materialize) {
5645
6691
  }];
5646
6692
  equipmentAuthored = true;
5647
6693
  remaining = candidateRemaining;
6694
+ equipmentSpan = { start: 0, end: rawPrefix.length };
5648
6695
  break;
5649
6696
  }
5650
- if (effortFound.diagnostic?.reason === "ambiguous-effort") {
6697
+ if (effortFound.diagnostic?.reason === "ambiguous-effort" && !wholeFound.entity) {
5651
6698
  push(effortFound.diagnostic);
5652
6699
  return {
5653
6700
  matched: "none",
@@ -5661,12 +6708,11 @@ function createReferenceIndex(catalog, materialize) {
5661
6708
  }
5662
6709
  }
5663
6710
  if (matched === "none") {
5664
- const found = resolveEffortExact(source);
5665
- if (found.entity) {
5666
- effortEntity = found.entity;
6711
+ if (wholeFound.entity) {
6712
+ effortEntity = wholeFound.entity;
5667
6713
  matched = "whole";
5668
- } else if (found.diagnostic?.reason === "ambiguous-effort") {
5669
- push(found.diagnostic);
6714
+ } else if (wholeFound.diagnostic?.reason === "ambiguous-effort") {
6715
+ push(wholeFound.diagnostic);
5670
6716
  return {
5671
6717
  matched: "none",
5672
6718
  label: source,
@@ -5676,8 +6722,65 @@ function createReferenceIndex(catalog, materialize) {
5676
6722
  remaining: "",
5677
6723
  diagnostics
5678
6724
  };
5679
- } else if (found.diagnostic) {
5680
- push(found.diagnostic);
6725
+ } else if (wholeFound.diagnostic) {
6726
+ push(wholeFound.diagnostic);
6727
+ }
6728
+ }
6729
+ if (matched === "none") {
6730
+ for (const candidate of equipmentCandidates) {
6731
+ if (!lowerSource.endsWith(candidate.lower)) continue;
6732
+ const beforeLen = source.length - candidate.lower.length;
6733
+ if (beforeLen <= 0 || !/\s$/.test(source.slice(0, beforeLen))) continue;
6734
+ const candidateRemaining = source.slice(0, beforeLen).trim();
6735
+ if (!candidateRemaining) continue;
6736
+ const equipmentFound = equipment.lookup(candidate.lower);
6737
+ if (equipmentFound.ambiguous.length > 0) {
6738
+ diagnostics.length = 0;
6739
+ push({
6740
+ reason: "ambiguous-equipment",
6741
+ message: `"${candidate.lower}" matches multiple equipment entries.`,
6742
+ token: source,
6743
+ candidates: equipmentFound.ambiguous.map((e) => e.slug)
6744
+ });
6745
+ return {
6746
+ matched: "none",
6747
+ label: source,
6748
+ effort: null,
6749
+ effortRef: null,
6750
+ equipment: [],
6751
+ remaining: "",
6752
+ diagnostics
6753
+ };
6754
+ }
6755
+ if (!equipmentFound.entity) continue;
6756
+ const effortFound = resolveEffortExact(candidateRemaining);
6757
+ if (effortFound.entity) {
6758
+ diagnostics.length = 0;
6759
+ matched = "split";
6760
+ effortEntity = effortFound.entity;
6761
+ const rawSuffix = source.slice(beforeLen);
6762
+ equipmentRefs = [{
6763
+ ...equipmentRef(equipmentFound.entity),
6764
+ ...rawSuffix.toLowerCase() !== equipmentFound.entity.label.toLowerCase() ? { matchedAlias: rawSuffix } : {}
6765
+ }];
6766
+ equipmentAuthored = true;
6767
+ remaining = candidateRemaining;
6768
+ equipmentSpan = { start: beforeLen, end: source.length };
6769
+ break;
6770
+ }
6771
+ if (effortFound.diagnostic?.reason === "ambiguous-effort") {
6772
+ diagnostics.length = 0;
6773
+ push(effortFound.diagnostic);
6774
+ return {
6775
+ matched: "none",
6776
+ label: source,
6777
+ effort: null,
6778
+ effortRef: null,
6779
+ equipment: [],
6780
+ remaining: "",
6781
+ diagnostics
6782
+ };
6783
+ }
5681
6784
  }
5682
6785
  }
5683
6786
  fillEquipment();
@@ -5694,6 +6797,7 @@ function createReferenceIndex(catalog, materialize) {
5694
6797
  } : null,
5695
6798
  equipment: equipmentRefs,
5696
6799
  remaining,
6800
+ ...equipmentSpan ? { equipmentSpan } : {},
5697
6801
  diagnostics
5698
6802
  };
5699
6803
  }
@@ -6612,6 +7716,48 @@ var CurrentRoundMetric = class {
6612
7716
  value;
6613
7717
  image;
6614
7718
  };
7719
+
7720
+ // src/runtime/time/calculateElapsed.ts
7721
+ function calculateElapsed(timer, now) {
7722
+ let total = 0;
7723
+ for (const span of timer.spans) {
7724
+ const end = span.ended ?? now;
7725
+ total += end - span.started;
7726
+ }
7727
+ return total;
7728
+ }
7729
+ function formatDuration(ms) {
7730
+ const totalSeconds = Math.floor(ms / 1e3);
7731
+ const mins = Math.floor(totalSeconds / 60);
7732
+ const secs = totalSeconds % 60;
7733
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
7734
+ }
7735
+
7736
+ // src/runtime/compiler/metrics/ElapsedMetric.ts
7737
+ var ElapsedMetric = class {
7738
+ /**
7739
+ * @param value Elapsed time in milliseconds
7740
+ * @param sourceBlockKey Block that produced this measurement
7741
+ * @param timestamp When this metrics was created
7742
+ */
7743
+ constructor(value, sourceBlockKey, timestamp) {
7744
+ this.value = value;
7745
+ this.sourceBlockKey = sourceBlockKey;
7746
+ this.timestamp = timestamp;
7747
+ }
7748
+ value;
7749
+ sourceBlockKey;
7750
+ timestamp;
7751
+ type = wodWikiCore.MetricType.Elapsed;
7752
+ origin = "analyzed";
7753
+ unit = "ms";
7754
+ /** Human-readable elapsed time (e.g., "5:03") */
7755
+ get image() {
7756
+ return formatDuration(this.value);
7757
+ }
7758
+ };
7759
+
7760
+ // src/runtime/OutputEmitter.ts
6615
7761
  var OutputEmitter = class {
6616
7762
  _outputStatements = [];
6617
7763
  _outputListeners = /* @__PURE__ */ new Set();
@@ -6897,6 +8043,13 @@ var OutputEmitter = class {
6897
8043
  }
6898
8044
  }
6899
8045
  const recordedSpans = resultFragments.filter((m) => m.type === wodWikiCore.MetricType.Spans && Array.isArray(m.value)).flatMap((m) => m.value).filter((s) => typeof s?.started === "number" && Number.isFinite(s.started));
8046
+ if (recordedSpans.length > 0 && !metrics.some((m) => m.type === wodWikiCore.MetricType.Elapsed)) {
8047
+ const activeElapsedMs = recordedSpans.reduce(
8048
+ (acc, s) => acc + Math.max(0, (typeof s.ended === "number" && Number.isFinite(s.ended) ? s.ended : fallbackEndMs) - s.started),
8049
+ 0
8050
+ );
8051
+ metrics.add(new ElapsedMetric(activeElapsedMs, block.key.toString(), new Date(fallbackEndMs)));
8052
+ }
6900
8053
  const timeSpan = recordedSpans.length > 0 ? new TimeSpan(
6901
8054
  Math.min(...recordedSpans.map((s) => s.started)),
6902
8055
  Math.max(...recordedSpans.map((s) => typeof s.ended === "number" && Number.isFinite(s.ended) ? s.ended : fallbackEndMs))
@@ -8617,22 +9770,6 @@ var ClearChildrenAction = class {
8617
9770
  }
8618
9771
  };
8619
9772
 
8620
- // src/runtime/time/calculateElapsed.ts
8621
- function calculateElapsed(timer, now) {
8622
- let total = 0;
8623
- for (const span of timer.spans) {
8624
- const end = span.ended ?? now;
8625
- total += end - span.started;
8626
- }
8627
- return total;
8628
- }
8629
- function formatDuration(ms) {
8630
- const totalSeconds = Math.floor(ms / 1e3);
8631
- const mins = Math.floor(totalSeconds / 60);
8632
- const secs = totalSeconds % 60;
8633
- return `${mins}:${secs.toString().padStart(2, "0")}`;
8634
- }
8635
-
8636
9773
  // src/runtime/behaviors/CountdownTimerBehavior.ts
8637
9774
  var CountdownTimerBehavior = class {
8638
9775
  constructor(config) {
@@ -11351,27 +12488,6 @@ var ChildSelectionBehavior = class _ChildSelectionBehavior {
11351
12488
  return "timer-active";
11352
12489
  }
11353
12490
  };
11354
- var ElapsedMetric = class {
11355
- /**
11356
- * @param value Elapsed time in milliseconds
11357
- * @param sourceBlockKey Block that produced this measurement
11358
- * @param timestamp When this metrics was created
11359
- */
11360
- constructor(value, sourceBlockKey, timestamp) {
11361
- this.value = value;
11362
- this.sourceBlockKey = sourceBlockKey;
11363
- this.timestamp = timestamp;
11364
- }
11365
- value;
11366
- sourceBlockKey;
11367
- timestamp;
11368
- type = wodWikiCore.MetricType.Elapsed;
11369
- origin = "analyzed";
11370
- /** Human-readable elapsed time (e.g., "5:03") */
11371
- get image() {
11372
- return formatDuration(this.value);
11373
- }
11374
- };
11375
12491
  var TotalMetric = class {
11376
12492
  /**
11377
12493
  * @param value Total wall-clock time in milliseconds
@@ -11517,14 +12633,19 @@ var ReportOutputBehavior = class {
11517
12633
  const timer = readTimer(ctx);
11518
12634
  const round = ctx.getMemoryByTag("round")[0]?.metrics[0];
11519
12635
  const shouldComputeTimeResults = this.config.computeTimeResults ?? true;
12636
+ const reason = ctx.block.completionReason;
12637
+ const earlyTermination = reason === "user-abort" || reason === "forced-pop" || reason === "timer-expired";
12638
+ const effectiveRound = round ? earlyTermination ? { current: Math.max(0, round.current - 1), total: round.total } : round : void 0;
11520
12639
  let completionLabel = this.config.label ?? "Completed";
11521
12640
  if (!this.config.label) {
11522
12641
  if (ctx.block.blockType === "SessionRoot") {
11523
12642
  completionLabel = "Session Completed";
11524
- } else if (round && round.total !== void 0 && round.total > 1) {
11525
- completionLabel = `Completed ${round.total} Round(s)`;
11526
- } else if (round && round.current > 1) {
11527
- completionLabel = `Completed ${round.current} Round(s)`;
12643
+ } else if (effectiveRound && !earlyTermination && effectiveRound.total !== void 0 && effectiveRound.total > 1) {
12644
+ completionLabel = `Completed ${effectiveRound.total} Round(s)`;
12645
+ } else if (effectiveRound && effectiveRound.current > 0) {
12646
+ completionLabel = `Completed ${effectiveRound.current} Round(s)`;
12647
+ } else if (earlyTermination && round) {
12648
+ completionLabel = "Completed 0 Round(s)";
11528
12649
  }
11529
12650
  }
11530
12651
  if (shouldComputeTimeResults) {
@@ -11607,6 +12728,9 @@ var ReportOutputBehavior = class {
11607
12728
  const nowMs = now.getTime();
11608
12729
  const blockKey = ctx.block.key.toString();
11609
12730
  const round = ctx.getMemoryByTag("round")[0]?.metrics[0];
12731
+ const reason = ctx.block.completionReason;
12732
+ const earlyTermination = reason === "user-abort" || reason === "forced-pop" || reason === "timer-expired";
12733
+ const reportedRound = round && earlyTermination ? { current: Math.max(0, round.current - 1), total: round.total } : round;
11610
12734
  if (timer && timer.spans.length > 0) {
11611
12735
  const elapsed = calculateElapsed(timer, nowMs);
11612
12736
  const closedSpans = timer.spans.map(
@@ -11622,8 +12746,8 @@ var ReportOutputBehavior = class {
11622
12746
  new SpansMetric(closedSpans, blockKey, now),
11623
12747
  new SystemTimeMetric(this._now.now(), blockKey)
11624
12748
  );
11625
- if (round) {
11626
- metrics2.add(new CurrentRoundMetric(round.current, round.total, blockKey, now, customRoundLabel));
12749
+ if (reportedRound && reportedRound.current > 0) {
12750
+ metrics2.add(new CurrentRoundMetric(reportedRound.current, reportedRound.total, blockKey, now, customRoundLabel));
11627
12751
  }
11628
12752
  return metrics2;
11629
12753
  }
@@ -11636,8 +12760,8 @@ var ReportOutputBehavior = class {
11636
12760
  new SpansMetric([span], blockKey, now),
11637
12761
  new SystemTimeMetric(this._now.now(), blockKey)
11638
12762
  );
11639
- if (round) {
11640
- metrics.add(new CurrentRoundMetric(round.current, round.total, blockKey, now, customRoundLabel));
12763
+ if (reportedRound && reportedRound.current > 0) {
12764
+ metrics.add(new CurrentRoundMetric(reportedRound.current, reportedRound.total, blockKey, now, customRoundLabel));
11641
12765
  }
11642
12766
  return metrics;
11643
12767
  }
@@ -12928,7 +14052,10 @@ var AnalyticsEngine = class {
12928
14052
  // metadata (effortSlug/discipline/…) through to stored logs.
12929
14053
  {
12930
14054
  type: p.metricType || wodWikiCore.MetricType.Metric,
12931
- image: `${p.value} ${p.unit}`,
14055
+ image: (() => {
14056
+ const displayVal = Number.isInteger(p.value) ? String(p.value) : (Math.round(p.value * 10) / 10).toFixed(1);
14057
+ return p.unit ? `${displayVal} ${p.unit}` : displayVal;
14058
+ })(),
12932
14059
  value: p.value,
12933
14060
  unit: p.unit,
12934
14061
  origin: p.origin ?? "analyzed",
@@ -13190,8 +14317,15 @@ var CalculationRegistry = class {
13190
14317
  if (def.kind === "output" && def.output?.unit && def.output.unit !== "auto") {
13191
14318
  for (const variant of def.variants) {
13192
14319
  for (const nodeId of outputNodeIds(def)) {
14320
+ const outNode = variant.nodes[nodeId];
13193
14321
  const dim = variant.nodeDims?.[nodeId];
13194
- if (dim) validateOutputUnit(dim, def.output.unit);
14322
+ if (outNode && (outNode.kind === "wql" || astHasWql(outNode.ast, variant))) {
14323
+ if (!getUnit(def.output.unit)) {
14324
+ throw new CalcRegistrationError(`Calc ${def.id}: Unknown output unit: ${def.output.unit}`);
14325
+ }
14326
+ } else if (dim) {
14327
+ validateOutputUnit(dim, def.output.unit);
14328
+ }
13195
14329
  }
13196
14330
  }
13197
14331
  }
@@ -13223,8 +14357,14 @@ var CalculationRegistry = class {
13223
14357
  const env = this.staticEnv(siblingRefDim);
13224
14358
  let dim = inferDim(ast, env);
13225
14359
  if (node.unit) {
13226
- validateOutputUnit(dim, node.unit);
13227
- if (AUTHORITATIVE_CASTS[node.unit]) dim = DIM_ZERO;
14360
+ if (astHasWql(ast, variant)) {
14361
+ const unitDef = getUnit(node.unit);
14362
+ if (!unitDef) throw new CalcRegistrationError(`Unknown output unit: ${node.unit}`);
14363
+ dim = AUTHORITATIVE_CASTS[node.unit] ? DIM_ZERO : unitDef.dim;
14364
+ } else {
14365
+ validateOutputUnit(dim, node.unit);
14366
+ if (AUTHORITATIVE_CASTS[node.unit]) dim = DIM_ZERO;
14367
+ }
13228
14368
  }
13229
14369
  nodeDims[nodeId] = dim;
13230
14370
  return dim;
@@ -13281,6 +14421,30 @@ function outputNodeIds(def) {
13281
14421
  if (!nodeId) return [];
13282
14422
  return Array.isArray(nodeId) ? nodeId : [nodeId];
13283
14423
  }
14424
+ function astHasWql(node, variant, seen = /* @__PURE__ */ new Set()) {
14425
+ if (!node) return false;
14426
+ switch (node.kind) {
14427
+ case "wql":
14428
+ return true;
14429
+ case "ref": {
14430
+ if (seen.has(node.name)) return false;
14431
+ const target = variant.nodes[node.name];
14432
+ if (!target) return false;
14433
+ if (target.kind === "wql") return true;
14434
+ const next = new Set(seen);
14435
+ next.add(node.name);
14436
+ return astHasWql(target.ast, variant, next);
14437
+ }
14438
+ case "unary":
14439
+ return astHasWql(node.arg, variant, seen);
14440
+ case "binary":
14441
+ return astHasWql(node.left, variant, seen) || astHasWql(node.right, variant, seen);
14442
+ case "call":
14443
+ return node.args.some((arg) => astHasWql(arg, variant, seen));
14444
+ default:
14445
+ return false;
14446
+ }
14447
+ }
13284
14448
 
13285
14449
  // src/analytics/calc/engine.ts
13286
14450
  var CalcEngine = class {
@@ -14443,7 +15607,7 @@ var STORE_CALCS = [
14443
15607
  value: expr("value", "daily * (daily / daily)")
14444
15608
  }
14445
15609
  }],
14446
- output: { nodeId: "value", key: "calc.sleep", unit: "pts", label: "Sleep (h)" }
15610
+ output: { nodeId: "value", key: "calc.sleep", unit: "h", label: "Sleep (h)" }
14447
15611
  },
14448
15612
  {
14449
15613
  id: "hrv",
@@ -14459,7 +15623,7 @@ var STORE_CALCS = [
14459
15623
  value: expr("value", "daily * (daily / daily)")
14460
15624
  }
14461
15625
  }],
14462
- output: { nodeId: "value", key: "calc.hrv", unit: "pts", label: "HRV (ms)" }
15626
+ output: { nodeId: "value", key: "calc.hrv", unit: "ms", label: "HRV (ms)" }
14463
15627
  },
14464
15628
  {
14465
15629
  // Readiness composite: soreness (inverted) 40%, sleep 30%, HRV 30%,
@@ -15006,7 +16170,7 @@ var LabelComposer = class {
15006
16170
  static getIdentityText(metrics) {
15007
16171
  const logicKeywords = ["AMRAP", "EMOM", "TABATA", "FOR TIME"];
15008
16172
  const identityFragments = metrics.filter((f) => {
15009
- if (f.type === wodWikiCore.MetricType.Duration || f.type === wodWikiCore.MetricType.Rounds || f.type === wodWikiCore.MetricType.Resistance || f.type === wodWikiCore.MetricType.Distance || f.type === wodWikiCore.MetricType.Lap || f.type === wodWikiCore.MetricType.Group) {
16173
+ if (f.type === wodWikiCore.MetricType.Duration || f.type === wodWikiCore.MetricType.Rounds || f.type === wodWikiCore.MetricType.Resistance || f.type === wodWikiCore.MetricType.Distance || f.type === wodWikiCore.MetricType.Lap || f.type === wodWikiCore.MetricType.Group || f.type === wodWikiCore.MetricType.Equipment) {
15010
16174
  return false;
15011
16175
  }
15012
16176
  const val = (f.image || f.value?.toString() || "").toUpperCase();
@@ -15126,6 +16290,7 @@ var AmrapLogicStrategy = class {
15126
16290
  mode: "countdown",
15127
16291
  label
15128
16292
  }));
16293
+ builder.declareExit("immediate");
15129
16294
  }
15130
16295
  };
15131
16296
  var IntervalLogicStrategy = class {
@@ -16441,7 +17606,9 @@ function readNextPreviewText(blocks) {
16441
17606
  const merged = wodWikiCore.MetricContainer.empty(block.key.toString());
16442
17607
  for (const loc of nextLocs) merged.merge(loc.metrics);
16443
17608
  if (merged.length > 0) {
16444
- return metricPresentation.presentGroup([...merged], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim() || null;
17609
+ return dedupePresentedLabels(
17610
+ metricPresentation.presentGroup([...merged], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label)
17611
+ ).join(" ").trim() || null;
16445
17612
  }
16446
17613
  }
16447
17614
  return null;
@@ -16571,7 +17738,9 @@ function projectSessionClock(runtime, options = {}) {
16571
17738
  let subLabels;
16572
17739
  if (!isRestHero && leafEntry && leafEntry.displayRows.length > 1) {
16573
17740
  const lines = leafEntry.displayRows.map(
16574
- (row) => metricPresentation.presentGroup([...row], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label).filter(Boolean).join(" ").trim()
17741
+ (row) => dedupePresentedLabels(
17742
+ metricPresentation.presentGroup([...row], "timer-subtitle").filter((t2) => t2.visible).map((t2) => t2.label)
17743
+ ).join(" ").trim()
16575
17744
  ).filter(Boolean);
16576
17745
  if (lines.length > 0) subLabels = lines;
16577
17746
  }
@@ -16761,14 +17930,7 @@ function formatStatementLabel(statement) {
16761
17930
  [...statement.metrics].filter((m) => m.type !== wodWikiCore.MetricType.Hint),
16762
17931
  "timer-subtitle"
16763
17932
  ).filter((t2) => t2.visible).map((t2) => t2.label.trim()).filter(Boolean);
16764
- const deduped = [];
16765
- for (const label of labels) {
16766
- const lower = label.toLowerCase();
16767
- const prev = deduped[deduped.length - 1]?.toLowerCase();
16768
- if (prev && (prev === lower || prev.endsWith(` ${lower}`))) continue;
16769
- deduped.push(label);
16770
- }
16771
- const presented = deduped.join(" ").trim();
17933
+ const presented = dedupePresentedLabels(labels).join(" ").trim();
16772
17934
  return presented || statement.text?.trim() || "Step";
16773
17935
  }
16774
17936
  function synthesizeWorkoutFormat(script) {
@@ -17507,6 +18669,7 @@ exports.composeMulUnit = composeMulUnit;
17507
18669
  exports.compoundName = compoundName;
17508
18670
  exports.computeColumnLabel = computeColumnLabel;
17509
18671
  exports.computeLabel = computeLabel;
18672
+ exports.computeWhiteboardEnterAction = computeWhiteboardEnterAction;
17510
18673
  exports.computeWorkloadRollups = computeWorkloadRollups;
17511
18674
  exports.convertScalar = convertScalar;
17512
18675
  exports.createAnalyticsEngineForBlock = createAnalyticsEngineForBlock;
@@ -17527,6 +18690,7 @@ exports.createRpeLabelsTable = createRpeLabelsTable;
17527
18690
  exports.dailySessionLoads = dailySessionLoads;
17528
18691
  exports.dayBucket = dayBucket;
17529
18692
  exports.dedupeEntitiesByPrecedence = dedupeEntitiesByPrecedence;
18693
+ exports.dedupePresentedLabels = dedupePresentedLabels;
17530
18694
  exports.dialectRegistry = dialectRegistry;
17531
18695
  exports.dialectStack = dialectStack;
17532
18696
  exports.diffStatement = diffStatement;
@@ -17594,6 +18758,7 @@ exports.isDimensionless = isDimensionless;
17594
18758
  exports.isEffortDiscipline = isEffortDiscipline;
17595
18759
  exports.isFragmentTag = isFragmentTag;
17596
18760
  exports.isRequiredCountdownLocked = isRequiredCountdownLocked;
18761
+ exports.isRoundsHeaderLine = isRoundsHeaderLine;
17597
18762
  exports.isTimeLikeMetric = isTimeLikeMetric;
17598
18763
  exports.isWithinThreshold = isWithinThreshold;
17599
18764
  exports.levenshteinDistance = levenshteinDistance;