@bitcobblers/wod-wiki-core 0.8.39 → 0.9.40

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -840,13 +840,13 @@ var fromNotebookTag = (tag) => tag.startsWith(NOTEBOOK_TAG_PREFIX) ? tag.slice(N
840
840
  var isNotebookTag = (tag) => tag.startsWith(NOTEBOOK_TAG_PREFIX);
841
841
 
842
842
  // src/version.ts
843
- var VERSION = "0.8.39";
844
- var GIT_SHA = "3c19185";
845
- var BUILD_TIME = "2026-08-26T00:07:31.934Z";
843
+ var VERSION = "0.9.40";
844
+ var GIT_SHA = "2462ec9";
845
+ var BUILD_TIME = "2026-08-26T01:04:47.412Z";
846
846
  var SEMVER = {
847
- version: "0.8.39",
848
- gitSha: "3c19185",
849
- buildTime: "2026-08-26T00:07:31.934Z"
847
+ version: "0.9.40",
848
+ gitSha: "2462ec9",
849
+ buildTime: "2026-08-26T01:04:47.412Z"
850
850
  };
851
851
 
852
852
  exports.BUILD_TIME = BUILD_TIME;
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ownership/types.ts","../src/ownership/ledger.ts","../src/models/Metric.ts","../src/ownership/OwnershipResolver.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/Duration.ts","../src/models/BlockKey.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/version.ts"],"names":["MetricType","resolveLayer"],"mappings":";;;AAqBO,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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AAA,GAAI;AAEzE,IAAM,aAAA,GAAgB,CAAC,GAAA,KAC5B,GAAA,CAAI,WAAW,mBAAmB;;;ACpB7B,IAAM,OAAA,GAAU;AAChB,IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,QAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.cjs","sourcesContent":["import type { IMetric, MetricOrigin } from '../models/Metric';\n\n/**\n * Canonical ownership vocabulary for metric visibility decisions.\n *\n * This is intentionally separate from {@link MetricOrigin}, which still carries\n * legacy producer/state detail used by existing callers.\n *\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 * 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","import type { IMetric } from '../models/Metric';\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\nfunction 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\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","import type { MetricOwnershipLayer } from '../ownership/types';\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/**\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 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 { IMetric, MetricType } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport type { MetricOwnershipLayer, MetricWithOptionalOwnershipLayer } from './types';\nimport { getMetricOwnershipLayer, METRIC_OWNERSHIP_LAYER_CHAIN } from './types';\nimport { createMetricOwnershipLedger } from './ledger';\n\nfunction resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) return maybeLayer;\n return getMetricOwnershipLayer(metric.origin ?? 'parser');\n}\n\n/**\n * Ownership layer rank for a metric (0 = lowest = parser, 4 = highest = user-entry).\n * Higher rank wins.\n */\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return METRIC_OWNERSHIP_LAYER_CHAIN.indexOf(layer);\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\n/**\n * Single-path resolver wrapping `MetricOwnershipLedger` + legacy filter translation.\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","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 } from './CodeStatement';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource, MetricFilter } 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 /** 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 implements IOutputStatement, IMetricSource {\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 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.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.timestamp = timestamp ?? Date.now();\n }\n }\n\n // ═══════════════════════════════════════════════════════════════\n // IMetricSource implementation\n // ═══════════════════════════════════════════════════════════════\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metrics.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metrics.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metrics.getAllMetricsByType(type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.metrics.hasMetric(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metrics.rawMetrics;\n }\n\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","import type { TimeSpan } from './TimeSpan';\n\nexport interface IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n original?: number;\n}\n\nexport class Duration implements IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n\n constructor(public original?: number) {\n let remaining = original ?? 0;\n\n this.days = Math.floor(remaining / 86400000);\n remaining %= 86400000;\n\n this.hours = Math.floor(remaining / 3600000);\n remaining %= 3600000;\n\n this.minutes = Math.floor(remaining / 60000);\n remaining %= 60000;\n\n this.seconds = Math.floor(remaining / 1000);\n\n this.milliseconds = Math.round(remaining - this.seconds * 1000);\n }\n}\n\nexport class SpanDuration extends Duration {\n constructor(spans: TimeSpan[]) {\n const total = spans.reduce((sum, span) => {\n const end = span.ended ?? Date.now();\n return sum + Math.max(0, end - span.started);\n }, 0);\n super(total);\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","import type { StoredOutputStatement, WorkoutResults } 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 = 'note' | 'template' | 'playground' | 'journal';\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n slug?: string;\n pageId?: string;\n createdAt: number;\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: 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\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general';\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// WorkoutResult — execution log\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface WorkoutResult {\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 data: WorkoutResults;\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 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 timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// UnifiedEventRecord — THE single stored record for all workout data\n// (wayfinder ticket 002). Replaces AnalyticsDataPoint as the stored/query\n// shape; results.data.logs stay the archival source of truth (ticket 005).\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\nexport interface UnifiedEventRecord {\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 /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n effortSlug?: 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 stackLevel?: number;\n completionReason?: string;\n segmentId?: string;\n segmentVersion?: 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 = 'title' | 'markdown' | 'time' | 'log' | 'frontmatter' | 'embed';\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 rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: 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","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.8.39';\nexport const GIT_SHA = '3c19185';\nexport const BUILD_TIME = '2026-08-26T00:07:31.934Z';\nexport const SEMVER = {\n version: '0.8.39',\n gitSha: '3c19185',\n buildTime: '2026-08-26T00:07:31.934Z',\n} as const;\n"]}
1
+ {"version":3,"sources":["../src/ownership/types.ts","../src/ownership/ledger.ts","../src/models/Metric.ts","../src/ownership/OwnershipResolver.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/Duration.ts","../src/models/BlockKey.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/version.ts"],"names":["MetricType","resolveLayer"],"mappings":";;;AAqBO,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,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IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,QAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.cjs","sourcesContent":["import type { IMetric, MetricOrigin } from '../models/Metric';\n\n/**\n * Canonical ownership vocabulary for metric visibility decisions.\n *\n * This is intentionally separate from {@link MetricOrigin}, which still carries\n * legacy producer/state detail used by existing callers.\n *\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 * 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","import type { IMetric } from '../models/Metric';\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\nfunction 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\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","import type { MetricOwnershipLayer } from '../ownership/types';\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/**\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 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 { IMetric, MetricType } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport type { MetricOwnershipLayer, MetricWithOptionalOwnershipLayer } from './types';\nimport { getMetricOwnershipLayer, METRIC_OWNERSHIP_LAYER_CHAIN } from './types';\nimport { createMetricOwnershipLedger } from './ledger';\n\nfunction resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) return maybeLayer;\n return getMetricOwnershipLayer(metric.origin ?? 'parser');\n}\n\n/**\n * Ownership layer rank for a metric (0 = lowest = parser, 4 = highest = user-entry).\n * Higher rank wins.\n */\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return METRIC_OWNERSHIP_LAYER_CHAIN.indexOf(layer);\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\n/**\n * Single-path resolver wrapping `MetricOwnershipLedger` + legacy filter translation.\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","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 } from './CodeStatement';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource, MetricFilter } 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 /** 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 implements IOutputStatement, IMetricSource {\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 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.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.timestamp = timestamp ?? Date.now();\n }\n }\n\n // ═══════════════════════════════════════════════════════════════\n // IMetricSource implementation\n // ═══════════════════════════════════════════════════════════════\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metrics.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metrics.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metrics.getAllMetricsByType(type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.metrics.hasMetric(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metrics.rawMetrics;\n }\n\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","import type { TimeSpan } from './TimeSpan';\n\nexport interface IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n original?: number;\n}\n\nexport class Duration implements IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n\n constructor(public original?: number) {\n let remaining = original ?? 0;\n\n this.days = Math.floor(remaining / 86400000);\n remaining %= 86400000;\n\n this.hours = Math.floor(remaining / 3600000);\n remaining %= 3600000;\n\n this.minutes = Math.floor(remaining / 60000);\n remaining %= 60000;\n\n this.seconds = Math.floor(remaining / 1000);\n\n this.milliseconds = Math.round(remaining - this.seconds * 1000);\n }\n}\n\nexport class SpanDuration extends Duration {\n constructor(spans: TimeSpan[]) {\n const total = spans.reduce((sum, span) => {\n const end = span.ended ?? Date.now();\n return sum + Math.max(0, end - span.started);\n }, 0);\n super(total);\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","import type { StoredOutputStatement, WorkoutResults } 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 = 'note' | 'template' | 'playground' | 'journal';\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n slug?: string;\n pageId?: string;\n createdAt: number;\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: 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\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general';\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// WorkoutResult — execution log\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface WorkoutResult {\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 data: WorkoutResults;\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 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 timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// UnifiedEventRecord — THE single stored record for all workout data\n// (wayfinder ticket 002). Replaces AnalyticsDataPoint as the stored/query\n// shape; results.data.logs stay the archival source of truth (ticket 005).\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\nexport interface UnifiedEventRecord {\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 /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n effortSlug?: 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 stackLevel?: number;\n completionReason?: string;\n segmentId?: string;\n segmentVersion?: 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 = 'title' | 'markdown' | 'time' | 'log' | 'frontmatter' | 'embed';\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 rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: 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","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.9.40';\nexport const GIT_SHA = '2462ec9';\nexport const BUILD_TIME = '2026-08-26T01:04:47.412Z';\nexport const SEMVER = {\n version: '0.9.40',\n gitSha: '2462ec9',\n buildTime: '2026-08-26T01:04:47.412Z',\n} as const;\n"]}
package/dist/index.d.cts CHANGED
@@ -1122,13 +1122,13 @@ interface IScript {
1122
1122
  * Auto-generated build version metadata.
1123
1123
  * Do not edit directly; updated by scripts/stamp-version.ts
1124
1124
  */
1125
- declare const VERSION = "0.8.39";
1126
- declare const GIT_SHA = "3c19185";
1127
- declare const BUILD_TIME = "2026-08-26T00:07:31.934Z";
1125
+ declare const VERSION = "0.9.40";
1126
+ declare const GIT_SHA = "2462ec9";
1127
+ declare const BUILD_TIME = "2026-08-26T01:04:47.412Z";
1128
1128
  declare const SEMVER: {
1129
- readonly version: "0.8.39";
1130
- readonly gitSha: "3c19185";
1131
- readonly buildTime: "2026-08-26T00:07:31.934Z";
1129
+ readonly version: "0.9.40";
1130
+ readonly gitSha: "2462ec9";
1131
+ readonly buildTime: "2026-08-26T01:04:47.412Z";
1132
1132
  };
1133
1133
 
1134
1134
  export { type AnalyticsDataPoint, type AnalyticsGraphConfig, type AnalyticsGroup, type Attachment, BUILD_TIME, type BlockIndexRow, BlockKey, CodeMetadata, CodeStatement, type DialectAnalysis, type DisplayStatus, Duration, type EventGrain, type FenceDialect, type FrontMatterSubtype, GIT_SHA, type IBlockKey, type ICodeMetadata, type ICodeStatement, type IDialect, type IDialectTagDescriptor, type IDuration, type IEstimate, type IMetric, type IMetricContainer, type IMetricOwnershipResolver, type IMetricSource, type IMetricSummary, type IOutputStatement, type IScript, type ISummary, KNOWN_OUTPUT_TYPES, LEGACY_ORIGIN_TO_OWNERSHIP_LAYER, METRIC_OWNERSHIP_LAYER_CHAIN, Metric, type MetricAction, MetricContainer, type MetricFilter, type MetricOrigin, type MetricOwnershipLayer, type MetricOwnershipLedger, type MetricOwnershipOutcome, type MetricOwnershipPromotionCandidate, type MetricOwnershipQuery, type MetricOwnershipResolvedContribution, type MetricOwnershipTypeExplanation, MetricType, type MetricWithOptionalOwnershipLayer, NOTEBOOK_TAG_PREFIX, type Note, type NoteKind, type NoteSegment, type NoteTag, type Notebook, type Origin, OutputStatement, type OutputStatementOptions, type OutputStatementType, OwnershipResolver, type Page, type ParseError, ParsedCodeStatement, type ResultOrigin, SEMVER, type ScriptBlock, type ScriptBlockState, type Section, type SectionDocument, type SectionType, type Segment, type SegmentDataType, SpanDuration, type StoredOutputStatement, type SummaryStage, type Tag, type TagType, type TimeSpan, type UnifiedEventRecord, VALID_FENCE_DIALECTS, VERSION, type VisualizerFilter, type VisualizerSize, type WorkoutResult, type WorkoutResults, type WorkoutSectionType, createMetricOwnershipLedger, fromNotebookTag, getMetricOwnershipLayer, isNotebookTag, isWorkoutSectionType, ownershipRank, runAffordance, toNotebookTag };
package/dist/index.d.ts CHANGED
@@ -1122,13 +1122,13 @@ interface IScript {
1122
1122
  * Auto-generated build version metadata.
1123
1123
  * Do not edit directly; updated by scripts/stamp-version.ts
1124
1124
  */
1125
- declare const VERSION = "0.8.39";
1126
- declare const GIT_SHA = "3c19185";
1127
- declare const BUILD_TIME = "2026-08-26T00:07:31.934Z";
1125
+ declare const VERSION = "0.9.40";
1126
+ declare const GIT_SHA = "2462ec9";
1127
+ declare const BUILD_TIME = "2026-08-26T01:04:47.412Z";
1128
1128
  declare const SEMVER: {
1129
- readonly version: "0.8.39";
1130
- readonly gitSha: "3c19185";
1131
- readonly buildTime: "2026-08-26T00:07:31.934Z";
1129
+ readonly version: "0.9.40";
1130
+ readonly gitSha: "2462ec9";
1131
+ readonly buildTime: "2026-08-26T01:04:47.412Z";
1132
1132
  };
1133
1133
 
1134
1134
  export { type AnalyticsDataPoint, type AnalyticsGraphConfig, type AnalyticsGroup, type Attachment, BUILD_TIME, type BlockIndexRow, BlockKey, CodeMetadata, CodeStatement, type DialectAnalysis, type DisplayStatus, Duration, type EventGrain, type FenceDialect, type FrontMatterSubtype, GIT_SHA, type IBlockKey, type ICodeMetadata, type ICodeStatement, type IDialect, type IDialectTagDescriptor, type IDuration, type IEstimate, type IMetric, type IMetricContainer, type IMetricOwnershipResolver, type IMetricSource, type IMetricSummary, type IOutputStatement, type IScript, type ISummary, KNOWN_OUTPUT_TYPES, LEGACY_ORIGIN_TO_OWNERSHIP_LAYER, METRIC_OWNERSHIP_LAYER_CHAIN, Metric, type MetricAction, MetricContainer, type MetricFilter, type MetricOrigin, type MetricOwnershipLayer, type MetricOwnershipLedger, type MetricOwnershipOutcome, type MetricOwnershipPromotionCandidate, type MetricOwnershipQuery, type MetricOwnershipResolvedContribution, type MetricOwnershipTypeExplanation, MetricType, type MetricWithOptionalOwnershipLayer, NOTEBOOK_TAG_PREFIX, type Note, type NoteKind, type NoteSegment, type NoteTag, type Notebook, type Origin, OutputStatement, type OutputStatementOptions, type OutputStatementType, OwnershipResolver, type Page, type ParseError, ParsedCodeStatement, type ResultOrigin, SEMVER, type ScriptBlock, type ScriptBlockState, type Section, type SectionDocument, type SectionType, type Segment, type SegmentDataType, SpanDuration, type StoredOutputStatement, type SummaryStage, type Tag, type TagType, type TimeSpan, type UnifiedEventRecord, VALID_FENCE_DIALECTS, VERSION, type VisualizerFilter, type VisualizerSize, type WorkoutResult, type WorkoutResults, type WorkoutSectionType, createMetricOwnershipLedger, fromNotebookTag, getMetricOwnershipLayer, isNotebookTag, isWorkoutSectionType, ownershipRank, runAffordance, toNotebookTag };
package/dist/index.mjs CHANGED
@@ -838,13 +838,13 @@ var fromNotebookTag = (tag) => tag.startsWith(NOTEBOOK_TAG_PREFIX) ? tag.slice(N
838
838
  var isNotebookTag = (tag) => tag.startsWith(NOTEBOOK_TAG_PREFIX);
839
839
 
840
840
  // src/version.ts
841
- var VERSION = "0.8.39";
842
- var GIT_SHA = "3c19185";
843
- var BUILD_TIME = "2026-08-26T00:07:31.934Z";
841
+ var VERSION = "0.9.40";
842
+ var GIT_SHA = "2462ec9";
843
+ var BUILD_TIME = "2026-08-26T01:04:47.412Z";
844
844
  var SEMVER = {
845
- version: "0.8.39",
846
- gitSha: "3c19185",
847
- buildTime: "2026-08-26T00:07:31.934Z"
845
+ version: "0.9.40",
846
+ gitSha: "2462ec9",
847
+ buildTime: "2026-08-26T01:04:47.412Z"
848
848
  };
849
849
 
850
850
  export { BUILD_TIME, BlockKey, CodeMetadata, CodeStatement, Duration, GIT_SHA, KNOWN_OUTPUT_TYPES, LEGACY_ORIGIN_TO_OWNERSHIP_LAYER, METRIC_OWNERSHIP_LAYER_CHAIN, Metric, MetricContainer, MetricType, NOTEBOOK_TAG_PREFIX, OutputStatement, OwnershipResolver, ParsedCodeStatement, SEMVER, SpanDuration, VALID_FENCE_DIALECTS, VERSION, createMetricOwnershipLedger, fromNotebookTag, getMetricOwnershipLayer, isNotebookTag, isWorkoutSectionType, ownershipRank, runAffordance, toNotebookTag };
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/ownership/types.ts","../src/ownership/ledger.ts","../src/models/Metric.ts","../src/ownership/OwnershipResolver.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/Duration.ts","../src/models/BlockKey.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/version.ts"],"names":["MetricType","resolveLayer"],"mappings":";AAqBO,IAAM,4BAAA,GAAgE;AAAA,EAC3E,QAAA;AAAA,EACA,SAAA;AAAA,EACA,WAAA;AAAA,EACA,SAAA;AAAA,EACA;AACF;AAMO,IAAM,g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,UAAU,CAAA;AAE9B,IAAM,eAAA,GAAkB,CAAC,GAAA,KAC9B,GAAA,CAAI,UAAA,CAAW,mBAAmB,CAAA,GAAI,GAAA,CAAI,KAAA,CAAM,mBAAA,CAAoB,MAAM,CAAA,GAAI;AAEzE,IAAM,aAAA,GAAgB,CAAC,GAAA,KAC5B,GAAA,CAAI,WAAW,mBAAmB;;;ACpB7B,IAAM,OAAA,GAAU;AAChB,IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,QAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.mjs","sourcesContent":["import type { IMetric, MetricOrigin } from '../models/Metric';\n\n/**\n * Canonical ownership vocabulary for metric visibility decisions.\n *\n * This is intentionally separate from {@link MetricOrigin}, which still carries\n * legacy producer/state detail used by existing callers.\n *\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 * 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","import type { IMetric } from '../models/Metric';\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\nfunction 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\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","import type { MetricOwnershipLayer } from '../ownership/types';\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/**\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 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 { IMetric, MetricType } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport type { MetricOwnershipLayer, MetricWithOptionalOwnershipLayer } from './types';\nimport { getMetricOwnershipLayer, METRIC_OWNERSHIP_LAYER_CHAIN } from './types';\nimport { createMetricOwnershipLedger } from './ledger';\n\nfunction resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) return maybeLayer;\n return getMetricOwnershipLayer(metric.origin ?? 'parser');\n}\n\n/**\n * Ownership layer rank for a metric (0 = lowest = parser, 4 = highest = user-entry).\n * Higher rank wins.\n */\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return METRIC_OWNERSHIP_LAYER_CHAIN.indexOf(layer);\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\n/**\n * Single-path resolver wrapping `MetricOwnershipLedger` + legacy filter translation.\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","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 } from './CodeStatement';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource, MetricFilter } 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 /** 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 implements IOutputStatement, IMetricSource {\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 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.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.timestamp = timestamp ?? Date.now();\n }\n }\n\n // ═══════════════════════════════════════════════════════════════\n // IMetricSource implementation\n // ═══════════════════════════════════════════════════════════════\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metrics.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metrics.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metrics.getAllMetricsByType(type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.metrics.hasMetric(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metrics.rawMetrics;\n }\n\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","import type { TimeSpan } from './TimeSpan';\n\nexport interface IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n original?: number;\n}\n\nexport class Duration implements IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n\n constructor(public original?: number) {\n let remaining = original ?? 0;\n\n this.days = Math.floor(remaining / 86400000);\n remaining %= 86400000;\n\n this.hours = Math.floor(remaining / 3600000);\n remaining %= 3600000;\n\n this.minutes = Math.floor(remaining / 60000);\n remaining %= 60000;\n\n this.seconds = Math.floor(remaining / 1000);\n\n this.milliseconds = Math.round(remaining - this.seconds * 1000);\n }\n}\n\nexport class SpanDuration extends Duration {\n constructor(spans: TimeSpan[]) {\n const total = spans.reduce((sum, span) => {\n const end = span.ended ?? Date.now();\n return sum + Math.max(0, end - span.started);\n }, 0);\n super(total);\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","import type { StoredOutputStatement, WorkoutResults } 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 = 'note' | 'template' | 'playground' | 'journal';\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n slug?: string;\n pageId?: string;\n createdAt: number;\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: 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\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general';\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// WorkoutResult — execution log\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface WorkoutResult {\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 data: WorkoutResults;\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 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 timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// UnifiedEventRecord — THE single stored record for all workout data\n// (wayfinder ticket 002). Replaces AnalyticsDataPoint as the stored/query\n// shape; results.data.logs stay the archival source of truth (ticket 005).\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\nexport interface UnifiedEventRecord {\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 /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n effortSlug?: 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 stackLevel?: number;\n completionReason?: string;\n segmentId?: string;\n segmentVersion?: 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 = 'title' | 'markdown' | 'time' | 'log' | 'frontmatter' | 'embed';\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 rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: 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","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.8.39';\nexport const GIT_SHA = '3c19185';\nexport const BUILD_TIME = '2026-08-26T00:07:31.934Z';\nexport const SEMVER = {\n version: '0.8.39',\n gitSha: '3c19185',\n buildTime: '2026-08-26T00:07:31.934Z',\n} as const;\n"]}
1
+ {"version":3,"sources":["../src/ownership/types.ts","../src/ownership/ledger.ts","../src/models/Metric.ts","../src/ownership/OwnershipResolver.ts","../src/models/CodeMetadata.ts","../src/models/MetricContainer.ts","../src/models/CodeStatement.ts","../src/models/OutputStatement.ts","../src/models/Duration.ts","../src/models/BlockKey.ts","../src/types/storage.ts","../src/types/section.ts","../src/types/notebook.ts","../src/version.ts"],"names":["MetricType","resolveLayer"],"mappings":";AAqBO,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,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,CAAM,mBAAA,CAAoB,MAAM,CAAA,GAAI;AAEzE,IAAM,aAAA,GAAgB,CAAC,GAAA,KAC5B,GAAA,CAAI,WAAW,mBAAmB;;;ACpB7B,IAAM,OAAA,GAAU;AAChB,IAAM,OAAA,GAAU;AAChB,IAAM,UAAA,GAAa;AACnB,IAAM,MAAA,GAAS;AAAA,EACpB,OAAA,EAAS,QAAA;AAAA,EACT,MAAA,EAAQ,SAAA;AAAA,EACR,SAAA,EAAW;AACb","file":"index.mjs","sourcesContent":["import type { IMetric, MetricOrigin } from '../models/Metric';\n\n/**\n * Canonical ownership vocabulary for metric visibility decisions.\n *\n * This is intentionally separate from {@link MetricOrigin}, which still carries\n * legacy producer/state detail used by existing callers.\n *\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 * 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","import type { IMetric } from '../models/Metric';\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\nfunction 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\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","import type { MetricOwnershipLayer } from '../ownership/types';\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/**\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 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 { IMetric, MetricType } from '../models/Metric';\nimport type { MetricFilter } from '../contracts/IMetricSource';\nimport type { IMetricOwnershipResolver } from '../contracts/IMetricOwnershipResolver';\nimport type { MetricOwnershipLayer, MetricWithOptionalOwnershipLayer } from './types';\nimport { getMetricOwnershipLayer, METRIC_OWNERSHIP_LAYER_CHAIN } from './types';\nimport { createMetricOwnershipLedger } from './ledger';\n\nfunction resolveLayer(metric: IMetric): MetricOwnershipLayer {\n const maybeLayer = (metric as MetricWithOptionalOwnershipLayer).ownershipLayer;\n if (maybeLayer != null) return maybeLayer;\n return getMetricOwnershipLayer(metric.origin ?? 'parser');\n}\n\n/**\n * Ownership layer rank for a metric (0 = lowest = parser, 4 = highest = user-entry).\n * Higher rank wins.\n */\nexport function ownershipRank(metric: IMetric): number {\n const layer = resolveLayer(metric);\n return METRIC_OWNERSHIP_LAYER_CHAIN.indexOf(layer);\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\n/**\n * Single-path resolver wrapping `MetricOwnershipLedger` + legacy filter translation.\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","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 } from './CodeStatement';\nimport { IMetric, MetricType } from './Metric';\nimport { MetricContainer } from './MetricContainer';\nimport { CodeMetadata } from './CodeMetadata';\nimport { TimeSpan } from './TimeSpan';\nimport type { IMetricSource, MetricFilter } 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 /** 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 implements IOutputStatement, IMetricSource {\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 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.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.timestamp = timestamp ?? Date.now();\n }\n }\n\n // ═══════════════════════════════════════════════════════════════\n // IMetricSource implementation\n // ═══════════════════════════════════════════════════════════════\n\n getDisplayMetrics(filter?: MetricFilter): IMetric[] {\n return this.metrics.getDisplayMetrics(filter);\n }\n\n getMetric(type: MetricType | string): IMetric | undefined {\n return this.metrics.getMetric(type);\n }\n\n getAllMetricsByType(type: MetricType | string): IMetric[] {\n return this.metrics.getAllMetricsByType(type);\n }\n\n hasMetric(type: MetricType | string): boolean {\n return this.metrics.hasMetric(type);\n }\n\n get rawMetrics(): IMetric[] {\n return this.metrics.rawMetrics;\n }\n\n /**\n * Reset the ID counter (useful for testing)\n */\n static resetIdCounter(startAt: number = 1000000): void {\n OutputStatement.nextId = startAt;\n }\n}\n","import type { TimeSpan } from './TimeSpan';\n\nexport interface IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n original?: number;\n}\n\nexport class Duration implements IDuration {\n days?: number;\n hours?: number;\n minutes?: number;\n seconds?: number;\n milliseconds?: number;\n\n constructor(public original?: number) {\n let remaining = original ?? 0;\n\n this.days = Math.floor(remaining / 86400000);\n remaining %= 86400000;\n\n this.hours = Math.floor(remaining / 3600000);\n remaining %= 3600000;\n\n this.minutes = Math.floor(remaining / 60000);\n remaining %= 60000;\n\n this.seconds = Math.floor(remaining / 1000);\n\n this.milliseconds = Math.round(remaining - this.seconds * 1000);\n }\n}\n\nexport class SpanDuration extends Duration {\n constructor(spans: TimeSpan[]) {\n const total = spans.reduce((sum, span) => {\n const end = span.ended ?? Date.now();\n return sum + Math.max(0, end - span.started);\n }, 0);\n super(total);\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","import type { StoredOutputStatement, WorkoutResults } 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 = 'note' | 'template' | 'playground' | 'journal';\n\nexport interface Note {\n id: string; // UUID — canonical storage identity\n title: string; // Display name\n slug?: string;\n pageId?: string;\n createdAt: number;\n type?: NoteKind;\n sourceId?: string;\n catalog?: string;\n tags?: 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\n slug?: string;\n title?: string;\n createdAt: number;\n}\n\n// ---------------------------------------------------------------------------\n// Tag / NoteTag — normalized note tagging\n// ---------------------------------------------------------------------------\nexport type TagType = 'template' | 'playground' | 'qualification' | 'notebook' | 'general';\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// WorkoutResult — execution log\n// ---------------------------------------------------------------------------\nexport type ResultOrigin = 'journal' | 'playground' | 'user';\n\nexport interface WorkoutResult {\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 data: WorkoutResults;\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 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 timestamp: number;\n createdAt: number;\n}\n\n\n// ---------------------------------------------------------------------------\n// UnifiedEventRecord — THE single stored record for all workout data\n// (wayfinder ticket 002). Replaces AnalyticsDataPoint as the stored/query\n// shape; results.data.logs stay the archival source of truth (ticket 005).\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\nexport interface UnifiedEventRecord {\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 /** Open vocabulary — see KNOWN_OUTPUT_TYPES. */\n outputType: string;\n effortSlug?: 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 stackLevel?: number;\n completionReason?: string;\n segmentId?: string;\n segmentVersion?: 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 = 'title' | 'markdown' | 'time' | 'log' | 'frontmatter' | 'embed';\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 rawContent: string;\n displayContent: string;\n startLine: number;\n endLine: number;\n lineCount: number;\n level?: number;\n sport?: 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","/**\n * Auto-generated build version metadata.\n * Do not edit directly; updated by scripts/stamp-version.ts\n */\nexport const VERSION = '0.9.40';\nexport const GIT_SHA = '2462ec9';\nexport const BUILD_TIME = '2026-08-26T01:04:47.412Z';\nexport const SEMVER = {\n version: '0.9.40',\n gitSha: '2462ec9',\n buildTime: '2026-08-26T01:04:47.412Z',\n} as const;\n"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bitcobblers/wod-wiki-core",
3
- "version": "0.8.39",
3
+ "version": "0.9.40",
4
4
  "description": "Shared data vocabulary for Whiteboard Language & WQL engine",
5
5
  "type": "module",
6
6
  "main": "./dist/index.cjs",