bpmax-cli 0.2.1-beta.55 → 0.2.1-beta.56

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
@@ -499,7 +499,7 @@ function pluginAgentCapabilityForRequest(method, normalizedPath) {
499
499
  // package.json
500
500
  var package_default = {
501
501
  name: "bpmax-cli",
502
- version: "0.2.1-beta.55",
502
+ version: "0.2.1-beta.56",
503
503
  description: "CLI for BPMAX environments with multi-profile config and local login callback flow",
504
504
  type: "module",
505
505
  bin: {
@@ -5347,6 +5347,7 @@ var DATASET_SOURCE_TABLE_COLUMNS = /* @__PURE__ */ new Map([
5347
5347
  "create_time",
5348
5348
  "update_time",
5349
5349
  "plan_end_time",
5350
+ "real_end_time",
5350
5351
  "user_id",
5351
5352
  "project_id",
5352
5353
  "step_id",
@@ -18631,6 +18632,7 @@ var SUPPORTED_ACTIONS = {
18631
18632
  radio: ["form.select_option"],
18632
18633
  checkbox: ["form.select_option"],
18633
18634
  "bp-date-picker": ["form.set_value", "form.set_date_range"],
18635
+ date_picker: ["form.set_value", "form.set_date_range"],
18634
18636
  "bp-upload": ["form.upload_file"],
18635
18637
  punishment_item_form_control: ["form.set_punishment"],
18636
18638
  signature: ["form.draw_signature"],
@@ -18639,7 +18641,8 @@ var SUPPORTED_ACTIONS = {
18639
18641
  flow_selector: ["form.select_option"],
18640
18642
  user_select: ["form.select_option", "form.select_user"],
18641
18643
  group_select: ["form.select_option"],
18642
- ecology_browser_review: ["form.select_option"]
18644
+ ecology_browser_review: ["form.select_option"],
18645
+ sub_form: ["detail.add_row", "detail.set_value"]
18643
18646
  };
18644
18647
  var SELECTOR_CONTROLS = /* @__PURE__ */ new Set([
18645
18648
  "selector",
@@ -18660,7 +18663,6 @@ var UNSUPPORTED_REQUIRED_CONTROLS = /* @__PURE__ */ new Set([
18660
18663
  "group_selector",
18661
18664
  "project_selector",
18662
18665
  "relation_selector",
18663
- "sub_form",
18664
18666
  "subform"
18665
18667
  ]);
18666
18668
  function controlActionsFor(controlType) {
@@ -18982,7 +18984,7 @@ import axios7 from "axios";
18982
18984
 
18983
18985
  // src/core/e2e-scenario-orchestrator.ts
18984
18986
  import { createHash as createHash11 } from "crypto";
18985
- import { chmod as chmod2, mkdir as mkdir12, readFile as readFile16, realpath as realpath6, rename as rename4, rm as rm6, stat as stat11, writeFile as writeFile12 } from "fs/promises";
18987
+ import { chmod as chmod3, mkdir as mkdir12, readFile as readFile16, realpath as realpath6, rename as rename4, rm as rm6, stat as stat11, writeFile as writeFile12 } from "fs/promises";
18986
18988
  import path17 from "path";
18987
18989
 
18988
18990
  // src/core/e2e-automation-schema.ts
@@ -19012,6 +19014,7 @@ var BROWSER_ACTION_TYPES = [
19012
19014
  "context.extract",
19013
19015
  "page.assert_step",
19014
19016
  "list.assert_record",
19017
+ "list.assert_cell",
19015
19018
  "message.open",
19016
19019
  "message.assert_delivery",
19017
19020
  "file.download",
@@ -19058,6 +19061,7 @@ var CHECK_TYPES = /* @__PURE__ */ new Set([
19058
19061
  "wait.route",
19059
19062
  "page.assert_step",
19060
19063
  "list.assert_record",
19064
+ "list.assert_cell",
19061
19065
  "message.assert_delivery"
19062
19066
  ]);
19063
19067
  var MUTATION_READBACK_CHECK_TYPES = /* @__PURE__ */ new Set([
@@ -19151,7 +19155,10 @@ function actionTargetMatchesField(action, field, label) {
19151
19155
  const actionLabels = [
19152
19156
  stringValue2(target.label),
19153
19157
  stringValue2(target.name),
19154
- stringValue2(target.text)
19158
+ stringValue2(target.text),
19159
+ stringValue2(target.table_label),
19160
+ stringValue2(target.column_label),
19161
+ stringValue2(action.table)
19155
19162
  ].filter(Boolean);
19156
19163
  return actionFields.includes(field) || actionLabels.includes(label);
19157
19164
  }
@@ -19357,7 +19364,7 @@ function formContractIssues(rawStep, stepKey, required) {
19357
19364
  const hasWrite = actions.some((action) => isRecord8(action) && allowedWrites.has(stringValue2(action.type)) && actionTargetMatchesField(action, field, label));
19358
19365
  const hasAssertion = checks.some((check) => isRecord8(check) && stringValue2(check.type) === "form.assert_value" && actionTargetMatchesField(check, field, label)) || // Upload execution validates selected file metadata and server response;
19359
19366
  // a text-value assertion cannot represent a browser File object.
19360
- controlType === "bp-upload" && actions.some((action) => isRecord8(action) && stringValue2(action.type) === "form.upload_file" && actionTargetMatchesField(action, field, label));
19367
+ controlType === "bp-upload" && actions.some((action) => isRecord8(action) && stringValue2(action.type) === "form.upload_file" && actionTargetMatchesField(action, field, label)) || controlType === "sub_form" && checks.some((check) => isRecord8(check) && stringValue2(check.type) === "detail.assert_rows" && [field, label].includes(stringValue2(check.table)) && Number(check.count) > 0);
19361
19368
  if (!hasWrite || !hasAssertion) {
19362
19369
  issues.push({
19363
19370
  rule_id: "test_suite.automation.required_field_uncovered",
@@ -19611,11 +19618,40 @@ function actionIssues(action, stepKey, index, check, resolutionOutcome) {
19611
19618
  message: `${stepKey} action[${index}] form.assert_value match must be exact, contains, or non_empty`
19612
19619
  });
19613
19620
  }
19614
- if (["detail.add_row", "detail.set_value", "detail.assert_rows"].includes(type) && !stringValue2(action.table)) {
19621
+ if (type === "form.assert_value" && action.count !== void 0 && (!Number.isInteger(action.count) || Number(action.count) < 0)) {
19622
+ issues.push({
19623
+ rule_id: "test_suite.automation.form_value_count_invalid",
19624
+ step_key: stepKey,
19625
+ message: `${stepKey} action[${index}] form.assert_value count must be a non-negative integer`
19626
+ });
19627
+ }
19628
+ if (type === "form.assert_value" && action.tag_name !== void 0 && !["input", "textarea", "select"].includes(stringValue2(action.tag_name))) {
19629
+ issues.push({
19630
+ rule_id: "test_suite.automation.form_value_tag_invalid",
19631
+ step_key: stepKey,
19632
+ message: `${stepKey} action[${index}] form.assert_value tag_name must be input, textarea, or select`
19633
+ });
19634
+ }
19635
+ if (type === "form.assert_value" && action.input_type !== void 0 && !stringValue2(action.input_type)) {
19636
+ issues.push({
19637
+ rule_id: "test_suite.automation.form_value_input_type_invalid",
19638
+ step_key: stepKey,
19639
+ message: `${stepKey} action[${index}] form.assert_value input_type must be a non-empty string`
19640
+ });
19641
+ }
19642
+ if (type === "form.assert_value" && action.disabled !== void 0 && typeof action.disabled !== "boolean") {
19643
+ issues.push({
19644
+ rule_id: "test_suite.automation.form_value_disabled_invalid",
19645
+ step_key: stepKey,
19646
+ message: `${stepKey} action[${index}] form.assert_value disabled must be boolean`
19647
+ });
19648
+ }
19649
+ const semanticDetailTarget = isRecord8(action.target) && Boolean(stringValue2(action.target.table_label)) && Boolean(stringValue2(action.target.column_label));
19650
+ if (["detail.add_row", "detail.assert_rows"].includes(type) && !stringValue2(action.table)) {
19615
19651
  issues.push({ rule_id: "test_suite.automation.target_missing", step_key: stepKey, message: `${stepKey} action[${index}] requires table` });
19616
19652
  }
19617
- if (type === "detail.set_value" && (!stringValue2(action.field) || !Number.isInteger(action.row) || Number(action.row) < 0)) {
19618
- issues.push({ rule_id: "test_suite.automation.detail_target_invalid", step_key: stepKey, message: `${stepKey} action[${index}] requires field and a zero-based row` });
19653
+ if (type === "detail.set_value" && !semanticDetailTarget && (!stringValue2(action.table) || !stringValue2(action.field) || !Number.isInteger(action.row) || Number(action.row) < 0)) {
19654
+ issues.push({ rule_id: "test_suite.automation.detail_target_invalid", step_key: stepKey, message: `${stepKey} action[${index}] requires a semantic table/column target or table, field, and a zero-based row` });
19619
19655
  }
19620
19656
  if (type === "navigation.open" && !stringValue2(action.route)) {
19621
19657
  issues.push({ rule_id: "test_suite.automation.route_missing", step_key: stepKey, message: `${stepKey} action[${index}] requires route` });
@@ -19638,6 +19674,21 @@ function actionIssues(action, stepKey, index, check, resolutionOutcome) {
19638
19674
  if (type === "list.assert_record" && !stringValue2(action.text) && !stringValue2(action.value)) {
19639
19675
  issues.push({ rule_id: "test_suite.automation.expected_check_invalid", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_record requires text or value` });
19640
19676
  }
19677
+ if (type === "list.assert_cell") {
19678
+ const listCellTarget = isRecord8(action.target) ? action.target : {};
19679
+ if (!stringValue2(action.source)) {
19680
+ issues.push({ rule_id: "test_suite.automation.list_cell_anchor_missing", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_cell requires source with the unique row anchor` });
19681
+ }
19682
+ if (!stringValue2(listCellTarget.column_label)) {
19683
+ issues.push({ rule_id: "test_suite.automation.list_cell_column_missing", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_cell requires target.column_label` });
19684
+ }
19685
+ if (action.value === void 0) {
19686
+ issues.push({ rule_id: "test_suite.automation.list_cell_value_missing", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_cell requires value; use an empty string to assert an empty cell` });
19687
+ }
19688
+ if (action.match !== void 0 && !["exact", "contains", "non_empty"].includes(stringValue2(action.match))) {
19689
+ issues.push({ rule_id: "test_suite.automation.value_match_invalid", step_key: stepKey, message: `${stepKey} action[${index}] list.assert_cell match must be exact, contains, or non_empty` });
19690
+ }
19691
+ }
19641
19692
  if (type === "message.open") {
19642
19693
  if (action.collateral_mutation !== "message.read") {
19643
19694
  issues.push({
@@ -20007,7 +20058,7 @@ function validateBrowserAutomationDataProfile(step, data, stepKey) {
20007
20058
 
20008
20059
  // src/core/e2e-browser-runner.ts
20009
20060
  import { createHash as createHash10 } from "crypto";
20010
- import { lstat as lstat3, mkdir as mkdir11, readFile as readFile15, realpath as realpath5, rename as rename3, stat as stat10, writeFile as writeFile11 } from "fs/promises";
20061
+ import { chmod as chmod2, lstat as lstat3, mkdir as mkdir11, readFile as readFile15, realpath as realpath5, rename as rename3, stat as stat10, writeFile as writeFile11 } from "fs/promises";
20011
20062
  import path16 from "path";
20012
20063
  import {
20013
20064
  chromium
@@ -20447,7 +20498,7 @@ function identityStepOperation(step) {
20447
20498
  if (/(mock|模拟用户|(?:确保|切换).{0,8}(?:身份|用户))/i.test(text5)) return "mock";
20448
20499
  return null;
20449
20500
  }
20450
- var BROWSER_TOOL_RE = /(Chrome Control|chrome:control-chrome|Chrome DevTools|DevTools|Playwright|AppleScript|app_in_browser|App in Browser)/i;
20501
+ var BROWSER_TOOL_RE = /(Chrome plugin|Chrome Control|chrome:control-chrome|Chrome DevTools|DevTools|Playwright|AppleScript|app_in_browser|App in Browser)/i;
20451
20502
  var REPORT_EVIDENCE_PLACEHOLDER_RE = /^(?:n\/?a|none|null|todo|tbd|xxx|unknown|pending|待补|暂无|无|未执行|跳过|-+)$/i;
20452
20503
  var LIVE_DRAFT_RE = /(live|draft|已发布|草稿|发布态|live_draft=)/i;
20453
20504
  var MULTI_ROLE_VALUE_RE = /[,、/]\s*[^,、/\s]+|多角色|跨角色/;
@@ -20476,6 +20527,19 @@ var TestSuiteError = class extends Error {
20476
20527
  this.suggestion = options.suggestion;
20477
20528
  }
20478
20529
  };
20530
+ var IDENTITY_PHASE_CONTRACT_FIELDS = [
20531
+ "identity_id",
20532
+ "case_id",
20533
+ "phase",
20534
+ "actor",
20535
+ "required_exact_id",
20536
+ "required_exact_name",
20537
+ "authorization_rule",
20538
+ "binding_source",
20539
+ "status",
20540
+ "pre_action_readback",
20541
+ "cleanup_policy"
20542
+ ];
20479
20543
  function runtimeRoute(runtimeUrl) {
20480
20544
  const url = new URL(runtimeUrl);
20481
20545
  const hashRoute = url.hash.startsWith("#/") ? new URL(url.hash.slice(1), url.origin) : null;
@@ -20677,6 +20741,93 @@ async function readCaseSteps(filePath) {
20677
20741
  return row;
20678
20742
  });
20679
20743
  }
20744
+ function identityContractIncludesCase(expression, caseId) {
20745
+ return expression.split("|").map((value) => value.trim()).filter(Boolean).some((token) => {
20746
+ if (token === caseId) return true;
20747
+ const range = token.match(/^([A-Za-z_-]*?)(\d+)-([A-Za-z_-]*?)(\d+)$/);
20748
+ const candidate = caseId.match(/^([A-Za-z_-]*?)(\d+)$/);
20749
+ if (!range || !candidate) return false;
20750
+ const startPrefix = range[1];
20751
+ const endPrefix = range[3] || startPrefix;
20752
+ return candidate[1] === startPrefix && startPrefix === endPrefix && Number(candidate[2]) >= Number(range[2]) && Number(candidate[2]) <= Number(range[4]);
20753
+ });
20754
+ }
20755
+ async function readIdentityPhaseContracts(scenarioDir) {
20756
+ const filePath = path15.join(scenarioDir, "contracts", "identity-phase-contracts.csv");
20757
+ if (!await exists3(filePath)) return [];
20758
+ const text5 = (await readText(filePath)).replace(/^\uFEFF/, "");
20759
+ const lines = text5.split(/\r?\n/).filter((line) => line.length > 0);
20760
+ const fields = lines.length ? splitCsvLine(lines[0]) : [];
20761
+ if (JSON.stringify(fields) !== JSON.stringify(IDENTITY_PHASE_CONTRACT_FIELDS)) {
20762
+ fail(`${filePath}: CSV fields must be exactly ${JSON.stringify(IDENTITY_PHASE_CONTRACT_FIELDS)}`, {
20763
+ rule_id: "test_suite.identity_phase.header",
20764
+ path: filePath
20765
+ });
20766
+ }
20767
+ return lines.slice(1).map((line) => {
20768
+ const values = splitCsvLine(line);
20769
+ const row = {};
20770
+ IDENTITY_PHASE_CONTRACT_FIELDS.forEach((field, index) => {
20771
+ row[field] = values[index] ?? "";
20772
+ });
20773
+ return row;
20774
+ });
20775
+ }
20776
+ async function validateIdentityPhaseContracts(scenarioDir, stepsByCase, selectedCaseIds) {
20777
+ const contracts = await readIdentityPhaseContracts(scenarioDir);
20778
+ if (contracts.length === 0) return;
20779
+ const contractPath = path15.join(scenarioDir, "contracts", "identity-phase-contracts.csv");
20780
+ for (const contract of contracts) {
20781
+ const exactUserId = Number(contract.required_exact_id);
20782
+ if (contract.status !== "exact_identity_verified" || !Number.isSafeInteger(exactUserId) || exactUserId <= 0) continue;
20783
+ for (const [caseId, caseSteps] of stepsByCase) {
20784
+ if (selectedCaseIds && !selectedCaseIds.has(caseId)) continue;
20785
+ if (!identityContractIncludesCase(contract.case_id, caseId)) continue;
20786
+ const ordered = [...caseSteps].sort((left, right) => Number(left.step_no) - Number(right.step_no));
20787
+ const businessSteps = ordered.filter((step) => step.actor === contract.actor && step.runner !== "identity");
20788
+ if (businessSteps.length === 0) continue;
20789
+ const firstBusinessStepNo = Number(businessSteps[0].step_no);
20790
+ const lastBusinessStepNo = Number(businessSteps.at(-1).step_no);
20791
+ const mockSteps = ordered.filter((step) => step.runner === "identity" && identityStepOperation(step) === "mock" && step.actor === contract.actor && Number(step.step_no) < firstBusinessStepNo);
20792
+ if (mockSteps.length !== 1) {
20793
+ fail(`${contractPath}:${contract.identity_id}:${caseId}: actor=${contract.actor} \u7684\u9996\u4E2A\u4E1A\u52A1\u6B65\u9AA4\u524D\u5FC5\u987B\u6709\u4E14\u53EA\u6709\u4E00\u4E2A\u5DF2\u5BA1\u6838 runner=identity mock \u6B65\u9AA4`, {
20794
+ rule_id: "test_suite.identity_phase.mock_missing",
20795
+ path: contractPath,
20796
+ suggestion: `Add a phase_bound identity step before ${caseId}/${businessSteps[0].step_id} with user_id=${exactUserId}; actor alone never switches the Playwright session.`
20797
+ });
20798
+ }
20799
+ const declaredUserId = mockSteps[0].input_data.match(/(?:user_id|用户ID|用户 id)\s*[=::]\s*(\d+)/i)?.[1];
20800
+ if (Number(declaredUserId) !== exactUserId) {
20801
+ fail(`${contractPath}:${contract.identity_id}:${caseId}: identity mock user_id \u5FC5\u987B\u4E0E required_exact_id=${exactUserId} \u5B8C\u5168\u4E00\u81F4`, {
20802
+ rule_id: "test_suite.identity_phase.mock_target_mismatch",
20803
+ path: contractPath
20804
+ });
20805
+ }
20806
+ if (/unmock|restore|恢复/i.test(contract.cleanup_policy)) {
20807
+ const unmockSteps = ordered.filter((step) => step.runner === "identity" && identityStepOperation(step) === "unmock" && Number(step.step_no) > lastBusinessStepNo);
20808
+ if (unmockSteps.length !== 1) {
20809
+ fail(`${contractPath}:${contract.identity_id}:${caseId}: cleanup_policy=${contract.cleanup_policy} \u8981\u6C42\u4E1A\u52A1\u9636\u6BB5\u540E\u6709\u4E14\u53EA\u6709\u4E00\u4E2A runner=identity unmock \u6B65\u9AA4`, {
20810
+ rule_id: "test_suite.identity_phase.unmock_missing",
20811
+ path: contractPath,
20812
+ suggestion: `Add a phase_bound unmock step after ${caseId}/${businessSteps.at(-1).step_id}.`
20813
+ });
20814
+ }
20815
+ }
20816
+ }
20817
+ }
20818
+ }
20819
+ async function validateExecutionManifestIdentityContracts(manifest) {
20820
+ const stepsByCase = /* @__PURE__ */ new Map();
20821
+ for (const step of manifest.steps) {
20822
+ const values = stepsByCase.get(step.case_id) ?? [];
20823
+ values.push(step);
20824
+ stepsByCase.set(step.case_id, values);
20825
+ }
20826
+ const selectedCaseIds = new Set(
20827
+ manifest.selected_case_ids?.length ? manifest.selected_case_ids : [manifest.case_id]
20828
+ );
20829
+ await validateIdentityPhaseContracts(manifest.source_suite, stepsByCase, selectedCaseIds);
20830
+ }
20680
20831
  async function writeAtomicText(filePath, content) {
20681
20832
  const resolved = path15.resolve(filePath);
20682
20833
  const tempPath = `${resolved}.tmp-${process.pid}-${Date.now()}`;
@@ -21204,7 +21355,7 @@ function validatePreflightEvidence(filePath, caseId, row, steps, prepTokens) {
21204
21355
  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" });
21205
21356
  }
21206
21357
  if (!prepTokens.browser_tool || !BROWSER_TOOL_RE.test(prepTokens.browser_tool)) {
21207
- 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" });
21358
+ fail(`${filePath}:${caseId}: E2E \u7528\u4F8B\u5FC5\u987B\u58F0\u660E\u6D4F\u89C8\u5668\u5DE5\u5177\u8BC1\u636E\uFF1BV2 \u5F55\u5236\u4F7F\u7528 \`browser_tool=Chrome plugin\`\uFF0C\u7A33\u5B9A\u590D\u8DD1\u4F7F\u7528 Playwright`, { rule_id: "test_suite.case.browser_tool" });
21208
21359
  }
21209
21360
  if (!prepTokens.live_draft || !LIVE_DRAFT_RE.test(prepTokens.live_draft)) {
21210
21361
  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" });
@@ -21587,6 +21738,7 @@ async function validateScenario(scenarioDir) {
21587
21738
  const caseStepsPath = path15.join(scenarioDir, "case_steps.csv");
21588
21739
  const caseSteps = await readCaseSteps(caseStepsPath);
21589
21740
  const stepsByCase = validateCaseSteps(caseStepsPath, rows2, caseSteps);
21741
+ await validateIdentityPhaseContracts(scenarioDir, stepsByCase);
21590
21742
  await validateScenarioAutomation(scenarioDir, caseSteps);
21591
21743
  if (rows2.length === 0) fail(`${casesPath}: at least one case is required`);
21592
21744
  const seen = /* @__PURE__ */ new Set();
@@ -23215,12 +23367,8 @@ async function assertExecutionManifestFresh(manifest, manifestPath) {
23215
23367
  path: manifestPath
23216
23368
  });
23217
23369
  }
23218
- if (stale?.rule_id === "test_suite.run.skill_content_stale") {
23219
- fail("execution manifest is stale because its E2E Skill bundle changed after run start", {
23220
- rule_id: stale.rule_id,
23221
- path: stale.path,
23222
- suggestion: "Do not continue this manifest with changed Agent instructions. Start a new run after reviewing and syncing the Skill bundle."
23223
- });
23370
+ if (manifest.result === "running" || manifest.mutation_attempt_guard) {
23371
+ await validateExecutionManifestIdentityContracts(manifest);
23224
23372
  }
23225
23373
  if (manifest.mutation_attempt_guard && !manifest.active_run_lease) {
23226
23374
  fail("execution manifest has an unresolved mutation attempt without its active-run lease", {
@@ -23258,20 +23406,27 @@ async function executionManifestStaleReason(manifest) {
23258
23406
  if (currentHash !== manifest.suite_hash) {
23259
23407
  return { rule_id: "test_suite.run.suite_stale", path: manifest.source_suite };
23260
23408
  }
23261
- if (manifest.skill_sources?.length && manifest.skill_bundle_sha256) {
23262
- for (const source of manifest.skill_sources) {
23263
- let currentSkillHash = "";
23264
- try {
23265
- currentSkillHash = await skillBundleSha256(source);
23266
- } catch {
23267
- currentSkillHash = "";
23268
- }
23269
- if (currentSkillHash !== manifest.skill_bundle_sha256) {
23270
- return { rule_id: "test_suite.run.skill_content_stale", path: source };
23271
- }
23409
+ return null;
23410
+ }
23411
+ async function executionManifestSkillWarnings(manifest) {
23412
+ if (!manifest.skill_sources?.length || !manifest.skill_bundle_sha256) return [];
23413
+ const warnings = [];
23414
+ for (const source of manifest.skill_sources) {
23415
+ let currentSkillHash = "";
23416
+ try {
23417
+ currentSkillHash = await skillBundleSha256(source);
23418
+ } catch {
23419
+ currentSkillHash = "";
23420
+ }
23421
+ if (currentSkillHash !== manifest.skill_bundle_sha256) {
23422
+ warnings.push({
23423
+ rule_id: "test_suite.run.skill_content_changed",
23424
+ path: source,
23425
+ message: "E2E Skill content changed after run start; the pinned suite, automation and runner contract remain authoritative for this run."
23426
+ });
23272
23427
  }
23273
23428
  }
23274
- return null;
23429
+ return warnings;
23275
23430
  }
23276
23431
  async function evidenceContainsDiagnostic(evidencePath) {
23277
23432
  const info = await stat9(evidencePath);
@@ -24336,6 +24491,7 @@ async function startTestSuiteRunUnlocked(options) {
24336
24491
  if (missingCaseId) fail(`${scenarioDir}: active case not found: ${missingCaseId}`, { rule_id: "test_suite.run.case_not_found" });
24337
24492
  const allSteps = await readCaseSteps(path15.join(scenarioDir, "case_steps.csv"));
24338
24493
  const grouped = validateCaseSteps(path15.join(scenarioDir, "case_steps.csv"), rows2, allSteps);
24494
+ await validateIdentityPhaseContracts(scenarioDir, grouped, new Set(selectedCaseIds));
24339
24495
  const selectedSteps = selectedCaseIds.flatMap((caseId) => grouped.get(caseId) ?? []);
24340
24496
  const selectedSeen = /* @__PURE__ */ new Set();
24341
24497
  for (const row of selectedRows) await validateCase(path15.join(scenarioDir, "cases.csv"), row, grouped.get(row.case_id) ?? [], selectedSeen);
@@ -25028,7 +25184,8 @@ async function testSuiteRunStatus(manifestPath, profile) {
25028
25184
  const manifest = await readExecutionManifest(manifestPath);
25029
25185
  await assertExecutionManifestFresh(manifest, path15.resolve(manifestPath));
25030
25186
  if (profile && manifest.profile !== profile) fail(`execution manifest profile is ${manifest.profile}, not ${profile}`, { rule_id: "test_suite.run.profile_mismatch", path: manifestPath });
25031
- return { ok: true, execution: manifest };
25187
+ const warnings = await executionManifestSkillWarnings(manifest);
25188
+ return { ok: true, execution: manifest, ...warnings.length > 0 ? { warnings } : {} };
25032
25189
  }
25033
25190
  async function indexSuite(root = DEFAULT_SUITE_ROOT, includeInactive = false, options = {}) {
25034
25191
  const items = await lintSuite(root, options);
@@ -26593,6 +26750,26 @@ function browserFormValueMatches(actual, expected, match = "exact") {
26593
26750
  const expectedText = expected !== null && typeof expected === "object" ? comparableBrowserFormValue(expected) : String(expected ?? "");
26594
26751
  return match === "contains" ? actualText.includes(expectedText) : actualText === expectedText;
26595
26752
  }
26753
+ async function waitForBrowserAssertion(options) {
26754
+ const deadline = Date.now() + options.timeout;
26755
+ const interval = Math.max(10, options.interval ?? 100);
26756
+ const sleep = options.sleep ?? ((milliseconds) => new Promise((resolve) => {
26757
+ setTimeout(resolve, milliseconds);
26758
+ }));
26759
+ let lastError = "browser assertion did not pass";
26760
+ do {
26761
+ try {
26762
+ const result = await options.evaluate();
26763
+ if (result.passed) return result.value;
26764
+ lastError = result.error;
26765
+ } catch (error) {
26766
+ lastError = error instanceof Error ? error.message : String(error);
26767
+ }
26768
+ if (Date.now() >= deadline) break;
26769
+ await sleep(Math.min(interval, Math.max(0, deadline - Date.now())));
26770
+ } while (Date.now() <= deadline);
26771
+ throw new Error(lastError);
26772
+ }
26596
26773
  function browserListRecordCountMatches(actualCount, expectedCount) {
26597
26774
  return expectedCount === void 0 ? actualCount > 0 : actualCount === expectedCount;
26598
26775
  }
@@ -26746,6 +26923,12 @@ function browserNetworkResponseAfterCursor(responses, urlPattern, cursor) {
26746
26923
  function browserActionNetworkCursor(actionType, currentActionCursor, previousActionCursor) {
26747
26924
  return actionType === "form.upload_file" ? currentActionCursor : previousActionCursor;
26748
26925
  }
26926
+ function browserExpectedCheckPhase(check, hasMutationAction) {
26927
+ if (hasMutationAction && ["form.assert_value", "detail.assert_rows"].includes(check.type)) {
26928
+ return "pre_mutation";
26929
+ }
26930
+ return "post_action";
26931
+ }
26749
26932
  function browserMutationUrlPatterns(action) {
26750
26933
  const patterns = [String(action.url_pattern ?? "").trim()];
26751
26934
  if (action.collateral_mutation === "project.share") {
@@ -26963,6 +27146,17 @@ async function locatorForTarget(page, target) {
26963
27146
  }
26964
27147
  throw new Error("browser action target is empty");
26965
27148
  }
27149
+ async function detailValueLocator(page, action) {
27150
+ if (action.target?.table_label && action.target.column_label) {
27151
+ return editableLocator(await locatorForTarget(page, action.target));
27152
+ }
27153
+ const table = await tableLocator(page, String(action.table));
27154
+ const row = table.locator(".el-table__body tr, tbody tr").nth(Number(action.row));
27155
+ const field = String(action.field);
27156
+ const escaped = field.replace(/["\\]/g, "\\$&");
27157
+ const target = row.locator(`[data-field-key="${escaped}"], [field="${escaped}"], [name="${escaped}"]`).first();
27158
+ return editableLocator(target);
27159
+ }
26966
27160
  async function editableLocator(locator) {
26967
27161
  const tagName = await locator.evaluate((element) => element.tagName.toLowerCase()).catch(() => "");
26968
27162
  if (["input", "textarea", "select"].includes(tagName)) return locator;
@@ -26979,6 +27173,23 @@ async function editableLocator(locator) {
26979
27173
  const groupedEditable = semanticGroup.locator("input:not([type=hidden]), textarea, [contenteditable=true], select");
26980
27174
  return await groupedEditable.count() ? groupedEditable.first() : locator;
26981
27175
  }
27176
+ async function setBrowserEditableValue(locator, value) {
27177
+ const text5 = String(value ?? "");
27178
+ const control = await locator.evaluate((element) => ({
27179
+ inputNumber: Boolean(element.closest(".el-input-number")),
27180
+ dateEditor: Boolean(element.closest(".el-date-editor"))
27181
+ })).catch(() => ({ inputNumber: false, dateEditor: false }));
27182
+ if (control.inputNumber) {
27183
+ await locator.click();
27184
+ await locator.press("ArrowUp");
27185
+ await locator.press("ControlOrMeta+A");
27186
+ await locator.type(text5);
27187
+ await locator.press("Tab");
27188
+ return;
27189
+ }
27190
+ await locator.fill(text5);
27191
+ if (control.dateEditor) await locator.press("Tab");
27192
+ }
26982
27193
  function targetLocatorByIndex(locator, target) {
26983
27194
  return Number.isInteger(target?.nth) ? locator.nth(Number(target?.nth)) : locator.first();
26984
27195
  }
@@ -27181,18 +27392,60 @@ async function readBrowserFormValue(page, target) {
27181
27392
  const locator = await editableLocator(semanticTarget);
27182
27393
  return locator.inputValue().catch(() => locator.textContent());
27183
27394
  }
27184
- async function selectBrowserUser(page, target, userName, timeout) {
27185
- const opener = await visibleTargetLocator(page, target);
27186
- await opener.click({ timeout });
27187
- const option = await firstVisibleLocator(page.getByText(userName, { exact: true }), timeout);
27188
- if (!option) throw new Error(`user picker option not visible: ${userName}`);
27189
- await option.click({ timeout });
27395
+ async function readBrowserFormControlMetadata(page, target) {
27396
+ const semanticTarget = await visibleTargetLocator(page, target);
27397
+ const locator = await editableLocator(semanticTarget);
27398
+ return {
27399
+ tag_name: String(await locator.evaluate((element) => element.tagName.toLowerCase())).trim(),
27400
+ input_type: String(await locator.getAttribute("type") ?? "").trim().toLowerCase(),
27401
+ disabled: await locator.isDisabled().catch(() => false)
27402
+ };
27403
+ }
27404
+ function browserFormControlMetadataMatches(metadata, action) {
27405
+ if (action.tag_name !== void 0 && metadata.tag_name !== action.tag_name) return false;
27406
+ if (action.input_type !== void 0 && metadata.input_type !== String(action.input_type).toLowerCase()) return false;
27407
+ if (action.disabled !== void 0 && metadata.disabled !== action.disabled) return false;
27408
+ return true;
27409
+ }
27410
+ async function selectBrowserUser(page, target, userName, expectedUserId, timeout) {
27411
+ const semanticTarget = await visibleTargetLocator(page, target);
27412
+ const formItem = nearestFormItem(semanticTarget);
27413
+ const pickerButton = await firstVisibleLocator(
27414
+ formItem.getByRole("button", { name: /添加|编辑|选择/ }),
27415
+ Math.min(timeout, 1e3)
27416
+ );
27417
+ await (pickerButton ?? semanticTarget).click({ timeout });
27190
27418
  const picker = await lastVisibleLocator(page.getByRole("dialog"), timeout);
27191
27419
  if (!picker) throw new Error("user picker dialog not visible");
27420
+ const search = picker.getByPlaceholder(/姓名|手机号|拼音|工号/).first();
27421
+ if (await search.isVisible().catch(() => false)) {
27422
+ await search.fill(userName);
27423
+ }
27424
+ if (expectedUserId) {
27425
+ const candidateRows = picker.locator(".checkbox-item-list").filter({ hasText: userName });
27426
+ const exactCandidates = [];
27427
+ const candidateCount = await candidateRows.count();
27428
+ for (let index = 0; index < candidateCount; index += 1) {
27429
+ const candidate = candidateRows.nth(index);
27430
+ const name = String(await candidate.locator(".item-user-name").textContent().catch(() => "") ?? "").trim();
27431
+ const userId = String(await candidate.locator(".item-user-id").textContent().catch(() => "") ?? "").trim();
27432
+ if (name === userName && userId === expectedUserId && await candidate.isVisible().catch(() => false)) {
27433
+ exactCandidates.push(candidate);
27434
+ }
27435
+ }
27436
+ if (exactCandidates.length !== 1) {
27437
+ throw new Error(`user picker exact candidate mismatch for ${userName}/${expectedUserId}: expected 1, got ${exactCandidates.length}`);
27438
+ }
27439
+ await exactCandidates[0].click({ timeout });
27440
+ } else {
27441
+ const option = await firstVisibleLocator(picker.getByText(userName, { exact: true }), timeout);
27442
+ if (!option) throw new Error(`user picker option not visible: ${userName}`);
27443
+ await option.click({ timeout });
27444
+ }
27192
27445
  const confirm3 = picker.getByRole("button", { name: /确认|确定/ }).first();
27193
27446
  await confirm3.waitFor({ state: "visible", timeout });
27194
27447
  await confirm3.click({ timeout });
27195
- const selected = await firstVisibleLocator(page.getByText(userName, { exact: true }), timeout);
27448
+ const selected = await firstVisibleLocator(formItem.getByText(userName, { exact: true }), timeout);
27196
27449
  if (!selected) throw new Error(`selected user readback not visible: ${userName}`);
27197
27450
  }
27198
27451
  function browserDateRangeValues(value) {
@@ -27341,7 +27594,7 @@ async function executeAction(page, action, variables, runtime) {
27341
27594
  case "form.set_value": {
27342
27595
  const target = next.target ?? { field: next.field };
27343
27596
  const locator = await editableLocator(await visibleTargetLocator(page, target));
27344
- await locator.fill(String(next.value ?? ""));
27597
+ await setBrowserEditableValue(locator, next.value);
27345
27598
  return {};
27346
27599
  }
27347
27600
  case "form.set_date_range": {
@@ -27371,6 +27624,7 @@ async function executeAction(page, action, variables, runtime) {
27371
27624
  page,
27372
27625
  next.target ?? { field: next.field },
27373
27626
  String(next.option ?? next.value ?? ""),
27627
+ next.source ? String(next.source) : void 0,
27374
27628
  timeout
27375
27629
  );
27376
27630
  return {};
@@ -27445,19 +27699,61 @@ async function executeAction(page, action, variables, runtime) {
27445
27699
  }
27446
27700
  case "form.assert_value": {
27447
27701
  const target = next.target ?? { field: next.field };
27448
- const actual = await readBrowserFormValue(page, target);
27449
- const match = next.match ?? "exact";
27450
- const passed = browserFormValueMatches(actual, next.value, match);
27451
- if (!passed) throw new Error(`form value mismatch (${match}): expected ${String(next.value ?? "")}, got ${String(actual ?? "")}`);
27452
- return {
27453
- assertion: {
27454
- type: next.type,
27455
- passed,
27456
- match,
27457
- target,
27458
- actual: match === "non_empty" ? "non_empty" : actual
27702
+ if (next.count !== void 0) {
27703
+ return waitForBrowserAssertion({
27704
+ timeout,
27705
+ evaluate: async () => {
27706
+ const locator = await locatorForTarget(page, target);
27707
+ const matchingValues = [];
27708
+ const locatorCount = await locator.count();
27709
+ for (let index = 0; index < locatorCount; index += 1) {
27710
+ const candidate = locator.nth(index);
27711
+ if (!await candidate.isVisible().catch(() => false)) continue;
27712
+ const actual = await readBrowserFormValue(page, { ...target, nth: index });
27713
+ const metadata = await readBrowserFormControlMetadata(page, { ...target, nth: index });
27714
+ if (browserFormValueMatches(actual, next.value, next.match ?? "exact") && browserFormControlMetadataMatches(metadata, next)) matchingValues.push(actual);
27715
+ }
27716
+ const passed = matchingValues.length === Number(next.count);
27717
+ return {
27718
+ passed,
27719
+ error: `form value count mismatch: expected ${next.count}, got ${matchingValues.length}`,
27720
+ value: {
27721
+ assertion: {
27722
+ type: next.type,
27723
+ passed,
27724
+ match: next.match ?? "exact",
27725
+ target,
27726
+ count: matchingValues.length,
27727
+ expected_count: next.count
27728
+ }
27729
+ }
27730
+ };
27731
+ }
27732
+ });
27733
+ }
27734
+ return waitForBrowserAssertion({
27735
+ timeout,
27736
+ evaluate: async () => {
27737
+ const actual = await readBrowserFormValue(page, target);
27738
+ const metadata = await readBrowserFormControlMetadata(page, target);
27739
+ const match = next.match ?? "exact";
27740
+ const passed = browserFormValueMatches(actual, next.value, match) && browserFormControlMetadataMatches(metadata, next);
27741
+ return {
27742
+ passed,
27743
+ error: `form value/control mismatch (${match}): expected ${String(next.value ?? "")}, got ${String(actual ?? "")}/${JSON.stringify(metadata)}`,
27744
+ value: {
27745
+ assertion: {
27746
+ type: next.type,
27747
+ passed,
27748
+ match,
27749
+ target,
27750
+ actual: match === "non_empty" ? "non_empty" : actual,
27751
+ ...metadata
27752
+ }
27753
+ }
27754
+ };
27459
27755
  }
27460
- };
27756
+ });
27461
27757
  }
27462
27758
  case "detail.add_row": {
27463
27759
  const table = await tableLocator(page, String(next.table));
@@ -27465,12 +27761,7 @@ async function executeAction(page, action, variables, runtime) {
27465
27761
  return {};
27466
27762
  }
27467
27763
  case "detail.set_value": {
27468
- const table = await tableLocator(page, String(next.table));
27469
- const row = table.locator(".el-table__body tr, tbody tr").nth(Number(next.row));
27470
- const field = String(next.field);
27471
- const escaped = field.replace(/["\\]/g, "\\$&");
27472
- const target = row.locator(`[data-field-key="${escaped}"], [field="${escaped}"], [name="${escaped}"]`).first();
27473
- await (await editableLocator(target)).fill(String(next.value ?? ""));
27764
+ await setBrowserEditableValue(await detailValueLocator(page, next), next.value);
27474
27765
  return {};
27475
27766
  }
27476
27767
  case "detail.assert_rows": {
@@ -27595,6 +27886,29 @@ async function executeAction(page, action, variables, runtime) {
27595
27886
  }
27596
27887
  return { assertion: { type: next.type, passed, expected, count: visibleCount, expected_count: expectedCount } };
27597
27888
  }
27889
+ case "list.assert_cell": {
27890
+ const rowAnchor = String(next.source ?? "");
27891
+ const columnLabel = String(next.target?.column_label ?? "");
27892
+ const headerCells = page.locator(".el-table__header-wrapper").first().locator("th .cell");
27893
+ const headerTexts = (await headerCells.allTextContents()).map((value) => value.replace(/\s+/g, " ").trim());
27894
+ const columnIndex = headerTexts.findIndex((value) => value === columnLabel || value.includes(columnLabel));
27895
+ if (columnIndex < 0) throw new Error(`list column not found: ${columnLabel}`);
27896
+ const rows2 = page.locator(".el-table__body-wrapper").first().locator("tbody tr").filter({ hasText: rowAnchor });
27897
+ const visibleRows = [];
27898
+ const rowCount = await rows2.count();
27899
+ for (let index = 0; index < rowCount; index += 1) {
27900
+ const row = rows2.nth(index);
27901
+ if (await row.isVisible().catch(() => false)) visibleRows.push(row);
27902
+ }
27903
+ if (visibleRows.length !== 1) {
27904
+ throw new Error(`list row anchor mismatch for ${rowAnchor}: expected 1, got ${visibleRows.length}`);
27905
+ }
27906
+ const actual = String(await visibleRows[0].locator("td").nth(columnIndex).innerText().catch(() => "")).replace(/\s+/g, " ").trim();
27907
+ const match = next.match ?? "exact";
27908
+ const passed = browserFormValueMatches(actual, next.value, match);
27909
+ if (!passed) throw new Error(`list cell mismatch for ${rowAnchor}/${columnLabel} (${match}): expected ${String(next.value ?? "")}, got ${actual}`);
27910
+ return { assertion: { type: next.type, passed, row_anchor: rowAnchor, column: columnLabel, match, actual } };
27911
+ }
27598
27912
  case "message.open": {
27599
27913
  const listUrlPattern = String(next.list_url_pattern ?? "");
27600
27914
  const readUrlPattern = String(next.url_pattern ?? "");
@@ -27709,6 +28023,7 @@ async function waitForInteractiveLogin(context2, options) {
27709
28023
  workspace,
27710
28024
  preferredRoute: targetRoute,
27711
28025
  fingerprint: options.fingerprint,
28026
+ fingerprintPolicy: "preferred",
27712
28027
  requireExistingCandidate: false,
27713
28028
  keepProbePage: true
27714
28029
  }).catch(() => void 0);
@@ -27731,12 +28046,21 @@ async function openInteractiveLoginSession(options) {
27731
28046
  });
27732
28047
  try {
27733
28048
  await waitForInteractiveLogin(context2, options);
28049
+ await persistInteractiveLoginStorageState(context2, options.storageState);
27734
28050
  return { context: context2, owned: true };
27735
28051
  } catch (error) {
27736
28052
  await context2.close().catch(() => void 0);
27737
28053
  throw error;
27738
28054
  }
27739
28055
  }
28056
+ async function persistInteractiveLoginStorageState(context2, storageStatePath) {
28057
+ if (!storageStatePath) return void 0;
28058
+ const target = path16.resolve(storageStatePath);
28059
+ const state = await context2.storageState();
28060
+ await writeAtomicJson2(target, state);
28061
+ await chmod2(target, 384);
28062
+ return target;
28063
+ }
27740
28064
  function workspacePathPrefix(workspace) {
27741
28065
  return `/w:${workspace.trim().replace(/^w:/, "")}`;
27742
28066
  }
@@ -27848,12 +28172,14 @@ async function probeAuthenticatedContext(options) {
27848
28172
  await page.waitForLoadState("networkidle", { timeout: 8e3 }).catch(() => void 0);
27849
28173
  const finalUrl = new URL(page.url());
27850
28174
  if (finalUrl.origin !== profileOrigin || /(?:^|\/)login(?:\/|$)/i.test(finalUrl.pathname) || !finalUrl.pathname.startsWith(workspacePrefix)) return void 0;
28175
+ let fingerprintMatched = false;
27851
28176
  if (options.fingerprint) {
27852
28177
  const failures = await assertFingerprint(page, options.fingerprint, { data: {}, context: {}, base_url: options.profileOrigin });
27853
- if (failures.length > 0) return void 0;
28178
+ fingerprintMatched = failures.length === 0;
28179
+ if (!fingerprintMatched && options.fingerprintPolicy !== "preferred") return void 0;
27854
28180
  }
27855
28181
  passed = true;
27856
- return { page, score: preferred?.score ?? 0 };
28182
+ return { page, score: (preferred?.score ?? 0) + (fingerprintMatched ? 4 : 0) };
27857
28183
  } finally {
27858
28184
  if (!passed || options.keepProbePage !== true) {
27859
28185
  await page.close().catch(() => void 0);
@@ -27864,12 +28190,14 @@ async function openContext(options) {
27864
28190
  const cookieEnv = options.cookieEnv?.trim();
27865
28191
  const cookieHeader = !options.storageState && cookieEnv ? process.env[cookieEnv]?.trim() : void 0;
27866
28192
  if (options.storageState || cookieHeader) {
27867
- const browser2 = await chromium.launch({
27868
- headless: !options.headed,
28193
+ let browser2 = await chromium.launch({
28194
+ // Invalid imported authentication must not flash a disposable window before
28195
+ // the persistent interactive-login surface is opened.
28196
+ headless: true,
27869
28197
  executablePath: options.executablePath,
27870
28198
  channel: options.executablePath ? void 0 : "chrome"
27871
28199
  });
27872
- const context3 = await browser2.newContext(options.storageState ? { storageState: path16.resolve(options.storageState) } : void 0);
28200
+ let context3 = await browser2.newContext(options.storageState ? { storageState: path16.resolve(options.storageState) } : void 0);
27873
28201
  if (cookieHeader) {
27874
28202
  await installCookieLoginBootstrap(context3, options.baseUrl || "");
27875
28203
  await context3.addCookies(browserCookiesFromHeader(cookieHeader, options.baseUrl || ""));
@@ -27880,6 +28208,7 @@ async function openContext(options) {
27880
28208
  workspace: options.workspace || "new_oa",
27881
28209
  preferredRoute: options.preferredRoute || "",
27882
28210
  fingerprint: options.fingerprint,
28211
+ fingerprintPolicy: "preferred",
27883
28212
  requireExistingCandidate: false,
27884
28213
  keepProbePage: true
27885
28214
  }).catch(() => void 0);
@@ -27891,6 +28220,32 @@ async function openContext(options) {
27891
28220
  throw new Error(`${prefix}: supplied authentication did not pass the target-route probe and interactive recovery failed: ${error instanceof Error ? error.message : String(error)}`);
27892
28221
  });
27893
28222
  }
28223
+ if (options.headed) {
28224
+ const importedState = await context3.storageState();
28225
+ await context3.close().catch(() => void 0);
28226
+ await browser2.close().catch(() => void 0);
28227
+ browser2 = await chromium.launch({
28228
+ headless: false,
28229
+ executablePath: options.executablePath,
28230
+ channel: options.executablePath ? void 0 : "chrome"
28231
+ });
28232
+ context3 = await browser2.newContext({ storageState: importedState });
28233
+ const headedProbe = await probeAuthenticatedContext({
28234
+ context: context3,
28235
+ profileOrigin: options.baseUrl || "",
28236
+ workspace: options.workspace || "new_oa",
28237
+ preferredRoute: options.preferredRoute || "",
28238
+ fingerprint: options.fingerprint,
28239
+ fingerprintPolicy: "preferred",
28240
+ requireExistingCandidate: false,
28241
+ keepProbePage: true
28242
+ }).catch(() => void 0);
28243
+ if (!headedProbe) {
28244
+ await context3.close().catch(() => void 0);
28245
+ await browser2.close().catch(() => void 0);
28246
+ return openInteractiveLoginSession(options);
28247
+ }
28248
+ }
27894
28249
  return { context: context3, browser: browser2, owned: true };
27895
28250
  }
27896
28251
  if (options.cdpEndpoint) {
@@ -27909,6 +28264,7 @@ async function openContext(options) {
27909
28264
  workspace,
27910
28265
  preferredRoute,
27911
28266
  fingerprint: options.fingerprint,
28267
+ fingerprintPolicy: "preferred",
27912
28268
  requireExistingCandidate: true
27913
28269
  }).catch(() => void 0);
27914
28270
  if (result) probes.push({ context: candidate, ...result });
@@ -27926,6 +28282,7 @@ async function openContext(options) {
27926
28282
  workspace,
27927
28283
  preferredRoute,
27928
28284
  fingerprint: options.fingerprint,
28285
+ fingerprintPolicy: "preferred",
27929
28286
  requireExistingCandidate: false,
27930
28287
  keepProbePage: true
27931
28288
  }).catch(() => void 0);
@@ -27953,6 +28310,7 @@ async function openContext(options) {
27953
28310
  workspace: options.workspace || "new_oa",
27954
28311
  preferredRoute: options.preferredRoute || "",
27955
28312
  fingerprint: options.fingerprint,
28313
+ fingerprintPolicy: "preferred",
27956
28314
  requireExistingCandidate: false,
27957
28315
  keepProbePage: true
27958
28316
  }).catch(() => void 0);
@@ -27968,6 +28326,7 @@ async function openContext(options) {
27968
28326
  });
27969
28327
  try {
27970
28328
  await waitForInteractiveLogin(context3, options);
28329
+ await persistInteractiveLoginStorageState(context3, options.storageState);
27971
28330
  } catch (error) {
27972
28331
  await context3.close().catch(() => void 0);
27973
28332
  throw error;
@@ -27987,6 +28346,7 @@ async function openContext(options) {
27987
28346
  workspace: options.workspace || "new_oa",
27988
28347
  preferredRoute: options.preferredRoute || "",
27989
28348
  fingerprint: options.fingerprint,
28349
+ fingerprintPolicy: "preferred",
27990
28350
  requireExistingCandidate: false,
27991
28351
  keepProbePage: true
27992
28352
  }).catch(() => void 0);
@@ -28607,11 +28967,19 @@ async function runOneBrowserStep(options, session) {
28607
28967
  try {
28608
28968
  currentActionIndex = -1;
28609
28969
  await restoreStepStartPage(page, definition, variables, actionTrace);
28970
+ const hasMutationAction = definition.actions.some((action) => action.mutation === true);
28971
+ const preMutationChecks = definition.expected_checks.filter(
28972
+ (check) => browserExpectedCheckPhase(check, hasMutationAction) === "pre_mutation"
28973
+ );
28974
+ const postActionChecks = definition.expected_checks.filter(
28975
+ (check) => browserExpectedCheckPhase(check, hasMutationAction) === "post_action"
28976
+ );
28977
+ let preMutationChecksExecuted = false;
28610
28978
  for (let index = 0; index < definition.actions.length; index += 1) {
28611
28979
  currentActionIndex = index;
28612
28980
  const action = definition.actions[index];
28613
28981
  const actionResponseCursor = responseSequence;
28614
- if (!fingerprintChecked && !["navigation.open", "wait.visible", "wait.route", "wait.network"].includes(action.type)) {
28982
+ if (!fingerprintChecked && action.type !== "navigation.open") {
28615
28983
  const failures = await assertFingerprint(page, definition.page_fingerprint, variables);
28616
28984
  if (failures.length > 0) {
28617
28985
  const evidence2 = await writeRunnerEvidence({
@@ -28651,6 +29019,20 @@ async function runOneBrowserStep(options, session) {
28651
29019
  }
28652
29020
  fingerprintChecked = true;
28653
29021
  }
29022
+ if (action.mutation === true && !preMutationChecksExecuted) {
29023
+ for (const check of preMutationChecks) {
29024
+ const result2 = await executeAction(page, check, variables, {
29025
+ responses,
29026
+ responseCursor: previousActionResponseCursor,
29027
+ recordResponse,
29028
+ onMutationAttempt: async () => {
29029
+ throw new Error("pre-mutation expected checks cannot attempt a remote mutation");
29030
+ }
29031
+ });
29032
+ assertions.push(result2.assertion ?? { type: check.type, passed: true });
29033
+ }
29034
+ preMutationChecksExecuted = true;
29035
+ }
28654
29036
  const startedAt = (/* @__PURE__ */ new Date()).toISOString();
28655
29037
  const result = await executeAction(page, action, variables, {
28656
29038
  responses,
@@ -28679,6 +29061,46 @@ async function runOneBrowserStep(options, session) {
28679
29061
  if (result.extracted) variables.context[result.extracted[0]] = result.extracted[1];
28680
29062
  if (result.assertion) assertions.push(result.assertion);
28681
29063
  actionTrace.push({ index, type: action.type, started_at: startedAt, finished_at: (/* @__PURE__ */ new Date()).toISOString(), ok: true });
29064
+ if (!fingerprintChecked && index === 0 && action.type === "navigation.open") {
29065
+ const failures = await assertFingerprint(page, definition.page_fingerprint, variables);
29066
+ if (failures.length > 0) {
29067
+ const evidence2 = await writeRunnerEvidence({
29068
+ dir: evidenceDir,
29069
+ page,
29070
+ caseId: requestedCase,
29071
+ stepId: requestedStep,
29072
+ runId: validated.manifest.run_id,
29073
+ evidenceNonce: validated.manifest.evidence_nonce,
29074
+ status: "cache_stale",
29075
+ assertions: failures.map((message) => ({ name: "page_fingerprint", passed: false, message })),
29076
+ actionTrace,
29077
+ automationStep: definition,
29078
+ consoleErrors,
29079
+ networkErrors,
29080
+ networkResponses: responses,
29081
+ remoteSubmitted: false,
29082
+ readbackConfirmed: false,
29083
+ error: failures.join("; ")
29084
+ });
29085
+ return {
29086
+ ok: false,
29087
+ status: "cache_stale",
29088
+ remote_submitted: false,
29089
+ readback_confirmed: false,
29090
+ llm_intervention_required: true,
29091
+ manifest: validated.manifestPath,
29092
+ case_id: requestedCase,
29093
+ case_step_id: requestedStep,
29094
+ evidence: evidence2,
29095
+ current_url: page.url(),
29096
+ error: failures.join("; "),
29097
+ repairable: true,
29098
+ failure_kind: "page_drift",
29099
+ failure_action_index: index
29100
+ };
29101
+ }
29102
+ fingerprintChecked = true;
29103
+ }
28682
29104
  previousActionResponseCursor = actionResponseCursor;
28683
29105
  }
28684
29106
  if (!fingerprintChecked) {
@@ -28720,7 +29142,7 @@ async function runOneBrowserStep(options, session) {
28720
29142
  };
28721
29143
  }
28722
29144
  }
28723
- for (const check of definition.expected_checks) {
29145
+ for (const check of postActionChecks) {
28724
29146
  const checkResponseCursor = responseSequence;
28725
29147
  const result = await executeAction(page, check, variables, {
28726
29148
  responses,
@@ -29709,7 +30131,7 @@ async function executeE2eScenarioUnlocked(options, dependencies = DEFAULT_DEPEND
29709
30131
  const generatedUserDataDir = !options.userDataDir ? path17.join(path17.dirname(manifest), ".playwright-session") : void 0;
29710
30132
  if (generatedUserDataDir) {
29711
30133
  await mkdir12(generatedUserDataDir, { recursive: true, mode: 448 });
29712
- await chmod2(generatedUserDataDir, 448);
30134
+ await chmod3(generatedUserDataDir, 448);
29713
30135
  options.userDataDir = generatedUserDataDir;
29714
30136
  }
29715
30137
  options.interactiveLogin ??= true;
@@ -30541,7 +30963,7 @@ async function resolveE2eScenarioWriteState(options, dependencies = DEFAULT_DEPE
30541
30963
 
30542
30964
  // src/core/e2e-identity-bridge.ts
30543
30965
  import { createHash as createHash12, randomUUID as randomUUID4 } from "crypto";
30544
- import { chmod as chmod3, lstat as lstat4, mkdir as mkdir13, readFile as readFile17, realpath as realpath7, rename as rename5, stat as stat12, unlink as unlink2, writeFile as writeFile13 } from "fs/promises";
30966
+ import { chmod as chmod4, lstat as lstat4, mkdir as mkdir13, readFile as readFile17, realpath as realpath7, rename as rename5, stat as stat12, unlink as unlink2, writeFile as writeFile13 } from "fs/promises";
30545
30967
  import path18 from "path";
30546
30968
  var REQUEST_TTL_SECONDS = 180;
30547
30969
  var RESULT_MAX_DURATION_MS = 15 * 60 * 1e3;
@@ -30639,6 +31061,17 @@ function recoveredOriginalIdentity(lease) {
30639
31061
  }
30640
31062
  return null;
30641
31063
  }
31064
+ function recoveredExpiredCorruptRecordingIdentity(lease, binding) {
31065
+ if (!binding.recording_session || binding.execution_manifest || !lease.binding.recording_session || lease.binding.execution_manifest || path18.resolve(binding.recording_session) !== path18.resolve(lease.binding.recording_session) || binding.profile !== lease.binding.profile || !lease.expires_at || Date.parse(lease.expires_at) > Date.now()) {
31066
+ return null;
31067
+ }
31068
+ const original = safeIdentity(lease.original_user);
31069
+ const target = safeIdentity(lease.target_user);
31070
+ if (!original?.id || !original.mock || !target?.id || !target.mock || original.id !== target.id) {
31071
+ return null;
31072
+ }
31073
+ return { identity: original, source: "lease_original" };
31074
+ }
30642
31075
  async function readJson(file) {
30643
31076
  return JSON.parse(await readFile17(file, "utf8"));
30644
31077
  }
@@ -30683,13 +31116,13 @@ async function atomicJson(file, value, exclusive = false) {
30683
31116
  if (exclusive) {
30684
31117
  await writeFile13(file, `${JSON.stringify(value, null, 2)}
30685
31118
  `, { encoding: "utf8", flag: "wx", mode: 384 });
30686
- await chmod3(file, 384);
31119
+ await chmod4(file, 384);
30687
31120
  return;
30688
31121
  }
30689
31122
  const temp = `${file}.tmp-${process.pid}-${Date.now()}`;
30690
31123
  await writeFile13(temp, `${JSON.stringify(value, null, 2)}
30691
31124
  `, { encoding: "utf8", mode: 384 });
30692
- await chmod3(temp, 384);
31125
+ await chmod4(temp, 384);
30693
31126
  await rename5(temp, file);
30694
31127
  }
30695
31128
  async function withLeaseLock(leaseFile, action) {
@@ -30813,7 +31246,7 @@ async function prepareIdentityBrowserBridge(options) {
30813
31246
  if (options.operation === "unmock" && (!activeLease || !["active", "uncertain"].includes(activeLease.state))) {
30814
31247
  throw new Error("e2e.identity.browser.unmock_without_lease: unmock \u5FC5\u987B\u5BF9\u5E94\u540C\u4E00\u6B63\u5F0F run \u6216 recording session \u7684 active/uncertain identity lease\u3002");
30815
31248
  }
30816
- const originalRecovery = options.operation === "unmock" && activeLease ? recoveredOriginalIdentity(activeLease) : null;
31249
+ const originalRecovery = options.operation === "unmock" && activeLease ? recoveredOriginalIdentity(activeLease) ?? recoveredExpiredCorruptRecordingIdentity(activeLease, options.binding) : null;
30817
31250
  if (options.operation === "unmock" && !originalRecovery) {
30818
31251
  throw new Error("e2e.identity.browser.original_identity_unrecoverable: lease \u65E0\u6CD5\u8BC1\u660E\u7CBE\u786E\u539F\u59CB\u8EAB\u4EFD\uFF0C\u7981\u6B62\u5C1D\u8BD5 unmock \u6216\u91CA\u653E\u79DF\u7EA6\u3002");
30819
31252
  }
@@ -32911,7 +33344,8 @@ async function updateAutomationFromRecordedTrace(options) {
32911
33344
  runner: "browser_action",
32912
33345
  page_fingerprint: trace.page_fingerprint,
32913
33346
  actions: trace.actions,
32914
- expected_checks: trace.expected_checks
33347
+ expected_checks: trace.expected_checks,
33348
+ ...isRecord15(trace.resolution_checks) ? { resolution_checks: trace.resolution_checks } : {}
32915
33349
  }
32916
33350
  };
32917
33351
  const candidateStep = document2.steps[automationStepKey(options.caseId, options.caseStepId)].automation;
@@ -34317,11 +34751,7 @@ function buildGitLabIssuePayload(input) {
34317
34751
  function resolveGitLabToken(options) {
34318
34752
  const env = options.env || process.env;
34319
34753
  if (options.tokenEnv) {
34320
- const explicitToken = env[options.tokenEnv]?.trim();
34321
- if (!explicitToken) {
34322
- throw new Error(`GitLab token is required. Set ${options.tokenEnv}.`);
34323
- }
34324
- return explicitToken;
34754
+ return env[options.tokenEnv]?.trim() || void 0;
34325
34755
  }
34326
34756
  const candidates = [
34327
34757
  env.GITLAB_TOKEN,
@@ -34330,28 +34760,40 @@ function resolveGitLabToken(options) {
34330
34760
  "-1pFevGtvjq4fXSxzZJQ"
34331
34761
  ];
34332
34762
  const token = candidates.find((candidate) => candidate?.trim());
34333
- if (!token) {
34334
- throw new Error("GitLab token is required. Set GITLAB_TOKEN.");
34335
- }
34336
- return token.trim();
34763
+ return token?.trim() || void 0;
34764
+ }
34765
+ function gitLabIssueAuthError(status, tokenConfigured) {
34766
+ return new Error(
34767
+ `GitLab issue submission failed with HTTP ${status}. ` + (tokenConfigured ? "The configured GitLab token was rejected. Replace GITLAB_TOKEN, GL_TOKEN, PRIVATE_TOKEN, or --token-env, then retry." : "No GitLab token was configured. Set GITLAB_TOKEN, GL_TOKEN, PRIVATE_TOKEN, or --token-env, then retry.") + " Browser login is not used for issue submission."
34768
+ );
34337
34769
  }
34338
34770
  async function createGitLabIssue(input, options) {
34339
- const token = options.token.trim();
34340
- if (!token) {
34341
- throw new Error("GitLab token is required.");
34342
- }
34343
34771
  const baseUrl = normalizeBaseUrl2(options.baseUrl);
34344
34772
  const projectPath = gitLabProjectApiPath(options.project);
34345
34773
  const client = options.client || axios8.create({ baseURL: baseUrl });
34346
34774
  const headers = AxiosHeaders3.from();
34347
- headers.set("PRIVATE-TOKEN", token);
34348
- const response = await client.request({
34349
- method: "POST",
34350
- url: `/api/v4/projects/${projectPath}/issues`,
34351
- headers,
34352
- data: buildGitLabIssuePayload(input)
34353
- });
34354
- return response.data;
34775
+ const token = options.token?.trim();
34776
+ if (token) {
34777
+ headers.set("PRIVATE-TOKEN", token);
34778
+ }
34779
+ try {
34780
+ const response = await client.request({
34781
+ method: "POST",
34782
+ url: `/api/v4/projects/${projectPath}/issues`,
34783
+ headers,
34784
+ data: buildGitLabIssuePayload(input)
34785
+ });
34786
+ return response.data;
34787
+ } catch (error) {
34788
+ const status = error && typeof error === "object" && "response" in error && error.response && typeof error.response === "object" && "status" in error.response && typeof error.response.status === "number" ? error.response.status : void 0;
34789
+ if (!token && (status === 401 || status === 403 || status === 404)) {
34790
+ throw gitLabIssueAuthError(status, false);
34791
+ }
34792
+ if (token && status === 401) {
34793
+ throw gitLabIssueAuthError(status, true);
34794
+ }
34795
+ throw error;
34796
+ }
34355
34797
  }
34356
34798
  function lintIssueReportDraft(input) {
34357
34799
  const findings = [];