@bitcobblers/wod-wiki-lang 0.61.2259 → 0.62.2260

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.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { UnitRegistry, hintsToContainer, hasHint, CONSUMED_HINTS, wallClockNow, TimeSpan, metricPresentation, hintMetric, resolveTagContributions, tagReferenceFor, tagContributionMetrics, tagMarkerType, collectTagReferences, tagMarkerSlugs, getHints } from './chunk-2WQW2LJ3.mjs';
2
- export { CONSUMED_HINTS, CONSUMED_HINT_KEYS, MAX_TAG_CONTRIBUTION_DEPTH, STANDARD_UNITS, TAG_MARKER_PREFIX, TimeSpan, UnitRegistry, UnitSet, buildTooltip, calculateDuration, computeColumnLabel, computeLabel, createBrowserRuntimeNow, createPolicy as createMetricPresentationPolicy, findTagContributionCycles, formatDurationCompact, formatDurationSmart, formatSecondsHHMMSS, formatSecondsMMSS, formatTime, formatTimeHHMMSS, formatTimeMMSS, formatTimePrecise, formatTimestamp, frozenNow, getHints, getRuntimeNowMs, hasHint, hintMetric, hintsToContainer, interpolateSessionClockFrame, isRequiredCountdownLocked, isTimeLikeMetric, metricPresentation, observeSessionClockInputs, projectLiveSessionTelemetry, projectScriptOutline, projectSessionClock, resolveTagContributions, resolveVisualPolarity, roundToTenth, synthesizeWorkoutFormat, tagContributionMetrics, tagMarkerSlug, tagMarkerSlugs, tagMarkerType, wallClockNow } from './chunk-2WQW2LJ3.mjs';
1
+ import { UnitRegistry, hintsToContainer, hasHint, CONSUMED_HINTS, wallClockNow, TimeSpan, metricPresentation, hintMetric, resolveTagContributions, tagReferenceFor, tagContributionMetrics, tagMarkerType, collectTagReferences, tagMarkerSlugs, getHints } from './chunk-74QMDNFW.mjs';
2
+ export { CONSUMED_HINTS, CONSUMED_HINT_KEYS, MAX_TAG_CONTRIBUTION_DEPTH, STANDARD_UNITS, TAG_MARKER_PREFIX, TimeSpan, UnitRegistry, UnitSet, buildTooltip, calculateDuration, computeColumnLabel, computeLabel, createBrowserRuntimeNow, createPolicy as createMetricPresentationPolicy, dedupePresentedLabels, findTagContributionCycles, formatDurationCompact, formatDurationSmart, formatSecondsHHMMSS, formatSecondsMMSS, formatTime, formatTimeHHMMSS, formatTimeMMSS, formatTimePrecise, formatTimestamp, frozenNow, getHints, getRuntimeNowMs, hasHint, hintMetric, hintsToContainer, interpolateSessionClockFrame, isRequiredCountdownLocked, isTimeLikeMetric, metricPresentation, observeSessionClockInputs, projectLiveSessionTelemetry, projectScriptOutline, projectSessionClock, resolveTagContributions, resolveVisualPolarity, roundToTenth, synthesizeWorkoutFormat, tagContributionMetrics, tagMarkerSlug, tagMarkerSlugs, tagMarkerType, wallClockNow } from './chunk-74QMDNFW.mjs';
3
3
  import { MetricType, MetricContainer, BlockKey, REFERENCE_METADATA_KEY, ParsedCodeStatement, getReferenceMetadata, TAG_REFERENCE_METADATA_KEY, parseFrontmatter, getScalar, OutputStatement, valueKindOf, normalizeFieldPath } from '@bitcobblers/wod-wiki-core';
4
4
  import { LRParser } from '@lezer/lr';
5
5
  import { LRLanguage, LanguageSupport, syntaxTree } from '@codemirror/language';
@@ -1072,6 +1072,7 @@ var DurationMetric = class {
1072
1072
  seconds;
1073
1073
  original;
1074
1074
  type = MetricType.Duration;
1075
+ unit = "ms";
1075
1076
  /**
1076
1077
  * Determines the intended timer direction based on value and modifiers.
1077
1078
  * - If forceCountUp is true (^ modifier), always returns 'up'
@@ -1294,6 +1295,24 @@ function classifyStatements(facts, references) {
1294
1295
  }
1295
1296
  function equipmentMeta(resolution, authored, meta2) {
1296
1297
  if (resolution.matched !== "split" || !resolution.remaining) return meta2;
1298
+ if (resolution.equipmentSpan) {
1299
+ const leadingTrim = authored.length - authored.trimStart().length;
1300
+ const start = leadingTrim + resolution.equipmentSpan.start;
1301
+ const end = leadingTrim + resolution.equipmentSpan.end;
1302
+ const raw2 = meta2.raw.slice(start, end);
1303
+ const length2 = raw2.length;
1304
+ if (length2 > 0) {
1305
+ return {
1306
+ ...meta2,
1307
+ startOffset: meta2.startOffset + start,
1308
+ endOffset: meta2.startOffset + end,
1309
+ length: length2,
1310
+ columnStart: meta2.columnStart + start,
1311
+ columnEnd: meta2.columnStart + end,
1312
+ raw: raw2
1313
+ };
1314
+ }
1315
+ }
1297
1316
  const prefixEnd = authored.trimEnd().length - resolution.remaining.length;
1298
1317
  if (prefixEnd <= 0) return meta2;
1299
1318
  const raw = meta2.raw.slice(0, prefixEnd).trimEnd();
@@ -1324,7 +1343,7 @@ function applyReferenceResolution(pairs, fact, references) {
1324
1343
  }
1325
1344
  if (resolution.equipment.length > 0) {
1326
1345
  const eqMeta = equipmentMeta(resolution, authored, meta2);
1327
- const eqSource = resolution.matched === "split" ? eqMeta.raw : resolution.matched === "explicit" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
1346
+ const eqSource = resolution.matched === "split" ? eqMeta.raw : resolution.matched === "explicit" || resolution.matched === "whole" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
1328
1347
  result.push({
1329
1348
  metrics: new EquipmentMetric(
1330
1349
  resolution.equipment.map((ref) => ref.slug),
@@ -1332,7 +1351,8 @@ function applyReferenceResolution(pairs, fact, references) {
1332
1351
  refs: resolution.equipment,
1333
1352
  source: eqSource,
1334
1353
  matched: resolution.matched,
1335
- diagnostics: resolution.diagnostics
1354
+ diagnostics: resolution.diagnostics,
1355
+ ...resolution.matched === "whole" ? { origin: "compiler" } : {}
1336
1356
  }
1337
1357
  ),
1338
1358
  meta: eqMeta
@@ -1450,14 +1470,15 @@ function resolveFusedEffortReferences(statements, references) {
1450
1470
  }
1451
1471
  if (resolution.equipment.length > 0) {
1452
1472
  const eqMeta = meta2 ? equipmentMeta(resolution, authored, meta2) : void 0;
1453
- const eqSource = resolution.matched === "split" && eqMeta ? eqMeta.raw : authored;
1473
+ const eqSource = resolution.matched === "split" && eqMeta ? eqMeta.raw : resolution.matched === "whole" || resolution.matched === "explicit" ? resolution.equipment.map((ref) => ref.label).join(", ") : authored;
1454
1474
  const eqMetric = new EquipmentMetric(
1455
1475
  resolution.equipment.map((ref) => ref.slug),
1456
1476
  {
1457
1477
  refs: resolution.equipment,
1458
1478
  source: eqSource,
1459
1479
  matched: resolution.matched,
1460
- diagnostics: resolution.diagnostics
1480
+ diagnostics: resolution.diagnostics,
1481
+ ...resolution.matched === "whole" ? { origin: "compiler" } : {}
1461
1482
  }
1462
1483
  );
1463
1484
  nextMetrics.push(eqMetric);
@@ -2969,6 +2990,69 @@ tagHighlighter([
2969
2990
  { tag: tags.invalid, class: "tok-invalid" },
2970
2991
  { tag: tags.punctuation, class: "tok-punctuation" }
2971
2992
  ]);
2993
+
2994
+ // src/effort-registry/fuzzyMatch.ts
2995
+ function levenshteinDistance(a, b) {
2996
+ if (a === b) return 0;
2997
+ if (a.length === 0) return b.length;
2998
+ if (b.length === 0) return a.length;
2999
+ if (a.length > b.length) {
3000
+ const tmp = a;
3001
+ a = b;
3002
+ b = tmp;
3003
+ }
3004
+ const m = a.length;
3005
+ const n = b.length;
3006
+ let prev = new Uint32Array(m + 1);
3007
+ let curr = new Uint32Array(m + 1);
3008
+ for (let i = 0; i <= m; i++) {
3009
+ prev[i] = i;
3010
+ }
3011
+ for (let j = 1; j <= n; j++) {
3012
+ curr[0] = j;
3013
+ const bj = b.charCodeAt(j - 1);
3014
+ for (let i = 1; i <= m; i++) {
3015
+ const cost = a.charCodeAt(i - 1) === bj ? 0 : 1;
3016
+ curr[i] = Math.min(
3017
+ prev[i] + 1,
3018
+ // deletion
3019
+ curr[i - 1] + 1,
3020
+ // insertion
3021
+ prev[i - 1] + cost
3022
+ // substitution
3023
+ );
3024
+ }
3025
+ const swap = prev;
3026
+ prev = curr;
3027
+ curr = swap;
3028
+ }
3029
+ return prev[m];
3030
+ }
3031
+ function normalizeForFuzzy(input) {
3032
+ return input.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").replace(/[-_]+/g, " ").trim().replace(/\s+/g, " ");
3033
+ }
3034
+ function isWithinThreshold(a, b, threshold) {
3035
+ const na = normalizeForFuzzy(a);
3036
+ const nb = normalizeForFuzzy(b);
3037
+ if (na === nb) return true;
3038
+ if (Math.abs(na.length - nb.length) > threshold) return false;
3039
+ return levenshteinDistance(na, nb) <= threshold;
3040
+ }
3041
+ function findBestFuzzyMatch(query, candidates, threshold) {
3042
+ const nq = normalizeForFuzzy(query);
3043
+ let best = null;
3044
+ for (const candidate of candidates) {
3045
+ const nc = normalizeForFuzzy(candidate);
3046
+ if (Math.abs(nq.length - nc.length) > threshold) continue;
3047
+ const distance = levenshteinDistance(nq, nc);
3048
+ if (distance > threshold) continue;
3049
+ if (!best || distance < best.distance) {
3050
+ best = { target: candidate, distance };
3051
+ if (distance === 0) break;
3052
+ }
3053
+ }
3054
+ return best;
3055
+ }
2972
3056
  var whiteboardScriptSnippets = [
2973
3057
  {
2974
3058
  name: "emom",
@@ -3071,6 +3155,8 @@ var STRUCTURE_KEYWORD_DISPLAY = {
3071
3155
  "for time": "FOR TIME",
3072
3156
  rest: "Rest"
3073
3157
  };
3158
+ var COUNT_QUALIFIER_WORDS = /^(reps?|rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
3159
+ var ROUNDS_QUALIFIER_WORDS = /^(rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
3074
3160
  var PRIMARY_UNIT_BOOST = {
3075
3161
  kg: 30,
3076
3162
  lb: 29,
@@ -3081,18 +3167,25 @@ var PRIMARY_UNIT_BOOST = {
3081
3167
  ft: 24,
3082
3168
  kcal: 23
3083
3169
  };
3170
+ function clampBoost(value) {
3171
+ return Math.max(-99, Math.min(99, Math.round(value)));
3172
+ }
3084
3173
  function unitCompletions(units, dimension, preferredSet) {
3085
3174
  return units.toArray().filter((def) => !dimension || def.dimension === dimension).flatMap((def) => {
3086
3175
  const canonicalLower = def.canonical.toLowerCase();
3087
3176
  const canonicalBoost = preferredSet?.has(canonicalLower) ? 40 : PRIMARY_UNIT_BOOST[canonicalLower] ?? 20;
3177
+ const canonicalOption = {
3178
+ label: def.canonical,
3179
+ detail: def.dimension,
3180
+ type: "unit",
3181
+ section: COMPLETION_SECTIONS.units,
3182
+ boost: canonicalBoost
3183
+ };
3184
+ if (def.aliases.length > 0) {
3185
+ completionAliases.set(canonicalOption, def.aliases.map((a) => a.toLowerCase()));
3186
+ }
3088
3187
  return [
3089
- {
3090
- label: def.canonical,
3091
- detail: def.dimension,
3092
- type: "unit",
3093
- section: COMPLETION_SECTIONS.units,
3094
- boost: canonicalBoost
3095
- },
3188
+ canonicalOption,
3096
3189
  ...def.aliases.map((alias) => ({
3097
3190
  label: alias,
3098
3191
  detail: def.dimension,
@@ -3103,6 +3196,33 @@ function unitCompletions(units, dimension, preferredSet) {
3103
3196
  ];
3104
3197
  });
3105
3198
  }
3199
+ function makeCountQualifiers(includeRounds, needsLeadingSpace, ladderDetail) {
3200
+ const space = needsLeadingSpace ? " " : "";
3201
+ const items = [
3202
+ {
3203
+ label: "reps",
3204
+ detail: ladderDetail ?? "count",
3205
+ type: "unit",
3206
+ section: COMPLETION_SECTIONS.units,
3207
+ apply: `${space}reps`,
3208
+ boost: ladderDetail ? 45 : 38
3209
+ }
3210
+ ];
3211
+ completionAliases.set(items[0], ["rep"]);
3212
+ if (includeRounds) {
3213
+ const roundsOpt = {
3214
+ label: "rounds",
3215
+ detail: "rounds",
3216
+ type: "unit",
3217
+ section: COMPLETION_SECTIONS.units,
3218
+ apply: `${space}rounds`,
3219
+ boost: 37
3220
+ };
3221
+ completionAliases.set(roundsOpt, ["round", "rd", "rds", "set", "sets"]);
3222
+ items.push(roundsOpt);
3223
+ }
3224
+ return items;
3225
+ }
3106
3226
  function titleCase(word) {
3107
3227
  return word.toLowerCase().replace(/(^|[\s])([a-z])/g, (_, lead, ch) => lead + ch.toUpperCase());
3108
3228
  }
@@ -3174,7 +3294,7 @@ function toCompletions(values, detail, quoteValues = false) {
3174
3294
  detail: value.detail ?? (value.label && value.label !== value.value ? value.value : detail),
3175
3295
  type: completionType,
3176
3296
  info: value.info,
3177
- ...value.boost !== void 0 ? { boost: value.boost } : {},
3297
+ ...value.boost !== void 0 ? { boost: clampBoost(value.boost) } : {},
3178
3298
  ...resolvedSection ? { section: resolvedSection } : {}
3179
3299
  };
3180
3300
  if (value.aliases?.length) {
@@ -3183,8 +3303,228 @@ function toCompletions(values, detail, quoteValues = false) {
3183
3303
  return item;
3184
3304
  });
3185
3305
  }
3186
- function appendCreateEffortOption(pool, typedPhrase, onCreateEffort) {
3187
- if (!onCreateEffort) return pool;
3306
+ function damerauDistance(a, b) {
3307
+ if (a === b) return 0;
3308
+ const m = a.length;
3309
+ const n = b.length;
3310
+ if (m === 0) return n;
3311
+ if (n === 0) return m;
3312
+ const dp = Array.from({ length: m + 1 }, () => new Array(n + 1).fill(0));
3313
+ for (let i = 0; i <= m; i++) dp[i][0] = i;
3314
+ for (let j = 0; j <= n; j++) dp[0][j] = j;
3315
+ for (let i = 1; i <= m; i++) {
3316
+ for (let j = 1; j <= n; j++) {
3317
+ const cost = a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1;
3318
+ let val = Math.min(
3319
+ dp[i - 1][j] + 1,
3320
+ dp[i][j - 1] + 1,
3321
+ dp[i - 1][j - 1] + cost
3322
+ );
3323
+ if (i > 1 && j > 1 && a[i - 1] === b[j - 2] && a[i - 2] === b[j - 1]) {
3324
+ val = Math.min(val, dp[i - 2][j - 2] + 1);
3325
+ }
3326
+ dp[i][j] = val;
3327
+ }
3328
+ }
3329
+ return dp[m][n];
3330
+ }
3331
+ function isOrderedSubsequence(needle, haystack) {
3332
+ if (needle.length < 3 || haystack.length > 28) return false;
3333
+ if (needle[0] !== haystack[0]) return false;
3334
+ let i = 0;
3335
+ for (let j = 0; j < haystack.length && i < needle.length; j++) {
3336
+ if (needle[i] === haystack[j]) i++;
3337
+ }
3338
+ return i === needle.length;
3339
+ }
3340
+ function dedupeStrings(values) {
3341
+ const seen = /* @__PURE__ */ new Set();
3342
+ const out = [];
3343
+ for (const v of values) {
3344
+ if (!v || seen.has(v)) continue;
3345
+ seen.add(v);
3346
+ out.push(v);
3347
+ }
3348
+ return out;
3349
+ }
3350
+ function buildCatalogIndex(rawEfforts, rawEquipment) {
3351
+ const eqCompletions = toCompletions(rawEquipment, "equipment");
3352
+ const eqTermsBySlug = /* @__PURE__ */ new Map();
3353
+ const equipmentLabelBySlug = /* @__PURE__ */ new Map();
3354
+ const equipment = rawEquipment.map((opt, idx) => {
3355
+ const label = opt.label ?? opt.value;
3356
+ const rawTerms = [label, opt.value, ...opt.aliases ?? []];
3357
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
3358
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
3359
+ const slugLower = opt.value.toLowerCase();
3360
+ eqTermsBySlug.set(slugLower, dedupeStrings([...terms, ...words]));
3361
+ equipmentLabelBySlug.set(slugLower, label);
3362
+ const base = eqCompletions[idx];
3363
+ return {
3364
+ kind: "equipment",
3365
+ option: opt,
3366
+ label,
3367
+ labelLower: label.toLowerCase(),
3368
+ terms,
3369
+ words,
3370
+ equipmentSlugs: [slugLower],
3371
+ equipmentTerms: [],
3372
+ completion: {
3373
+ ...base,
3374
+ section: resolveSection(opt.section) ?? COMPLETION_SECTIONS.equipment
3375
+ }
3376
+ };
3377
+ });
3378
+ const effortCompletions = toCompletions(rawEfforts, "effort");
3379
+ const efforts = rawEfforts.map((opt, idx) => {
3380
+ const label = opt.label ?? opt.value;
3381
+ const rawTerms = [label, opt.value, ...opt.aliases ?? []];
3382
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
3383
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
3384
+ const equipmentSlugs = (opt.equipment ?? []).map((s) => s.toLowerCase());
3385
+ const equipmentTerms = dedupeStrings(
3386
+ equipmentSlugs.flatMap((slug) => eqTermsBySlug.get(slug) ?? [normalizeForFuzzy(slug)])
3387
+ );
3388
+ return {
3389
+ kind: "effort",
3390
+ option: opt,
3391
+ label,
3392
+ labelLower: label.toLowerCase(),
3393
+ terms,
3394
+ words,
3395
+ equipmentSlugs,
3396
+ equipmentTerms,
3397
+ completion: effortCompletions[idx]
3398
+ };
3399
+ });
3400
+ return { efforts, equipment, equipmentLabelBySlug };
3401
+ }
3402
+ function bestTokenScore(qTok, entry) {
3403
+ let best = 0;
3404
+ for (const term of entry.terms) {
3405
+ if (term === qTok) return 100;
3406
+ if (term.startsWith(qTok)) best = Math.max(best, 86);
3407
+ else if (qTok.length >= 2 && term.includes(qTok)) best = Math.max(best, 58);
3408
+ else if (isOrderedSubsequence(qTok, term)) best = Math.max(best, 32);
3409
+ }
3410
+ for (const word of entry.words) {
3411
+ if (word === qTok) best = Math.max(best, 95);
3412
+ else if (word.startsWith(qTok)) best = Math.max(best, 82);
3413
+ else if (qTok.length >= 2 && word.includes(qTok)) best = Math.max(best, 55);
3414
+ else if (qTok.length >= 3) {
3415
+ const maxDist = qTok.length <= 4 ? 1 : 2;
3416
+ if (Math.abs(word.length - qTok.length) <= maxDist) {
3417
+ const dist = damerauDistance(qTok, word);
3418
+ if (dist <= maxDist) best = Math.max(best, 46 - dist * 10);
3419
+ } else if (qTok.length >= 4 && word.length > qTok.length) {
3420
+ const prefix = word.slice(0, qTok.length);
3421
+ const dist = damerauDistance(qTok, prefix);
3422
+ if (dist <= 1) best = Math.max(best, 38);
3423
+ }
3424
+ if (isOrderedSubsequence(qTok, word)) best = Math.max(best, 30);
3425
+ }
3426
+ }
3427
+ for (const eqTerm of entry.equipmentTerms) {
3428
+ if (eqTerm === qTok) best = Math.max(best, 76);
3429
+ else if (qTok.length >= 2 && eqTerm.startsWith(qTok)) best = Math.max(best, 66);
3430
+ else if (qTok.length >= 4 && Math.abs(eqTerm.length - qTok.length) <= 1) {
3431
+ if (damerauDistance(qTok, eqTerm) <= 1) best = Math.max(best, 34);
3432
+ }
3433
+ }
3434
+ return best;
3435
+ }
3436
+ function scoreCatalogEntry(query, entry) {
3437
+ const normQuery = normalizeForFuzzy(query);
3438
+ if (!normQuery) return 1;
3439
+ const qTokens = normQuery.split(" ").filter(Boolean);
3440
+ if (qTokens.length === 0) return 1;
3441
+ let wholeBonus = 0;
3442
+ for (const term of entry.terms) {
3443
+ if (term === normQuery) {
3444
+ wholeBonus = Math.max(wholeBonus, 140);
3445
+ } else if (term.startsWith(normQuery)) {
3446
+ wholeBonus = Math.max(wholeBonus, 115);
3447
+ } else if (normQuery.length >= 2 && term.includes(normQuery)) {
3448
+ wholeBonus = Math.max(wholeBonus, 80);
3449
+ }
3450
+ }
3451
+ let tokenSum = 0;
3452
+ for (const qTok of qTokens) {
3453
+ const tokenScore = bestTokenScore(qTok, entry);
3454
+ if (tokenScore === 0) return null;
3455
+ tokenSum += tokenScore;
3456
+ }
3457
+ const labelWordCount = normalizeForFuzzy(entry.label).split(" ").filter(Boolean).length;
3458
+ const extraWordPenalty = Math.max(0, labelWordCount - qTokens.length) * 3;
3459
+ return wholeBonus + Math.round(tokenSum / qTokens.length) - extraWordPenalty + (entry.option.boost ?? 0);
3460
+ }
3461
+ function scoreCompletionOption(query, option) {
3462
+ const normQuery = normalizeForFuzzy(query);
3463
+ if (!normQuery) return 1;
3464
+ const qTokens = normQuery.split(" ").filter(Boolean);
3465
+ if (qTokens.length === 0) return 1;
3466
+ const aliases = completionAliases.get(option) ?? [];
3467
+ const rawTerms = [
3468
+ option.label,
3469
+ typeof option.apply === "string" ? option.apply : "",
3470
+ ...aliases
3471
+ ].filter(Boolean);
3472
+ const terms = dedupeStrings(rawTerms.map((t2) => normalizeForFuzzy(t2)));
3473
+ const words = dedupeStrings(terms.flatMap((t2) => t2.split(" ")));
3474
+ let wholeBonus = 0;
3475
+ for (const term of terms) {
3476
+ if (term === normQuery) wholeBonus = Math.max(wholeBonus, 130);
3477
+ else if (term.startsWith(normQuery)) wholeBonus = Math.max(wholeBonus, 105);
3478
+ else if (normQuery.length >= 2 && term.includes(normQuery)) wholeBonus = Math.max(wholeBonus, 70);
3479
+ }
3480
+ let tokenSum = 0;
3481
+ for (const qTok of qTokens) {
3482
+ let best = 0;
3483
+ for (const term of terms) {
3484
+ if (term === qTok) best = Math.max(best, 100);
3485
+ else if (term.startsWith(qTok)) best = Math.max(best, 85);
3486
+ else if (qTok.length >= 2 && term.includes(qTok)) best = Math.max(best, 55);
3487
+ }
3488
+ for (const word of words) {
3489
+ if (word === qTok) best = Math.max(best, 95);
3490
+ else if (word.startsWith(qTok)) best = Math.max(best, 80);
3491
+ else if (qTok.length >= 3) {
3492
+ const maxDist = qTok.length <= 4 ? 1 : 2;
3493
+ if (Math.abs(word.length - qTok.length) <= maxDist) {
3494
+ const dist = damerauDistance(qTok, word);
3495
+ if (dist <= maxDist) best = Math.max(best, 44 - dist * 10);
3496
+ }
3497
+ }
3498
+ }
3499
+ if (best === 0) return null;
3500
+ tokenSum += best;
3501
+ }
3502
+ return wholeBonus + Math.round(tokenSum / qTokens.length) + (option.boost ?? 0);
3503
+ }
3504
+ function findExactEntry(phrase, entries) {
3505
+ const norm = normalizeForFuzzy(phrase);
3506
+ if (!norm) return void 0;
3507
+ return entries.find((entry) => entry.terms.includes(norm));
3508
+ }
3509
+ function isExactAliasOrTermSplit(phrase, index) {
3510
+ const norm = normalizeForFuzzy(phrase);
3511
+ if (!norm) return false;
3512
+ if (index.efforts.some((e) => e.terms.includes(norm))) return true;
3513
+ const words = norm.split(" ").filter(Boolean);
3514
+ for (let k = 1; k < words.length; k++) {
3515
+ const left = words.slice(0, k).join(" ");
3516
+ const right = words.slice(k).join(" ");
3517
+ const effortLeft = index.efforts.some((e) => e.terms.includes(left));
3518
+ const eqRight = index.equipment.some((e) => e.terms.includes(right));
3519
+ if (effortLeft && eqRight) return true;
3520
+ const eqLeft = index.equipment.some((e) => e.terms.includes(left));
3521
+ const effortRight = index.efforts.some((e) => e.terms.includes(right));
3522
+ if (eqLeft && effortRight) return true;
3523
+ }
3524
+ return false;
3525
+ }
3526
+ function appendCreateEffortOption(pool, typedPhrase, onCreateEffort, suppressCreate = false) {
3527
+ if (!onCreateEffort || suppressCreate) return pool;
3188
3528
  const trimmed = typedPhrase.trim();
3189
3529
  if (trimmed.length < 3 || !/^[A-Za-z][A-Za-z0-9 -]*$/.test(trimmed)) return pool;
3190
3530
  const lower = trimmed.toLowerCase();
@@ -3256,8 +3596,10 @@ function suppliedPropertyKeys(context) {
3256
3596
  }
3257
3597
  return keys;
3258
3598
  }
3259
- function isUnitFragment(context, fragment, units) {
3260
- return fragment.firstChild?.name === "Effort" && units.has(context.state.doc.sliceString(fragment.from, fragment.to));
3599
+ function isUnitOrQualifierFragment(context, fragment, units) {
3600
+ if (fragment.firstChild?.name !== "Effort") return false;
3601
+ const raw = context.state.doc.sliceString(fragment.from, fragment.to).trim();
3602
+ return units.has(raw) || COUNT_QUALIFIER_WORDS.test(raw);
3261
3603
  }
3262
3604
  function trailingEffortRun(context, statement, units) {
3263
3605
  const nodes = statement?.name === "Block" ? statement.getChildren("Fragment") : [];
@@ -3267,9 +3609,154 @@ function trailingEffortRun(context, statement, units) {
3267
3609
  while (start > 0 && nodes[start - 1].firstChild?.name === "Effort") start--;
3268
3610
  const run = nodes.slice(start, end);
3269
3611
  let firstEffort = 0;
3270
- while (firstEffort < run.length - 1 && isUnitFragment(context, run[firstEffort], units)) firstEffort++;
3612
+ while (firstEffort < run.length && isUnitOrQualifierFragment(context, run[firstEffort], units)) firstEffort++;
3271
3613
  return run.slice(firstEffort);
3272
3614
  }
3615
+ function detectRepLadder(context, nodes, qtyIdx) {
3616
+ if (qtyIdx < 2 || nodes[qtyIdx]?.firstChild?.name !== "Quantity") {
3617
+ return { isLadder: false, rungCount: 1 };
3618
+ }
3619
+ const qtyText = context.state.doc.sliceString(nodes[qtyIdx].from, nodes[qtyIdx].to);
3620
+ if (!/^\d+$/.test(qtyText)) return { isLadder: false, rungCount: 1 };
3621
+ let rungCount = 1;
3622
+ let j = qtyIdx;
3623
+ 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))) {
3624
+ rungCount++;
3625
+ j -= 2;
3626
+ }
3627
+ return { isLadder: rungCount >= 2, rungCount };
3628
+ }
3629
+ function analyzeStatementBefore(context, nodes, uptoEnd, index, units) {
3630
+ let hasRounds = false;
3631
+ let hasEffort = false;
3632
+ let hasEquipment = false;
3633
+ const wordChunks = [];
3634
+ for (let i = 0; i < uptoEnd; i++) {
3635
+ const frag = nodes[i];
3636
+ const kind = frag.firstChild?.name;
3637
+ if (kind === "Rounds" || kind === "RoundScheme") {
3638
+ hasRounds = true;
3639
+ continue;
3640
+ }
3641
+ if (kind === "Quantity") {
3642
+ if (detectRepLadder(context, nodes, i).isLadder) hasRounds = true;
3643
+ continue;
3644
+ }
3645
+ if (kind === "Effort") {
3646
+ const raw = context.state.doc.sliceString(frag.from, frag.to).trim();
3647
+ if (raw === "-" || raw === "/" || raw === "|") continue;
3648
+ if (ROUNDS_QUALIFIER_WORDS.test(raw)) {
3649
+ hasRounds = true;
3650
+ continue;
3651
+ }
3652
+ if (COUNT_QUALIFIER_WORDS.test(raw) || units.has(raw)) continue;
3653
+ wordChunks.push(raw);
3654
+ }
3655
+ }
3656
+ if (wordChunks.length > 0) {
3657
+ const phrase = wordChunks.join(" ");
3658
+ const norm = normalizeForFuzzy(phrase);
3659
+ const exactEq = findExactEntry(phrase, index.equipment);
3660
+ const exactEff = findExactEntry(phrase, index.efforts);
3661
+ if (exactEq && !exactEff) {
3662
+ hasEquipment = true;
3663
+ } else if (exactEff) {
3664
+ hasEffort = true;
3665
+ const eqWords = exactEff.equipmentSlugs.some((slug) => {
3666
+ const label = index.equipmentLabelBySlug.get(slug);
3667
+ return label ? norm.includes(normalizeForFuzzy(label)) : false;
3668
+ });
3669
+ if (eqWords) hasEquipment = true;
3670
+ } else if (isExactAliasOrTermSplit(phrase, index)) {
3671
+ hasEffort = true;
3672
+ hasEquipment = true;
3673
+ } else {
3674
+ hasEffort = true;
3675
+ }
3676
+ }
3677
+ return { hasRounds, hasEffort, hasEquipment };
3678
+ }
3679
+ function phraseHasExplicitEquipment(phrase, index) {
3680
+ const norm = normalizeForFuzzy(phrase);
3681
+ if (!norm) return false;
3682
+ const words = norm.split(" ").filter(Boolean);
3683
+ for (let k = 1; k < words.length; k++) {
3684
+ const left = words.slice(0, k).join(" ");
3685
+ const right = words.slice(k).join(" ");
3686
+ if (index.efforts.some((e) => e.terms.includes(left)) && index.equipment.some((e) => e.terms.includes(right))) {
3687
+ return true;
3688
+ }
3689
+ if (index.equipment.some((e) => e.terms.includes(left)) && index.efforts.some((e) => e.terms.includes(right))) {
3690
+ return true;
3691
+ }
3692
+ }
3693
+ const exactEq = findExactEntry(phrase, index.equipment);
3694
+ if (!exactEq) {
3695
+ for (let k = 1; k < words.length; k++) {
3696
+ const left = words.slice(0, k).join(" ");
3697
+ const right = words.slice(k).join(" ");
3698
+ if (index.equipment.some((e) => e.terms.includes(right)) && !index.equipment.some((e) => e.terms.includes(left))) {
3699
+ return true;
3700
+ }
3701
+ }
3702
+ }
3703
+ const exactEff = findExactEntry(phrase, index.efforts);
3704
+ if (!exactEff) return false;
3705
+ return exactEff.equipmentSlugs.some((slug) => {
3706
+ const label = index.equipmentLabelBySlug.get(slug);
3707
+ if (label && norm.includes(normalizeForFuzzy(label))) return true;
3708
+ const eqEntry = index.equipment.find((eq) => eq.equipmentSlugs[0] === slug);
3709
+ return eqEntry ? eqEntry.terms.some((t2) => t2.length >= 2 && words.includes(t2)) : false;
3710
+ });
3711
+ }
3712
+ function specializedEffortsForBase(phrase, index) {
3713
+ const normBase = normalizeForFuzzy(phrase);
3714
+ const baseWords = normBase.split(" ").filter(Boolean);
3715
+ if (baseWords.length === 0) return [];
3716
+ const exactCurrent = findExactEntry(phrase, index.efforts);
3717
+ const results = [];
3718
+ for (const entry of index.efforts) {
3719
+ if (entry.labelLower === phrase.toLowerCase()) continue;
3720
+ if (exactCurrent && entry.labelLower === exactCurrent.labelLower) continue;
3721
+ const matchesAllWords = baseWords.every((w) => entry.words.includes(w) || entry.terms.some((t2) => t2.includes(w)));
3722
+ if (!matchesAllWords) continue;
3723
+ const eqNames = entry.equipmentSlugs.map((slug) => index.equipmentLabelBySlug.get(slug)).filter((name2) => Boolean(name2));
3724
+ const detail = eqNames.length > 0 ? `${entry.completion.detail ?? "effort"} \xB7 ${eqNames.join(", ")}` : entry.completion.detail;
3725
+ results.push({
3726
+ ...entry.completion,
3727
+ detail,
3728
+ boost: clampBoost((entry.option.boost ?? 0) + 18),
3729
+ apply: (view, _completion, from, to) => {
3730
+ view.dispatch({
3731
+ changes: { from, to, insert: entry.label },
3732
+ selection: { anchor: from + entry.label.length },
3733
+ userEvent: "input.complete"
3734
+ });
3735
+ }
3736
+ });
3737
+ }
3738
+ return results;
3739
+ }
3740
+ function specializedEffortsForEquipment(eqEntry, index) {
3741
+ const eqSlug = eqEntry.equipmentSlugs[0];
3742
+ const results = [];
3743
+ for (const entry of index.efforts) {
3744
+ const usesEq = entry.equipmentSlugs.includes(eqSlug) || eqEntry.terms.some((t2) => t2.length >= 2 && entry.words.includes(t2));
3745
+ if (!usesEq) continue;
3746
+ results.push({
3747
+ ...entry.completion,
3748
+ boost: clampBoost((entry.option.boost ?? 0) + 20),
3749
+ apply: (view, _completion, from, to) => {
3750
+ view.dispatch({
3751
+ changes: { from, to, insert: entry.label },
3752
+ selection: { anchor: from + entry.label.length },
3753
+ userEvent: "input.complete"
3754
+ });
3755
+ }
3756
+ });
3757
+ }
3758
+ return results;
3759
+ }
3273
3760
  function inNode(context, names) {
3274
3761
  for (let node = syntaxTree(context.state).resolveInner(context.pos, -1); node; node = node.parent) {
3275
3762
  if (names.has(node.name)) return true;
@@ -3278,6 +3765,56 @@ function inNode(context, names) {
3278
3765
  }
3279
3766
  var ALWAYS_SUPPRESSED_NODES = /* @__PURE__ */ new Set(["Text", "textComment", "MetricObject"]);
3280
3767
  var HEADING_NODES = /* @__PURE__ */ new Set(["Heading", "heading"]);
3768
+ function completeParenthesizedRounds(before, pos) {
3769
+ if (!/\([^)\n]*$/.test(before)) return void 0;
3770
+ const openIdx = before.lastIndexOf("(");
3771
+ const inner = before.slice(openIdx + 1);
3772
+ if (inner.includes("-")) return null;
3773
+ const m = /^(\s*)(\d+)([ \t]*)([A-Za-z]*)$/.exec(inner);
3774
+ if (!m) return null;
3775
+ const hasSpace = m[3].length > 0;
3776
+ const typedWord = m[4];
3777
+ const lead = hasSpace ? "" : " ";
3778
+ const wordFrom = pos - typedWord.length;
3779
+ const makeParenApply = (word) => (view, _c, from, to) => {
3780
+ const hasClose = view.state.doc.sliceString(to, to + 1) === ")";
3781
+ const insert = `${lead}${word}${hasClose ? "" : ")"}`;
3782
+ view.dispatch({
3783
+ changes: { from, to, insert },
3784
+ selection: { anchor: from + insert.length + (hasClose ? 1 : 0) },
3785
+ userEvent: "input.complete"
3786
+ });
3787
+ };
3788
+ const options = [
3789
+ {
3790
+ label: "rounds",
3791
+ detail: "rounds",
3792
+ type: "unit",
3793
+ section: COMPLETION_SECTIONS.units,
3794
+ boost: 45,
3795
+ apply: makeParenApply("rounds")
3796
+ },
3797
+ {
3798
+ label: "reps",
3799
+ detail: "count",
3800
+ type: "unit",
3801
+ section: COMPLETION_SECTIONS.units,
3802
+ boost: 40,
3803
+ apply: makeParenApply("reps")
3804
+ }
3805
+ ];
3806
+ completionAliases.set(options[0], ["round", "rd", "rds", "set", "sets"]);
3807
+ completionAliases.set(options[1], ["rep"]);
3808
+ if (typedWord.length > 0) {
3809
+ 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);
3810
+ return scored.length > 0 ? { from: wordFrom, options: scored, filter: false } : null;
3811
+ }
3812
+ return {
3813
+ from: wordFrom,
3814
+ options,
3815
+ validFor: /^[A-Za-z]*$/
3816
+ };
3817
+ }
3281
3818
  function whiteboardScriptCompletionSource(options = {}) {
3282
3819
  const sportWords = dialectWords(options.sport);
3283
3820
  const keywords = structureKeywords();
@@ -3327,6 +3864,21 @@ function whiteboardScriptCompletionSource(options = {}) {
3327
3864
  });
3328
3865
  }
3329
3866
  }
3867
+ const restTag = /^[A-Za-z0-9-]*/.exec(line.text.slice(pos - line.from))[0];
3868
+ if (restTag.length > 0) {
3869
+ const lower = word.toLowerCase();
3870
+ const filteredTags = tagOptions.filter((opt) => {
3871
+ if (opt.type === "create") return true;
3872
+ const applyLower = typeof opt.apply === "string" ? opt.apply.toLowerCase() : "";
3873
+ return opt.label.toLowerCase().includes(lower) || applyLower.includes(lower);
3874
+ });
3875
+ return filteredTags.length > 0 ? {
3876
+ from: pos - word.length,
3877
+ to: pos + restTag.length,
3878
+ options: filteredTags,
3879
+ filter: false
3880
+ } : null;
3881
+ }
3330
3882
  return {
3331
3883
  from: pos - word.length,
3332
3884
  options: tagOptions,
@@ -3334,6 +3886,8 @@ function whiteboardScriptCompletionSource(options = {}) {
3334
3886
  };
3335
3887
  }
3336
3888
  if (inNode(context, HEADING_NODES)) return null;
3889
+ const parenResult = completeParenthesizedRounds(before, pos);
3890
+ if (parenResult !== void 0) return parenResult;
3337
3891
  const statement = currentStatement(context);
3338
3892
  if (statement?.name === "Property") {
3339
3893
  const keyNode = statement.firstChild;
@@ -3345,17 +3899,12 @@ function whiteboardScriptCompletionSource(options = {}) {
3345
3899
  if (source) return { from: value && !value.type.isError ? value.from : pos, options: toCompletions(await source(), key, true) };
3346
3900
  return null;
3347
3901
  }
3348
- const efforts = options.efforts ? toCompletions(await options.efforts(), "effort") : [];
3349
- const equipmentPrefixes = options.equipment ? (await options.equipment()).map((eq) => ({
3350
- label: eq.label ?? eq.value,
3351
- apply: `${eq.label ?? eq.value} `,
3352
- detail: eq.detail ?? "equipment",
3353
- type: "text",
3354
- section: resolveSection(eq.section) ?? COMPLETION_SECTIONS.equipment,
3355
- ...eq.boost !== void 0 ? { boost: eq.boost } : {}
3356
- })) : [];
3357
- const postQuantityEffortOptions = [...efforts, ...equipmentPrefixes, ...sportWords];
3358
- const effortOptions = [...keywords, ...efforts, ...equipmentPrefixes, ...sportWords];
3902
+ const rawEfforts = options.efforts ? await options.efforts() : [];
3903
+ const rawEquipment = options.equipment ? await options.equipment() : [];
3904
+ const catalog = buildCatalogIndex(rawEfforts, rawEquipment);
3905
+ const efforts = catalog.efforts.map((e) => e.completion);
3906
+ const equipmentOpts = catalog.equipment.map((e) => e.completion);
3907
+ const missingLineElements = [...efforts, ...equipmentOpts, ...sportWords];
3359
3908
  if (/^[ \t]*[A-Za-z][A-Za-z0-9]*$/.test(before)) {
3360
3909
  const supplied = suppliedPropertyKeys(context);
3361
3910
  const propertyOptions = COMPLETION_PROPERTY_KEYS.filter((key) => !supplied.has(key)).map((key) => ({
@@ -3370,24 +3919,38 @@ function whiteboardScriptCompletionSource(options = {}) {
3370
3919
  ...snippets,
3371
3920
  ...startKeywords,
3372
3921
  ...efforts,
3922
+ ...equipmentOpts,
3373
3923
  ...sportWords,
3374
3924
  ...propertyOptions
3375
3925
  ];
3376
3926
  const typedRaw = before.trimStart();
3377
3927
  const typedStart = typedRaw.toLowerCase();
3378
- const hasAliasHit = typedStart.length >= 2 && effortOptions.some((opt) => completionMatchesWord(opt, typedStart) === "alias");
3379
- if (hasAliasHit) {
3380
- const matched = allStartOptions.filter((opt) => completionMatchesWord(opt, typedStart) !== null);
3928
+ const hasSubstringOrPrefix = allStartOptions.some((opt) => {
3929
+ const m = completionMatchesWord(opt, typedStart);
3930
+ return m === "prefix" || m === "word";
3931
+ });
3932
+ 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);
3933
+ 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);
3934
+ const restWord = /^[A-Za-z0-9-]*/.exec(line.text.slice(pos - line.from))[0];
3935
+ const hasAliasOrFuzzyOnly = (fuzzyEfforts.length > 0 || fuzzyEquipment.length > 0) && (!hasSubstringOrPrefix || typedStart.length >= 2 && fuzzyEfforts.some((e) => completionMatchesWord(e.opt, typedStart) === "alias"));
3936
+ if (hasAliasOrFuzzyOnly || restWord.length > 0) {
3937
+ const otherMatched = [...snippets, ...startKeywords, ...sportWords, ...propertyOptions].filter((opt) => scoreCompletionOption(typedRaw, opt) !== null);
3938
+ const matched = [
3939
+ ...otherMatched,
3940
+ ...fuzzyEfforts.map((x) => x.opt),
3941
+ ...fuzzyEquipment.map((x) => x.opt)
3942
+ ];
3943
+ const suppressCreate = isExactAliasOrTermSplit(typedRaw, catalog);
3381
3944
  return {
3382
3945
  from: pos - typedRaw.length,
3383
- options: appendCreateEffortOption(matched, typedRaw, options.onCreateEffort),
3384
- filter: false,
3385
- validFor: /^[A-Za-z]*$/
3946
+ ...restWord.length > 0 ? { to: pos + restWord.length } : {},
3947
+ options: appendCreateEffortOption(matched, typedRaw, options.onCreateEffort, suppressCreate),
3948
+ filter: false
3386
3949
  };
3387
3950
  }
3388
3951
  return {
3389
3952
  from: pos - typedRaw.length,
3390
- options: appendCreateEffortOption(allStartOptions, typedRaw, options.onCreateEffort),
3953
+ options: appendCreateEffortOption(allStartOptions, typedRaw, options.onCreateEffort, isExactAliasOrTermSplit(typedRaw, catalog)),
3391
3954
  validFor: /^[A-Za-z]*$/
3392
3955
  };
3393
3956
  }
@@ -3395,71 +3958,340 @@ function whiteboardScriptCompletionSource(options = {}) {
3395
3958
  let end = nodes.length;
3396
3959
  while (end > 0 && nodes[end - 1].from >= pos) end--;
3397
3960
  const last = nodes[end - 1];
3398
- const completingWord = last?.firstChild?.name === "Effort" && last.to === pos;
3399
- const quantityFragment = completingWord ? nodes[end - 2] : last;
3961
+ const completingWord = last?.firstChild?.name === "Effort" && last.from < pos && pos <= last.to;
3962
+ const qtyIdx = completingWord ? end - 2 : end - 1;
3963
+ const quantityFragment = qtyIdx >= 0 ? nodes[qtyIdx] : void 0;
3400
3964
  const quantity = quantityFragment?.firstChild?.name === "Quantity" ? quantityFragment.firstChild : null;
3401
3965
  const incompleteAction = statement?.name === "Block" && statement.getChildren("Fragment").some(
3402
3966
  (fragment) => fragment.firstChild?.name === "Action" && fragment.from < (quantity?.from ?? pos) && !context.state.doc.sliceString(fragment.from, fragment.to).includes(":")
3403
3967
  );
3404
3968
  if (quantity && !incompleteAction) {
3969
+ const hasAtSign = Boolean(quantity.getChild("AtSign"));
3970
+ const rawQty = context.state.doc.sliceString(quantity.from, quantity.to);
3971
+ const isWholeInteger = !hasAtSign && /^\d+$/.test(rawQty);
3972
+ const isWildcard = !hasAtSign && rawQty === "?";
3973
+ const isGlued = completingWord ? last.from === quantityFragment.to : pos === quantityFragment.to;
3974
+ const hasTrailingSpace = !completingWord && pos > quantityFragment.to && /[ \t]$/.test(before);
3975
+ const ladder = !hasAtSign ? detectRepLadder(context, nodes, qtyIdx) : { isLadder: false, rungCount: 1 };
3976
+ const prefixLine = analyzeStatementBefore(context, nodes, qtyIdx, catalog, units);
3405
3977
  const preferredSet = new Set(
3406
3978
  (options.preferredUnits?.() ?? []).map((u) => u.toLowerCase())
3407
3979
  );
3408
- const unitPool = unitCompletions(
3409
- units,
3410
- quantity.getChild("AtSign") ? "mass" : void 0,
3411
- preferredSet.size > 0 ? preferredSet : void 0
3412
- );
3413
- const wordText = completingWord ? context.state.doc.sliceString(last.from, pos).toLowerCase() : "";
3414
- const hasAliasHit = wordText.length >= 2 && postQuantityEffortOptions.some((opt) => completionMatchesWord(opt, wordText) === "alias");
3415
- const pool = [...unitPool, ...postQuantityEffortOptions];
3416
- if (hasAliasHit && completingWord) {
3417
- const rawPhrase = context.state.doc.sliceString(last.from, pos);
3980
+ if (hasAtSign) {
3981
+ const massPool = unitCompletions(units, "mass", preferredSet.size > 0 ? preferredSet : void 0);
3982
+ const wordText = completingWord ? context.state.doc.sliceString(last.from, pos) : "";
3983
+ if (completingWord && (last.to > pos || wordText.length >= 2)) {
3984
+ const hasAlias = massPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias");
3985
+ if (hasAlias || last.to > pos) {
3986
+ return {
3987
+ from: last.from,
3988
+ ...last.to > pos ? { to: last.to } : {},
3989
+ options: massPool.filter((opt) => scoreCompletionOption(wordText, opt) !== null),
3990
+ filter: false
3991
+ };
3992
+ }
3993
+ }
3418
3994
  return {
3419
- from: last.from,
3420
- options: appendCreateEffortOption(
3421
- pool.filter((opt) => completionMatchesWord(opt, wordText) !== null),
3422
- rawPhrase,
3423
- options.onCreateEffort
3424
- ),
3425
- filter: false,
3995
+ from: completingWord ? last.from : pos,
3996
+ options: massPool,
3426
3997
  validFor: /^[A-Za-z]*$/
3427
3998
  };
3428
3999
  }
3429
- return {
3430
- from: completingWord ? last.from : pos,
3431
- options: completingWord ? appendCreateEffortOption(pool, context.state.doc.sliceString(last.from, pos), options.onCreateEffort) : pool,
3432
- validFor: /^[A-Za-z]*$/
3433
- };
4000
+ if (ladder.isLadder) {
4001
+ const ladderDetail = ladder.rungCount >= 3 ? `rep scheme (${ladder.rungCount} rounds)` : "rep scheme";
4002
+ const ladderReps = makeCountQualifiers(false, isGlued, ladderDetail);
4003
+ if (hasTrailingSpace) {
4004
+ return {
4005
+ from: pos,
4006
+ options: [
4007
+ ...missingLineElements,
4008
+ ...keywords.filter((k) => k.label === "FOR TIME")
4009
+ ]
4010
+ };
4011
+ }
4012
+ if (completingWord) {
4013
+ const wordText = context.state.doc.sliceString(last.from, pos);
4014
+ const pool = isGlued ? ladderReps : [...isGlued ? [] : makeCountQualifiers(false, false, ladderDetail), ...missingLineElements, ...keywords.filter((k) => k.label === "FOR TIME")];
4015
+ const matched = scorePhrasePool(wordText, pool, catalog, options.onCreateEffort, !isGlued);
4016
+ return matched.length > 0 ? {
4017
+ from: last.from,
4018
+ ...last.to > pos ? { to: last.to } : {},
4019
+ options: matched,
4020
+ filter: false
4021
+ } : null;
4022
+ }
4023
+ return {
4024
+ from: pos,
4025
+ options: ladderReps,
4026
+ validFor: /^[A-Za-z]*$/
4027
+ };
4028
+ }
4029
+ if (isGlued) {
4030
+ const countOpts = isWholeInteger || isWildcard ? makeCountQualifiers(isWholeInteger && !prefixLine.hasRounds, true) : [];
4031
+ const unitPool = [
4032
+ ...countOpts,
4033
+ ...unitCompletions(units, void 0, preferredSet.size > 0 ? preferredSet : void 0)
4034
+ ];
4035
+ if (completingWord) {
4036
+ const wordText = context.state.doc.sliceString(last.from, pos);
4037
+ const hasAliasHit = unitPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias");
4038
+ if (hasAliasHit || last.to > pos) {
4039
+ return {
4040
+ from: last.from,
4041
+ ...last.to > pos ? { to: last.to } : {},
4042
+ options: unitPool.filter((opt) => scoreCompletionOption(wordText, opt) !== null),
4043
+ filter: false
4044
+ };
4045
+ }
4046
+ }
4047
+ return {
4048
+ from: completingWord ? last.from : pos,
4049
+ options: unitPool,
4050
+ validFor: /^[A-Za-z]*$/
4051
+ };
4052
+ }
4053
+ if (hasTrailingSpace) {
4054
+ if (!prefixLine.hasEffort) {
4055
+ return missingLineElements.length > 0 ? { from: pos, options: missingLineElements } : null;
4056
+ }
4057
+ if (!prefixLine.hasEquipment) {
4058
+ return equipmentOpts.length > 0 ? { from: pos, options: equipmentOpts } : null;
4059
+ }
4060
+ return null;
4061
+ }
4062
+ if (completingWord) {
4063
+ const wordText = context.state.doc.sliceString(last.from, pos);
4064
+ const unitCandidates = [
4065
+ ...isWholeInteger || isWildcard ? makeCountQualifiers(isWholeInteger && !prefixLine.hasRounds, false) : [],
4066
+ ...unitCompletions(units, void 0, preferredSet.size > 0 ? preferredSet : void 0)
4067
+ ];
4068
+ const matchingUnits = unitCandidates.filter((opt) => {
4069
+ const norm = normalizeForFuzzy(wordText);
4070
+ const labelLower = opt.label.toLowerCase();
4071
+ const aliases = completionAliases.get(opt) ?? [];
4072
+ return labelLower.startsWith(norm) || aliases.some((a) => a.startsWith(norm));
4073
+ });
4074
+ const elementPool = prefixLine.hasEffort && !prefixLine.hasEquipment ? equipmentOpts : prefixLine.hasEffort ? [] : missingLineElements;
4075
+ const effortMatches = scoreCatalogList(wordText, prefixLine.hasEffort ? [] : catalog.efforts);
4076
+ const equipmentMatches = scoreCatalogList(wordText, prefixLine.hasEquipment ? [] : catalog.equipment);
4077
+ 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);
4078
+ const combined = [
4079
+ ...matchingUnits,
4080
+ ...effortMatches.map((x) => x.opt),
4081
+ ...equipmentMatches.map((x) => x.opt),
4082
+ ...sportMatches
4083
+ ];
4084
+ const hasAliasHit = elementPool.some((opt) => completionMatchesWord(opt, wordText.toLowerCase()) === "alias") || matchingUnits.length > 0 || effortMatches.length + equipmentMatches.length > 0;
4085
+ const suppressCreate = isExactAliasOrTermSplit(wordText, catalog);
4086
+ return hasAliasHit || combined.length > 0 || options.onCreateEffort && !prefixLine.hasEffort ? {
4087
+ from: last.from,
4088
+ ...last.to > pos ? { to: last.to } : {},
4089
+ options: !prefixLine.hasEffort ? appendCreateEffortOption(combined, wordText, options.onCreateEffort, suppressCreate) : combined,
4090
+ filter: false
4091
+ } : null;
4092
+ }
3434
4093
  }
3435
4094
  if (before.trim() === "") {
3436
- return { from: pos, options: [...snippets, ...startKeywords, ...efforts, ...sportWords] };
4095
+ return { from: pos, options: [...snippets, ...startKeywords, ...efforts, ...equipmentOpts, ...sportWords] };
3437
4096
  }
4097
+ const effortRun = trailingEffortRun(context, statement, units);
3438
4098
  if (word.length === 0 && /[ \t]$/.test(before)) {
3439
- const effortRun = trailingEffortRun(context, statement, units);
3440
- const last2 = effortRun[effortRun.length - 1];
3441
- if (last2 && !isUnitFragment(context, last2, units)) return null;
3442
- return { from: pos, options: effortOptions };
4099
+ if (effortRun.length === 0) {
4100
+ return { from: pos, options: [...keywords, ...missingLineElements] };
4101
+ }
4102
+ const runFirst = effortRun[0];
4103
+ const runLast = effortRun[effortRun.length - 1];
4104
+ const phraseFrom = runFirst.from;
4105
+ const phraseText = context.state.doc.sliceString(phraseFrom, runLast.to).trim();
4106
+ if (phraseHasExplicitEquipment(phraseText, catalog)) return null;
4107
+ const exactEq = findExactEntry(phraseText, catalog.equipment);
4108
+ if (exactEq) {
4109
+ const dedicated = specializedEffortsForEquipment(exactEq, catalog);
4110
+ const dedicatedLabels = new Set(dedicated.map((d) => d.label.toLowerCase()));
4111
+ const appendedEfforts = catalog.efforts.filter((e) => !dedicatedLabels.has(e.labelLower)).map((e) => ({
4112
+ ...e.completion,
4113
+ apply: (view, _c, from, to) => {
4114
+ const existing = view.state.doc.sliceString(from, to);
4115
+ const insert = `${existing}${e.label}`;
4116
+ view.dispatch({
4117
+ changes: { from, to, insert },
4118
+ selection: { anchor: from + insert.length },
4119
+ userEvent: "input.complete"
4120
+ });
4121
+ }
4122
+ }));
4123
+ const allEqOptions = [...dedicated, ...appendedEfforts];
4124
+ return allEqOptions.length > 0 ? { from: phraseFrom, options: allEqOptions, filter: false } : null;
4125
+ }
4126
+ const specialized = specializedEffortsForBase(phraseText, catalog);
4127
+ const suffixEquipment = catalog.equipment.map((eq) => ({
4128
+ ...eq.completion,
4129
+ apply: (view, _completion, from, to) => {
4130
+ const existing = view.state.doc.sliceString(from, to);
4131
+ const insert = `${existing}${eq.label}`;
4132
+ view.dispatch({
4133
+ changes: { from, to, insert },
4134
+ selection: { anchor: from + insert.length },
4135
+ userEvent: "input.complete"
4136
+ });
4137
+ }
4138
+ }));
4139
+ const combined = [...specialized, ...suffixEquipment];
4140
+ return combined.length > 0 ? { from: phraseFrom, options: combined, filter: false } : null;
3443
4141
  }
3444
4142
  if (word.length > 0 && /^[A-Za-z][A-Za-z0-9'-]*$/.test(word)) {
3445
- const effortRun = trailingEffortRun(context, statement, units);
3446
- const first = effortRun[0];
3447
- const last2 = effortRun[effortRun.length - 1];
3448
- if (!first || !last2 || last2.to < pos) return null;
3449
- const rawPhrase = context.state.doc.sliceString(first.from, pos);
3450
- const typed = rawPhrase.toLowerCase();
3451
- const compatible = effortOptions.filter((option) => completionMatchesWord(option, typed) !== null);
3452
- const usesAlias = compatible.some((option) => completionMatchesWord(option, typed) === "alias");
4143
+ if (effortRun.length === 0) return null;
4144
+ const phraseFrom = effortRun[0].from;
4145
+ const runLast = effortRun[effortRun.length - 1];
4146
+ if (runLast.to < pos) return null;
4147
+ const rawPhrase = context.state.doc.sliceString(phraseFrom, pos);
4148
+ const isSingleWord = effortRun.length === 1;
4149
+ const scoredOptions = [];
4150
+ const seenOutcome = /* @__PURE__ */ new Set();
4151
+ const pushScored = (option, score, outcomeKey) => {
4152
+ if (seenOutcome.has(outcomeKey)) return;
4153
+ seenOutcome.add(outcomeKey);
4154
+ scoredOptions.push({ option, score });
4155
+ };
4156
+ const strategy1Efforts = scoreCatalogList(rawPhrase, catalog.efforts);
4157
+ for (const { entry, opt, score } of strategy1Efforts) {
4158
+ const eqLabels = entry.equipmentSlugs.map((slug) => catalog.equipmentLabelBySlug.get(slug)).filter((lbl) => Boolean(lbl));
4159
+ const multiTokenUpgrade = !isSingleWord && eqLabels.length > 0;
4160
+ const upgradedDetail = multiTokenUpgrade && !(opt.detail ?? "").toLowerCase().includes(eqLabels[0].toLowerCase()) ? `${opt.detail ?? "effort"} \xB7 includes ${eqLabels.join(", ")}` : opt.detail;
4161
+ pushScored(
4162
+ {
4163
+ ...opt,
4164
+ detail: upgradedDetail,
4165
+ boost: clampBoost(Math.min(75, Math.round(score / 4)) + (multiTokenUpgrade ? 10 : 0)),
4166
+ apply: (view, _completion, from, to) => {
4167
+ view.dispatch({
4168
+ changes: { from, to, insert: entry.label },
4169
+ selection: { anchor: from + entry.label.length },
4170
+ userEvent: "input.complete"
4171
+ });
4172
+ }
4173
+ },
4174
+ score + (multiTokenUpgrade ? 25 : 0),
4175
+ `whole:${entry.labelLower}`
4176
+ );
4177
+ }
4178
+ if (isSingleWord) {
4179
+ for (const { entry, opt, score } of scoreCatalogList(rawPhrase, catalog.equipment)) {
4180
+ pushScored(
4181
+ {
4182
+ ...opt,
4183
+ boost: clampBoost(Math.min(70, Math.round(score / 4))),
4184
+ apply: (view, _completion, from, to) => {
4185
+ view.dispatch({
4186
+ changes: { from, to, insert: entry.label },
4187
+ selection: { anchor: from + entry.label.length },
4188
+ userEvent: "input.complete"
4189
+ });
4190
+ }
4191
+ },
4192
+ score,
4193
+ `eq-whole:${entry.labelLower}`
4194
+ );
4195
+ }
4196
+ for (const kw of [...keywords, ...sportWords]) {
4197
+ const s = scoreCompletionOption(rawPhrase, kw);
4198
+ if (s !== null) pushScored(kw, s, `kw:${kw.label.toLowerCase()}`);
4199
+ }
4200
+ } else {
4201
+ for (let k = 1; k < effortRun.length; k++) {
4202
+ const prefixText = context.state.doc.sliceString(phraseFrom, effortRun[k - 1].to).trim();
4203
+ const suffixFrom = effortRun[k].from;
4204
+ const suffixText = context.state.doc.sliceString(suffixFrom, pos).trim();
4205
+ if (!prefixText || !suffixText) continue;
4206
+ const suffixDelta = suffixFrom - phraseFrom;
4207
+ const prefixIsEq = findExactEntry(prefixText, catalog.equipment);
4208
+ const prefixIsEff = findExactEntry(prefixText, catalog.efforts);
4209
+ if (prefixIsEq) {
4210
+ for (const { entry, opt, score } of scoreCatalogList(suffixText, catalog.efforts)) {
4211
+ if (seenOutcome.has(`whole:${entry.labelLower}`)) continue;
4212
+ if (normalizeForFuzzy(entry.label).includes(normalizeForFuzzy(prefixIsEq.label))) continue;
4213
+ const resultingText = `${prefixText} ${entry.label}`.toLowerCase();
4214
+ if (seenOutcome.has(`whole:${resultingText}`)) continue;
4215
+ const dedicatedEqText = `${prefixIsEq.label} ${entry.label}`.toLowerCase();
4216
+ if (seenOutcome.has(`whole:${dedicatedEqText}`)) continue;
4217
+ pushScored(
4218
+ {
4219
+ ...opt,
4220
+ boost: clampBoost(Math.min(72, Math.round(score / 4))),
4221
+ apply: (view, _completion, from, to) => {
4222
+ view.dispatch({
4223
+ changes: { from: from + suffixDelta, to, insert: entry.label },
4224
+ selection: { anchor: from + suffixDelta + entry.label.length },
4225
+ userEvent: "input.complete"
4226
+ });
4227
+ }
4228
+ },
4229
+ score,
4230
+ `eq-prefix-eff:${entry.labelLower}:${suffixDelta}`
4231
+ );
4232
+ }
4233
+ }
4234
+ const allowEquipmentSuffix = Boolean(prefixIsEff) || !prefixIsEq && suffixText.length >= 2 && (strategy1Efforts.length === 0 || scoreCatalogList(suffixText, catalog.equipment).some((m) => m.score >= 70));
4235
+ if (allowEquipmentSuffix && !prefixIsEq) {
4236
+ for (const { entry, opt, score } of scoreCatalogList(suffixText, catalog.equipment)) {
4237
+ pushScored(
4238
+ {
4239
+ ...opt,
4240
+ detail: opt.detail ?? "Equipment",
4241
+ boost: clampBoost(Math.min(70, Math.round(score / 4))),
4242
+ apply: (view, _completion, from, to) => {
4243
+ view.dispatch({
4244
+ changes: { from: from + suffixDelta, to, insert: entry.label },
4245
+ selection: { anchor: from + suffixDelta + entry.label.length },
4246
+ userEvent: "input.complete"
4247
+ });
4248
+ }
4249
+ },
4250
+ score,
4251
+ `eff-prefix-eq:${entry.labelLower}:${suffixDelta}`
4252
+ );
4253
+ }
4254
+ }
4255
+ }
4256
+ }
4257
+ scoredOptions.sort((a, b) => b.score - a.score);
4258
+ const finalOptions = scoredOptions.map((x) => x.option);
4259
+ const suppressCreate = isExactAliasOrTermSplit(rawPhrase, catalog);
4260
+ const withCreate = appendCreateEffortOption(finalOptions, rawPhrase, options.onCreateEffort, suppressCreate);
4261
+ if (withCreate.length === 0) return null;
3453
4262
  return {
3454
- from: first.from,
3455
- options: appendCreateEffortOption(compatible, rawPhrase, options.onCreateEffort),
3456
- ...usesAlias ? { filter: false } : {},
3457
- validFor: /^[A-Za-z ]*$/
4263
+ from: phraseFrom,
4264
+ ...runLast.to > pos ? { to: runLast.to } : {},
4265
+ options: withCreate,
4266
+ filter: false
3458
4267
  };
3459
4268
  }
3460
4269
  return null;
3461
4270
  };
3462
4271
  }
4272
+ function scoreCatalogList(query, entries) {
4273
+ const scored = [];
4274
+ for (const entry of entries) {
4275
+ const score = scoreCatalogEntry(query, entry);
4276
+ if (score !== null) scored.push({ entry, opt: entry.completion, score });
4277
+ }
4278
+ scored.sort((a, b) => b.score - a.score);
4279
+ return scored;
4280
+ }
4281
+ function scorePhrasePool(query, pool, catalog, onCreateEffort, allowCreate = true) {
4282
+ const scored = [];
4283
+ const effortMap = new Map(catalog.efforts.map((e) => [e.completion, e]));
4284
+ const eqMap = new Map(catalog.equipment.map((e) => [e.completion, e]));
4285
+ for (const opt of pool) {
4286
+ const eff = effortMap.get(opt);
4287
+ const eq = eqMap.get(opt);
4288
+ const score = eff ? scoreCatalogEntry(query, eff) : eq ? scoreCatalogEntry(query, eq) : scoreCompletionOption(query, opt);
4289
+ if (score !== null) scored.push({ opt, score });
4290
+ }
4291
+ scored.sort((a, b) => b.score - a.score);
4292
+ const res = scored.map((x) => x.opt);
4293
+ return allowCreate ? appendCreateEffortOption(res, query, onCreateEffort, isExactAliasOrTermSplit(query, catalog)) : res;
4294
+ }
3463
4295
  function whiteboardScriptCompletion(options = {}) {
3464
4296
  return autocompletion({ override: [whiteboardScriptCompletionSource(options)] });
3465
4297
  }
@@ -3502,6 +4334,196 @@ function whiteboardScript(options) {
3502
4334
  return new LanguageSupport(whiteboardScriptLanguage, whiteboardScriptCompletion(options ?? {}));
3503
4335
  }
3504
4336
 
4337
+ // src/parser/indentation.ts
4338
+ var ROUNDS_QUALIFIER_WORDS2 = /^(rounds?|rds?|sets?|laps?|cycles?|intervals?)$/i;
4339
+ var CONTAINER_KEYWORDS = /* @__PURE__ */ new Set(["amrap", "emom", "tabata"]);
4340
+ function hasAnyErrorNode(node) {
4341
+ let found = false;
4342
+ node.cursor().iterate((cur) => {
4343
+ if (cur.type.isError) {
4344
+ found = true;
4345
+ return false;
4346
+ }
4347
+ return void 0;
4348
+ });
4349
+ return found;
4350
+ }
4351
+ function isRoundsHeaderLine(lineContent) {
4352
+ const trimmed = lineContent.trim();
4353
+ if (!trimmed) return false;
4354
+ const source = `${trimmed}
4355
+ `;
4356
+ const tree = parser.parse(source);
4357
+ if (hasAnyErrorNode(tree.topNode)) return false;
4358
+ const topChildren = [];
4359
+ for (let child = tree.topNode.firstChild; child; child = child.nextSibling) {
4360
+ if (child.name !== "newline") topChildren.push(child);
4361
+ }
4362
+ if (topChildren.length !== 1 || topChildren[0].name !== "Block") return false;
4363
+ const fragments = topChildren[0].getChildren("Fragment");
4364
+ if (fragments.length === 0) return false;
4365
+ let hasRoundsHeader = false;
4366
+ let hasContainerKeyword = false;
4367
+ let hasDuration = false;
4368
+ let hasLeafPayload = false;
4369
+ for (let i = 0; i < fragments.length; i++) {
4370
+ const frag = fragments[i];
4371
+ const kind = frag.firstChild;
4372
+ if (!kind) {
4373
+ hasLeafPayload = true;
4374
+ break;
4375
+ }
4376
+ switch (kind.name) {
4377
+ case "Rounds": {
4378
+ const raw = source.slice(kind.from, kind.to);
4379
+ if (!raw.endsWith(")")) return false;
4380
+ const seq = kind.getChild("Sequence");
4381
+ const idNode = kind.getChild("Identifier");
4382
+ if (!seq) {
4383
+ hasLeafPayload = true;
4384
+ break;
4385
+ }
4386
+ const numbers = seq.getChildren("Number");
4387
+ const idText = idNode ? source.slice(idNode.from, idNode.to) : "";
4388
+ if (numbers.length >= 2 && !idNode) {
4389
+ hasRoundsHeader = true;
4390
+ } else if (numbers.length === 1 && (!idNode || ROUNDS_QUALIFIER_WORDS2.test(idText))) {
4391
+ hasRoundsHeader = true;
4392
+ } else {
4393
+ hasLeafPayload = true;
4394
+ }
4395
+ break;
4396
+ }
4397
+ case "RoundScheme": {
4398
+ hasRoundsHeader = true;
4399
+ break;
4400
+ }
4401
+ case "Duration": {
4402
+ hasDuration = true;
4403
+ break;
4404
+ }
4405
+ case "Quantity": {
4406
+ const hasAtSign = Boolean(kind.getChild("AtSign"));
4407
+ const qtyRaw = source.slice(kind.from, kind.to);
4408
+ const isWholeInt = !hasAtSign && /^\d+$/.test(qtyRaw);
4409
+ if (!isWholeInt) {
4410
+ hasLeafPayload = true;
4411
+ break;
4412
+ }
4413
+ let j = i;
4414
+ let rungCount = 1;
4415
+ 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))) {
4416
+ rungCount++;
4417
+ j += 2;
4418
+ }
4419
+ if (rungCount >= 2) {
4420
+ hasRoundsHeader = true;
4421
+ i = j;
4422
+ 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())) {
4423
+ i++;
4424
+ }
4425
+ break;
4426
+ }
4427
+ 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())) {
4428
+ hasRoundsHeader = true;
4429
+ i++;
4430
+ break;
4431
+ }
4432
+ hasLeafPayload = true;
4433
+ break;
4434
+ }
4435
+ case "Effort": {
4436
+ const raw = source.slice(kind.from, kind.to).trim().toLowerCase();
4437
+ 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") {
4438
+ hasContainerKeyword = true;
4439
+ i++;
4440
+ break;
4441
+ }
4442
+ if (CONTAINER_KEYWORDS.has(raw)) {
4443
+ hasContainerKeyword = true;
4444
+ break;
4445
+ }
4446
+ if (raw === "work" && (hasRoundsHeader || hasDuration)) {
4447
+ break;
4448
+ }
4449
+ hasLeafPayload = true;
4450
+ break;
4451
+ }
4452
+ case "TagRef":
4453
+ case "Text":
4454
+ break;
4455
+ default:
4456
+ hasLeafPayload = true;
4457
+ break;
4458
+ }
4459
+ if (hasLeafPayload) break;
4460
+ }
4461
+ return (hasRoundsHeader || hasContainerKeyword) && !hasLeafPayload;
4462
+ }
4463
+ function computeWhiteboardEnterAction(lineText, fromCol, toCol = fromCol, unit = " ") {
4464
+ const indent = /^[ \t]*/.exec(lineText)[0];
4465
+ const before = lineText.slice(0, fromCol);
4466
+ const after = lineText.slice(toCol);
4467
+ const isCollapsed = fromCol === toCol;
4468
+ if (lineText.trim() === "") {
4469
+ if (indent.length > 0) {
4470
+ return {
4471
+ replaceFromCol: 0,
4472
+ replaceToCol: lineText.length,
4473
+ insert: "\n",
4474
+ cursorOffset: 1
4475
+ };
4476
+ }
4477
+ return {
4478
+ replaceFromCol: fromCol,
4479
+ replaceToCol: toCol,
4480
+ insert: "\n",
4481
+ cursorOffset: 1
4482
+ };
4483
+ }
4484
+ if (/^([ \t]*)([+-])(?![+-])[ \t]*$/.test(lineText) && fromCol >= indent.length + 1) {
4485
+ return {
4486
+ replaceFromCol: 0,
4487
+ replaceToCol: lineText.length,
4488
+ insert: "\n",
4489
+ cursorOffset: 1
4490
+ };
4491
+ }
4492
+ if (isCollapsed && fromCol <= indent.length && after.trim().length > 0) {
4493
+ const keptIndent = indent.slice(0, fromCol);
4494
+ return {
4495
+ replaceFromCol: 0,
4496
+ replaceToCol: fromCol,
4497
+ insert: `
4498
+ ${keptIndent}`,
4499
+ cursorOffset: 1 + keptIndent.length
4500
+ };
4501
+ }
4502
+ const leadingAfterSpaces = /^[ \t]+/.exec(after)?.[0].length ?? 0;
4503
+ const markerMatch = /^([ \t]*)([+-])(?![+-])([ \t]*)(.*)$/.exec(before);
4504
+ if (markerMatch) {
4505
+ const marker = markerMatch[2];
4506
+ const contentBefore = markerMatch[4].trim();
4507
+ const nextPrefix2 = contentBefore.length > 0 ? isRoundsHeaderLine(contentBefore) ? `${indent}${unit}` : `${indent}${marker} ` : indent;
4508
+ return {
4509
+ replaceFromCol: fromCol,
4510
+ replaceToCol: toCol + leadingAfterSpaces,
4511
+ insert: `
4512
+ ${nextPrefix2}`,
4513
+ cursorOffset: 1 + nextPrefix2.length
4514
+ };
4515
+ }
4516
+ const beforeContent = before.slice(indent.length).trim();
4517
+ const nextPrefix = isRoundsHeaderLine(beforeContent) ? `${indent}${unit}` : indent;
4518
+ return {
4519
+ replaceFromCol: fromCol,
4520
+ replaceToCol: toCol + leadingAfterSpaces,
4521
+ insert: `
4522
+ ${nextPrefix}`,
4523
+ cursorOffset: 1 + nextPrefix.length
4524
+ };
4525
+ }
4526
+
3505
4527
  // src/effort-registry/types.ts
3506
4528
  var EFFORT_REGISTRY_ORIGINS = ["bundled", "user"];
3507
4529
  var SEED_PRECEDENCE_RANK = {
@@ -4190,71 +5212,6 @@ function tagCategoryRecordToDocument(category, record) {
4190
5212
  ...Object.keys(widgets).length > 0 ? { widgets } : {}
4191
5213
  });
4192
5214
  }
4193
-
4194
- // src/effort-registry/fuzzyMatch.ts
4195
- function levenshteinDistance(a, b) {
4196
- if (a === b) return 0;
4197
- if (a.length === 0) return b.length;
4198
- if (b.length === 0) return a.length;
4199
- if (a.length > b.length) {
4200
- const tmp = a;
4201
- a = b;
4202
- b = tmp;
4203
- }
4204
- const m = a.length;
4205
- const n = b.length;
4206
- let prev = new Uint32Array(m + 1);
4207
- let curr = new Uint32Array(m + 1);
4208
- for (let i = 0; i <= m; i++) {
4209
- prev[i] = i;
4210
- }
4211
- for (let j = 1; j <= n; j++) {
4212
- curr[0] = j;
4213
- const bj = b.charCodeAt(j - 1);
4214
- for (let i = 1; i <= m; i++) {
4215
- const cost = a.charCodeAt(i - 1) === bj ? 0 : 1;
4216
- curr[i] = Math.min(
4217
- prev[i] + 1,
4218
- // deletion
4219
- curr[i - 1] + 1,
4220
- // insertion
4221
- prev[i - 1] + cost
4222
- // substitution
4223
- );
4224
- }
4225
- const swap = prev;
4226
- prev = curr;
4227
- curr = swap;
4228
- }
4229
- return prev[m];
4230
- }
4231
- function normalizeForFuzzy(input) {
4232
- return input.toLowerCase().replace(/[^\p{L}\p{N}\s-]/gu, " ").replace(/[-_]+/g, " ").trim().replace(/\s+/g, " ");
4233
- }
4234
- function isWithinThreshold(a, b, threshold) {
4235
- const na = normalizeForFuzzy(a);
4236
- const nb = normalizeForFuzzy(b);
4237
- if (na === nb) return true;
4238
- if (Math.abs(na.length - nb.length) > threshold) return false;
4239
- return levenshteinDistance(na, nb) <= threshold;
4240
- }
4241
- function findBestFuzzyMatch(query, candidates, threshold) {
4242
- const nq = normalizeForFuzzy(query);
4243
- let best = null;
4244
- for (const candidate of candidates) {
4245
- const nc = normalizeForFuzzy(candidate);
4246
- if (Math.abs(nq.length - nc.length) > threshold) continue;
4247
- const distance = levenshteinDistance(nq, nc);
4248
- if (distance > threshold) continue;
4249
- if (!best || distance < best.distance) {
4250
- best = { target: candidate, distance };
4251
- if (distance === 0) break;
4252
- }
4253
- }
4254
- return best;
4255
- }
4256
-
4257
- // src/effort-registry/EffortResolver.ts
4258
5215
  function normalizeSlug(label) {
4259
5216
  return normalizeForFuzzy(label).replace(/\s+/g, "-");
4260
5217
  }
@@ -4789,6 +5746,14 @@ function buildExactIndex(entities) {
4789
5746
  }
4790
5747
  const topTier = direct.filter((candidate) => resolveEntityRank(candidate) === maxRank);
4791
5748
  if (topTier.length === 1) return { entity: topTier[0], ambiguous: [] };
5749
+ const trimmedLower = key.trim().toLowerCase();
5750
+ const slugified = normalizeForFuzzy(key).replace(/\s+/g, "-");
5751
+ const exactSlugMatches = topTier.filter(
5752
+ (candidate) => candidate.slug.toLowerCase() === trimmedLower || candidate.slug.toLowerCase() === slugified
5753
+ );
5754
+ if (exactSlugMatches.length === 1) {
5755
+ return { entity: exactSlugMatches[0], ambiguous: [] };
5756
+ }
4792
5757
  return { entity: null, ambiguous: topTier };
4793
5758
  }
4794
5759
  };
@@ -4811,7 +5776,7 @@ function createReferenceIndex(catalog, materialize) {
4811
5776
  const dedupedEquipment = dedupeEntitiesByPrecedence(catalog.equipment ?? []);
4812
5777
  const efforts = buildExactIndex(catalog.efforts ?? []);
4813
5778
  const equipment = buildExactIndex(dedupedEquipment);
4814
- 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);
5779
+ 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);
4815
5780
  const materializer = materialize ?? ((effort) => ({
4816
5781
  effort,
4817
5782
  definition: effort,
@@ -4899,6 +5864,7 @@ function createReferenceIndex(catalog, materialize) {
4899
5864
  let remaining = "";
4900
5865
  let equipmentRefs = [];
4901
5866
  let equipmentAuthored = false;
5867
+ let equipmentSpan;
4902
5868
  const fillEquipment = () => {
4903
5869
  if (equipmentRefs.length > 0 || equipmentAuthored) return;
4904
5870
  if (effortEntity === null) return;
@@ -5011,8 +5977,9 @@ function createReferenceIndex(catalog, materialize) {
5011
5977
  };
5012
5978
  }
5013
5979
  }
5980
+ const wholeFound = resolveEffortExact(source);
5014
5981
  const lowerSource = source.toLowerCase();
5015
- for (const candidate of prefixCandidates) {
5982
+ for (const candidate of equipmentCandidates) {
5016
5983
  if (!lowerSource.startsWith(candidate.lower)) continue;
5017
5984
  const after = source.slice(candidate.lower.length);
5018
5985
  if (after && !/^\s/.test(after)) continue;
@@ -5038,6 +6005,11 @@ function createReferenceIndex(catalog, materialize) {
5038
6005
  }
5039
6006
  if (!equipmentFound.entity) continue;
5040
6007
  const effortFound = resolveEffortExact(candidateRemaining);
6008
+ if (wholeFound.entity && wholeFound.entity.equipment?.includes(equipmentFound.entity.slug) && (effortFound.entity || effortFound.diagnostic?.reason === "ambiguous-effort")) {
6009
+ matched = "whole";
6010
+ effortEntity = wholeFound.entity;
6011
+ break;
6012
+ }
5041
6013
  if (effortFound.entity) {
5042
6014
  matched = "split";
5043
6015
  effortEntity = effortFound.entity;
@@ -5048,9 +6020,10 @@ function createReferenceIndex(catalog, materialize) {
5048
6020
  }];
5049
6021
  equipmentAuthored = true;
5050
6022
  remaining = candidateRemaining;
6023
+ equipmentSpan = { start: 0, end: rawPrefix.length };
5051
6024
  break;
5052
6025
  }
5053
- if (effortFound.diagnostic?.reason === "ambiguous-effort") {
6026
+ if (effortFound.diagnostic?.reason === "ambiguous-effort" && !wholeFound.entity) {
5054
6027
  push(effortFound.diagnostic);
5055
6028
  return {
5056
6029
  matched: "none",
@@ -5064,12 +6037,11 @@ function createReferenceIndex(catalog, materialize) {
5064
6037
  }
5065
6038
  }
5066
6039
  if (matched === "none") {
5067
- const found = resolveEffortExact(source);
5068
- if (found.entity) {
5069
- effortEntity = found.entity;
6040
+ if (wholeFound.entity) {
6041
+ effortEntity = wholeFound.entity;
5070
6042
  matched = "whole";
5071
- } else if (found.diagnostic?.reason === "ambiguous-effort") {
5072
- push(found.diagnostic);
6043
+ } else if (wholeFound.diagnostic?.reason === "ambiguous-effort") {
6044
+ push(wholeFound.diagnostic);
5073
6045
  return {
5074
6046
  matched: "none",
5075
6047
  label: source,
@@ -5079,8 +6051,65 @@ function createReferenceIndex(catalog, materialize) {
5079
6051
  remaining: "",
5080
6052
  diagnostics
5081
6053
  };
5082
- } else if (found.diagnostic) {
5083
- push(found.diagnostic);
6054
+ } else if (wholeFound.diagnostic) {
6055
+ push(wholeFound.diagnostic);
6056
+ }
6057
+ }
6058
+ if (matched === "none") {
6059
+ for (const candidate of equipmentCandidates) {
6060
+ if (!lowerSource.endsWith(candidate.lower)) continue;
6061
+ const beforeLen = source.length - candidate.lower.length;
6062
+ if (beforeLen <= 0 || !/\s$/.test(source.slice(0, beforeLen))) continue;
6063
+ const candidateRemaining = source.slice(0, beforeLen).trim();
6064
+ if (!candidateRemaining) continue;
6065
+ const equipmentFound = equipment.lookup(candidate.lower);
6066
+ if (equipmentFound.ambiguous.length > 0) {
6067
+ diagnostics.length = 0;
6068
+ push({
6069
+ reason: "ambiguous-equipment",
6070
+ message: `"${candidate.lower}" matches multiple equipment entries.`,
6071
+ token: source,
6072
+ candidates: equipmentFound.ambiguous.map((e) => e.slug)
6073
+ });
6074
+ return {
6075
+ matched: "none",
6076
+ label: source,
6077
+ effort: null,
6078
+ effortRef: null,
6079
+ equipment: [],
6080
+ remaining: "",
6081
+ diagnostics
6082
+ };
6083
+ }
6084
+ if (!equipmentFound.entity) continue;
6085
+ const effortFound = resolveEffortExact(candidateRemaining);
6086
+ if (effortFound.entity) {
6087
+ diagnostics.length = 0;
6088
+ matched = "split";
6089
+ effortEntity = effortFound.entity;
6090
+ const rawSuffix = source.slice(beforeLen);
6091
+ equipmentRefs = [{
6092
+ ...equipmentRef(equipmentFound.entity),
6093
+ ...rawSuffix.toLowerCase() !== equipmentFound.entity.label.toLowerCase() ? { matchedAlias: rawSuffix } : {}
6094
+ }];
6095
+ equipmentAuthored = true;
6096
+ remaining = candidateRemaining;
6097
+ equipmentSpan = { start: beforeLen, end: source.length };
6098
+ break;
6099
+ }
6100
+ if (effortFound.diagnostic?.reason === "ambiguous-effort") {
6101
+ diagnostics.length = 0;
6102
+ push(effortFound.diagnostic);
6103
+ return {
6104
+ matched: "none",
6105
+ label: source,
6106
+ effort: null,
6107
+ effortRef: null,
6108
+ equipment: [],
6109
+ remaining: "",
6110
+ diagnostics
6111
+ };
6112
+ }
5084
6113
  }
5085
6114
  }
5086
6115
  fillEquipment();
@@ -5097,6 +6126,7 @@ function createReferenceIndex(catalog, materialize) {
5097
6126
  } : null,
5098
6127
  equipment: equipmentRefs,
5099
6128
  remaining,
6129
+ ...equipmentSpan ? { equipmentSpan } : {},
5100
6130
  diagnostics
5101
6131
  };
5102
6132
  }
@@ -5964,6 +6994,48 @@ var CurrentRoundMetric = class {
5964
6994
  value;
5965
6995
  image;
5966
6996
  };
6997
+
6998
+ // src/runtime/time/calculateElapsed.ts
6999
+ function calculateElapsed(timer, now) {
7000
+ let total = 0;
7001
+ for (const span of timer.spans) {
7002
+ const end = span.ended ?? now;
7003
+ total += end - span.started;
7004
+ }
7005
+ return total;
7006
+ }
7007
+ function formatDuration(ms) {
7008
+ const totalSeconds = Math.floor(ms / 1e3);
7009
+ const mins = Math.floor(totalSeconds / 60);
7010
+ const secs = totalSeconds % 60;
7011
+ return `${mins}:${secs.toString().padStart(2, "0")}`;
7012
+ }
7013
+
7014
+ // src/runtime/compiler/metrics/ElapsedMetric.ts
7015
+ var ElapsedMetric = class {
7016
+ /**
7017
+ * @param value Elapsed time in milliseconds
7018
+ * @param sourceBlockKey Block that produced this measurement
7019
+ * @param timestamp When this metrics was created
7020
+ */
7021
+ constructor(value, sourceBlockKey, timestamp) {
7022
+ this.value = value;
7023
+ this.sourceBlockKey = sourceBlockKey;
7024
+ this.timestamp = timestamp;
7025
+ }
7026
+ value;
7027
+ sourceBlockKey;
7028
+ timestamp;
7029
+ type = MetricType.Elapsed;
7030
+ origin = "analyzed";
7031
+ unit = "ms";
7032
+ /** Human-readable elapsed time (e.g., "5:03") */
7033
+ get image() {
7034
+ return formatDuration(this.value);
7035
+ }
7036
+ };
7037
+
7038
+ // src/runtime/OutputEmitter.ts
5967
7039
  var OutputEmitter = class {
5968
7040
  _outputStatements = [];
5969
7041
  _outputListeners = /* @__PURE__ */ new Set();
@@ -6249,6 +7321,13 @@ var OutputEmitter = class {
6249
7321
  }
6250
7322
  }
6251
7323
  const recordedSpans = resultFragments.filter((m) => m.type === MetricType.Spans && Array.isArray(m.value)).flatMap((m) => m.value).filter((s) => typeof s?.started === "number" && Number.isFinite(s.started));
7324
+ if (recordedSpans.length > 0 && !metrics.some((m) => m.type === MetricType.Elapsed)) {
7325
+ const activeElapsedMs = recordedSpans.reduce(
7326
+ (acc, s) => acc + Math.max(0, (typeof s.ended === "number" && Number.isFinite(s.ended) ? s.ended : fallbackEndMs) - s.started),
7327
+ 0
7328
+ );
7329
+ metrics.add(new ElapsedMetric(activeElapsedMs, block.key.toString(), new Date(fallbackEndMs)));
7330
+ }
6252
7331
  const timeSpan = recordedSpans.length > 0 ? new TimeSpan(
6253
7332
  Math.min(...recordedSpans.map((s) => s.started)),
6254
7333
  Math.max(...recordedSpans.map((s) => typeof s.ended === "number" && Number.isFinite(s.ended) ? s.ended : fallbackEndMs))
@@ -7946,22 +9025,6 @@ var ClearChildrenAction = class {
7946
9025
  }
7947
9026
  };
7948
9027
 
7949
- // src/runtime/time/calculateElapsed.ts
7950
- function calculateElapsed(timer, now) {
7951
- let total = 0;
7952
- for (const span of timer.spans) {
7953
- const end = span.ended ?? now;
7954
- total += end - span.started;
7955
- }
7956
- return total;
7957
- }
7958
- function formatDuration(ms) {
7959
- const totalSeconds = Math.floor(ms / 1e3);
7960
- const mins = Math.floor(totalSeconds / 60);
7961
- const secs = totalSeconds % 60;
7962
- return `${mins}:${secs.toString().padStart(2, "0")}`;
7963
- }
7964
-
7965
9028
  // src/runtime/behaviors/CountdownTimerBehavior.ts
7966
9029
  var CountdownTimerBehavior = class {
7967
9030
  constructor(config) {
@@ -10680,27 +11743,6 @@ var ChildSelectionBehavior = class _ChildSelectionBehavior {
10680
11743
  return "timer-active";
10681
11744
  }
10682
11745
  };
10683
- var ElapsedMetric = class {
10684
- /**
10685
- * @param value Elapsed time in milliseconds
10686
- * @param sourceBlockKey Block that produced this measurement
10687
- * @param timestamp When this metrics was created
10688
- */
10689
- constructor(value, sourceBlockKey, timestamp) {
10690
- this.value = value;
10691
- this.sourceBlockKey = sourceBlockKey;
10692
- this.timestamp = timestamp;
10693
- }
10694
- value;
10695
- sourceBlockKey;
10696
- timestamp;
10697
- type = MetricType.Elapsed;
10698
- origin = "analyzed";
10699
- /** Human-readable elapsed time (e.g., "5:03") */
10700
- get image() {
10701
- return formatDuration(this.value);
10702
- }
10703
- };
10704
11746
  var TotalMetric = class {
10705
11747
  /**
10706
11748
  * @param value Total wall-clock time in milliseconds
@@ -10846,14 +11888,19 @@ var ReportOutputBehavior = class {
10846
11888
  const timer = readTimer(ctx);
10847
11889
  const round = ctx.getMemoryByTag("round")[0]?.metrics[0];
10848
11890
  const shouldComputeTimeResults = this.config.computeTimeResults ?? true;
11891
+ const reason = ctx.block.completionReason;
11892
+ const earlyTermination = reason === "user-abort" || reason === "forced-pop" || reason === "timer-expired";
11893
+ const effectiveRound = round ? earlyTermination ? { current: Math.max(0, round.current - 1), total: round.total } : round : void 0;
10849
11894
  let completionLabel = this.config.label ?? "Completed";
10850
11895
  if (!this.config.label) {
10851
11896
  if (ctx.block.blockType === "SessionRoot") {
10852
11897
  completionLabel = "Session Completed";
10853
- } else if (round && round.total !== void 0 && round.total > 1) {
10854
- completionLabel = `Completed ${round.total} Round(s)`;
10855
- } else if (round && round.current > 1) {
10856
- completionLabel = `Completed ${round.current} Round(s)`;
11898
+ } else if (effectiveRound && !earlyTermination && effectiveRound.total !== void 0 && effectiveRound.total > 1) {
11899
+ completionLabel = `Completed ${effectiveRound.total} Round(s)`;
11900
+ } else if (effectiveRound && effectiveRound.current > 0) {
11901
+ completionLabel = `Completed ${effectiveRound.current} Round(s)`;
11902
+ } else if (earlyTermination && round) {
11903
+ completionLabel = "Completed 0 Round(s)";
10857
11904
  }
10858
11905
  }
10859
11906
  if (shouldComputeTimeResults) {
@@ -10936,6 +11983,9 @@ var ReportOutputBehavior = class {
10936
11983
  const nowMs = now.getTime();
10937
11984
  const blockKey = ctx.block.key.toString();
10938
11985
  const round = ctx.getMemoryByTag("round")[0]?.metrics[0];
11986
+ const reason = ctx.block.completionReason;
11987
+ const earlyTermination = reason === "user-abort" || reason === "forced-pop" || reason === "timer-expired";
11988
+ const reportedRound = round && earlyTermination ? { current: Math.max(0, round.current - 1), total: round.total } : round;
10939
11989
  if (timer && timer.spans.length > 0) {
10940
11990
  const elapsed = calculateElapsed(timer, nowMs);
10941
11991
  const closedSpans = timer.spans.map(
@@ -10951,8 +12001,8 @@ var ReportOutputBehavior = class {
10951
12001
  new SpansMetric(closedSpans, blockKey, now),
10952
12002
  new SystemTimeMetric(this._now.now(), blockKey)
10953
12003
  );
10954
- if (round) {
10955
- metrics2.add(new CurrentRoundMetric(round.current, round.total, blockKey, now, customRoundLabel));
12004
+ if (reportedRound && reportedRound.current > 0) {
12005
+ metrics2.add(new CurrentRoundMetric(reportedRound.current, reportedRound.total, blockKey, now, customRoundLabel));
10956
12006
  }
10957
12007
  return metrics2;
10958
12008
  }
@@ -10965,8 +12015,8 @@ var ReportOutputBehavior = class {
10965
12015
  new SpansMetric([span], blockKey, now),
10966
12016
  new SystemTimeMetric(this._now.now(), blockKey)
10967
12017
  );
10968
- if (round) {
10969
- metrics.add(new CurrentRoundMetric(round.current, round.total, blockKey, now, customRoundLabel));
12018
+ if (reportedRound && reportedRound.current > 0) {
12019
+ metrics.add(new CurrentRoundMetric(reportedRound.current, reportedRound.total, blockKey, now, customRoundLabel));
10970
12020
  }
10971
12021
  return metrics;
10972
12022
  }
@@ -12257,7 +13307,10 @@ var AnalyticsEngine = class {
12257
13307
  // metadata (effortSlug/discipline/…) through to stored logs.
12258
13308
  {
12259
13309
  type: p.metricType || MetricType.Metric,
12260
- image: `${p.value} ${p.unit}`,
13310
+ image: (() => {
13311
+ const displayVal = Number.isInteger(p.value) ? String(p.value) : (Math.round(p.value * 10) / 10).toFixed(1);
13312
+ return p.unit ? `${displayVal} ${p.unit}` : displayVal;
13313
+ })(),
12261
13314
  value: p.value,
12262
13315
  unit: p.unit,
12263
13316
  origin: p.origin ?? "analyzed",
@@ -12519,8 +13572,15 @@ var CalculationRegistry = class {
12519
13572
  if (def.kind === "output" && def.output?.unit && def.output.unit !== "auto") {
12520
13573
  for (const variant of def.variants) {
12521
13574
  for (const nodeId of outputNodeIds(def)) {
13575
+ const outNode = variant.nodes[nodeId];
12522
13576
  const dim = variant.nodeDims?.[nodeId];
12523
- if (dim) validateOutputUnit(dim, def.output.unit);
13577
+ if (outNode && (outNode.kind === "wql" || astHasWql(outNode.ast, variant))) {
13578
+ if (!getUnit(def.output.unit)) {
13579
+ throw new CalcRegistrationError(`Calc ${def.id}: Unknown output unit: ${def.output.unit}`);
13580
+ }
13581
+ } else if (dim) {
13582
+ validateOutputUnit(dim, def.output.unit);
13583
+ }
12524
13584
  }
12525
13585
  }
12526
13586
  }
@@ -12552,8 +13612,14 @@ var CalculationRegistry = class {
12552
13612
  const env = this.staticEnv(siblingRefDim);
12553
13613
  let dim = inferDim(ast, env);
12554
13614
  if (node.unit) {
12555
- validateOutputUnit(dim, node.unit);
12556
- if (AUTHORITATIVE_CASTS[node.unit]) dim = DIM_ZERO;
13615
+ if (astHasWql(ast, variant)) {
13616
+ const unitDef = getUnit(node.unit);
13617
+ if (!unitDef) throw new CalcRegistrationError(`Unknown output unit: ${node.unit}`);
13618
+ dim = AUTHORITATIVE_CASTS[node.unit] ? DIM_ZERO : unitDef.dim;
13619
+ } else {
13620
+ validateOutputUnit(dim, node.unit);
13621
+ if (AUTHORITATIVE_CASTS[node.unit]) dim = DIM_ZERO;
13622
+ }
12557
13623
  }
12558
13624
  nodeDims[nodeId] = dim;
12559
13625
  return dim;
@@ -12610,6 +13676,30 @@ function outputNodeIds(def) {
12610
13676
  if (!nodeId) return [];
12611
13677
  return Array.isArray(nodeId) ? nodeId : [nodeId];
12612
13678
  }
13679
+ function astHasWql(node, variant, seen = /* @__PURE__ */ new Set()) {
13680
+ if (!node) return false;
13681
+ switch (node.kind) {
13682
+ case "wql":
13683
+ return true;
13684
+ case "ref": {
13685
+ if (seen.has(node.name)) return false;
13686
+ const target = variant.nodes[node.name];
13687
+ if (!target) return false;
13688
+ if (target.kind === "wql") return true;
13689
+ const next = new Set(seen);
13690
+ next.add(node.name);
13691
+ return astHasWql(target.ast, variant, next);
13692
+ }
13693
+ case "unary":
13694
+ return astHasWql(node.arg, variant, seen);
13695
+ case "binary":
13696
+ return astHasWql(node.left, variant, seen) || astHasWql(node.right, variant, seen);
13697
+ case "call":
13698
+ return node.args.some((arg) => astHasWql(arg, variant, seen));
13699
+ default:
13700
+ return false;
13701
+ }
13702
+ }
12613
13703
 
12614
13704
  // src/analytics/calc/engine.ts
12615
13705
  var CalcEngine = class {
@@ -13772,7 +14862,7 @@ var STORE_CALCS = [
13772
14862
  value: expr("value", "daily * (daily / daily)")
13773
14863
  }
13774
14864
  }],
13775
- output: { nodeId: "value", key: "calc.sleep", unit: "pts", label: "Sleep (h)" }
14865
+ output: { nodeId: "value", key: "calc.sleep", unit: "h", label: "Sleep (h)" }
13776
14866
  },
13777
14867
  {
13778
14868
  id: "hrv",
@@ -13788,7 +14878,7 @@ var STORE_CALCS = [
13788
14878
  value: expr("value", "daily * (daily / daily)")
13789
14879
  }
13790
14880
  }],
13791
- output: { nodeId: "value", key: "calc.hrv", unit: "pts", label: "HRV (ms)" }
14881
+ output: { nodeId: "value", key: "calc.hrv", unit: "ms", label: "HRV (ms)" }
13792
14882
  },
13793
14883
  {
13794
14884
  // Readiness composite: soreness (inverted) 40%, sleep 30%, HRV 30%,
@@ -14335,7 +15425,7 @@ var LabelComposer = class {
14335
15425
  static getIdentityText(metrics) {
14336
15426
  const logicKeywords = ["AMRAP", "EMOM", "TABATA", "FOR TIME"];
14337
15427
  const identityFragments = metrics.filter((f) => {
14338
- if (f.type === MetricType.Duration || f.type === MetricType.Rounds || f.type === MetricType.Resistance || f.type === MetricType.Distance || f.type === MetricType.Lap || f.type === MetricType.Group) {
15428
+ if (f.type === MetricType.Duration || f.type === MetricType.Rounds || f.type === MetricType.Resistance || f.type === MetricType.Distance || f.type === MetricType.Lap || f.type === MetricType.Group || f.type === MetricType.Equipment) {
14339
15429
  return false;
14340
15430
  }
14341
15431
  const val = (f.image || f.value?.toString() || "").toUpperCase();
@@ -14455,6 +15545,7 @@ var AmrapLogicStrategy = class {
14455
15545
  mode: "countdown",
14456
15546
  label
14457
15547
  }));
15548
+ builder.declareExit("immediate");
14458
15549
  }
14459
15550
  };
14460
15551
  var IntervalLogicStrategy = class {
@@ -16111,6 +17202,6 @@ function compareStatement(expectations, actual, mode) {
16111
17202
  return diffs;
16112
17203
  }
16113
17204
 
16114
- export { ABSENT, AGGREGATE_BUILTINS, AUTHORITATIVE_CASTS, AbortSessionAction, AmrapLogicStrategy, AnalyticsEngine, AnalyticsTransformer, BUILTIN_CALCS, BUNDLED_EFFORT_COUNT, BehaviorContext, BlockBuilder, BlockContext, ButtonBehavior, COMPLETION_PROPERTY_KEYS, COMPLETION_SECTIONS, CONTEXT_ATOMS, CalcEngine, CalcEvalError, CalcParseError, CalcRegistrationError, CalcUnitError, CalculationRegistry, CardioDialect, ChildSelectionBehavior, ChildrenStrategy, ChoiceGroupMetric, ClearChildrenAction, ClimbDialect, ClimbMetricType, CompileAndPushBlockAction, CompletionTimestampBehavior, CompositeEffortRegistry, CompositeEquipmentRegistry, CompositePropertyRegistry, CountdownTimerBehavior, CountupTimerBehavior, CrossFitDialect, DAY, DEFAULT_RESOLVER_OPTIONS, DEFAULT_RUNTIME_OPTIONS, DEFAULT_SOUND_PROFILE, DEFAULT_UNRESOLVED_EFFORT_MET, DIM_COUNT, DIM_ENERGY, DIM_LENGTH, DIM_MASS, DIM_TIME, DIM_ZERO, DISCIPLINE_FACTORS, DialectStack, EFFORT_DATA_METRIC_TYPE, EFFORT_DISCIPLINES, EFFORT_REGISTRY_ORIGINS, EffortBlock, EffortFallbackStrategy, EffortResolver, EmitEventAction, EmitSystemOutputAction, ErrorAction, EventBus, ExecutionContext, ExitBehavior, FixtureSyntaxError, GenericGroupStrategy, GenericLoopStrategy, GenericTimerStrategy, HabitsDialect, INTENSITY_TIERS, InMemoryEffortRegistry, IntervalLogicStrategy, JitCompiler, LabelingBehavior, LocalEventProvider, LocalRuntimeSubscription, LookupRegistry, MdTimerRuntime, MemoryLocation, MemoryTypeEnum, MetricPromotionBehavior, NAMED_COMPOUNDS, NextAction, NextEvent, NextEventHandler, OutputEmitter, PRODUCTION_STRATEGIES, PROPERTY_KEY_TO_METRIC_TYPE, PopBlockAction, PushBlockAction, PushRestBlockAction, REFERENCE_PAIR_KEYS, REST_EXCLUSION, RPE_LABELS, RUNTIME_LOG_SUBJECT_WIDTH, RegisterEventHandlerAction, Registry, ReportOutputBehavior, ReportOutputStrategy, RestBlock, RoundsMetric, RuntimeAdapter, RuntimeBlock, RuntimeBuilder, RuntimeClock, RuntimeFactory, RuntimeLogger, RuntimeMemory, RuntimeObservers, RuntimeStack, SEED_PRECEDENCE_RANK, SOUND_PLAY_EVENT, SOUND_PROFILE_METRIC, STORE_CALCS, STREAM_ATOMS, STRUCTURAL_EFFORT_WORDS, ScriptRuntime, SessionRootBlock, SessionRootStrategy, SnapshotClock, SoundProfileBehavior, SoundStrategy, SpanTrackingBehavior, StandardAnalyticsProfile, StartSessionAction, StartWorkoutAction, SubscriptionManager, ThrowError, ThrowErrorAction, TwoPassEffortResolutionProcess, TypedMemoryReference, UNITS, UnitsDialect, UnregisterEventHandlerAction, UpdateNextPreviewAction, VISIBILITY_ICONS, VISIBILITY_LABELS, WaitingToStartBlock, WaitingToStartInjectorBehavior, WhiteboardScript, WodDialect, YogaDialect, addAliasToEffort, addDim, applyTemplateDefaults, buildStaticLookups, bundledEfforts, calculateElapsed, canonicalizeType, checkCalcLine, classifyStatements, closeCurrentSpan, collapseUnresolvedChoices, commonFixtureSet, compareStatement, compileLineForm, compilePropertySummaryCalcs, compilePropertySummaryCalcsWithDiagnostics, composeDivUnit, composeMulUnit, compoundName, computeWorkloadRollups, convertScalar, createAnalyticsEngineForBlock, createCalcEngine, createCalcStack, createCompiler, createDialectStack, createDisciplinesTable, createEffortTable, createLineLocator, createMockClock, createParser, createProfileTable, createReferenceIndex, createRpeLabelsTable, dailySessionLoads, dayBucket, dedupeEntitiesByPrecedence, dialectRegistry, dialectStack, diffStatement, dimEquals, disciplineFactorFor, documentToEffort, documentToEquipment, documentToTag, effortToDocument, equipmentToDocument, evaluate, extractEffortData, extractMetrics, extractPropertyRulesFromMeta, extractStatementRefs, extractStatements, extractStatementsRaw, extractSyntaxFacts, extractTagPropertyRules, filterTagsByVisibility, findBestFuzzyMatch, findUnresolvedChoices, fixtureBackSquat, fixtureBurpee, fixturePlank, fixtureRowing, fixtureRunning, fixtureUserCustom, fixtureUserOverride, formatDim, formatDuration, formatRuntimeLogLine, formatRuntimeLogRule, formatRuntimeTimestamp, formatSoundTrigger, metricsToLabel as fragmentsToLabel, fullFixtureSet, fuseUnits, fuseUnitsInMetrics, getAnalyticsFromLogs, getAnalyticsFromRuntime, getMetricVisibility, getUnit, inferDim, isCastSubscription, isChoiceResolved, isDimensionless, isEffortDiscipline, isFragmentTag, isWithinThreshold, levenshteinDistance, mutateTimerSpans, normalizeForFuzzy, num, openSpan, outputNodeId, outputNodeIds, padRuntimeLogEvent, padRuntimeLogSubject, parseCalcLine, parseEffortFile, parseEquipmentFile, parseExpression, parseMetricLine, parseScript, parseSoundTrigger, printCalculation, readNestedSection, readTimer, realtimeProcessorRegistry, renderMetric, resolveDominantOrigin, resolveEntityRank, resolveEntityTier, resolveFusedEffortReferences, resolveProfileRules, resolvePropertyDashboardWidgets, resolveSoundProfile, resolveSourceRank, resolveSourceTier, runMetricShakeOutQueue, slugifyRefLabel, snippetCompletions, startSpan, str, strategyRegistry, subDim, summaryProcessorRegistry, tagCategoryRecordToDocument, tagCategoryToDocument, tagRecordToDocument, tagToDocument, toStoredOutputStatement, truthy, validateOutputUnit, parser as whiteboardParser, whiteboardScript, whiteboardScriptCompletion, whiteboardScriptCompletionSource, whiteboardScriptLanguage, whiteboardScriptSnippets, writeChoiceSelection };
17205
+ export { ABSENT, AGGREGATE_BUILTINS, AUTHORITATIVE_CASTS, AbortSessionAction, AmrapLogicStrategy, AnalyticsEngine, AnalyticsTransformer, BUILTIN_CALCS, BUNDLED_EFFORT_COUNT, BehaviorContext, BlockBuilder, BlockContext, ButtonBehavior, COMPLETION_PROPERTY_KEYS, COMPLETION_SECTIONS, CONTEXT_ATOMS, CalcEngine, CalcEvalError, CalcParseError, CalcRegistrationError, CalcUnitError, CalculationRegistry, CardioDialect, ChildSelectionBehavior, ChildrenStrategy, ChoiceGroupMetric, ClearChildrenAction, ClimbDialect, ClimbMetricType, CompileAndPushBlockAction, CompletionTimestampBehavior, CompositeEffortRegistry, CompositeEquipmentRegistry, CompositePropertyRegistry, CountdownTimerBehavior, CountupTimerBehavior, CrossFitDialect, DAY, DEFAULT_RESOLVER_OPTIONS, DEFAULT_RUNTIME_OPTIONS, DEFAULT_SOUND_PROFILE, DEFAULT_UNRESOLVED_EFFORT_MET, DIM_COUNT, DIM_ENERGY, DIM_LENGTH, DIM_MASS, DIM_TIME, DIM_ZERO, DISCIPLINE_FACTORS, DialectStack, EFFORT_DATA_METRIC_TYPE, EFFORT_DISCIPLINES, EFFORT_REGISTRY_ORIGINS, EffortBlock, EffortFallbackStrategy, EffortResolver, EmitEventAction, EmitSystemOutputAction, ErrorAction, EventBus, ExecutionContext, ExitBehavior, FixtureSyntaxError, GenericGroupStrategy, GenericLoopStrategy, GenericTimerStrategy, HabitsDialect, INTENSITY_TIERS, InMemoryEffortRegistry, IntervalLogicStrategy, JitCompiler, LabelingBehavior, LocalEventProvider, LocalRuntimeSubscription, LookupRegistry, MdTimerRuntime, MemoryLocation, MemoryTypeEnum, MetricPromotionBehavior, NAMED_COMPOUNDS, NextAction, NextEvent, NextEventHandler, OutputEmitter, PRODUCTION_STRATEGIES, PROPERTY_KEY_TO_METRIC_TYPE, PopBlockAction, PushBlockAction, PushRestBlockAction, REFERENCE_PAIR_KEYS, REST_EXCLUSION, RPE_LABELS, RUNTIME_LOG_SUBJECT_WIDTH, RegisterEventHandlerAction, Registry, ReportOutputBehavior, ReportOutputStrategy, RestBlock, RoundsMetric, RuntimeAdapter, RuntimeBlock, RuntimeBuilder, RuntimeClock, RuntimeFactory, RuntimeLogger, RuntimeMemory, RuntimeObservers, RuntimeStack, SEED_PRECEDENCE_RANK, SOUND_PLAY_EVENT, SOUND_PROFILE_METRIC, STORE_CALCS, STREAM_ATOMS, STRUCTURAL_EFFORT_WORDS, ScriptRuntime, SessionRootBlock, SessionRootStrategy, SnapshotClock, SoundProfileBehavior, SoundStrategy, SpanTrackingBehavior, StandardAnalyticsProfile, StartSessionAction, StartWorkoutAction, SubscriptionManager, ThrowError, ThrowErrorAction, TwoPassEffortResolutionProcess, TypedMemoryReference, UNITS, UnitsDialect, UnregisterEventHandlerAction, UpdateNextPreviewAction, VISIBILITY_ICONS, VISIBILITY_LABELS, WaitingToStartBlock, WaitingToStartInjectorBehavior, WhiteboardScript, WodDialect, YogaDialect, addAliasToEffort, addDim, applyTemplateDefaults, buildStaticLookups, bundledEfforts, calculateElapsed, canonicalizeType, checkCalcLine, classifyStatements, closeCurrentSpan, collapseUnresolvedChoices, commonFixtureSet, compareStatement, compileLineForm, compilePropertySummaryCalcs, compilePropertySummaryCalcsWithDiagnostics, composeDivUnit, composeMulUnit, compoundName, computeWhiteboardEnterAction, computeWorkloadRollups, convertScalar, createAnalyticsEngineForBlock, createCalcEngine, createCalcStack, createCompiler, createDialectStack, createDisciplinesTable, createEffortTable, createLineLocator, createMockClock, createParser, createProfileTable, createReferenceIndex, createRpeLabelsTable, dailySessionLoads, dayBucket, dedupeEntitiesByPrecedence, dialectRegistry, dialectStack, diffStatement, dimEquals, disciplineFactorFor, documentToEffort, documentToEquipment, documentToTag, effortToDocument, equipmentToDocument, evaluate, extractEffortData, extractMetrics, extractPropertyRulesFromMeta, extractStatementRefs, extractStatements, extractStatementsRaw, extractSyntaxFacts, extractTagPropertyRules, filterTagsByVisibility, findBestFuzzyMatch, findUnresolvedChoices, fixtureBackSquat, fixtureBurpee, fixturePlank, fixtureRowing, fixtureRunning, fixtureUserCustom, fixtureUserOverride, formatDim, formatDuration, formatRuntimeLogLine, formatRuntimeLogRule, formatRuntimeTimestamp, formatSoundTrigger, metricsToLabel as fragmentsToLabel, fullFixtureSet, fuseUnits, fuseUnitsInMetrics, getAnalyticsFromLogs, getAnalyticsFromRuntime, getMetricVisibility, getUnit, inferDim, isCastSubscription, isChoiceResolved, isDimensionless, isEffortDiscipline, isFragmentTag, isRoundsHeaderLine, isWithinThreshold, levenshteinDistance, mutateTimerSpans, normalizeForFuzzy, num, openSpan, outputNodeId, outputNodeIds, padRuntimeLogEvent, padRuntimeLogSubject, parseCalcLine, parseEffortFile, parseEquipmentFile, parseExpression, parseMetricLine, parseScript, parseSoundTrigger, printCalculation, readNestedSection, readTimer, realtimeProcessorRegistry, renderMetric, resolveDominantOrigin, resolveEntityRank, resolveEntityTier, resolveFusedEffortReferences, resolveProfileRules, resolvePropertyDashboardWidgets, resolveSoundProfile, resolveSourceRank, resolveSourceTier, runMetricShakeOutQueue, slugifyRefLabel, snippetCompletions, startSpan, str, strategyRegistry, subDim, summaryProcessorRegistry, tagCategoryRecordToDocument, tagCategoryToDocument, tagRecordToDocument, tagToDocument, toStoredOutputStatement, truthy, validateOutputUnit, parser as whiteboardParser, whiteboardScript, whiteboardScriptCompletion, whiteboardScriptCompletionSource, whiteboardScriptLanguage, whiteboardScriptSnippets, writeChoiceSelection };
16115
17206
  //# sourceMappingURL=index.mjs.map
16116
17207
  //# sourceMappingURL=index.mjs.map