@radicaltools/cli 0.5.0 → 0.6.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.
package/dist/index.js CHANGED
@@ -2,11 +2,11 @@
2
2
  import {
3
3
  define_RADICAL_BUILD_default,
4
4
  init_define_RADICAL_BUILD
5
- } from "./chunk-J5ULJOOY.js";
5
+ } from "./chunk-SBQRTX3Y.js";
6
6
 
7
7
  // src/index.ts
8
8
  init_define_RADICAL_BUILD();
9
- import { spawn as spawn8 } from "child_process";
9
+ import { spawn as spawn10 } from "child_process";
10
10
  import { createInterface } from "readline/promises";
11
11
 
12
12
  // src/cli.ts
@@ -2677,10 +2677,10 @@ function filterRuns(filters) {
2677
2677
  function applyFilters(source, filters, ctx) {
2678
2678
  let nodes = source;
2679
2679
  const counts = [];
2680
- for (const run2 of filterRuns(filters)) {
2681
- const on2 = run2.map((i) => filters[i]).filter((f) => !f.off);
2680
+ for (const run3 of filterRuns(filters)) {
2681
+ const on2 = run3.map((i) => filters[i]).filter((f) => !f.off);
2682
2682
  if (on2.length) nodes = nodes.filter((n) => on2.some((f) => matchesFilter(f, n, ctx)));
2683
- for (const i of run2) counts[i] = nodes.length;
2683
+ for (const i of run3) counts[i] = nodes.length;
2684
2684
  }
2685
2685
  return { nodes, counts };
2686
2686
  }
@@ -4042,7 +4042,7 @@ var MdFolderSession = class {
4042
4042
  /** Lists the files after an open from the cache: those that differ are
4043
4043
  * read into the baseline's place for them by the next read. */
4044
4044
  verifyLater() {
4045
- const run2 = this.tail.then(async () => {
4045
+ const run3 = this.tail.then(async () => {
4046
4046
  this.running++;
4047
4047
  try {
4048
4048
  const stamps = await this.storage.list();
@@ -4056,9 +4056,9 @@ var MdFolderSession = class {
4056
4056
  this.running--;
4057
4057
  }
4058
4058
  });
4059
- this.tail = run2.catch(() => {
4059
+ this.tail = run3.catch(() => {
4060
4060
  });
4061
- return run2;
4061
+ return run3;
4062
4062
  }
4063
4063
  /** Brings the cache up to the baseline: changes.json, or model.json
4064
4064
  * again when it is missing or more files differ from it than it can
@@ -4067,7 +4067,7 @@ var MdFolderSession = class {
4067
4067
  keepCache() {
4068
4068
  if (this.options.writeCache === false || !this.storage.writeCache) return;
4069
4069
  if (!isValidMdFolderManifest(this.baseline.get(MD_MANIFEST_FILE)?.content)) return;
4070
- const run2 = this.tail.then(async () => {
4070
+ const run3 = this.tail.then(async () => {
4071
4071
  this.running++;
4072
4072
  try {
4073
4073
  const files = {};
@@ -4085,8 +4085,8 @@ var MdFolderSession = class {
4085
4085
  this.running--;
4086
4086
  }
4087
4087
  });
4088
- this.tail = run2;
4089
- this.cacheWrite = run2;
4088
+ this.tail = run3;
4089
+ this.cacheWrite = run3;
4090
4090
  }
4091
4091
  /** Resolves once the cache is written as far as the session has gone. */
4092
4092
  cacheWritten() {
@@ -4151,14 +4151,14 @@ var MdFolderSession = class {
4151
4151
  }
4152
4152
  exclusive(fn) {
4153
4153
  this.running++;
4154
- const run2 = this.tail.then(fn, fn);
4155
- this.tail = run2.catch(() => {
4154
+ const run3 = this.tail.then(fn, fn);
4155
+ this.tail = run3.catch(() => {
4156
4156
  });
4157
4157
  const done = () => {
4158
4158
  this.running--;
4159
4159
  };
4160
- run2.then(done, done);
4161
- return run2;
4160
+ run3.then(done, done);
4161
+ return run3;
4162
4162
  }
4163
4163
  };
4164
4164
  function sameStamps(a2, b) {
@@ -4186,7 +4186,7 @@ init_define_RADICAL_BUILD();
4186
4186
 
4187
4187
  // ../../packages/common/src/check/sensors.ts
4188
4188
  init_define_RADICAL_BUILD();
4189
- var SENSOR_NAMES = ["command", "json", "playwright"];
4189
+ var SENSOR_NAMES = ["command", "github-actions", "json", "lighthouse", "machine", "playwright"];
4190
4190
  function commandWords(line) {
4191
4191
  const words = [];
4192
4192
  let word = "";
@@ -4584,6 +4584,7 @@ function parseMeasurementStore(text3) {
4584
4584
  var TEST_LINE = /^test\((.+)\)(?:\s+passed)?$/;
4585
4585
  var REVIEW_LINE = /^review\((.+)\)\s+passed$/i;
4586
4586
  var REVIEW_METRIC = "review";
4587
+ var SCALED = /\s+scaled$/i;
4587
4588
  var METRIC_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*(-?\d+(?:\.\d+)?(?:e-?\d+)?)\s*(\S+)?$/i;
4588
4589
  var BASELINE_LINE = /^([A-Za-z_][\w.:/-]*)\s*(?:\{([^}]*)\})?\s*(<=|>=|==|!=|=|<|>)\s*baseline(?:\s*([+-])\s*(\d+(?:\.\d+)?(?:e-?\d+)?)\s*(%|[^\s%]+)?)?$/i;
4589
4590
  function parseLabels(text3) {
@@ -4612,11 +4613,14 @@ function parseCondition(line) {
4612
4613
  const baseline = b[4] ? { sign: b[4] === "-" ? -1 : 1, by: Number(b[5]), percent: b[6] === "%", ...b[6] !== "%" ? { unit: b[6] } : {} } : { sign: 1, by: 0, percent: true };
4613
4614
  return { kind: "metric", raw, metric: b[1], labels: labels2, op: b[3] === "=" ? "==" : b[3], value: Number.NaN, baseline };
4614
4615
  }
4615
- const m = METRIC_LINE.exec(raw);
4616
- if (!m) return { kind: "invalid", raw, problem: "it is neither `test(<file> \u203A <title>) passed`, `review(<name>) passed`, `<metric>{<labels>} <op> <number> [unit]` nor `<metric>{<labels>} <op> baseline [+|- <number> %|unit]`" };
4616
+ const scaled = SCALED.test(raw);
4617
+ const m = METRIC_LINE.exec(scaled ? raw.replace(SCALED, "") : raw);
4618
+ if (!m) return { kind: "invalid", raw, problem: "it is neither `test(<file> \u203A <title>) passed`, `review(<name>) passed`, `<metric>{<labels>} <op> <number> [unit] [scaled]` nor `<metric>{<labels>} <op> baseline [+|- <number> %|unit]`" };
4617
4619
  const labels = m[2] === void 0 ? {} : parseLabels(m[2]);
4618
4620
  if (typeof labels === "string") return { kind: "invalid", raw, problem: labels };
4619
- return { kind: "metric", raw, metric: m[1], labels, op: m[3] === "=" ? "==" : m[3], value: Number(m[4]), ...m[5] ? { unit: m[5] } : {} };
4621
+ const op = m[3] === "=" ? "==" : m[3];
4622
+ if (scaled && (op === "==" || op === "!=")) return { kind: "invalid", raw, problem: "scaled stretches a limit: it takes <, <=, > or >=, not == or !=" };
4623
+ return { kind: "metric", raw, metric: m[1], labels, op, value: Number(m[4]), ...m[5] ? { unit: m[5] } : {}, ...scaled ? { scaled: true } : {} };
4620
4624
  }
4621
4625
  function parseConditions(text3) {
4622
4626
  if (typeof text3 !== "string") return [];
@@ -4680,6 +4684,25 @@ function baselineOf(condition2, baseline, unit) {
4680
4684
  return { median: values.length % 2 ? values[mid] : (values[mid - 1] + values[mid]) / 2, runs: values.length };
4681
4685
  }
4682
4686
  var round = (n) => Math.round(n * 100) / 100;
4687
+ var MACHINE_WORK_METRIC = "machine.work";
4688
+ var MACHINE_SPEED_METRIC = "machine.speed";
4689
+ function machineSpeedAt(measurements, at) {
4690
+ const t = Date.parse(at);
4691
+ let best;
4692
+ for (const m of measurements) {
4693
+ if (m.metric !== MACHINE_SPEED_METRIC || !Number.isFinite(m.value) || m.value <= 0) continue;
4694
+ if (!best || Math.abs(Date.parse(m.at) - t) < Math.abs(Date.parse(best.at) - t)) best = m;
4695
+ }
4696
+ return best;
4697
+ }
4698
+ function scaledLimit(condition2, speed) {
4699
+ const factor = Math.max(1, round(speed));
4700
+ const upper = condition2.op === "<" || condition2.op === "<=";
4701
+ const limit = upper ? condition2.value * factor : condition2.value / factor;
4702
+ const unit = condition2.unit ? ` ${condition2.unit}` : "";
4703
+ const text3 = `${condition2.value}${unit} ${upper ? "\xD7" : "\xF7"} ${factor} = ${round(limit)}${unit}${speed < 1 ? ` (machine.speed ${round(speed)}, never below \xD71)` : ""}`;
4704
+ return { limit, factor, text: text3 };
4705
+ }
4683
4706
  function evaluateMetric(condition2, measurements, maxAge, now, baseline = []) {
4684
4707
  const measurement = latestMeasurement(condition2, measurements);
4685
4708
  if (!measurement) return { outcome: "not-run" };
@@ -4707,6 +4730,12 @@ function evaluateMetric(condition2, measurements, maxAge, now, baseline = []) {
4707
4730
  value = converted;
4708
4731
  }
4709
4732
  if (maxAge !== void 0 && age > maxAge) return { outcome: "stale", measurement, detail: `measured ${formatAge(age)} ago` };
4733
+ if (condition2.scaled) {
4734
+ const machine = machineSpeedAt(measurements, measurement.at);
4735
+ if (!machine) return { outcome: "not-run", measurement, detail: `scaled to the machine, and no ${MACHINE_SPEED_METRIC} was measured: run radical sense machine where the value is measured` };
4736
+ const scaled = scaledLimit(condition2, machine.value);
4737
+ return { outcome: COMPARE[condition2.op](value, scaled.limit) ? "passed" : "failed", measurement, detail: `limit ${scaled.text}` };
4738
+ }
4710
4739
  return { outcome: COMPARE[condition2.op](value, condition2.value) ? "passed" : "failed", measurement };
4711
4740
  }
4712
4741
 
@@ -6085,18 +6114,22 @@ function concernStatuses(packs, nodes, relations) {
6085
6114
  const targets = concernTargets(pack, nodes, relations, asked);
6086
6115
  if (!targets.length) continue;
6087
6116
  const marked = adrsBy.get(pack.concern.id) ?? [];
6088
- const settled = /* @__PURE__ */ new Set();
6117
+ const settled2 = /* @__PURE__ */ new Set();
6089
6118
  for (const n of marked) {
6090
- if (prop2(n, "status") === "accepted") for (const id of constrained.get(n.id) ?? []) settled.add(id);
6119
+ if (prop2(n, "status") === "accepted") for (const id of constrained.get(n.id) ?? []) settled2.add(id);
6091
6120
  }
6092
6121
  const covered = (id) => {
6093
- for (let cur = id; cur; cur = nodes[cur]?.parentId) if (settled.has(cur)) return true;
6122
+ for (let cur = id; cur; cur = nodes[cur]?.parentId) if (settled2.has(cur)) return true;
6094
6123
  return false;
6095
6124
  };
6096
6125
  out.push({ pack, targets, open: targets.filter((id) => !covered(id)), pending: marked.filter((n) => prop2(n, "status") === "proposed") });
6097
6126
  }
6098
6127
  return out;
6099
6128
  }
6129
+ function openConcerns(packs, nodes, relations, metamodel) {
6130
+ if (!holdsConcerns(metamodel)) return [];
6131
+ return concernStatuses(packs, nodes, relations).filter((s2) => s2.open.length);
6132
+ }
6100
6133
  var prop2 = (node, key) => {
6101
6134
  const value = node[key];
6102
6135
  return typeof value === "string" ? value.trim() : "";
@@ -6245,11 +6278,11 @@ var SCALES = { hundred: 100, thousand: 1e3, million: 1e6 };
6245
6278
  var has = (o, k) => Object.prototype.hasOwnProperty.call(o, k);
6246
6279
  var isNumberWord = (w) => has(UNITS, w) || has(TENS, w) || has(SCALES, w);
6247
6280
  function numerals(text3) {
6248
- return text3.replace(/\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million)(?:[ -]+(?:and[ -]+)?|\b))+/gi, (run2) => {
6249
- const words = run2.toLowerCase().split(/[ -]+/).filter((w) => w && w !== "and");
6250
- if (!words.length || words.some((w) => !isNumberWord(w))) return run2;
6251
- if (words.length === 1 && words[0] === "one") return run2;
6252
- if (has(SCALES, words[0])) return run2;
6281
+ return text3.replace(/\b(?:(?:zero|one|two|three|four|five|six|seven|eight|nine|ten|eleven|twelve|thirteen|fourteen|fifteen|sixteen|seventeen|eighteen|nineteen|twenty|thirty|forty|fifty|sixty|seventy|eighty|ninety|hundred|thousand|million)(?:[ -]+(?:and[ -]+)?|\b))+/gi, (run3) => {
6282
+ const words = run3.toLowerCase().split(/[ -]+/).filter((w) => w && w !== "and");
6283
+ if (!words.length || words.some((w) => !isNumberWord(w))) return run3;
6284
+ if (words.length === 1 && words[0] === "one") return run3;
6285
+ if (has(SCALES, words[0])) return run3;
6253
6286
  let total = 0;
6254
6287
  let current = 0;
6255
6288
  for (const w of words) {
@@ -6261,7 +6294,7 @@ function numerals(text3) {
6261
6294
  current = 0;
6262
6295
  }
6263
6296
  }
6264
- return `${total + current}${/\s$/.test(run2) ? " " : ""}`;
6297
+ return `${total + current}${/\s$/.test(run3) ? " " : ""}`;
6265
6298
  });
6266
6299
  }
6267
6300
  var DURATION = [
@@ -6310,13 +6343,13 @@ function valuesOf(text3) {
6310
6343
  const id = (m[1] ?? m[2] ?? m[3]).trim().toLowerCase();
6311
6344
  if (/^[a-z0-9][a-z0-9_-]*$/.test(id) && !/^\d+$/.test(id)) values.add(id);
6312
6345
  }
6313
- t = t.replace(/\b(\d{4}-\d{2}-\d{2})(?:[t ](\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?z?)?\b/gi, (_, date, time) => {
6346
+ t = t.replace(/\b(\d{4}-\d{2}-\d{2})(?:[t ](\d{2}:\d{2})(?::\d{2}(?:\.\d+)?)?z?)?\b/gi, (_, date, time2) => {
6314
6347
  values.add(date);
6315
- if (time) values.add(time);
6348
+ if (time2) values.add(time2);
6316
6349
  return " ";
6317
6350
  });
6318
- t = t.replace(/(?<![\d:])(\d{1,2}:\d{2})(?![\d:])/g, (_, time) => {
6319
- values.add(time.padStart(5, "0"));
6351
+ t = t.replace(/(?<![\d:])(\d{1,2}:\d{2})(?![\d:])/g, (_, time2) => {
6352
+ values.add(time2.padStart(5, "0"));
6320
6353
  return " ";
6321
6354
  });
6322
6355
  t = minusSigns(numerals(t));
@@ -6590,7 +6623,8 @@ function testRule(outcome, message) {
6590
6623
  if (!model.tests) return [];
6591
6624
  return Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type)).flatMap((node) => testOutcomes(node, model).filter((o) => o.outcome === outcome).map((o) => {
6592
6625
  const related = failing ? affectedBy(model, node).map((n) => n.id) : [];
6593
- return { nodeId: node.id, message: message(node, o.id.raw, model), ...related.length ? { relatedIds: related } : {} };
6626
+ const reason = outcome === "failed" ? findTests(o.id, model.tests ?? []).matches.find((c) => c.status === "failed" && c.message)?.message : void 0;
6627
+ return { nodeId: node.id, test: o.id.raw, message: message(node, o.id.raw, model), ...reason ? { reason } : {}, ...related.length ? { relatedIds: related } : {} };
6594
6628
  }));
6595
6629
  };
6596
6630
  }
@@ -6613,6 +6647,9 @@ function metricRule(outcome, message) {
6613
6647
  const origin = originOf(node);
6614
6648
  return elements.flatMap((element) => elementConditions(node, model, element).filter((r) => r.outcome === outcome).map((r) => ({
6615
6649
  nodeId: origin ? element.id : node.id,
6650
+ condition: r.condition,
6651
+ ...r.measurement ? { measured: r.measurement } : {},
6652
+ ...r.detail ? { why: r.detail } : {},
6616
6653
  message: `${message(node, r.condition, seen(r), r.detail).replace(/\.$/, "")} for ${TYPE_NAME[element.type] ?? element.type} ${quote(element)}${origin ? ` (a fitness function of ${origin})` : ""}.`,
6617
6654
  ...origin ? { relatedIds: [node.id] } : outcome === "failed" ? { relatedIds: [element.id] } : {}
6618
6655
  })));
@@ -6620,7 +6657,14 @@ function metricRule(outcome, message) {
6620
6657
  const metricLines = new Set(conditionsOf(node).filter((c) => c.kind === "metric").map((c) => c.raw));
6621
6658
  return conditionResults(node, model).filter((r) => r.outcome === outcome && metricLines.has(r.condition)).map((r) => {
6622
6659
  const related = outcome === "failed" ? affectedBy(model, node).map((n) => n.id) : [];
6623
- return { nodeId: node.id, message: message(node, r.condition, seen(r), r.detail), ...related.length ? { relatedIds: related } : {} };
6660
+ return {
6661
+ nodeId: node.id,
6662
+ condition: r.condition,
6663
+ ...r.measurement ? { measured: r.measurement } : {},
6664
+ ...r.detail ? { why: r.detail } : {},
6665
+ message: message(node, r.condition, seen(r), r.detail),
6666
+ ...related.length ? { relatedIds: related } : {}
6667
+ };
6624
6668
  });
6625
6669
  });
6626
6670
  };
@@ -6831,7 +6875,7 @@ var sourceReading = (text3) => reading(text3.replace(/(\d)_(?=\d)/g, "$1").repla
6831
6875
  var CHECK_RULES = [
6832
6876
  {
6833
6877
  id: "metamodel",
6834
- description: 'The model follows its metamodel: types, parents, relation pairs, required properties, references and the state machine rules. The Validation list in Studio and get_issues over MCP, with their severities: an unknown type or a relation to no element is an error, a relation pair the metamodel does not allow a warning (`"metamodel": "error"` makes every issue one).',
6878
+ description: '**The model follows its metamodel**: types, parents, relation pairs, required properties, references and the state machine rules. The Validation list in Studio and get_issues over MCP, with their severities: an unknown type or a relation to no element is an error, a relation pair the metamodel does not allow a warning (`"metamodel": "error"` makes every issue one).',
6835
6879
  severity: "error",
6836
6880
  dimension: "consistency",
6837
6881
  run: (model) => validateModel(model.nodes, model.relations, model.metamodel).map((issue) => ({
@@ -6844,42 +6888,42 @@ var CHECK_RULES = [
6844
6888
  },
6845
6889
  {
6846
6890
  id: "requirement-incomplete",
6847
- description: "A requirement has an action and every field its EARS type reads (an event-driven one a trigger, a state-driven one a precondition, \u2026).",
6891
+ description: "**A requirement has an action and every field its EARS type reads** (an event-driven one a trigger, a state-driven one a precondition, \u2026).",
6848
6892
  severity: "warning",
6849
6893
  dimension: "completeness",
6850
6894
  run: (model) => nodesOf(model, "requirement").filter((n) => !composeEarsSentence(n, void 0, requirementStatePhrase(n, model.nodes, model.relations)).complete).map((n) => ({ nodeId: n.id, message: `Requirement ${quote(n)} (${prop3(n, "ears_type") || "ubiquitous"}) misses the action or a field its EARS type needs.` }))
6851
6895
  },
6852
6896
  {
6853
6897
  id: "requirement-without-scenario",
6854
- description: "Every requirement is verified by at least one scenario.",
6898
+ description: "**Every requirement is verified by at least one scenario**.",
6855
6899
  severity: "warning",
6856
6900
  dimension: "traceability",
6857
6901
  run: (model) => model.metamodel.nodeTypes.scenario ? unlinked(model, "requirement", "verifies", "in", ["scenario"]).map((n) => ({ nodeId: n.id, message: `No scenario verifies requirement ${quote(n)}.` })) : []
6858
6902
  },
6859
6903
  {
6860
6904
  id: "requirement-unsatisfied",
6861
- description: "Every requirement is satisfied by an element of the architecture.",
6905
+ description: "**Every requirement is satisfied by an element of the architecture**.",
6862
6906
  severity: "warning",
6863
6907
  dimension: "traceability",
6864
6908
  run: (model) => unlinked(model, "requirement", "satisfies", "in").map((n) => ({ nodeId: n.id, message: `Nothing satisfies requirement ${quote(n)}.` }))
6865
6909
  },
6866
6910
  {
6867
6911
  id: "requirement-without-origin",
6868
- description: "Every requirement derives from a need or from another requirement.",
6912
+ description: "**Every requirement derives from a need or from another requirement**.",
6869
6913
  severity: "warning",
6870
6914
  dimension: "traceability",
6871
6915
  run: (model) => unlinked(model, "requirement", "derives", "out", ["need", "requirement"]).map((n) => ({ nodeId: n.id, message: `Requirement ${quote(n)} derives from no need and no other requirement.` }))
6872
6916
  },
6873
6917
  {
6874
6918
  id: "need-without-requirement",
6875
- description: "Every need has at least one requirement derived from it, or from a need inside it (a need that derives from it, Part of).",
6919
+ description: "**Every need has at least one requirement derived from it**, or from a need inside it (a need that derives from it, Part of).",
6876
6920
  severity: "warning",
6877
6921
  dimension: "traceability",
6878
6922
  run: (model) => unlinked(model, "need", "derives", "in", ["requirement"]).filter((n) => !requirementsOfNeed(model, n.id).length).map((n) => ({ nodeId: n.id, message: `No requirement derives from need ${quote(n)}.` }))
6879
6923
  },
6880
6924
  {
6881
6925
  id: "derives-quote-missing",
6882
- description: "A requirement's derives relation to a need quotes the words of the need it rests on (property quote, one verbatim fragment per line). Off unless check.json turns it on; the goal requirements-quoting-need follows it in percent.",
6926
+ description: "A requirement's derives relation to a need **quotes the words of the need it rests on** (property quote, one verbatim fragment per line). Off unless check.json turns it on; the goal requirements-quoting-need follows it in percent.",
6883
6927
  severity: "warning",
6884
6928
  off: true,
6885
6929
  dimension: "traceability",
@@ -6887,7 +6931,7 @@ var CHECK_RULES = [
6887
6931
  },
6888
6932
  {
6889
6933
  id: "derives-quote-not-in-need",
6890
- description: "Every fragment a derives relation quotes is in the need's text outside its superseded answers, as whole words (case, white space, Markdown marks, dashes and quotation marks aside; an ellipsis joins pieces that must be there in that order, within one question, answer or the text before the questions), and holds at least two words; only a relation to a need quotes.",
6934
+ description: "**Every fragment a derives relation quotes is in the need's text** outside its superseded answers, as whole words (case, white space, Markdown marks, dashes and quotation marks aside; an ellipsis joins pieces that must be there in that order, within one question, answer or the text before the questions), and holds at least two words; only a relation to a need quotes.",
6891
6935
  severity: "error",
6892
6936
  dimension: "traceability",
6893
6937
  run: (model) => Object.values(model.relations).filter((r) => r.relationType === "derives" && relationQuote(r).trim() && model.nodes[r.sourceId]?.type === "requirement" && !originOf(model.nodes[r.sourceId])).flatMap((r) => {
@@ -6902,7 +6946,7 @@ var CHECK_RULES = [
6902
6946
  },
6903
6947
  {
6904
6948
  id: "quote-value-missing",
6905
- description: "Every hard value a derives relation quotes (a number, null, true or false, a date or time, an identifier in backticks or quotation marks) is in the requirement's sentence, in that form or another (20 percent as 20%, 15 minutes as 900 seconds, 12.30 \u20AC as 1230 cents).",
6949
+ description: "**Every hard value a derives relation quotes** (a number, null, true or false, a date or time, an identifier in backticks or quotation marks) **is in the requirement's sentence**, in that form or another (20 percent as 20%, 15 minutes as 900 seconds, 12.30 \u20AC as 1230 cents).",
6906
6950
  severity: "warning",
6907
6951
  dimension: "traceability",
6908
6952
  run: (model) => nodesOf(model, "requirement").filter((n) => !originOf(n)).flatMap((req) => {
@@ -6913,14 +6957,14 @@ var CHECK_RULES = [
6913
6957
  },
6914
6958
  {
6915
6959
  id: "quote-value-differs",
6916
- description: "A requirement keeps the sense the words it quotes give a value: the same side of a limit (at most, more than, from \u2026 to; a refusal speaks of the other side), the same unit, the same order of a list, the same rounding.",
6960
+ description: "**A requirement keeps the sense the words it quotes give a value**: the same side of a limit (at most, more than, from \u2026 to; a refusal speaks of the other side), the same unit, the same order of a list, the same rounding.",
6917
6961
  severity: "warning",
6918
6962
  dimension: "traceability",
6919
6963
  run: (model) => nodesOf(model, "requirement").filter((n) => !originOf(n)).flatMap((req) => quoteSenseGaps(model, req))
6920
6964
  },
6921
6965
  {
6922
6966
  id: "requirement-value-unquoted",
6923
- description: "Every hard value a requirement states that quotes its need is in those quotes (or in those of the requirements it derives from), in that form or another, or its rationale names it as a decision of the model.",
6967
+ description: "**Every hard value a requirement states that quotes its need is in those quotes** (or in those of the requirements it derives from), in that form or another, or its rationale names it as a decision of the model.",
6924
6968
  severity: "warning",
6925
6969
  dimension: "traceability",
6926
6970
  run: (model) => nodesOf(model, "requirement").filter((n) => !originOf(n)).flatMap((req) => {
@@ -6930,7 +6974,7 @@ var CHECK_RULES = [
6930
6974
  },
6931
6975
  {
6932
6976
  id: "scenario-value-missing",
6933
- description: "Every hard value a requirement takes from the words it quotes is in a scenario that verifies it (its given, when, then or Gherkin text): what the person said reaches a check.",
6977
+ description: "**Every hard value a requirement takes from the words it quotes is in a scenario that verifies it** (its given, when, then or Gherkin text): what the person said reaches a check.",
6934
6978
  severity: "warning",
6935
6979
  dimension: "traceability",
6936
6980
  run: (model) => nodesOf(model, "requirement").filter((n) => !originOf(n)).flatMap((req) => {
@@ -6947,7 +6991,7 @@ var CHECK_RULES = [
6947
6991
  },
6948
6992
  {
6949
6993
  id: "example-not-in-scenario",
6950
- description: `Every example a need gives with values ("for example", "e.g.", "Example:") is whole in one scenario of the requirements derived from the need: the person's own case checks what they meant.`,
6994
+ description: `**Every example a need gives with values** ("for example", "e.g.", "Example:") **is whole in one scenario** of the requirements derived from the need: the person's own case checks what they meant.`,
6951
6995
  severity: "warning",
6952
6996
  dimension: "traceability",
6953
6997
  run: (model) => nodesOf(model, "need").filter((n) => !originOf(n)).flatMap((need) => {
@@ -6965,7 +7009,7 @@ var CHECK_RULES = [
6965
7009
  },
6966
7010
  {
6967
7011
  id: "scenario-value-untested",
6968
- description: "With the test sources (radical check reads the files of the tests .radical/radical.json binds): every hard value a scenario names that tells a case apart (not a count below 10) is in the file of a test bound to it.",
7012
+ description: "With the test sources (radical check reads the files of the tests .radical/radical.json binds): **every hard value a scenario names that tells a case apart** (not a count below 10) **is in the file of a test bound to it**.",
6969
7013
  severity: "warning",
6970
7014
  dimension: "traceability",
6971
7015
  run: (model) => {
@@ -6985,7 +7029,7 @@ var CHECK_RULES = [
6985
7029
  },
6986
7030
  {
6987
7031
  id: "need-answer-unquoted",
6988
- description: "Every paragraph and list item of an answer of a person in a need (from a line that starts with A:, Answer: or A1:, or an answer on its question's line; lead-ins and lines of fewer than four words aside) is quoted by a requirement that derives from the need, or the answer is marked (no requirement) or (superseded).",
7032
+ description: "**Every paragraph and list item of an answer of a person in a need** (from a line that starts with A:, Answer: or A1:, or an answer on its question's line; lead-ins and lines of fewer than four words aside) **is quoted by a requirement that derives from the need**, or the answer is marked (no requirement) or (superseded).",
6989
7033
  severity: "warning",
6990
7034
  dimension: "traceability",
6991
7035
  run: (model) => {
@@ -7003,7 +7047,7 @@ var CHECK_RULES = [
7003
7047
  },
7004
7048
  {
7005
7049
  id: "need-answer-changed",
7006
- description: "With the model at the base (radical check in git, the Inspector with the branch's base): every answer of a person a need held there it still holds, word for word; a person's words are only added to, and an answer a later one replaces is marked (superseded).",
7050
+ description: "With the model at the base (radical check in git, the Inspector with the branch's base): **every answer of a person a need held there it still holds, word for word**; a person's words are only added to, and an answer a later one replaces is marked (superseded).",
7007
7051
  severity: "error",
7008
7052
  dimension: "traceability",
7009
7053
  run: (model) => {
@@ -7017,21 +7061,21 @@ var CHECK_RULES = [
7017
7061
  },
7018
7062
  {
7019
7063
  id: "scenario-verifies-nothing",
7020
- description: "Every scenario verifies a requirement or a state machine.",
7064
+ description: "**Every scenario verifies a requirement or a state machine**.",
7021
7065
  severity: "warning",
7022
7066
  dimension: "traceability",
7023
7067
  run: (model) => unlinked(model, "scenario", "verifies", "out").map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} verifies no requirement and no state machine.` }))
7024
7068
  },
7025
7069
  {
7026
7070
  id: "adr-without-fitness-fn",
7027
- description: "Every accepted ADR is implemented by a fitness function that checks it.",
7071
+ description: "**Every accepted ADR is implemented by a fitness function** that checks it.",
7028
7072
  severity: "warning",
7029
7073
  dimension: "decisions",
7030
7074
  run: (model) => model.metamodel.nodeTypes["fitness-fn"] ? unlinked(model, "adr", "implements", "in", ["fitness-fn"]).filter((n) => prop3(n, "status") === "accepted").filter((n) => !relationsOf(model, "waives").from.has(n.id)).map((n) => ({ nodeId: n.id, message: `No fitness function implements accepted ADR ${quote(n)}.` })) : []
7031
7075
  },
7032
7076
  {
7033
7077
  id: "inherited-adr-unapplied",
7034
- description: "Every accepted ADR of a model this one depends on (deps.json) binds it: it constrains at least one of this model's elements, or an accepted ADR of this model waives it and says why.",
7078
+ description: "**Every accepted ADR of a model this one depends on** (deps.json) **binds it**: it constrains at least one of this model's elements, or an accepted ADR of this model waives it and says why.",
7035
7079
  severity: "error",
7036
7080
  dimension: "decisions",
7037
7081
  run: (model) => inheritedDecisions(model).filter((d) => !d.elements.length).map(({ adr, origin }) => ({
@@ -7041,7 +7085,7 @@ var CHECK_RULES = [
7041
7085
  },
7042
7086
  {
7043
7087
  id: "inherited-adr-unchecked",
7044
- description: "Every element an accepted ADR of a model this one depends on constrains is checked: a fitness function implements the ADR (this model's or the other's) and names its check (metric conditions, or tests .radical/radical.json binds to it).",
7088
+ description: "**Every element an accepted ADR of a model this one depends on constrains is checked**: a fitness function implements the ADR (this model's or the other's) and names its check (metric conditions, or tests .radical/radical.json binds to it).",
7045
7089
  severity: "error",
7046
7090
  dimension: "decisions",
7047
7091
  run: (model) => inheritedDecisions(model).flatMap(({ adr, origin, elements }) => {
@@ -7055,7 +7099,7 @@ var CHECK_RULES = [
7055
7099
  },
7056
7100
  {
7057
7101
  id: "adr-incomplete",
7058
- description: "An accepted ADR records its date, context, decision and consequences.",
7102
+ description: "**An accepted ADR records its date, context, decision and consequences**.",
7059
7103
  severity: "warning",
7060
7104
  dimension: "completeness",
7061
7105
  run: (model) => nodesOf(model, "adr").filter((n) => prop3(n, "status") === "accepted").flatMap((n) => {
@@ -7065,7 +7109,7 @@ var CHECK_RULES = [
7065
7109
  },
7066
7110
  {
7067
7111
  id: "adr-superseded-unlinked",
7068
- description: "An ADR is superseded exactly when a newer ADR supersedes it.",
7112
+ description: "**An ADR is superseded exactly when a newer ADR supersedes it**.",
7069
7113
  severity: "warning",
7070
7114
  dimension: "consistency",
7071
7115
  run: (model) => {
@@ -7082,7 +7126,7 @@ var CHECK_RULES = [
7082
7126
  },
7083
7127
  {
7084
7128
  id: "fitness-fn-unlinked",
7085
- description: "Every fitness function implements an ADR or constrains an element.",
7129
+ description: "**Every fitness function implements an ADR or constrains an element**.",
7086
7130
  severity: "warning",
7087
7131
  dimension: "decisions",
7088
7132
  run: (model) => {
@@ -7093,10 +7137,10 @@ var CHECK_RULES = [
7093
7137
  },
7094
7138
  {
7095
7139
  id: "concern-unaddressed",
7096
- description: "Every concern a Hub concern pack finds in the model is settled by an accepted ADR marked with it (property `concern`) that constrains the elements it applies to, or what contains them.",
7140
+ description: "**Every concern a Hub concern pack finds in the model is settled by an accepted ADR marked with it** (property `concern`) that constrains the elements it applies to, or what contains them.",
7097
7141
  severity: "warning",
7098
7142
  dimension: "decisions",
7099
- run: (model) => holdsConcerns(model.metamodel) ? concernStatuses(model.concerns ?? [], model.nodes, model.relations).filter((s2) => s2.open.length).map(({ pack, open: open4, pending }) => {
7143
+ run: (model) => openConcerns(model.concerns ?? [], model.nodes, model.relations, model.metamodel).map(({ pack, open: open4, pending }) => {
7100
7144
  const names = open4.map((id) => quote(model.nodes[id])).join(", ");
7101
7145
  const being = pending.length ? ` ${pending.map(quote).join(", ")} ${pending.length === 1 ? "is" : "are"} proposed: the decision is being made.` : "";
7102
7146
  return {
@@ -7106,11 +7150,11 @@ var CHECK_RULES = [
7106
7150
  message: `${pack.name}: ${pack.concern.why} No accepted ADR marked "${pack.concern.id}" settles it for ${names}.${being}`,
7107
7151
  details: (pack.templateParams ?? []).map(questionLine)
7108
7152
  };
7109
- }) : []
7153
+ })
7110
7154
  },
7111
7155
  {
7112
7156
  id: "concern-unbound",
7113
- description: "Every accepted ADR marked with a concern (property `concern`, set by a Hub concern pack) constrains the elements it settles the concern for.",
7157
+ description: "**Every accepted ADR marked with a concern** (property `concern`, set by a Hub concern pack) **constrains the elements it settles the concern for**.",
7114
7158
  severity: "warning",
7115
7159
  dimension: "decisions",
7116
7160
  run: (model) => unboundDecisions(model.concerns ?? [], model.nodes, model.relations, model.metamodel).map(({ adr, concern, checks, bindTo }) => ({
@@ -7122,21 +7166,21 @@ var CHECK_RULES = [
7122
7166
  },
7123
7167
  {
7124
7168
  id: "scenario-without-metrics",
7125
- description: "Every scenario has what checks it: tests the repository's .radical/radical.json binds to it, or metric conditions (property `metrics`, one per line: `<metric>{<labels>} <op> <number> [unit]`). One the repository must verify is scenario-not-verified-here's.",
7169
+ description: "**Every scenario has what checks it**: tests the repository's .radical/radical.json binds to it, or metric conditions (property `metrics`, one per line: `<metric>{<labels>} <op> <number> [unit]`). One the repository must verify is scenario-not-verified-here's.",
7126
7170
  severity: "warning",
7127
7171
  dimension: "traceability",
7128
7172
  run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length && !verifiedHere(model, n)).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} names no check.` }))
7129
7173
  },
7130
7174
  {
7131
7175
  id: "scenario-not-verified-here",
7132
- description: "With the repository's .radical/radical.json (the CLI): every scenario of a requirement an element the repository builds satisfies has tests the file binds to it, or metric conditions.",
7176
+ description: "With the repository's .radical/radical.json (the CLI): **every scenario of a requirement an element the repository builds satisfies has tests the file binds to it, or metric conditions**.",
7133
7177
  severity: "warning",
7134
7178
  dimension: "traceability",
7135
7179
  run: (model) => nodesOf(model, "scenario").filter((n) => !conditionsOf(n).length && verifiedHere(model, n)).map((n) => ({ nodeId: n.id, message: `Scenario ${quote(n)} is this repository's to verify (an element it builds satisfies its requirement), and ${model.repository.file} binds no test to it: radical verify ${n.id} --test "<file> \u203A <title>".` }))
7136
7180
  },
7137
7181
  {
7138
7182
  id: "model-names-tests",
7139
- description: "A scenario or fitness function names no test in its Metrics: the repository binds its tests in .radical/radical.json (radical setup moves them there). A test named in Metrics still counts.",
7183
+ description: "**A scenario or fitness function names no test in its Metrics**: the repository binds its tests in .radical/radical.json (radical setup moves them there). A test named in Metrics still counts.",
7140
7184
  severity: "warning",
7141
7185
  dimension: "traceability",
7142
7186
  run: (model) => Object.values(model.nodes).filter((n) => TESTED_TYPES.includes(n.type) && !originOf(n)).flatMap((n) => {
@@ -7146,14 +7190,14 @@ var CHECK_RULES = [
7146
7190
  },
7147
7191
  {
7148
7192
  id: "fitness-fn-without-metrics",
7149
- description: "Every fitness function states what checks it and when it passes (property `metrics`, one condition per line).",
7193
+ description: "**Every fitness function states what checks it and when it passes** (property `metrics`, one condition per line).",
7150
7194
  severity: "warning",
7151
7195
  dimension: "decisions",
7152
7196
  run: (model) => nodesOf(model, "fitness-fn").filter((n) => !conditionsOf(n).length).map((n) => ({ nodeId: n.id, message: `Fitness function ${quote(n)} names no check.` }))
7153
7197
  },
7154
7198
  {
7155
7199
  id: "fitness-fn-unclassified",
7156
- description: "Every fitness function states its characteristic (ISO/IEC 25010), scope, cadence (with the event it is triggered on, or how often a temporal one falls due) and invocation.",
7200
+ description: "**Every fitness function states its characteristic** (ISO/IEC 25010), scope, cadence (with the event it is triggered on, or how often a temporal one falls due) and invocation.",
7157
7201
  severity: "warning",
7158
7202
  dimension: "decisions",
7159
7203
  run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => {
@@ -7166,7 +7210,7 @@ var CHECK_RULES = [
7166
7210
  },
7167
7211
  {
7168
7212
  id: "fitness-fn-measure-invalid",
7169
- description: `Every line of a fitness function's \`measure\` names a sensor of radical sense (${SENSOR_NAMES.join(", ")}) or, run by the CLI, one of the repository's .radical/sensors/sensors.json.`,
7213
+ description: `**Every line of a fitness function's \`measure\` names a sensor** of radical sense (${SENSOR_NAMES.join(", ")}) or, run by the CLI, one of the repository's .radical/sensors/sensors.json.`,
7170
7214
  severity: "error",
7171
7215
  dimension: "completeness",
7172
7216
  run: (model) => model.sensors === void 0 ? [] : nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => !isSensorName(line.sensor) && !model.sensors?.names.includes(line.sensor)).map((line) => ({
@@ -7176,14 +7220,14 @@ var CHECK_RULES = [
7176
7220
  },
7177
7221
  {
7178
7222
  id: "repository-mapping",
7179
- description: "With the repository's .radical/radical.json (the CLI): each entry names an element of the model, its own or another model's of the federation, under the element's name, with paths the repository has; tests are bound to scenarios and fitness functions.",
7223
+ description: "With the repository's .radical/radical.json (the CLI): **each entry names an element of the model**, its own or another model's of the federation, under the element's name, with paths the repository has; tests are bound to scenarios and fitness functions.",
7180
7224
  severity: "warning",
7181
7225
  dimension: "traceability",
7182
7226
  run: repositoryMapping
7183
7227
  },
7184
7228
  {
7185
7229
  id: "repository-settings-in-model",
7186
- description: `The model's check.json holds the model's rules and goals; the repository's test files (test-unbound's include and exclude) and CI's artifacts belong in .radical/radical.json ("tests", "ci"). Those in check.json are still read.`,
7230
+ description: `The model's check.json holds the model's rules and goals; **the repository's test files** (test-unbound's include and exclude) and CI's artifacts **belong in .radical/radical.json** ("tests", "ci"). Those in check.json are still read.`,
7187
7231
  severity: "warning",
7188
7232
  dimension: "completeness",
7189
7233
  run: (model) => (model.settingsInModel ?? []).map((what) => ({
@@ -7193,7 +7237,7 @@ var CHECK_RULES = [
7193
7237
  },
7194
7238
  {
7195
7239
  id: "description-path-missing",
7196
- description: "With the repository (the CLI): a path from the repository's root an element's description names (apps/cli/src/sense.ts) is in the repository; one that is gone tells of code that moved.",
7240
+ description: "With the repository (the CLI): **a path from the repository's root an element's description names** (apps/cli/src/sense.ts) **is in the repository**; one that is gone tells of code that moved.",
7197
7241
  severity: "warning",
7198
7242
  dimension: "consistency",
7199
7243
  run: (model) => Object.entries(model.missingPaths ?? {}).flatMap(([id, paths]) => {
@@ -7203,21 +7247,21 @@ var CHECK_RULES = [
7203
7247
  },
7204
7248
  {
7205
7249
  id: "measure-with-arguments",
7206
- description: `A fitness function's measure lines name sensors only: an adapter's arguments (files, options of the repository) belong to a sensor of .radical/sensors/sensors.json ({ "adapter": "playwright", "args": [...] }). A line with arguments still runs.`,
7250
+ description: `**A fitness function's measure lines name sensors only**: an adapter's arguments (files, options of the repository) belong to a sensor of .radical/sensors/sensors.json ({ "adapter": "playwright", "args": [...] }). A line with arguments still runs.`,
7207
7251
  severity: "warning",
7208
7252
  dimension: "completeness",
7209
7253
  run: (model) => nodesOf(model, "fitness-fn").flatMap((n) => parseMeasure(n.measure).filter((line) => line.args.length > 0).map((line) => ({ nodeId: n.id, message: `Fitness function ${quote(n)}: measure "${line.raw}" has the repository's arguments; name a sensor of .radical/sensors/sensors.json that holds them ({ "adapter": "${line.sensor}", "args": [...] }).` })))
7210
7254
  },
7211
7255
  {
7212
7256
  id: "metric-invalid",
7213
- description: "Every line of a scenario's or fitness function's `metrics` reads as a condition, its unit converts to the unit of the measurement it matches, and `combine` and `max_age` read.",
7257
+ description: "**Every line of a scenario's or fitness function's `metrics` reads as a condition**, its unit converts to the unit of the measurement it matches, and `combine` and `max_age` read.",
7214
7258
  severity: "error",
7215
7259
  dimension: "completeness",
7216
7260
  run: invalidChecks
7217
7261
  },
7218
7262
  {
7219
7263
  id: "test-failed",
7220
- description: "With --report: every test a scenario or fitness function names passed.",
7264
+ description: "With --report: **every test a scenario or fitness function names passed**.",
7221
7265
  severity: "error",
7222
7266
  dimension: "tests",
7223
7267
  readsReports: true,
@@ -7225,7 +7269,7 @@ var CHECK_RULES = [
7225
7269
  },
7226
7270
  {
7227
7271
  id: "test-not-found",
7228
- description: "With --report: every test a scenario or fitness function names is in the report of its file (a renamed or deleted test is not).",
7272
+ description: "With --report: **every test a scenario or fitness function names is in the report of its file** (a renamed or deleted test is not).",
7229
7273
  severity: "error",
7230
7274
  dimension: "tests",
7231
7275
  readsReports: true,
@@ -7233,7 +7277,7 @@ var CHECK_RULES = [
7233
7277
  },
7234
7278
  {
7235
7279
  id: "test-skipped",
7236
- description: "With --report: no test a scenario or fitness function names was skipped.",
7280
+ description: "With --report: **no test a scenario or fitness function names was skipped**.",
7237
7281
  severity: "warning",
7238
7282
  dimension: "tests",
7239
7283
  readsReports: true,
@@ -7241,15 +7285,15 @@ var CHECK_RULES = [
7241
7285
  },
7242
7286
  {
7243
7287
  id: "test-not-run",
7244
- description: "With --report: every file a scenario or fitness function names a test in is in the reports.",
7288
+ description: "With --report: **every file a scenario or fitness function names a test in is in the reports**.",
7245
7289
  severity: "warning",
7246
7290
  dimension: "tests",
7247
7291
  readsReports: true,
7248
- run: testRule("not-run", (node, id) => `${testedName(node)}: no report has the file of test ${id}.`)
7292
+ run: testRule("not-run", (node, id) => `${testedName(node)}: test ${id} did not run: no report has its file.`)
7249
7293
  },
7250
7294
  {
7251
7295
  id: "metric-failed",
7252
- description: "With measurements: every metric condition a scenario or fitness function states holds for the latest measurement it matches.",
7296
+ description: "With measurements: **every metric condition a scenario or fitness function states holds** for the latest measurement it matches.",
7253
7297
  severity: "error",
7254
7298
  dimension: "tests",
7255
7299
  readsMeasurements: true,
@@ -7257,7 +7301,7 @@ var CHECK_RULES = [
7257
7301
  },
7258
7302
  {
7259
7303
  id: "metric-stale",
7260
- description: "With measurements: the latest measurement each metric condition matches is no older than the element's max_age (a stale one never passes).",
7304
+ description: "With measurements: **the latest measurement each metric condition matches is no older than the element's max_age** (a stale one never passes).",
7261
7305
  severity: "warning",
7262
7306
  dimension: "tests",
7263
7307
  readsMeasurements: true,
@@ -7265,7 +7309,7 @@ var CHECK_RULES = [
7265
7309
  },
7266
7310
  {
7267
7311
  id: "metric-not-measured",
7268
- description: "With measurements: a measurement matches every metric condition a scenario or fitness function states.",
7312
+ description: "With measurements: **a measurement matches every metric condition a scenario or fitness function states**.",
7269
7313
  severity: "warning",
7270
7314
  dimension: "tests",
7271
7315
  readsMeasurements: true,
@@ -7273,7 +7317,7 @@ var CHECK_RULES = [
7273
7317
  },
7274
7318
  {
7275
7319
  id: "test-unbound",
7276
- description: "With --report and an include in check.json: every test in the files it includes is named by a scenario or a fitness function, by its title or its describe block (a whole file or directory does not count). One finding per test file.",
7320
+ description: "With --report and an include in check.json: **every test in the files it includes is named by a scenario or a fitness function**, by its title or its describe block (a whole file or directory does not count). One finding per test file.",
7277
7321
  severity: "warning",
7278
7322
  dimension: "tests",
7279
7323
  readsReports: true,
@@ -7309,11 +7353,64 @@ function testBinding(model) {
7309
7353
  return byFile;
7310
7354
  }
7311
7355
 
7356
+ // ../../packages/common/src/check/profiles.ts
7357
+ init_define_RADICAL_BUILD();
7358
+ var ADOPT_RULE = {
7359
+ id: "baselines-pending",
7360
+ description: '**check.json does not wait for the baselines of its first run** ("adopt": true); radical check --adopt takes them once.',
7361
+ severity: "error",
7362
+ dimension: "consistency"
7363
+ };
7364
+ var ADOPT_MESSAGE = 'check.json waits for the baselines of its first run ("adopt": true): run radical check --adopt and commit check.json.';
7365
+ function strictCheckConfig(ruleIds, metricIds) {
7366
+ return {
7367
+ rules: Object.fromEntries(ruleIds.filter((id) => id !== ADOPT_RULE.id).map((id) => [id, "error"])),
7368
+ goals: Object.fromEntries(metricIds.map((id) => [id, { min: 100 }]))
7369
+ };
7370
+ }
7371
+ function existingCodeCheckConfig(ruleIds) {
7372
+ return {
7373
+ adopt: true,
7374
+ rules: Object.fromEntries(ruleIds.filter((id) => id !== ADOPT_RULE.id).map((id) => [id, "error"]))
7375
+ };
7376
+ }
7377
+ var severityOf = (setting2) => typeof setting2 === "object" ? setting2.severity : setting2;
7378
+ function adoptBaselines(config, result) {
7379
+ if (!config.adopt) throw new Error('check.json does not wait for baselines (no "adopt": true): they were taken already, and only radical check --ratchet lowers them');
7380
+ const rules = { ...config.rules ?? {} };
7381
+ const baselines = [];
7382
+ const notRun = [];
7383
+ for (const r of result.rules) {
7384
+ if (r.id === ADOPT_RULE.id || r.id.startsWith("goal-unmet")) continue;
7385
+ if (r.notRun) {
7386
+ notRun.push(r.id);
7387
+ continue;
7388
+ }
7389
+ if (r.severity === "off" || r.count === 0) continue;
7390
+ const severity = severityOf(rules[r.id]) ?? r.severity;
7391
+ rules[r.id] = { ...typeof rules[r.id] === "object" ? rules[r.id] : {}, severity, max: r.count };
7392
+ baselines.push({ id: r.id, max: r.count });
7393
+ }
7394
+ const goals = [];
7395
+ for (const m of result.metrics) {
7396
+ if (m.total === 0) continue;
7397
+ goals.push({ id: m.id, min: m.percent });
7398
+ }
7399
+ for (const g of result.goalsNotRun) notRun.push(g.id);
7400
+ const { adopt: _adopt, ...rest } = config;
7401
+ return {
7402
+ config: { ...rest, rules, goals: { ...config.goals ?? {}, ...Object.fromEntries(goals.map((g) => [g.id, { min: g.min }])) } },
7403
+ baselines,
7404
+ goals,
7405
+ notRun
7406
+ };
7407
+ }
7408
+
7312
7409
  // ../../packages/common/src/check/goals.ts
7313
7410
  init_define_RADICAL_BUILD();
7314
7411
  var GOAL_RULE = {
7315
7412
  id: "goal-unmet",
7316
- description: 'Every metric check.json sets a goal for ("goals": { "<metric>": { "min": <percent> } }) reaches it. One finding per goal, with the metric as its code.',
7413
+ description: '**Every metric check.json sets a goal for** ("goals": { "<metric>": { "min": <percent> } }) **reaches it**. One finding per goal, with the metric as its code.',
7317
7414
  severity: "error"
7318
7415
  };
7319
7416
  var without = (rule) => (population) => (ctx) => {
@@ -7452,6 +7549,135 @@ function measureGoals(ctx, goals) {
7452
7549
  return { metrics, findings, notRun };
7453
7550
  }
7454
7551
 
7552
+ // ../../packages/common/src/check/files.ts
7553
+ init_define_RADICAL_BUILD();
7554
+ var CHECK_CONFIG_FILE = "check.json";
7555
+ var TEST_RESULTS_FILE = `${STATE_DIR}/test-results.json`;
7556
+ var MEASUREMENTS_FILE = `${STATE_DIR}/measurements.json`;
7557
+ var CI_FETCH_FILE = `${STATE_DIR}/ci-fetch.json`;
7558
+ function serializeTestResults(cases, reports, readAt = /* @__PURE__ */ new Date(), from = {}) {
7559
+ const results = {
7560
+ version: 1,
7561
+ readAt: readAt.toISOString(),
7562
+ reports,
7563
+ cases,
7564
+ ...from.commit ? { commit: from.commit } : {},
7565
+ ...from.ci ? { ci: from.ci } : {},
7566
+ ...from.kept ? { kept: from.kept } : {}
7567
+ };
7568
+ return JSON.stringify(results);
7569
+ }
7570
+ var sameTestFile = (a2, b) => a2 === b || a2.endsWith("/" + b) || b.endsWith("/" + a2);
7571
+ function withEarlierResults(cases, earlier) {
7572
+ if (!earlier?.cases.length) return { cases };
7573
+ const slash = (file) => file.replace(/\\/g, "/");
7574
+ const ran = [...new Set(cases.map((c) => slash(c.file)))];
7575
+ const ranSet = new Set(ran);
7576
+ const replaced = /* @__PURE__ */ new Map();
7577
+ const isReplaced = (file) => {
7578
+ let r = replaced.get(file);
7579
+ if (r === void 0) {
7580
+ r = ranSet.has(file) || ran.some((f) => sameTestFile(f, file));
7581
+ replaced.set(file, r);
7582
+ }
7583
+ return r;
7584
+ };
7585
+ const left = earlier.cases.filter((c) => !isReplaced(slash(c.file)));
7586
+ if (!left.length) return { cases };
7587
+ return {
7588
+ cases: [...cases, ...left],
7589
+ kept: { since: earlier.kept?.since ?? testsRanAt(earlier), cases: left.length, files: new Set(left.map((c) => slash(c.file))).size }
7590
+ };
7591
+ }
7592
+ function testsRanAt(results) {
7593
+ const runs = results.ci?.runs.map((r) => r.ranAt).filter((at) => !Number.isNaN(Date.parse(at))).sort() ?? [];
7594
+ return runs.length ? runs[runs.length - 1] : results.readAt;
7595
+ }
7596
+ function ciSourceOf(value) {
7597
+ const ci = value;
7598
+ if (!ci || ci.provider !== "github" || typeof ci.commit !== "string" || typeof ci.behind !== "number" || !Array.isArray(ci.runs)) return void 0;
7599
+ const runs = ci.runs.filter((r) => !!r && typeof r.id === "number" && typeof r.url === "string" && typeof r.sha === "string" && typeof r.ranAt === "string" && typeof r.workflow === "string" && Array.isArray(r.artifacts));
7600
+ return { provider: "github", commit: ci.commit, behind: ci.behind, runs, ...typeof ci.measurements === "number" ? { measurements: ci.measurements } : {} };
7601
+ }
7602
+ var STATUSES = /* @__PURE__ */ new Set(["passed", "failed", "skipped"]);
7603
+ function parseTestResults(text3) {
7604
+ let data;
7605
+ try {
7606
+ data = JSON.parse(text3);
7607
+ } catch {
7608
+ return null;
7609
+ }
7610
+ const r = data;
7611
+ if (r?.version !== 1 || typeof r.readAt !== "string" || !Array.isArray(r.cases)) return null;
7612
+ const cases = r.cases.filter((c) => !!c && typeof c.file === "string" && Array.isArray(c.title) && c.title.every((t) => typeof t === "string") && STATUSES.has(c.status));
7613
+ const ci = ciSourceOf(r.ci);
7614
+ const k = r.kept;
7615
+ const kept2 = k && typeof k.since === "string" && typeof k.cases === "number" && typeof k.files === "number" ? { since: k.since, cases: k.cases, files: k.files } : void 0;
7616
+ return {
7617
+ version: 1,
7618
+ readAt: r.readAt,
7619
+ reports: Array.isArray(r.reports) ? r.reports.filter((x) => typeof x === "string") : [],
7620
+ cases,
7621
+ ...typeof r.commit === "string" ? { commit: r.commit } : {},
7622
+ ...ci ? { ci } : {},
7623
+ ...kept2 ? { kept: kept2 } : {}
7624
+ };
7625
+ }
7626
+ function parseCheckConfig(text3) {
7627
+ const data = JSON.parse(stripBom(text3));
7628
+ if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("a config is a JSON object");
7629
+ const rules = data.rules;
7630
+ if (rules !== void 0 && (typeof rules !== "object" || rules === null || Array.isArray(rules))) throw new Error('"rules" is an object of rule settings');
7631
+ const goals = data.goals;
7632
+ if (goals !== void 0) {
7633
+ if (typeof goals !== "object" || goals === null || Array.isArray(goals)) throw new Error('"goals" is an object of goals by metric');
7634
+ for (const [id, goal] of Object.entries(goals)) {
7635
+ const min = goal?.min;
7636
+ if (typeof min !== "number" || !(min >= 0 && min <= 100)) throw new Error(`goal "${id}" needs a "min" from 0 to 100 (percent)`);
7637
+ }
7638
+ }
7639
+ const adopt = data.adopt;
7640
+ if (adopt !== void 0 && typeof adopt !== "boolean") throw new Error('"adopt" is true while check.json waits for the baselines of its first run (radical check --adopt), else left out');
7641
+ const ci = data.ci;
7642
+ if (ci !== void 0) {
7643
+ const artifacts = ci?.artifacts;
7644
+ if (typeof ci !== "object" || ci === null || Array.isArray(ci) || artifacts !== void 0 && !(Array.isArray(artifacts) && artifacts.every((a2) => typeof a2 === "string" && a2)))
7645
+ throw new Error('"ci" is an object whose "artifacts" lists the names of the CI artifacts that hold test reports');
7646
+ }
7647
+ return data;
7648
+ }
7649
+ var CI_ARTIFACTS_HINT = `CI has to keep its test reports (and its radical sense --out files) as artifacts of the run, named in .radical/radical.json's "ci": { "artifacts": [...] }`;
7650
+ var serializeCiFetch = (fetch2) => JSON.stringify({ version: 1, ...fetch2 }, null, 2) + "\n";
7651
+ var OUTCOMES = /* @__PURE__ */ new Set(["read", "same", "kept", "failed"]);
7652
+ function parseCiFetch(text3) {
7653
+ let data;
7654
+ try {
7655
+ data = JSON.parse(text3);
7656
+ } catch {
7657
+ return null;
7658
+ }
7659
+ const f = data;
7660
+ if (f?.version !== 1 || typeof f.at !== "string" || Number.isNaN(Date.parse(f.at)) || !OUTCOMES.has(f.outcome) || typeof f.message !== "string") return null;
7661
+ const runs = Array.isArray(f.runs) ? f.runs.filter((r) => !!r && typeof r.id === "number" && typeof r.url === "string").map((r) => ({ id: r.id, url: r.url })) : void 0;
7662
+ return {
7663
+ version: 1,
7664
+ at: f.at,
7665
+ outcome: f.outcome,
7666
+ message: f.message,
7667
+ ...typeof f.head === "string" ? { head: f.head } : {},
7668
+ ...typeof f.commit === "string" ? { commit: f.commit } : {},
7669
+ ...runs?.length ? { runs } : {},
7670
+ ...typeof f.tests === "number" ? { tests: f.tests } : {},
7671
+ ...typeof f.measurements === "number" ? { measurements: f.measurements } : {}
7672
+ };
7673
+ }
7674
+ function ciFetchProblem(fetch2) {
7675
+ if (!fetch2) return null;
7676
+ if (fetch2.outcome === "failed") return fetch2.message;
7677
+ if (fetch2.outcome === "read" && fetch2.tests === 0) return fetch2.message;
7678
+ return null;
7679
+ }
7680
+
7455
7681
  // ../../packages/common/src/check/testSource.ts
7456
7682
  init_define_RADICAL_BUILD();
7457
7683
  function splitTestId(id) {
@@ -7616,68 +7842,6 @@ function formatTrace(trace, nodes, now = Date.now()) {
7616
7842
  return out.join("\n");
7617
7843
  }
7618
7844
 
7619
- // ../../packages/common/src/check/files.ts
7620
- init_define_RADICAL_BUILD();
7621
- var CHECK_CONFIG_FILE = "check.json";
7622
- var TEST_RESULTS_FILE = `${STATE_DIR}/test-results.json`;
7623
- var MEASUREMENTS_FILE = `${STATE_DIR}/measurements.json`;
7624
- function serializeTestResults(cases, reports, readAt = /* @__PURE__ */ new Date(), from = {}) {
7625
- const results = { version: 1, readAt: readAt.toISOString(), reports, cases, ...from.commit ? { commit: from.commit } : {}, ...from.ci ? { ci: from.ci } : {} };
7626
- return JSON.stringify(results);
7627
- }
7628
- function testsRanAt(results) {
7629
- const runs = results.ci?.runs.map((r) => r.ranAt).filter((at) => !Number.isNaN(Date.parse(at))).sort() ?? [];
7630
- return runs.length ? runs[runs.length - 1] : results.readAt;
7631
- }
7632
- function ciSourceOf(value) {
7633
- const ci = value;
7634
- if (!ci || ci.provider !== "github" || typeof ci.commit !== "string" || typeof ci.behind !== "number" || !Array.isArray(ci.runs)) return void 0;
7635
- const runs = ci.runs.filter((r) => !!r && typeof r.id === "number" && typeof r.url === "string" && typeof r.sha === "string" && typeof r.ranAt === "string" && typeof r.workflow === "string" && Array.isArray(r.artifacts));
7636
- return { provider: "github", commit: ci.commit, behind: ci.behind, runs };
7637
- }
7638
- var STATUSES = /* @__PURE__ */ new Set(["passed", "failed", "skipped"]);
7639
- function parseTestResults(text3) {
7640
- let data;
7641
- try {
7642
- data = JSON.parse(text3);
7643
- } catch {
7644
- return null;
7645
- }
7646
- const r = data;
7647
- if (r?.version !== 1 || typeof r.readAt !== "string" || !Array.isArray(r.cases)) return null;
7648
- const cases = r.cases.filter((c) => !!c && typeof c.file === "string" && Array.isArray(c.title) && c.title.every((t) => typeof t === "string") && STATUSES.has(c.status));
7649
- const ci = ciSourceOf(r.ci);
7650
- return {
7651
- version: 1,
7652
- readAt: r.readAt,
7653
- reports: Array.isArray(r.reports) ? r.reports.filter((x) => typeof x === "string") : [],
7654
- cases,
7655
- ...typeof r.commit === "string" ? { commit: r.commit } : {},
7656
- ...ci ? { ci } : {}
7657
- };
7658
- }
7659
- function parseCheckConfig(text3) {
7660
- const data = JSON.parse(stripBom(text3));
7661
- if (!data || typeof data !== "object" || Array.isArray(data)) throw new Error("a config is a JSON object");
7662
- const rules = data.rules;
7663
- if (rules !== void 0 && (typeof rules !== "object" || rules === null || Array.isArray(rules))) throw new Error('"rules" is an object of rule settings');
7664
- const goals = data.goals;
7665
- if (goals !== void 0) {
7666
- if (typeof goals !== "object" || goals === null || Array.isArray(goals)) throw new Error('"goals" is an object of goals by metric');
7667
- for (const [id, goal] of Object.entries(goals)) {
7668
- const min = goal?.min;
7669
- if (typeof min !== "number" || !(min >= 0 && min <= 100)) throw new Error(`goal "${id}" needs a "min" from 0 to 100 (percent)`);
7670
- }
7671
- }
7672
- const ci = data.ci;
7673
- if (ci !== void 0) {
7674
- const artifacts = ci?.artifacts;
7675
- if (typeof ci !== "object" || ci === null || Array.isArray(ci) || artifacts !== void 0 && !(Array.isArray(artifacts) && artifacts.every((a2) => typeof a2 === "string" && a2)))
7676
- throw new Error('"ci" is an object whose "artifacts" lists the names of the CI artifacts that hold test reports');
7677
- }
7678
- return data;
7679
- }
7680
-
7681
7845
  // ../../packages/common/src/check/reviews.ts
7682
7846
  init_define_RADICAL_BUILD();
7683
7847
  var REVIEWS_FILE2 = "reviews.json";
@@ -7779,23 +7943,27 @@ function evidenceSummary(result) {
7779
7943
  return lines;
7780
7944
  }
7781
7945
 
7946
+ // ../../packages/common/src/check/findingWords.ts
7947
+ init_define_RADICAL_BUILD();
7948
+ var plainRuleText = (description) => description.replace(/\*\*/g, "");
7949
+
7782
7950
  // ../../packages/common/src/check/configChanges.ts
7783
7951
  init_define_RADICAL_BUILD();
7784
7952
 
7785
7953
  // ../../packages/common/src/check/index.ts
7786
7954
  var FOLDER_RULES = [
7787
- { id: "folder-manifest", description: "The folder has a radical.md manifest of the Markdown-folder format, version 1.", severity: "error", dimension: "consistency" },
7788
- { id: "folder-json", description: "Every JSON sidecar (relations.json, views.json, \u2026) parses.", severity: "error", dimension: "consistency" },
7789
- { id: "folder-conflict", description: "No node file holds git conflict markers.", severity: "error", dimension: "consistency" },
7790
- { id: "folder-not-a-node", description: "A node file with frontmatter has an id and a type (one without them is skipped on loading, and its element is gone).", severity: "error", dimension: "consistency" },
7791
- { id: "folder-duplicate-id", description: "No two node files hold the same id.", severity: "error", dimension: "consistency" },
7792
- { id: "stale-reference", description: "Views, sequences and slides point only at elements, relations and views the model has.", severity: "warning", dimension: "consistency" }
7955
+ { id: "folder-manifest", description: "**The folder has a radical.md manifest** of the Markdown-folder format, version 1.", severity: "error", dimension: "consistency" },
7956
+ { id: "folder-json", description: "**Every JSON sidecar** (relations.json, views.json, \u2026) **parses**.", severity: "error", dimension: "consistency" },
7957
+ { id: "folder-conflict", description: "**No node file holds git conflict markers**.", severity: "error", dimension: "consistency" },
7958
+ { id: "folder-not-a-node", description: "**A node file with frontmatter has an id and a type** (one without them is skipped on loading, and its element is gone).", severity: "error", dimension: "consistency" },
7959
+ { id: "folder-duplicate-id", description: "**No two node files hold the same id**.", severity: "error", dimension: "consistency" },
7960
+ { id: "stale-reference", description: "**Views, sequences and slides point only at elements, relations and views the model has**.", severity: "warning", dimension: "consistency" }
7793
7961
  ];
7794
7962
  var FATAL = /* @__PURE__ */ new Set(["folder-manifest", "folder-json", "folder-conflict"]);
7795
7963
  var STALE_REFERENCE = "stale-reference";
7796
- var MODEL_RULE_IDS = /* @__PURE__ */ new Set([STALE_REFERENCE, ...CHECK_RULES.map((r) => r.id), GOAL_RULE.id]);
7964
+ var MODEL_RULE_IDS = /* @__PURE__ */ new Set([STALE_REFERENCE, ...CHECK_RULES.map((r) => r.id), GOAL_RULE.id, ADOPT_RULE.id]);
7797
7965
  var byId = (items) => Object.fromEntries(items.map((item) => [item.id, item]));
7798
- var ALL_RULES = [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE];
7966
+ var ALL_RULES = [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE, ADOPT_RULE];
7799
7967
  var RENAMED_RULES = {
7800
7968
  "scenario-without-tests": "scenario-without-metrics",
7801
7969
  "fitness-fn-without-tests": "fitness-fn-without-metrics",
@@ -7931,6 +8099,7 @@ function checkData(data, options, config) {
7931
8099
  const evidence = options.tests || options.measurements ? computeEvidence(model) : void 0;
7932
8100
  const goals = measureGoals({ model: ownModel2, found, ...evidence ? { evidence } : {} }, config.goals ?? {});
7933
8101
  goals.findings.forEach((finding) => found.push({ rule: GOAL_RULE.id, ...finding }));
8102
+ if (config.adopt) found.push({ rule: ADOPT_RULE.id, message: ADOPT_MESSAGE, path: CHECK_CONFIG_FILE });
7934
8103
  return {
7935
8104
  found,
7936
8105
  nodeCount: Object.keys(ownModel2.nodes).length,
@@ -7997,18 +8166,18 @@ function settle(found, config, { nodeCount, relationCount, metrics, notRun, goal
7997
8166
  continue;
7998
8167
  }
7999
8168
  const withinBaseline = max2 !== void 0 && list.length <= max2;
8000
- const settled = list.map((f) => ({
8169
+ const settled2 = list.map((f) => ({
8001
8170
  ...f,
8002
8171
  key,
8003
8172
  severity: withinBaseline || f.asOf ? "warning" : set2 ?? f.severity ?? ruleSeverity
8004
8173
  }));
8005
- findings.push(...settled);
8174
+ findings.push(...settled2);
8006
8175
  results.push({
8007
8176
  id: key,
8008
8177
  count: list.length,
8009
8178
  severity: set2 ?? ruleSeverity,
8010
8179
  ...max2 !== void 0 ? { max: max2 } : {},
8011
- failed: settled.some((f) => f.severity === "error")
8180
+ failed: settled2.some((f) => f.severity === "error")
8012
8181
  });
8013
8182
  }
8014
8183
  const errors = findings.filter((f) => f.severity === "error").length;
@@ -8037,6 +8206,9 @@ function ratchetConfig(config, result) {
8037
8206
  }
8038
8207
  return { config: { ...config, rules }, lowered };
8039
8208
  }
8209
+ var strictCheckConfig2 = () => strictCheckConfig(ALL_RULES.map((r) => r.id), CHECK_METRICS.map((m) => m.id));
8210
+ var existingCodeCheckConfig2 = () => existingCodeCheckConfig(ALL_RULES.map((r) => r.id));
8211
+ var serializeCheckConfig = (config) => JSON.stringify(config, null, 2) + "\n";
8040
8212
 
8041
8213
  // ../../packages/common/src/federation.ts
8042
8214
  init_define_RADICAL_BUILD();
@@ -13179,7 +13351,7 @@ After review, repeat this command with --apply --expect ${preview.token}`);
13179
13351
  // src/check.ts
13180
13352
  init_define_RADICAL_BUILD();
13181
13353
  import { existsSync as existsSync2 } from "fs";
13182
- import { mkdir as mkdir5, readFile as readFile10, readdir as readdir4, realpath as realpath4, stat as stat7, writeFile as writeFile5 } from "fs/promises";
13354
+ import { mkdir as mkdir5, readFile as readFile10, readdir as readdir4, realpath as realpath4, rename as rename4, stat as stat7, writeFile as writeFile5 } from "fs/promises";
13183
13355
  import { basename as basename3, dirname as dirname8, join as join13, relative as relative5, resolve as resolve10 } from "path";
13184
13356
  import { fileURLToPath as fileURLToPath2 } from "url";
13185
13357
  import { parseArgs as parseArgs4 } from "util";
@@ -13279,21 +13451,21 @@ async function findCiRuns(root, gh, names) {
13279
13451
  const runs = [];
13280
13452
  for (const { sha, pr: pr2 } of candidates) {
13281
13453
  for (const [id, artifacts] of byCommit.get(sha)) {
13282
- const run2 = await json(gh, root, `repos/{owner}/{repo}/actions/runs/${id}`);
13283
- if (run2.status !== "completed") continue;
13284
- const number = pr2 ?? run2.pull_requests?.[0]?.number;
13285
- runs.push({ id, url: run2.html_url, sha, ranAt: run2.updated_at, workflow: run2.name, ...number ? { pr: number } : {}, artifacts: [...artifacts].sort() });
13454
+ const run3 = await json(gh, root, `repos/{owner}/{repo}/actions/runs/${id}`);
13455
+ if (run3.status !== "completed") continue;
13456
+ const number = pr2 ?? run3.pull_requests?.[0]?.number;
13457
+ runs.push({ id, url: run3.html_url, sha, ranAt: run3.updated_at, workflow: run3.name, ...number ? { pr: number } : {}, artifacts: [...artifacts].sort() });
13286
13458
  }
13287
13459
  }
13288
13460
  if (!runs.length) continue;
13289
13461
  runs.sort((a2, b) => Date.parse(b.ranAt) - Date.parse(a2.ranAt));
13290
13462
  const taken = /* @__PURE__ */ new Set();
13291
13463
  const chosen = [];
13292
- for (const run2 of runs) {
13293
- const artifacts = run2.artifacts.filter((name) => !taken.has(name));
13464
+ for (const run3 of runs) {
13465
+ const artifacts = run3.artifacts.filter((name) => !taken.has(name));
13294
13466
  if (!artifacts.length) continue;
13295
13467
  artifacts.forEach((name) => taken.add(name));
13296
- chosen.push({ ...run2, artifacts });
13468
+ chosen.push({ ...run3, artifacts });
13297
13469
  }
13298
13470
  return { provider: "github", commit, behind, runs: chosen.sort((a2, b) => a2.id - b.id) };
13299
13471
  }
@@ -13313,32 +13485,48 @@ async function downloadCiReports(root, gh, source) {
13313
13485
  try {
13314
13486
  const cases = [];
13315
13487
  const reports = [];
13316
- for (const run2 of source.runs) {
13317
- for (const artifact of run2.artifacts) {
13318
- const into = join9(dir, String(run2.id), artifact);
13319
- await gh(["run", "download", String(run2.id), "--name", artifact, "--dir", into], root);
13488
+ const measurements = [];
13489
+ for (const run3 of source.runs) {
13490
+ for (const artifact of run3.artifacts) {
13491
+ const into = join9(dir, String(run3.id), artifact);
13492
+ await gh(["run", "download", String(run3.id), "--name", artifact, "--dir", into], root);
13320
13493
  for (const file of await filesUnder(into)) {
13494
+ const text3 = await readFile6(file, "utf8");
13495
+ const measured = metricsIn(text3, file);
13496
+ if (measured) {
13497
+ measurements.push(...measured.map((m) => ({ ...m, context: { ...m.context, "ci.run": String(run3.id), "ci.commit": source.commit } })));
13498
+ continue;
13499
+ }
13321
13500
  let read2;
13322
13501
  try {
13323
- read2 = parseTestReport(await readFile6(file, "utf8"), file);
13502
+ read2 = parseTestReport(text3, file);
13324
13503
  } catch {
13325
13504
  continue;
13326
13505
  }
13327
13506
  if (!read2.length) continue;
13328
13507
  cases.push(...read2);
13329
- reports.push(`run ${run2.id} ${artifact}/${relative3(into, file).replace(/\\/g, "/")}`);
13508
+ reports.push(`run ${run3.id} ${artifact}/${relative3(into, file).replace(/\\/g, "/")}`);
13330
13509
  }
13331
13510
  }
13332
13511
  }
13333
- if (!reports.length) throw new CiError(`the artifacts of run${source.runs.length > 1 ? "s" : ""} ${source.runs.map((r) => r.id).join(", ")} hold no test report`);
13334
- return { cases, reports };
13512
+ if (!reports.length && !measurements.length) throw new CiError(`the artifacts of run${source.runs.length > 1 ? "s" : ""} ${source.runs.map((r) => r.id).join(", ")} hold no test report and no radical-metrics/1 file`);
13513
+ return { cases, reports, measurements };
13335
13514
  } finally {
13336
13515
  await rm4(dir, { recursive: true, force: true });
13337
13516
  }
13338
13517
  }
13518
+ function metricsIn(text3, file) {
13519
+ if (!text3.includes(METRICS_FORMAT)) return null;
13520
+ try {
13521
+ const data = JSON.parse(text3);
13522
+ return data?.format === METRICS_FORMAT ? parseMetricsFile(text3, file) : null;
13523
+ } catch {
13524
+ return null;
13525
+ }
13526
+ }
13339
13527
  function sameRuns(results, source) {
13340
13528
  const key = (s2) => s2.runs.map((r) => `${r.id}:${r.artifacts.join(",")}`).join(" ");
13341
- return !!results?.ci && key(results.ci) === key(source);
13529
+ return !!results?.ci && results.ci.measurements !== void 0 && key(results.ci) === key(source);
13342
13530
  }
13343
13531
  async function readLater(root, results, commit) {
13344
13532
  return !!results && !results.ci && !!results.commit && isAncestor(root, commit, results.commit);
@@ -13575,7 +13763,7 @@ async function readModelAtCommit(folder, commit, from) {
13575
13763
  return Object.fromEntries(blobs.map((blob, i) => [blob.path, contents[i]]));
13576
13764
  }
13577
13765
  function catFiles(cwd, shas) {
13578
- return new Promise((resolve27, reject) => {
13766
+ return new Promise((resolve28, reject) => {
13579
13767
  const child = spawn("git", ["cat-file", "--batch"], { cwd, windowsHide: true });
13580
13768
  const chunks = [];
13581
13769
  let stderr = "";
@@ -13603,7 +13791,7 @@ function catFiles(cwd, shas) {
13603
13791
  contents.push(stripBom(out.subarray(start, start + Number(size)).toString("utf8")));
13604
13792
  at = start + Number(size) + 1;
13605
13793
  }
13606
- resolve27(contents);
13794
+ resolve28(contents);
13607
13795
  });
13608
13796
  child.stdin.end(shas.join("\n") + "\n");
13609
13797
  });
@@ -13667,9 +13855,9 @@ async function modelChangesSince(folder, current, since, options = {}) {
13667
13855
  // ../../packages/node-files/src/gitDeps.ts
13668
13856
  var exec3 = promisify3(execFile3);
13669
13857
  async function git3(cwd, args, input) {
13670
- const run2 = exec3("git", args, { cwd, maxBuffer: 256 * 1024 * 1024, encoding: "utf8", windowsHide: true });
13671
- if (input !== void 0) run2.child.stdin?.end(input);
13672
- const { stdout } = await run2;
13858
+ const run3 = exec3("git", args, { cwd, maxBuffer: 256 * 1024 * 1024, encoding: "utf8", windowsHide: true });
13859
+ if (input !== void 0) run3.child.stdin?.end(input);
13860
+ const { stdout } = await run3;
13673
13861
  return stdout.trim();
13674
13862
  }
13675
13863
  var gitOk2 = (cwd, args) => git3(cwd, args).catch(() => null);
@@ -13840,11 +14028,11 @@ function addressKey(address) {
13840
14028
  }
13841
14029
  async function ownLocations(root) {
13842
14030
  const own = /* @__PURE__ */ new Set([`file:${await realpath3(root).catch(() => root)}`]);
13843
- const run2 = (args) => exec4("git", args, { cwd: root, windowsHide: true }).then((r) => r.stdout.trim(), () => "");
13844
- const top = await run2(["rev-parse", "--show-toplevel"]);
14031
+ const run3 = (args) => exec4("git", args, { cwd: root, windowsHide: true }).then((r) => r.stdout.trim(), () => "");
14032
+ const top = await run3(["rev-parse", "--show-toplevel"]);
13845
14033
  if (!top) return own;
13846
14034
  const folder = relative4(await realpath3(top).catch(() => top), await realpath3(root).catch(() => root)) || ".";
13847
- for (const line of (await run2(["remote", "-v"])).split("\n")) {
14035
+ for (const line of (await run3(["remote", "-v"])).split("\n")) {
13848
14036
  const address = line.split(/\s+/)[1];
13849
14037
  if (!address) continue;
13850
14038
  if (isAddress(address)) own.add(`${addressKey(address)}#${folder}`);
@@ -13869,8 +14057,8 @@ function federationOthers(files, fetched) {
13869
14057
  }
13870
14058
  async function latestRef(repo, home) {
13871
14059
  const address = repoAddress(repo, home);
13872
- const run2 = (args) => exec4("git", args, { cwd: home, windowsHide: true, timeout: 3e4 }).then((r) => r.stdout, () => "");
13873
- const tags = (await run2(["ls-remote", "--tags", "--refs", address])).split("\n").map((line) => line.split("refs/tags/")[1]?.trim()).filter((tag2) => !!tag2 && /^v?\d+(\.\d+)*$/.test(tag2));
14060
+ const run3 = (args) => exec4("git", args, { cwd: home, windowsHide: true, timeout: 3e4 }).then((r) => r.stdout, () => "");
14061
+ const tags = (await run3(["ls-remote", "--tags", "--refs", address])).split("\n").map((line) => line.split("refs/tags/")[1]?.trim()).filter((tag2) => !!tag2 && /^v?\d+(\.\d+)*$/.test(tag2));
13874
14062
  if (tags.length) {
13875
14063
  const parts2 = (tag2) => tag2.replace(/^v/, "").split(".").map(Number);
13876
14064
  return tags.sort((a2, b) => {
@@ -13879,7 +14067,7 @@ async function latestRef(repo, home) {
13879
14067
  return 0;
13880
14068
  }).at(-1);
13881
14069
  }
13882
- return (await run2(["ls-remote", "--symref", address, "HEAD"])).match(/^ref: refs\/heads\/(\S+)\s+HEAD/m)?.[1] ?? "main";
14070
+ return (await run3(["ls-remote", "--symref", address, "HEAD"])).match(/^ref: refs\/heads\/(\S+)\s+HEAD/m)?.[1] ?? "main";
13883
14071
  }
13884
14072
  function parseDependsOn(spec) {
13885
14073
  const at = spec.indexOf("=");
@@ -14083,8 +14271,19 @@ its own ("model": { "repo": \u2026 }), it judges that repository's part of the m
14083
14271
  the run. They are kept for Studio as --report keeps
14084
14272
  them, with the commit and runs they come from, unless
14085
14273
  the results there were read with --report at that
14086
- commit or a later one. radical hooks install fetches
14274
+ commit or a later one. The radical-metrics/1 files in
14275
+ the artifacts (radical sense --out) are added to the
14276
+ measurements, as --metrics adds them. What it found,
14277
+ or why it found nothing, is kept in the folder's
14278
+ .state/ci-fetch.json, with --quiet too, for Studio and
14279
+ radical setup --status. CI has to keep the reports as
14280
+ artifacts of the run. radical hooks install fetches
14087
14281
  them after a checkout, a commit, a pull and a rebase
14282
+ --no-keep read the reports and measurements given and judge with
14283
+ them, but keep nothing beside the model: what Studio
14284
+ shows stays as it was (a check used as a gate, a test
14285
+ of the gate). --evidence, --ratchet and --adopt still
14286
+ write the file they name
14088
14287
  --quiet print nothing (the git hooks fetch with --from-ci --quiet)
14089
14288
  --detach start this check in the background and return at once
14090
14289
  (the git hooks, which git waits for)
@@ -14117,6 +14316,15 @@ its own ("model": { "repo": \u2026 }), it judges that repository's part of the m
14117
14316
  baseline of the model's check.json (exit 2): only one
14118
14317
  --config names. With --alone or --trigger, which leave
14119
14318
  part of the model out, it lowers none (exit 2)
14319
+ --adopt take the baselines of this first run into check.json
14320
+ once: each rule that finds something gets its count as
14321
+ max, each measured metric its share as the goal, and
14322
+ "adopt": true goes. Only for a check.json that waits for
14323
+ them (radical setup and Assay write one for existing
14324
+ code), or none (it writes one with every rule an error);
14325
+ from then on only --ratchet lowers them. Give the test
14326
+ reports and measurements too, or the rules that read
14327
+ them get no baseline
14120
14328
  --alone check without the models deps.json names; with a
14121
14329
  deps.json the model is checked composed with them, at
14122
14330
  their pinned refs (radical federation --help)
@@ -14146,6 +14354,7 @@ async function checkCommand(args, io2) {
14146
14354
  format: { type: "string", default: "text" },
14147
14355
  report: { type: "string", multiple: true },
14148
14356
  "from-ci": { type: "boolean", default: false },
14357
+ "no-keep": { type: "boolean", default: false },
14149
14358
  quiet: { type: "boolean", default: false },
14150
14359
  detach: { type: "boolean", default: false },
14151
14360
  metrics: { type: "string", multiple: true },
@@ -14154,6 +14363,7 @@ async function checkCommand(args, io2) {
14154
14363
  evidence: { type: "string" },
14155
14364
  trace: { type: "string" },
14156
14365
  ratchet: { type: "boolean", default: false },
14366
+ adopt: { type: "boolean", default: false },
14157
14367
  alone: { type: "boolean", default: false },
14158
14368
  verbose: { type: "boolean", default: false },
14159
14369
  "list-rules": { type: "boolean", default: false },
@@ -14172,17 +14382,22 @@ ${CHECK_USAGE}`);
14172
14382
  return 0;
14173
14383
  }
14174
14384
  if (values["list-rules"]) {
14175
- for (const rule of [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE]) io2.out(`${rule.id.padEnd(30)} ${(rule.off ? "off" : rule.severity).padEnd(8)} ${rule.description}`);
14385
+ for (const rule of [...FOLDER_RULES, ...CHECK_RULES, GOAL_RULE]) io2.out(`${rule.id.padEnd(30)} ${(rule.off ? "off" : rule.severity).padEnd(8)} ${plainRuleText(rule.description)}`);
14176
14386
  io2.out("\nMetrics for goals (in percent):");
14177
14387
  for (const metric of CHECK_METRICS) io2.out(`${metric.id.padEnd(30)} ${(metric.tests ? "evidence" : "").padEnd(8)} ${metric.description}`);
14178
14388
  return 0;
14179
14389
  }
14180
14390
  const fromCi = values["from-ci"];
14181
- if (positionals.length > 1 || !["text", "json", "github"].includes(values.format) || fromCi && values.report?.length || values.evidence && !values.report?.length && !fromCi && !values.metrics?.length || values.trace !== void 0 && (!values.trace.trim() || values.format === "github" || values.ratchet)) {
14391
+ const keepBeside = !values["no-keep"];
14392
+ if (positionals.length > 1 || !["text", "json", "github"].includes(values.format) || fromCi && values.report?.length || values.evidence && !values.report?.length && !fromCi && !values.metrics?.length || values.trace !== void 0 && (!values.trace.trim() || values.format === "github" || values.ratchet || values.adopt)) {
14182
14393
  io2.err(CHECK_USAGE);
14183
14394
  return 2;
14184
14395
  }
14185
14396
  const partial = values.alone ? "--alone" : values.trigger !== void 0 ? "--trigger" : null;
14397
+ if (values.adopt && (values.ratchet || partial)) {
14398
+ io2.err(`radical check --adopt: ${values.ratchet ? "takes the first baselines; --ratchet lowers them later, not in the same run" : `with ${partial} the check leaves part of the model out, and a baseline counts the whole model`}.`);
14399
+ return 2;
14400
+ }
14186
14401
  if (values.ratchet && partial) {
14187
14402
  io2.err(`radical check --ratchet: with ${partial} the check leaves part of the model out (${partial === "--alone" ? "the models deps.json names" : "the metric conditions of other events"}), and a baseline counts the whole model. Ratchet with a check of all of it.`);
14188
14403
  return 2;
@@ -14216,6 +14431,7 @@ ${CHECK_USAGE}`);
14216
14431
  io2.err(missing2 ? `No config at ${configPath}.` : `Cannot read the config ${configPath}: ${error.message}`);
14217
14432
  return 2;
14218
14433
  }
14434
+ if (values.adopt) config = existingCodeCheckConfig2();
14219
14435
  }
14220
14436
  let repository;
14221
14437
  let mappedFrom = root;
@@ -14241,23 +14457,32 @@ ${CHECK_USAGE}`);
14241
14457
  let tests;
14242
14458
  let testsReadAt;
14243
14459
  let keep;
14460
+ let keptCases;
14461
+ let ciMeasurements = [];
14244
14462
  if (fromCi) {
14245
14463
  const say = (text3) => {
14246
14464
  if (!values.quiet) io2.err(text3);
14247
14465
  };
14248
- const resultsPath = join13(root, TEST_RESULTS_FILE);
14249
14466
  const existing = parseTestResults(await readEditorStateFile(root, TEST_RESULTS_FILE) ?? "");
14250
14467
  const gh = io2.gh ?? ghCli(io2.env ?? process.env);
14468
+ const head = await headOf(root) ?? void 0;
14469
+ const record3 = async (fetch2) => {
14470
+ if (keepBeside) await writeBeside(join13(root, CI_FETCH_FILE), serializeCiFetch({ at: (/* @__PURE__ */ new Date()).toISOString(), ...head ? { head } : {}, ...fetch2 }));
14471
+ };
14251
14472
  let got;
14252
14473
  try {
14253
14474
  got = await withFetchLock(root, async () => {
14254
14475
  const source2 = await findCiRuns(root, gh, repository?.ci?.artifacts ?? config.ci?.artifacts);
14255
14476
  if (await readLater(root, existing, source2.commit)) return { source: source2, kept: existing };
14256
- if (sameRuns(existing, source2)) return { source: source2, cases: existing.cases, reports: existing.reports };
14257
- return { source: source2, ...await downloadCiReports(root, gh, source2) };
14477
+ if (sameRuns(existing, source2)) return { source: { ...source2, measurements: existing.ci.measurements }, same: true, cases: existing.cases, reports: existing.reports, measurements: [] };
14478
+ const read3 = await downloadCiReports(root, gh, source2);
14479
+ return { source: { ...source2, measurements: read3.measurements.length }, ...read3 };
14258
14480
  });
14259
14481
  } catch (error) {
14260
- say(`radical check --from-ci: ${error instanceof CiError ? error.message : error.message}`);
14482
+ const message = error instanceof CiError ? error.message : error.message;
14483
+ await record3({ outcome: "failed", message: `radical check --from-ci: ${message}` }).catch(() => {
14484
+ });
14485
+ say(`radical check --from-ci: ${message}`);
14261
14486
  return 2;
14262
14487
  }
14263
14488
  if (!got) {
@@ -14266,15 +14491,29 @@ ${CHECK_USAGE}`);
14266
14491
  }
14267
14492
  const { source } = got;
14268
14493
  const runs = `run${source.runs.length > 1 ? "s" : ""} ${source.runs.map((r) => r.id).join(", ")}${source.runs[0]?.pr ? ` (pull request #${source.runs[0].pr})` : ""}`;
14494
+ const from = { commit: source.commit, runs: source.runs.map((r) => ({ id: r.id, url: r.url })) };
14495
+ const behind = source.behind ? `, ${source.behind} commit${source.behind > 1 ? "s" : ""} before HEAD` : "";
14269
14496
  if (got.kept) {
14270
14497
  tests = got.kept.cases;
14271
14498
  testsReadAt = got.kept.readAt;
14272
- say(`Kept the test results read with --report at ${got.kept.commit.slice(0, 7)}: CI's (${runs}) are of ${source.commit.slice(0, 7)}, before it.`);
14499
+ const message = `Kept the test results read with --report at ${got.kept.commit.slice(0, 7)}: CI's (${runs}) are of ${source.commit.slice(0, 7)}, before it.`;
14500
+ await record3({ outcome: "kept", message, ...from });
14501
+ say(message);
14273
14502
  } else {
14274
- tests = got.cases;
14275
- testsReadAt = testsRanAt({ version: 1, readAt: (/* @__PURE__ */ new Date()).toISOString(), reports: [], cases: [], ci: source });
14276
- keep = { reports: got.reports, ci: source, commit: await headOf(root) ?? void 0 };
14277
- say(`Test results of CI ${runs} for ${source.commit.slice(0, 7)}${source.behind ? `, ${source.behind} commit${source.behind > 1 ? "s" : ""} before HEAD` : ""}.`);
14503
+ ciMeasurements = got.measurements;
14504
+ const measured = ciMeasurements.length ? `; ${ciMeasurements.length} measurement${ciMeasurements.length === 1 ? "" : "s"}` : "";
14505
+ if (got.cases.length) {
14506
+ tests = got.cases;
14507
+ testsReadAt = testsRanAt({ version: 1, readAt: (/* @__PURE__ */ new Date()).toISOString(), reports: [], cases: [], ci: source });
14508
+ keep = { reports: got.reports, ci: source, commit: head };
14509
+ const message = `${got.same ? "The same test results of CI" : "Test results of CI"} ${runs} for ${source.commit.slice(0, 7)}${behind}${measured}.`;
14510
+ await record3({ outcome: got.same ? "same" : "read", message, ...from, tests: tests.length, ...got.same ? {} : { measurements: ciMeasurements.length } });
14511
+ say(message);
14512
+ } else {
14513
+ const message = `The artifacts of CI ${runs} for ${source.commit.slice(0, 7)}${behind} hold no test report${measured}.`;
14514
+ await record3({ outcome: "read", message, ...from, tests: 0, measurements: ciMeasurements.length });
14515
+ say(message);
14516
+ }
14278
14517
  }
14279
14518
  } else if (values.report?.length) {
14280
14519
  tests = [];
@@ -14295,6 +14534,12 @@ ${CHECK_USAGE}`);
14295
14534
  return 2;
14296
14535
  }
14297
14536
  }
14537
+ const merged = withEarlierResults(tests, parseTestResults(await readEditorStateFile(root, TEST_RESULTS_FILE) ?? ""));
14538
+ if (merged.kept) {
14539
+ tests = merged.cases;
14540
+ keptCases = merged.kept;
14541
+ if (!values.quiet) io2.err(`Kept the results of ${merged.kept.cases} test${merged.kept.cases === 1 ? "" : "s"} in ${merged.kept.files} file${merged.kept.files === 1 ? "" : "s"} the reports here do not have, read since ${merged.kept.since.slice(0, 10)}.`);
14542
+ }
14298
14543
  }
14299
14544
  let fromKept = false;
14300
14545
  if (values.trace && !tests) {
@@ -14308,16 +14553,18 @@ ${CHECK_USAGE}`);
14308
14553
  const kept2 = await readEditorStateFile(root, MEASUREMENTS_FILE);
14309
14554
  const stored = kept2 === null ? null : parseMeasurementStore(kept2);
14310
14555
  let measurements = stored ?? void 0;
14556
+ const read2 = [...ciMeasurements];
14311
14557
  if (values.metrics?.length) {
14312
- const read2 = [];
14313
14558
  try {
14314
14559
  for (const file of await reportFiles(values.metrics, io2.cwd, /\.json$/i, "measurement")) read2.push(...parseMetricsFile(await readFile10(resolve10(io2.cwd, file), "utf8"), file));
14315
14560
  } catch (error) {
14316
14561
  io2.err(error.code === "ENOENT" ? `Cannot read the measurements ${error.path}: no such file.` : error.message);
14317
14562
  return 2;
14318
14563
  }
14564
+ }
14565
+ if (read2.length) {
14319
14566
  measurements = mergeMeasurements(stored ?? [], read2);
14320
- await writeBeside(join13(root, MEASUREMENTS_FILE), serializeMeasurementStore(measurements));
14567
+ if (keepBeside) await writeBeside(join13(root, MEASUREMENTS_FILE), serializeMeasurementStore(measurements));
14321
14568
  }
14322
14569
  for (const [where2, path] of [[REVIEWS_FILE, join13(await mappingRoot(root), REVIEWS_FILE)], [REVIEWS_FILE2, join13(root, REVIEWS_FILE2)]]) {
14323
14570
  const reviewsText = await readFile10(path, "utf8").catch(() => null);
@@ -14362,13 +14609,29 @@ ${CHECK_USAGE}`);
14362
14609
  }
14363
14610
  const testSources = repository?.verifies?.length ? await boundTestSources(mappedFrom, repository.verifies) : void 0;
14364
14611
  const baseNodes = await baseModelNodes(root);
14365
- const result = runCheck(files, config, { sensors, repository, missingPaths, ...testSources ? { testSources } : {}, ...baseNodes ? { baseNodes } : {}, ...tests ? { tests } : {}, ...testsReadAt ? { testsReadAt } : {}, ...measurements ? { measurements } : {}, ...baseline ? { baseline } : {}, ...values.trigger ? { trigger: values.trigger } : {}, concerns: concernPacks(), ...others2 ? { others: others2 } : {} });
14366
- if (tests && !fromKept && (keep || !fromCi)) {
14612
+ const checkOptions = { sensors, repository, missingPaths, ...testSources ? { testSources } : {}, ...baseNodes ? { baseNodes } : {}, ...tests ? { tests } : {}, ...testsReadAt ? { testsReadAt } : {}, ...measurements ? { measurements } : {}, ...baseline ? { baseline } : {}, ...values.trigger ? { trigger: values.trigger } : {}, concerns: concernPacks(), ...others2 ? { others: others2 } : {} };
14613
+ let result = runCheck(files, config, checkOptions);
14614
+ if (values.adopt) {
14615
+ let adopted;
14616
+ try {
14617
+ adopted = adoptBaselines(config, result);
14618
+ } catch (error) {
14619
+ io2.err(`radical check --adopt: ${error.message}.`);
14620
+ return 2;
14621
+ }
14622
+ await writeFile5(configPath, serializeCheckConfig(adopted.config));
14623
+ result = runCheck(files, adopted.config, checkOptions);
14624
+ if (!values.quiet) {
14625
+ io2.err(`Adopted the first run's baselines into ${configPath}: ${adopted.baselines.length ? adopted.baselines.map((b) => `${b.id} max ${b.max}`).join(", ") : "no rule found anything"}; goals ${adopted.goals.length ? adopted.goals.map((g) => `${g.id} ${g.min}%`).join(", ") : "none measured"}. From now on only --ratchet lowers them. Commit it.`);
14626
+ if (adopted.notRun.length) io2.err(`Not run, so no baseline taken (give the test reports with --report, the measurements with --metrics): ${adopted.notRun.join(", ")}.`);
14627
+ }
14628
+ }
14629
+ if (tests && keepBeside && !fromKept && (keep || !fromCi)) {
14367
14630
  await writeBeside(join13(root, TEST_RESULTS_FILE), serializeTestResults(
14368
14631
  tests,
14369
14632
  keep?.reports ?? values.report ?? [],
14370
14633
  /* @__PURE__ */ new Date(),
14371
- keep ?? { commit: await headOf(root) ?? void 0 }
14634
+ keep ?? { commit: await headOf(root) ?? void 0, ...keptCases ? { kept: keptCases } : {} }
14372
14635
  ));
14373
14636
  }
14374
14637
  if (values.evidence && result.evidence) await writeBeside(resolve10(io2.cwd, values.evidence), JSON.stringify(result.evidence, null, 2) + "\n");
@@ -14424,7 +14687,9 @@ async function writeBeside(path, content) {
14424
14687
  if (error.code !== "EEXIST") throw error;
14425
14688
  });
14426
14689
  }
14427
- await writeFile5(path, content);
14690
+ const partial = join13(dir, `.${basename3(path)}.${process.pid}.tmp`);
14691
+ await writeFile5(partial, content);
14692
+ await rename4(partial, path);
14428
14693
  }
14429
14694
  function concernPacks() {
14430
14695
  const bundled = join13(dirname8(fileURLToPath2(import.meta.url)), "hub-catalogue");
@@ -14655,8 +14920,8 @@ ${HOOKS_USAGE}`);
14655
14920
  const launcher = launcherEnv?.endsWith(".sh") ? relative6(top, await realpath6(launcherEnv).catch(() => launcherEnv)) : null;
14656
14921
  const viaLauncher = launcher !== null && !launcher.startsWith("..") && !isAbsolute3(launcher);
14657
14922
  const command = viaLauncher ? `sh ${quote2(launcher)}` : viaNpx ? `npx -y ${cliPackage()}` : io2.cli ? `${io2.cli.node} ${quote2(inRepo ? fromTop : script)}` : io2.command ?? "radical";
14658
- const run2 = `${command} diff ${folderArg} --save-base --quiet </dev/null || true; ${command} check ${folderArg} --from-ci --quiet --detach </dev/null >/dev/null 2>&1 || true; ${command} federation fetch ${folderArg} --quiet --detach </dev/null >/dev/null 2>&1 || true`;
14659
- const line = inRepo && !viaLauncher ? `if [ -f ${quote2(fromTop)} ]; then ${run2}; else echo ${quote2(`radical hooks: ${fromTop} is not in this working tree, so the base of ${relative6(top, root) || "."} was not saved; build the CLI there, or install the hooks again.`)} >&2; fi` : run2;
14923
+ const run3 = `${command} diff ${folderArg} --save-base --quiet </dev/null || true; ${command} check ${folderArg} --from-ci --quiet --detach </dev/null >/dev/null 2>&1 || true; ${command} federation fetch ${folderArg} --quiet --detach </dev/null >/dev/null 2>&1 || true`;
14924
+ const line = inRepo && !viaLauncher ? `if [ -f ${quote2(fromTop)} ]; then ${run3}; else echo ${quote2(`radical hooks: ${fromTop} is not in this working tree, so the base of ${relative6(top, root) || "."} was not saved; build the CLI there, or install the hooks again.`)} >&2; fi` : run3;
14660
14925
  const written = [];
14661
14926
  const updated = [];
14662
14927
  const foreign = [];
@@ -15360,9 +15625,9 @@ ${HARDEN_USAGE}`);
15360
15625
  io2.out(bound === 0 ? said.join("\n") : `Not bound to scenario "${values.scenario}" (${said[0]?.split("\n")[0] ?? "no model"}): ${bind}`);
15361
15626
  return 0;
15362
15627
  }
15363
- const run2 = finding ? findingRun(finding, config, root) : testRun(values.test, config, root);
15364
- if (typeof run2 === "string") {
15365
- io2.err(run2);
15628
+ const run3 = finding ? findingRun(finding, config, root) : testRun(values.test, config, root);
15629
+ if (typeof run3 === "string") {
15630
+ io2.err(run3);
15366
15631
  return 2;
15367
15632
  }
15368
15633
  const top = git4(root, ["rev-parse", "--show-toplevel"]).stdout?.trim();
@@ -15384,7 +15649,7 @@ ${HARDEN_USAGE}`);
15384
15649
  io2.err(`No source file changed since ${base}: no fix to set back.`);
15385
15650
  return 2;
15386
15651
  }
15387
- io2.out(`Gate for ${run2.label}, base ${base}, ${changed.length} source file${changed.length === 1 ? "" : "s"} changed since:`);
15652
+ io2.out(`Gate for ${run3.label}, base ${base}, ${changed.length} source file${changed.length === 1 ? "" : "s"} changed since:`);
15388
15653
  for (const f of changed) io2.out(` ${f}`);
15389
15654
  let putBack;
15390
15655
  const interrupted = (signal) => {
@@ -15400,11 +15665,11 @@ ${HARDEN_USAGE}`);
15400
15665
  const signals = ["SIGINT", "SIGTERM", "SIGHUP"];
15401
15666
  for (const s2 of signals) process.on(s2, interrupted);
15402
15667
  try {
15403
- return await gate(run2, runs, io2, async () => {
15668
+ return await gate(run3, runs, io2, async () => {
15404
15669
  putBack = setBack(top, base, changed);
15405
15670
  try {
15406
- if (!await build(run2, "without the fix", io2)) return BUILD_FAILED;
15407
- return await runTest(run2, io2);
15671
+ if (!await build(run3, "without the fix", io2)) return BUILD_FAILED;
15672
+ return await runTest(run3, io2);
15408
15673
  } finally {
15409
15674
  const done = putBack;
15410
15675
  putBack = void 0;
@@ -15415,7 +15680,7 @@ ${HARDEN_USAGE}`);
15415
15680
  for (const s2 of signals) process.off(s2, interrupted);
15416
15681
  }
15417
15682
  }
15418
- async function gate(run2, runs, io2, withoutFix) {
15683
+ async function gate(run3, runs, io2, withoutFix) {
15419
15684
  const without2 = await withoutFix();
15420
15685
  if (without2 === BUILD_FAILED) return 2;
15421
15686
  if (without2 === 0) {
@@ -15423,15 +15688,15 @@ async function gate(run2, runs, io2, withoutFix) {
15423
15688
  return 1;
15424
15689
  }
15425
15690
  io2.out(`1. Without the fix: failed (exit ${without2}), as it should.`);
15426
- if (!await build(run2, "with the fix", io2)) return 2;
15427
- const withFix = await runTest(run2, io2);
15691
+ if (!await build(run3, "with the fix", io2)) return 2;
15692
+ const withFix = await runTest(run3, io2);
15428
15693
  if (withFix !== 0) {
15429
15694
  io2.out(`2. With the fix: failed (exit ${withFix}). \u2716`);
15430
15695
  return 1;
15431
15696
  }
15432
15697
  io2.out("2. With the fix: passed.");
15433
- if (run2.repeat) {
15434
- const code = await runTest({ ...run2, ...run2.repeat, args: run2.repeat.args.map((a2) => a2.replace("{runs}", String(runs))) }, { ...io2, out: () => {
15698
+ if (run3.repeat) {
15699
+ const code = await runTest({ ...run3, ...run3.repeat, args: run3.repeat.args.map((a2) => a2.replace("{runs}", String(runs))) }, { ...io2, out: () => {
15435
15700
  }, err: () => {
15436
15701
  } });
15437
15702
  if (code !== 0) {
@@ -15442,7 +15707,7 @@ async function gate(run2, runs, io2, withoutFix) {
15442
15707
  io2.out("The gate passed.");
15443
15708
  return 0;
15444
15709
  }
15445
- const codes = await Promise.all(Array.from({ length: runs }, () => runTest(run2, { ...io2, out: () => {
15710
+ const codes = await Promise.all(Array.from({ length: runs }, () => runTest(run3, { ...io2, out: () => {
15446
15711
  }, err: () => {
15447
15712
  } })));
15448
15713
  const failed = codes.filter((c) => c !== 0).length;
@@ -15547,8 +15812,8 @@ function setBack(root, base, files) {
15547
15812
  return putBack;
15548
15813
  }
15549
15814
  var BUILD_FAILED = -1;
15550
- async function build(run2, stage, io2) {
15551
- for (const step of run2.build ?? []) {
15815
+ async function build(run3, stage, io2) {
15816
+ for (const step of run3.build ?? []) {
15552
15817
  const line = [step.command, ...step.args].join(" ");
15553
15818
  io2.out(`Building ${stage}: ${line}`);
15554
15819
  let printed = "";
@@ -15566,9 +15831,9 @@ async function build(run2, stage, io2) {
15566
15831
  return true;
15567
15832
  }
15568
15833
  var running = /* @__PURE__ */ new Set();
15569
- function runTest(run2, io2) {
15834
+ function runTest(run3, io2) {
15570
15835
  return new Promise((done) => {
15571
- const child = spawn3(run2.command, run2.args, { cwd: run2.cwd, shell: process.platform === "win32" });
15836
+ const child = spawn3(run3.command, run3.args, { cwd: run3.cwd, shell: process.platform === "win32" });
15572
15837
  running.add(child);
15573
15838
  child.on("close", () => running.delete(child));
15574
15839
  child.stdout.on("data", (d) => {
@@ -15578,7 +15843,7 @@ function runTest(run2, io2) {
15578
15843
  for (const line of d.toString().split("\n")) if (line.trim()) io2.err(` ${line}`);
15579
15844
  });
15580
15845
  child.on("error", (error) => {
15581
- io2.err(`${run2.command}: ${error.message}`);
15846
+ io2.err(`${run3.command}: ${error.message}`);
15582
15847
  done(2);
15583
15848
  });
15584
15849
  child.on("close", (code) => done(code ?? 1));
@@ -15729,13 +15994,13 @@ function rounds(dir) {
15729
15994
  if (!existsSync7(dir)) return [];
15730
15995
  return readdirSync3(dir).map((d) => join18(dir, d, "round.json")).filter((f) => existsSync7(f)).map((f) => JSON.parse(readFileSync5(f, "utf8"))).sort((a2, b) => a2.from - b.from);
15731
15996
  }
15732
- function portsOf(explore, run2) {
15733
- const nn2 = run2 % 100;
15997
+ function portsOf(explore, run3) {
15998
+ const nn2 = run3 % 100;
15734
15999
  return { app: explore.ports + nn2, hub: explore.ports + 100 + nn2, other: explore.ports + 200 + nn2 };
15735
16000
  }
15736
- function serveCommands(settings, round2, entry) {
16001
+ function serveCommands(settings, round4, entry) {
15737
16002
  return settings.explore.serve.map((serve) => {
15738
- const fill = (part) => part.replace(/\{port\}/g, String(entry.ports.app)).replace(/\{hubPort\}/g, String(entry.ports.hub)).replace(/\{otherPort\}/g, String(entry.ports.other)).replace(/\{build\}/g, join18(round2, "build")).replace(/\{run\}/g, entry.folder);
16003
+ const fill = (part) => part.replace(/\{port\}/g, String(entry.ports.app)).replace(/\{hubPort\}/g, String(entry.ports.hub)).replace(/\{otherPort\}/g, String(entry.ports.other)).replace(/\{build\}/g, join18(round4, "build")).replace(/\{run\}/g, entry.folder);
15739
16004
  return { cwd: resolve16(settings.root, serve.cwd ?? "."), command: serve.command.map(fill), port: entry.ports[serve.port] };
15740
16005
  });
15741
16006
  }
@@ -15788,12 +16053,12 @@ ${r.stdout ?? ""}${r.stderr ?? ""}
15788
16053
  cpSync(source, join18(dir, "build", copyName), { recursive: true });
15789
16054
  }
15790
16055
  const runs = [];
15791
- for (let run2 = from; run2 <= to2; run2++) {
15792
- const folder = join18(dir, `run-${run2}`);
16056
+ for (let run3 = from; run3 <= to2; run3++) {
16057
+ const folder = join18(dir, `run-${run3}`);
15793
16058
  mkdirSync4(folder, { recursive: true });
15794
- runs.push({ run: run2, area: areas[run2 - from], folder, ports: portsOf(explore, run2), verified: [] });
16059
+ runs.push({ run: run3, area: areas[run3 - from], folder, ports: portsOf(explore, run3), verified: [] });
15795
16060
  }
15796
- const round2 = { round: name, from, to: to2, commit, ...since ? { since } : {}, created: (/* @__PURE__ */ new Date()).toISOString(), runs };
16061
+ const round4 = { round: name, from, to: to2, commit, ...since ? { since } : {}, created: (/* @__PURE__ */ new Date()).toISOString(), runs };
15797
16062
  const commits = since ? git5(root, ["log", "--oneline", "--no-decorate", `${since}..HEAD`]).stdout.trim().split("\n").filter(Boolean) : [];
15798
16063
  const modelAreas = since && explore.model ? await changedAreas(root, explore.model, since) : [];
15799
16064
  const open4 = readFindings(resolve16(root, settings.findings)).filter((f) => f.status === "open" || f.status === "question" || f.status === "hardened");
@@ -15860,7 +16125,7 @@ ${r.stdout ?? ""}${r.stderr ?? ""}
15860
16125
  ""
15861
16126
  ].join("\n"));
15862
16127
  }
15863
- writeFileSync3(join18(dir, "round.json"), JSON.stringify(round2, null, 2) + "\n");
16128
+ writeFileSync3(join18(dir, "round.json"), JSON.stringify(round4, null, 2) + "\n");
15864
16129
  io2.out(`Prepared runs ${from}\u2013${to2} at ${commit} in ${relative10(io2.cwd, dir) || "."}:`);
15865
16130
  for (const entry of runs) io2.out(` run ${entry.run}: port ${entry.ports.app}, ${entry.area ?? "area of its choice"} \u2014 ${relative10(io2.cwd, join18(entry.folder, "PROMPT.md"))}`);
15866
16131
  if (modelAreas.length) io2.out(`Candidate areas from the model:
@@ -15886,25 +16151,25 @@ async function changedAreas(root, model, since) {
15886
16151
  return [...byArea].sort((a2, b) => count(b[1]) - count(a2[1])).map(([area, c]) => `${area}: ${[c.added.length && `${c.added.length} added`, c.changed.length && `${c.changed.length} changed`, c.removed.length && `${c.removed.length} removed`].filter(Boolean).join(", ")} \u2014 ${[...c.changed, ...c.added, ...c.removed].slice(0, 6).join(", ")}${count(c) > 6 ? ", \u2026" : ""}`);
15887
16152
  }
15888
16153
  var count = (c) => c.added.length + c.changed.length + c.removed.length;
15889
- var runFolder = (roundsDir, round2, entry) => join18(roundsDir, round2.round, `run-${entry.run}`);
15890
- function findRun(settings, run2) {
16154
+ var runFolder = (roundsDir, round4, entry) => join18(roundsDir, round4.round, `run-${entry.run}`);
16155
+ function findRun(settings, run3) {
15891
16156
  const roundsDir = resolve16(settings.root, settings.explore.rounds);
15892
- for (const round2 of rounds(roundsDir)) {
15893
- const entry = round2.runs.find((r) => r.run === run2);
16157
+ for (const round4 of rounds(roundsDir)) {
16158
+ const entry = round4.runs.find((r) => r.run === run3);
15894
16159
  if (entry) {
15895
- entry.folder = runFolder(roundsDir, round2, entry);
15896
- return { dir: join18(roundsDir, round2.round), round: round2, entry };
16160
+ entry.folder = runFolder(roundsDir, round4, entry);
16161
+ return { dir: join18(roundsDir, round4.round), round: round4, entry };
15897
16162
  }
15898
16163
  }
15899
16164
  return void 0;
15900
16165
  }
15901
- async function verify(settings, run2, scripts, io2) {
15902
- const found = findRun(settings, run2);
16166
+ async function verify(settings, run3, scripts, io2) {
16167
+ const found = findRun(settings, run3);
15903
16168
  if (!found) {
15904
- io2.err(`No round has run ${run2}.`);
16169
+ io2.err(`No round has run ${run3}.`);
15905
16170
  return 2;
15906
16171
  }
15907
- const { dir, round: round2, entry } = found;
16172
+ const { dir, round: round4, entry } = found;
15908
16173
  const absent = scripts.map((line) => line.trim().split(/\s+/)[0]).find((script) => !existsSync7(resolve16(entry.folder, script)));
15909
16174
  if (absent !== void 0) {
15910
16175
  io2.err(`No script ${absent} in ${relative10(io2.cwd, entry.folder)}: nothing was run.`);
@@ -15927,7 +16192,7 @@ async function verify(settings, run2, scripts, io2) {
15927
16192
  }
15928
16193
  if (servers.length) {
15929
16194
  const ports = servers.map((s2) => s2.port);
15930
- io2.out(`Serving run ${run2}'s build on port${ports.length === 1 ? "" : "s"} ${ports.length === 1 ? ports[0] : `${ports.slice(0, -1).join(", ")} and ${ports[ports.length - 1]}`}.`);
16195
+ io2.out(`Serving run ${run3}'s build on port${ports.length === 1 ? "" : "s"} ${ports.length === 1 ? ports[0] : `${ports.slice(0, -1).join(", ")} and ${ports[ports.length - 1]}`}.`);
15931
16196
  }
15932
16197
  const shown3 = [];
15933
16198
  const notShown = [];
@@ -15946,7 +16211,7 @@ async function verify(settings, run2, scripts, io2) {
15946
16211
  entry.verified.push({ at: (/* @__PURE__ */ new Date()).toISOString(), script: line, exit: r.status ?? -1, ...judged.shown !== void 0 ? { shown: judged.shown } : {}, ...says2.length ? { says: says2 } : {} });
15947
16212
  }
15948
16213
  if (shown3.length || notShown.length) io2.out(`Shows the bug: ${shown3.join(", ") || "none"}. Does not: ${notShown.join(", ") || "none"}.`);
15949
- writeFileSync3(join18(dir, "round.json"), JSON.stringify(round2, null, 2) + "\n");
16214
+ writeFileSync3(join18(dir, "round.json"), JSON.stringify(round4, null, 2) + "\n");
15950
16215
  return 0;
15951
16216
  } finally {
15952
16217
  for (const server of started) {
@@ -16459,10 +16724,10 @@ function askServer(entry, cwd, place, timeoutMs) {
16459
16724
  let stdout = "";
16460
16725
  let stderr = "";
16461
16726
  let version;
16462
- let settled = false;
16727
+ let settled2 = false;
16463
16728
  const finish = (answer) => {
16464
- if (settled) return;
16465
- settled = true;
16729
+ if (settled2) return;
16730
+ settled2 = true;
16466
16731
  clearTimeout(timer);
16467
16732
  child.stdin.end();
16468
16733
  child.kill();
@@ -16588,6 +16853,13 @@ async function statusCommand(options, io2) {
16588
16853
  const fromTop = relative12(top, folder).replace(/\\/g, "/");
16589
16854
  if (await hooksSaveBase(hooksDir, fromTop)) ok("the git hooks save its base for Studio's Changes on branch");
16590
16855
  else warn(`the git hooks do not save its base for Studio's Changes on branch: radical hooks install ${shown2(folder, place)}`);
16856
+ const fetch2 = parseCiFetch(await readEditorStateFile(folder, CI_FETCH_FILE).catch(() => null) ?? "");
16857
+ if (fetch2) {
16858
+ const when = `the last fetch from CI (${formatAge(Date.now() - Date.parse(fetch2.at))} ago)`;
16859
+ const problem = ciFetchProblem(fetch2);
16860
+ if (problem) warn(`${when} found no test results: ${problem.replace(/^radical check --from-ci: /, "").replace(/\.$/, "")}. ${CI_ARTIFACTS_HINT}`);
16861
+ else ok(`${when}: ${fetch2.message}`);
16862
+ }
16591
16863
  }
16592
16864
  }
16593
16865
  }
@@ -16616,10 +16888,10 @@ async function statusCommand(options, io2) {
16616
16888
  }
16617
16889
  configured++;
16618
16890
  const before = problems;
16619
- const run2 = expanded(entry, place);
16620
- const command = isAbsolute5(run2.command) ? existsSync10(run2.command) ? run2.command : null : onPath(run2.command, place, entry.env?.PATH);
16891
+ const run3 = expanded(entry, place);
16892
+ const command = isAbsolute5(run3.command) ? existsSync10(run3.command) ? run3.command : null : onPath(run3.command, place, entry.env?.PATH);
16621
16893
  const launcher = launcherPath(entry, client, place);
16622
- if (!command && run2.command !== launcherOf(run2)) fail(`${where2}: its command ${entry.command} is not there${entry.env?.PATH ? ` (PATH ${entry.env.PATH})` : ""}: radical setup writes it again`);
16894
+ if (!command && run3.command !== launcherOf(run3)) fail(`${where2}: its command ${entry.command} is not there${entry.env?.PATH ? ` (PATH ${entry.env.PATH})` : ""}: radical setup writes it again`);
16623
16895
  if (launcher && !existsSync10(launcher)) fail(`${where2}: its launcher ${shown2(launcher, place)} is not there: download it from https://radical.tools/${launcher.endsWith(".cmd") ? "radical.cmd" : "radical.sh"}`);
16624
16896
  if (!servesReal) fail(`${where2}: names no --folder`);
16625
16897
  else if (!existsSync10(resolve18(servesReal, "radical.md")) && !folder) fail(`${where2}: serves ${shown2(servesReal, place)}, which holds no model`);
@@ -16662,7 +16934,7 @@ ${problems} problem${problems > 1 ? "s" : ""} found.` : "\nNothing is broken.");
16662
16934
  init_define_RADICAL_BUILD();
16663
16935
  import { execFile as execFile7 } from "child_process";
16664
16936
  import { existsSync as existsSync11 } from "fs";
16665
- import { mkdir as mkdir10, readFile as readFile15, rename as rename4, writeFile as writeFile10 } from "fs/promises";
16937
+ import { mkdir as mkdir10, readFile as readFile15, rename as rename5, writeFile as writeFile10 } from "fs/promises";
16666
16938
  import { dirname as dirname17, join as join21, relative as relative13, resolve as resolve19 } from "path";
16667
16939
  import { promisify as promisify7 } from "util";
16668
16940
  var exec7 = promisify7(execFile7);
@@ -16683,7 +16955,7 @@ async function moveToRadical(root, parts2) {
16683
16955
  for (const part of parts2) {
16684
16956
  const to2 = MOVES[part];
16685
16957
  await mkdir10(dirname17(join21(root, to2)), { recursive: true });
16686
- await git6("mv", part, to2).catch(() => rename4(join21(root, part), join21(root, to2)));
16958
+ await git6("mv", part, to2).catch(() => rename5(join21(root, part), join21(root, to2)));
16687
16959
  said.push(`moved ${part} to ${to2}`);
16688
16960
  }
16689
16961
  if (!existsSync11(join21(root, RADICAL_DIR, ".gitignore"))) {
@@ -16692,7 +16964,7 @@ async function moveToRadical(root, parts2) {
16692
16964
  }
16693
16965
  const model = join21(root, MODEL_FOLDER);
16694
16966
  if (parts2.includes(OLD_MODEL_FOLDER) && existsSync11(join21(model, OLD_STATE_DIR)) && !existsSync11(join21(model, STATE_DIR))) {
16695
- await rename4(join21(model, OLD_STATE_DIR), join21(model, STATE_DIR));
16967
+ await rename5(join21(model, OLD_STATE_DIR), join21(model, STATE_DIR));
16696
16968
  said.push(`renamed the model's ${OLD_STATE_DIR}/ to ${STATE_DIR}/`);
16697
16969
  }
16698
16970
  const plan = join21(root, CRUCIBLE_FILE);
@@ -16750,13 +17022,24 @@ async function pointAtModel(root, from, to2) {
16750
17022
 
16751
17023
  // src/setup.ts
16752
17024
  var exec8 = promisify8(execFile8);
17025
+ var NOT_CODE = /^(\.|docs?\/|LICEN[CS]E|COPYING|NOTICE|AUTHORS|CODEOWNERS)|\.(md|markdown|txt|rst|adoc)$/i;
17026
+ async function hasCode(root, folder) {
17027
+ const inModel = (path) => !relative14(folder, resolve20(root, path)).startsWith("..");
17028
+ const listed = await exec8("git", ["ls-files", "--cached", "--others", "--exclude-standard"], { cwd: root, windowsHide: true, maxBuffer: 64 * 1024 * 1024 }).then(({ stdout }) => stdout.split("\n").filter(Boolean), () => null);
17029
+ const files = listed ?? (await readdir5(root, { withFileTypes: true }).catch(() => [])).map((e2) => e2.name + (e2.isDirectory() ? "/" : ""));
17030
+ return files.some((path) => !NOT_CODE.test(path) && !inModel(path));
17031
+ }
16753
17032
  var METAMODELS = { radical: builtInGovernanceMetamodel, c4: builtInC4Metamodel };
16754
17033
  var SETUP_USAGE = `Usage: radical setup [folder] [options]
16755
17034
  radical setup --status [folder] [--no-start] [--timeout <s>]
16756
17035
 
16757
17036
  Connects your coding agents to a Radical model folder, step by step:
16758
17037
  1. Node checks the version
16759
- 2. Folder a missing or empty folder becomes a new model
17038
+ 2. Folder a missing or empty folder becomes a new model, with the
17039
+ check.json its gate starts from: in a repository without
17040
+ code every rule an error and every goal at 100%; in one with
17041
+ code every rule an error, waiting for the baselines of its
17042
+ first run (radical check --adopt)
16760
17043
  3. Other models
16761
17044
  the models this one depends on (a federation): their names,
16762
17045
  repositories, model folders and versions go into deps.json,
@@ -16981,6 +17264,15 @@ ${SETUP_USAGE}`);
16981
17264
  }
16982
17265
  io2.out(` + started a new model (${metamodel} metamodel) in ${folderArg}`);
16983
17266
  }
17267
+ if (!existsSync12(resolve20(folder, CHECK_CONFIG_FILE))) {
17268
+ const code2 = await hasCode(await repositoryRoot(existsSync12(folder) ? folder : io2.cwd) ?? io2.cwd, folder);
17269
+ const what = code2 ? "every rule an error, waiting for the baselines of its first run: radical check --adopt takes them once the model describes the code" : "every rule an error and every goal at 100%";
17270
+ if (dry) io2.out(` would write ${CHECK_CONFIG_FILE}: ${what}`);
17271
+ else {
17272
+ await writeFile11(resolve20(folder, CHECK_CONFIG_FILE), serializeCheckConfig(code2 ? existingCodeCheckConfig2() : strictCheckConfig2()));
17273
+ io2.out(` + ${CHECK_CONFIG_FILE}: ${what}`);
17274
+ }
17275
+ }
16984
17276
  } else if (!existsSync12(resolve20(folder, "radical.md"))) {
16985
17277
  io2.err(`radical setup: ${folderArg} holds other files and no radical.md, so it is not a Radical model folder. Name an empty or new folder, or one with a model.`);
16986
17278
  return 2;
@@ -17098,8 +17390,8 @@ Next: restart the agents you connected (quit Claude Desktop and Cursor fully, ru
17098
17390
 
17099
17391
  // src/sense.ts
17100
17392
  init_define_RADICAL_BUILD();
17101
- import { mkdir as mkdir12, readFile as readFile19, rm as rm6, stat as stat11, writeFile as writeFile12 } from "fs/promises";
17102
- import { basename as basename5, dirname as dirname19, join as join23, resolve as resolve23 } from "path";
17393
+ import { mkdir as mkdir13, readFile as readFile21, rm as rm6, stat as stat12, writeFile as writeFile13 } from "fs/promises";
17394
+ import { basename as basename5, dirname as dirname20, join as join25, resolve as resolve24 } from "path";
17103
17395
  import { parseArgs as parseArgs13 } from "util";
17104
17396
 
17105
17397
  // src/sensors/registry.ts
@@ -17122,11 +17414,11 @@ var commandAdapter = {
17122
17414
  if (!args.length) throw new Error("no command after --");
17123
17415
  const name = typeof options.name === "string" && options.name ? options.name : "command";
17124
17416
  const started = process.hrtime.bigint();
17125
- const code = await new Promise((resolve27, reject) => {
17417
+ const code = await new Promise((resolve28, reject) => {
17126
17418
  const child = spawn6(args[0], args.slice(1), { cwd, stdio: ["ignore", "pipe", "inherit"], shell: process.platform === "win32" });
17127
17419
  child.stdout?.pipe(process.stderr);
17128
17420
  child.on("error", (error) => reject(new Error(`cannot run ${args[0]}: ${error.message}`)));
17129
- child.on("close", (status, signal) => resolve27(status ?? (signal ? 128 : 1)));
17421
+ child.on("close", (status, signal) => resolve28(status ?? (signal ? 128 : 1)));
17130
17422
  });
17131
17423
  const seconds = Number(process.hrtime.bigint() - started) / 1e9;
17132
17424
  return [
@@ -17137,6 +17429,296 @@ var commandAdapter = {
17137
17429
  fixture: { args: [process.execPath, "-e", "process.exit(3)"], options: { name: "fixture" } }
17138
17430
  };
17139
17431
 
17432
+ // src/sensors/github-actions.ts
17433
+ init_define_RADICAL_BUILD();
17434
+ import { spawn as spawn7 } from "child_process";
17435
+ var GH = "gh";
17436
+ var DAYS = 30;
17437
+ var BRANCH = "main";
17438
+ function runGh(command, base, args, cwd) {
17439
+ return new Promise((done, fail) => {
17440
+ const child = spawn7(command, [...base, ...args], { cwd, stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32" });
17441
+ let stdout = "";
17442
+ let stderr = "";
17443
+ child.stdout.setEncoding("utf8").on("data", (d) => {
17444
+ stdout += d;
17445
+ });
17446
+ child.stderr.setEncoding("utf8").on("data", (d) => {
17447
+ stderr += d;
17448
+ });
17449
+ child.on("error", (error) => fail(new Error(`cannot run ${command}: ${error.message}${command === GH ? " (install the GitHub CLI, https://cli.github.com, and sign in with gh auth login)" : ""}`)));
17450
+ child.on("close", (status, signal) => done({ code: status ?? (signal ? 128 : 1), stdout, stderr }));
17451
+ });
17452
+ }
17453
+ function jsonValues(text3) {
17454
+ const out = [];
17455
+ let depth = 0;
17456
+ let start = -1;
17457
+ let inString = false;
17458
+ let escaped = false;
17459
+ for (let i = 0; i < text3.length; i++) {
17460
+ const ch = text3[i];
17461
+ if (inString) {
17462
+ if (escaped) escaped = false;
17463
+ else if (ch === "\\") escaped = true;
17464
+ else if (ch === '"') inString = false;
17465
+ continue;
17466
+ }
17467
+ if (ch === '"') {
17468
+ inString = true;
17469
+ if (start < 0) start = i;
17470
+ continue;
17471
+ }
17472
+ if (ch === "{" || ch === "[") {
17473
+ if (depth === 0) start = i;
17474
+ depth++;
17475
+ continue;
17476
+ }
17477
+ if (ch === "}" || ch === "]") {
17478
+ depth--;
17479
+ if (depth === 0 && start >= 0) {
17480
+ out.push(JSON.parse(text3.slice(start, i + 1)));
17481
+ start = -1;
17482
+ }
17483
+ continue;
17484
+ }
17485
+ if (depth === 0 && /\s/.test(ch) && start >= 0) {
17486
+ out.push(JSON.parse(text3.slice(start, i)));
17487
+ start = -1;
17488
+ continue;
17489
+ }
17490
+ if (depth === 0 && !/\s/.test(ch) && start < 0) start = i;
17491
+ }
17492
+ if (start >= 0) out.push(JSON.parse(text3.slice(start)));
17493
+ return out;
17494
+ }
17495
+ var httpStatus = (r) => {
17496
+ const m = /\(HTTP (\d{3})\)/.exec(r.stderr);
17497
+ return m ? Number(m[1]) : void 0;
17498
+ };
17499
+ var time = (iso) => iso ? Date.parse(iso) : NaN;
17500
+ function percentile(values, p) {
17501
+ const v = [...values].sort((a2, b) => a2 - b);
17502
+ const at = (v.length - 1) * p;
17503
+ const lo = Math.floor(at);
17504
+ const hi2 = Math.ceil(at);
17505
+ return v[lo] + (v[hi2] - v[lo]) * (at - lo);
17506
+ }
17507
+ var round2 = (n, digits) => Math.round(n * 10 ** digits) / 10 ** digits;
17508
+ function settled(runs) {
17509
+ const counted = runs.filter((r) => !(r.status === "completed" && (r.conclusion === "cancelled" || r.conclusion === "skipped")));
17510
+ return counted.length && counted.every((r) => r.status === "completed") ? counted : void 0;
17511
+ }
17512
+ function bySha(runs) {
17513
+ const groups = /* @__PURE__ */ new Map();
17514
+ for (const r of runs) {
17515
+ if (!r.head_sha) continue;
17516
+ groups.set(r.head_sha, [...groups.get(r.head_sha) ?? [], r]);
17517
+ }
17518
+ return [...groups.values()];
17519
+ }
17520
+ var matchesWorkflow = (run3, names) => !names.length || names.some((w) => run3.name === w || run3.path === w || (run3.path ?? "").endsWith(`/${w}`));
17521
+ function runValues(runs, branch) {
17522
+ const values = [];
17523
+ const pr2 = [];
17524
+ for (const group of bySha(runs.filter((r) => r.event === "pull_request"))) {
17525
+ const done = settled(group);
17526
+ if (!done) continue;
17527
+ const start = Math.min(...done.map((r) => time(r.run_started_at ?? r.created_at)));
17528
+ const end = Math.max(...done.map((r) => time(r.updated_at)));
17529
+ if (Number.isFinite(start) && Number.isFinite(end) && end >= start) pr2.push((end - start) / 6e4);
17530
+ }
17531
+ if (pr2.length) {
17532
+ values.push({ metric: "ci.pr.duration.p50", value: round2(percentile(pr2, 0.5), 2), unit: "min" });
17533
+ values.push({ metric: "ci.pr.duration.p90", value: round2(percentile(pr2, 0.9), 2), unit: "min" });
17534
+ }
17535
+ const commits = bySha(runs.filter((r) => r.event === "push" && r.head_branch === branch)).map(settled).filter((g) => !!g);
17536
+ if (commits.length) {
17537
+ const green = commits.filter((g) => g.every((r) => r.conclusion === "success")).length;
17538
+ values.push({ metric: "ci.main.success.rate", value: round2(green / commits.length * 100, 1), unit: "%" });
17539
+ }
17540
+ const completed = runs.filter((r) => r.status === "completed");
17541
+ if (completed.length) {
17542
+ const reruns = completed.filter((r) => (r.run_attempt ?? 1) > 1).length;
17543
+ values.push({ metric: "ci.rerun.rate", value: round2(reruns / completed.length * 100, 1), unit: "%" });
17544
+ }
17545
+ values.push({ metric: "ci.runs", value: completed.length });
17546
+ return values;
17547
+ }
17548
+ function branchRules(rules, protection) {
17549
+ const checks = /* @__PURE__ */ new Set();
17550
+ let reviews = 0;
17551
+ for (const rule of rules.flatMap((page) => Array.isArray(page) ? page : [page])) {
17552
+ if (rule?.type === "required_status_checks") {
17553
+ for (const c of rule.parameters?.required_status_checks ?? []) if (typeof c?.context === "string") checks.add(c.context);
17554
+ } else if (rule?.type === "pull_request") {
17555
+ const n2 = rule.parameters?.required_approving_review_count;
17556
+ if (typeof n2 === "number") reviews = Math.max(reviews, n2);
17557
+ }
17558
+ }
17559
+ const p = protection;
17560
+ for (const c of p?.required_status_checks?.contexts ?? []) if (typeof c === "string") checks.add(c);
17561
+ for (const c of p?.required_status_checks?.checks ?? []) if (typeof c?.context === "string") checks.add(c.context);
17562
+ const n = p?.required_pull_request_reviews?.required_approving_review_count;
17563
+ if (typeof n === "number") reviews = Math.max(reviews, n);
17564
+ return { checks: checks.size, reviews };
17565
+ }
17566
+ var option = (v) => typeof v === "string" && v.trim() ? v.trim() : void 0;
17567
+ var run2 = (o) => ({
17568
+ workflow_id: 0,
17569
+ run_number: o.id,
17570
+ status: "completed",
17571
+ conclusion: "success",
17572
+ run_attempt: 1,
17573
+ ...o
17574
+ });
17575
+ var FIXTURE_RUNS = [
17576
+ run2({ id: 101, name: "CI", path: ".github/workflows/ci.yml", event: "pull_request", head_branch: "feat/cart", head_sha: "a1", run_started_at: "2026-11-20T10:00:00Z", created_at: "2026-11-20T10:00:00Z", updated_at: "2026-11-20T10:08:00Z" }),
17577
+ run2({ id: 102, name: "Lint", path: ".github/workflows/lint.yml", event: "pull_request", head_branch: "feat/cart", head_sha: "a1", run_started_at: "2026-11-20T10:00:30Z", created_at: "2026-11-20T10:00:30Z", updated_at: "2026-11-20T10:03:00Z" }),
17578
+ run2({ id: 103, name: "CI", path: ".github/workflows/ci.yml", event: "pull_request", head_branch: "feat/cart", head_sha: "a2", run_started_at: "2026-11-20T11:00:00Z", created_at: "2026-11-20T11:00:00Z", updated_at: "2026-11-20T11:12:00Z" }),
17579
+ run2({ id: 104, name: "E2E", path: ".github/workflows/e2e.yml", event: "pull_request", head_branch: "feat/cart", head_sha: "a2", run_attempt: 2, run_started_at: "2026-11-20T11:01:00Z", created_at: "2026-11-20T11:00:10Z", updated_at: "2026-11-20T11:20:00Z" }),
17580
+ run2({ id: 105, name: "CI", path: ".github/workflows/ci.yml", event: "pull_request", head_branch: "fix/tax", head_sha: "a3", run_started_at: "2026-11-21T12:00:00Z", created_at: "2026-11-21T12:00:00Z", updated_at: "2026-11-21T12:05:00Z" }),
17581
+ run2({ id: 106, name: "CI", path: ".github/workflows/ci.yml", event: "pull_request", head_branch: "fix/tax", head_sha: "a3", conclusion: "cancelled", run_started_at: "2026-11-21T11:58:00Z", created_at: "2026-11-21T11:58:00Z", updated_at: "2026-11-21T12:30:00Z" }),
17582
+ run2({ id: 107, name: "CI", path: ".github/workflows/ci.yml", event: "pull_request", head_branch: "fix/tax", head_sha: "a4", status: "in_progress", conclusion: null, run_started_at: "2026-11-24T08:00:00Z", created_at: "2026-11-24T08:00:00Z", updated_at: "2026-11-24T08:02:00Z" }),
17583
+ run2({ id: 201, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "main", head_sha: "m1", run_started_at: "2026-11-20T13:00:00Z", created_at: "2026-11-20T13:00:00Z", updated_at: "2026-11-20T13:09:00Z" }),
17584
+ run2({ id: 202, name: "Deploy", path: ".github/workflows/deploy.yml", event: "push", head_branch: "main", head_sha: "m1", run_started_at: "2026-11-20T13:00:05Z", created_at: "2026-11-20T13:00:05Z", updated_at: "2026-11-20T13:04:00Z" }),
17585
+ run2({ id: 203, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "main", head_sha: "m2", conclusion: "failure", run_started_at: "2026-11-21T09:00:00Z", created_at: "2026-11-21T09:00:00Z", updated_at: "2026-11-21T09:07:00Z" }),
17586
+ run2({ id: 204, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "main", head_sha: "m3", run_started_at: "2026-11-22T09:00:00Z", created_at: "2026-11-22T09:00:00Z", updated_at: "2026-11-22T09:08:00Z" }),
17587
+ run2({ id: 205, name: "Deploy", path: ".github/workflows/deploy.yml", event: "push", head_branch: "main", head_sha: "m3", conclusion: "cancelled", run_started_at: "2026-11-22T09:00:05Z", created_at: "2026-11-22T09:00:05Z", updated_at: "2026-11-22T09:01:00Z" }),
17588
+ run2({ id: 206, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "main", head_sha: "m4", conclusion: "cancelled", run_started_at: "2026-11-22T10:00:00Z", created_at: "2026-11-22T10:00:00Z", updated_at: "2026-11-22T10:01:00Z" }),
17589
+ run2({ id: 207, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "main", head_sha: "m5", run_attempt: 2, run_started_at: "2026-11-23T09:20:00Z", created_at: "2026-11-23T09:00:00Z", updated_at: "2026-11-23T09:29:00Z" }),
17590
+ run2({ id: 208, name: "CI", path: ".github/workflows/ci.yml", event: "push", head_branch: "feat/cart", head_sha: "a1", conclusion: "failure", run_started_at: "2026-11-20T09:50:00Z", created_at: "2026-11-20T09:50:00Z", updated_at: "2026-11-20T09:55:00Z" })
17591
+ ];
17592
+ var FIXTURE_ANSWERS = {
17593
+ "repo view": { out: "acme/shop" },
17594
+ "actions/runs": { pages: [
17595
+ { total_count: FIXTURE_RUNS.length, workflow_runs: FIXTURE_RUNS.slice(0, 8) },
17596
+ { total_count: FIXTURE_RUNS.length, workflow_runs: FIXTURE_RUNS.slice(8) }
17597
+ ] },
17598
+ "rules/branches/": { pages: [[
17599
+ { type: "deletion", ruleset_source_type: "Repository", ruleset_source: "acme/shop", ruleset_id: 42 },
17600
+ { type: "required_status_checks", ruleset_source_type: "Repository", ruleset_source: "acme/shop", ruleset_id: 42, parameters: { strict_required_status_checks_policy: true, required_status_checks: [{ context: "CI / test", integration_id: 15368 }, { context: "Lint" }] } },
17601
+ { type: "pull_request", ruleset_source_type: "Organization", ruleset_source: "acme", ruleset_id: 7, parameters: { required_approving_review_count: 1, dismiss_stale_reviews_on_push: true, require_code_owner_review: false, require_last_push_approval: false, required_review_thread_resolution: false } }
17602
+ ]] },
17603
+ "/protection": { out: {
17604
+ url: "https://api.github.com/repos/acme/shop/branches/main/protection",
17605
+ required_status_checks: { strict: true, contexts: ["CI / test", "E2E"], checks: [{ context: "CI / test", app_id: 15368 }, { context: "E2E", app_id: 15368 }] },
17606
+ required_pull_request_reviews: { dismiss_stale_reviews: false, require_code_owner_reviews: false, required_approving_review_count: 2 },
17607
+ enforce_admins: { enabled: false }
17608
+ } }
17609
+ };
17610
+ var FIXTURE_GH = `import { appendFileSync, readFileSync } from 'node:fs'
17611
+ const args = process.argv.slice(2)
17612
+ appendFileSync('gh-calls.log', JSON.stringify(args) + '\\n')
17613
+ const line = args.join(' ')
17614
+ const answers = JSON.parse(readFileSync('gh-answers.json', 'utf8'))
17615
+ const found = Object.entries(answers).find(([pattern]) => line.includes(pattern))
17616
+ if (!found) { process.stderr.write('gh: no answer for ' + line + '\\n'); process.exit(1) }
17617
+ const answer = found[1]
17618
+ if (answer.status) {
17619
+ process.stdout.write(JSON.stringify({ message: answer.message, status: String(answer.status) }))
17620
+ process.stderr.write('gh: ' + answer.message + ' (HTTP ' + answer.status + ')\\n')
17621
+ process.exit(1)
17622
+ }
17623
+ if (answer.pages) process.stdout.write(answer.pages.map((p) => JSON.stringify(p, null, 2)).join(''))
17624
+ else process.stdout.write(typeof answer.out === 'string' ? answer.out + '\\n' : JSON.stringify(answer.out))
17625
+ `;
17626
+ var githubActionsAdapter = {
17627
+ name: "github-actions",
17628
+ description: "reads a repository's GitHub Actions runs and branch rules with the GitHub CLI (gh): pipeline time, success, reruns, required checks",
17629
+ usage: `radical sense github-actions [--repo <owner/name>] [--branch <name>] [--days <n>] [--workflow <name>]\u2026 [--gh <command>]
17630
+
17631
+ --repo <owner/name> the repository (default: the one gh finds in the working
17632
+ directory, gh repo view)
17633
+ --branch <name> the branch that is pushed to and protected (default: ${BRANCH})
17634
+ --days <n> the runs created in the last n days (default: ${DAYS};
17635
+ GitHub lists at most 1000 runs)
17636
+ --workflow <name> only the runs of this workflow, by its name or its file
17637
+ (ci.yml); repeat for more (default: every workflow)
17638
+ --gh <command> the command that runs the GitHub CLI (default: ${GH}); it
17639
+ must be signed in (gh auth login, or GH_TOKEN)
17640
+ Measures, with no labels:
17641
+ ci.pr.duration.p50, ci.pr.duration.p90 (min): the wall time of one pull
17642
+ request commit, from the first start to the last end of its runs (event
17643
+ pull_request, by head commit), over the commits whose runs completed
17644
+ ci.main.success.rate (%): the share of the commits pushed to the branch
17645
+ whose completed runs all succeeded
17646
+ ci.rerun.rate (%): the share of completed runs that ran more than once
17647
+ ci.runs: the completed runs read
17648
+ ci.required-checks: the required status checks of the branch, its classic
17649
+ protection and its rulesets together (protection gh may not read, which
17650
+ needs admin rights, counts as none)
17651
+ ci.required-reviews: the required approving reviews, the larger of the two
17652
+ Cancelled and skipped runs are left out of the time and the success rate.`,
17653
+ options: {
17654
+ repo: { type: "string" },
17655
+ branch: { type: "string" },
17656
+ days: { type: "string" },
17657
+ workflow: { type: "string", multiple: true },
17658
+ gh: { type: "string" }
17659
+ },
17660
+ async measure({ args, options, cwd }) {
17661
+ if (args.length) throw new Error(`github-actions takes no input (${args.join(" ")}): name the repository with --repo`);
17662
+ const [command, ...base] = commandWords(option(options.gh) ?? GH);
17663
+ const gh = async (...a2) => runGh(command, base, a2, cwd);
17664
+ const failed = (what, r) => new Error(`${what}: ${r.stderr.trim() || `${command} exited with ${r.code}`}`);
17665
+ const branch = option(options.branch) ?? BRANCH;
17666
+ const daysText = option(options.days) ?? String(DAYS);
17667
+ const days = Number(daysText);
17668
+ if (!Number.isInteger(days) || days < 1) throw new Error(`--days ${daysText} is not a whole number of days`);
17669
+ const workflows = (Array.isArray(options.workflow) ? options.workflow : []).map((w) => w.trim()).filter(Boolean);
17670
+ let repo = option(options.repo);
17671
+ if (!repo) {
17672
+ const r = await gh("repo", "view", "--json", "nameWithOwner", "--jq", ".nameWithOwner");
17673
+ if (r.code !== 0) throw failed("cannot tell the repository (name it with --repo)", r);
17674
+ repo = r.stdout.trim();
17675
+ }
17676
+ if (!/^[\w.-]+\/[\w.-]+$/.test(repo)) throw new Error(`${repo} is not <owner>/<name>`);
17677
+ const since = new Date(Date.now() - days * 864e5).toISOString().slice(0, 10);
17678
+ const listed = await gh("api", "--paginate", `repos/${repo}/actions/runs?created=%3E%3D${since}&exclude_pull_requests=true&per_page=100`);
17679
+ if (listed.code !== 0) throw failed(`cannot read the workflow runs of ${repo}`, listed);
17680
+ let pages;
17681
+ try {
17682
+ pages = jsonValues(listed.stdout);
17683
+ } catch (error) {
17684
+ throw new Error(`the workflow runs of ${repo} are no JSON: ${error.message}`);
17685
+ }
17686
+ const runs = pages.flatMap((page) => {
17687
+ if (Array.isArray(page)) return page;
17688
+ const list = page?.workflow_runs;
17689
+ return Array.isArray(list) ? list : [page];
17690
+ }).filter((r) => r && typeof r === "object" && matchesWorkflow(r, workflows));
17691
+ const ref = encodeURIComponent(branch);
17692
+ const optional = async (path, what, paginate) => {
17693
+ const r = await gh("api", ...paginate ? ["--paginate"] : [], path);
17694
+ if (r.code === 0) return jsonValues(r.stdout);
17695
+ const status = httpStatus(r);
17696
+ if (status === 404 || status === 403) {
17697
+ if (status === 403) process.stderr.write(`radical sense github-actions: cannot read the ${what} of ${branch} (HTTP 403); counted as none
17698
+ `);
17699
+ return [];
17700
+ }
17701
+ throw failed(`cannot read the ${what} of ${branch}`, r);
17702
+ };
17703
+ const rules = await optional(`repos/${repo}/rules/branches/${ref}`, "rulesets", true);
17704
+ const [protection] = await optional(`repos/${repo}/branches/${ref}/protection`, "branch protection", false);
17705
+ const { checks, reviews } = branchRules(rules, protection ?? null);
17706
+ return [
17707
+ ...runValues(runs, branch),
17708
+ { metric: "ci.required-checks", value: checks },
17709
+ { metric: "ci.required-reviews", value: reviews }
17710
+ ];
17711
+ },
17712
+ fixture: {
17713
+ args: [],
17714
+ options: { gh: `"${process.execPath}" gh.mjs`, branch: "main", days: "30" },
17715
+ files: {
17716
+ "gh.mjs": FIXTURE_GH,
17717
+ "gh-answers.json": JSON.stringify(FIXTURE_ANSWERS, null, 2)
17718
+ }
17719
+ }
17720
+ };
17721
+
17140
17722
  // src/sensors/json.ts
17141
17723
  init_define_RADICAL_BUILD();
17142
17724
  import { readFile as readFile17 } from "fs/promises";
@@ -17189,12 +17771,336 @@ var jsonAdapter = {
17189
17771
  }
17190
17772
  };
17191
17773
 
17774
+ // src/sensors/lighthouse.ts
17775
+ init_define_RADICAL_BUILD();
17776
+ import { readdir as readdir6, readFile as readFile18, stat as stat11 } from "fs/promises";
17777
+ import { join as join22, resolve as resolve22 } from "path";
17778
+ var DEFAULT_INPUT = ".lighthouseci";
17779
+ var AUDITS = [
17780
+ { metric: "web.lab.lcp", audit: "largest-contentful-paint", unit: "ms" },
17781
+ { metric: "web.lab.fcp", audit: "first-contentful-paint", unit: "ms" },
17782
+ { metric: "web.lab.tbt", audit: "total-blocking-time", unit: "ms" },
17783
+ { metric: "web.lab.speed_index", audit: "speed-index", unit: "ms" },
17784
+ { metric: "web.lab.cls", audit: "cumulative-layout-shift" },
17785
+ // Only timespan reports (a user flow's interactions) have it.
17786
+ { metric: "web.lab.inp", audit: "interaction-to-next-paint", unit: "ms" },
17787
+ { metric: "web.lab.bytes", audit: "total-byte-weight", unit: "B" }
17788
+ ];
17789
+ var CATEGORIES = ["performance", "accessibility", "best-practices", "seo"];
17790
+ var isLhr = (data) => !!data && typeof data === "object" && typeof data.lighthouseVersion === "string" && !!data.audits && typeof data.audits === "object";
17791
+ function reportsIn(data) {
17792
+ if (isLhr(data)) return [data];
17793
+ const steps = data?.steps;
17794
+ if (Array.isArray(steps)) return steps.map((s2) => s2?.lhr).filter(isLhr);
17795
+ return [];
17796
+ }
17797
+ var finite = (v) => typeof v === "number" && Number.isFinite(v);
17798
+ function pageOf2(lhr, file) {
17799
+ const url = lhr.finalDisplayedUrl ?? lhr.finalUrl ?? lhr.requestedUrl;
17800
+ if (!url) throw new Error(`${file}: the report names no URL (finalDisplayedUrl, finalUrl, requestedUrl)`);
17801
+ try {
17802
+ const u = new URL(url);
17803
+ return `${u.pathname}${u.search}`;
17804
+ } catch {
17805
+ return url;
17806
+ }
17807
+ }
17808
+ var deviceOf = (lhr) => (lhr.configSettings?.formFactor ?? lhr.configSettings?.emulatedFormFactor) === "desktop" ? "desktop" : "mobile";
17809
+ function valuesOf2(lhr) {
17810
+ const out = [];
17811
+ for (const a2 of AUDITS) {
17812
+ const value = lhr.audits[a2.audit]?.numericValue;
17813
+ if (finite(value)) out.push({ metric: a2.metric, value, ...a2.unit ? { unit: a2.unit } : {} });
17814
+ }
17815
+ const items = lhr.audits["resource-summary"]?.details?.items;
17816
+ const script = Array.isArray(items) ? items.find((i) => i?.resourceType === "script")?.transferSize : void 0;
17817
+ if (finite(script)) out.push({ metric: "web.lab.script_bytes", value: script, unit: "B" });
17818
+ for (const category of CATEGORIES) {
17819
+ const score = lhr.categories?.[category]?.score;
17820
+ if (finite(score)) out.push({ metric: "web.lab.score", value: Math.round(score * 100), category });
17821
+ }
17822
+ return out;
17823
+ }
17824
+ function median(values) {
17825
+ const v = [...values].sort((a2, b) => a2 - b);
17826
+ const mid = Math.floor(v.length / 2);
17827
+ return v.length % 2 ? v[mid] : (v[mid - 1] + v[mid]) / 2;
17828
+ }
17829
+ var round3 = (n) => Math.round(n * 1e3) / 1e3;
17830
+ async function readReports(inputs, cwd) {
17831
+ const out = [];
17832
+ const parse3 = async (path, shown3) => {
17833
+ const text3 = await readFile18(path, "utf8");
17834
+ try {
17835
+ return JSON.parse(text3);
17836
+ } catch (error) {
17837
+ throw new Error(`${shown3} is no JSON: ${error.message}`);
17838
+ }
17839
+ };
17840
+ for (const input of inputs) {
17841
+ const path = resolve22(cwd, input);
17842
+ const kind = await stat11(path).then((s2) => s2.isDirectory() ? "dir" : "file", () => null);
17843
+ if (!kind) throw new Error(`cannot read ${input}: no such file or directory${input === DEFAULT_INPUT ? " (run Lighthouse CI first, or name the reports)" : ""}`);
17844
+ if (kind === "file") {
17845
+ const reports = reportsIn(await parse3(path, input));
17846
+ if (!reports.length) throw new Error(`${input} is no Lighthouse report (no lighthouseVersion and audits)`);
17847
+ out.push(...reports.map((lhr) => ({ file: input, lhr })));
17848
+ continue;
17849
+ }
17850
+ for (const name of (await readdir6(path)).filter((f) => f.endsWith(".json")).sort()) {
17851
+ const shown3 = join22(input, name);
17852
+ out.push(...reportsIn(await parse3(join22(path, name), shown3)).map((lhr) => ({ file: shown3, lhr })));
17853
+ }
17854
+ }
17855
+ return out;
17856
+ }
17857
+ function lighthouseValues(reports) {
17858
+ const series = /* @__PURE__ */ new Map();
17859
+ for (const { file, lhr } of reports) {
17860
+ if (lhr.runtimeError?.code) continue;
17861
+ const labels = { page: pageOf2(lhr, file), device: deviceOf(lhr) };
17862
+ for (const v of valuesOf2(lhr)) {
17863
+ const l = v.category ? { ...labels, category: v.category } : labels;
17864
+ const key = JSON.stringify([v.metric, l.page, l.device, v.category ?? ""]);
17865
+ const s2 = series.get(key) ?? { metric: v.metric, ...v.unit ? { unit: v.unit } : {}, labels: l, values: [] };
17866
+ s2.values.push(v.value);
17867
+ series.set(key, s2);
17868
+ }
17869
+ }
17870
+ const perPage = [...series.values()].map((s2) => ({ metric: s2.metric, value: round3(median(s2.values)), ...s2.unit ? { unit: s2.unit } : {}, labels: s2.labels }));
17871
+ const across = /* @__PURE__ */ new Map();
17872
+ for (const v of perPage) {
17873
+ const { page: _page, ...labels } = v.labels ?? {};
17874
+ const score = v.metric === "web.lab.score";
17875
+ const metric = `${v.metric}.${score ? "min" : "max"}`;
17876
+ const key = JSON.stringify([metric, labels.device, labels.category ?? ""]);
17877
+ const at = across.get(key);
17878
+ if (!at || (score ? v.value < at.value : v.value > at.value)) across.set(key, { metric, value: v.value, ...v.unit ? { unit: v.unit } : {}, labels });
17879
+ }
17880
+ return [...perPage, ...across.values()];
17881
+ }
17882
+ function fixtureLhr(o) {
17883
+ const ms = (id, title, value, score) => ({ id, title, score, scoreDisplayMode: "numeric", numericValue: value, numericUnit: "millisecond", displayValue: `${(value / 1e3).toFixed(1)} s` });
17884
+ return JSON.stringify({
17885
+ lighthouseVersion: "12.2.1",
17886
+ requestedUrl: o.url,
17887
+ mainDocumentUrl: o.url,
17888
+ finalDisplayedUrl: o.url,
17889
+ finalUrl: o.url,
17890
+ fetchTime: o.fetchTime,
17891
+ gatherMode: "navigation",
17892
+ runWarnings: [],
17893
+ userAgent: "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) HeadlessChrome/131.0.0.0 Safari/537.36",
17894
+ configSettings: { output: ["json"], formFactor: o.device, throttlingMethod: "simulate", screenEmulation: o.device === "mobile" ? { mobile: true, width: 412, height: 823, deviceScaleFactor: 1.75, disabled: false } : { mobile: false, width: 1350, height: 940, deviceScaleFactor: 1, disabled: false }, onlyCategories: null },
17895
+ audits: {
17896
+ "first-contentful-paint": ms("first-contentful-paint", "First Contentful Paint", o.fcp, 0.9),
17897
+ "largest-contentful-paint": ms("largest-contentful-paint", "Largest Contentful Paint", o.lcp, 0.7),
17898
+ "total-blocking-time": { ...ms("total-blocking-time", "Total Blocking Time", o.tbt, 0.8), displayValue: `${o.tbt} ms` },
17899
+ "speed-index": ms("speed-index", "Speed Index", o.si, 0.85),
17900
+ "cumulative-layout-shift": { id: "cumulative-layout-shift", title: "Cumulative Layout Shift", score: 0.95, scoreDisplayMode: "numeric", numericValue: o.cls, numericUnit: "unitless", displayValue: String(o.cls) },
17901
+ "total-byte-weight": { id: "total-byte-weight", title: "Avoids enormous network payloads", score: 1, scoreDisplayMode: "numeric", numericValue: o.bytes, numericUnit: "byte", displayValue: `Total size was ${Math.round(o.bytes / 1024)} KiB` },
17902
+ "resource-summary": {
17903
+ id: "resource-summary",
17904
+ title: "Keep request counts low and transfer sizes small",
17905
+ score: null,
17906
+ scoreDisplayMode: "informative",
17907
+ details: { type: "table", items: [
17908
+ { resourceType: "total", label: "Total", requestCount: 24, transferSize: o.bytes },
17909
+ { resourceType: "script", label: "Script", requestCount: 9, transferSize: o.script },
17910
+ { resourceType: "stylesheet", label: "Stylesheet", requestCount: 2, transferSize: 18204 }
17911
+ ] }
17912
+ }
17913
+ },
17914
+ categories: {
17915
+ performance: { id: "performance", title: "Performance", score: o.scores[0] },
17916
+ accessibility: { id: "accessibility", title: "Accessibility", score: o.scores[1] },
17917
+ "best-practices": { id: "best-practices", title: "Best Practices", score: o.scores[2] },
17918
+ seo: { id: "seo", title: "SEO", score: o.scores[3] }
17919
+ }
17920
+ });
17921
+ }
17922
+ var lighthouseAdapter = {
17923
+ name: "lighthouse",
17924
+ description: "reads Lighthouse result JSON (LHR) files, e.g. Lighthouse CI's .lighthouseci, as lab Web Vitals per page and device",
17925
+ usage: `radical sense lighthouse [<file>|<dir>]\u2026
17926
+
17927
+ Reads Lighthouse results (LHR, \`lighthouse --output json\`, or a user flow's
17928
+ result) from the files named, or every *.json report in the directories
17929
+ named (other JSON there, such as Lighthouse CI's manifest.json, is left
17930
+ out); with none, from ${DEFAULT_INPUT} (where \`lhci collect\` writes).
17931
+ Run it once a page several times: each value is the median of the runs of
17932
+ one page on one device, labelled page (path and query of the final URL,
17933
+ e.g. /pricing) and device (mobile or desktop, the report's formFactor):
17934
+ web.lab.lcp, web.lab.fcp, web.lab.tbt, web.lab.speed_index (ms),
17935
+ web.lab.cls, web.lab.inp (ms; only timespan reports measure it),
17936
+ web.lab.bytes, web.lab.script_bytes (B, all and script transfer size),
17937
+ web.lab.score{category=performance|accessibility|best-practices|seo} (0-100)
17938
+ and across the pages, labelled only device (and category):
17939
+ web.lab.<metric>.max of each metric above, web.lab.score.min
17940
+ so a condition states the worst page:
17941
+ web.lab.lcp.max{device=mobile} <= 2500 ms
17942
+ A report with a runtime error is left out.`,
17943
+ async measure({ args, cwd }) {
17944
+ const inputs = args.length ? args : [DEFAULT_INPUT];
17945
+ const reports = await readReports(inputs, cwd);
17946
+ if (!reports.length) throw new Error(`no Lighthouse report in ${inputs.join(", ")}`);
17947
+ const values = lighthouseValues(reports);
17948
+ if (!values.length) throw new Error(`the Lighthouse reports in ${inputs.join(", ")} measured nothing (each has a runtime error)`);
17949
+ return values;
17950
+ },
17951
+ fixture: {
17952
+ // Lighthouse CI's output: three mobile runs of /, one desktop run of /,
17953
+ // one mobile run of /pricing, beside its manifest and assertion results.
17954
+ args: [],
17955
+ files: {
17956
+ ".lighthouseci/lhr-1732435200001.json": fixtureLhr({ url: "https://example.com/", device: "mobile", fetchTime: "2026-11-24T08:00:01.000Z", lcp: 2400, fcp: 1500, tbt: 180, si: 3e3, cls: 0.02, bytes: 82e4, script: 31e4, scores: [0.86, 0.95, 1, 0.92] }),
17957
+ ".lighthouseci/lhr-1732435200002.json": fixtureLhr({ url: "https://example.com/", device: "mobile", fetchTime: "2026-11-24T08:00:15.000Z", lcp: 3100, fcp: 1700, tbt: 260, si: 3600, cls: 0.05, bytes: 83e4, script: 312e3, scores: [0.78, 0.95, 1, 0.92] }),
17958
+ ".lighthouseci/lhr-1732435200003.json": fixtureLhr({ url: "https://example.com/", device: "mobile", fetchTime: "2026-11-24T08:00:29.000Z", lcp: 2800, fcp: 1600, tbt: 220, si: 3300, cls: 0.03, bytes: 825e3, script: 311e3, scores: [0.82, 0.95, 1, 0.92] }),
17959
+ ".lighthouseci/lhr-1732435200004.json": fixtureLhr({ url: "https://example.com/", device: "desktop", fetchTime: "2026-11-24T08:00:43.000Z", lcp: 900, fcp: 500, tbt: 40, si: 1100, cls: 0.01, bytes: 815e3, script: 309e3, scores: [0.99, 0.95, 1, 0.92] }),
17960
+ ".lighthouseci/lhr-1732435200005.json": fixtureLhr({ url: "https://example.com/pricing?plan=team", device: "mobile", fetchTime: "2026-11-24T08:00:57.000Z", lcp: 3500, fcp: 1400, tbt: 150, si: 3900, cls: 0.12, bytes: 124e4, script: 45e4, scores: [0.74, 0.88, 0.96, 1] }),
17961
+ ".lighthouseci/manifest.json": JSON.stringify([{ url: "https://example.com/", isRepresentativeRun: true, jsonPath: ".lighthouseci/lhr-1732435200003.json", htmlPath: ".lighthouseci/lhr-1732435200003.html", summary: { performance: 0.82, accessibility: 0.95, "best-practices": 1, seo: 0.92 } }]),
17962
+ ".lighthouseci/assertion-results.json": JSON.stringify([])
17963
+ }
17964
+ }
17965
+ };
17966
+
17967
+ // src/sensors/machine.ts
17968
+ init_define_RADICAL_BUILD();
17969
+ import { spawn as spawn8 } from "child_process";
17970
+ import { mkdir as mkdir12, readFile as readFile19, writeFile as writeFile12 } from "fs/promises";
17971
+ import { dirname as dirname19, join as join23 } from "path";
17972
+ import { performance } from "perf_hooks";
17973
+ var AGAIN_WITHIN = 2 * 36e5;
17974
+ function builtInWork() {
17975
+ const n = 2e4;
17976
+ const samples = Array.from({ length: n }, (_, i) => ({ t: i, v: 3 + Math.sin(i / 50), h: 120 + i % 30 }));
17977
+ let sum = 0;
17978
+ for (let k = 0; k < 40; k++) {
17979
+ const means = [];
17980
+ for (let i = 0; i < n; i += 10) {
17981
+ let m = 0;
17982
+ for (let j = i; j < i + 10 && j < n; j++) m += samples[j].v * (1 + k / 100);
17983
+ means.push(m / 10);
17984
+ }
17985
+ means.sort((a2, b) => a2 - b);
17986
+ sum += means[means.length >> 1];
17987
+ }
17988
+ return sum + JSON.parse(JSON.stringify(samples.slice(0, 5e3))).length;
17989
+ }
17990
+ var median2 = (xs) => {
17991
+ const s2 = [...xs].sort((a2, b) => a2 - b);
17992
+ const mid = s2.length >> 1;
17993
+ return s2.length % 2 ? s2[mid] : (s2[mid - 1] + s2[mid]) / 2;
17994
+ };
17995
+ var round1 = (n) => Math.round(n * 10) / 10;
17996
+ var round22 = (n) => Math.round(n * 100) / 100;
17997
+ function timeBuiltIn(runs) {
17998
+ for (let i = 0; i < 3; i++) builtInWork();
17999
+ const times = [];
18000
+ for (let i = 0; i < runs; i++) {
18001
+ const t0 = performance.now();
18002
+ builtInWork();
18003
+ times.push(performance.now() - t0);
18004
+ }
18005
+ return median2(times);
18006
+ }
18007
+ async function timeCommand(command, runs, cwd) {
18008
+ const [cmd, ...args] = commandWords(command);
18009
+ if (!cmd) throw new Error("--work names no command");
18010
+ const once = () => new Promise((done, fail) => {
18011
+ const t0 = performance.now();
18012
+ const child = spawn8(cmd, args, { cwd, stdio: ["ignore", "ignore", "inherit"], shell: process.platform === "win32" });
18013
+ child.on("error", (error) => fail(new Error(`cannot run ${cmd}: ${error.message}`)));
18014
+ child.on("close", (status) => status === 0 ? done(performance.now() - t0) : fail(new Error(`${command} exited with ${status}`)));
18015
+ });
18016
+ await once();
18017
+ const times = [];
18018
+ for (let i = 0; i < runs; i++) times.push(await once());
18019
+ return median2(times);
18020
+ }
18021
+ async function repositoryFile(cwd) {
18022
+ const found = await findRepositoryFile(cwd, REPOSITORY_FILE, REPOSITORY_FILE);
18023
+ if (found) return { path: found.path, file: parseRepositoryFile(await readFile19(found.path, "utf8"), found.path) };
18024
+ return { path: join23(await repositoryRoot(cwd) ?? cwd, REPOSITORY_FILE), file: null };
18025
+ }
18026
+ function readReference(file) {
18027
+ const m = file?.machine;
18028
+ return m && typeof m.ms === "number" && m.ms > 0 && typeof m.work === "string" ? { ms: m.ms, work: m.work, at: typeof m.at === "string" ? m.at : "" } : null;
18029
+ }
18030
+ var machineAdapter = {
18031
+ name: "machine",
18032
+ description: "times a fixed piece of work against the reference machine, for limits scaled to the machine",
18033
+ usage: `radical sense machine [--reference] [--again] [--work <command>] [--runs <n>]
18034
+
18035
+ Times a fixed piece of work and measures it as machine.work (ms) and as
18036
+ machine.speed, its ratio to the reference time the repository keeps in
18037
+ .radical/radical.json ("machine"). A condition that ends in scaled
18038
+ (\`test.duration.max{kind=unit} <= 100 ms scaled\`) has its limit multiplied
18039
+ by the machine.speed measured nearest in time to its value (a lower limit
18040
+ divided), never below \xD71.
18041
+
18042
+ --reference measure on the machine the limits were set on and keep the
18043
+ time as the reference in .radical/radical.json (commit it)
18044
+ --again run after the tests: keep the slower of this run and the
18045
+ one measured before them (a shared runner's speed changes
18046
+ while it works)
18047
+ --work <command> time this command instead of Radical's own work (when the
18048
+ limits depend on disk or network); the reference must have
18049
+ been taken with the same command
18050
+ --runs <n> how many timed runs the median is taken over (default 9
18051
+ for the built-in work, 5 for a command)`,
18052
+ options: {
18053
+ reference: { type: "boolean", default: false },
18054
+ again: { type: "boolean", default: false },
18055
+ work: { type: "string" },
18056
+ runs: { type: "string" }
18057
+ },
18058
+ async measure({ args, options, cwd, previous }) {
18059
+ if (args.length) throw new Error(`takes no arguments: ${args.join(" ")}`);
18060
+ const command = typeof options.work === "string" && options.work.trim() ? options.work.trim() : void 0;
18061
+ const work = command ?? "builtin";
18062
+ const runs = options.runs === void 0 ? command ? 5 : 9 : Number(options.runs);
18063
+ if (!Number.isInteger(runs) || runs < 1) throw new Error(`--runs ${String(options.runs)} is no whole number of runs`);
18064
+ const { path, file } = await repositoryFile(cwd);
18065
+ const reference = readReference(file);
18066
+ if (!options.reference) {
18067
+ if (!reference) throw new Error(`no reference time in ${REPOSITORY_FILE}: run radical sense machine --reference on the machine the limits were set on, and commit ${REPOSITORY_FILE}`);
18068
+ if (reference.work !== work) throw new Error(`the reference in ${REPOSITORY_FILE} was taken with ${reference.work === "builtin" ? "the built-in work" : `--work "${reference.work}"`}, not ${command ? `--work "${command}"` : "the built-in work"}: time the same work, or take the reference again`);
18069
+ }
18070
+ let ms = command ? await timeCommand(command, runs, cwd) : timeBuiltIn(runs);
18071
+ if (options.again) {
18072
+ const before = (previous ?? []).filter((m) => m.metric === MACHINE_WORK_METRIC && m.labels.work === work && Date.now() - Date.parse(m.at) <= AGAIN_WITHIN).sort((a2, b) => Date.parse(b.at) - Date.parse(a2.at))[0];
18073
+ if (before) ms = Math.max(ms, before.value);
18074
+ }
18075
+ ms = round1(ms);
18076
+ if (options.reference) {
18077
+ const next = { ...file ?? { implements: [], verifies: [] }, machine: { ms, work, at: (/* @__PURE__ */ new Date()).toISOString() } };
18078
+ await mkdir12(dirname19(path), { recursive: true });
18079
+ await writeFile12(path, serializeRepositoryFile(next));
18080
+ }
18081
+ const base = options.reference ? ms : reference.ms;
18082
+ const values = [
18083
+ { metric: MACHINE_WORK_METRIC, value: ms, unit: "ms", labels: { work } },
18084
+ { metric: MACHINE_SPEED_METRIC, value: round22(ms / base) }
18085
+ ];
18086
+ return values;
18087
+ },
18088
+ fixture: {
18089
+ args: [],
18090
+ options: { runs: "1" },
18091
+ files: {
18092
+ // A reference no machine reaches, so the fixture measures a speed.
18093
+ [REPOSITORY_FILE]: JSON.stringify({ machine: { ms: 1e-3, work: "builtin", at: "2026-11-24T00:00:00.000Z" }, implements: [], verifies: [] })
18094
+ }
18095
+ }
18096
+ };
18097
+
17192
18098
  // src/sensors/playwright.ts
17193
18099
  init_define_RADICAL_BUILD();
17194
- import { spawn as spawn7 } from "child_process";
17195
- import { mkdtemp as mkdtemp2, readdir as readdir6, readFile as readFile18, rm as rm5 } from "fs/promises";
18100
+ import { spawn as spawn9 } from "child_process";
18101
+ import { mkdtemp as mkdtemp2, readdir as readdir7, readFile as readFile20, rm as rm5 } from "fs/promises";
17196
18102
  import { tmpdir as tmpdir4 } from "os";
17197
- import { join as join22, resolve as resolve22 } from "path";
18103
+ import { join as join24, resolve as resolve23 } from "path";
17198
18104
  var RUNNER = "npx playwright test";
17199
18105
  function envPairs(list) {
17200
18106
  const out = {};
@@ -17225,14 +18131,14 @@ var playwrightAdapter = {
17225
18131
  },
17226
18132
  async measure({ args, options, cwd }) {
17227
18133
  if (!args.length) throw new Error("no spec to run");
17228
- const dir = resolve22(cwd, typeof options.cwd === "string" ? options.cwd : ".");
18134
+ const dir = resolve23(cwd, typeof options.cwd === "string" ? options.cwd : ".");
17229
18135
  const env = envPairs(options.env);
17230
18136
  const [command, ...runnerArgs] = commandWords(typeof options.runner === "string" && options.runner ? options.runner : RUNNER);
17231
- const out = await mkdtemp2(join22(tmpdir4(), "radical-playwright-"));
18137
+ const out = await mkdtemp2(join24(tmpdir4(), "radical-playwright-"));
17232
18138
  try {
17233
18139
  const project = typeof options.project === "string" && options.project ? [`--project=${options.project}`] : [];
17234
18140
  const code = await new Promise((done, fail) => {
17235
- const child = spawn7(command, [...runnerArgs, ...args, ...project], {
18141
+ const child = spawn9(command, [...runnerArgs, ...args, ...project], {
17236
18142
  cwd: dir,
17237
18143
  env: { ...process.env, ...env, RADICAL_METRICS_DIR: out },
17238
18144
  stdio: ["ignore", "pipe", "inherit"],
@@ -17242,10 +18148,10 @@ var playwrightAdapter = {
17242
18148
  child.on("error", (error) => fail(new Error(`cannot run ${command}: ${error.message}`)));
17243
18149
  child.on("close", (status, signal) => done(status ?? (signal ? 128 : 1)));
17244
18150
  });
17245
- const files = (await readdir6(out)).filter((f) => f.endsWith(".json")).sort();
18151
+ const files = (await readdir7(out)).filter((f) => f.endsWith(".json")).sort();
17246
18152
  const values = [];
17247
18153
  for (const file of files) {
17248
- for (const m of parseMetricsFile(await readFile18(join22(out, file), "utf8"), file)) {
18154
+ for (const m of parseMetricsFile(await readFile20(join24(out, file), "utf8"), file)) {
17249
18155
  values.push({ metric: m.metric, value: m.value, ...m.unit ? { unit: m.unit } : {}, ...Object.keys(m.labels).length ? { labels: m.labels } : {} });
17250
18156
  }
17251
18157
  }
@@ -17271,7 +18177,7 @@ writeFileSync(process.env.RADICAL_METRICS_DIR + '/spec.json', JSON.stringify({
17271
18177
  };
17272
18178
 
17273
18179
  // src/sensors/registry.ts
17274
- var SENSOR_ADAPTERS = [commandAdapter, jsonAdapter, playwrightAdapter];
18180
+ var SENSOR_ADAPTERS = [commandAdapter, githubActionsAdapter, jsonAdapter, lighthouseAdapter, machineAdapter, playwrightAdapter];
17275
18181
  var sensorAdapter = (name) => SENSOR_ADAPTERS.find((a2) => a2.name === name);
17276
18182
 
17277
18183
  // src/sense.ts
@@ -17321,11 +18227,11 @@ var COMMON = {
17321
18227
  list: { type: "boolean", default: false },
17322
18228
  help: { type: "boolean", short: "h", default: false }
17323
18229
  };
17324
- function pairs(list, option) {
18230
+ function pairs(list, option2) {
17325
18231
  const out = {};
17326
18232
  for (const item of list ?? []) {
17327
18233
  const m = /^([\w.-]+)=(.*)$/.exec(item);
17328
- if (!m) throw new Error(`--${option} ${item} is not <name>=<value>`);
18234
+ if (!m) throw new Error(`--${option2} ${item} is not <name>=<value>`);
17329
18235
  out[m[1]] = m[2];
17330
18236
  }
17331
18237
  return out;
@@ -17382,12 +18288,12 @@ ${SENSE_USAGE}`);
17382
18288
  return 2;
17383
18289
  }
17384
18290
  const named = await modelFolderArg(given, io2.cwd);
17385
- const folder = resolve23(io2.cwd, named);
18291
+ const folder = resolve24(io2.cwd, named);
17386
18292
  let nodes;
17387
18293
  let model;
17388
18294
  let sensors;
17389
18295
  try {
17390
- if (!await stat11(join23(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) throw new Error(`no ${MD_MANIFEST_FILE}`);
18296
+ if (!await stat12(join25(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) throw new Error(`no ${MD_MANIFEST_FILE}`);
17391
18297
  const files = await new MdFolderSession(diskFolderStorage(folder), { writeCache: false }).readAll();
17392
18298
  const own = deserializeFromMdFolder(files).data;
17393
18299
  const federation = await composeFolder(folder);
@@ -17427,9 +18333,9 @@ ${SENSE_USAGE}`);
17427
18333
  if (sensor) {
17428
18334
  for (const element of elements.length ? elements : [null]) {
17429
18335
  ran++;
17430
- const file2 = join23(resolve23(io2.cwd, out), `${base}${element ? `-${slug(element.label)}` : ""}.json`);
18336
+ const file2 = join25(resolve24(io2.cwd, out), `${base}${element ? `-${slug(element.label)}` : ""}.json`);
17431
18337
  const metricsOut = file2.replace(/\.json$/, ".sensor.json");
17432
- await mkdir12(dirname19(metricsOut), { recursive: true });
18338
+ await mkdir13(dirname20(metricsOut), { recursive: true });
17433
18339
  await rm6(metricsOut, { force: true });
17434
18340
  const sensorContext = model.context(node, element, metricsOut);
17435
18341
  const labels = element ? ["--label", `${ELEMENT_LABEL}=${element.id}`] : [];
@@ -17439,11 +18345,11 @@ ${SENSE_USAGE}`);
17439
18345
  failed++;
17440
18346
  continue;
17441
18347
  }
17442
- const written = await readFile19(metricsOut, "utf8").catch(() => null);
18348
+ const written = await readFile21(metricsOut, "utf8").catch(() => null);
17443
18349
  if (written === null) continue;
17444
18350
  try {
17445
18351
  const measured = parseMetricsFile(written, line.sensor);
17446
- await writeFile12(metricsOut, serializeMetricsFile({
18352
+ await writeFile13(metricsOut, serializeMetricsFile({
17447
18353
  source: line.sensor,
17448
18354
  at: now().toISOString(),
17449
18355
  measurements: measured.map(({ source: _s, at: _a5, context: _c, ...m }) => ({ ...m, labels: { ...m.labels, ...element ? { [ELEMENT_LABEL]: element.id } : {} } }))
@@ -17457,7 +18363,7 @@ ${SENSE_USAGE}`);
17457
18363
  continue;
17458
18364
  }
17459
18365
  ran++;
17460
- const file = join23(resolve23(io2.cwd, out), `${base}.json`);
18366
+ const file = join25(resolve24(io2.cwd, out), `${base}.json`);
17461
18367
  if (!isSensorName(line.sensor)) {
17462
18368
  failed++;
17463
18369
  io2.err(`${node.label}: cannot measure "${line.raw}": no sensor ${line.sensor}, neither an adapter (radical sense --list) nor in ${sensors ? sensors.file : `the repository's ${SENSORS_FILE}`}.`);
@@ -17487,13 +18393,13 @@ ${SENSE_USAGE}`);
17487
18393
  ${SENSE_USAGE}`);
17488
18394
  return 2;
17489
18395
  }
17490
- const folder = resolve23(io2.cwd, await modelFolderArg(values.folder, io2.cwd));
17491
- if (!await stat11(join23(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) {
18396
+ const folder = resolve24(io2.cwd, await modelFolderArg(values.folder, io2.cwd));
18397
+ if (!await stat12(join25(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) {
17492
18398
  io2.err(`${values.folder ?? "The working directory"} is no model folder (no ${MD_MANIFEST_FILE}); name one with --folder.`);
17493
18399
  return 2;
17494
18400
  }
17495
- const path = join23(await mappingRoot(folder), REVIEWS_FILE);
17496
- const existing = await readFile19(path, "utf8").catch(() => void 0);
18401
+ const path = join25(await mappingRoot(folder), REVIEWS_FILE);
18402
+ const existing = await readFile21(path, "utf8").catch(() => void 0);
17497
18403
  const result = values.passed ? "passed" : "failed";
17498
18404
  let text3;
17499
18405
  try {
@@ -17502,8 +18408,8 @@ ${SENSE_USAGE}`);
17502
18408
  io2.err(`Cannot read ${REVIEWS_FILE}: ${error.message}`);
17503
18409
  return 2;
17504
18410
  }
17505
- await mkdir12(dirname19(path), { recursive: true });
17506
- await writeFile12(path, text3, "utf8");
18411
+ await mkdir13(dirname20(path), { recursive: true });
18412
+ await writeFile13(path, text3, "utf8");
17507
18413
  io2.out(`Recorded in ${REVIEWS_FILE}: ${name} ${result}, by ${values.by.trim()}. Commit it.`);
17508
18414
  return 0;
17509
18415
  }
@@ -17555,9 +18461,10 @@ ${adapter.usage}`);
17555
18461
  return 2;
17556
18462
  }
17557
18463
  const options = Object.fromEntries(Object.entries(values).filter(([k]) => !(k in COMMON)));
18464
+ const previous = typeof values.out === "string" ? await readFile21(resolve24(io2.cwd, values.out), "utf8").then((text4) => parseMetricsFile(text4, values.out), () => []) : await modelFolderArg(typeof values.folder === "string" ? values.folder : void 0, io2.cwd).then((named) => readEditorStateFile(resolve24(io2.cwd, named), MEASUREMENTS_FILE)).then((text4) => parseMeasurementStore(text4 ?? ""), () => []);
17558
18465
  let measured;
17559
18466
  try {
17560
- measured = await adapter.measure({ args: [...positionals, ...after], options, cwd: io2.cwd });
18467
+ measured = await adapter.measure({ args: [...positionals, ...after], options, cwd: io2.cwd, previous });
17561
18468
  } catch (error) {
17562
18469
  io2.err(`radical sense ${adapter.name}: ${error.message}
17563
18470
 
@@ -17576,14 +18483,14 @@ ${adapter.usage}`);
17576
18483
  return 2;
17577
18484
  }
17578
18485
  if (typeof values.out === "string") {
17579
- await writeBeside(resolve23(io2.cwd, values.out), text3);
18486
+ await writeBeside(resolve24(io2.cwd, values.out), text3);
17580
18487
  } else {
17581
- const folder = resolve23(io2.cwd, await modelFolderArg(typeof values.folder === "string" ? values.folder : void 0, io2.cwd));
17582
- if (!await stat11(join23(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) {
18488
+ const folder = resolve24(io2.cwd, await modelFolderArg(typeof values.folder === "string" ? values.folder : void 0, io2.cwd));
18489
+ if (!await stat12(join25(folder, MD_MANIFEST_FILE)).then((s2) => s2.isFile(), () => false)) {
17583
18490
  io2.err(`${typeof values.folder === "string" ? values.folder : "The working directory"} is no model folder (no ${MD_MANIFEST_FILE}); name one with --folder, or write a file with --out.`);
17584
18491
  return 2;
17585
18492
  }
17586
- const store = join23(folder, MEASUREMENTS_FILE);
18493
+ const store = join25(folder, MEASUREMENTS_FILE);
17587
18494
  const existing = parseMeasurementStore(await readEditorStateFile(folder, MEASUREMENTS_FILE) ?? "");
17588
18495
  await writeBeside(store, serializeMeasurementStore(mergeMeasurements(existing, parseMetricsFile(text3, adapter.name))));
17589
18496
  }
@@ -17593,8 +18500,8 @@ ${adapter.usage}`);
17593
18500
 
17594
18501
  // src/assay.ts
17595
18502
  init_define_RADICAL_BUILD();
17596
- import { mkdir as mkdir13, writeFile as writeFile13 } from "fs/promises";
17597
- import { dirname as dirname22, join as join32 } from "path";
18503
+ import { mkdir as mkdir14, writeFile as writeFile14 } from "fs/promises";
18504
+ import { dirname as dirname23, join as join34 } from "path";
17598
18505
  import { parseArgs as parseArgs14 } from "util";
17599
18506
 
17600
18507
  // ../../packages/assay/src/index.ts
@@ -17603,10 +18510,10 @@ init_define_RADICAL_BUILD();
17603
18510
  // ../../packages/assay/src/facts.ts
17604
18511
  init_define_RADICAL_BUILD();
17605
18512
  import { existsSync as existsSync13 } from "fs";
17606
- import { join as join24 } from "path";
18513
+ import { join as join26 } from "path";
17607
18514
  var FACTS_FILE = ".radical/assay/facts.json";
17608
18515
  var FOLDER_FACTS_DIR = ".radical/assay/facts";
17609
- var factsFileOf = (dir, name, root) => existsSync13(join24(dir, ".git")) ? join24(dir, FACTS_FILE) : join24(root, FOLDER_FACTS_DIR, `${name}.json`);
18516
+ var factsFileOf = (dir, name, root) => existsSync13(join26(dir, ".git")) ? join26(dir, FACTS_FILE) : join26(root, FOLDER_FACTS_DIR, `${name}.json`);
17610
18517
  var FORMAT = "radical-assay-facts/1";
17611
18518
  var emptyFacts = (repository, dir) => ({
17612
18519
  repository,
@@ -17641,13 +18548,13 @@ function serializeFacts(facts) {
17641
18548
  // ../../packages/assay/src/cite.ts
17642
18549
  init_define_RADICAL_BUILD();
17643
18550
  import { existsSync as existsSync16, readFileSync as readFileSync9, realpathSync as realpathSync4, statSync as statSync4 } from "fs";
17644
- import { isAbsolute as isAbsolute7, join as join27, sep as sep5 } from "path";
18551
+ import { isAbsolute as isAbsolute7, join as join29, sep as sep5 } from "path";
17645
18552
 
17646
18553
  // ../../packages/assay/src/files.ts
17647
18554
  init_define_RADICAL_BUILD();
17648
18555
  import { execFileSync } from "child_process";
17649
18556
  import { existsSync as existsSync14, readFileSync as readFileSync7, readdirSync as readdirSync4, statSync as statSync2 } from "fs";
17650
- import { join as join25, sep as sep4 } from "path";
18557
+ import { join as join27, sep as sep4 } from "path";
17651
18558
  var withoutComments = (code) => code.replace(/\/\*[\s\S]*?\*\//g, (m) => m.replace(/[^\n]/g, " ")).replace(/(^|[^:"'])\/\/[^\n]*/g, (m, lead) => lead + " ".repeat(m.length - lead.length));
17652
18559
  function shownOnly(text3, at, file) {
17653
18560
  if (!/\.(svelte|vue|[cm]?[jt]sx?)$/i.test(file)) return false;
@@ -17689,11 +18596,11 @@ var MAX_FILES = 2e5;
17689
18596
  var GIT = ["-c", "core.fsmonitor=false"];
17690
18597
  function listFiles(root) {
17691
18598
  try {
17692
- if (!existsSync14(join25(root, ".git"))) throw new Error("no repository");
18599
+ if (!existsSync14(join27(root, ".git"))) throw new Error("no repository");
17693
18600
  const out = execFileSync("git", [...GIT, "ls-files", "-co", "--exclude-standard", "-z"], { cwd: root, maxBuffer: 1 << 28, stdio: ["ignore", "pipe", "ignore"] }).toString();
17694
18601
  return { files: out.split("\0").filter((f) => f && !f.endsWith("/")).filter((f) => {
17695
18602
  try {
17696
- return statSync2(join25(root, f)).isFile();
18603
+ return statSync2(join27(root, f)).isFile();
17697
18604
  } catch {
17698
18605
  return false;
17699
18606
  }
@@ -17703,7 +18610,7 @@ function listFiles(root) {
17703
18610
  const walk = (dir) => {
17704
18611
  let entries;
17705
18612
  try {
17706
- entries = readdirSync4(join25(root, dir), { withFileTypes: true });
18613
+ entries = readdirSync4(join27(root, dir), { withFileTypes: true });
17707
18614
  } catch {
17708
18615
  return;
17709
18616
  }
@@ -17711,7 +18618,7 @@ function listFiles(root) {
17711
18618
  const path = dir ? `${dir}/${d.name}` : d.name;
17712
18619
  if (d.isDirectory()) {
17713
18620
  if (SKIPPED.has(d.name)) continue;
17714
- if (existsSync14(join25(root, path, ".git"))) listing.nested.push(path);
18621
+ if (existsSync14(join27(root, path, ".git"))) listing.nested.push(path);
17715
18622
  else walk(path);
17716
18623
  } else if (d.isFile()) {
17717
18624
  if (listing.files.length < MAX_FILES) listing.files.push(path);
@@ -17745,7 +18652,7 @@ var RepoFiles = class {
17745
18652
  if (cached !== void 0) return cached;
17746
18653
  let text3 = "";
17747
18654
  try {
17748
- const full = join25(this.root, file);
18655
+ const full = join27(this.root, file);
17749
18656
  if (statSync2(full).size <= (SQL_DUMP.test(file) ? MAX_SQL_FILE : MAX_FILE)) text3 = decodeText(readFileSync7(full));
17750
18657
  } catch {
17751
18658
  }
@@ -17801,7 +18708,7 @@ import { lookup as lookupCallback } from "dns";
17801
18708
  import { lookup } from "dns/promises";
17802
18709
  import { existsSync as existsSync15, mkdirSync as mkdirSync5, readFileSync as readFileSync8, readdirSync as readdirSync5, realpathSync as realpathSync3, renameSync, rmSync as rmSync3, statSync as statSync3, writeFileSync as writeFileSync4 } from "fs";
17803
18710
  import { isIP } from "net";
17804
- import { basename as basename6, dirname as dirname20, extname, isAbsolute as isAbsolute6, join as join26, relative as relative15, resolve as resolve24 } from "path";
18711
+ import { basename as basename6, dirname as dirname21, extname, isAbsolute as isAbsolute6, join as join28, relative as relative15, resolve as resolve25 } from "path";
17805
18712
 
17806
18713
  // ../../node_modules/fflate/esm/index.mjs
17807
18714
  init_define_RADICAL_BUILD();
@@ -19245,9 +20152,9 @@ function replaceFolder(parent, into, write) {
19245
20152
  if (had) rmSync3(old, { recursive: true, force: true });
19246
20153
  }
19247
20154
  function writeInside(dir, name, data) {
19248
- const path = resolve24(dir, name);
20155
+ const path = resolve25(dir, name);
19249
20156
  if (!within(dir, path)) throw new Error(`${name} would land outside ${basename6(dir)}`);
19250
- mkdirSync5(dirname20(path), { recursive: true });
20157
+ mkdirSync5(dirname21(path), { recursive: true });
19251
20158
  writeFileSync4(path, data);
19252
20159
  }
19253
20160
  function unpackZip(zip, parent, into) {
@@ -19259,7 +20166,7 @@ function unpackZip(zip, parent, into) {
19259
20166
  }
19260
20167
  function ignored(dir) {
19261
20168
  mkdirSync5(dir, { recursive: true });
19262
- const file = join26(dir, ".gitignore");
20169
+ const file = join28(dir, ".gitignore");
19263
20170
  if (!existsSync15(file)) writeFileSync4(file, "# Radical Assay's copies: kept out of git unless the team chooses otherwise.\n*\n");
19264
20171
  }
19265
20172
 
@@ -19336,7 +20243,7 @@ function describeFacts(repositories, links, from, brief = false) {
19336
20243
  init_define_RADICAL_BUILD();
19337
20244
  import { execFileSync as execFileSync2 } from "child_process";
19338
20245
  import { existsSync as existsSync18, readFileSync as readFileSync11, readdirSync as readdirSync6, realpathSync as realpathSync5, statSync as statSync5 } from "fs";
19339
- import { basename as basename10, isAbsolute as isAbsolute8, join as join30, relative as relative17, resolve as resolve25 } from "path";
20246
+ import { basename as basename10, isAbsolute as isAbsolute8, join as join32, relative as relative17, resolve as resolve26 } from "path";
19340
20247
 
19341
20248
  // ../../packages/assay/src/yaml.ts
19342
20249
  init_define_RADICAL_BUILD();
@@ -22859,8 +23766,8 @@ function npm(files, notes) {
22859
23766
  const d = draft("npm", path, file, typeof json3.name === "string" ? json3.name : void 0, lineOf(text3, /"name"\s*:/));
22860
23767
  const scripts = json3.scripts && typeof json3.scripts === "object" ? json3.scripts : {};
22861
23768
  if (json3.bin) d.reasons.push("it has a bin");
22862
- const run2 = ["start", "dev", "serve", "preview"].find((s2) => typeof scripts[s2] === "string");
22863
- if (run2) d.reasons.push(`it has a ${run2} script`);
23769
+ const run3 = ["start", "dev", "serve", "preview"].find((s2) => typeof scripts[s2] === "string");
23770
+ if (run3) d.reasons.push(`it has a ${run3} script`);
22864
23771
  if (files.has(`${path === "." ? "" : `${path}/`}index.html`)) d.reasons.push("it has an index.html");
22865
23772
  if (json3.engines?.vscode) d.reasons.push("it is a VS Code extension");
22866
23773
  for (const field of ["dependencies", "devDependencies", "peerDependencies", "optionalDependencies"]) {
@@ -23911,7 +24818,7 @@ function vbValues(files, texts, iniFiles) {
23911
24818
  }
23912
24819
  return void 0;
23913
24820
  };
23914
- const resolve27 = (expr, depth, seen) => {
24821
+ const resolve28 = (expr, depth, seen) => {
23915
24822
  let e2 = expr.trim();
23916
24823
  for (let w = WRAPPER.exec(e2); w; w = WRAPPER.exec(e2)) e2 = w[1].trim();
23917
24824
  const literal3 = /^"((?:[^"]|"")*)"$/.exec(e2);
@@ -23922,10 +24829,10 @@ function vbValues(files, texts, iniFiles) {
23922
24829
  if (!/^[A-Za-z_]\w*(?:\.[A-Za-z_]\w*)*\$?$/.test(e2) || depth > 6) return void 0;
23923
24830
  const key = e2.replace(/\$$/, "").replace(/^Me\./i, "").toLowerCase();
23924
24831
  if (seen.has(key)) return void 0;
23925
- const values = new Set((assigned.get(key) ?? []).map((v) => resolve27(v, depth + 1, /* @__PURE__ */ new Set([...seen, key]))).filter((v) => v !== void 0));
24832
+ const values = new Set((assigned.get(key) ?? []).map((v) => resolve28(v, depth + 1, /* @__PURE__ */ new Set([...seen, key]))).filter((v) => v !== void 0));
23926
24833
  return values.size === 1 ? [...values][0] : void 0;
23927
24834
  };
23928
- return { resolve: (expr) => resolve27(expr, 0, /* @__PURE__ */ new Set()) };
24835
+ return { resolve: (expr) => resolve28(expr, 0, /* @__PURE__ */ new Set()) };
23929
24836
  }
23930
24837
  var CONNECTION = /\b(?:Server|Database|Driver|Data Source|DSN|Provider|Initial Catalog|Dbq|Uid|Host)\s*=/i;
23931
24838
  function inlineValues(text3, values) {
@@ -24118,7 +25025,7 @@ function readCode(files, repo, units) {
24118
25025
  const accessNamed = /* @__PURE__ */ new Map();
24119
25026
  const accessUsers = /* @__PURE__ */ new Set();
24120
25027
  const valuesByUnit = /* @__PURE__ */ new Map();
24121
- const valuesOf2 = (unit) => {
25028
+ const valuesOf3 = (unit) => {
24122
25029
  const known = valuesByUnit.get(unit.id);
24123
25030
  if (known) return known;
24124
25031
  const mine = files.list.filter((f) => owner(units, f)?.id === unit.id);
@@ -24148,7 +25055,7 @@ function readCode(files, repo, units) {
24148
25055
  let text3 = configures.has(file) ? settingsFor(files, file, unit) : files.read(file);
24149
25056
  if (!text3) continue;
24150
25057
  const vb = VB_CODE.test(file);
24151
- if (vb) text3 = inlineValues(joinContinuations(withoutVbComments(text3)), valuesOf2(unit));
25058
+ if (vb) text3 = inlineValues(joinContinuations(withoutVbComments(text3)), valuesOf3(unit));
24152
25059
  if (config && /\.(ya?ml|properties|env|toml|conf|ini)$|(^|\/)\.env(\.[\w-]+)?$/i.test(file)) text3 = text3.replace(/^[ \t]*#.*$/gm, "").replace(/\.ini$/i.test(file) ? /^[ \t]*;.*$/gm : /$^/, "");
24153
25060
  const unresolved = text3;
24154
25061
  text3 = text3.replace(/\$\{([\w.-]+):([^${}\n]*)\}/g, (_, key, value) => value.startsWith("?") ? `\${${key}}` : value.replace(/^-/, ""));
@@ -24213,7 +25120,7 @@ function readCode(files, repo, units) {
24213
25120
  accessNamed.set(unit.id, [...accessNamed.get(unit.id) ?? [], { name: m[2], evidence: at(m.index) }]);
24214
25121
  }
24215
25122
  if (/\.(frm|dob|pag|ctl)$/i.test(file)) formAddress(text3, file, unit, repo, out, once);
24216
- const values = valuesOf2(unit);
25123
+ const values = valuesOf3(unit);
24217
25124
  const hostOf = (expr) => (values.resolve(expr) ?? /^"([^"]+)"$/.exec(expr.trim())?.[1] ?? expr.trim()).toLowerCase();
24218
25125
  const remoteHost = /\.RemoteHost\s*=\s*([^\n]+)/i.exec(text3)?.[1];
24219
25126
  const connects = [
@@ -24381,7 +25288,7 @@ function formAddress(text3, file, unit, repo, out, once) {
24381
25288
  // ../../packages/assay/src/domain.ts
24382
25289
  init_define_RADICAL_BUILD();
24383
25290
  import { readFileSync as readFileSync10 } from "fs";
24384
- import { extname as extname3, join as join29 } from "path";
25291
+ import { extname as extname3, join as join31 } from "path";
24385
25292
 
24386
25293
  // ../../packages/assay/src/laravel.ts
24387
25294
  init_define_RADICAL_BUILD();
@@ -24854,7 +25761,7 @@ function readRoutineCalls(files, repo, units) {
24854
25761
  init_define_RADICAL_BUILD();
24855
25762
  import { existsSync as existsSync17 } from "fs";
24856
25763
  import { createRequire as createRequire2 } from "module";
24857
- import { dirname as dirname21, join as join28 } from "path";
25764
+ import { dirname as dirname22, join as join30 } from "path";
24858
25765
  import { fileURLToPath as fileURLToPath3 } from "url";
24859
25766
 
24860
25767
  // ../../packages/assay/src/grammars.json
@@ -24874,20 +25781,20 @@ var grammars_default = {
24874
25781
  var GRAMMARS = grammars_default.grammars;
24875
25782
  var RUNTIME = grammars_default.runtime;
24876
25783
  function wasmDir() {
24877
- const beside = join28(dirname21(fileURLToPath3(import.meta.url)), "tree-sitter");
25784
+ const beside = join30(dirname22(fileURLToPath3(import.meta.url)), "tree-sitter");
24878
25785
  const shipped = RUNTIME[0].replace(/\.js$/, ".cjs");
24879
- if (existsSync17(join28(beside, shipped))) return { dir: beside, runtime: shipped };
24880
- return { dir: dirname21(createRequire2(import.meta.url).resolve("@vscode/tree-sitter-wasm")), runtime: RUNTIME[0] };
25786
+ if (existsSync17(join30(beside, shipped))) return { dir: beside, runtime: shipped };
25787
+ return { dir: dirname22(createRequire2(import.meta.url).resolve("@vscode/tree-sitter-wasm")), runtime: RUNTIME[0] };
24881
25788
  }
24882
25789
  var loaded;
24883
25790
  var loading;
24884
25791
  function prepareSyntax() {
24885
25792
  loading ??= (async () => {
24886
25793
  const { dir, runtime: file } = wasmDir();
24887
- const runtime = createRequire2(import.meta.url)(join28(dir, file));
24888
- await runtime.Parser.init({ locateFile: (name) => join28(dir, name) });
25794
+ const runtime = createRequire2(import.meta.url)(join30(dir, file));
25795
+ await runtime.Parser.init({ locateFile: (name) => join30(dir, name) });
24889
25796
  const languages = /* @__PURE__ */ new Map();
24890
- for (const [name, file2] of Object.entries(GRAMMARS)) languages.set(name, await runtime.Language.load(join28(dir, file2)));
25797
+ for (const [name, file2] of Object.entries(GRAMMARS)) languages.set(name, await runtime.Language.load(join30(dir, file2)));
24891
25798
  loaded = { parser: new runtime.Parser(), languages, Query: runtime.Query };
24892
25799
  })();
24893
25800
  return loading;
@@ -25531,7 +26438,7 @@ function readDomain(files, repo, units, named, used = [], access, dependencies =
25531
26438
  }
25532
26439
  let schema2;
25533
26440
  try {
25534
- schema2 = access(readFileSync10(join29(files.root, file)));
26441
+ schema2 = access(readFileSync10(join31(files.root, file)));
25535
26442
  } catch (error) {
25536
26443
  notes.push(`${file}: an Access file not read (${error.message.split("\n")[0]})`);
25537
26444
  continue;
@@ -25564,9 +26471,9 @@ function readDomain(files, repo, units, named, used = [], access, dependencies =
25564
26471
  const runByInstall = new Set(scripts.filter((f) => !TEARDOWN.test(f)).flatMap(runOf));
25565
26472
  const dropsOnly = (f) => ((t) => /\bdrop\s+\w/i.test(t) && !/\bcreate\b/i.test(t) && !/^\s*(?:@@?|start\s+)\S/im.test(t))(withoutSqlComments(files.read(f)));
25566
26473
  const resets = new Set(scripts.flatMap((runner) => {
25567
- const run2 = runOf(runner);
25568
- const first = run2.findIndex((f) => !dropsOnly(f));
25569
- return run2.filter((f, i) => dropsOnly(f) && first >= 0 && i < first);
26474
+ const run3 = runOf(runner);
26475
+ const first = run3.findIndex((f) => !dropsOnly(f));
26476
+ return run3.filter((f, i) => dropsOnly(f) && first >= 0 && i < first);
25570
26477
  }));
25571
26478
  for (const file of sqitchOrder(files, files.list).filter((f) => SQL_SCRIPT.test(f) && !DEV_TOOLING.test(f) && !/(^|\/)(tests?|__tests__|e2e|testdata|revert|verify)\//i.test(f) && !dumped(f) && !/\.down\.sql$|(^|\/)U\d+__[^/]*\.sql$/i.test(f))) {
25572
26479
  const schema2 = readSchema(files.read(file), file);
@@ -27044,11 +27951,11 @@ function openApiOperations(text3, file) {
27044
27951
  return ops;
27045
27952
  }
27046
27953
  function extractRepository(dir, options = {}) {
27047
- const given = resolve25(dir);
27954
+ const given = resolve26(dir);
27048
27955
  const repo = basename10(given);
27049
27956
  const root = realpathSync5(given);
27050
27957
  const facts = emptyFacts(repo, given);
27051
- if (existsSync18(join30(root, ".git"))) {
27958
+ if (existsSync18(join32(root, ".git"))) {
27052
27959
  try {
27053
27960
  const commit = execFileSync2("git", [...GIT, "rev-parse", "HEAD"], { cwd: root, stdio: ["ignore", "pipe", "ignore"] }).toString().trim();
27054
27961
  if (commit) facts.commit = commit;
@@ -27135,16 +28042,16 @@ function extractRepository(dir, options = {}) {
27135
28042
  return facts;
27136
28043
  }
27137
28044
  function reportFiles2(root, given, notes) {
27138
- const entries = given ?? (existsSync18(join30(root, "reports")) ? ["reports"] : []);
28045
+ const entries = given ?? (existsSync18(join32(root, "reports")) ? ["reports"] : []);
27139
28046
  const out = [];
27140
28047
  for (const entry of entries) {
27141
- const path = isAbsolute8(entry) ? entry : join30(root, entry);
28048
+ const path = isAbsolute8(entry) ? entry : join32(root, entry);
27142
28049
  if (!existsSync18(path)) {
27143
28050
  notes.push(`report ${entry} does not exist`);
27144
28051
  continue;
27145
28052
  }
27146
28053
  if (statSync5(path).isDirectory()) {
27147
- for (const f of readdirSync6(path).sort()) if (/\.(json|xml)$/i.test(f)) out.push(join30(path, f));
28054
+ for (const f of readdirSync6(path).sort()) if (/\.(json|xml)$/i.test(f)) out.push(join32(path, f));
27148
28055
  } else {
27149
28056
  out.push(path);
27150
28057
  }
@@ -27195,7 +28102,7 @@ function repositoryPath(root, file, files, byName, report) {
27195
28102
  if (!rel.startsWith("..") && files.has(rel)) return rel;
27196
28103
  } else {
27197
28104
  if (files.has(name)) return name;
27198
- const beside = posix(join30(report.includes("/") ? report.slice(0, report.lastIndexOf("/")) : ".", name));
28105
+ const beside = posix(join32(report.includes("/") ? report.slice(0, report.lastIndexOf("/")) : ".", name));
27199
28106
  if (files.has(beside)) return beside;
27200
28107
  }
27201
28108
  const base = name.slice(name.lastIndexOf("/") + 1);
@@ -27229,8 +28136,8 @@ function checksNothing(text3, at) {
27229
28136
  // ../../packages/assay/src/repositories.ts
27230
28137
  init_define_RADICAL_BUILD();
27231
28138
  import { existsSync as existsSync19, readdirSync as readdirSync7, statSync as statSync6 } from "fs";
27232
- import { basename as basename11, join as join31, resolve as resolve26 } from "path";
27233
- var isRepository = (dir) => existsSync19(join31(dir, ".git"));
28139
+ import { basename as basename11, join as join33, resolve as resolve27 } from "path";
28140
+ var isRepository = (dir) => existsSync19(join33(dir, ".git"));
27234
28141
  var DEPTH = 3;
27235
28142
  var ASIDE = /^(readme|license|licence|notice|changelog)(\.|$)/i;
27236
28143
  function repositoriesBelow(dir, depth) {
@@ -27238,7 +28145,7 @@ function repositoriesBelow(dir, depth) {
27238
28145
  const found = [];
27239
28146
  for (const d of readdirSync7(dir, { withFileTypes: true }).sort((a2, b) => a2.name.localeCompare(b.name))) {
27240
28147
  if (!d.isDirectory() || d.name.startsWith(".") || SKIPPED.has(d.name)) continue;
27241
- const path = join31(dir, d.name);
28148
+ const path = join33(dir, d.name);
27242
28149
  if (isRepository(path)) found.push(path);
27243
28150
  else found.push(...repositoriesBelow(path, depth - 1));
27244
28151
  }
@@ -27251,16 +28158,16 @@ function repositoriesIn(given, cwd = process.cwd(), unpackInto) {
27251
28158
  const notes = [];
27252
28159
  const unpacked = /* @__PURE__ */ new Set();
27253
28160
  for (const entry of given) {
27254
- let dir = resolve26(cwd, entry);
28161
+ let dir = resolve27(cwd, entry);
27255
28162
  if (existsSync19(dir) && statSync6(dir).isFile() && /\.zip$/i.test(dir)) {
27256
28163
  if (!unpackInto) throw new Error(`${entry}: a .zip file needs a folder to be unpacked into`);
27257
28164
  let name = safeName(basename11(dir).replace(/\.zip$/i, ""), "code");
27258
28165
  for (let i = 2, base = name; unpacked.has(name.toLowerCase()); i++) name = `${base}-${i}`;
27259
28166
  unpacked.add(name.toLowerCase());
27260
- const into = join31(unpackInto, name);
28167
+ const into = join33(unpackInto, name);
27261
28168
  const packed = unpackZip(dir, unpackInto, into);
27262
28169
  if (packed.length && !packed.includes("")) {
27263
- dirs.push(...packed.map((r) => join31(into, r)));
28170
+ dirs.push(...packed.map((r) => join33(into, r)));
27264
28171
  notes.push(`${entry} holds ${packed.length} repositor${packed.length === 1 ? "y" : "ies"} (${packed.join(", ")}): each is read as a folder of code, without its .git folder`);
27265
28172
  continue;
27266
28173
  }
@@ -27362,8 +28269,8 @@ ${ASSAY_USAGE}`);
27362
28269
  }
27363
28270
  let found;
27364
28271
  try {
27365
- if (parsed.positionals.some((p) => /\.zip$/i.test(p))) ignored(join32(io2.cwd, UNPACKED_DIR));
27366
- found = repositoriesIn(parsed.positionals, io2.cwd, join32(io2.cwd, UNPACKED_DIR));
28272
+ if (parsed.positionals.some((p) => /\.zip$/i.test(p))) ignored(join34(io2.cwd, UNPACKED_DIR));
28273
+ found = repositoriesIn(parsed.positionals, io2.cwd, join34(io2.cwd, UNPACKED_DIR));
27367
28274
  } catch (error) {
27368
28275
  io2.err(error.message);
27369
28276
  return 2;
@@ -27384,9 +28291,9 @@ ${ASSAY_USAGE}`);
27384
28291
  repositories.push(facts);
27385
28292
  const file = factsFileOf(dir, facts.repository, io2.cwd);
27386
28293
  try {
27387
- if (!isRepository(dir)) ignored(join32(io2.cwd, FOLDER_FACTS_DIR));
27388
- await mkdir13(dirname22(file), { recursive: true });
27389
- await writeFile13(file, serializeFacts(facts));
28294
+ if (!isRepository(dir)) ignored(join34(io2.cwd, FOLDER_FACTS_DIR));
28295
+ await mkdir14(dirname23(file), { recursive: true });
28296
+ await writeFile14(file, serializeFacts(facts));
27390
28297
  } catch (error) {
27391
28298
  facts.notes.push(`${file} not written: ${error.message}`);
27392
28299
  }
@@ -27497,7 +28404,7 @@ var io = {
27497
28404
  cli: { node: `"$(command -v node || echo '${process.execPath.replace(/\\/g, "/")}')"`, script: process.argv[1] },
27498
28405
  // This very CLI again, on its own: the git hook that started this one
27499
28406
  // returns at once, and nothing the child prints reaches it.
27500
- background: (args) => spawn8(process.execPath, [process.argv[1], ...args], { cwd: process.cwd(), detached: true, stdio: "ignore", windowsHide: true }).unref()
28407
+ background: (args) => spawn10(process.execPath, [process.argv[1], ...args], { cwd: process.cwd(), detached: true, stdio: "ignore", windowsHide: true }).unref()
27501
28408
  };
27502
28409
  main(process.argv.slice(2), io).then(
27503
28410
  (code) => {