margin-ts 0.6.0

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/src/index.ts ADDED
@@ -0,0 +1,33 @@
1
+ /**
2
+ * margin — Typed health classification for systems that measure things.
3
+ *
4
+ * TypeScript port of the Python margin library.
5
+ * Zero dependencies. Pure TypeScript.
6
+ *
7
+ * Copyright (c) 2026 Cope Labs LLC. MIT License.
8
+ */
9
+
10
+ export { Confidence, confidenceRank, confidenceGte, confidenceLt, minConfidence } from './confidence.js';
11
+
12
+ export {
13
+ Health, SEVERITY, Thresholds, createThresholds,
14
+ isIntact, isAblated, classify,
15
+ } from './health.js';
16
+
17
+ export {
18
+ Op, Observation, Correction, Expression,
19
+ observationSigma, observationToAtom, observationToDict, observationFromDict,
20
+ correctionIsActive,
21
+ createExpression, healthOf, degraded, expressionToString, expressionToDict,
22
+ Parser,
23
+ } from './observation.js';
24
+
25
+ export {
26
+ DriftState, DriftDirection, DriftClassification,
27
+ classifyDrift,
28
+ } from './drift.js';
29
+
30
+ export {
31
+ AnomalyState, ANOMALY_SEVERITY, AnomalyClassification,
32
+ classifyAnomaly,
33
+ } from './anomaly.js';
@@ -0,0 +1,201 @@
1
+ /**
2
+ * Observations, corrections, expressions, and parser.
3
+ */
4
+
5
+ import { Confidence, minConfidence } from './confidence.js';
6
+ import { Health, Thresholds, classify, createThresholds, isIntact, SEVERITY } from './health.js';
7
+
8
+ // -----------------------------------------------------------------------
9
+ // Observation
10
+ // -----------------------------------------------------------------------
11
+
12
+ export interface Observation {
13
+ name: string;
14
+ health: Health;
15
+ value: number;
16
+ baseline: number;
17
+ confidence: Confidence;
18
+ higherIsBetter: boolean;
19
+ provenance: string[];
20
+ measuredAt?: Date;
21
+ }
22
+
23
+ export function observationSigma(obs: Observation): number {
24
+ if (obs.baseline === 0) return 0;
25
+ const raw = (obs.value - obs.baseline) / Math.abs(obs.baseline);
26
+ return obs.higherIsBetter ? raw : -raw;
27
+ }
28
+
29
+ export function observationToAtom(obs: Observation): string {
30
+ if (obs.health === Health.OOD) return `${obs.name}:${obs.health}`;
31
+ const sigma = observationSigma(obs);
32
+ const sign = sigma >= 0 ? '+' : '';
33
+ return `${obs.name}:${obs.health}(${sign}${sigma.toFixed(2)}σ)`;
34
+ }
35
+
36
+ export function observationToDict(obs: Observation): Record<string, unknown> {
37
+ const d: Record<string, unknown> = {
38
+ name: obs.name,
39
+ health: obs.health,
40
+ value: obs.value,
41
+ baseline: obs.baseline,
42
+ sigma: observationSigma(obs),
43
+ confidence: obs.confidence,
44
+ higherIsBetter: obs.higherIsBetter,
45
+ provenance: obs.provenance,
46
+ };
47
+ if (obs.measuredAt) d.measuredAt = obs.measuredAt.toISOString();
48
+ return d;
49
+ }
50
+
51
+ export function observationFromDict(d: Record<string, unknown>): Observation {
52
+ return {
53
+ name: d.name as string,
54
+ health: d.health as Health,
55
+ value: d.value as number,
56
+ baseline: d.baseline as number,
57
+ confidence: d.confidence as Confidence,
58
+ higherIsBetter: (d.higherIsBetter as boolean) ?? true,
59
+ provenance: (d.provenance as string[]) ?? [],
60
+ measuredAt: d.measuredAt ? new Date(d.measuredAt as string) : undefined,
61
+ };
62
+ }
63
+
64
+ // -----------------------------------------------------------------------
65
+ // Correction
66
+ // -----------------------------------------------------------------------
67
+
68
+ export enum Op {
69
+ RESTORE = 'RESTORE',
70
+ SUPPRESS = 'SUPPRESS',
71
+ AMPLIFY = 'AMPLIFY',
72
+ NOOP = 'NOOP',
73
+ }
74
+
75
+ export interface Correction {
76
+ target: string;
77
+ op: Op;
78
+ alpha: number;
79
+ magnitude: number;
80
+ triggeredBy: string[];
81
+ provenance: string[];
82
+ }
83
+
84
+ export function correctionIsActive(c: Correction): boolean {
85
+ return c.op !== Op.NOOP && c.alpha > 0;
86
+ }
87
+
88
+ // -----------------------------------------------------------------------
89
+ // Expression
90
+ // -----------------------------------------------------------------------
91
+
92
+ export interface Expression {
93
+ observations: Observation[];
94
+ corrections: Correction[];
95
+ confidence: Confidence;
96
+ label: string;
97
+ step?: number;
98
+ }
99
+
100
+ export function createExpression(
101
+ observations: Observation[] = [],
102
+ corrections: Correction[] = [],
103
+ label = '',
104
+ step?: number,
105
+ ): Expression {
106
+ const confidence = observations.length > 0
107
+ ? minConfidence(...observations.map(o => o.confidence))
108
+ : Confidence.INDETERMINATE;
109
+ return { observations, corrections, confidence, label, step };
110
+ }
111
+
112
+ export function healthOf(expr: Expression, name: string): Health | undefined {
113
+ return expr.observations.find(o => o.name === name)?.health;
114
+ }
115
+
116
+ export function degraded(expr: Expression): Observation[] {
117
+ return expr.observations.filter(
118
+ o => o.health === Health.DEGRADED || o.health === Health.ABLATED || o.health === Health.RECOVERING,
119
+ );
120
+ }
121
+
122
+ export function expressionToString(expr: Expression): string {
123
+ if (expr.observations.length === 0) return '[∅]';
124
+ const parts = expr.observations.map(o => {
125
+ const atom = observationToAtom(o);
126
+ const corr = expr.corrections.find(c => c.target === o.name);
127
+ if (corr && correctionIsActive(corr)) {
128
+ return `[${atom} → ${corr.op}(α=${corr.alpha.toFixed(2)})]`;
129
+ }
130
+ return `[${atom}]`;
131
+ });
132
+ return parts.join(' ');
133
+ }
134
+
135
+ export function expressionToDict(expr: Expression): Record<string, unknown> {
136
+ return {
137
+ confidence: expr.confidence,
138
+ label: expr.label,
139
+ step: expr.step,
140
+ observations: expr.observations.map(observationToDict),
141
+ corrections: expr.corrections.map(c => ({
142
+ target: c.target, op: c.op, alpha: c.alpha,
143
+ magnitude: c.magnitude, triggeredBy: c.triggeredBy,
144
+ })),
145
+ };
146
+ }
147
+
148
+ // -----------------------------------------------------------------------
149
+ // Parser
150
+ // -----------------------------------------------------------------------
151
+
152
+ export class Parser {
153
+ baselines: Record<string, number>;
154
+ thresholds: Thresholds;
155
+ componentThresholds: Record<string, Thresholds>;
156
+
157
+ constructor(
158
+ baselines: Record<string, number>,
159
+ thresholds: Thresholds,
160
+ componentThresholds: Record<string, Thresholds> = {},
161
+ ) {
162
+ this.baselines = baselines;
163
+ this.thresholds = thresholds;
164
+ this.componentThresholds = componentThresholds;
165
+ }
166
+
167
+ thresholdsFor(name: string): Thresholds {
168
+ return this.componentThresholds[name] ?? this.thresholds;
169
+ }
170
+
171
+ parse(
172
+ values: Record<string, number>,
173
+ options: {
174
+ label?: string;
175
+ step?: number;
176
+ confidences?: Record<string, Confidence>;
177
+ } = {},
178
+ ): Expression {
179
+ const confidences = options.confidences ?? {};
180
+ const observations: Observation[] = [];
181
+
182
+ for (const [name, val] of Object.entries(values)) {
183
+ const baseline = this.baselines[name] ?? val;
184
+ const conf = confidences[name] ?? Confidence.MODERATE;
185
+ const t = this.thresholdsFor(name);
186
+ const h = classify(val, conf, t);
187
+ observations.push({
188
+ name,
189
+ health: h,
190
+ value: val,
191
+ baseline,
192
+ confidence: conf,
193
+ higherIsBetter: t.higherIsBetter !== false,
194
+ provenance: [],
195
+ measuredAt: undefined,
196
+ });
197
+ }
198
+
199
+ return createExpression(observations, [], options.label ?? '', options.step);
200
+ }
201
+ }