@warren-dean/code-kit 0.35.0 → 0.36.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.
@@ -0,0 +1,554 @@
1
+ // Promotion: a stream's code that belongs in core (docs/specs/31-streams-and-platform.md, PROM-1 to
2
+ // PROM-4). code-kit notices it from five signals: the same code in two streams' modules, a refused
3
+ // import of another stream's module, a copy into a module, new module code that repeats core, and a
4
+ // requirement another stream already meets. Each is a candidate the platform lead decides; nothing is
5
+ // moved by itself. A clone is found by tokens: names and literals masked, comments, strings and imports
6
+ // left out, so a copy with renamed variables still matches, and runs of at least `promote.tokens` tokens
7
+ // are found by hashing every window of that length.
8
+ import { execFileSync } from 'node:child_process';
9
+ import {
10
+ appendFileSync,
11
+ existsSync,
12
+ mkdirSync,
13
+ readFileSync,
14
+ readdirSync,
15
+ realpathSync,
16
+ } from 'node:fs';
17
+ import { dirname, isAbsolute, join, relative } from 'node:path';
18
+ import { CORE, hasStreams, ownerStreamOf, platformOf, streamsOf } from './streams.mjs';
19
+ import { projectWorktrees } from './rules.mjs';
20
+ import { EVENTS_DIR } from './events.mjs';
21
+ import { commandsOf, wordsOf } from './shell.mjs';
22
+
23
+ export const PROMOTIONS_FILE = '.claude/state/promotions.jsonl';
24
+ const SOURCE = /\.(ts|tsx|mts|cts|js|jsx|mjs|cjs|py)$/;
25
+ const PY_KEYWORDS = new Set(
26
+ 'and as assert async await break class continue def del elif else except False finally for from global if import in is lambda None nonlocal not or pass raise return True try while with yield match case self'.split(
27
+ ' ',
28
+ ),
29
+ );
30
+ const JS_KEYWORDS = new Set(
31
+ 'async await break case catch class const continue debugger default delete do else export extends false finally for function if import in instanceof let new null of return static super switch this throw true try typeof undefined var void while with yield interface type enum implements readonly private public protected as'.split(
32
+ ' ',
33
+ ),
34
+ );
35
+
36
+ const mainOf = (root) => projectWorktrees(root)[0] ?? root;
37
+
38
+ /**
39
+ * The code's tokens, each { t, line }: keywords and punctuation as written, every other name `I`, every
40
+ * number `N` and string `S`. Comments go, and so do import lines, which every file has.
41
+ */
42
+ export function tokensOf(text, file) {
43
+ const py = file.endsWith('.py');
44
+ const keywords = py ? PY_KEYWORDS : JS_KEYWORDS;
45
+ const out = [];
46
+ const lines = String(text).split('\n');
47
+ let inBlock = false;
48
+ let inTriple = null;
49
+ for (let n = 0; n < lines.length; n++) {
50
+ let line = lines[n];
51
+ if (inTriple) {
52
+ const end = line.indexOf(inTriple);
53
+ if (end < 0) continue;
54
+ line = line.slice(end + 3);
55
+ inTriple = null;
56
+ }
57
+ if (inBlock) {
58
+ const end = line.indexOf('*/');
59
+ if (end < 0) continue;
60
+ line = line.slice(end + 2);
61
+ inBlock = false;
62
+ }
63
+ const trimmed = line.trim();
64
+ if (py ? /^(?:import|from)\s/.test(trimmed) : /^(?:import\b|export\s.*\bfrom\s)/.test(trimmed))
65
+ continue;
66
+ const re = py
67
+ ? /("""|''')|#.*$|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b\d[\w.]*|[A-Za-z_]\w*|==|!=|<=|>=|->|\*\*|\/\/|[^\s\w]/g
68
+ : /\/\*|\/\/.*$|`(?:\\.|[^`\\])*`|"(?:\\.|[^"\\])*"|'(?:\\.|[^'\\])*'|\b\d[\w.]*|[A-Za-z_$][\w$]*|===|!==|==|!=|<=|>=|=>|&&|\|\||\?\?|\.\.\.|[^\s\w]/g;
69
+ for (const m of line.matchAll(re)) {
70
+ const w = m[0];
71
+ if (py && m[1]) {
72
+ const close = line.indexOf(m[1], m.index + 3);
73
+ if (close < 0) {
74
+ inTriple = m[1];
75
+ break;
76
+ }
77
+ out.push({ t: 'S', line: n + 1 });
78
+ continue;
79
+ }
80
+ if (w === '/*') {
81
+ const close = line.indexOf('*/', m.index + 2);
82
+ if (close < 0) {
83
+ inBlock = true;
84
+ break;
85
+ }
86
+ continue;
87
+ }
88
+ if (w.startsWith('//') || (py && w.startsWith('#'))) break;
89
+ if (/^["'`]/.test(w)) out.push({ t: 'S', line: n + 1 });
90
+ else if (/^\d/.test(w)) out.push({ t: 'N', line: n + 1 });
91
+ else if (/^[A-Za-z_$]/.test(w)) out.push({ t: keywords.has(w) ? w : 'I', line: n + 1 });
92
+ else out.push({ t: w, line: n + 1 });
93
+ }
94
+ }
95
+ return out;
96
+ }
97
+
98
+ // A 32-bit hash of a window of tokens.
99
+ function hashOf(tokens, from, size) {
100
+ let h = 2166136261;
101
+ for (let i = from; i < from + size; i++) {
102
+ const t = tokens[i].t;
103
+ for (let j = 0; j < t.length; j++) h = Math.imul(h ^ t.charCodeAt(j), 16777619);
104
+ h = Math.imul(h ^ 0x1f, 16777619);
105
+ }
106
+ return h >>> 0;
107
+ }
108
+
109
+ /** The name a line of code sits in: the nearest function, class or constant above it, or null. */
110
+ function symbolAt(lines, line) {
111
+ for (let i = line - 1; i >= 0; i--) {
112
+ const m =
113
+ lines[i]?.match(
114
+ /^\s*(?:export\s+)?(?:async\s+)?(?:function\*?|class|def)\s+([A-Za-z_$][\w$]*)/,
115
+ ) ?? lines[i]?.match(/^\s*(?:export\s+)?(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*=/);
116
+ if (m) return m[1];
117
+ }
118
+ return null;
119
+ }
120
+
121
+ /**
122
+ * PROM-1, signals 1 and 4: the clones between files of different owners (`owner(file)`: a stream's
123
+ * name, `core`, or null to leave a file out). `texts` is { file: text }. Returns [{ a, b }], each side
124
+ * { file, owner, from, to, symbol, tokens }, the longest run first.
125
+ */
126
+ export function findClones(texts, owner, { tokens: size = 60 } = {}) {
127
+ const parsed = new Map();
128
+ const seen = new Map();
129
+ for (const [file, text] of Object.entries(texts)) {
130
+ const who = owner(file);
131
+ if (!who || !SOURCE.test(file)) continue;
132
+ const tokens = tokensOf(text, file);
133
+ parsed.set(file, { tokens, lines: String(text).split('\n'), who });
134
+ for (let i = 0; i + size <= tokens.length; i++) {
135
+ const h = hashOf(tokens, i, size);
136
+ const at = seen.get(h);
137
+ if (at) at.push({ file, i });
138
+ else seen.set(h, [{ file, i }]);
139
+ }
140
+ }
141
+ // Runs: the windows two files share, in step, joined into the longest stretch.
142
+ const pairs = new Map();
143
+ for (const at of seen.values()) {
144
+ if (at.length < 2 || at.length > 40) continue;
145
+ for (let x = 0; x < at.length; x++)
146
+ for (let y = x + 1; y < at.length; y++) {
147
+ const [p, q] = at[x].file < at[y].file ? [at[x], at[y]] : [at[y], at[x]];
148
+ if (p.file === q.file || parsed.get(p.file).who === parsed.get(q.file).who) continue;
149
+ const key = `${p.file}\n${q.file}`;
150
+ if (!pairs.has(key)) pairs.set(key, []);
151
+ pairs.get(key).push([p.i, q.i]);
152
+ }
153
+ }
154
+ const clones = [];
155
+ for (const [key, hits] of pairs) {
156
+ const [fa, fb] = key.split('\n');
157
+ const A = parsed.get(fa);
158
+ const B = parsed.get(fb);
159
+ hits.sort((u, v) => u[0] - v[0] || u[1] - v[1]);
160
+ let run = null;
161
+ const flush = () => {
162
+ if (!run) return;
163
+ const side = (P, file, from, to) => ({
164
+ file,
165
+ owner: P.who,
166
+ from: P.tokens[from].line,
167
+ to: P.tokens[Math.min(to, P.tokens.length - 1)].line,
168
+ symbol: symbolAt(P.lines, P.tokens[from].line),
169
+ tokens: to - from + 1,
170
+ });
171
+ clones.push({
172
+ a: side(A, fa, run.a, run.a2 + size - 1),
173
+ b: side(B, fb, run.b, run.b2 + size - 1),
174
+ });
175
+ run = null;
176
+ };
177
+ for (const [i, j] of hits) {
178
+ if (run && i === run.a2 + 1 && j === run.b2 + 1) {
179
+ run.a2 = i;
180
+ run.b2 = j;
181
+ continue;
182
+ }
183
+ flush();
184
+ run = { a: i, a2: i, b: j, b2: j };
185
+ }
186
+ flush();
187
+ }
188
+ return clones.sort((u, v) => v.a.tokens - u.a.tokens);
189
+ }
190
+
191
+ // The record kept for each candidate, and each decision.
192
+ function readLog(root) {
193
+ try {
194
+ return readFileSync(join(mainOf(root), PROMOTIONS_FILE), 'utf8')
195
+ .split('\n')
196
+ .flatMap((l) => {
197
+ try {
198
+ return l ? [JSON.parse(l)] : [];
199
+ } catch {
200
+ return [];
201
+ }
202
+ });
203
+ } catch {
204
+ return [];
205
+ }
206
+ }
207
+
208
+ function append(root, record) {
209
+ const file = join(mainOf(root), PROMOTIONS_FILE);
210
+ mkdirSync(dirname(file), { recursive: true });
211
+ appendFileSync(file, `${JSON.stringify(record)}\n`);
212
+ }
213
+
214
+ /**
215
+ * Every candidate: [{ id, key, kind, what, where, streams, evidence, raised, state, decided }]. `state`
216
+ * is open, promoted (with the platform story that moves it) or rejected (with why).
217
+ */
218
+ export function promotions(root) {
219
+ const byId = new Map();
220
+ for (const r of readLog(root)) {
221
+ if (r.kind === 'raise') byId.set(r.id, { ...r, kind: r.signal, state: 'open', decided: null });
222
+ const had = byId.get(r.id);
223
+ if (!had) continue;
224
+ if (r.kind === 'evidence')
225
+ byId.set(r.id, {
226
+ ...had,
227
+ where: [...new Set([...had.where, ...r.where])],
228
+ streams: [...new Set([...had.streams, ...r.streams])],
229
+ evidence: [...had.evidence, r.evidence],
230
+ ...(had.state === 'rejected' && r.reopens ? { state: 'open', decided: null } : {}),
231
+ });
232
+ if (r.kind === 'decide')
233
+ byId.set(r.id, {
234
+ ...had,
235
+ state: r.how,
236
+ decided: { at: r.at, by: r.by ?? null, story: r.story ?? null, reason: r.reason ?? null },
237
+ });
238
+ }
239
+ return [...byId.values()];
240
+ }
241
+
242
+ /**
243
+ * PROM-1, PROM-3: raises a candidate, or adds to the one with the same key. A rejected one opens again
244
+ * only when its evidence changes: a stream or a file it didn't have. Returns the candidate, or null when
245
+ * nothing changed.
246
+ */
247
+ export function raise(root, { key, signal, what, where, streams, evidence }, now = Date.now()) {
248
+ const had = promotions(root).find((p) => p.key === key);
249
+ const at = new Date(now).toISOString();
250
+ if (!had) {
251
+ const id = `P-${readLog(root).filter((r) => r.kind === 'raise').length + 1}`;
252
+ append(root, {
253
+ kind: 'raise',
254
+ id,
255
+ at,
256
+ key,
257
+ signal,
258
+ what,
259
+ where,
260
+ streams,
261
+ evidence: [evidence],
262
+ });
263
+ return promotions(root).find((p) => p.id === id);
264
+ }
265
+ const newWhere = where.filter((w) => !had.where.includes(w));
266
+ const newStreams = streams.filter((s) => !had.streams.includes(s));
267
+ if (!newWhere.length && !newStreams.length) return null;
268
+ if (had.state === 'promoted') return null;
269
+ append(root, {
270
+ kind: 'evidence',
271
+ id: had.id,
272
+ at,
273
+ where: newWhere,
274
+ streams: newStreams,
275
+ evidence,
276
+ reopens: had.state === 'rejected',
277
+ });
278
+ return promotions(root).find((p) => p.id === had.id);
279
+ }
280
+
281
+ /** PROM-3: the platform lead's decision: promoted, with the platform story; or rejected, with why. */
282
+ export function decidePromotion(
283
+ root,
284
+ id,
285
+ { how, story = null, reason = null, by = null },
286
+ now = Date.now(),
287
+ ) {
288
+ const p = promotions(root).find((x) => x.id === id);
289
+ if (!p) return { ok: false, why: `There's no candidate ${id}. code-kit promote lists them.` };
290
+ if (p.state !== 'open') return { ok: false, why: `${id} was ${p.state} already.` };
291
+ if (how === 'promoted' && !/^ST-\d+$/.test(story ?? ''))
292
+ return { ok: false, why: 'Name the platform story that moves it into core: --story ST-n.' };
293
+ if (how === 'rejected' && !reason?.trim())
294
+ return {
295
+ ok: false,
296
+ why: "Say why it stays in its module, with --reason: it isn't proposed again until that changes.",
297
+ };
298
+ append(root, { kind: 'decide', id, at: new Date(now).toISOString(), how, story, reason, by });
299
+ return { ok: true, promotion: promotions(root).find((x) => x.id === id) };
300
+ }
301
+
302
+ const sideWords = (s) => `${s.file}:${s.from}-${s.to}${s.symbol ? ` (${s.symbol})` : ''}`;
303
+
304
+ /** PROM-1: a clone between two owners as a candidate's fields. */
305
+ export function cloneCandidate(clone) {
306
+ const sides = [clone.a, clone.b].sort((x, y) => x.file.localeCompare(y.file));
307
+ const core = sides.find((s) => s.owner === CORE);
308
+ const streams = [...new Set(sides.map((s) => s.owner).filter((o) => o !== CORE))];
309
+ return {
310
+ key: `clone:${sides.map((s) => `${s.file}#${s.symbol ?? s.from}`).join('|')}`,
311
+ signal: core ? 'core-clone' : 'clone',
312
+ what: core
313
+ ? `${sideWords(sides.find((s) => s !== core))} repeats core's ${sideWords(core)}`
314
+ : `${sides.map(sideWords).join(' and ')}: the same code in ${streams.join(' and ')}`,
315
+ where: sides.map((s) => s.file),
316
+ streams,
317
+ evidence: `${clone.a.tokens} tokens alike`,
318
+ };
319
+ }
320
+
321
+ /** The project's source files, as git tracks them, or as `ref` has them. */
322
+ function trackedSources(root, ref = null) {
323
+ try {
324
+ const args = ref ? ['ls-tree', '-r', '--name-only', ref] : ['ls-files'];
325
+ return execFileSync('git', ['-C', root, ...args], { encoding: 'utf8', maxBuffer: 1 << 28 })
326
+ .split('\n')
327
+ .filter((f) => SOURCE.test(f));
328
+ } catch {
329
+ return [];
330
+ }
331
+ }
332
+
333
+ /** The text of each of `files` as `ref` has it, read in one batch: { file: text }. */
334
+ function textsAt(root, ref, files) {
335
+ if (!files.length) return {};
336
+ let raw;
337
+ try {
338
+ raw = execFileSync('git', ['-C', root, 'cat-file', '--batch'], {
339
+ input: `${files.map((f) => `${ref}:${f}`).join('\n')}\n`,
340
+ maxBuffer: 1 << 30,
341
+ });
342
+ } catch {
343
+ return {};
344
+ }
345
+ const texts = {};
346
+ let at = 0;
347
+ for (const f of files) {
348
+ const nl = raw.indexOf(10, at);
349
+ if (nl < 0) break;
350
+ const header = raw.subarray(at, nl).toString('utf8');
351
+ at = nl + 1;
352
+ if (header.endsWith(' missing')) continue;
353
+ const size = Number(header.split(' ')[2]);
354
+ if (!Number.isFinite(size)) break;
355
+ texts[f] = raw.subarray(at, at + size).toString('utf8');
356
+ at += size + 1;
357
+ }
358
+ return texts;
359
+ }
360
+
361
+ /** A path a command named, relative to the project, with a worktree's folder taken off; null outside it. */
362
+ export function projectPath(root, path) {
363
+ const main = mainOf(root);
364
+ let real = main;
365
+ try {
366
+ real = realpathSync(main);
367
+ } catch {
368
+ // a checkout that's gone: its own path only
369
+ }
370
+ const abs = isAbsolute(path) ? path : join(main, path);
371
+ // macOS shows the temporary folder both as /var and as /private/var.
372
+ const forms = [abs, abs.replace(/^\/private(?=\/)/, ''), `/private${abs}`];
373
+ for (const base of [main, real])
374
+ for (const form of forms) {
375
+ const rel = relative(base, form).split('\\').join('/');
376
+ if (!rel.startsWith('..') && !isAbsolute(rel))
377
+ return rel.replace(/^\.claude\/worktrees\/[^/]+\//, '');
378
+ }
379
+ return null;
380
+ }
381
+
382
+ /**
383
+ * PROM-1, signal 3: copies a lane made into a stream's module, from another stream's module or from
384
+ * outside the project, read from the event log: [{ from, to, stream, outside }].
385
+ */
386
+ export function copiesIn(root, config) {
387
+ const dir = join(mainOf(root), EVENTS_DIR);
388
+ let files = [];
389
+ try {
390
+ files = readdirSync(dir).filter((f) => f.endsWith('.jsonl'));
391
+ } catch {
392
+ return [];
393
+ }
394
+ const found = [];
395
+ for (const f of files) {
396
+ let lines = [];
397
+ try {
398
+ lines = readFileSync(join(dir, f), 'utf8').split('\n');
399
+ } catch {
400
+ continue;
401
+ }
402
+ for (const l of lines) {
403
+ let e;
404
+ try {
405
+ e = l ? JSON.parse(l) : null;
406
+ } catch {
407
+ continue;
408
+ }
409
+ if (!e || e.phase !== 'end' || e.result?.ok === false || typeof e.target !== 'string')
410
+ continue;
411
+ for (const { text } of commandsOf(e.target)) {
412
+ const words = wordsOf(text);
413
+ if (!['cp', 'rsync', 'ditto'].includes(words[0])) continue;
414
+ const paths = words.slice(1).filter((w) => !w.startsWith('-'));
415
+ if (paths.length < 2 || paths.some((p) => p.includes('$'))) continue;
416
+ const to = projectPath(root, paths.at(-1));
417
+ const toOwner = to ? ownerStreamOf(config, to) : null;
418
+ if (!toOwner || toOwner === CORE) continue;
419
+ for (const src of paths.slice(0, -1)) {
420
+ const from = projectPath(root, src);
421
+ const fromOwner = from ? ownerStreamOf(config, from) : null;
422
+ if (from && fromOwner === toOwner) continue;
423
+ if (from && !fromOwner) continue;
424
+ found.push({
425
+ from: from ?? src,
426
+ to,
427
+ stream: toOwner,
428
+ fromStream: fromOwner,
429
+ outside: !from,
430
+ });
431
+ }
432
+ }
433
+ }
434
+ }
435
+ return found;
436
+ }
437
+
438
+ /**
439
+ * PROM-1: looks for candidates across the project, or, with `files`, in those files against the rest,
440
+ * and raises each one found. Returns { raised: [candidate], clones: [clone] }: what's new or changed, and
441
+ * every clone seen.
442
+ */
443
+ export function scanForPromotions(
444
+ root,
445
+ config,
446
+ { files = null, ref = null, tokens = null, record = true, now = Date.now() } = {},
447
+ ) {
448
+ if (!hasStreams(config)) return { raised: [], clones: [] };
449
+ const size = tokens ?? config.harness?.promote?.tokens ?? 60;
450
+ const owner = (f) => ownerStreamOf(config, f);
451
+ const sources = trackedSources(root, ref).filter((f) => owner(f));
452
+ const texts = ref ? textsAt(root, ref, sources) : {};
453
+ if (!ref)
454
+ for (const f of sources) {
455
+ if (!existsSync(join(root, f))) continue;
456
+ try {
457
+ texts[f] = readFileSync(join(root, f), 'utf8');
458
+ } catch {
459
+ // unreadable: left out
460
+ }
461
+ }
462
+ let clones = findClones(texts, owner, { tokens: size });
463
+ if (files) clones = clones.filter((c) => files.includes(c.a.file) || files.includes(c.b.file));
464
+ const raised = [];
465
+ for (const c of record ? clones : []) {
466
+ const r = raise(root, cloneCandidate(c), now);
467
+ if (r) raised.push(r);
468
+ }
469
+ if (!files && record)
470
+ for (const copy of copiesIn(root, config)) {
471
+ const r = raise(
472
+ root,
473
+ {
474
+ key: `copy:${copy.from}>${copy.to}`,
475
+ signal: 'copy',
476
+ what: `${copy.from} was copied into ${copy.to} (${copy.stream})${copy.outside ? ', from outside the project' : `, from ${copy.fromStream}`}`,
477
+ where: [copy.to, ...(copy.outside ? [] : [copy.from])],
478
+ streams: [
479
+ copy.stream,
480
+ ...(copy.fromStream && copy.fromStream !== CORE ? [copy.fromStream] : []),
481
+ ],
482
+ evidence: 'copied by a lane',
483
+ },
484
+ now,
485
+ );
486
+ if (r) raised.push(r);
487
+ }
488
+ return { raised, clones };
489
+ }
490
+
491
+ /** PROM-1, signal 2: a lane was refused an import of another stream's module: what it wanted. */
492
+ export function recordRefusedImport(root, config, { file, target, spec }, now = Date.now()) {
493
+ try {
494
+ const from = ownerStreamOf(config, file);
495
+ const to = ownerStreamOf(config, target);
496
+ if (!from || !to || from === to || to === CORE) return null;
497
+ return raise(
498
+ root,
499
+ {
500
+ key: `import:${target}`,
501
+ signal: 'import',
502
+ what: `${from} wants ${spec} (${target}), ${to}'s`,
503
+ where: [target, file],
504
+ streams: [to, ...(from === CORE ? [] : [from])],
505
+ evidence: `${file} was refused importing it`,
506
+ },
507
+ now,
508
+ );
509
+ } catch {
510
+ return null;
511
+ }
512
+ }
513
+
514
+ const words = (t) =>
515
+ new Set(
516
+ String(t)
517
+ .toLowerCase()
518
+ .match(/[a-z][a-z0-9]+/g)
519
+ ?.filter((w) => w.length > 2 && !['the', 'and', 'for', 'with', 'from', 'its'].includes(w)) ??
520
+ [],
521
+ );
522
+
523
+ /**
524
+ * PROM-1, signal 5: the requirements of other streams' specs that a story's requirements repeat:
525
+ * [{ requirement, matches, stream, file, score }], by how alike their titles are.
526
+ */
527
+ export function repeatedRequirements(config, requirements, story, { at = 0.6 } = {}) {
528
+ const mine = streamsOf(config).find((s) => s.lanes.includes(story.lane));
529
+ const specOf = (file) =>
530
+ streamsOf(config).find((s) =>
531
+ s.specs.some((g) => file === g || file.startsWith(g.replace(/\*.*$/, ''))),
532
+ )?.name ?? null;
533
+ const own = requirements.filter((r) => story.requirements.includes(r.id));
534
+ const out = [];
535
+ for (const r of own) {
536
+ const a = words(r.title);
537
+ if (a.size < 2) continue;
538
+ for (const o of requirements) {
539
+ const stream = specOf(o.file);
540
+ if (!stream || stream === mine?.name || o.id === r.id) continue;
541
+ const b = words(o.title);
542
+ const shared = [...a].filter((w) => b.has(w)).length;
543
+ const score = shared / new Set([...a, ...b]).size;
544
+ if (score >= at)
545
+ out.push({ requirement: r.id, matches: o.id, title: o.title, stream, file: o.file, score });
546
+ }
547
+ }
548
+ return out.sort((x, y) => y.score - x.score);
549
+ }
550
+
551
+ /** PROM-2: whose a candidate is to decide: the platform's lead, or, without one, a stream it touches. */
552
+ export function decidedFor(config, candidate) {
553
+ return platformOf(config)?.name ?? candidate.streams[0] ?? null;
554
+ }