@bitcobblers/wod-wiki-core 0.35.2115 → 0.35.2117

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ownership/types.ts","../src/models/Metric.ts","../src/ownership/ledger.ts","../src/fields/fieldIdentity.ts","../src/units/catalog.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/BlockKey.ts","../src/models/blockContentId.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/sections/blockDetection.ts","../src/sections/sectionParser.ts","../src/version.ts"],"names":["MetricType"],"mappings":";;;AAQO,IAAM,4BAAA,GAAgE;AAAA,EAC3E,QAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF;AAMO,IAAM,gCAAA,GAA+E;AAAA,EAC1F,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,SAAA;AAAA,EACV,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,WAAA,EAAa,WAAA;AAAA,EACb,OAAA,EAAS,SAAA;AAAA,EACT,OAAA,EAAS,SAAA;AAAA,EACT,QAAA,EAAU,SAAA;AAAA,EACV,oBAAA,EAAsB,SAAA;AAAA,EACtB,SAAA,EAAW,SAAA;AAAA,EACX,IAAA,EAAM,YAAA;AAAA,EACN,SAAA,EAAW;AACb;AA+CO,SAAS,wBAAwB,MAAA,EAAwD;AAC9F,EAAA,OAAO,gCAAA,CAAiC,MAAA,IAAU,QAAQ,CAAA,IAAK,QAAA;AACjE;;;AC+BO,IAAK,UAAA,qBAAAA,WAAAA,KAAL;AAQL,EAAAA,YAAA,UAAA,CAAA,GAAW,UAAA;AASX,EAAAA,YAAA,OAAA,CAAA,GAAQ,OAAA;AAQR,EAAAA,YAAA,YAAA,CAAA,GAAa,aAAA;AAGb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AAA,QAClB,OAAA,EAAS,UAAA;AAAA,QACT,WAAW,aAAA,CAAc;AAAA,OAC3B;AACA,MAAA,IAAI,QAAQ,WAAA,EAAa;AACvB,QAAA,OAAA,CAAQ,WAAA,GAAc,EAAE,GAAG,OAAA,CAAQ,aAAa,EAAA,EAAI,aAAA,CAAc,EAAA,EAAI,OAAA,EAAS,UAAA,EAAW;AAAA,MAC5F;AACA,MAAA,OAAO,OAAA;AAAA,IACT;AAEA,IAAA,OAAO,MAAA;AAAA,EACT,CAAC,CAAA;AACH;;;ACpZO,IAAM,OAAA,GAAU;AAChB,IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,WAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.cjs","sourcesContent":["import type { IMetric, MetricOrigin, MetricOwnershipLayer } from '../models/Metric';\n\nexport type { MetricOwnershipLayer };\n\n/**\n * Canonical low->high ownership chain used by characterization tests and\n * ownership resolution work.\n */\nexport const METRIC_OWNERSHIP_LAYER_CHAIN: readonly MetricOwnershipLayer[] = [\n 'parser',\n 'dialect',\n 'user-plan',\n 'runtime',\n 'user-entry',\n] as const;\n\n/**\n * Compatibility map from the current mixed-purpose `origin` field into the\n * canonical ownership-layer vocabulary.\n */\nexport const LEGACY_ORIGIN_TO_OWNERSHIP_LAYER: Record<MetricOrigin, MetricOwnershipLayer> = {\n parser: 'parser',\n compiler: 'dialect',\n dialect: 'dialect',\n hinted: 'dialect',\n 'user-plan': 'user-plan',\n runtime: 'runtime',\n tracked: 'runtime',\n analyzed: 'runtime',\n 'analyzed-estimated': 'runtime',\n execution: 'runtime',\n user: 'user-entry',\n collected: 'user-entry',\n};\n\nexport interface MetricWithOptionalOwnershipLayer extends IMetric {\n readonly ownershipLayer?: MetricOwnershipLayer;\n}\n\nexport interface MetricOwnershipQuery {\n readonly types?: readonly (IMetric['type'])[];\n readonly layers?: readonly MetricOwnershipLayer[];\n}\n\nexport type MetricOwnershipOutcome =\n | 'visible'\n | 'hidden-by-layer'\n | 'hidden-by-suppressor'\n | 'suppressor';\n\nexport interface MetricOwnershipResolvedContribution {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly outcome: MetricOwnershipOutcome;\n}\n\nexport interface MetricOwnershipPromotionCandidate {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly reason: 'shadowed-by-higher-layer' | 'suppressed';\n readonly blockedByLayer?: MetricOwnershipLayer;\n}\n\nexport interface MetricOwnershipTypeExplanation {\n readonly type: IMetric['type'];\n readonly winnerLayer?: MetricOwnershipLayer;\n readonly suppressed: boolean;\n readonly entries: readonly MetricOwnershipResolvedContribution[];\n}\n\nexport interface MetricOwnershipLedger {\n raw(query?: MetricOwnershipQuery): IMetric[];\n visible(query?: MetricOwnershipQuery): IMetric[];\n byLayer(query?: MetricOwnershipQuery): Partial<Record<MetricOwnershipLayer, IMetric[]>>;\n promotionCandidates(query?: MetricOwnershipQuery): MetricOwnershipPromotionCandidate[];\n explain(query?: MetricOwnershipQuery): MetricOwnershipTypeExplanation[];\n}\n\nexport function getMetricOwnershipLayer(origin: MetricOrigin | undefined): MetricOwnershipLayer {\n return LEGACY_ORIGIN_TO_OWNERSHIP_LAYER[origin ?? 'parser'] ?? 'parser';\n}\n","/**\n * Canonical ownership vocabulary for metric visibility decisions.\n * Ordered from lowest to highest ownership precedence.\n */\nexport type MetricOwnershipLayer =\n | 'parser'\n | 'dialect'\n | 'user-plan'\n | 'runtime'\n | 'user-entry';\n\n/**\n * Origin of a metric - where it was created and its current state.\n *\n * Source origins:\n * - 'parser': Created by the parser from source text\n * - 'compiler': Synthesized by a compiler strategy\n * - 'dialect': Synthesized by a dialect policy before runtime\n * - 'runtime': Generated during execution (e.g., elapsed time)\n * - 'user': Collected from user input (e.g., actual reps completed)\n *\n * Value states:\n * - 'collected': Value has been collected and populated\n * - 'hinted': Value is a hint or suggestion not strictly enforced\n * - 'tracked': Value is actively being tracked during execution\n * - 'analyzed': Value is derived from analysis\n * - 'analyzed-estimated': Value is derived from estimation\n * - 'execution': Generated by runtime execution\n * - 'user-plan': Planned override set by user before execution\n */\nexport type MetricAction = 'suppress';\n\nexport type MetricOrigin =\n | 'parser'\n | 'compiler'\n | 'dialect'\n | 'runtime'\n | 'user'\n | 'collected'\n | 'hinted'\n | 'tracked'\n | 'analyzed'\n | 'analyzed-estimated'\n | 'execution'\n | 'user-plan';\n\nexport type Origin = MetricOrigin;\n\nexport interface IMetric {\n readonly image?: string;\n readonly value?: unknown;\n /**\n * The metric type. Use a `MetricType` enum value for standard types, or any\n * string for custom derived metrics produced by enrichment processes\n * (e.g. `'speed'`, `'pace'`, `'rep-rate'`, `'power'`).\n */\n readonly type: MetricType | string;\n /** Backward-compatible alias for type */\n readonly metricType?: MetricType | string;\n readonly origin: MetricOrigin;\n readonly unit?: string;\n\n /**\n * Visibility instruction. The only live value is `'suppress'`, which hides\n * all metrics of this type from display (resolved by the ownership ledger).\n * Most metrics carry no action (undefined = passive).\n */\n readonly action?: MetricAction;\n\n /**\n * Block key that created/owns this metric.\n * Present for runtime and user-collected metrics.\n */\n readonly sourceBlockKey?: string;\n\n /**\n * Timestamp when this metric was created/recorded.\n * Present for runtime and user-collected metrics.\n */\n readonly timestamp?: Date;\n\n /**\n * Processor-attached structured payload. Summary processors (e.g. TIS) hang\n * derivation metadata (effortSlug, effortDiscipline, effortIntensityTier,\n * component scores) on the projection value metric; fact normalization reads\n * it back out. Pure data — survives the stored-logs round-trip.\n */\n readonly metadata?: Record<string, unknown>;\n\n /** Optional explicit ownership layer for legacy compatibility */\n readonly ownershipLayer?: MetricOwnershipLayer;\n\n /** Optional human-readable name or label */\n readonly name?: string;\n\n /**\n * Optional icon (emoji/glyph) for hint metrics. Hints without an icon are\n * data-only — they never render in display surfaces; a hint WITH an icon\n * renders as the icon alone, with the hint text on hover.\n */\n readonly icon?: string;\n}\n\n/**\n * Metric type enumeration.\n *\n * Time-related terms follow the glossary in docs/architecture/time-terminology.md:\n * - **Duration** (Parser) — planned target from the script (e.g., \"5:00\" -> 300 000 ms)\n * - **Time / Spans** (Block) — the raw TimeSpan[] start/stop recordings a block tracks\n * - **TimeStamp** (Runtime) — system Date.now() when a message is logged\n * - **Elapsed** (Runtime) — Σ(end - start) of each span segment (active time, excludes pauses)\n * - **Total** (Runtime) — lastEnd - firstStart (wall-clock bracket, includes pauses)\n */\nexport enum MetricType {\n /**\n * **Duration** (Core) — parser-defined planned target.\n *\n * A metric defined by the CodeStatement during parsing (e.g., \"5:00\" -> 300 000 ms).\n * It can be a time (duration) or a placeholder to be resolved.\n * Owned by the parser — the runtime reads it but never computes it.\n */\n Duration = 'duration',\n\n /**\n * **Spans** (Core) — raw start/stop TimeSpan[] recordings.\n *\n * Source-of-truth data recorded using the runtime clock.\n * Each span represents a continuous period of active (unpaused) execution.\n * These can be recorded at runtime or back-filled during analytics.\n */\n Spans = 'spans',\n\n /**\n * **SystemTime** (Core) — real system time (Date.now()) when a message is logged.\n *\n * Ground-truth wall-clock reference (timestamp) associated with system time metrics.\n * Independent of the runtime clock.\n */\n SystemTime = 'system-time',\n\n /** Live timer state written into block memory by the count-up/count-down timer behaviors. */\n Time = 'time',\n\n /** Active elapsed time — Σ(end - start) of active spans; derived during analytics. */\n Elapsed = 'elapsed',\n\n /** Total wall-clock bracket (lastEnd - firstStart) for a block; derived during analytics. */\n Total = 'total',\n\n Rep = 'rep',\n Effort = 'effort',\n Distance = 'distance',\n Rounds = 'rounds',\n CurrentRound = 'current-round',\n Action = 'action',\n Increment = 'increment',\n Group = 'group',\n Text = 'text',\n Resistance = 'resistance',\n Sound = 'sound',\n System = 'system',\n Label = 'label',\n Lap = 'lap',\n Metric = 'metric',\n\n /**\n * **Hint** (Core) — a semantic marker emitted by a dialect or the parser.\n *\n * Dot-namespaced string markers (e.g. `workout.amrap`, `behavior.required_timer`)\n * that strategies and the label composer query to drive compilation decisions.\n * Hints are metrics so they flow through the single ownership channel, but they\n * are excluded from display resolution and from runtime block fragments.\n */\n Hint = 'hint',\n\n /** Generic custom metric bucket for parser-owned property metrics. */\n Custom = 'custom',\n Volume = 'volume',\n Intensity = 'intensity',\n\n /** Climb grade label carried by an observation (e.g. `V8`, `5.12a`) —\n * user-authored grade metrics promote to the analytics `grade` dim. */\n Grade = 'grade',\n Load = 'load',\n Work = 'work',\n\n /** Per-set Reps in Reserve (real-time, strength) */\n RIR = 'rir',\n\n /** Post-session subjective effort rating (0–10) */\n SessionRPE = 'session-rpe',\n\n /** Session RPE x total minutes */\n SessionLoad = 'session-load',\n\n /** Normalized MET ((Activity METs ÷ METmax) x 100) */\n METScore = 'met-score',\n\n /** Training Intensity Score (composite) */\n TIS = 'tis',\n\n /** Runtime-layer calculated metric emitted from declarative formulas */\n Calculated = 'calculated',\n\n /**\n * **Choice** (Parser) — a pipe-separated OR expression.\n *\n * Emitted by Fusion when a pipe separates two homogeneous alternatives\n * (same MetricType on both sides). Carries `alternatives: IMetric[]`.\n * Resolved in the Pre-Run Wizard before the JIT compiles: the chosen\n * alternative is written at origin `user-plan` into the Statement's\n * MetricContainer, shadowing this group via ownership-layer precedence.\n * Never reaches compiled Blocks or display output once resolved.\n */\n Choice = 'choice',\n}\n\n/**\n * Concrete helper class implementing IMetric\n */\nexport class Metric implements IMetric {\n readonly type: MetricType | string;\n readonly metricType?: MetricType | string;\n readonly value?: unknown;\n readonly origin: MetricOrigin;\n readonly unit?: string;\n readonly action?: MetricAction;\n readonly image?: string;\n readonly sourceBlockKey?: string;\n readonly timestamp?: Date;\n readonly metadata?: Record<string, unknown>;\n readonly name?: string;\n readonly ownershipLayer?: MetricOwnershipLayer;\n\n constructor(\n typeOrName: MetricType | string,\n valueOrType?: unknown,\n originOrValue?: unknown,\n unit?: string,\n origin?: MetricOrigin | string,\n action?: MetricAction | string,\n image?: string,\n ) {\n if (\n typeof valueOrType === 'string' &&\n (typeof originOrValue === 'number' ||\n typeof originOrValue === 'string' ||\n typeof originOrValue === 'boolean' ||\n originOrValue === null ||\n originOrValue === undefined)\n ) {\n // Signature: (name, type, value, unit?, origin?, action?, image?)\n this.name = String(typeOrName);\n this.type = valueOrType;\n this.metricType = valueOrType;\n this.value = originOrValue;\n this.unit = unit;\n this.origin = (origin as MetricOrigin) || 'parser';\n this.action = action === 'suppress' ? 'suppress' : undefined;\n this.image = image ?? String(originOrValue ?? valueOrType);\n } else {\n // Signature: (type, value?, origin?, unit?, action?, image?)\n this.type = typeOrName;\n this.metricType = typeOrName;\n this.value = valueOrType;\n this.origin = (originOrValue as MetricOrigin) || 'parser';\n this.unit = unit;\n this.action = (typeof origin === 'string' && origin === 'suppress')\n ? 'suppress'\n : (action === 'suppress' ? 'suppress' : undefined);\n this.image = image ?? String(valueOrType ?? typeOrName);\n }\n }\n\n toNumber(): number {\n if (typeof this.value === 'number') return this.value;\n if (typeof this.value === 'string') {\n const parsed = parseFloat(this.value);\n return isNaN(parsed) ? 0 : parsed;\n }\n return 0;\n }\n}\n","import { MetricType, type IMetric } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport {\n getMetricOwnershipLayer,\n METRIC_OWNERSHIP_LAYER_CHAIN,\n type MetricOwnershipLayer,\n type MetricOwnershipLedger,\n type MetricOwnershipPromotionCandidate,\n type MetricOwnershipQuery,\n type MetricOwnershipResolvedContribution,\n type MetricOwnershipTypeExplanation,\n type MetricWithOptionalOwnershipLayer,\n} from './types';\n\ninterface OwnershipContribution {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly layerRank: number;\n readonly index: number;\n readonly isSuppressor: boolean;\n}\n\nconst LAYER_RANK: Record<MetricOwnershipLayer, number> = {\n parser: 0,\n dialect: 1,\n 'user-plan': 2,\n runtime: 3,\n 'user-entry': 4,\n};\n\nexport function resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) {\n return maybeLayer;\n }\n return getMetricOwnershipLayer(metric.origin);\n}\n\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return LAYER_RANK[layer] ?? 0;\n}\n\nfunction normalize(metrics: readonly IMetric[]): OwnershipContribution[] {\n return metrics.map((metric, index) => {\n const layer = resolveLayer(metric);\n return {\n metric,\n type: metric.type,\n layer,\n layerRank: LAYER_RANK[layer] ?? 0,\n index,\n isSuppressor: metric.action === 'suppress',\n };\n });\n}\n\nfunction applyQuery(\n contributions: readonly OwnershipContribution[],\n query?: MetricOwnershipQuery,\n): OwnershipContribution[] {\n if (!query) {\n return [...contributions];\n }\n\n return contributions.filter((contribution) => {\n if (query.types && !query.types.includes(contribution.type)) {\n return false;\n }\n if (query.layers && !query.layers.includes(contribution.layer)) {\n return false;\n }\n return true;\n });\n}\n\nfunction groupByType(contributions: readonly OwnershipContribution[]): Map<IMetric['type'], OwnershipContribution[]> {\n const grouped = new Map<IMetric['type'], OwnershipContribution[]>();\n for (const contribution of contributions) {\n const bucket = grouped.get(contribution.type);\n if (bucket) {\n bucket.push(contribution);\n continue;\n }\n grouped.set(contribution.type, [contribution]);\n }\n return grouped;\n}\n\nfunction getWinningLayerRank(contributions: readonly OwnershipContribution[]): number | undefined {\n let winningLayerRank: number | undefined;\n for (const contribution of contributions) {\n if (contribution.isSuppressor) {\n continue;\n }\n if (winningLayerRank == null || contribution.layerRank > winningLayerRank) {\n winningLayerRank = contribution.layerRank;\n }\n }\n return winningLayerRank;\n}\n\nfunction toResolvedContribution(\n contribution: OwnershipContribution,\n outcome: MetricOwnershipResolvedContribution['outcome'],\n): MetricOwnershipResolvedContribution {\n return {\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n outcome,\n };\n}\n\nfunction compareByOriginalIndex(a: OwnershipContribution, b: OwnershipContribution): number {\n return a.index - b.index;\n}\n\nexport function createMetricOwnershipLedger(metrics: readonly IMetric[]): MetricOwnershipLedger {\n const contributions = normalize(metrics);\n\n return {\n raw(query) {\n return applyQuery(contributions, query).map((contribution) => contribution.metric);\n },\n\n visible(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const visible: OwnershipContribution[] = [];\n\n for (const groupedContributions of grouped.values()) {\n if (groupedContributions.some((contribution) => contribution.isSuppressor)) {\n continue;\n }\n\n const winningLayerRank = getWinningLayerRank(groupedContributions);\n if (winningLayerRank == null) {\n continue;\n }\n\n for (const contribution of groupedContributions) {\n if (!contribution.isSuppressor && contribution.layerRank === winningLayerRank) {\n visible.push(contribution);\n }\n }\n }\n\n visible.sort(compareByOriginalIndex);\n return visible.map((contribution) => contribution.metric);\n },\n\n byLayer(query) {\n const filtered = applyQuery(contributions, query);\n const grouped: Partial<Record<MetricOwnershipLayer, IMetric[]>> = {};\n\n for (const layer of METRIC_OWNERSHIP_LAYER_CHAIN) {\n grouped[layer] = [];\n }\n\n for (const contribution of filtered) {\n grouped[contribution.layer]!.push(contribution.metric);\n }\n\n for (const layer of METRIC_OWNERSHIP_LAYER_CHAIN) {\n if (grouped[layer]?.length === 0) {\n delete grouped[layer];\n }\n }\n\n return grouped;\n },\n\n promotionCandidates(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const candidates: MetricOwnershipPromotionCandidate[] = [];\n\n for (const groupedContributions of grouped.values()) {\n const suppressors = groupedContributions.filter((contribution) => contribution.isSuppressor);\n const nonSuppressors = groupedContributions.filter((contribution) => !contribution.isSuppressor);\n\n if (nonSuppressors.length === 0) {\n continue;\n }\n\n if (suppressors.length > 0) {\n const highestCandidateRank = Math.max(...nonSuppressors.map((contribution) => contribution.layerRank));\n const suppressingLayerRank = Math.max(...suppressors.map((contribution) => contribution.layerRank));\n\n for (const contribution of nonSuppressors) {\n if (contribution.layerRank === highestCandidateRank) {\n candidates.push({\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n reason: 'suppressed',\n blockedByLayer: METRIC_OWNERSHIP_LAYER_CHAIN[suppressingLayerRank],\n });\n }\n }\n continue;\n }\n\n const winningLayerRank = getWinningLayerRank(nonSuppressors);\n if (winningLayerRank == null) {\n continue;\n }\n\n const lowerLayerContributions = nonSuppressors.filter(\n (contribution) => contribution.layerRank < winningLayerRank,\n );\n\n if (lowerLayerContributions.length === 0) {\n continue;\n }\n\n const promotionLayerRank = Math.max(...lowerLayerContributions.map((contribution) => contribution.layerRank));\n\n for (const contribution of lowerLayerContributions) {\n if (contribution.layerRank === promotionLayerRank) {\n candidates.push({\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n reason: 'shadowed-by-higher-layer',\n blockedByLayer: METRIC_OWNERSHIP_LAYER_CHAIN[winningLayerRank],\n });\n }\n }\n }\n\n candidates.sort((a, b) => {\n const rankDelta = (LAYER_RANK[b.layer] ?? 0) - (LAYER_RANK[a.layer] ?? 0);\n if (rankDelta !== 0) {\n return rankDelta;\n }\n return 0;\n });\n return candidates;\n },\n\n explain(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const explanations: MetricOwnershipTypeExplanation[] = [];\n\n for (const [type, groupedContributions] of grouped.entries()) {\n const suppressed = groupedContributions.some((contribution) => contribution.isSuppressor);\n const winningLayerRank = suppressed ? undefined : getWinningLayerRank(groupedContributions);\n\n const entries = groupedContributions.map((contribution) => {\n if (contribution.isSuppressor) {\n return toResolvedContribution(contribution, 'suppressor');\n }\n if (suppressed) {\n return toResolvedContribution(contribution, 'hidden-by-suppressor');\n }\n if (winningLayerRank != null && contribution.layerRank === winningLayerRank) {\n return toResolvedContribution(contribution, 'visible');\n }\n return toResolvedContribution(contribution, 'hidden-by-layer');\n });\n\n explanations.push({\n type,\n winnerLayer: winningLayerRank == null ? undefined : METRIC_OWNERSHIP_LAYER_CHAIN[winningLayerRank],\n suppressed,\n entries,\n });\n }\n\n return explanations;\n },\n };\n}\n\nfunction applyFilter(metrics: readonly IMetric[], filter?: MetricFilter): IMetric[] {\n let filtered = [...metrics];\n const wantsHints = filter?.types?.includes(MetricType.Hint) ?? false;\n if (!wantsHints) {\n filtered = filtered.filter((m) => m.type !== MetricType.Hint);\n }\n if (!filter) return filtered;\n if (filter.origins) {\n filtered = filtered.filter((m) => filter.origins!.includes(m.origin ?? 'parser'));\n }\n if (filter.types) {\n filtered = filtered.filter((m) => filter.types!.includes(m.type));\n }\n if (filter.excludeTypes) {\n filtered = filtered.filter((m) => !filter.excludeTypes!.includes(m.type));\n }\n return filtered;\n}\n\nexport class OwnershipResolver implements IMetricOwnershipResolver {\n resolve(metrics: readonly IMetric[], filter?: MetricFilter): IMetric[] {\n const filtered = applyFilter(metrics, filter);\n const ledger = createMetricOwnershipLedger(filtered);\n return ledger.visible();\n }\n\n resolveOne(metrics: readonly IMetric[], type: MetricType | string): IMetric | undefined {\n return this.resolve(metrics, { types: [type] })[0];\n }\n\n resolveAll(metrics: readonly IMetric[], type: MetricType | string): IMetric[] {\n const ofType = metrics.filter((m) => m.type === type);\n if (ofType.length <= 1) return ofType;\n return [...ofType].sort((a, b) => ownershipRank(b) - ownershipRank(a));\n }\n}\n","/**\n * Field identity — the pure normalization/identity layer for typed metric\n * fields (wayfinder datadog-analytics ticket 11, per the field discovery\n * contract §Identity and discovery).\n *\n * A metric variant is identified by **normalized full property path + value\n * kind + physical dimension where applicable**. Source, display label,\n * original spelling, and convertible unit spelling are provenance, not\n * identity. Built-in and custom metrics use the same rules.\n *\n * This module is pure data + functions with zero dependencies: `lang` and\n * `wql` (and the app adapter) both consume it through their existing core\n * dependency. Dimension resolution from units lives with the unit catalog —\n * callers attach a resolved `dimension` when one is known.\n */\n\n/** The observed value kinds of a field variant (field discovery contract). */\nexport type FieldValueKind = 'number' | 'string' | 'boolean' | 'array';\n\n/** Presence/clearing marker — null records presence, never a value. */\nexport type NullValueKind = 'null';\n\n/**\n * Typed field reference — the identity of one metric variant.\n * `dimension` is the physical dimension for numeric kinds (resolved through\n * the unit registry); undefined means dimensionless or unknown.\n */\nexport interface FieldRef {\n /** Normalized full property path — lower camelCase components, dots delimit. */\n readonly path: string;\n /** Observed value kind of the variant. */\n readonly kind: FieldValueKind | NullValueKind;\n /** Physical dimension for numeric kinds, when known. */\n readonly dimension?: string;\n}\n\n/** Split one path component into words: whitespace/underscores/hyphens are\n * word separators; existing camel/Pascal boundaries are recognized.\n * Acronym runs (≥2 uppercase) end before a following upper+lower pair. */\nfunction splitWords(component: string): string[] {\n const onSeparators = component.split(/[\\s_\\-\\u2010-\\u2015]+/).filter(Boolean);\n const words: string[] = [];\n for (const chunk of onSeparators) {\n // Insert a boundary before an uppercase letter that follows a lowercase\n // letter or digit, and before the last uppercase of an acronym run when\n // a lowercase pair follows (e.g. 'HRVValue' → 'HRV' | 'Value').\n const cased = chunk\n .replace(/([\\p{Ll}\\p{Nd}])(\\p{Lu})/gu, '$1\\u0000$2')\n .replace(/(\\p{Lu})(\\p{Lu}\\p{Ll})/gu, '$1\\u0000$2');\n for (const word of cased.split('\\u0000')) {\n if (word) words.push(word);\n }\n }\n return words;\n}\n\n/** Lower camelCase one path component: `heart rate`, `heart_rate`,\n * `HeartRate`, and `heartRate` all normalize to `heartRate`; `HRV`\n * normalizes to `hrv`. No synonym inference: `heartrate` stays `heartrate`. */\nexport function normalizeFieldComponent(component: string): string {\n const words = splitWords(component);\n if (words.length === 0) return '';\n return words\n .map((word, index) => {\n const lower = word.toLowerCase();\n return index === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n/**\n * Normalize a full property path. Dots are reserved path separators, so\n * `sleep_quality.score_value` → `sleepQuality.scoreValue` and nested/flat\n * forms share one identity. Empty components collapse: `sleep..score` →\n * `sleep.score`.\n */\nexport function normalizeFieldPath(path: string): string {\n return path\n .split('.')\n .map(normalizeFieldComponent)\n .filter((component) => component.length > 0)\n .join('.');\n}\n\n/** Classify an observed value into a field value kind. Objects and null are\n * deliberately outside the value kinds: objects contribute nested leaves and\n * null records presence/clearing — neither is a value. */\nexport function valueKindOf(value: unknown): FieldValueKind | 'object' | 'null' | 'undefined' {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return 'array';\n switch (typeof value) {\n case 'number': return 'number';\n case 'string': return 'string';\n case 'boolean': return 'boolean';\n case 'object': return 'object';\n default: return 'undefined';\n }\n}\n\n/** One flattened leaf observation: identity path + kind, the raw value, and\n * the original spelling/shape it was authored with (provenance). */\nexport interface FieldLeaf {\n /** Normalized full path. */\n readonly path: string;\n /** Value kind — 'null' leaves record presence/clearing, never a value. */\n readonly kind: FieldValueKind | NullValueKind;\n readonly value: unknown;\n /** Original path spelling/shape as authored (flat dotted or nested). */\n readonly originalPath: string;\n}\n\n/**\n * Flatten an authored property object into typed leaves.\n *\n * - Dots in keys delimit paths: flat `{\"sleep.score\": 85}` ≡ nested\n * `{sleep:{score:85}}` — one identity.\n * - Objects contribute nested leaves; empty objects contribute nothing.\n * - Arrays are collections: one collection-valued leaf, never per-element\n * observations.\n * - Null records presence under its path without a value.\n */\nexport function flattenFieldLeaves(\n input: Record<string, unknown>,\n prefix = '',\n): FieldLeaf[] {\n const leaves: FieldLeaf[] = [];\n for (const [rawKey, value] of Object.entries(input)) {\n const path = prefix ? `${prefix}.${normalizeFieldPath(rawKey)}` : normalizeFieldPath(rawKey);\n if (!path) continue;\n const kind = valueKindOf(value);\n if (kind === 'object') {\n leaves.push(...flattenFieldLeaves(value as Record<string, unknown>, path));\n } else if (kind !== 'undefined') {\n leaves.push({ path, kind, value, originalPath: prefix ? `${prefix}.${rawKey}` : rawKey });\n }\n }\n return leaves;\n}\n\n/**\n * Collision-free canonical string for a typed variant identity. JSON array\n * encoding keeps a separator character inside a path from masquerading as a\n * structural boundary (`a|number` as path cannot collide with `a` + a\n * `number` dimension).\n */\nexport function fieldRefKey(ref: FieldRef): string {\n return JSON.stringify([ref.path, ref.kind, ref.dimension ?? null]);\n}\n\n/** Parse a {@link fieldRefKey} back into a FieldRef (round-trip helper). */\nexport function fieldRefFromKey(key: string): FieldRef {\n const [path, kind, dimension] = JSON.parse(key) as [string, string, string | null];\n return { path, kind: kind as FieldRef['kind'], ...(dimension ? { dimension } : {}) };\n}\n","/**\n * Unit catalog — the shared home for unit recognition, conversion evidence,\n * and the system default output table (wayfinder decision ticket 21;\n * consumed by wql's arithmetic rewrite, ticket 13).\n *\n * Recognition spellings are case-insensitive through canonical spellings and\n * aliases. Every entry carries its conversion evidence: the physical\n * dimension it measures and the fixed factor converting it to that\n * dimension's base unit. Compound units (speed, pace) convert through their\n * own scale factors to the compound base.\n *\n * `bw` (body-weight-relative load) is deliberately NOT a fixed-factor entry:\n * it requires genuine measurement-time context persisted with the value\n * (ticket 14's conversion evidence) — never a constant kg conversion, never\n * today's body mass reinterpreting history (missing-context limitation).\n */\n\n/** Named result dimensions — the keys of the system default table. */\nexport type DimensionKey =\n | 'mass'\n | 'distance'\n | 'duration'\n | 'count'\n | 'count-rate'\n | 'energy'\n | 'speed'\n | 'pace'\n | 'ratio';\n\n/** Error taxonomy (decision ticket 21). */\nexport type UnitErrorCode =\n | 'unknown-unit'\n | 'dimension-mismatch'\n | 'scale-mismatch'\n | 'missing-context'\n | 'non-finite'\n | 'non-convertible';\n\nexport class UnitConversionError extends Error {\n readonly code: UnitErrorCode;\n constructor(code: UnitErrorCode, message: string) {\n super(message);\n this.name = 'UnitConversionError';\n this.code = code;\n }\n}\n\nexport interface UnitDefinition {\n /** Canonical spelling (e.g. `kg`, `mi`, `min/km`). */\n readonly canonical: string;\n /** Named result dimension. */\n readonly dimension: DimensionKey;\n /** Fixed factor converting a value of this unit to the dimension's base\n * unit (conversion evidence). */\n readonly factor: number;\n /** Registered alternate spellings (case-insensitive at lookup). */\n readonly aliases?: readonly string[];\n}\n\n/**\n * Base units per dimension: mass `kg`, distance `m`, duration `s`,\n * count `count`, energy `cal`, speed `m/s`, pace `min/km`; ratio is\n * unitless (factor 1).\n */\nexport const UNIT_CATALOG: readonly UnitDefinition[] = [\n // Distance — base m\n { canonical: 'm', dimension: 'distance', factor: 1, aliases: ['meter', 'meters', 'metre', 'metres'] },\n { canonical: 'km', dimension: 'distance', factor: 1000, aliases: ['kilometer', 'kilometers', 'kilometre', 'kilometres'] },\n { canonical: 'cm', dimension: 'distance', factor: 0.01, aliases: ['centimeter', 'centimeters'] },\n { canonical: 'mm', dimension: 'distance', factor: 0.001, aliases: ['millimeter', 'millimeters'] },\n { canonical: 'ft', dimension: 'distance', factor: 0.3048, aliases: ['foot', 'feet'] },\n { canonical: 'in', dimension: 'distance', factor: 0.0254, aliases: ['inch', 'inches'] },\n { canonical: 'yd', dimension: 'distance', factor: 0.9144, aliases: ['yard', 'yards'] },\n { canonical: 'mi', dimension: 'distance', factor: 1609.344, aliases: ['mile', 'miles'] },\n // Mass — base kg\n { canonical: 'kg', dimension: 'mass', factor: 1, aliases: ['kilogram', 'kilograms', 'kilo', 'kilos'] },\n { canonical: 'g', dimension: 'mass', factor: 0.001, aliases: ['gram', 'grams'] },\n { canonical: 'lb', dimension: 'mass', factor: 0.45359237, aliases: ['lbs', 'pound', 'pounds'] },\n // Duration — base s\n { canonical: 'ms', dimension: 'duration', factor: 0.001, aliases: ['millisecond', 'milliseconds'] },\n { canonical: 's', dimension: 'duration', factor: 1, aliases: ['sec', 'secs', 'second', 'seconds'] },\n { canonical: 'min', dimension: 'duration', factor: 60, aliases: ['mins', 'minute', 'minutes'] },\n { canonical: 'h', dimension: 'duration', factor: 3600, aliases: ['hr', 'hrs', 'hour', 'hours'] },\n // Count — base count. Test-result scales (\"pull-up\", \"thruster\",\n // \"problem\") are count-dimension scales: one of their units is one rep.\n { canonical: 'count', dimension: 'count', factor: 1 },\n { canonical: 'rep', dimension: 'count', factor: 1, aliases: ['reps'] },\n { canonical: 'pull-up', dimension: 'count', factor: 1 },\n { canonical: 'thruster', dimension: 'count', factor: 1 },\n { canonical: 'problem', dimension: 'count', factor: 1 },\n // Count-rate — base count/s; bpm (beats per minute) is its registered scale\n { canonical: 'count/s', dimension: 'count-rate', factor: 1 },\n { canonical: 'bpm', dimension: 'count-rate', factor: 1 / 60 },\n // Energy — base cal\n { canonical: 'cal', dimension: 'energy', factor: 1, aliases: ['calorie', 'calories'] },\n { canonical: 'kcal', dimension: 'energy', factor: 1000, aliases: ['kilocalorie', 'kilocalories'] },\n // Speed — base m/s\n { canonical: 'm/s', dimension: 'speed', factor: 1 },\n { canonical: 'km/h', dimension: 'speed', factor: 1000 / 3600, aliases: ['kmh', 'kph'] },\n { canonical: 'mph', dimension: 'speed', factor: 1609.344 / 3600 },\n // Pace — base min/km\n { canonical: 'min/km', dimension: 'pace', factor: 1 },\n { canonical: 'min/mi', dimension: 'pace', factor: 1000 / 1609.344 },\n { canonical: 's/m', dimension: 'pace', factor: 1 / 60 },\n // Ratio — unitless base (factor 1); percent via 100% = 1.\n // Dimensionless named scales (arbitrary units, points) share the ratio\n // dimension but are convertible only to the base — never to each other.\n { canonical: 'ratio', dimension: 'ratio', factor: 1, aliases: ['x'] },\n { canonical: '%', dimension: 'ratio', factor: 0.01, aliases: ['pct', 'percent'] },\n { canonical: 'au', dimension: 'ratio', factor: 1, aliases: ['AU'] },\n { canonical: 'pts', dimension: 'ratio', factor: 1, aliases: ['point', 'points'] },\n { canonical: 'rating', dimension: 'ratio', factor: 1, aliases: ['ratings'] },\n];\nconst bySpelling = (() => {\n const map = new Map<string, UnitDefinition>();\n for (const def of UNIT_CATALOG) {\n map.set(def.canonical.toLowerCase(), def);\n for (const alias of def.aliases ?? []) {\n if (!map.has(alias.toLowerCase())) map.set(alias.toLowerCase(), def);\n }\n }\n return map;\n})();\n\n/** Look up a unit by canonical spelling or alias (case-insensitive). */\nexport function lookupUnit(spelling: string): UnitDefinition | undefined {\n return bySpelling.get(spelling.trim().toLowerCase());\n}\n\n/** The named result dimension of a unit spelling, or undefined when the\n * spelling is not in the catalog. */\nexport function dimensionKeyOf(spelling: string): DimensionKey | undefined {\n return lookupUnit(spelling)?.dimension;\n}\n\n/** System default output unit per result dimension (arithmetic contract §5;\n * values agreed in ticket 13, home resolved in ticket 21). Ratio defaults\n * to unitless — `undefined`, never a fabricated unit label. */\nexport const SYSTEM_DEFAULT_OUTPUT_UNIT: Readonly<Record<DimensionKey, string | undefined>> = Object.freeze({\n mass: 'kg',\n distance: 'm',\n duration: 's',\n count: 'count',\n 'count-rate': 'count/s',\n energy: 'cal',\n speed: 'm/s',\n pace: 'min/km',\n ratio: undefined,\n});\n\n/** Default output unit for a result dimension — undefined means unitless. */\nexport function systemDefaultUnit(dimension: DimensionKey): string | undefined {\n return SYSTEM_DEFAULT_OUTPUT_UNIT[dimension];\n}\n\n/**\n * Strict conversion through the catalog's conversion evidence.\n *\n * Errors (`UnitConversionError`) on unknown units (`unknown-unit`) and\n * cross-dimension conversions (`dimension-mismatch`) — an explicit unknown\n * unit is never passed through and never replaced by a default.\n */\nexport function convertViaCatalog(value: number, from: string, to: string): number {\n const fromDef = lookupUnit(from);\n if (!fromDef) throw new UnitConversionError('unknown-unit', `Unknown unit \"${from}\"`);\n const toDef = lookupUnit(to);\n if (!toDef) throw new UnitConversionError('unknown-unit', `Unknown unit \"${to}\"`);\n if (fromDef.dimension !== toDef.dimension) {\n throw new UnitConversionError(\n 'dimension-mismatch',\n `Cannot convert ${from} (${fromDef.dimension}) to ${to} (${toDef.dimension})`,\n );\n }\n // A shared zero dimension vector is not proof that arbitrary named scales\n // are interchangeable (arithmetic contract §5): dimensionless scales are\n // convertible only to the ratio base, never directly to another scale.\n if (fromDef.dimension === 'ratio' && fromDef.canonical !== toDef.canonical) {\n if (fromDef.canonical !== 'ratio' && toDef.canonical !== 'ratio') {\n throw new UnitConversionError(\n 'scale-mismatch',\n `Named scales ${from} and ${to} are not interchangeable`,\n );\n }\n }\n if (!Number.isFinite(value)) {\n throw new UnitConversionError('non-finite', `Non-finite value cannot be converted`);\n }\n return (value * fromDef.factor) / toDef.factor;\n}\n","export interface ICodeMetadata {\n line: number;\n startOffset: number;\n endOffset: number;\n columnStart: number;\n columnEnd: number;\n length: number;\n raw?: string;\n}\n\nexport class CodeMetadata implements ICodeMetadata {\n constructor(\n public line: number,\n public startOffset: number,\n public endOffset: number,\n public length: number,\n public columnStart: number = 0,\n public columnEnd: number = 0,\n public raw: string = '',\n ) {}\n}\n","import { IMetric, MetricType, MetricOrigin } from './Metric';\nimport type { IMetricSource, MetricFilter } from '../contracts/IMetricSource';\nimport { OwnershipResolver, ownershipRank } from '../ownership/OwnershipResolver';\n\n/**\n * MetricContainer — a typed collection for `IMetric` objects.\n *\n * Provides lookup, add, remove, merge, and iteration operations over a\n * flat `IMetric[]` array. Standard way to work with metric collections on\n * `ICodeStatement`, `IRuntimeBlock`, and `OutputStatement`.\n *\n * Numeric indexes are mirrored for backwards compatibility with legacy\n * `metrics[0]` call sites.\n */\nexport class MetricContainer implements IMetricSource, Iterable<IMetric> {\n [index: number]: IMetric;\n private _metrics: IMetric[];\n private _indexedLength = 0;\n private readonly _resolver = new OwnershipResolver();\n readonly id: string | number;\n\n // ── Construction ───────────────────────────────────────────\n\n constructor(metrics?: IMetric[] | MetricContainer, id: string | number = 'metrics') {\n this.id = id;\n if (metrics instanceof MetricContainer) {\n this._metrics = metrics.toArray();\n this.syncIndexProperties();\n return;\n }\n if (Array.isArray(metrics)) {\n this._metrics = [...metrics];\n } else if (metrics != null) {\n this._metrics = [];\n } else {\n this._metrics = [];\n }\n this.syncIndexProperties();\n }\n\n /**\n * Create a container from an existing metric array, MetricContainer, or\n * a deserialized plain object.\n */\n static from(\n metrics: IMetric[] | MetricContainer | undefined | unknown,\n id: string | number = 'metrics',\n ): MetricContainer {\n if (metrics instanceof MetricContainer) {\n return metrics.clone(id);\n }\n if (Array.isArray(metrics)) {\n return new MetricContainer(metrics, id);\n }\n if (metrics != null && typeof metrics === 'object' && '_metrics' in (metrics as object)) {\n const raw = (metrics as Record<string, unknown>)._metrics;\n if (Array.isArray(raw)) {\n return new MetricContainer(raw as IMetric[], id);\n }\n }\n return MetricContainer.empty(id);\n }\n\n /** Create an empty container. */\n static empty(id: string | number = 'metrics'): MetricContainer {\n return new MetricContainer(undefined, id);\n }\n\n /** Create a defensive copy of this container. */\n clone(id: string | number = this.id): MetricContainer {\n return new MetricContainer(this._metrics, id);\n }\n\n // ── Read ───────────────────────────────────────────────────\n\n /** All metrics in insertion order. Returns a defensive copy. */\n get all(): readonly IMetric[] {\n return [...this._metrics];\n }\n\n /** Number of metrics in the container. */\n get length(): number {\n return this._metrics.length;\n }\n\n /** Alias for length */\n get size(): number {\n return this._metrics.length;\n }\n\n /** Whether the container has no metrics. */\n get isEmpty(): boolean {\n return this._metrics.length === 0;\n }\n\n /**\n * Get all metrics of a given MetricType / name, sorted by ownership layer\n * (highest precedence first).\n */\n getByType(type: MetricType | string): IMetric[] {\n const ofType = this._metrics.filter((m) => m.type === type || m.name === type);\n if (ofType.length <= 1) return ofType;\n return [...ofType].sort((a, b) => ownershipRank(b) - ownershipRank(a));\n }\n\n /**\n * Get the highest-precedence metric of a given type/name, or undefined.\n */\n getFirst(type: MetricType | string): IMetric | undefined {\n const byType = this.getByType(type);\n return byType.length > 0 ? byType[0] : undefined;\n }\n\n /**\n * Lookup a metric by type or name.\n */\n get(type: MetricType | string): IMetric | undefined {\n return this.getFirst(type);\n }\n\n /** Whether any metric of the given type/name exists. */\n has(type: MetricType | string): boolean {\n return this._metrics.some((m) => m.type === type || m.name === type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.has(type);\n }\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.resolve(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this._resolver.resolveOne(this._metrics, type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.getByType(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.toArray();\n }\n\n getAll(): IMetric[] {\n return this.toArray();\n }\n\n /**\n * Get all metrics matching the given origin.\n */\n getByOrigin(origin: MetricOrigin): IMetric[] {\n return this._metrics.filter((m) => (m.origin ?? 'parser') === origin);\n }\n\n /**\n * Apply the standard precedence resolution algorithm.\n */\n resolve(filter?: MetricFilter): IMetric[] {\n return this._resolver.resolve(this._metrics, filter);\n }\n\n // ── Write (mutating, returns `this` for chaining) ──────────\n\n /** Append one or more metrics. */\n add(...metrics: IMetric[]): this {\n this._metrics.push(...metrics);\n this.syncIndexProperties();\n return this;\n }\n\n /**\n * Remove metrics matching a predicate.\n * Returns the removed metrics.\n */\n remove(predicate: (m: IMetric) => boolean): IMetric[] {\n const removed: IMetric[] = [];\n this._metrics = this._metrics.filter((m) => {\n if (predicate(m)) {\n removed.push(m);\n return false;\n }\n return true;\n });\n this.syncIndexProperties();\n return removed;\n }\n\n /**\n * Remove all metrics of a given type.\n * Returns the removed metrics.\n */\n removeByType(type: MetricType | string): IMetric[] {\n return this.remove((m) => m.type === type || m.name === type);\n }\n\n /** Remove all metrics. */\n clear(): this {\n this._metrics = [];\n this.syncIndexProperties();\n return this;\n }\n\n /**\n * Replace all metrics of a given type with new ones.\n */\n replaceByType(type: MetricType | string, ...replacements: IMetric[]): IMetric[] {\n const removed = this.removeByType(type);\n this._metrics.push(...replacements);\n this.syncIndexProperties();\n return removed;\n }\n\n // ── Merge ──────────────────────────────────────────────────\n\n /**\n * Merge another container (or raw array) into this one.\n */\n merge(other: MetricContainer | IMetric[] | { metrics: MetricContainer }): this {\n const incoming =\n other instanceof MetricContainer\n ? other._metrics\n : Array.isArray(other)\n ? other\n : other.metrics.toArray();\n\n const byType = new Map<IMetric['type'], IMetric[]>();\n for (const m of incoming) {\n const group = byType.get(m.type) ?? [];\n group.push(m);\n byType.set(m.type, group);\n }\n\n for (const [type, incomingGroup] of byType) {\n const existing = this._metrics.filter((m) => m.type === type);\n\n if (existing.length === 0) {\n this._metrics.push(...incomingGroup);\n continue;\n }\n\n const existingRank = Math.max(...existing.map((m) => ownershipRank(m)));\n const incomingRank = Math.max(...incomingGroup.map((m) => ownershipRank(m)));\n\n if (incomingRank > existingRank) {\n this._metrics = this._metrics.filter((m) => m.type !== type);\n this._metrics.push(...incomingGroup);\n } else if (incomingRank === existingRank) {\n this._metrics.push(...incomingGroup);\n }\n }\n\n this.syncIndexProperties();\n return this;\n }\n\n // ── Iteration / Projection ─────────────────────────────────\n\n /** Iterate over all metrics. */\n [Symbol.iterator](): Iterator<IMetric> {\n return this._metrics[Symbol.iterator]();\n }\n\n /** Filter metrics, returning a new array. */\n filter(predicate: (m: IMetric) => boolean): IMetric[] {\n return this._metrics.filter(predicate);\n }\n\n /** Map metrics to a new array. */\n map<T>(fn: (m: IMetric, index: number) => T): T[] {\n return this._metrics.map(fn);\n }\n\n /** Flat-map metrics to a new array. */\n flatMap<T>(fn: (m: IMetric, index: number) => T | readonly T[]): T[] {\n return this._metrics.flatMap(fn);\n }\n\n /** Find the first metric matching a predicate. */\n find(predicate: (m: IMetric) => boolean): IMetric | undefined {\n return this._metrics.find(predicate);\n }\n\n /** Whether any metric matches the predicate. */\n some(predicate: (m: IMetric) => boolean): boolean {\n return this._metrics.some(predicate);\n }\n\n /** Whether all metrics match the predicate. */\n every(predicate: (m: IMetric) => boolean): boolean {\n return this._metrics.every(predicate);\n }\n\n // ── Conversion ─────────────────────────────────────────────\n\n /** Return a mutable copy of the underlying array. */\n toArray(): IMetric[] {\n return [...this._metrics];\n }\n\n /** Spread-friendly: returns the underlying array (no copy). */\n get raw(): IMetric[] {\n return this._metrics;\n }\n\n private syncIndexProperties(): void {\n for (let i = 0; i < this._indexedLength; i++) {\n delete this[i];\n }\n for (let i = 0; i < this._metrics.length; i++) {\n this[i] = this._metrics[i];\n }\n this._indexedLength = this._metrics.length;\n }\n\n toString(): string {\n return `MetricContainer(${this._metrics.length})[${this._metrics.map((m) => m.type).join(', ')}]`;\n }\n}\n","import { CodeMetadata } from './CodeMetadata';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport type { IMetricSource, MetricFilter } from '../contracts/IMetricSource';\n\nexport interface ICodeStatement extends IMetricSource {\n id: number;\n parent?: number;\n children: number[][];\n exerciseId?: string;\n metrics: MetricContainer;\n isLeaf?: boolean;\n meta: CodeMetadata;\n metricMeta: Map<IMetric, CodeMetadata>;\n line?: number;\n text?: string;\n raw?: string;\n dialect?: string;\n}\n\nexport abstract class CodeStatement implements ICodeStatement, IMetricSource {\n abstract id: number;\n abstract parent?: number;\n abstract children: number[][];\n abstract meta: CodeMetadata;\n abstract metrics: MetricContainer;\n abstract metricMeta: Map<IMetric, CodeMetadata>;\n abstract isLeaf?: boolean;\n exerciseId?: string;\n line?: number;\n text?: string;\n raw?: string;\n dialect?: string;\n\n // ── IMetricSource ─────────────────────────────────────────────\n\n hasMetric(type: MetricType | string): boolean {\n return this.metricContainer.hasMetric(type);\n }\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metricContainer.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metricContainer.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metricContainer.getAllMetricsByType(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metricContainer.rawMetrics;\n }\n\n private get metricContainer(): MetricContainer {\n return this.metrics instanceof MetricContainer\n ? this.metrics\n : MetricContainer.from(this.metrics as unknown as IMetric[], this.id);\n }\n}\n\nexport class ParsedCodeStatement extends CodeStatement {\n id: number = 0;\n parent?: number;\n children: number[][] = [];\n meta: CodeMetadata = new CodeMetadata(0, 0, 0, 0);\n private _metrics: MetricContainer = MetricContainer.empty();\n metricMeta: Map<IMetric, CodeMetadata> = new Map();\n isLeaf?: boolean;\n\n get metrics(): MetricContainer {\n return this._metrics;\n }\n\n set metrics(metrics: MetricContainer | IMetric[]) {\n this._metrics = MetricContainer.from(metrics, this.id);\n }\n\n constructor(init?: Partial<ParsedCodeStatement>) {\n super();\n if (init) {\n Object.assign(this, init);\n if (init.metrics) {\n this.metrics = MetricContainer.from(init.metrics, this.id);\n }\n if (!this.metricMeta) {\n this.metricMeta = new Map();\n }\n }\n }\n}\n","import { ICodeStatement, CodeStatement } from './CodeStatement';\nimport { IMetric } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource } from '../contracts/IMetricSource';\n\n/**\n * Output statement types indicating what kind of result this represents.\n *\n * - 'segment': A timed portion of execution (e.g., a round, an effort interval)\n * - 'milestone': A notable event during execution (e.g., halfway point, personal record)\n * - 'system': Debug/diagnostic output from lifecycle events\n * - 'event': Tracks external stimuli or internal triggers\n * - 'group': Identified segment with children\n * - 'load': Initial script state\n * - 'compiler': Behavior configuration and setup\n * - 'analytics': Output generated by the analytics engine\n */\nexport type OutputStatementType =\n | 'segment'\n | 'milestone'\n | 'completion'\n | 'metric'\n | 'system'\n | 'event'\n | 'group'\n | 'load'\n | 'compiler'\n | 'analytics';\n\n/**\n * IOutputStatement extends ICodeStatement to represent runtime-generated output.\n *\n * This is the return type of execution — what \"came out\" of running a statement.\n */\nexport interface IOutputStatement extends ICodeStatement, IMetricSource {\n readonly id: number;\n readonly outputType: OutputStatementType;\n readonly timeSpan: TimeSpan;\n readonly sourceStatementId?: number;\n readonly sourceBlockKey: string;\n readonly stackLevel: number;\n readonly metrics: MetricContainer;\n readonly metricMeta: Map<IMetric, CodeMetadata>;\n readonly completionReason?: string;\n readonly statement?: ICodeStatement;\n readonly timestamp?: number;\n}\n\n/**\n * Options for creating an OutputStatement.\n */\nexport interface OutputStatementOptions {\n /** Output type classification */\n outputType: OutputStatementType;\n\n /** Execution timing */\n timeSpan: TimeSpan;\n\n /** The block key that produced this output */\n sourceBlockKey?: string;\n\n /** Stack level (depth) when this output was emitted */\n stackLevel?: number;\n\n /** The source statement ID (optional) */\n sourceStatementId?: number;\n\n /** Original source line/text/dialect (when rebuilding from stored records) */\n line?: number;\n text?: string;\n dialect?: string;\n\n /** Runtime-collected metrics */\n metrics?: MetricContainer | IMetric[];\n\n /** Map of metrics to metadata */\n metricMeta?: Map<IMetric, CodeMetadata>;\n\n /** Reason the block completed (e.g., 'user-advance', 'forced-pop') */\n completionReason?: string;\n\n /** Parent output statement ID (for hierarchy) */\n parent?: number;\n\n /** Child output statement groups (for hierarchy) */\n children?: number[][];\n}\n\n/**\n * Concrete implementation of IOutputStatement.\n */\nexport class OutputStatement extends CodeStatement implements IOutputStatement {\n private static nextId = 1000000;\n\n readonly id: number;\n readonly outputType: OutputStatementType;\n readonly timeSpan: TimeSpan;\n\n readonly sourceStatementId?: number;\n readonly sourceBlockKey: string;\n readonly stackLevel: number;\n readonly metrics: MetricContainer;\n readonly metricMeta: Map<IMetric, CodeMetadata>;\n\n readonly completionReason?: string;\n readonly parent?: number;\n readonly children: number[][];\n readonly isLeaf: boolean;\n readonly meta: CodeMetadata;\n readonly statement?: ICodeStatement;\n readonly timestamp?: number;\n\n constructor(\n optionsOrStatement: OutputStatementOptions | ICodeStatement,\n metricsArg?: MetricContainer | IMetric[],\n timestamp?: number,\n ) {\n super();\n if (\n optionsOrStatement &&\n 'outputType' in optionsOrStatement &&\n 'timeSpan' in optionsOrStatement\n ) {\n const options = optionsOrStatement as OutputStatementOptions;\n this.id = OutputStatement.nextId++;\n this.outputType = options.outputType;\n this.timeSpan = options.timeSpan;\n this.sourceBlockKey = options.sourceBlockKey ?? '';\n this.sourceStatementId = options.sourceStatementId;\n this.line = options.line;\n this.text = options.text;\n this.dialect = options.dialect;\n this.stackLevel = options.stackLevel ?? 0;\n this.metrics = MetricContainer.from(options.metrics, this.id);\n this.metricMeta = options.metricMeta ?? new Map();\n this.completionReason = options.completionReason;\n this.parent = options.parent;\n this.children = options.children ?? [];\n this.isLeaf = this.children.length === 0;\n this.meta = new CodeMetadata(0, 0, 0, 0);\n } else {\n const stmt = optionsOrStatement as ICodeStatement;\n this.id = OutputStatement.nextId++;\n this.statement = stmt;\n this.outputType = 'segment';\n this.timeSpan = { started: timestamp ?? Date.now() };\n this.sourceBlockKey = '';\n this.sourceStatementId = typeof stmt?.id === 'number' ? stmt.id : undefined;\n this.stackLevel = 0;\n this.metrics = MetricContainer.from(metricsArg, this.id);\n this.metricMeta = new Map();\n this.children = [];\n this.isLeaf = true;\n this.meta = stmt?.meta ?? new CodeMetadata(0, 0, 0, 0);\n this.line = stmt?.line;\n this.text = stmt?.text;\n this.dialect = stmt?.dialect;\n this.timestamp = timestamp ?? Date.now();\n }\n }\n\n // IMetricSource implementation is inherited from CodeStatement\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","export interface IBlockKey {\n readonly value: string;\n toString(): string;\n valueOf(): string;\n equals(other: IBlockKey): boolean;\n}\n\nexport class BlockKey implements IBlockKey {\n readonly value: string;\n\n constructor(value?: string) {\n this.value =\n value ??\n (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2));\n }\n\n toString(): string {\n return this.value;\n }\n\n valueOf(): string {\n return this.value;\n }\n\n equals(other: IBlockKey): boolean {\n return this.value === other?.value;\n }\n}\n","/**\n * Content-stable identity for a workout block.\n *\n * A 32-bit FNV-1a hash of the trimmed fenced content, formatted as `bc-<8 hex>`.\n * Survives clone / reorder / edit-above so results and facts keyed by it stay\n * linked across runs.\n */\nexport function blockContentId(content: string): string {\n const normalized = content.trim();\n let hash = 0x811c9dc5;\n for (let i = 0; i < normalized.length; i++) {\n hash ^= normalized.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return `bc-${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n","import type { StoredOutputStatement } from './results';\n\n// ---------------------------------------------------------------------------\n// Segment data types\n// ---------------------------------------------------------------------------\nexport type SegmentDataType =\n | 'script'\n | 'youtube'\n | 'markdown'\n | 'header'\n | 'frontmatter'\n | 'wod'\n | 'title'\n | 'h1'\n | 'h2'\n | 'h3'\n | 'h4'\n | 'h5'\n | 'h6';\n\n// ---------------------------------------------------------------------------\n// Note — root container\n// ---------------------------------------------------------------------------\nexport type NoteKind = 'journal' | 'template' | 'playground' | 'feed' | 'dashboard' | 'page' | (string & {});\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n date?: number; // Domain date of the record (e.g. workout date, publish date)\n createdAt: number; // Creation timestamp\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: string[];\n /** Original seed file path (e.g. `markdown/collections/girls/fran.md`) — the\n * deterministic UUID is derived from this path; retained for seed content\n * reconstruction (canvas routes, collection READMEs, block-index lookup). */\n sourcePath?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Page — named/slug-addressable grouped collection of notes\n// ---------------------------------------------------------------------------\nexport interface Page {\n id: string;\n date?: string; // YYYY-MM-DD (publish/calendar date)\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// PageNote — N:M junction linking a Note to a Page\n// ---------------------------------------------------------------------------\nexport interface PageNote {\n id: string; // UUID\n pageId: string;\n noteId: string;\n position?: number;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general' | (string & {});\n\nexport interface TagTypeRecord {\n id: string;\n name: string;\n label: string;\n color?: string;\n createdAt: number;\n}\n\nexport interface Tag {\n id: string;\n label: string;\n type?: TagType;\n createdAt: number;\n}\n\nexport interface NoteTag {\n id: string;\n noteId: string;\n tagId: string;\n}\n\n// ---------------------------------------------------------------------------\n// NoteSegment — versioned content chunk\n// ---------------------------------------------------------------------------\nexport interface NoteSegment {\n id: string;\n version: number;\n noteId: string;\n position?: number;\n pageId?: string;\n dataType: SegmentDataType;\n data: unknown;\n rawContent: string;\n createdAt: number;\n updatedAt?: number;\n isHistory?: boolean;\n}\n\n// ---------------------------------------------------------------------------\n// BlockIndexRow — derived block index for WQL content queries\n// ---------------------------------------------------------------------------\nexport interface BlockIndexRow {\n /** Composite key: `${noteId}:${segmentId}:${segmentVersion}` */\n id: string;\n noteId: string;\n segmentId: string;\n segmentVersion: number;\n position?: number;\n dataType: string;\n blockContentId?: string;\n rawContent: string;\n noteTitle: string;\n createdAt: number;\n isStatic?: boolean;\n sourceId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Session — execution log (renamed from WorkoutResult; table results -> sessions in DB V20)\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface Session {\n id: string;\n segmentId?: string;\n segmentVersion?: number;\n noteId: string;\n blockId?: string;\n blockContentId?: string;\n version?: number;\n origin?: ResultOrigin;\n pageId?: string;\n /** Write-path lifecycle (ticket 005): row born 'in-progress' at workout\n * start, flipped to 'completed' at finalize. Absent = 'completed'\n * (legacy rows predate streaming). */\n status?: 'in-progress' | 'completed';\n\n /** When workout started */\n startTime: number;\n\n /** When workout ended */\n endTime: number;\n\n /** Total elapsed time (ms) */\n duration: number;\n\n /** Rounds completed (for rounds-based workouts) */\n roundsCompleted?: number;\n\n /** Total rounds (for rounds-based workouts) */\n totalRounds?: number;\n\n /** Reps completed (for rep-based workouts) */\n repsCompleted?: number;\n\n /** Whether workout was completed or stopped early */\n completed: boolean;\n\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Attachment — external temporal data blobs (GPS / HR)\n// ---------------------------------------------------------------------------\nexport interface Attachment {\n id: string;\n noteId: string;\n pageId?: string;\n resultId?: string;\n mimeType: string;\n label: string;\n data: ArrayBuffer | string;\n timeSpan: {\n start: number;\n end: number;\n };\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// AnalyticsDataPoint — de-normalized metric for cross-workout queries\n// ---------------------------------------------------------------------------\nexport interface AnalyticsDataPoint {\n id: string;\n noteId: string;\n blockContentId?: string;\n origin?: ResultOrigin;\n pageId?: string;\n grain?: 'event' | 'summary';\n effortSlug?: string;\n discipline?: string;\n intensityTier?: string;\n grade?: string;\n /** User-authored categorical dims (custom property metrics and grouped\n * partitions) — normalized key → value, resolved by factTagValue after\n * the structural switch so `by {coach}` / `{coach:greg}` work. */\n dimensions?: Record<string, string>;\n segmentId: string;\n segmentVersion: number;\n resultId: string;\n type: string;\n value: unknown;\n unit?: string;\n label: string;\n metricKey?: string;\n metricLabel?: string;\n metricUnit?: string;\n /** Typed field reference provenance (ticket 11) — normalized path + kind\n * of the variant this observation belongs to. */\n fieldRef?: { path: string; kind: string; dimension?: string };\n /** The observation's own civil date (YYYY-MM-DD) when it is date-only\n * (ticket 12) — grouping uses this instead of a fabricated instant. */\n metricDate?: string;\n /** Temporal kind of the observation's anchor (ticket 12). */\n temporalKind?: 'instant' | 'civil-date';\n /** Ticket 14 provenance carried onto the fact (ticket 16 selection). */\n representationKind?: 'direct' | 'calculated' | 'substitute_summary';\n summaryCoverage?: SummaryCoverage;\n reducerStats?: ReducerStats;\n timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// EventRecord — THE single stored record for all workout data (V21).\n// Statement rows are the archival source: sessions hold execution metadata\n// only, and display/replay shapes are reconstructed from these rows.\n// ---------------------------------------------------------------------------\n\n/** Store-row kind: 'event' = raw statement row, 'summary' = folded row.\n * Authorship lives on `origin` (engine-authored summaries are finalize-owned;\n * user-authored summaries — wellness — are reconcile-owned). Ticket 005. */\nexport type EventGrain = 'event' | 'summary';\n\n/** Known producer values for the open `outputType` vocabulary (ticket 002:\n * open string + known-values module; unknowns are stored and returned,\n * matched only by kind-agnostic logic). */\nexport const KNOWN_OUTPUT_TYPES = [\n 'segment',\n 'system',\n 'load',\n 'event',\n 'compiler',\n 'completion',\n 'analytics',\n 'wellness',\n] as const;\n// EventRecord — THE single stored record for all workout data (renamed from UnifiedEventRecord)\n// ---------------------------------------------------------------------------\nexport interface EventRecord {\n /**\n * Event rows: `${resultId}:${seq}` — immutable, append-only.\n * Summary rows: `${resultId}:summary:${metricKey}[:k=v…]` — deterministic\n * content key; re-finalize overwrites cleanly (ticket 002).\n * Wellness rows: `wellness:${noteId}:${key}` — reconcile-owned upserts.\n */\n id: string;\n resultId: string;\n noteId: string;\n /** Content-stable cross-workout join key (promoted, ticket 003 amendment). */\n blockContentId?: string;\n pageId?: string;\n origin?: ResultOrigin;\n /** Canonical time — when the workout happened, never when derived. */\n timestamp: number;\n grain: EventGrain;\n effortSlug?: string;\n /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n /** Typed metric array; EXACTLY ONE entry when grain:'summary'. Summary\n * fold identity (canonicalKey, groupTags, effort metadata) lives in\n * metrics[0].metadata — shape-uniform with events. */\n metrics: StoredOutputStatement['metrics'];\n timeSpan?: { started: number; ended?: number };\n sourceBlockKey?: string;\n sourceStatementId?: number;\n line?: number;\n text?: string;\n dialect?: string;\n stackLevel?: number;\n completionReason?: string;\n segmentId?: string;\n segmentVersion?: number;\n /** Per-metric temporal anchors (ticket 12) — parallel to `metrics` when\n * the producing statement carries its own instants/dates:\n * 'instant' = recorded occurrence instant; 'civil-date' = recorded civil\n * date (date-only wellness), never a fabricated midnight. The row\n * timestamp remains the V16 fetch anchor until the by-metricDate index\n * (ticket 14); it must not relocate a metric whose own date differs. */\n metricTemporal?: MetricTemporal[];\n /** Ticket 14: civil-date keys (d:YYYY-MM-DD) of every metricTemporal with\n * temporalKind 'civil-date' — the multiEntry `by-metric-date` index\n * source. Kept distinct from the instant index on purpose: a date-only\n * observation is never a midnight instant. */\n metricDateKeys?: string[];\n /** Ticket 14 provenance: how this row represents the underlying\n * observations — directly recorded, calculated, or a substitute summary. */\n representationKind?: 'direct' | 'calculated' | 'substitute_summary';\n /** Ticket 14: the temporal/production scope a substitute summary covers. */\n summaryCoverage?: SummaryCoverage;\n /** Ticket 14: retained reducer statistics for substitution proofs. */\n reducerStats?: ReducerStats;\n}\n\n/** Scope descriptor of a substitute summary's coverage (ticket 14). */\nexport interface SummaryCoverage {\n scope: 'workout' | 'effort' | 'partition';\n effortSlug?: string;\n /** Partition identity (group-tag pairs, key-sorted). */\n groupTags?: Record<string, string>;\n}\n\n/** Retained statistics for substitution proofs (ticket 16 consumes).\n * `observedCount` is the true represented observation count — never\n * invented for legacy rows that lack it (undefined = insufficient\n * evidence, not 1). */\nexport interface ReducerStats {\n observedCount?: number;\n sum?: number;\n min?: number;\n max?: number;\n}\n\nexport interface MetricTemporal {\n temporalKind: 'instant' | 'civil-date';\n /** Occurrence instant (ms epoch) when temporalKind === 'instant'. */\n instant?: number;\n /** Civil YYYY-MM-DD when temporalKind === 'civil-date'. */\n civilDate?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Field Catalog — V17 derived stores (wayfinder datadog-analytics tickets\n// 14/15). The catalog is a derived index of saved data: reference counts\n// track supporting source records, rows prune at zero, and deltas commit\n// atomically with the source mutation.\n// ---------------------------------------------------------------------------\n\n/** One typed field identity in the catalog. `id` is the collision-free\n * typed key (see fieldRefKey in fields/fieldIdentity). */\nexport interface FieldCatalogEntry {\n id: string;\n /** Normalized full path — the ordered prefix-lookup key for typeahead. */\n path: string;\n kind: string;\n /** Physical/named dimension of a numeric variant, when known. */\n dimension?: string;\n /** Observed original spellings → supporting-source counts (provenance,\n * not identity); a spelling disappears when its final support does. */\n spellings: Record<string, number>;\n /** Observed effective units → supporting-source counts. */\n units: Record<string, number>;\n /** Number of source records currently supporting this identity. */\n sourceCount: number;\n firstSeen: number;\n lastSeen: number;\n}\n\n/** One field identity a source record supports, with everything needed to\n * reverse the contribution (per-source unit/spelling/value evidence). */\nexport interface FieldContribution {\n fieldId: string;\n path: string;\n kind: string;\n unit?: string;\n /** Original spelling this source used. */\n spelling?: string;\n /** Categorical value (string/boolean fields only) — original spelling. */\n value?: string;\n}\n\n/** The contribution set of one stable source record — the reversal record\n * that makes re-saves idempotent and deletions reversible. Contributions\n * are attributed to their owning row id, so streaming appends, finalize\n * replacement, and cascade deletes reverse exactly the affected rows. */\nexport interface FieldSourceRecord {\n /** `${entityKind}:${recordId}` — e.g. `result:r1`, `note:n1`. */\n id: string;\n contributions: Array<FieldContribution & { rowId: string }>;\n}\n\n/** One observed categorical value of a field (string/boolean only). */\nexport interface FieldValueRecord {\n key: [string, string]; // [fieldId, value] — value keeps original spelling\n fieldId: string;\n value: string;\n sourceCount: number;\n}\n\n/** Backfill progress/completion marker (field_catalog_meta store). */\nexport interface CatalogBackfillState {\n id: 'backfill';\n status: 'initializing' | 'complete';\n /** Last processed source key per source store (resume cursor). */\n cursor?: { results?: string; notes?: string; events?: string };\n revision: number;\n updatedAt: number;\n}\n","import type { ICodeStatement } from '../models/CodeStatement';\nimport type { WorkoutResults } from './results';\n\n/**\n * State of a WOD block\n */\nexport type ScriptBlockState =\n | 'idle'\n | 'parsing'\n | 'parsed'\n | 'error'\n | 'starting'\n | 'running'\n | 'paused'\n | 'completed'\n | 'stopped';\n\n/**\n * Parse error information\n */\nexport interface ParseError {\n message: string;\n line?: number;\n column?: number;\n token?: unknown;\n excerpt?: string;\n severity?: 'error' | 'warning' | 'info';\n}\n\n/** Workout fence tags — `time` is runnable, `log` is recorded */\nexport type FenceDialect = 'time' | 'log';\n\n/** Ordered list of recognised workout fence tags */\nexport const VALID_FENCE_DIALECTS: FenceDialect[] = ['time', 'log'];\n\n/**\n * Run affordance for a fence base tag:\n * `'time'` -> `'run'` (runnable) · `'log'` -> `'log'` (log-mode runtime) · else `null`.\n */\nexport function runAffordance(baseTag: string): 'run' | 'log' | null {\n if (baseTag === 'time') return 'run';\n if (baseTag === 'log') return 'log';\n return null;\n}\n\n/** Section types the editor can parse and render */\nexport type SectionType =\n | 'title'\n | 'markdown'\n | 'time'\n | 'log'\n | 'frontmatter'\n | 'embed'\n | 'code'\n | 'widget'\n | 'query';\n\n/** Workout section types — the runnable/recorded fence tags */\nexport type WorkoutSectionType = Extract<SectionType, FenceDialect>;\n\n/** Type guard for workout sections */\nexport function isWorkoutSectionType(type: SectionType): type is WorkoutSectionType {\n return type === 'time' || type === 'log';\n}\n\n/** Typed front matter subtypes */\nexport type FrontMatterSubtype = 'default' | 'youtube' | 'strava' | 'amazon' | 'file' | 'effort';\n\n/**\n * Represents a single WOD block within the markdown document\n */\nexport interface ScriptBlock {\n /** Unique identifier for this block */\n id: string;\n /** Content-stable identity */\n contentId?: string;\n /** Workout fence tag ('time' runnable / 'log' recorded) */\n dialect?: FenceDialect;\n /** Sport suffix from the fence */\n sport?: string;\n /** Line number where ```time/```log appears (0-indexed) */\n startLine: number;\n /** Line number where closing ``` appears (0-indexed) */\n endLine: number;\n /** Raw text content of the WOD block */\n content: string;\n /** Parsed statements (populated after parsing) */\n statements?: ICodeStatement[];\n /** Parse errors, if any */\n errors?: ParseError[];\n /** Execution state */\n state: ScriptBlockState;\n /** Collected workout data (after completion) */\n results?: WorkoutResults;\n /** Block version */\n version: number;\n /** Creation timestamp */\n createdAt: number;\n}\n\n/**\n * A single section in the document — the atomic unit of display and editing.\n */\nexport interface Section {\n id: string;\n contentId?: string;\n type: SectionType;\n subtype?: string;\n rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: string;\n widgetName?: string;\n queryType?: string;\n queryError?: string;\n scriptBlock?: ScriptBlock;\n properties?: Record<string, string>;\n frontmatterType?: FrontMatterSubtype;\n embed?: {\n type: 'image' | 'link' | 'youtube';\n label: string;\n url: string;\n isImage: boolean;\n };\n version: number;\n createdAt: number;\n deleted?: boolean;\n}\n\n/**\n * The full document as an ordered section list.\n */\nexport interface SectionDocument {\n sections: Section[];\n totalLines: number;\n activeSectionId: string | null;\n}\n","/**\n * Notebook Types\n *\n * A notebook is a named, tag-based collection of workout entries.\n */\n\nexport interface Notebook {\n id: string;\n name: string;\n description: string;\n icon: string;\n createdAt: number;\n lastEditedAt: number;\n}\n\nexport const NOTEBOOK_TAG_PREFIX = 'notebook:';\n\nexport const toNotebookTag = (notebookId: string): string =>\n `${NOTEBOOK_TAG_PREFIX}${notebookId}`;\n\nexport const fromNotebookTag = (tag: string): string | null =>\n tag.startsWith(NOTEBOOK_TAG_PREFIX) ? tag.slice(NOTEBOOK_TAG_PREFIX.length) : null;\n\nexport const isNotebookTag = (tag: string): boolean =>\n tag.startsWith(NOTEBOOK_TAG_PREFIX);\n","import type { FenceDialect, ScriptBlock } from '../types/section';\nimport { VALID_FENCE_DIALECTS } from '../types/section';\n\n/**\n * Try to match a line against known workout fence patterns.\n * Returns the base tag and optional :sport suffix, or null otherwise.\n */\nexport function matchDialectFence(trimmedLine: string): { dialect: FenceDialect; sport?: string } | null {\n if (!trimmedLine.startsWith('```')) return null;\n const tag = trimmedLine.slice(3).split(/[\\s\\t]/)[0].toLowerCase();\n const [base, sport] = tag.split(':', 2);\n if ((VALID_FENCE_DIALECTS as readonly string[]).includes(base)) {\n return { dialect: base as FenceDialect, sport: sport || undefined };\n }\n return null;\n}\n\n/**\n * Detects all WOD blocks in markdown content.\n * Recognises ```time and ```log as valid workout fences (optional :sport suffix).\n *\n * @param content - Markdown content to parse\n * @returns Array of detected WOD blocks (with dialect set)\n */\nexport function detectScriptBlocks(content: string): ScriptBlock[] {\n const lines = content.split('\\n');\n const blocks: ScriptBlock[] = [];\n let inBlock = false;\n let currentBlock: Partial<ScriptBlock> = {};\n let blockContent: string[] = [];\n\n lines.forEach((line, index) => {\n const trimmedLine = line.trim();\n\n if (!inBlock) {\n const fence = matchDialectFence(trimmedLine);\n if (fence) {\n inBlock = true;\n const now = Date.now();\n currentBlock = {\n id: `${fence.dialect}-block-${now}-${Math.random().toString(36).slice(2, 9)}`,\n dialect: fence.dialect,\n sport: fence.sport,\n startLine: index,\n state: 'idle',\n version: 1,\n createdAt: now,\n };\n blockContent = [];\n return;\n }\n }\n\n if (inBlock && trimmedLine.startsWith('```')) {\n inBlock = false;\n currentBlock.endLine = index;\n currentBlock.content = blockContent.join('\\n');\n blocks.push(currentBlock as ScriptBlock);\n currentBlock = {};\n blockContent = [];\n } else if (inBlock) {\n blockContent.push(line);\n }\n });\n\n if (inBlock && currentBlock.startLine !== undefined) {\n currentBlock.endLine = lines.length - 1;\n currentBlock.content = blockContent.join('\\n');\n blocks.push(currentBlock as ScriptBlock);\n }\n\n return blocks;\n}\n\n/**\n * Find which block contains a given line number.\n *\n * @param blocks - Array of WOD blocks\n * @param lineNumber - Line number to search for (0-indexed)\n * @returns The block containing the line, or null if not found\n */\nexport function findBlockAtLine(\n blocks: ScriptBlock[],\n lineNumber: number\n): ScriptBlock | null {\n return (\n blocks.find(\n (block) => lineNumber >= block.startLine && lineNumber <= block.endLine\n ) ?? null\n );\n}\n\n/**\n * Extract WOD block content from markdown (without backticks).\n *\n * @param content - Full markdown content\n * @param startLine - Start line of block (0-indexed)\n * @param endLine - End line of block (0-indexed)\n * @returns Extracted block content\n */\nexport function extractBlockContent(\n content: string,\n startLine: number,\n endLine: number\n): string {\n const lines = content.split('\\n');\n return lines.slice(startLine + 1, endLine).join('\\n');\n}\n","import { blockContentId } from '../models/blockContentId';\nimport type {\n FenceDialect,\n FrontMatterSubtype,\n ScriptBlock,\n Section,\n SectionType,\n} from '../types/section';\nimport { detectScriptBlocks } from './blockDetection';\n\n/** Metadata regex: <!-- section-metadata id:UUID version:N created:TS --> */\nconst METADATA_REGEX = /<!--\\s*section-metadata\\s+id:(\\S+)\\s+version:(\\d+)\\s+created:(\\d+)\\s*-->/i;\n\nexport interface SectionMetadata {\n id: string;\n version: number;\n createdAt: number;\n}\n\n/**\n * Extract metadata from a string of text.\n * Returns the metadata and the text with metadata stripped.\n */\nfunction extractMetadata(text: string): { metadata: SectionMetadata | null; cleanText: string } {\n const match = text.match(METADATA_REGEX);\n if (!match) return { metadata: null, cleanText: text };\n\n return {\n metadata: {\n id: match[1],\n version: parseInt(match[2], 10),\n createdAt: parseInt(match[3], 10),\n },\n cleanText: text.replace(METADATA_REGEX, '').trim(),\n };\n}\n\n\n/**\n * Generate a deterministic section ID from type, startLine (0-indexed), and a content hash.\n * Stable across re-parses when structure doesn't change.\n */\nexport function generateSectionId(type: SectionType | string, startLine: number, content: string): string {\n let hash = 0;\n for (let i = 0; i < content.length && i < 64; i++) {\n hash = ((hash << 5) - hash + content.charCodeAt(i)) | 0;\n }\n const hashHex = (hash >>> 0).toString(16).padStart(8, '0');\n return `${type}-${startLine}-${hashHex}`;\n}\n\nexport { blockContentId };\n\nfunction detectUrlSubtype(url: string): FrontMatterSubtype | null {\n if (!url) return null;\n const withoutScheme = url.trim().replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, '');\n const host = withoutScheme.split(/[/?#:]/, 1)[0].toLowerCase();\n if (host === 'youtube.com' || host.endsWith('.youtube.com') || host === 'youtu.be') return 'youtube';\n if (host === 'strava.com' || host.endsWith('.strava.com')) return 'strava';\n if (host === 'amazon.com' || host.endsWith('.amazon.com') || host === 'amzn.to') return 'amazon';\n return null;\n}\n\nfunction resolveFrontMatterSubtype(props: Record<string, string>): FrontMatterSubtype {\n const typeValue = (props['type'] || '').toLowerCase();\n if (typeValue === 'youtube') return 'youtube';\n if (typeValue === 'strava') return 'strava';\n if (typeValue === 'amazon') return 'amazon';\n if (typeValue === 'file') return 'file';\n if (typeValue === 'effort') return 'effort';\n\n const url = props['url'] || props['link'] || '';\n if (url) {\n const detected = detectUrlSubtype(url);\n if (detected) return detected;\n }\n\n if (\n props['baseAttributes'] !== undefined ||\n props['discipline'] !== undefined ||\n props['effortType'] !== undefined ||\n props['targetRPE'] !== undefined ||\n props['equipment'] !== undefined ||\n props['aliases'] !== undefined ||\n props['derivation'] !== undefined\n ) {\n return 'effort';\n }\n\n return 'default';\n}\n\nfunction parseFrontMatterProperties(innerLines: string[]): Record<string, string> {\n const props: Record<string, string> = {};\n for (const line of innerLines) {\n const match = line.match(/^([^:]+):\\s*(.*)$/);\n if (match) {\n props[match[1].trim()] = match[2].trim();\n }\n }\n return props;\n}\n\nfunction matchMarkdownEmbed(trimmed: string): {\n type: 'image' | 'link' | 'youtube';\n label: string;\n url: string;\n isImage: boolean;\n} | null {\n const match = trimmed.match(/^(!)?\\[([^\\]]*)\\]\\(([^)]+)\\)$/);\n if (!match) return null;\n\n const isImage = !!match[1];\n const label = match[2];\n const url = match[3];\n\n let type: 'image' | 'link' | 'youtube' = isImage ? 'image' : 'link';\n if (/youtube\\.com|youtu\\.be/i.test(url)) {\n type = 'youtube';\n }\n\n return { type, label, url, isImage };\n}\n\ninterface FrontMatterRange {\n startLine: number;\n endLine: number;\n}\n\nfunction detectFrontMatterBlocks(lines: string[], scriptBlocks: ScriptBlock[]): FrontMatterRange[] {\n const ranges: FrontMatterRange[] = [];\n let i = 0;\n\n while (i < lines.length) {\n const inScript = scriptBlocks.some((b) => i >= b.startLine && i <= b.endLine);\n if (inScript) {\n i++;\n continue;\n }\n\n if (lines[i].trim() === '---') {\n const openLine = i;\n let j = i + 1;\n while (j < lines.length) {\n const inScriptInner = scriptBlocks.some((b) => j >= b.startLine && j <= b.endLine);\n if (inScriptInner) {\n j++;\n continue;\n }\n if (lines[j].trim() === '---') {\n ranges.push({ startLine: openLine, endLine: j });\n i = j + 1;\n break;\n }\n j++;\n }\n if (j >= lines.length) {\n i++;\n }\n } else {\n i++;\n }\n }\n return ranges;\n}\n\nexport function parseDocumentSections(content: string, scriptBlocks?: ScriptBlock[]): Section[] {\n if (!content) return [];\n\n const blocks = scriptBlocks ?? detectScriptBlocks(content);\n const lines = content.split('\\n');\n const sections: Section[] = [];\n const fmRanges = detectFrontMatterBlocks(lines, blocks);\n\n const now = Date.now();\n let currentLine = 0;\n let isFirstTextBlock = true;\n\n function flushMarkdownLines(mdLines: string[], startLine: number) {\n if (mdLines.length === 0) return;\n\n let currentGroup: string[] = [];\n let groupStartLine = startLine;\n\n const flushGroup = () => {\n if (currentGroup.length > 0) {\n const raw = currentGroup.join('\\n');\n const { metadata, cleanText } = extractMetadata(raw);\n const trimmed = cleanText.trim();\n const embed = currentGroup.length === 1 ? matchMarkdownEmbed(trimmed) : null;\n\n if (embed) {\n sections.push({\n id: metadata?.id || generateSectionId('embed', groupStartLine, trimmed),\n type: 'embed',\n rawContent: cleanText,\n displayContent: cleanText,\n startLine: groupStartLine,\n endLine: groupStartLine,\n lineCount: 1,\n embed,\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n });\n } else if (isFirstTextBlock) {\n isFirstTextBlock = false;\n sections.push({\n id: metadata?.id || generateSectionId('title', groupStartLine, cleanText),\n type: 'title',\n rawContent: cleanText,\n displayContent: cleanText,\n startLine: groupStartLine,\n endLine: groupStartLine + currentGroup.length - 1,\n lineCount: currentGroup.length,\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n });\n } else {\n sections.push({\n id: metadata?.id || generateSectionId('markdown', groupStartLine, cleanText),\n type: 'markdown',\n rawContent: cleanText,\n displayContent: cleanText,\n startLine: groupStartLine,\n endLine: groupStartLine + currentGroup.length - 1,\n lineCount: currentGroup.length,\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n });\n }\n }\n currentGroup = [];\n };\n\n for (let i = 0; i < mdLines.length; i++) {\n const line = mdLines[i];\n if (line.trim().length === 0) {\n flushGroup();\n sections.push({\n id: generateSectionId('markdown', startLine + i, ''),\n type: 'markdown',\n rawContent: '',\n displayContent: '',\n startLine: startLine + i,\n endLine: startLine + i,\n lineCount: 1,\n version: 1,\n createdAt: now,\n });\n groupStartLine = startLine + i + 1;\n } else {\n currentGroup.push(line);\n }\n }\n\n flushGroup();\n }\n\n let mdBuffer: string[] = [];\n let mdBufferStart = 0;\n\n while (currentLine < lines.length) {\n const scriptBlock = blocks.find((b) => b.startLine === currentLine);\n\n if (scriptBlock) {\n flushMarkdownLines(mdBuffer, mdBufferStart);\n mdBuffer = [];\n\n const dialect: FenceDialect = scriptBlock.dialect ?? 'time';\n const { metadata, cleanText } = extractMetadata(scriptBlock.content);\n const fenceTag = scriptBlock.sport ? `${dialect}:${scriptBlock.sport}` : dialect;\n const cleanRawContent = `\\`\\`\\`${fenceTag}\\n${cleanText}\\n\\`\\`\\``;\n const cleanLineCount = cleanRawContent.split('\\n').length;\n\n const sectionId = metadata?.id || generateSectionId(dialect, scriptBlock.startLine, cleanText);\n const contentId = blockContentId(cleanText);\n\n sections.push({\n id: sectionId,\n contentId,\n type: dialect,\n sport: scriptBlock.sport,\n rawContent: cleanRawContent,\n displayContent: cleanText,\n startLine: scriptBlock.startLine,\n endLine: scriptBlock.startLine + cleanLineCount - 1,\n lineCount: cleanLineCount,\n scriptBlock: {\n ...scriptBlock,\n id: sectionId,\n contentId,\n content: cleanText,\n dialect,\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n },\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n });\n\n currentLine = scriptBlock.endLine + 1;\n mdBufferStart = currentLine;\n continue;\n }\n\n const fmRange = fmRanges.find((r) => r.startLine === currentLine);\n\n if (fmRange) {\n flushMarkdownLines(mdBuffer, mdBufferStart);\n mdBuffer = [];\n\n const rawLines = lines.slice(fmRange.startLine, fmRange.endLine + 1);\n const raw = rawLines.join('\\n');\n const innerLines = lines.slice(fmRange.startLine + 1, fmRange.endLine);\n const { metadata, cleanText } = extractMetadata(innerLines.join('\\n'));\n const properties = parseFrontMatterProperties(cleanText.split('\\n'));\n const subtype = resolveFrontMatterSubtype(properties);\n const lineCount = fmRange.endLine - fmRange.startLine + 1;\n\n sections.push({\n id: metadata?.id || generateSectionId('frontmatter', fmRange.startLine, raw),\n type: 'frontmatter',\n rawContent: raw,\n displayContent: cleanText,\n startLine: fmRange.startLine,\n endLine: fmRange.endLine,\n lineCount,\n properties,\n frontmatterType: subtype,\n version: metadata?.version || 1,\n createdAt: metadata?.createdAt || now,\n });\n\n currentLine = fmRange.endLine + 1;\n mdBufferStart = currentLine;\n continue;\n }\n\n if (mdBuffer.length === 0) {\n mdBufferStart = currentLine;\n }\n mdBuffer.push(lines[currentLine]);\n currentLine++;\n }\n\n flushMarkdownLines(mdBuffer, mdBufferStart);\n\n return sections;\n}\n\nexport function buildRawContent(sections: Section[]): string {\n return sections\n .filter((s) => !s.deleted)\n .map((s) => s.rawContent)\n .join('\\n');\n}\n\nexport function calculateTotalLines(sections: Section[]): number {\n const visible = sections.filter((s) => !s.deleted);\n if (visible.length === 0) return 0;\n const last = visible[visible.length - 1];\n return last.endLine + 1;\n}\n\nexport function matchSectionIds(oldSections: Section[], newSections: Section[]): Section[] {\n return newSections.map((newSec) => {\n const { metadata } = extractMetadata(newSec.rawContent);\n if (metadata) {\n const updated = { ...newSec, id: metadata.id, version: metadata.version, createdAt: metadata.createdAt };\n if (updated.scriptBlock) {\n updated.scriptBlock = { ...updated.scriptBlock, id: metadata.id };\n }\n return updated;\n }\n\n const exactMatch = oldSections.find(\n (old) =>\n old.type === newSec.type &&\n old.startLine === newSec.startLine &&\n old.displayContent === newSec.displayContent\n );\n if (exactMatch) {\n const updated = { ...newSec, id: exactMatch.id, version: exactMatch.version, createdAt: exactMatch.createdAt };\n if (updated.scriptBlock) {\n updated.scriptBlock = { ...updated.scriptBlock, id: exactMatch.id };\n }\n return updated;\n }\n\n const positionMatch = oldSections.find(\n (old) => old.type === newSec.type && old.startLine === newSec.startLine\n );\n if (positionMatch) {\n const newVersion = (positionMatch.version || 1) + 1;\n const updated = {\n ...newSec,\n id: positionMatch.id,\n version: newVersion,\n createdAt: positionMatch.createdAt,\n };\n if (updated.scriptBlock) {\n updated.scriptBlock = { ...updated.scriptBlock, id: positionMatch.id, version: newVersion };\n }\n return updated;\n }\n\n return newSec;\n });\n}\n","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.35.2115';\nexport const GIT_SHA = '37944a8';\nexport const BUILD_TIME = '2026-10-11T23:54:36.367Z';\nexport const SEMVER = {\n version: '0.35.2115',\n gitSha: '37944a8',\n buildTime: '2026-10-11T23:54:36.367Z',\n} as const;\n"]}
1
+ {"version":3,"sources":["../src/ownership/types.ts","../src/models/Metric.ts","../src/ownership/ledger.ts","../src/fields/fieldIdentity.ts","../src/units/catalog.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/BlockKey.ts","../src/models/blockContentId.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/sections/sectionParser.ts","../src/sections/blockDetection.ts","../src/version.ts"],"names":["MetricType","end","section"],"mappings":";;;AAQO,IAAM,4BAAA,GAAgE;AAAA,EAC3E,QAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF;AAMO,IAAM,gCAAA,GAA+E;AAAA,EAC1F,MAAA,EAAQ,QAAA;AAAA,EACR,QAAA,EAAU,SAAA;AAAA,EACV,OAAA,EAAS,SAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,WAAA,EAAa,WAAA;AAAA,EACb,OAAA,EAAS,SAAA;AAAA,EACT,OAAA,EAAS,SAAA;AAAA,EACT,QAAA,EAAU,SAAA;AAAA,EACV,oBAAA,EAAsB,SAAA;AAAA,EACtB,SAAA,EAAW,SAAA;AAAA,EACX,IAAA,EAAM,YAAA;AAAA,EACN,SAAA,EAAW;AACb;AA+CO,SAAS,wBAAwB,MAAA,EAAwD;AAC9F,EAAA,OAAO,gCAAA,CAAiC,MAAA,IAAU,QAAQ,CAAA,IAAK,QAAA;AACjE;;;AC+BO,IAAK,UAAA,qBAAAA,WAAAA,KAAL;AAQL,EAAAA,YAAA,UAAA,CAAA,GAAW,UAAA;AASX,EAAAA,YAAA,OAAA,CAAA,GAAQ,OAAA;AAQR,EAAAA,YAAA,YAAA,CAAA,GAAa,aAAA;AAGb,EAAAA,YAAA,MAAA,CAAA,GAAO,MAAA;AAGP,EAAAA,YAAA,SAAA,CAAA,GAAU,SAAA;AAGV,EAAAA,YAAA,OAAA,CAAA,GAAQ,OAAA;AAER,EAAAA,YAAA,KAAA,CAAA,GAAM,KAAA;AACN,EAAAA,YAAA,QAAA,CAAA,GAAS,QAAA;AACT,EAAAA,YAAA,UAAA,CAAA,GAAW,UAAA;AACX,EAAAA,YAAA,QAAA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A,GAAU;AAChB,IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,WAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.cjs","sourcesContent":["import type { IMetric, MetricOrigin, MetricOwnershipLayer } from '../models/Metric';\n\nexport type { MetricOwnershipLayer };\n\n/**\n * Canonical low->high ownership chain used by characterization tests and\n * ownership resolution work.\n */\nexport const METRIC_OWNERSHIP_LAYER_CHAIN: readonly MetricOwnershipLayer[] = [\n 'parser',\n 'dialect',\n 'user-plan',\n 'runtime',\n 'user-entry',\n] as const;\n\n/**\n * Compatibility map from the current mixed-purpose `origin` field into the\n * canonical ownership-layer vocabulary.\n */\nexport const LEGACY_ORIGIN_TO_OWNERSHIP_LAYER: Record<MetricOrigin, MetricOwnershipLayer> = {\n parser: 'parser',\n compiler: 'dialect',\n dialect: 'dialect',\n hinted: 'dialect',\n 'user-plan': 'user-plan',\n runtime: 'runtime',\n tracked: 'runtime',\n analyzed: 'runtime',\n 'analyzed-estimated': 'runtime',\n execution: 'runtime',\n user: 'user-entry',\n collected: 'user-entry',\n};\n\nexport interface MetricWithOptionalOwnershipLayer extends IMetric {\n readonly ownershipLayer?: MetricOwnershipLayer;\n}\n\nexport interface MetricOwnershipQuery {\n readonly types?: readonly (IMetric['type'])[];\n readonly layers?: readonly MetricOwnershipLayer[];\n}\n\nexport type MetricOwnershipOutcome =\n | 'visible'\n | 'hidden-by-layer'\n | 'hidden-by-suppressor'\n | 'suppressor';\n\nexport interface MetricOwnershipResolvedContribution {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly outcome: MetricOwnershipOutcome;\n}\n\nexport interface MetricOwnershipPromotionCandidate {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly reason: 'shadowed-by-higher-layer' | 'suppressed';\n readonly blockedByLayer?: MetricOwnershipLayer;\n}\n\nexport interface MetricOwnershipTypeExplanation {\n readonly type: IMetric['type'];\n readonly winnerLayer?: MetricOwnershipLayer;\n readonly suppressed: boolean;\n readonly entries: readonly MetricOwnershipResolvedContribution[];\n}\n\nexport interface MetricOwnershipLedger {\n raw(query?: MetricOwnershipQuery): IMetric[];\n visible(query?: MetricOwnershipQuery): IMetric[];\n byLayer(query?: MetricOwnershipQuery): Partial<Record<MetricOwnershipLayer, IMetric[]>>;\n promotionCandidates(query?: MetricOwnershipQuery): MetricOwnershipPromotionCandidate[];\n explain(query?: MetricOwnershipQuery): MetricOwnershipTypeExplanation[];\n}\n\nexport function getMetricOwnershipLayer(origin: MetricOrigin | undefined): MetricOwnershipLayer {\n return LEGACY_ORIGIN_TO_OWNERSHIP_LAYER[origin ?? 'parser'] ?? 'parser';\n}\n","/**\n * Canonical ownership vocabulary for metric visibility decisions.\n * Ordered from lowest to highest ownership precedence.\n */\nexport type MetricOwnershipLayer =\n | 'parser'\n | 'dialect'\n | 'user-plan'\n | 'runtime'\n | 'user-entry';\n\n/**\n * Origin of a metric - where it was created and its current state.\n *\n * Source origins:\n * - 'parser': Created by the parser from source text\n * - 'compiler': Synthesized by a compiler strategy\n * - 'dialect': Synthesized by a dialect policy before runtime\n * - 'runtime': Generated during execution (e.g., elapsed time)\n * - 'user': Collected from user input (e.g., actual reps completed)\n *\n * Value states:\n * - 'collected': Value has been collected and populated\n * - 'hinted': Value is a hint or suggestion not strictly enforced\n * - 'tracked': Value is actively being tracked during execution\n * - 'analyzed': Value is derived from analysis\n * - 'analyzed-estimated': Value is derived from estimation\n * - 'execution': Generated by runtime execution\n * - 'user-plan': Planned override set by user before execution\n */\nexport type MetricAction = 'suppress';\n\nexport type MetricOrigin =\n | 'parser'\n | 'compiler'\n | 'dialect'\n | 'runtime'\n | 'user'\n | 'collected'\n | 'hinted'\n | 'tracked'\n | 'analyzed'\n | 'analyzed-estimated'\n | 'execution'\n | 'user-plan';\n\nexport type Origin = MetricOrigin;\n\nexport interface IMetric {\n readonly image?: string;\n readonly value?: unknown;\n /**\n * The metric type. Use a `MetricType` enum value for standard types, or any\n * string for custom derived metrics produced by enrichment processes\n * (e.g. `'speed'`, `'pace'`, `'rep-rate'`, `'power'`).\n */\n readonly type: MetricType | string;\n /** Backward-compatible alias for type */\n readonly metricType?: MetricType | string;\n readonly origin: MetricOrigin;\n readonly unit?: string;\n\n /**\n * Visibility instruction. The only live value is `'suppress'`, which hides\n * all metrics of this type from display (resolved by the ownership ledger).\n * Most metrics carry no action (undefined = passive).\n */\n readonly action?: MetricAction;\n\n /**\n * Block key that created/owns this metric.\n * Present for runtime and user-collected metrics.\n */\n readonly sourceBlockKey?: string;\n\n /**\n * Timestamp when this metric was created/recorded.\n * Present for runtime and user-collected metrics.\n */\n readonly timestamp?: Date;\n\n /**\n * Processor-attached structured payload. Summary processors (e.g. TIS) hang\n * derivation metadata (effortSlug, effortDiscipline, effortIntensityTier,\n * component scores) on the projection value metric; fact normalization reads\n * it back out. Pure data — survives the stored-logs round-trip.\n */\n readonly metadata?: Record<string, unknown>;\n\n /** Optional explicit ownership layer for legacy compatibility */\n readonly ownershipLayer?: MetricOwnershipLayer;\n\n /** Optional human-readable name or label */\n readonly name?: string;\n\n /**\n * Optional icon (emoji/glyph) for hint metrics. Hints without an icon are\n * data-only — they never render in display surfaces; a hint WITH an icon\n * renders as the icon alone, with the hint text on hover.\n */\n readonly icon?: string;\n}\n\n/**\n * Metric type enumeration.\n *\n * Time-related terms follow the glossary in docs/architecture/time-terminology.md:\n * - **Duration** (Parser) — planned target from the script (e.g., \"5:00\" -> 300 000 ms)\n * - **Time / Spans** (Block) — the raw TimeSpan[] start/stop recordings a block tracks\n * - **TimeStamp** (Runtime) — system Date.now() when a message is logged\n * - **Elapsed** (Runtime) — Σ(end - start) of each span segment (active time, excludes pauses)\n * - **Total** (Runtime) — lastEnd - firstStart (wall-clock bracket, includes pauses)\n */\nexport enum MetricType {\n /**\n * **Duration** (Core) — parser-defined planned target.\n *\n * A metric defined by the CodeStatement during parsing (e.g., \"5:00\" -> 300 000 ms).\n * It can be a time (duration) or a placeholder to be resolved.\n * Owned by the parser — the runtime reads it but never computes it.\n */\n Duration = 'duration',\n\n /**\n * **Spans** (Core) — raw start/stop TimeSpan[] recordings.\n *\n * Source-of-truth data recorded using the runtime clock.\n * Each span represents a continuous period of active (unpaused) execution.\n * These can be recorded at runtime or back-filled during analytics.\n */\n Spans = 'spans',\n\n /**\n * **SystemTime** (Core) — real system time (Date.now()) when a message is logged.\n *\n * Ground-truth wall-clock reference (timestamp) associated with system time metrics.\n * Independent of the runtime clock.\n */\n SystemTime = 'system-time',\n\n /** Live timer state written into block memory by the count-up/count-down timer behaviors. */\n Time = 'time',\n\n /** Active elapsed time — Σ(end - start) of active spans; derived during analytics. */\n Elapsed = 'elapsed',\n\n /** Total wall-clock bracket (lastEnd - firstStart) for a block; derived during analytics. */\n Total = 'total',\n\n Rep = 'rep',\n Effort = 'effort',\n Distance = 'distance',\n Rounds = 'rounds',\n CurrentRound = 'current-round',\n Action = 'action',\n Increment = 'increment',\n Group = 'group',\n Text = 'text',\n Resistance = 'resistance',\n Sound = 'sound',\n System = 'system',\n Label = 'label',\n Lap = 'lap',\n Metric = 'metric',\n\n /**\n * **Hint** (Core) — a semantic marker emitted by a dialect or the parser.\n *\n * Dot-namespaced string markers (e.g. `workout.amrap`, `behavior.required_timer`)\n * that strategies and the label composer query to drive compilation decisions.\n * Hints are metrics so they flow through the single ownership channel, but they\n * are excluded from display resolution and from runtime block fragments.\n */\n Hint = 'hint',\n\n /** Generic custom metric bucket for parser-owned property metrics. */\n Custom = 'custom',\n Volume = 'volume',\n Intensity = 'intensity',\n\n /** Climb grade label carried by an observation (e.g. `V8`, `5.12a`) —\n * user-authored grade metrics promote to the analytics `grade` dim. */\n Grade = 'grade',\n Load = 'load',\n Work = 'work',\n\n /** Per-set Reps in Reserve (real-time, strength) */\n RIR = 'rir',\n\n /** Post-session subjective effort rating (0–10) */\n SessionRPE = 'session-rpe',\n\n /** Session RPE x total minutes */\n SessionLoad = 'session-load',\n\n /** Normalized MET ((Activity METs ÷ METmax) x 100) */\n METScore = 'met-score',\n\n /** Training Intensity Score (composite) */\n TIS = 'tis',\n\n /** Runtime-layer calculated metric emitted from declarative formulas */\n Calculated = 'calculated',\n\n /**\n * **Choice** (Parser) — a pipe-separated OR expression.\n *\n * Emitted by Fusion when a pipe separates two homogeneous alternatives\n * (same MetricType on both sides). Carries `alternatives: IMetric[]`.\n * Resolved in the Pre-Run Wizard before the JIT compiles: the chosen\n * alternative is written at origin `user-plan` into the Statement's\n * MetricContainer, shadowing this group via ownership-layer precedence.\n * Never reaches compiled Blocks or display output once resolved.\n */\n Choice = 'choice',\n}\n\n/**\n * Concrete helper class implementing IMetric\n */\nexport class Metric implements IMetric {\n readonly type: MetricType | string;\n readonly metricType?: MetricType | string;\n readonly value?: unknown;\n readonly origin: MetricOrigin;\n readonly unit?: string;\n readonly action?: MetricAction;\n readonly image?: string;\n readonly sourceBlockKey?: string;\n readonly timestamp?: Date;\n readonly metadata?: Record<string, unknown>;\n readonly name?: string;\n readonly ownershipLayer?: MetricOwnershipLayer;\n\n constructor(\n typeOrName: MetricType | string,\n valueOrType?: unknown,\n originOrValue?: unknown,\n unit?: string,\n origin?: MetricOrigin | string,\n action?: MetricAction | string,\n image?: string,\n ) {\n if (\n typeof valueOrType === 'string' &&\n (typeof originOrValue === 'number' ||\n typeof originOrValue === 'string' ||\n typeof originOrValue === 'boolean' ||\n originOrValue === null ||\n originOrValue === undefined)\n ) {\n // Signature: (name, type, value, unit?, origin?, action?, image?)\n this.name = String(typeOrName);\n this.type = valueOrType;\n this.metricType = valueOrType;\n this.value = originOrValue;\n this.unit = unit;\n this.origin = (origin as MetricOrigin) || 'parser';\n this.action = action === 'suppress' ? 'suppress' : undefined;\n this.image = image ?? String(originOrValue ?? valueOrType);\n } else {\n // Signature: (type, value?, origin?, unit?, action?, image?)\n this.type = typeOrName;\n this.metricType = typeOrName;\n this.value = valueOrType;\n this.origin = (originOrValue as MetricOrigin) || 'parser';\n this.unit = unit;\n this.action = (typeof origin === 'string' && origin === 'suppress')\n ? 'suppress'\n : (action === 'suppress' ? 'suppress' : undefined);\n this.image = image ?? String(valueOrType ?? typeOrName);\n }\n }\n\n toNumber(): number {\n if (typeof this.value === 'number') return this.value;\n if (typeof this.value === 'string') {\n const parsed = parseFloat(this.value);\n return isNaN(parsed) ? 0 : parsed;\n }\n return 0;\n }\n}\n","import { MetricType, type IMetric } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport {\n getMetricOwnershipLayer,\n METRIC_OWNERSHIP_LAYER_CHAIN,\n type MetricOwnershipLayer,\n type MetricOwnershipLedger,\n type MetricOwnershipPromotionCandidate,\n type MetricOwnershipQuery,\n type MetricOwnershipResolvedContribution,\n type MetricOwnershipTypeExplanation,\n type MetricWithOptionalOwnershipLayer,\n} from './types';\n\ninterface OwnershipContribution {\n readonly metric: IMetric;\n readonly type: IMetric['type'];\n readonly layer: MetricOwnershipLayer;\n readonly layerRank: number;\n readonly index: number;\n readonly isSuppressor: boolean;\n}\n\nconst LAYER_RANK: Record<MetricOwnershipLayer, number> = {\n parser: 0,\n dialect: 1,\n 'user-plan': 2,\n runtime: 3,\n 'user-entry': 4,\n};\n\nexport function resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) {\n return maybeLayer;\n }\n return getMetricOwnershipLayer(metric.origin);\n}\n\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return LAYER_RANK[layer] ?? 0;\n}\n\nfunction normalize(metrics: readonly IMetric[]): OwnershipContribution[] {\n return metrics.map((metric, index) => {\n const layer = resolveLayer(metric);\n return {\n metric,\n type: metric.type,\n layer,\n layerRank: LAYER_RANK[layer] ?? 0,\n index,\n isSuppressor: metric.action === 'suppress',\n };\n });\n}\n\nfunction applyQuery(\n contributions: readonly OwnershipContribution[],\n query?: MetricOwnershipQuery,\n): OwnershipContribution[] {\n if (!query) {\n return [...contributions];\n }\n\n return contributions.filter((contribution) => {\n if (query.types && !query.types.includes(contribution.type)) {\n return false;\n }\n if (query.layers && !query.layers.includes(contribution.layer)) {\n return false;\n }\n return true;\n });\n}\n\nfunction groupByType(contributions: readonly OwnershipContribution[]): Map<IMetric['type'], OwnershipContribution[]> {\n const grouped = new Map<IMetric['type'], OwnershipContribution[]>();\n for (const contribution of contributions) {\n const bucket = grouped.get(contribution.type);\n if (bucket) {\n bucket.push(contribution);\n continue;\n }\n grouped.set(contribution.type, [contribution]);\n }\n return grouped;\n}\n\nfunction getWinningLayerRank(contributions: readonly OwnershipContribution[]): number | undefined {\n let winningLayerRank: number | undefined;\n for (const contribution of contributions) {\n if (contribution.isSuppressor) {\n continue;\n }\n if (winningLayerRank == null || contribution.layerRank > winningLayerRank) {\n winningLayerRank = contribution.layerRank;\n }\n }\n return winningLayerRank;\n}\n\nfunction toResolvedContribution(\n contribution: OwnershipContribution,\n outcome: MetricOwnershipResolvedContribution['outcome'],\n): MetricOwnershipResolvedContribution {\n return {\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n outcome,\n };\n}\n\nfunction compareByOriginalIndex(a: OwnershipContribution, b: OwnershipContribution): number {\n return a.index - b.index;\n}\n\nexport function createMetricOwnershipLedger(metrics: readonly IMetric[]): MetricOwnershipLedger {\n const contributions = normalize(metrics);\n\n return {\n raw(query) {\n return applyQuery(contributions, query).map((contribution) => contribution.metric);\n },\n\n visible(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const visible: OwnershipContribution[] = [];\n\n for (const groupedContributions of grouped.values()) {\n if (groupedContributions.some((contribution) => contribution.isSuppressor)) {\n continue;\n }\n\n const winningLayerRank = getWinningLayerRank(groupedContributions);\n if (winningLayerRank == null) {\n continue;\n }\n\n for (const contribution of groupedContributions) {\n if (!contribution.isSuppressor && contribution.layerRank === winningLayerRank) {\n visible.push(contribution);\n }\n }\n }\n\n visible.sort(compareByOriginalIndex);\n return visible.map((contribution) => contribution.metric);\n },\n\n byLayer(query) {\n const filtered = applyQuery(contributions, query);\n const grouped: Partial<Record<MetricOwnershipLayer, IMetric[]>> = {};\n\n for (const layer of METRIC_OWNERSHIP_LAYER_CHAIN) {\n grouped[layer] = [];\n }\n\n for (const contribution of filtered) {\n grouped[contribution.layer]!.push(contribution.metric);\n }\n\n for (const layer of METRIC_OWNERSHIP_LAYER_CHAIN) {\n if (grouped[layer]?.length === 0) {\n delete grouped[layer];\n }\n }\n\n return grouped;\n },\n\n promotionCandidates(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const candidates: MetricOwnershipPromotionCandidate[] = [];\n\n for (const groupedContributions of grouped.values()) {\n const suppressors = groupedContributions.filter((contribution) => contribution.isSuppressor);\n const nonSuppressors = groupedContributions.filter((contribution) => !contribution.isSuppressor);\n\n if (nonSuppressors.length === 0) {\n continue;\n }\n\n if (suppressors.length > 0) {\n const highestCandidateRank = Math.max(...nonSuppressors.map((contribution) => contribution.layerRank));\n const suppressingLayerRank = Math.max(...suppressors.map((contribution) => contribution.layerRank));\n\n for (const contribution of nonSuppressors) {\n if (contribution.layerRank === highestCandidateRank) {\n candidates.push({\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n reason: 'suppressed',\n blockedByLayer: METRIC_OWNERSHIP_LAYER_CHAIN[suppressingLayerRank],\n });\n }\n }\n continue;\n }\n\n const winningLayerRank = getWinningLayerRank(nonSuppressors);\n if (winningLayerRank == null) {\n continue;\n }\n\n const lowerLayerContributions = nonSuppressors.filter(\n (contribution) => contribution.layerRank < winningLayerRank,\n );\n\n if (lowerLayerContributions.length === 0) {\n continue;\n }\n\n const promotionLayerRank = Math.max(...lowerLayerContributions.map((contribution) => contribution.layerRank));\n\n for (const contribution of lowerLayerContributions) {\n if (contribution.layerRank === promotionLayerRank) {\n candidates.push({\n metric: contribution.metric,\n type: contribution.type,\n layer: contribution.layer,\n reason: 'shadowed-by-higher-layer',\n blockedByLayer: METRIC_OWNERSHIP_LAYER_CHAIN[winningLayerRank],\n });\n }\n }\n }\n\n candidates.sort((a, b) => {\n const rankDelta = (LAYER_RANK[b.layer] ?? 0) - (LAYER_RANK[a.layer] ?? 0);\n if (rankDelta !== 0) {\n return rankDelta;\n }\n return 0;\n });\n return candidates;\n },\n\n explain(query) {\n const filtered = applyQuery(contributions, query);\n const grouped = groupByType(filtered);\n const explanations: MetricOwnershipTypeExplanation[] = [];\n\n for (const [type, groupedContributions] of grouped.entries()) {\n const suppressed = groupedContributions.some((contribution) => contribution.isSuppressor);\n const winningLayerRank = suppressed ? undefined : getWinningLayerRank(groupedContributions);\n\n const entries = groupedContributions.map((contribution) => {\n if (contribution.isSuppressor) {\n return toResolvedContribution(contribution, 'suppressor');\n }\n if (suppressed) {\n return toResolvedContribution(contribution, 'hidden-by-suppressor');\n }\n if (winningLayerRank != null && contribution.layerRank === winningLayerRank) {\n return toResolvedContribution(contribution, 'visible');\n }\n return toResolvedContribution(contribution, 'hidden-by-layer');\n });\n\n explanations.push({\n type,\n winnerLayer: winningLayerRank == null ? undefined : METRIC_OWNERSHIP_LAYER_CHAIN[winningLayerRank],\n suppressed,\n entries,\n });\n }\n\n return explanations;\n },\n };\n}\n\nfunction applyFilter(metrics: readonly IMetric[], filter?: MetricFilter): IMetric[] {\n let filtered = [...metrics];\n const wantsHints = filter?.types?.includes(MetricType.Hint) ?? false;\n if (!wantsHints) {\n filtered = filtered.filter((m) => m.type !== MetricType.Hint);\n }\n if (!filter) return filtered;\n if (filter.origins) {\n filtered = filtered.filter((m) => filter.origins!.includes(m.origin ?? 'parser'));\n }\n if (filter.types) {\n filtered = filtered.filter((m) => filter.types!.includes(m.type));\n }\n if (filter.excludeTypes) {\n filtered = filtered.filter((m) => !filter.excludeTypes!.includes(m.type));\n }\n return filtered;\n}\n\nexport class OwnershipResolver implements IMetricOwnershipResolver {\n resolve(metrics: readonly IMetric[], filter?: MetricFilter): IMetric[] {\n const filtered = applyFilter(metrics, filter);\n const ledger = createMetricOwnershipLedger(filtered);\n return ledger.visible();\n }\n\n resolveOne(metrics: readonly IMetric[], type: MetricType | string): IMetric | undefined {\n return this.resolve(metrics, { types: [type] })[0];\n }\n\n resolveAll(metrics: readonly IMetric[], type: MetricType | string): IMetric[] {\n const ofType = metrics.filter((m) => m.type === type);\n if (ofType.length <= 1) return ofType;\n return [...ofType].sort((a, b) => ownershipRank(b) - ownershipRank(a));\n }\n}\n","/**\n * Field identity — the pure normalization/identity layer for typed metric\n * fields (wayfinder datadog-analytics ticket 11, per the field discovery\n * contract §Identity and discovery).\n *\n * A metric variant is identified by **normalized full property path + value\n * kind + physical dimension where applicable**. Source, display label,\n * original spelling, and convertible unit spelling are provenance, not\n * identity. Built-in and custom metrics use the same rules.\n *\n * This module is pure data + functions with zero dependencies: `lang` and\n * `wql` (and the app adapter) both consume it through their existing core\n * dependency. Dimension resolution from units lives with the unit catalog —\n * callers attach a resolved `dimension` when one is known.\n */\n\n/** The observed value kinds of a field variant (field discovery contract). */\nexport type FieldValueKind = 'number' | 'string' | 'boolean' | 'array';\n\n/** Presence/clearing marker — null records presence, never a value. */\nexport type NullValueKind = 'null';\n\n/**\n * Typed field reference — the identity of one metric variant.\n * `dimension` is the physical dimension for numeric kinds (resolved through\n * the unit registry); undefined means dimensionless or unknown.\n */\nexport interface FieldRef {\n /** Normalized full property path — lower camelCase components, dots delimit. */\n readonly path: string;\n /** Observed value kind of the variant. */\n readonly kind: FieldValueKind | NullValueKind;\n /** Physical dimension for numeric kinds, when known. */\n readonly dimension?: string;\n}\n\n/** Split one path component into words: whitespace/underscores/hyphens are\n * word separators; existing camel/Pascal boundaries are recognized.\n * Acronym runs (≥2 uppercase) end before a following upper+lower pair. */\nfunction splitWords(component: string): string[] {\n const onSeparators = component.split(/[\\s_\\-\\u2010-\\u2015]+/).filter(Boolean);\n const words: string[] = [];\n for (const chunk of onSeparators) {\n // Insert a boundary before an uppercase letter that follows a lowercase\n // letter or digit, and before the last uppercase of an acronym run when\n // a lowercase pair follows (e.g. 'HRVValue' → 'HRV' | 'Value').\n const cased = chunk\n .replace(/([\\p{Ll}\\p{Nd}])(\\p{Lu})/gu, '$1\\u0000$2')\n .replace(/(\\p{Lu})(\\p{Lu}\\p{Ll})/gu, '$1\\u0000$2');\n for (const word of cased.split('\\u0000')) {\n if (word) words.push(word);\n }\n }\n return words;\n}\n\n/** Lower camelCase one path component: `heart rate`, `heart_rate`,\n * `HeartRate`, and `heartRate` all normalize to `heartRate`; `HRV`\n * normalizes to `hrv`. No synonym inference: `heartrate` stays `heartrate`. */\nexport function normalizeFieldComponent(component: string): string {\n const words = splitWords(component);\n if (words.length === 0) return '';\n return words\n .map((word, index) => {\n const lower = word.toLowerCase();\n return index === 0 ? lower : lower.charAt(0).toUpperCase() + lower.slice(1);\n })\n .join('');\n}\n\n/**\n * Normalize a full property path. Dots are reserved path separators, so\n * `sleep_quality.score_value` → `sleepQuality.scoreValue` and nested/flat\n * forms share one identity. Empty components collapse: `sleep..score` →\n * `sleep.score`.\n */\nexport function normalizeFieldPath(path: string): string {\n return path\n .split('.')\n .map(normalizeFieldComponent)\n .filter((component) => component.length > 0)\n .join('.');\n}\n\n/** Classify an observed value into a field value kind. Objects and null are\n * deliberately outside the value kinds: objects contribute nested leaves and\n * null records presence/clearing — neither is a value. */\nexport function valueKindOf(value: unknown): FieldValueKind | 'object' | 'null' | 'undefined' {\n if (value === null) return 'null';\n if (value === undefined) return 'undefined';\n if (Array.isArray(value)) return 'array';\n switch (typeof value) {\n case 'number': return 'number';\n case 'string': return 'string';\n case 'boolean': return 'boolean';\n case 'object': return 'object';\n default: return 'undefined';\n }\n}\n\n/** One flattened leaf observation: identity path + kind, the raw value, and\n * the original spelling/shape it was authored with (provenance). */\nexport interface FieldLeaf {\n /** Normalized full path. */\n readonly path: string;\n /** Value kind — 'null' leaves record presence/clearing, never a value. */\n readonly kind: FieldValueKind | NullValueKind;\n readonly value: unknown;\n /** Original path spelling/shape as authored (flat dotted or nested). */\n readonly originalPath: string;\n}\n\n/**\n * Flatten an authored property object into typed leaves.\n *\n * - Dots in keys delimit paths: flat `{\"sleep.score\": 85}` ≡ nested\n * `{sleep:{score:85}}` — one identity.\n * - Objects contribute nested leaves; empty objects contribute nothing.\n * - Arrays are collections: one collection-valued leaf, never per-element\n * observations.\n * - Null records presence under its path without a value.\n */\nexport function flattenFieldLeaves(\n input: Record<string, unknown>,\n prefix = '',\n): FieldLeaf[] {\n const leaves: FieldLeaf[] = [];\n for (const [rawKey, value] of Object.entries(input)) {\n const path = prefix ? `${prefix}.${normalizeFieldPath(rawKey)}` : normalizeFieldPath(rawKey);\n if (!path) continue;\n const kind = valueKindOf(value);\n if (kind === 'object') {\n leaves.push(...flattenFieldLeaves(value as Record<string, unknown>, path));\n } else if (kind !== 'undefined') {\n leaves.push({ path, kind, value, originalPath: prefix ? `${prefix}.${rawKey}` : rawKey });\n }\n }\n return leaves;\n}\n\n/**\n * Collision-free canonical string for a typed variant identity. JSON array\n * encoding keeps a separator character inside a path from masquerading as a\n * structural boundary (`a|number` as path cannot collide with `a` + a\n * `number` dimension).\n */\nexport function fieldRefKey(ref: FieldRef): string {\n return JSON.stringify([ref.path, ref.kind, ref.dimension ?? null]);\n}\n\n/** Parse a {@link fieldRefKey} back into a FieldRef (round-trip helper). */\nexport function fieldRefFromKey(key: string): FieldRef {\n const [path, kind, dimension] = JSON.parse(key) as [string, string, string | null];\n return { path, kind: kind as FieldRef['kind'], ...(dimension ? { dimension } : {}) };\n}\n","/**\n * Unit catalog — the shared home for unit recognition, conversion evidence,\n * and the system default output table (wayfinder decision ticket 21;\n * consumed by wql's arithmetic rewrite, ticket 13).\n *\n * Recognition spellings are case-insensitive through canonical spellings and\n * aliases. Every entry carries its conversion evidence: the physical\n * dimension it measures and the fixed factor converting it to that\n * dimension's base unit. Compound units (speed, pace) convert through their\n * own scale factors to the compound base.\n *\n * `bw` (body-weight-relative load) is deliberately NOT a fixed-factor entry:\n * it requires genuine measurement-time context persisted with the value\n * (ticket 14's conversion evidence) — never a constant kg conversion, never\n * today's body mass reinterpreting history (missing-context limitation).\n */\n\n/** Named result dimensions — the keys of the system default table. */\nexport type DimensionKey =\n | 'mass'\n | 'distance'\n | 'duration'\n | 'count'\n | 'count-rate'\n | 'energy'\n | 'speed'\n | 'pace'\n | 'ratio';\n\n/** Error taxonomy (decision ticket 21). */\nexport type UnitErrorCode =\n | 'unknown-unit'\n | 'dimension-mismatch'\n | 'scale-mismatch'\n | 'missing-context'\n | 'non-finite'\n | 'non-convertible';\n\nexport class UnitConversionError extends Error {\n readonly code: UnitErrorCode;\n constructor(code: UnitErrorCode, message: string) {\n super(message);\n this.name = 'UnitConversionError';\n this.code = code;\n }\n}\n\nexport interface UnitDefinition {\n /** Canonical spelling (e.g. `kg`, `mi`, `min/km`). */\n readonly canonical: string;\n /** Named result dimension. */\n readonly dimension: DimensionKey;\n /** Fixed factor converting a value of this unit to the dimension's base\n * unit (conversion evidence). */\n readonly factor: number;\n /** Registered alternate spellings (case-insensitive at lookup). */\n readonly aliases?: readonly string[];\n}\n\n/**\n * Base units per dimension: mass `kg`, distance `m`, duration `s`,\n * count `count`, energy `cal`, speed `m/s`, pace `min/km`; ratio is\n * unitless (factor 1).\n */\nexport const UNIT_CATALOG: readonly UnitDefinition[] = [\n // Distance — base m\n { canonical: 'm', dimension: 'distance', factor: 1, aliases: ['meter', 'meters', 'metre', 'metres'] },\n { canonical: 'km', dimension: 'distance', factor: 1000, aliases: ['kilometer', 'kilometers', 'kilometre', 'kilometres'] },\n { canonical: 'cm', dimension: 'distance', factor: 0.01, aliases: ['centimeter', 'centimeters'] },\n { canonical: 'mm', dimension: 'distance', factor: 0.001, aliases: ['millimeter', 'millimeters'] },\n { canonical: 'ft', dimension: 'distance', factor: 0.3048, aliases: ['foot', 'feet'] },\n { canonical: 'in', dimension: 'distance', factor: 0.0254, aliases: ['inch', 'inches'] },\n { canonical: 'yd', dimension: 'distance', factor: 0.9144, aliases: ['yard', 'yards'] },\n { canonical: 'mi', dimension: 'distance', factor: 1609.344, aliases: ['mile', 'miles'] },\n // Mass — base kg\n { canonical: 'kg', dimension: 'mass', factor: 1, aliases: ['kilogram', 'kilograms', 'kilo', 'kilos'] },\n { canonical: 'g', dimension: 'mass', factor: 0.001, aliases: ['gram', 'grams'] },\n { canonical: 'lb', dimension: 'mass', factor: 0.45359237, aliases: ['lbs', 'pound', 'pounds'] },\n // Duration — base s\n { canonical: 'ms', dimension: 'duration', factor: 0.001, aliases: ['millisecond', 'milliseconds'] },\n { canonical: 's', dimension: 'duration', factor: 1, aliases: ['sec', 'secs', 'second', 'seconds'] },\n { canonical: 'min', dimension: 'duration', factor: 60, aliases: ['mins', 'minute', 'minutes'] },\n { canonical: 'h', dimension: 'duration', factor: 3600, aliases: ['hr', 'hrs', 'hour', 'hours'] },\n // Count — base count. Test-result scales (\"pull-up\", \"thruster\",\n // \"problem\") are count-dimension scales: one of their units is one rep.\n { canonical: 'count', dimension: 'count', factor: 1 },\n { canonical: 'rep', dimension: 'count', factor: 1, aliases: ['reps'] },\n { canonical: 'pull-up', dimension: 'count', factor: 1 },\n { canonical: 'thruster', dimension: 'count', factor: 1 },\n { canonical: 'problem', dimension: 'count', factor: 1 },\n // Count-rate — base count/s; bpm (beats per minute) is its registered scale\n { canonical: 'count/s', dimension: 'count-rate', factor: 1 },\n { canonical: 'bpm', dimension: 'count-rate', factor: 1 / 60 },\n // Energy — base cal\n { canonical: 'cal', dimension: 'energy', factor: 1, aliases: ['calorie', 'calories'] },\n { canonical: 'kcal', dimension: 'energy', factor: 1000, aliases: ['kilocalorie', 'kilocalories'] },\n // Speed — base m/s\n { canonical: 'm/s', dimension: 'speed', factor: 1 },\n { canonical: 'km/h', dimension: 'speed', factor: 1000 / 3600, aliases: ['kmh', 'kph'] },\n { canonical: 'mph', dimension: 'speed', factor: 1609.344 / 3600 },\n // Pace — base min/km\n { canonical: 'min/km', dimension: 'pace', factor: 1 },\n { canonical: 'min/mi', dimension: 'pace', factor: 1000 / 1609.344 },\n { canonical: 's/m', dimension: 'pace', factor: 1 / 60 },\n // Ratio — unitless base (factor 1); percent via 100% = 1.\n // Dimensionless named scales (arbitrary units, points) share the ratio\n // dimension but are convertible only to the base — never to each other.\n { canonical: 'ratio', dimension: 'ratio', factor: 1, aliases: ['x'] },\n { canonical: '%', dimension: 'ratio', factor: 0.01, aliases: ['pct', 'percent'] },\n { canonical: 'au', dimension: 'ratio', factor: 1, aliases: ['AU'] },\n { canonical: 'pts', dimension: 'ratio', factor: 1, aliases: ['point', 'points'] },\n { canonical: 'rating', dimension: 'ratio', factor: 1, aliases: ['ratings'] },\n];\nconst bySpelling = (() => {\n const map = new Map<string, UnitDefinition>();\n for (const def of UNIT_CATALOG) {\n map.set(def.canonical.toLowerCase(), def);\n for (const alias of def.aliases ?? []) {\n if (!map.has(alias.toLowerCase())) map.set(alias.toLowerCase(), def);\n }\n }\n return map;\n})();\n\n/** Look up a unit by canonical spelling or alias (case-insensitive). Stored\n * event rows are a trust boundary — a missing/legacy unit arrives as\n * undefined at runtime despite the static type. */\nexport function lookupUnit(spelling: string): UnitDefinition | undefined {\n if (typeof spelling !== 'string') return undefined;\n return bySpelling.get(spelling.trim().toLowerCase());\n}\n\n/** The named result dimension of a unit spelling, or undefined when the\n * spelling is not in the catalog. */\nexport function dimensionKeyOf(spelling: string): DimensionKey | undefined {\n return lookupUnit(spelling)?.dimension;\n}\n\n/** System default output unit per result dimension (arithmetic contract §5;\n * values agreed in ticket 13, home resolved in ticket 21). Ratio defaults\n * to unitless — `undefined`, never a fabricated unit label. */\nexport const SYSTEM_DEFAULT_OUTPUT_UNIT: Readonly<Record<DimensionKey, string | undefined>> = Object.freeze({\n mass: 'kg',\n distance: 'm',\n duration: 's',\n count: 'count',\n 'count-rate': 'count/s',\n energy: 'cal',\n speed: 'm/s',\n pace: 'min/km',\n ratio: undefined,\n});\n\n/** Default output unit for a result dimension — undefined means unitless. */\nexport function systemDefaultUnit(dimension: DimensionKey): string | undefined {\n return SYSTEM_DEFAULT_OUTPUT_UNIT[dimension];\n}\n\n/**\n * Strict conversion through the catalog's conversion evidence.\n *\n * Errors (`UnitConversionError`) on unknown units (`unknown-unit`) and\n * cross-dimension conversions (`dimension-mismatch`) — an explicit unknown\n * unit is never passed through and never replaced by a default.\n */\nexport function convertViaCatalog(value: number, from: string, to: string): number {\n const fromDef = lookupUnit(from);\n if (!fromDef) throw new UnitConversionError('unknown-unit', `Unknown unit \"${from}\"`);\n const toDef = lookupUnit(to);\n if (!toDef) throw new UnitConversionError('unknown-unit', `Unknown unit \"${to}\"`);\n if (fromDef.dimension !== toDef.dimension) {\n throw new UnitConversionError(\n 'dimension-mismatch',\n `Cannot convert ${from} (${fromDef.dimension}) to ${to} (${toDef.dimension})`,\n );\n }\n // A shared zero dimension vector is not proof that arbitrary named scales\n // are interchangeable (arithmetic contract §5): dimensionless scales are\n // convertible only to the ratio base, never directly to another scale.\n if (fromDef.dimension === 'ratio' && fromDef.canonical !== toDef.canonical) {\n if (fromDef.canonical !== 'ratio' && toDef.canonical !== 'ratio') {\n throw new UnitConversionError(\n 'scale-mismatch',\n `Named scales ${from} and ${to} are not interchangeable`,\n );\n }\n }\n if (!Number.isFinite(value)) {\n throw new UnitConversionError('non-finite', `Non-finite value cannot be converted`);\n }\n return (value * fromDef.factor) / toDef.factor;\n}\n","export interface ICodeMetadata {\n line: number;\n startOffset: number;\n endOffset: number;\n columnStart: number;\n columnEnd: number;\n length: number;\n raw?: string;\n}\n\nexport class CodeMetadata implements ICodeMetadata {\n constructor(\n public line: number,\n public startOffset: number,\n public endOffset: number,\n public length: number,\n public columnStart: number = 0,\n public columnEnd: number = 0,\n public raw: string = '',\n ) {}\n}\n","import { IMetric, MetricType, MetricOrigin } from './Metric';\nimport type { IMetricSource, MetricFilter } from '../contracts/IMetricSource';\nimport { OwnershipResolver, ownershipRank } from '../ownership/OwnershipResolver';\n\n/**\n * MetricContainer — a typed collection for `IMetric` objects.\n *\n * Provides lookup, add, remove, merge, and iteration operations over a\n * flat `IMetric[]` array. Standard way to work with metric collections on\n * `ICodeStatement`, `IRuntimeBlock`, and `OutputStatement`.\n *\n * Numeric indexes are mirrored for backwards compatibility with legacy\n * `metrics[0]` call sites.\n */\nexport class MetricContainer implements IMetricSource, Iterable<IMetric> {\n [index: number]: IMetric;\n private _metrics: IMetric[];\n private _indexedLength = 0;\n private readonly _resolver = new OwnershipResolver();\n readonly id: string | number;\n\n // ── Construction ───────────────────────────────────────────\n\n constructor(metrics?: IMetric[] | MetricContainer, id: string | number = 'metrics') {\n this.id = id;\n if (metrics instanceof MetricContainer) {\n this._metrics = metrics.toArray();\n this.syncIndexProperties();\n return;\n }\n if (Array.isArray(metrics)) {\n this._metrics = [...metrics];\n } else if (metrics != null) {\n this._metrics = [];\n } else {\n this._metrics = [];\n }\n this.syncIndexProperties();\n }\n\n /**\n * Create a container from an existing metric array, MetricContainer, or\n * a deserialized plain object.\n */\n static from(\n metrics: IMetric[] | MetricContainer | undefined | unknown,\n id: string | number = 'metrics',\n ): MetricContainer {\n if (metrics instanceof MetricContainer) {\n return metrics.clone(id);\n }\n if (Array.isArray(metrics)) {\n return new MetricContainer(metrics, id);\n }\n if (metrics != null && typeof metrics === 'object' && '_metrics' in (metrics as object)) {\n const raw = (metrics as Record<string, unknown>)._metrics;\n if (Array.isArray(raw)) {\n return new MetricContainer(raw as IMetric[], id);\n }\n }\n return MetricContainer.empty(id);\n }\n\n /** Create an empty container. */\n static empty(id: string | number = 'metrics'): MetricContainer {\n return new MetricContainer(undefined, id);\n }\n\n /** Create a defensive copy of this container. */\n clone(id: string | number = this.id): MetricContainer {\n return new MetricContainer(this._metrics, id);\n }\n\n // ── Read ───────────────────────────────────────────────────\n\n /** All metrics in insertion order. Returns a defensive copy. */\n get all(): readonly IMetric[] {\n return [...this._metrics];\n }\n\n /** Number of metrics in the container. */\n get length(): number {\n return this._metrics.length;\n }\n\n /** Alias for length */\n get size(): number {\n return this._metrics.length;\n }\n\n /** Whether the container has no metrics. */\n get isEmpty(): boolean {\n return this._metrics.length === 0;\n }\n\n /**\n * Get all metrics of a given MetricType / name, sorted by ownership layer\n * (highest precedence first).\n */\n getByType(type: MetricType | string): IMetric[] {\n const ofType = this._metrics.filter((m) => m.type === type || m.name === type);\n if (ofType.length <= 1) return ofType;\n return [...ofType].sort((a, b) => ownershipRank(b) - ownershipRank(a));\n }\n\n /**\n * Get the highest-precedence metric of a given type/name, or undefined.\n */\n getFirst(type: MetricType | string): IMetric | undefined {\n const byType = this.getByType(type);\n return byType.length > 0 ? byType[0] : undefined;\n }\n\n /**\n * Lookup a metric by type or name.\n */\n get(type: MetricType | string): IMetric | undefined {\n return this.getFirst(type);\n }\n\n /** Whether any metric of the given type/name exists. */\n has(type: MetricType | string): boolean {\n return this._metrics.some((m) => m.type === type || m.name === type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.has(type);\n }\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.resolve(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this._resolver.resolveOne(this._metrics, type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.getByType(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.toArray();\n }\n\n getAll(): IMetric[] {\n return this.toArray();\n }\n\n /**\n * Get all metrics matching the given origin.\n */\n getByOrigin(origin: MetricOrigin): IMetric[] {\n return this._metrics.filter((m) => (m.origin ?? 'parser') === origin);\n }\n\n /**\n * Apply the standard precedence resolution algorithm.\n */\n resolve(filter?: MetricFilter): IMetric[] {\n return this._resolver.resolve(this._metrics, filter);\n }\n\n // ── Write (mutating, returns `this` for chaining) ──────────\n\n /** Append one or more metrics. */\n add(...metrics: IMetric[]): this {\n this._metrics.push(...metrics);\n this.syncIndexProperties();\n return this;\n }\n\n /**\n * Remove metrics matching a predicate.\n * Returns the removed metrics.\n */\n remove(predicate: (m: IMetric) => boolean): IMetric[] {\n const removed: IMetric[] = [];\n this._metrics = this._metrics.filter((m) => {\n if (predicate(m)) {\n removed.push(m);\n return false;\n }\n return true;\n });\n this.syncIndexProperties();\n return removed;\n }\n\n /**\n * Remove all metrics of a given type.\n * Returns the removed metrics.\n */\n removeByType(type: MetricType | string): IMetric[] {\n return this.remove((m) => m.type === type || m.name === type);\n }\n\n /** Remove all metrics. */\n clear(): this {\n this._metrics = [];\n this.syncIndexProperties();\n return this;\n }\n\n /**\n * Replace all metrics of a given type with new ones.\n */\n replaceByType(type: MetricType | string, ...replacements: IMetric[]): IMetric[] {\n const removed = this.removeByType(type);\n this._metrics.push(...replacements);\n this.syncIndexProperties();\n return removed;\n }\n\n // ── Merge ──────────────────────────────────────────────────\n\n /**\n * Merge another container (or raw array) into this one.\n */\n merge(other: MetricContainer | IMetric[] | { metrics: MetricContainer }): this {\n const incoming =\n other instanceof MetricContainer\n ? other._metrics\n : Array.isArray(other)\n ? other\n : other.metrics.toArray();\n\n const byType = new Map<IMetric['type'], IMetric[]>();\n for (const m of incoming) {\n const group = byType.get(m.type) ?? [];\n group.push(m);\n byType.set(m.type, group);\n }\n\n for (const [type, incomingGroup] of byType) {\n const existing = this._metrics.filter((m) => m.type === type);\n\n if (existing.length === 0) {\n this._metrics.push(...incomingGroup);\n continue;\n }\n\n const existingRank = Math.max(...existing.map((m) => ownershipRank(m)));\n const incomingRank = Math.max(...incomingGroup.map((m) => ownershipRank(m)));\n\n if (incomingRank > existingRank) {\n this._metrics = this._metrics.filter((m) => m.type !== type);\n this._metrics.push(...incomingGroup);\n } else if (incomingRank === existingRank) {\n this._metrics.push(...incomingGroup);\n }\n }\n\n this.syncIndexProperties();\n return this;\n }\n\n // ── Iteration / Projection ─────────────────────────────────\n\n /** Iterate over all metrics. */\n [Symbol.iterator](): Iterator<IMetric> {\n return this._metrics[Symbol.iterator]();\n }\n\n /** Filter metrics, returning a new array. */\n filter(predicate: (m: IMetric) => boolean): IMetric[] {\n return this._metrics.filter(predicate);\n }\n\n /** Map metrics to a new array. */\n map<T>(fn: (m: IMetric, index: number) => T): T[] {\n return this._metrics.map(fn);\n }\n\n /** Flat-map metrics to a new array. */\n flatMap<T>(fn: (m: IMetric, index: number) => T | readonly T[]): T[] {\n return this._metrics.flatMap(fn);\n }\n\n /** Find the first metric matching a predicate. */\n find(predicate: (m: IMetric) => boolean): IMetric | undefined {\n return this._metrics.find(predicate);\n }\n\n /** Whether any metric matches the predicate. */\n some(predicate: (m: IMetric) => boolean): boolean {\n return this._metrics.some(predicate);\n }\n\n /** Whether all metrics match the predicate. */\n every(predicate: (m: IMetric) => boolean): boolean {\n return this._metrics.every(predicate);\n }\n\n // ── Conversion ─────────────────────────────────────────────\n\n /** Return a mutable copy of the underlying array. */\n toArray(): IMetric[] {\n return [...this._metrics];\n }\n\n /** Spread-friendly: returns the underlying array (no copy). */\n get raw(): IMetric[] {\n return this._metrics;\n }\n\n private syncIndexProperties(): void {\n for (let i = 0; i < this._indexedLength; i++) {\n delete this[i];\n }\n for (let i = 0; i < this._metrics.length; i++) {\n this[i] = this._metrics[i];\n }\n this._indexedLength = this._metrics.length;\n }\n\n toString(): string {\n return `MetricContainer(${this._metrics.length})[${this._metrics.map((m) => m.type).join(', ')}]`;\n }\n}\n","import { CodeMetadata } from './CodeMetadata';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport type { IMetricSource, MetricFilter } from '../contracts/IMetricSource';\n\nexport interface ICodeStatement extends IMetricSource {\n id: number;\n parent?: number;\n children: number[][];\n exerciseId?: string;\n metrics: MetricContainer;\n isLeaf?: boolean;\n meta: CodeMetadata;\n metricMeta: Map<IMetric, CodeMetadata>;\n line?: number;\n text?: string;\n raw?: string;\n dialect?: string;\n}\n\nexport abstract class CodeStatement implements ICodeStatement, IMetricSource {\n abstract id: number;\n abstract parent?: number;\n abstract children: number[][];\n abstract meta: CodeMetadata;\n abstract metrics: MetricContainer;\n abstract metricMeta: Map<IMetric, CodeMetadata>;\n abstract isLeaf?: boolean;\n exerciseId?: string;\n line?: number;\n text?: string;\n raw?: string;\n dialect?: string;\n\n // ── IMetricSource ─────────────────────────────────────────────\n\n hasMetric(type: MetricType | string): boolean {\n return this.metricContainer.hasMetric(type);\n }\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metricContainer.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metricContainer.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metricContainer.getAllMetricsByType(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metricContainer.rawMetrics;\n }\n\n private get metricContainer(): MetricContainer {\n return this.metrics instanceof MetricContainer\n ? this.metrics\n : MetricContainer.from(this.metrics as unknown as IMetric[], this.id);\n }\n}\n\nexport class ParsedCodeStatement extends CodeStatement {\n id: number = 0;\n parent?: number;\n children: number[][] = [];\n meta: CodeMetadata = new CodeMetadata(0, 0, 0, 0);\n private _metrics: MetricContainer = MetricContainer.empty();\n metricMeta: Map<IMetric, CodeMetadata> = new Map();\n isLeaf?: boolean;\n\n get metrics(): MetricContainer {\n return this._metrics;\n }\n\n set metrics(metrics: MetricContainer | IMetric[]) {\n this._metrics = MetricContainer.from(metrics, this.id);\n }\n\n constructor(init?: Partial<ParsedCodeStatement>) {\n super();\n if (init) {\n Object.assign(this, init);\n if (init.metrics) {\n this.metrics = MetricContainer.from(init.metrics, this.id);\n }\n if (!this.metricMeta) {\n this.metricMeta = new Map();\n }\n }\n }\n}\n","import { ICodeStatement, CodeStatement } from './CodeStatement';\nimport { IMetric } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource } from '../contracts/IMetricSource';\n\n/**\n * Output statement types indicating what kind of result this represents.\n *\n * - 'segment': A timed portion of execution (e.g., a round, an effort interval)\n * - 'milestone': A notable event during execution (e.g., halfway point, personal record)\n * - 'system': Debug/diagnostic output from lifecycle events\n * - 'event': Tracks external stimuli or internal triggers\n * - 'group': Identified segment with children\n * - 'load': Initial script state\n * - 'compiler': Behavior configuration and setup\n * - 'analytics': Output generated by the analytics engine\n */\nexport type OutputStatementType =\n | 'segment'\n | 'milestone'\n | 'completion'\n | 'metric'\n | 'system'\n | 'event'\n | 'group'\n | 'load'\n | 'compiler'\n | 'analytics';\n\n/**\n * IOutputStatement extends ICodeStatement to represent runtime-generated output.\n *\n * This is the return type of execution — what \"came out\" of running a statement.\n */\nexport interface IOutputStatement extends ICodeStatement, IMetricSource {\n readonly id: number;\n readonly outputType: OutputStatementType;\n readonly timeSpan: TimeSpan;\n readonly sourceStatementId?: number;\n readonly sourceBlockKey: string;\n readonly stackLevel: number;\n readonly metrics: MetricContainer;\n readonly metricMeta: Map<IMetric, CodeMetadata>;\n readonly completionReason?: string;\n readonly statement?: ICodeStatement;\n readonly timestamp?: number;\n}\n\n/**\n * Options for creating an OutputStatement.\n */\nexport interface OutputStatementOptions {\n /** Output type classification */\n outputType: OutputStatementType;\n\n /** Execution timing */\n timeSpan: TimeSpan;\n\n /** The block key that produced this output */\n sourceBlockKey?: string;\n\n /** Stack level (depth) when this output was emitted */\n stackLevel?: number;\n\n /** The source statement ID (optional) */\n sourceStatementId?: number;\n\n /** Original source line/text/dialect (when rebuilding from stored records) */\n line?: number;\n text?: string;\n dialect?: string;\n\n /** Runtime-collected metrics */\n metrics?: MetricContainer | IMetric[];\n\n /** Map of metrics to metadata */\n metricMeta?: Map<IMetric, CodeMetadata>;\n\n /** Reason the block completed (e.g., 'user-advance', 'forced-pop') */\n completionReason?: string;\n\n /** Parent output statement ID (for hierarchy) */\n parent?: number;\n\n /** Child output statement groups (for hierarchy) */\n children?: number[][];\n}\n\n/**\n * Concrete implementation of IOutputStatement.\n */\nexport class OutputStatement extends CodeStatement implements IOutputStatement {\n private static nextId = 1000000;\n\n readonly id: number;\n readonly outputType: OutputStatementType;\n readonly timeSpan: TimeSpan;\n\n readonly sourceStatementId?: number;\n readonly sourceBlockKey: string;\n readonly stackLevel: number;\n readonly metrics: MetricContainer;\n readonly metricMeta: Map<IMetric, CodeMetadata>;\n\n readonly completionReason?: string;\n readonly parent?: number;\n readonly children: number[][];\n readonly isLeaf: boolean;\n readonly meta: CodeMetadata;\n readonly statement?: ICodeStatement;\n readonly timestamp?: number;\n\n constructor(\n optionsOrStatement: OutputStatementOptions | ICodeStatement,\n metricsArg?: MetricContainer | IMetric[],\n timestamp?: number,\n ) {\n super();\n if (\n optionsOrStatement &&\n 'outputType' in optionsOrStatement &&\n 'timeSpan' in optionsOrStatement\n ) {\n const options = optionsOrStatement as OutputStatementOptions;\n this.id = OutputStatement.nextId++;\n this.outputType = options.outputType;\n this.timeSpan = options.timeSpan;\n this.sourceBlockKey = options.sourceBlockKey ?? '';\n this.sourceStatementId = options.sourceStatementId;\n this.line = options.line;\n this.text = options.text;\n this.dialect = options.dialect;\n this.stackLevel = options.stackLevel ?? 0;\n this.metrics = MetricContainer.from(options.metrics, this.id);\n this.metricMeta = options.metricMeta ?? new Map();\n this.completionReason = options.completionReason;\n this.parent = options.parent;\n this.children = options.children ?? [];\n this.isLeaf = this.children.length === 0;\n this.meta = new CodeMetadata(0, 0, 0, 0);\n } else {\n const stmt = optionsOrStatement as ICodeStatement;\n this.id = OutputStatement.nextId++;\n this.statement = stmt;\n this.outputType = 'segment';\n this.timeSpan = { started: timestamp ?? Date.now() };\n this.sourceBlockKey = '';\n this.sourceStatementId = typeof stmt?.id === 'number' ? stmt.id : undefined;\n this.stackLevel = 0;\n this.metrics = MetricContainer.from(metricsArg, this.id);\n this.metricMeta = new Map();\n this.children = [];\n this.isLeaf = true;\n this.meta = stmt?.meta ?? new CodeMetadata(0, 0, 0, 0);\n this.line = stmt?.line;\n this.text = stmt?.text;\n this.dialect = stmt?.dialect;\n this.timestamp = timestamp ?? Date.now();\n }\n }\n\n // IMetricSource implementation is inherited from CodeStatement\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","export interface IBlockKey {\n readonly value: string;\n toString(): string;\n valueOf(): string;\n equals(other: IBlockKey): boolean;\n}\n\nexport class BlockKey implements IBlockKey {\n readonly value: string;\n\n constructor(value?: string) {\n this.value =\n value ??\n (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function'\n ? crypto.randomUUID()\n : Math.random().toString(36).slice(2));\n }\n\n toString(): string {\n return this.value;\n }\n\n valueOf(): string {\n return this.value;\n }\n\n equals(other: IBlockKey): boolean {\n return this.value === other?.value;\n }\n}\n","/** Cross-note fingerprint of the trimmed, unfenced workout body. Never an occurrence ID. */\nexport function blockContentId(content: string): string {\n const normalized = content.trim();\n let hash = 0x811c9dc5;\n for (let i = 0; i < normalized.length; i++) {\n hash ^= normalized.charCodeAt(i);\n hash = Math.imul(hash, 0x01000193);\n }\n return `bc-${(hash >>> 0).toString(16).padStart(8, '0')}`;\n}\n","import type { StoredOutputStatement } from './results';\n\nexport type NoteBlockKind = 'wod' | 'query' | 'widget' | 'embed';\n\nexport interface NoteBlock {\n id: string;\n kind: NoteBlockKind;\n version: number;\n sourceRevision: number;\n from: number;\n to: number;\n dialect?: 'time' | 'log';\n sport?: string;\n}\n\nexport interface BlockRevision {\n noteId: string;\n blockId: string;\n version: number;\n kind: NoteBlockKind;\n rawContent: string;\n savedAt: number;\n dialect?: 'time' | 'log';\n sport?: string;\n}\n// ---------------------------------------------------------------------------\n// Note — root container\n// ---------------------------------------------------------------------------\nexport type NoteKind = 'journal' | 'template' | 'playground' | 'feed' | 'dashboard' | 'page' | (string & {});\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n rawContent: string;\n sourceRevision: number;\n blocks: Record<string, NoteBlock>;\n date?: number; // Domain date of the record (e.g. workout date, publish date)\n createdAt: number; // Creation timestamp\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: string[];\n seedOrigin?: 'seed' | 'user';\n seedVersion?: number;\n seedChunkId?: string;\n /** Authored seed path used for deterministic identity and routing. */\n sourcePath?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Page — named/slug-addressable grouped collection of notes\n// ---------------------------------------------------------------------------\nexport interface Page {\n id: string;\n date?: string; // YYYY-MM-DD (publish/calendar date)\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// PageNote — N:M junction linking a Note to a Page\n// ---------------------------------------------------------------------------\nexport interface PageNote {\n id: string; // UUID\n pageId: string;\n noteId: string;\n position?: number;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general' | (string & {});\n\nexport interface TagTypeRecord {\n id: string;\n name: string;\n label: string;\n color?: string;\n createdAt: number;\n}\n\nexport interface Tag {\n id: string;\n label: string;\n type?: TagType;\n createdAt: number;\n}\n\nexport interface NoteTag {\n id: string;\n noteId: string;\n tagId: string;\n}\n\n// ---------------------------------------------------------------------------\n// BlockIndexRow — derived block index for WQL content queries\n// ---------------------------------------------------------------------------\nexport interface BlockIndexRow {\n /** Current occurrence key `${noteId}:${blockId}`. */\n id: string;\n noteId: string;\n blockId: string;\n blockVersion: number;\n sourceRevision: number;\n from: number;\n to: number;\n position?: number;\n dataType: NoteBlock['kind'];\n blockContentId?: string;\n rawContent: string;\n noteTitle: string;\n createdAt: number;\n isStatic?: boolean;\n sourceId?: string;\n sourcePath?: string;\n routeId?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Session — execution log (renamed from WorkoutResult; table results -> sessions in DB V20)\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface Session {\n id: string;\n noteId: string;\n blockId: string;\n blockVersion: number;\n blockContentId?: string;\n origin?: ResultOrigin;\n pageId?: string;\n /** Born in-progress at run start, completed when finalization commits. */\n status?: 'in-progress' | 'completed';\n\n /** When workout started */\n startTime: number;\n\n /** When workout ended */\n endTime: number;\n\n /** Total elapsed time (ms) */\n duration: number;\n\n /** Rounds completed (for rounds-based workouts) */\n roundsCompleted?: number;\n\n /** Total rounds (for rounds-based workouts) */\n totalRounds?: number;\n\n /** Reps completed (for rep-based workouts) */\n repsCompleted?: number;\n\n /** Whether workout was completed or stopped early */\n completed: boolean;\n\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Attachment — external temporal data blobs (GPS / HR)\n// ---------------------------------------------------------------------------\nexport interface Attachment {\n id: string;\n noteId: string;\n pageId?: string;\n resultId?: string;\n mimeType: string;\n label: string;\n data: ArrayBuffer | string;\n timeSpan: {\n start: number;\n end: number;\n };\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// AnalyticsDataPoint — de-normalized metric for cross-workout queries\n// ---------------------------------------------------------------------------\nexport interface AnalyticsDataPoint {\n id: string;\n noteId: string;\n blockContentId?: string;\n origin?: ResultOrigin;\n pageId?: string;\n grain?: 'event' | 'summary';\n effortSlug?: string;\n discipline?: string;\n intensityTier?: string;\n grade?: string;\n /** User-authored categorical dims (custom property metrics and grouped\n * partitions) — normalized key → value, resolved by factTagValue after\n * the structural switch so `by {coach}` / `{coach:greg}` work. */\n dimensions?: Record<string, string>;\n blockId: string;\n blockVersion: number;\n resultId: string;\n type: string;\n value: unknown;\n unit?: string;\n label: string;\n metricKey?: string;\n metricLabel?: string;\n metricUnit?: string;\n /** Typed field reference provenance (ticket 11) — normalized path + kind\n * of the variant this observation belongs to. */\n fieldRef?: { path: string; kind: string; dimension?: string };\n /** The observation's own civil date (YYYY-MM-DD) when it is date-only\n * (ticket 12) — grouping uses this instead of a fabricated instant. */\n metricDate?: string;\n /** Temporal kind of the observation's anchor (ticket 12). */\n temporalKind?: 'instant' | 'civil-date';\n /** Ticket 14 provenance carried onto the fact (ticket 16 selection). */\n representationKind?: 'direct' | 'calculated' | 'substitute_summary';\n summaryCoverage?: SummaryCoverage;\n reducerStats?: ReducerStats;\n timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// EventRecord — THE single stored record for all workout data (V21).\n// Statement rows are the archival source: sessions hold execution metadata\n// only, and display/replay shapes are reconstructed from these rows.\n// ---------------------------------------------------------------------------\n\n/** Store-row kind: 'event' = raw statement row, 'summary' = folded row.\n * Authorship lives on `origin` (engine-authored summaries are finalize-owned;\n * user-authored summaries — wellness — are reconcile-owned). Ticket 005. */\nexport type EventGrain = 'event' | 'summary';\n\n/** Known producer values for the open `outputType` vocabulary (ticket 002:\n * open string + known-values module; unknowns are stored and returned,\n * matched only by kind-agnostic logic). */\nexport const KNOWN_OUTPUT_TYPES = [\n 'segment',\n 'system',\n 'load',\n 'event',\n 'compiler',\n 'completion',\n 'analytics',\n 'wellness',\n] as const;\n// EventRecord — THE single stored record for all workout data (renamed from UnifiedEventRecord)\n// ---------------------------------------------------------------------------\nexport interface EventRecord {\n /**\n * Event rows: `${resultId}:${seq}` — immutable, append-only.\n * Summary rows: `${resultId}:summary:${metricKey}[:k=v…]` — deterministic\n * content key; re-finalize overwrites cleanly (ticket 002).\n * Wellness rows: `wellness:${noteId}:${key}` — reconcile-owned upserts.\n */\n id: string;\n resultId: string;\n noteId: string;\n /** Content-stable cross-workout join key (promoted, ticket 003 amendment). */\n blockContentId?: string;\n pageId?: string;\n origin?: ResultOrigin;\n /** Canonical time — when the workout happened, never when derived. */\n timestamp: number;\n grain: EventGrain;\n effortSlug?: string;\n /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n /** Typed metric array; EXACTLY ONE entry when grain:'summary'. Summary\n * fold identity (canonicalKey, groupTags, effort metadata) lives in\n * metrics[0].metadata — shape-uniform with events. */\n metrics: StoredOutputStatement['metrics'];\n timeSpan?: { started: number; ended?: number };\n sourceBlockKey?: string;\n sourceStatementId?: number;\n line?: number;\n text?: string;\n dialect?: string;\n stackLevel?: number;\n completionReason?: string;\n blockId?: string;\n blockVersion?: number;\n /** Per-metric temporal anchors (ticket 12) — parallel to `metrics` when\n * the producing statement carries its own instants/dates:\n * 'instant' = recorded occurrence instant; 'civil-date' = recorded civil\n * date (date-only wellness), never a fabricated midnight. The row\n * timestamp remains the V16 fetch anchor until the by-metricDate index\n * (ticket 14); it must not relocate a metric whose own date differs. */\n metricTemporal?: MetricTemporal[];\n /** Ticket 14: civil-date keys (d:YYYY-MM-DD) of every metricTemporal with\n * temporalKind 'civil-date' — the multiEntry `by-metric-date` index\n * source. Kept distinct from the instant index on purpose: a date-only\n * observation is never a midnight instant. */\n metricDateKeys?: string[];\n /** Ticket 14 provenance: how this row represents the underlying\n * observations — directly recorded, calculated, or a substitute summary. */\n representationKind?: 'direct' | 'calculated' | 'substitute_summary';\n /** Ticket 14: the temporal/production scope a substitute summary covers. */\n summaryCoverage?: SummaryCoverage;\n /** Ticket 14: retained reducer statistics for substitution proofs. */\n reducerStats?: ReducerStats;\n}\n\n/** Scope descriptor of a substitute summary's coverage (ticket 14). */\nexport interface SummaryCoverage {\n scope: 'workout' | 'effort' | 'partition';\n effortSlug?: string;\n /** Partition identity (group-tag pairs, key-sorted). */\n groupTags?: Record<string, string>;\n}\n\n/** Retained statistics for substitution proofs (ticket 16 consumes).\n * `observedCount` is the true represented observation count — never\n * invented for legacy rows that lack it (undefined = insufficient\n * evidence, not 1). */\nexport interface ReducerStats {\n observedCount?: number;\n sum?: number;\n min?: number;\n max?: number;\n}\n\nexport interface MetricTemporal {\n temporalKind: 'instant' | 'civil-date';\n /** Occurrence instant (ms epoch) when temporalKind === 'instant'. */\n instant?: number;\n /** Civil YYYY-MM-DD when temporalKind === 'civil-date'. */\n civilDate?: string;\n}\n\n// ---------------------------------------------------------------------------\n// Field Catalog — V17 derived stores (wayfinder datadog-analytics tickets\n// 14/15). The catalog is a derived index of saved data: reference counts\n// track supporting source records, rows prune at zero, and deltas commit\n// atomically with the source mutation.\n// ---------------------------------------------------------------------------\n\n/** One typed field identity in the catalog. `id` is the collision-free\n * typed key (see fieldRefKey in fields/fieldIdentity). */\nexport interface FieldCatalogEntry {\n id: string;\n /** Normalized full path — the ordered prefix-lookup key for typeahead. */\n path: string;\n kind: string;\n /** Physical/named dimension of a numeric variant, when known. */\n dimension?: string;\n /** Observed original spellings → supporting-source counts (provenance,\n * not identity); a spelling disappears when its final support does. */\n spellings: Record<string, number>;\n /** Observed effective units → supporting-source counts. */\n units: Record<string, number>;\n /** Number of source records currently supporting this identity. */\n sourceCount: number;\n firstSeen: number;\n lastSeen: number;\n}\n\n/** One field identity a source record supports, with everything needed to\n * reverse the contribution (per-source unit/spelling/value evidence). */\nexport interface FieldContribution {\n fieldId: string;\n path: string;\n kind: string;\n unit?: string;\n /** Original spelling this source used. */\n spelling?: string;\n /** Categorical value (string/boolean fields only) — original spelling. */\n value?: string;\n}\n\n/** The contribution set of one stable source record — the reversal record\n * that makes re-saves idempotent and deletions reversible. Contributions\n * are attributed to their owning row id, so streaming appends, finalize\n * replacement, and cascade deletes reverse exactly the affected rows. */\nexport interface FieldSourceRecord {\n /** `${entityKind}:${recordId}` — e.g. `result:r1`, `note:n1`. */\n id: string;\n contributions: Array<FieldContribution & { rowId: string }>;\n}\n\n/** One observed categorical value of a field (string/boolean only). */\nexport interface FieldValueRecord {\n key: [string, string]; // [fieldId, value] — value keeps original spelling\n fieldId: string;\n value: string;\n sourceCount: number;\n}\n\n/** Backfill progress/completion marker (field_catalog_meta store). */\nexport interface CatalogBackfillState {\n id: 'backfill';\n status: 'initializing' | 'complete';\n /** Last processed source key per source store (resume cursor). */\n cursor?: { results?: string; notes?: string; events?: string };\n revision: number;\n updatedAt: number;\n}\n\nexport interface BlockEffort {\n id: string;\n noteId: string;\n blockId: string;\n blockContentId?: string;\n effortSlug: string;\n isStatic?: boolean;\n sourcePath?: string;\n createdAt: number;\n}\n\nexport interface Membership {\n id: string;\n displayName: string;\n picture?: string;\n weight?: number;\n weightUnit?: 'kg' | 'lb';\n height?: number;\n heightUnit?: 'cm' | 'in';\n birthDate?: string;\n createdAt: number;\n updatedAt?: number;\n}\n","import type { ICodeStatement } from '../models/CodeStatement';\nimport type { WorkoutResults } from './results';\n\n/**\n * State of a WOD block\n */\nexport type ScriptBlockState =\n | 'idle'\n | 'parsing'\n | 'parsed'\n | 'error'\n | 'starting'\n | 'running'\n | 'paused'\n | 'completed'\n | 'stopped';\n\n/**\n * Parse error information\n */\nexport interface ParseError {\n message: string;\n line?: number;\n column?: number;\n token?: unknown;\n excerpt?: string;\n severity?: 'error' | 'warning' | 'info';\n}\n\n/** Workout fence tags — `time` is runnable, `log` is recorded */\nexport type FenceDialect = 'time' | 'log';\n\n/** Ordered list of recognised workout fence tags */\nexport const VALID_FENCE_DIALECTS: FenceDialect[] = ['time', 'log'];\n\n/**\n * Run affordance for a fence base tag:\n * `'time'` -> `'run'` (runnable) · `'log'` -> `'log'` (log-mode runtime) · else `null`.\n */\nexport function runAffordance(baseTag: string): 'run' | 'log' | null {\n if (baseTag === 'time') return 'run';\n if (baseTag === 'log') return 'log';\n return null;\n}\n\n/** Section types the editor can parse and render */\nexport type SectionType =\n | 'title'\n | 'markdown'\n | 'time'\n | 'log'\n | 'frontmatter'\n | 'embed'\n | 'code'\n | 'widget'\n | 'query';\n\n/** Workout section types — the runnable/recorded fence tags */\nexport type WorkoutSectionType = Extract<SectionType, FenceDialect>;\n\n/** Type guard for workout sections */\nexport function isWorkoutSectionType(type: SectionType): type is WorkoutSectionType {\n return type === 'time' || type === 'log';\n}\n\n/** Typed front matter subtypes */\nexport type FrontMatterSubtype = 'default' | 'youtube' | 'strava' | 'amazon' | 'file' | 'effort';\n\n/**\n * Represents a single WOD block within the markdown document\n */\nexport interface ScriptBlock {\n /** Unique identifier for this block */\n id: string;\n /** Cross-note content fingerprint, never occurrence identity. */\n contentId?: string;\n /** Workout fence tag ('time' runnable / 'log' recorded) */\n dialect?: FenceDialect;\n /** Sport suffix from the fence */\n sport?: string;\n /** Line number where ```time/```log appears (0-indexed) */\n startLine: number;\n /** Line number where closing ``` appears (0-indexed) */\n endLine: number;\n /** Raw text content of the WOD block */\n content: string;\n /** Parsed statements (populated after parsing) */\n statements?: ICodeStatement[];\n /** Parse errors, if any */\n errors?: ParseError[];\n /** Execution state */\n state: ScriptBlockState;\n /** Collected workout data (after completion) */\n results?: WorkoutResults;\n /** Block version */\n version: number;\n /** Creation timestamp */\n createdAt: number;\n}\n\n/**\n * A single section in the document — the atomic unit of display and editing.\n */\nexport interface Section {\n id: string;\n contentId?: string;\n type: SectionType;\n /** Half-open UTF-16 offsets in the exact authored document. */\n from: number;\n to: number;\n contentFrom?: number;\n contentTo?: number;\n querySuffix?: string;\n separatorAfter?: string;\n subtype?: string;\n rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: string;\n widgetName?: string;\n queryType?: string;\n queryError?: string;\n scriptBlock?: ScriptBlock;\n properties?: Record<string, string>;\n frontmatterType?: FrontMatterSubtype;\n embed?: {\n type: 'image' | 'link' | 'youtube';\n label: string;\n url: string;\n isImage: boolean;\n };\n version: number;\n createdAt: number;\n deleted?: boolean;\n}\n\n/**\n * The full document as an ordered section list.\n */\nexport interface SectionDocument {\n sections: Section[];\n totalLines: number;\n activeSectionId: string | null;\n}\n","/**\n * Notebook Types\n *\n * A notebook is a named, tag-based collection of workout entries.\n */\n\nexport interface Notebook {\n id: string;\n name: string;\n description: string;\n icon: string;\n createdAt: number;\n lastEditedAt: number;\n}\n\nexport const NOTEBOOK_TAG_PREFIX = 'notebook:';\n\nexport const toNotebookTag = (notebookId: string): string =>\n `${NOTEBOOK_TAG_PREFIX}${notebookId}`;\n\nexport const fromNotebookTag = (tag: string): string | null =>\n tag.startsWith(NOTEBOOK_TAG_PREFIX) ? tag.slice(NOTEBOOK_TAG_PREFIX.length) : null;\n\nexport const isNotebookTag = (tag: string): boolean =>\n tag.startsWith(NOTEBOOK_TAG_PREFIX);\n","import { blockContentId } from '../models/blockContentId';\nimport type { NoteBlock } from '../types/storage';\nimport type { FrontMatterSubtype, Section } from '../types/section';\n\nexport { blockContentId };\nexport const KNOWN_SECTION_WIDGETS: readonly string[] = ['playground-run-tip', 'attention', 'code-example', 'syntax-group'];\n\nexport function matchDialectFence(trimmedLine: string): { dialect: 'time' | 'log'; sport?: string } | null {\n const match = trimmedLine.match(/^`{3,}(time|log)(?::([\\w-]+))?\\s*$/i);\n if (!match) return null;\n return { dialect: match[1].toLowerCase() === 'time' ? 'time' : 'log', ...(match[2] ? { sport: match[2] } : {}) };\n}\n\nexport interface SectionRecognitionOptions {\n registeredWidgets?: ReadonlySet<string> | readonly string[];\n}\n\nexport interface ReconcileNoteBlocksOptions extends SectionRecognitionOptions {\n sourceRevision: number;\n /** Current-source occurrence lineage, not a previous document's locations. */\n blocks?: Record<string, NoteBlock>;\n createId?: () => string;\n}\n\n\nfunction frontmatterSubtype(properties: Record<string, string>): FrontMatterSubtype {\n const type = properties.type?.toLowerCase();\n if (type === 'youtube' || type === 'strava' || type === 'amazon' || type === 'file' || type === 'effort') return type;\n const url = properties.url || properties.link || '';\n const host = url.replace(/^[a-z][a-z0-9+.-]*:\\/\\//i, '').split(/[/?#:]/, 1)[0].toLowerCase();\n if (host === 'youtu.be' || host === 'youtube.com' || host.endsWith('.youtube.com')) return 'youtube';\n if (host === 'strava.com' || host.endsWith('.strava.com')) return 'strava';\n if (host === 'amzn.to' || host === 'amazon.com' || host.endsWith('.amazon.com')) return 'amazon';\n if (['baseAttributes', 'discipline', 'effortType', 'targetRPE', 'equipment', 'aliases', 'derivation'].some(key => key in properties)) return 'effort';\n return 'default';\n}\n\nfunction markdownSubtype(text: string): string {\n if (/^#{1,6}\\s/.test(text)) return 'heading';\n if (/^[-*+]\\s|^\\d+\\.\\s/.test(text)) return 'list';\n if (/^>\\s?/.test(text)) return 'blockquote';\n if (text.startsWith('|') && /^\\|[\\s:]*-+/m.test(text)) return 'table';\n return 'paragraph';\n}\n\nexport function parseDocumentSections(content: string, options: SectionRecognitionOptions = {}): Section[] {\n if (!content) return [];\n const lines = content.split(/\\r\\n|\\n|\\r/);\n const offsets: number[] = [];\n const separators: string[] = [];\n let offset = 0;\n for (const text of lines) {\n offsets.push(offset);\n offset += text.length;\n const separator = content.startsWith('\\r\\n', offset) ? '\\r\\n' : /[\\r\\n]/.test(content[offset] ?? '') ? content[offset] : '';\n separators.push(separator);\n offset += separator.length;\n }\n const sections: Section[] = [];\n const createdAt = Date.now();\n let firstText = true;\n let line = 0;\n\n function make(type: Section['type'], start: number, end: number): Section {\n const from = offsets[start];\n const to = offsets[end] + lines[end].length;\n return {\n id: crypto.randomUUID(), type, from, to,\n rawContent: content.slice(from, to), displayContent: content.slice(from, to),\n startLine: start, endLine: end, lineCount: end - start + 1,\n version: 1, createdAt, separatorAfter: separators[end],\n };\n }\n\n while (line < lines.length) {\n const text = lines[line].trim();\n const fence = text.match(/^(`{3,}|~{3,})(.*)$/);\n if (fence) {\n const marker = fence[1];\n let close = line + 1;\n const closing = new RegExp(`^${marker[0]}{${marker.length},}\\\\s*$`);\n while (close < lines.length && !closing.test(lines[close].trim())) close++;\n const closed = close < lines.length;\n const end = closed ? close : lines.length - 1;\n const tag = fence[2].trim();\n const dialect = marker[0] === '`' ? matchDialectFence(`\\`\\`\\`${tag}`) : null;\n const widget = marker[0] === '`' ? tag.match(/^widget:([\\w-]+)$/) : null;\n const query = marker[0] === '`' ? tag.match(/^query(?:[:\\s](.*))?$/i) : null;\n const names = options.registeredWidgets ?? KNOWN_SECTION_WIDGETS;\n const knownWidget = widget && ('has' in names ? names.has(widget[1]) : names.includes(widget[1]));\n const type = closed && dialect ? dialect.dialect : closed && knownWidget ? 'widget' : closed && query ? 'query' : 'code';\n const section = make(type, line, end);\n section.contentFrom = offsets[line] + lines[line].length + separators[line].length;\n section.contentTo = closed ? offsets[close] : section.to;\n section.displayContent = content.slice(section.contentFrom, section.contentTo);\n if (dialect && closed) {\n section.sport = dialect.sport;\n section.contentId = blockContentId(section.displayContent);\n section.scriptBlock = {\n id: section.id, contentId: section.contentId, dialect: dialect.dialect, sport: dialect.sport,\n startLine: line, endLine: end, content: section.displayContent,\n state: 'idle', version: 1, createdAt,\n };\n }\n if (type === 'widget' && widget) section.widgetName = widget[1];\n if (type === 'query' && query) section.querySuffix = (query[1] ?? '').trim();\n sections.push(section);\n line = end + 1;\n continue;\n }\n if (text === '---' && lines[line + 1]?.trim()) {\n let close = line + 1;\n while (close < lines.length && lines[close].trim() !== '---' && !/^(`{3,}|~{3,})/.test(lines[close].trim())) close++;\n const inner = lines.slice(line + 1, close);\n if (lines[close]?.trim() === '---' && inner.some(value => /^[A-Za-z_][\\w-]*\\s*:/.test(value.trim()))) {\n const section = make('frontmatter', line, close);\n section.contentFrom = offsets[line + 1];\n section.contentTo = offsets[close];\n section.displayContent = content.slice(section.contentFrom, section.contentTo);\n section.properties = {};\n for (const value of inner) {\n const pair = value.match(/^([^:]+):\\s*(.*)$/);\n if (pair) section.properties[pair[1].trim()] = pair[2].trim();\n }\n section.frontmatterType = frontmatterSubtype(section.properties);\n sections.push(section);\n line = close + 1;\n continue;\n }\n }\n const embed = text.match(/^(!)?\\[([^\\]]*)\\]\\((https?:\\/\\/[^)\\s]+|\\/[^)\\s]+)\\)$/);\n if (embed) {\n const section = make('embed', line, line);\n const isImage = !!embed[1];\n section.embed = { type: isImage ? 'image' : /(?:youtube\\.com|youtu\\.be)/i.test(embed[3]) ? 'youtube' : 'link', label: embed[2], url: embed[3], isImage };\n sections.push(section);\n line++;\n continue;\n }\n let end = line;\n if (text) {\n while (end + 1 < lines.length && lines[end + 1].trim() && !/^(?:`{3,}|~{3,}|---\\s*$|!?\\[[^\\]]*\\]\\()/.test(lines[end + 1].trim())) end++;\n }\n const section = make(text && firstText ? 'title' : 'markdown', line, end);\n section.subtype = markdownSubtype(section.displayContent.trim());\n if (text) firstText = false;\n sections.push(section);\n line = end + 1;\n }\n return sections;\n}\n\nexport function actionableSectionKind(section: Section): NoteBlock['kind'] | null {\n if (section.type === 'time' || section.type === 'log') return 'wod';\n if (section.type === 'query' || section.type === 'widget' || section.type === 'embed') return section.type;\n return null;\n}\n\nexport function reconcileNoteBlocks(rawContent: string, options: ReconcileNoteBlocksOptions): Record<string, NoteBlock> {\n if (!Number.isSafeInteger(options.sourceRevision) || options.sourceRevision < 1) throw new Error('Invalid source revision');\n const result: Record<string, NoteBlock> = Object.create(null);\n const lineage = Object.values(options.blocks ?? {}).filter(block => block && typeof block === 'object');\n const createId = options.createId ?? (() => crypto.randomUUID());\n for (const section of parseDocumentSections(rawContent, options)) {\n const kind = actionableSectionKind(section);\n if (!kind) continue;\n const matches = lineage.filter(block => block.from === section.from && block.to === section.to && block.kind === kind);\n const prior = matches.length === 1 ? matches[0] : undefined;\n const id = prior?.id ?? createId();\n if (!id || Object.hasOwn(result, id)) throw new Error('Duplicate block occurrence ID');\n result[id] = { id, kind, from: section.from, to: section.to, sourceRevision: options.sourceRevision, version: prior?.version ?? 1,\n ...(kind === 'wod' && (section.type === 'time' || section.type === 'log') ? { dialect: section.type, ...(section.sport ? { sport: section.sport } : {}) } : {}),\n };\n }\n return result;\n}\n\nexport function validateNoteBlocks(rawContent: string, blocks: Record<string, NoteBlock>, sourceRevision: number, options: SectionRecognitionOptions = {}): void {\n if (typeof rawContent !== 'string' || !blocks || typeof blocks !== 'object' || Array.isArray(blocks)) throw new Error('Invalid Note source or blocks');\n for (const [id, block] of Object.entries(blocks)) {\n if (!block || block.id !== id || !id || !Number.isSafeInteger(block.version) || block.version < 1 || block.sourceRevision !== sourceRevision || !Number.isSafeInteger(block.from) || !Number.isSafeInteger(block.to)) throw new Error('Invalid block identity, version or source revision');\n }\n const expected = reconcileNoteBlocks(rawContent, { ...options, sourceRevision, blocks });\n if (Object.keys(expected).length !== Object.keys(blocks).length) throw new Error('Incomplete actionable block map');\n for (const [id, block] of Object.entries(blocks)) {\n const recognized = expected[id];\n if (!recognized || recognized.from !== block.from || recognized.to !== block.to || recognized.kind !== block.kind || recognized.dialect !== block.dialect || recognized.sport !== block.sport) throw new Error('Block does not match authored source');\n }\n}\n\nexport interface NoteBlockChange { from: number; to: number; insert: string }\n\nexport function mapNoteBlockChanges(blocks: Record<string, NoteBlock>, changes: readonly NoteBlockChange[]): Record<string, NoteBlock> {\n let previousEnd = 0;\n for (const change of changes) {\n if (!Number.isSafeInteger(change.from) || !Number.isSafeInteger(change.to) || change.from < previousEnd || change.to < change.from || typeof change.insert !== 'string') throw new Error('Invalid source changes');\n previousEnd = change.to;\n }\n const result: Record<string, NoteBlock> = {};\n for (const block of Object.values(blocks)) {\n let from = block.from;\n let to = block.to;\n let removed = false;\n for (const change of changes) {\n const delta = change.insert.length - (change.to - change.from);\n if (change.from <= block.from && change.to >= block.to || change.from < block.from && change.to > block.from || change.from < block.to && change.to > block.to) { removed = true; break; }\n if (change.to <= block.from) { from += delta; to += delta; }\n else if (change.from < block.to) to += delta;\n }\n if (!removed) result[block.id] = { ...block, from, to };\n }\n return result;\n}\n\nexport function buildRawContent(sections: Section[]): string {\n return sections.filter(section => !section.deleted).map(section => section.rawContent + (section.separatorAfter ?? '')).join('');\n}\n\nexport function calculateTotalLines(sections: Section[]): number {\n const visible = sections.filter(section => !section.deleted);\n return visible.length ? visible[visible.length - 1].endLine + 1 : 0;\n}\n","import { parseDocumentSections } from './sectionParser';\nimport type { ScriptBlock } from '../types/section';\n\n\n/**\n * Detects all WOD blocks in markdown content.\n * Recognises ```time and ```log as valid workout fences (optional :sport suffix).\n *\n * @param content - Markdown content to parse\n * @returns Array of detected WOD blocks (with dialect set)\n */\nexport function detectScriptBlocks(content: string): ScriptBlock[] {\n return parseDocumentSections(content).flatMap(section => section.scriptBlock ? [section.scriptBlock] : []);\n}\n\n/**\n * Find which block contains a given line number.\n *\n * @param blocks - Array of WOD blocks\n * @param lineNumber - Line number to search for (0-indexed)\n * @returns The block containing the line, or null if not found\n */\nexport function findBlockAtLine(\n blocks: ScriptBlock[],\n lineNumber: number\n): ScriptBlock | null {\n return (\n blocks.find(\n (block) => lineNumber >= block.startLine && lineNumber <= block.endLine\n ) ?? null\n );\n}\n\n/**\n * Extract WOD block content from markdown (without backticks).\n *\n * @param content - Full markdown content\n * @param startLine - Start line of block (0-indexed)\n * @param endLine - End line of block (0-indexed)\n * @returns Extracted block content\n */\nexport function extractBlockContent(content: string, startLine: number, endLine: number): string {\n return parseDocumentSections(content).find(section => section.startLine === startLine && section.endLine === endLine && section.scriptBlock)?.scriptBlock?.content ?? '';\n}\n","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.35.2117';\nexport const GIT_SHA = '03d1dfc';\nexport const BUILD_TIME = '2026-10-12T20:08:12.374Z';\nexport const SEMVER = {\n version: '0.35.2117',\n gitSha: '03d1dfc',\n buildTime: '2026-10-12T20:08:12.374Z',\n} as const;\n"]}