@autotelic/joggle 0.0.0-stage → 0.1.2
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/JOGGLE.md +634 -0
- package/LICENSE +21 -0
- package/README.md +88 -2
- package/bin/joggle.js +6 -0
- package/dist/answer-store.js +305 -0
- package/dist/architecture.js +190 -0
- package/dist/ask.js +184 -0
- package/dist/astro.js +75 -0
- package/dist/atoms.js +76 -0
- package/dist/bundles.js +156 -0
- package/dist/calibration.js +60 -0
- package/dist/candidates.js +561 -0
- package/dist/canonical.js +24 -0
- package/dist/cascade.js +98 -0
- package/dist/check.js +854 -0
- package/dist/cluster.js +69 -0
- package/dist/config.js +195 -0
- package/dist/content-mappers.js +83 -0
- package/dist/decision.js +203 -0
- package/dist/fingerprint.js +61 -0
- package/dist/git.js +127 -0
- package/dist/gitignore.js +65 -0
- package/dist/glob.js +51 -0
- package/dist/imports.js +153 -0
- package/dist/jsonc.js +95 -0
- package/dist/main.js +630 -0
- package/dist/manifest.js +42 -0
- package/dist/meta.js +170 -0
- package/dist/moves.js +47 -0
- package/dist/operation.js +133 -0
- package/dist/parsecache.js +264 -0
- package/dist/plans.js +425 -0
- package/dist/plugin.js +71 -0
- package/dist/plugins.js +136 -0
- package/dist/policy.js +676 -0
- package/dist/presets/composition.js +32 -0
- package/dist/report.js +474 -0
- package/dist/reporting.js +132 -0
- package/dist/result.js +28 -0
- package/dist/roles.js +303 -0
- package/dist/rule.js +194 -0
- package/dist/rules/append-only-honoured.js +190 -0
- package/dist/rules/bundle-conformance.js +245 -0
- package/dist/rules/call-pattern.js +209 -0
- package/dist/rules/cluster-verdict.js +700 -0
- package/dist/rules/compose-types.js +250 -0
- package/dist/rules/data-error-as-outage.js +482 -0
- package/dist/rules/declared-staleness.js +242 -0
- package/dist/rules/dependency-fit.js +297 -0
- package/dist/rules/deviation-has-a-shape.js +225 -0
- package/dist/rules/doc-matches-code.js +191 -0
- package/dist/rules/duplicate-call-run.js +240 -0
- package/dist/rules/duplicate-implementation.js +89 -0
- package/dist/rules/duplicate-meaning.js +130 -0
- package/dist/rules/fact-or-derivation.js +202 -0
- package/dist/rules/field-type-drift.js +373 -0
- package/dist/rules/generic-carries-a-caller.js +198 -0
- package/dist/rules/hoist-to-domain.js +288 -0
- package/dist/rules/import-architecture.js +393 -0
- package/dist/rules/index.js +105 -0
- package/dist/rules/inferred-over-recorded.js +214 -0
- package/dist/rules/intent-drift.js +286 -0
- package/dist/rules/invariant-has-a-reconciler.js +190 -0
- package/dist/rules/language-drift.js +234 -0
- package/dist/rules/meaning-switched-by-flag.js +189 -0
- package/dist/rules/module-direction.js +231 -0
- package/dist/rules/name-as-address.js +216 -0
- package/dist/rules/name-the-primitive.js +203 -0
- package/dist/rules/naming-drift.js +218 -0
- package/dist/rules/nullability-drift.js +220 -0
- package/dist/rules/object-shape.js +280 -0
- package/dist/rules/one-concept-one-type.js +243 -0
- package/dist/rules/page-needs-composition.js +227 -0
- package/dist/rules/reimplemented-primitive.js +283 -0
- package/dist/rules/reversal.js +264 -0
- package/dist/rules/rule-judgment.js +252 -0
- package/dist/rules/schema-excludes-domain-value.js +190 -0
- package/dist/rules/shallow-module.js +204 -0
- package/dist/rules/single-path.js +237 -0
- package/dist/rules/structural-collapse.js +198 -0
- package/dist/rules/temporal-coupling.js +205 -0
- package/dist/rules/types-over-logic.js +198 -0
- package/dist/rules/unaccounted-drop.js +190 -0
- package/dist/rules/unbounded-default-read.js +227 -0
- package/dist/run-cache.js +132 -0
- package/dist/schema.js +285 -0
- package/dist/similarity.js +119 -0
- package/dist/source.js +30 -0
- package/dist/sql.js +34 -0
- package/dist/stages.js +39 -0
- package/dist/state.js +65 -0
- package/dist/testing.js +131 -0
- package/dist/tsconfig-scope.js +32 -0
- package/dist/tsgo.js +127 -0
- package/dist/typefacts.js +455 -0
- package/dist/typetrace.js +283 -0
- package/dist/verdict.js +65 -0
- package/dist/vocabulary.js +365 -0
- package/dist/workspace.js +1963 -0
- package/extensions/joggle.ts +454 -0
- package/package.json +85 -3
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
import { Effect, FileSystem, Path, Result, Schema, SchemaParser } from "effect";
|
|
2
|
+
import { Service as Tsgo } from "./tsgo.js";
|
|
3
|
+
/* -------------------------------------------------------------------------- */
|
|
4
|
+
/* Vocabulary */
|
|
5
|
+
/* -------------------------------------------------------------------------- */
|
|
6
|
+
/**
|
|
7
|
+
* One resolved type, as `tsgo --generateTrace` describes it.
|
|
8
|
+
*
|
|
9
|
+
* The trace is a hack that works: it needs no fork and no patch, and the checker
|
|
10
|
+
* writes it while it is already checking the program. What it carries is the
|
|
11
|
+
* resolved type in the checker's own printed form, the flags the checker gave it,
|
|
12
|
+
* the declaration it was attributed to, and the type arguments and union members
|
|
13
|
+
* it was built from.
|
|
14
|
+
*
|
|
15
|
+
* What it does NOT carry is an object type's members. This was assumed otherwise
|
|
16
|
+
* and measured false (2026-09, tsgo 7.0.0-dev.20260707.2): a NAMED interface or
|
|
17
|
+
* type alias has no `display` at all -- `PersonSummary` is just a descriptor with
|
|
18
|
+
* `flags: ["Object"]` and a symbol name -- and the trace records no property
|
|
19
|
+
* list, so `PersonSummary.treesPlanted`'s resolved type cannot be read from it.
|
|
20
|
+
* Only an ANONYMOUS object type gets a printed `display` --
|
|
21
|
+
* `{ readonly id: String; readonly email: String }` -- which is why an object
|
|
22
|
+
* literal's inferred type is readable and a declaration's fields are not.
|
|
23
|
+
*
|
|
24
|
+
* Type ALIASES are worse: `type ProjectRole = (typeof PROJECT_ROLES)[number]`
|
|
25
|
+
* produced no entry attributed to `ProjectRole` at all. So a field-level
|
|
26
|
+
* resolved type is simply not in the trace, and `field-type-drift` cannot be
|
|
27
|
+
* made trace-based. What would answer it is a checker host that calls
|
|
28
|
+
* `getTypeAtLocation` on the property -- `docs/type-resolution.md`.
|
|
29
|
+
*/
|
|
30
|
+
export const TypeFact = Schema.Struct({
|
|
31
|
+
/**
|
|
32
|
+
* The checker's printed form of the resolved type. Empty when the checker had
|
|
33
|
+
* nothing to print, which is itself a fact about the declaration.
|
|
34
|
+
*/
|
|
35
|
+
display: Schema.String,
|
|
36
|
+
/** The symbol the checker resolved, when it named one. */
|
|
37
|
+
symbol: Schema.String,
|
|
38
|
+
/** The checker's flags: `Object`, `Union`, `Any`, `Conditional`, ... */
|
|
39
|
+
flags: Schema.Array(Schema.String),
|
|
40
|
+
/** Resolved type arguments, printed, in declaration order. */
|
|
41
|
+
arguments: Schema.Array(Schema.String),
|
|
42
|
+
/** Resolved union members, printed, in the checker's order. */
|
|
43
|
+
members: Schema.Array(Schema.String),
|
|
44
|
+
/**
|
|
45
|
+
* Where the CHECKER says the type was declared, root-relative.
|
|
46
|
+
*
|
|
47
|
+
* This is not always the declaration joggle is looking at: an alias resolves
|
|
48
|
+
* to the type it aliases, and the trace attributes the type to the aliased
|
|
49
|
+
* declaration. That difference is the useful part -- it is the join from a
|
|
50
|
+
* name to its meaning that text cannot make.
|
|
51
|
+
*/
|
|
52
|
+
origin: Schema.Struct({ file: Schema.String, line: Schema.Number }),
|
|
53
|
+
});
|
|
54
|
+
/** No types were resolved, for a caller that ran without a trace. */
|
|
55
|
+
export const emptyTypeIndex = {
|
|
56
|
+
at: () => undefined,
|
|
57
|
+
sites: 0,
|
|
58
|
+
};
|
|
59
|
+
const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
60
|
+
const stringsOf = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "string") : [];
|
|
61
|
+
const numbersOf = (value) => Array.isArray(value) ? value.filter((item) => typeof item === "number") : [];
|
|
62
|
+
const declarationOf = (value) => {
|
|
63
|
+
if (!isRecord(value))
|
|
64
|
+
return undefined;
|
|
65
|
+
const file = value["path"];
|
|
66
|
+
const start = value["start"];
|
|
67
|
+
if (typeof file !== "string" || !isRecord(start))
|
|
68
|
+
return undefined;
|
|
69
|
+
const line = start["line"];
|
|
70
|
+
return typeof line === "number" ? { file, line } : undefined;
|
|
71
|
+
};
|
|
72
|
+
const rawOf = (value) => {
|
|
73
|
+
if (!isRecord(value))
|
|
74
|
+
return undefined;
|
|
75
|
+
const id = value["id"];
|
|
76
|
+
if (typeof id !== "number")
|
|
77
|
+
return undefined;
|
|
78
|
+
const display = value["display"];
|
|
79
|
+
const intrinsic = value["intrinsicName"];
|
|
80
|
+
const symbol = value["symbolName"];
|
|
81
|
+
return {
|
|
82
|
+
id,
|
|
83
|
+
display: typeof display === "string" ? display : typeof intrinsic === "string" ? intrinsic : "",
|
|
84
|
+
symbol: typeof symbol === "string" ? symbol : "",
|
|
85
|
+
flags: stringsOf(value["flags"]),
|
|
86
|
+
arguments: [...numbersOf(value["typeArguments"]), ...numbersOf(value["aliasTypeArguments"])],
|
|
87
|
+
unionTypes: numbersOf(value["unionTypes"]),
|
|
88
|
+
declaration: declarationOf(value["firstDeclaration"]),
|
|
89
|
+
};
|
|
90
|
+
};
|
|
91
|
+
/**
|
|
92
|
+
* A function from a trace path to a root-relative path, or undefined when the
|
|
93
|
+
* file sits outside the root.
|
|
94
|
+
*
|
|
95
|
+
* Curried rather than taking the root and the file as two adjacent strings: a
|
|
96
|
+
* swapped call would compile and produce a path of the wrong shape, which is
|
|
97
|
+
* exactly the class of bug the trace reader exists to avoid.
|
|
98
|
+
*/
|
|
99
|
+
const relativeTo = (root) => (file) => {
|
|
100
|
+
const normalizedRoot = root.split("\\").join("/").replace(/\/+$/, "");
|
|
101
|
+
const normalized = file.split("\\").join("/");
|
|
102
|
+
if (!normalized.toLowerCase().startsWith(normalizedRoot.toLowerCase() + "/"))
|
|
103
|
+
return undefined;
|
|
104
|
+
return normalized.slice(normalizedRoot.length + 1);
|
|
105
|
+
};
|
|
106
|
+
/** The most informative fact for one declaration: the longest printed type wins. */
|
|
107
|
+
const better = ({ left, right, }) => (right.display.length > left.display.length ? right : left);
|
|
108
|
+
/**
|
|
109
|
+
* Turn the parsed `types_N.json` documents into entries, one per declaration.
|
|
110
|
+
*
|
|
111
|
+
* Each document is one checker, and type ids are only meaningful inside the
|
|
112
|
+
* document that defines them, so the arguments and union members are resolved
|
|
113
|
+
* against the same document and the results are merged by declaration site. The
|
|
114
|
+
* checkers agree about a declaration; when they do not, the longest printed type
|
|
115
|
+
* is kept, because a short print is a partial view and a long one is not.
|
|
116
|
+
*/
|
|
117
|
+
export const parseTrace = (root, documents) => {
|
|
118
|
+
const bySite = new Map();
|
|
119
|
+
const byName = new Map();
|
|
120
|
+
const relative = relativeTo(root);
|
|
121
|
+
const insert = (site, key, entry) => {
|
|
122
|
+
const existing = site.get(key);
|
|
123
|
+
site.set(key, existing === undefined ? entry : { ...entry, fact: better({ left: existing.fact, right: entry.fact }) });
|
|
124
|
+
};
|
|
125
|
+
for (const document of documents) {
|
|
126
|
+
const byId = new Map();
|
|
127
|
+
for (const value of document) {
|
|
128
|
+
const raw = rawOf(value);
|
|
129
|
+
if (raw !== undefined)
|
|
130
|
+
byId.set(raw.id, raw);
|
|
131
|
+
}
|
|
132
|
+
const printed = (id) => {
|
|
133
|
+
const target = byId.get(id);
|
|
134
|
+
if (target === undefined)
|
|
135
|
+
return "";
|
|
136
|
+
return target.display !== "" ? target.display : target.symbol;
|
|
137
|
+
};
|
|
138
|
+
for (const raw of byId.values()) {
|
|
139
|
+
if (raw.declaration === undefined)
|
|
140
|
+
continue;
|
|
141
|
+
const file = relative(raw.declaration.file);
|
|
142
|
+
if (file === undefined)
|
|
143
|
+
continue;
|
|
144
|
+
const fact = {
|
|
145
|
+
display: raw.display,
|
|
146
|
+
symbol: raw.symbol,
|
|
147
|
+
flags: raw.flags,
|
|
148
|
+
arguments: raw.arguments.slice(0, 8).map(printed),
|
|
149
|
+
members: raw.unionTypes.slice(0, 16).map(printed),
|
|
150
|
+
origin: { file, line: raw.declaration.line },
|
|
151
|
+
};
|
|
152
|
+
const entry = { file, line: raw.declaration.line, name: raw.symbol, fact };
|
|
153
|
+
insert(bySite, file.toLowerCase() + "\u0000" + raw.declaration.line, entry);
|
|
154
|
+
if (raw.symbol !== "")
|
|
155
|
+
insert(byName, file.toLowerCase() + "\u0000" + raw.symbol, entry);
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
return [...bySite.values()];
|
|
159
|
+
};
|
|
160
|
+
/** Build the lookup from parsed entries. */
|
|
161
|
+
export const indexOf = (entries) => {
|
|
162
|
+
const bySite = new Map();
|
|
163
|
+
const byName = new Map();
|
|
164
|
+
for (const entry of entries) {
|
|
165
|
+
const siteKey = entry.file.toLowerCase() + "\u0000" + entry.line;
|
|
166
|
+
const site = bySite.get(siteKey);
|
|
167
|
+
bySite.set(siteKey, site === undefined ? entry.fact : better({ left: site, right: entry.fact }));
|
|
168
|
+
if (entry.name === "")
|
|
169
|
+
continue;
|
|
170
|
+
const nameKey = entry.file.toLowerCase() + "\u0000" + entry.name;
|
|
171
|
+
const named = byName.get(nameKey);
|
|
172
|
+
byName.set(nameKey, named === undefined ? entry.fact : better({ left: named, right: entry.fact }));
|
|
173
|
+
}
|
|
174
|
+
return {
|
|
175
|
+
sites: bySite.size,
|
|
176
|
+
at: (file, line, name) => {
|
|
177
|
+
const key = file.toLowerCase() + "\u0000";
|
|
178
|
+
return bySite.get(key + line) ?? (name === undefined ? undefined : byName.get(key + name));
|
|
179
|
+
},
|
|
180
|
+
};
|
|
181
|
+
};
|
|
182
|
+
/* -------------------------------------------------------------------------- */
|
|
183
|
+
/* Reading and caching */
|
|
184
|
+
/* -------------------------------------------------------------------------- */
|
|
185
|
+
const TRACE_VERSION = "1";
|
|
186
|
+
const CachedEntry = Schema.Struct({
|
|
187
|
+
file: Schema.String,
|
|
188
|
+
line: Schema.Number,
|
|
189
|
+
name: Schema.String,
|
|
190
|
+
fact: TypeFact,
|
|
191
|
+
});
|
|
192
|
+
const CachedIndex = Schema.Struct({
|
|
193
|
+
version: Schema.String,
|
|
194
|
+
tool: Schema.String,
|
|
195
|
+
manifest: Schema.String,
|
|
196
|
+
entries: Schema.Array(CachedEntry),
|
|
197
|
+
});
|
|
198
|
+
const decodeCache = SchemaParser.decodeUnknownResult(Schema.fromJsonString(CachedIndex));
|
|
199
|
+
/**
|
|
200
|
+
* Parse JSON at the boundary, recording the failure instead of throwing it past
|
|
201
|
+
* the typed channel. A trace file that will not parse is an issue, and an issue
|
|
202
|
+
* is a fact the run reports rather than a defect that escapes it.
|
|
203
|
+
*/
|
|
204
|
+
const parseJson = (text) => Effect.try(() => JSON.parse(text)).pipe(Effect.orElseSucceed(() => undefined));
|
|
205
|
+
/** The paths the legend names, one per checker. */
|
|
206
|
+
const legendPaths = (parsed) => {
|
|
207
|
+
if (!Array.isArray(parsed))
|
|
208
|
+
return [];
|
|
209
|
+
return parsed.flatMap((entry) => {
|
|
210
|
+
if (!isRecord(entry))
|
|
211
|
+
return [];
|
|
212
|
+
const typesPath = entry["typesPath"];
|
|
213
|
+
return typeof typesPath === "string" ? [typesPath] : [];
|
|
214
|
+
});
|
|
215
|
+
};
|
|
216
|
+
/**
|
|
217
|
+
* Resolve the declarations to their types, from the cache or from a fresh trace.
|
|
218
|
+
*
|
|
219
|
+
* The cache key is the same manifest the run already computed plus the tool
|
|
220
|
+
* fingerprint, because a trace depends on the whole program: the compiler
|
|
221
|
+
* version, the tsconfig, and every file it checked. The manifest is content, not
|
|
222
|
+
* mtimes, so a trace is reused exactly when the code it describes is unchanged.
|
|
223
|
+
*/
|
|
224
|
+
export const loadTypeFacts = (input) => Effect.gen(function* () {
|
|
225
|
+
const fs = yield* FileSystem.FileSystem;
|
|
226
|
+
const path = yield* Path.Path;
|
|
227
|
+
const issues = [];
|
|
228
|
+
const store = path.join(input.cacheDir, "types.json");
|
|
229
|
+
const exists = yield* Effect.orElseSucceed(fs.exists(store), () => false);
|
|
230
|
+
if (exists) {
|
|
231
|
+
const body = yield* Effect.orElseSucceed(fs.readFileString(store), () => "");
|
|
232
|
+
const decoded = decodeCache(body);
|
|
233
|
+
if (Result.isSuccess(decoded)) {
|
|
234
|
+
const cached = decoded.success;
|
|
235
|
+
if (cached.version === TRACE_VERSION &&
|
|
236
|
+
cached.tool === input.tool &&
|
|
237
|
+
cached.manifest === input.manifest) {
|
|
238
|
+
return {
|
|
239
|
+
index: indexOf(cached.entries),
|
|
240
|
+
issues,
|
|
241
|
+
loadedFrom: "cache",
|
|
242
|
+
};
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
else if (body.trim() !== "") {
|
|
246
|
+
issues.push("the type cache did not match the expected shape and was ignored");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
const documents = [];
|
|
250
|
+
yield* Effect.scoped(Effect.gen(function* () {
|
|
251
|
+
const dir = yield* fs.makeTempDirectoryScoped({ directory: input.cacheDir });
|
|
252
|
+
const tsgo = yield* Tsgo;
|
|
253
|
+
yield* tsgo.generateTrace(input.root, dir);
|
|
254
|
+
const legend = yield* fs.readFileString(path.join(dir, "legend.json"));
|
|
255
|
+
const paths = legendPaths(yield* parseJson(legend));
|
|
256
|
+
if (paths.length === 0)
|
|
257
|
+
issues.push("the trace legend named no type files");
|
|
258
|
+
for (const typesPath of paths) {
|
|
259
|
+
const body = yield* fs.readFileString(typesPath);
|
|
260
|
+
const parsed = yield* parseJson(body);
|
|
261
|
+
if (Array.isArray(parsed))
|
|
262
|
+
documents.push(parsed);
|
|
263
|
+
else
|
|
264
|
+
issues.push("a trace type file was not an array: " + typesPath);
|
|
265
|
+
}
|
|
266
|
+
})).pipe(Effect.catch((error) => {
|
|
267
|
+
issues.push("the trace could not be generated: " + String(error));
|
|
268
|
+
return Effect.void;
|
|
269
|
+
}));
|
|
270
|
+
const entries = parseTrace(input.root, documents);
|
|
271
|
+
const index = indexOf(entries);
|
|
272
|
+
if (entries.length > 0) {
|
|
273
|
+
const body = JSON.stringify({
|
|
274
|
+
version: TRACE_VERSION,
|
|
275
|
+
tool: input.tool,
|
|
276
|
+
manifest: input.manifest,
|
|
277
|
+
entries,
|
|
278
|
+
});
|
|
279
|
+
yield* Effect.orElseSucceed(fs.makeDirectory(input.cacheDir, { recursive: true }), () => undefined);
|
|
280
|
+
yield* Effect.orElseSucceed(fs.writeFileString(store, body), () => undefined);
|
|
281
|
+
}
|
|
282
|
+
return { index, issues, loadedFrom: "trace" };
|
|
283
|
+
});
|
package/dist/verdict.js
ADDED
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
import { policy } from "./policy.js";
|
|
2
|
+
const clamp01 = (value) => Math.min(1, Math.max(0, value));
|
|
3
|
+
/**
|
|
4
|
+
* Reduce one answer to the probability its rule is violated.
|
|
5
|
+
*
|
|
6
|
+
* @param answer - the decision's answer, or undefined when the run had none.
|
|
7
|
+
* @param violating - the Choice labels that mean "violated"; empty for a Noul,
|
|
8
|
+
* whose "yes" is the violation.
|
|
9
|
+
* @returns the verdict, or undefined when the answer carries no label and no
|
|
10
|
+
* probability -- an unreadable answer, which every caller reports unverified.
|
|
11
|
+
*/
|
|
12
|
+
export const verdictOf = (answer, violating) => {
|
|
13
|
+
if (answer === undefined)
|
|
14
|
+
return undefined;
|
|
15
|
+
// A Noul answers with a probability, and the violation is "yes".
|
|
16
|
+
if ("probability" in answer) {
|
|
17
|
+
// A Noul asked more than once carries the AGREEMENT across its asks, and that
|
|
18
|
+
// is its margin: one yes/no has no distribution, so without the repeats the
|
|
19
|
+
// probability floor was its only gate (docs/typesafe.md, self-consistency).
|
|
20
|
+
// The agreement maps onto the margin's range by its distance from a coin
|
|
21
|
+
// flip: every ask agreed is 1, an even split is 0. Below the agreement floor
|
|
22
|
+
// the asks disagreed, and a disagreement among a handful of asks is no margin.
|
|
23
|
+
const agreement = answer.consistency === undefined ? undefined : clamp01(answer.consistency);
|
|
24
|
+
const margin = agreement === undefined
|
|
25
|
+
? 1
|
|
26
|
+
: agreement < policy.decision.gates.minAgreement
|
|
27
|
+
? 0
|
|
28
|
+
: 2 * agreement - 1;
|
|
29
|
+
return {
|
|
30
|
+
label: undefined,
|
|
31
|
+
probability: clamp01(answer.probability),
|
|
32
|
+
margin,
|
|
33
|
+
confidence: undefined,
|
|
34
|
+
};
|
|
35
|
+
}
|
|
36
|
+
// A Choice picks a label and distributes the rest.
|
|
37
|
+
if ("label" in answer) {
|
|
38
|
+
const label = answer.label;
|
|
39
|
+
const probabilities = "probabilities" in answer ? answer.probabilities : {};
|
|
40
|
+
const violatingSet = new Set(violating);
|
|
41
|
+
// No distribution (a bare pick): the label is either violating or not.
|
|
42
|
+
if (Object.keys(probabilities).length === 0) {
|
|
43
|
+
return {
|
|
44
|
+
label,
|
|
45
|
+
probability: violatingSet.has(label) ? 1 : 0,
|
|
46
|
+
margin: 1,
|
|
47
|
+
confidence: "confidence" in answer ? answer.confidence : undefined,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
let mass = 0;
|
|
51
|
+
for (const [name, value] of Object.entries(probabilities)) {
|
|
52
|
+
if (violatingSet.has(name))
|
|
53
|
+
mass += value;
|
|
54
|
+
}
|
|
55
|
+
const ranked = Object.values(probabilities).sort((left, right) => right - left);
|
|
56
|
+
const margin = ranked.length < 2 ? 1 : (ranked[0] ?? 0) - (ranked[1] ?? 0);
|
|
57
|
+
return {
|
|
58
|
+
label,
|
|
59
|
+
probability: clamp01(mass),
|
|
60
|
+
margin,
|
|
61
|
+
confidence: "confidence" in answer ? answer.confidence : undefined,
|
|
62
|
+
};
|
|
63
|
+
}
|
|
64
|
+
return undefined;
|
|
65
|
+
};
|