@ohos-perf/core 0.22.4 → 0.24.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/index.d.ts +557 -35
  2. package/dist/index.js +1045 -225
  3. package/package.json +48 -48
package/dist/index.js CHANGED
@@ -562,8 +562,8 @@ function combined(result) {
562
562
  ${result.stderr}`;
563
563
  }
564
564
  var DETAIL_MAX_LINES = 5;
565
- function detail(text) {
566
- const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
565
+ function detail(text2) {
566
+ const lines = text2.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
567
567
  if (lines.length === 0) return "(no output)";
568
568
  const shown = lines.slice(0, DETAIL_MAX_LINES).join(" | ");
569
569
  return lines.length > DETAIL_MAX_LINES ? `${shown} | ... (${lines.length - DETAIL_MAX_LINES} more lines)` : shown;
@@ -749,8 +749,8 @@ var DONE_MARKER = "DONE";
749
749
  var SKELETON_MAX_BYTES = 2048;
750
750
  var MAX_DURATION_MS = 2147483647;
751
751
  var DETAIL_MAX_LINES2 = 5;
752
- function detail2(text) {
753
- const lines = text.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
752
+ function detail2(text2) {
753
+ const lines = text2.split(/\r?\n/).map((l) => l.trim()).filter((l) => l.length > 0);
754
754
  if (lines.length === 0) return "(no output)";
755
755
  const shown = lines.slice(0, DETAIL_MAX_LINES2).join(" | ");
756
756
  return lines.length > DETAIL_MAX_LINES2 ? `${shown} | ... (${lines.length - DETAIL_MAX_LINES2} more lines)` : shown;
@@ -1003,21 +1003,21 @@ var HITCH_WINDOW = /^\s*window \[\] Id\[(\d+)\]:\s*$/gm;
1003
1003
  var HITCH_16_67 = /^\s*more than 16\.67 ms\s+(\d+)\s*$/m;
1004
1004
  var HITCH_33 = /^\s*more than 33 ms\s+(\d+)\s*$/m;
1005
1005
  var HITCH_66 = /^\s*more than 66 ms\s+(\d+)\s*$/m;
1006
- function parseFpsCounts(text) {
1007
- const header = text.indexOf(FPS_HEADER);
1006
+ function parseFpsCounts(text2) {
1007
+ const header = text2.indexOf(FPS_HEADER);
1008
1008
  if (header < 0) return [];
1009
- const block = text.slice(header + FPS_HEADER.length);
1009
+ const block = text2.slice(header + FPS_HEADER.length);
1010
1010
  return [...block.matchAll(FPS_LINE)].map((match) => ({
1011
1011
  refreshRate: Number(match[1]),
1012
1012
  count: Number(match[2])
1013
1013
  }));
1014
1014
  }
1015
- function parseHitches(text) {
1016
- const headers = [...text.matchAll(HITCH_WINDOW)];
1015
+ function parseHitches(text2) {
1016
+ const headers = [...text2.matchAll(HITCH_WINDOW)];
1017
1017
  return headers.map((match, index) => {
1018
1018
  const start = (match.index ?? 0) + match[0].length;
1019
1019
  const next = headers[index + 1];
1020
- const block = text.slice(start, next?.index ?? text.length);
1020
+ const block = text2.slice(start, next?.index ?? text2.length);
1021
1021
  const count = (pattern, label2) => {
1022
1022
  const found = block.match(pattern);
1023
1023
  if (found === null) {
@@ -1215,9 +1215,9 @@ function parseHilogLine(line, year, captureNs) {
1215
1215
  parsed: true
1216
1216
  };
1217
1217
  }
1218
- function parseHilogText(text, opts) {
1219
- if (text === "") return [];
1220
- const parts = text.split(/\r?\n/);
1218
+ function parseHilogText(text2, opts) {
1219
+ if (text2 === "") return [];
1220
+ const parts = text2.split(/\r?\n/);
1221
1221
  if (parts.length > 0 && parts[parts.length - 1] === "") parts.pop();
1222
1222
  const year = opts.year;
1223
1223
  return parts.map((line, index) => {
@@ -1257,22 +1257,22 @@ var HilogCollector = class {
1257
1257
  assertDuration4(opts.durationMs);
1258
1258
  removeStaleArtifacts(layout);
1259
1259
  const result = await hdc.shellFor(target, HILOG_COMMAND, opts.durationMs);
1260
- const text = result.stdout;
1261
- if (text.trim() === "") {
1260
+ const text2 = result.stdout;
1261
+ if (text2.trim() === "") {
1262
1262
  throw new OhosPerfError(
1263
1263
  `hilog produced no output in ${opts.durationMs} ms` + (result.stderr.trim() === "" ? "" : `; device stderr: ${result.stderr.trim().slice(0, 200)}`),
1264
1264
  { code: "HILOG_NO_OUTPUT" }
1265
1265
  );
1266
1266
  }
1267
1267
  mkdirSync3(layout.root, { recursive: true });
1268
- writeFileSync3(layout.hilogFile, text);
1269
- const rows = parseHilogText(text, { captureNs: 0 });
1268
+ writeFileSync3(layout.hilogFile, text2);
1269
+ const rows = parseHilogText(text2, { captureNs: 0 });
1270
1270
  writeFileSync3(
1271
1271
  layout.hilogJsonlFile,
1272
1272
  rows.map((row2) => `${JSON.stringify(row2)}
1273
1273
  `).join("")
1274
1274
  );
1275
- const lines = text.split(/\r?\n/).filter((line) => line.trim() !== "").length;
1275
+ const lines = text2.split(/\r?\n/).filter((line) => line.trim() !== "").length;
1276
1276
  return { lines };
1277
1277
  }
1278
1278
  };
@@ -1291,10 +1291,10 @@ var EVENT_PATTERN = /^[a-z0-9-]+$/;
1291
1291
  var SAMPLES_MARKER = /\[ Sample records: (\d+), Non sample records: (\d+) \]/;
1292
1292
  var LOST_MARKER = /\[ Sample lost: (\d+), Non sample lost: (\d+) \]/;
1293
1293
  var NOT_DEBUGGABLE = /only support debug(?: or profileable)? application/;
1294
- function parseHiperfSummary(text) {
1295
- const samples = SAMPLES_MARKER.exec(text);
1294
+ function parseHiperfSummary(text2) {
1295
+ const samples = SAMPLES_MARKER.exec(text2);
1296
1296
  if (samples === null) return void 0;
1297
- const lost = LOST_MARKER.exec(text);
1297
+ const lost = LOST_MARKER.exec(text2);
1298
1298
  return {
1299
1299
  samples: Number(samples[1]),
1300
1300
  nonSamples: Number(samples[2]),
@@ -1390,8 +1390,8 @@ function combined3(result) {
1390
1390
  return `${result.stdout}
1391
1391
  ${result.stderr}`;
1392
1392
  }
1393
- function detail4(text) {
1394
- const lines = text.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
1393
+ function detail4(text2) {
1394
+ const lines = text2.split(/\r?\n/).map((line) => line.trim()).filter((line) => line.length > 0);
1395
1395
  if (lines.length === 0) return "(no output)";
1396
1396
  const shown = lines.slice(0, DETAIL_MAX_LINES3).join(" | ");
1397
1397
  return lines.length > DETAIL_MAX_LINES3 ? `${shown} | ... (${lines.length - DETAIL_MAX_LINES3} more lines)` : shown;
@@ -1458,15 +1458,15 @@ var MIN_INTERVAL_MS2 = 100;
1458
1458
  var APP_PATTERN2 = /^[A-Za-z0-9_.]+$/;
1459
1459
  var STATUS_FIELDS = /^(VmRSS|VmHWM|Threads):\s+(\d+)(?:\s+kB)?$/gm;
1460
1460
  var SMAPS_FIELDS = /^(Pss|Private_Dirty|SwapPss):\s+(\d+)(?:\s+kB)?$/gm;
1461
- function parseFields(text, pattern) {
1461
+ function parseFields(text2, pattern) {
1462
1462
  const values = /* @__PURE__ */ new Map();
1463
- for (const match of text.matchAll(pattern)) {
1463
+ for (const match of text2.matchAll(pattern)) {
1464
1464
  values.set(match[1], Number(match[2]));
1465
1465
  }
1466
1466
  return values;
1467
1467
  }
1468
- function parseProcfsStatus(text) {
1469
- const values = parseFields(text, STATUS_FIELDS);
1468
+ function parseProcfsStatus(text2) {
1469
+ const values = parseFields(text2, STATUS_FIELDS);
1470
1470
  const vmRssKb = values.get("VmRSS");
1471
1471
  const vmHwmKb = values.get("VmHWM");
1472
1472
  const threads = values.get("Threads");
@@ -1479,8 +1479,8 @@ function parseProcfsStatus(text) {
1479
1479
  threads
1480
1480
  };
1481
1481
  }
1482
- function parseSmapsRollup(text) {
1483
- const values = parseFields(text, SMAPS_FIELDS);
1482
+ function parseSmapsRollup(text2) {
1483
+ const values = parseFields(text2, SMAPS_FIELDS);
1484
1484
  const pssKb = values.get("Pss");
1485
1485
  const privateDirtyKb = values.get("Private_Dirty");
1486
1486
  const swapPssKb = values.get("SwapPss");
@@ -2600,14 +2600,14 @@ function assertKey(key) {
2600
2600
  `gesture key must be Back, Home, Power or a positive key code (got ${JSON.stringify(key)})`
2601
2601
  );
2602
2602
  }
2603
- function assertText(text) {
2604
- if (text === "") throw badGesture("gesture text must not be empty");
2605
- if (CONTROL_CHARS.test(text)) {
2603
+ function assertText(text2) {
2604
+ if (text2 === "") throw badGesture("gesture text must not be empty");
2605
+ if (CONTROL_CHARS.test(text2)) {
2606
2606
  throw badGesture("gesture text must not contain control characters");
2607
2607
  }
2608
2608
  }
2609
- function quote(text) {
2610
- return `'${text.replace(/'/g, "'\\''")}'`;
2609
+ function quote(text2) {
2610
+ return `'${text2.replace(/'/g, "'\\''")}'`;
2611
2611
  }
2612
2612
  function detail9(result) {
2613
2613
  const lines = `${result.stdout}
@@ -3149,8 +3149,8 @@ var UNSUPPORTED_PREFIX = "event not support";
3149
3149
  function parseBinaries(whichOutputs) {
3150
3150
  const binaries = {};
3151
3151
  for (const [name, output] of Object.entries(whichOutputs)) {
3152
- const text = output.trim();
3153
- binaries[name] = text !== "" && !text.includes("MISSING") && !text.includes("No such file");
3152
+ const text2 = output.trim();
3153
+ binaries[name] = text2 !== "" && !text2.includes("MISSING") && !text2.includes("No such file");
3154
3154
  }
3155
3155
  return binaries;
3156
3156
  }
@@ -3793,9 +3793,9 @@ function defaultCommonPaths3(env, platform) {
3793
3793
  paths.push(join6("C:", "Program Files", "Huawei", "DevEco Studio", ...tail));
3794
3794
  return paths;
3795
3795
  }
3796
- function parseEmuConfig(text) {
3796
+ function parseEmuConfig(text2) {
3797
3797
  const entries = {};
3798
- for (const line of text.split(/\r?\n/)) {
3798
+ for (const line of text2.split(/\r?\n/)) {
3799
3799
  const at = line.indexOf(":");
3800
3800
  if (at <= 0) continue;
3801
3801
  const key = line.slice(0, at).trim();
@@ -3817,13 +3817,13 @@ function readEmuConfigRoots(env, platform) {
3817
3817
  }
3818
3818
  const roots = {};
3819
3819
  for (const dir of dirs) {
3820
- let text;
3820
+ let text2;
3821
3821
  try {
3822
- text = readFileSync9(join6(huawei, dir, ".emu_config"), "utf8");
3822
+ text2 = readFileSync9(join6(huawei, dir, ".emu_config"), "utf8");
3823
3823
  } catch {
3824
3824
  continue;
3825
3825
  }
3826
- const entries = parseEmuConfig(text);
3826
+ const entries = parseEmuConfig(text2);
3827
3827
  if (roots.instancePath === void 0 && entries.emuPath) roots.instancePath = entries.emuPath;
3828
3828
  if (roots.imageRoot === void 0 && entries.imagePath) roots.imageRoot = entries.imagePath;
3829
3829
  if (roots.instancePath !== void 0 && roots.imageRoot !== void 0) break;
@@ -4733,9 +4733,9 @@ function compileRules(rules) {
4733
4733
  return {
4734
4734
  name: rule.name,
4735
4735
  match(line) {
4736
- const text = rule.scope === "line" ? renderLine(line) : line.message;
4736
+ const text2 = rule.scope === "line" ? renderLine(line) : line.message;
4737
4737
  regex.lastIndex = 0;
4738
- const hit = regex.exec(text);
4738
+ const hit = regex.exec(text2);
4739
4739
  if (hit === null) return void 0;
4740
4740
  const extracted = groupIndexes.map((index) => {
4741
4741
  if (index === 0) return hit[0];
@@ -5495,12 +5495,12 @@ function parseSelector(value, path) {
5495
5495
  checkKeys(value, selectorKind, path);
5496
5496
  switch (selectorKind) {
5497
5497
  case "text": {
5498
- const text = requiredText(value.text, `${path}.text`);
5498
+ const text2 = requiredText(value.text, `${path}.text`);
5499
5499
  const exact = value.exact;
5500
5500
  if (exact !== void 0 && typeof exact !== "boolean") {
5501
5501
  bad3(`${path}.exact`, "expected true or false");
5502
5502
  }
5503
- return exact === void 0 ? { kind: "text", text } : { kind: "text", text, exact };
5503
+ return exact === void 0 ? { kind: "text", text: text2 } : { kind: "text", text: text2, exact };
5504
5504
  }
5505
5505
  case "id":
5506
5506
  return { kind: "id", id: requiredText(value.id, `${path}.id`) };
@@ -5728,11 +5728,11 @@ function requiredString(value, path, error) {
5728
5728
  return value;
5729
5729
  }
5730
5730
  function bareName(value, path, error) {
5731
- const text = requiredString(value, path, error);
5732
- if (!BARE_NAME2.test(text)) {
5733
- throw error(path, `expected a bare name matching ${String(BARE_NAME2)}, got ${JSON.stringify(text)}`);
5731
+ const text2 = requiredString(value, path, error);
5732
+ if (!BARE_NAME2.test(text2)) {
5733
+ throw error(path, `expected a bare name matching ${String(BARE_NAME2)}, got ${JSON.stringify(text2)}`);
5734
5734
  }
5735
- return text;
5735
+ return text2;
5736
5736
  }
5737
5737
  function positiveInt(value, path, error) {
5738
5738
  if (typeof value !== "number" || !Number.isSafeInteger(value) || value <= 0) {
@@ -5747,11 +5747,11 @@ function nonNegativeInt(value, path, error) {
5747
5747
  return value;
5748
5748
  }
5749
5749
  function gestureText(value, path, error) {
5750
- const text = requiredString(value, path, error);
5751
- if (CONTROL_CHARS2.test(text)) {
5750
+ const text2 = requiredString(value, path, error);
5751
+ if (CONTROL_CHARS2.test(text2)) {
5752
5752
  throw error(path, "expected no control characters");
5753
5753
  }
5754
- return text;
5754
+ return text2;
5755
5755
  }
5756
5756
  var ACTION_KEYS = {
5757
5757
  launch: ["kind", "ability"],
@@ -5845,14 +5845,14 @@ function parseAction(value, path, error) {
5845
5845
  };
5846
5846
  }
5847
5847
  case "tapText": {
5848
- const text = requiredString(action.text, at("text"), error);
5849
- if (text === "") {
5848
+ const text2 = requiredString(action.text, at("text"), error);
5849
+ if (text2 === "") {
5850
5850
  throw error(at("text"), "expected a non-empty label; an empty one matches every node");
5851
5851
  }
5852
5852
  const scrollTo = action.scrollTo === void 0 ? void 0 : parseSelector(action.scrollTo, at("scrollTo"));
5853
5853
  return {
5854
5854
  kind: "tapText",
5855
- text,
5855
+ text: text2,
5856
5856
  ...scrollTo === void 0 ? {} : { scrollTo }
5857
5857
  };
5858
5858
  }
@@ -6043,10 +6043,10 @@ function parseExpectation(value, path) {
6043
6043
  ...foreground === void 0 ? {} : { foreground }
6044
6044
  };
6045
6045
  }
6046
- function parseScenario(text) {
6046
+ function parseScenario(text2) {
6047
6047
  let parsed;
6048
6048
  try {
6049
- parsed = JSON.parse(text);
6049
+ parsed = JSON.parse(text2);
6050
6050
  } catch (err) {
6051
6051
  throw new OhosPerfError(
6052
6052
  `invalid scenario: not valid JSON (${err instanceof Error ? err.message : String(err)})`,
@@ -6137,9 +6137,9 @@ function discoverCases(dir, filter) {
6137
6137
  }
6138
6138
  function loadCases(cases) {
6139
6139
  return cases.map((entry) => {
6140
- let text;
6140
+ let text2;
6141
6141
  try {
6142
- text = readFileSync11(entry.path, "utf8");
6142
+ text2 = readFileSync11(entry.path, "utf8");
6143
6143
  } catch (err) {
6144
6144
  return {
6145
6145
  id: entry.id,
@@ -6148,7 +6148,7 @@ function loadCases(cases) {
6148
6148
  };
6149
6149
  }
6150
6150
  try {
6151
- return { id: entry.id, path: entry.path, scenario: parseScenario(text) };
6151
+ return { id: entry.id, path: entry.path, scenario: parseScenario(text2) };
6152
6152
  } catch (err) {
6153
6153
  return { id: entry.id, path: entry.path, error: `${basename(entry.path)}: ${message(err)}` };
6154
6154
  }
@@ -6375,6 +6375,34 @@ var PARITY_ROWS = [
6375
6375
  name: "Report comparison",
6376
6376
  status: "ported",
6377
6377
  reason: ""
6378
+ },
6379
+ /*
6380
+ * Rows 36–39 were added after the pinned revision. They keep counting from
6381
+ * 35 so a reader can tell the original inventory from what followed it.
6382
+ */
6383
+ {
6384
+ row: 36,
6385
+ name: "Root-cause narrative (`root-cause`)",
6386
+ status: "ported",
6387
+ reason: ""
6388
+ },
6389
+ {
6390
+ row: 37,
6391
+ name: "Debug HAP build (`build`, wraps deveco-cli)",
6392
+ status: "out",
6393
+ reason: "this is a build tool, not a measurement: it invokes deveco-cli to produce a debug package. A package analyzer cannot own the toolchain that compiles the package it reads, and a half-ported wrapper would make every measurement depend on a compiler version this package does not control. `hap` and `opt` read what the build produced instead."
6394
+ },
6395
+ {
6396
+ row: 38,
6397
+ name: "LLM exploration strategy and state comparator (`haptest`)",
6398
+ status: "ported",
6399
+ reason: ""
6400
+ },
6401
+ {
6402
+ row: 39,
6403
+ name: "Thermal analysis (`hidumper -s ThermalService`)",
6404
+ status: "missing",
6405
+ reason: "a collector plus an analyzer, so it is a capability of its own rather than part of the root-cause narrative: HapRay samples each sensor through hidumper and reports start/end/peak/mean and the rise. Not ported yet; the collector is the part that has to be measured on a device first, because a sensor list that is assumed rather than read would produce a thermal curve for a sensor the device lacks."
6378
6406
  }
6379
6407
  ];
6380
6408
  function paritySummary() {
@@ -6392,10 +6420,10 @@ function paritySummary() {
6392
6420
  }
6393
6421
 
6394
6422
  // src/analyze/redundant-file.ts
6395
- function parseRedundantFile(text) {
6423
+ function parseRedundantFile(text2) {
6396
6424
  const byPath2 = /* @__PURE__ */ new Map();
6397
6425
  let reads = 0;
6398
- const lines = text.split(/\r?\n/);
6426
+ const lines = text2.split(/\r?\n/);
6399
6427
  for (let index = 0; index < lines.length; index += 1) {
6400
6428
  const line = lines[index].trim();
6401
6429
  if (line === "" || line.startsWith("#")) continue;
@@ -6430,8 +6458,8 @@ var RedundantFileAnalyzer = class {
6430
6458
  id = "redundant-file";
6431
6459
  requires = [];
6432
6460
  async run(ctx) {
6433
- const text = ctx.redundantFile;
6434
- if (text === void 0) {
6461
+ const text2 = ctx.redundantFile;
6462
+ if (text2 === void 0) {
6435
6463
  return {
6436
6464
  metrics: [],
6437
6465
  evidence: [
@@ -6448,7 +6476,7 @@ var RedundantFileAnalyzer = class {
6448
6476
  ]
6449
6477
  };
6450
6478
  }
6451
- const report = parseRedundantFile(text);
6479
+ const report = parseRedundantFile(text2);
6452
6480
  const make = (id, value) => metric({
6453
6481
  id,
6454
6482
  value,
@@ -7303,9 +7331,9 @@ function renderReportHtml(model) {
7303
7331
  // src/report/csv.ts
7304
7332
  function cell(value) {
7305
7333
  if (value === void 0) return "";
7306
- const text = String(value);
7307
- if (!/[,",\n\r]/.test(text)) return text;
7308
- return `"${text.replace(/"/g, '""')}"`;
7334
+ const text2 = String(value);
7335
+ if (!/[,",\n\r]/.test(text2)) return text2;
7336
+ return `"${text2.replace(/"/g, '""')}"`;
7309
7337
  }
7310
7338
  function row(fields2) {
7311
7339
  return fields2.map(cell).join(",") + "\n";
@@ -7704,10 +7732,10 @@ function readSummary(value, section) {
7704
7732
  };
7705
7733
  return { lines: ratio("lines"), functions: ratio("functions"), branches: ratio("branches") };
7706
7734
  }
7707
- function parseCoverageReport(text) {
7735
+ function parseCoverageReport(text2) {
7708
7736
  let document;
7709
7737
  try {
7710
- document = JSON.parse(text);
7738
+ document = JSON.parse(text2);
7711
7739
  } catch (err) {
7712
7740
  throw new OhosPerfError(
7713
7741
  `coverageReport.json is not valid JSON: ${err.message}`,
@@ -7753,8 +7781,8 @@ var CoverageAnalyzer = class {
7753
7781
  id = "coverage";
7754
7782
  requires = [];
7755
7783
  async run(ctx) {
7756
- const text = ctx.coverage;
7757
- if (text === void 0) {
7784
+ const text2 = ctx.coverage;
7785
+ if (text2 === void 0) {
7758
7786
  return {
7759
7787
  metrics: [],
7760
7788
  evidence: [
@@ -7771,7 +7799,7 @@ var CoverageAnalyzer = class {
7771
7799
  ]
7772
7800
  };
7773
7801
  }
7774
- const report = parseCoverageReport(text);
7802
+ const report = parseCoverageReport(text2);
7775
7803
  const make = (id, value, unit) => metric({
7776
7804
  id,
7777
7805
  value,
@@ -8054,6 +8082,51 @@ function swipeInside(rect, direction, travel) {
8054
8082
 
8055
8083
  // src/scenario/explore.ts
8056
8084
  import { createHash as createHash2 } from "node:crypto";
8085
+
8086
+ // src/scenario/guard.ts
8087
+ var IRREVERSIBLE_PATTERNS = [
8088
+ {
8089
+ pattern: /\bpay\b|\bpay now\b|立即支付|确认支付|去支付|立即购买/i,
8090
+ why: "payment is irreversible",
8091
+ sample: "\u7ACB\u5373\u652F\u4ED8"
8092
+ },
8093
+ {
8094
+ pattern: /\b(?:confirm order|place order|submit order|buy now)\b|提交订单|确认下单/i,
8095
+ why: "placing an order is irreversible",
8096
+ sample: "Confirm order"
8097
+ },
8098
+ {
8099
+ pattern: /\btransfer\b|\bsend money\b|\bremit\b|转账/i,
8100
+ why: "a transfer moves money and cannot be undone",
8101
+ sample: "Transfer"
8102
+ },
8103
+ {
8104
+ pattern: /\b(?:log ?in|sign ?in|register|sign ?up)\b|登录|注册/i,
8105
+ why: "signing in changes the account state",
8106
+ sample: "Log in"
8107
+ },
8108
+ {
8109
+ pattern: /\b(?:delete|unsubscribe|publish|post|share)\b|删除|注销|发布/i,
8110
+ why: "the action destroys or publishes content",
8111
+ sample: "Delete"
8112
+ }
8113
+ ];
8114
+ function labelsOf(node) {
8115
+ const labels = [node.text.trim(), node.id.replace(/[_-]+/g, " ").trim()];
8116
+ return labels.filter((label2) => label2 !== "");
8117
+ }
8118
+ function irreversibleReason(node) {
8119
+ for (const label2 of labelsOf(node)) {
8120
+ for (const entry of IRREVERSIBLE_PATTERNS) {
8121
+ if (entry.pattern.test(label2)) return entry.why;
8122
+ }
8123
+ }
8124
+ return void 0;
8125
+ }
8126
+
8127
+ // src/scenario/explore.ts
8128
+ var SCROLLS_PER_SCREEN = 3;
8129
+ var BACKS_PER_SCREEN = 1;
8057
8130
  var DEFAULT_SEED = 0;
8058
8131
  var DIGEST_CHARS = 16;
8059
8132
  function canonical(tree) {
@@ -8072,7 +8145,25 @@ function canonical(tree) {
8072
8145
  return tree.map(line).join("");
8073
8146
  }
8074
8147
  function hashTree(tree) {
8075
- return createHash2("sha256").update(canonical(tree)).digest("hex").slice(0, DIGEST_CHARS);
8148
+ return digest(canonical(tree));
8149
+ }
8150
+ function digest(text2) {
8151
+ return createHash2("sha256").update(text2).digest("hex").slice(0, DIGEST_CHARS);
8152
+ }
8153
+ function pageCanonical(tree) {
8154
+ const line = (node) => [
8155
+ node.bundleName,
8156
+ node.abilityName,
8157
+ node.depth,
8158
+ node.type,
8159
+ node.clickable ? "1" : "0",
8160
+ node.enabled ? "1" : "0",
8161
+ node.scrollable ? "1" : "0"
8162
+ ].map((field2) => `${String(field2).length}:${String(field2)}`).join("");
8163
+ return tree.map(line).join("");
8164
+ }
8165
+ function hashPageShape(tree) {
8166
+ return digest(pageCanonical(tree));
8076
8167
  }
8077
8168
  function mulberry32(seed) {
8078
8169
  let state = seed >>> 0;
@@ -8110,25 +8201,57 @@ function rectOf(node) {
8110
8201
  return node.boundsRect ?? parseBounds(node.bounds);
8111
8202
  }
8112
8203
  function planNextAction(state) {
8113
- const ids = identities(state.tree);
8114
- const candidates = state.tree.filter(
8115
- (node2) => node2.clickable && node2.enabled && rectOf(node2) !== void 0 && !state.visited.has(ids.get(node2))
8116
- );
8117
- if (candidates.length === 0) return void 0;
8118
- let ordered2;
8119
- switch (state.strategy) {
8204
+ const first = orderCandidates(candidatesOf(state), state.strategy, state.seed)[0];
8205
+ if (first === void 0) return void 0;
8206
+ return { kind: "tap", nodeId: first.identity, bounds: first.node.bounds };
8207
+ }
8208
+ function orderCandidates(candidates, strategy, seed) {
8209
+ switch (strategy) {
8120
8210
  case "depth_first":
8121
- ordered2 = candidates;
8122
- break;
8211
+ return candidates;
8123
8212
  case "breadth_first":
8124
- ordered2 = [...candidates].sort((a, b) => a.depth - b.depth);
8125
- break;
8213
+ return [...candidates].sort((a, b) => a.node.depth - b.node.depth);
8126
8214
  case "random":
8127
- ordered2 = shuffled(candidates, state.seed ?? DEFAULT_SEED);
8128
- break;
8215
+ return shuffled(candidates, seed ?? DEFAULT_SEED);
8216
+ }
8217
+ }
8218
+ function offerOf(candidate) {
8219
+ return {
8220
+ identity: candidate.identity,
8221
+ type: candidate.node.type,
8222
+ text: candidate.node.text,
8223
+ bounds: candidate.node.bounds,
8224
+ depth: candidate.node.depth
8225
+ };
8226
+ }
8227
+ function candidatesOf(state) {
8228
+ const ids = identities(state.tree);
8229
+ const out = [];
8230
+ for (const node of state.tree) {
8231
+ if (!node.clickable || !node.enabled) continue;
8232
+ if (rectOf(node) === void 0) continue;
8233
+ if (state.app !== void 0 && node.bundleName !== "" && node.bundleName !== state.app) continue;
8234
+ const identity = ids.get(node);
8235
+ if (state.visited.has(identity)) continue;
8236
+ out.push({ node, identity });
8237
+ }
8238
+ return out;
8239
+ }
8240
+ function scrollableNode(tree, app) {
8241
+ return tree.find(
8242
+ (node) => node.scrollable && node.enabled && rectOf(node) !== void 0 && (app === void 0 || node.bundleName === "" || node.bundleName === app)
8243
+ );
8244
+ }
8245
+ function isOutsideApp(tree, app) {
8246
+ if (app === void 0) return false;
8247
+ const bundles = tree.map((node) => node.bundleName).filter((bundle) => bundle !== "");
8248
+ return bundles.length > 0 && !bundles.includes(app);
8249
+ }
8250
+ function trailIndexFor(trail, page) {
8251
+ for (let index = trail.length - 1; index >= 0; index -= 1) {
8252
+ if (trail[index].page === page) return index;
8129
8253
  }
8130
- const node = ordered2[0];
8131
- return { kind: "tap", nodeId: ids.get(node), bounds: node.bounds };
8254
+ return -1;
8132
8255
  }
8133
8256
  async function explore(device, options) {
8134
8257
  if (!Number.isSafeInteger(options.maxSteps) || options.maxSteps < 1) {
@@ -8139,45 +8262,175 @@ async function explore(device, options) {
8139
8262
  const seed = options.strategy === "random" ? options.seed ?? DEFAULT_SEED : void 0;
8140
8263
  const steps = [];
8141
8264
  const states = /* @__PURE__ */ new Set();
8265
+ const pages = /* @__PURE__ */ new Set();
8142
8266
  const visitedByScreen = /* @__PURE__ */ new Map();
8267
+ const scrollsByScreen = /* @__PURE__ */ new Map();
8268
+ const backsByScreen = /* @__PURE__ */ new Map();
8269
+ const proposals = options.choose === void 0 ? void 0 : { used: 0, refused: 0, refusals: [] };
8143
8270
  let tree = await device.dump();
8144
8271
  let hash = hashTree(tree);
8272
+ let page = hashPageShape(tree);
8145
8273
  states.add(hash);
8146
- let exhausted = false;
8274
+ pages.add(page);
8275
+ const trail = [{ hash, page }];
8276
+ let stoppedBy = "budget";
8147
8277
  while (steps.length < options.maxSteps) {
8148
- const visited = visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set();
8149
- const action = planNextAction({
8278
+ const state = {
8150
8279
  tree,
8151
- visited,
8280
+ visited: visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set(),
8152
8281
  strategy: options.strategy,
8153
- ...seed === void 0 ? {} : { seed }
8154
- });
8155
- if (action === void 0) {
8156
- exhausted = true;
8282
+ ...seed === void 0 ? {} : { seed },
8283
+ ...options.app === void 0 ? {} : { app: options.app }
8284
+ };
8285
+ const outside = isOutsideApp(tree, options.app);
8286
+ const target = outside ? void 0 : scrollableNode(tree, options.app);
8287
+ const canScroll = device.swipe !== void 0 && target !== void 0 && (scrollsByScreen.get(hash) ?? 0) < SCROLLS_PER_SCREEN;
8288
+ const canBack = device.back !== void 0 && trail.length > 1 && (backsByScreen.get(hash) ?? 0) < BACKS_PER_SCREEN;
8289
+ const all = candidatesOf(state);
8290
+ const allowed = options.choose === void 0 ? all : all.filter((candidate) => irreversibleReason(candidate.node) === void 0);
8291
+ const ordered2 = orderCandidates(allowed, options.strategy, seed);
8292
+ let decision;
8293
+ let decidedBy = "strategy";
8294
+ let reason;
8295
+ if (options.choose !== void 0 && allowed.length > 0) {
8296
+ const proposal = await options.choose({
8297
+ ...options.app === void 0 ? {} : { app: options.app },
8298
+ step: steps.length,
8299
+ maxSteps: options.maxSteps,
8300
+ screen: tree,
8301
+ candidates: allowed.map(offerOf),
8302
+ history: steps.slice(),
8303
+ canScroll,
8304
+ canBack
8305
+ });
8306
+ let refusal2;
8307
+ switch (proposal.kind) {
8308
+ case "tap": {
8309
+ const match2 = allowed.find(
8310
+ (candidate) => candidate.identity === proposal.identity
8311
+ );
8312
+ if (match2 === void 0) {
8313
+ refusal2 = `the chooser named ${JSON.stringify(proposal.identity)}, which is not among the ${allowed.length} offered element(s)`;
8314
+ } else {
8315
+ decision = { kind: "tap", nodeId: match2.identity, bounds: match2.node.bounds };
8316
+ decidedBy = "model";
8317
+ reason = proposal.reason;
8318
+ }
8319
+ break;
8320
+ }
8321
+ case "scroll":
8322
+ if (!canScroll) {
8323
+ refusal2 = "the chooser asked to scroll, but this screen has no scrollable node left to swipe";
8324
+ } else {
8325
+ decision = {
8326
+ kind: "scroll",
8327
+ bounds: target.bounds,
8328
+ direction: proposal.direction
8329
+ };
8330
+ decidedBy = "model";
8331
+ reason = proposal.reason;
8332
+ }
8333
+ break;
8334
+ case "back":
8335
+ if (!canBack) {
8336
+ refusal2 = "the chooser asked to go back, but the walk has no earlier page to return to";
8337
+ } else {
8338
+ decision = { kind: "back" };
8339
+ decidedBy = "model";
8340
+ reason = proposal.reason;
8341
+ }
8342
+ break;
8343
+ case "stop":
8344
+ stoppedBy = "model";
8345
+ break;
8346
+ case "refusal":
8347
+ refusal2 = proposal.detail;
8348
+ break;
8349
+ }
8350
+ if (proposals !== void 0) {
8351
+ if (decision !== void 0) proposals.used += 1;
8352
+ if (refusal2 !== void 0) {
8353
+ proposals.refused += 1;
8354
+ proposals.refusals.push({ step: steps.length, detail: refusal2 });
8355
+ }
8356
+ }
8357
+ if (stoppedBy === "model") break;
8358
+ }
8359
+ if (decision === void 0) {
8360
+ if (outside) {
8361
+ if (canBack) decision = { kind: "back" };
8362
+ } else {
8363
+ const first = ordered2[0];
8364
+ if (first !== void 0) {
8365
+ decision = { kind: "tap", nodeId: first.identity, bounds: first.node.bounds };
8366
+ } else if (canScroll) {
8367
+ decision = { kind: "scroll", bounds: target.bounds, direction: "up" };
8368
+ } else if (canBack) {
8369
+ decision = { kind: "back" };
8370
+ }
8371
+ }
8372
+ }
8373
+ if (decision === void 0) {
8374
+ stoppedBy = outside ? "left_app" : "exhausted";
8157
8375
  break;
8158
8376
  }
8159
- visited.add(action.nodeId);
8160
- visitedByScreen.set(hash, visited);
8161
- await device.tap(action.bounds);
8377
+ switch (decision.kind) {
8378
+ case "tap": {
8379
+ const visited = visitedByScreen.get(hash) ?? /* @__PURE__ */ new Set();
8380
+ visited.add(decision.nodeId);
8381
+ visitedByScreen.set(hash, visited);
8382
+ await device.tap(decision.bounds);
8383
+ break;
8384
+ }
8385
+ case "scroll":
8386
+ scrollsByScreen.set(hash, (scrollsByScreen.get(hash) ?? 0) + 1);
8387
+ await device.swipe(decision.bounds, decision.direction);
8388
+ break;
8389
+ case "back":
8390
+ backsByScreen.set(hash, (backsByScreen.get(hash) ?? 0) + 1);
8391
+ await device.back();
8392
+ break;
8393
+ }
8162
8394
  tree = await device.dump();
8163
8395
  const after = hashTree(tree);
8396
+ const afterPage = hashPageShape(tree);
8164
8397
  states.add(after);
8398
+ pages.add(afterPage);
8399
+ const outcome = after === hash ? "no_change" : afterPage === page ? "updated" : "navigated";
8165
8400
  steps.push({
8166
8401
  index: steps.length,
8167
- nodeId: action.nodeId,
8168
- bounds: action.bounds,
8402
+ kind: decision.kind,
8403
+ ...decision.kind === "tap" ? { nodeId: decision.nodeId, bounds: decision.bounds } : decision.kind === "scroll" ? { bounds: decision.bounds } : {},
8169
8404
  before: hash,
8170
8405
  after,
8171
- outcome: after === hash ? "no_change" : "navigated"
8406
+ outcome,
8407
+ decidedBy,
8408
+ ...reason === void 0 ? {} : { reason }
8172
8409
  });
8410
+ const match = trailIndexFor(trail, afterPage);
8411
+ if (match !== -1) {
8412
+ trail.length = match + 1;
8413
+ trail[match] = { hash: after, page: afterPage };
8414
+ } else if (afterPage !== page) {
8415
+ trail.push({ hash: after, page: afterPage });
8416
+ } else {
8417
+ trail[trail.length - 1] = { hash: after, page: afterPage };
8418
+ }
8173
8419
  hash = after;
8420
+ page = afterPage;
8174
8421
  }
8175
8422
  return {
8176
8423
  strategy: options.strategy,
8177
8424
  ...seed === void 0 ? {} : { seed },
8178
8425
  steps,
8179
8426
  statesReached: states.size,
8180
- exhausted
8427
+ pagesReached: pages.size,
8428
+ pages: [...pages],
8429
+ scrolls: steps.filter((step) => step.kind === "scroll").length,
8430
+ backs: steps.filter((step) => step.kind === "back").length,
8431
+ stoppedBy,
8432
+ exhausted: stoppedBy === "exhausted",
8433
+ ...proposals === void 0 ? {} : { proposals }
8181
8434
  };
8182
8435
  }
8183
8436
  var DEFAULT_SETTLE_MS = 5e3;
@@ -8196,27 +8449,30 @@ function explorationDevice(host, options = {}) {
8196
8449
  if (settled === void 0) settled = await host.dump();
8197
8450
  return settled;
8198
8451
  };
8199
- return {
8200
- dump: read,
8201
- async tap(bounds) {
8202
- const before = hashTree(await read());
8203
- await host.tap(bounds);
8204
- const deadline = host.now() + settleMs;
8205
- for (; ; ) {
8206
- const next = await host.dump();
8207
- if (hashTree(next) !== before) {
8208
- settled = next;
8209
- return;
8210
- }
8211
- const remaining = deadline - host.now();
8212
- if (remaining <= 0) {
8213
- settled = next;
8214
- return;
8215
- }
8216
- await host.sleep(Math.min(pollMs, remaining));
8452
+ const act = async (perform) => {
8453
+ const before = hashTree(await read());
8454
+ await perform();
8455
+ const deadline = host.now() + settleMs;
8456
+ for (; ; ) {
8457
+ const next = await host.dump();
8458
+ if (hashTree(next) !== before) {
8459
+ settled = next;
8460
+ return;
8217
8461
  }
8462
+ const remaining = deadline - host.now();
8463
+ if (remaining <= 0) {
8464
+ settled = next;
8465
+ return;
8466
+ }
8467
+ await host.sleep(Math.min(pollMs, remaining));
8218
8468
  }
8219
8469
  };
8470
+ return {
8471
+ dump: read,
8472
+ tap: (bounds) => act(() => host.tap(bounds)),
8473
+ ...host.swipe === void 0 ? {} : { swipe: (bounds, direction) => act(() => host.swipe(bounds, direction)) },
8474
+ ...host.back === void 0 ? {} : { back: () => act(() => host.back()) }
8475
+ };
8220
8476
  }
8221
8477
  var ACCEPTED_MARKER3 = "No Error";
8222
8478
  function deviceExplorationHost(device, options = {}) {
@@ -8228,6 +8484,15 @@ function deviceExplorationHost(device, options = {}) {
8228
8484
  ...options.settleMs === void 0 ? {} : { settleMs: options.settleMs },
8229
8485
  ...options.pollMs === void 0 ? {} : { pollMs: options.pollMs }
8230
8486
  };
8487
+ const perform = async (gesture, label2) => {
8488
+ const result = await device.gesture(gesture);
8489
+ if (!result.output.includes(ACCEPTED_MARKER3)) {
8490
+ throw new OhosPerfError(
8491
+ `exploration: uitest uiInput ${label2} did not report "${ACCEPTED_MARKER3}": ${result.output === "" ? "(no output)" : result.output}`,
8492
+ { code: "SCENARIO_ACTION_FAILED" }
8493
+ );
8494
+ }
8495
+ };
8231
8496
  return explorationDevice(
8232
8497
  {
8233
8498
  dump: () => device.uiTree(),
@@ -8240,20 +8505,54 @@ function deviceExplorationHost(device, options = {}) {
8240
8505
  { code: "SCENARIO_EXPLORE_STALE" }
8241
8506
  );
8242
8507
  }
8243
- const result = await device.gesture({ action: "click", x: point.x, y: point.y });
8244
- if (!result.output.includes(ACCEPTED_MARKER3)) {
8508
+ await perform({ action: "click", x: point.x, y: point.y }, "click");
8509
+ },
8510
+ swipe: async (bounds, direction) => {
8511
+ const rect = rectOfBounds(bounds);
8512
+ const tree = await device.uiTree();
8513
+ const target = tree.find((candidate) => candidate.bounds === bounds);
8514
+ if (target === void 0) {
8245
8515
  throw new OhosPerfError(
8246
- `exploration: uitest uiInput click did not report "${ACCEPTED_MARKER3}": ${result.output === "" ? "(no output)" : result.output}`,
8247
- { code: "SCENARIO_ACTION_FAILED" }
8516
+ `exploration: no node on the current screen carries these bounds ${JSON.stringify(bounds)}; the target is not on the screen any more`,
8517
+ { code: "SCENARIO_EXPLORE_STALE" }
8518
+ );
8519
+ }
8520
+ if (!target.scrollable) {
8521
+ throw new OhosPerfError(
8522
+ `exploration: the node at ${JSON.stringify(bounds)} is not scrollable, so a swipe on it would drag whatever happens to be under that rect`,
8523
+ { code: "SCENARIO_EXPLORE_STALE" }
8248
8524
  );
8249
8525
  }
8526
+ const { from, to } = swipePoints(rect, direction);
8527
+ await perform(
8528
+ { action: "swipe", fromX: from.x, fromY: from.y, toX: to.x, toY: to.y },
8529
+ `swipe ${direction}`
8530
+ );
8250
8531
  },
8532
+ back: () => perform({ action: "key", key: "Back" }, "key Back"),
8251
8533
  now: () => clock.now(),
8252
8534
  sleep: (ms) => clock.sleep(ms)
8253
8535
  },
8254
8536
  settleOptions
8255
8537
  );
8256
8538
  }
8539
+ function rectOfBounds(bounds) {
8540
+ const rect = parseBounds(bounds);
8541
+ if (rect === void 0) {
8542
+ throw new OhosPerfError(
8543
+ `exploration: ${JSON.stringify(bounds)} is not a "[l,t][r,b]" bounds string; it has no swipe path`,
8544
+ { code: "SCENARIO_EXPLORE_STALE" }
8545
+ );
8546
+ }
8547
+ return rect;
8548
+ }
8549
+ function swipePoints(rect, direction) {
8550
+ const x = Math.round((rect.left + rect.right) / 2);
8551
+ const height = rect.bottom - rect.top;
8552
+ const upper = Math.round(rect.top + height * 0.2);
8553
+ const lower = Math.round(rect.top + height * 0.8);
8554
+ return direction === "up" ? { from: { x, y: lower }, to: { x, y: upper } } : { from: { x, y: upper }, to: { x, y: lower } };
8555
+ }
8257
8556
  function centreOfBounds(bounds) {
8258
8557
  const rect = parseBounds(bounds);
8259
8558
  if (rect === void 0) {
@@ -8579,45 +8878,6 @@ function writeRunFiles(outDir, result) {
8579
8878
  }
8580
8879
 
8581
8880
  // src/scenario/agent.ts
8582
- var IRREVERSIBLE_PATTERNS = [
8583
- {
8584
- pattern: /\bpay\b|\bpay now\b|立即支付|确认支付|去支付|立即购买/i,
8585
- why: "payment is irreversible",
8586
- sample: "\u7ACB\u5373\u652F\u4ED8"
8587
- },
8588
- {
8589
- pattern: /\b(?:confirm order|place order|submit order|buy now)\b|提交订单|确认下单/i,
8590
- why: "placing an order is irreversible",
8591
- sample: "Confirm order"
8592
- },
8593
- {
8594
- pattern: /\btransfer\b|\bsend money\b|\bremit\b|转账/i,
8595
- why: "a transfer moves money and cannot be undone",
8596
- sample: "Transfer"
8597
- },
8598
- {
8599
- pattern: /\b(?:log ?in|sign ?in|register|sign ?up)\b|登录|注册/i,
8600
- why: "signing in changes the account state",
8601
- sample: "Log in"
8602
- },
8603
- {
8604
- pattern: /\b(?:delete|unsubscribe|publish|post|share)\b|删除|注销|发布/i,
8605
- why: "the action destroys or publishes content",
8606
- sample: "Delete"
8607
- }
8608
- ];
8609
- function labelsOf(node) {
8610
- const labels = [node.text.trim(), node.id.replace(/[_-]+/g, " ").trim()];
8611
- return labels.filter((label2) => label2 !== "");
8612
- }
8613
- function irreversibleReason(node) {
8614
- for (const label2 of labelsOf(node)) {
8615
- for (const entry of IRREVERSIBLE_PATTERNS) {
8616
- if (entry.pattern.test(label2)) return entry.why;
8617
- }
8618
- }
8619
- return void 0;
8620
- }
8621
8881
  function describeDecision(decision) {
8622
8882
  if ("done" in decision) return "done";
8623
8883
  const action = decision.action;
@@ -8634,8 +8894,8 @@ function describeDecision(decision) {
8634
8894
  return `type ${JSON.stringify(action.text)}`;
8635
8895
  }
8636
8896
  }
8637
- function oneLine(text) {
8638
- return text.replace(/\r?\n/g, "\\n").replace(/\t/g, "\\t");
8897
+ function oneLine(text2) {
8898
+ return text2.replace(/\r?\n/g, "\\n").replace(/\t/g, "\\t");
8639
8899
  }
8640
8900
  function renderTree(tree) {
8641
8901
  if (tree.length === 0) {
@@ -8722,17 +8982,17 @@ function parseGesture(value) {
8722
8982
  }
8723
8983
  return value;
8724
8984
  }
8725
- function unfence(text) {
8726
- const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text);
8727
- return match === null ? text : match[1];
8985
+ function unfence(text2) {
8986
+ const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text2);
8987
+ return match === null ? text2 : match[1];
8728
8988
  }
8729
- function parseDecision(text) {
8989
+ function parseDecision(text2) {
8730
8990
  let parsed;
8731
8991
  try {
8732
- parsed = JSON.parse(unfence(text));
8992
+ parsed = JSON.parse(unfence(text2));
8733
8993
  } catch {
8734
8994
  throw badInput(
8735
- `the model's answer is not JSON: ${JSON.stringify(text.slice(0, 120))}`
8995
+ `the model's answer is not JSON: ${JSON.stringify(text2.slice(0, 120))}`
8736
8996
  );
8737
8997
  }
8738
8998
  const decision = assertDecision(parsed, 0);
@@ -8973,7 +9233,7 @@ function typeOf(info) {
8973
9233
  function symbolTableOf(dv, sections, links, bytes, index) {
8974
9234
  const section = sections[index];
8975
9235
  const link = links[index];
8976
- const strings = link >= 0 && link < sections.length ? bytes.subarray(sections[link].offset, sections[link].offset + sections[link].size) : new Uint8Array(0);
9236
+ const strings2 = link >= 0 && link < sections.length ? bytes.subarray(sections[link].offset, sections[link].offset + sections[link].size) : new Uint8Array(0);
8977
9237
  const entrySize = section.entrySize === 0 ? 24 : section.entrySize;
8978
9238
  const count = Math.floor(section.size / entrySize);
8979
9239
  const symbols = [];
@@ -8985,7 +9245,7 @@ function symbolTableOf(dv, sections, links, bytes, index) {
8985
9245
  const sectionIndex = field(dv, base + 6, 2, "st_shndx");
8986
9246
  const value = field(dv, base + 8, 8, "st_value");
8987
9247
  const size = field(dv, base + 16, 8, "st_size");
8988
- const name = readString(strings, nameOffset);
9248
+ const name = readString(strings2, nameOffset);
8989
9249
  symbols.push({ name, bind: bindOf(info), type: typeOf(info), size, value, sectionIndex });
8990
9250
  }
8991
9251
  return symbols;
@@ -9069,9 +9329,9 @@ function readElf(bytes) {
9069
9329
  }
9070
9330
  }
9071
9331
  const nameTable = raw[shstrndx];
9072
- const strings = bytes.subarray(nameTable.offset, nameTable.offset + nameTable.size);
9332
+ const strings2 = bytes.subarray(nameTable.offset, nameTable.offset + nameTable.size);
9073
9333
  const sections = raw.map((section) => ({
9074
- name: readString(strings, section.nameOffset),
9334
+ name: readString(strings2, section.nameOffset),
9075
9335
  type: section.type,
9076
9336
  flags: section.flags,
9077
9337
  offset: section.offset,
@@ -9209,13 +9469,13 @@ function recoverSymbols(bytes, unresolved) {
9209
9469
  }
9210
9470
  var PLACEHOLDER = /^(?:fcn|sym|sub|loc|unk|fun)[._][0-9a-f]+$/i;
9211
9471
  function normaliseName(name) {
9212
- let text = name.trim();
9213
- text = text.replace(/^(?:sym\.(?:imp\.)?|fcn\.)/i, "");
9214
- text = text.replace(/\(.*\)$/, "");
9215
- text = text.replace(/\s*->.*$/, "");
9216
- text = text.replace(/^_Z\d+/, "");
9217
- text = text.replace(/^_+/, "");
9218
- return text.toLowerCase();
9472
+ let text2 = name.trim();
9473
+ text2 = text2.replace(/^(?:sym\.(?:imp\.)?|fcn\.)/i, "");
9474
+ text2 = text2.replace(/\(.*\)$/, "");
9475
+ text2 = text2.replace(/\s*->.*$/, "");
9476
+ text2 = text2.replace(/^_Z\d+/, "");
9477
+ text2 = text2.replace(/^_+/, "");
9478
+ return text2.toLowerCase();
9219
9479
  }
9220
9480
  function isNameable(symbol) {
9221
9481
  if (symbol.type !== "func" || symbol.size === 0) return false;
@@ -9231,12 +9491,12 @@ async function measureNaming(bytes, answer) {
9231
9491
  size: symbol.size,
9232
9492
  bind: symbol.bind
9233
9493
  })).sort((a, b) => a.start - b.start || (a.truth < b.truth ? -1 : a.truth > b.truth ? 1 : 0));
9234
- const text = elf.bytesOf(".text");
9494
+ const text2 = elf.bytesOf(".text");
9235
9495
  const textStart = elf.section(".text")?.offset ?? 0;
9236
9496
  const bodyOf = (start, size) => {
9237
9497
  const from = start - textStart;
9238
- if (from < 0 || from + size > text.length) return new Uint8Array(0);
9239
- return text.subarray(from, from + size);
9498
+ if (from < 0 || from + size > text2.length) return new Uint8Array(0);
9499
+ return text2.subarray(from, from + size);
9240
9500
  };
9241
9501
  const cases = [];
9242
9502
  for (const held_out of held) {
@@ -9273,6 +9533,7 @@ async function measureNaming(bytes, answer) {
9273
9533
  }
9274
9534
 
9275
9535
  // src/scenario/agent-client.ts
9536
+ var GUI_TURN = { prompt: agentPrompt, parse: parseDecision };
9276
9537
  var OWN_BASE_URL = "OHOS_PERF_AGENT_BASE_URL";
9277
9538
  var OWN_API_KEY = "OHOS_PERF_AGENT_API_KEY";
9278
9539
  var OWN_MODEL = "OHOS_PERF_AGENT_MODEL";
@@ -9324,20 +9585,20 @@ function contentOf(body) {
9324
9585
  }
9325
9586
  return content;
9326
9587
  }
9327
- function httpAgentModel(options) {
9588
+ function httpChatModel(options) {
9328
9589
  const baseUrl = options.baseUrl.trim().replace(/\/+$/, "");
9329
9590
  const model = options.model.trim();
9330
- if (baseUrl === "") throw badClient("the agent base URL must not be empty");
9331
- if (model === "") throw badClient("the agent model name must not be empty");
9591
+ if (baseUrl === "") throw badClient("the model base URL must not be empty");
9592
+ if (model === "") throw badClient("the model name must not be empty");
9332
9593
  const url = `${baseUrl}/chat/completions`;
9333
9594
  const timeoutMs = options.timeoutMs ?? DEFAULT_TIMEOUT_MS4;
9334
9595
  return {
9335
- async decide(turn) {
9596
+ async complete(prompt) {
9336
9597
  const body = {
9337
9598
  model,
9338
- messages: [{ role: "user", content: agentPrompt(turn) }],
9339
- // The answer is JSON the loop parses, so the endpoint is asked for JSON
9340
- // rather than for prose that happens to contain some.
9599
+ messages: [{ role: "user", content: prompt }],
9600
+ // The answers this package reads are JSON, so the endpoint is asked
9601
+ // for JSON rather than for prose that happens to contain some.
9341
9602
  response_format: { type: "json_object" }
9342
9603
  };
9343
9604
  let response;
@@ -9353,38 +9614,204 @@ function httpAgentModel(options) {
9353
9614
  });
9354
9615
  } catch (err) {
9355
9616
  throw new OhosPerfError(
9356
- `the agent endpoint could not be reached: ${err.message}`,
9617
+ `the model endpoint could not be reached: ${err.message}`,
9357
9618
  { code: "AGENT_UNREACHABLE", cause: err }
9358
9619
  );
9359
9620
  }
9360
- const text = await response.text();
9621
+ const text2 = await response.text();
9361
9622
  if (!response.ok) {
9362
9623
  throw new OhosPerfError(
9363
- `the agent endpoint answered ${response.status}: ${text.slice(0, EXCERPT_CHARS)}`,
9624
+ `the model endpoint answered ${response.status}: ${text2.slice(0, EXCERPT_CHARS)}`,
9364
9625
  { code: "AGENT_HTTP_ERROR" }
9365
9626
  );
9366
9627
  }
9367
- const content = contentOf(safeJson(text));
9628
+ const content = contentOf(safeJson(text2));
9368
9629
  if (content.trim() === "") {
9369
9630
  throw new OhosPerfError("the model returned an empty answer", {
9370
9631
  code: "AGENT_BAD_RESPONSE"
9371
9632
  });
9372
9633
  }
9373
- return parseDecision(content);
9634
+ return content;
9635
+ }
9636
+ };
9637
+ }
9638
+ function httpAgentModel(options) {
9639
+ const shape = options.shape ?? GUI_TURN;
9640
+ const chat = httpChatModel(options);
9641
+ return {
9642
+ async decide(turn) {
9643
+ return shape.parse(await chat.complete(shape.prompt(turn)));
9374
9644
  }
9375
9645
  };
9376
9646
  }
9377
- function safeJson(text) {
9647
+ function safeJson(text2) {
9378
9648
  try {
9379
- return JSON.parse(text);
9649
+ return JSON.parse(text2);
9380
9650
  } catch {
9381
9651
  throw new OhosPerfError(
9382
- `the agent endpoint answered with something that is not JSON: ${text.slice(0, EXCERPT_CHARS)}`,
9652
+ `the agent endpoint answered with something that is not JSON: ${text2.slice(0, EXCERPT_CHARS)}`,
9383
9653
  { code: "AGENT_BAD_RESPONSE" }
9384
9654
  );
9385
9655
  }
9386
9656
  }
9387
9657
 
9658
+ // src/scenario/llm-strategy.ts
9659
+ var HISTORY_LIMIT = 8;
9660
+ var EXCERPT_CHARS2 = 200;
9661
+ function refusal(detail11) {
9662
+ return { action: "refused", detail: detail11 };
9663
+ }
9664
+ function explorationPrompt(turn) {
9665
+ const elements = turn.elements.length === 0 ? "(no element is left to choose on this screen)" : turn.elements.map(
9666
+ (element) => `${element.index}. ${element.type} ${JSON.stringify(oneLine2(element.text))} bounds=${element.bounds} depth=${element.depth}`
9667
+ ).join("\n");
9668
+ const history = turn.history.length === 0 ? "(no steps yet)" : turn.history.join("\n");
9669
+ const actions = [
9670
+ "tap",
9671
+ ...turn.canScroll ? ["scroll"] : [],
9672
+ ...turn.canBack ? ["back"] : [],
9673
+ "stop"
9674
+ ];
9675
+ const formats = [
9676
+ ' {"action": "tap", "element": 0, "reason": "why this element"}',
9677
+ ...turn.canScroll ? [' {"action": "scroll", "direction": "up", "reason": "why"}'] : [],
9678
+ ...turn.canBack ? [' {"action": "back", "reason": "why"}'] : [],
9679
+ ' {"action": "stop", "reason": "why"}'
9680
+ ];
9681
+ return [
9682
+ `You are exploring the OHOS app ${turn.app ?? "(the app on screen)"} to reach as many distinct pages as possible.`,
9683
+ `Step ${turn.step + 1} of ${turn.maxSteps}.`,
9684
+ "",
9685
+ "The current screen, one node per line:",
9686
+ turn.screen,
9687
+ "",
9688
+ "Elements you may choose, with their index:",
9689
+ elements,
9690
+ "",
9691
+ "Steps so far:",
9692
+ history,
9693
+ "",
9694
+ `Available actions: ${actions.join(", ")}.`,
9695
+ "Answer with one JSON object and nothing else:",
9696
+ ...formats,
9697
+ "An element index that was not offered is refused."
9698
+ ].join("\n");
9699
+ }
9700
+ function oneLine2(text2) {
9701
+ return text2.replace(/\s+/g, " ").trim();
9702
+ }
9703
+ function unfence2(text2) {
9704
+ const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text2);
9705
+ return match === null ? text2 : match[1];
9706
+ }
9707
+ var ACTIONS = /* @__PURE__ */ new Set(["tap", "scroll", "back", "stop"]);
9708
+ function parseStrategyAnswer(content) {
9709
+ let parsed;
9710
+ try {
9711
+ parsed = JSON.parse(unfence2(content.trim()));
9712
+ } catch {
9713
+ return refusal(
9714
+ `the model's answer is not JSON: ${JSON.stringify(content.slice(0, EXCERPT_CHARS2))}`
9715
+ );
9716
+ }
9717
+ if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) {
9718
+ return refusal("the model's answer is not a JSON object");
9719
+ }
9720
+ const record = parsed;
9721
+ const action = record["action"];
9722
+ if (typeof action !== "string" || !ACTIONS.has(action)) {
9723
+ return refusal(
9724
+ `the model's answer must have an "action" of tap, scroll, back or stop (got ${JSON.stringify(action)})`
9725
+ );
9726
+ }
9727
+ const reason = typeof record["reason"] === "string" ? record["reason"] : "";
9728
+ switch (action) {
9729
+ case "tap": {
9730
+ const element = record["element"];
9731
+ if (typeof element !== "number" || !Number.isSafeInteger(element) || element < 0) {
9732
+ return refusal(
9733
+ `the model's "element" must be a non-negative integer (got ${JSON.stringify(element)})`
9734
+ );
9735
+ }
9736
+ return { action: "tap", element, reason };
9737
+ }
9738
+ case "scroll": {
9739
+ const direction = record["direction"];
9740
+ if (direction !== "up" && direction !== "down") {
9741
+ return refusal(
9742
+ `the model's scroll "direction" must be up or down (got ${JSON.stringify(direction)})`
9743
+ );
9744
+ }
9745
+ return { action: "scroll", direction, reason };
9746
+ }
9747
+ case "back":
9748
+ return { action: "back", reason };
9749
+ default:
9750
+ return { action: "stop", reason };
9751
+ }
9752
+ }
9753
+ function strategyTurn(context) {
9754
+ return {
9755
+ ...context.app === void 0 ? {} : { app: context.app },
9756
+ step: context.step,
9757
+ maxSteps: context.maxSteps,
9758
+ screen: renderTree(context.screen),
9759
+ elements: context.candidates.map((candidate, index) => ({
9760
+ index,
9761
+ type: candidate.type,
9762
+ text: candidate.text,
9763
+ bounds: candidate.bounds,
9764
+ depth: candidate.depth
9765
+ })),
9766
+ history: context.history.slice(-HISTORY_LIMIT).map(historyLine),
9767
+ canScroll: context.canScroll,
9768
+ canBack: context.canBack
9769
+ };
9770
+ }
9771
+ function historyLine(step) {
9772
+ const what = step.kind === "tap" ? `tap ${step.nodeId ?? "(unknown)"}` : step.kind;
9773
+ const why = step.reason === void 0 ? "" : ` \u2014 ${step.reason}`;
9774
+ return `${step.index + 1}. ${what} \u2192 ${step.outcome}${why}`;
9775
+ }
9776
+ function llmChooser(model) {
9777
+ return async (context) => {
9778
+ const answer = parseStrategyAnswer(
9779
+ await model.complete(explorationPrompt(strategyTurn(context)))
9780
+ );
9781
+ if (answer.action === "refused") return { kind: "refusal", detail: answer.detail };
9782
+ switch (answer.action) {
9783
+ case "tap": {
9784
+ const candidate = context.candidates[answer.element];
9785
+ if (candidate === void 0) {
9786
+ return {
9787
+ kind: "refusal",
9788
+ detail: `the model chose element ${answer.element}, but ${context.candidates.length} element(s) were offered`
9789
+ };
9790
+ }
9791
+ return { kind: "tap", identity: candidate.identity, reason: answer.reason };
9792
+ }
9793
+ case "scroll":
9794
+ if (!context.canScroll) {
9795
+ return {
9796
+ kind: "refusal",
9797
+ detail: "the model asked to scroll, but this screen has no scrollable node left to swipe"
9798
+ };
9799
+ }
9800
+ return { kind: "scroll", direction: answer.direction, reason: answer.reason };
9801
+ case "back":
9802
+ if (!context.canBack) {
9803
+ return {
9804
+ kind: "refusal",
9805
+ detail: "the model asked to go back, but the walk has no earlier page to return to"
9806
+ };
9807
+ }
9808
+ return { kind: "back", reason: answer.reason };
9809
+ default:
9810
+ return { kind: "stop", reason: answer.reason };
9811
+ }
9812
+ };
9813
+ }
9814
+
9388
9815
  // src/query/rows.ts
9389
9816
  function num(value) {
9390
9817
  if (value == null) return 0;
@@ -10495,7 +10922,7 @@ ORDER BY id`,
10495
10922
  const dict = /* @__PURE__ */ new Map();
10496
10923
  if (!this.hasTable("data_dict")) return dict;
10497
10924
  const ids = [...new Set(
10498
- frames.map((frame) => frameName(frame.name)).filter((text) => /^\d+$/.test(text)).map((text) => Number(text))
10925
+ frames.map((frame) => frameName(frame.name)).filter((text2) => /^\d+$/.test(text2)).map((text2) => Number(text2))
10499
10926
  )].filter((id) => id !== 0).sort((a, b) => a - b);
10500
10927
  if (ids.length === 0) return dict;
10501
10928
  const rows = this.db.query(
@@ -10505,8 +10932,8 @@ ORDER BY id`,
10505
10932
  ids
10506
10933
  );
10507
10934
  for (const row2 of rows) {
10508
- const text = str(row2.data).trim();
10509
- if (text !== "") dict.set(num(row2.id), text);
10935
+ const text2 = str(row2.data).trim();
10936
+ if (text2 !== "") dict.set(num(row2.id), text2);
10510
10937
  }
10511
10938
  return dict;
10512
10939
  }
@@ -10710,8 +11137,8 @@ LEFT JOIN data_dict kd ON a.key = kd.id
10710
11137
  LEFT JOIN data_dict vd ON a.value = vd.id AND a.datatype = 1
10711
11138
  WHERE c.name LIKE '%binder%'`;
10712
11139
  function parseCode(value) {
10713
- const text = String(value).trim();
10714
- const first = text.split(/\s+/)[0] ?? "";
11140
+ const text2 = String(value).trim();
11141
+ const first = text2.split(/\s+/)[0] ?? "";
10715
11142
  if (!first.startsWith("0x")) return value;
10716
11143
  const parsed = Number.parseInt(first, 16);
10717
11144
  return Number.isNaN(parsed) ? value : parsed;
@@ -13477,18 +13904,18 @@ function divideRoundHalfEven(numerator, denominator) {
13477
13904
  return quotient;
13478
13905
  }
13479
13906
  function decimalText(quotient, digits) {
13480
- let text = quotient.toString();
13907
+ let text2 = quotient.toString();
13481
13908
  if (digits > 0) {
13482
- if (text.length <= digits) {
13483
- text = `0.${"0".repeat(digits - text.length)}${text}`;
13909
+ if (text2.length <= digits) {
13910
+ text2 = `0.${"0".repeat(digits - text2.length)}${text2}`;
13484
13911
  } else {
13485
- const split = text.length - digits;
13486
- text = `${text.slice(0, split)}.${text.slice(split)}`;
13912
+ const split = text2.length - digits;
13913
+ text2 = `${text2.slice(0, split)}.${text2.slice(split)}`;
13487
13914
  }
13488
13915
  } else if (digits < 0) {
13489
- text += "0".repeat(-digits);
13916
+ text2 += "0".repeat(-digits);
13490
13917
  }
13491
- return text;
13918
+ return text2;
13492
13919
  }
13493
13920
  function roundedDecimalText(value, digits) {
13494
13921
  const { negative, mantissa, exponent } = exactDouble(value);
@@ -16433,14 +16860,14 @@ function appProcessName9(ctx) {
16433
16860
  }
16434
16861
  function treeStats(nodes) {
16435
16862
  let clickable = 0;
16436
- let text = 0;
16863
+ let text2 = 0;
16437
16864
  let depth = 0;
16438
16865
  for (const node of nodes) {
16439
16866
  if (node.clickable) clickable += 1;
16440
- if (node.text !== "") text += 1;
16867
+ if (node.text !== "") text2 += 1;
16441
16868
  if (node.depth > depth) depth = node.depth;
16442
16869
  }
16443
- return { nodes: nodes.length, clickable, text, depth };
16870
+ return { nodes: nodes.length, clickable, text: text2, depth };
16444
16871
  }
16445
16872
  function treeMetrics(ctx, nodes) {
16446
16873
  if (nodes === void 0) {
@@ -18936,12 +19363,12 @@ var EntryReader = class {
18936
19363
  };
18937
19364
  function matchContent(ruleId, rule, data) {
18938
19365
  if (data === void 0) return { matched: false };
18939
- const text = new TextDecoder("utf-8").decode(data);
19366
+ const text2 = new TextDecoder("utf-8").decode(data);
18940
19367
  let best;
18941
19368
  for (const item of rule.patterns ?? []) {
18942
19369
  const source = typeof item === "string" ? item : item.pattern;
18943
19370
  const own = typeof item === "string" ? void 0 : item.confidence;
18944
- if (!compile(ruleId, source).test(text)) continue;
19371
+ if (!compile(ruleId, source).test(text2)) continue;
18945
19372
  const confidence = own ?? rule.confidence ?? 1;
18946
19373
  best = best === void 0 ? confidence : Math.max(best, confidence);
18947
19374
  }
@@ -19534,9 +19961,9 @@ function findDuplicates(archive, inventory) {
19534
19961
  for (const file of bucket) {
19535
19962
  const entry = entriesByName.get(file.path);
19536
19963
  if (entry === void 0) continue;
19537
- const digest = sha256(archive.read(entry));
19538
- const group = byHash.get(digest);
19539
- if (group === void 0) byHash.set(digest, [file]);
19964
+ const digest2 = sha256(archive.read(entry));
19965
+ const group = byHash.get(digest2);
19966
+ if (group === void 0) byHash.set(digest2, [file]);
19540
19967
  else group.push(file);
19541
19968
  }
19542
19969
  }
@@ -19832,10 +20259,10 @@ function drawFrame(frame, x, width, total, out) {
19832
20259
  out.push(
19833
20260
  `<rect x="${round(x)}" y="${y}" width="${round(width)}" height="${FRAME_HEIGHT}" fill="${fill}"><title>${escapeHtml(frame.path)} (${frame.weight} samples, ${share3}%)</title></rect>`
19834
20261
  );
19835
- const text = label(frame.name);
19836
- if (text !== "" && width >= 24) {
20262
+ const text2 = label(frame.name);
20263
+ if (text2 !== "" && width >= 24) {
19837
20264
  out.push(
19838
- `<text x="${round(x + 4)}" y="${y + 13}" fill="#1c1f24" font-size="11" font-family="system-ui, sans-serif">${escapeHtml(text)}</text>`
20265
+ `<text x="${round(x + 4)}" y="${y + 13}" fill="#1c1f24" font-size="11" font-family="system-ui, sans-serif">${escapeHtml(text2)}</text>`
19839
20266
  );
19840
20267
  }
19841
20268
  }
@@ -19936,6 +20363,382 @@ function renderFlamegraphHtml(input) {
19936
20363
  ""
19937
20364
  ].join("\n");
19938
20365
  }
20366
+
20367
+ // src/report/root-cause.ts
20368
+ var ROOT_CAUSE_SCHEMA_VERSION = 1;
20369
+ var SEVERITY_RANK = {
20370
+ critical: 0,
20371
+ warn: 1,
20372
+ info: 2
20373
+ };
20374
+ function rankObservations(evidence2) {
20375
+ return [...evidence2].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity] || (a.id < b.id ? -1 : a.id > b.id ? 1 : 0)).map((item) => ({
20376
+ evidenceId: item.id,
20377
+ kind: item.kind,
20378
+ severity: item.severity,
20379
+ explain: item.explain,
20380
+ // Only the identity a reader needs; `pid` and `rule` are not part of the
20381
+ // narrative and would make the document's shape depend on the analyzer.
20382
+ subject: {
20383
+ process: item.subject.process,
20384
+ ...item.subject.thread === void 0 ? {} : { thread: item.subject.thread },
20385
+ ...item.subject.frameNo === void 0 ? {} : { frameNo: item.subject.frameNo }
20386
+ },
20387
+ signals: { ...item.signals }
20388
+ }));
20389
+ }
20390
+ function countSeverities(evidence2) {
20391
+ const totals = { info: 0, warn: 0, critical: 0, gaps: 0 };
20392
+ for (const item of evidence2) {
20393
+ totals[item.severity] += 1;
20394
+ if (isGap(item)) totals.gaps += 1;
20395
+ }
20396
+ return totals;
20397
+ }
20398
+ function isGap(item) {
20399
+ if (item.kind === "degraded_capability" || item.kind === "no_data") return true;
20400
+ return Object.keys(item.signals).length === 0;
20401
+ }
20402
+ function observationIsGap(item) {
20403
+ if (item.kind === "degraded_capability" || item.kind === "no_data") return true;
20404
+ return Object.keys(item.signals).length === 0;
20405
+ }
20406
+ function verdictFor(ranked, total, gaps) {
20407
+ if (total === 0) {
20408
+ return "no evidence was produced for this scene, so there is nothing to explain";
20409
+ }
20410
+ const finding = ranked.find((item) => !observationIsGap(item));
20411
+ if (finding === void 0) {
20412
+ return `nothing was measured: all ${total} observation${total === 1 ? "" : "s"} report a gap in the capture, not a finding about the app`;
20413
+ }
20414
+ const more = total === 1 ? "" : ` (and ${total - 1} other observation${total === 2 ? "" : "s"}${gaps === 0 ? "" : `, ${gaps} of them gaps in the capture`})`;
20415
+ return `${finding.severity}: ${finding.explain}${more}`;
20416
+ }
20417
+ function buildRootCauseDocument(input) {
20418
+ const ranked = rankObservations(input.evidence);
20419
+ const totals = countSeverities(input.evidence);
20420
+ return {
20421
+ schemaVersion: ROOT_CAUSE_SCHEMA_VERSION,
20422
+ generator: { ...input.generator },
20423
+ scene: {
20424
+ app: input.app,
20425
+ device: input.device,
20426
+ window: { startNs: input.window.startNs, endNs: input.window.endNs }
20427
+ },
20428
+ summary: {
20429
+ totals,
20430
+ verdict: verdictFor(ranked, input.evidence.length, totals.gaps)
20431
+ },
20432
+ observations: ranked
20433
+ };
20434
+ }
20435
+
20436
+ // src/report/root-cause-model.ts
20437
+ var PROMPT_EVIDENCE_LIMIT = 40;
20438
+ var BAD_RESPONSE = "ROOT_CAUSE_BAD_RESPONSE";
20439
+ function badResponse(message3) {
20440
+ return new OhosPerfError(message3, { code: BAD_RESPONSE });
20441
+ }
20442
+ var ANSWER_SHAPE = [
20443
+ "{",
20444
+ ' "summary": "one sentence naming the dominant cause",',
20445
+ ' "suspects": [',
20446
+ " {",
20447
+ ' "evidenceIds": ["the ids you reasoned from"],',
20448
+ ' "rootCause": "1-2 sentences",',
20449
+ ' "fix": "what to change",',
20450
+ ' "confidence": "high | medium | low",',
20451
+ ' "triggerChain": "optional: A -> B -> C"',
20452
+ " }",
20453
+ " ],",
20454
+ ' "caveats": ["what limits this conclusion"],',
20455
+ ' "needsMoreData": ["what would raise confidence"]',
20456
+ "}"
20457
+ ].join("\n");
20458
+ function rootCausePrompt(document) {
20459
+ const observations = document.observations.slice(0, PROMPT_EVIDENCE_LIMIT);
20460
+ const omitted = document.observations.length - observations.length;
20461
+ const lines = observations.map((item) => {
20462
+ const subject = item.subject.thread === void 0 ? item.subject.process : `${item.subject.process}/${item.subject.thread}`;
20463
+ const signals = Object.keys(item.signals).sort().map((key) => `${key}=${String(item.signals[key])}`).join(", ");
20464
+ return `- [${item.evidenceId}] ${item.severity} ${item.kind} ${subject}: ${item.explain}` + (signals === "" ? "" : ` {${signals}}`);
20465
+ });
20466
+ return [
20467
+ "You are explaining the measured performance evidence for one app run.",
20468
+ "Every observation below was produced by an analyzer in this package; the",
20469
+ "bracketed id is what you must cite.",
20470
+ "",
20471
+ `app ${document.scene.app === "unknown" ? "(not identified in this capture)" : document.scene.app} on ${document.scene.device === "offline" ? "an offline analysis" : document.scene.device}`,
20472
+ `verdict ${document.summary.verdict}`,
20473
+ "",
20474
+ "Observations:",
20475
+ ...lines.length === 0 ? ["(none)"] : lines,
20476
+ ...omitted <= 0 ? [] : [`(${omitted} lower-severity observations omitted)`],
20477
+ "",
20478
+ "Answer with one JSON object and nothing else:",
20479
+ ANSWER_SHAPE,
20480
+ "",
20481
+ "Rules:",
20482
+ "- Cite only ids that appear above; an id you invent is rejected and recorded.",
20483
+ "- Name a file, symbol, library or thread only if it appears above.",
20484
+ "- If the evidence does not support a cause, say so in caveats rather than guessing."
20485
+ ].join("\n");
20486
+ }
20487
+ function turnFor(document) {
20488
+ return {
20489
+ task: "explain the root cause of the measured performance evidence",
20490
+ app: document.scene.app,
20491
+ step: 0,
20492
+ maxSteps: 1,
20493
+ screen: rootCausePrompt(document),
20494
+ history: []
20495
+ };
20496
+ }
20497
+ var ROOT_CAUSE_TURN = {
20498
+ prompt: (turn) => turn.screen,
20499
+ parse(content) {
20500
+ try {
20501
+ JSON.parse(unfence3(content));
20502
+ } catch {
20503
+ throw badResponse(
20504
+ `the model's answer is not JSON: ${JSON.stringify(content.slice(0, 200))}`
20505
+ );
20506
+ }
20507
+ return { done: true, reason: content };
20508
+ }
20509
+ };
20510
+ function unfence3(text2) {
20511
+ const match = /^\s*```(?:json)?\s*\n([\s\S]*?)\n\s*```\s*$/.exec(text2);
20512
+ return match === null ? text2 : match[1];
20513
+ }
20514
+ function asRecord(value, what) {
20515
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
20516
+ throw badResponse(`the model's ${what} must be a JSON object`);
20517
+ }
20518
+ return value;
20519
+ }
20520
+ function strings(value) {
20521
+ if (!Array.isArray(value)) return [];
20522
+ return value.filter((item) => typeof item === "string" && item.trim() !== "").map((item) => item.trim());
20523
+ }
20524
+ function text(value) {
20525
+ return typeof value === "string" ? value.trim() : "";
20526
+ }
20527
+ var CONFIDENCE = /* @__PURE__ */ new Set(["high", "medium", "low"]);
20528
+ function confidenceOf(value) {
20529
+ return typeof value === "string" && CONFIDENCE.has(value) ? value : "low";
20530
+ }
20531
+ function parseRootCauseAnswer(content, document, model) {
20532
+ let parsed;
20533
+ try {
20534
+ parsed = JSON.parse(unfence3(content));
20535
+ } catch {
20536
+ throw badResponse(
20537
+ `the model's answer is not JSON: ${JSON.stringify(content.slice(0, 200))}`
20538
+ );
20539
+ }
20540
+ const record = asRecord(parsed, "answer");
20541
+ const known = new Set(document.observations.map((item) => item.evidenceId));
20542
+ const rawSuspects = record["suspects"];
20543
+ const suspects = [];
20544
+ if (rawSuspects !== void 0 && !Array.isArray(rawSuspects)) {
20545
+ throw badResponse(`the model's "suspects" must be an array`);
20546
+ }
20547
+ for (const [index, entry] of (rawSuspects ?? []).entries()) {
20548
+ const suspect = asRecord(entry, `suspects[${index}]`);
20549
+ const cited = strings(suspect["evidenceIds"]);
20550
+ const evidenceIds = cited.filter((id) => known.has(id));
20551
+ const ungrounded = cited.filter((id) => !known.has(id));
20552
+ suspects.push({
20553
+ rank: suspects.length + 1,
20554
+ evidenceIds,
20555
+ rootCause: text(suspect["rootCause"]),
20556
+ fix: text(suspect["fix"]),
20557
+ confidence: confidenceOf(suspect["confidence"]),
20558
+ ungrounded,
20559
+ ...text(suspect["triggerChain"]) === "" ? {} : { triggerChain: text(suspect["triggerChain"]) }
20560
+ });
20561
+ }
20562
+ return {
20563
+ model,
20564
+ summary: text(record["summary"]),
20565
+ suspects,
20566
+ caveats: strings(record["caveats"]),
20567
+ needsMoreData: strings(record["needsMoreData"])
20568
+ };
20569
+ }
20570
+ function groundingVocabulary(document) {
20571
+ const vocabulary = /* @__PURE__ */ new Set();
20572
+ for (const item of document.observations) {
20573
+ vocabulary.add(item.subject.process);
20574
+ if (item.subject.thread !== void 0) vocabulary.add(item.subject.thread);
20575
+ for (const value of Object.values(item.signals)) {
20576
+ if (typeof value === "string") vocabulary.add(value);
20577
+ else if (Array.isArray(value)) for (const entry of value) vocabulary.add(entry);
20578
+ }
20579
+ vocabulary.add(item.kind);
20580
+ for (const token of identifierTokens(item.explain)) vocabulary.add(token);
20581
+ }
20582
+ return vocabulary;
20583
+ }
20584
+ function identifierTokens(text2) {
20585
+ return (text2.match(/[A-Za-z_][A-Za-z0-9_.\-]{2,}/g) ?? []).map((token) => token.replace(/[.\-]+$/, "")).filter((token) => looksLikeIdentifier(token));
20586
+ }
20587
+ function ungroundedNames(suspect, vocabulary) {
20588
+ const text2 = [suspect.rootCause, suspect.fix, suspect.triggerChain ?? ""].join(" ");
20589
+ const candidates = text2.match(/[A-Za-z_][A-Za-z0-9_.\-]{2,}/g) ?? [];
20590
+ const found = /* @__PURE__ */ new Set();
20591
+ for (const token of candidates) {
20592
+ const trimmed = token.replace(/[.\-]+$/, "");
20593
+ if (trimmed === "" || vocabulary.has(trimmed)) continue;
20594
+ if (!looksLikeIdentifier(trimmed)) continue;
20595
+ found.add(trimmed);
20596
+ }
20597
+ return [...found].sort();
20598
+ }
20599
+ function looksLikeIdentifier(token) {
20600
+ if (/\.(?:so|ets|ts|js|json|hap|hsp|db|abc)$/i.test(token)) return true;
20601
+ if (token.includes("_")) return true;
20602
+ if (/[a-z][A-Z]/.test(token)) return true;
20603
+ return false;
20604
+ }
20605
+ async function askRootCause(model, document, options) {
20606
+ const decision = await model.decide(turnFor(document));
20607
+ const content = "done" in decision ? decision.reason : "";
20608
+ const analysis = parseRootCauseAnswer(content, document, options.model);
20609
+ const vocabulary = groundingVocabulary(document);
20610
+ return {
20611
+ ...document,
20612
+ observations: document.observations.map((item) => ({ ...item, signals: { ...item.signals } })),
20613
+ summary: { ...document.summary, totals: { ...document.summary.totals } },
20614
+ scene: { ...document.scene, window: { ...document.scene.window } },
20615
+ generator: { ...document.generator },
20616
+ analysis: {
20617
+ ...analysis,
20618
+ suspects: analysis.suspects.map((suspect) => {
20619
+ const names = ungroundedNames(suspect, vocabulary);
20620
+ return names.length === 0 ? suspect : { ...suspect, ungrounded: [...suspect.ungrounded, ...names] };
20621
+ })
20622
+ }
20623
+ };
20624
+ }
20625
+
20626
+ // src/report/root-cause-markdown.ts
20627
+ var PIPE = /\|/g;
20628
+ var NEWLINE = /\r?\n/g;
20629
+ function cell2(value) {
20630
+ return value.replace(PIPE, "\\|").replace(NEWLINE, " ");
20631
+ }
20632
+ function signalsCell(signals) {
20633
+ const keys = Object.keys(signals).sort();
20634
+ if (keys.length === 0) return "\u2014";
20635
+ return keys.map((key) => `${key}=${String(signals[key])}`).join(", ");
20636
+ }
20637
+ function subjectText2(subject) {
20638
+ const parts = [subject.process];
20639
+ if (subject.thread !== void 0) parts.push(subject.thread);
20640
+ if (subject.frameNo !== void 0) parts.push(`frame ${subject.frameNo}`);
20641
+ return parts.join(" / ");
20642
+ }
20643
+ function renderObservations(observations) {
20644
+ if (observations.length === 0) {
20645
+ return ["no evidence was produced for this scene."];
20646
+ }
20647
+ const lines = [
20648
+ "| # | severity | kind | subject | what was measured | signals |",
20649
+ "| --- | --- | --- | --- | --- | --- |"
20650
+ ];
20651
+ for (const [index, item] of observations.entries()) {
20652
+ lines.push(
20653
+ `| ${index + 1} | ${item.severity} | ${cell2(item.kind)} | ${cell2(subjectText2(item.subject))} | ${cell2(item.explain)} | ${cell2(signalsCell(item.signals))} |`
20654
+ );
20655
+ }
20656
+ return lines;
20657
+ }
20658
+ function renderSuspect(suspect) {
20659
+ const lines = [];
20660
+ const mark = suspect.ungrounded.length === 0 ? "" : " \u2014 **ungrounded**";
20661
+ lines.push(`### ${suspect.rank}. ${suspect.confidence} confidence${mark}`);
20662
+ lines.push("");
20663
+ lines.push(suspect.rootCause === "" ? "(no cause stated)" : suspect.rootCause);
20664
+ lines.push("");
20665
+ lines.push(`**Fix:** ${suspect.fix === "" ? "(none stated)" : suspect.fix}`);
20666
+ if (suspect.triggerChain !== void 0) {
20667
+ lines.push("");
20668
+ lines.push(`**Trigger chain:** ${suspect.triggerChain}`);
20669
+ }
20670
+ if (suspect.evidenceIds.length > 0) {
20671
+ lines.push("");
20672
+ lines.push(`**Grounded in:** ${suspect.evidenceIds.join(", ")}`);
20673
+ }
20674
+ if (suspect.ungrounded.length > 0) {
20675
+ lines.push("");
20676
+ lines.push(
20677
+ `**Ungrounded:** ${suspect.ungrounded.join(", ")} \u2014 not measured in this run, so this suspect may describe something the capture never saw.`
20678
+ );
20679
+ }
20680
+ lines.push("");
20681
+ return lines;
20682
+ }
20683
+ function renderRootCauseMarkdown(document) {
20684
+ const { summary, scene } = document;
20685
+ const lines = [];
20686
+ lines.push("# Root cause");
20687
+ lines.push("");
20688
+ lines.push(`app ${scene.app}`);
20689
+ lines.push(`device ${scene.device}`);
20690
+ lines.push(
20691
+ isWholeCapture(scene.window) ? "window the whole capture" : `window ${scene.window.startNs}..${scene.window.endNs} ns (${((scene.window.endNs - scene.window.startNs) / 1e9).toFixed(2)} s)`
20692
+ );
20693
+ lines.push(`produced by ${document.generator.name} ${document.generator.version}`);
20694
+ lines.push("");
20695
+ lines.push("## Verdict");
20696
+ lines.push("");
20697
+ lines.push(summary.verdict);
20698
+ lines.push("");
20699
+ lines.push(
20700
+ `totals: ${summary.totals.critical} critical, ${summary.totals.warn} warn, ${summary.totals.info} info` + (summary.totals.gaps === 0 ? "" : ` (${summary.totals.gaps} report a gap in the capture rather than a finding)`)
20701
+ );
20702
+ lines.push("");
20703
+ lines.push("## Observations");
20704
+ lines.push("");
20705
+ lines.push(...renderObservations(document.observations));
20706
+ lines.push("");
20707
+ const analysis = document.analysis;
20708
+ if (analysis === void 0) {
20709
+ lines.push("## Offline report");
20710
+ lines.push("");
20711
+ lines.push(
20712
+ "no model was asked: this report was produced offline from the measured evidence alone. Configure a model endpoint and run without `--offline` to add an analysis section."
20713
+ );
20714
+ lines.push("");
20715
+ } else {
20716
+ lines.push(`## Model analysis (${analysis.model})`);
20717
+ lines.push("");
20718
+ lines.push(analysis.summary === "" ? "(no summary stated)" : analysis.summary);
20719
+ lines.push("");
20720
+ if (analysis.suspects.length === 0) {
20721
+ lines.push("the model proposed no suspects.");
20722
+ lines.push("");
20723
+ } else {
20724
+ for (const suspect of analysis.suspects) lines.push(...renderSuspect(suspect));
20725
+ }
20726
+ if (analysis.caveats.length > 0) {
20727
+ lines.push("### Caveats");
20728
+ lines.push("");
20729
+ for (const caveat of analysis.caveats) lines.push(`- ${caveat}`);
20730
+ lines.push("");
20731
+ }
20732
+ if (analysis.needsMoreData.length > 0) {
20733
+ lines.push("### What would raise confidence");
20734
+ lines.push("");
20735
+ for (const item of analysis.needsMoreData) lines.push(`- ${item}`);
20736
+ lines.push("");
20737
+ }
20738
+ }
20739
+ return `${lines.join("\n").replace(/\n+$/, "")}
20740
+ `;
20741
+ }
19939
20742
  export {
19940
20743
  ANIMATION_BANDS,
19941
20744
  BUNDLE_RENDERED_FILES,
@@ -19973,6 +20776,7 @@ export {
19973
20776
  FrameLoadIndex,
19974
20777
  FrameQuery,
19975
20778
  GEOMETRY_TOLERANCE_PX,
20779
+ GUI_TURN,
19976
20780
  GcAnalyzer,
19977
20781
  GestureDriver,
19978
20782
  HILOG_COMMAND,
@@ -20004,10 +20808,13 @@ export {
20004
20808
  OhosPerfError,
20005
20809
  PARITY_ROWS,
20006
20810
  PLANE_A_PLUGINS,
20811
+ PROMPT_EVIDENCE_LIMIT,
20007
20812
  PerfQuery,
20008
20813
  ProcessQuery,
20009
20814
  ProcfsCollector,
20010
20815
  REPORT_SCHEMA_VERSION,
20816
+ ROOT_CAUSE_SCHEMA_VERSION,
20817
+ ROOT_CAUSE_TURN,
20011
20818
  RedundantFileAnalyzer,
20012
20819
  RenderAnalyzer,
20013
20820
  RsSkipAnalyzer,
@@ -20037,12 +20844,14 @@ export {
20037
20844
  analyzeHap,
20038
20845
  analyzeThreadWakeup,
20039
20846
  animationSeverity,
20847
+ askRootCause,
20040
20848
  buildDepGraph,
20041
20849
  buildHiprofilerConfig,
20042
20850
  buildInventory,
20043
20851
  buildMatrix,
20044
20852
  buildNativeTimeline,
20045
20853
  buildReport,
20854
+ buildRootCauseDocument,
20046
20855
  buildTrend,
20047
20856
  categorize,
20048
20857
  classifyInstruction,
@@ -20079,6 +20888,7 @@ export {
20079
20888
  evidence,
20080
20889
  executeAction,
20081
20890
  explorationDevice,
20891
+ explorationPrompt,
20082
20892
  explore,
20083
20893
  extractBinaries,
20084
20894
  filterEmptyFrames,
@@ -20086,15 +20896,19 @@ export {
20086
20896
  ftracePlugin,
20087
20897
  functionAt,
20088
20898
  gpuPlugin,
20899
+ groundingVocabulary,
20089
20900
  hapSection,
20901
+ hashPageShape,
20090
20902
  hashTree,
20091
20903
  hiperfRecordCommand,
20092
20904
  httpAgentModel,
20905
+ httpChatModel,
20093
20906
  ingestScene,
20094
20907
  inspectBinary,
20095
20908
  irreversibleReason,
20096
20909
  isUnresolvedSymbol,
20097
20910
  isZip,
20911
+ llmChooser,
20098
20912
  loadCases,
20099
20913
  lookupQuery,
20100
20914
  markRegions,
@@ -20123,11 +20937,14 @@ export {
20123
20937
  parseHitches,
20124
20938
  parseProcfsStatus,
20125
20939
  parseRedundantFile,
20940
+ parseRootCauseAnswer,
20126
20941
  parseScenario,
20127
20942
  parseSelector,
20128
20943
  parseSmapsRollup,
20944
+ parseStrategyAnswer,
20129
20945
  planNextAction,
20130
20946
  queryDefinitions,
20947
+ rankObservations,
20131
20948
  readAgentConfig,
20132
20949
  readElf,
20133
20950
  readHidumperCapture,
@@ -20145,6 +20962,7 @@ export {
20145
20962
  renderReportHtml,
20146
20963
  renderReportJson,
20147
20964
  renderReportXlsx,
20965
+ renderRootCauseMarkdown,
20148
20966
  renderScenesComparison,
20149
20967
  renderSummaryJson,
20150
20968
  renderTree,
@@ -20156,6 +20974,7 @@ export {
20156
20974
  resolveAppIpids,
20157
20975
  resolveQueryLimit,
20158
20976
  resolveSelector,
20977
+ rootCausePrompt,
20159
20978
  round2HalfEven,
20160
20979
  runAgent,
20161
20980
  runAnalyzerSections,
@@ -20168,6 +20987,7 @@ export {
20168
20987
  symbolIndex,
20169
20988
  tableRowCounts,
20170
20989
  trendRunFromReport,
20990
+ ungroundedNames,
20171
20991
  unknownQueryError,
20172
20992
  validateRules,
20173
20993
  writeProcfsSamples,