bpmax-cli 0.2.1-beta.49 → 0.2.1-beta.50

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/bin.js CHANGED
@@ -233,8 +233,8 @@ function throwCliGovernanceUnsupportedIfNeeded(error, fallbackPath) {
233
233
  }
234
234
  throw error;
235
235
  }
236
- function normalizePath(path17) {
237
- let normalized = path17.split("?")[0] || "/";
236
+ function normalizePath(path19) {
237
+ let normalized = path19.split("?")[0] || "/";
238
238
  if (!normalized.startsWith("/")) {
239
239
  normalized = `/${normalized}`;
240
240
  }
@@ -244,17 +244,17 @@ function normalizePath(path17) {
244
244
  }
245
245
  return normalized.replace(/\/+$/g, "") || "/api";
246
246
  }
247
- function getNumber(value, path17) {
248
- const result = getValue(value, path17);
247
+ function getNumber(value, path19) {
248
+ const result = getValue(value, path19);
249
249
  return typeof result === "number" ? result : void 0;
250
250
  }
251
- function getString(value, path17) {
252
- const result = getValue(value, path17);
251
+ function getString(value, path19) {
252
+ const result = getValue(value, path19);
253
253
  return typeof result === "string" ? result : void 0;
254
254
  }
255
- function getValue(value, path17) {
255
+ function getValue(value, path19) {
256
256
  let current = value;
257
- for (const key of path17) {
257
+ for (const key of path19) {
258
258
  if (!current || typeof current !== "object" || !(key in current)) {
259
259
  return void 0;
260
260
  }
@@ -264,10 +264,10 @@ function getValue(value, path17) {
264
264
  }
265
265
 
266
266
  // src/core/capabilities.ts
267
- function capabilityForRequest(method, path17) {
267
+ function capabilityForRequest(method, path19) {
268
268
  const normalizedMethod = method.toUpperCase();
269
- const normalizedPath = normalizePath2(path17);
270
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path17);
269
+ const normalizedPath = normalizePath2(path19);
270
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path19);
271
271
  if (normalizedPath === "/cli/capabilities") {
272
272
  return void 0;
273
273
  }
@@ -446,8 +446,8 @@ async function updateProfileCapabilities(profileName, cache) {
446
446
  };
447
447
  await saveConfig(config);
448
448
  }
449
- function flowPageTemplateCapabilityPrefix(path17) {
450
- const query = path17.includes("?") ? path17.slice(path17.indexOf("?") + 1) : "";
449
+ function flowPageTemplateCapabilityPrefix(path19) {
450
+ const query = path19.includes("?") ? path19.slice(path19.indexOf("?") + 1) : "";
451
451
  const type = new URLSearchParams(query).get("type");
452
452
  if (type === "2") {
453
453
  return "config.project_detail_template";
@@ -466,8 +466,8 @@ function flowPageTemplateCapabilityPrefix(path17) {
466
466
  }
467
467
  return "config.list_template";
468
468
  }
469
- function normalizePath2(path17) {
470
- let normalized = path17.split("?")[0] || "/";
469
+ function normalizePath2(path19) {
470
+ let normalized = path19.split("?")[0] || "/";
471
471
  if (!normalized.startsWith("/")) {
472
472
  normalized = `/${normalized}`;
473
473
  }
@@ -498,7 +498,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
498
498
  // package.json
499
499
  var package_default = {
500
500
  name: "bpmax-cli",
501
- version: "0.2.1-beta.49",
501
+ version: "0.2.1-beta.50",
502
502
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
503
503
  type: "module",
504
504
  bin: {
@@ -525,12 +525,13 @@ var package_default = {
525
525
  node: ">=18"
526
526
  },
527
527
  dependencies: {
528
- acorn: "^8.16.0",
529
528
  "@clack/prompts": "1.0.1",
529
+ acorn: "^8.16.0",
530
530
  axios: "^1.9.0",
531
531
  commander: "^14.0.0",
532
532
  jszip: "^3.10.1",
533
- open: "^10.1.2"
533
+ open: "^10.1.2",
534
+ "playwright-core": "1.61.1"
534
535
  },
535
536
  devDependencies: {
536
537
  "@types/node": "^22.15.17",
@@ -549,8 +550,8 @@ var NPM_PACKAGE = "bpmax-cli";
549
550
  // src/core/terminal.ts
550
551
  import { randomUUID } from "crypto";
551
552
  import os from "os";
552
- function isCliControlPath(path17) {
553
- const normalized = normalizeApiPath(path17);
553
+ function isCliControlPath(path19) {
554
+ const normalized = normalizeApiPath(path19);
554
555
  return normalized === "/api/cli/capabilities" || normalized === "/api/cli/terminals/register" || normalized === "/api/cli/audit/start" || normalized === "/api/cli/audit/finish" || normalized === "/api/cli/bbs_invocations/start" || normalized === "/api/cli/bbs_invocations/finish";
555
556
  }
556
557
  function commandSummary(argv = process.argv) {
@@ -714,8 +715,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
714
715
  profile.config.terminal_status = status;
715
716
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
716
717
  }
717
- function normalizeApiPath(path17) {
718
- let normalized = path17.split("?")[0] || "/";
718
+ function normalizeApiPath(path19) {
719
+ let normalized = path19.split("?")[0] || "/";
719
720
  if (!normalized.startsWith("/")) {
720
721
  normalized = `/${normalized}`;
721
722
  }
@@ -838,14 +839,14 @@ function recordCommandAuditResult(value) {
838
839
  state.result_summary = redactAuditValue(value);
839
840
  }
840
841
  }
841
- var ensureApiPath = (path17) => {
842
- if (!path17.startsWith("/")) {
843
- path17 = `/${path17}`;
842
+ var ensureApiPath = (path19) => {
843
+ if (!path19.startsWith("/")) {
844
+ path19 = `/${path19}`;
844
845
  }
845
- if (path17.startsWith("/api/")) {
846
- return path17;
846
+ if (path19.startsWith("/api/")) {
847
+ return path19;
847
848
  }
848
- return `/api${path17}`;
849
+ return `/api${path19}`;
849
850
  };
850
851
  function normalizeWorkspaceForApi(workspace) {
851
852
  const normalized = workspace?.trim();
@@ -891,10 +892,10 @@ function createApiClient(profile) {
891
892
  });
892
893
  return instance;
893
894
  }
894
- async function apiRequest(client, method, path17, options = {}) {
895
+ async function apiRequest(client, method, path19, options = {}) {
895
896
  const profile = clientProfiles.get(client);
896
- const apiPath2 = ensureApiPath(path17);
897
- const capability = options.capability ?? capabilityForRequest(method, path17);
897
+ const apiPath2 = ensureApiPath(path19);
898
+ const capability = options.capability ?? capabilityForRequest(method, path19);
898
899
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
899
900
  const reqId = requestId();
900
901
  if (profile) {
@@ -1221,8 +1222,8 @@ async function parseJsonAny(input, label = "JSON input") {
1221
1222
  function isMutatingMethod(method) {
1222
1223
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1223
1224
  }
1224
- function normalizeApiPath2(path17) {
1225
- let normalized = path17.trim();
1225
+ function normalizeApiPath2(path19) {
1226
+ let normalized = path19.trim();
1226
1227
  const queryIndex = normalized.indexOf("?");
1227
1228
  if (queryIndex >= 0) {
1228
1229
  normalized = normalized.slice(0, queryIndex);
@@ -1239,9 +1240,9 @@ function normalizeApiPath2(path17) {
1239
1240
  }
1240
1241
  return normalized;
1241
1242
  }
1242
- function pluginAgentCapabilityForRawApi(method, path17) {
1243
+ function pluginAgentCapabilityForRawApi(method, path19) {
1243
1244
  const normalizedMethod = method.toUpperCase();
1244
- const normalizedPath = normalizeApiPath2(path17);
1245
+ const normalizedPath = normalizeApiPath2(path19);
1245
1246
  const match = normalizedPath.match(/^\/(plugin_[A-Za-z0-9_]+)\/agents(?:\/|$)/);
1246
1247
  if (!match) {
1247
1248
  return void 0;
@@ -1255,19 +1256,19 @@ function pluginAgentCapabilityForRawApi(method, path17) {
1255
1256
  }
1256
1257
  return void 0;
1257
1258
  }
1258
- function parseQuery(path17) {
1259
- const queryIndex = path17.indexOf("?");
1260
- return new URLSearchParams(queryIndex >= 0 ? path17.slice(queryIndex + 1) : "");
1259
+ function parseQuery(path19) {
1260
+ const queryIndex = path19.indexOf("?");
1261
+ return new URLSearchParams(queryIndex >= 0 ? path19.slice(queryIndex + 1) : "");
1261
1262
  }
1262
- function isRawConfigPath(method, path17) {
1263
- const normalizedPath = normalizeApiPath2(path17);
1263
+ function isRawConfigPath(method, path19) {
1264
+ const normalizedPath = normalizeApiPath2(path19);
1264
1265
  if (/^\/(configuration|form_template|flow_page_template|data_set|data_set_field|api_platform|api_platform_instance|api_proxy|api_proxy_entity_binding|entity|entity_field|role|point|user_role|workspace|group|config_repository)(\/|$)/.test(normalizedPath)) {
1265
1266
  return true;
1266
1267
  }
1267
1268
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1268
1269
  return true;
1269
1270
  }
1270
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path17).has("draft")) {
1271
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path19).has("draft")) {
1271
1272
  return true;
1272
1273
  }
1273
1274
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1278,35 +1279,35 @@ function isRawConfigPath(method, path17) {
1278
1279
  }
1279
1280
  return false;
1280
1281
  }
1281
- function assertRawApiPathAllowed(method, path17) {
1282
- if (isRawConfigPath(method, path17)) {
1282
+ function assertRawApiPathAllowed(method, path19) {
1283
+ if (isRawConfigPath(method, path19)) {
1283
1284
  throw new Error(
1284
- `Raw API ${method} ${path17} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1285
+ `Raw API ${method} ${path19} is blocked because BPMAX configuration APIs must use typed bpmax-cli config commands. Run bpmax-cli config adapters --format json to check whether the target config domain is supported.`
1285
1286
  );
1286
1287
  }
1287
1288
  if (!isMutatingMethod(method)) {
1288
1289
  return;
1289
1290
  }
1290
- const normalizedPath = normalizeApiPath2(path17);
1291
+ const normalizedPath = normalizeApiPath2(path19);
1291
1292
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1292
1293
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1293
1294
  if (!isProjectPath || isAllowedProjectReadPost) {
1294
1295
  return;
1295
1296
  }
1296
1297
  throw new Error(
1297
- `Raw API ${method} ${path17} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1298
+ `Raw API ${method} ${path19} is blocked because /api/project/<id> falls back to project creation in huanpingtong-server. Do not call /project/es-search or /project/raw-es-search; huanpingtong-server does not expose those as public ES APIs. Use bpmax-cli project create --flow-id <id> --json <json> for project creation, or bpmax-cli project search / project list for project reads.`
1298
1299
  );
1299
1300
  }
1300
1301
  function registerApiCommands(program2) {
1301
- program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path17, options) => {
1302
+ program2.command("api <method> <path>").description("Call an arbitrary BPMAX /api endpoint").option("--profile <profile>", "Profile name").option("--params <json>", "Query params JSON or @file").option("--data <json>", "Request body JSON or @file").option("--confirm-mutating", "Allow mutating API calls").option("--format <format>", "Output format", "json").action(async (method, path19, options) => {
1302
1303
  const normalizedMethod = method.toUpperCase();
1303
- assertRawApiPathAllowed(normalizedMethod, path17);
1304
+ assertRawApiPathAllowed(normalizedMethod, path19);
1304
1305
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1305
1306
  printResult(options.format, {
1306
1307
  ok: false,
1307
1308
  dry_run: true,
1308
1309
  method: normalizedMethod,
1309
- path: path17,
1310
+ path: path19,
1310
1311
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1311
1312
  });
1312
1313
  return;
@@ -1314,8 +1315,8 @@ function registerApiCommands(program2) {
1314
1315
  const config = await loadConfig();
1315
1316
  const profile = resolveProfile(config, options.profile);
1316
1317
  const client = createApiClient(profile);
1317
- const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path17) || "api.raw";
1318
- const result = await apiRequest(client, normalizedMethod, path17, {
1318
+ const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path19) || "api.raw";
1319
+ const result = await apiRequest(client, normalizedMethod, path19, {
1319
1320
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1320
1321
  data: await parseJsonAny(options.data, "--data"),
1321
1322
  capability
@@ -1402,18 +1403,18 @@ function lintDeviceAuthorizationUrl(urlValue, expectedOrigin, expectedWorkspace,
1402
1403
  );
1403
1404
  }
1404
1405
  }
1405
- function apiPath(path17) {
1406
- if (path17.startsWith("/api/")) {
1407
- return path17;
1406
+ function apiPath(path19) {
1407
+ if (path19.startsWith("/api/")) {
1408
+ return path19;
1408
1409
  }
1409
- return `/api${path17.startsWith("/") ? path17 : `/${path17}`}`;
1410
+ return `/api${path19.startsWith("/") ? path19 : `/${path19}`}`;
1410
1411
  }
1411
1412
  function createDeviceRequest(origin) {
1412
1413
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1413
- return async (method, path17, options) => {
1414
+ return async (method, path19, options) => {
1414
1415
  const response = await client.request({
1415
1416
  method,
1416
- url: apiPath(path17),
1417
+ url: apiPath(path19),
1417
1418
  data: options.data
1418
1419
  });
1419
1420
  const body = response.data;
@@ -3872,20 +3873,20 @@ function requireNumericId(value, name) {
3872
3873
  }
3873
3874
  return nextValue;
3874
3875
  }
3875
- function withQuery(path17, query) {
3876
+ function withQuery(path19, query) {
3876
3877
  const params = new URLSearchParams();
3877
3878
  for (const [key, value] of Object.entries(query)) {
3878
3879
  if (value !== void 0) {
3879
3880
  params.set(key, value);
3880
3881
  }
3881
3882
  }
3882
- return `${path17}?${params.toString()}`;
3883
+ return `${path19}?${params.toString()}`;
3883
3884
  }
3884
3885
  function buildBpmaxUrl(profile, kind, params = {}) {
3885
3886
  const origin = normalizeOrigin2(profile.config.origin);
3886
3887
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
3887
3888
  const basePath = `/${workspace}`;
3888
- let path17 = basePath;
3889
+ let path19 = basePath;
3889
3890
  const result = {
3890
3891
  kind,
3891
3892
  profile: profile.name,
@@ -3893,15 +3894,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
3893
3894
  workspace
3894
3895
  };
3895
3896
  if (kind === "project-list") {
3896
- path17 = `${basePath}/project`;
3897
+ path19 = `${basePath}/project`;
3897
3898
  } else if (kind === "project-detail") {
3898
3899
  const projectId = requireNumericId(params.projectId, "projectId");
3899
- path17 = `${basePath}/project_detail/0/${projectId}`;
3900
+ path19 = `${basePath}/project_detail/0/${projectId}`;
3900
3901
  result.project_id = projectId;
3901
3902
  } else if (kind === "project-step") {
3902
3903
  const projectId = requireNumericId(params.projectId, "projectId");
3903
3904
  const stepId = requireNumericId(params.stepId, "stepId");
3904
- path17 = withQuery(`${basePath}/projectContinue`, {
3905
+ path19 = withQuery(`${basePath}/projectContinue`, {
3905
3906
  id: projectId,
3906
3907
  step_id: stepId,
3907
3908
  prefill_token: params.prefillToken
@@ -3919,15 +3920,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
3919
3920
  ...flowKey ? { key: flowKey } : {},
3920
3921
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
3921
3922
  };
3922
- path17 = withQuery(`${basePath}/project/create`, query);
3923
+ path19 = withQuery(`${basePath}/project/create`, query);
3923
3924
  result.flow_type = flowType;
3924
3925
  result.flow_key = flowKey;
3925
3926
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
3926
3927
  }
3927
- const url = `${origin}${path17}`;
3928
+ const url = `${origin}${path19}`;
3928
3929
  return {
3929
3930
  ...result,
3930
- path: path17,
3931
+ path: path19,
3931
3932
  url,
3932
3933
  ...kind === "project-create" ? { pc_url: url } : {}
3933
3934
  };
@@ -4307,17 +4308,17 @@ function containsOuterReturn(value, root = true) {
4307
4308
  return containsOuterReturn(child, false);
4308
4309
  });
4309
4310
  }
4310
- function validateExpression(expression, path17, errors) {
4311
+ function validateExpression(expression, path19, errors) {
4311
4312
  try {
4312
4313
  const program2 = parse(`async function __bpmaxReport(ctx) {
4313
4314
  ${expression}
4314
4315
  }`, { ecmaVersion: "latest" });
4315
4316
  const reportFunction = program2.body[0];
4316
4317
  if (!containsOuterReturn(reportFunction)) {
4317
- errors.push(`${path17} \u662F\u5E73\u53F0\u5F02\u6B65\u51FD\u6570\u4F53\uFF0C\u5FC5\u987B\u663E\u5F0F return\uFF0C\u4E14 return \u5FC5\u987B\u4F4D\u4E8E\u5916\u5C42\u51FD\u6570\u4E2D\uFF1B\u5426\u5219\u62A5\u544A\u5B57\u6BB5\u4F1A\u751F\u6210\u7A7A\u503C\u3002`);
4318
+ errors.push(`${path19} \u662F\u5E73\u53F0\u5F02\u6B65\u51FD\u6570\u4F53\uFF0C\u5FC5\u987B\u663E\u5F0F return\uFF0C\u4E14 return \u5FC5\u987B\u4F4D\u4E8E\u5916\u5C42\u51FD\u6570\u4E2D\uFF1B\u5426\u5219\u62A5\u544A\u5B57\u6BB5\u4F1A\u751F\u6210\u7A7A\u503C\u3002`);
4318
4319
  }
4319
4320
  } catch (error) {
4320
- errors.push(`${path17} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4321
+ errors.push(`${path19} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4321
4322
  }
4322
4323
  }
4323
4324
  function analyzeFlowReportTemplate(value, options = {}) {
@@ -5111,9 +5112,9 @@ function summarizeOperationPlan(payload) {
5111
5112
  return "submit operation";
5112
5113
  }
5113
5114
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
5114
- const path17 = typeof operation.path === "string" ? operation.path : "";
5115
+ const path19 = typeof operation.path === "string" ? operation.path : "";
5115
5116
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
5116
- return `submit${type}: ${method}${path17 ? ` ${path17}` : ""}`;
5117
+ return `submit${type}: ${method}${path19 ? ` ${path19}` : ""}`;
5117
5118
  }),
5118
5119
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
5119
5120
  if (!isRecord4(operation)) {
@@ -7163,23 +7164,23 @@ function lintConsoleTemplateDataSource(dataSource, moduleLabel, errors) {
7163
7164
  errors.push(`${moduleLabel} \u4E0D\u80FD\u76F4\u63A5\u4F7F\u7528 /bpmax/project/list\u3001/api/project/list \u6216 ESProjectList\uFF1B\u5982\u786E\u9700\u7528\u6237\u8303\u56F4\u67E5\u8BE2\uFF0C\u811A\u672C\u4E2D\u5FC5\u987B\u5199\u660E bpmax-allow-user-scope-project-list: <reason>\u3002`);
7164
7165
  }
7165
7166
  }
7166
- function lintConsoleTemplateWildcardFallback(value, path17, errors) {
7167
+ function lintConsoleTemplateWildcardFallback(value, path19, errors) {
7167
7168
  if (typeof value === "string") {
7168
7169
  const scriptedWildcard = /(?:wildcard|value)\s*:\s*['\"](\*{1,2})['\"]/i.exec(value);
7169
7170
  if (scriptedWildcard) {
7170
- errors.push(`${path17}.wildcard \u4E0D\u80FD\u7528 ${scriptedWildcard[1]} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7171
+ errors.push(`${path19}.wildcard \u4E0D\u80FD\u7528 ${scriptedWildcard[1]} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7171
7172
  }
7172
7173
  return;
7173
7174
  }
7174
7175
  if (Array.isArray(value)) {
7175
- value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path17}[${index}]`, errors));
7176
+ value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path19}[${index}]`, errors));
7176
7177
  return;
7177
7178
  }
7178
7179
  if (!isRecord4(value)) {
7179
7180
  return;
7180
7181
  }
7181
7182
  Object.entries(value).forEach(([key, item]) => {
7182
- const nextPath = `${path17}.${key}`;
7183
+ const nextPath = `${path19}.${key}`;
7183
7184
  if ((key === "wildcard" || key === "value") && (item === "*" || item === "**")) {
7184
7185
  errors.push(`${nextPath} \u4E0D\u80FD\u7528 ${String(item)} \u4F5C\u4E3A\u975E\u7A7A\u6216\u515C\u5E95\u7ED3\u679C\uFF1B\u8BF7\u5199\u660E\u786E\u7684\u7A7A\u6001\u3001\u6761\u4EF6\u6216\u805A\u5408\u7ED3\u679C\u3002`);
7185
7186
  }
@@ -9366,6 +9367,40 @@ function validateRadioFormTemplateControl(field, rule, value, errors, warnings,
9366
9367
  else warnings.push(`${message} \u5386\u53F2 edit \u6A21\u677F\u6682\u4E0D\u963B\u65AD\uFF1B\u4FEE\u6539\u8BE5\u5B57\u6BB5\u65F6\u5E94\u540C\u6B65\u8FC1\u79FB\u3002`);
9367
9368
  }
9368
9369
  }
9370
+ function subFormFixedFields(props, snakeKey, camelKey) {
9371
+ return [props[snakeKey], props[camelKey]].filter(Array.isArray).flatMap((value) => value.filter((item) => typeof item === "string" && item.trim().length > 0));
9372
+ }
9373
+ function validateSubFormAdaptiveColumn(field, rule, errors) {
9374
+ if (!rule) {
9375
+ return;
9376
+ }
9377
+ const props = isRecord4(rule.props) ? rule.props : {};
9378
+ const displayMode = typeof props.mode === "string" ? props.mode : "table";
9379
+ if (displayMode !== "table") {
9380
+ return;
9381
+ }
9382
+ const applyColWidthOnPreview = props.applyColWidthOnPreview;
9383
+ if (applyColWidthOnPreview !== void 0 && typeof applyColWidthOnPreview !== "boolean") {
9384
+ errors.push(
9385
+ `[form.sub_form.apply_column_width_type] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u7684 props.applyColWidthOnPreview \u5FC5\u987B\u662F boolean\uFF1B\u4F7F\u7528 false \u6216\u7701\u7565\u8BE5\u914D\u7F6E\uFF0C\u624D\u80FD\u8BA9\u684C\u9762\u9884\u89C8\u5217\u81EA\u52A8\u586B\u5145\u5269\u4F59\u5BBD\u5EA6\u3002`
9386
+ );
9387
+ }
9388
+ const fixedLeftFields = subFormFixedFields(props, "fixed_left_fields", "fixedLeftFields");
9389
+ const fixedRightFields = subFormFixedFields(props, "fixed_right_fields", "fixedRightFields");
9390
+ const fixedFields = [.../* @__PURE__ */ new Set([...fixedLeftFields, ...fixedRightFields])];
9391
+ const allFixedReasons = [];
9392
+ if (applyColWidthOnPreview === true) {
9393
+ allFixedReasons.push("props.applyColWidthOnPreview=true");
9394
+ }
9395
+ if (fixedFields.length > 0) {
9396
+ allFixedReasons.push(`\u56FA\u5B9A\u5217=${fixedFields.join(",")}`);
9397
+ }
9398
+ if (allFixedReasons.length > 0) {
9399
+ errors.push(
9400
+ `[form.sub_form.adaptive_column_required] \u5173\u8054\u8868\u5355\u5B57\u6BB5 ${field} \u4F1A\u8BA9\u5168\u90E8\u6570\u636E\u5217\u4F7F\u7528\u56FA\u5B9A\u5BBD\u5EA6\uFF08${allFixedReasons.join("\uFF1B")}\uFF09\u3002\u5F53\u524D\u5E73\u53F0\u53EA\u6709\u5728 props.applyColWidthOnPreview=false\uFF08\u6216\u7701\u7565\uFF09\u4E14\u4E0D\u914D\u7F6E fixed_left_fields/fixed_right_fields \u65F6\uFF0C\u684C\u9762\u9884\u89C8\u7684\u6570\u636E\u5217\u624D\u4F1A\u7701\u7565 width \u5E76\u81EA\u52A8\u586B\u5145\u5269\u4F59\u7A7A\u95F4\uFF1B\u4E0D\u5F97\u7528\u7A7A col_width \u9879\u3001auto \u6216\u767E\u5206\u6BD4\u5192\u5145\u81EA\u9002\u5E94\u5217\u3002`
9401
+ );
9402
+ }
9403
+ }
9369
9404
  function validateFormTemplateControlContracts(payload, errors, warnings, mode) {
9370
9405
  const validatePair = (field, rule, value) => {
9371
9406
  const type = typeof rule?.type === "string" ? rule.type : value ? formTemplateValueFieldType(value) : "";
@@ -9378,6 +9413,9 @@ function validateFormTemplateControlContracts(payload, errors, warnings, mode) {
9378
9413
  if (type === "radio") {
9379
9414
  validateRadioFormTemplateControl(field, rule, value, errors, warnings, mode);
9380
9415
  }
9416
+ if (type === "sub_form") {
9417
+ validateSubFormAdaptiveColumn(field, rule, errors);
9418
+ }
9381
9419
  if (rule?.lambda === "ctx.userInfo?.name || ''") {
9382
9420
  const props = isRecord4(rule.props) ? rule.props : {};
9383
9421
  if (type !== "i_input" || props.disabled !== true) {
@@ -12517,24 +12555,24 @@ function normalizeTypedReadbackComparable(domain, value) {
12517
12555
  }
12518
12556
  function jsonSubsetMismatches(expected, actual) {
12519
12557
  const mismatches = [];
12520
- const compare = (left, right, path17 = "") => {
12558
+ const compare = (left, right, path19 = "") => {
12521
12559
  if (Array.isArray(left)) {
12522
12560
  if (!Array.isArray(right) || left.length !== right.length) {
12523
- mismatches.push(path17 || "/");
12561
+ mismatches.push(path19 || "/");
12524
12562
  return;
12525
12563
  }
12526
- left.forEach((item, index) => compare(item, right[index], `${path17}/${index}`));
12564
+ left.forEach((item, index) => compare(item, right[index], `${path19}/${index}`));
12527
12565
  return;
12528
12566
  }
12529
12567
  if (isRecord4(left)) {
12530
12568
  if (!isRecord4(right)) {
12531
- mismatches.push(path17 || "/");
12569
+ mismatches.push(path19 || "/");
12532
12570
  return;
12533
12571
  }
12534
- for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path17}/${key}`);
12572
+ for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path19}/${key}`);
12535
12573
  return;
12536
12574
  }
12537
- if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path17 || "/");
12575
+ if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path19 || "/");
12538
12576
  };
12539
12577
  compare(expected, actual);
12540
12578
  return mismatches;
@@ -17766,11 +17804,244 @@ function registerConfigCommands(program2) {
17766
17804
  }
17767
17805
 
17768
17806
  // src/commands/e2e.ts
17769
- import { createHash as createHash6 } from "crypto";
17770
- import { mkdir as mkdir10, readFile as readFile13, readdir as readdir5, stat as stat8, writeFile as writeFile10 } from "fs/promises";
17771
- import path12 from "path";
17807
+ import { createHash as createHash7 } from "crypto";
17808
+ import { mkdir as mkdir11, readFile as readFile15, readdir as readdir5, stat as stat8, writeFile as writeFile11 } from "fs/promises";
17809
+ import path14 from "path";
17772
17810
  import axios7 from "axios";
17773
17811
 
17812
+ // src/core/e2e-browser-runner.ts
17813
+ import { createHash as createHash6 } from "crypto";
17814
+ import { mkdir as mkdir10, readFile as readFile14, writeFile as writeFile10 } from "fs/promises";
17815
+ import path13 from "path";
17816
+ import {
17817
+ chromium
17818
+ } from "playwright-core";
17819
+
17820
+ // src/core/e2e-automation-schema.ts
17821
+ import { readFile as readFile12 } from "fs/promises";
17822
+ import path11 from "path";
17823
+ var BROWSER_ACTION_TYPES = [
17824
+ "navigation.open",
17825
+ "form.set_value",
17826
+ "form.select_option",
17827
+ "form.assert_value",
17828
+ "detail.add_row",
17829
+ "detail.set_value",
17830
+ "detail.assert_rows",
17831
+ "button.click",
17832
+ "dialog.confirm",
17833
+ "wait.visible",
17834
+ "wait.network",
17835
+ "wait.route",
17836
+ "context.extract",
17837
+ "page.assert_step",
17838
+ "list.assert_record",
17839
+ "evidence.capture"
17840
+ ];
17841
+ var ACTION_TYPES = new Set(BROWSER_ACTION_TYPES);
17842
+ var CHECK_TYPES = /* @__PURE__ */ new Set([
17843
+ "form.assert_value",
17844
+ "detail.assert_rows",
17845
+ "wait.visible",
17846
+ "wait.route",
17847
+ "page.assert_step",
17848
+ "list.assert_record"
17849
+ ]);
17850
+ var TARGET_KEYS = ["field", "label", "role", "text", "test_id", "css"];
17851
+ function isRecord8(value) {
17852
+ return typeof value === "object" && value !== null && !Array.isArray(value);
17853
+ }
17854
+ function stringValue2(value) {
17855
+ return typeof value === "string" ? value.trim() : "";
17856
+ }
17857
+ function hasDynamicRuntimeId(value) {
17858
+ if (!value || value.includes("{{")) return false;
17859
+ return /(?:[?&](?:id|project_id|step_id|trace_id)=\d+)|(?:\/project(?:Continue|_detail)?\/\d+)/i.test(value);
17860
+ }
17861
+ function targetIssues(target, stepKey, actionIndex) {
17862
+ if (!isRecord8(target)) {
17863
+ return [{
17864
+ rule_id: "test_suite.automation.target_missing",
17865
+ step_key: stepKey,
17866
+ message: `${stepKey} action[${actionIndex}] requires a semantic target`
17867
+ }];
17868
+ }
17869
+ const populated = TARGET_KEYS.filter((key) => stringValue2(target[key]));
17870
+ if (populated.length === 0) {
17871
+ return [{
17872
+ rule_id: "test_suite.automation.target_missing",
17873
+ step_key: stepKey,
17874
+ message: `${stepKey} action[${actionIndex}] requires field, label, role, text, test_id, or stable css`
17875
+ }];
17876
+ }
17877
+ if ("x" in target || "y" in target || "coordinates" in target) {
17878
+ return [{
17879
+ rule_id: "test_suite.automation.selector_unstable",
17880
+ step_key: stepKey,
17881
+ message: `${stepKey} action[${actionIndex}] must not use coordinates`
17882
+ }];
17883
+ }
17884
+ const css = stringValue2(target.css);
17885
+ if (css && !/^(?:\[(?:data-[\w-]+|name|aria-label)=|#[A-Za-z][\w:-]*$)/.test(css)) {
17886
+ return [{
17887
+ rule_id: "test_suite.automation.selector_unstable",
17888
+ step_key: stepKey,
17889
+ message: `${stepKey} action[${actionIndex}] css selector must use a stable id, name, aria-label, or data-* attribute`
17890
+ }];
17891
+ }
17892
+ const serialized = JSON.stringify(target);
17893
+ if (/xpath|\/html\/|\/\/div\[/i.test(serialized)) {
17894
+ return [{
17895
+ rule_id: "test_suite.automation.selector_unstable",
17896
+ step_key: stepKey,
17897
+ message: `${stepKey} action[${actionIndex}] must not use absolute XPath`
17898
+ }];
17899
+ }
17900
+ return [];
17901
+ }
17902
+ function actionIssues(action, stepKey, index, check) {
17903
+ if (!isRecord8(action)) {
17904
+ return [{ rule_id: "test_suite.automation.action_invalid", step_key: stepKey, message: `${stepKey} action[${index}] must be an object` }];
17905
+ }
17906
+ const type = stringValue2(action.type);
17907
+ const issues = [];
17908
+ if (!ACTION_TYPES.has(type)) {
17909
+ issues.push({
17910
+ rule_id: "test_suite.automation.action_unsupported",
17911
+ step_key: stepKey,
17912
+ message: `${stepKey} action[${index}] uses unsupported action type ${type || "<missing>"}`
17913
+ });
17914
+ return issues;
17915
+ }
17916
+ if (check && !CHECK_TYPES.has(type)) {
17917
+ issues.push({
17918
+ rule_id: "test_suite.automation.expected_check_invalid",
17919
+ step_key: stepKey,
17920
+ message: `${stepKey} expected_checks[${index}] must be a deterministic assertion action`
17921
+ });
17922
+ }
17923
+ if (["form.set_value", "form.select_option", "form.assert_value", "button.click", "wait.visible"].includes(type)) {
17924
+ issues.push(...targetIssues(action.target ?? (action.field ? { field: action.field } : void 0), stepKey, index));
17925
+ }
17926
+ if (["detail.add_row", "detail.set_value", "detail.assert_rows"].includes(type) && !stringValue2(action.table)) {
17927
+ issues.push({ rule_id: "test_suite.automation.target_missing", step_key: stepKey, message: `${stepKey} action[${index}] requires table` });
17928
+ }
17929
+ if (type === "detail.set_value" && (!stringValue2(action.field) || !Number.isInteger(action.row) || Number(action.row) < 0)) {
17930
+ issues.push({ rule_id: "test_suite.automation.detail_target_invalid", step_key: stepKey, message: `${stepKey} action[${index}] requires field and a zero-based row` });
17931
+ }
17932
+ if (type === "navigation.open" && !stringValue2(action.route)) {
17933
+ issues.push({ rule_id: "test_suite.automation.route_missing", step_key: stepKey, message: `${stepKey} action[${index}] requires route` });
17934
+ }
17935
+ if (type === "wait.route" && !stringValue2(action.route) && !stringValue2(action.value)) {
17936
+ issues.push({ rule_id: "test_suite.automation.route_missing", step_key: stepKey, message: `${stepKey} action[${index}] wait.route requires route` });
17937
+ }
17938
+ if (type === "wait.network" && !stringValue2(action.url_pattern) && !stringValue2(action.value)) {
17939
+ issues.push({ rule_id: "test_suite.automation.network_pattern_missing", step_key: stepKey, message: `${stepKey} action[${index}] wait.network requires url_pattern` });
17940
+ }
17941
+ if (type === "context.extract" && (!stringValue2(action.name) || !stringValue2(action.source))) {
17942
+ issues.push({ rule_id: "test_suite.automation.extract_invalid", step_key: stepKey, message: `${stepKey} action[${index}] context.extract requires name and source` });
17943
+ }
17944
+ if (type === "page.assert_step" && !stringValue2(action.expected) && !stringValue2(action.value)) {
17945
+ issues.push({ rule_id: "test_suite.automation.expected_check_invalid", step_key: stepKey, message: `${stepKey} action[${index}] page.assert_step requires expected` });
17946
+ }
17947
+ if (type === "list.assert_record" && !stringValue2(action.text) && !stringValue2(action.value)) {
17948
+ issues.push({ rule_id: "test_suite.automation.expected_check_invalid", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_record requires text or value` });
17949
+ }
17950
+ if (hasDynamicRuntimeId(stringValue2(action.route)) || hasDynamicRuntimeId(stringValue2(action.value))) {
17951
+ issues.push({
17952
+ rule_id: "test_suite.automation.dynamic_id_hardcoded",
17953
+ step_key: stepKey,
17954
+ message: `${stepKey} action[${index}] hardcodes a runtime project/step/trace id; use {{data.*}} or {{context.*}}`
17955
+ });
17956
+ }
17957
+ if (!check && type === "button.click" && typeof action.mutation !== "boolean") {
17958
+ issues.push({
17959
+ rule_id: "test_suite.automation.mutation_classification_missing",
17960
+ step_key: stepKey,
17961
+ message: `${stepKey} action[${index}] button.click must declare mutation=true or mutation=false`
17962
+ });
17963
+ }
17964
+ if (!check && typeof action.mutation === "boolean" && !["button.click", "dialog.confirm"].includes(type)) {
17965
+ issues.push({
17966
+ rule_id: "test_suite.automation.mutation_type_invalid",
17967
+ step_key: stepKey,
17968
+ message: `${stepKey} action[${index}] ${type} cannot declare remote mutation; only button.click and dialog.confirm may do so`
17969
+ });
17970
+ }
17971
+ if (!check && (action.mutation === true || type === "dialog.confirm")) {
17972
+ if (action.mutation !== true || action.retry !== "never") {
17973
+ issues.push({
17974
+ rule_id: "test_suite.automation.submit_retry_unsafe",
17975
+ step_key: stepKey,
17976
+ message: `${stepKey} action[${index}] ${type} must declare mutation=true and retry=never`
17977
+ });
17978
+ }
17979
+ }
17980
+ return issues;
17981
+ }
17982
+ function automationStepKey(caseId, stepId) {
17983
+ return `${caseId}/${stepId}`;
17984
+ }
17985
+ function validateBrowserAutomationDocument(value) {
17986
+ const issues = [];
17987
+ if (!isRecord8(value) || value.version !== 1 || !isRecord8(value.steps)) {
17988
+ return {
17989
+ issues: [{
17990
+ rule_id: "test_suite.automation.schema_invalid",
17991
+ message: "automation.json must contain version=1 and a steps object"
17992
+ }]
17993
+ };
17994
+ }
17995
+ for (const [stepKey, rawStep] of Object.entries(value.steps)) {
17996
+ if (!/^[^/]+\/[^/]+$/.test(stepKey)) {
17997
+ issues.push({ rule_id: "test_suite.automation.step_key_invalid", step_key: stepKey, message: `${stepKey} must use <case_id>/<step_id>` });
17998
+ continue;
17999
+ }
18000
+ if (!isRecord8(rawStep) || rawStep.runner !== "browser_action") {
18001
+ issues.push({ rule_id: "test_suite.automation.runner_invalid", step_key: stepKey, message: `${stepKey} runner must be browser_action` });
18002
+ continue;
18003
+ }
18004
+ if (!isRecord8(rawStep.page_fingerprint) || Object.keys(rawStep.page_fingerprint).length === 0) {
18005
+ issues.push({
18006
+ rule_id: "test_suite.automation.page_fingerprint_missing",
18007
+ step_key: stepKey,
18008
+ message: `${stepKey} requires page_fingerprint so cache drift is detected before mutation`
18009
+ });
18010
+ }
18011
+ const actions = Array.isArray(rawStep.actions) ? rawStep.actions : [];
18012
+ const checks = Array.isArray(rawStep.expected_checks) ? rawStep.expected_checks : [];
18013
+ if (actions.length === 0) {
18014
+ issues.push({ rule_id: "test_suite.automation.actions_missing", step_key: stepKey, message: `${stepKey} requires at least one action` });
18015
+ }
18016
+ if (checks.length === 0) {
18017
+ issues.push({
18018
+ rule_id: "test_suite.automation.expected_checks_missing",
18019
+ step_key: stepKey,
18020
+ message: `${stepKey} requires expected_checks`
18021
+ });
18022
+ }
18023
+ actions.forEach((action, index) => issues.push(...actionIssues(action, stepKey, index, false)));
18024
+ checks.forEach((action, index) => issues.push(...actionIssues(action, stepKey, index, true)));
18025
+ }
18026
+ return { document: value, issues };
18027
+ }
18028
+ async function loadBrowserAutomation(file) {
18029
+ const resolved = path11.resolve(file);
18030
+ let value;
18031
+ try {
18032
+ value = JSON.parse(await readFile12(resolved, "utf8"));
18033
+ } catch (error) {
18034
+ throw new Error(`Invalid browser automation file ${resolved}: ${error instanceof Error ? error.message : String(error)}`);
18035
+ }
18036
+ const validated = validateBrowserAutomationDocument(value);
18037
+ if (!validated.document || validated.issues.length > 0) {
18038
+ const details = validated.issues.map((issue3) => `[${issue3.rule_id}] ${issue3.message}`).join("\n");
18039
+ throw new Error(`Browser automation lint failed for ${resolved}:
18040
+ ${details}`);
18041
+ }
18042
+ return validated.document;
18043
+ }
18044
+
17774
18045
  // src/core/test-suite.ts
17775
18046
  import { createHash as createHash5 } from "crypto";
17776
18047
  import {
@@ -17779,7 +18050,7 @@ import {
17779
18050
  mkdir as mkdir9,
17780
18051
  open as open2,
17781
18052
  readdir as readdir4,
17782
- readFile as readFile12,
18053
+ readFile as readFile13,
17783
18054
  realpath as realpath2,
17784
18055
  rename,
17785
18056
  rm as rm4,
@@ -17787,7 +18058,7 @@ import {
17787
18058
  unlink,
17788
18059
  writeFile as writeFile9
17789
18060
  } from "fs/promises";
17790
- import path11 from "path";
18061
+ import path12 from "path";
17791
18062
  import { inflateSync } from "zlib";
17792
18063
  var DEFAULT_SUITE_ROOT = ".ai_test/suite";
17793
18064
  var DEFAULT_DRAFT_ROOT = ".ai_test/suite_draft";
@@ -17843,7 +18114,7 @@ var REQUIRED_README_KEYS = ["scenario_id", "workspace", "flow_type", "core", "st
17843
18114
  var PRIORITIES = /* @__PURE__ */ new Set(["P0", "P1", "P2"]);
17844
18115
  var CASE_TYPES = /* @__PURE__ */ new Set(["positive", "negative", "boundary", "permission", "data_consistency", "regression"]);
17845
18116
  var STATUSES = /* @__PURE__ */ new Set(["active", "deprecated", "draft"]);
17846
- var CASE_STEP_RUNNERS = /* @__PURE__ */ new Set(["browser", "identity", "e2e_create_page", "e2e_step_run", "observe"]);
18117
+ var CASE_STEP_RUNNERS = /* @__PURE__ */ new Set(["browser", "browser_action", "identity", "e2e_create_page", "e2e_step_run", "observe"]);
17847
18118
  var IDENTITY_STEP_RE = /(?:切换|恢复|检查|核对|验证).{0,12}(?:身份|用户|管理员)|(?:mock|unmock|模拟用户)/i;
17848
18119
  var CASE_STEP_ACTION_VERBS = [
17849
18120
  "\u6253\u5F00",
@@ -17994,7 +18265,7 @@ async function exists3(filePath) {
17994
18265
  }
17995
18266
  }
17996
18267
  async function readText(filePath) {
17997
- return readFile12(filePath, "utf8");
18268
+ return readFile13(filePath, "utf8");
17998
18269
  }
17999
18270
  function fail(message, options = {}) {
18000
18271
  throw new TestSuiteError(message, options);
@@ -18055,12 +18326,12 @@ function reviewSchemaExplanation() {
18055
18326
  };
18056
18327
  }
18057
18328
  function reviewFail(reviewPath, message) {
18058
- const scenarioId = path11.basename(path11.dirname(reviewPath));
18329
+ const scenarioId = path12.basename(path12.dirname(reviewPath));
18059
18330
  fail(
18060
18331
  [
18061
18332
  message,
18062
18333
  "\u8FD0\u884C `bpmax-cli test-suite review explain --format json` \u67E5\u770B\u5B8C\u6574 schema\u3002",
18063
- `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path11.dirname(path11.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
18334
+ `\u8FD0\u884C \`bpmax-cli test-suite review repair --scenario ${scenarioId} --draft-root ${path12.dirname(path12.dirname(reviewPath))} --latest-proof <proof.json> --format json\` \u4FEE\u8865\u7F3A\u5931\u5B57\u6BB5\u3002`,
18064
18335
  `\u6700\u5C0F review.json \u793A\u4F8B\uFF1A${JSON.stringify(reviewSchemaExample(scenarioId))}`
18065
18336
  ].join("\n"),
18066
18337
  {
@@ -18115,7 +18386,7 @@ async function readCases(filePath) {
18115
18386
  code: "legacy_case_steps_format",
18116
18387
  rule_id: "test_suite.case_steps.legacy_aggregated",
18117
18388
  path: filePath,
18118
- suggestion: `\u8FD0\u884C \`bpmax-cli test-suite steps migrate --scenario ${path11.basename(path11.dirname(filePath))} --draft-root ${path11.dirname(path11.dirname(filePath))} --latest-proof <proof.json> --format json\`\uFF0C\u518D\u8865\u9F50\u9010\u6B65\u9AA4\u5B57\u6BB5\u3002`
18389
+ suggestion: `\u8FD0\u884C \`bpmax-cli test-suite steps migrate --scenario ${path12.basename(path12.dirname(filePath))} --draft-root ${path12.dirname(path12.dirname(filePath))} --latest-proof <proof.json> --format json\`\uFF0C\u518D\u8865\u9F50\u9010\u6B65\u9AA4\u5B57\u6BB5\u3002`
18119
18390
  });
18120
18391
  }
18121
18392
  if (JSON.stringify(fields) !== JSON.stringify(CASE_FIELDS)) {
@@ -18215,14 +18486,14 @@ function parseReadmeText(filePath, text5) {
18215
18486
  return metadata;
18216
18487
  }
18217
18488
  async function validateReadme(scenarioDir) {
18218
- const readmePath = path11.join(scenarioDir, "README.md");
18489
+ const readmePath = path12.join(scenarioDir, "README.md");
18219
18490
  if (!await exists3(readmePath)) fail(`missing README.md: ${readmePath}`);
18220
18491
  const text5 = await readText(readmePath);
18221
18492
  const metadata = parseReadmeText(readmePath, text5);
18222
18493
  for (const key of REQUIRED_README_KEYS) {
18223
18494
  if (!metadata[key]) fail(`${scenarioDir}: README.md missing \`${key}\``);
18224
18495
  }
18225
- if (metadata.scenario_id !== path11.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
18496
+ if (metadata.scenario_id !== path12.basename(scenarioDir)) fail(`${scenarioDir}: scenario_id must match directory name`);
18226
18497
  if (!["true", "false"].includes(metadata.core.toLowerCase())) fail(`${scenarioDir}: core must be true or false`);
18227
18498
  if (!STATUSES.has(metadata.status)) fail(`${scenarioDir}: status must be one of ${JSON.stringify([...STATUSES].sort())}`);
18228
18499
  if (UUID_RE2.test(text5) || ID_AS_ENTRY_RE.test(text5)) {
@@ -18317,6 +18588,76 @@ function hasE2eReusableAsset(row, steps) {
18317
18588
  const evidencePlan = [row.prep_data, caseStepText(steps), row.expected_result, row.evidence_required, row.tags].join(" ");
18318
18589
  return E2E_REUSABLE_ASSET_RE.test(evidencePlan);
18319
18590
  }
18591
+ async function readScenarioAutomation(scenarioDir) {
18592
+ const filePath = path12.join(scenarioDir, "automation.json");
18593
+ if (!await exists3(filePath)) return void 0;
18594
+ let value;
18595
+ try {
18596
+ value = JSON.parse(await readText(filePath));
18597
+ } catch (error) {
18598
+ fail(`${filePath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`, {
18599
+ rule_id: "test_suite.automation.schema_invalid",
18600
+ path: filePath
18601
+ });
18602
+ }
18603
+ const validated = validateBrowserAutomationDocument(value);
18604
+ if (!validated.document || validated.issues.length > 0) {
18605
+ const first = validated.issues[0];
18606
+ fail(`${filePath}: ${first?.message ?? "invalid browser automation"}`, {
18607
+ rule_id: first?.rule_id ?? "test_suite.automation.schema_invalid",
18608
+ path: filePath,
18609
+ suggestion: "Fix automation.json so every browser_action step has stable semantic selectors, page_fingerprint, actions, and expected_checks."
18610
+ });
18611
+ }
18612
+ return validated.document;
18613
+ }
18614
+ async function validateScenarioAutomation(scenarioDir, steps) {
18615
+ const browserSteps = steps.filter((step) => step.runner === "browser" || step.runner === "browser_action");
18616
+ const deterministicSteps = steps.filter((step) => step.runner === "browser_action");
18617
+ const automation = await readScenarioAutomation(scenarioDir);
18618
+ const automationPath = path12.join(scenarioDir, "automation.json");
18619
+ if (deterministicSteps.length > 0 && !automation) {
18620
+ fail(`${automationPath}: browser_action steps require automation.json`, {
18621
+ rule_id: "test_suite.automation.file_missing",
18622
+ path: automationPath,
18623
+ suggestion: "Create automation.json or keep a first-time unsupported step as runner=browser until it has been recorded and reviewed."
18624
+ });
18625
+ }
18626
+ const knownStepKeys = new Set(steps.map((step) => automationStepKey(step.case_id, step.step_id)));
18627
+ const deterministicKeys = new Set(deterministicSteps.map((step) => automationStepKey(step.case_id, step.step_id)));
18628
+ for (const key of Object.keys(automation?.steps ?? {})) {
18629
+ if (!knownStepKeys.has(key)) {
18630
+ fail(`${automationPath}: automation step ${key} does not match case_steps.csv`, {
18631
+ rule_id: "test_suite.automation.orphan_step",
18632
+ path: automationPath
18633
+ });
18634
+ }
18635
+ if (!deterministicKeys.has(key)) {
18636
+ fail(`${automationPath}: automation step ${key} must reference a case_steps.csv row with runner=browser_action`, {
18637
+ rule_id: "test_suite.automation.runner_mismatch",
18638
+ path: automationPath
18639
+ });
18640
+ }
18641
+ }
18642
+ for (const step of deterministicSteps) {
18643
+ const key = automationStepKey(step.case_id, step.step_id);
18644
+ if (!automation?.steps[key]) {
18645
+ fail(`${automationPath}: missing automation for ${key}`, {
18646
+ rule_id: "test_suite.automation.step_missing",
18647
+ path: automationPath
18648
+ });
18649
+ }
18650
+ }
18651
+ const automatedSteps = deterministicSteps.length;
18652
+ const manualSteps = browserSteps.length - automatedSteps;
18653
+ return {
18654
+ browser_steps: browserSteps.length,
18655
+ automated_steps: automatedSteps,
18656
+ manual_only_steps: manualSteps,
18657
+ coverage: browserSteps.length === 0 ? 1 : Number((automatedSteps / browserSteps.length).toFixed(4)),
18658
+ ready_for_batch: browserSteps.length === automatedSteps
18659
+ };
18660
+ }
18320
18661
  function validateReadableCaseContent(filePath, caseId, row) {
18321
18662
  for (const field of ["title", "preconditions", "config_basis", "prep_data", "expected_result", "test_data"]) {
18322
18663
  const value = row[field].trim();
@@ -18456,9 +18797,15 @@ function validateCaseSteps(filePath, cases, steps) {
18456
18797
  if (step.actor !== "system" && !roles.includes(step.actor)) {
18457
18798
  fail(`${location}: actor \u5FC5\u987B\u5C5E\u4E8E cases.csv roles\uFF0C\u7CFB\u7EDF\u89C2\u5BDF\u6B65\u9AA4\u53EF\u4F7F\u7528 system`, { rule_id: "test_suite.case_step.actor_role", path: filePath });
18458
18799
  }
18459
- if ((step.runner === "browser" || step.runner === "e2e_create_page") && !/screenshot|截图/i.test(step.evidence_required)) {
18800
+ if ((step.runner === "browser" || step.runner === "browser_action" || step.runner === "e2e_create_page") && !/screenshot|截图/i.test(step.evidence_required)) {
18460
18801
  fail(`${location}: browser \u6B65\u9AA4 evidence_required \u5FC5\u987B\u5305\u542B screenshot`, { rule_id: "test_suite.case_step.browser_evidence", path: filePath });
18461
18802
  }
18803
+ if (step.runner === "browser" && /manual[_ -]?only|仅人工|无法自动化/i.test([step.action, step.input_data, step.expected_result].join(" ")) && !/manual_reason\s*=|人工原因\s*=|无法自动化原因\s*=/i.test(step.input_data)) {
18804
+ fail(`${location}: manual_only browser \u6B65\u9AA4\u5FC5\u987B\u5728 input_data \u5199\u660E manual_reason=<\u65E0\u6CD5\u81EA\u52A8\u5316\u7684\u5177\u4F53\u539F\u56E0>`, {
18805
+ rule_id: "test_suite.automation.manual_reason_missing",
18806
+ path: filePath
18807
+ });
18808
+ }
18462
18809
  if (step.runner === "e2e_step_run" && !/(context|submit|readback|step)/i.test(step.evidence_required)) {
18463
18810
  fail(`${location}: e2e_step_run \u6B65\u9AA4\u5FC5\u987B\u8981\u6C42 context/submit/readback \u8BC1\u636E`, { rule_id: "test_suite.case_step.cli_evidence", path: filePath });
18464
18811
  }
@@ -18561,17 +18908,20 @@ async function validateCase(filePath, row, steps, seen) {
18561
18908
  async function collectE2eAccelerationGaps(dirs) {
18562
18909
  const gaps = [];
18563
18910
  for (const dir of dirs) {
18564
- const scenarioId = path11.basename(dir);
18565
- const casesPath = path11.join(dir, "cases.csv");
18911
+ const scenarioId = path12.basename(dir);
18912
+ const casesPath = path12.join(dir, "cases.csv");
18566
18913
  if (!await exists3(casesPath)) {
18567
18914
  continue;
18568
18915
  }
18569
18916
  const rows2 = await readCases(casesPath);
18570
- const steps = await readCaseSteps(path11.join(dir, "case_steps.csv"));
18571
- const stepsByCase = validateCaseSteps(path11.join(dir, "case_steps.csv"), rows2, steps);
18917
+ const steps = await readCaseSteps(path12.join(dir, "case_steps.csv"));
18918
+ const stepsByCase = validateCaseSteps(path12.join(dir, "case_steps.csv"), rows2, steps);
18919
+ const automation = await readScenarioAutomation(dir);
18572
18920
  for (const row of rows2) {
18573
18921
  const caseSteps = stepsByCase.get(row.case_id.trim()) ?? [];
18574
- if (row.status === "deprecated" || hasE2eReusableAsset(row, caseSteps)) {
18922
+ const deterministicBrowserSteps = caseSteps.filter((step) => step.runner === "browser_action");
18923
+ const hasDeterministicAutomation = deterministicBrowserSteps.length > 0 && deterministicBrowserSteps.every((step) => Boolean(automation?.steps[automationStepKey(step.case_id, step.step_id)]));
18924
+ if (row.status === "deprecated" || hasE2eReusableAsset(row, caseSteps) || hasDeterministicAutomation) {
18575
18925
  continue;
18576
18926
  }
18577
18927
  gaps.push({
@@ -18588,7 +18938,7 @@ async function collectE2eAccelerationGaps(dirs) {
18588
18938
  async function scenarioDirs(root) {
18589
18939
  if (!await exists3(root)) return [];
18590
18940
  const items = await readdir4(root, { withFileTypes: true });
18591
- return items.filter((item) => item.isDirectory()).map((item) => path11.join(root, item.name)).sort();
18941
+ return items.filter((item) => item.isDirectory()).map((item) => path12.join(root, item.name)).sort();
18592
18942
  }
18593
18943
  function normalizedScenarioIds(scenarios) {
18594
18944
  return [...new Set((scenarios ?? []).map((scenario) => scenario.trim()).filter(Boolean))];
@@ -18621,11 +18971,12 @@ async function lintScenarioDirs(dirs) {
18621
18971
  }
18622
18972
  async function validateScenario(scenarioDir) {
18623
18973
  const metadata = await validateReadme(scenarioDir);
18624
- const casesPath = path11.join(scenarioDir, "cases.csv");
18974
+ const casesPath = path12.join(scenarioDir, "cases.csv");
18625
18975
  const rows2 = await readCases(casesPath);
18626
- const caseStepsPath = path11.join(scenarioDir, "case_steps.csv");
18976
+ const caseStepsPath = path12.join(scenarioDir, "case_steps.csv");
18627
18977
  const caseSteps = await readCaseSteps(caseStepsPath);
18628
18978
  const stepsByCase = validateCaseSteps(caseStepsPath, rows2, caseSteps);
18979
+ await validateScenarioAutomation(scenarioDir, caseSteps);
18629
18980
  if (rows2.length === 0) fail(`${casesPath}: at least one case is required`);
18630
18981
  const seen = /* @__PURE__ */ new Set();
18631
18982
  for (const row of rows2) await validateCase(casesPath, row, stepsByCase.get(row.case_id.trim()) ?? [], seen);
@@ -18659,6 +19010,13 @@ async function lintSuiteDetailed(root = DEFAULT_SUITE_ROOT, options = {}) {
18659
19010
  const selection = await selectedScenarioDirs(root, options.scenarios);
18660
19011
  const scenarios = await lintScenarioDirs(selection.dirs);
18661
19012
  const accelerationGaps = await collectE2eAccelerationGaps(selection.dirs);
19013
+ const coverageRows = await Promise.all(selection.dirs.map(async (dir) => {
19014
+ const steps = await readCaseSteps(path12.join(dir, "case_steps.csv"));
19015
+ return validateScenarioAutomation(dir, steps);
19016
+ }));
19017
+ const browserSteps = coverageRows.reduce((sum, row) => sum + row.browser_steps, 0);
19018
+ const automatedSteps = coverageRows.reduce((sum, row) => sum + row.automated_steps, 0);
19019
+ const manualOnlySteps = coverageRows.reduce((sum, row) => sum + row.manual_only_steps, 0);
18662
19020
  const selected = selection.scenarioIds.length > 0;
18663
19021
  return {
18664
19022
  ok: true,
@@ -18674,6 +19032,13 @@ async function lintSuiteDetailed(root = DEFAULT_SUITE_ROOT, options = {}) {
18674
19032
  missing_cases: accelerationGaps,
18675
19033
  rule: "Missing reusable acceleration assets do not fail lint directly. The E2E runner must bootstrap once through real browser/step execution, save evidence, and run record-from-evidence before repeating the scenario."
18676
19034
  },
19035
+ automation_coverage: {
19036
+ browser_steps: browserSteps,
19037
+ automated_steps: automatedSteps,
19038
+ manual_only_steps: manualOnlySteps,
19039
+ coverage: browserSteps === 0 ? 1 : Number((automatedSteps / browserSteps).toFixed(4)),
19040
+ ready_for_batch: browserSteps === automatedSteps
19041
+ },
18677
19042
  ...options.explain ? {
18678
19043
  review_schema: reviewSchemaExplanation(),
18679
19044
  case_fields: CASE_FIELDS,
@@ -18689,7 +19054,7 @@ function migratedStepActions(value) {
18689
19054
  async function migrateScenarioSteps(options) {
18690
19055
  const scenarioDir = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
18691
19056
  await validateReadme(scenarioDir);
18692
- const casesPath = path11.join(scenarioDir, "cases.csv");
19057
+ const casesPath = path12.join(scenarioDir, "cases.csv");
18693
19058
  const legacyRows = await readLegacyCases(casesPath);
18694
19059
  const nextCases = legacyRows.map(({ steps: _steps, ...row }) => row);
18695
19060
  const stepRows = [];
@@ -18719,7 +19084,7 @@ async function migrateScenarioSteps(options) {
18719
19084
  });
18720
19085
  }
18721
19086
  await writeFile9(casesPath, csvText(CASE_FIELDS, nextCases), "utf8");
18722
- const stepsPath = path11.join(scenarioDir, "case_steps.csv");
19087
+ const stepsPath = path12.join(scenarioDir, "case_steps.csv");
18723
19088
  await writeFile9(stepsPath, csvText(CASE_STEP_FIELDS, stepRows), "utf8");
18724
19089
  return {
18725
19090
  ok: false,
@@ -18734,9 +19099,11 @@ async function migrateScenarioSteps(options) {
18734
19099
  }
18735
19100
  async function suiteHash(scenarioDir) {
18736
19101
  const hash = createHash5("sha256");
18737
- hash.update(await readText(path11.join(scenarioDir, "README.md")));
18738
- hash.update(await readText(path11.join(scenarioDir, "cases.csv")));
18739
- hash.update(await readText(path11.join(scenarioDir, "case_steps.csv")));
19102
+ hash.update(await readText(path12.join(scenarioDir, "README.md")));
19103
+ hash.update(await readText(path12.join(scenarioDir, "cases.csv")));
19104
+ hash.update(await readText(path12.join(scenarioDir, "case_steps.csv")));
19105
+ const automationPath = path12.join(scenarioDir, "automation.json");
19106
+ if (await exists3(automationPath)) hash.update(await readText(automationPath));
18740
19107
  return hash.digest("hex");
18741
19108
  }
18742
19109
  function executionManifestHash(manifest) {
@@ -18745,7 +19112,7 @@ function executionManifestHash(manifest) {
18745
19112
  async function readExecutionManifest(manifestPath) {
18746
19113
  let value;
18747
19114
  try {
18748
- value = JSON.parse(await readText(path11.resolve(manifestPath)));
19115
+ value = JSON.parse(await readText(path12.resolve(manifestPath)));
18749
19116
  } catch {
18750
19117
  fail(`invalid execution manifest: ${manifestPath}`, { rule_id: "test_suite.execution_manifest.invalid", path: manifestPath });
18751
19118
  }
@@ -18756,10 +19123,10 @@ async function readExecutionManifest(manifestPath) {
18756
19123
  if (!RUN_RE.test(String(manifest.run_id || "")) || !SCENARIO_ID_RE.test(String(manifest.scenario_id || "")) || !String(manifest.case_id || "").trim() || !String(manifest.source_suite || "").trim() || !/^[a-f0-9]{64}$/.test(String(manifest.suite_hash || "")) || !Array.isArray(manifest.steps) || !["running", "pass", "fail", "blocked"].includes(manifest.result)) {
18757
19124
  fail(`invalid execution manifest shape: ${manifestPath}`, { rule_id: "test_suite.execution_manifest.invalid", path: manifestPath });
18758
19125
  }
18759
- if (path11.basename(path11.dirname(path11.resolve(manifestPath))) !== manifest.run_id) {
19126
+ if (path12.basename(path12.dirname(path12.resolve(manifestPath))) !== manifest.run_id) {
18760
19127
  fail("execution manifest run_id must match its report directory", { rule_id: "test_suite.execution_manifest.run_scope", path: manifestPath });
18761
19128
  }
18762
- const statePath = `${path11.resolve(manifestPath)}.state.json`;
19129
+ const statePath = `${path12.resolve(manifestPath)}.state.json`;
18763
19130
  if (await exists3(statePath)) {
18764
19131
  try {
18765
19132
  const state = JSON.parse(await readText(statePath));
@@ -18777,14 +19144,14 @@ async function readExecutionManifest(manifestPath) {
18777
19144
  return manifest;
18778
19145
  }
18779
19146
  async function writeAtomicJson(filePath, value) {
18780
- const resolved = path11.resolve(filePath);
19147
+ const resolved = path12.resolve(filePath);
18781
19148
  const tempPath = `${resolved}.tmp-${process.pid}-${Date.now()}`;
18782
19149
  await writeFile9(tempPath, `${JSON.stringify(value, null, 2)}
18783
19150
  `, "utf8");
18784
19151
  await rename(tempPath, resolved);
18785
19152
  }
18786
19153
  async function withExecutionManifestLock(manifestPath, action) {
18787
- const resolved = path11.resolve(manifestPath);
19154
+ const resolved = path12.resolve(manifestPath);
18788
19155
  const lockPath = `${resolved}.lock`;
18789
19156
  let handle;
18790
19157
  try {
@@ -18818,20 +19185,20 @@ async function evidenceContainsDiagnostic(evidencePath) {
18818
19185
  if (!entry.isFile()) continue;
18819
19186
  if (/diagnostic/i.test(entry.name)) return true;
18820
19187
  if (!/\.(json|txt|md)$/i.test(entry.name)) continue;
18821
- const value2 = await readText(path11.join(evidencePath, entry.name)).catch(() => "");
19188
+ const value2 = await readText(path12.join(evidencePath, entry.name)).catch(() => "");
18822
19189
  if (/"?diagnostic"?\s*[:=]\s*(?:true|"diagnostic")|result\s*[:=]\s*diagnostic/i.test(value2)) return true;
18823
19190
  }
18824
19191
  return false;
18825
19192
  }
18826
- if (/diagnostic/i.test(path11.basename(evidencePath))) return true;
19193
+ if (/diagnostic/i.test(path12.basename(evidencePath))) return true;
18827
19194
  if (!/\.(json|txt|md)$/i.test(evidencePath)) return false;
18828
19195
  const value = await readText(evidencePath).catch(() => "");
18829
19196
  return /"?diagnostic"?\s*[:=]\s*(?:true|"diagnostic")|result\s*[:=]\s*diagnostic/i.test(value);
18830
19197
  }
18831
19198
  function pathInside(root, candidate) {
18832
- const resolvedRoot = path11.resolve(root);
18833
- const resolvedCandidate = path11.resolve(candidate);
18834
- return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path11.sep}`);
19199
+ const resolvedRoot = path12.resolve(root);
19200
+ const resolvedCandidate = path12.resolve(candidate);
19201
+ return resolvedCandidate === resolvedRoot || resolvedCandidate.startsWith(`${resolvedRoot}${path12.sep}`);
18835
19202
  }
18836
19203
  async function pathInsideReal(root, candidate) {
18837
19204
  if (!pathInside(root, candidate)) return false;
@@ -18862,7 +19229,7 @@ async function assertCurrentRunArtifact(manifest, artifactPath) {
18862
19229
  }
18863
19230
  async function assertCurrentRunEvidence(manifest, manifestPath, evidencePath) {
18864
19231
  if (!await exists3(evidencePath)) fail(`execution evidence not found: ${evidencePath}`, { rule_id: "test_suite.run.evidence_missing", path: evidencePath });
18865
- const runDir = path11.dirname(path11.resolve(manifestPath));
19232
+ const runDir = path12.dirname(path12.resolve(manifestPath));
18866
19233
  await assertCurrentRunPathScope(runDir, evidencePath, "formal execution evidence must stay inside the current report run directory");
18867
19234
  const info = await stat7(evidencePath);
18868
19235
  if (info.mtime.getTime() + 1e3 < new Date(manifest.started_at).getTime()) {
@@ -18879,13 +19246,13 @@ async function evidenceTexts(evidencePath) {
18879
19246
  const texts = [];
18880
19247
  for (const entry of entries) {
18881
19248
  if (!entry.isFile() || !/\.(json|txt|md)$/i.test(entry.name)) continue;
18882
- texts.push(await readText(path11.join(evidencePath, entry.name)).catch(() => ""));
19249
+ texts.push(await readText(path12.join(evidencePath, entry.name)).catch(() => ""));
18883
19250
  }
18884
19251
  return texts;
18885
19252
  }
18886
19253
  async function evidenceJsonRecords(evidencePath) {
18887
19254
  const info = await stat7(evidencePath);
18888
- const paths = info.isDirectory() ? (await readdir4(evidencePath, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path11.join(evidencePath, entry.name)) : [evidencePath];
19255
+ const paths = info.isDirectory() ? (await readdir4(evidencePath, { withFileTypes: true })).filter((entry) => entry.isFile() && entry.name.endsWith(".json")).map((entry) => path12.join(evidencePath, entry.name)) : [evidencePath];
18889
19256
  const records = [];
18890
19257
  for (const source of paths) {
18891
19258
  try {
@@ -18930,9 +19297,9 @@ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidence
18930
19297
  if (expectedResult !== "pass" && !assertions.some((assertion) => assertion.passed === false)) continue;
18931
19298
  const screenshot = typeof value.screenshot === "string" ? value.screenshot.trim() : "";
18932
19299
  if (!screenshot) continue;
18933
- const screenshotPath = path11.resolve(path11.dirname(source), screenshot);
19300
+ const screenshotPath = path12.resolve(path12.dirname(source), screenshot);
18934
19301
  await assertCurrentRunArtifact(manifest, source);
18935
- await assertCurrentRunPathScope(path11.dirname(manifestPath), screenshotPath, "browser screenshot must stay inside the current report run directory");
19302
+ await assertCurrentRunPathScope(path12.dirname(manifestPath), screenshotPath, "browser screenshot must stay inside the current report run directory");
18936
19303
  await assertCurrentRunArtifact(manifest, screenshotPath);
18937
19304
  if (!await isValidCurrentRunScreenshot(screenshotPath)) {
18938
19305
  fail("browser pass evidence screenshot must be a valid visible PNG of at least 100x80", { rule_id: "test_suite.run.screenshot_invalid", path: screenshotPath });
@@ -18940,8 +19307,8 @@ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidence
18940
19307
  if (/\bdom\b/i.test(step.evidence_required)) {
18941
19308
  const domSnapshot = typeof value.dom_snapshot === "string" ? value.dom_snapshot.trim() : "";
18942
19309
  if (!domSnapshot) continue;
18943
- const domPath = path11.resolve(path11.dirname(source), domSnapshot);
18944
- await assertCurrentRunPathScope(path11.dirname(manifestPath), domPath, "browser DOM evidence must stay inside the current report run directory");
19310
+ const domPath = path12.resolve(path12.dirname(source), domSnapshot);
19311
+ await assertCurrentRunPathScope(path12.dirname(manifestPath), domPath, "browser DOM evidence must stay inside the current report run directory");
18945
19312
  await assertCurrentRunArtifact(manifest, domPath);
18946
19313
  }
18947
19314
  matchedRecord = true;
@@ -19024,7 +19391,7 @@ async function browserReportEvidence(manifest) {
19024
19391
  const result = { assertions: [], screenshots: [] };
19025
19392
  const priority = { page: 1, project: 2, step: 3 };
19026
19393
  for (const step of manifest.steps) {
19027
- if (step.status === "planned" || !["browser", "e2e_create_page"].includes(step.runner)) continue;
19394
+ if (step.status === "planned" || !["browser", "browser_action", "e2e_create_page"].includes(step.runner)) continue;
19028
19395
  for (const evidencePath of step.evidence) {
19029
19396
  for (const { value, source } of await evidenceJsonRecords(evidencePath)) {
19030
19397
  if (value.case_id !== step.case_id || value.case_step_id !== step.step_id || value.browser_verified !== true) continue;
@@ -19043,11 +19410,14 @@ async function browserReportEvidence(manifest) {
19043
19410
  const assertions = Array.isArray(value.assertions) ? value.assertions.map(asRecord) : [];
19044
19411
  for (const assertion of assertions) {
19045
19412
  if (step.status === "pass" && assertion.passed !== true) continue;
19046
- const label = String(assertion.name || assertion.message || "").trim();
19413
+ const target = asRecord(assertion.target);
19414
+ const targetLabel = String(target.field || target.label || target.name || target.text || "").trim();
19415
+ const label = String(assertion.name || assertion.message || assertion.type || "").trim();
19047
19416
  if (label) result.assertions.push(assertion.passed === false ? `\u5931\u8D25\u65AD\u8A00\uFF1A${label}` : label);
19417
+ if (label && targetLabel) result.assertions.push(`${label}: ${targetLabel}`);
19048
19418
  }
19049
19419
  const screenshot = String(value.screenshot || "").trim();
19050
- if (screenshot) result.screenshots.push({ stepId: step.step_id, path: path11.resolve(path11.dirname(source), screenshot) });
19420
+ if (screenshot) result.screenshots.push({ stepId: step.step_id, path: path12.resolve(path12.dirname(source), screenshot) });
19051
19421
  }
19052
19422
  }
19053
19423
  }
@@ -19055,11 +19425,11 @@ async function browserReportEvidence(manifest) {
19055
19425
  return result;
19056
19426
  }
19057
19427
  async function syncTestSuiteRunReportUnlocked(manifestFile) {
19058
- const manifestPath = path11.resolve(manifestFile);
19428
+ const manifestPath = path12.resolve(manifestFile);
19059
19429
  const manifest = await readExecutionManifest(manifestPath);
19060
19430
  await assertExecutionManifestFresh(manifest, manifestPath);
19061
- const runDir = path11.dirname(manifestPath);
19062
- const reportPath = path11.join(runDir, `${manifest.scenario_id}.md`);
19431
+ const runDir = path12.dirname(manifestPath);
19432
+ const reportPath = path12.join(runDir, `${manifest.scenario_id}.md`);
19063
19433
  if (!await exists3(reportPath)) {
19064
19434
  fail("scenario report scaffold is missing; restart the run or restore the generated report", { rule_id: "test_suite.run.report_missing", path: reportPath });
19065
19435
  }
@@ -19078,7 +19448,7 @@ async function syncTestSuiteRunReportUnlocked(manifestFile) {
19078
19448
  report = replaceReportMetadata(report, "executed_steps", executedSteps.length > 0 ? executedSteps.map((step) => `${manifest.case_id}/${step.step_id}`).join(", ") : "pending");
19079
19449
  const stoppedStep = manifest.steps.find((step) => step.status === "fail" || step.status === "blocked");
19080
19450
  report = replaceReportMetadata(report, "stopped_after_fail", stoppedStep ? `${manifest.case_id}/${stoppedStep.step_id}` : null);
19081
- const browserBlocked = stoppedStep?.status === "blocked" && ["browser", "e2e_create_page"].includes(stoppedStep.runner);
19451
+ const browserBlocked = stoppedStep?.status === "blocked" && ["browser", "browser_action", "e2e_create_page"].includes(stoppedStep.runner);
19082
19452
  let blockerEvidence;
19083
19453
  if (browserBlocked) {
19084
19454
  for (const evidencePath of stoppedStep.evidence) {
@@ -19087,7 +19457,7 @@ async function syncTestSuiteRunReportUnlocked(manifestFile) {
19087
19457
  }
19088
19458
  }
19089
19459
  report = replaceReportMetadata(report, "browser_status", blockerEvidence ? "blocked" : null);
19090
- report = replaceReportMetadata(report, "blocker_evidence", blockerEvidence ? path11.relative(runDir, blockerEvidence) : null);
19460
+ report = replaceReportMetadata(report, "blocker_evidence", blockerEvidence ? path12.relative(runDir, blockerEvidence) : null);
19091
19461
  report = replaceReportMetadata(report, "runtime_profile", manifest.profile);
19092
19462
  report = replaceReportMetadata(report, "profile_origin", manifest.profile_origin || null);
19093
19463
  report = replaceReportMetadata(report, "runtime_workspace", manifest.workspace || null);
@@ -19106,11 +19476,11 @@ async function syncTestSuiteRunReportUnlocked(manifestFile) {
19106
19476
  `| ${manifest.case_id}`,
19107
19477
  `${step.step_id} ${step.action}`,
19108
19478
  step.status,
19109
- step.evidence.length ? step.evidence.map((item) => `\`${path11.relative(runDir, item)}\``).join("<br>") : "pending"
19479
+ step.evidence.length ? step.evidence.map((item) => `\`${path12.relative(runDir, item)}\``).join("<br>") : "pending"
19110
19480
  ].join(" | ") + " |")
19111
19481
  ].join("\n");
19112
19482
  report = replaceReportSection(report, "## 3. \u7528\u4F8B\u6267\u884C\u7ED3\u679C", "## 4. \u622A\u56FE\u8BC1\u636E", table);
19113
- const screenshotBody = evidence.screenshots.length ? evidence.screenshots.map((item) => `![${manifest.case_id} ${item.stepId} \u672C\u8F6E\u9875\u9762\u8BC1\u636E](${path11.relative(runDir, item.path)})`).join("\n\n") : "pending";
19483
+ const screenshotBody = evidence.screenshots.length ? evidence.screenshots.map((item) => `![${manifest.case_id} ${item.stepId} \u672C\u8F6E\u9875\u9762\u8BC1\u636E](${path12.relative(runDir, item.path)})`).join("\n\n") : "pending";
19114
19484
  report = replaceReportSection(report, "## 4. \u622A\u56FE\u8BC1\u636E", "## 5. \u63A5\u53E3 / \u6570\u636E\u56DE\u8BFB\u8BC1\u636E", screenshotBody);
19115
19485
  const tempPath = `${reportPath}.tmp-${process.pid}`;
19116
19486
  await writeFile9(tempPath, report, "utf8");
@@ -19124,12 +19494,12 @@ async function previousBrowserScreenshotHashes(manifest, step) {
19124
19494
  const hashes = /* @__PURE__ */ new Set();
19125
19495
  for (const previous of manifest.steps) {
19126
19496
  if (previous.step_no === step.step_no) break;
19127
- if (previous.status !== "pass" || !["browser", "e2e_create_page"].includes(previous.runner)) continue;
19497
+ if (previous.status !== "pass" || !["browser", "browser_action", "e2e_create_page"].includes(previous.runner)) continue;
19128
19498
  for (const previousEvidence of previous.evidence) {
19129
19499
  for (const { value, source } of await evidenceJsonRecords(previousEvidence)) {
19130
19500
  const screenshot = typeof value.screenshot === "string" ? value.screenshot.trim() : "";
19131
19501
  if (!screenshot) continue;
19132
- const screenshotPath = path11.resolve(path11.dirname(source), screenshot);
19502
+ const screenshotPath = path12.resolve(path12.dirname(source), screenshot);
19133
19503
  if (await exists3(screenshotPath)) hashes.add(await sha256(screenshotPath));
19134
19504
  }
19135
19505
  }
@@ -19164,7 +19534,7 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
19164
19534
  });
19165
19535
  }
19166
19536
  }
19167
- if (step.runner === "browser" || step.runner === "e2e_create_page") {
19537
+ if (step.runner === "browser" || step.runner === "browser_action" || step.runner === "e2e_create_page") {
19168
19538
  const screenshots = await browserEvidenceScreenshots(manifest, manifestPath, step, evidencePath);
19169
19539
  const previousHashes = await previousBrowserScreenshotHashes(manifest, step);
19170
19540
  for (const screenshot of screenshots) {
@@ -19181,8 +19551,8 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
19181
19551
  const sourceEvidence = typeof value.source_evidence === "string" ? value.source_evidence : "";
19182
19552
  if (!observed || assertions.length === 0 || !assertions.every((assertion) => assertion.passed === true) || !sourceEvidence) continue;
19183
19553
  await assertCurrentRunArtifact(manifest, source);
19184
- const sourcePath = path11.resolve(path11.dirname(source), sourceEvidence);
19185
- const runDir = path11.dirname(path11.resolve(manifestPath));
19554
+ const sourcePath = path12.resolve(path12.dirname(source), sourceEvidence);
19555
+ const runDir = path12.dirname(path12.resolve(manifestPath));
19186
19556
  if (!pathInside(runDir, sourcePath)) {
19187
19557
  fail("observe source_evidence must stay inside the current report run directory", { rule_id: "test_suite.run.evidence_scope", path: sourcePath });
19188
19558
  }
@@ -19202,7 +19572,7 @@ async function writeExecutionManifest(manifestPath, manifest, incrementRevision
19202
19572
  if (incrementRevision) manifest.revision = (manifest.revision ?? 0) + 1;
19203
19573
  else manifest.revision ??= 0;
19204
19574
  await writeAtomicJson(manifestPath, manifest);
19205
- await writeAtomicJson(`${path11.resolve(manifestPath)}.state.json`, {
19575
+ await writeAtomicJson(`${path12.resolve(manifestPath)}.state.json`, {
19206
19576
  revision: manifest.revision,
19207
19577
  hash: executionManifestHash(manifest),
19208
19578
  updated_at: (/* @__PURE__ */ new Date()).toISOString()
@@ -19214,15 +19584,15 @@ function currentManifestStep(manifest) {
19214
19584
  async function startTestSuiteRun(options) {
19215
19585
  const scenarioDir = scenarioPath(options.suiteRoot ?? DEFAULT_SUITE_ROOT, options.scenario);
19216
19586
  const scenario = await validateScenario(scenarioDir);
19217
- const rows2 = await readCases(path11.join(scenarioDir, "cases.csv"));
19587
+ const rows2 = await readCases(path12.join(scenarioDir, "cases.csv"));
19218
19588
  const row = rows2.find((item) => item.case_id === options.caseId && item.status !== "deprecated");
19219
19589
  if (!row) fail(`${scenarioDir}: active case not found: ${options.caseId}`, { rule_id: "test_suite.run.case_not_found" });
19220
- const allSteps = await readCaseSteps(path11.join(scenarioDir, "case_steps.csv"));
19221
- const grouped = validateCaseSteps(path11.join(scenarioDir, "case_steps.csv"), rows2, allSteps);
19590
+ const allSteps = await readCaseSteps(path12.join(scenarioDir, "case_steps.csv"));
19591
+ const grouped = validateCaseSteps(path12.join(scenarioDir, "case_steps.csv"), rows2, allSteps);
19222
19592
  const selectedSteps = grouped.get(options.caseId) ?? [];
19223
19593
  const reportDir = await nextReportDir(options.reportRoot ?? DEFAULT_REPORT_ROOT, true);
19224
- const runId = path11.basename(reportDir);
19225
- const manifestPath = path11.join(reportDir, "execution-manifest.json");
19594
+ const runId = path12.basename(reportDir);
19595
+ const manifestPath = path12.join(reportDir, "execution-manifest.json");
19226
19596
  const manifest = {
19227
19597
  version: 1,
19228
19598
  run_id: runId,
@@ -19234,7 +19604,7 @@ async function startTestSuiteRun(options) {
19234
19604
  revision: 0,
19235
19605
  ...options.skillSource ? { skill_source: options.skillSource } : {},
19236
19606
  ...options.skillVersion ? { skill_version: options.skillVersion } : {},
19237
- source_suite: path11.resolve(scenarioDir),
19607
+ source_suite: path12.resolve(scenarioDir),
19238
19608
  suite_hash: await suiteHash(scenarioDir),
19239
19609
  rerun_policy: "full_rerun",
19240
19610
  started_at: (/* @__PURE__ */ new Date()).toISOString(),
@@ -19244,7 +19614,7 @@ async function startTestSuiteRun(options) {
19244
19614
  };
19245
19615
  await writeExecutionManifest(manifestPath, manifest);
19246
19616
  await writeFile9(
19247
- path11.join(reportDir, "ux-findings.json"),
19617
+ path12.join(reportDir, "ux-findings.json"),
19248
19618
  `${JSON.stringify({
19249
19619
  version: 1,
19250
19620
  run_id: runId,
@@ -19256,14 +19626,14 @@ async function startTestSuiteRun(options) {
19256
19626
  `,
19257
19627
  "utf8"
19258
19628
  );
19259
- const scenarioReport = path11.join(reportDir, `${options.scenario}.md`);
19629
+ const scenarioReport = path12.join(reportDir, `${options.scenario}.md`);
19260
19630
  const plannedSteps = selectedSteps.map((step) => `${options.caseId}/${step.step_id}`).join(", ");
19261
19631
  await writeFile9(
19262
19632
  scenarioReport,
19263
19633
  [
19264
19634
  `run_id: ${runId}`,
19265
19635
  `scenario_id: ${options.scenario}`,
19266
- `source_suite: ${path11.resolve(scenarioDir)}`,
19636
+ `source_suite: ${path12.resolve(scenarioDir)}`,
19267
19637
  "result: partial",
19268
19638
  "test_design_skill: bpmax-functional-test-design",
19269
19639
  "ux_audit_skill: bpmax-ui-ux-audit",
@@ -19278,7 +19648,7 @@ async function startTestSuiteRun(options) {
19278
19648
  `planned_steps: ${plannedSteps}`,
19279
19649
  "executed_steps: pending",
19280
19650
  "execution_manifest: execution-manifest.json",
19281
- `precondition_check: ${path11.join(reportDir, `precondition-${runId}.json`)}`,
19651
+ `precondition_check: ${path12.join(reportDir, `precondition-${runId}.json`)}`,
19282
19652
  `state_file: ${manifestPath}`,
19283
19653
  `report_run: ${reportDir}`,
19284
19654
  "browser_tool: Chrome DevTools",
@@ -19320,8 +19690,15 @@ async function startTestSuiteRun(options) {
19320
19690
  };
19321
19691
  }
19322
19692
  async function validateExecutionManifestStep(options) {
19323
- const manifestPath = path11.resolve(options.manifest);
19693
+ const manifestPath = path12.resolve(options.manifest);
19324
19694
  const manifest = await readExecutionManifest(manifestPath);
19695
+ if (manifest.result !== "running") {
19696
+ fail("completed execution manifests cannot be resumed or reused as a new run", {
19697
+ rule_id: "test_suite.run.completed_manifest",
19698
+ path: manifestPath,
19699
+ suggestion: "Run `bpmax-cli test-suite run start ...` to create a new full_rerun manifest with new evidence."
19700
+ });
19701
+ }
19325
19702
  if (manifest.case_id !== options.caseId || manifest.current_step_id !== options.caseStepId) {
19326
19703
  fail(`execution manifest current step is ${manifest.case_id}/${manifest.current_step_id ?? "<complete>"}, not ${options.caseId}/${options.caseStepId}`, { rule_id: "test_suite.run.step_mismatch", path: manifestPath });
19327
19704
  }
@@ -19340,11 +19717,11 @@ async function validateExecutionManifestStep(options) {
19340
19717
  return { manifestPath, manifest, step };
19341
19718
  }
19342
19719
  async function preflightExecutionEvidenceDirectory(options) {
19343
- const manifestPath = path11.resolve(options.manifest);
19720
+ const manifestPath = path12.resolve(options.manifest);
19344
19721
  const manifest = await readExecutionManifest(manifestPath);
19345
19722
  await assertExecutionManifestFresh(manifest, manifestPath);
19346
- const runDir = path11.dirname(manifestPath);
19347
- const evidenceDir = path11.resolve(options.evidenceDir);
19723
+ const runDir = path12.dirname(manifestPath);
19724
+ const evidenceDir = path12.resolve(options.evidenceDir);
19348
19725
  if (!pathInside(runDir, evidenceDir)) {
19349
19726
  fail("formal execution evidence must stay inside the current report run directory", {
19350
19727
  rule_id: "test_suite.run.evidence_scope",
@@ -19368,10 +19745,10 @@ async function preflightExecutionEvidenceDirectory(options) {
19368
19745
  suggestion: `Remove the symlink and use a real directory under ${runDir}.`
19369
19746
  });
19370
19747
  }
19371
- const probe = path11.join(evidenceDir, `.bpmax-write-probe-${process.pid}-${Date.now()}`);
19748
+ const probe = path12.join(evidenceDir, `.bpmax-write-probe-${process.pid}-${Date.now()}`);
19372
19749
  try {
19373
19750
  await writeFile9(probe, "ok", "utf8");
19374
- await readFile12(probe, "utf8");
19751
+ await readFile13(probe, "utf8");
19375
19752
  } catch (error) {
19376
19753
  fail(`formal execution evidence directory is not writable: ${error instanceof Error ? error.message : String(error)}`, {
19377
19754
  rule_id: "test_suite.run.evidence_unwritable",
@@ -19385,7 +19762,7 @@ async function preflightExecutionEvidenceDirectory(options) {
19385
19762
  async function appendExecutionManifestEvidence(options) {
19386
19763
  await withExecutionManifestLock(options.manifest, async () => {
19387
19764
  const validated = await validateExecutionManifestStep(options);
19388
- const evidencePath = path11.resolve(options.evidence);
19765
+ const evidencePath = path12.resolve(options.evidence);
19389
19766
  await assertCurrentRunEvidence(validated.manifest, validated.manifestPath, evidencePath);
19390
19767
  validated.step.evidence = [.../* @__PURE__ */ new Set([...validated.step.evidence, evidencePath])];
19391
19768
  await writeExecutionManifest(validated.manifestPath, validated.manifest, true);
@@ -19393,10 +19770,17 @@ async function appendExecutionManifestEvidence(options) {
19393
19770
  }
19394
19771
  async function nextTestSuiteRunStep(manifestPath, profile) {
19395
19772
  const manifest = await readExecutionManifest(manifestPath);
19396
- await assertExecutionManifestFresh(manifest, path11.resolve(manifestPath));
19773
+ await assertExecutionManifestFresh(manifest, path12.resolve(manifestPath));
19397
19774
  if (profile && manifest.profile !== profile) fail(`execution manifest profile is ${manifest.profile}, not ${profile}`, { rule_id: "test_suite.run.profile_mismatch", path: manifestPath });
19398
19775
  const step = currentManifestStep(manifest);
19399
- if (!step) return { ok: true, complete: true, result: manifest.result, execution: manifest };
19776
+ if (!step) return {
19777
+ ok: true,
19778
+ complete: true,
19779
+ result: manifest.result,
19780
+ rerun_required: manifest.rerun_policy === "full_rerun",
19781
+ next_action: manifest.rerun_policy === "full_rerun" ? "Start a new test-suite run. Completed case results and evidence are never reused for a rerun." : void 0,
19782
+ execution: manifest
19783
+ };
19400
19784
  if (step.status !== "planned") fail("current execution step is not planned", { rule_id: "test_suite.run.no_current_step", path: manifestPath });
19401
19785
  return { ok: true, complete: false, current_step: step, execution: manifest };
19402
19786
  }
@@ -19404,10 +19788,10 @@ async function recordTestSuiteRunStep(options) {
19404
19788
  if (!["pass", "fail", "blocked"].includes(options.result)) fail("run record result must be pass, fail, or blocked", { rule_id: "test_suite.run.result" });
19405
19789
  return withExecutionManifestLock(options.manifest, async () => {
19406
19790
  const validated = await validateExecutionManifestStep(options);
19407
- const evidencePath = path11.resolve(options.evidence);
19791
+ const evidencePath = path12.resolve(options.evidence);
19408
19792
  await assertCurrentRunEvidence(validated.manifest, validated.manifestPath, evidencePath);
19409
19793
  if (options.result === "pass") await assertFormalExecutionEvidence(validated.manifest, validated.manifestPath, validated.step, evidencePath);
19410
- if (options.result !== "pass" && !["browser", "e2e_create_page"].includes(validated.step.runner)) {
19794
+ if (options.result !== "pass" && !["browser", "browser_action", "e2e_create_page"].includes(validated.step.runner)) {
19411
19795
  if (!await hasStructuredTerminalEvidence(validated.manifest, validated.step, evidencePath, options.result)) {
19412
19796
  fail("non-browser fail/blocked evidence must identify the current case/step and include structured failure.kind/message or blocker.kind/message", {
19413
19797
  rule_id: "test_suite.run.terminal_evidence",
@@ -19415,7 +19799,7 @@ async function recordTestSuiteRunStep(options) {
19415
19799
  });
19416
19800
  }
19417
19801
  }
19418
- if (options.result !== "pass" && ["browser", "e2e_create_page"].includes(validated.step.runner)) {
19802
+ if (options.result !== "pass" && ["browser", "browser_action", "e2e_create_page"].includes(validated.step.runner)) {
19419
19803
  const structuredBlocker = options.result === "blocked" && await hasStructuredBlockedEvidence(validated.manifest, validated.step, evidencePath);
19420
19804
  if (!structuredBlocker) {
19421
19805
  await browserEvidenceScreenshots(validated.manifest, validated.manifestPath, validated.step, evidencePath, options.result);
@@ -19457,7 +19841,7 @@ async function recordTestSuiteRunStep(options) {
19457
19841
  }
19458
19842
  async function testSuiteRunStatus(manifestPath, profile) {
19459
19843
  const manifest = await readExecutionManifest(manifestPath);
19460
- await assertExecutionManifestFresh(manifest, path11.resolve(manifestPath));
19844
+ await assertExecutionManifestFresh(manifest, path12.resolve(manifestPath));
19461
19845
  if (profile && manifest.profile !== profile) fail(`execution manifest profile is ${manifest.profile}, not ${profile}`, { rule_id: "test_suite.run.profile_mismatch", path: manifestPath });
19462
19846
  return { ok: true, execution: manifest };
19463
19847
  }
@@ -19490,9 +19874,9 @@ function validateLatestProofObject(proofPath, proof) {
19490
19874
  }
19491
19875
  function scenarioPath(root, scenario) {
19492
19876
  if (!SCENARIO_ID_RE.test(scenario)) fail(`invalid scenario id: ${scenario}`);
19493
- const rootResolved = path11.resolve(root);
19494
- const candidate = path11.resolve(root, scenario);
19495
- if (!candidate.startsWith(`${rootResolved}${path11.sep}`) && candidate !== rootResolved) {
19877
+ const rootResolved = path12.resolve(root);
19878
+ const candidate = path12.resolve(root, scenario);
19879
+ if (!candidate.startsWith(`${rootResolved}${path12.sep}`) && candidate !== rootResolved) {
19496
19880
  fail(`scenario path escapes root: ${candidate}`);
19497
19881
  }
19498
19882
  return candidate;
@@ -19501,13 +19885,13 @@ async function fileMap(root) {
19501
19885
  const result = /* @__PURE__ */ new Map();
19502
19886
  async function walk(dir) {
19503
19887
  for (const item of await readdir4(dir, { withFileTypes: true })) {
19504
- const itemPath = path11.join(dir, item.name);
19505
- const rel = path11.relative(root, itemPath);
19506
- if (rel.split(path11.sep)[0] === COPY_DIFF_DIR) continue;
19888
+ const itemPath = path12.join(dir, item.name);
19889
+ const rel = path12.relative(root, itemPath);
19890
+ if (rel.split(path12.sep)[0] === COPY_DIFF_DIR) continue;
19507
19891
  if (item.isDirectory()) {
19508
19892
  await walk(itemPath);
19509
19893
  } else if (item.isFile()) {
19510
- result.set(rel.split(path11.sep).join("/"), itemPath);
19894
+ result.set(rel.split(path12.sep).join("/"), itemPath);
19511
19895
  }
19512
19896
  }
19513
19897
  }
@@ -19515,10 +19899,10 @@ async function fileMap(root) {
19515
19899
  return result;
19516
19900
  }
19517
19901
  async function sha256(filePath) {
19518
- return createHash5("sha256").update(await readFile12(filePath)).digest("hex");
19902
+ return createHash5("sha256").update(await readFile13(filePath)).digest("hex");
19519
19903
  }
19520
19904
  async function readForDiff(filePath) {
19521
- const buffer = await readFile12(filePath);
19905
+ const buffer = await readFile13(filePath);
19522
19906
  if (buffer.includes(0)) return [`<binary sha256=${createHash5("sha256").update(buffer).digest("hex")}>
19523
19907
  `];
19524
19908
  return buffer.toString("utf8").split(/(?<=\n)/);
@@ -19578,7 +19962,7 @@ async function buildCopyDiff(src, dst, operation) {
19578
19962
  return {
19579
19963
  manifest: {
19580
19964
  operation,
19581
- scenario_id: path11.basename(src),
19965
+ scenario_id: path12.basename(src),
19582
19966
  source: src,
19583
19967
  destination: dst,
19584
19968
  generated_at: (/* @__PURE__ */ new Date()).toISOString().replace(/\.\d{3}Z$/, "+00:00"),
@@ -19591,12 +19975,12 @@ async function buildCopyDiff(src, dst, operation) {
19591
19975
  };
19592
19976
  }
19593
19977
  async function writeCopyDiffArtifacts(dst, artifacts) {
19594
- const diffDir = path11.join(dst, COPY_DIFF_DIR);
19978
+ const diffDir = path12.join(dst, COPY_DIFF_DIR);
19595
19979
  await mkdir9(diffDir, { recursive: true });
19596
- await writeFile9(path11.join(diffDir, "last.diff"), artifacts.diff, "utf8");
19597
- await writeFile9(path11.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
19980
+ await writeFile9(path12.join(diffDir, "last.diff"), artifacts.diff, "utf8");
19981
+ await writeFile9(path12.join(diffDir, "last.json"), `${JSON.stringify(artifacts.manifest, null, 2)}
19598
19982
  `, "utf8");
19599
- return path11.join(diffDir, "last.diff");
19983
+ return path12.join(diffDir, "last.diff");
19600
19984
  }
19601
19985
  function summarizeCopyDiff(artifacts) {
19602
19986
  const files = Array.isArray(artifacts.manifest.files) ? artifacts.manifest.files : [];
@@ -19622,18 +20006,18 @@ async function copyScenarioTree(src, dst, replace, operation) {
19622
20006
  artifacts = await buildCopyDiff(src, dst, operation);
19623
20007
  await rm4(dst, { recursive: true, force: true });
19624
20008
  }
19625
- await mkdir9(path11.dirname(dst), { recursive: true });
20009
+ await mkdir9(path12.dirname(dst), { recursive: true });
19626
20010
  await cp3(src, dst, { recursive: true });
19627
20011
  return artifacts ? { path: await writeCopyDiffArtifacts(dst, artifacts), summary: summarizeCopyDiff(artifacts) } : {};
19628
20012
  }
19629
20013
  async function copyScenarioBatch(candidates, replace) {
19630
- const suiteRoot = path11.dirname(candidates[0].dst);
19631
- const transactionRoot = path11.join(
19632
- path11.dirname(suiteRoot),
19633
- `.${path11.basename(suiteRoot)}-promote-transaction-${process.pid}-${Date.now()}`
20014
+ const suiteRoot = path12.dirname(candidates[0].dst);
20015
+ const transactionRoot = path12.join(
20016
+ path12.dirname(suiteRoot),
20017
+ `.${path12.basename(suiteRoot)}-promote-transaction-${process.pid}-${Date.now()}`
19634
20018
  );
19635
- const stagedRoot = path11.join(transactionRoot, "staged");
19636
- const backupRoot = path11.join(transactionRoot, "backup");
20019
+ const stagedRoot = path12.join(transactionRoot, "staged");
20020
+ const backupRoot = path12.join(transactionRoot, "backup");
19637
20021
  const prepared = [];
19638
20022
  const committed = /* @__PURE__ */ new Set();
19639
20023
  try {
@@ -19643,14 +20027,14 @@ async function copyScenarioBatch(candidates, replace) {
19643
20027
  const destinationExists = await exists3(candidate.dst);
19644
20028
  if (destinationExists && !replace) fail(`destination already exists, pass --replace: ${candidate.dst}`);
19645
20029
  const copyDiff = destinationExists ? await buildCopyDiff(candidate.src, candidate.dst, "promote") : void 0;
19646
- const staged = path11.join(stagedRoot, candidate.scenarioId);
20030
+ const staged = path12.join(stagedRoot, candidate.scenarioId);
19647
20031
  await cp3(candidate.src, staged, { recursive: true });
19648
20032
  if (copyDiff) await writeCopyDiffArtifacts(staged, copyDiff);
19649
20033
  prepared.push({
19650
20034
  scenarioId: candidate.scenarioId,
19651
20035
  dst: candidate.dst,
19652
20036
  staged,
19653
- backup: path11.join(backupRoot, candidate.scenarioId),
20037
+ backup: path12.join(backupRoot, candidate.scenarioId),
19654
20038
  copyDiff
19655
20039
  });
19656
20040
  }
@@ -19663,7 +20047,7 @@ async function copyScenarioBatch(candidates, replace) {
19663
20047
  return prepared.map((item) => ({
19664
20048
  scenario_id: item.scenarioId,
19665
20049
  destination: item.dst,
19666
- copy_diff: item.copyDiff ? path11.join(item.dst, COPY_DIFF_DIR, "last.diff") : void 0,
20050
+ copy_diff: item.copyDiff ? path12.join(item.dst, COPY_DIFF_DIR, "last.diff") : void 0,
19667
20051
  copy_diff_summary: item.copyDiff ? summarizeCopyDiff(item.copyDiff) : void 0
19668
20052
  }));
19669
20053
  } catch (error) {
@@ -19672,7 +20056,7 @@ async function copyScenarioBatch(candidates, replace) {
19672
20056
  await rm4(item.dst, { recursive: true, force: true }).catch(() => void 0);
19673
20057
  }
19674
20058
  if (await exists3(item.backup)) {
19675
- await mkdir9(path11.dirname(item.dst), { recursive: true }).catch(() => void 0);
20059
+ await mkdir9(path12.dirname(item.dst), { recursive: true }).catch(() => void 0);
19676
20060
  await rename(item.backup, item.dst).catch(() => void 0);
19677
20061
  }
19678
20062
  }
@@ -19682,7 +20066,7 @@ async function copyScenarioBatch(candidates, replace) {
19682
20066
  }
19683
20067
  }
19684
20068
  async function copyDiffPreview(src, dst, operation) {
19685
- const previewDir = path11.join(DEFAULT_TMP_ROOT, `${operation}-${path11.basename(src)}-copy-diff`);
20069
+ const previewDir = path12.join(DEFAULT_TMP_ROOT, `${operation}-${path12.basename(src)}-copy-diff`);
19686
20070
  await rm4(previewDir, { recursive: true, force: true });
19687
20071
  await mkdir9(previewDir, { recursive: true });
19688
20072
  const artifacts = await buildCopyDiff(src, dst, operation);
@@ -19704,7 +20088,7 @@ async function draftUpdate(options) {
19704
20088
  return { destination: dst, copy_diff: copyDiff.path, copy_diff_summary: copyDiff.summary };
19705
20089
  }
19706
20090
  async function validateReviewGate(scenarioDir) {
19707
- const reviewPath = path11.join(scenarioDir, "review.json");
20091
+ const reviewPath = path12.join(scenarioDir, "review.json");
19708
20092
  if (!await exists3(reviewPath)) reviewFail(reviewPath, `${scenarioDir}: missing review.json; run multi-subagent SKILL review before promote`);
19709
20093
  let review;
19710
20094
  try {
@@ -19712,7 +20096,7 @@ async function validateReviewGate(scenarioDir) {
19712
20096
  } catch (error) {
19713
20097
  reviewFail(reviewPath, `${reviewPath}: invalid JSON: ${error instanceof Error ? error.message : String(error)}`);
19714
20098
  }
19715
- if (review.scenario_id !== path11.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
20099
+ if (review.scenario_id !== path12.basename(scenarioDir)) reviewFail(reviewPath, `${reviewPath}: scenario_id must match directory name`);
19716
20100
  if (!review.latest_proof || typeof review.latest_proof !== "object" || Array.isArray(review.latest_proof)) reviewFail(reviewPath, `${reviewPath}: latest_proof is required`);
19717
20101
  validateLatestProofObject(reviewPath, review.latest_proof);
19718
20102
  if (!REVIEW_STATUSES.has(String(review.status))) reviewFail(reviewPath, `${reviewPath}: status must be one of ${JSON.stringify([...REVIEW_STATUSES].sort())}`);
@@ -19737,8 +20121,8 @@ async function validateReviewGate(scenarioDir) {
19737
20121
  if (!Array.isArray(review.fixes) || review.fixes.length === 0) reviewFail(reviewPath, `${reviewPath}: fixes must be a non-empty list`);
19738
20122
  }
19739
20123
  async function validateExecutionOperabilityReview(reviewPath, scenarioDir, item) {
19740
- const rows2 = await readCases(path11.join(scenarioDir, "cases.csv"));
19741
- const steps = await readCaseSteps(path11.join(scenarioDir, "case_steps.csv"));
20124
+ const rows2 = await readCases(path12.join(scenarioDir, "cases.csv"));
20125
+ const steps = await readCaseSteps(path12.join(scenarioDir, "case_steps.csv"));
19742
20126
  const activeCases = new Set(rows2.filter((row) => row.status !== "deprecated").map((row) => row.case_id));
19743
20127
  const required = steps.filter((step) => activeCases.has(step.case_id)).map((step) => `${step.case_id}/${step.step_id}`);
19744
20128
  const judgments = item.step_judgments;
@@ -19862,10 +20246,10 @@ async function initOrRepairReview(options) {
19862
20246
  const scenarioDir = scenarioPath(options.draftRoot ?? DEFAULT_DRAFT_ROOT, options.scenario);
19863
20247
  if (!await exists3(scenarioDir)) fail(`draft scenario not found: ${scenarioDir}`);
19864
20248
  await validateReadme(scenarioDir);
19865
- const rows2 = await readCases(path11.join(scenarioDir, "cases.csv"));
19866
- const steps = await readCaseSteps(path11.join(scenarioDir, "case_steps.csv"));
20249
+ const rows2 = await readCases(path12.join(scenarioDir, "cases.csv"));
20250
+ const steps = await readCaseSteps(path12.join(scenarioDir, "case_steps.csv"));
19867
20251
  const proof = await readLatestProof(options.latestProof);
19868
- const reviewPath = path11.join(scenarioDir, "review.json");
20252
+ const reviewPath = path12.join(scenarioDir, "review.json");
19869
20253
  let existing;
19870
20254
  const existed = await exists3(reviewPath);
19871
20255
  if (existed) {
@@ -19876,7 +20260,7 @@ async function initOrRepairReview(options) {
19876
20260
  existing = {};
19877
20261
  }
19878
20262
  }
19879
- const review = mergeReviewDraft(path11.basename(scenarioDir), proof, rows2, steps, existing);
20263
+ const review = mergeReviewDraft(path12.basename(scenarioDir), proof, rows2, steps, existing);
19880
20264
  await writeFile9(reviewPath, `${JSON.stringify(review, null, 2)}
19881
20265
  `, "utf8");
19882
20266
  return {
@@ -19957,16 +20341,16 @@ async function nextReportDir(root = DEFAULT_REPORT_ROOT, create = false, today =
19957
20341
  String(today.getDate()).padStart(2, "0")
19958
20342
  ].join("");
19959
20343
  const dirs = await scenarioDirs(root);
19960
- const nums = dirs.map((dir) => path11.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
19961
- const reportDir = path11.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
20344
+ const nums = dirs.map((dir) => path12.basename(dir)).filter((name) => name.startsWith(prefix)).map((name) => RUN_RE.exec(name)?.[1]).filter((value) => Boolean(value)).map((value) => Number(value));
20345
+ const reportDir = path12.join(root, `${prefix}-${String(Math.max(0, ...nums) + 1).padStart(3, "0")}`);
19962
20346
  if (create) {
19963
- await mkdir9(path11.join(reportDir, "screenshots"), { recursive: true });
20347
+ await mkdir9(path12.join(reportDir, "screenshots"), { recursive: true });
19964
20348
  await writeFile9(
19965
- path11.join(reportDir, "summary.md"),
20349
+ path12.join(reportDir, "summary.md"),
19966
20350
  [
19967
20351
  "# BPMAX E2E \u6D4B\u8BD5\u62A5\u544A\u6C47\u603B",
19968
20352
  "",
19969
- `run_id: ${path11.basename(reportDir)}`,
20353
+ `run_id: ${path12.basename(reportDir)}`,
19970
20354
  "rerun_policy: full_rerun",
19971
20355
  "status: draft",
19972
20356
  "",
@@ -19974,7 +20358,7 @@ async function nextReportDir(root = DEFAULT_REPORT_ROOT, create = false, today =
19974
20358
  "",
19975
20359
  "## \u622A\u56FE\u76EE\u5F55",
19976
20360
  "",
19977
- `screenshots: ${path11.join(path11.basename(reportDir), "screenshots")}`,
20361
+ `screenshots: ${path12.join(path12.basename(reportDir), "screenshots")}`,
19978
20362
  "",
19979
20363
  "## \u603B\u7ED3",
19980
20364
  ""
@@ -20009,7 +20393,7 @@ function crc32(value) {
20009
20393
  return (crc ^ 4294967295) >>> 0;
20010
20394
  }
20011
20395
  async function isValidCurrentRunScreenshot(filePath) {
20012
- const buffer = await readFile12(filePath);
20396
+ const buffer = await readFile13(filePath);
20013
20397
  const signature = Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]);
20014
20398
  if (buffer.length < 33 || !buffer.subarray(0, 8).equals(signature)) return false;
20015
20399
  let offset = 8;
@@ -20237,8 +20621,8 @@ function reportExecutionWindow(runName, text5) {
20237
20621
  if (!startedAt || !finishedAt || finishedAt < startedAt) return fallback;
20238
20622
  return { start: startedAt, end: finishedAt };
20239
20623
  }
20240
- function isWithinWindow(date, window) {
20241
- return date >= window.start && date <= window.end;
20624
+ function isWithinWindow(date, window2) {
20625
+ return date >= window2.start && date <= window2.end;
20242
20626
  }
20243
20627
  function caseEvidencePattern(caseId) {
20244
20628
  const escaped = caseId.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
@@ -20267,12 +20651,12 @@ async function reportHasValidBlockedEvidence(text5, reportPath, runDir, manifest
20267
20651
  if (reportKeyValue(text5, "browser_status:").toLowerCase() !== "blocked") return false;
20268
20652
  const evidenceValue = reportKeyValue(text5, "blocker_evidence:");
20269
20653
  if (!evidenceValue) return false;
20270
- const evidencePath = path11.resolve(path11.dirname(reportPath), evidenceValue);
20654
+ const evidencePath = path12.resolve(path12.dirname(reportPath), evidenceValue);
20271
20655
  if (!await exists3(evidencePath) || !(await stat7(evidencePath)).isFile() || !await pathInsideReal(runDir, evidencePath)) return false;
20272
20656
  await assertCurrentRunArtifact(manifest, evidencePath);
20273
20657
  const blockedStep = manifest.steps.find((step) => step.status === "blocked");
20274
20658
  return Boolean(
20275
- blockedStep && ["browser", "e2e_create_page"].includes(blockedStep.runner) && await hasStructuredBlockedEvidence(manifest, blockedStep, evidencePath)
20659
+ blockedStep && ["browser", "browser_action", "e2e_create_page"].includes(blockedStep.runner) && await hasStructuredBlockedEvidence(manifest, blockedStep, evidencePath)
20276
20660
  );
20277
20661
  }
20278
20662
  function emptyUxBugCounts() {
@@ -20295,7 +20679,7 @@ async function uxManifestArtifacts(text5, reportPath, runDir) {
20295
20679
  const artifacts = /* @__PURE__ */ new Set();
20296
20680
  const manifestValue = reportKeyValue(text5, "execution_manifest:");
20297
20681
  if (!manifestValue) return { artifacts, result: "" };
20298
- const manifestPath = path11.resolve(path11.dirname(reportPath), manifestValue);
20682
+ const manifestPath = path12.resolve(path12.dirname(reportPath), manifestValue);
20299
20683
  if (!pathInside(runDir, manifestPath) || !await exists3(manifestPath) || !await pathInsideReal(runDir, manifestPath)) {
20300
20684
  return { artifacts, result: "" };
20301
20685
  }
@@ -20305,15 +20689,15 @@ async function uxManifestArtifacts(text5, reportPath, runDir) {
20305
20689
  result = typeof manifest.result === "string" ? manifest.result.toLowerCase() : "";
20306
20690
  for (const step of manifest.steps ?? []) {
20307
20691
  for (const item of step.evidence ?? []) {
20308
- const evidencePath = path11.isAbsolute(item) ? path11.resolve(item) : path11.resolve(path11.dirname(manifestPath), item);
20692
+ const evidencePath = path12.isAbsolute(item) ? path12.resolve(item) : path12.resolve(path12.dirname(manifestPath), item);
20309
20693
  if (!pathInside(runDir, evidencePath) || !await exists3(evidencePath) || !await pathInsideReal(runDir, evidencePath)) continue;
20310
20694
  artifacts.add(evidencePath);
20311
20695
  for (const { value, source } of await evidenceJsonRecords(evidencePath)) {
20312
- artifacts.add(path11.resolve(source));
20696
+ artifacts.add(path12.resolve(source));
20313
20697
  for (const key of ["screenshot", "dom_snapshot", "source_evidence"]) {
20314
20698
  const referenced = typeof value[key] === "string" ? value[key].trim() : "";
20315
20699
  if (!referenced) continue;
20316
- const referencedPath = path11.resolve(path11.dirname(source), referenced);
20700
+ const referencedPath = path12.resolve(path12.dirname(source), referenced);
20317
20701
  if (pathInside(runDir, referencedPath) && await exists3(referencedPath) && await pathInsideReal(runDir, referencedPath)) {
20318
20702
  artifacts.add(referencedPath);
20319
20703
  }
@@ -20329,7 +20713,7 @@ async function validateUxEvidence(values, options) {
20329
20713
  const errors = [];
20330
20714
  const mtimes = [];
20331
20715
  for (const evidenceValue of values) {
20332
- const evidencePath = path11.resolve(options.runDir, evidenceValue);
20716
+ const evidencePath = path12.resolve(options.runDir, evidenceValue);
20333
20717
  if (!pathInside(options.runDir, evidencePath) || !await exists3(evidencePath) || !await pathInsideReal(options.runDir, evidencePath) || evidencePath === options.findingsPath) {
20334
20718
  errors.push(`[test_suite.report.ux_evidence] ${options.prefix}: UX BUG \u8BC1\u636E\u5FC5\u987B\u662F\u672C\u8F6E\u76EE\u5F55\u5185\u5B58\u5728\u7684\u72EC\u7ACB\u6587\u4EF6: ${evidenceValue}`);
20335
20719
  continue;
@@ -20345,7 +20729,7 @@ async function validateUxEvidence(values, options) {
20345
20729
  if (!isWithinWindow(info.mtime, options.window)) {
20346
20730
  errors.push(`[test_suite.report.ux_evidence_current_run] ${options.prefix}: UX BUG \u8BC1\u636E\u5FC5\u987B\u5728\u672C\u8F6E\u6267\u884C\u7A97\u53E3\u5185\u751F\u6210: ${evidenceValue}`);
20347
20731
  }
20348
- const extension = path11.extname(evidencePath).toLowerCase();
20732
+ const extension = path12.extname(evidencePath).toLowerCase();
20349
20733
  if (extension === ".png") {
20350
20734
  if (!await isValidCurrentRunScreenshot(evidencePath)) {
20351
20735
  errors.push(`[test_suite.report.ux_evidence_invalid] ${options.prefix}: UX \u622A\u56FE\u8BC1\u636E\u5FC5\u987B\u662F\u53EF\u89E3\u6790\u3001\u5C3A\u5BF8\u81F3\u5C11 100x80 \u7684\u771F\u5B9E PNG: ${evidenceValue}`);
@@ -20389,12 +20773,12 @@ async function lintUxAudit(text5, reportPath, runDir, runName) {
20389
20773
  const resultValue = reportKeyValue(text5, "result:").toLowerCase();
20390
20774
  const manifestContext = await uxManifestArtifacts(text5, reportPath, runDir);
20391
20775
  const manifestArtifacts = manifestContext.artifacts;
20392
- const window = reportExecutionWindow(runName, text5);
20776
+ const window2 = reportExecutionWindow(runName, text5);
20393
20777
  let actualCounts = emptyUxBugCounts();
20394
20778
  if (!findingsValue) {
20395
20779
  errors.push(`[test_suite.report.ux_findings_missing] ${reportPath}: missing \`ux_findings:\``);
20396
20780
  } else {
20397
- const findingsPath = path11.resolve(path11.dirname(reportPath), findingsValue);
20781
+ const findingsPath = path12.resolve(path12.dirname(reportPath), findingsValue);
20398
20782
  if (!pathInside(runDir, findingsPath)) {
20399
20783
  errors.push(`[test_suite.report.ux_findings_scope] ${reportPath}: ux_findings \u5FC5\u987B\u4F4D\u4E8E\u672C\u8F6E\u62A5\u544A\u76EE\u5F55\u5185`);
20400
20784
  } else if (!await exists3(findingsPath)) {
@@ -20432,7 +20816,7 @@ async function lintUxAudit(text5, reportPath, runDir, runName) {
20432
20816
  prefix,
20433
20817
  reportPath,
20434
20818
  runDir,
20435
- window
20819
+ window: window2
20436
20820
  });
20437
20821
  errors.push(...evidenceCheck.errors);
20438
20822
  if (finding.status === "verified") {
@@ -20445,11 +20829,11 @@ async function lintUxAudit(text5, reportPath, runDir, runName) {
20445
20829
  prefix,
20446
20830
  reportPath,
20447
20831
  runDir,
20448
- window
20832
+ window: window2
20449
20833
  });
20450
20834
  errors.push(...retestCheck.errors);
20451
- const initialPaths = new Set(finding.evidence.map((item) => path11.resolve(runDir, item)));
20452
- if (finding.retest_evidence.some((item) => initialPaths.has(path11.resolve(runDir, item)))) {
20835
+ const initialPaths = new Set(finding.evidence.map((item) => path12.resolve(runDir, item)));
20836
+ if (finding.retest_evidence.some((item) => initialPaths.has(path12.resolve(runDir, item)))) {
20453
20837
  errors.push(`[test_suite.report.ux_verified_evidence] ${prefix}: retest_evidence \u5FC5\u987B\u4F7F\u7528\u4FEE\u590D\u540E\u7684\u65B0\u8BC1\u636E\uFF0C\u4E0D\u80FD\u590D\u7528\u539F\u59CB evidence`);
20454
20838
  }
20455
20839
  const latestInitial = Math.max(...evidenceCheck.mtimes.map((item) => item.getTime()));
@@ -20502,22 +20886,22 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20502
20886
  if (!await exists3(root)) return { errors: [`report root not found: ${root}`], reports: [] };
20503
20887
  const errors = [];
20504
20888
  const reports = [];
20505
- const resolvedRoot = path11.resolve(root);
20506
- const candidateDirs = RUN_RE.test(path11.basename(resolvedRoot)) ? [resolvedRoot] : (await scenarioDirs(resolvedRoot)).filter((dir) => RUN_RE.test(path11.basename(dir)));
20889
+ const resolvedRoot = path12.resolve(root);
20890
+ const candidateDirs = RUN_RE.test(path12.basename(resolvedRoot)) ? [resolvedRoot] : (await scenarioDirs(resolvedRoot)).filter((dir) => RUN_RE.test(path12.basename(dir)));
20507
20891
  if (candidateDirs.length === 0) return { errors: [`report run not found under: ${resolvedRoot}`], reports };
20508
20892
  const runDirs = options.allRuns ? candidateDirs : candidateDirs.slice(-1);
20509
20893
  for (const runDir of runDirs) {
20510
- const runName = path11.basename(runDir);
20894
+ const runName = path12.basename(runDir);
20511
20895
  if (!RUN_RE.test(runName)) {
20512
20896
  errors.push(`${runDir}: run directory name must be YYYYMMDD-NNN`);
20513
20897
  continue;
20514
20898
  }
20515
- if (!await exists3(path11.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
20899
+ if (!await exists3(path12.join(runDir, "summary.md"))) errors.push(`${runDir}: missing summary.md`);
20516
20900
  const files = await readdir4(runDir);
20517
20901
  const scenarioReports = files.filter((file) => file.endsWith(".md") && file !== "summary.md");
20518
20902
  if (scenarioReports.length === 0) errors.push(`${runDir}: missing scenario report markdown`);
20519
20903
  for (const reportName of scenarioReports) {
20520
- const reportPath = path11.join(runDir, reportName);
20904
+ const reportPath = path12.join(runDir, reportName);
20521
20905
  const text5 = await readText(reportPath);
20522
20906
  const uxAudit = await lintUxAudit(text5, reportPath, runDir, runName);
20523
20907
  errors.push(...uxAudit.errors);
@@ -20562,8 +20946,8 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20562
20946
  }
20563
20947
  const manifestValue = reportKeyValue(text5, "execution_manifest:");
20564
20948
  if (manifestValue) {
20565
- const manifestPath = path11.resolve(path11.dirname(reportPath), manifestValue);
20566
- const runRoot = path11.resolve(runDir);
20949
+ const manifestPath = path12.resolve(path12.dirname(reportPath), manifestValue);
20950
+ const runRoot = path12.resolve(runDir);
20567
20951
  if (!pathInside(runRoot, manifestPath)) {
20568
20952
  errors.push(`[test_suite.report.execution_manifest_scope] ${reportPath}: execution_manifest \u5FC5\u987B\u4F4D\u4E8E\u672C\u8F6E\u62A5\u544A\u76EE\u5F55\u5185`);
20569
20953
  } else if (!await exists3(manifestPath)) {
@@ -20592,10 +20976,10 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20592
20976
  const resultMatchesManifest = manifest.result === "fail" ? /^(?:fail|failed|error|失败)$/.test(resultValue) : /^(?:blocked|阻塞)$/.test(resultValue);
20593
20977
  validTerminalStop = stoppedAfterFail === expectedStop && resultMatchesManifest && manifest.steps.slice(0, terminalIndex).every((step) => step.status === "pass") && manifest.steps.slice(terminalIndex + 1).every((step) => step.status === "planned") && JSON.stringify(executedSteps) === JSON.stringify(expectedExecuted) && JSON.stringify(missingExecutedSteps) === JSON.stringify(expectedUnexecuted);
20594
20978
  validNonBrowserTerminalStop = false;
20595
- if (validTerminalStop && !["browser", "e2e_create_page"].includes(manifest.steps[terminalIndex].runner)) {
20979
+ if (validTerminalStop && !["browser", "browser_action", "e2e_create_page"].includes(manifest.steps[terminalIndex].runner)) {
20596
20980
  const terminalStep = manifest.steps[terminalIndex];
20597
20981
  for (const evidencePath of terminalStep.evidence) {
20598
- const resolvedEvidencePath = path11.isAbsolute(evidencePath) ? path11.resolve(evidencePath) : path11.resolve(path11.dirname(manifestPath), evidencePath);
20982
+ const resolvedEvidencePath = path12.isAbsolute(evidencePath) ? path12.resolve(evidencePath) : path12.resolve(path12.dirname(manifestPath), evidencePath);
20599
20983
  if (!pathInside(runRoot, resolvedEvidencePath) || !await pathInsideReal(runRoot, resolvedEvidencePath)) {
20600
20984
  errors.push(`[test_suite.report.terminal_evidence_scope] ${reportPath}: \u975E\u6D4F\u89C8\u5668 terminal evidence \u5FC5\u987B\u4F4D\u4E8E\u672C\u8F6E\u62A5\u544A\u76EE\u5F55\u5185: ${evidencePath}`);
20601
20985
  continue;
@@ -20672,7 +21056,7 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20672
21056
  if (/browser_status:\s*blocked|页面结论停止|停止页面结论/i.test(text5) && /pass|passed|complete|success|通过|完整/.test(resultValue) && !/partial|stage|blocked|阶段|局部|不完整|诊断/.test(resultValue)) {
20673
21057
  errors.push(`[test_suite.report.page_conclusion_browser] ${reportPath}: browser_status: blocked \u65F6\u4E0D\u80FD\u58F0\u660E\u5B8C\u6574\u9875\u9762\u901A\u8FC7\uFF1B\u5FC5\u987B\u964D\u7EA7\u4E3A partial/stage/blocked/diagnostic`);
20674
21058
  }
20675
- const screenshotsDir = path11.join(runDir, "screenshots");
21059
+ const screenshotsDir = path12.join(runDir, "screenshots");
20676
21060
  if (!await exists3(screenshotsDir)) errors.push(`${runDir}: missing screenshots directory`);
20677
21061
  if (isFullRerun) {
20678
21062
  for (const key of ["state_file:", "precondition_check:", "report_run:"]) {
@@ -20691,15 +21075,15 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20691
21075
  errors.push(`${reportPath}: missing embedded screenshot image`);
20692
21076
  }
20693
21077
  const validCurrentRunImages = [];
20694
- const window = reportExecutionWindow(runName, text5);
21078
+ const window2 = reportExecutionWindow(runName, text5);
20695
21079
  for (const imageRef of imageRefs) {
20696
21080
  if (imageRef.includes("://")) {
20697
21081
  errors.push(`${reportPath}: screenshot must be a local file under this run's screenshots directory`);
20698
21082
  continue;
20699
21083
  }
20700
- const imagePath = path11.resolve(path11.dirname(reportPath), imageRef);
20701
- const screenshotsResolved = path11.resolve(screenshotsDir);
20702
- if (!imagePath.startsWith(`${screenshotsResolved}${path11.sep}`)) {
21084
+ const imagePath = path12.resolve(path12.dirname(reportPath), imageRef);
21085
+ const screenshotsResolved = path12.resolve(screenshotsDir);
21086
+ if (!imagePath.startsWith(`${screenshotsResolved}${path12.sep}`)) {
20703
21087
  errors.push(`${reportPath}: image reference must stay under this run's screenshots directory: ${imageRef}`);
20704
21088
  continue;
20705
21089
  }
@@ -20714,7 +21098,7 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20714
21098
  validCurrentRunImages.push(imageRef);
20715
21099
  if (isFullRerun) {
20716
21100
  const imageStat = await stat7(imagePath);
20717
- if (!isWithinWindow(imageStat.mtime, window)) {
21101
+ if (!isWithinWindow(imageStat.mtime, window2)) {
20718
21102
  errors.push(`[test_suite.report.current_run_screenshot] ${reportPath}: full_rerun \u622A\u56FE\u5FC5\u987B\u5728\u672C\u8F6E\u6267\u884C\u65F6\u95F4\u5185\u751F\u6210\uFF0C\u4E0D\u80FD\u590D\u7528\u5386\u53F2\u622A\u56FE: ${imageRef}`);
20719
21103
  }
20720
21104
  }
@@ -20737,10 +21121,10 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
20737
21121
  return { errors, reports };
20738
21122
  }
20739
21123
  async function validateCopyDiffArtifacts(scenarioDir) {
20740
- const diffDir = path11.join(scenarioDir, COPY_DIFF_DIR);
21124
+ const diffDir = path12.join(scenarioDir, COPY_DIFF_DIR);
20741
21125
  if (!await exists3(diffDir)) return;
20742
- const manifestPath = path11.join(diffDir, "last.json");
20743
- const diffPath = path11.join(diffDir, "last.diff");
21126
+ const manifestPath = path12.join(diffDir, "last.json");
21127
+ const diffPath = path12.join(diffDir, "last.diff");
20744
21128
  if (!await exists3(manifestPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.json is required when copy diff artifacts exist`);
20745
21129
  if (!await exists3(diffPath)) fail(`${scenarioDir}: ${COPY_DIFF_DIR}/last.diff is required when copy diff artifacts exist`);
20746
21130
  let manifest;
@@ -20752,11 +21136,673 @@ async function validateCopyDiffArtifacts(scenarioDir) {
20752
21136
  for (const key of ["operation", "scenario_id", "source", "destination", "generated_at", "summary", "diff_file", "files"]) {
20753
21137
  if (!(key in manifest)) fail(`${manifestPath}: missing \`${key}\``);
20754
21138
  }
20755
- if (manifest.scenario_id !== path11.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
21139
+ if (manifest.scenario_id !== path12.basename(scenarioDir)) fail(`${manifestPath}: scenario_id must match directory name`);
20756
21140
  if (manifest.diff_file !== "last.diff") fail(`${manifestPath}: diff_file must be last.diff`);
20757
21141
  if (!(await readText(diffPath)).trim()) fail(`${diffPath}: copy diff must not be empty`);
20758
21142
  }
20759
21143
 
21144
+ // src/core/e2e-browser-runner.ts
21145
+ function isRecord9(value) {
21146
+ return typeof value === "object" && value !== null && !Array.isArray(value);
21147
+ }
21148
+ function pushBounded(items, value, key, limit = 100) {
21149
+ if (items.length >= limit) return;
21150
+ if (items.some((item) => JSON.stringify(item) === key)) return;
21151
+ items.push(value);
21152
+ }
21153
+ async function readJsonInput(value) {
21154
+ if (!value) return {};
21155
+ const raw = value.startsWith("@") ? await readFile14(path13.resolve(value.slice(1)), "utf8") : value;
21156
+ const parsed = JSON.parse(raw);
21157
+ if (!isRecord9(parsed)) throw new Error("browser-run data profile must be a JSON object");
21158
+ return parsed;
21159
+ }
21160
+ function valueAt(source, dottedPath) {
21161
+ return dottedPath.split(".").reduce((current, segment) => isRecord9(current) ? current[segment] : void 0, source);
21162
+ }
21163
+ function interpolateString(value, variables) {
21164
+ return value.replace(/\{\{\s*(data|context)\.([\w.-]+)\s*}}/g, (_match, root, key) => {
21165
+ const result = valueAt(isRecord9(variables[root]) ? variables[root] : {}, key);
21166
+ if (result === void 0 || result === null) throw new Error(`missing browser automation variable ${root}.${key}`);
21167
+ return String(result);
21168
+ });
21169
+ }
21170
+ function interpolateValue(value, variables) {
21171
+ if (typeof value === "string") return interpolateString(value, variables);
21172
+ if (Array.isArray(value)) return value.map((item) => interpolateValue(item, variables));
21173
+ if (isRecord9(value)) return Object.fromEntries(Object.entries(value).map(([key, item]) => [key, interpolateValue(item, variables)]));
21174
+ return value;
21175
+ }
21176
+ function resolvedAction(action, variables) {
21177
+ return interpolateValue(action, variables);
21178
+ }
21179
+ function routeUrl(route, baseUrl) {
21180
+ if (/^https?:\/\//i.test(route)) return route;
21181
+ if (!baseUrl) throw new Error(`relative route ${route} requires --base-url or a profile origin`);
21182
+ return new URL(route, baseUrl.endsWith("/") ? baseUrl : `${baseUrl}/`).toString();
21183
+ }
21184
+ async function locatorForTarget(page, target) {
21185
+ if (target.test_id) return page.getByTestId(target.test_id);
21186
+ if (target.role) return page.getByRole(target.role, target.name ? { name: target.name } : void 0);
21187
+ if (target.label) {
21188
+ const nativeLabel = page.getByLabel(target.label, { exact: false });
21189
+ if (await nativeLabel.count()) return nativeLabel.first();
21190
+ const formItem = page.locator(".el-form-item, .form-item, [role=group]").filter({ hasText: target.label });
21191
+ const editable = formItem.locator("input:not([type=hidden]), textarea, [contenteditable=true], select");
21192
+ if (await editable.count()) return editable.first();
21193
+ const labelText = page.getByText(target.label, { exact: true }).first();
21194
+ const semanticGroup = labelText.locator('xpath=ancestor::*[.//input[not(@type="hidden")] or .//textarea or .//*[@contenteditable="true"] or .//select][1]');
21195
+ const groupedEditable = semanticGroup.locator("input:not([type=hidden]), textarea, [contenteditable=true], select");
21196
+ if (await groupedEditable.count()) return groupedEditable.first();
21197
+ return page.getByText(target.label, { exact: false });
21198
+ }
21199
+ if (target.text) return page.getByText(target.text, { exact: false });
21200
+ if (target.css) return page.locator(target.css);
21201
+ if (target.field) {
21202
+ const escaped = target.field.replace(/["\\]/g, "\\$&");
21203
+ const direct = page.locator([
21204
+ `[data-field-key="${escaped}"]`,
21205
+ `[field="${escaped}"]`,
21206
+ `[name="${escaped}"]`,
21207
+ `[data-key="${escaped}"]`
21208
+ ].join(","));
21209
+ if (await direct.count()) return direct.first();
21210
+ return page.getByLabel(target.field, { exact: false });
21211
+ }
21212
+ throw new Error("browser action target is empty");
21213
+ }
21214
+ async function editableLocator(locator) {
21215
+ const tagName = await locator.evaluate((element) => element.tagName.toLowerCase()).catch(() => "");
21216
+ if (["input", "textarea", "select"].includes(tagName)) return locator;
21217
+ const nested = locator.locator("input:not([type=hidden]), textarea, [contenteditable=true], select");
21218
+ return await nested.count() ? nested.first() : locator;
21219
+ }
21220
+ async function tableLocator(page, table) {
21221
+ const escaped = table.replace(/["\\]/g, "\\$&");
21222
+ const direct = page.locator(`[data-table-key="${escaped}"], [table-key="${escaped}"], [data-key="${escaped}"]`);
21223
+ if (await direct.count()) return direct.first();
21224
+ const heading = page.getByText(table, { exact: false }).first();
21225
+ return heading.locator('xpath=ancestor::*[contains(@class,"table") or contains(@class,"sub-form")][1]');
21226
+ }
21227
+ async function assertFingerprint(page, fingerprint, variables) {
21228
+ const failures = [];
21229
+ const resolved = interpolateValue(fingerprint, variables);
21230
+ if (resolved.route && !page.url().includes(resolved.route)) failures.push(`route expected ${resolved.route}, got ${page.url()}`);
21231
+ if (resolved.title) {
21232
+ const title = await page.title();
21233
+ if (!title.includes(resolved.title)) failures.push(`title expected ${resolved.title}, got ${title}`);
21234
+ }
21235
+ for (const field of resolved.fields ?? []) {
21236
+ const locator = await locatorForTarget(page, { field });
21237
+ if (!await locator.first().isVisible().catch(() => false)) failures.push(`field not visible: ${field}`);
21238
+ }
21239
+ for (const button of resolved.buttons ?? []) {
21240
+ if (!await page.getByRole("button", { name: button }).first().isVisible().catch(() => false)) failures.push(`button not visible: ${button}`);
21241
+ }
21242
+ for (const text5 of resolved.texts ?? []) {
21243
+ if (!await page.getByText(text5, { exact: false }).first().isVisible().catch(() => false)) failures.push(`text not visible: ${text5}`);
21244
+ }
21245
+ return failures;
21246
+ }
21247
+ async function executeAction(page, action, variables, runtime) {
21248
+ const next = resolvedAction(action, variables);
21249
+ const timeout = next.timeout_ms ?? 15e3;
21250
+ switch (next.type) {
21251
+ case "navigation.open":
21252
+ await page.goto(routeUrl(String(next.route), String(variables.base_url || "")), { waitUntil: "domcontentloaded", timeout });
21253
+ await page.waitForLoadState("networkidle", { timeout: Math.min(timeout, 8e3) }).catch(() => void 0);
21254
+ return {};
21255
+ case "wait.visible": {
21256
+ const locator = await locatorForTarget(page, next.target ?? { field: next.field });
21257
+ await locator.first().waitFor({ state: "visible", timeout });
21258
+ return { assertion: { type: next.type, passed: true, target: next.target ?? { field: next.field } } };
21259
+ }
21260
+ case "form.set_value": {
21261
+ const locator = await editableLocator((await locatorForTarget(page, next.target ?? { field: next.field })).first());
21262
+ await locator.fill(String(next.value ?? ""));
21263
+ return {};
21264
+ }
21265
+ case "form.select_option": {
21266
+ const target = (await locatorForTarget(page, next.target ?? { field: next.field })).first();
21267
+ const editable = await editableLocator(target);
21268
+ if (await editable.evaluate((element) => element.tagName.toLowerCase()).catch(() => "") === "select") {
21269
+ await editable.selectOption({ label: String(next.option ?? next.value ?? "") });
21270
+ } else {
21271
+ await target.click();
21272
+ await page.getByRole("option", { name: String(next.option ?? next.value ?? "") }).or(page.getByText(String(next.option ?? next.value ?? ""), { exact: true })).first().click();
21273
+ }
21274
+ return {};
21275
+ }
21276
+ case "form.assert_value": {
21277
+ const locator = await editableLocator((await locatorForTarget(page, next.target ?? { field: next.field })).first());
21278
+ const actual = await locator.inputValue().catch(() => locator.textContent());
21279
+ const passed = String(actual ?? "") === String(next.value ?? "");
21280
+ if (!passed) throw new Error(`form value mismatch: expected ${String(next.value ?? "")}, got ${String(actual ?? "")}`);
21281
+ return { assertion: { type: next.type, passed, target: next.target ?? { field: next.field }, actual } };
21282
+ }
21283
+ case "detail.add_row": {
21284
+ const table = await tableLocator(page, String(next.table));
21285
+ await table.getByRole("button", { name: /新增|添加/ }).or(table.getByText(/新增|添加/)).first().click();
21286
+ return {};
21287
+ }
21288
+ case "detail.set_value": {
21289
+ const table = await tableLocator(page, String(next.table));
21290
+ const row = table.locator(".el-table__body tr, tbody tr").nth(Number(next.row));
21291
+ const field = String(next.field);
21292
+ const escaped = field.replace(/["\\]/g, "\\$&");
21293
+ const target = row.locator(`[data-field-key="${escaped}"], [field="${escaped}"], [name="${escaped}"]`).first();
21294
+ await (await editableLocator(target)).fill(String(next.value ?? ""));
21295
+ return {};
21296
+ }
21297
+ case "detail.assert_rows": {
21298
+ const table = await tableLocator(page, String(next.table));
21299
+ const count = await table.locator(".el-table__body tr, tbody tr").count();
21300
+ const passed = count === Number(next.count);
21301
+ if (!passed) throw new Error(`detail row count mismatch: expected ${next.count}, got ${count}`);
21302
+ return { assertion: { type: next.type, passed, table: next.table, count } };
21303
+ }
21304
+ case "button.click": {
21305
+ const locator = await locatorForTarget(page, next.target ?? {});
21306
+ if (next.mutation === true) runtime.onMutationAttempt();
21307
+ await locator.first().click({ timeout });
21308
+ return {};
21309
+ }
21310
+ case "dialog.confirm": {
21311
+ const dialog = page.getByRole("dialog").last();
21312
+ const button = dialog.getByRole("button", { name: next.name || /确定|确认|提交|通过/ }).first();
21313
+ runtime.onMutationAttempt();
21314
+ await button.click({ timeout });
21315
+ return {};
21316
+ }
21317
+ case "wait.network":
21318
+ if (!runtime.responseUrls.some((url) => url.includes(String(next.url_pattern ?? next.value ?? "")))) {
21319
+ await page.waitForResponse((response) => response.url().includes(String(next.url_pattern ?? next.value ?? "")), { timeout });
21320
+ }
21321
+ return {};
21322
+ case "wait.route": {
21323
+ const expected = String(next.route ?? next.value ?? "");
21324
+ await page.waitForURL((url) => url.toString().includes(expected), { timeout });
21325
+ return { assertion: { type: next.type, passed: true, expected, actual: page.url() } };
21326
+ }
21327
+ case "context.extract": {
21328
+ const source = String(next.source ?? "url");
21329
+ let value;
21330
+ if (source === "url") value = page.url();
21331
+ else if (source.startsWith("url.query.")) value = runtimeUrlObject(page.url()).searchParams.get(source.slice("url.query.".length));
21332
+ else if (source === "title") value = await page.title();
21333
+ else if (next.target) value = await (await locatorForTarget(page, next.target)).first().textContent();
21334
+ else throw new Error(`unsupported context.extract source ${source}`);
21335
+ return { extracted: [String(next.name), value] };
21336
+ }
21337
+ case "page.assert_step": {
21338
+ const expected = String(next.expected ?? next.value ?? "");
21339
+ const visible = await page.getByText(expected, { exact: false }).first().isVisible().catch(() => false);
21340
+ if (!visible) throw new Error(`expected flow step is not visible: ${expected}`);
21341
+ return { assertion: { type: next.type, passed: true, expected } };
21342
+ }
21343
+ case "list.assert_record": {
21344
+ const expected = String(next.value ?? next.text ?? "");
21345
+ const visible = await page.getByText(expected, { exact: false }).first().isVisible().catch(() => false);
21346
+ if (!visible) throw new Error(`expected list record is not visible: ${expected}`);
21347
+ return { assertion: { type: next.type, passed: true, expected } };
21348
+ }
21349
+ case "evidence.capture":
21350
+ return {};
21351
+ default:
21352
+ throw new Error(`unsupported browser action ${next.type}`);
21353
+ }
21354
+ }
21355
+ async function openContext(options) {
21356
+ if (options.cdpEndpoint) {
21357
+ const browser2 = await chromium.connectOverCDP(options.cdpEndpoint);
21358
+ const context3 = browser2.contexts()[0] ?? await browser2.newContext(options.storageState ? { storageState: path13.resolve(options.storageState) } : void 0);
21359
+ return { context: context3, browser: browser2, owned: false };
21360
+ }
21361
+ if (options.userDataDir) {
21362
+ const context3 = await chromium.launchPersistentContext(path13.resolve(options.userDataDir), {
21363
+ headless: !options.headed,
21364
+ executablePath: options.executablePath,
21365
+ channel: options.executablePath ? void 0 : "chrome"
21366
+ });
21367
+ return { context: context3, owned: true };
21368
+ }
21369
+ const browser = await chromium.launch({
21370
+ headless: !options.headed,
21371
+ executablePath: options.executablePath,
21372
+ channel: options.executablePath ? void 0 : "chrome"
21373
+ });
21374
+ const context2 = await browser.newContext(options.storageState ? { storageState: path13.resolve(options.storageState) } : void 0);
21375
+ return { context: context2, browser, owned: true };
21376
+ }
21377
+ function runtimeIds(runtimeUrl) {
21378
+ const url = runtimeUrlObject(runtimeUrl);
21379
+ const projectId = url.searchParams.get("project_id") || url.searchParams.get("id") || runtimeUrl.match(/\/project(?:Continue|_detail)?\/(?:0\/)?(\d+)/)?.[1];
21380
+ const stepId = url.searchParams.get("step_id");
21381
+ return {
21382
+ ...projectId && /^\d+$/.test(projectId) ? { project_id: projectId } : {},
21383
+ ...stepId && /^\d+$/.test(stepId) ? { step_id: stepId } : {}
21384
+ };
21385
+ }
21386
+ function runtimeUrlObject(runtimeUrl) {
21387
+ const url = new URL(runtimeUrl);
21388
+ return url.hash.startsWith("#/") ? new URL(url.hash.slice(1), url.origin) : url;
21389
+ }
21390
+ function executionScope(runtimeUrl) {
21391
+ const ids = runtimeIds(runtimeUrl);
21392
+ if (ids.step_id) return "step";
21393
+ if (ids.project_id) return "project";
21394
+ return "page";
21395
+ }
21396
+ function runtimeEnvironmentFor(baseUrl) {
21397
+ try {
21398
+ const hostname = new URL(baseUrl).hostname;
21399
+ return /^(?:localhost|127\.0\.0\.1|\[::1\]|::1)$/.test(hostname) ? "local-browser" : "profile";
21400
+ } catch {
21401
+ return "profile";
21402
+ }
21403
+ }
21404
+ function browserRunnerArtifactPaths(evidenceDir, caseId, stepId) {
21405
+ const resolvedEvidenceDir = path13.resolve(evidenceDir);
21406
+ const screenshotsDir = path13.resolve(resolvedEvidenceDir, "..", "..", "screenshots");
21407
+ const screenshotPath = path13.join(screenshotsDir, `${caseId}-${stepId}.png`);
21408
+ return {
21409
+ screenshotsDir,
21410
+ screenshotPath,
21411
+ screenshotReference: path13.relative(resolvedEvidenceDir, screenshotPath).split(path13.sep).join("/")
21412
+ };
21413
+ }
21414
+ function browserEvidenceDirectoriesForRun(manifestFile, execution, currentStepId, untilBlocked) {
21415
+ const steps = Array.isArray(execution.steps) ? execution.steps.map((step) => isRecord9(step) ? step : {}) : [];
21416
+ const startIndex = steps.findIndex((step) => String(step.step_id || "") === currentStepId);
21417
+ if (startIndex < 0) return [];
21418
+ const runDir = path13.dirname(path13.resolve(manifestFile));
21419
+ const fallbackCaseId = String(execution.case_id || "");
21420
+ const result = [];
21421
+ for (let index = startIndex; index < steps.length; index += 1) {
21422
+ const step = steps[index];
21423
+ if (step.status !== "planned" || step.runner !== "browser_action") break;
21424
+ const caseId = String(step.case_id || fallbackCaseId);
21425
+ const stepId = String(step.step_id || "");
21426
+ if (!caseId || !stepId) break;
21427
+ result.push(path13.join(runDir, "evidence", `${caseId}-${stepId}`));
21428
+ if (!untilBlocked) break;
21429
+ }
21430
+ return result;
21431
+ }
21432
+ async function writeRunnerEvidence(options) {
21433
+ await mkdir10(options.dir, { recursive: true });
21434
+ const screenshot = browserRunnerArtifactPaths(options.dir, options.caseId, options.stepId);
21435
+ await mkdir10(screenshot.screenshotsDir, { recursive: true });
21436
+ const domName = `${options.caseId}-${options.stepId}-dom.json`;
21437
+ const traceName = "browser-action-trace.json";
21438
+ await options.page.screenshot({ path: screenshot.screenshotPath, fullPage: true });
21439
+ const domSnapshot = await options.page.evaluate(() => {
21440
+ const controls = [...document.querySelectorAll("input, textarea, select, button, [role], [data-field-key], [field]")].slice(0, 500).map((element) => ({
21441
+ tag: element.tagName.toLowerCase(),
21442
+ type: element.getAttribute("type"),
21443
+ role: element.getAttribute("role"),
21444
+ name: element.getAttribute("name"),
21445
+ id: element.getAttribute("id"),
21446
+ aria_label: element.getAttribute("aria-label"),
21447
+ field: element.getAttribute("data-field-key") || element.getAttribute("field"),
21448
+ text: (element.textContent || "").trim().slice(0, 200)
21449
+ }));
21450
+ return {
21451
+ url: window.location.href,
21452
+ title: document.title,
21453
+ visible_text: (document.body?.innerText || "").slice(0, 1e5),
21454
+ controls
21455
+ };
21456
+ });
21457
+ await writeFile10(path13.join(options.dir, domName), `${JSON.stringify(domSnapshot, null, 2)}
21458
+ `, "utf8");
21459
+ await writeFile10(path13.join(options.dir, traceName), `${JSON.stringify({
21460
+ page_fingerprint: options.automationStep.page_fingerprint,
21461
+ actions: options.automationStep.actions,
21462
+ expected_checks: options.automationStep.expected_checks,
21463
+ execution: options.actionTrace
21464
+ }, null, 2)}
21465
+ `, "utf8");
21466
+ const runtimeUrl = options.page.url();
21467
+ const evidence = path13.join(options.dir, `${options.caseId}-${options.stepId}.json`);
21468
+ const payload = {
21469
+ schema_version: 2,
21470
+ case_id: options.caseId,
21471
+ case_step_id: options.stepId,
21472
+ status: options.status,
21473
+ browser_verified: options.status === "pass" || options.status === "fail",
21474
+ browser_tool: "Playwright",
21475
+ runtime_scope: executionScope(runtimeUrl),
21476
+ runtime_environment: runtimeEnvironmentFor(runtimeUrl),
21477
+ runtime_url: runtimeUrl,
21478
+ screenshot: screenshot.screenshotReference,
21479
+ dom_snapshot: domName,
21480
+ assertions: options.assertions,
21481
+ remote_submitted: options.remoteSubmitted,
21482
+ readback_confirmed: options.status === "pass",
21483
+ console_errors: options.consoleErrors,
21484
+ network_errors: options.networkErrors,
21485
+ ...options.error ? { failure: { kind: options.status, message: options.error } } : {},
21486
+ ...runtimeIds(runtimeUrl)
21487
+ };
21488
+ await writeFile10(evidence, `${JSON.stringify(payload, null, 2)}
21489
+ `, "utf8");
21490
+ const evidenceFiles = [
21491
+ { file: screenshot.screenshotReference, absolutePath: screenshot.screenshotPath },
21492
+ { file: domName, absolutePath: path13.join(options.dir, domName) },
21493
+ { file: traceName, absolutePath: path13.join(options.dir, traceName) },
21494
+ { file: path13.basename(evidence), absolutePath: evidence }
21495
+ ];
21496
+ await writeFile10(path13.join(options.dir, "evidence-files.json"), `${JSON.stringify({
21497
+ generated_at: (/* @__PURE__ */ new Date()).toISOString(),
21498
+ files: await Promise.all(evidenceFiles.map(async ({ file, absolutePath }) => {
21499
+ const content = await readFile14(absolutePath);
21500
+ const extension = path13.extname(file).toLowerCase();
21501
+ const mimeType = extension === ".png" ? "image/png" : "application/json";
21502
+ return { file, mime_type: mimeType, sha256: createHash6("sha256").update(content).digest("hex"), size: content.length };
21503
+ }))
21504
+ }, null, 2)}
21505
+ `, "utf8");
21506
+ return evidence;
21507
+ }
21508
+ async function runOneBrowserStep(options, session) {
21509
+ const automation = await loadBrowserAutomation(options.automation);
21510
+ const state = await nextTestSuiteRunStep(options.executionManifest, options.profile);
21511
+ if (state.complete === true) {
21512
+ throw new Error("test_suite.run.completed_manifest: completed cases are never skipped or reused; start a new full_rerun manifest to execute the case again");
21513
+ }
21514
+ const currentStep = isRecord9(state.current_step) ? state.current_step : {};
21515
+ const execution = isRecord9(state.execution) ? state.execution : {};
21516
+ const requestedCase = options.caseId || String(execution.case_id || "");
21517
+ const requestedStep = options.caseStepId || String(currentStep.step_id || "");
21518
+ if (!requestedCase || !requestedStep) throw new Error("browser-run cannot resolve the current case/step from the execution manifest");
21519
+ const priorPassCount = Array.isArray(execution.steps) ? execution.steps.filter((step) => isRecord9(step) && step.status === "pass").length : 0;
21520
+ if (priorPassCount > 0 && !options.resume) {
21521
+ throw new Error("test_suite.run.resume_required: this current run already has recorded steps; use --resume to continue this same unfinished manifest");
21522
+ }
21523
+ const validated = await validateExecutionManifestStep({
21524
+ manifest: options.executionManifest,
21525
+ caseId: requestedCase,
21526
+ caseStepId: requestedStep,
21527
+ runners: ["browser_action"],
21528
+ profile: options.profile
21529
+ });
21530
+ if (validated.manifest.result !== "running") {
21531
+ throw new Error("test_suite.run.completed_manifest: a completed run cannot be resumed; start a new full_rerun manifest so the case executes again with new evidence");
21532
+ }
21533
+ const definition = automation.steps[automationStepKey(requestedCase, requestedStep)];
21534
+ if (!definition) throw new Error(`test_suite.automation.step_missing: ${requestedCase}/${requestedStep} is not defined in ${options.automation}`);
21535
+ const evidenceDir = path13.join(path13.dirname(validated.manifestPath), "evidence", `${requestedCase}-${requestedStep}`);
21536
+ await preflightExecutionEvidenceDirectory({ manifest: validated.manifestPath, evidenceDir });
21537
+ const data = await readJsonInput(options.dataProfile);
21538
+ const browserBaseUrl = options.baseUrl || validated.manifest.profile_origin || "";
21539
+ const variables = { data, context: {}, base_url: browserBaseUrl };
21540
+ const existingPages = session.context.pages();
21541
+ const page = existingPages.at(-1) ?? await session.context.newPage();
21542
+ const consoleErrors = [];
21543
+ const networkErrors = [];
21544
+ const responseUrls = [];
21545
+ const onConsole = (message) => {
21546
+ if (message.type() !== "error") return;
21547
+ const value = message.text().slice(0, 1e3);
21548
+ pushBounded(consoleErrors, value, JSON.stringify(value));
21549
+ };
21550
+ const onRequestFailed = (request) => {
21551
+ const value = { url: request.url(), failure: request.failure()?.errorText };
21552
+ pushBounded(networkErrors, value, JSON.stringify(value));
21553
+ };
21554
+ const onResponse = (response) => {
21555
+ pushBounded(responseUrls, response.url(), JSON.stringify(response.url()), 500);
21556
+ if (response.status() >= 400) {
21557
+ const value = { url: response.url(), status: response.status() };
21558
+ pushBounded(networkErrors, value, JSON.stringify(value));
21559
+ }
21560
+ };
21561
+ page.on("console", onConsole);
21562
+ page.on("requestfailed", onRequestFailed);
21563
+ page.on("response", onResponse);
21564
+ const actionTrace = [];
21565
+ const assertions = [];
21566
+ let remoteSubmitted = false;
21567
+ let fingerprintChecked = false;
21568
+ try {
21569
+ for (let index = 0; index < definition.actions.length; index += 1) {
21570
+ const action = definition.actions[index];
21571
+ if (!fingerprintChecked && !["navigation.open", "wait.visible", "wait.route", "wait.network"].includes(action.type)) {
21572
+ const failures = await assertFingerprint(page, definition.page_fingerprint, variables);
21573
+ if (failures.length > 0) {
21574
+ const evidence2 = await writeRunnerEvidence({
21575
+ dir: evidenceDir,
21576
+ page,
21577
+ caseId: requestedCase,
21578
+ stepId: requestedStep,
21579
+ status: "cache_stale",
21580
+ assertions: failures.map((message) => ({ name: "page_fingerprint", passed: false, message })),
21581
+ actionTrace,
21582
+ automationStep: definition,
21583
+ consoleErrors,
21584
+ networkErrors,
21585
+ remoteSubmitted: false,
21586
+ error: failures.join("; ")
21587
+ });
21588
+ return {
21589
+ ok: false,
21590
+ status: "cache_stale",
21591
+ remote_submitted: false,
21592
+ readback_confirmed: false,
21593
+ llm_intervention_required: true,
21594
+ manifest: validated.manifestPath,
21595
+ case_id: requestedCase,
21596
+ case_step_id: requestedStep,
21597
+ evidence: evidence2,
21598
+ current_url: page.url(),
21599
+ error: failures.join("; ")
21600
+ };
21601
+ }
21602
+ fingerprintChecked = true;
21603
+ }
21604
+ const startedAt = (/* @__PURE__ */ new Date()).toISOString();
21605
+ const result = await executeAction(page, action, variables, {
21606
+ responseUrls,
21607
+ onMutationAttempt: () => {
21608
+ remoteSubmitted = true;
21609
+ }
21610
+ });
21611
+ if (result.extracted) variables.context[result.extracted[0]] = result.extracted[1];
21612
+ if (result.assertion) assertions.push(result.assertion);
21613
+ actionTrace.push({ index, type: action.type, started_at: startedAt, finished_at: (/* @__PURE__ */ new Date()).toISOString(), ok: true });
21614
+ }
21615
+ if (!fingerprintChecked) {
21616
+ const failures = await assertFingerprint(page, definition.page_fingerprint, variables);
21617
+ if (failures.length) {
21618
+ const evidence2 = await writeRunnerEvidence({
21619
+ dir: evidenceDir,
21620
+ page,
21621
+ caseId: requestedCase,
21622
+ stepId: requestedStep,
21623
+ status: "cache_stale",
21624
+ assertions: failures.map((message) => ({ name: "page_fingerprint", passed: false, message })),
21625
+ actionTrace,
21626
+ automationStep: definition,
21627
+ consoleErrors,
21628
+ networkErrors,
21629
+ remoteSubmitted: false,
21630
+ error: failures.join("; ")
21631
+ });
21632
+ return {
21633
+ ok: false,
21634
+ status: "cache_stale",
21635
+ remote_submitted: false,
21636
+ readback_confirmed: false,
21637
+ llm_intervention_required: true,
21638
+ manifest: validated.manifestPath,
21639
+ case_id: requestedCase,
21640
+ case_step_id: requestedStep,
21641
+ evidence: evidence2,
21642
+ current_url: page.url(),
21643
+ error: failures.join("; ")
21644
+ };
21645
+ }
21646
+ }
21647
+ for (const check of definition.expected_checks) {
21648
+ const result = await executeAction(page, check, variables, {
21649
+ responseUrls,
21650
+ onMutationAttempt: () => {
21651
+ remoteSubmitted = true;
21652
+ }
21653
+ });
21654
+ assertions.push(result.assertion ?? { type: check.type, passed: true });
21655
+ }
21656
+ const evidence = await writeRunnerEvidence({
21657
+ dir: evidenceDir,
21658
+ page,
21659
+ caseId: requestedCase,
21660
+ stepId: requestedStep,
21661
+ status: "pass",
21662
+ assertions,
21663
+ actionTrace,
21664
+ automationStep: definition,
21665
+ consoleErrors,
21666
+ networkErrors,
21667
+ remoteSubmitted
21668
+ });
21669
+ const recorded = await recordTestSuiteRunStep({
21670
+ manifest: validated.manifestPath,
21671
+ caseId: requestedCase,
21672
+ caseStepId: requestedStep,
21673
+ result: "pass",
21674
+ evidence,
21675
+ profile: options.profile
21676
+ });
21677
+ const reportSync = isRecord9(recorded.report_sync) ? recorded.report_sync : {};
21678
+ if (reportSync.ok === false) {
21679
+ return {
21680
+ ok: false,
21681
+ status: "evidence_failed",
21682
+ remote_submitted: remoteSubmitted,
21683
+ readback_confirmed: true,
21684
+ evidence_failed: true,
21685
+ llm_intervention_required: true,
21686
+ manifest: validated.manifestPath,
21687
+ case_id: requestedCase,
21688
+ case_step_id: requestedStep,
21689
+ evidence,
21690
+ current_url: page.url(),
21691
+ next_step: recorded.current_step,
21692
+ error: String(reportSync.error || "execution report sync failed; run test-suite run report-sync before continuing")
21693
+ };
21694
+ }
21695
+ return {
21696
+ ok: true,
21697
+ status: "pass",
21698
+ remote_submitted: remoteSubmitted,
21699
+ readback_confirmed: true,
21700
+ llm_intervention_required: false,
21701
+ manifest: validated.manifestPath,
21702
+ case_id: requestedCase,
21703
+ case_step_id: requestedStep,
21704
+ evidence,
21705
+ current_url: page.url(),
21706
+ next_step: recorded.current_step
21707
+ };
21708
+ } catch (error) {
21709
+ const message = error instanceof Error ? error.message : String(error);
21710
+ assertions.push({ name: "browser_action", passed: false, message });
21711
+ actionTrace.push({ index: actionTrace.length, finished_at: (/* @__PURE__ */ new Date()).toISOString(), ok: false, error: message });
21712
+ const evidence = await writeRunnerEvidence({
21713
+ dir: evidenceDir,
21714
+ page,
21715
+ caseId: requestedCase,
21716
+ stepId: requestedStep,
21717
+ status: "fail",
21718
+ assertions,
21719
+ actionTrace,
21720
+ automationStep: definition,
21721
+ consoleErrors,
21722
+ networkErrors,
21723
+ remoteSubmitted,
21724
+ error: message
21725
+ });
21726
+ let recordError;
21727
+ await recordTestSuiteRunStep({
21728
+ manifest: validated.manifestPath,
21729
+ caseId: requestedCase,
21730
+ caseStepId: requestedStep,
21731
+ result: "fail",
21732
+ evidence,
21733
+ profile: options.profile
21734
+ }).catch((recordFailure) => {
21735
+ recordError = recordFailure instanceof Error ? recordFailure.message : String(recordFailure);
21736
+ });
21737
+ return {
21738
+ ok: false,
21739
+ status: recordError ? "evidence_failed" : remoteSubmitted ? "submitted_outcome_unknown" : "execution_failed",
21740
+ remote_submitted: remoteSubmitted,
21741
+ readback_confirmed: false,
21742
+ evidence_failed: Boolean(recordError),
21743
+ llm_intervention_required: true,
21744
+ manifest: validated.manifestPath,
21745
+ case_id: requestedCase,
21746
+ case_step_id: requestedStep,
21747
+ evidence,
21748
+ current_url: page.url(),
21749
+ error: recordError ? `${message}; evidence record failed: ${recordError}` : message
21750
+ };
21751
+ } finally {
21752
+ page.off("console", onConsole);
21753
+ page.off("requestfailed", onRequestFailed);
21754
+ page.off("response", onResponse);
21755
+ }
21756
+ }
21757
+ async function runBrowserAutomation(options) {
21758
+ if (!options.resume && options.untilBlocked) {
21759
+ throw new Error("--until-blocked requires --resume to make the within-run continuation explicit");
21760
+ }
21761
+ const initialState = await nextTestSuiteRunStep(options.executionManifest, options.profile);
21762
+ if (initialState.complete === true) {
21763
+ throw new Error("test_suite.run.completed_manifest: completed cases are never skipped or reused; start a new full_rerun manifest to execute the case again");
21764
+ }
21765
+ const initialStep = isRecord9(initialState.current_step) ? initialState.current_step : {};
21766
+ if (initialStep.runner !== "browser_action") {
21767
+ throw new Error(`test_suite.run.runner_mismatch: current step runner is ${String(initialStep.runner || "<missing>")}, not browser_action`);
21768
+ }
21769
+ const initialExecution = isRecord9(initialState.execution) ? initialState.execution : {};
21770
+ const priorPassCount = Array.isArray(initialExecution.steps) ? initialExecution.steps.filter((step) => isRecord9(step) && step.status === "pass").length : 0;
21771
+ if (priorPassCount > 0 && !options.resume) {
21772
+ throw new Error("test_suite.run.resume_required: this current run already has recorded steps; use --resume to continue this same unfinished manifest");
21773
+ }
21774
+ const currentStepId = String(initialStep.step_id || "");
21775
+ const evidenceDirs = browserEvidenceDirectoriesForRun(
21776
+ options.executionManifest,
21777
+ initialExecution,
21778
+ currentStepId,
21779
+ Boolean(options.untilBlocked)
21780
+ );
21781
+ for (const evidenceDir of evidenceDirs) {
21782
+ await preflightExecutionEvidenceDirectory({ manifest: options.executionManifest, evidenceDir });
21783
+ }
21784
+ const session = await openContext(options);
21785
+ try {
21786
+ let currentOptions = { ...options };
21787
+ let result = await runOneBrowserStep(currentOptions, session);
21788
+ let remoteSubmitted = result.remote_submitted;
21789
+ while (options.untilBlocked && result.ok && isRecord9(result.next_step) && result.next_step.runner === "browser_action") {
21790
+ currentOptions = {
21791
+ ...options,
21792
+ resume: true,
21793
+ caseId: result.next_step.case_id ? String(result.next_step.case_id) : void 0,
21794
+ caseStepId: result.next_step.step_id ? String(result.next_step.step_id) : void 0
21795
+ };
21796
+ result = await runOneBrowserStep(currentOptions, session);
21797
+ remoteSubmitted = remoteSubmitted || result.remote_submitted;
21798
+ }
21799
+ return remoteSubmitted === result.remote_submitted ? result : { ...result, remote_submitted: remoteSubmitted, current_step_remote_submitted: result.remote_submitted };
21800
+ } finally {
21801
+ if (session.owned) await session.context.close().catch(() => void 0);
21802
+ if (session.owned && session.browser) await session.browser.close().catch(() => void 0);
21803
+ }
21804
+ }
21805
+
20760
21806
  // src/core/form-schema.ts
20761
21807
  var FIELD_KEY_NAMES = [
20762
21808
  "key",
@@ -20776,7 +21822,7 @@ var OPTION_NAMES = ["options", "items", "choices", "values"];
20776
21822
  var REQUIRED_NAMES = ["required", "is_required", "isRequired", "require", "must", "validateRequired"];
20777
21823
  var HIDDEN_NAMES = ["hidden", "is_hidden", "isHidden", "hide", "hideInForm"];
20778
21824
  var VISIBLE_NAMES = ["visible", "display", "show"];
20779
- function isRecord8(value) {
21825
+ function isRecord10(value) {
20780
21826
  return typeof value === "object" && value !== null && !Array.isArray(value);
20781
21827
  }
20782
21828
  function pickString(source, keys) {
@@ -20803,10 +21849,10 @@ function pickBoolean(source, keys) {
20803
21849
  }
20804
21850
  const rules = source.rules;
20805
21851
  if (Array.isArray(rules)) {
20806
- return rules.some((rule) => isRecord8(rule) && pickBoolean(rule, REQUIRED_NAMES));
21852
+ return rules.some((rule) => isRecord10(rule) && pickBoolean(rule, REQUIRED_NAMES));
20807
21853
  }
20808
21854
  const validateMap = source.validateMap;
20809
- if (isRecord8(validateMap) && pickBoolean(validateMap, REQUIRED_NAMES)) {
21855
+ if (isRecord10(validateMap) && pickBoolean(validateMap, REQUIRED_NAMES)) {
20810
21856
  return true;
20811
21857
  }
20812
21858
  return false;
@@ -20830,7 +21876,7 @@ function optionValue(option) {
20830
21876
  if (typeof option === "string" || typeof option === "number") {
20831
21877
  return String(option);
20832
21878
  }
20833
- if (!isRecord8(option)) {
21879
+ if (!isRecord10(option)) {
20834
21880
  return null;
20835
21881
  }
20836
21882
  return pickString(option, ["value", "key", "id", "name", "label", "title"]) ?? null;
@@ -20848,7 +21894,7 @@ function pickOptions(source) {
20848
21894
  }
20849
21895
  for (const containerKey of ["props", "config", "setting", "value"]) {
20850
21896
  const container = source[containerKey];
20851
- if (isRecord8(container)) {
21897
+ if (isRecord10(container)) {
20852
21898
  const nested = pickOptions(container);
20853
21899
  if (nested?.length) {
20854
21900
  return nested;
@@ -20904,7 +21950,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
20904
21950
  }
20905
21951
  return;
20906
21952
  }
20907
- if (!isRecord8(value)) {
21953
+ if (!isRecord10(value)) {
20908
21954
  return;
20909
21955
  }
20910
21956
  const field = fieldFromRecord(value);
@@ -20912,7 +21958,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
20912
21958
  if (isSubFormField(field)) {
20913
21959
  const childFields = /* @__PURE__ */ new Map();
20914
21960
  for (const child of Object.values(value)) {
20915
- if (isRecord8(child) || Array.isArray(child)) {
21961
+ if (isRecord10(child) || Array.isArray(child)) {
20916
21962
  collectFieldCandidates(child, childFields, depth + 1);
20917
21963
  }
20918
21964
  }
@@ -20926,7 +21972,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
20926
21972
  fields.set(field.key, mergeField(fields.get(field.key), field));
20927
21973
  }
20928
21974
  for (const child of Object.values(value)) {
20929
- if (isRecord8(child) || Array.isArray(child)) {
21975
+ if (isRecord10(child) || Array.isArray(child)) {
20930
21976
  collectFieldCandidates(child, fields, depth + 1);
20931
21977
  }
20932
21978
  }
@@ -20944,7 +21990,7 @@ function validateComplexSelector(field, value) {
20944
21990
  if (!isComplexSelectorType(type)) {
20945
21991
  return null;
20946
21992
  }
20947
- const validObject = (item) => isRecord8(item);
21993
+ const validObject = (item) => isRecord10(item);
20948
21994
  const hint = complexSelectorHint(field);
20949
21995
  if (Array.isArray(value)) {
20950
21996
  return value.every(validObject) ? null : `${field.key} must contain selector option object(s), not scalar values. ${hint}`;
@@ -20961,7 +22007,7 @@ function isEnumSelectType(type) {
20961
22007
  return /enum_select/.test(type);
20962
22008
  }
20963
22009
  function optionComparableValue(value) {
20964
- if (isRecord8(value) && ("value" in value || "label" in value)) {
22010
+ if (isRecord10(value) && ("value" in value || "label" in value)) {
20965
22011
  return value.value ?? value.label;
20966
22012
  }
20967
22013
  return value;
@@ -20975,7 +22021,7 @@ function validateType(field, value) {
20975
22021
  if (!Array.isArray(value)) {
20976
22022
  return `${field.key} must be a JSON array of row objects`;
20977
22023
  }
20978
- const invalidRowIndex = value.findIndex((row) => !isRecord8(row));
22024
+ const invalidRowIndex = value.findIndex((row) => !isRecord10(row));
20979
22025
  return invalidRowIndex >= 0 ? `${field.key}[${invalidRowIndex}] must be a row object` : null;
20980
22026
  }
20981
22027
  const selectorError = validateComplexSelector(field, value);
@@ -21001,7 +22047,7 @@ function validateType(field, value) {
21001
22047
  if (/(array|multi|multiple)/.test(type) && !Array.isArray(value)) {
21002
22048
  return `${field.key} must be an array`;
21003
22049
  }
21004
- if (isEnumSelectType(type) && isRecord8(value)) {
22050
+ if (isEnumSelectType(type) && isRecord10(value)) {
21005
22051
  const optionValue2 = value.value ?? value.label;
21006
22052
  return typeof optionValue2 === "string" || typeof optionValue2 === "number" ? null : `${field.key} must be an enum option object with a scalar value`;
21007
22053
  }
@@ -21031,7 +22077,7 @@ function validateFormEntries(form, fields, prefix = "") {
21031
22077
  }
21032
22078
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
21033
22079
  for (const [index, row] of value.entries()) {
21034
- if (isRecord8(row)) {
22080
+ if (isRecord10(row)) {
21035
22081
  errors.push(...validateFormEntries(row, field.children, `${prefix}${field.key}[${index}].`));
21036
22082
  }
21037
22083
  }
@@ -21109,10 +22155,10 @@ function explainFormValidationSchema(fields) {
21109
22155
  }
21110
22156
 
21111
22157
  // src/commands/step.ts
21112
- function isRecord9(value) {
22158
+ function isRecord11(value) {
21113
22159
  return typeof value === "object" && value !== null && !Array.isArray(value);
21114
22160
  }
21115
- function stringValue2(value) {
22161
+ function stringValue3(value) {
21116
22162
  if (value === void 0 || value === null) {
21117
22163
  return void 0;
21118
22164
  }
@@ -21120,7 +22166,7 @@ function stringValue2(value) {
21120
22166
  return next ? next : void 0;
21121
22167
  }
21122
22168
  function idValue(value) {
21123
- const next = stringValue2(value);
22169
+ const next = stringValue3(value);
21124
22170
  return next && /^\d+$/.test(next) ? next : void 0;
21125
22171
  }
21126
22172
  function hasMeaningfulValue(value) {
@@ -21136,7 +22182,7 @@ function hasMeaningfulValue(value) {
21136
22182
  if (Array.isArray(value)) {
21137
22183
  return value.some(hasMeaningfulValue);
21138
22184
  }
21139
- if (isRecord9(value)) {
22185
+ if (isRecord11(value)) {
21140
22186
  return Object.values(value).some(hasMeaningfulValue);
21141
22187
  }
21142
22188
  return false;
@@ -21145,11 +22191,11 @@ function isEmptyValue(value) {
21145
22191
  return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
21146
22192
  }
21147
22193
  function projectIdOfStep(step) {
21148
- const nestedProjectId = isRecord9(step.project) ? step.project.id : void 0;
22194
+ const nestedProjectId = isRecord11(step.project) ? step.project.id : void 0;
21149
22195
  return idValue(step.project_id ?? step.projectId ?? nestedProjectId);
21150
22196
  }
21151
22197
  function stepFlowNodeId(step) {
21152
- return stringValue2(step.flow_step_id ?? step.flowStepId ?? step.flow_node_id ?? step.flowNodeId);
22198
+ return stringValue3(step.flow_step_id ?? step.flowStepId ?? step.flow_node_id ?? step.flowNodeId);
21153
22199
  }
21154
22200
  function isStepFinished(step) {
21155
22201
  if (step.real_end_time || step.end_time) {
@@ -21173,12 +22219,12 @@ function collectRecords(value, output = [], seen = /* @__PURE__ */ new Set()) {
21173
22219
  value.forEach((item) => collectRecords(item, output, seen));
21174
22220
  return output;
21175
22221
  }
21176
- if (!isRecord9(value)) {
22222
+ if (!isRecord11(value)) {
21177
22223
  return output;
21178
22224
  }
21179
22225
  output.push(value);
21180
22226
  for (const child of Object.values(value)) {
21181
- if (Array.isArray(child) || isRecord9(child)) {
22227
+ if (Array.isArray(child) || isRecord11(child)) {
21182
22228
  collectRecords(child, output, seen);
21183
22229
  }
21184
22230
  }
@@ -21200,7 +22246,7 @@ function findFlowNode(project, step) {
21200
22246
  project.config
21201
22247
  ];
21202
22248
  for (const candidate of candidates) {
21203
- const match = collectRecords(candidate).find((item) => stringValue2(item.id) === flowStepId);
22249
+ const match = collectRecords(candidate).find((item) => stringValue3(item.id) === flowStepId);
21204
22250
  if (match) {
21205
22251
  return match;
21206
22252
  }
@@ -21262,7 +22308,7 @@ function formListOfStep(step) {
21262
22308
  return values.filter(hasMeaningfulValue);
21263
22309
  }
21264
22310
  function unwrapFormValue(value) {
21265
- if (!isRecord9(value)) {
22311
+ if (!isRecord11(value)) {
21266
22312
  return value;
21267
22313
  }
21268
22314
  if ("value" in value && Object.keys(value).length <= 3) {
@@ -21279,10 +22325,10 @@ function collectFormValues(value, output = {}, seen = /* @__PURE__ */ new Set())
21279
22325
  value.forEach((item) => collectFormValues(item, output, seen));
21280
22326
  return output;
21281
22327
  }
21282
- if (!isRecord9(value)) {
22328
+ if (!isRecord11(value)) {
21283
22329
  return output;
21284
22330
  }
21285
- const key = stringValue2(value.key ?? value.field_key ?? value.fieldKey ?? value.name);
22331
+ const key = stringValue3(value.key ?? value.field_key ?? value.fieldKey ?? value.name);
21286
22332
  if (key && "value" in value) {
21287
22333
  const nextValue = unwrapFormValue(value.value);
21288
22334
  if (hasMeaningfulValue(nextValue)) {
@@ -21290,7 +22336,7 @@ function collectFormValues(value, output = {}, seen = /* @__PURE__ */ new Set())
21290
22336
  }
21291
22337
  }
21292
22338
  for (const child of Object.values(value)) {
21293
- if (Array.isArray(child) || isRecord9(child)) {
22339
+ if (Array.isArray(child) || isRecord11(child)) {
21294
22340
  collectFormValues(child, output, seen);
21295
22341
  }
21296
22342
  }
@@ -21337,7 +22383,7 @@ function collectMissingRequiredInputs(fields, values) {
21337
22383
  continue;
21338
22384
  }
21339
22385
  value.forEach((row, index) => {
21340
- if (!isRecord9(row)) {
22386
+ if (!isRecord11(row)) {
21341
22387
  return;
21342
22388
  }
21343
22389
  for (const child of field.children ?? []) {
@@ -21391,7 +22437,7 @@ function ownerIdsFromStep(step) {
21391
22437
  ];
21392
22438
  const ids = /* @__PURE__ */ new Set();
21393
22439
  for (const owner of owners) {
21394
- if (isRecord9(owner)) {
22440
+ if (isRecord11(owner)) {
21395
22441
  const id = idValue(owner.owner_id ?? owner.user_id ?? owner.id);
21396
22442
  if (id) {
21397
22443
  ids.add(id);
@@ -21430,7 +22476,7 @@ function ownerDiagnosticsFromStep(step, currentUser) {
21430
22476
  const values = Array.isArray(value) ? value : [value];
21431
22477
  for (const item of values) {
21432
22478
  let id;
21433
- if (isRecord9(item)) {
22479
+ if (isRecord11(item)) {
21434
22480
  id = idValue(item.owner_id ?? item.user_id ?? item.id);
21435
22481
  } else {
21436
22482
  id = idValue(item);
@@ -21553,12 +22599,12 @@ function extractSubmitInputValues(data) {
21553
22599
  const candidates = [data.form, data.form_data, data.formData, data.fields, data.values];
21554
22600
  const values = {};
21555
22601
  for (const candidate of candidates) {
21556
- if (isRecord9(candidate)) {
22602
+ if (isRecord11(candidate)) {
21557
22603
  Object.assign(values, candidate);
21558
22604
  }
21559
22605
  }
21560
22606
  for (const [key, value] of Object.entries(data)) {
21561
- if (!SUBMIT_NON_FORM_KEYS.has(key) && !isRecord9(value) && !Array.isArray(value)) {
22607
+ if (!SUBMIT_NON_FORM_KEYS.has(key) && !isRecord11(value) && !Array.isArray(value)) {
21562
22608
  values[key] = value;
21563
22609
  }
21564
22610
  }
@@ -21720,10 +22766,10 @@ async function appendE2eExecutionEvidence(options, evidence, runners) {
21720
22766
  runners
21721
22767
  });
21722
22768
  }
21723
- function isRecord10(value) {
22769
+ function isRecord12(value) {
21724
22770
  return typeof value === "object" && value !== null && !Array.isArray(value);
21725
22771
  }
21726
- function stringValue3(value) {
22772
+ function stringValue4(value) {
21727
22773
  if (value === void 0 || value === null) {
21728
22774
  return void 0;
21729
22775
  }
@@ -21741,18 +22787,18 @@ function timestampSlug() {
21741
22787
  return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
21742
22788
  }
21743
22789
  async function ensureDir(dir) {
21744
- const resolved = path12.resolve(dir);
21745
- await mkdir10(resolved, { recursive: true });
22790
+ const resolved = path14.resolve(dir);
22791
+ await mkdir11(resolved, { recursive: true });
21746
22792
  return resolved;
21747
22793
  }
21748
22794
  async function writeEvidence(dir, name, value) {
21749
- const file = path12.join(await ensureDir(dir), name);
21750
- await writeFile10(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
22795
+ const file = path14.join(await ensureDir(dir), name);
22796
+ await writeFile11(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
21751
22797
  `, "utf8");
21752
22798
  return file;
21753
22799
  }
21754
22800
  function summarizeRemoteResult(value) {
21755
- if (!isRecord10(value)) return value;
22801
+ if (!isRecord12(value)) return value;
21756
22802
  const summary = {};
21757
22803
  for (const key of ["id", "project_id", "step_id", "status", "state", "code", "msg", "message", "next", "action"]) {
21758
22804
  if (value[key] !== void 0) summary[key] = value[key];
@@ -21760,18 +22806,18 @@ function summarizeRemoteResult(value) {
21760
22806
  return Object.keys(summary).length > 0 ? redactAuditValue(summary) : { received: true };
21761
22807
  }
21762
22808
  function stepReadbackConfirmed(before, after) {
21763
- const beforeStatus = isRecord10(before.step) ? before.step.status : void 0;
21764
- const afterStatus = isRecord10(after.step) ? after.step.status : void 0;
21765
- const beforeProjectStep = isRecord10(before.project) ? before.project.current_flow_step_id : void 0;
21766
- const afterProjectStep = isRecord10(after.project) ? after.project.current_flow_step_id : void 0;
22809
+ const beforeStatus = isRecord12(before.step) ? before.step.status : void 0;
22810
+ const afterStatus = isRecord12(after.step) ? after.step.status : void 0;
22811
+ const beforeProjectStep = isRecord12(before.project) ? before.project.current_flow_step_id : void 0;
22812
+ const afterProjectStep = isRecord12(after.project) ? after.project.current_flow_step_id : void 0;
21767
22813
  return after.step_finished === true || beforeStatus !== afterStatus || beforeProjectStep !== afterProjectStep;
21768
22814
  }
21769
22815
  function evidenceMime(buffer, file) {
21770
22816
  if (buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
21771
22817
  if (buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return "image/jpeg";
21772
22818
  if (buffer.length >= 12 && buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
21773
- if (path12.extname(file).toLowerCase() === ".json") return "application/json";
21774
- if ([".txt", ".md", ".log"].includes(path12.extname(file).toLowerCase())) return "text/plain";
22819
+ if (path14.extname(file).toLowerCase() === ".json") return "application/json";
22820
+ if ([".txt", ".md", ".log"].includes(path14.extname(file).toLowerCase())) return "text/plain";
21775
22821
  return "application/octet-stream";
21776
22822
  }
21777
22823
  async function writeEvidenceManifest(evidenceDir, details) {
@@ -21779,15 +22825,15 @@ async function writeEvidenceManifest(evidenceDir, details) {
21779
22825
  const artifacts = [];
21780
22826
  for (const entry of files) {
21781
22827
  if (!entry.isFile() || entry.name === "evidence-manifest.json") continue;
21782
- const file = path12.join(evidenceDir, entry.name);
21783
- const buffer = await readFile13(file);
22828
+ const file = path14.join(evidenceDir, entry.name);
22829
+ const buffer = await readFile15(file);
21784
22830
  const mimeType = evidenceMime(buffer, entry.name);
21785
- const extension = path12.extname(entry.name).toLowerCase();
22831
+ const extension = path14.extname(entry.name).toLowerCase();
21786
22832
  const expectedMime = extension === ".png" ? "image/png" : [".jpg", ".jpeg"].includes(extension) ? "image/jpeg" : extension === ".webp" ? "image/webp" : void 0;
21787
22833
  artifacts.push({
21788
22834
  path: entry.name,
21789
22835
  size: buffer.length,
21790
- sha256: createHash6("sha256").update(buffer).digest("hex"),
22836
+ sha256: createHash7("sha256").update(buffer).digest("hex"),
21791
22837
  mime_type: mimeType,
21792
22838
  ...expectedMime && expectedMime !== mimeType ? { extension_mismatch: true, expected_mime: expectedMime } : {}
21793
22839
  });
@@ -21795,19 +22841,19 @@ async function writeEvidenceManifest(evidenceDir, details) {
21795
22841
  return writeEvidence(evidenceDir, "evidence-manifest.json", {
21796
22842
  schema_version: 1,
21797
22843
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
21798
- evidence_dir: path12.resolve(evidenceDir),
22844
+ evidence_dir: path14.resolve(evidenceDir),
21799
22845
  ...details,
21800
22846
  artifacts
21801
22847
  });
21802
22848
  }
21803
22849
  function cacheRoot() {
21804
- return path12.resolve(".codex/cache/bpmax-e2e");
22850
+ return path14.resolve(".codex/cache/bpmax-e2e");
21805
22851
  }
21806
22852
  function safeSegment(value) {
21807
22853
  return value.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_") || "default";
21808
22854
  }
21809
22855
  function safeIdentity(value) {
21810
- if (!isRecord10(value)) return null;
22856
+ if (!isRecord12(value)) return null;
21811
22857
  return {
21812
22858
  id: value.id,
21813
22859
  name: value.name,
@@ -21848,14 +22894,14 @@ async function browserSessionRequest(profile, cookie, method, apiPath2, data, hr
21848
22894
  response.status
21849
22895
  );
21850
22896
  }
21851
- if (isRecord10(body) && typeof body.code === "number" && body.code !== 0) {
22897
+ if (isRecord12(body) && typeof body.code === "number" && body.code !== 0) {
21852
22898
  throw new BrowserSessionRejectedError(
21853
22899
  `e2e.identity.api_error: ${String(body.msg ?? body.message ?? body.code)}`,
21854
22900
  response.status,
21855
22901
  body.code
21856
22902
  );
21857
22903
  }
21858
- return isRecord10(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
22904
+ return isRecord12(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
21859
22905
  }
21860
22906
  function identityCookie(cookieEnv) {
21861
22907
  const cookie = process.env[cookieEnv]?.trim();
@@ -21888,7 +22934,7 @@ function valuesEqual(left, right) {
21888
22934
  }
21889
22935
  function pathValue(source, dottedPath) {
21890
22936
  return dottedPath.split(".").reduce((current, segment) => {
21891
- if (!isRecord10(current)) {
22937
+ if (!isRecord12(current)) {
21892
22938
  return void 0;
21893
22939
  }
21894
22940
  return current[segment];
@@ -21898,10 +22944,10 @@ function normalizeExpectedChecks(value) {
21898
22944
  if (!Array.isArray(value)) {
21899
22945
  return [];
21900
22946
  }
21901
- return value.filter(isRecord10).map((item) => ({
21902
- ...stringValue3(item.name) ? { name: stringValue3(item.name) } : {},
21903
- path: stringValue3(item.path) ?? "",
21904
- op: stringValue3(item.op) ?? "equals",
22947
+ return value.filter(isRecord12).map((item) => ({
22948
+ ...stringValue4(item.name) ? { name: stringValue4(item.name) } : {},
22949
+ path: stringValue4(item.path) ?? "",
22950
+ op: stringValue4(item.op) ?? "equals",
21905
22951
  ...Object.prototype.hasOwnProperty.call(item, "value") ? { value: item.value } : {},
21906
22952
  ...Array.isArray(item.values) ? { values: item.values } : {}
21907
22953
  })).filter((item) => item.path);
@@ -21973,13 +23019,13 @@ function buildExpectedChecks(options) {
21973
23019
  ];
21974
23020
  }
21975
23021
  function flowCachePath(profileName, flowId) {
21976
- return path12.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
23022
+ return path14.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
21977
23023
  }
21978
23024
  async function readOptionalJson(file) {
21979
23025
  try {
21980
- const raw = await readFile13(file, "utf8");
23026
+ const raw = await readFile15(file, "utf8");
21981
23027
  const parsed = JSON.parse(raw);
21982
- return isRecord10(parsed) ? parsed : null;
23028
+ return isRecord12(parsed) ? parsed : null;
21983
23029
  } catch (error) {
21984
23030
  if (error.code === "ENOENT") {
21985
23031
  return null;
@@ -22001,34 +23047,34 @@ function stepsFromProfile(profile) {
22001
23047
  if (!profile) {
22002
23048
  return [];
22003
23049
  }
22004
- if (stringValue3(profile.step_id ?? profile.stepId)) {
23050
+ if (stringValue4(profile.step_id ?? profile.stepId)) {
22005
23051
  return [profile];
22006
23052
  }
22007
23053
  const steps = profile.steps;
22008
23054
  if (Array.isArray(steps)) {
22009
- return steps.filter(isRecord10);
23055
+ return steps.filter(isRecord12);
22010
23056
  }
22011
- if (isRecord10(steps)) {
23057
+ if (isRecord12(steps)) {
22012
23058
  return Object.entries(steps).map(([stepId, value]) => ({
22013
- ...isRecord10(value) ? value : { data: value },
23059
+ ...isRecord12(value) ? value : { data: value },
22014
23060
  step_id: stepId
22015
23061
  }));
22016
23062
  }
22017
23063
  return [];
22018
23064
  }
22019
23065
  function normalizeStepPlan(input, defaults) {
22020
- const stepId = stringValue3(input.step_id ?? input.stepId ?? defaults.stepId);
23066
+ const stepId = stringValue4(input.step_id ?? input.stepId ?? defaults.stepId);
22021
23067
  if (!stepId) {
22022
23068
  throw new Error("e2e step-run requires --step-id or data-profile steps[].step_id.");
22023
23069
  }
22024
23070
  const rawData = input.data ?? input.payload_template ?? input.payloadTemplate ?? input.form ?? input.values ?? {};
22025
- const data = isRecord10(rawData) ? rawData : {};
23071
+ const data = isRecord12(rawData) ? rawData : {};
22026
23072
  return {
22027
23073
  step_id: stepId,
22028
- action: stringValue3(input.action) ?? defaults.action,
22029
- ...stringValue3(input.label) ? { label: stringValue3(input.label) } : {},
22030
- ...stringValue3(input.target_step ?? input.targetStep) ? { target_step: stringValue3(input.target_step ?? input.targetStep) } : {},
22031
- ...stringValue3(input.comments) ?? defaults.comments ? { comments: stringValue3(input.comments) ?? defaults.comments } : {},
23074
+ action: stringValue4(input.action) ?? defaults.action,
23075
+ ...stringValue4(input.label) ? { label: stringValue4(input.label) } : {},
23076
+ ...stringValue4(input.target_step ?? input.targetStep) ? { target_step: stringValue4(input.target_step ?? input.targetStep) } : {},
23077
+ ...stringValue4(input.comments) ?? defaults.comments ? { comments: stringValue4(input.comments) ?? defaults.comments } : {},
22032
23078
  urgency: numberValue(input.urgency, defaults.urgency),
22033
23079
  data,
22034
23080
  expected_checks: normalizeExpectedChecks(input.expected_checks ?? input.expectedChecks)
@@ -22062,7 +23108,7 @@ function dataProfilePath(input) {
22062
23108
  if (!input?.startsWith("@")) {
22063
23109
  return void 0;
22064
23110
  }
22065
- return path12.resolve(input.slice(1));
23111
+ return path14.resolve(input.slice(1));
22066
23112
  }
22067
23113
  function refreshedStepTemplate(options) {
22068
23114
  return {
@@ -22086,15 +23132,15 @@ function refreshedStepTemplate(options) {
22086
23132
  variables: Object.keys(options.plan.data).filter((key) => !["project_id", "action", "urgency"].includes(key)),
22087
23133
  payload_template: options.plan.data,
22088
23134
  source_evidence: {
22089
- evidence_dir: path12.resolve(options.evidenceDir),
22090
- context: path12.basename(options.contextFile)
23135
+ evidence_dir: path14.resolve(options.evidenceDir),
23136
+ context: path14.basename(options.contextFile)
22091
23137
  }
22092
23138
  };
22093
23139
  }
22094
23140
  async function writeRefreshedCache(file, template) {
22095
- const out = path12.resolve(file);
22096
- await mkdir10(path12.dirname(out), { recursive: true });
22097
- await writeFile10(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
23141
+ const out = path14.resolve(file);
23142
+ await mkdir11(path14.dirname(out), { recursive: true });
23143
+ await writeFile11(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
22098
23144
  `, "utf8");
22099
23145
  return out;
22100
23146
  }
@@ -22117,7 +23163,7 @@ function blockedReason(context2, canSubmit) {
22117
23163
  return void 0;
22118
23164
  }
22119
23165
  function handoffUrlFromInput(input) {
22120
- const url = stringValue3(input.handoff_url ?? input.handoffUrl ?? input.url);
23166
+ const url = stringValue4(input.handoff_url ?? input.handoffUrl ?? input.url);
22121
23167
  if (!url) {
22122
23168
  throw new Error("handoff JSON must contain handoff_url, handoffUrl, or url.");
22123
23169
  }
@@ -22174,25 +23220,55 @@ test(${JSON.stringify(options.title)}, async ({ page }) => {
22174
23220
  async function writeBrowserTemplate(options) {
22175
23221
  const handoffUrl = handoffUrlFromInput(options.handoff);
22176
23222
  const assertFields = (options.assertFields ?? "").split(",").map((item) => item.trim()).filter(Boolean);
22177
- const out = path12.resolve(options.out);
22178
- await mkdir10(path12.dirname(out), { recursive: true });
22179
- await writeFile10(out, playwrightTemplate({
23223
+ const out = path14.resolve(options.out);
23224
+ await mkdir11(path14.dirname(out), { recursive: true });
23225
+ await writeFile11(out, playwrightTemplate({
22180
23226
  title: options.title ?? "BPMAX create page handoff submit",
22181
23227
  handoffUrl,
22182
23228
  assertFields,
22183
- evidenceDir: path12.resolve(options.evidenceDir)
23229
+ evidenceDir: path14.resolve(options.evidenceDir)
22184
23230
  }), "utf8");
22185
23231
  return { out, handoff_url: handoffUrl, assert_fields: assertFields };
22186
23232
  }
23233
+ async function updateAutomationFromRecordedTrace(options) {
23234
+ if (!options.caseId || !options.caseStepId) {
23235
+ throw new Error("--automation-out requires --case-id and --case-step-id");
23236
+ }
23237
+ const tracePath = path14.join(path14.resolve(options.evidenceDir), "browser-action-trace.json");
23238
+ const trace = await readOptionalJson(tracePath);
23239
+ if (!trace || !isRecord12(trace) || !Array.isArray(trace.actions) || !Array.isArray(trace.expected_checks) || !isRecord12(trace.page_fingerprint)) {
23240
+ throw new Error("browser-action-trace.json must contain page_fingerprint, actions, and expected_checks before automation can be generated");
23241
+ }
23242
+ const out = path14.resolve(options.automationOut);
23243
+ const existing = await readOptionalJson(out);
23244
+ const document2 = existing && isRecord12(existing) ? existing : { version: 1, ...options.scenario ? { scenario: options.scenario } : {}, steps: {} };
23245
+ if (!isRecord12(document2.steps)) document2.steps = {};
23246
+ document2.steps[automationStepKey(options.caseId, options.caseStepId)] = {
23247
+ runner: "browser_action",
23248
+ page_fingerprint: trace.page_fingerprint,
23249
+ actions: trace.actions,
23250
+ expected_checks: trace.expected_checks
23251
+ };
23252
+ const validated = validateBrowserAutomationDocument(document2);
23253
+ if (!validated.document || validated.issues.length > 0) {
23254
+ const details = validated.issues.map((issue3) => `[${issue3.rule_id}] ${issue3.message}`).join("\n");
23255
+ throw new Error(`recorded browser automation requires review:
23256
+ ${details}`);
23257
+ }
23258
+ await mkdir11(path14.dirname(out), { recursive: true });
23259
+ await writeFile11(out, `${JSON.stringify(document2, null, 2)}
23260
+ `, "utf8");
23261
+ return out;
23262
+ }
22187
23263
  function scenarioRecords(plan) {
22188
23264
  const records = plan.records;
22189
23265
  if (!Array.isArray(records)) {
22190
23266
  return [];
22191
23267
  }
22192
- return records.filter(isRecord10);
23268
+ return records.filter(isRecord12);
22193
23269
  }
22194
23270
  function recordKey(record, index) {
22195
- return stringValue3(record.demo_no ?? record.id ?? record.case_id ?? record.subject) ?? `record-${index + 1}`;
23271
+ return stringValue4(record.demo_no ?? record.id ?? record.case_id ?? record.subject) ?? `record-${index + 1}`;
22196
23272
  }
22197
23273
  function registerE2eCommands(program2) {
22198
23274
  const e2e = program2.command("e2e").description("BPMAX E2E acceleration helpers with evidence-first safety gates");
@@ -22551,7 +23627,7 @@ function registerE2eCommands(program2) {
22551
23627
  mode: "handoff_command_hint",
22552
23628
  browser: options.browser,
22553
23629
  next_command: `bpmax-cli project create ${flowFlag}${jsonFlag}${profileFlag} --handoff-only --format json > handoff.json`,
22554
- next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path12.resolve(options.evidenceDir)} --format json`,
23630
+ next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path14.resolve(options.evidenceDir)} --format json`,
22555
23631
  note: "create-page-submit does not raw-create a project. First generate a handoff URL, then execute the generated browser template and keep screenshots/result JSON as evidence."
22556
23632
  });
22557
23633
  return;
@@ -22573,7 +23649,7 @@ function registerE2eCommands(program2) {
22573
23649
  browser_verified: false,
22574
23650
  browser: options.browser,
22575
23651
  ...generated,
22576
- evidence_dir: path12.resolve(options.evidenceDir),
23652
+ evidence_dir: path14.resolve(options.evidenceDir),
22577
23653
  next_command: `npx playwright test ${generated.out}`,
22578
23654
  note: "This command does not raw-create a project. Run the generated Playwright script against a logged-in browser context and keep its screenshots/result JSON as browser evidence."
22579
23655
  });
@@ -22617,15 +23693,15 @@ function registerE2eCommands(program2) {
22617
23693
  if (!result) {
22618
23694
  throw new Error(`Flow ${options.flowId} was not found.`);
22619
23695
  }
22620
- const sourceUpdateTime = stringValue3(result.update_time ?? result.updateTime ?? result.updated_at ?? result.updatedAt);
22621
- const cacheKey = createHash6("sha256").update(JSON.stringify({
23696
+ const sourceUpdateTime = stringValue4(result.update_time ?? result.updateTime ?? result.updated_at ?? result.updatedAt);
23697
+ const cacheKey = createHash7("sha256").update(JSON.stringify({
22622
23698
  flow_id: options.flowId,
22623
23699
  update_time: sourceUpdateTime,
22624
23700
  template_id: result.template_id ?? result.templateId
22625
23701
  })).digest("hex").slice(0, 16);
22626
23702
  const file = flowCachePath(profile.name, options.flowId);
22627
- await mkdir10(path12.dirname(file), { recursive: true });
22628
- await writeFile10(file, `${JSON.stringify(redactAuditValue({
23703
+ await mkdir11(path14.dirname(file), { recursive: true });
23704
+ await writeFile11(file, `${JSON.stringify(redactAuditValue({
22629
23705
  cache_key: cacheKey,
22630
23706
  cached_at: (/* @__PURE__ */ new Date()).toISOString(),
22631
23707
  profile: profile.name,
@@ -22644,6 +23720,10 @@ function registerE2eCommands(program2) {
22644
23720
  });
22645
23721
  });
22646
23722
  const browserTemplate = e2e.command("browser-template").description("Generate reusable browser automation templates");
23723
+ e2e.command("browser-run").description("Execute the current browser_action step deterministically with Playwright and record current-run evidence").requiredOption("--automation <file>", "Scenario automation.json").requiredOption("--execution-manifest <file>", "Current formal test-suite execution manifest").option("--case-id <id>", "Expected current case id; normally resolved from the manifest").option("--case-step-id <id>", "Expected current case step id; normally resolved from the manifest").option("--data-profile <json>", "Current-run JSON variables or @file").option("--base-url <url>", "Browser base URL; defaults to the manifest profile origin").option("--profile <profile>", "Profile name; must match the execution manifest").option("--cdp-endpoint <url>", "Connect to an existing authenticated Chrome CDP endpoint").option("--storage-state <file>", "Playwright storage state JSON for a new browser context").option("--user-data-dir <dir>", "Persistent Chrome user data directory").option("--executable-path <file>", "Chrome/Chromium executable path").option("--headed", "Run a visible browser window").option("--resume", "Continue only the same unfinished manifest after earlier steps passed").option("--until-blocked", "Continue consecutive browser_action steps in this manifest until another runner or a failure is reached").option("--format <format>", "Output format", "json").action(async (options) => {
23724
+ const result = await runBrowserAutomation(options);
23725
+ printResult(options.format, result);
23726
+ });
22647
23727
  browserTemplate.command("create-form").description("Generate a Playwright template for a BPMAX create-page handoff").requiredOption("--handoff-json <json>", "Handoff JSON from project create --handoff-only or @file").option("--assert-fields <fields>", "Comma-separated labels/field keys that must appear before submit").option("--out <file>", "Playwright script output", `.codex/e2e-scripts/create-form-${timestampSlug()}.spec.ts`).option("--evidence-dir <dir>", "Browser evidence directory", `.codex/tmp/e2e/create-form-${timestampSlug()}`).option("--format <format>", "Output format", "json").action(async (options) => {
22648
23728
  const handoff = await parseJsonInput(options.handoffJson, "--handoff-json");
22649
23729
  const generated = await writeBrowserTemplate({
@@ -22655,12 +23735,12 @@ function registerE2eCommands(program2) {
22655
23735
  printResult(options.format, {
22656
23736
  ok: true,
22657
23737
  ...generated,
22658
- evidence_dir: path12.resolve(options.evidenceDir),
23738
+ evidence_dir: path14.resolve(options.evidenceDir),
22659
23739
  next_command: `npx playwright test ${generated.out}`
22660
23740
  });
22661
23741
  });
22662
- e2e.command("record-from-evidence").description("Create a reusable E2E template from an evidence directory").option("--project-id <projectId>", "Project id for step evidence").option("--step-id <stepId>", "Step id for step evidence").requiredOption("--evidence-dir <dir>", "Evidence directory").requiredOption("--out <file>", "Template output JSON").option("--name <name>", "Template name").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--case-id <id>", "Formal test-suite case id").option("--case-step-id <id>", "Formal test-suite case step id").option("--diagnostic", "Run without a formal manifest; result cannot be used as pass evidence").option("--format <format>", "Output format", "json").action(async (options) => {
22663
- await requireE2eExecutionBinding(options, ["browser", "e2e_create_page", "e2e_step_run", "observe"]);
23742
+ e2e.command("record-from-evidence").description("Create a reusable E2E template from an evidence directory").option("--project-id <projectId>", "Project id for step evidence").option("--step-id <stepId>", "Step id for step evidence").requiredOption("--evidence-dir <dir>", "Evidence directory").requiredOption("--out <file>", "Template output JSON").option("--automation-out <file>", "Merge browser-action-trace.json into scenario automation.json").option("--scenario <id>", "Scenario id stored in a newly created automation.json").option("--name <name>", "Template name").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--case-id <id>", "Formal test-suite case id").option("--case-step-id <id>", "Formal test-suite case step id").option("--diagnostic", "Run without a formal manifest; result cannot be used as pass evidence").option("--format <format>", "Output format", "json").action(async (options) => {
23743
+ await requireE2eExecutionBinding(options, ["browser", "browser_action", "e2e_create_page", "e2e_step_run", "observe"]);
22664
23744
  const files = await readdir5(options.evidenceDir).catch(() => []);
22665
23745
  const inferredStepId = options.stepId ?? files.map(inferStepIdFromEvidenceFile).find(Boolean);
22666
23746
  const contextFile = inferredStepId ? stepEvidenceFile(files, inferredStepId, "context") : void 0;
@@ -22668,13 +23748,13 @@ function registerE2eCommands(program2) {
22668
23748
  if (inferredStepId && !contextFile && !submitFile) {
22669
23749
  throw new Error(`No step evidence files found for step ${inferredStepId} in ${options.evidenceDir}.`);
22670
23750
  }
22671
- const context2 = contextFile ? await readOptionalJson(path12.join(options.evidenceDir, contextFile)) : null;
22672
- const submit = submitFile ? await readOptionalJson(path12.join(options.evidenceDir, submitFile)) : null;
22673
- const requirements = isRecord10(context2?.requirements) ? context2.requirements : {};
22674
- const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord10) : [];
22675
- const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord10) : [];
22676
- const requestData = isRecord10(submit?.request) && isRecord10(submit.request.data) ? submit.request.data : {};
22677
- const recordedAction = stringValue3(requestData.action);
23751
+ const context2 = contextFile ? await readOptionalJson(path14.join(options.evidenceDir, contextFile)) : null;
23752
+ const submit = submitFile ? await readOptionalJson(path14.join(options.evidenceDir, submitFile)) : null;
23753
+ const requirements = isRecord12(context2?.requirements) ? context2.requirements : {};
23754
+ const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord12) : [];
23755
+ const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord12) : [];
23756
+ const requestData = isRecord12(submit?.request) && isRecord12(submit.request.data) ? submit.request.data : {};
23757
+ const recordedAction = stringValue4(requestData.action);
22678
23758
  const expectedChecks = buildExpectedChecks({
22679
23759
  context: context2,
22680
23760
  requirements: {
@@ -22712,16 +23792,16 @@ function registerE2eCommands(program2) {
22712
23792
  variables: Object.keys(requestData).filter((key) => !["project_id", "action", "urgency"].includes(key)),
22713
23793
  payload_template: requestData,
22714
23794
  source_evidence: {
22715
- evidence_dir: path12.resolve(options.evidenceDir),
23795
+ evidence_dir: path14.resolve(options.evidenceDir),
22716
23796
  ...contextFile ? { context: contextFile } : {},
22717
23797
  ...submitFile ? { submit: submitFile } : {}
22718
23798
  }
22719
23799
  } : {
22720
- name: options.name ?? path12.basename(path12.resolve(options.evidenceDir)),
23800
+ name: options.name ?? path14.basename(path14.resolve(options.evidenceDir)),
22721
23801
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
22722
23802
  submit_mode: "browser_evidence_bootstrap",
22723
23803
  source_evidence: {
22724
- evidence_dir: path12.resolve(options.evidenceDir),
23804
+ evidence_dir: path14.resolve(options.evidenceDir),
22725
23805
  files: evidenceFiles
22726
23806
  },
22727
23807
  reuse_requirements: [
@@ -22734,21 +23814,46 @@ function registerE2eCommands(program2) {
22734
23814
  template.result = "diagnostic";
22735
23815
  template.diagnostic = true;
22736
23816
  }
22737
- const out = path12.resolve(options.out);
22738
- await mkdir10(path12.dirname(out), { recursive: true });
22739
- await writeFile10(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
23817
+ const out = path14.resolve(options.out);
23818
+ await mkdir11(path14.dirname(out), { recursive: true });
23819
+ await writeFile11(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
22740
23820
  `, "utf8");
22741
- await appendE2eExecutionEvidence(options, out, ["browser", "e2e_create_page", "e2e_step_run", "observe"]);
23821
+ const automationOut = options.automationOut ? await updateAutomationFromRecordedTrace({
23822
+ evidenceDir: options.evidenceDir,
23823
+ automationOut: options.automationOut,
23824
+ scenario: options.scenario,
23825
+ caseId: options.caseId,
23826
+ caseStepId: options.caseStepId
23827
+ }) : void 0;
23828
+ await appendE2eExecutionEvidence(options, out, ["browser", "browser_action", "e2e_create_page", "e2e_step_run", "observe"]);
22742
23829
  printResult(options.format, {
22743
23830
  ok: true,
22744
23831
  result: options.diagnostic ? "diagnostic" : "reusable_template_recorded",
22745
23832
  diagnostic: Boolean(options.diagnostic),
22746
23833
  out,
23834
+ ...automationOut ? { automation_out: automationOut } : {},
22747
23835
  template
22748
23836
  });
22749
23837
  });
22750
23838
  const scenario = e2e.command("scenario").description("Run resumable BPMAX E2E scenario plans");
23839
+ scenario.command("execute").description("Execute deterministic browser_action steps for the current formal scenario run").requiredOption("--plan <file>", "Scenario plan JSON file").requiredOption("--automation <file>", "Scenario automation.json").requiredOption("--execution-manifest <file>", "Current formal test-suite execution manifest").option("--data-profile <json>", "Current-run JSON variables or @file").option("--base-url <url>", "Browser base URL; defaults to the manifest profile origin").option("--profile <profile>", "Profile name; must match the execution manifest").option("--cdp-endpoint <url>", "Connect to an existing authenticated Chrome CDP endpoint").option("--storage-state <file>", "Playwright storage state JSON").option("--user-data-dir <dir>", "Persistent Chrome user data directory").option("--executable-path <file>", "Chrome/Chromium executable path").option("--headed", "Run a visible browser window").option("--resume", "Continue only the same unfinished manifest").option("--until-blocked", "Continue consecutive browser_action steps until another runner or failure").option("--format <format>", "Output format", "json").action(async (options) => {
23840
+ const plan = await parseJsonFileOrInput(options.plan, "--plan");
23841
+ const state = await nextTestSuiteRunStep(options.executionManifest, options.profile);
23842
+ const execution = isRecord12(state.execution) ? state.execution : {};
23843
+ if (stringValue4(plan.scenario) && stringValue4(execution.scenario_id) !== stringValue4(plan.scenario)) {
23844
+ throw new Error(`e2e.scenario.plan_mismatch: plan scenario ${stringValue4(plan.scenario)} does not match execution manifest ${stringValue4(execution.scenario_id)}`);
23845
+ }
23846
+ const result = await runBrowserAutomation(options);
23847
+ printResult(options.format, {
23848
+ ...result,
23849
+ scenario: plan.scenario,
23850
+ plan: path14.resolve(options.plan)
23851
+ });
23852
+ });
22751
23853
  scenario.command("run").description("Validate or dry-run a scenario plan and produce a resumable status matrix").requiredOption("--plan <file>", "Scenario plan JSON file").option("--from <id>", "Start record id/demo_no").option("--to <id>", "End record id/demo_no").option("--resume", "Skip records already marked complete in existing status").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--case-id <id>", "Formal test-suite case id").option("--case-step-id <id>", "Formal test-suite case step id").option("--diagnostic", "Run without a formal manifest; result cannot be used as pass evidence").option("--evidence-dir <dir>", "Scenario evidence directory", `.codex/tmp/e2e/scenario-${timestampSlug()}`).option("--format <format>", "Output format", "json").action(async (options) => {
23854
+ if (options.resume) {
23855
+ throw new Error("e2e.scenario.run_resume_not_execution: scenario run only produces a dry-run matrix and cannot skip completed cases. Use test-suite run start plus e2e scenario execute for a real rerun.");
23856
+ }
22752
23857
  await requireE2eExecutionBinding(options, ["observe"]);
22753
23858
  const plan = await parseJsonFileOrInput(options.plan, "--plan");
22754
23859
  const records = scenarioRecords(plan);
@@ -22761,7 +23866,7 @@ function registerE2eCommands(program2) {
22761
23866
  });
22762
23867
  const status = selected.map((record, index) => ({
22763
23868
  record: recordKey(record, index),
22764
- subject: stringValue3(record.subject),
23869
+ subject: stringValue4(record.subject),
22765
23870
  status: "bootstrap_required",
22766
23871
  next_action: "If no reusable cache/template exists yet, run the first real browser create-page-submit or safe step-run for this record, save evidence, then run e2e record-from-evidence before repeat runs."
22767
23872
  }));
@@ -22780,6 +23885,8 @@ function registerE2eCommands(program2) {
22780
23885
  result: options.diagnostic ? "diagnostic" : "bootstrap_required",
22781
23886
  diagnostic: Boolean(options.diagnostic),
22782
23887
  dry_run: true,
23888
+ deprecated_execution_path: true,
23889
+ next_command: "Use `bpmax-cli test-suite run start ...` and then `bpmax-cli e2e scenario execute ...` for deterministic execution.",
22783
23890
  scenario: plan.scenario,
22784
23891
  profile: plan.profile,
22785
23892
  workspace: plan.workspace,
@@ -22793,11 +23900,11 @@ function registerE2eCommands(program2) {
22793
23900
  }
22794
23901
 
22795
23902
  // src/core/project-search.ts
22796
- function isRecord11(value) {
23903
+ function isRecord13(value) {
22797
23904
  return typeof value === "object" && value !== null && !Array.isArray(value);
22798
23905
  }
22799
23906
  function hasRawProjectSearchBody(value) {
22800
- return isRecord11(value) && Object.prototype.hasOwnProperty.call(value, "body");
23907
+ return isRecord13(value) && Object.prototype.hasOwnProperty.call(value, "body");
22801
23908
  }
22802
23909
  function assertProjectSearchBody(value) {
22803
23910
  if (hasRawProjectSearchBody(value)) {
@@ -22811,13 +23918,13 @@ function isProjectListEsQuery(value) {
22811
23918
  }
22812
23919
  function splitProjectListPagination(body, options) {
22813
23920
  const data = { ...body };
22814
- const normalizePositiveInteger = (value, path17) => {
23921
+ const normalizePositiveInteger = (value, path19) => {
22815
23922
  if (typeof value === "string" && value.trim() === "") {
22816
- throw new Error(`project search ${path17} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32\u3002`);
23923
+ throw new Error(`project search ${path19} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32\u3002`);
22817
23924
  }
22818
23925
  const number = typeof value === "number" ? value : Number(value);
22819
23926
  if (!Number.isSafeInteger(number) || number < 1) {
22820
- throw new Error(`project search ${path17} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u503C\u4E3A ${String(value)}\u3002`);
23927
+ throw new Error(`project search ${path19} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u503C\u4E3A ${String(value)}\u3002`);
22821
23928
  }
22822
23929
  return number;
22823
23930
  };
@@ -22948,7 +24055,7 @@ function registerFlowCommands(program2) {
22948
24055
  const client = createApiClient(profile);
22949
24056
  if (options.flowType) {
22950
24057
  const bindings = await getWorkspaceFlowBindings(client, profile, options);
22951
- const path17 = options.flowKey ? "/flow/options" : "/flow/flow_type";
24058
+ const path19 = options.flowKey ? "/flow/options" : "/flow/flow_type";
22952
24059
  const params = options.flowKey ? {
22953
24060
  detail: "1"
22954
24061
  } : {
@@ -22958,7 +24065,7 @@ function registerFlowCommands(program2) {
22958
24065
  const result2 = await apiRequest(
22959
24066
  client,
22960
24067
  "GET",
22961
- path17,
24068
+ path19,
22962
24069
  {
22963
24070
  params
22964
24071
  }
@@ -23194,7 +24301,7 @@ function registerInitCommand(program2, deps = {}) {
23194
24301
  }
23195
24302
 
23196
24303
  // src/commands/issue.ts
23197
- import { readFile as readFile14 } from "fs/promises";
24304
+ import { readFile as readFile16 } from "fs/promises";
23198
24305
 
23199
24306
  // src/core/issues.ts
23200
24307
  import axios8, { AxiosHeaders as AxiosHeaders3 } from "axios";
@@ -23370,7 +24477,7 @@ async function readDescription(options) {
23370
24477
  if (!options.descriptionFile) {
23371
24478
  return options.description;
23372
24479
  }
23373
- return readFile14(options.descriptionFile, "utf8");
24480
+ return readFile16(options.descriptionFile, "utf8");
23374
24481
  }
23375
24482
  function parseAssigneeIds(values) {
23376
24483
  return (values || []).flatMap(
@@ -23469,10 +24576,10 @@ async function parseOptionalJson(input, label) {
23469
24576
  }
23470
24577
  return parseJsonInput(input, label);
23471
24578
  }
23472
- async function memoryRequest(options, method, path17, capability, data, params) {
24579
+ async function memoryRequest(options, method, path19, capability, data, params) {
23473
24580
  const profile = resolveProfile(await loadConfig(), options.profile);
23474
24581
  const client = createApiClient(profile);
23475
- return apiRequest(client, method, path17, {
24582
+ return apiRequest(client, method, path19, {
23476
24583
  capability,
23477
24584
  data: redactAuditValue(data),
23478
24585
  params: params ? redactAuditValue(params) : void 0
@@ -23527,7 +24634,7 @@ function registerMemoryCommands(program2) {
23527
24634
  }
23528
24635
 
23529
24636
  // src/commands/matrix.ts
23530
- import { readFile as readFile15 } from "fs/promises";
24637
+ import { readFile as readFile17 } from "fs/promises";
23531
24638
  var UUID_VALUE_PATTERN2 = /\b[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}\b/i;
23532
24639
  var UUID_PATH_PATTERN = /uuid'[^'"\s/]+/i;
23533
24640
  async function parseSeedRules(input) {
@@ -23535,7 +24642,7 @@ async function parseSeedRules(input) {
23535
24642
  if (source === "") {
23536
24643
  throw new Error("--rules file path is empty.");
23537
24644
  }
23538
- const raw = source ? await readFile15(source, "utf8") : input;
24645
+ const raw = source ? await readFile17(source, "utf8") : input;
23539
24646
  let parsed;
23540
24647
  try {
23541
24648
  parsed = JSON.parse(raw);
@@ -23554,15 +24661,15 @@ async function parseSeedRules(input) {
23554
24661
  });
23555
24662
  return rules;
23556
24663
  }
23557
- function collectUuidPaths(value, path17 = "$") {
24664
+ function collectUuidPaths(value, path19 = "$") {
23558
24665
  if (typeof value === "string") {
23559
- return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path17] : [];
24666
+ return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path19] : [];
23560
24667
  }
23561
24668
  if (Array.isArray(value)) {
23562
- return value.flatMap((item, index) => collectUuidPaths(item, `${path17}[${index}]`));
24669
+ return value.flatMap((item, index) => collectUuidPaths(item, `${path19}[${index}]`));
23563
24670
  }
23564
24671
  if (typeof value === "object" && value !== null) {
23565
- return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path17}.${key}`));
24672
+ return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path19}.${key}`));
23566
24673
  }
23567
24674
  return [];
23568
24675
  }
@@ -23585,20 +24692,20 @@ function isEmptyApproverValue(value) {
23585
24692
  function shellQuote7(value) {
23586
24693
  return `'${value.replace(/'/g, `'\\''`)}'`;
23587
24694
  }
23588
- var isRecord12 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24695
+ var isRecord14 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
23589
24696
  function dataArray(value) {
23590
24697
  if (Array.isArray(value)) return value;
23591
- if (isRecord12(value) && Array.isArray(value.data)) return value.data;
23592
- if (isRecord12(value) && Array.isArray(value.list)) return value.list;
23593
- if (isRecord12(value) && Array.isArray(value.rows)) return value.rows;
24698
+ if (isRecord14(value) && Array.isArray(value.data)) return value.data;
24699
+ if (isRecord14(value) && Array.isArray(value.list)) return value.list;
24700
+ if (isRecord14(value) && Array.isArray(value.rows)) return value.rows;
23594
24701
  return [];
23595
24702
  }
23596
24703
  function predictedNodes(value) {
23597
- if (!isRecord12(value)) return [];
23598
- return dataArray(value.predicted_nodes).filter(isRecord12);
24704
+ if (!isRecord14(value)) return [];
24705
+ return dataArray(value.predicted_nodes).filter(isRecord14);
23599
24706
  }
23600
24707
  function safePredictedOwners(value) {
23601
- return (Array.isArray(value) ? value : []).filter(isRecord12).map((owner) => ({
24708
+ return (Array.isArray(value) ? value : []).filter(isRecord14).map((owner) => ({
23602
24709
  id: owner.id ?? owner.user_id ?? owner.owner_id,
23603
24710
  name: owner.name ?? null
23604
24711
  }));
@@ -23613,7 +24720,7 @@ async function fetchAllMatrixRuleRecords(client, flowType) {
23613
24720
  data: { flow_type: flowType, page, page_size: pageSize },
23614
24721
  capability: "project.list"
23615
24722
  });
23616
- const rows2 = dataArray(result).filter(isRecord12);
24723
+ const rows2 = dataArray(result).filter(isRecord14);
23617
24724
  records.push(...rows2);
23618
24725
  const total = Number(result.count ?? result.total ?? records.length);
23619
24726
  if (rows2.length < pageSize || records.length >= total) break;
@@ -23632,23 +24739,23 @@ async function hydrateMatrixRuleRecords(client, records) {
23632
24739
  for (let index = 0; index < records.length; index += 10) {
23633
24740
  const chunk = records.slice(index, index + 10);
23634
24741
  hydrated.push(...await Promise.all(chunk.map(async (record) => {
23635
- if (isRecord12(record.metaForm) || Array.isArray(record.formList)) return record;
24742
+ if (isRecord14(record.metaForm) || Array.isArray(record.formList)) return record;
23636
24743
  const id = Number(record.id ?? record.project_id);
23637
24744
  return Number.isSafeInteger(id) && id > 0 ? apiRequest(client, "GET", `/project/${id}`) : record;
23638
24745
  })));
23639
24746
  }
23640
24747
  return hydrated;
23641
24748
  }
23642
- function collectMatrixOwnerPaths(value, path17 = "$") {
24749
+ function collectMatrixOwnerPaths(value, path19 = "$") {
23643
24750
  if (Array.isArray(value)) {
23644
- return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path17}[${index}]`));
24751
+ return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path19}[${index}]`));
23645
24752
  }
23646
- if (!isRecord12(value)) {
24753
+ if (!isRecord14(value)) {
23647
24754
  return [];
23648
24755
  }
23649
24756
  const matches = [];
23650
24757
  Object.entries(value).forEach(([key, child]) => {
23651
- const childPath = `${path17}.${key}`;
24758
+ const childPath = `${path19}.${key}`;
23652
24759
  if (key.includes("matrix_owner") || typeof child === "string" && child.includes("matrix_owner")) {
23653
24760
  matches.push({ path: childPath, value: child });
23654
24761
  }
@@ -23657,25 +24764,25 @@ function collectMatrixOwnerPaths(value, path17 = "$") {
23657
24764
  return matches;
23658
24765
  }
23659
24766
  function projectFormKeys(project) {
23660
- const metaForm = isRecord12(project.metaForm) ? project.metaForm : {};
24767
+ const metaForm = isRecord14(project.metaForm) ? project.metaForm : {};
23661
24768
  const values = dataArray(metaForm.value ?? project.formList);
23662
- return values.filter(isRecord12).map((item) => String(item.key ?? item.field_key ?? "")).filter(Boolean);
24769
+ return values.filter(isRecord14).map((item) => String(item.key ?? item.field_key ?? "")).filter(Boolean);
23663
24770
  }
23664
24771
  function findFlowNode2(flow, nodeId) {
23665
- const data = isRecord12(flow.data) ? flow.data : {};
23666
- return dataArray(data.nodes).filter(isRecord12).find((node) => String(node.id ?? node.key ?? node.flow_step_id ?? "") === nodeId);
24772
+ const data = isRecord14(flow.data) ? flow.data : {};
24773
+ return dataArray(data.nodes).filter(isRecord14).find((node) => String(node.id ?? node.key ?? node.flow_step_id ?? "") === nodeId);
23667
24774
  }
23668
24775
  function flowCategory(flow) {
23669
- const data = isRecord12(flow.data) ? flow.data : {};
23670
- const meta = isRecord12(data.meta) ? data.meta : {};
24776
+ const data = isRecord14(flow.data) ? flow.data : {};
24777
+ const meta = isRecord14(data.meta) ? data.meta : {};
23671
24778
  return String(flow.category ?? data.category ?? meta.category ?? "");
23672
24779
  }
23673
24780
  function hasIdentifier(value) {
23674
24781
  return value !== void 0 && value !== null && String(value).trim() !== "" && String(value) !== "0";
23675
24782
  }
23676
24783
  function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], datasets = [], workspaceBound = false) {
23677
- const data = isRecord12(flow.data) ? flow.data : {};
23678
- const meta = isRecord12(data.meta) ? data.meta : {};
24784
+ const data = isRecord14(flow.data) ? flow.data : {};
24785
+ const meta = isRecord14(data.meta) ? data.meta : {};
23679
24786
  const refs = {
23680
24787
  form_template_id: meta.form_template ?? flow.form_template_id,
23681
24788
  list_template_ids: listTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier),
@@ -23716,7 +24823,7 @@ function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], datase
23716
24823
  suggestion: "\u4ECE\u6700\u65B0 workspace-flow \u56DE\u8BFB merge \u540E\u901A\u8FC7 typed CLI \u63D0\u4EA4\u7ED1\u5B9A\u3002"
23717
24824
  });
23718
24825
  }
23719
- const nodes = dataArray(data.nodes).filter(isRecord12);
24826
+ const nodes = dataArray(data.nodes).filter(isRecord14);
23720
24827
  const activeNodes = nodes.filter((node) => {
23721
24828
  const name = String(node.name ?? "").trim();
23722
24829
  return name === "\u751F\u6548\u4E2D" || name === "\u8FDB\u884C\u4E2D" || Number(node.status) === 1;
@@ -23765,10 +24872,10 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
23765
24872
  apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: flowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
23766
24873
  apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
23767
24874
  ]);
23768
- const flowData = isRecord12(flow.data) ? flow.data : {};
23769
- const meta = isRecord12(flowData.meta) ? flowData.meta : {};
23770
- const listRows = dataArray(listResult).filter(isRecord12);
23771
- const filterRows = dataArray(filterResult).filter(isRecord12);
24875
+ const flowData = isRecord14(flow.data) ? flow.data : {};
24876
+ const meta = isRecord14(flowData.meta) ? flowData.meta : {};
24877
+ const listRows = dataArray(listResult).filter(isRecord14);
24878
+ const filterRows = dataArray(filterResult).filter(isRecord14);
23772
24879
  const listIds = uniqueIds([meta.table_list_template, ...listRows.map((item) => item.id ?? item.flow_page_template_id)]);
23773
24880
  const filterIds = uniqueIds([meta.table_filter_template, ...filterRows.map((item) => item.id ?? item.flow_page_template_id)]);
23774
24881
  const formId = String(meta.form_template ?? flow.form_template_id ?? "");
@@ -23786,7 +24893,7 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
23786
24893
  if (strict) {
23787
24894
  assertNoMatrixErrors(summary.errors);
23788
24895
  }
23789
- const formRecord = isRecord12(form) ? form : {};
24896
+ const formRecord = isRecord14(form) ? form : {};
23790
24897
  const exactReadback = {
23791
24898
  flow: { id: flowType, readback_hash: matrixHash(flow), ...includeRaw ? { readback: flow } : {} },
23792
24899
  form_template: { id: formId, draft_id: formRecord.origin_template_id ?? formRecord.id ?? null, readback_hash: matrixHash(formRecord), ...includeRaw ? { readback: formRecord } : {} },
@@ -23798,8 +24905,8 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
23798
24905
  return { ok: summary.errors.length === 0, domain: "approval-matrix", action: "app.inspect", flow_type: flowType, workspace, ...summary, exact_readback: exactReadback };
23799
24906
  }
23800
24907
  function workspaceHasFlow(value, flowType) {
23801
- if (!isRecord12(value)) return false;
23802
- const rows2 = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord12) : isRecord12(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord12) : [];
24908
+ if (!isRecord14(value)) return false;
24909
+ const rows2 = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord14) : isRecord14(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord14) : [];
23803
24910
  return rows2.some((item) => String(item.flow_type ?? "") === flowType && Number(item.is_del ?? 0) === 0);
23804
24911
  }
23805
24912
  function matrixConsumerSummary(node, expectedMatrixFlowType) {
@@ -23815,8 +24922,8 @@ function matrixConsumerSummary(node, expectedMatrixFlowType) {
23815
24922
  });
23816
24923
  return { errors, owner: null, cc: null };
23817
24924
  }
23818
- const owner = isRecord12(node.matrix_owner) ? node.matrix_owner : null;
23819
- const cc = isRecord12(node.cc_matrix) ? node.cc_matrix : null;
24925
+ const owner = isRecord14(node.matrix_owner) ? node.matrix_owner : null;
24926
+ const cc = isRecord14(node.cc_matrix) ? node.cc_matrix : null;
23820
24927
  const normalizeFlowRef = (value) => String(value ?? "").trim().replace(/:$/, "");
23821
24928
  if (node.auto_range_type === "matrix") {
23822
24929
  if (!owner || !String(owner.flow ?? owner.matrix_flow_type ?? "").trim()) {
@@ -23847,16 +24954,16 @@ function matrixConsumerSummary(node, expectedMatrixFlowType) {
23847
24954
  return { errors, owner, cc };
23848
24955
  }
23849
24956
  function projectField(project, key) {
23850
- const metaForm = isRecord12(project.metaForm) ? project.metaForm : {};
23851
- const values = dataArray(metaForm.value ?? project.formList).filter(isRecord12);
24957
+ const metaForm = isRecord14(project.metaForm) ? project.metaForm : {};
24958
+ const values = dataArray(metaForm.value ?? project.formList).filter(isRecord14);
23852
24959
  const row = values.find((item) => String(item.key ?? item.field_key ?? "") === key);
23853
24960
  if (!row) return void 0;
23854
24961
  const value = row.value;
23855
- return isRecord12(value) && Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;
24962
+ return isRecord14(value) && Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;
23856
24963
  }
23857
24964
  function collectUserIds(value) {
23858
24965
  if (Array.isArray(value)) return [...new Set(value.flatMap(collectUserIds))];
23859
- if (isRecord12(value)) {
24966
+ if (isRecord14(value)) {
23860
24967
  const direct2 = Number(value.id ?? value.user_id ?? value.value);
23861
24968
  if (Number.isSafeInteger(direct2) && direct2 > 0) return [direct2];
23862
24969
  return [...new Set(Object.values(value).flatMap(collectUserIds))];
@@ -23877,7 +24984,7 @@ async function readMatrixApprovers(client, ids) {
23877
24984
  },
23878
24985
  capability: "user.readback"
23879
24986
  });
23880
- users.push(...dataArray(result).filter(isRecord12));
24987
+ users.push(...dataArray(result).filter(isRecord14));
23881
24988
  }
23882
24989
  return users;
23883
24990
  }
@@ -23961,7 +25068,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
23961
25068
  const matrixOwnerConfig = node ? collectMatrixOwnerPaths(node) : [];
23962
25069
  const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
23963
25070
  const owners = safePredictedOwners(predictedNode?.owners);
23964
- const ownerResolution = predictedNode && isRecord12(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
25071
+ const ownerResolution = predictedNode && isRecord14(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
23965
25072
  const projectFlowType = String(project.flow_type ?? "");
23966
25073
  const flowMatchesProject = !projectFlowType || projectFlowType === options.flowType;
23967
25074
  printResult(options.format, {
@@ -24052,14 +25159,14 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
24052
25159
  if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u5220\u9664\u77E9\u9635\u5E94\u7528\u3002");
24053
25160
  const definition = await inspectMatrixAppDefinition(profile, options.flowType, workspace, true, false);
24054
25161
  const exact = definition.exact_readback;
24055
- const listItems = Array.isArray(exact.list_templates) ? exact.list_templates.filter(isRecord12) : [];
24056
- const filterItems = Array.isArray(exact.filter_templates) ? exact.filter_templates.filter(isRecord12) : [];
24057
- const datasetItems = Array.isArray(exact.datasets) ? exact.datasets.filter(isRecord12) : [];
25162
+ const listItems = Array.isArray(exact.list_templates) ? exact.list_templates.filter(isRecord14) : [];
25163
+ const filterItems = Array.isArray(exact.filter_templates) ? exact.filter_templates.filter(isRecord14) : [];
25164
+ const datasetItems = Array.isArray(exact.datasets) ? exact.datasets.filter(isRecord14) : [];
24058
25165
  const datasetFieldIds = uniqueIds(datasetItems.flatMap((item) => {
24059
- const readback = isRecord12(item.readback) ? item.readback : {};
24060
- return Array.isArray(readback.dataSetFields) ? readback.dataSetFields.filter(isRecord12).map((field) => field.id) : [];
25166
+ const readback = isRecord14(item.readback) ? item.readback : {};
25167
+ return Array.isArray(readback.dataSetFields) ? readback.dataSetFields.filter(isRecord14).map((field) => field.id) : [];
24061
25168
  }));
24062
- const formItem = isRecord12(exact.form_template) ? exact.form_template : {};
25169
+ const formItem = isRecord14(exact.form_template) ? exact.form_template : {};
24063
25170
  const formDraftId = String(formItem.draft_id ?? formItem.id ?? "");
24064
25171
  const expectedConfirm = `delete matrix app ${options.flowType} from ${workspace}`;
24065
25172
  const plan = [
@@ -24121,8 +25228,8 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
24121
25228
  apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.matrixFlowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
24122
25229
  apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
24123
25230
  ]);
24124
- const listRows = dataArray(listResult).filter(isRecord12);
24125
- const filterRows = dataArray(filterResult).filter(isRecord12);
25231
+ const listRows = dataArray(listResult).filter(isRecord14);
25232
+ const filterRows = dataArray(filterResult).filter(isRecord14);
24126
25233
  const listTemplates = await Promise.all(uniqueIds(listRows.map((item) => item.id ?? item.flow_page_template_id)).map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.list_template.export" })));
24127
25234
  const filterTemplates = await Promise.all(uniqueIds(filterRows.map((item) => item.id ?? item.flow_page_template_id)).map((id) => apiRequest(client, "GET", `/flow_page_template/${encodeURIComponent(id)}?skip_i18n=true`, { capability: "config.filter_template.export" })));
24128
25235
  const datasetIds = uniqueIds([...listTemplates.map((item) => item.data_set_id), ...filterTemplates.map((item) => item.data_set_id)]);
@@ -24156,7 +25263,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
24156
25263
  }
24157
25264
  const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
24158
25265
  const predictedOwners = safePredictedOwners(predictedNode?.owners);
24159
- const ownerResolution = predictedNode && isRecord12(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
25266
+ const ownerResolution = predictedNode && isRecord14(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
24160
25267
  if (ownerResolution.status === "error") {
24161
25268
  errors.push({ code: "matrix.consumer.owner_resolution_error", rule_id: "matrix.consumer.owner_resolution_error", domain: "approval-matrix", path: "$.predicted_nodes[].owner_resolution", message: `\u7EDF\u4E00 owner resolver \u6267\u884C\u5931\u8D25\uFF1A${String(ownerResolution.error_code ?? "unknown")}\u3002`, suggestion: "\u4FEE\u590D\u77E9\u9635/\u5B57\u6BB5/\u89D2\u8272 owner \u89E3\u6790\u9519\u8BEF\u540E\u91CD\u65B0 verify\uFF0C\u4E0D\u5F97\u5C06\u7A7A owners \u5F53\u6210\u6B63\u5E38\u65E0\u4EBA\u3002" });
24162
25269
  } else if (!predictedNode || predictedOwners.length === 0) {
@@ -24180,13 +25287,13 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
24180
25287
  }
24181
25288
 
24182
25289
  // src/commands/organization.ts
24183
- function isRecord13(value) {
25290
+ function isRecord15(value) {
24184
25291
  return typeof value === "object" && value !== null && !Array.isArray(value);
24185
25292
  }
24186
25293
  function rows(value) {
24187
- if (Array.isArray(value)) return value.filter(isRecord13);
24188
- if (!isRecord13(value)) return [];
24189
- if (Array.isArray(value.data)) return value.data.filter(isRecord13);
25294
+ if (Array.isArray(value)) return value.filter(isRecord15);
25295
+ if (!isRecord15(value)) return [];
25296
+ if (Array.isArray(value.data)) return value.data.filter(isRecord15);
24190
25297
  return value.id ? [value] : [];
24191
25298
  }
24192
25299
  function positiveId(value, errorCode) {
@@ -24210,7 +25317,7 @@ function safeDepartment(group) {
24210
25317
  function departmentRows(value) {
24211
25318
  const result = [];
24212
25319
  const visit = (item) => {
24213
- if (!isRecord13(item)) return;
25320
+ if (!isRecord15(item)) return;
24214
25321
  if (item.id !== void 0) result.push(safeDepartment(item));
24215
25322
  if (Array.isArray(item.children)) item.children.forEach(visit);
24216
25323
  };
@@ -24219,7 +25326,7 @@ function departmentRows(value) {
24219
25326
  }
24220
25327
  function relationDepartments(value) {
24221
25328
  if (!Array.isArray(value)) return [];
24222
- return value.filter(isRecord13).map(safeDepartment);
25329
+ return value.filter(isRecord15).map(safeDepartment);
24223
25330
  }
24224
25331
  function safeUser(user) {
24225
25332
  const status = user.status === void 0 ? null : Number(user.status);
@@ -24266,8 +25373,8 @@ async function readDepartments(client, ids) {
24266
25373
  function pathIds(departments) {
24267
25374
  const ids = /* @__PURE__ */ new Set();
24268
25375
  for (const department of departments) {
24269
- const path17 = String(department.path ?? "");
24270
- for (const part of path17.split(/[|,]/)) {
25376
+ const path19 = String(department.path ?? "");
25377
+ for (const part of path19.split(/[|,]/)) {
24271
25378
  const id = Number(part);
24272
25379
  if (Number.isSafeInteger(id) && id > 0) ids.add(id);
24273
25380
  }
@@ -24277,7 +25384,7 @@ function pathIds(departments) {
24277
25384
  function mainDepartmentId(raw) {
24278
25385
  for (const key of ["main_department_id", "main_group_id", "main_department"]) {
24279
25386
  const value = raw[key];
24280
- if (isRecord13(value)) {
25387
+ if (isRecord15(value)) {
24281
25388
  const id2 = Number(value.id);
24282
25389
  if (Number.isSafeInteger(id2) && id2 > 0) return id2;
24283
25390
  }
@@ -24289,7 +25396,7 @@ function mainDepartmentId(raw) {
24289
25396
  function branchId(raw) {
24290
25397
  for (const key of ["branch_id", "branch_group_id", "branch"]) {
24291
25398
  const value = raw[key];
24292
- if (isRecord13(value)) {
25399
+ if (isRecord15(value)) {
24293
25400
  const id2 = Number(value.id);
24294
25401
  if (Number.isSafeInteger(id2) && id2 > 0) return id2;
24295
25402
  }
@@ -24807,15 +25914,15 @@ async function promptProjectCreateForm(input) {
24807
25914
  }
24808
25915
 
24809
25916
  // src/core/project-form.ts
24810
- function isRecord14(value) {
25917
+ function isRecord16(value) {
24811
25918
  return typeof value === "object" && value !== null && !Array.isArray(value);
24812
25919
  }
24813
25920
  function clone(value) {
24814
25921
  return JSON.parse(JSON.stringify(value));
24815
25922
  }
24816
25923
  function getFlowFormTemplateId(flowDetail) {
24817
- const data = isRecord14(flowDetail?.data) ? flowDetail.data : void 0;
24818
- const meta = isRecord14(data?.meta) ? data.meta : void 0;
25924
+ const data = isRecord16(flowDetail?.data) ? flowDetail.data : void 0;
25925
+ const meta = isRecord16(data?.meta) ? data.meta : void 0;
24819
25926
  const templateId = meta?.form_template;
24820
25927
  if (typeof templateId === "number" && Number.isFinite(templateId)) {
24821
25928
  return templateId;
@@ -24840,7 +25947,7 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
24840
25947
  if (Array.isArray(value)) {
24841
25948
  return value.some((item) => hasAutoInitLambda(item, seen));
24842
25949
  }
24843
- if (!isRecord14(value)) {
25950
+ if (!isRecord16(value)) {
24844
25951
  return false;
24845
25952
  }
24846
25953
  if (seen.has(value)) {
@@ -24855,14 +25962,14 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
24855
25962
  function setControlValue(control, value) {
24856
25963
  const next = clone(control);
24857
25964
  next.value = {
24858
- ...isRecord14(next.value) ? next.value : {},
25965
+ ...isRecord16(next.value) ? next.value : {},
24859
25966
  type: next.value?.type ?? next.field_type,
24860
25967
  value
24861
25968
  };
24862
25969
  return next;
24863
25970
  }
24864
25971
  function applyRowValues(rowTemplate, rowValue) {
24865
- const source = isRecord14(rowValue) ? rowValue : {};
25972
+ const source = isRecord16(rowValue) ? rowValue : {};
24866
25973
  return rowTemplate.map((control) => {
24867
25974
  if (control.key && Object.prototype.hasOwnProperty.call(source, control.key)) {
24868
25975
  return setControlValue(control, source[control.key]);
@@ -25148,17 +26255,17 @@ function assertStepProjectFormWritable(fields, form, prefix = "") {
25148
26255
  for (const [key, value] of Object.entries(form)) {
25149
26256
  const field = fieldsByKey.get(key);
25150
26257
  if (!field) continue;
25151
- const path17 = `${prefix}${key}`;
26258
+ const path19 = `${prefix}${key}`;
25152
26259
  if (field.hidden) {
25153
- throw new Error(`Step project form handoff cannot write hidden field ${path17}.`);
26260
+ throw new Error(`Step project form handoff cannot write hidden field ${path19}.`);
25154
26261
  }
25155
26262
  if (isUnsupportedStepPrefillField(field)) {
25156
- throw new Error(`Step project form handoff cannot write system or manual field ${path17} (${field.type || "unknown"}).`);
26263
+ throw new Error(`Step project form handoff cannot write system or manual field ${path19} (${field.type || "unknown"}).`);
25157
26264
  }
25158
26265
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
25159
26266
  value.forEach((row, index) => {
25160
26267
  if (isRecordValue(row)) {
25161
- assertStepProjectFormWritable(field.children ?? [], row, `${path17}[${index}].`);
26268
+ assertStepProjectFormWritable(field.children ?? [], row, `${path19}[${index}].`);
25162
26269
  }
25163
26270
  });
25164
26271
  }
@@ -25420,8 +26527,8 @@ function fieldsForValidation(flowDetail, projectFormTemplate) {
25420
26527
  }));
25421
26528
  }
25422
26529
  function metaUsesTemplateProjectName(flowDetail) {
25423
- const data = isRecord15(flowDetail?.data) ? flowDetail.data : void 0;
25424
- const meta = isRecord15(data?.meta) ? data.meta : void 0;
26530
+ const data = isRecord17(flowDetail?.data) ? flowDetail.data : void 0;
26531
+ const meta = isRecord17(data?.meta) ? data.meta : void 0;
25425
26532
  const hideFields = Array.isArray(meta?.hide_fields) ? meta.hide_fields.map(String) : [];
25426
26533
  return meta?.use_template_project_name === true || hideFields.includes("project.name");
25427
26534
  }
@@ -25515,9 +26622,9 @@ function contextField(field, reason, options = {}) {
25515
26622
  function collectPrefillContextForFields(fields, form, result, options = {}) {
25516
26623
  for (const field of fields) {
25517
26624
  const value = form[field.key];
25518
- const path17 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
26625
+ const path19 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
25519
26626
  const fieldOptions = {
25520
- path: path17,
26627
+ path: path19,
25521
26628
  rootKey: options.rootKey ?? field.key,
25522
26629
  parentKey: options.parentKey
25523
26630
  };
@@ -25530,7 +26637,7 @@ function collectPrefillContextForFields(fields, form, result, options = {}) {
25530
26637
  result.filled_fields.push(contextField(field, "prefilled", fieldOptions));
25531
26638
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
25532
26639
  value.forEach((row, index) => {
25533
- if (isRecord15(row)) {
26640
+ if (isRecord17(row)) {
25534
26641
  collectPrefillContextForFields(field.children ?? [], row, result, {
25535
26642
  prefix: `${field.key}[${index}]`,
25536
26643
  rootKey: field.key,
@@ -25557,7 +26664,7 @@ function buildPrefillContext(fields, form) {
25557
26664
  }
25558
26665
  };
25559
26666
  }
25560
- function isRecord15(value) {
26667
+ function isRecord17(value) {
25561
26668
  return typeof value === "object" && value !== null && !Array.isArray(value);
25562
26669
  }
25563
26670
  function isEndedStep(step) {
@@ -25580,7 +26687,7 @@ function stepIdOf(step) {
25580
26687
  function pickStepFormPayload(step) {
25581
26688
  const formList = Array.isArray(step.formList) ? step.formList : [];
25582
26689
  const forms = Array.isArray(step.forms) ? step.forms : [];
25583
- const metaForm = isRecord15(step.metaForm) ? step.metaForm : void 0;
26690
+ const metaForm = isRecord17(step.metaForm) ? step.metaForm : void 0;
25584
26691
  return {
25585
26692
  step_id: step.id,
25586
26693
  flow_step_id: step.flow_step_id,
@@ -25597,7 +26704,7 @@ function pickStepFormPayload(step) {
25597
26704
  }
25598
26705
  async function buildApprovalContext(client, projectId, options) {
25599
26706
  const projectDetail = await apiRequest(client, "GET", `/project/${projectId}`);
25600
- const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord15) : [];
26707
+ const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord17) : [];
25601
26708
  const targetStepIds = /* @__PURE__ */ new Set();
25602
26709
  for (const step of steps) {
25603
26710
  const id = stepIdOf(step);
@@ -25623,7 +26730,7 @@ async function buildApprovalContext(client, projectId, options) {
25623
26730
  }
25624
26731
  return {
25625
26732
  project: projectDetail,
25626
- project_form: isRecord15(projectDetail.metaForm) ? projectDetail.metaForm : null,
26733
+ project_form: isRecord17(projectDetail.metaForm) ? projectDetail.metaForm : null,
25627
26734
  inspected_step_count: stepForms.length,
25628
26735
  step_forms: stepForms,
25629
26736
  failed_steps: failedSteps
@@ -25961,8 +27068,8 @@ import { spawn as spawn2 } from "child_process";
25961
27068
  import { fileURLToPath as fileURLToPath3 } from "url";
25962
27069
 
25963
27070
  // src/core/recipes.ts
25964
- import { access, mkdir as mkdir11, readdir as readdir6, readFile as readFile16, writeFile as writeFile11 } from "fs/promises";
25965
- import path13 from "path";
27071
+ import { access, mkdir as mkdir12, readdir as readdir6, readFile as readFile18, writeFile as writeFile12 } from "fs/promises";
27072
+ import path15 from "path";
25966
27073
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
25967
27074
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
25968
27075
  function assertSafeName(kind, value) {
@@ -25986,14 +27093,14 @@ function resolveRecipeLocation(options) {
25986
27093
  workspace,
25987
27094
  workspaceDirName,
25988
27095
  recipeName: options.recipeName,
25989
- recipeDir: path13.join(profileDir, "recipes", workspaceDirName, options.recipeName)
27096
+ recipeDir: path15.join(profileDir, "recipes", workspaceDirName, options.recipeName)
25990
27097
  };
25991
27098
  }
25992
27099
  function getRecipesDir(options) {
25993
27100
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
25994
- return path13.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
27101
+ return path15.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
25995
27102
  }
25996
- function isRecord16(value) {
27103
+ function isRecord18(value) {
25997
27104
  return typeof value === "object" && value !== null && !Array.isArray(value);
25998
27105
  }
25999
27106
  function asString(value, fieldName) {
@@ -26003,7 +27110,7 @@ function asString(value, fieldName) {
26003
27110
  return value;
26004
27111
  }
26005
27112
  function parseRecipeDefinition(input) {
26006
- if (!isRecord16(input)) {
27113
+ if (!isRecord18(input)) {
26007
27114
  throw new Error("recipe.json must be a JSON object.");
26008
27115
  }
26009
27116
  if (input.version !== 1) {
@@ -26011,7 +27118,7 @@ function parseRecipeDefinition(input) {
26011
27118
  }
26012
27119
  const name = asString(input.name, "recipe.name");
26013
27120
  assertSafeName("Recipe name", name);
26014
- if (!isRecord16(input.command)) {
27121
+ if (!isRecord18(input.command)) {
26015
27122
  throw new Error("recipe.command must be an object.");
26016
27123
  }
26017
27124
  const argv = input.command.argv;
@@ -26019,7 +27126,7 @@ function parseRecipeDefinition(input) {
26019
27126
  throw new Error("recipe.command.argv must be a non-empty string array.");
26020
27127
  }
26021
27128
  const variables = Array.isArray(input.variables) ? input.variables.map((item, index) => {
26022
- if (!isRecord16(item)) {
27129
+ if (!isRecord18(item)) {
26023
27130
  throw new Error(`recipe.variables[${index}] must be an object.`);
26024
27131
  }
26025
27132
  const variableName = asString(item.name, `recipe.variables[${index}].name`);
@@ -26043,7 +27150,7 @@ function parseRecipeDefinition(input) {
26043
27150
  };
26044
27151
  }
26045
27152
  async function loadRecipe(recipeDir) {
26046
- const raw = await readFile16(path13.join(recipeDir, "recipe.json"), "utf8");
27153
+ const raw = await readFile18(path15.join(recipeDir, "recipe.json"), "utf8");
26047
27154
  return parseRecipeDefinition(JSON.parse(raw));
26048
27155
  }
26049
27156
  async function listRecipes(recipesDir) {
@@ -26061,7 +27168,7 @@ async function listRecipes(recipesDir) {
26061
27168
  if (!RECIPE_NAME_PATTERN.test(entry)) {
26062
27169
  continue;
26063
27170
  }
26064
- const recipeDir = path13.join(recipesDir, entry);
27171
+ const recipeDir = path15.join(recipesDir, entry);
26065
27172
  try {
26066
27173
  const recipe = await loadRecipe(recipeDir);
26067
27174
  summaries.push({
@@ -26095,7 +27202,7 @@ function parseVarsJson(input) {
26095
27202
  return {};
26096
27203
  }
26097
27204
  const parsed = JSON.parse(input);
26098
- if (!isRecord16(parsed)) {
27205
+ if (!isRecord18(parsed)) {
26099
27206
  throw new Error("--vars must be a JSON object.");
26100
27207
  }
26101
27208
  const variables = {};
@@ -26127,12 +27234,12 @@ function renderTemplate(template, variables) {
26127
27234
  }
26128
27235
  function resolveRecipeFile(recipeDir, token) {
26129
27236
  const relative = token.slice(1);
26130
- if (!relative || relative.includes("..") || path13.isAbsolute(relative)) {
27237
+ if (!relative || relative.includes("..") || path15.isAbsolute(relative)) {
26131
27238
  throw new Error(`Unsafe recipe file reference: ${token}`);
26132
27239
  }
26133
- const resolved = path13.resolve(recipeDir, relative);
26134
- const root = path13.resolve(recipeDir);
26135
- if (resolved !== root && !resolved.startsWith(`${root}${path13.sep}`)) {
27240
+ const resolved = path15.resolve(recipeDir, relative);
27241
+ const root = path15.resolve(recipeDir);
27242
+ if (resolved !== root && !resolved.startsWith(`${root}${path15.sep}`)) {
26136
27243
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
26137
27244
  }
26138
27245
  return resolved;
@@ -26142,7 +27249,7 @@ async function renderArgv(options) {
26142
27249
  const rendered = [];
26143
27250
  for (const token of options.recipe.command.argv) {
26144
27251
  if (token.startsWith("@")) {
26145
- const raw = await readFile16(resolveRecipeFile(options.recipeDir, token), "utf8");
27252
+ const raw = await readFile18(resolveRecipeFile(options.recipeDir, token), "utf8");
26146
27253
  rendered.push(renderTemplate(raw, options.variables));
26147
27254
  } else {
26148
27255
  rendered.push(renderTemplate(token, options.variables));
@@ -26168,7 +27275,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
26168
27275
  }
26169
27276
  async function writeRecipeScaffold(options) {
26170
27277
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
26171
- await mkdir11(options.location.recipeDir, { recursive: true });
27278
+ await mkdir12(options.location.recipeDir, { recursive: true });
26172
27279
  const title = options.title || options.location.recipeName;
26173
27280
  const recipe = {
26174
27281
  version: 1,
@@ -26185,16 +27292,16 @@ async function writeRecipeScaffold(options) {
26185
27292
  mutating: true
26186
27293
  }
26187
27294
  };
26188
- await writeFile11(path13.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
27295
+ await writeFile12(path15.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
26189
27296
  `, "utf8");
26190
- await writeFile11(
26191
- path13.join(options.location.recipeDir, "payload.json"),
27297
+ await writeFile12(
27298
+ path15.join(options.location.recipeDir, "payload.json"),
26192
27299
  `${JSON.stringify({ form: {} }, null, 2)}
26193
27300
  `,
26194
27301
  "utf8"
26195
27302
  );
26196
- await writeFile11(
26197
- path13.join(options.location.recipeDir, "README.md"),
27303
+ await writeFile12(
27304
+ path15.join(options.location.recipeDir, "README.md"),
26198
27305
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
26199
27306
  "utf8"
26200
27307
  );
@@ -26629,8 +27736,8 @@ function registerSetupCommand(program2, deps = {}) {
26629
27736
  }
26630
27737
 
26631
27738
  // src/core/taskbook.ts
26632
- import { mkdir as mkdir12, readFile as readFile17, writeFile as writeFile12 } from "fs/promises";
26633
- import path14 from "path";
27739
+ import { mkdir as mkdir13, readFile as readFile19, writeFile as writeFile13 } from "fs/promises";
27740
+ import path16 from "path";
26634
27741
  var TaskbookError = class extends Error {
26635
27742
  };
26636
27743
  var REQUIRED_TASKBOOK_TERMS = [
@@ -26846,26 +27953,26 @@ function hasDomainWriteEvidence(domain, evidenceText, patterns) {
26846
27953
  function uuidValues(text5) {
26847
27954
  return [...new Set([...text5.matchAll(UUID_PATTERN)].map((match) => match[0]))];
26848
27955
  }
26849
- function addUuidIssues(text5, issues, path17) {
27956
+ function addUuidIssues(text5, issues, path19) {
26850
27957
  for (const value of uuidValues(text5)) {
26851
27958
  addTaskbookIssue(
26852
27959
  issues,
26853
27960
  "uuid_not_allowed",
26854
27961
  "taskbook.config.no_uuid",
26855
27962
  `BPMAX \u914D\u7F6E\u4EFB\u52A1\u4E0D\u80FD\u4F7F\u7528 UUID\uFF1A${value}\u3002`,
26856
- { path: path17, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
27963
+ { path: path19, suggestion: "\u4F7F\u7528\u5E73\u53F0\u8FD4\u56DE\u7684\u6570\u5B57 ID \u6216 flow<number>\uFF1B\u521B\u5EFA\u524D\u4F7F\u7528 new-flow:<name>\uFF0C\u521B\u5EFA\u540E\u56DE\u586B\u771F\u5B9E flow_type\u3002" }
26857
27964
  );
26858
27965
  }
26859
27966
  }
26860
27967
  async function readTaskbookText(file) {
26861
- const raw = await readFile17(file, "utf8");
27968
+ const raw = await readFile19(file, "utf8");
26862
27969
  try {
26863
27970
  const parsed = JSON.parse(raw);
26864
27971
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
26865
27972
  const root = parsed;
26866
- const document = root.data?.document;
26867
- if (document && typeof document === "object" && !Array.isArray(document)) {
26868
- const content = document.content;
27973
+ const document2 = root.data?.document;
27974
+ if (document2 && typeof document2 === "object" && !Array.isArray(document2)) {
27975
+ const content = document2.content;
26869
27976
  if (typeof content === "string") {
26870
27977
  return content;
26871
27978
  }
@@ -26885,7 +27992,7 @@ function findNavigationStrategy(text5) {
26885
27992
  const matches = [...text5.matchAll(/导航入口策略\s*[::]\s*(nav-config:(?:included|skipped:[^\s|,。]+|deferred:[^\s|,。]+))/gi)];
26886
27993
  return matches.at(-1)?.[1] || null;
26887
27994
  }
26888
- function validateNavigationStrategy(text5, issues, path17, subject) {
27995
+ function validateNavigationStrategy(text5, issues, path19, subject) {
26889
27996
  const strategy = findNavigationStrategy(text5);
26890
27997
  if (!strategy) {
26891
27998
  addTaskbookIssue(
@@ -26893,7 +28000,7 @@ function validateNavigationStrategy(text5, issues, path17, subject) {
26893
28000
  "missing_navigation_strategy",
26894
28001
  "taskbook.nav.strategy",
26895
28002
  `${subject}\u7F3A\u5C11\u660E\u786E\u7684\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u3002`,
26896
- { path: path17, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
28003
+ { path: path19, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
26897
28004
  );
26898
28005
  return null;
26899
28006
  }
@@ -26903,7 +28010,7 @@ function validateNavigationStrategy(text5, issues, path17, subject) {
26903
28010
  "empty_navigation_strategy_reason",
26904
28011
  "taskbook.nav.strategy_reason",
26905
28012
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u8DF3\u8FC7\u6216\u5EF6\u540E\u65F6\u5FC5\u987B\u5199\u660E\u539F\u56E0\u3002`,
26906
- { path: path17, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
28013
+ { path: path19, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
26907
28014
  );
26908
28015
  }
26909
28016
  if (/(待完成范围确认后回填|待确认|TODO|TBD|占位)/i.test(strategy)) {
@@ -26912,7 +28019,7 @@ function validateNavigationStrategy(text5, issues, path17, subject) {
26912
28019
  "placeholder_navigation_strategy",
26913
28020
  "taskbook.nav.strategy_placeholder",
26914
28021
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u4ECD\u662F\u5360\u4F4D\u5185\u5BB9\u3002`,
26915
- { path: path17, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
28022
+ { path: path19, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
26916
28023
  );
26917
28024
  }
26918
28025
  return strategy;
@@ -27464,8 +28571,8 @@ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1
27464
28571
  }
27465
28572
  async function initTaskbook(outFile, title) {
27466
28573
  const content = taskbookTemplate(title);
27467
- await mkdir12(path14.dirname(outFile), { recursive: true });
27468
- await writeFile12(outFile, content, "utf8");
28574
+ await mkdir13(path16.dirname(outFile), { recursive: true });
28575
+ await writeFile13(outFile, content, "utf8");
27469
28576
  return { out: outFile, bytes: Buffer.byteLength(content) };
27470
28577
  }
27471
28578
  function splitMarkdownRow(line) {
@@ -27554,8 +28661,8 @@ async function initTaskbookProgress(source, outFile) {
27554
28661
  fields.join(","),
27555
28662
  ...rows2.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
27556
28663
  ].join("\n") + "\n";
27557
- await mkdir12(path14.dirname(outFile), { recursive: true });
27558
- await writeFile12(outFile, csv, "utf8");
28664
+ await mkdir13(path16.dirname(outFile), { recursive: true });
28665
+ await writeFile13(outFile, csv, "utf8");
27559
28666
  return { source, out: outFile, task_count: rows2.length };
27560
28667
  }
27561
28668
 
@@ -27597,8 +28704,8 @@ function registerTaskbookCommands(program2) {
27597
28704
  }
27598
28705
 
27599
28706
  // src/commands/test-suite.ts
27600
- import { readFile as readFile18 } from "fs/promises";
27601
- import path15 from "path";
28707
+ import { readFile as readFile20 } from "fs/promises";
28708
+ import path17 from "path";
27602
28709
  function collect2(value, previous = []) {
27603
28710
  previous.push(value);
27604
28711
  return previous;
@@ -27608,8 +28715,8 @@ function effectiveProfileOption(options, command) {
27608
28715
  }
27609
28716
  async function resolveE2eSkillSource(sourceSkill) {
27610
28717
  if (sourceSkill) {
27611
- const resolved = path15.resolve(sourceSkill);
27612
- const content = await readFile18(resolved, "utf8").catch(() => "");
28718
+ const resolved = path17.resolve(sourceSkill);
28719
+ const content = await readFile20(resolved, "utf8").catch(() => "");
27613
28720
  if (!content.includes('name: "bpmax-e2e-flow-test-operator"') && !content.includes("name: bpmax-e2e-flow-test-operator")) {
27614
28721
  throw new TestSuiteError("source skill is not bpmax-e2e-flow-test-operator", {
27615
28722
  rule_id: "test_suite.run.skill_source_invalid",
@@ -27711,8 +28818,8 @@ function registerTestSuiteCommands(program2) {
27711
28818
  }
27712
28819
 
27713
28820
  // src/core/update.ts
27714
- import { access as access2, mkdir as mkdir13, readFile as readFile19, realpath as realpath3, writeFile as writeFile13 } from "fs/promises";
27715
- import path16 from "path";
28821
+ import { access as access2, mkdir as mkdir14, readFile as readFile21, realpath as realpath3, writeFile as writeFile14 } from "fs/promises";
28822
+ import path18 from "path";
27716
28823
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
27717
28824
  var UPDATE_STATE_FILE = "update-state.json";
27718
28825
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -27828,11 +28935,11 @@ async function fetchLatestVersion(options = {}) {
27828
28935
  }
27829
28936
  }
27830
28937
  function updateStatePath(configDir = getConfigDir()) {
27831
- return path16.join(configDir, UPDATE_STATE_FILE);
28938
+ return path18.join(configDir, UPDATE_STATE_FILE);
27832
28939
  }
27833
28940
  async function readUpdateState(configDir) {
27834
28941
  try {
27835
- const raw = await readFile19(updateStatePath(configDir), "utf8");
28942
+ const raw = await readFile21(updateStatePath(configDir), "utf8");
27836
28943
  const parsed = JSON.parse(raw);
27837
28944
  if (typeof parsed.latest_version !== "string" || typeof parsed.checked_at !== "number") {
27838
28945
  return null;
@@ -27847,8 +28954,8 @@ async function readUpdateState(configDir) {
27847
28954
  }
27848
28955
  }
27849
28956
  async function writeUpdateState(state, configDir = getConfigDir()) {
27850
- await mkdir13(configDir, { recursive: true });
27851
- await writeFile13(updateStatePath(configDir), JSON.stringify(state), "utf8");
28957
+ await mkdir14(configDir, { recursive: true });
28958
+ await writeFile14(updateStatePath(configDir), JSON.stringify(state), "utf8");
27852
28959
  }
27853
28960
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
27854
28961
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -27909,7 +29016,7 @@ async function findNpmPath() {
27909
29016
  }
27910
29017
  function detectInstallMethod(input) {
27911
29018
  const resolvedPath = input.executablePath || "";
27912
- const method = resolvedPath.includes(`node_modules${path16.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
29019
+ const method = resolvedPath.includes(`node_modules${path18.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
27913
29020
  return {
27914
29021
  method,
27915
29022
  resolvedPath,
@@ -28150,17 +29257,17 @@ function registerUrlCommands(program2, deps = {}) {
28150
29257
  }
28151
29258
 
28152
29259
  // src/commands/user.ts
28153
- function isRecord17(value) {
29260
+ function isRecord19(value) {
28154
29261
  return typeof value === "object" && value !== null && !Array.isArray(value);
28155
29262
  }
28156
29263
  function userRows(value) {
28157
- if (Array.isArray(value)) return value.filter(isRecord17);
28158
- if (!isRecord17(value)) return [];
28159
- if (Array.isArray(value.data)) return value.data.filter(isRecord17);
29264
+ if (Array.isArray(value)) return value.filter(isRecord19);
29265
+ if (!isRecord19(value)) return [];
29266
+ if (Array.isArray(value.data)) return value.data.filter(isRecord19);
28160
29267
  return value.id ? [value] : [];
28161
29268
  }
28162
29269
  function safeUser2(user) {
28163
- const roles = Array.isArray(user.role) ? user.role.filter(isRecord17).map((role) => ({
29270
+ const roles = Array.isArray(user.role) ? user.role.filter(isRecord19).map((role) => ({
28164
29271
  id: role.id,
28165
29272
  key: role.key,
28166
29273
  name: role.name