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

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(path19) {
237
- let normalized = path19.split("?")[0] || "/";
236
+ function normalizePath(path20) {
237
+ let normalized = path20.split("?")[0] || "/";
238
238
  if (!normalized.startsWith("/")) {
239
239
  normalized = `/${normalized}`;
240
240
  }
@@ -244,17 +244,17 @@ function normalizePath(path19) {
244
244
  }
245
245
  return normalized.replace(/\/+$/g, "") || "/api";
246
246
  }
247
- function getNumber(value, path19) {
248
- const result = getValue(value, path19);
247
+ function getNumber(value, path20) {
248
+ const result = getValue(value, path20);
249
249
  return typeof result === "number" ? result : void 0;
250
250
  }
251
- function getString(value, path19) {
252
- const result = getValue(value, path19);
251
+ function getString(value, path20) {
252
+ const result = getValue(value, path20);
253
253
  return typeof result === "string" ? result : void 0;
254
254
  }
255
- function getValue(value, path19) {
255
+ function getValue(value, path20) {
256
256
  let current = value;
257
- for (const key of path19) {
257
+ for (const key of path20) {
258
258
  if (!current || typeof current !== "object" || !(key in current)) {
259
259
  return void 0;
260
260
  }
@@ -264,10 +264,10 @@ function getValue(value, path19) {
264
264
  }
265
265
 
266
266
  // src/core/capabilities.ts
267
- function capabilityForRequest(method, path19) {
267
+ function capabilityForRequest(method, path20) {
268
268
  const normalizedMethod = method.toUpperCase();
269
- const normalizedPath = normalizePath2(path19);
270
- const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path19);
269
+ const normalizedPath = normalizePath2(path20);
270
+ const pageTemplatePrefix = flowPageTemplateCapabilityPrefix(path20);
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(path19) {
450
- const query = path19.includes("?") ? path19.slice(path19.indexOf("?") + 1) : "";
449
+ function flowPageTemplateCapabilityPrefix(path20) {
450
+ const query = path20.includes("?") ? path20.slice(path20.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(path19) {
466
466
  }
467
467
  return "config.list_template";
468
468
  }
469
- function normalizePath2(path19) {
470
- let normalized = path19.split("?")[0] || "/";
469
+ function normalizePath2(path20) {
470
+ let normalized = path20.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.50",
501
+ version: "0.2.1-beta.52",
502
502
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
503
503
  type: "module",
504
504
  bin: {
@@ -550,8 +550,8 @@ var NPM_PACKAGE = "bpmax-cli";
550
550
  // src/core/terminal.ts
551
551
  import { randomUUID } from "crypto";
552
552
  import os from "os";
553
- function isCliControlPath(path19) {
554
- const normalized = normalizeApiPath(path19);
553
+ function isCliControlPath(path20) {
554
+ const normalized = normalizeApiPath(path20);
555
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";
556
556
  }
557
557
  function commandSummary(argv = process.argv) {
@@ -715,8 +715,8 @@ async function updateProfileTerminal(profile, terminalId, status) {
715
715
  profile.config.terminal_status = status;
716
716
  profile.config.terminal_registered_at = config.profiles[profile.name].terminal_registered_at;
717
717
  }
718
- function normalizeApiPath(path19) {
719
- let normalized = path19.split("?")[0] || "/";
718
+ function normalizeApiPath(path20) {
719
+ let normalized = path20.split("?")[0] || "/";
720
720
  if (!normalized.startsWith("/")) {
721
721
  normalized = `/${normalized}`;
722
722
  }
@@ -839,14 +839,14 @@ function recordCommandAuditResult(value) {
839
839
  state.result_summary = redactAuditValue(value);
840
840
  }
841
841
  }
842
- var ensureApiPath = (path19) => {
843
- if (!path19.startsWith("/")) {
844
- path19 = `/${path19}`;
842
+ var ensureApiPath = (path20) => {
843
+ if (!path20.startsWith("/")) {
844
+ path20 = `/${path20}`;
845
845
  }
846
- if (path19.startsWith("/api/")) {
847
- return path19;
846
+ if (path20.startsWith("/api/")) {
847
+ return path20;
848
848
  }
849
- return `/api${path19}`;
849
+ return `/api${path20}`;
850
850
  };
851
851
  function normalizeWorkspaceForApi(workspace) {
852
852
  const normalized = workspace?.trim();
@@ -892,10 +892,10 @@ function createApiClient(profile) {
892
892
  });
893
893
  return instance;
894
894
  }
895
- async function apiRequest(client, method, path19, options = {}) {
895
+ async function apiRequest(client, method, path20, options = {}) {
896
896
  const profile = clientProfiles.get(client);
897
- const apiPath2 = ensureApiPath(path19);
898
- const capability = options.capability ?? capabilityForRequest(method, path19);
897
+ const apiPath2 = ensureApiPath(path20);
898
+ const capability = options.capability ?? capabilityForRequest(method, path20);
899
899
  const shouldControl = Boolean(profile?.config.api_key) && !isCliControlPath(apiPath2);
900
900
  const reqId = requestId();
901
901
  if (profile) {
@@ -1222,8 +1222,8 @@ async function parseJsonAny(input, label = "JSON input") {
1222
1222
  function isMutatingMethod(method) {
1223
1223
  return ["POST", "PUT", "PATCH", "DELETE"].includes(method.toUpperCase());
1224
1224
  }
1225
- function normalizeApiPath2(path19) {
1226
- let normalized = path19.trim();
1225
+ function normalizeApiPath2(path20) {
1226
+ let normalized = path20.trim();
1227
1227
  const queryIndex = normalized.indexOf("?");
1228
1228
  if (queryIndex >= 0) {
1229
1229
  normalized = normalized.slice(0, queryIndex);
@@ -1240,9 +1240,9 @@ function normalizeApiPath2(path19) {
1240
1240
  }
1241
1241
  return normalized;
1242
1242
  }
1243
- function pluginAgentCapabilityForRawApi(method, path19) {
1243
+ function pluginAgentCapabilityForRawApi(method, path20) {
1244
1244
  const normalizedMethod = method.toUpperCase();
1245
- const normalizedPath = normalizeApiPath2(path19);
1245
+ const normalizedPath = normalizeApiPath2(path20);
1246
1246
  const match = normalizedPath.match(/^\/(plugin_[A-Za-z0-9_]+)\/agents(?:\/|$)/);
1247
1247
  if (!match) {
1248
1248
  return void 0;
@@ -1256,19 +1256,19 @@ function pluginAgentCapabilityForRawApi(method, path19) {
1256
1256
  }
1257
1257
  return void 0;
1258
1258
  }
1259
- function parseQuery(path19) {
1260
- const queryIndex = path19.indexOf("?");
1261
- return new URLSearchParams(queryIndex >= 0 ? path19.slice(queryIndex + 1) : "");
1259
+ function parseQuery(path20) {
1260
+ const queryIndex = path20.indexOf("?");
1261
+ return new URLSearchParams(queryIndex >= 0 ? path20.slice(queryIndex + 1) : "");
1262
1262
  }
1263
- function isRawConfigPath(method, path19) {
1264
- const normalizedPath = normalizeApiPath2(path19);
1263
+ function isRawConfigPath(method, path20) {
1264
+ const normalizedPath = normalizeApiPath2(path20);
1265
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)) {
1266
1266
  return true;
1267
1267
  }
1268
1268
  if (normalizedPath === "/flow/list/lightweight" || normalizedPath.startsWith("/flow/configuration/")) {
1269
1269
  return true;
1270
1270
  }
1271
- if (normalizedPath === "/flow" && method === "GET" && parseQuery(path19).has("draft")) {
1271
+ if (normalizedPath === "/flow" && method === "GET" && parseQuery(path20).has("draft")) {
1272
1272
  return true;
1273
1273
  }
1274
1274
  if (normalizedPath.startsWith("/flow/") && !["/flow/flow_type", "/flow/options", "/flow/batch_get"].includes(normalizedPath)) {
@@ -1279,35 +1279,35 @@ function isRawConfigPath(method, path19) {
1279
1279
  }
1280
1280
  return false;
1281
1281
  }
1282
- function assertRawApiPathAllowed(method, path19) {
1283
- if (isRawConfigPath(method, path19)) {
1282
+ function assertRawApiPathAllowed(method, path20) {
1283
+ if (isRawConfigPath(method, path20)) {
1284
1284
  throw new Error(
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
+ `Raw API ${method} ${path20} 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.`
1286
1286
  );
1287
1287
  }
1288
1288
  if (!isMutatingMethod(method)) {
1289
1289
  return;
1290
1290
  }
1291
- const normalizedPath = normalizeApiPath2(path19);
1291
+ const normalizedPath = normalizeApiPath2(path20);
1292
1292
  const isProjectPath = normalizedPath === "/project" || normalizedPath.startsWith("/project/");
1293
1293
  const isAllowedProjectReadPost = method === "POST" && normalizedPath === "/project/list";
1294
1294
  if (!isProjectPath || isAllowedProjectReadPost) {
1295
1295
  return;
1296
1296
  }
1297
1297
  throw new Error(
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
+ `Raw API ${method} ${path20} 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.`
1299
1299
  );
1300
1300
  }
1301
1301
  function registerApiCommands(program2) {
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
+ 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, path20, options) => {
1303
1303
  const normalizedMethod = method.toUpperCase();
1304
- assertRawApiPathAllowed(normalizedMethod, path19);
1304
+ assertRawApiPathAllowed(normalizedMethod, path20);
1305
1305
  if (isMutatingMethod(normalizedMethod) && options.confirmMutating !== true) {
1306
1306
  printResult(options.format, {
1307
1307
  ok: false,
1308
1308
  dry_run: true,
1309
1309
  method: normalizedMethod,
1310
- path: path19,
1310
+ path: path20,
1311
1311
  warning: "Mutating raw API calls require --confirm-mutating. Prefer typed bpmax-cli commands such as step submit."
1312
1312
  });
1313
1313
  return;
@@ -1315,8 +1315,8 @@ function registerApiCommands(program2) {
1315
1315
  const config = await loadConfig();
1316
1316
  const profile = resolveProfile(config, options.profile);
1317
1317
  const client = createApiClient(profile);
1318
- const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path19) || "api.raw";
1319
- const result = await apiRequest(client, normalizedMethod, path19, {
1318
+ const capability = pluginAgentCapabilityForRawApi(normalizedMethod, path20) || "api.raw";
1319
+ const result = await apiRequest(client, normalizedMethod, path20, {
1320
1320
  params: options.params ? await parseJsonInput(options.params, "--params") : void 0,
1321
1321
  data: await parseJsonAny(options.data, "--data"),
1322
1322
  capability
@@ -1397,24 +1397,36 @@ function lintDeviceAuthorizationUrl(urlValue, expectedOrigin, expectedWorkspace,
1397
1397
  );
1398
1398
  }
1399
1399
  const actualWorkspace = firstPathSegment(url);
1400
- if (actualWorkspace !== expectedWorkspace) {
1400
+ const acceptedWorkspaces = expectedWorkspace === "default" ? /* @__PURE__ */ new Set(["default", "w:default"]) : /* @__PURE__ */ new Set([expectedWorkspace]);
1401
+ if (!actualWorkspace || !acceptedWorkspaces.has(actualWorkspace)) {
1401
1402
  throw new Error(
1402
1403
  `Device authorization URL workspace mismatch for ${fieldName}: expected ${expectedWorkspace}, got ${actualWorkspace || "(missing)"}. Refusing to print a potentially wrong authorization link.`
1403
1404
  );
1404
1405
  }
1405
1406
  }
1406
- function apiPath(path19) {
1407
- if (path19.startsWith("/api/")) {
1408
- return path19;
1407
+ function normalizeDeviceAuthorizationUrl(urlValue, workspace) {
1408
+ if (workspace !== "default") {
1409
+ return urlValue;
1409
1410
  }
1410
- return `/api${path19.startsWith("/") ? path19 : `/${path19}`}`;
1411
+ const url = new URL(urlValue);
1412
+ const segments = url.pathname.split("/").filter(Boolean).map((segment) => decodeURIComponent(segment));
1413
+ if (segments.length === 2 && segments[0] === "default" && segments[1] === "cli-device") {
1414
+ url.pathname = "/w:default/cli-device";
1415
+ }
1416
+ return url.toString();
1417
+ }
1418
+ function apiPath(path20) {
1419
+ if (path20.startsWith("/api/")) {
1420
+ return path20;
1421
+ }
1422
+ return `/api${path20.startsWith("/") ? path20 : `/${path20}`}`;
1411
1423
  }
1412
1424
  function createDeviceRequest(origin) {
1413
1425
  const client = axios2.create({ baseURL: origin, withCredentials: false });
1414
- return async (method, path19, options) => {
1426
+ return async (method, path20, options) => {
1415
1427
  const response = await client.request({
1416
1428
  method,
1417
- url: apiPath(path19),
1429
+ url: apiPath(path20),
1418
1430
  data: options.data
1419
1431
  });
1420
1432
  const body = response.data;
@@ -1458,12 +1470,14 @@ async function startDeviceLogin(options) {
1458
1470
  });
1459
1471
  const expiresIn = numberField(response.expires_in, "expires_in");
1460
1472
  const now = options.now?.() || /* @__PURE__ */ new Date();
1461
- const verificationUri = stringField(response.verification_uri, "verification_uri");
1462
- lintDeviceAuthorizationUrl(verificationUri, origin, workspace, "verification_uri");
1463
- const verificationUriComplete = typeof response.verification_uri_complete === "string" && response.verification_uri_complete.trim() ? response.verification_uri_complete : void 0;
1464
- if (verificationUriComplete) {
1465
- lintDeviceAuthorizationUrl(verificationUriComplete, origin, workspace, "verification_uri_complete");
1466
- }
1473
+ const verificationUriRaw = stringField(response.verification_uri, "verification_uri");
1474
+ lintDeviceAuthorizationUrl(verificationUriRaw, origin, workspace, "verification_uri");
1475
+ const verificationUri = normalizeDeviceAuthorizationUrl(verificationUriRaw, workspace);
1476
+ const verificationUriCompleteRaw = typeof response.verification_uri_complete === "string" && response.verification_uri_complete.trim() ? response.verification_uri_complete : void 0;
1477
+ if (verificationUriCompleteRaw) {
1478
+ lintDeviceAuthorizationUrl(verificationUriCompleteRaw, origin, workspace, "verification_uri_complete");
1479
+ }
1480
+ const verificationUriComplete = verificationUriCompleteRaw ? normalizeDeviceAuthorizationUrl(verificationUriCompleteRaw, workspace) : void 0;
1467
1481
  const authorizationUrl = verificationUriComplete || verificationUri;
1468
1482
  return {
1469
1483
  profile: options.profileName,
@@ -2573,7 +2587,7 @@ function validatePluginLintManifest(item, issues, context2) {
2573
2587
  }
2574
2588
  }
2575
2589
  function isAllowedPluginConfigScanPath(scanPath) {
2576
- return scanPath === "data.meta.<plugin_key>" || scanPath === "data.nodes[].<plugin_key>" || /^data\.nodes\[\]\.<plugin_key>\.[A-Za-z0-9_]+\[\]$/.test(scanPath) || /^data\.nodes\[\]\.[A-Za-z0-9_]+_(?:triggers|configs|plugins)\[\]$/.test(scanPath);
2590
+ return scanPath === "data.meta.<plugin_key>" || scanPath === "data.nodes[].<plugin_key>" || /^data\.nodes\[\]\.<plugin_key>\.[A-Za-z0-9_]+\[\]$/.test(scanPath) || /^data\.nodes\[\]\.plugin_[A-Za-z0-9_]+$/.test(scanPath) || /^data\.nodes\[\]\.[A-Za-z0-9_]+_(?:triggers|configs|plugins)\[\]$/.test(scanPath);
2577
2591
  }
2578
2592
  async function validatePluginLintRuleFiles(skillDir, files, issues) {
2579
2593
  for (const file of files) {
@@ -3324,6 +3338,28 @@ function collectFlowTemplatePluginConfigsByPath(flowWork, scanPath, pluginKey) {
3324
3338
  });
3325
3339
  return occurrences2;
3326
3340
  }
3341
+ const objectMatch = scanPath.match(/^data\.nodes\[\]\.(plugin_[A-Za-z0-9_]+)$/);
3342
+ if (objectMatch) {
3343
+ const field2 = objectMatch[1];
3344
+ const data2 = typeof flowWork.data === "object" && flowWork.data !== null && !Array.isArray(flowWork.data) ? flowWork.data : {};
3345
+ const nodes2 = Array.isArray(data2.nodes) ? data2.nodes : [];
3346
+ const occurrences2 = [];
3347
+ nodes2.forEach((node, nodeIndex) => {
3348
+ if (!node || typeof node !== "object" || Array.isArray(node)) {
3349
+ return;
3350
+ }
3351
+ const nodeRecord = node;
3352
+ if (!Object.prototype.hasOwnProperty.call(nodeRecord, field2)) {
3353
+ return;
3354
+ }
3355
+ const nodeName = typeof nodeRecord.name === "string" && nodeRecord.name.trim() ? nodeRecord.name.trim() : `nodes[${nodeIndex}]`;
3356
+ occurrences2.push({
3357
+ location: `${nodeName}.${field2}`,
3358
+ config: nodeRecord[field2]
3359
+ });
3360
+ });
3361
+ return occurrences2;
3362
+ }
3327
3363
  const match = scanPath.match(/^data\.nodes\[\]\.([A-Za-z0-9_]+)\[\]$/);
3328
3364
  if (!match) {
3329
3365
  return [];
@@ -3459,8 +3495,11 @@ async function lintFlowTemplatePluginExtensions(options) {
3459
3495
  ...platformLintDeclarations.map((item) => item.lint.plugin_key),
3460
3496
  ...installedLintDeclarations.map((item) => item.lint.plugin_key)
3461
3497
  ]);
3498
+ const declaredExplicitNodeKeys = new Set(
3499
+ [...platformLintDeclarations, ...installedLintDeclarations].flatMap((item) => item.lint.paths || []).map((scanPath) => scanPath.match(/^data\.nodes\[\]\.(plugin_[A-Za-z0-9_]+)$/)?.[1]).filter((key) => Boolean(key))
3500
+ );
3462
3501
  for (const pluginKey of usedPluginKeys) {
3463
- if (allPluginKeys.has(pluginKey)) {
3502
+ if (allPluginKeys.has(pluginKey) || declaredExplicitNodeKeys.has(pluginKey)) {
3464
3503
  continue;
3465
3504
  }
3466
3505
  const occurrences = collectFlowTemplatePluginConfigs(options.flowWork, pluginKey);
@@ -3524,7 +3563,12 @@ async function lintFlowTemplatePluginExtensions(options) {
3524
3563
  lintErrors.push(error instanceof Error ? error.message : String(error));
3525
3564
  ruleFile = {};
3526
3565
  }
3527
- for (const occurrence of occurrences) {
3566
+ const declarationOccurrences = collectFlowTemplatePluginConfigs(
3567
+ options.flowWork,
3568
+ pluginKey,
3569
+ [declaration.lint]
3570
+ );
3571
+ for (const occurrence of declarationOccurrences) {
3528
3572
  if (shouldSkipPluginLint(occurrence.config, ruleFile.skipWhen)) {
3529
3573
  continue;
3530
3574
  }
@@ -3552,7 +3596,7 @@ async function lintFlowTemplatePluginExtensions(options) {
3552
3596
  plugin_key: pluginKey,
3553
3597
  domain: declaration.lint.domain,
3554
3598
  rule_path: declaration.lint.path,
3555
- checked_locations: occurrences.map((item) => item.location),
3599
+ checked_locations: declarationOccurrences.map((item) => item.location),
3556
3600
  errors: lintErrors,
3557
3601
  warnings: lintWarnings
3558
3602
  });
@@ -3873,20 +3917,20 @@ function requireNumericId(value, name) {
3873
3917
  }
3874
3918
  return nextValue;
3875
3919
  }
3876
- function withQuery(path19, query) {
3920
+ function withQuery(path20, query) {
3877
3921
  const params = new URLSearchParams();
3878
3922
  for (const [key, value] of Object.entries(query)) {
3879
3923
  if (value !== void 0) {
3880
3924
  params.set(key, value);
3881
3925
  }
3882
3926
  }
3883
- return `${path19}?${params.toString()}`;
3927
+ return `${path20}?${params.toString()}`;
3884
3928
  }
3885
3929
  function buildBpmaxUrl(profile, kind, params = {}) {
3886
3930
  const origin = normalizeOrigin2(profile.config.origin);
3887
3931
  const workspace = normalizeWorkspaceForUrl(params.workspace || profile.config.workspace);
3888
3932
  const basePath = `/${workspace}`;
3889
- let path19 = basePath;
3933
+ let path20 = basePath;
3890
3934
  const result = {
3891
3935
  kind,
3892
3936
  profile: profile.name,
@@ -3894,15 +3938,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
3894
3938
  workspace
3895
3939
  };
3896
3940
  if (kind === "project-list") {
3897
- path19 = `${basePath}/project`;
3941
+ path20 = `${basePath}/project`;
3898
3942
  } else if (kind === "project-detail") {
3899
3943
  const projectId = requireNumericId(params.projectId, "projectId");
3900
- path19 = `${basePath}/project_detail/0/${projectId}`;
3944
+ path20 = `${basePath}/project_detail/0/${projectId}`;
3901
3945
  result.project_id = projectId;
3902
3946
  } else if (kind === "project-step") {
3903
3947
  const projectId = requireNumericId(params.projectId, "projectId");
3904
3948
  const stepId = requireNumericId(params.stepId, "stepId");
3905
- path19 = withQuery(`${basePath}/projectContinue`, {
3949
+ path20 = withQuery(`${basePath}/projectContinue`, {
3906
3950
  id: projectId,
3907
3951
  step_id: stepId,
3908
3952
  prefill_token: params.prefillToken
@@ -3920,15 +3964,15 @@ function buildBpmaxUrl(profile, kind, params = {}) {
3920
3964
  ...flowKey ? { key: flowKey } : {},
3921
3965
  ...prefillToken ? { prefill_token: prefillToken } : { init_value: initValue }
3922
3966
  };
3923
- path19 = withQuery(`${basePath}/project/create`, query);
3967
+ path20 = withQuery(`${basePath}/project/create`, query);
3924
3968
  result.flow_type = flowType;
3925
3969
  result.flow_key = flowKey;
3926
3970
  result.mobile_path = withQuery("/pages/projectCreate/projectCreate", query);
3927
3971
  }
3928
- const url = `${origin}${path19}`;
3972
+ const url = `${origin}${path20}`;
3929
3973
  return {
3930
3974
  ...result,
3931
- path: path19,
3975
+ path: path20,
3932
3976
  url,
3933
3977
  ...kind === "project-create" ? { pc_url: url } : {}
3934
3978
  };
@@ -4308,17 +4352,17 @@ function containsOuterReturn(value, root = true) {
4308
4352
  return containsOuterReturn(child, false);
4309
4353
  });
4310
4354
  }
4311
- function validateExpression(expression, path19, errors) {
4355
+ function validateExpression(expression, path20, errors) {
4312
4356
  try {
4313
4357
  const program2 = parse(`async function __bpmaxReport(ctx) {
4314
4358
  ${expression}
4315
4359
  }`, { ecmaVersion: "latest" });
4316
4360
  const reportFunction = program2.body[0];
4317
4361
  if (!containsOuterReturn(reportFunction)) {
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`);
4362
+ errors.push(`${path20} \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`);
4319
4363
  }
4320
4364
  } catch (error) {
4321
- errors.push(`${path19} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4365
+ errors.push(`${path20} \u4E0D\u662F\u5408\u6CD5\u7684 JavaScript \u5F02\u6B65\u51FD\u6570\u4F53\uFF1A${error instanceof Error ? error.message : String(error)}\u3002`);
4322
4366
  }
4323
4367
  }
4324
4368
  function analyzeFlowReportTemplate(value, options = {}) {
@@ -5112,9 +5156,9 @@ function summarizeOperationPlan(payload) {
5112
5156
  return "submit operation";
5113
5157
  }
5114
5158
  const method = typeof operation.method === "string" ? operation.method : "REQUEST";
5115
- const path19 = typeof operation.path === "string" ? operation.path : "";
5159
+ const path20 = typeof operation.path === "string" ? operation.path : "";
5116
5160
  const type = typeof operation.type === "string" ? ` ${operation.type}` : "";
5117
- return `submit${type}: ${method}${path19 ? ` ${path19}` : ""}`;
5161
+ return `submit${type}: ${method}${path20 ? ` ${path20}` : ""}`;
5118
5162
  }),
5119
5163
  ...skipped.slice(0, Math.max(0, 20 - operations.length)).map((operation) => {
5120
5164
  if (!isRecord4(operation)) {
@@ -6765,7 +6809,65 @@ function stepDetailPayloadWithLintArtifact(payload, submit) {
6765
6809
  function numericTemplateId(value) {
6766
6810
  return isRemoteNumericTemplateId(value) ? String(value).trim() : null;
6767
6811
  }
6768
- async function auditFlowStepDetailReferences(flowWork, profile) {
6812
+ function flowStepDetailBindingSnapshot(value) {
6813
+ const snapshot = /* @__PURE__ */ new Map();
6814
+ const data = isRecord4(value.data) ? value.data : {};
6815
+ const meta = isRecord4(data.meta) ? data.meta : {};
6816
+ const metaId = numericTemplateId(meta.step_detail_id);
6817
+ if (metaId) snapshot.set("data.meta.step_detail_id", metaId);
6818
+ const nodes = Array.isArray(data.nodes) ? data.nodes : [];
6819
+ nodes.forEach((node, index) => {
6820
+ if (!isRecord4(node)) return;
6821
+ const id = numericTemplateId(node.step_detail_id);
6822
+ if (!id) return;
6823
+ const stableNodeId = String(node.id ?? "").trim();
6824
+ snapshot.set(stableNodeId ? `node:${stableNodeId}` : `node-index:${index}`, id);
6825
+ });
6826
+ return snapshot;
6827
+ }
6828
+ function flowStepDetailBindingChanges(current, baseline) {
6829
+ const currentSnapshot = flowStepDetailBindingSnapshot(current);
6830
+ const baselineSnapshot = flowStepDetailBindingSnapshot(baseline);
6831
+ const keys = /* @__PURE__ */ new Set([...currentSnapshot.keys(), ...baselineSnapshot.keys()]);
6832
+ return [...keys].filter((key) => currentSnapshot.get(key) !== baselineSnapshot.get(key)).map((key) => `${key}: ${baselineSnapshot.get(key) ?? "<none>"} -> ${currentSnapshot.get(key) ?? "<none>"}`);
6833
+ }
6834
+ function isMissingStepDetailCapability(error) {
6835
+ const message = error instanceof Error ? error.message : String(error);
6836
+ return message.includes('capability "config.step_detail_template.export" is not allowed for profile') && message.includes("server did not grant this capability");
6837
+ }
6838
+ async function readFlowTemplateBaselineFromMeta(meta) {
6839
+ if (!isRecord4(meta) || meta.domain !== "flow-template" || typeof meta.raw_file !== "string" || typeof meta.base_hash !== "string") {
6840
+ return void 0;
6841
+ }
6842
+ const candidates = [
6843
+ path5.resolve(meta.raw_file),
6844
+ ...typeof meta.meta_file === "string" ? [path5.resolve(path5.dirname(meta.meta_file), meta.raw_file)] : []
6845
+ ];
6846
+ for (const candidate of [...new Set(candidates)]) {
6847
+ try {
6848
+ const raw = await readJsonFile(candidate);
6849
+ if (isRecord4(raw) && hashJson(raw) === meta.base_hash) return raw;
6850
+ } catch {
6851
+ }
6852
+ }
6853
+ return void 0;
6854
+ }
6855
+ async function inferFlowTemplateBaselineFromWorkFile(file) {
6856
+ if (path5.basename(path5.dirname(file)) !== "work") return void 0;
6857
+ const stem = path5.basename(file, path5.extname(file));
6858
+ const metaFile = path5.join(path5.dirname(path5.dirname(file)), "meta", `${stem}.meta.json`);
6859
+ try {
6860
+ const meta = await readJsonFile(metaFile);
6861
+ if (!isRecord4(meta)) return void 0;
6862
+ if (typeof meta.work_file === "string" && path5.resolve(meta.work_file) !== path5.resolve(file)) {
6863
+ return void 0;
6864
+ }
6865
+ return readFlowTemplateBaselineFromMeta({ ...meta, meta_file: metaFile });
6866
+ } catch {
6867
+ return void 0;
6868
+ }
6869
+ }
6870
+ async function auditFlowStepDetailReferences(flowWork, profile, baseline) {
6769
6871
  const errors = [];
6770
6872
  const warnings = [];
6771
6873
  const references = [];
@@ -6789,40 +6891,60 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6789
6891
  if (directId) ids.add(directId);
6790
6892
  });
6791
6893
  const templates = /* @__PURE__ */ new Map();
6894
+ let baselineFallback = false;
6895
+ let capabilityUnavailable = false;
6792
6896
  if (ids.size) {
6793
- await ensureConfigCapability(profile, "config.step_detail_template.export");
6794
- const definition = CONFIG_DOMAINS["step-detail-template"];
6795
- const remoteResults = await Promise.all([...ids].map(async (id) => {
6796
- try {
6797
- const remote = await readRemoteConfigDomain(profile, "step-detail-template", id, definition);
6798
- validateExpectedType("step-detail-template", definition, remote);
6799
- if (!isRecord4(remote)) {
6800
- throw new Error("\u8FDC\u7AEF\u54CD\u5E94\u4E0D\u662F\u6A21\u677F\u5BF9\u8C61");
6801
- }
6802
- const analysis = analyzeStepDetailTemplate(remote, { allowUndeclaredCustomModules: true });
6803
- return { id, remote, analysis, error: null };
6804
- } catch (error) {
6805
- return {
6806
- id,
6807
- remote: null,
6808
- analysis: null,
6809
- error: error instanceof Error ? error.message : String(error)
6810
- };
6811
- }
6812
- }));
6813
- remoteResults.forEach((result) => {
6814
- if (result.error || !result.remote || !result.analysis) {
6815
- errors.push(`step_detail_id=${result.id} \u65E0\u6CD5\u5728\u5F53\u524D profile \u56DE\u8BFB\u4E3A type=6 \u73AF\u8282\u8BE6\u60C5\u6A21\u677F\uFF1A${result.error || "\u8FDC\u7AEF\u54CD\u5E94\u65E0\u6548"}\u3002`);
6816
- return;
6897
+ try {
6898
+ await ensureConfigCapability(profile, "config.step_detail_template.export");
6899
+ } catch (error) {
6900
+ if (!isMissingStepDetailCapability(error)) throw error;
6901
+ const changes = baseline ? flowStepDetailBindingChanges(flowWork, baseline) : [];
6902
+ if (baseline && changes.length === 0) {
6903
+ baselineFallback = true;
6904
+ warnings.push(
6905
+ "[server_cli_capability_mismatch] \u670D\u52A1\u7AEF\u672A\u6CE8\u518C config.step_detail_template.export\uFF1B\u5F53\u524D step_detail_id \u7ED1\u5B9A\u4E0E\u5BFC\u51FA\u57FA\u7EBF\u4E00\u81F4\uFF0C\u672C\u6B21\u8DF3\u8FC7 type=6 \u6A21\u677F\u6DF1\u5EA6\u56DE\u8BFB\u3002\u63D0\u4EA4\u540E\u5FC5\u987B\u4F7F\u7528\u771F\u5B9E\u73AF\u8282\u9875\u9762\u5B8C\u6210\u8FD0\u884C\u6001\u9A8C\u6536\u3002"
6906
+ );
6907
+ } else {
6908
+ capabilityUnavailable = true;
6909
+ errors.push(
6910
+ "[server_cli_capability_mismatch] \u670D\u52A1\u7AEF\u672A\u6CE8\u518C config.step_detail_template.export\uFF0CCLI \u65E0\u6CD5\u6DF1\u5EA6\u6821\u9A8C type=6 \u73AF\u8282\u8BE6\u60C5\u6A21\u677F\u3002" + (baseline ? ` \u68C0\u6D4B\u5230 step_detail_id \u7ED1\u5B9A\u53D8\u5316\uFF1A${changes.join("; ")}\u3002\u8BF7\u5148\u5347\u7EA7\u670D\u52A1\u7AEF capability manifest\uFF0C\u6216\u6062\u590D\u4E3A\u5BFC\u51FA\u57FA\u7EBF\u540E\u518D\u5904\u7406\u65E0\u5173\u6D41\u7A0B\u4FEE\u6539\u3002` : " \u672A\u627E\u5230\u53EF\u4FE1\u5BFC\u51FA\u57FA\u7EBF\uFF0C\u4E0D\u80FD\u628A\u8BE5\u9519\u8BEF\u964D\u7EA7\u4E3A warning\uFF1B\u8BF7\u4F7F\u7528 config flow-template export \u751F\u6210\u6807\u51C6 raw/work/meta \u6587\u4EF6\u540E\u91CD\u8BD5\u3002")
6911
+ );
6817
6912
  }
6818
- errors.push(...result.analysis.errors.map((message) => `step_detail_id=${result.id}: ${message}`));
6819
- warnings.push(...result.analysis.warnings.map((message) => `step_detail_id=${result.id}: ${message}`));
6820
- templates.set(result.id, {
6821
- record: result.remote,
6822
- analysis: result.analysis,
6823
- structuralOk: result.analysis.errors.length === 0
6913
+ }
6914
+ if (!baselineFallback && !capabilityUnavailable) {
6915
+ const definition = CONFIG_DOMAINS["step-detail-template"];
6916
+ const remoteResults = await Promise.all([...ids].map(async (id) => {
6917
+ try {
6918
+ const remote = await readRemoteConfigDomain(profile, "step-detail-template", id, definition);
6919
+ validateExpectedType("step-detail-template", definition, remote);
6920
+ if (!isRecord4(remote)) {
6921
+ throw new Error("\u8FDC\u7AEF\u54CD\u5E94\u4E0D\u662F\u6A21\u677F\u5BF9\u8C61");
6922
+ }
6923
+ const analysis = analyzeStepDetailTemplate(remote, { allowUndeclaredCustomModules: true });
6924
+ return { id, remote, analysis, error: null };
6925
+ } catch (error) {
6926
+ return {
6927
+ id,
6928
+ remote: null,
6929
+ analysis: null,
6930
+ error: error instanceof Error ? error.message : String(error)
6931
+ };
6932
+ }
6933
+ }));
6934
+ remoteResults.forEach((result) => {
6935
+ if (result.error || !result.remote || !result.analysis) {
6936
+ errors.push(`step_detail_id=${result.id} \u65E0\u6CD5\u5728\u5F53\u524D profile \u56DE\u8BFB\u4E3A type=6 \u73AF\u8282\u8BE6\u60C5\u6A21\u677F\uFF1A${result.error || "\u8FDC\u7AEF\u54CD\u5E94\u65E0\u6548"}\u3002`);
6937
+ return;
6938
+ }
6939
+ errors.push(...result.analysis.errors.map((message) => `step_detail_id=${result.id}: ${message}`));
6940
+ warnings.push(...result.analysis.warnings.map((message) => `step_detail_id=${result.id}: ${message}`));
6941
+ templates.set(result.id, {
6942
+ record: result.remote,
6943
+ analysis: result.analysis,
6944
+ structuralOk: result.analysis.errors.length === 0
6945
+ });
6824
6946
  });
6825
- });
6947
+ }
6826
6948
  }
6827
6949
  if (metaConfigured) {
6828
6950
  const template = metaId ? templates.get(metaId) : void 0;
@@ -6831,7 +6953,7 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6831
6953
  source: metaId ? "flow_default" : "invalid_flow_default",
6832
6954
  configured_value: meta.step_detail_id,
6833
6955
  effective_id: metaId,
6834
- status: metaId && template?.structuralOk ? "verified" : "invalid",
6956
+ status: !metaId ? "invalid" : template?.structuralOk ? "verified" : baselineFallback ? "baseline_confirmed" : capabilityUnavailable ? "unverified" : "invalid",
6835
6957
  template_name: template?.record.name ?? null,
6836
6958
  template_type: template?.record.type ?? null,
6837
6959
  template_structural_ok: template ? template.structuralOk : null,
@@ -6839,7 +6961,7 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6839
6961
  modules: template?.analysis.moduleNames ?? [],
6840
6962
  unknown_modules: template?.analysis.unknownModules ?? [],
6841
6963
  custom_modules: template?.analysis.customModules ?? [],
6842
- runtime_proof_required: template?.analysis.requiresRuntimeProof ?? false
6964
+ runtime_proof_required: baselineFallback || (template?.analysis.requiresRuntimeProof ?? false)
6843
6965
  });
6844
6966
  }
6845
6967
  nodes.forEach(({ node, index }) => {
@@ -6852,7 +6974,7 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6852
6974
  const hideStepDetail = node.hide_step_detail === true;
6853
6975
  const hasStepForm = !isEmptyTemplateReference(node.form_template);
6854
6976
  const enableRelatedProjectForm = node.enable_relate_project_form === true;
6855
- let suitability = hideStepDetail ? "hidden" : source === "invalid_node_reference" || source === "invalid_flow_default" ? "invalid" : effectiveId ? template?.structuralOk ? "verified" : "mismatch" : "platform_default_layout";
6977
+ let suitability = hideStepDetail ? "hidden" : source === "invalid_node_reference" || source === "invalid_flow_default" ? "invalid" : effectiveId ? template?.structuralOk ? "verified" : baselineFallback ? "runtime_proof_required" : capabilityUnavailable ? "unverified" : "mismatch" : "platform_default_layout";
6856
6978
  if (hideStepDetail && effectiveId) {
6857
6979
  warnings.push(`${nodeName} \u5DF2\u8BBE\u7F6E hide_step_detail=true\uFF0C\u4F46\u4ECD\u7ED1\u5B9A step_detail_id=${effectiveId}\uFF1B\u8BE5\u6A21\u677F\u4E0D\u4F1A\u4F5C\u4E3A\u6B63\u5E38\u73AF\u8282\u8BE6\u60C5\u5165\u53E3\u5C55\u793A\u3002`);
6858
6980
  }
@@ -6880,7 +7002,7 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6880
7002
  hide_step_detail: hideStepDetail,
6881
7003
  form_template: node.form_template ?? null,
6882
7004
  enable_relate_project_form: enableRelatedProjectForm,
6883
- status: source === "invalid_node_reference" || source === "invalid_flow_default" ? "invalid" : effectiveId ? template?.structuralOk ? "verified" : "invalid" : "not_configured",
7005
+ status: source === "invalid_node_reference" || source === "invalid_flow_default" ? "invalid" : effectiveId ? template?.structuralOk ? "verified" : baselineFallback ? "baseline_confirmed" : capabilityUnavailable ? "unverified" : "invalid" : "not_configured",
6884
7006
  suitability,
6885
7007
  template_name: template?.record.name ?? null,
6886
7008
  template_type: template?.record.type ?? null,
@@ -6889,7 +7011,7 @@ async function auditFlowStepDetailReferences(flowWork, profile) {
6889
7011
  modules: template?.analysis.moduleNames ?? [],
6890
7012
  unknown_modules: template?.analysis.unknownModules ?? [],
6891
7013
  custom_modules: template?.analysis.customModules ?? [],
6892
- runtime_proof_required: template?.analysis.requiresRuntimeProof ?? false
7014
+ runtime_proof_required: baselineFallback || (template?.analysis.requiresRuntimeProof ?? false)
6893
7015
  });
6894
7016
  });
6895
7017
  return { errors, warnings, references };
@@ -7164,23 +7286,23 @@ function lintConsoleTemplateDataSource(dataSource, moduleLabel, errors) {
7164
7286
  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`);
7165
7287
  }
7166
7288
  }
7167
- function lintConsoleTemplateWildcardFallback(value, path19, errors) {
7289
+ function lintConsoleTemplateWildcardFallback(value, path20, errors) {
7168
7290
  if (typeof value === "string") {
7169
- const scriptedWildcard = /(?:wildcard|value)\s*:\s*['\"](\*{1,2})['\"]/i.exec(value);
7291
+ const scriptedWildcard = /(?:wildcard|value)\s*:\s*(['\"])(\*{1,2})\1(?=\s*(?:[,};)\]]|$))/i.exec(value);
7170
7292
  if (scriptedWildcard) {
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`);
7293
+ errors.push(`${path20}.wildcard \u4E0D\u80FD\u7528 ${scriptedWildcard[2]} \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`);
7172
7294
  }
7173
7295
  return;
7174
7296
  }
7175
7297
  if (Array.isArray(value)) {
7176
- value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path19}[${index}]`, errors));
7298
+ value.forEach((item, index) => lintConsoleTemplateWildcardFallback(item, `${path20}[${index}]`, errors));
7177
7299
  return;
7178
7300
  }
7179
7301
  if (!isRecord4(value)) {
7180
7302
  return;
7181
7303
  }
7182
7304
  Object.entries(value).forEach(([key, item]) => {
7183
- const nextPath = `${path19}.${key}`;
7305
+ const nextPath = `${path20}.${key}`;
7184
7306
  if ((key === "wildcard" || key === "value") && (item === "*" || item === "**")) {
7185
7307
  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`);
7186
7308
  }
@@ -7392,7 +7514,18 @@ function lintConsoleTemplateFrontendDetailCounting(script, dataSource, moduleLab
7392
7514
  const hasControlledOuterPageSize = /ctx\.pageInfo[\s\S]*?(?:pageSize|page_size)/i.test(outerPageSizeBinding) && !/\b(?:total|count|length)\b/i.test(outerPageSizeBinding);
7393
7515
  const hasControlledOuterPage = /ctx\.pageInfo[\s\S]*?(?:\.page\b|pageIndex|current)/i.test(outerPageBinding) && !/\b(?:total|count|length)\b/i.test(outerPageBinding);
7394
7516
  const usesBodyInEsSearch = (code) => /\bctx\.\$searchByEs\s*\(\s*{\s*body(?:\s*:\s*body)?\s*[,}]/i.test(code);
7395
- const hasCustomBpmaxAggregation = customServerCodes.some((code) => /\b(?:const|let)\s+body\s*=\s*{[\s\S]*?\bsize\s*:\s*0\b[\s\S]*?\b(?:aggs|aggregations)\s*:\s*{/i.test(code) && usesBodyInEsSearch(code));
7517
+ const usesQueryObjectInEsSearch = (code, queryName) => {
7518
+ const escaped = queryName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
7519
+ if (queryName === "body" && usesBodyInEsSearch(code)) return true;
7520
+ return new RegExp(`\\bctx\\.\\$searchByEs\\s*\\(\\s*\\{[^)]{0,1000}?\\bbody\\s*:\\s*${escaped}\\s*[,}]`, "i").test(code);
7521
+ };
7522
+ const hasCustomBpmaxAggregation = customServerCodes.some((code) => {
7523
+ const aggregationQueryPattern = /\b(?:const|let)\s+([A-Za-z_$][\w$]*)\s*=\s*{[\s\S]*?\bsize\s*:\s*0\b[\s\S]*?\b(?:aggs|aggregations)\s*:\s*{/gi;
7524
+ for (let match = aggregationQueryPattern.exec(code); match; match = aggregationQueryPattern.exec(code)) {
7525
+ if (usesQueryObjectInEsSearch(code, match[1])) return true;
7526
+ }
7527
+ return /\bctx\.\$searchByEs\s*\(\s*{[^)]{0,1000}?\bbody\s*:\s*{[\s\S]*?\bsize\s*:\s*0\b[\s\S]*?\b(?:aggs|aggregations)\s*:\s*{/i.test(code);
7528
+ });
7396
7529
  const hasCustomBpmaxServerPagination = customServerCodes.some((code) => {
7397
7530
  const pageSizeBinding = /\b(?:const|let)\s+pageSize\s*=\s*([^;]+)/i.exec(code)?.[1] || "";
7398
7531
  const pageBinding = /\b(?:const|let)\s+page\s*=\s*([^;]+)/i.exec(code)?.[1] || "";
@@ -12555,24 +12688,24 @@ function normalizeTypedReadbackComparable(domain, value) {
12555
12688
  }
12556
12689
  function jsonSubsetMismatches(expected, actual) {
12557
12690
  const mismatches = [];
12558
- const compare = (left, right, path19 = "") => {
12691
+ const compare = (left, right, path20 = "") => {
12559
12692
  if (Array.isArray(left)) {
12560
12693
  if (!Array.isArray(right) || left.length !== right.length) {
12561
- mismatches.push(path19 || "/");
12694
+ mismatches.push(path20 || "/");
12562
12695
  return;
12563
12696
  }
12564
- left.forEach((item, index) => compare(item, right[index], `${path19}/${index}`));
12697
+ left.forEach((item, index) => compare(item, right[index], `${path20}/${index}`));
12565
12698
  return;
12566
12699
  }
12567
12700
  if (isRecord4(left)) {
12568
12701
  if (!isRecord4(right)) {
12569
- mismatches.push(path19 || "/");
12702
+ mismatches.push(path20 || "/");
12570
12703
  return;
12571
12704
  }
12572
- for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path19}/${key}`);
12705
+ for (const [key, item] of Object.entries(left)) compare(item, right[key], `${path20}/${key}`);
12573
12706
  return;
12574
12707
  }
12575
- if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path19 || "/");
12708
+ if (JSON.stringify(left) !== JSON.stringify(right)) mismatches.push(path20 || "/");
12576
12709
  };
12577
12710
  compare(expected, actual);
12578
12711
  return mismatches;
@@ -13438,7 +13571,11 @@ async function buildConfigSubmitPayload(domain, workFile, outFile, metaFile, opt
13438
13571
  if (flowCategoryReferenceAudit.errors.length) {
13439
13572
  throw new Error(`flow-template category reference gate failed: ${flowCategoryReferenceAudit.errors.join("; ")}`);
13440
13573
  }
13441
- stepDetailReferenceAudit = await auditFlowStepDetailReferences(work, options.pluginLint.profile);
13574
+ stepDetailReferenceAudit = await auditFlowStepDetailReferences(
13575
+ work,
13576
+ options.pluginLint.profile,
13577
+ isRecord4(raw) ? raw : void 0
13578
+ );
13442
13579
  if (stepDetailReferenceAudit.errors.length) {
13443
13580
  throw new Error(`flow-template step-detail reference gate failed: ${stepDetailReferenceAudit.errors.join("; ")}`);
13444
13581
  }
@@ -13656,6 +13793,7 @@ function hasPotentialFlowTemplatePluginExtension(flowWork) {
13656
13793
  }
13657
13794
  async function lintConfigWorkFile(file, options = {}) {
13658
13795
  const value = await readJsonFile(file);
13796
+ const flowTemplateBaseline = options.domain === "flow-template" ? await inferFlowTemplateBaselineFromWorkFile(file) : void 0;
13659
13797
  const errors = [];
13660
13798
  const warnings = [];
13661
13799
  let pluginLint;
@@ -13736,7 +13874,7 @@ async function lintConfigWorkFile(file, options = {}) {
13736
13874
  if (profile) {
13737
13875
  flowCategoryReferenceAudit = await auditFlowCategoryReference(flowWork, profile);
13738
13876
  errors.push(...flowCategoryReferenceAudit.errors.filter((error) => !errors.includes(error)));
13739
- stepDetailReferenceAudit = await auditFlowStepDetailReferences(flowWork, profile);
13877
+ stepDetailReferenceAudit = await auditFlowStepDetailReferences(flowWork, profile, flowTemplateBaseline);
13740
13878
  errors.push(...stepDetailReferenceAudit.errors.filter((error) => !errors.includes(error)));
13741
13879
  warnings.push(...stepDetailReferenceAudit.warnings);
13742
13880
  flowReportReferenceAudit = await auditFlowReportReferences(flowWork, profile);
@@ -14293,7 +14431,11 @@ async function submitConfigDomain(config, profile, domain, id, submitFile, confi
14293
14431
  if (flowCategoryReferenceAudit.errors.length) {
14294
14432
  throw new Error(`flow-template category reference gate failed: ${flowCategoryReferenceAudit.errors.join("; ")}`);
14295
14433
  }
14296
- stepDetailReferenceAudit = await auditFlowStepDetailReferences(submit.payload, profile);
14434
+ stepDetailReferenceAudit = await auditFlowStepDetailReferences(
14435
+ submit.payload,
14436
+ profile,
14437
+ await readFlowTemplateBaselineFromMeta(submit.meta)
14438
+ );
14297
14439
  if (stepDetailReferenceAudit.errors.length) {
14298
14440
  throw new Error(`flow-template step-detail reference gate failed: ${stepDetailReferenceAudit.errors.join("; ")}`);
14299
14441
  }
@@ -17804,9 +17946,9 @@ function registerConfigCommands(program2) {
17804
17946
  }
17805
17947
 
17806
17948
  // src/commands/e2e.ts
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";
17949
+ import { createHash as createHash8 } from "crypto";
17950
+ import { mkdir as mkdir12, readFile as readFile16, readdir as readdir5, stat as stat9, writeFile as writeFile12 } from "fs/promises";
17951
+ import path15 from "path";
17810
17952
  import axios7 from "axios";
17811
17953
 
17812
17954
  // src/core/e2e-browser-runner.ts
@@ -18115,7 +18257,7 @@ var PRIORITIES = /* @__PURE__ */ new Set(["P0", "P1", "P2"]);
18115
18257
  var CASE_TYPES = /* @__PURE__ */ new Set(["positive", "negative", "boundary", "permission", "data_consistency", "regression"]);
18116
18258
  var STATUSES = /* @__PURE__ */ new Set(["active", "deprecated", "draft"]);
18117
18259
  var CASE_STEP_RUNNERS = /* @__PURE__ */ new Set(["browser", "browser_action", "identity", "e2e_create_page", "e2e_step_run", "observe"]);
18118
- var IDENTITY_STEP_RE = /(?:切换|恢复|检查|核对|验证).{0,12}(?:身份|用户|管理员)|(?:mock|unmock|模拟用户)/i;
18260
+ var IDENTITY_STEP_RE = /(?:切换|恢复|检查|核对|验证|确认|读取).{0,12}(?:身份|用户|管理员)|(?:mock|unmock|模拟用户)/i;
18119
18261
  var CASE_STEP_ACTION_VERBS = [
18120
18262
  "\u6253\u5F00",
18121
18263
  "\u8FDB\u5165",
@@ -18215,10 +18357,19 @@ var YBS_NONZERO_DETAIL_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/project
18215
18357
  var YBS_PC_CREATE_WRONG_RE = /https:\/\/yaditest\.yitaiyitai\.com\/w:ybs\/pages\/projectCreate\/projectCreate\?flow_type=/;
18216
18358
  var IDENTITY_MOCK_CASE_RE = /(非处理人|越权|只读|多角色|角色隔离|无权限|低权限|unauthorized|limited|readonly|permission)/;
18217
18359
  var IDENTITY_MOCK_VALUE_RE = /(mock|模拟).*(unmock|退出模拟|恢复)|bpmax-user-mock-operator/;
18360
+ var IDENTITY_BROWSER_BRIDGE_RE = /(identity_transport\s*=\s*chrome_bridge|chrome identity bridge|Chrome Control 身份桥|浏览器身份桥)/i;
18361
+ var IDENTITY_COOKIE_TRANSPORT_RE = /(BPMAX_COOKIE_HEADER|cookie[_ -]?env|cookie transport|导出.*Cookie|复制.*Cookie)/i;
18218
18362
  var E2E_REUSABLE_ASSET_RE = /bpmax-cli\s+e2e|record-from-evidence|create-page-submit|step-run|browser-template|scenario\s+plan|data\s+profile|reusable\s+step|复用模板|可复用|首次运行沉淀|沉淀模板/;
18219
18363
  var ERROR_CAPTURE_CASE_RE = /(negative|boundary|异常|错误|失败|报错|无效|非法|invalid|error|扫码.*(异常|错误|无效)|错误\s*SN|异常\s*SN|无效\s*SN)/i;
18220
18364
  var ERROR_CAPTURE_EVIDENCE_RE = /(expected_error_text|error_capture_required|错误提示|提示文案|报错文案|toast|校验文案).*(screenshot|截图)|截图.*(错误提示|提示文案|报错文案|toast|校验文案)/i;
18221
- var BROWSER_TOOL_RE = /(Chrome DevTools|DevTools|Playwright|AppleScript)/i;
18365
+ function identityStepOperation(step) {
18366
+ const text5 = [step.action, step.target, step.input_data, step.expected_result].join(" ");
18367
+ if (/(unmock|退出模拟|恢复原始|恢复管理员)/i.test(text5)) return "unmock";
18368
+ if (/(status|当前身份|身份回读|(?:确认|检查|读取|核对).{0,8}身份)/i.test(text5)) return "status";
18369
+ if (/(mock|模拟用户|切换.{0,8}(?:身份|用户))/i.test(text5)) return "mock";
18370
+ return null;
18371
+ }
18372
+ var BROWSER_TOOL_RE = /(Chrome Control|chrome:control-chrome|Chrome DevTools|DevTools|Playwright|AppleScript)/i;
18222
18373
  var REPORT_EVIDENCE_PLACEHOLDER_RE = /^(?:n\/?a|none|null|todo|tbd|xxx|unknown|pending|待补|暂无|无|未执行|跳过|-+)$/i;
18223
18374
  var LIVE_DRAFT_RE = /(live|draft|已发布|草稿|发布态|live_draft=)/i;
18224
18375
  var MULTI_ROLE_VALUE_RE = /[,、/]\s*[^,、/\s]+|多角色|跨角色/;
@@ -18675,7 +18826,7 @@ function validatePreflightEvidence(filePath, caseId, row, steps, prepTokens) {
18675
18826
  fail(`${filePath}:${caseId}: \`prep_data\` \u5FC5\u987B\u5305\u542B \`precondition_check=\`\uFF0C\u5426\u5219\u53EA\u80FD\u8FDB\u5165\u51C6\u5907\u9636\u6BB5\uFF0C\u4E0D\u80FD\u5F00\u59CB\u6B63\u5F0F E2E \u6267\u884C`, { rule_id: "test_suite.case.precondition_check" });
18676
18827
  }
18677
18828
  if (!prepTokens.browser_tool || !BROWSER_TOOL_RE.test(prepTokens.browser_tool)) {
18678
- fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u6D4F\u89C8\u5668\u5DE5\u5177\u8BC1\u636E\uFF0C\u4F8B\u5982 \`browser_tool=Chrome DevTools\` \u6216 AppleScript fallback`, { rule_id: "test_suite.case.browser_tool" });
18829
+ fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u6D4F\u89C8\u5668\u5DE5\u5177\u8BC1\u636E\uFF1B\u9996\u6B21\u5F55\u5236\u548C\u5F02\u5E38\u63A2\u7D22\u4F18\u5148\u4F7F\u7528 \`browser_tool=Chrome Control\`\uFF0C\u7A33\u5B9A\u590D\u8DD1\u4F7F\u7528 Playwright`, { rule_id: "test_suite.case.browser_tool" });
18679
18830
  }
18680
18831
  if (!prepTokens.live_draft || !LIVE_DRAFT_RE.test(prepTokens.live_draft)) {
18681
18832
  fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u672C\u8F6E\u76EE\u6807\u662F live \u53D1\u5E03\u6001\u8FD8\u662F draft \u8349\u7A3F\u6001`, { rule_id: "test_suite.case.live_draft" });
@@ -18809,16 +18960,16 @@ function validateCaseSteps(filePath, cases, steps) {
18809
18960
  if (step.runner === "e2e_step_run" && !/(context|submit|readback|step)/i.test(step.evidence_required)) {
18810
18961
  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 });
18811
18962
  }
18812
- const identityStepText = [step.action, step.target, step.input_data, step.expected_result].join(" ");
18813
- if (step.runner === "e2e_step_run" && IDENTITY_STEP_RE.test(identityStepText)) {
18814
- fail(`${location}: identity mock/status/unmock \u4E0D\u80FD\u58F0\u660E\u4E3A e2e_step_run\uFF1B\u8BF7\u4F7F\u7528 runner=identity`, {
18963
+ const identityOperation = identityStepOperation(step);
18964
+ if (step.runner !== "identity" && identityOperation) {
18965
+ fail(`${location}: identity ${identityOperation} \u4E0D\u80FD\u58F0\u660E\u4E3A runner=${step.runner}\uFF1B\u8BF7\u4F7F\u7528 runner=identity`, {
18815
18966
  rule_id: "test_suite.case_step.identity_runner",
18816
18967
  path: filePath,
18817
18968
  suggestion: "Set runner=identity and require identity operation plus readback evidence."
18818
18969
  });
18819
18970
  }
18820
18971
  if (step.runner === "identity") {
18821
- if (!IDENTITY_STEP_RE.test(identityStepText)) {
18972
+ if (!identityOperation) {
18822
18973
  fail(`${location}: runner=identity \u53EA\u80FD\u7528\u4E8E\u8EAB\u4EFD mock/status/unmock \u6B65\u9AA4`, {
18823
18974
  rule_id: "test_suite.case_step.identity_action",
18824
18975
  path: filePath
@@ -18830,6 +18981,25 @@ function validateCaseSteps(filePath, cases, steps) {
18830
18981
  path: filePath
18831
18982
  });
18832
18983
  }
18984
+ const identityContractText = [step.input_data, step.evidence_required].join(" ");
18985
+ if (!IDENTITY_BROWSER_BRIDGE_RE.test(identityContractText)) {
18986
+ fail(`${location}: \u6B63\u5F0F identity \u6B65\u9AA4\u5FC5\u987B\u5728 input_data \u58F0\u660E identity_transport=chrome_bridge\uFF0C\u5E76\u7531 Chrome Control \u8EAB\u4EFD\u6865\u6267\u884C`, {
18987
+ rule_id: "test_suite.case_step.identity_browser_bridge",
18988
+ path: filePath
18989
+ });
18990
+ }
18991
+ if (IDENTITY_COOKIE_TRANSPORT_RE.test(identityContractText)) {
18992
+ fail(`${location}: \u6B63\u5F0F identity \u6B65\u9AA4\u7981\u6B62 Cookie transport\uFF1B\u4E0D\u5F97\u5BFC\u51FA\u6216\u590D\u5236\u6D4F\u89C8\u5668 Cookie`, {
18993
+ rule_id: "test_suite.case_step.identity_cookie_transport",
18994
+ path: filePath
18995
+ });
18996
+ }
18997
+ if (!/screenshot|截图/i.test(step.evidence_required)) {
18998
+ fail(`${location}: identity \u6B65\u9AA4\u5FC5\u987B\u8981\u6C42\u672C\u8F6E Chrome \u8EAB\u4EFD\u622A\u56FE`, {
18999
+ rule_id: "test_suite.case_step.identity_screenshot",
19000
+ path: filePath
19001
+ });
19002
+ }
18833
19003
  }
18834
19004
  const values = grouped.get(caseId) ?? [];
18835
19005
  values.push(step);
@@ -18846,6 +19016,48 @@ function validateCaseSteps(filePath, cases, steps) {
18846
19016
  fail(`${filePath}:${row.case_id}: step_no \u5FC5\u987B\u4ECE 1 \u5F00\u59CB\u8FDE\u7EED\u9012\u589E`, { rule_id: "test_suite.case_step.sequence", path: filePath });
18847
19017
  }
18848
19018
  });
19019
+ let statusReady = false;
19020
+ let activeMock = null;
19021
+ for (const step of caseSteps.filter((item) => item.runner === "identity")) {
19022
+ const operation = identityStepOperation(step);
19023
+ if (operation === "status") {
19024
+ statusReady = true;
19025
+ continue;
19026
+ }
19027
+ if (operation === "mock") {
19028
+ if (!statusReady) {
19029
+ fail(`${filePath}:${row.case_id}:${step.step_id}: mock \u524D\u5FC5\u987B\u6709\u672C\u8F6E\u72EC\u7ACB identity status \u6B65\u9AA4`, {
19030
+ rule_id: "test_suite.case_step.identity_status_before_mock",
19031
+ path: filePath
19032
+ });
19033
+ }
19034
+ if (activeMock) {
19035
+ fail(`${filePath}:${row.case_id}:${step.step_id}: \u524D\u4E00\u4E2A mock ${activeMock.step_id} \u5C1A\u672A unmock\uFF0C\u7981\u6B62\u53E0\u52A0\u8EAB\u4EFD\u79DF\u7EA6`, {
19036
+ rule_id: "test_suite.case_step.identity_nested_mock",
19037
+ path: filePath
19038
+ });
19039
+ }
19040
+ activeMock = step;
19041
+ statusReady = false;
19042
+ continue;
19043
+ }
19044
+ if (operation === "unmock") {
19045
+ if (!activeMock) {
19046
+ fail(`${filePath}:${row.case_id}:${step.step_id}: unmock \u5FC5\u987B\u5BF9\u5E94\u5F53\u524D\u7528\u4F8B\u4E2D\u66F4\u65E9\u7684 mock \u6B65\u9AA4`, {
19047
+ rule_id: "test_suite.case_step.identity_unmock_without_mock",
19048
+ path: filePath
19049
+ });
19050
+ }
19051
+ activeMock = null;
19052
+ statusReady = false;
19053
+ }
19054
+ }
19055
+ if (activeMock) {
19056
+ fail(`${filePath}:${row.case_id}:${activeMock.step_id}: \u6BCF\u4E2A mock \u5FC5\u987B\u5728\u7528\u4F8B\u7ED3\u675F\u524D\u6709\u540E\u7EED identity unmock \u6B65\u9AA4`, {
19057
+ rule_id: "test_suite.case_step.identity_unmock_required",
19058
+ path: filePath
19059
+ });
19060
+ }
18849
19061
  grouped.set(row.case_id.trim(), caseSteps);
18850
19062
  }
18851
19063
  return grouped;
@@ -19263,11 +19475,12 @@ async function evidenceJsonRecords(evidencePath) {
19263
19475
  }
19264
19476
  return records;
19265
19477
  }
19266
- async function browserEvidenceScreenshots(manifest, manifestPath, step, evidencePath, expectedResult = "pass") {
19478
+ async function browserEvidenceScreenshots(manifest, manifestPath, step, evidencePath, expectedResult = "pass", recordFilter) {
19267
19479
  const jsonRecords = await evidenceJsonRecords(evidencePath);
19268
19480
  const screenshotPaths = [];
19269
19481
  let matchedRecord = false;
19270
19482
  for (const { value, source } of jsonRecords) {
19483
+ if (recordFilter && !recordFilter(value)) continue;
19271
19484
  if (value.browser_verified !== true) continue;
19272
19485
  if (value.case_id !== step.case_id || value.case_step_id !== step.step_id) continue;
19273
19486
  const runtimeUrl = typeof value.runtime_url === "string" ? value.runtime_url.trim() : "";
@@ -19357,7 +19570,8 @@ async function hasStructuredTerminalEvidence(manifest, step, evidencePath, resul
19357
19570
  if (result === "blocked") return hasStructuredBlockedEvidence(manifest, step, evidencePath);
19358
19571
  for (const { value, source } of await evidenceJsonRecords(evidencePath)) {
19359
19572
  if (value.case_id !== step.case_id || value.case_step_id !== step.step_id) continue;
19360
- if (value.failed !== true && !["fail", "failed", "error"].includes(String(value.status || "").toLowerCase())) continue;
19573
+ const terminalStatus = String(value.status || value.result || "").toLowerCase();
19574
+ if (value.failed !== true && !["fail", "failed", "error"].includes(terminalStatus)) continue;
19361
19575
  const failure = asRecord(value.failure);
19362
19576
  const error = asRecord(value.error);
19363
19577
  const detail = Object.keys(failure).length > 0 ? failure : error;
@@ -19391,7 +19605,7 @@ async function browserReportEvidence(manifest) {
19391
19605
  const result = { assertions: [], screenshots: [] };
19392
19606
  const priority = { page: 1, project: 2, step: 3 };
19393
19607
  for (const step of manifest.steps) {
19394
- if (step.status === "planned" || !["browser", "browser_action", "e2e_create_page"].includes(step.runner)) continue;
19608
+ if (step.status === "planned" || !["browser", "browser_action", "e2e_create_page", "identity"].includes(step.runner)) continue;
19395
19609
  for (const evidencePath of step.evidence) {
19396
19610
  for (const { value, source } of await evidenceJsonRecords(evidencePath)) {
19397
19611
  if (value.case_id !== step.case_id || value.case_step_id !== step.step_id || value.browser_verified !== true) continue;
@@ -19399,13 +19613,18 @@ async function browserReportEvidence(manifest) {
19399
19613
  if (!["page", "project", "step"].includes(scope)) continue;
19400
19614
  const environment = String(value.runtime_environment || "profile");
19401
19615
  if (!["profile", "local-browser"].includes(environment)) continue;
19402
- if (!result.scope || priority[scope] >= priority[result.scope]) {
19616
+ if (step.runner !== "identity" && (!result.scope || priority[scope] >= priority[result.scope])) {
19403
19617
  result.scope = scope;
19404
19618
  result.environment = environment;
19405
19619
  result.runtimeUrl = String(value.runtime_url || "").trim() || result.runtimeUrl;
19406
19620
  result.browserTool = String(value.browser_tool || "").trim() || result.browserTool;
19407
19621
  result.projectId = String(value.project_id ?? "").trim() || void 0;
19408
19622
  result.stepId = String(value.step_id ?? "").trim() || void 0;
19623
+ } else if (step.runner === "identity" && !result.scope) {
19624
+ result.scope = scope;
19625
+ result.environment = environment;
19626
+ result.runtimeUrl = String(value.runtime_url || "").trim() || result.runtimeUrl;
19627
+ result.browserTool = String(value.browser_tool || "").trim() || result.browserTool;
19409
19628
  }
19410
19629
  const assertions = Array.isArray(value.assertions) ? value.assertions.map(asRecord) : [];
19411
19630
  for (const assertion of assertions) {
@@ -19464,7 +19683,7 @@ async function syncTestSuiteRunReportUnlocked(manifestFile) {
19464
19683
  report = replaceReportMetadata(report, "runtime_scope", evidence.scope || null);
19465
19684
  report = replaceReportMetadata(report, "runtime_environment", evidence.environment || null);
19466
19685
  report = replaceReportMetadata(report, "runtime_url", evidence.runtimeUrl || null);
19467
- report = replaceReportMetadata(report, "browser_tool", evidence.browserTool || "Chrome DevTools");
19686
+ report = replaceReportMetadata(report, "browser_tool", evidence.browserTool || "Chrome Control");
19468
19687
  report = replaceReportMetadata(report, "browser_action_log", actions || null);
19469
19688
  report = replaceReportMetadata(report, "visible_assertions", evidence.assertions.length ? evidence.assertions.join("\uFF1B") : null);
19470
19689
  report = replaceReportMetadata(report, "project_id", evidence.scope === "project" || evidence.scope === "step" ? evidence.projectId || null : null);
@@ -19494,7 +19713,7 @@ async function previousBrowserScreenshotHashes(manifest, step) {
19494
19713
  const hashes = /* @__PURE__ */ new Set();
19495
19714
  for (const previous of manifest.steps) {
19496
19715
  if (previous.step_no === step.step_no) break;
19497
- if (previous.status !== "pass" || !["browser", "browser_action", "e2e_create_page"].includes(previous.runner)) continue;
19716
+ if (previous.status !== "pass" || !["browser", "browser_action", "e2e_create_page", "identity"].includes(previous.runner)) continue;
19498
19717
  for (const previousEvidence of previous.evidence) {
19499
19718
  for (const { value, source } of await evidenceJsonRecords(previousEvidence)) {
19500
19719
  const screenshot = typeof value.screenshot === "string" ? value.screenshot.trim() : "";
@@ -19517,22 +19736,49 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
19517
19736
  fail("e2e_step_run pass evidence must prove a confirmed submitted operation", { rule_id: "test_suite.run.unexecuted_evidence", path: evidencePath });
19518
19737
  }
19519
19738
  if (step.runner === "identity") {
19739
+ const expectedIdentityOperation = identityStepOperation(step);
19520
19740
  const validIdentityEvidence = jsonRecords.some(({ value }) => {
19741
+ if (value.case_id !== step.case_id || value.case_step_id !== step.step_id || value.transport !== "chrome_identity_bridge" || value.browser_tool !== "chrome:control-chrome" || value.browser_verified !== true || value.readback_confirmed !== true) {
19742
+ return false;
19743
+ }
19744
+ const assertions = Array.isArray(value.assertions) ? value.assertions.map(asRecord).filter((assertion) => Object.keys(assertion).length > 0) : [];
19745
+ if (assertions.length === 0 || assertions.some((assertion) => assertion.passed !== true)) return false;
19521
19746
  const operation = String(value.operation || "").toLowerCase();
19747
+ if (!expectedIdentityOperation || operation !== expectedIdentityOperation) return false;
19522
19748
  if (operation === "status") {
19523
- return ["observed", "verified"].includes(String(value.result || value.status || "").toLowerCase()) && Object.keys(asRecord(value.current_user)).length > 0;
19749
+ return ["observed", "verified"].includes(String(value.result || value.status || "").toLowerCase()) && value.mutation_attempted !== true && value.operation_executed === false && value.remote_submitted === false && Object.keys(asRecord(value.current_user)).length > 0;
19524
19750
  }
19525
19751
  if (operation === "mock" || operation === "unmock") {
19526
- return value.operation_executed === true && value.remote_submitted === true && value.readback_confirmed === true;
19752
+ const currentUser = asRecord(value.current_user);
19753
+ return value.operation_executed === true && value.mutation_attempted === true && value.remote_submitted === true && value.readback_confirmed === true && (operation === "mock" ? currentUser.mock === true : currentUser.mock === false);
19527
19754
  }
19528
19755
  return false;
19529
19756
  });
19530
19757
  if (!validIdentityEvidence) {
19531
- fail("identity pass evidence must prove status readback or a confirmed mock/unmock operation", {
19758
+ fail("identity pass evidence must use the Chrome identity bridge and include browser_verified=true, a matching case/step, passed assertions, screenshot, and confirmed status/mock/unmock readback", {
19532
19759
  rule_id: "test_suite.run.unexecuted_evidence",
19533
19760
  path: evidencePath
19534
19761
  });
19535
19762
  }
19763
+ const screenshots = await browserEvidenceScreenshots(
19764
+ manifest,
19765
+ manifestPath,
19766
+ step,
19767
+ evidencePath,
19768
+ "pass",
19769
+ (value) => value.transport === "chrome_identity_bridge" && value.browser_tool === "chrome:control-chrome"
19770
+ );
19771
+ if (identityStepOperation(step) !== "unmock") {
19772
+ const previousHashes = await previousBrowserScreenshotHashes(manifest, step);
19773
+ for (const screenshot of screenshots) {
19774
+ if (previousHashes.has(await sha256(screenshot))) {
19775
+ fail("identity pass evidence reuses an identical screenshot from an earlier step in this run", {
19776
+ rule_id: "test_suite.run.duplicate_screenshot",
19777
+ path: screenshot
19778
+ });
19779
+ }
19780
+ }
19781
+ }
19536
19782
  }
19537
19783
  if (step.runner === "browser" || step.runner === "browser_action" || step.runner === "e2e_create_page") {
19538
19784
  const screenshots = await browserEvidenceScreenshots(manifest, manifestPath, step, evidencePath);
@@ -19568,6 +19814,57 @@ async function assertFormalExecutionEvidence(manifest, manifestPath, step, evide
19568
19814
  if (!validObservation) fail("observe pass evidence must include only passed assertions and an existing source_evidence artifact", { rule_id: "test_suite.run.unexecuted_evidence", path: evidencePath });
19569
19815
  }
19570
19816
  }
19817
+ async function assertIdentityLeaseForRecordedStep(manifestPath, step) {
19818
+ if (step.runner !== "identity") return;
19819
+ const operation = identityStepOperation(step);
19820
+ if (operation !== "mock" && operation !== "unmock") return;
19821
+ const leasePath = path12.join(path12.dirname(path12.resolve(manifestPath)), "identity-lease.json");
19822
+ if (!await exists3(leasePath)) {
19823
+ fail(`${operation} pass evidence requires the current-run identity lease`, {
19824
+ rule_id: "test_suite.run.identity_lease_missing",
19825
+ path: leasePath
19826
+ });
19827
+ }
19828
+ let lease;
19829
+ try {
19830
+ lease = asRecord(JSON.parse(await readText(leasePath)));
19831
+ } catch (error) {
19832
+ fail(`identity lease is invalid: ${error instanceof Error ? error.message : String(error)}`, {
19833
+ rule_id: "test_suite.run.identity_lease_invalid",
19834
+ path: leasePath
19835
+ });
19836
+ }
19837
+ const expectedState = operation === "mock" ? "active" : "released";
19838
+ if (lease.state !== expectedState) {
19839
+ fail(`${operation} pass evidence requires identity lease state=${expectedState}, got ${String(lease.state || "<missing>")}`, {
19840
+ rule_id: "test_suite.run.identity_lease_state",
19841
+ path: leasePath
19842
+ });
19843
+ }
19844
+ if (lease.browser_tool !== "chrome:control-chrome") {
19845
+ fail(`${operation} pass evidence requires a Chrome Control identity lease`, {
19846
+ rule_id: "test_suite.run.identity_lease_tool",
19847
+ path: leasePath
19848
+ });
19849
+ }
19850
+ const binding = asRecord(operation === "mock" ? lease.binding : lease.release_binding);
19851
+ const expectedManifest = path12.resolve(manifestPath);
19852
+ const actualManifest = typeof binding.execution_manifest === "string" ? path12.resolve(binding.execution_manifest) : "";
19853
+ if (binding.case_id !== step.case_id || binding.case_step_id !== step.step_id || binding.profile !== (await readExecutionManifest(manifestPath)).profile || actualManifest !== expectedManifest) {
19854
+ fail(`${operation} identity lease does not match the current manifest/case/step/profile`, {
19855
+ rule_id: "test_suite.run.identity_lease_binding",
19856
+ path: leasePath
19857
+ });
19858
+ }
19859
+ const recoveryRequired = lease.recovery_required === true;
19860
+ if (operation === "mock" && !recoveryRequired || operation === "unmock" && recoveryRequired) {
19861
+ fail(`${operation} identity lease recovery_required state is inconsistent`, {
19862
+ rule_id: "test_suite.run.identity_lease_recovery",
19863
+ path: leasePath
19864
+ });
19865
+ }
19866
+ await assertCurrentRunArtifact(await readExecutionManifest(manifestPath), leasePath);
19867
+ }
19571
19868
  async function writeExecutionManifest(manifestPath, manifest, incrementRevision = false) {
19572
19869
  if (incrementRevision) manifest.revision = (manifest.revision ?? 0) + 1;
19573
19870
  else manifest.revision ??= 0;
@@ -19651,7 +19948,7 @@ async function startTestSuiteRun(options) {
19651
19948
  `precondition_check: ${path12.join(reportDir, `precondition-${runId}.json`)}`,
19652
19949
  `state_file: ${manifestPath}`,
19653
19950
  `report_run: ${reportDir}`,
19654
- "browser_tool: Chrome DevTools",
19951
+ "browser_tool: Chrome Control",
19655
19952
  "",
19656
19953
  "## 1. \u6D4B\u8BD5\u8303\u56F4",
19657
19954
  "",
@@ -19790,7 +20087,10 @@ async function recordTestSuiteRunStep(options) {
19790
20087
  const validated = await validateExecutionManifestStep(options);
19791
20088
  const evidencePath = path12.resolve(options.evidence);
19792
20089
  await assertCurrentRunEvidence(validated.manifest, validated.manifestPath, evidencePath);
19793
- if (options.result === "pass") await assertFormalExecutionEvidence(validated.manifest, validated.manifestPath, validated.step, evidencePath);
20090
+ if (options.result === "pass") {
20091
+ await assertFormalExecutionEvidence(validated.manifest, validated.manifestPath, validated.step, evidencePath);
20092
+ await assertIdentityLeaseForRecordedStep(validated.manifestPath, validated.step);
20093
+ }
19794
20094
  if (options.result !== "pass" && !["browser", "browser_action", "e2e_create_page"].includes(validated.step.runner)) {
19795
20095
  if (!await hasStructuredTerminalEvidence(validated.manifest, validated.step, evidencePath, options.result)) {
19796
20096
  fail("non-browser fail/blocked evidence must identify the current case/step and include structured failure.kind/message or blocker.kind/message", {
@@ -20486,7 +20786,7 @@ function reportHasSupportedBrowserTool(value) {
20486
20786
  return false;
20487
20787
  }
20488
20788
  const tools = value.split(/\s*(?:\+|,|,|、|\/|;|;)\s*/).map((item) => item.trim()).filter(Boolean);
20489
- return tools.length > 0 && tools.every((item) => /^(?:Chrome DevTools(?: MCP)?|DevTools|Playwright|AppleScript)$/i.test(item));
20789
+ return tools.length > 0 && tools.every((item) => /^(?:Chrome Control|chrome:control-chrome|Chrome DevTools(?: MCP)?|DevTools|Playwright|AppleScript)$/i.test(item));
20490
20790
  }
20491
20791
  function reportRuntimeEvidenceMissing(text5) {
20492
20792
  const missing = [];
@@ -20861,7 +21161,7 @@ async function lintUxAudit(text5, reportPath, runDir, runName) {
20861
21161
  } else if (counts.P0 > 0 || counts.P1 > 0) {
20862
21162
  if (resultValue !== "fail" && !preservesBlockedManifest) errors.push(`[test_suite.report.ux_result] ${reportPath}: \u5B58\u5728 P0/P1 UX BUG \u65F6 result \u5FC5\u987B\u662F fail\uFF1B\u5408\u6CD5 blocked manifest \u53EF\u4FDD\u7559 result=blocked`);
20863
21163
  } else if (counts.P2 > 0 || counts.P3 > 0) {
20864
- if (!["pass-with-warnings", "fail"].includes(resultValue)) errors.push(`[test_suite.report.ux_result] ${reportPath}: \u53EA\u6709 P2/P3 UX BUG \u65F6 result \u5FC5\u987B\u662F pass-with-warnings\uFF1B\u5B58\u5728\u5176\u4ED6\u5931\u8D25\u65F6\u53EF\u4E3A fail`);
21164
+ if (!["pass-with-warnings", "fail"].includes(resultValue) && !preservesBlockedManifest) errors.push(`[test_suite.report.ux_result] ${reportPath}: \u53EA\u6709 P2/P3 UX BUG \u65F6 result \u5FC5\u987B\u662F pass-with-warnings\uFF1B\u5B58\u5728\u5176\u4ED6\u5931\u8D25\u65F6\u53EF\u4E3A fail\uFF1B\u5408\u6CD5 blocked manifest \u53EF\u4FDD\u7559 result=blocked`);
20865
21165
  } else if (reportAuditStatus === "completed" && resultValue === "pass-with-warnings") {
20866
21166
  errors.push(`[test_suite.report.ux_result] ${reportPath}: \u65E0 UX BUG \u65F6\u4E0D\u80FD\u7528 pass-with-warnings \u89C4\u907F\u660E\u786E\u7ED3\u8BBA`);
20867
21167
  }
@@ -21006,6 +21306,37 @@ async function lintReport(root = DEFAULT_REPORT_ROOT, options = {}) {
21006
21306
  errors.push(`[test_suite.report.diagnostic_evidence] ${reportPath}: diagnostic \u8BC1\u636E\u4E0D\u80FD\u8FDB\u5165\u5B8C\u6574 E2E \u901A\u8FC7\u62A5\u544A`);
21007
21307
  }
21008
21308
  }
21309
+ const identityMockSteps = manifest.steps.filter((step) => step.runner === "identity" && identityStepOperation(step) === "mock");
21310
+ const identityLeasePath = path12.join(runDir, "identity-lease.json");
21311
+ if (await exists3(identityLeasePath)) {
21312
+ try {
21313
+ const identityLease = asRecord(JSON.parse(await readText(identityLeasePath)));
21314
+ const leaseState = String(identityLease.state || "");
21315
+ if (leaseState === "active" || leaseState === "uncertain") {
21316
+ errors.push(`[test_suite.report.identity_lease_open] ${reportPath}: identity lease \u4ECD\u4E3A ${leaseState}\uFF0C\u5FC5\u987B\u5148\u6062\u590D\u539F\u59CB\u8EAB\u4EFD\u5E76\u786E\u8BA4 released`);
21317
+ }
21318
+ if (reportClaimsCompleteResult(resultValue) && identityMockSteps.length > 0 && leaseState !== "released") {
21319
+ errors.push(`[test_suite.report.identity_lease_not_released] ${reportPath}: \u591A\u8EAB\u4EFD\u5B8C\u6574\u901A\u8FC7\u8981\u6C42 identity lease state=released\uFF0C\u5F53\u524D\u4E3A ${leaseState || "<missing>"}`);
21320
+ }
21321
+ if (reportClaimsCompleteResult(resultValue) && identityMockSteps.length > 0 && leaseState === "released") {
21322
+ const lastMockStep = identityMockSteps.at(-1);
21323
+ const lastUnmockStep = manifest.steps.filter((step) => step.runner === "identity" && identityStepOperation(step) === "unmock").at(-1);
21324
+ const mockBinding = asRecord(identityLease.binding);
21325
+ const releaseBinding = asRecord(identityLease.release_binding);
21326
+ const bindingMatches = (binding, step) => {
21327
+ if (!step || typeof binding.execution_manifest !== "string") return false;
21328
+ return path12.resolve(binding.execution_manifest) === path12.resolve(manifestPath) && binding.profile === manifest.profile && binding.case_id === step.case_id && binding.case_step_id === step.step_id;
21329
+ };
21330
+ if (identityLease.kind !== "bpmax_identity_lease" || identityLease.schema_version !== 1 || identityLease.browser_tool !== "chrome:control-chrome" || identityLease.recovery_required !== false || !bindingMatches(mockBinding, lastMockStep) || !bindingMatches(releaseBinding, lastUnmockStep)) {
21331
+ errors.push(`[test_suite.report.identity_lease_binding] ${reportPath}: released identity lease \u5FC5\u987B\u7ED1\u5B9A\u672C\u8F6E\u6700\u540E\u4E00\u6B21 mock/unmock\u3001\u5F53\u524D profile \u548C execution manifest`);
21332
+ }
21333
+ }
21334
+ } catch (error) {
21335
+ errors.push(`[test_suite.report.identity_lease_invalid] ${reportPath}: identity lease \u65E0\u6CD5\u89E3\u6790: ${error instanceof Error ? error.message : String(error)}`);
21336
+ }
21337
+ } else if (reportClaimsCompleteResult(resultValue) && identityMockSteps.length > 0) {
21338
+ errors.push(`[test_suite.report.identity_lease_missing] ${reportPath}: \u591A\u8EAB\u4EFD\u5B8C\u6574\u901A\u8FC7\u7F3A\u5C11\u672C\u8F6E identity-lease.json`);
21339
+ }
21009
21340
  } catch (error) {
21010
21341
  errors.push(`[test_suite.report.execution_manifest_invalid] ${reportPath}: execution_manifest \u65E0\u6CD5\u89E3\u6790: ${error instanceof Error ? error.message : String(error)}`);
21011
21342
  }
@@ -21803,6 +22134,563 @@ async function runBrowserAutomation(options) {
21803
22134
  }
21804
22135
  }
21805
22136
 
22137
+ // src/core/e2e-identity-bridge.ts
22138
+ import { createHash as createHash7, randomUUID as randomUUID4 } from "crypto";
22139
+ import { chmod as chmod2, lstat, mkdir as mkdir11, readFile as readFile15, realpath as realpath3, rename as rename2, stat as stat8, unlink as unlink2, writeFile as writeFile11 } from "fs/promises";
22140
+ import path14 from "path";
22141
+ var REQUEST_TTL_SECONDS = 180;
22142
+ var RESULT_MAX_DURATION_MS = 15 * 60 * 1e3;
22143
+ var COMPLETION_CLAIM_TTL_MS = 5 * 60 * 1e3;
22144
+ var DEFAULT_LEASE_TTL_SECONDS = 900;
22145
+ var MIN_LEASE_TTL_SECONDS = 60;
22146
+ var MAX_LEASE_TTL_SECONDS = 3600;
22147
+ function isRecord10(value) {
22148
+ return typeof value === "object" && value !== null && !Array.isArray(value);
22149
+ }
22150
+ function stringValue3(value) {
22151
+ if (value === void 0 || value === null) return void 0;
22152
+ const result = String(value).trim();
22153
+ return result || void 0;
22154
+ }
22155
+ function integerValue(value) {
22156
+ const result = Number(value);
22157
+ return Number.isSafeInteger(result) && result > 0 ? result : null;
22158
+ }
22159
+ function booleanValue(value) {
22160
+ if (value === true || value === 1 || value === "1" || value === "true") return true;
22161
+ if (value === false || value === 0 || value === "0" || value === "false") return false;
22162
+ return null;
22163
+ }
22164
+ function pathInside2(parent, child) {
22165
+ const relative = path14.relative(parent, child);
22166
+ return relative === "" || !relative.startsWith("..") && !path14.isAbsolute(relative);
22167
+ }
22168
+ function safeOrigin(value) {
22169
+ const parsed = new URL(value);
22170
+ if (!["http:", "https:"].includes(parsed.protocol)) {
22171
+ throw new Error("e2e.identity.browser.invalid_origin: profile origin \u5FC5\u987B\u662F HTTP(S) \u5730\u5740\u3002");
22172
+ }
22173
+ return parsed.origin;
22174
+ }
22175
+ function safeHrefPath(value) {
22176
+ const next = value.trim();
22177
+ if (!next.startsWith("/") || next.startsWith("//") || next.includes("\\")) {
22178
+ throw new Error("e2e.identity.browser.invalid_href: --href-path \u5FC5\u987B\u662F BPMAX \u7AD9\u5185\u7EDD\u5BF9\u8DEF\u5F84\u3002");
22179
+ }
22180
+ const parsed = new URL(next, "https://bpmax.invalid");
22181
+ if (parsed.origin !== "https://bpmax.invalid") {
22182
+ throw new Error("e2e.identity.browser.invalid_href: --href-path \u4E0D\u80FD\u5207\u6362\u5230\u5916\u90E8 origin\u3002");
22183
+ }
22184
+ return `${parsed.pathname}${parsed.search}${parsed.hash}`;
22185
+ }
22186
+ function normalizeLeaseTtl(value) {
22187
+ const ttl = value ?? DEFAULT_LEASE_TTL_SECONDS;
22188
+ if (!Number.isSafeInteger(ttl) || ttl < MIN_LEASE_TTL_SECONDS || ttl > MAX_LEASE_TTL_SECONDS) {
22189
+ throw new Error(`e2e.identity.browser.invalid_lease_ttl: lease TTL \u5FC5\u987B\u5728 ${MIN_LEASE_TTL_SECONDS}-${MAX_LEASE_TTL_SECONDS} \u79D2\u4E4B\u95F4\u3002`);
22190
+ }
22191
+ return ttl;
22192
+ }
22193
+ function safeIdentity(value) {
22194
+ if (!isRecord10(value)) return null;
22195
+ const sourceValue = stringValue3(value.source);
22196
+ const source = sourceValue === "vuex" || sourceValue === "profile_route" || sourceValue === "dom" ? sourceValue : "unknown";
22197
+ return {
22198
+ id: integerValue(value.id),
22199
+ name: stringValue3(value.name) ?? null,
22200
+ organization_id: integerValue(value.organization_id),
22201
+ mock: booleanValue(value.mock) === true,
22202
+ mock_by_user: integerValue(isRecord10(value.mock_by_user) ? value.mock_by_user.id : value.mock_by_user),
22203
+ can_mock: booleanValue(value.can_mock),
22204
+ source
22205
+ };
22206
+ }
22207
+ async function readJson(file) {
22208
+ return JSON.parse(await readFile15(file, "utf8"));
22209
+ }
22210
+ async function lstatOptional(file) {
22211
+ try {
22212
+ return await lstat(file);
22213
+ } catch (error) {
22214
+ if (error.code === "ENOENT") return null;
22215
+ throw error;
22216
+ }
22217
+ }
22218
+ async function assertSafeExistingFile(file, label) {
22219
+ const info = await lstatOptional(file);
22220
+ if (!info) return;
22221
+ if (info.isSymbolicLink() || !info.isFile()) {
22222
+ throw new Error(`e2e.identity.browser.${label}_unsafe: ${label} \u5FC5\u987B\u662F\u5F53\u524D run \u5185\u7684\u666E\u901A\u6587\u4EF6\uFF0C\u4E0D\u80FD\u662F\u7B26\u53F7\u94FE\u63A5\u3002`);
22223
+ }
22224
+ }
22225
+ async function readOptionalLease(file) {
22226
+ try {
22227
+ await assertSafeExistingFile(file, "lease");
22228
+ const value = await readJson(file);
22229
+ if (!isRecord10(value) || value.kind !== "bpmax_identity_lease" || value.schema_version !== 1) {
22230
+ throw new Error("invalid identity lease state");
22231
+ }
22232
+ const state = stringValue3(value.state);
22233
+ if (!state || !["active", "uncertain", "released"].includes(state)) {
22234
+ throw new Error("invalid identity lease state");
22235
+ }
22236
+ const lease = value;
22237
+ if (!stringValue3(lease.lease_id) || lease.browser_tool !== "chrome:control-chrome" || typeof lease.recovery_required !== "boolean" || !isRecord10(lease.binding)) {
22238
+ throw new Error("invalid identity lease binding");
22239
+ }
22240
+ return lease;
22241
+ } catch (error) {
22242
+ if (error.code === "ENOENT") return null;
22243
+ throw new Error(`e2e.identity.browser.lease_invalid: ${error instanceof Error ? error.message : String(error)}`);
22244
+ }
22245
+ }
22246
+ async function atomicJson(file, value, exclusive = false) {
22247
+ await mkdir11(path14.dirname(file), { recursive: true });
22248
+ if (exclusive) {
22249
+ await writeFile11(file, `${JSON.stringify(value, null, 2)}
22250
+ `, { encoding: "utf8", flag: "wx", mode: 384 });
22251
+ await chmod2(file, 384);
22252
+ return;
22253
+ }
22254
+ const temp = `${file}.tmp-${process.pid}-${Date.now()}`;
22255
+ await writeFile11(temp, `${JSON.stringify(value, null, 2)}
22256
+ `, { encoding: "utf8", mode: 384 });
22257
+ await chmod2(temp, 384);
22258
+ await rename2(temp, file);
22259
+ }
22260
+ function requestAllowedActions(operation) {
22261
+ if (operation === "status") return ["read_current_identity"];
22262
+ if (operation === "mock") return ["read_current_identity", "filter_target_name", "verify_exact_user_id", "click_simulation", "click_exit_simulation"];
22263
+ return ["read_current_identity", "click_exit_simulation"];
22264
+ }
22265
+ function assertWorkspaceKey(value) {
22266
+ const workspace = value.replace(/^w:/, "").trim();
22267
+ if (!workspace || !/^[A-Za-z0-9._-]+$/.test(workspace)) {
22268
+ throw new Error("e2e.identity.browser.workspace_invalid: profile workspace \u5FC5\u987B\u662F\u5355\u4E00 BPMAX workspace key\u3002");
22269
+ }
22270
+ return workspace;
22271
+ }
22272
+ function expectedIdentityUrls(origin, workspace, hrefPath) {
22273
+ return {
22274
+ userManagementUrl: `${origin}/w:${encodeURIComponent(workspace)}/userManagement`,
22275
+ returnUrl: new URL(hrefPath, origin).toString()
22276
+ };
22277
+ }
22278
+ async function prepareIdentityBrowserBridge(options) {
22279
+ const origin = safeOrigin(options.origin);
22280
+ const workspace = assertWorkspaceKey(options.workspace);
22281
+ const hrefPath = safeHrefPath(options.hrefPath?.trim() || `/w:${workspace}`);
22282
+ const targetUserId = options.operation === "mock" ? integerValue(options.targetUserId) : null;
22283
+ const targetUserName = options.operation === "mock" ? stringValue3(options.targetUserName) : void 0;
22284
+ const targetOrganizationId = options.operation === "mock" ? integerValue(options.targetOrganizationId) : null;
22285
+ if (options.operation === "mock" && !targetUserId) {
22286
+ throw new Error("e2e.identity.browser.invalid_user_id: browser mock \u5FC5\u987B\u63D0\u4F9B\u7CBE\u786E\u6B63\u6574\u6570 --user-id\u3002");
22287
+ }
22288
+ if (options.operation === "mock" && !targetUserName) {
22289
+ throw new Error("e2e.identity.browser.target_readback_required: browser mock \u5FC5\u987B\u5148\u901A\u8FC7 typed user readback \u83B7\u53D6\u76EE\u6807\u7528\u6237\u59D3\u540D\u3002");
22290
+ }
22291
+ const evidenceDir = path14.resolve(options.evidenceDir);
22292
+ const runDir = options.binding.execution_manifest ? path14.dirname(path14.resolve(options.binding.execution_manifest)) : evidenceDir;
22293
+ const leaseFile = path14.resolve(options.leaseFile);
22294
+ if (!pathInside2(runDir, evidenceDir)) {
22295
+ throw new Error("e2e.identity.browser.evidence_scope: identity evidence \u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run \u76EE\u5F55\u5185\u3002");
22296
+ }
22297
+ if (!pathInside2(runDir, leaseFile)) {
22298
+ throw new Error("e2e.identity.browser.lease_scope: identity lease \u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run/evidence \u76EE\u5F55\u5185\u3002");
22299
+ }
22300
+ await mkdir11(evidenceDir, { recursive: true });
22301
+ await mkdir11(path14.dirname(leaseFile), { recursive: true });
22302
+ const [realRunDir, realEvidenceDir, realLeaseParent] = await Promise.all([
22303
+ realpath3(runDir),
22304
+ realpath3(evidenceDir),
22305
+ realpath3(path14.dirname(leaseFile))
22306
+ ]);
22307
+ if (!pathInside2(realRunDir, realEvidenceDir) || !pathInside2(realRunDir, realLeaseParent)) {
22308
+ throw new Error("e2e.identity.browser.output_scope: identity evidence/lease \u7684\u771F\u5B9E\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run \u5185\u3002");
22309
+ }
22310
+ await assertSafeExistingFile(leaseFile, "lease");
22311
+ const activeLease = await readOptionalLease(leaseFile);
22312
+ if (options.operation === "mock" && activeLease && ["active", "uncertain"].includes(activeLease.state)) {
22313
+ const expired = activeLease.expires_at ? Date.parse(activeLease.expires_at) <= Date.now() : false;
22314
+ throw new Error(expired ? `e2e.identity.browser.expired_lease_recovery_required: lease ${activeLease.lease_id} \u5DF2\u8FC7\u671F\u4F46\u672A\u786E\u8BA4\u6062\u590D\uFF0C\u5FC5\u987B\u5148\u6267\u884C browser unmock\u3002` : `e2e.identity.browser.active_lease: lease ${activeLease.lease_id} \u4ECD\u5728\u4F7F\u7528\uFF0C\u7981\u6B62\u53E0\u52A0 mock\u3002`);
22315
+ }
22316
+ if (options.operation === "unmock" && !options.binding.diagnostic && (!activeLease || !["active", "uncertain"].includes(activeLease.state))) {
22317
+ throw new Error("e2e.identity.browser.unmock_without_lease: \u6B63\u5F0F unmock \u5FC5\u987B\u5BF9\u5E94\u672C\u8F6E active/uncertain identity lease\u3002");
22318
+ }
22319
+ const ttlSeconds = normalizeLeaseTtl(options.leaseTtlSeconds);
22320
+ const now = /* @__PURE__ */ new Date();
22321
+ const requestId2 = randomUUID4();
22322
+ const leaseId = options.operation === "unmock" && activeLease ? activeLease.lease_id : randomUUID4();
22323
+ const stem = `identity-browser-${options.operation}-${now.toISOString().replace(/[:.]/g, "-")}-${requestId2.slice(0, 8)}`;
22324
+ const requestPath = path14.join(evidenceDir, `${stem}.request.json`);
22325
+ const resultPath = path14.join(evidenceDir, `${stem}.result.json`);
22326
+ const screenshotDir = options.binding.execution_manifest ? path14.join(runDir, "screenshots") : evidenceDir;
22327
+ await mkdir11(screenshotDir, { recursive: true });
22328
+ const realScreenshotDir = await realpath3(screenshotDir);
22329
+ if (!pathInside2(realRunDir, realScreenshotDir)) {
22330
+ throw new Error("e2e.identity.browser.screenshot_scope: identity screenshot \u7684\u771F\u5B9E\u76EE\u5F55\u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run \u5185\u3002");
22331
+ }
22332
+ const screenshotPath = path14.join(screenshotDir, `${stem}.jpg`);
22333
+ const leaseExpiresAt = options.operation === "mock" ? new Date(now.getTime() + ttlSeconds * 1e3).toISOString() : activeLease?.expires_at;
22334
+ const expectedUrls = expectedIdentityUrls(origin, workspace, hrefPath);
22335
+ const request = {
22336
+ schema_version: 1,
22337
+ kind: "bpmax_identity_browser_request",
22338
+ transport: "chrome_control_ui",
22339
+ request_id: requestId2,
22340
+ nonce: randomUUID4(),
22341
+ operation: options.operation,
22342
+ created_at: now.toISOString(),
22343
+ expires_at: new Date(now.getTime() + REQUEST_TTL_SECONDS * 1e3).toISOString(),
22344
+ origin,
22345
+ workspace,
22346
+ language: options.language || "zhCN",
22347
+ href_path: hrefPath,
22348
+ user_management_url: expectedUrls.userManagementUrl,
22349
+ return_url: expectedUrls.returnUrl,
22350
+ ...targetUserId ? { target_user_id: targetUserId } : {},
22351
+ ...targetUserName ? { target_user_name: targetUserName } : {},
22352
+ ...targetOrganizationId ? { target_organization_id: targetOrganizationId } : {},
22353
+ run_dir: runDir,
22354
+ evidence_dir: evidenceDir,
22355
+ result_path: resultPath,
22356
+ screenshot_path: screenshotPath,
22357
+ screenshot_mime: "image/jpeg",
22358
+ binding: options.binding,
22359
+ lease: {
22360
+ lease_id: leaseId,
22361
+ lease_file: leaseFile,
22362
+ ttl_seconds: ttlSeconds,
22363
+ ...leaseExpiresAt ? { expires_at: leaseExpiresAt } : {},
22364
+ requires_dedicated_tab: true,
22365
+ recovery_required: true,
22366
+ ...activeLease?.original_user ? { expected_original_user: activeLease.original_user } : {}
22367
+ },
22368
+ allowed_ui_actions: requestAllowedActions(options.operation)
22369
+ };
22370
+ await atomicJson(requestPath, request, true);
22371
+ return {
22372
+ request,
22373
+ request_path: requestPath,
22374
+ result_path: resultPath,
22375
+ screenshot_path: screenshotPath,
22376
+ lease_file: leaseFile,
22377
+ active_lease: activeLease
22378
+ };
22379
+ }
22380
+ async function readIdentityBrowserRequest(file, options = {}) {
22381
+ const requestPath = path14.resolve(file);
22382
+ const value = await readJson(requestPath);
22383
+ if (!isRecord10(value) || value.schema_version !== 1 || value.kind !== "bpmax_identity_browser_request" || value.transport !== "chrome_control_ui") {
22384
+ throw new Error("e2e.identity.browser.request_invalid: \u4E0D\u652F\u6301\u7684 identity browser request\u3002");
22385
+ }
22386
+ const request = value;
22387
+ if (!request.request_id || !request.nonce || !["status", "mock", "unmock"].includes(request.operation) || !request.run_dir || !request.evidence_dir || !request.result_path || !request.screenshot_path || request.screenshot_mime !== "image/jpeg" || !request.lease?.lease_file || !request.binding || request.operation === "mock" && (!integerValue(request.target_user_id) || !stringValue3(request.target_user_name))) {
22388
+ throw new Error("e2e.identity.browser.request_invalid: request \u7F3A\u5C11\u8EAB\u4EFD\u6865\u7ED1\u5B9A\u5B57\u6BB5\u3002");
22389
+ }
22390
+ const runDir = path14.resolve(request.run_dir);
22391
+ const evidenceDir = path14.resolve(request.evidence_dir);
22392
+ const realRunDir = await realpath3(runDir);
22393
+ const realEvidenceDir = await realpath3(evidenceDir);
22394
+ const realRequestPath = await realpath3(requestPath);
22395
+ const requestLinkInfo = await lstat(requestPath);
22396
+ const requestInfo = await stat8(realRequestPath);
22397
+ const [realResultParent, realScreenshotParent, realLeaseParent] = await Promise.all([
22398
+ realpath3(path14.dirname(path14.resolve(request.result_path))),
22399
+ realpath3(path14.dirname(path14.resolve(request.screenshot_path))),
22400
+ realpath3(path14.dirname(path14.resolve(request.lease.lease_file)))
22401
+ ]);
22402
+ if (!pathInside2(realRunDir, realEvidenceDir) || !pathInside2(realEvidenceDir, realRequestPath) || !pathInside2(realEvidenceDir, realResultParent) || !pathInside2(realRunDir, realScreenshotParent) || !pathInside2(realRunDir, realLeaseParent)) {
22403
+ throw new Error("e2e.identity.browser.request_scope: identity request/result/screenshot/lease \u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run \u76EE\u5F55\u5185\u3002");
22404
+ }
22405
+ if (requestLinkInfo.isSymbolicLink() || (requestInfo.mode & 63) !== 0) {
22406
+ throw new Error("e2e.identity.browser.request_permissions: identity browser request \u5FC5\u987B\u4FDD\u6301 mode 0600\u3002");
22407
+ }
22408
+ await Promise.all([
22409
+ assertSafeExistingFile(path14.resolve(request.result_path), "result"),
22410
+ assertSafeExistingFile(path14.resolve(request.screenshot_path), "screenshot"),
22411
+ assertSafeExistingFile(path14.resolve(request.lease.lease_file), "lease")
22412
+ ]);
22413
+ const origin = safeOrigin(request.origin);
22414
+ const workspace = assertWorkspaceKey(request.workspace);
22415
+ const hrefPath = safeHrefPath(request.href_path);
22416
+ const expectedUrls = expectedIdentityUrls(origin, workspace, hrefPath);
22417
+ if (request.user_management_url !== expectedUrls.userManagementUrl || request.return_url !== expectedUrls.returnUrl) {
22418
+ throw new Error("e2e.identity.browser.request_url_mismatch: identity browser request \u7684\u7BA1\u7406\u9875\u6216\u8FD4\u56DE\u9875\u5DF2\u88AB\u7BE1\u6539\u3002");
22419
+ }
22420
+ const expectedActions = requestAllowedActions(request.operation);
22421
+ if (!Array.isArray(request.allowed_ui_actions) || request.allowed_ui_actions.length !== expectedActions.length || request.allowed_ui_actions.some((item, index) => item !== expectedActions[index])) {
22422
+ throw new Error("e2e.identity.browser.request_actions_mismatch: identity browser request \u7684\u5141\u8BB8\u52A8\u4F5C\u5DF2\u88AB\u7BE1\u6539\u3002");
22423
+ }
22424
+ const createdAt = Date.parse(request.created_at);
22425
+ const expiresAt = Date.parse(request.expires_at);
22426
+ if (!Number.isFinite(createdAt) || !Number.isFinite(expiresAt) || expiresAt <= createdAt || !options.allowExpired && Date.now() > expiresAt) {
22427
+ throw new Error("e2e.identity.browser.request_expired: identity browser request \u5DF2\u8FC7\u671F\uFF0C\u5FC5\u987B\u91CD\u65B0\u751F\u6210\u3002");
22428
+ }
22429
+ return request;
22430
+ }
22431
+ function identityAssertion(name, passed, actual, expected) {
22432
+ return { name, passed, actual, expected };
22433
+ }
22434
+ function resultError(value) {
22435
+ const error = isRecord10(value.error) ? value.error : {};
22436
+ return {
22437
+ kind: stringValue3(error.kind) ?? "browser_identity_failed",
22438
+ message: (stringValue3(error.message) ?? "Chrome identity bridge failed").slice(0, 500)
22439
+ };
22440
+ }
22441
+ async function validateScreenshot(request, result) {
22442
+ const screenshot = path14.resolve(stringValue3(result.screenshot_path) ?? "");
22443
+ if (screenshot !== path14.resolve(request.screenshot_path)) {
22444
+ throw new Error("e2e.identity.browser.screenshot_mismatch: result screenshot \u4E0E request \u4E0D\u4E00\u81F4\u3002");
22445
+ }
22446
+ if (stringValue3(result.screenshot_mime) !== request.screenshot_mime || path14.extname(screenshot).toLowerCase() !== ".jpg") {
22447
+ throw new Error("e2e.identity.browser.screenshot_mismatch: screenshot MIME \u6216\u6269\u5C55\u540D\u4E0E request \u4E0D\u4E00\u81F4\u3002");
22448
+ }
22449
+ await assertSafeExistingFile(screenshot, "screenshot");
22450
+ const realScreenshot = await realpath3(screenshot);
22451
+ const realRunDir = await realpath3(request.run_dir);
22452
+ if (!pathInside2(realRunDir, realScreenshot)) {
22453
+ throw new Error("e2e.identity.browser.screenshot_scope: Chrome identity screenshot \u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D run \u5185\u3002");
22454
+ }
22455
+ const info = await stat8(realScreenshot);
22456
+ if (!info.isFile() || info.size < 100) {
22457
+ throw new Error("e2e.identity.browser.screenshot_invalid: Chrome identity screenshot \u4E0D\u5B58\u5728\u6216\u4E3A\u7A7A\u3002");
22458
+ }
22459
+ const content = Buffer.from(await readFile15(realScreenshot));
22460
+ const signature = content.subarray(0, 3);
22461
+ if (!signature.equals(Buffer.from([255, 216, 255]))) {
22462
+ throw new Error("e2e.identity.browser.screenshot_invalid: Chrome identity screenshot \u5FC5\u987B\u662F\u771F\u5B9E JPEG\u3002");
22463
+ }
22464
+ const startedAt = Date.parse(stringValue3(result.started_at) ?? "");
22465
+ const finishedAt = Date.parse(stringValue3(result.finished_at) ?? "");
22466
+ if (info.mtimeMs < startedAt - 1e3 || info.mtimeMs > finishedAt + 6e4) {
22467
+ throw new Error("e2e.identity.browser.screenshot_stale: Chrome identity screenshot \u4E0D\u662F\u672C\u6B21 request \u4EA7\u751F\u7684\u65B0\u8BC1\u636E\u3002");
22468
+ }
22469
+ return {
22470
+ path: realScreenshot,
22471
+ mime: "image/jpeg",
22472
+ sha256: createHash7("sha256").update(content).digest("hex")
22473
+ };
22474
+ }
22475
+ function validateResultEnvelope(request, value) {
22476
+ if (value.schema_version !== 1 || value.kind !== "bpmax_identity_browser_result" || value.transport !== "chrome_control_ui" || value.browser_tool !== "chrome:control-chrome" || value.request_id !== request.request_id || value.nonce !== request.nonce || value.operation !== request.operation) {
22477
+ throw new Error("e2e.identity.browser.result_binding: Chrome identity result \u4E0E\u4E00\u6B21\u6027 request \u4E0D\u5339\u914D\u3002");
22478
+ }
22479
+ const runtimeUrl = stringValue3(value.runtime_url);
22480
+ if (!runtimeUrl || safeOrigin(runtimeUrl) !== request.origin) {
22481
+ throw new Error("e2e.identity.browser.result_origin: Chrome identity result \u4E0D\u662F\u5F53\u524D profile origin\u3002");
22482
+ }
22483
+ const finishedAt = Date.parse(stringValue3(value.finished_at) ?? "");
22484
+ const startedAt = Date.parse(stringValue3(value.started_at) ?? "");
22485
+ const createdAt = Date.parse(request.created_at);
22486
+ const expiresAt = Date.parse(request.expires_at);
22487
+ if (!Number.isFinite(finishedAt) || !Number.isFinite(startedAt) || startedAt < createdAt - 1e3 || startedAt > expiresAt || finishedAt < startedAt || finishedAt - startedAt > RESULT_MAX_DURATION_MS || finishedAt > Date.now() + 6e4) {
22488
+ throw new Error("e2e.identity.browser.result_expired: Chrome identity result \u5DF2\u8FC7\u671F\uFF0C\u5FC5\u987B\u91CD\u65B0\u751F\u6210 request\u3002");
22489
+ }
22490
+ }
22491
+ function expectedOriginalIdentityId(request, before) {
22492
+ return request.lease.expected_original_user?.id ?? before?.mock_by_user ?? null;
22493
+ }
22494
+ function restoredIdentityMatches(request, before, after) {
22495
+ const expectedOriginalId = expectedOriginalIdentityId(request, before);
22496
+ return Boolean(after && !after.mock && (expectedOriginalId === null || after.id === expectedOriginalId));
22497
+ }
22498
+ function operationSucceeded(request, value, before, after) {
22499
+ if (value.ok !== true || value.readback_confirmed !== true || !after) return false;
22500
+ if (request.operation === "status") {
22501
+ return value.operation_executed === false && value.remote_submitted === false && after.id !== null && Boolean(after.name);
22502
+ }
22503
+ if (request.operation === "mock") {
22504
+ const permission = isRecord10(value.permission_preflight) ? booleanValue(value.permission_preflight.granted) : null;
22505
+ const originalIdentityBound = after.mock_by_user === before?.id || after.mock_by_user === null && after.source === "profile_route" && before?.id !== null;
22506
+ return permission === true && value.operation_executed === true && value.remote_submitted === true && before?.mock === false && after.mock === true && after.id === request.target_user_id && before?.id !== null && originalIdentityBound && isRecord10(value.lease) && value.lease.lease_id === request.lease.lease_id && value.lease.recovery_required === true;
22507
+ }
22508
+ const expectedOriginalId = expectedOriginalIdentityId(request, before);
22509
+ if (value.already_restored === true) {
22510
+ return value.operation_executed === false && value.remote_submitted === false && before?.mock === false && after.mock === false && expectedOriginalId !== null && before?.id === expectedOriginalId && after.id === expectedOriginalId;
22511
+ }
22512
+ return value.operation_executed === true && value.remote_submitted === true && before?.mock === true && restoredIdentityMatches(request, before, after);
22513
+ }
22514
+ async function completeIdentityBrowserBridge(requestFile) {
22515
+ const requestPath = path14.resolve(requestFile);
22516
+ const request = await readIdentityBrowserRequest(requestPath, { allowExpired: true });
22517
+ const receiptPath = `${requestPath}.completed.json`;
22518
+ try {
22519
+ await stat8(receiptPath);
22520
+ throw new Error("e2e.identity.browser.request_consumed: identity browser request \u5DF2\u88AB\u9A8C\u6536\uFF0C\u7981\u6B62\u590D\u7528\u3002");
22521
+ } catch (error) {
22522
+ if (error.code !== "ENOENT") throw error;
22523
+ }
22524
+ await assertSafeExistingFile(request.result_path, "result");
22525
+ const realResultPath = await realpath3(request.result_path);
22526
+ const realEvidenceDir = await realpath3(request.evidence_dir);
22527
+ if (!pathInside2(realEvidenceDir, realResultPath)) {
22528
+ throw new Error("e2e.identity.browser.result_scope: Chrome identity result \u5FC5\u987B\u4F4D\u4E8E\u5F53\u524D evidence \u76EE\u5F55\u5185\u3002");
22529
+ }
22530
+ const value = await readJson(realResultPath);
22531
+ if (!isRecord10(value)) throw new Error("e2e.identity.browser.result_invalid: Chrome identity result \u5FC5\u987B\u662F JSON object\u3002");
22532
+ validateResultEnvelope(request, value);
22533
+ const screenshot = await validateScreenshot(request, value);
22534
+ const before = safeIdentity(value.before);
22535
+ const after = safeIdentity(value.after ?? value.current_user);
22536
+ const ok = operationSucceeded(request, value, before, after);
22537
+ const failure = ok ? void 0 : resultError(value);
22538
+ const cleanup = isRecord10(value.cleanup) ? value.cleanup : {};
22539
+ let lease = await readOptionalLease(request.lease.lease_file);
22540
+ if (request.operation === "mock" && ok) {
22541
+ lease = {
22542
+ schema_version: 1,
22543
+ kind: "bpmax_identity_lease",
22544
+ lease_id: request.lease.lease_id,
22545
+ state: "active",
22546
+ operation_request_id: request.request_id,
22547
+ created_at: request.created_at,
22548
+ ...request.lease.expires_at ? { expires_at: request.lease.expires_at } : {},
22549
+ target_user: after,
22550
+ original_user: before,
22551
+ browser_tool: "chrome:control-chrome",
22552
+ recovery_required: true,
22553
+ binding: request.binding
22554
+ };
22555
+ await atomicJson(request.lease.lease_file, lease);
22556
+ } else if (request.operation === "mock" && (value.remote_submitted === true || value.mutation_attempted === true) && cleanup.readback_confirmed !== true) {
22557
+ lease = {
22558
+ schema_version: 1,
22559
+ kind: "bpmax_identity_lease",
22560
+ lease_id: request.lease.lease_id,
22561
+ state: "uncertain",
22562
+ operation_request_id: request.request_id,
22563
+ created_at: request.created_at,
22564
+ ...request.lease.expires_at ? { expires_at: request.lease.expires_at } : {},
22565
+ target_user: after,
22566
+ original_user: before,
22567
+ browser_tool: "chrome:control-chrome",
22568
+ recovery_required: true,
22569
+ binding: request.binding
22570
+ };
22571
+ await atomicJson(request.lease.lease_file, lease);
22572
+ } else if (request.operation === "unmock" && ok && lease) {
22573
+ lease = {
22574
+ ...lease,
22575
+ state: "released",
22576
+ released_at: stringValue3(value.finished_at) ?? (/* @__PURE__ */ new Date()).toISOString(),
22577
+ recovery_required: false,
22578
+ release_operation_request_id: request.request_id,
22579
+ release_binding: request.binding
22580
+ };
22581
+ await atomicJson(request.lease.lease_file, lease);
22582
+ } else if (request.operation === "unmock" && !ok && lease && (value.remote_submitted === true || value.mutation_attempted === true)) {
22583
+ lease = {
22584
+ ...lease,
22585
+ state: "uncertain",
22586
+ recovery_required: true,
22587
+ release_operation_request_id: request.request_id,
22588
+ release_binding: request.binding
22589
+ };
22590
+ await atomicJson(request.lease.lease_file, lease);
22591
+ }
22592
+ const assertions = request.operation === "status" ? [identityAssertion("\u5F53\u524D\u6D4F\u89C8\u5668\u8EAB\u4EFD\u5DF2\u56DE\u8BFB", Boolean(after?.id && after.name), after, "non-empty current identity")] : request.operation === "mock" ? [
22593
+ identityAssertion("\u539F\u8D26\u53F7\u5177\u5907\u6A21\u62DF\u8EAB\u4EFD\u6743\u9650", isRecord10(value.permission_preflight) && value.permission_preflight.granted === true, isRecord10(value.permission_preflight) ? value.permission_preflight.granted : null, true),
22594
+ identityAssertion("\u6D4F\u89C8\u5668\u5DF2\u5207\u6362\u5230\u7CBE\u786E\u76EE\u6807\u7528\u6237", Boolean(after?.mock && after.id === request.target_user_id), after?.id, request.target_user_id),
22595
+ identityAssertion("\u539F\u8EAB\u4EFD\u6062\u590D\u95E8\u7981\u5DF2\u542F\u7528", isRecord10(value.lease) && value.lease.recovery_required === true, isRecord10(value.lease) ? value.lease.recovery_required : null, true)
22596
+ ] : [identityAssertion(
22597
+ "\u6D4F\u89C8\u5668\u5DF2\u6062\u590D\u539F\u59CB\u8EAB\u4EFD",
22598
+ restoredIdentityMatches(request, before, after),
22599
+ after,
22600
+ request.lease.expected_original_user ?? "original identity"
22601
+ )];
22602
+ const evidence = {
22603
+ schema_version: 1,
22604
+ status: ok ? request.operation === "status" ? "observed" : request.operation === "mock" ? "mocked" : "restored" : "failed",
22605
+ result: ok ? request.operation === "status" ? "observed" : request.operation === "mock" ? "mocked" : "restored" : "failed",
22606
+ transport: "chrome_identity_bridge",
22607
+ browser_tool: "chrome:control-chrome",
22608
+ browser_verified: true,
22609
+ operation: request.operation,
22610
+ mutation_attempted: value.mutation_attempted === true,
22611
+ operation_executed: value.operation_executed === true,
22612
+ remote_submitted: value.remote_submitted === true,
22613
+ readback_confirmed: value.readback_confirmed === true,
22614
+ request_id: request.request_id,
22615
+ current_user: after,
22616
+ before,
22617
+ after,
22618
+ ...isRecord10(value.permission_preflight) ? { permission_preflight: value.permission_preflight } : {},
22619
+ ...isRecord10(value.lease) ? { lease: value.lease } : {},
22620
+ ...failure ? { failure } : {},
22621
+ runtime_scope: "page",
22622
+ runtime_environment: "profile",
22623
+ runtime_url: stringValue3(value.runtime_url),
22624
+ screenshot: path14.relative(request.evidence_dir, screenshot.path),
22625
+ screenshot_mime: screenshot.mime,
22626
+ screenshot_sha256: screenshot.sha256,
22627
+ assertions,
22628
+ browser_action_log: Array.isArray(value.actions) ? value.actions.slice(0, 20) : [],
22629
+ ...request.binding.case_id ? { case_id: request.binding.case_id } : {},
22630
+ ...request.binding.case_step_id ? { case_step_id: request.binding.case_step_id } : {}
22631
+ };
22632
+ return { ok, request, operation: request.operation, evidence, lease, ...failure ? { failure } : {} };
22633
+ }
22634
+ async function claimIdentityBrowserRequestCompletion(requestFile) {
22635
+ const requestPath = path14.resolve(requestFile);
22636
+ const request = await readIdentityBrowserRequest(requestPath, { allowExpired: true });
22637
+ const receiptPath = `${requestPath}.completed.json`;
22638
+ if (await lstatOptional(receiptPath)) {
22639
+ throw new Error("e2e.identity.browser.request_consumed: identity browser request \u5DF2\u88AB\u9A8C\u6536\uFF0C\u7981\u6B62\u590D\u7528\u3002");
22640
+ }
22641
+ const claimPath = `${requestPath}.completion-claim.json`;
22642
+ for (let attempt = 0; attempt < 2; attempt += 1) {
22643
+ const now = /* @__PURE__ */ new Date();
22644
+ const claimId = randomUUID4();
22645
+ try {
22646
+ await atomicJson(claimPath, {
22647
+ schema_version: 1,
22648
+ kind: "bpmax_identity_completion_claim",
22649
+ claim_id: claimId,
22650
+ request_id: request.request_id,
22651
+ created_at: now.toISOString(),
22652
+ expires_at: new Date(now.getTime() + COMPLETION_CLAIM_TTL_MS).toISOString()
22653
+ }, true);
22654
+ return { claim_id: claimId, claim_path: claimPath, request_id: request.request_id };
22655
+ } catch (error) {
22656
+ if (error.code !== "EEXIST") throw error;
22657
+ await assertSafeExistingFile(claimPath, "completion_claim");
22658
+ const existing = await readJson(claimPath).catch(() => null);
22659
+ const expiresAt = isRecord10(existing) ? Date.parse(stringValue3(existing.expires_at) ?? "") : Number.NaN;
22660
+ if (Number.isFinite(expiresAt) && expiresAt > Date.now()) {
22661
+ throw new Error("e2e.identity.browser.completion_in_progress: identity browser request \u6B63\u5728\u9A8C\u6536\uFF0C\u7981\u6B62\u5E76\u53D1 complete\u3002");
22662
+ }
22663
+ await rename2(claimPath, `${claimPath}.stale-${Date.now()}-${randomUUID4()}`).catch((renameError) => {
22664
+ if (renameError.code !== "ENOENT") throw renameError;
22665
+ });
22666
+ }
22667
+ }
22668
+ throw new Error("e2e.identity.browser.completion_claim_failed: \u65E0\u6CD5\u53D6\u5F97 identity browser request \u9A8C\u6536\u9501\u3002");
22669
+ }
22670
+ async function releaseIdentityBrowserRequestCompletionClaim(claim) {
22671
+ await assertSafeExistingFile(claim.claim_path, "completion_claim");
22672
+ const current = await readJson(claim.claim_path).catch(() => null);
22673
+ if (isRecord10(current) && current.claim_id === claim.claim_id && current.request_id === claim.request_id) {
22674
+ await unlink2(claim.claim_path).catch((error) => {
22675
+ if (error.code !== "ENOENT") throw error;
22676
+ });
22677
+ }
22678
+ }
22679
+ async function markIdentityBrowserRequestCompleted(requestFile, ok, knownRequest) {
22680
+ const request = knownRequest ?? await readIdentityBrowserRequest(requestFile, { allowExpired: true });
22681
+ const receiptPath = `${path14.resolve(requestFile)}.completed.json`;
22682
+ await atomicJson(receiptPath, {
22683
+ schema_version: 1,
22684
+ request_id: request.request_id,
22685
+ completed_at: (/* @__PURE__ */ new Date()).toISOString(),
22686
+ ok
22687
+ }, true);
22688
+ return receiptPath;
22689
+ }
22690
+ async function identityLeaseStatus(file) {
22691
+ return readOptionalLease(path14.resolve(file));
22692
+ }
22693
+
21806
22694
  // src/core/form-schema.ts
21807
22695
  var FIELD_KEY_NAMES = [
21808
22696
  "key",
@@ -21822,7 +22710,7 @@ var OPTION_NAMES = ["options", "items", "choices", "values"];
21822
22710
  var REQUIRED_NAMES = ["required", "is_required", "isRequired", "require", "must", "validateRequired"];
21823
22711
  var HIDDEN_NAMES = ["hidden", "is_hidden", "isHidden", "hide", "hideInForm"];
21824
22712
  var VISIBLE_NAMES = ["visible", "display", "show"];
21825
- function isRecord10(value) {
22713
+ function isRecord11(value) {
21826
22714
  return typeof value === "object" && value !== null && !Array.isArray(value);
21827
22715
  }
21828
22716
  function pickString(source, keys) {
@@ -21849,10 +22737,10 @@ function pickBoolean(source, keys) {
21849
22737
  }
21850
22738
  const rules = source.rules;
21851
22739
  if (Array.isArray(rules)) {
21852
- return rules.some((rule) => isRecord10(rule) && pickBoolean(rule, REQUIRED_NAMES));
22740
+ return rules.some((rule) => isRecord11(rule) && pickBoolean(rule, REQUIRED_NAMES));
21853
22741
  }
21854
22742
  const validateMap = source.validateMap;
21855
- if (isRecord10(validateMap) && pickBoolean(validateMap, REQUIRED_NAMES)) {
22743
+ if (isRecord11(validateMap) && pickBoolean(validateMap, REQUIRED_NAMES)) {
21856
22744
  return true;
21857
22745
  }
21858
22746
  return false;
@@ -21876,7 +22764,7 @@ function optionValue(option) {
21876
22764
  if (typeof option === "string" || typeof option === "number") {
21877
22765
  return String(option);
21878
22766
  }
21879
- if (!isRecord10(option)) {
22767
+ if (!isRecord11(option)) {
21880
22768
  return null;
21881
22769
  }
21882
22770
  return pickString(option, ["value", "key", "id", "name", "label", "title"]) ?? null;
@@ -21894,7 +22782,7 @@ function pickOptions(source) {
21894
22782
  }
21895
22783
  for (const containerKey of ["props", "config", "setting", "value"]) {
21896
22784
  const container = source[containerKey];
21897
- if (isRecord10(container)) {
22785
+ if (isRecord11(container)) {
21898
22786
  const nested = pickOptions(container);
21899
22787
  if (nested?.length) {
21900
22788
  return nested;
@@ -21950,7 +22838,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
21950
22838
  }
21951
22839
  return;
21952
22840
  }
21953
- if (!isRecord10(value)) {
22841
+ if (!isRecord11(value)) {
21954
22842
  return;
21955
22843
  }
21956
22844
  const field = fieldFromRecord(value);
@@ -21958,7 +22846,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
21958
22846
  if (isSubFormField(field)) {
21959
22847
  const childFields = /* @__PURE__ */ new Map();
21960
22848
  for (const child of Object.values(value)) {
21961
- if (isRecord10(child) || Array.isArray(child)) {
22849
+ if (isRecord11(child) || Array.isArray(child)) {
21962
22850
  collectFieldCandidates(child, childFields, depth + 1);
21963
22851
  }
21964
22852
  }
@@ -21972,7 +22860,7 @@ function collectFieldCandidates(value, fields, depth = 0) {
21972
22860
  fields.set(field.key, mergeField(fields.get(field.key), field));
21973
22861
  }
21974
22862
  for (const child of Object.values(value)) {
21975
- if (isRecord10(child) || Array.isArray(child)) {
22863
+ if (isRecord11(child) || Array.isArray(child)) {
21976
22864
  collectFieldCandidates(child, fields, depth + 1);
21977
22865
  }
21978
22866
  }
@@ -21990,7 +22878,7 @@ function validateComplexSelector(field, value) {
21990
22878
  if (!isComplexSelectorType(type)) {
21991
22879
  return null;
21992
22880
  }
21993
- const validObject = (item) => isRecord10(item);
22881
+ const validObject = (item) => isRecord11(item);
21994
22882
  const hint = complexSelectorHint(field);
21995
22883
  if (Array.isArray(value)) {
21996
22884
  return value.every(validObject) ? null : `${field.key} must contain selector option object(s), not scalar values. ${hint}`;
@@ -22007,7 +22895,7 @@ function isEnumSelectType(type) {
22007
22895
  return /enum_select/.test(type);
22008
22896
  }
22009
22897
  function optionComparableValue(value) {
22010
- if (isRecord10(value) && ("value" in value || "label" in value)) {
22898
+ if (isRecord11(value) && ("value" in value || "label" in value)) {
22011
22899
  return value.value ?? value.label;
22012
22900
  }
22013
22901
  return value;
@@ -22021,7 +22909,7 @@ function validateType(field, value) {
22021
22909
  if (!Array.isArray(value)) {
22022
22910
  return `${field.key} must be a JSON array of row objects`;
22023
22911
  }
22024
- const invalidRowIndex = value.findIndex((row) => !isRecord10(row));
22912
+ const invalidRowIndex = value.findIndex((row) => !isRecord11(row));
22025
22913
  return invalidRowIndex >= 0 ? `${field.key}[${invalidRowIndex}] must be a row object` : null;
22026
22914
  }
22027
22915
  const selectorError = validateComplexSelector(field, value);
@@ -22047,7 +22935,7 @@ function validateType(field, value) {
22047
22935
  if (/(array|multi|multiple)/.test(type) && !Array.isArray(value)) {
22048
22936
  return `${field.key} must be an array`;
22049
22937
  }
22050
- if (isEnumSelectType(type) && isRecord10(value)) {
22938
+ if (isEnumSelectType(type) && isRecord11(value)) {
22051
22939
  const optionValue2 = value.value ?? value.label;
22052
22940
  return typeof optionValue2 === "string" || typeof optionValue2 === "number" ? null : `${field.key} must be an enum option object with a scalar value`;
22053
22941
  }
@@ -22077,7 +22965,7 @@ function validateFormEntries(form, fields, prefix = "") {
22077
22965
  }
22078
22966
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
22079
22967
  for (const [index, row] of value.entries()) {
22080
- if (isRecord10(row)) {
22968
+ if (isRecord11(row)) {
22081
22969
  errors.push(...validateFormEntries(row, field.children, `${prefix}${field.key}[${index}].`));
22082
22970
  }
22083
22971
  }
@@ -22155,10 +23043,10 @@ function explainFormValidationSchema(fields) {
22155
23043
  }
22156
23044
 
22157
23045
  // src/commands/step.ts
22158
- function isRecord11(value) {
23046
+ function isRecord12(value) {
22159
23047
  return typeof value === "object" && value !== null && !Array.isArray(value);
22160
23048
  }
22161
- function stringValue3(value) {
23049
+ function stringValue4(value) {
22162
23050
  if (value === void 0 || value === null) {
22163
23051
  return void 0;
22164
23052
  }
@@ -22166,7 +23054,7 @@ function stringValue3(value) {
22166
23054
  return next ? next : void 0;
22167
23055
  }
22168
23056
  function idValue(value) {
22169
- const next = stringValue3(value);
23057
+ const next = stringValue4(value);
22170
23058
  return next && /^\d+$/.test(next) ? next : void 0;
22171
23059
  }
22172
23060
  function hasMeaningfulValue(value) {
@@ -22182,7 +23070,7 @@ function hasMeaningfulValue(value) {
22182
23070
  if (Array.isArray(value)) {
22183
23071
  return value.some(hasMeaningfulValue);
22184
23072
  }
22185
- if (isRecord11(value)) {
23073
+ if (isRecord12(value)) {
22186
23074
  return Object.values(value).some(hasMeaningfulValue);
22187
23075
  }
22188
23076
  return false;
@@ -22191,11 +23079,11 @@ function isEmptyValue(value) {
22191
23079
  return value === void 0 || value === null || value === "" || Array.isArray(value) && value.length === 0;
22192
23080
  }
22193
23081
  function projectIdOfStep(step) {
22194
- const nestedProjectId = isRecord11(step.project) ? step.project.id : void 0;
23082
+ const nestedProjectId = isRecord12(step.project) ? step.project.id : void 0;
22195
23083
  return idValue(step.project_id ?? step.projectId ?? nestedProjectId);
22196
23084
  }
22197
23085
  function stepFlowNodeId(step) {
22198
- return stringValue3(step.flow_step_id ?? step.flowStepId ?? step.flow_node_id ?? step.flowNodeId);
23086
+ return stringValue4(step.flow_step_id ?? step.flowStepId ?? step.flow_node_id ?? step.flowNodeId);
22199
23087
  }
22200
23088
  function isStepFinished(step) {
22201
23089
  if (step.real_end_time || step.end_time) {
@@ -22219,12 +23107,12 @@ function collectRecords(value, output = [], seen = /* @__PURE__ */ new Set()) {
22219
23107
  value.forEach((item) => collectRecords(item, output, seen));
22220
23108
  return output;
22221
23109
  }
22222
- if (!isRecord11(value)) {
23110
+ if (!isRecord12(value)) {
22223
23111
  return output;
22224
23112
  }
22225
23113
  output.push(value);
22226
23114
  for (const child of Object.values(value)) {
22227
- if (Array.isArray(child) || isRecord11(child)) {
23115
+ if (Array.isArray(child) || isRecord12(child)) {
22228
23116
  collectRecords(child, output, seen);
22229
23117
  }
22230
23118
  }
@@ -22246,7 +23134,7 @@ function findFlowNode(project, step) {
22246
23134
  project.config
22247
23135
  ];
22248
23136
  for (const candidate of candidates) {
22249
- const match = collectRecords(candidate).find((item) => stringValue3(item.id) === flowStepId);
23137
+ const match = collectRecords(candidate).find((item) => stringValue4(item.id) === flowStepId);
22250
23138
  if (match) {
22251
23139
  return match;
22252
23140
  }
@@ -22308,7 +23196,7 @@ function formListOfStep(step) {
22308
23196
  return values.filter(hasMeaningfulValue);
22309
23197
  }
22310
23198
  function unwrapFormValue(value) {
22311
- if (!isRecord11(value)) {
23199
+ if (!isRecord12(value)) {
22312
23200
  return value;
22313
23201
  }
22314
23202
  if ("value" in value && Object.keys(value).length <= 3) {
@@ -22325,10 +23213,10 @@ function collectFormValues(value, output = {}, seen = /* @__PURE__ */ new Set())
22325
23213
  value.forEach((item) => collectFormValues(item, output, seen));
22326
23214
  return output;
22327
23215
  }
22328
- if (!isRecord11(value)) {
23216
+ if (!isRecord12(value)) {
22329
23217
  return output;
22330
23218
  }
22331
- const key = stringValue3(value.key ?? value.field_key ?? value.fieldKey ?? value.name);
23219
+ const key = stringValue4(value.key ?? value.field_key ?? value.fieldKey ?? value.name);
22332
23220
  if (key && "value" in value) {
22333
23221
  const nextValue = unwrapFormValue(value.value);
22334
23222
  if (hasMeaningfulValue(nextValue)) {
@@ -22336,7 +23224,7 @@ function collectFormValues(value, output = {}, seen = /* @__PURE__ */ new Set())
22336
23224
  }
22337
23225
  }
22338
23226
  for (const child of Object.values(value)) {
22339
- if (Array.isArray(child) || isRecord11(child)) {
23227
+ if (Array.isArray(child) || isRecord12(child)) {
22340
23228
  collectFormValues(child, output, seen);
22341
23229
  }
22342
23230
  }
@@ -22383,7 +23271,7 @@ function collectMissingRequiredInputs(fields, values) {
22383
23271
  continue;
22384
23272
  }
22385
23273
  value.forEach((row, index) => {
22386
- if (!isRecord11(row)) {
23274
+ if (!isRecord12(row)) {
22387
23275
  return;
22388
23276
  }
22389
23277
  for (const child of field.children ?? []) {
@@ -22437,7 +23325,7 @@ function ownerIdsFromStep(step) {
22437
23325
  ];
22438
23326
  const ids = /* @__PURE__ */ new Set();
22439
23327
  for (const owner of owners) {
22440
- if (isRecord11(owner)) {
23328
+ if (isRecord12(owner)) {
22441
23329
  const id = idValue(owner.owner_id ?? owner.user_id ?? owner.id);
22442
23330
  if (id) {
22443
23331
  ids.add(id);
@@ -22476,7 +23364,7 @@ function ownerDiagnosticsFromStep(step, currentUser) {
22476
23364
  const values = Array.isArray(value) ? value : [value];
22477
23365
  for (const item of values) {
22478
23366
  let id;
22479
- if (isRecord11(item)) {
23367
+ if (isRecord12(item)) {
22480
23368
  id = idValue(item.owner_id ?? item.user_id ?? item.id);
22481
23369
  } else {
22482
23370
  id = idValue(item);
@@ -22599,12 +23487,12 @@ function extractSubmitInputValues(data) {
22599
23487
  const candidates = [data.form, data.form_data, data.formData, data.fields, data.values];
22600
23488
  const values = {};
22601
23489
  for (const candidate of candidates) {
22602
- if (isRecord11(candidate)) {
23490
+ if (isRecord12(candidate)) {
22603
23491
  Object.assign(values, candidate);
22604
23492
  }
22605
23493
  }
22606
23494
  for (const [key, value] of Object.entries(data)) {
22607
- if (!SUBMIT_NON_FORM_KEYS.has(key) && !isRecord11(value) && !Array.isArray(value)) {
23495
+ if (!SUBMIT_NON_FORM_KEYS.has(key) && !isRecord12(value) && !Array.isArray(value)) {
22608
23496
  values[key] = value;
22609
23497
  }
22610
23498
  }
@@ -22747,7 +23635,8 @@ async function requireE2eExecutionBinding(options, runners, evidenceDir) {
22747
23635
  manifest: options.executionManifest,
22748
23636
  caseId: options.caseId,
22749
23637
  caseStepId: options.caseStepId,
22750
- runners
23638
+ runners,
23639
+ ...options.profile ? { profile: options.profile } : {}
22751
23640
  });
22752
23641
  if (evidenceDir) {
22753
23642
  await preflightExecutionEvidenceDirectory({
@@ -22766,10 +23655,10 @@ async function appendE2eExecutionEvidence(options, evidence, runners) {
22766
23655
  runners
22767
23656
  });
22768
23657
  }
22769
- function isRecord12(value) {
23658
+ function isRecord13(value) {
22770
23659
  return typeof value === "object" && value !== null && !Array.isArray(value);
22771
23660
  }
22772
- function stringValue4(value) {
23661
+ function stringValue5(value) {
22773
23662
  if (value === void 0 || value === null) {
22774
23663
  return void 0;
22775
23664
  }
@@ -22787,18 +23676,18 @@ function timestampSlug() {
22787
23676
  return (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
22788
23677
  }
22789
23678
  async function ensureDir(dir) {
22790
- const resolved = path14.resolve(dir);
22791
- await mkdir11(resolved, { recursive: true });
23679
+ const resolved = path15.resolve(dir);
23680
+ await mkdir12(resolved, { recursive: true });
22792
23681
  return resolved;
22793
23682
  }
22794
23683
  async function writeEvidence(dir, name, value) {
22795
- const file = path14.join(await ensureDir(dir), name);
22796
- await writeFile11(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
23684
+ const file = path15.join(await ensureDir(dir), name);
23685
+ await writeFile12(file, `${JSON.stringify(redactAuditValue(value), null, 2)}
22797
23686
  `, "utf8");
22798
23687
  return file;
22799
23688
  }
22800
23689
  function summarizeRemoteResult(value) {
22801
- if (!isRecord12(value)) return value;
23690
+ if (!isRecord13(value)) return value;
22802
23691
  const summary = {};
22803
23692
  for (const key of ["id", "project_id", "step_id", "status", "state", "code", "msg", "message", "next", "action"]) {
22804
23693
  if (value[key] !== void 0) summary[key] = value[key];
@@ -22806,34 +23695,37 @@ function summarizeRemoteResult(value) {
22806
23695
  return Object.keys(summary).length > 0 ? redactAuditValue(summary) : { received: true };
22807
23696
  }
22808
23697
  function stepReadbackConfirmed(before, after) {
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;
23698
+ const beforeStatus = isRecord13(before.step) ? before.step.status : void 0;
23699
+ const afterStatus = isRecord13(after.step) ? after.step.status : void 0;
23700
+ const beforeProjectStep = isRecord13(before.project) ? before.project.current_flow_step_id : void 0;
23701
+ const afterProjectStep = isRecord13(after.project) ? after.project.current_flow_step_id : void 0;
22813
23702
  return after.step_finished === true || beforeStatus !== afterStatus || beforeProjectStep !== afterProjectStep;
22814
23703
  }
22815
23704
  function evidenceMime(buffer, file) {
22816
23705
  if (buffer.length >= 8 && buffer.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]))) return "image/png";
22817
23706
  if (buffer.length >= 3 && buffer[0] === 255 && buffer[1] === 216 && buffer[2] === 255) return "image/jpeg";
22818
23707
  if (buffer.length >= 12 && buffer.subarray(0, 4).toString("ascii") === "RIFF" && buffer.subarray(8, 12).toString("ascii") === "WEBP") return "image/webp";
22819
- if (path14.extname(file).toLowerCase() === ".json") return "application/json";
22820
- if ([".txt", ".md", ".log"].includes(path14.extname(file).toLowerCase())) return "text/plain";
23708
+ if (path15.extname(file).toLowerCase() === ".json") return "application/json";
23709
+ if ([".txt", ".md", ".log"].includes(path15.extname(file).toLowerCase())) return "text/plain";
22821
23710
  return "application/octet-stream";
22822
23711
  }
22823
- async function writeEvidenceManifest(evidenceDir, details) {
23712
+ async function writeEvidenceManifest(evidenceDir, details, extraFiles = []) {
22824
23713
  const files = await readdir5(evidenceDir, { withFileTypes: true });
23714
+ const artifactFiles = [
23715
+ ...files.filter((entry) => entry.isFile() && entry.name !== "evidence-manifest.json" && !entry.name.includes(".completion-claim.json") && !entry.name.includes(".completion-claim.json.stale-")).map((entry) => path15.join(evidenceDir, entry.name)),
23716
+ ...extraFiles.map((file) => path15.resolve(file))
23717
+ ];
22825
23718
  const artifacts = [];
22826
- for (const entry of files) {
22827
- if (!entry.isFile() || entry.name === "evidence-manifest.json") continue;
22828
- const file = path14.join(evidenceDir, entry.name);
22829
- const buffer = await readFile15(file);
22830
- const mimeType = evidenceMime(buffer, entry.name);
22831
- const extension = path14.extname(entry.name).toLowerCase();
23719
+ for (const file of [...new Set(artifactFiles)]) {
23720
+ const buffer = await readFile16(file);
23721
+ const relativePath = path15.relative(evidenceDir, file);
23722
+ const mimeType = evidenceMime(buffer, relativePath);
23723
+ const extension = path15.extname(relativePath).toLowerCase();
22832
23724
  const expectedMime = extension === ".png" ? "image/png" : [".jpg", ".jpeg"].includes(extension) ? "image/jpeg" : extension === ".webp" ? "image/webp" : void 0;
22833
23725
  artifacts.push({
22834
- path: entry.name,
23726
+ path: relativePath,
22835
23727
  size: buffer.length,
22836
- sha256: createHash7("sha256").update(buffer).digest("hex"),
23728
+ sha256: createHash8("sha256").update(buffer).digest("hex"),
22837
23729
  mime_type: mimeType,
22838
23730
  ...expectedMime && expectedMime !== mimeType ? { extension_mismatch: true, expected_mime: expectedMime } : {}
22839
23731
  });
@@ -22841,19 +23733,19 @@ async function writeEvidenceManifest(evidenceDir, details) {
22841
23733
  return writeEvidence(evidenceDir, "evidence-manifest.json", {
22842
23734
  schema_version: 1,
22843
23735
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
22844
- evidence_dir: path14.resolve(evidenceDir),
23736
+ evidence_dir: path15.resolve(evidenceDir),
22845
23737
  ...details,
22846
23738
  artifacts
22847
23739
  });
22848
23740
  }
22849
23741
  function cacheRoot() {
22850
- return path14.resolve(".codex/cache/bpmax-e2e");
23742
+ return path15.resolve(".codex/cache/bpmax-e2e");
22851
23743
  }
22852
23744
  function safeSegment(value) {
22853
23745
  return value.trim().replace(/[^a-zA-Z0-9._:-]+/g, "_") || "default";
22854
23746
  }
22855
- function safeIdentity(value) {
22856
- if (!isRecord12(value)) return null;
23747
+ function safeIdentity2(value) {
23748
+ if (!isRecord13(value)) return null;
22857
23749
  return {
22858
23750
  id: value.id,
22859
23751
  name: value.name,
@@ -22894,14 +23786,14 @@ async function browserSessionRequest(profile, cookie, method, apiPath2, data, hr
22894
23786
  response.status
22895
23787
  );
22896
23788
  }
22897
- if (isRecord12(body) && typeof body.code === "number" && body.code !== 0) {
23789
+ if (isRecord13(body) && typeof body.code === "number" && body.code !== 0) {
22898
23790
  throw new BrowserSessionRejectedError(
22899
23791
  `e2e.identity.api_error: ${String(body.msg ?? body.message ?? body.code)}`,
22900
23792
  response.status,
22901
23793
  body.code
22902
23794
  );
22903
23795
  }
22904
- return isRecord12(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
23796
+ return isRecord13(body) && Object.prototype.hasOwnProperty.call(body, "data") ? body.data : body;
22905
23797
  }
22906
23798
  function identityCookie(cookieEnv) {
22907
23799
  const cookie = process.env[cookieEnv]?.trim();
@@ -22910,6 +23802,78 @@ function identityCookie(cookieEnv) {
22910
23802
  }
22911
23803
  return cookie;
22912
23804
  }
23805
+ async function restoreBrowserSessionIdentity(profile, cookie, current, hrefPath) {
23806
+ const primaryEndpoint = "/user/current?identity_action=unmock";
23807
+ try {
23808
+ await browserSessionRequest(profile, cookie, "PUT", primaryEndpoint, { unmock: true }, hrefPath);
23809
+ return { compatibility_fallback: false, endpoint: primaryEndpoint };
23810
+ } catch (error) {
23811
+ const currentUserId = Number(current?.id);
23812
+ if (!(error instanceof BrowserSessionRejectedError) || error.status !== 403 && error.apiCode !== 403 || !/organization\.admin/.test(error.message) || current?.mock !== true || !Number.isSafeInteger(currentUserId) || currentUserId <= 0) {
23813
+ throw error;
23814
+ }
23815
+ const legacyEndpoint = `/user/${currentUserId}`;
23816
+ await browserSessionRequest(profile, cookie, "PUT", legacyEndpoint, { unmock: true }, hrefPath);
23817
+ return { compatibility_fallback: true, endpoint: legacyEndpoint };
23818
+ }
23819
+ }
23820
+ function assertRestoredIdentity(before, after, errorCode) {
23821
+ if (!after || after.mock === true || before?.mock_by_user && Number(after.id) !== Number(before.mock_by_user)) {
23822
+ throw new Error(`${errorCode}: unmock \u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u786E\u8BA4\u6062\u590D\u539F\u59CB\u8EAB\u4EFD\uFF0C\u5FC5\u987B\u505C\u6B62\u540E\u7EED\u7528\u4F8B\u3002`);
23823
+ }
23824
+ }
23825
+ function requireLegacyIdentityDiagnostic(options) {
23826
+ if (!options.diagnostic) {
23827
+ throw new Error(
23828
+ "e2e.identity.legacy_cookie_diagnostic_only: Cookie transport \u53EA\u4FDD\u7559\u663E\u5F0F --diagnostic \u6392\u969C\uFF1B\u6B63\u5F0F\u591A\u89D2\u8272 E2E \u5FC5\u987B\u4F7F\u7528 `e2e identity browser status|mock|unmock`\u3002"
23829
+ );
23830
+ }
23831
+ if (options.executionManifest || options.caseId || options.caseStepId) {
23832
+ throw new Error(
23833
+ "e2e.identity.legacy_cookie_formal_binding_forbidden: Cookie transport \u4E0D\u5F97\u7ED1\u5B9A execution manifest/case/step\uFF0C\u4E5F\u4E0D\u80FD\u5F62\u6210\u6B63\u5F0F\u901A\u8FC7\u8BC1\u636E\u3002"
23834
+ );
23835
+ }
23836
+ }
23837
+ function identityBridgeBinding(options) {
23838
+ return {
23839
+ diagnostic: options.diagnostic === true,
23840
+ ...options.executionManifest ? { execution_manifest: path15.resolve(options.executionManifest) } : {},
23841
+ ...options.caseId ? { case_id: options.caseId } : {},
23842
+ ...options.caseStepId ? { case_step_id: options.caseStepId } : {}
23843
+ };
23844
+ }
23845
+ function identityLeaseFile(options, evidenceDir) {
23846
+ return path15.join(
23847
+ options.executionManifest ? path15.dirname(path15.resolve(options.executionManifest)) : path15.resolve(evidenceDir),
23848
+ "identity-lease.json"
23849
+ );
23850
+ }
23851
+ async function identityBridgeTargetUser(profile, userId) {
23852
+ const result = await apiRequest(createApiClient(profile), "GET", "/user", {
23853
+ params: {
23854
+ ids: String(userId),
23855
+ subRelations: "role",
23856
+ field_filter: "id,name,status,is_del,organization_id"
23857
+ },
23858
+ capability: "user.readback"
23859
+ });
23860
+ const rows2 = Array.isArray(result) ? result.filter(isRecord13) : isRecord13(result) && Array.isArray(result.data) ? result.data.filter(isRecord13) : isRecord13(result) && result.id !== void 0 ? [result] : [];
23861
+ const matched = rows2.find((item) => Number(item.id) === userId);
23862
+ if (!matched) throw new Error(`e2e.identity.browser.target_not_found: typed user readback \u672A\u627E\u5230\u7528\u6237 ${userId}\u3002`);
23863
+ const name = stringValue5(matched.name);
23864
+ if (!name) throw new Error(`e2e.identity.browser.target_name_missing: \u7528\u6237 ${userId} \u7F3A\u5C11\u53EF\u7528\u4E8E\u9875\u9762\u7CBE\u786E\u5B9A\u4F4D\u7684\u59D3\u540D\u3002`);
23865
+ const status = Number(matched.status);
23866
+ const deleted = matched.is_del !== void 0 && Number(matched.is_del) !== 0;
23867
+ if (status !== 0 || deleted) {
23868
+ throw new Error(`e2e.identity.browser.target_inactive: \u7528\u6237 ${userId} \u4E0D\u662F\u53EF\u6A21\u62DF\u7684\u6709\u6548\u72B6\u6001\u3002`);
23869
+ }
23870
+ const organizationId = Number(matched.organization_id);
23871
+ return {
23872
+ id: userId,
23873
+ name,
23874
+ ...Number.isSafeInteger(organizationId) && organizationId > 0 ? { organization_id: organizationId } : {}
23875
+ };
23876
+ }
22913
23877
  function shellQuote5(value) {
22914
23878
  if (/^[a-zA-Z0-9_@%+=:,./-]+$/.test(value)) {
22915
23879
  return value;
@@ -22934,7 +23898,7 @@ function valuesEqual(left, right) {
22934
23898
  }
22935
23899
  function pathValue(source, dottedPath) {
22936
23900
  return dottedPath.split(".").reduce((current, segment) => {
22937
- if (!isRecord12(current)) {
23901
+ if (!isRecord13(current)) {
22938
23902
  return void 0;
22939
23903
  }
22940
23904
  return current[segment];
@@ -22944,10 +23908,10 @@ function normalizeExpectedChecks(value) {
22944
23908
  if (!Array.isArray(value)) {
22945
23909
  return [];
22946
23910
  }
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",
23911
+ return value.filter(isRecord13).map((item) => ({
23912
+ ...stringValue5(item.name) ? { name: stringValue5(item.name) } : {},
23913
+ path: stringValue5(item.path) ?? "",
23914
+ op: stringValue5(item.op) ?? "equals",
22951
23915
  ...Object.prototype.hasOwnProperty.call(item, "value") ? { value: item.value } : {},
22952
23916
  ...Array.isArray(item.values) ? { values: item.values } : {}
22953
23917
  })).filter((item) => item.path);
@@ -23019,13 +23983,13 @@ function buildExpectedChecks(options) {
23019
23983
  ];
23020
23984
  }
23021
23985
  function flowCachePath(profileName, flowId) {
23022
- return path14.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
23986
+ return path15.join(cacheRoot(), "profiles", safeSegment(profileName), "flows", `${safeSegment(flowId)}.json`);
23023
23987
  }
23024
23988
  async function readOptionalJson(file) {
23025
23989
  try {
23026
- const raw = await readFile15(file, "utf8");
23990
+ const raw = await readFile16(file, "utf8");
23027
23991
  const parsed = JSON.parse(raw);
23028
- return isRecord12(parsed) ? parsed : null;
23992
+ return isRecord13(parsed) ? parsed : null;
23029
23993
  } catch (error) {
23030
23994
  if (error.code === "ENOENT") {
23031
23995
  return null;
@@ -23047,34 +24011,34 @@ function stepsFromProfile(profile) {
23047
24011
  if (!profile) {
23048
24012
  return [];
23049
24013
  }
23050
- if (stringValue4(profile.step_id ?? profile.stepId)) {
24014
+ if (stringValue5(profile.step_id ?? profile.stepId)) {
23051
24015
  return [profile];
23052
24016
  }
23053
24017
  const steps = profile.steps;
23054
24018
  if (Array.isArray(steps)) {
23055
- return steps.filter(isRecord12);
24019
+ return steps.filter(isRecord13);
23056
24020
  }
23057
- if (isRecord12(steps)) {
24021
+ if (isRecord13(steps)) {
23058
24022
  return Object.entries(steps).map(([stepId, value]) => ({
23059
- ...isRecord12(value) ? value : { data: value },
24023
+ ...isRecord13(value) ? value : { data: value },
23060
24024
  step_id: stepId
23061
24025
  }));
23062
24026
  }
23063
24027
  return [];
23064
24028
  }
23065
24029
  function normalizeStepPlan(input, defaults) {
23066
- const stepId = stringValue4(input.step_id ?? input.stepId ?? defaults.stepId);
24030
+ const stepId = stringValue5(input.step_id ?? input.stepId ?? defaults.stepId);
23067
24031
  if (!stepId) {
23068
24032
  throw new Error("e2e step-run requires --step-id or data-profile steps[].step_id.");
23069
24033
  }
23070
24034
  const rawData = input.data ?? input.payload_template ?? input.payloadTemplate ?? input.form ?? input.values ?? {};
23071
- const data = isRecord12(rawData) ? rawData : {};
24035
+ const data = isRecord13(rawData) ? rawData : {};
23072
24036
  return {
23073
24037
  step_id: stepId,
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 } : {},
24038
+ action: stringValue5(input.action) ?? defaults.action,
24039
+ ...stringValue5(input.label) ? { label: stringValue5(input.label) } : {},
24040
+ ...stringValue5(input.target_step ?? input.targetStep) ? { target_step: stringValue5(input.target_step ?? input.targetStep) } : {},
24041
+ ...stringValue5(input.comments) ?? defaults.comments ? { comments: stringValue5(input.comments) ?? defaults.comments } : {},
23078
24042
  urgency: numberValue(input.urgency, defaults.urgency),
23079
24043
  data,
23080
24044
  expected_checks: normalizeExpectedChecks(input.expected_checks ?? input.expectedChecks)
@@ -23108,7 +24072,7 @@ function dataProfilePath(input) {
23108
24072
  if (!input?.startsWith("@")) {
23109
24073
  return void 0;
23110
24074
  }
23111
- return path14.resolve(input.slice(1));
24075
+ return path15.resolve(input.slice(1));
23112
24076
  }
23113
24077
  function refreshedStepTemplate(options) {
23114
24078
  return {
@@ -23132,15 +24096,15 @@ function refreshedStepTemplate(options) {
23132
24096
  variables: Object.keys(options.plan.data).filter((key) => !["project_id", "action", "urgency"].includes(key)),
23133
24097
  payload_template: options.plan.data,
23134
24098
  source_evidence: {
23135
- evidence_dir: path14.resolve(options.evidenceDir),
23136
- context: path14.basename(options.contextFile)
24099
+ evidence_dir: path15.resolve(options.evidenceDir),
24100
+ context: path15.basename(options.contextFile)
23137
24101
  }
23138
24102
  };
23139
24103
  }
23140
24104
  async function writeRefreshedCache(file, template) {
23141
- const out = path14.resolve(file);
23142
- await mkdir11(path14.dirname(out), { recursive: true });
23143
- await writeFile11(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
24105
+ const out = path15.resolve(file);
24106
+ await mkdir12(path15.dirname(out), { recursive: true });
24107
+ await writeFile12(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
23144
24108
  `, "utf8");
23145
24109
  return out;
23146
24110
  }
@@ -23163,7 +24127,7 @@ function blockedReason(context2, canSubmit) {
23163
24127
  return void 0;
23164
24128
  }
23165
24129
  function handoffUrlFromInput(input) {
23166
- const url = stringValue4(input.handoff_url ?? input.handoffUrl ?? input.url);
24130
+ const url = stringValue5(input.handoff_url ?? input.handoffUrl ?? input.url);
23167
24131
  if (!url) {
23168
24132
  throw new Error("handoff JSON must contain handoff_url, handoffUrl, or url.");
23169
24133
  }
@@ -23220,13 +24184,13 @@ test(${JSON.stringify(options.title)}, async ({ page }) => {
23220
24184
  async function writeBrowserTemplate(options) {
23221
24185
  const handoffUrl = handoffUrlFromInput(options.handoff);
23222
24186
  const assertFields = (options.assertFields ?? "").split(",").map((item) => item.trim()).filter(Boolean);
23223
- const out = path14.resolve(options.out);
23224
- await mkdir11(path14.dirname(out), { recursive: true });
23225
- await writeFile11(out, playwrightTemplate({
24187
+ const out = path15.resolve(options.out);
24188
+ await mkdir12(path15.dirname(out), { recursive: true });
24189
+ await writeFile12(out, playwrightTemplate({
23226
24190
  title: options.title ?? "BPMAX create page handoff submit",
23227
24191
  handoffUrl,
23228
24192
  assertFields,
23229
- evidenceDir: path14.resolve(options.evidenceDir)
24193
+ evidenceDir: path15.resolve(options.evidenceDir)
23230
24194
  }), "utf8");
23231
24195
  return { out, handoff_url: handoffUrl, assert_fields: assertFields };
23232
24196
  }
@@ -23234,15 +24198,15 @@ async function updateAutomationFromRecordedTrace(options) {
23234
24198
  if (!options.caseId || !options.caseStepId) {
23235
24199
  throw new Error("--automation-out requires --case-id and --case-step-id");
23236
24200
  }
23237
- const tracePath = path14.join(path14.resolve(options.evidenceDir), "browser-action-trace.json");
24201
+ const tracePath = path15.join(path15.resolve(options.evidenceDir), "browser-action-trace.json");
23238
24202
  const trace = await readOptionalJson(tracePath);
23239
- if (!trace || !isRecord12(trace) || !Array.isArray(trace.actions) || !Array.isArray(trace.expected_checks) || !isRecord12(trace.page_fingerprint)) {
24203
+ if (!trace || !isRecord13(trace) || !Array.isArray(trace.actions) || !Array.isArray(trace.expected_checks) || !isRecord13(trace.page_fingerprint)) {
23240
24204
  throw new Error("browser-action-trace.json must contain page_fingerprint, actions, and expected_checks before automation can be generated");
23241
24205
  }
23242
- const out = path14.resolve(options.automationOut);
24206
+ const out = path15.resolve(options.automationOut);
23243
24207
  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 = {};
24208
+ const document2 = existing && isRecord13(existing) ? existing : { version: 1, ...options.scenario ? { scenario: options.scenario } : {}, steps: {} };
24209
+ if (!isRecord13(document2.steps)) document2.steps = {};
23246
24210
  document2.steps[automationStepKey(options.caseId, options.caseStepId)] = {
23247
24211
  runner: "browser_action",
23248
24212
  page_fingerprint: trace.page_fingerprint,
@@ -23255,8 +24219,8 @@ async function updateAutomationFromRecordedTrace(options) {
23255
24219
  throw new Error(`recorded browser automation requires review:
23256
24220
  ${details}`);
23257
24221
  }
23258
- await mkdir11(path14.dirname(out), { recursive: true });
23259
- await writeFile11(out, `${JSON.stringify(document2, null, 2)}
24222
+ await mkdir12(path15.dirname(out), { recursive: true });
24223
+ await writeFile12(out, `${JSON.stringify(document2, null, 2)}
23260
24224
  `, "utf8");
23261
24225
  return out;
23262
24226
  }
@@ -23265,20 +24229,21 @@ function scenarioRecords(plan) {
23265
24229
  if (!Array.isArray(records)) {
23266
24230
  return [];
23267
24231
  }
23268
- return records.filter(isRecord12);
24232
+ return records.filter(isRecord13);
23269
24233
  }
23270
24234
  function recordKey(record, index) {
23271
- return stringValue4(record.demo_no ?? record.id ?? record.case_id ?? record.subject) ?? `record-${index + 1}`;
24235
+ return stringValue5(record.demo_no ?? record.id ?? record.case_id ?? record.subject) ?? `record-${index + 1}`;
23272
24236
  }
23273
24237
  function registerE2eCommands(program2) {
23274
24238
  const e2e = program2.command("e2e").description("BPMAX E2E acceleration helpers with evidence-first safety gates");
23275
- const identity = e2e.command("identity").description("Control browser-session mock identity for formal multi-role E2E");
24239
+ const identity = e2e.command("identity").description("Control browser-session mock identity for multi-role E2E");
23276
24240
  const addIdentityOptions = (command) => command.requiredOption("--evidence-dir <dir>", "Current-run identity evidence directory").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; cannot become pass evidence").option("--profile <profile>", "Profile providing origin and workspace").option("--cookie-env <name>", "Environment variable containing current browser Cookie", "BPMAX_COOKIE_HEADER").option("--href-path <path>", "BPMAX page path used for Referer and x-href").option("--format <format>", "Output format", "json");
23277
- addIdentityOptions(identity.command("status").description("Read and record current browser-session identity")).action(async (options) => {
24241
+ addIdentityOptions(identity.command("status").description("Legacy Cookie diagnostic: read current browser-session identity")).action(async (options) => {
24242
+ requireLegacyIdentityDiagnostic(options);
23278
24243
  await requireE2eExecutionBinding(options, ["identity", "browser", "observe"], options.evidenceDir);
23279
24244
  const config = await loadConfig();
23280
24245
  const profile = resolveProfile(config, options.profile);
23281
- const current = safeIdentity(await browserSessionRequest(
24246
+ const current = safeIdentity2(await browserSessionRequest(
23282
24247
  profile,
23283
24248
  identityCookie(options.cookieEnv),
23284
24249
  "GET",
@@ -23302,7 +24267,8 @@ function registerE2eCommands(program2) {
23302
24267
  evidence
23303
24268
  });
23304
24269
  });
23305
- addIdentityOptions(identity.command("mock").description("Switch the current browser session to one exact BPMAX user")).requiredOption("--user-id <id>", "Exact target BPMAX user id").action(async (options) => {
24270
+ addIdentityOptions(identity.command("mock").description("Legacy Cookie diagnostic: switch the browser session to one exact BPMAX user")).requiredOption("--user-id <id>", "Exact target BPMAX user id").action(async (options) => {
24271
+ requireLegacyIdentityDiagnostic(options);
23306
24272
  const userId = Number(options.userId);
23307
24273
  if (!Number.isSafeInteger(userId) || userId <= 0) {
23308
24274
  throw new Error("e2e.identity.invalid_user_id: --user-id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002");
@@ -23316,7 +24282,30 @@ function registerE2eCommands(program2) {
23316
24282
  target_user_id: userId,
23317
24283
  remote_submitted: false
23318
24284
  });
23319
- const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24285
+ const initialBefore = safeIdentity2(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24286
+ let before = initialBefore;
24287
+ let preMockRestore = null;
24288
+ if (before?.mock === true) {
24289
+ let restoreResult;
24290
+ try {
24291
+ restoreResult = await restoreBrowserSessionIdentity(profile, cookie, before, options.hrefPath);
24292
+ } catch (error) {
24293
+ throw new Error(
24294
+ `e2e.identity.pre_mock_restore_failed: \u5F53\u524D\u4F1A\u8BDD\u4ECD\u5904\u4E8E mock \u72B6\u6001\uFF0C\u5207\u6362\u4E0B\u4E00\u89D2\u8272\u524D\u6062\u590D\u539F\u8EAB\u4EFD\u5931\u8D25\uFF1B\u672A\u63D0\u4EA4\u65B0\u7684 mock\u3002${error instanceof Error ? error.message : String(error)}`
24295
+ );
24296
+ }
24297
+ const restored = safeIdentity2(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24298
+ assertRestoredIdentity(before, restored, "e2e.identity.pre_mock_restore_verify_failed");
24299
+ preMockRestore = {
24300
+ operation: "unmock_before_mock",
24301
+ operation_executed: true,
24302
+ readback_confirmed: true,
24303
+ ...restoreResult,
24304
+ before,
24305
+ after: restored
24306
+ };
24307
+ before = restored;
24308
+ }
23320
24309
  let after = null;
23321
24310
  try {
23322
24311
  await browserSessionRequest(profile, cookie, "PUT", `/user/${userId}?identity_action=mock`, { mock: true }, options.hrefPath);
@@ -23330,7 +24319,7 @@ function registerE2eCommands(program2) {
23330
24319
  throw new Error(`e2e.identity.mock_outcome_unknown: mock \u8BF7\u6C42\u6216\u5199\u540E\u56DE\u8BFB\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\uFF1B\u4E0D\u5F97\u91CD\u590D\u6267\u884C\u5F53\u524D\u6B65\u9AA4\uFF0C\u5148\u8FD0\u884C identity status \u786E\u8BA4\u4F1A\u8BDD\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
23331
24320
  }
23332
24321
  try {
23333
- after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24322
+ after = safeIdentity2(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
23334
24323
  } catch (error) {
23335
24324
  await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
23336
24325
  throw new Error(`e2e.identity.mock_outcome_unknown: mock \u5DF2\u63D0\u4EA4\u4F46\u5199\u540E\u56DE\u8BFB\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\uFF1B\u4E0D\u5F97\u91CD\u590D\u6267\u884C\u5F53\u524D\u6B65\u9AA4\uFF0C\u5148\u8FD0\u884C identity status \u786E\u8BA4\u4F1A\u8BDD\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
@@ -23352,13 +24341,13 @@ function registerE2eCommands(program2) {
23352
24341
  target_user_id: userId
23353
24342
  });
23354
24343
  } catch (error) {
23355
- await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
24344
+ await restoreBrowserSessionIdentity(profile, cookie, after, options.hrefPath).catch(() => void 0);
23356
24345
  throw new Error(`e2e.identity.evidence_failed: mock \u540E\u8BC1\u636E\u5199\u5165\u5931\u8D25\uFF0C\u5DF2\u5C1D\u8BD5\u6062\u590D\u539F\u8EAB\u4EFD\u3002${error instanceof Error ? error.message : String(error)}`);
23357
24346
  }
23358
24347
  try {
23359
24348
  await appendE2eExecutionEvidence(options, evidence, ["identity", "browser"]);
23360
24349
  } catch (error) {
23361
- await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath).catch(() => void 0);
24350
+ await restoreBrowserSessionIdentity(profile, cookie, after, options.hrefPath).catch(() => void 0);
23362
24351
  throw new Error(`e2e.identity.manifest_evidence_failed: mock \u5DF2\u6267\u884C\u4F46\u7528\u4F8B\u8BC1\u636E\u767B\u8BB0\u5931\u8D25\uFF0CCLI \u5DF2\u5C1D\u8BD5\u81EA\u52A8 unmock\u3002${error instanceof Error ? error.message : String(error)}`);
23363
24352
  }
23364
24353
  printResult(options.format, {
@@ -23369,11 +24358,13 @@ function registerE2eCommands(program2) {
23369
24358
  remote_submitted: true,
23370
24359
  readback_confirmed: true,
23371
24360
  current_user: after,
24361
+ pre_mock_restore: preMockRestore,
23372
24362
  evidence,
23373
24363
  preflight_evidence: preflightEvidence
23374
24364
  });
23375
24365
  });
23376
- addIdentityOptions(identity.command("unmock").description("Restore the original browser-session identity and verify recovery")).action(async (options) => {
24366
+ addIdentityOptions(identity.command("unmock").description("Legacy Cookie diagnostic: restore the original browser-session identity")).action(async (options) => {
24367
+ requireLegacyIdentityDiagnostic(options);
23377
24368
  await requireE2eExecutionBinding(options, ["identity", "browser"], options.evidenceDir);
23378
24369
  const config = await loadConfig();
23379
24370
  const profile = resolveProfile(config, options.profile);
@@ -23382,12 +24373,10 @@ function registerE2eCommands(program2) {
23382
24373
  operation: "unmock",
23383
24374
  remote_submitted: false
23384
24375
  });
23385
- const before = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
23386
- await browserSessionRequest(profile, cookie, "PUT", "/user/current?identity_action=unmock", { unmock: true }, options.hrefPath);
23387
- const after = safeIdentity(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
23388
- if (!after || after.mock === true || before?.mock_by_user && Number(after.id) !== Number(before.mock_by_user)) {
23389
- throw new Error("e2e.identity.unmock_verify_failed: unmock \u5DF2\u63D0\u4EA4\uFF0C\u4F46\u672A\u786E\u8BA4\u6062\u590D\u539F\u59CB\u8EAB\u4EFD\uFF0C\u5FC5\u987B\u505C\u6B62\u540E\u7EED\u7528\u4F8B\u3002");
23390
- }
24376
+ const before = safeIdentity2(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24377
+ const restoreResult = await restoreBrowserSessionIdentity(profile, cookie, before, options.hrefPath);
24378
+ const after = safeIdentity2(await browserSessionRequest(profile, cookie, "GET", "/user/current", void 0, options.hrefPath));
24379
+ assertRestoredIdentity(before, after, "e2e.identity.unmock_verify_failed");
23391
24380
  const evidence = await writeEvidence(options.evidenceDir, `identity-unmock-${timestampSlug()}.json`, {
23392
24381
  result: options.diagnostic ? "diagnostic" : "restored",
23393
24382
  operation: "unmock",
@@ -23395,7 +24384,8 @@ function registerE2eCommands(program2) {
23395
24384
  remote_submitted: true,
23396
24385
  readback_confirmed: true,
23397
24386
  before,
23398
- after
24387
+ after,
24388
+ ...restoreResult
23399
24389
  });
23400
24390
  await appendE2eExecutionEvidence(options, evidence, ["identity", "browser"]);
23401
24391
  printResult(options.format, {
@@ -23406,9 +24396,134 @@ function registerE2eCommands(program2) {
23406
24396
  remote_submitted: true,
23407
24397
  readback_confirmed: true,
23408
24398
  current_user: after,
24399
+ ...restoreResult,
23409
24400
  evidence
23410
24401
  });
23411
24402
  });
24403
+ const identityBrowser = identity.command("browser").description("Prepare and verify Chrome Control identity switching without exporting browser Cookie");
24404
+ const addIdentityBrowserPrepareOptions = (command) => command.requiredOption("--evidence-dir <dir>", "Current-run identity evidence directory").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; cannot become pass evidence").option("--profile <profile>", "Profile providing origin and workspace").option("--href-path <path>", "BPMAX page restored after identity switching").option("--lease-ttl <seconds>", "Recovery lease TTL before further mock operations are blocked", "900").option("--format <format>", "Output format", "json");
24405
+ const registerIdentityBrowserPrepare = (operation, command) => {
24406
+ addIdentityBrowserPrepareOptions(command).action(async (options) => {
24407
+ const targetUserId = options.userId === void 0 ? void 0 : Number(options.userId);
24408
+ if (operation === "mock" && (!Number.isSafeInteger(targetUserId) || Number(targetUserId) <= 0)) {
24409
+ throw new Error("e2e.identity.browser.invalid_user_id: --user-id \u5FC5\u987B\u662F\u6B63\u6574\u6570\u3002");
24410
+ }
24411
+ await requireE2eExecutionBinding(options, ["identity"], options.evidenceDir);
24412
+ const evidenceDir = await ensureDir(options.evidenceDir);
24413
+ const config = await loadConfig();
24414
+ const profile = resolveProfile(config, options.profile);
24415
+ const targetUser = operation === "mock" && targetUserId ? await identityBridgeTargetUser(profile, targetUserId) : void 0;
24416
+ const prepared = await prepareIdentityBrowserBridge({
24417
+ operation,
24418
+ origin: profile.config.origin,
24419
+ workspace: profile.config.workspace,
24420
+ language: profile.config.language,
24421
+ hrefPath: options.hrefPath,
24422
+ ...targetUser ? {
24423
+ targetUserId: targetUser.id,
24424
+ targetUserName: targetUser.name,
24425
+ ...targetUser.organization_id ? { targetOrganizationId: targetUser.organization_id } : {}
24426
+ } : {},
24427
+ evidenceDir,
24428
+ leaseFile: identityLeaseFile(options, evidenceDir),
24429
+ binding: { ...identityBridgeBinding(options), profile: profile.name },
24430
+ leaseTtlSeconds: Number(options.leaseTtl)
24431
+ });
24432
+ printResult(options.format, {
24433
+ ok: true,
24434
+ result: "browser_action_required",
24435
+ operation,
24436
+ transport: "chrome_identity_bridge",
24437
+ browser_tool: "chrome:control-chrome",
24438
+ cookie_export_required: false,
24439
+ request: prepared.request_path,
24440
+ result_out: prepared.result_path,
24441
+ screenshot_out: prepared.screenshot_path,
24442
+ lease_file: prepared.lease_file,
24443
+ lease_expires_at: prepared.request.lease.expires_at ?? null,
24444
+ ...targetUser ? { target_user: targetUser } : {},
24445
+ helper: "bpmax-user-mock-operator/scripts/chrome_identity_bridge.mjs",
24446
+ next_action: "Use chrome:control-chrome in a dedicated BPMAX tab to execute the fixed identity bridge helper, then run `bpmax-cli e2e identity browser complete --request <request>`."
24447
+ });
24448
+ });
24449
+ };
24450
+ registerIdentityBrowserPrepare(
24451
+ "status",
24452
+ identityBrowser.command("status").description("Prepare a Chrome Control current-identity readback")
24453
+ );
24454
+ registerIdentityBrowserPrepare(
24455
+ "mock",
24456
+ identityBrowser.command("mock").description("Prepare an exact-user Chrome Control identity switch").requiredOption("--user-id <id>", "Exact target BPMAX user id")
24457
+ );
24458
+ registerIdentityBrowserPrepare(
24459
+ "unmock",
24460
+ identityBrowser.command("unmock").description("Prepare Chrome Control recovery to the original identity")
24461
+ );
24462
+ identityBrowser.command("complete").description("Verify one Chrome Control identity result, update the lease, and attach current-run evidence").requiredOption("--request <file>", "Identity browser request generated by status/mock/unmock").option("--format <format>", "Output format", "json").action(async (options) => {
24463
+ const request = await readIdentityBrowserRequest(options.request, { allowExpired: true });
24464
+ const executionOptions = {
24465
+ diagnostic: request.binding.diagnostic,
24466
+ profile: request.binding.profile,
24467
+ executionManifest: request.binding.execution_manifest,
24468
+ caseId: request.binding.case_id,
24469
+ caseStepId: request.binding.case_step_id
24470
+ };
24471
+ await requireE2eExecutionBinding(executionOptions, ["identity"], request.evidence_dir);
24472
+ const config = await loadConfig();
24473
+ const profile = resolveProfile(config, request.binding.profile);
24474
+ const profileOrigin = new URL(profile.config.origin).origin;
24475
+ const profileWorkspace = normalizeWorkspaceForApi(profile.config.workspace) || "";
24476
+ if (profileOrigin !== request.origin || profileWorkspace !== request.workspace) {
24477
+ throw new Error(`e2e.identity.browser.profile_drift: request \u76EE\u6807 ${request.origin}/w:${request.workspace} \u4E0E\u5F53\u524D profile ${profileOrigin}/w:${profileWorkspace} \u4E0D\u4E00\u81F4\u3002`);
24478
+ }
24479
+ const claim = await claimIdentityBrowserRequestCompletion(options.request);
24480
+ try {
24481
+ const completed = await completeIdentityBrowserBridge(options.request);
24482
+ const evidence = await writeEvidence(
24483
+ request.evidence_dir,
24484
+ `identity-browser-${completed.operation}-${completed.request.request_id}.json`,
24485
+ completed.evidence
24486
+ );
24487
+ await appendE2eExecutionEvidence(executionOptions, evidence, ["identity"]);
24488
+ const evidenceManifest = await writeEvidenceManifest(request.evidence_dir, {
24489
+ status: completed.ok ? "completed" : "failed",
24490
+ operation: completed.operation,
24491
+ transport: "chrome_identity_bridge",
24492
+ remote_submitted: completed.evidence.remote_submitted === true,
24493
+ readback_confirmed: completed.evidence.readback_confirmed === true
24494
+ }, [request.screenshot_path]);
24495
+ const receipt = await markIdentityBrowserRequestCompleted(options.request, completed.ok, completed.request);
24496
+ if (!completed.ok) {
24497
+ throw new Error(`e2e.identity.browser.operation_failed: ${completed.failure?.kind ?? "unknown"}: ${completed.failure?.message ?? "identity operation failed"}\u3002evidence=${evidence}`);
24498
+ }
24499
+ printResult(options.format, {
24500
+ ok: true,
24501
+ result: completed.evidence.result,
24502
+ operation: completed.operation,
24503
+ transport: "chrome_identity_bridge",
24504
+ browser_tool: "chrome:control-chrome",
24505
+ remote_submitted: completed.evidence.remote_submitted,
24506
+ readback_confirmed: completed.evidence.readback_confirmed,
24507
+ current_user: completed.evidence.current_user,
24508
+ lease: completed.lease,
24509
+ evidence,
24510
+ evidence_manifest: evidenceManifest,
24511
+ receipt
24512
+ });
24513
+ } finally {
24514
+ await releaseIdentityBrowserRequestCompletionClaim(claim);
24515
+ }
24516
+ });
24517
+ identityBrowser.command("lease-status").description("Inspect the current run identity lease without changing browser identity").option("--execution-manifest <file>", "Formal test-suite execution manifest").option("--evidence-dir <dir>", "Diagnostic evidence directory", ".codex/tmp/e2e/identity").option("--format <format>", "Output format", "json").action(async (options) => {
24518
+ const leaseFile = identityLeaseFile({ executionManifest: options.executionManifest }, options.evidenceDir);
24519
+ const lease = await identityLeaseStatus(leaseFile);
24520
+ printResult(options.format, {
24521
+ ok: true,
24522
+ result: lease ? lease.state : "none",
24523
+ lease_file: leaseFile,
24524
+ lease
24525
+ });
24526
+ });
23412
24527
  e2e.command("step-run").description("Run one or more BPMAX step safe-chain submissions with evidence files").requiredOption("--project-id <projectId>", "Project id").option("--step-id <stepId>", "Step id for single-step mode").option("--action <action>", "Step action", "approve").option("--data <json>", "Single-step submit data JSON or @file").option("--data-profile <json>", "Reusable step profile JSON or @file; supports steps[] or steps object").option("--auto-refresh-cache", "Write a refreshed cache template when expected checks are missing or stale").option("--cache-out <file>", "Refreshed cache template output; defaults to --data-profile @file when possible").option("--comments <comments>", "Step comments").option("--urgency <urgency>", "Urgency value", "1").option("--confirm <confirmation>", "Actually submit; otherwise dry-run only").option("--profile <profile>", "Profile 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("--evidence-dir <dir>", "Evidence directory", `.codex/tmp/e2e/${timestampSlug()}`).option("--format <format>", "Output format", "json").action(async (options) => {
23413
24528
  await requireE2eExecutionBinding(options, ["e2e_step_run"], options.evidenceDir);
23414
24529
  const config = await loadConfig();
@@ -23627,7 +24742,7 @@ function registerE2eCommands(program2) {
23627
24742
  mode: "handoff_command_hint",
23628
24743
  browser: options.browser,
23629
24744
  next_command: `bpmax-cli project create ${flowFlag}${jsonFlag}${profileFlag} --handoff-only --format json > handoff.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`,
24745
+ next_after_handoff: `bpmax-cli e2e create-page-submit --handoff-json @handoff.json --browser ${options.browser} --evidence-dir ${path15.resolve(options.evidenceDir)} --format json`,
23631
24746
  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."
23632
24747
  });
23633
24748
  return;
@@ -23649,7 +24764,7 @@ function registerE2eCommands(program2) {
23649
24764
  browser_verified: false,
23650
24765
  browser: options.browser,
23651
24766
  ...generated,
23652
- evidence_dir: path14.resolve(options.evidenceDir),
24767
+ evidence_dir: path15.resolve(options.evidenceDir),
23653
24768
  next_command: `npx playwright test ${generated.out}`,
23654
24769
  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."
23655
24770
  });
@@ -23659,7 +24774,7 @@ function registerE2eCommands(program2) {
23659
24774
  const profile = resolveProfile(await loadConfig(), options.profile);
23660
24775
  const file = flowCachePath(profile.name, options.flowId);
23661
24776
  const cached = await readOptionalJson(file);
23662
- const fileStat = await stat8(file).catch(() => null);
24777
+ const fileStat = await stat9(file).catch(() => null);
23663
24778
  printResult(options.format, {
23664
24779
  ok: true,
23665
24780
  profile: profile.name,
@@ -23693,15 +24808,15 @@ function registerE2eCommands(program2) {
23693
24808
  if (!result) {
23694
24809
  throw new Error(`Flow ${options.flowId} was not found.`);
23695
24810
  }
23696
- const sourceUpdateTime = stringValue4(result.update_time ?? result.updateTime ?? result.updated_at ?? result.updatedAt);
23697
- const cacheKey = createHash7("sha256").update(JSON.stringify({
24811
+ const sourceUpdateTime = stringValue5(result.update_time ?? result.updateTime ?? result.updated_at ?? result.updatedAt);
24812
+ const cacheKey = createHash8("sha256").update(JSON.stringify({
23698
24813
  flow_id: options.flowId,
23699
24814
  update_time: sourceUpdateTime,
23700
24815
  template_id: result.template_id ?? result.templateId
23701
24816
  })).digest("hex").slice(0, 16);
23702
24817
  const file = flowCachePath(profile.name, options.flowId);
23703
- await mkdir11(path14.dirname(file), { recursive: true });
23704
- await writeFile11(file, `${JSON.stringify(redactAuditValue({
24818
+ await mkdir12(path15.dirname(file), { recursive: true });
24819
+ await writeFile12(file, `${JSON.stringify(redactAuditValue({
23705
24820
  cache_key: cacheKey,
23706
24821
  cached_at: (/* @__PURE__ */ new Date()).toISOString(),
23707
24822
  profile: profile.name,
@@ -23735,7 +24850,7 @@ function registerE2eCommands(program2) {
23735
24850
  printResult(options.format, {
23736
24851
  ok: true,
23737
24852
  ...generated,
23738
- evidence_dir: path14.resolve(options.evidenceDir),
24853
+ evidence_dir: path15.resolve(options.evidenceDir),
23739
24854
  next_command: `npx playwright test ${generated.out}`
23740
24855
  });
23741
24856
  });
@@ -23748,13 +24863,13 @@ function registerE2eCommands(program2) {
23748
24863
  if (inferredStepId && !contextFile && !submitFile) {
23749
24864
  throw new Error(`No step evidence files found for step ${inferredStepId} in ${options.evidenceDir}.`);
23750
24865
  }
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);
24866
+ const context2 = contextFile ? await readOptionalJson(path15.join(options.evidenceDir, contextFile)) : null;
24867
+ const submit = submitFile ? await readOptionalJson(path15.join(options.evidenceDir, submitFile)) : null;
24868
+ const requirements = isRecord13(context2?.requirements) ? context2.requirements : {};
24869
+ const requiredInputs = Array.isArray(requirements.required_inputs) ? requirements.required_inputs.filter(isRecord13) : [];
24870
+ const missingInputs = Array.isArray(requirements.missing_required_inputs) ? requirements.missing_required_inputs.filter(isRecord13) : [];
24871
+ const requestData = isRecord13(submit?.request) && isRecord13(submit.request.data) ? submit.request.data : {};
24872
+ const recordedAction = stringValue5(requestData.action);
23758
24873
  const expectedChecks = buildExpectedChecks({
23759
24874
  context: context2,
23760
24875
  requirements: {
@@ -23792,16 +24907,16 @@ function registerE2eCommands(program2) {
23792
24907
  variables: Object.keys(requestData).filter((key) => !["project_id", "action", "urgency"].includes(key)),
23793
24908
  payload_template: requestData,
23794
24909
  source_evidence: {
23795
- evidence_dir: path14.resolve(options.evidenceDir),
24910
+ evidence_dir: path15.resolve(options.evidenceDir),
23796
24911
  ...contextFile ? { context: contextFile } : {},
23797
24912
  ...submitFile ? { submit: submitFile } : {}
23798
24913
  }
23799
24914
  } : {
23800
- name: options.name ?? path14.basename(path14.resolve(options.evidenceDir)),
24915
+ name: options.name ?? path15.basename(path15.resolve(options.evidenceDir)),
23801
24916
  generated_at: (/* @__PURE__ */ new Date()).toISOString(),
23802
24917
  submit_mode: "browser_evidence_bootstrap",
23803
24918
  source_evidence: {
23804
- evidence_dir: path14.resolve(options.evidenceDir),
24919
+ evidence_dir: path15.resolve(options.evidenceDir),
23805
24920
  files: evidenceFiles
23806
24921
  },
23807
24922
  reuse_requirements: [
@@ -23814,9 +24929,9 @@ function registerE2eCommands(program2) {
23814
24929
  template.result = "diagnostic";
23815
24930
  template.diagnostic = true;
23816
24931
  }
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)}
24932
+ const out = path15.resolve(options.out);
24933
+ await mkdir12(path15.dirname(out), { recursive: true });
24934
+ await writeFile12(out, `${JSON.stringify(redactAuditValue(template), null, 2)}
23820
24935
  `, "utf8");
23821
24936
  const automationOut = options.automationOut ? await updateAutomationFromRecordedTrace({
23822
24937
  evidenceDir: options.evidenceDir,
@@ -23839,15 +24954,15 @@ function registerE2eCommands(program2) {
23839
24954
  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
24955
  const plan = await parseJsonFileOrInput(options.plan, "--plan");
23841
24956
  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)}`);
24957
+ const execution = isRecord13(state.execution) ? state.execution : {};
24958
+ if (stringValue5(plan.scenario) && stringValue5(execution.scenario_id) !== stringValue5(plan.scenario)) {
24959
+ throw new Error(`e2e.scenario.plan_mismatch: plan scenario ${stringValue5(plan.scenario)} does not match execution manifest ${stringValue5(execution.scenario_id)}`);
23845
24960
  }
23846
24961
  const result = await runBrowserAutomation(options);
23847
24962
  printResult(options.format, {
23848
24963
  ...result,
23849
24964
  scenario: plan.scenario,
23850
- plan: path14.resolve(options.plan)
24965
+ plan: path15.resolve(options.plan)
23851
24966
  });
23852
24967
  });
23853
24968
  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) => {
@@ -23866,7 +24981,7 @@ function registerE2eCommands(program2) {
23866
24981
  });
23867
24982
  const status = selected.map((record, index) => ({
23868
24983
  record: recordKey(record, index),
23869
- subject: stringValue4(record.subject),
24984
+ subject: stringValue5(record.subject),
23870
24985
  status: "bootstrap_required",
23871
24986
  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."
23872
24987
  }));
@@ -23900,11 +25015,11 @@ function registerE2eCommands(program2) {
23900
25015
  }
23901
25016
 
23902
25017
  // src/core/project-search.ts
23903
- function isRecord13(value) {
25018
+ function isRecord14(value) {
23904
25019
  return typeof value === "object" && value !== null && !Array.isArray(value);
23905
25020
  }
23906
25021
  function hasRawProjectSearchBody(value) {
23907
- return isRecord13(value) && Object.prototype.hasOwnProperty.call(value, "body");
25022
+ return isRecord14(value) && Object.prototype.hasOwnProperty.call(value, "body");
23908
25023
  }
23909
25024
  function assertProjectSearchBody(value) {
23910
25025
  if (hasRawProjectSearchBody(value)) {
@@ -23918,13 +25033,13 @@ function isProjectListEsQuery(value) {
23918
25033
  }
23919
25034
  function splitProjectListPagination(body, options) {
23920
25035
  const data = { ...body };
23921
- const normalizePositiveInteger = (value, path19) => {
25036
+ const normalizePositiveInteger = (value, path20) => {
23922
25037
  if (typeof value === "string" && value.trim() === "") {
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`);
25038
+ throw new Error(`project search ${path20} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u4E0D\u80FD\u662F\u7A7A\u5B57\u7B26\u4E32\u3002`);
23924
25039
  }
23925
25040
  const number = typeof value === "number" ? value : Number(value);
23926
25041
  if (!Number.isSafeInteger(number) || number < 1) {
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`);
25042
+ throw new Error(`project search ${path20} \u5FC5\u987B\u662F\u5927\u4E8E\u7B49\u4E8E 1 \u7684\u6574\u6570\uFF0C\u5F53\u524D\u503C\u4E3A ${String(value)}\u3002`);
23928
25043
  }
23929
25044
  return number;
23930
25045
  };
@@ -24055,7 +25170,7 @@ function registerFlowCommands(program2) {
24055
25170
  const client = createApiClient(profile);
24056
25171
  if (options.flowType) {
24057
25172
  const bindings = await getWorkspaceFlowBindings(client, profile, options);
24058
- const path19 = options.flowKey ? "/flow/options" : "/flow/flow_type";
25173
+ const path20 = options.flowKey ? "/flow/options" : "/flow/flow_type";
24059
25174
  const params = options.flowKey ? {
24060
25175
  detail: "1"
24061
25176
  } : {
@@ -24065,7 +25180,7 @@ function registerFlowCommands(program2) {
24065
25180
  const result2 = await apiRequest(
24066
25181
  client,
24067
25182
  "GET",
24068
- path19,
25183
+ path20,
24069
25184
  {
24070
25185
  params
24071
25186
  }
@@ -24301,7 +25416,7 @@ function registerInitCommand(program2, deps = {}) {
24301
25416
  }
24302
25417
 
24303
25418
  // src/commands/issue.ts
24304
- import { readFile as readFile16 } from "fs/promises";
25419
+ import { readFile as readFile17 } from "fs/promises";
24305
25420
 
24306
25421
  // src/core/issues.ts
24307
25422
  import axios8, { AxiosHeaders as AxiosHeaders3 } from "axios";
@@ -24477,7 +25592,7 @@ async function readDescription(options) {
24477
25592
  if (!options.descriptionFile) {
24478
25593
  return options.description;
24479
25594
  }
24480
- return readFile16(options.descriptionFile, "utf8");
25595
+ return readFile17(options.descriptionFile, "utf8");
24481
25596
  }
24482
25597
  function parseAssigneeIds(values) {
24483
25598
  return (values || []).flatMap(
@@ -24576,10 +25691,10 @@ async function parseOptionalJson(input, label) {
24576
25691
  }
24577
25692
  return parseJsonInput(input, label);
24578
25693
  }
24579
- async function memoryRequest(options, method, path19, capability, data, params) {
25694
+ async function memoryRequest(options, method, path20, capability, data, params) {
24580
25695
  const profile = resolveProfile(await loadConfig(), options.profile);
24581
25696
  const client = createApiClient(profile);
24582
- return apiRequest(client, method, path19, {
25697
+ return apiRequest(client, method, path20, {
24583
25698
  capability,
24584
25699
  data: redactAuditValue(data),
24585
25700
  params: params ? redactAuditValue(params) : void 0
@@ -24634,7 +25749,7 @@ function registerMemoryCommands(program2) {
24634
25749
  }
24635
25750
 
24636
25751
  // src/commands/matrix.ts
24637
- import { readFile as readFile17 } from "fs/promises";
25752
+ import { readFile as readFile18 } from "fs/promises";
24638
25753
  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;
24639
25754
  var UUID_PATH_PATTERN = /uuid'[^'"\s/]+/i;
24640
25755
  async function parseSeedRules(input) {
@@ -24642,7 +25757,7 @@ async function parseSeedRules(input) {
24642
25757
  if (source === "") {
24643
25758
  throw new Error("--rules file path is empty.");
24644
25759
  }
24645
- const raw = source ? await readFile17(source, "utf8") : input;
25760
+ const raw = source ? await readFile18(source, "utf8") : input;
24646
25761
  let parsed;
24647
25762
  try {
24648
25763
  parsed = JSON.parse(raw);
@@ -24661,15 +25776,15 @@ async function parseSeedRules(input) {
24661
25776
  });
24662
25777
  return rules;
24663
25778
  }
24664
- function collectUuidPaths(value, path19 = "$") {
25779
+ function collectUuidPaths(value, path20 = "$") {
24665
25780
  if (typeof value === "string") {
24666
- return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path19] : [];
25781
+ return UUID_VALUE_PATTERN2.test(value) || UUID_PATH_PATTERN.test(value) ? [path20] : [];
24667
25782
  }
24668
25783
  if (Array.isArray(value)) {
24669
- return value.flatMap((item, index) => collectUuidPaths(item, `${path19}[${index}]`));
25784
+ return value.flatMap((item, index) => collectUuidPaths(item, `${path20}[${index}]`));
24670
25785
  }
24671
25786
  if (typeof value === "object" && value !== null) {
24672
- return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path19}.${key}`));
25787
+ return Object.entries(value).flatMap(([key, child]) => collectUuidPaths(child, `${path20}.${key}`));
24673
25788
  }
24674
25789
  return [];
24675
25790
  }
@@ -24692,20 +25807,20 @@ function isEmptyApproverValue(value) {
24692
25807
  function shellQuote7(value) {
24693
25808
  return `'${value.replace(/'/g, `'\\''`)}'`;
24694
25809
  }
24695
- var isRecord14 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
25810
+ var isRecord15 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
24696
25811
  function dataArray(value) {
24697
25812
  if (Array.isArray(value)) return value;
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;
25813
+ if (isRecord15(value) && Array.isArray(value.data)) return value.data;
25814
+ if (isRecord15(value) && Array.isArray(value.list)) return value.list;
25815
+ if (isRecord15(value) && Array.isArray(value.rows)) return value.rows;
24701
25816
  return [];
24702
25817
  }
24703
25818
  function predictedNodes(value) {
24704
- if (!isRecord14(value)) return [];
24705
- return dataArray(value.predicted_nodes).filter(isRecord14);
25819
+ if (!isRecord15(value)) return [];
25820
+ return dataArray(value.predicted_nodes).filter(isRecord15);
24706
25821
  }
24707
25822
  function safePredictedOwners(value) {
24708
- return (Array.isArray(value) ? value : []).filter(isRecord14).map((owner) => ({
25823
+ return (Array.isArray(value) ? value : []).filter(isRecord15).map((owner) => ({
24709
25824
  id: owner.id ?? owner.user_id ?? owner.owner_id,
24710
25825
  name: owner.name ?? null
24711
25826
  }));
@@ -24720,7 +25835,7 @@ async function fetchAllMatrixRuleRecords(client, flowType) {
24720
25835
  data: { flow_type: flowType, page, page_size: pageSize },
24721
25836
  capability: "project.list"
24722
25837
  });
24723
- const rows2 = dataArray(result).filter(isRecord14);
25838
+ const rows2 = dataArray(result).filter(isRecord15);
24724
25839
  records.push(...rows2);
24725
25840
  const total = Number(result.count ?? result.total ?? records.length);
24726
25841
  if (rows2.length < pageSize || records.length >= total) break;
@@ -24739,23 +25854,23 @@ async function hydrateMatrixRuleRecords(client, records) {
24739
25854
  for (let index = 0; index < records.length; index += 10) {
24740
25855
  const chunk = records.slice(index, index + 10);
24741
25856
  hydrated.push(...await Promise.all(chunk.map(async (record) => {
24742
- if (isRecord14(record.metaForm) || Array.isArray(record.formList)) return record;
25857
+ if (isRecord15(record.metaForm) || Array.isArray(record.formList)) return record;
24743
25858
  const id = Number(record.id ?? record.project_id);
24744
25859
  return Number.isSafeInteger(id) && id > 0 ? apiRequest(client, "GET", `/project/${id}`) : record;
24745
25860
  })));
24746
25861
  }
24747
25862
  return hydrated;
24748
25863
  }
24749
- function collectMatrixOwnerPaths(value, path19 = "$") {
25864
+ function collectMatrixOwnerPaths(value, path20 = "$") {
24750
25865
  if (Array.isArray(value)) {
24751
- return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path19}[${index}]`));
25866
+ return value.flatMap((item, index) => collectMatrixOwnerPaths(item, `${path20}[${index}]`));
24752
25867
  }
24753
- if (!isRecord14(value)) {
25868
+ if (!isRecord15(value)) {
24754
25869
  return [];
24755
25870
  }
24756
25871
  const matches = [];
24757
25872
  Object.entries(value).forEach(([key, child]) => {
24758
- const childPath = `${path19}.${key}`;
25873
+ const childPath = `${path20}.${key}`;
24759
25874
  if (key.includes("matrix_owner") || typeof child === "string" && child.includes("matrix_owner")) {
24760
25875
  matches.push({ path: childPath, value: child });
24761
25876
  }
@@ -24764,25 +25879,25 @@ function collectMatrixOwnerPaths(value, path19 = "$") {
24764
25879
  return matches;
24765
25880
  }
24766
25881
  function projectFormKeys(project) {
24767
- const metaForm = isRecord14(project.metaForm) ? project.metaForm : {};
25882
+ const metaForm = isRecord15(project.metaForm) ? project.metaForm : {};
24768
25883
  const values = dataArray(metaForm.value ?? project.formList);
24769
- return values.filter(isRecord14).map((item) => String(item.key ?? item.field_key ?? "")).filter(Boolean);
25884
+ return values.filter(isRecord15).map((item) => String(item.key ?? item.field_key ?? "")).filter(Boolean);
24770
25885
  }
24771
25886
  function findFlowNode2(flow, 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);
25887
+ const data = isRecord15(flow.data) ? flow.data : {};
25888
+ return dataArray(data.nodes).filter(isRecord15).find((node) => String(node.id ?? node.key ?? node.flow_step_id ?? "") === nodeId);
24774
25889
  }
24775
25890
  function flowCategory(flow) {
24776
- const data = isRecord14(flow.data) ? flow.data : {};
24777
- const meta = isRecord14(data.meta) ? data.meta : {};
25891
+ const data = isRecord15(flow.data) ? flow.data : {};
25892
+ const meta = isRecord15(data.meta) ? data.meta : {};
24778
25893
  return String(flow.category ?? data.category ?? meta.category ?? "");
24779
25894
  }
24780
25895
  function hasIdentifier(value) {
24781
25896
  return value !== void 0 && value !== null && String(value).trim() !== "" && String(value) !== "0";
24782
25897
  }
24783
25898
  function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], datasets = [], workspaceBound = false) {
24784
- const data = isRecord14(flow.data) ? flow.data : {};
24785
- const meta = isRecord14(data.meta) ? data.meta : {};
25899
+ const data = isRecord15(flow.data) ? flow.data : {};
25900
+ const meta = isRecord15(data.meta) ? data.meta : {};
24786
25901
  const refs = {
24787
25902
  form_template_id: meta.form_template ?? flow.form_template_id,
24788
25903
  list_template_ids: listTemplates.map((item) => item.id ?? item.flow_page_template_id).filter(hasIdentifier),
@@ -24823,7 +25938,7 @@ function matrixAppSummary(flow, listTemplates = [], filterTemplates = [], datase
24823
25938
  suggestion: "\u4ECE\u6700\u65B0 workspace-flow \u56DE\u8BFB merge \u540E\u901A\u8FC7 typed CLI \u63D0\u4EA4\u7ED1\u5B9A\u3002"
24824
25939
  });
24825
25940
  }
24826
- const nodes = dataArray(data.nodes).filter(isRecord14);
25941
+ const nodes = dataArray(data.nodes).filter(isRecord15);
24827
25942
  const activeNodes = nodes.filter((node) => {
24828
25943
  const name = String(node.name ?? "").trim();
24829
25944
  return name === "\u751F\u6548\u4E2D" || name === "\u8FDB\u884C\u4E2D" || Number(node.status) === 1;
@@ -24872,10 +25987,10 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
24872
25987
  apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: flowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
24873
25988
  apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
24874
25989
  ]);
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);
25990
+ const flowData = isRecord15(flow.data) ? flow.data : {};
25991
+ const meta = isRecord15(flowData.meta) ? flowData.meta : {};
25992
+ const listRows = dataArray(listResult).filter(isRecord15);
25993
+ const filterRows = dataArray(filterResult).filter(isRecord15);
24879
25994
  const listIds = uniqueIds([meta.table_list_template, ...listRows.map((item) => item.id ?? item.flow_page_template_id)]);
24880
25995
  const filterIds = uniqueIds([meta.table_filter_template, ...filterRows.map((item) => item.id ?? item.flow_page_template_id)]);
24881
25996
  const formId = String(meta.form_template ?? flow.form_template_id ?? "");
@@ -24893,7 +26008,7 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
24893
26008
  if (strict) {
24894
26009
  assertNoMatrixErrors(summary.errors);
24895
26010
  }
24896
- const formRecord = isRecord14(form) ? form : {};
26011
+ const formRecord = isRecord15(form) ? form : {};
24897
26012
  const exactReadback = {
24898
26013
  flow: { id: flowType, readback_hash: matrixHash(flow), ...includeRaw ? { readback: flow } : {} },
24899
26014
  form_template: { id: formId, draft_id: formRecord.origin_template_id ?? formRecord.id ?? null, readback_hash: matrixHash(formRecord), ...includeRaw ? { readback: formRecord } : {} },
@@ -24905,8 +26020,8 @@ async function inspectMatrixAppDefinition(profile, flowType, workspace, includeR
24905
26020
  return { ok: summary.errors.length === 0, domain: "approval-matrix", action: "app.inspect", flow_type: flowType, workspace, ...summary, exact_readback: exactReadback };
24906
26021
  }
24907
26022
  function workspaceHasFlow(value, flowType) {
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) : [];
26023
+ if (!isRecord15(value)) return false;
26024
+ const rows2 = Array.isArray(value.workspace_flow) ? value.workspace_flow.filter(isRecord15) : isRecord15(value.data) && Array.isArray(value.data.workspace_flow) ? value.data.workspace_flow.filter(isRecord15) : [];
24910
26025
  return rows2.some((item) => String(item.flow_type ?? "") === flowType && Number(item.is_del ?? 0) === 0);
24911
26026
  }
24912
26027
  function matrixConsumerSummary(node, expectedMatrixFlowType) {
@@ -24922,8 +26037,8 @@ function matrixConsumerSummary(node, expectedMatrixFlowType) {
24922
26037
  });
24923
26038
  return { errors, owner: null, cc: null };
24924
26039
  }
24925
- const owner = isRecord14(node.matrix_owner) ? node.matrix_owner : null;
24926
- const cc = isRecord14(node.cc_matrix) ? node.cc_matrix : null;
26040
+ const owner = isRecord15(node.matrix_owner) ? node.matrix_owner : null;
26041
+ const cc = isRecord15(node.cc_matrix) ? node.cc_matrix : null;
24927
26042
  const normalizeFlowRef = (value) => String(value ?? "").trim().replace(/:$/, "");
24928
26043
  if (node.auto_range_type === "matrix") {
24929
26044
  if (!owner || !String(owner.flow ?? owner.matrix_flow_type ?? "").trim()) {
@@ -24954,16 +26069,16 @@ function matrixConsumerSummary(node, expectedMatrixFlowType) {
24954
26069
  return { errors, owner, cc };
24955
26070
  }
24956
26071
  function projectField(project, key) {
24957
- const metaForm = isRecord14(project.metaForm) ? project.metaForm : {};
24958
- const values = dataArray(metaForm.value ?? project.formList).filter(isRecord14);
26072
+ const metaForm = isRecord15(project.metaForm) ? project.metaForm : {};
26073
+ const values = dataArray(metaForm.value ?? project.formList).filter(isRecord15);
24959
26074
  const row = values.find((item) => String(item.key ?? item.field_key ?? "") === key);
24960
26075
  if (!row) return void 0;
24961
26076
  const value = row.value;
24962
- return isRecord14(value) && Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;
26077
+ return isRecord15(value) && Object.prototype.hasOwnProperty.call(value, "value") ? value.value : value;
24963
26078
  }
24964
26079
  function collectUserIds(value) {
24965
26080
  if (Array.isArray(value)) return [...new Set(value.flatMap(collectUserIds))];
24966
- if (isRecord14(value)) {
26081
+ if (isRecord15(value)) {
24967
26082
  const direct2 = Number(value.id ?? value.user_id ?? value.value);
24968
26083
  if (Number.isSafeInteger(direct2) && direct2 > 0) return [direct2];
24969
26084
  return [...new Set(Object.values(value).flatMap(collectUserIds))];
@@ -24984,7 +26099,7 @@ async function readMatrixApprovers(client, ids) {
24984
26099
  },
24985
26100
  capability: "user.readback"
24986
26101
  });
24987
- users.push(...dataArray(result).filter(isRecord14));
26102
+ users.push(...dataArray(result).filter(isRecord15));
24988
26103
  }
24989
26104
  return users;
24990
26105
  }
@@ -25068,7 +26183,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
25068
26183
  const matrixOwnerConfig = node ? collectMatrixOwnerPaths(node) : [];
25069
26184
  const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
25070
26185
  const owners = safePredictedOwners(predictedNode?.owners);
25071
- const ownerResolution = predictedNode && isRecord14(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
26186
+ const ownerResolution = predictedNode && isRecord15(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
25072
26187
  const projectFlowType = String(project.flow_type ?? "");
25073
26188
  const flowMatchesProject = !projectFlowType || projectFlowType === options.flowType;
25074
26189
  printResult(options.format, {
@@ -25159,14 +26274,14 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
25159
26274
  if (!workspace) throw new Error("matrix.app.workspace_required: \u8BF7\u63D0\u4F9B --workspace \u4EE5\u5220\u9664\u77E9\u9635\u5E94\u7528\u3002");
25160
26275
  const definition = await inspectMatrixAppDefinition(profile, options.flowType, workspace, true, false);
25161
26276
  const exact = definition.exact_readback;
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) : [];
26277
+ const listItems = Array.isArray(exact.list_templates) ? exact.list_templates.filter(isRecord15) : [];
26278
+ const filterItems = Array.isArray(exact.filter_templates) ? exact.filter_templates.filter(isRecord15) : [];
26279
+ const datasetItems = Array.isArray(exact.datasets) ? exact.datasets.filter(isRecord15) : [];
25165
26280
  const datasetFieldIds = uniqueIds(datasetItems.flatMap((item) => {
25166
- const readback = isRecord14(item.readback) ? item.readback : {};
25167
- return Array.isArray(readback.dataSetFields) ? readback.dataSetFields.filter(isRecord14).map((field) => field.id) : [];
26281
+ const readback = isRecord15(item.readback) ? item.readback : {};
26282
+ return Array.isArray(readback.dataSetFields) ? readback.dataSetFields.filter(isRecord15).map((field) => field.id) : [];
25168
26283
  }));
25169
- const formItem = isRecord14(exact.form_template) ? exact.form_template : {};
26284
+ const formItem = isRecord15(exact.form_template) ? exact.form_template : {};
25170
26285
  const formDraftId = String(formItem.draft_id ?? formItem.id ?? "");
25171
26286
  const expectedConfirm = `delete matrix app ${options.flowType} from ${workspace}`;
25172
26287
  const plan = [
@@ -25228,8 +26343,8 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
25228
26343
  apiRequest(client, "GET", "/flow_page_template", { params: { type: 3, flow_type: options.matrixFlowType, flow_key: "", skip_i18n: true }, capability: "config.filter_template.export" }),
25229
26344
  apiRequest(client, "GET", "/workspace/by_key", { params: { key: workspace }, capability: "config.workspace_flow.export" })
25230
26345
  ]);
25231
- const listRows = dataArray(listResult).filter(isRecord14);
25232
- const filterRows = dataArray(filterResult).filter(isRecord14);
26346
+ const listRows = dataArray(listResult).filter(isRecord15);
26347
+ const filterRows = dataArray(filterResult).filter(isRecord15);
25233
26348
  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" })));
25234
26349
  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" })));
25235
26350
  const datasetIds = uniqueIds([...listTemplates.map((item) => item.data_set_id), ...filterTemplates.map((item) => item.data_set_id)]);
@@ -25263,7 +26378,7 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
25263
26378
  }
25264
26379
  const predictedNode = predictedNodes(prediction).find((item) => String(item.node_id ?? item.id ?? "") === options.node);
25265
26380
  const predictedOwners = safePredictedOwners(predictedNode?.owners);
25266
- const ownerResolution = predictedNode && isRecord14(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
26381
+ const ownerResolution = predictedNode && isRecord15(predictedNode.owner_resolution) ? predictedNode.owner_resolution : { status: predictedNode ? "resolved" : "missing" };
25267
26382
  if (ownerResolution.status === "error") {
25268
26383
  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" });
25269
26384
  } else if (!predictedNode || predictedOwners.length === 0) {
@@ -25287,13 +26402,13 @@ ${errors.map((error) => `- [${error.rule_index}] ${error.code}${error.path ? ` $
25287
26402
  }
25288
26403
 
25289
26404
  // src/commands/organization.ts
25290
- function isRecord15(value) {
26405
+ function isRecord16(value) {
25291
26406
  return typeof value === "object" && value !== null && !Array.isArray(value);
25292
26407
  }
25293
26408
  function rows(value) {
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);
26409
+ if (Array.isArray(value)) return value.filter(isRecord16);
26410
+ if (!isRecord16(value)) return [];
26411
+ if (Array.isArray(value.data)) return value.data.filter(isRecord16);
25297
26412
  return value.id ? [value] : [];
25298
26413
  }
25299
26414
  function positiveId(value, errorCode) {
@@ -25317,7 +26432,7 @@ function safeDepartment(group) {
25317
26432
  function departmentRows(value) {
25318
26433
  const result = [];
25319
26434
  const visit = (item) => {
25320
- if (!isRecord15(item)) return;
26435
+ if (!isRecord16(item)) return;
25321
26436
  if (item.id !== void 0) result.push(safeDepartment(item));
25322
26437
  if (Array.isArray(item.children)) item.children.forEach(visit);
25323
26438
  };
@@ -25326,7 +26441,7 @@ function departmentRows(value) {
25326
26441
  }
25327
26442
  function relationDepartments(value) {
25328
26443
  if (!Array.isArray(value)) return [];
25329
- return value.filter(isRecord15).map(safeDepartment);
26444
+ return value.filter(isRecord16).map(safeDepartment);
25330
26445
  }
25331
26446
  function safeUser(user) {
25332
26447
  const status = user.status === void 0 ? null : Number(user.status);
@@ -25373,8 +26488,8 @@ async function readDepartments(client, ids) {
25373
26488
  function pathIds(departments) {
25374
26489
  const ids = /* @__PURE__ */ new Set();
25375
26490
  for (const department of departments) {
25376
- const path19 = String(department.path ?? "");
25377
- for (const part of path19.split(/[|,]/)) {
26491
+ const path20 = String(department.path ?? "");
26492
+ for (const part of path20.split(/[|,]/)) {
25378
26493
  const id = Number(part);
25379
26494
  if (Number.isSafeInteger(id) && id > 0) ids.add(id);
25380
26495
  }
@@ -25384,7 +26499,7 @@ function pathIds(departments) {
25384
26499
  function mainDepartmentId(raw) {
25385
26500
  for (const key of ["main_department_id", "main_group_id", "main_department"]) {
25386
26501
  const value = raw[key];
25387
- if (isRecord15(value)) {
26502
+ if (isRecord16(value)) {
25388
26503
  const id2 = Number(value.id);
25389
26504
  if (Number.isSafeInteger(id2) && id2 > 0) return id2;
25390
26505
  }
@@ -25396,7 +26511,7 @@ function mainDepartmentId(raw) {
25396
26511
  function branchId(raw) {
25397
26512
  for (const key of ["branch_id", "branch_group_id", "branch"]) {
25398
26513
  const value = raw[key];
25399
- if (isRecord15(value)) {
26514
+ if (isRecord16(value)) {
25400
26515
  const id2 = Number(value.id);
25401
26516
  if (Number.isSafeInteger(id2) && id2 > 0) return id2;
25402
26517
  }
@@ -25914,15 +27029,15 @@ async function promptProjectCreateForm(input) {
25914
27029
  }
25915
27030
 
25916
27031
  // src/core/project-form.ts
25917
- function isRecord16(value) {
27032
+ function isRecord17(value) {
25918
27033
  return typeof value === "object" && value !== null && !Array.isArray(value);
25919
27034
  }
25920
27035
  function clone(value) {
25921
27036
  return JSON.parse(JSON.stringify(value));
25922
27037
  }
25923
27038
  function getFlowFormTemplateId(flowDetail) {
25924
- const data = isRecord16(flowDetail?.data) ? flowDetail.data : void 0;
25925
- const meta = isRecord16(data?.meta) ? data.meta : void 0;
27039
+ const data = isRecord17(flowDetail?.data) ? flowDetail.data : void 0;
27040
+ const meta = isRecord17(data?.meta) ? data.meta : void 0;
25926
27041
  const templateId = meta?.form_template;
25927
27042
  if (typeof templateId === "number" && Number.isFinite(templateId)) {
25928
27043
  return templateId;
@@ -25947,7 +27062,7 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
25947
27062
  if (Array.isArray(value)) {
25948
27063
  return value.some((item) => hasAutoInitLambda(item, seen));
25949
27064
  }
25950
- if (!isRecord16(value)) {
27065
+ if (!isRecord17(value)) {
25951
27066
  return false;
25952
27067
  }
25953
27068
  if (seen.has(value)) {
@@ -25962,14 +27077,14 @@ function hasAutoInitLambda(value, seen = /* @__PURE__ */ new WeakSet()) {
25962
27077
  function setControlValue(control, value) {
25963
27078
  const next = clone(control);
25964
27079
  next.value = {
25965
- ...isRecord16(next.value) ? next.value : {},
27080
+ ...isRecord17(next.value) ? next.value : {},
25966
27081
  type: next.value?.type ?? next.field_type,
25967
27082
  value
25968
27083
  };
25969
27084
  return next;
25970
27085
  }
25971
27086
  function applyRowValues(rowTemplate, rowValue) {
25972
- const source = isRecord16(rowValue) ? rowValue : {};
27087
+ const source = isRecord17(rowValue) ? rowValue : {};
25973
27088
  return rowTemplate.map((control) => {
25974
27089
  if (control.key && Object.prototype.hasOwnProperty.call(source, control.key)) {
25975
27090
  return setControlValue(control, source[control.key]);
@@ -26255,17 +27370,17 @@ function assertStepProjectFormWritable(fields, form, prefix = "") {
26255
27370
  for (const [key, value] of Object.entries(form)) {
26256
27371
  const field = fieldsByKey.get(key);
26257
27372
  if (!field) continue;
26258
- const path19 = `${prefix}${key}`;
27373
+ const path20 = `${prefix}${key}`;
26259
27374
  if (field.hidden) {
26260
- throw new Error(`Step project form handoff cannot write hidden field ${path19}.`);
27375
+ throw new Error(`Step project form handoff cannot write hidden field ${path20}.`);
26261
27376
  }
26262
27377
  if (isUnsupportedStepPrefillField(field)) {
26263
- throw new Error(`Step project form handoff cannot write system or manual field ${path19} (${field.type || "unknown"}).`);
27378
+ throw new Error(`Step project form handoff cannot write system or manual field ${path20} (${field.type || "unknown"}).`);
26264
27379
  }
26265
27380
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
26266
27381
  value.forEach((row, index) => {
26267
27382
  if (isRecordValue(row)) {
26268
- assertStepProjectFormWritable(field.children ?? [], row, `${path19}[${index}].`);
27383
+ assertStepProjectFormWritable(field.children ?? [], row, `${path20}[${index}].`);
26269
27384
  }
26270
27385
  });
26271
27386
  }
@@ -26527,8 +27642,8 @@ function fieldsForValidation(flowDetail, projectFormTemplate) {
26527
27642
  }));
26528
27643
  }
26529
27644
  function metaUsesTemplateProjectName(flowDetail) {
26530
- const data = isRecord17(flowDetail?.data) ? flowDetail.data : void 0;
26531
- const meta = isRecord17(data?.meta) ? data.meta : void 0;
27645
+ const data = isRecord18(flowDetail?.data) ? flowDetail.data : void 0;
27646
+ const meta = isRecord18(data?.meta) ? data.meta : void 0;
26532
27647
  const hideFields = Array.isArray(meta?.hide_fields) ? meta.hide_fields.map(String) : [];
26533
27648
  return meta?.use_template_project_name === true || hideFields.includes("project.name");
26534
27649
  }
@@ -26622,9 +27737,9 @@ function contextField(field, reason, options = {}) {
26622
27737
  function collectPrefillContextForFields(fields, form, result, options = {}) {
26623
27738
  for (const field of fields) {
26624
27739
  const value = form[field.key];
26625
- const path19 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
27740
+ const path20 = options.prefix ? `${options.prefix}.${field.key}` : field.key;
26626
27741
  const fieldOptions = {
26627
- path: path19,
27742
+ path: path20,
26628
27743
  rootKey: options.rootKey ?? field.key,
26629
27744
  parentKey: options.parentKey
26630
27745
  };
@@ -26637,7 +27752,7 @@ function collectPrefillContextForFields(fields, form, result, options = {}) {
26637
27752
  result.filled_fields.push(contextField(field, "prefilled", fieldOptions));
26638
27753
  if (isSubFormField(field) && Array.isArray(value) && field.children?.length) {
26639
27754
  value.forEach((row, index) => {
26640
- if (isRecord17(row)) {
27755
+ if (isRecord18(row)) {
26641
27756
  collectPrefillContextForFields(field.children ?? [], row, result, {
26642
27757
  prefix: `${field.key}[${index}]`,
26643
27758
  rootKey: field.key,
@@ -26664,7 +27779,7 @@ function buildPrefillContext(fields, form) {
26664
27779
  }
26665
27780
  };
26666
27781
  }
26667
- function isRecord17(value) {
27782
+ function isRecord18(value) {
26668
27783
  return typeof value === "object" && value !== null && !Array.isArray(value);
26669
27784
  }
26670
27785
  function isEndedStep(step) {
@@ -26687,7 +27802,7 @@ function stepIdOf(step) {
26687
27802
  function pickStepFormPayload(step) {
26688
27803
  const formList = Array.isArray(step.formList) ? step.formList : [];
26689
27804
  const forms = Array.isArray(step.forms) ? step.forms : [];
26690
- const metaForm = isRecord17(step.metaForm) ? step.metaForm : void 0;
27805
+ const metaForm = isRecord18(step.metaForm) ? step.metaForm : void 0;
26691
27806
  return {
26692
27807
  step_id: step.id,
26693
27808
  flow_step_id: step.flow_step_id,
@@ -26704,7 +27819,7 @@ function pickStepFormPayload(step) {
26704
27819
  }
26705
27820
  async function buildApprovalContext(client, projectId, options) {
26706
27821
  const projectDetail = await apiRequest(client, "GET", `/project/${projectId}`);
26707
- const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord17) : [];
27822
+ const steps = Array.isArray(projectDetail.steps) ? projectDetail.steps.filter(isRecord18) : [];
26708
27823
  const targetStepIds = /* @__PURE__ */ new Set();
26709
27824
  for (const step of steps) {
26710
27825
  const id = stepIdOf(step);
@@ -26730,7 +27845,7 @@ async function buildApprovalContext(client, projectId, options) {
26730
27845
  }
26731
27846
  return {
26732
27847
  project: projectDetail,
26733
- project_form: isRecord17(projectDetail.metaForm) ? projectDetail.metaForm : null,
27848
+ project_form: isRecord18(projectDetail.metaForm) ? projectDetail.metaForm : null,
26734
27849
  inspected_step_count: stepForms.length,
26735
27850
  step_forms: stepForms,
26736
27851
  failed_steps: failedSteps
@@ -27068,8 +28183,8 @@ import { spawn as spawn2 } from "child_process";
27068
28183
  import { fileURLToPath as fileURLToPath3 } from "url";
27069
28184
 
27070
28185
  // src/core/recipes.ts
27071
- import { access, mkdir as mkdir12, readdir as readdir6, readFile as readFile18, writeFile as writeFile12 } from "fs/promises";
27072
- import path15 from "path";
28186
+ import { access, mkdir as mkdir13, readdir as readdir6, readFile as readFile19, writeFile as writeFile13 } from "fs/promises";
28187
+ import path16 from "path";
27073
28188
  var RECIPE_NAME_PATTERN = /^[a-zA-Z0-9][a-zA-Z0-9._-]*$/;
27074
28189
  var TEMPLATE_PATTERN = /{{\s*([a-zA-Z0-9_.-]+)\s*}}/g;
27075
28190
  function assertSafeName(kind, value) {
@@ -27093,14 +28208,14 @@ function resolveRecipeLocation(options) {
27093
28208
  workspace,
27094
28209
  workspaceDirName,
27095
28210
  recipeName: options.recipeName,
27096
- recipeDir: path15.join(profileDir, "recipes", workspaceDirName, options.recipeName)
28211
+ recipeDir: path16.join(profileDir, "recipes", workspaceDirName, options.recipeName)
27097
28212
  };
27098
28213
  }
27099
28214
  function getRecipesDir(options) {
27100
28215
  const workspaceDirName = normalizeWorkspaceForPath(options.workspace || DEFAULT_WORKSPACE);
27101
- return path15.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
28216
+ return path16.join((options.getProfileDir || getProfileDataDir)(options.profileName), "recipes", workspaceDirName);
27102
28217
  }
27103
- function isRecord18(value) {
28218
+ function isRecord19(value) {
27104
28219
  return typeof value === "object" && value !== null && !Array.isArray(value);
27105
28220
  }
27106
28221
  function asString(value, fieldName) {
@@ -27110,7 +28225,7 @@ function asString(value, fieldName) {
27110
28225
  return value;
27111
28226
  }
27112
28227
  function parseRecipeDefinition(input) {
27113
- if (!isRecord18(input)) {
28228
+ if (!isRecord19(input)) {
27114
28229
  throw new Error("recipe.json must be a JSON object.");
27115
28230
  }
27116
28231
  if (input.version !== 1) {
@@ -27118,7 +28233,7 @@ function parseRecipeDefinition(input) {
27118
28233
  }
27119
28234
  const name = asString(input.name, "recipe.name");
27120
28235
  assertSafeName("Recipe name", name);
27121
- if (!isRecord18(input.command)) {
28236
+ if (!isRecord19(input.command)) {
27122
28237
  throw new Error("recipe.command must be an object.");
27123
28238
  }
27124
28239
  const argv = input.command.argv;
@@ -27126,7 +28241,7 @@ function parseRecipeDefinition(input) {
27126
28241
  throw new Error("recipe.command.argv must be a non-empty string array.");
27127
28242
  }
27128
28243
  const variables = Array.isArray(input.variables) ? input.variables.map((item, index) => {
27129
- if (!isRecord18(item)) {
28244
+ if (!isRecord19(item)) {
27130
28245
  throw new Error(`recipe.variables[${index}] must be an object.`);
27131
28246
  }
27132
28247
  const variableName = asString(item.name, `recipe.variables[${index}].name`);
@@ -27150,7 +28265,7 @@ function parseRecipeDefinition(input) {
27150
28265
  };
27151
28266
  }
27152
28267
  async function loadRecipe(recipeDir) {
27153
- const raw = await readFile18(path15.join(recipeDir, "recipe.json"), "utf8");
28268
+ const raw = await readFile19(path16.join(recipeDir, "recipe.json"), "utf8");
27154
28269
  return parseRecipeDefinition(JSON.parse(raw));
27155
28270
  }
27156
28271
  async function listRecipes(recipesDir) {
@@ -27168,7 +28283,7 @@ async function listRecipes(recipesDir) {
27168
28283
  if (!RECIPE_NAME_PATTERN.test(entry)) {
27169
28284
  continue;
27170
28285
  }
27171
- const recipeDir = path15.join(recipesDir, entry);
28286
+ const recipeDir = path16.join(recipesDir, entry);
27172
28287
  try {
27173
28288
  const recipe = await loadRecipe(recipeDir);
27174
28289
  summaries.push({
@@ -27202,7 +28317,7 @@ function parseVarsJson(input) {
27202
28317
  return {};
27203
28318
  }
27204
28319
  const parsed = JSON.parse(input);
27205
- if (!isRecord18(parsed)) {
28320
+ if (!isRecord19(parsed)) {
27206
28321
  throw new Error("--vars must be a JSON object.");
27207
28322
  }
27208
28323
  const variables = {};
@@ -27234,12 +28349,12 @@ function renderTemplate(template, variables) {
27234
28349
  }
27235
28350
  function resolveRecipeFile(recipeDir, token) {
27236
28351
  const relative = token.slice(1);
27237
- if (!relative || relative.includes("..") || path15.isAbsolute(relative)) {
28352
+ if (!relative || relative.includes("..") || path16.isAbsolute(relative)) {
27238
28353
  throw new Error(`Unsafe recipe file reference: ${token}`);
27239
28354
  }
27240
- const resolved = path15.resolve(recipeDir, relative);
27241
- const root = path15.resolve(recipeDir);
27242
- if (resolved !== root && !resolved.startsWith(`${root}${path15.sep}`)) {
28355
+ const resolved = path16.resolve(recipeDir, relative);
28356
+ const root = path16.resolve(recipeDir);
28357
+ if (resolved !== root && !resolved.startsWith(`${root}${path16.sep}`)) {
27243
28358
  throw new Error(`Recipe file reference escapes recipe directory: ${token}`);
27244
28359
  }
27245
28360
  return resolved;
@@ -27249,7 +28364,7 @@ async function renderArgv(options) {
27249
28364
  const rendered = [];
27250
28365
  for (const token of options.recipe.command.argv) {
27251
28366
  if (token.startsWith("@")) {
27252
- const raw = await readFile18(resolveRecipeFile(options.recipeDir, token), "utf8");
28367
+ const raw = await readFile19(resolveRecipeFile(options.recipeDir, token), "utf8");
27253
28368
  rendered.push(renderTemplate(raw, options.variables));
27254
28369
  } else {
27255
28370
  rendered.push(renderTemplate(token, options.variables));
@@ -27275,7 +28390,7 @@ async function ensureEmptyOrForce(targetDir, force = false) {
27275
28390
  }
27276
28391
  async function writeRecipeScaffold(options) {
27277
28392
  await ensureEmptyOrForce(options.location.recipeDir, options.force);
27278
- await mkdir12(options.location.recipeDir, { recursive: true });
28393
+ await mkdir13(options.location.recipeDir, { recursive: true });
27279
28394
  const title = options.title || options.location.recipeName;
27280
28395
  const recipe = {
27281
28396
  version: 1,
@@ -27292,16 +28407,16 @@ async function writeRecipeScaffold(options) {
27292
28407
  mutating: true
27293
28408
  }
27294
28409
  };
27295
- await writeFile12(path15.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
28410
+ await writeFile13(path16.join(options.location.recipeDir, "recipe.json"), `${JSON.stringify(recipe, null, 2)}
27296
28411
  `, "utf8");
27297
- await writeFile12(
27298
- path15.join(options.location.recipeDir, "payload.json"),
28412
+ await writeFile13(
28413
+ path16.join(options.location.recipeDir, "payload.json"),
27299
28414
  `${JSON.stringify({ form: {} }, null, 2)}
27300
28415
  `,
27301
28416
  "utf8"
27302
28417
  );
27303
- await writeFile12(
27304
- path15.join(options.location.recipeDir, "README.md"),
28418
+ await writeFile13(
28419
+ path16.join(options.location.recipeDir, "README.md"),
27305
28420
  [`# ${title}`, "", "Describe the BPMAX flow, field mapping, prerequisites, and verification steps for this recipe.", ""].join("\n"),
27306
28421
  "utf8"
27307
28422
  );
@@ -27736,8 +28851,8 @@ function registerSetupCommand(program2, deps = {}) {
27736
28851
  }
27737
28852
 
27738
28853
  // src/core/taskbook.ts
27739
- import { mkdir as mkdir13, readFile as readFile19, writeFile as writeFile13 } from "fs/promises";
27740
- import path16 from "path";
28854
+ import { mkdir as mkdir14, readFile as readFile20, writeFile as writeFile14 } from "fs/promises";
28855
+ import path17 from "path";
27741
28856
  var TaskbookError = class extends Error {
27742
28857
  };
27743
28858
  var REQUIRED_TASKBOOK_TERMS = [
@@ -27953,19 +29068,19 @@ function hasDomainWriteEvidence(domain, evidenceText, patterns) {
27953
29068
  function uuidValues(text5) {
27954
29069
  return [...new Set([...text5.matchAll(UUID_PATTERN)].map((match) => match[0]))];
27955
29070
  }
27956
- function addUuidIssues(text5, issues, path19) {
29071
+ function addUuidIssues(text5, issues, path20) {
27957
29072
  for (const value of uuidValues(text5)) {
27958
29073
  addTaskbookIssue(
27959
29074
  issues,
27960
29075
  "uuid_not_allowed",
27961
29076
  "taskbook.config.no_uuid",
27962
29077
  `BPMAX \u914D\u7F6E\u4EFB\u52A1\u4E0D\u80FD\u4F7F\u7528 UUID\uFF1A${value}\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" }
29078
+ { path: path20, 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" }
27964
29079
  );
27965
29080
  }
27966
29081
  }
27967
29082
  async function readTaskbookText(file) {
27968
- const raw = await readFile19(file, "utf8");
29083
+ const raw = await readFile20(file, "utf8");
27969
29084
  try {
27970
29085
  const parsed = JSON.parse(raw);
27971
29086
  if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
@@ -27992,7 +29107,7 @@ function findNavigationStrategy(text5) {
27992
29107
  const matches = [...text5.matchAll(/导航入口策略\s*[::]\s*(nav-config:(?:included|skipped:[^\s|,。]+|deferred:[^\s|,。]+))/gi)];
27993
29108
  return matches.at(-1)?.[1] || null;
27994
29109
  }
27995
- function validateNavigationStrategy(text5, issues, path19, subject) {
29110
+ function validateNavigationStrategy(text5, issues, path20, subject) {
27996
29111
  const strategy = findNavigationStrategy(text5);
27997
29112
  if (!strategy) {
27998
29113
  addTaskbookIssue(
@@ -28000,7 +29115,7 @@ function validateNavigationStrategy(text5, issues, path19, subject) {
28000
29115
  "missing_navigation_strategy",
28001
29116
  "taskbook.nav.strategy",
28002
29117
  `${subject}\u7F3A\u5C11\u660E\u786E\u7684\u5BFC\u822A\u5165\u53E3\u7B56\u7565\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" }
29118
+ { path: path20, suggestion: "\u5199\u660E \u5BFC\u822A\u5165\u53E3\u7B56\u7565\uFF1Anav-config:included\u3001nav-config:skipped:<reason> \u6216 nav-config:deferred:<reason>\u3002" }
28004
29119
  );
28005
29120
  return null;
28006
29121
  }
@@ -28010,7 +29125,7 @@ function validateNavigationStrategy(text5, issues, path19, subject) {
28010
29125
  "empty_navigation_strategy_reason",
28011
29126
  "taskbook.nav.strategy_reason",
28012
29127
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u8DF3\u8FC7\u6216\u5EF6\u540E\u65F6\u5FC5\u987B\u5199\u660E\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" }
29128
+ { path: path20, suggestion: "\u4F7F\u7528 nav-config:skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 nav-config:deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
28014
29129
  );
28015
29130
  }
28016
29131
  if (/(待完成范围确认后回填|待确认|TODO|TBD|占位)/i.test(strategy)) {
@@ -28019,7 +29134,7 @@ function validateNavigationStrategy(text5, issues, path19, subject) {
28019
29134
  "placeholder_navigation_strategy",
28020
29135
  "taskbook.nav.strategy_placeholder",
28021
29136
  `${subject}\u5BFC\u822A\u5165\u53E3\u7B56\u7565\u4ECD\u662F\u5360\u4F4D\u5185\u5BB9\u3002`,
28022
- { path: path19, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
29137
+ { path: path20, suggestion: "\u66FF\u6362\u4E3A included\u3001skipped:<\u771F\u5B9E\u539F\u56E0> \u6216 deferred:<\u771F\u5B9E\u539F\u56E0>\u3002" }
28023
29138
  );
28024
29139
  }
28025
29140
  return strategy;
@@ -28571,8 +29686,8 @@ function taskbookTemplate(title = "BPMAX AI \u5B9E\u65BD\u7F16\u6392\u4EFB\u52A1
28571
29686
  }
28572
29687
  async function initTaskbook(outFile, title) {
28573
29688
  const content = taskbookTemplate(title);
28574
- await mkdir13(path16.dirname(outFile), { recursive: true });
28575
- await writeFile13(outFile, content, "utf8");
29689
+ await mkdir14(path17.dirname(outFile), { recursive: true });
29690
+ await writeFile14(outFile, content, "utf8");
28576
29691
  return { out: outFile, bytes: Buffer.byteLength(content) };
28577
29692
  }
28578
29693
  function splitMarkdownRow(line) {
@@ -28661,8 +29776,8 @@ async function initTaskbookProgress(source, outFile) {
28661
29776
  fields.join(","),
28662
29777
  ...rows2.map((row) => fields.map((field) => csvEscape(field === "status" ? "\u672A\u5F00\u59CB" : row[field] || "")).join(","))
28663
29778
  ].join("\n") + "\n";
28664
- await mkdir13(path16.dirname(outFile), { recursive: true });
28665
- await writeFile13(outFile, csv, "utf8");
29779
+ await mkdir14(path17.dirname(outFile), { recursive: true });
29780
+ await writeFile14(outFile, csv, "utf8");
28666
29781
  return { source, out: outFile, task_count: rows2.length };
28667
29782
  }
28668
29783
 
@@ -28704,8 +29819,8 @@ function registerTaskbookCommands(program2) {
28704
29819
  }
28705
29820
 
28706
29821
  // src/commands/test-suite.ts
28707
- import { readFile as readFile20 } from "fs/promises";
28708
- import path17 from "path";
29822
+ import { readFile as readFile21 } from "fs/promises";
29823
+ import path18 from "path";
28709
29824
  function collect2(value, previous = []) {
28710
29825
  previous.push(value);
28711
29826
  return previous;
@@ -28715,8 +29830,8 @@ function effectiveProfileOption(options, command) {
28715
29830
  }
28716
29831
  async function resolveE2eSkillSource(sourceSkill) {
28717
29832
  if (sourceSkill) {
28718
- const resolved = path17.resolve(sourceSkill);
28719
- const content = await readFile20(resolved, "utf8").catch(() => "");
29833
+ const resolved = path18.resolve(sourceSkill);
29834
+ const content = await readFile21(resolved, "utf8").catch(() => "");
28720
29835
  if (!content.includes('name: "bpmax-e2e-flow-test-operator"') && !content.includes("name: bpmax-e2e-flow-test-operator")) {
28721
29836
  throw new TestSuiteError("source skill is not bpmax-e2e-flow-test-operator", {
28722
29837
  rule_id: "test_suite.run.skill_source_invalid",
@@ -28818,8 +29933,8 @@ function registerTestSuiteCommands(program2) {
28818
29933
  }
28819
29934
 
28820
29935
  // src/core/update.ts
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";
29936
+ import { access as access2, mkdir as mkdir15, readFile as readFile22, realpath as realpath4, writeFile as writeFile15 } from "fs/promises";
29937
+ import path19 from "path";
28823
29938
  var DEFAULT_REGISTRY_URL = "https://registry.npmjs.org/";
28824
29939
  var UPDATE_STATE_FILE = "update-state.json";
28825
29940
  var CACHE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -28935,11 +30050,11 @@ async function fetchLatestVersion(options = {}) {
28935
30050
  }
28936
30051
  }
28937
30052
  function updateStatePath(configDir = getConfigDir()) {
28938
- return path18.join(configDir, UPDATE_STATE_FILE);
30053
+ return path19.join(configDir, UPDATE_STATE_FILE);
28939
30054
  }
28940
30055
  async function readUpdateState(configDir) {
28941
30056
  try {
28942
- const raw = await readFile21(updateStatePath(configDir), "utf8");
30057
+ const raw = await readFile22(updateStatePath(configDir), "utf8");
28943
30058
  const parsed = JSON.parse(raw);
28944
30059
  if (typeof parsed.latest_version !== "string" || typeof parsed.checked_at !== "number") {
28945
30060
  return null;
@@ -28954,8 +30069,8 @@ async function readUpdateState(configDir) {
28954
30069
  }
28955
30070
  }
28956
30071
  async function writeUpdateState(state, configDir = getConfigDir()) {
28957
- await mkdir14(configDir, { recursive: true });
28958
- await writeFile14(updateStatePath(configDir), JSON.stringify(state), "utf8");
30072
+ await mkdir15(configDir, { recursive: true });
30073
+ await writeFile15(updateStatePath(configDir), JSON.stringify(state), "utf8");
28959
30074
  }
28960
30075
  async function checkCachedUpdate(currentVersion, configDir = getConfigDir()) {
28961
30076
  if (process.env.BPMAX_CLI_NO_UPDATE_NOTIFIER) {
@@ -29001,7 +30116,7 @@ async function executablePath() {
29001
30116
  return "";
29002
30117
  }
29003
30118
  try {
29004
- return await realpath3(candidate);
30119
+ return await realpath4(candidate);
29005
30120
  } catch {
29006
30121
  return candidate;
29007
30122
  }
@@ -29016,7 +30131,7 @@ async function findNpmPath() {
29016
30131
  }
29017
30132
  function detectInstallMethod(input) {
29018
30133
  const resolvedPath = input.executablePath || "";
29019
- const method = resolvedPath.includes(`node_modules${path18.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
30134
+ const method = resolvedPath.includes(`node_modules${path19.sep}`) || resolvedPath.includes("node_modules/") ? "npm" : "manual";
29020
30135
  return {
29021
30136
  method,
29022
30137
  resolvedPath,
@@ -29257,17 +30372,17 @@ function registerUrlCommands(program2, deps = {}) {
29257
30372
  }
29258
30373
 
29259
30374
  // src/commands/user.ts
29260
- function isRecord19(value) {
30375
+ function isRecord20(value) {
29261
30376
  return typeof value === "object" && value !== null && !Array.isArray(value);
29262
30377
  }
29263
30378
  function userRows(value) {
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);
30379
+ if (Array.isArray(value)) return value.filter(isRecord20);
30380
+ if (!isRecord20(value)) return [];
30381
+ if (Array.isArray(value.data)) return value.data.filter(isRecord20);
29267
30382
  return value.id ? [value] : [];
29268
30383
  }
29269
30384
  function safeUser2(user) {
29270
- const roles = Array.isArray(user.role) ? user.role.filter(isRecord19).map((role) => ({
30385
+ const roles = Array.isArray(user.role) ? user.role.filter(isRecord20).map((role) => ({
29271
30386
  id: role.id,
29272
30387
  key: role.key,
29273
30388
  name: role.name