Verify the declared Node entry before completing Agent tasks
This commit is contained in:
1 parent
da93d4fa1c
commit
6d55806b4f
6 files changed
+113
-9
No files matched your search
@@ -151,7 +151,7 @@ public class AgentWorker {
|
||||
.multiply(BigDecimal.valueOf(context))
|
||||
.add(((BigDecimal) price.get("output_price")).multiply(BigDecimal.valueOf(maxOutput)))
|
||||
.divide(BigDecimal.valueOf(1000000), 8, RoundingMode.UP);
|
||||
int emptyCompletions = 0;
|
||||
int incompleteCompletions = 0;
|
||||
while (true) {
|
||||
task = tasks.config(id);
|
||||
String action = task.get("requested_action").toString();
|
||||
@@ -242,10 +242,18 @@ public class AgentWorker {
|
||||
tasks.finish(id, lease, "PAUSED", "源码检查达到扫描上限,尚不能确认生成结果;请检查工作区后继续", false);
|
||||
return;
|
||||
}
|
||||
if (inspection == null || inspection.path("sourceFiles").asInt(0) == 0) {
|
||||
tasks.requireSource(id, lease);
|
||||
if (++emptyCompletions < 2) continue;
|
||||
tasks.finish(id, lease, "PAUSED", "AI 尚未生成实际源码,已暂停;请调整需求或模型后继续", false);
|
||||
String missingStart =
|
||||
inspection == null ? "" : inspection.path("missingStartFile").asText("");
|
||||
if (inspection == null
|
||||
|| inspection.path("sourceFiles").asInt(0) == 0
|
||||
|| !missingStart.isEmpty()) {
|
||||
tasks.requireSource(id, lease, missingStart);
|
||||
if (++incompleteCompletions < 2) continue;
|
||||
String reason =
|
||||
missingStart.isEmpty()
|
||||
? "AI 尚未生成实际源码,已暂停;请调整需求或模型后继续"
|
||||
: "缺少 package.json 指定的启动文件 " + missingStart + ",补齐后可继续任务";
|
||||
tasks.finish(id, lease, "PAUSED", reason, false);
|
||||
return;
|
||||
}
|
||||
tasks.finish(id, lease, "COMPLETED", "本轮开发已结束,工作区已有源码;完整功能与构建结果以实际测试为准", true);
|
||||
|
||||
@@ -465,8 +465,22 @@ public class TaskService {
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void requireSource(UUID id, String lease) {
|
||||
public void requireSource(UUID id, String lease, String missingStart) {
|
||||
locked(id, lease);
|
||||
if (!missingStart.isEmpty()) {
|
||||
message(
|
||||
id,
|
||||
Map.of(
|
||||
"role",
|
||||
"user",
|
||||
"content",
|
||||
"The workspace is missing the Node startup file declared in package.json: "
|
||||
+ missingStart
|
||||
+ ". Use the tools to create the entry point or correct the start script to match"
|
||||
+ " the project, then verify that the app can start before finishing."));
|
||||
event(id, "SOURCE_REQUIRED", "缺少 package.json 指定的启动文件 " + missingStart + ",已要求 AI 补齐");
|
||||
return;
|
||||
}
|
||||
message(
|
||||
id,
|
||||
Map.of(
|
||||
|
||||
@@ -336,6 +336,31 @@ class AgentWorkerIntegrationTest {
|
||||
.request(anyString(), anyString(), anyString(), anyString(), anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void existingModulesCannotCompleteWithoutTheDeclaredStartupFile() throws Exception {
|
||||
when(sandbox.inspect(any()))
|
||||
.thenReturn(
|
||||
json.createObjectNode()
|
||||
.put("sourceFiles", 4)
|
||||
.put("complete", true)
|
||||
.put("missingStartFile", "server.js"));
|
||||
when(transport.request(anyString(), anyString(), anyString(), anyString(), anyInt(), any()))
|
||||
.thenReturn(response("Done without a startup file", null));
|
||||
UUID id =
|
||||
(UUID)
|
||||
tasks
|
||||
.create(user, project, model, "Build", new BigDecimal("20"), "missing-start")
|
||||
.get("id");
|
||||
|
||||
new AgentWorker(tasks, gateway, sandbox, vault, json).run(tasks.claim());
|
||||
|
||||
assertEquals("PAUSED", tasks.config(id).get("status"));
|
||||
assertTrue(tasks.config(id).get("error").toString().contains("server.js"));
|
||||
assertTrue(tasks.history(id).getLast().path("content").asText().contains("server.js"));
|
||||
verify(transport, times(2))
|
||||
.request(anyString(), anyString(), anyString(), anyString(), anyInt(), any());
|
||||
}
|
||||
|
||||
@Test
|
||||
void emptyCompletionCanRecoverByActuallyWritingSource() throws Exception {
|
||||
when(sandbox.inspect(any()))
|
||||
|
||||
@@ -257,6 +257,9 @@ try:
|
||||
if len(files)<100:files.append({'path':str(file.relative_to(root)),'bytes':size})
|
||||
if not complete:break
|
||||
result={'sourceFiles':source_count,'files':files,'totalBytes':total,'complete':complete}
|
||||
missing_start = workspace_missing_start(root)
|
||||
if missing_start:
|
||||
result['missingStartFile'] = missing_start
|
||||
elif name=='archive_source':
|
||||
import io,zipfile
|
||||
output=io.BytesIO();total=0;count=0
|
||||
|
||||
@@ -71,6 +71,45 @@ def review_export(root, release=False):
|
||||
'complete': True, 'totalBytes': total}
|
||||
|
||||
|
||||
def node_start_entry(scripts):
|
||||
start = scripts.get('start')
|
||||
build = scripts.get('build')
|
||||
if not isinstance(start, str) or (isinstance(build, str) and build.strip()):
|
||||
return None
|
||||
simple = re.fullmatch(r'node\s+(?:\./)?([\w./-]+\.(?:mjs|cjs|js))', start.strip())
|
||||
if not simple:
|
||||
return None
|
||||
entry = pathlib.PurePosixPath(simple.group(1))
|
||||
if entry.is_absolute() or '..' in entry.parts or simple.group(1).startswith('-'):
|
||||
return None
|
||||
return entry.as_posix()
|
||||
|
||||
|
||||
def workspace_missing_start(root):
|
||||
package_file = root / 'package.json'
|
||||
try:
|
||||
if package_file.is_symlink() or not package_file.is_file():
|
||||
return None
|
||||
with package_file.open('rb') as stream:
|
||||
content = stream.read(256_001)
|
||||
if len(content) > 256_000:
|
||||
return None
|
||||
package = json.loads(content)
|
||||
except (OSError, ValueError):
|
||||
return None
|
||||
scripts = package.get('scripts') if isinstance(package, dict) else None
|
||||
entry = node_start_entry(scripts) if isinstance(scripts, dict) else None
|
||||
if entry:
|
||||
target = root / entry
|
||||
try:
|
||||
if target.resolve() == target and target.is_file():
|
||||
return None
|
||||
except (OSError, RuntimeError):
|
||||
pass
|
||||
return entry
|
||||
return None
|
||||
|
||||
|
||||
def release_snapshot(root):
|
||||
snapshot = review_export(root, release=True)
|
||||
data = base64.b64decode(snapshot['archive'])
|
||||
@@ -90,9 +129,9 @@ def release_snapshot(root):
|
||||
or package.get('optionalDependencies'))
|
||||
if start:
|
||||
runtime = 'NODE'
|
||||
simple = re.fullmatch(r'node\s+(?:\./)?([\w./-]+\.(?:mjs|cjs|js))', start)
|
||||
if simple and not build and simple.group(1) not in names:
|
||||
raise ValueError('Start file missing: ' + simple.group(1))
|
||||
entry = node_start_entry(scripts)
|
||||
if entry and entry not in names:
|
||||
raise ValueError('Start file missing: ' + entry)
|
||||
elif build:
|
||||
runtime = 'STATIC_BUILD'
|
||||
elif 'index.html' in names:
|
||||
|
||||
@@ -56,6 +56,21 @@ class GatewayTests(unittest.TestCase):
|
||||
with zipfile.ZipFile(io.BytesIO(base64.b64decode(result["archive"]))) as archive:
|
||||
self.assertEqual({"package.json", "server.js"}, set(archive.namelist()))
|
||||
|
||||
def test_workspace_inspection_reports_missing_start_even_with_other_source(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
(root / "index.js").write_text("console.log('other source')")
|
||||
package = root / "package.json"
|
||||
package.write_text('{"scripts":{"start":"node ./src/server.cjs"}}')
|
||||
result = self.execute_file_tool(root, "workspace_inspect", {})
|
||||
self.assertEqual(1, result["sourceFiles"])
|
||||
self.assertEqual("src/server.cjs", result["missingStartFile"])
|
||||
(root / "src").mkdir()
|
||||
(root / "src/server.cjs").write_text("console.log('ready')")
|
||||
self.assertNotIn("missingStartFile", self.execute_file_tool(root, "workspace_inspect", {}))
|
||||
package.write_text('{"scripts":{"start":"node dist/server.js","build":"tsc"}}')
|
||||
self.assertNotIn("missingStartFile", self.execute_file_tool(root, "workspace_inspect", {}))
|
||||
|
||||
def test_agent_file_change_counts_and_manual_edits_are_separate(self):
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
|
||||
Reference in new issue
Block a user