@tea-agent/loop-agent 0.1.0-fe-test.2 → 0.1.0-fe-test.3

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/CHANGELOG.md CHANGED
@@ -4,6 +4,8 @@
4
4
 
5
5
  ### 变更
6
6
 
7
+ - frontend-test 重跑候选判定修复:首次执行子节点常把 `case-result.json` 的 `rerunAttempt` 写成 1(含义「第 1 次执行」),旧选择器把它当「已重跑过 1 轮」,导致 10 个 blocked 用例只重跑了 4 个。选择器改为结构化 shell 节点 `frontendTestRerunCandidates`(纯函数 `selectFrontendRerunCandidates`),已完成重跑轮次只认 `execution.md` 中的 DAG 重跑标记 `RERUN attempt N`,首次执行的 `rerunAttempt` 字段一律忽略;首次执行提示词同步禁止写 `rerunAttempt` 与 `RERUN attempt` 标记(保留给重跑子节点),候选 JSON 增加 `round` 字段。
8
+ - frontend-test checklist 不再把用例元信息里的仓库相对路径引用(如 `` `testcase/frontend/rag/context.md` ``、evidence `*.md`/`*.json`)当成可执行命令拦截;绝对路径与 `./bin/...` 仍走命令闸。
7
9
  - frontend-test 用例生成预算与契约:去掉 generate「4–8 条 smoke」软建议;`frontendTest.maxCasesPerBatch` 默认 50、配置最高 100。dimension 不再封闭为 core/boundary/flow/backend,仅校验 kebab-case,允许 `ux` 等扩充。生成阶段改为紧凑 planner JSON + 有界 map 一例一文件 + finalize shell,并统一为资深前端测试专家角色,禁止页面探索;标准场景补交互体验(提交防重复、操作反馈为 must)。入库中文优先用例模板 `docs/templates/frontend-test-case.example.md`:需登录则 `open` 登录页再 `goto` 目标页,否则 `open`/`goto` 目标页。
8
10
 
9
11
 
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
- "version": "0.1.0-fe-test.2",
4
- "gitSha": "9a784591284f7e3db81990472e2820f79946a723",
5
- "builtAt": "2026-09-03T10:59:11.913Z"
3
+ "version": "0.1.0-fe-test.3",
4
+ "gitSha": "b093f705d42d852f62973b2a6192ab910f77f76c",
5
+ "builtAt": "2026-09-04T00:25:45.112Z"
6
6
  }
@@ -18,6 +18,7 @@ import { materializeFrontendTestResult, validateFrontendCaseEvidence, } from "..
18
18
  import { renderFrontendTestL5Report } from "../workflows/dag/frontend-test-l5-report.js";
19
19
  import { validateFrontendCaseChecklist } from "../workflows/dag/frontend-test-case-checklist.js";
20
20
  import { materializeFrontendTestCaseManifest } from "../workflows/dag/frontend-test-case-manifest.js";
21
+ import { selectFrontendRerunCandidates } from "../workflows/dag/frontend-test-rerun-candidates.js";
21
22
  import { renderFrontendTestHtmlReport } from "../workflows/dag/frontend-test-html-report.js";
22
23
  import { formatFrontendVerificationTraceStdout, runFrontendVerificationTraceGate, } from "../workflows/dag/frontend-verification-trace.js";
23
24
  import { formatFrontendWorktreeDiffStdout, runFrontendWorktreeDiffGate, } from "../workflows/dag/frontend-worktree-diff.js";
@@ -2152,6 +2153,34 @@ async function executeFrontendTestCasePackageFinalize(input, meta) {
2152
2153
  return { ok: false, stdout: "", stderr: error instanceof Error ? error.message : String(error), failureCategory: "invalid-output", durationMs: Date.now() - started };
2153
2154
  }
2154
2155
  }
2156
+ async function executeFrontendTestRerunCandidates(input, _meta) {
2157
+ const started = Date.now();
2158
+ try {
2159
+ const round = input.task.shell?.frontendTestRerunCandidates?.round;
2160
+ if (round === undefined)
2161
+ throw new Error("frontend-test rerun selector missing round");
2162
+ const selected = await selectFrontendRerunCandidates({
2163
+ workspaceRoot: input.cwd,
2164
+ round,
2165
+ });
2166
+ return {
2167
+ ok: true,
2168
+ stdout: `${JSON.stringify({ cases: selected.cases })}\n`,
2169
+ stderr: "",
2170
+ failureCategory: "success",
2171
+ durationMs: Date.now() - started,
2172
+ };
2173
+ }
2174
+ catch (error) {
2175
+ return {
2176
+ ok: false,
2177
+ stdout: "",
2178
+ stderr: error instanceof Error ? error.message : String(error),
2179
+ failureCategory: "invalid-output",
2180
+ durationMs: Date.now() - started,
2181
+ };
2182
+ }
2183
+ }
2155
2184
  async function executeFrontendTestCaseManifest(input, meta) {
2156
2185
  const started = Date.now();
2157
2186
  try {
@@ -2530,6 +2559,9 @@ export async function executeDagShellNode(input, meta) {
2530
2559
  if (shell?.frontendTestCasePackageFinalize) {
2531
2560
  return executeFrontendTestCasePackageFinalize(input, meta);
2532
2561
  }
2562
+ if (shell?.frontendTestRerunCandidates) {
2563
+ return executeFrontendTestRerunCandidates(input, meta);
2564
+ }
2533
2565
  if (shell?.frontendTestEvidenceValidation) {
2534
2566
  return executeFrontendTestEvidenceValidation(input);
2535
2567
  }
@@ -17,6 +17,9 @@ const ENV_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=(?:"[^"]*"|'[^']*'|[^\s]*)/;
17
17
  const ENV_WRAPPER = /^env(?:\s+(?:-[A-Za-z]+|--[A-Za-z][A-Za-z-]*))*\s+/i;
18
18
  const SHELL_BUILTIN_WRAPPER = /^(?:command|exec|sudo)\s+/i;
19
19
  const PLAYWRIGHT_API = /^(?:from\s+playwright(?:\.[A-Za-z_][A-Za-z0-9_]*)*\s+import\b|import\s+playwright(?:\.[A-Za-z_][A-Za-z0-9_]*)*(?:\s+as\s+[A-Za-z_][A-Za-z0-9_]*)?\b|import\s+.+\s+from\s+["'](?:playwright|@playwright\/test)["']|(?:const|let|var)\s+.+\brequire\s*\(\s*["'](?:playwright|@playwright\/test)["']\s*\)|require\s*\(\s*["'](?:playwright|@playwright\/test)["']\s*\)|(?:sync_playwright|async_playwright|chromium|firefox|webkit)\.(?:launch|connect)\b)/i;
20
+ /** Repo-relative doc/evidence paths cited in case metadata (not shell commands). */
21
+ const REPO_PATH_REFERENCE = /^[A-Za-z0-9_][A-Za-z0-9._-]*(?:[\\/][A-Za-z0-9._-]+)+[\\/]?$/;
22
+ const PATH_REFERENCE_EXTENSION = /\.(?:md|json|ya?ml|txt|log|har|csv|png|jpe?g|gif|webp|html?)$/i;
20
23
  async function exists(file) {
21
24
  try {
22
25
  return (await stat(file)).isFile();
@@ -111,6 +114,21 @@ function isCommandLikeExecutable(command) {
111
114
  const executable = stripLeadingCommandWrappers(command);
112
115
  return AUTOMATION_EXECUTABLE.test(executable) || SHELL_WRAPPED_EXECUTABLE.test(executable) || PLAYWRIGHT_API.test(executable);
113
116
  }
117
+ /**
118
+ * Bare repo-relative documentation/evidence paths (e.g. `testcase/frontend/rag/context.md`)
119
+ * cited as metadata, not executable shell commands. Absolute (`/usr/bin/curl`) and
120
+ * dot-relative (`./node_modules/.bin/playwright`) paths stay gated.
121
+ */
122
+ function isRepositoryPathReference(command) {
123
+ const token = command.trim();
124
+ if (!token || /\s/.test(token))
125
+ return false;
126
+ if (hasShellControl(token))
127
+ return false;
128
+ if (!REPO_PATH_REFERENCE.test(token))
129
+ return false;
130
+ return token.endsWith("/") || token.endsWith("\\") || PATH_REFERENCE_EXTENSION.test(token);
131
+ }
114
132
  function executableListStep(value) {
115
133
  const trimmed = value.trim();
116
134
  if (isNonExecutableBlockedProse(trimmed))
@@ -235,10 +253,14 @@ function extractExecutableInstructions(markdown) {
235
253
  return instructions;
236
254
  }
237
255
  function commandGateIssue(input) {
238
- // Outside fences, blocked/unavailable prose must never become a gate failure.
256
+ // Outside fences, blocked/unavailable prose and repo-relative path citations
257
+ // (RAG sources, evidence files) must never become a gate failure.
239
258
  if (!input.instruction.fromFence && isNonExecutableBlockedProse(input.instruction.command)) {
240
259
  return null;
241
260
  }
261
+ if (!input.instruction.fromFence && isRepositoryPathReference(input.instruction.command)) {
262
+ return null;
263
+ }
242
264
  if (input.instruction.fromFence && isBlockedReason(input.instruction.command)) {
243
265
  return null;
244
266
  }
@@ -0,0 +1,103 @@
1
+ import { mkdir, readFile, writeFile } from "node:fs/promises";
2
+ import path from "node:path";
3
+ const RERUN_ATTEMPT_MARK = /RERUN\s+attempt\s+(\d+)/gi;
4
+ /**
5
+ * Completed DAG rerun rounds for a case.
6
+ *
7
+ * First-run children often write `rerunAttempt: 1` meaning "this is the first
8
+ * execution". That field is not an authority for "already rerun". Only the
9
+ * DAG rerun prompt's `RERUN attempt N` marker in execution.md counts.
10
+ */
11
+ export function completedRerunAttemptFromEvidence(input) {
12
+ const text = input.executionMarkdown ?? "";
13
+ let max = 0;
14
+ for (const match of text.matchAll(RERUN_ATTEMPT_MARK)) {
15
+ const n = Number(match[1]);
16
+ if (Number.isFinite(n) && n > max)
17
+ max = Math.trunc(n);
18
+ }
19
+ return max;
20
+ }
21
+ export function isEligibleForRerunRound(input) {
22
+ const missing = input.resultMissing || (input.executionMissing && input.status !== "blocked");
23
+ const blocked = input.status === "blocked";
24
+ const reason = blocked
25
+ ? "blocked"
26
+ : missing
27
+ ? "missing-result-files"
28
+ : null;
29
+ const eligible = (blocked || missing) && input.completedAttempt < input.round;
30
+ return { eligible, reason: eligible ? (reason ?? "blocked") : null };
31
+ }
32
+ export async function selectFrontendRerunCandidates(input) {
33
+ const round = Math.trunc(input.round);
34
+ if (!Number.isFinite(round) || round < 1) {
35
+ throw new Error(`frontend-test rerun selector requires round >= 1, got ${input.round}`);
36
+ }
37
+ const manifestPath = path.join(input.workspaceRoot, "testcase/frontend/cases/manifest.json");
38
+ let manifest;
39
+ try {
40
+ manifest = JSON.parse(await readFile(manifestPath, "utf8"));
41
+ }
42
+ catch {
43
+ return { schemaVersion: 1, round, cases: [] };
44
+ }
45
+ const cases = [];
46
+ for (const c of manifest.cases ?? []) {
47
+ if (typeof c.caseId !== "string" || !c.caseId)
48
+ continue;
49
+ const evidenceDir = (typeof c.evidenceDir === "string" && c.evidenceDir
50
+ ? c.evidenceDir
51
+ : `testcase/frontend/evidence/${c.caseId}/`)
52
+ .replace(/\\/g, "/")
53
+ .replace(/\/+$/, "") + "/";
54
+ const resultPath = path.join(input.workspaceRoot, evidenceDir, "case-result.json");
55
+ const execPath = path.join(input.workspaceRoot, evidenceDir, "execution.md");
56
+ let status = null;
57
+ let resultMissing = false;
58
+ let executionMarkdown = null;
59
+ try {
60
+ const raw = JSON.parse(await readFile(resultPath, "utf8"));
61
+ status = typeof raw.status === "string" ? raw.status : null;
62
+ if (!status)
63
+ resultMissing = true;
64
+ }
65
+ catch {
66
+ resultMissing = true;
67
+ }
68
+ let executionMissing = false;
69
+ try {
70
+ executionMarkdown = await readFile(execPath, "utf8");
71
+ }
72
+ catch {
73
+ executionMissing = true;
74
+ }
75
+ const completedAttempt = completedRerunAttemptFromEvidence({ executionMarkdown });
76
+ const { eligible, reason } = isEligibleForRerunRound({
77
+ status,
78
+ resultMissing,
79
+ executionMissing,
80
+ completedAttempt,
81
+ round,
82
+ });
83
+ if (!eligible || !reason)
84
+ continue;
85
+ cases.push({
86
+ caseId: c.caseId,
87
+ casePath: typeof c.casePath === "string" && c.casePath
88
+ ? c.casePath
89
+ : `testcase/frontend/cases/${c.caseId}.md`,
90
+ evidenceDir,
91
+ dimension: typeof c.dimension === "string" && c.dimension ? c.dimension : "core",
92
+ acIds: Array.isArray(c.acIds) ? c.acIds.filter((id) => typeof id === "string") : [],
93
+ rerunAttempt: completedAttempt + 1,
94
+ reason,
95
+ });
96
+ }
97
+ const evidenceRoot = path.join(input.workspaceRoot, "testcase/frontend/evidence");
98
+ await mkdir(evidenceRoot, { recursive: true });
99
+ const artifact = round === 1 ? "rerun-candidates.json" : `rerun-candidates-round${round}.json`;
100
+ const body = { schemaVersion: 1, round, cases };
101
+ await writeFile(path.join(evidenceRoot, artifact), `${JSON.stringify(body, null, 2)}\n`, "utf8");
102
+ return body;
103
+ }
@@ -5208,7 +5208,7 @@ function buildFrontendTestHybridDag(sources) {
5208
5208
  "Primary job: EXECUTE case {{case.caseId}} from {{case.casePath}} with skill playwright-cli (fresh Pi session; do not use /new). playwright-cli-only: never bare Playwright CLI/API/test runner; no fallback.",
5209
5209
  "Use the structured playwright_cli tool for every browser action. Do not request or search for bash. Do not execute raw shell commands. Translate each playwright-cli line in the case Markdown into one playwright_cli tool call ({command, args?, timeoutSeconds?}).",
5210
5210
  "1) Read the concrete baseUrl from testcase/frontend/rag/context.md; it has already passed the environment shell safety/reachability gate. Start browser ONLY via playwright_cli command=open with args [--browser=chrome, <that-concrete-baseUrl>] (default session only; no -s=). 2) Dynamic refs: eX/eY in case Markdown are documentation placeholders, never tool args. Immediately before every structured playwright_cli call that references an element, parse the current real eNN from the immediately preceding latest snapshot and pass only that real eNN; never send literal `eX`/`eY`. A new snapshot invalidates prior refs, so never reuse stale refs. File outputs are canonical: screenshot args [--filename, final.png] (or [e5, --filename, final.png] for a real target), PDF args [--filename, final.pdf], and snapshot writes a file only with [--filename, snapshot.txt]; snapshot without filename is response-only. Never use --path, --output, --file, or any output path as a positional target. Follow case steps with snapshot before element refs using only playwright_cli. A passed case requires this same child receipt order: successful open → successful find → controller post-execution cleanup. Only successful find is a meaningful assertion; snapshot, goto, screenshot, request/console, click/fill and other ordinary interactions cannot establish passed authority. 3) Only when preflight or playwright_cli tool explicitly fails may you write blocked evidence (blockedReason playwright-cli-unavailable | frontend-base-url-unreachable); never invent CLI-unavailable solely because bash is absent. 4) For U/D: enforce current-user ownership / create-or-mock-or-blocked; never mutate other users' data.",
5211
- "Always write {{case.evidenceDir}}execution.md and {{case.evidenceDir}}case-result.json with caseId={{case.caseId}}, status passed|failed|blocked, evidencePaths (relative under evidenceDir). blocked needs non-empty blockedReason. After writing, self-check the same contract; if self-check fails, rewrite both files as status=blocked blockedReason=invalid-evidence-shape (never leave missing/malformed evidence).",
5211
+ "Always write {{case.evidenceDir}}execution.md and {{case.evidenceDir}}case-result.json with caseId={{case.caseId}}, status passed|failed|blocked, evidencePaths (relative under evidenceDir). blocked needs non-empty blockedReason. Do NOT write rerunAttempt (omit the field). Do NOT write the marker `RERUN attempt N` — that marker is reserved for DAG rerun children. After writing, self-check the same contract; if self-check fails, rewrite both files as status=blocked blockedReason=invalid-evidence-shape (never leave missing/malformed evidence).",
5212
5212
  "Business failed/blocked is a recorded result, not a node failure. Close browser via playwright_cli command=close. Return compact JSON (<=1200 chars): {caseId,status,evidencePaths,errorSummary,tokens}.",
5213
5213
  ].join("\n\n"),
5214
5214
  },
@@ -5222,17 +5222,6 @@ function buildFrontendTestHybridDag(sources) {
5222
5222
  const mapId = round === 1
5223
5223
  ? "rerun-frontend-cases-map"
5224
5224
  : `rerun-frontend-cases-round${round}-map`;
5225
- const candidateArtifact = round === 1
5226
- ? "rerun-candidates.json"
5227
- : `rerun-candidates-round${round}.json`;
5228
- const selectCommand = [
5229
- "const fs=require('fs'),path=require('path');",
5230
- "const manifestPath='testcase/frontend/cases/manifest.json';",
5231
- "if(!fs.existsSync(manifestPath)){process.stdout.write(JSON.stringify({cases:[]}));process.exit(0);}",
5232
- "const manifest=JSON.parse(fs.readFileSync(manifestPath,'utf8'));const cases=[];",
5233
- "for(const c of (manifest.cases||[])){const evidenceDir=(c.evidenceDir||('testcase/frontend/evidence/'+c.caseId+'/')).replace(/\\/+$/,'')+'/';const resultPath=path.join(evidenceDir,'case-result.json');const execPath=path.join(evidenceDir,'execution.md');let reason=null;let attempt=0;let missing=false;if(!fs.existsSync(resultPath)){missing=true;reason='missing-result-files';}else{try{const r=JSON.parse(fs.readFileSync(resultPath,'utf8'));attempt=Number(r.rerunAttempt||0)||0;if(r.status==='blocked')reason='blocked';if(!r.status){missing=true;reason='missing-result-files';}}catch(_){missing=true;reason='missing-result-files';}}if(!fs.existsSync(execPath)&&reason!=='blocked'){missing=true;reason=reason||'missing-result-files';}const should=(reason==='blocked'||missing)&&attempt<" + String(round) + ";if(should){cases.push({caseId:c.caseId,casePath:c.casePath||('testcase/frontend/cases/'+c.caseId+'.md'),evidenceDir,dimension:c.dimension||'core',acIds:c.acIds||[],rerunAttempt:attempt+1,reason:reason||'blocked'});}}",
5234
- `fs.mkdirSync('testcase/frontend/evidence',{recursive:true});fs.writeFileSync('testcase/frontend/evidence/${candidateArtifact}',JSON.stringify({schemaVersion:1,cases},null,2)+'\\n');process.stdout.write(JSON.stringify({cases}));`,
5235
- ].join("");
5236
5225
  tasks.push({
5237
5226
  id: selectorId,
5238
5227
  depends_on: [rerunDependency],
@@ -5243,10 +5232,11 @@ function buildFrontendTestHybridDag(sources) {
5243
5232
  writeSet: ["testcase/frontend/evidence/**"],
5244
5233
  allowedPaths: [...casesWriteSet, "testcase/frontend/evidence/**"],
5245
5234
  forbiddenPaths: forbidden,
5246
- outputContract: `Stdout JSON {cases} for blocked or missing-result-file cases eligible for rerun round ${round}/${maxRerunAttempts}.`,
5235
+ outputContract: `Stdout JSON {cases} for blocked or missing-result-file cases eligible for rerun round ${round}/${maxRerunAttempts}. First-run rerunAttempt fields are ignored; only execution.md "RERUN attempt N" counts as a completed DAG rerun.`,
5247
5236
  subtask_prompt: "Select frontend-test cases eligible for this bounded rerun round.",
5248
5237
  shell: {
5249
- commands: [["node -e", JSON.stringify(selectCommand)].join(" ")],
5238
+ commands: [],
5239
+ frontendTestRerunCandidates: { round },
5250
5240
  cwd: ".",
5251
5241
  timeoutMs: 120_000,
5252
5242
  },
@@ -436,6 +436,11 @@ export const dagFrontendTestHtmlReportSchema = z.object({}).strict();
436
436
  * materializes testcase/frontend/cases/manifest.json from manifest.draft.json.
437
437
  * Stdout is exactly one final JSON line {cases}.
438
438
  */
439
+ export const dagFrontendTestRerunCandidatesSchema = z
440
+ .object({
441
+ round: z.number().int().min(1).max(4),
442
+ })
443
+ .strict();
439
444
  export const dagFrontendTestCasePackageFinalizeSchema = z
440
445
  .object({
441
446
  plannerNodeId: z.string().regex(/^[a-z][a-z0-9-]*$/),
@@ -530,6 +535,7 @@ export const dagShellConfigSchema = z.object({
530
535
  frontendTestHtmlReport: dagFrontendTestHtmlReportSchema.optional(),
531
536
  frontendTestCaseManifest: dagFrontendTestCaseManifestSchema.optional(),
532
537
  frontendTestCasePackageFinalize: dagFrontendTestCasePackageFinalizeSchema.optional(),
538
+ frontendTestRerunCandidates: dagFrontendTestRerunCandidatesSchema.optional(),
533
539
  frontendTestResultFinalize: dagFrontendTestResultFinalizeSchema.optional(),
534
540
  frontendTestReports: dagFrontendTestReportsSchema.optional(),
535
541
  backendTestPipeline: dagBackendTestPipelineSchema.optional(),
@@ -473,6 +473,7 @@ function validateShellTaskConfig(task, spec, issues) {
473
473
  !shell.frontendTestHtmlReport &&
474
474
  !shell.frontendTestCaseManifest &&
475
475
  !shell.frontendTestCasePackageFinalize &&
476
+ !shell.frontendTestRerunCandidates &&
476
477
  !shell.frontendTestResultFinalize &&
477
478
  !shell.frontendTestReports) {
478
479
  issues.push({
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tea-agent/loop-agent",
3
- "version": "0.1.0-fe-test.2",
3
+ "version": "0.1.0-fe-test.3",
4
4
  "type": "module",
5
5
  "bin": {
6
6
  "loop-agent": "bin/loop-agent.js",