@omercnet/paseo-pr-radar 3.4.0-next.541.1 → 3.4.0-next.545.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,3 +1,11 @@
1
+ import {
2
+ ESCAPED_CHARS,
3
+ fallbackNoteProblem,
4
+ type LabelFallbackRule,
5
+ LabelFallbackRuleSchema,
6
+ UNSAFE_CHARS,
7
+ } from "./settings";
8
+
1
9
  // Labels a routing script asks for. The script sees PR text on stdin, so its output is untrusted:
2
10
  // every label is validated all or nothing, and a bad set blocks the launch instead of dropping
3
11
  // labels (a dropped trust-downgrade label would launch an agent without it).
@@ -7,15 +15,11 @@ export const MAX_SCRIPT_LABELS = 16;
7
15
  export const MAX_LABEL_KEY_LEN = 128;
8
16
  export const MAX_LABEL_VALUE_LEN = 128;
9
17
  export const ROUTE_NAMESPACE = "pr-radar.route.";
18
+ export const MAX_FALLBACK_DAYS = 7;
19
+ const MAX_FALLBACK_MS = MAX_FALLBACK_DAYS * 24 * 60 * 60 * 1_000;
10
20
  const MAX_SHOWN_KEY_LEN = 64;
11
21
 
12
22
  const LABEL_KEY = /^[A-Za-z0-9][A-Za-z0-9._/-]*$/;
13
- // Unicode general categories Cc (C0, DEL and C1 controls), Cf (format characters: bidi controls
14
- // such as U+202A-U+202E and U+2066-U+2069 used by Trojan Source, CVE-2021-42574, zero-width
15
- // U+200B-U+200F, U+2060-U+2064, U+FEFF, tag characters), Cs (lone surrogates), Zl and Zp.
16
- // Default_Ignorable_Code_Point adds invisible fillers (U+3164, U+115F, U+FFA0) and variation selectors.
17
- const UNSAFE_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
18
- const ESCAPED_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
19
23
  // A script that returns more raw keys than this is rejected before any per-key work.
20
24
  const MAX_RAW_LABELS = MAX_SCRIPT_LABELS * 4;
21
25
  const MAX_LISTED_REJECTIONS = 5;
@@ -33,11 +37,19 @@ export interface CheckedLabels {
33
37
 
34
38
  export interface LabelPolicy {
35
39
  routingLabelPrefixes: string;
40
+ routingLabelFallbacks: readonly LabelFallbackRule[];
36
41
  }
37
42
 
38
43
  export type RoutedLabelsDecision =
39
44
  | { status: "ok"; labels: Record<string, string> }
40
- | { status: "blocked"; rejected: RejectedLabel[]; message: string };
45
+ | { status: "fallback"; rejected: RejectedLabel[]; rule: LabelFallbackRule; warning: string }
46
+ | {
47
+ status: "blocked";
48
+ rejected: RejectedLabel[];
49
+ message: string;
50
+ // Set when an active fallback rule was refused because it would drop a downgrade label.
51
+ fallbackRefusal?: string;
52
+ };
41
53
 
42
54
  export class RoutedLabelsBlockedError extends Error {
43
55
  readonly rejected: RejectedLabel[];
@@ -57,8 +69,32 @@ export function parseLabelPrefixes(raw: string): string[] {
57
69
  return prefixes.every((prefix) => prefixProblem(prefix) === null) ? prefixes : [];
58
70
  }
59
71
 
72
+ // The only separators between prefix entries: ASCII space, tab, line breaks and the comma. Not
73
+ // `\s`: in JavaScript that also matches U+FEFF, U+00A0, U+2028, U+3000 and every other Unicode
74
+ // space, so `a<U+FEFF>de.kind` would split into the valid prefixes `a` and `de.kind`, neither of
75
+ // which protects `ade.kind`. Any other character stays inside its entry and makes it malformed.
76
+ const PREFIX_SEPARATORS = /[ \t\n\r,]+/;
77
+
60
78
  function splitPrefixes(raw: string): string[] {
61
- return raw.split(/[\s,]+/).filter((prefix) => prefix.length > 0);
79
+ return raw.split(PREFIX_SEPARATORS).filter((prefix) => prefix.length > 0);
80
+ }
81
+
82
+ // One normalizer for both sides of the downgrade guard's comparison: a configured prefix and a key
83
+ // a script returns. NFKC folds compatibility forms (full-width letters, U+2024 for a dot), and every
84
+ // control, format and default-ignorable character goes, so an invisible character in a prefix
85
+ // cannot make it differ from the key it looks like (UTS #39 skeleton step 2 removes the same code
86
+ // points). Case and surrounding space are the caller's business. Validation does not use it: a
87
+ // prefix that holds such a character is a visible error there, never silently repaired.
88
+ function stripInvisible(text: string): string {
89
+ return text.normalize("NFKC").replace(ESCAPED_CHARS, "");
90
+ }
91
+
92
+ function firstPrefixProblem(raw: string): { prefix: string; problem: string } | null {
93
+ for (const prefix of splitPrefixes(raw)) {
94
+ const problem = prefixProblem(prefix);
95
+ if (problem) return { prefix, problem };
96
+ }
97
+ return null;
62
98
  }
63
99
 
64
100
  function prefixProblem(prefix: string): string | null {
@@ -78,13 +114,10 @@ function prefixProblem(prefix: string): string | null {
78
114
  // Why the whole setting is void, naming the first bad entry; null when every entry is usable.
79
115
  // The settings screen shows it, so a typo does not silently turn every prefix off.
80
116
  export function labelPrefixesProblem(raw: string): string | null {
81
- for (const prefix of splitPrefixes(raw)) {
82
- const problem = prefixProblem(prefix);
83
- if (problem) {
84
- return `Ignoring every prefix: ${quoteLabelKey(prefix)} ${problem}. Fix or remove it.`;
85
- }
86
- }
87
- return null;
117
+ const bad = firstPrefixProblem(raw);
118
+ return bad
119
+ ? `Ignoring every prefix: ${quotePrefix(bad.prefix)} ${bad.problem}. Fix or remove it.`
120
+ : null;
88
121
  }
89
122
 
90
123
  // Keys shown in a notice come from the script, so control and invisible characters are written out.
@@ -102,6 +135,16 @@ function quoteLabelKey(key: string, maxShown = MAX_SHOWN_KEY_LEN): string {
102
135
  return `"${displayLabelKey(key, maxShown).replaceAll('"', '\\"')}"`;
103
136
  }
104
137
 
138
+ // A prefix in a notice about a malformed prefix: every character outside ASCII is written out too,
139
+ // because a look-alike letter (Cyrillic a) prints exactly like the Latin one it imitates.
140
+ function quotePrefix(prefix: string): string {
141
+ const shown = displayLabelKey(prefix).replace(
142
+ /[^\x20-\x7e]/gu,
143
+ (char) => `\\u{${(char.codePointAt(0) ?? 0).toString(16).toUpperCase()}}`,
144
+ );
145
+ return `"${shown.replaceAll('"', '\\"')}"`;
146
+ }
147
+
105
148
  // How a label is shown in the modal: quoted, so a value cannot pass for a second label. Keys and
106
149
  // values are quoted the same way, so a backslash is written once as two, never doubled again.
107
150
  // Only accepted labels reach here: they hold no control or invisible characters, so escaping can at
@@ -238,6 +281,106 @@ export function checkRoutedLabels(raw: unknown, prefixes: readonly string[]): Ch
238
281
  return { labels: rejected.length > 0 ? {} : labels, rejected };
239
282
  }
240
283
 
284
+ export type FallbackRuleStatus = "active" | "expired" | "too-far" | "not-a-date";
285
+
286
+ // The date and time fields name a moment that exists. `Date.parse` in V8 rolls 2026-11-31 over to
287
+ // 2026-12-01 and other engines read it as invalid, so devices could disagree about when a rule ends.
288
+ // A timestamp that fails this is never active.
289
+ export function isRealTimestamp(value: string): boolean {
290
+ const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2}))?/.exec(value);
291
+ if (!match) return false;
292
+ const [year, month, day, hour, minute, second] = match.slice(1).map((part) => Number(part ?? 0));
293
+ const daysInMonth = new Date(Date.UTC(year ?? 0, month ?? 0, 0)).getUTCDate();
294
+ return (
295
+ (month ?? 0) >= 1 &&
296
+ (month ?? 0) <= 12 &&
297
+ (day ?? 0) >= 1 &&
298
+ (day ?? 0) <= daysInMonth &&
299
+ (hour ?? 99) <= 23 &&
300
+ (minute ?? 99) <= 59 &&
301
+ (second ?? 0) <= 59
302
+ );
303
+ }
304
+
305
+ export function fallbackRuleStatus(rule: LabelFallbackRule, now: number): FallbackRuleStatus {
306
+ if (!isRealTimestamp(rule.until)) return "not-a-date";
307
+ const until = Date.parse(rule.until);
308
+ if (!Number.isFinite(until) || until <= now) return "expired";
309
+ if (until - now > MAX_FALLBACK_MS) return "too-far";
310
+ return "active";
311
+ }
312
+
313
+ // The next instant a rule changes what it does: it expires, or it comes within the seven day cap
314
+ // and starts to apply. Null when no rule has a boundary ahead.
315
+ export function nextFallbackBoundary(
316
+ rules: readonly LabelFallbackRule[],
317
+ now: number,
318
+ ): number | null {
319
+ let next: number | null = null;
320
+ for (const rule of rules) {
321
+ const until = Date.parse(rule.until);
322
+ if (!isRealTimestamp(rule.until) || !Number.isFinite(until)) continue;
323
+ for (const boundary of [until, until - MAX_FALLBACK_MS]) {
324
+ if (boundary > now && (next === null || boundary < next)) next = boundary;
325
+ }
326
+ }
327
+ return next;
328
+ }
329
+
330
+ // A timer reads at most about 24.8 days; the cap keeps a far boundary from firing at once.
331
+ const MAX_TIMER_MS = 2_147_483_647;
332
+ // Fires a little after the boundary so the clock reads past it when the callback runs.
333
+ const BOUNDARY_SLACK_MS = 50;
334
+
335
+ // Calls `onChange` when a rule's status may have changed, so a screen that decided at render time
336
+ // does not keep showing an expired rule as active. The caller re-runs it with the new time, so a
337
+ // timer that fired early, or a boundary beyond the timer limit, just schedules the next one.
338
+ // Returns a function that cancels the timer.
339
+ export function watchFallbackBoundary(
340
+ rules: readonly LabelFallbackRule[],
341
+ now: number,
342
+ onChange: () => void,
343
+ ): () => void {
344
+ const next = nextFallbackBoundary(rules, now);
345
+ if (next === null) return () => undefined;
346
+ const timer = setTimeout(onChange, Math.min(next - now + BOUNDARY_SLACK_MS, MAX_TIMER_MS));
347
+ return () => clearTimeout(timer);
348
+ }
349
+
350
+ export function describeFallbackStatus(rule: LabelFallbackRule, now: number): string {
351
+ const status = fallbackRuleStatus(rule, now);
352
+ if (status === "not-a-date") return `ignored: ${rule.until} is not a real date`;
353
+ if (status === "expired") return `expired ${rule.until}`;
354
+ if (status === "too-far") {
355
+ return `ignored: ends more than ${MAX_FALLBACK_DAYS} days from now (${rule.until})`;
356
+ }
357
+ return `active until ${rule.until}`;
358
+ }
359
+
360
+ export function activeFallbackRule(
361
+ rules: readonly LabelFallbackRule[],
362
+ repository: string,
363
+ now: number,
364
+ ): LabelFallbackRule | undefined {
365
+ const repo = repository.toLowerCase();
366
+ return rules.find(
367
+ (rule) =>
368
+ (rule.repository === "*" || rule.repository.toLowerCase() === repo) &&
369
+ fallbackRuleStatus(rule, now) === "active",
370
+ );
371
+ }
372
+
373
+ // What a rule does: the repository without regard to case and the instant it ends, the same way
374
+ // `activeFallbackRule` and `fallbackRuleStatus` read it. Two rules with the same target are the
375
+ // same rule, whatever their spelling (`Acme/Api` and `acme/api`, `18:00Z` and `19:00+01:00`).
376
+ // A timestamp that is not a real date stays as written, so it matches only itself: `Date.parse` in V8
377
+ // rolls 2026-11-31 over to 2026-12-01, which would make a rule that never applies a duplicate of
378
+ // one that does.
379
+ export function fallbackRuleTarget(rule: Pick<LabelFallbackRule, "repository" | "until">): string {
380
+ const until = isRealTimestamp(rule.until) ? Date.parse(rule.until) : Number.NaN;
381
+ return `${rule.repository.toLowerCase()} ${Number.isFinite(until) ? until : `raw:${rule.until}`}`;
382
+ }
383
+
241
384
  export function describeRejection({ key, reason }: RejectedLabel): string {
242
385
  return `${quoteLabelKey(key)}: ${reason}`;
243
386
  }
@@ -253,17 +396,113 @@ export function describeRejected(rejected: readonly RejectedLabel[]): string {
253
396
  return `${listed.join("; ")}${rest}`;
254
397
  }
255
398
 
399
+ export function describeFallbackRule(rule: LabelFallbackRule): string {
400
+ const note = rule.note ? ` (${rule.note})` : "";
401
+ return `${rule.repository} until ${rule.until}${note}`;
402
+ }
403
+
404
+ // A downgrade label is one an operator trusted to keep its own name: an Allowed label prefix admits
405
+ // it. A fallback rule skips every script label, so it must never apply to a set that holds one.
406
+ // The guard is wider than the real check, so it fails closed. It reads the raw prefix entries (one
407
+ // malformed entry voids the parsed list, which would otherwise let the fallback drop the label),
408
+ // ignores case, and normalizes prefixes and keys the same way before comparing, so an invisible
409
+ // character in a prefix cannot hide the key it imitates. A prefix that is still malformed (a
410
+ // look-alike letter, say) cannot be matched to any key, so the fallback is refused outright.
411
+ // Blocking more is harmless.
412
+ function downgradeRefusal(labels: unknown, rawPrefixes: string): string | null {
413
+ const prefixes = splitPrefixes(rawPrefixes)
414
+ .map((prefix) => stripInvisible(prefix).toLowerCase())
415
+ .filter((prefix) => prefix.length > 0);
416
+ if (prefixes.length > 0 && labels !== undefined && labels !== null) {
417
+ if (typeof labels !== "object" || Array.isArray(labels)) {
418
+ return "The labels are not an object of keys and values, so PR Radar cannot tell whether they hold a label an Allowed label prefix trusts, and a fallback rule cannot drop it.";
419
+ }
420
+ const held = Object.keys(labels).find((key) => {
421
+ const guarded = stripInvisible(key).trim().toLowerCase();
422
+ return prefixes.some((prefix) => admits(prefix, guarded));
423
+ });
424
+ if (held !== undefined) {
425
+ return `The label ${quoteLabelKey(held)} is one an Allowed label prefix trusts, and a fallback rule cannot drop it.`;
426
+ }
427
+ }
428
+ const bad = firstPrefixProblem(rawPrefixes);
429
+ if (bad) {
430
+ return `The Allowed label prefix ${quotePrefix(bad.prefix)} ${bad.problem}, so PR Radar cannot tell which labels a prefix trusts, and a fallback rule cannot be used until it is fixed.`;
431
+ }
432
+ return null;
433
+ }
434
+
256
435
  export function decideRoutedLabels(input: {
257
436
  labels: unknown;
437
+ repository: string;
258
438
  policy: LabelPolicy;
439
+ now: number;
259
440
  }): RoutedLabelsDecision {
260
- const { labels, policy } = input;
441
+ const { labels, repository, policy, now } = input;
261
442
  const checked = checkRoutedLabels(labels, parseLabelPrefixes(policy.routingLabelPrefixes));
262
443
  if (checked.rejected.length === 0) return { status: "ok", labels: checked.labels };
263
444
 
445
+ const listed = describeRejected(checked.rejected);
446
+ const rule = activeFallbackRule(policy.routingLabelFallbacks, repository, now);
447
+ const refusal = rule ? downgradeRefusal(labels, policy.routingLabelPrefixes) : null;
448
+ if (rule && refusal) {
449
+ return {
450
+ status: "blocked",
451
+ rejected: checked.rejected,
452
+ fallbackRefusal: `${refusal} Fallback rule ${describeFallbackRule(rule)} does not apply. Fix the script.`,
453
+ message: `${BLOCKED_HEADLINE} (${listed}). ${refusal} Fallback rule ${describeFallbackRule(rule)} does not apply. Fix the script.`,
454
+ };
455
+ }
456
+ if (rule) {
457
+ return {
458
+ status: "fallback",
459
+ rejected: checked.rejected,
460
+ rule,
461
+ warning: `Routing script labels rejected (${listed}). Fallback rule ${describeFallbackRule(rule)} lets this launch go ahead without any script labels.`,
462
+ };
463
+ }
264
464
  return {
265
465
  status: "blocked",
266
466
  rejected: checked.rejected,
267
- message: `${BLOCKED_HEADLINE} (${describeRejected(checked.rejected)}). Fix the script.`,
467
+ message: `${BLOCKED_HEADLINE} (${listed}). Fix the script, or add a short-term fallback rule for ${repository} in the PR Radar settings.`,
268
468
  };
269
469
  }
470
+
471
+ export type ParsedFallbackRule = { rule: LabelFallbackRule } | { error: string };
472
+
473
+ // "owner/name 2026-11-25T18:00Z optional note": the add-rule field in settings.
474
+ export function parseFallbackRuleInput(input: string, now: number): ParsedFallbackRule {
475
+ // Fields are separated and edge-trimmed by ASCII space or tab only, never `\s` or `.trim()`:
476
+ // U+FEFF, U+00A0 or U+2028 would otherwise split a single word or disappear from the ends before
477
+ // validation sees them.
478
+ const [repository, until, ...noteWords] = input.replace(/^[ \t]+|[ \t]+$/g, "").split(/[ \t]+/);
479
+ if (!repository || !until) {
480
+ return {
481
+ error:
482
+ "Enter: owner/name (or *), an ISO-8601 time such as 2026-11-25T18:00Z, then an optional note.",
483
+ };
484
+ }
485
+ const note = noteWords.join(" ");
486
+ // The note is shown in the launch warning, so a bidi override in it could reorder that text.
487
+ const noteIssue = fallbackNoteProblem(note);
488
+ if (noteIssue) {
489
+ return { error: noteIssue };
490
+ }
491
+ const parsed = LabelFallbackRuleSchema.safeParse({
492
+ repository,
493
+ until,
494
+ ...(note ? { note } : {}),
495
+ });
496
+ if (!parsed.success) {
497
+ return {
498
+ error: "Use owner/name (or *) and an ISO-8601 time with a zone, e.g. 2026-11-25T18:00Z.",
499
+ };
500
+ }
501
+ const status = fallbackRuleStatus(parsed.data, now);
502
+ if (status === "not-a-date") return { error: "That date does not exist." };
503
+ if (status === "expired") return { error: "That time has already passed." };
504
+ if (status === "too-far") {
505
+ return { error: `Fallback rules must end within ${MAX_FALLBACK_DAYS} days.` };
506
+ }
507
+ return { rule: parsed.data };
508
+ }
@@ -7,6 +7,50 @@ export type CwdMode = (typeof CWD_MODES)[number];
7
7
  export const AUTO_LAUNCH_MODES = ["prompt", "existing_only", "existing_or_clone"] as const;
8
8
  export type AutoLaunchMode = (typeof AUTO_LAUNCH_MODES)[number];
9
9
 
10
+ const ISO_TIMESTAMP = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
11
+
12
+ // Unicode general categories Cc (C0, DEL and C1 controls), Cf (format characters: bidi controls
13
+ // such as U+202A-U+202E and U+2066-U+2069 used by Trojan Source, CVE-2021-42574, zero-width
14
+ // U+200B-U+200F, U+2060-U+2064, U+FEFF, tag characters), Cs (lone surrogates), Zl and Zp.
15
+ // Default_Ignorable_Code_Point adds invisible fillers (U+3164, U+115F, U+FFA0) and variation selectors.
16
+ export const UNSAFE_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/u;
17
+ export const ESCAPED_CHARS = /[\p{Cc}\p{Cf}\p{Cs}\p{Zl}\p{Zp}\p{Default_Ignorable_Code_Point}]/gu;
18
+
19
+ export const FALLBACK_NOTE_UNSAFE_ERROR = "The note may not hold control or invisible characters.";
20
+
21
+ // Shared validator for fallback rule notes (add-rule input and persisted settings). Runs on the
22
+ // raw text before any trim, so leading/trailing BOM, bidi or control characters cannot slip past.
23
+ export function fallbackNoteProblem(rawNote: string): string | null {
24
+ return UNSAFE_CHARS.test(rawNote) ? FALLBACK_NOTE_UNSAFE_ERROR : null;
25
+ }
26
+
27
+ // A short-term rule that lets a launch go ahead without the routing script's labels when the
28
+ // script returns invalid ones. `repository` is `owner/name` or `*`; `until` is an ISO-8601
29
+ // timestamp with an offset. Only rules that expire within the next week are honored (see
30
+ // `routed-labels.ts`).
31
+ export const LabelFallbackRuleSchema = z
32
+ .object({
33
+ repository: z
34
+ .string()
35
+ .max(256)
36
+ .regex(/^(\*|[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)$/, "Use owner/name or *."),
37
+ until: z
38
+ .string()
39
+ .regex(ISO_TIMESTAMP, "Use an ISO-8601 timestamp with a time zone, e.g. 2026-11-25T18:00Z.")
40
+ .refine((value) => Number.isFinite(Date.parse(value)), "Not a real date."),
41
+ note: z
42
+ .string()
43
+ .refine((value) => fallbackNoteProblem(value) === null, {
44
+ message: FALLBACK_NOTE_UNSAFE_ERROR,
45
+ })
46
+ .trim()
47
+ .max(256)
48
+ .optional(),
49
+ })
50
+ .strict();
51
+
52
+ export type LabelFallbackRule = z.infer<typeof LabelFallbackRuleSchema>;
53
+
10
54
  export const DEFAULT_PR_RADAR_SETTINGS = {
11
55
  sourceCodeDir: "~/src",
12
56
  defaultCwdMode: "CWD-WORKTREE",
@@ -19,8 +63,18 @@ export const DEFAULT_PR_RADAR_SETTINGS = {
19
63
  defaultContextMode: "",
20
64
  routingScriptPath: "",
21
65
  routingLabelPrefixes: "",
66
+ routingLabelFallbacks: [] as LabelFallbackRule[],
22
67
  } as const;
23
68
 
69
+ // Drops any stored fallback rule that fails `LabelFallbackRuleSchema` (unsafe note, edge
70
+ // whitespace in repository, non-string or over-long note, unknown keys, etc.) so one bad rule
71
+ // fails closed (consistent with the pre-v3 strip) without invalidating the rest of the saved
72
+ // settings. Non-arrays and lists over 32 entries still fail schema validation.
73
+ function dropInvalidFallbackRules(value: unknown): unknown {
74
+ if (!Array.isArray(value) || value.length > 32) return value;
75
+ return value.filter((entry) => LabelFallbackRuleSchema.safeParse(entry).success);
76
+ }
77
+
24
78
  export const PrRadarSettingsSchema = z
25
79
  .object({
26
80
  /** Base directory for local repositories and auto-clones. */
@@ -58,32 +112,40 @@ export const PrRadarSettingsSchema = z
58
112
  .default(DEFAULT_PR_RADAR_SETTINGS.routingScriptPath),
59
113
  // Label key prefixes the routing script may use as-is, separated by commas or spaces (for
60
114
  // example `ade.`). Every other script label is stored as `pr-radar.route.<key>`. Never admits
61
- // `pr-radar`, `pr-radar.*`, `paseo` or `paseo.*`.
115
+ // `pr-radar`, `pr-radar.*`, `paseo` or `paseo.*`. Kept raw (no `.trim()`): JS `.trim()` strips
116
+ // Unicode whitespace and U+FEFF at the edges, which would hide a malformed entry like
117
+ // `"team/,\uFEFF"` from the fallback guard; ASCII separators are handled by `splitPrefixes`.
62
118
  routingLabelPrefixes: z
63
119
  .string()
64
- .trim()
65
120
  .max(1_024)
66
121
  .default(DEFAULT_PR_RADAR_SETTINGS.routingLabelPrefixes),
122
+ // Temporary rules that let a launch proceed without script labels when they are invalid.
123
+ // Any stored rule that fails `LabelFallbackRuleSchema` is dropped on load (fail closed).
124
+ routingLabelFallbacks: z
125
+ .preprocess(dropInvalidFallbackRules, z.array(LabelFallbackRuleSchema).max(32))
126
+ .default(() => [...DEFAULT_PR_RADAR_SETTINGS.routingLabelFallbacks]),
67
127
  })
68
128
  .strict();
69
129
 
70
130
  export type PrRadarSettings = z.infer<typeof PrRadarSettingsSchema>;
71
131
 
72
- // Settings saved before label fallback rules moved out of the label feature may still hold
73
- // `routingLabelFallbacks`. The schema is strict, so the stored document must lose it before it is
74
- // parsed; a retired rule then enables nothing.
75
- const RETIRED_SETTINGS_KEYS = ["routingLabelFallbacks"] as const;
76
-
77
- export function migratePrRadarSettings(values: unknown): unknown {
78
- if (typeof values !== "object" || values === null || Array.isArray(values)) return values;
79
- const retired: readonly string[] = RETIRED_SETTINGS_KEYS;
80
- return Object.fromEntries(Object.entries(values).filter(([key]) => !retired.includes(key)));
132
+ // Version 2 (the label feature without fallback rules) dropped `routingLabelFallbacks`, and its
133
+ // migration deleted that key from older documents. Rules are live again in version 3, but a
134
+ // document saved before it (version 1, or 2 skipped by an upgrade) may hold rules that version 2
135
+ // had already retired, so they are stripped here and fail closed: nobody gets a rule back that a
136
+ // release in between removed. A version 3 document is not migrated and keeps its rules.
137
+ export function migratePrRadarSettings(values: unknown, fromVersion: number): unknown {
138
+ if (fromVersion >= 3 || typeof values !== "object" || values === null || Array.isArray(values)) {
139
+ return values;
140
+ }
141
+ const { routingLabelFallbacks: _retired, ...kept } = values as Record<string, unknown>;
142
+ return kept;
81
143
  }
82
144
 
83
145
  export const prRadarSettings = defineSettings({
84
146
  id: "pr-radar",
85
147
  scope: "host",
86
- version: 2,
148
+ version: 3,
87
149
  schema: PrRadarSettingsSchema,
88
150
  migrate: migratePrRadarSettings,
89
151
  });