Compare commits
8 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 2043f8c966 | |||
| 65012e89b6 | |||
| 64b9ccfb9d | |||
| fcc3c39dad | |||
| f7a0adc616 | |||
| 57cd81d551 | |||
| 78088e422a | |||
| 65551cd827 |
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@genarrative/ai-game-creator-shell",
|
||||
"private": true,
|
||||
"version": "0.1.12",
|
||||
"version": "0.1.19",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "node scripts/start-tauri-dev.mjs",
|
||||
@@ -9,6 +9,7 @@
|
||||
"dev-stack": "node scripts/start-dev-stack.mjs",
|
||||
"build": "node scripts/build-release.mjs",
|
||||
"release:upload": "node scripts/release-upload.mjs",
|
||||
"bump-version": "node scripts/bump-version.mjs",
|
||||
"skill-pack:check": "node scripts/check-skill-pack.mjs",
|
||||
"skill-pack:sync": "node scripts/check-skill-pack.mjs --write",
|
||||
"skill-pack:test": "node --test scripts/check-skill-pack.test.mjs",
|
||||
@@ -53,7 +54,6 @@
|
||||
"focus-trap-react": "^12.0.3",
|
||||
"lexical": "^0.47.0",
|
||||
"lucide-react": "^0.546.0",
|
||||
"phaser": "^4.2.1",
|
||||
"react": "^19.0.0",
|
||||
"react-arborist": "^3.16.0",
|
||||
"react-colorful": "^5.8.0",
|
||||
|
||||
@@ -5,6 +5,7 @@ import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
const defaultReleaseTarget = 'x86_64-pc-windows-msvc';
|
||||
const releaseTarget =
|
||||
process.env.AGC_BUILD_TARGET?.trim() || defaultReleaseTarget;
|
||||
@@ -49,16 +50,23 @@ function parseVersion(value, label) {
|
||||
return value;
|
||||
}
|
||||
|
||||
export function nextPatchVersion(localVersion, remoteVersion) {
|
||||
const local = parseVersion(localVersion, '本地版本');
|
||||
const remote =
|
||||
remoteVersion == null ? null : parseVersion(remoteVersion, 'OSS版本');
|
||||
const base = remote && compareVersions(remote, local) > 0 ? remote : local;
|
||||
const [major, minor, patch] = base.split('.').map(Number);
|
||||
if (patch === Number.MAX_SAFE_INTEGER) {
|
||||
throw new Error(`版本号 patch 已达到上限:${base}`);
|
||||
export function bumpVersion(current, target = 'patch') {
|
||||
const [major, minor, patch] =
|
||||
parseVersion(current, '当前版本').split('.').map(Number);
|
||||
if (target === 'major') return `${major + 1}.0.0`;
|
||||
if (target === 'minor') return `${major}.${minor + 1}.0`;
|
||||
if (target === 'patch' || target == null) {
|
||||
if (patch === Number.MAX_SAFE_INTEGER) {
|
||||
throw new Error(`版本号 patch 已达到上限:${current}`);
|
||||
}
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
}
|
||||
return `${major}.${minor}.${patch + 1}`;
|
||||
if (typeof target === 'string' && /^\d+\.\d+\.\d+$/u.test(target)) {
|
||||
return parseVersion(target, '指定版本');
|
||||
}
|
||||
throw new Error(
|
||||
`无法识别的版本目标:${String(target)}(支持 patch / minor / major / 明确的三段版本号)`,
|
||||
);
|
||||
}
|
||||
|
||||
async function readRemoteVersion() {
|
||||
@@ -88,14 +96,52 @@ function replaceVersionLine(source, version, pattern, label) {
|
||||
return source.replace(pattern, `$1${version}$3`);
|
||||
}
|
||||
|
||||
export async function prepareReleaseVersion() {
|
||||
const localVersion = parseVersion(readPackageJson().version, '本地版本');
|
||||
const remoteVersion = await readRemoteVersion();
|
||||
const requestedVersion = process.env.AGC_RELEASE_VERSION?.trim();
|
||||
const nextVersion = requestedVersion
|
||||
? parseVersion(requestedVersion, '指定版本')
|
||||
: nextPatchVersion(localVersion, remoteVersion);
|
||||
const versionFileSources = [
|
||||
{
|
||||
file: packageJsonPath,
|
||||
pattern: /("version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'package.json',
|
||||
},
|
||||
{
|
||||
file: rootPackageLockPath,
|
||||
pattern: /("apps\/ai-game-creator-shell"\s*:\s*\{\s*\n\s*"name"\s*:\s*"@genarrative\/ai-game-creator-shell"\s*,\s*\n\s*"version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'package-lock.json',
|
||||
},
|
||||
{
|
||||
file: tauriConfigPath,
|
||||
pattern: /("version"\s*:\s*")([^"]+)(")/u,
|
||||
label: 'tauri.conf.json',
|
||||
},
|
||||
{
|
||||
file: cargoManifestPath,
|
||||
pattern: /(^\[package\][\s\S]*?^version\s*=\s*")([^"]+)(")/mu,
|
||||
label: 'Cargo.toml',
|
||||
},
|
||||
{
|
||||
file: cargoLockPath,
|
||||
pattern: /(^name\s*=\s*"genarrative-ai-game-creator-shell"\s*\nversion\s*=\s*")([^"]+)(")/mu,
|
||||
label: 'Cargo.lock',
|
||||
},
|
||||
];
|
||||
|
||||
export function readLocalVersion() {
|
||||
return parseVersion(readPackageJson().version, '本地版本');
|
||||
}
|
||||
|
||||
export function validateVersionConsistency(expectedVersion) {
|
||||
for (const source of versionFileSources) {
|
||||
const match = fs.readFileSync(source.file, 'utf8').match(source.pattern);
|
||||
const actual = match ? match[2].trim() : '<未找到>';
|
||||
if (actual !== expectedVersion) {
|
||||
throw new Error(
|
||||
`AGC 版本号不一致:${source.label} 应为 ${expectedVersion},实际 ${actual}`,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function writeVersionFiles(version) {
|
||||
const nextVersion = parseVersion(version, '目标版本');
|
||||
const packageSource = fs.readFileSync(packageJsonPath, 'utf8');
|
||||
fs.writeFileSync(
|
||||
packageJsonPath,
|
||||
@@ -151,14 +197,47 @@ export async function prepareReleaseVersion() {
|
||||
),
|
||||
);
|
||||
|
||||
console.log(
|
||||
requestedVersion
|
||||
? `[ai-game-creator-shell] 使用指定版本 ${nextVersion}(本地 ${localVersion} / OSS ${remoteVersion ?? '不存在'})`
|
||||
: `[ai-game-creator-shell] 版本 ${localVersion} / OSS ${remoteVersion ?? '不存在'} -> ${nextVersion}`,
|
||||
);
|
||||
return nextVersion;
|
||||
}
|
||||
|
||||
export function assertVersionCommitted() {
|
||||
const repoPaths = versionFileSources.map((source) =>
|
||||
path.relative(repoRoot, source.file).replaceAll('\\', '/'),
|
||||
);
|
||||
const changed =
|
||||
spawnSync(
|
||||
'git',
|
||||
['diff', '--quiet', 'HEAD', '--', ...repoPaths],
|
||||
{ cwd: repoRoot },
|
||||
).status === 1;
|
||||
if (changed) {
|
||||
throw new Error(
|
||||
'版本文件相对 HEAD 存在未提交改动,请先提交后再发布:运行 npm --prefix apps/ai-game-creator-shell run bump-version -- --commit',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
export function prepareReleaseVersion() {
|
||||
const localVersion = readLocalVersion();
|
||||
validateVersionConsistency(localVersion);
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 使用仓库版本 ${localVersion}(不再自动递增或自由指定版本)`,
|
||||
);
|
||||
return localVersion;
|
||||
}
|
||||
|
||||
export async function assertVersionNotBelowOss(version) {
|
||||
const remoteVersion = await readRemoteVersion();
|
||||
if (remoteVersion && compareVersions(version, remoteVersion) < 0) {
|
||||
throw new Error(
|
||||
`仓库版本 ${version} 低于线上 OSS 版本 ${remoteVersion}。请先运行 npm --prefix apps/ai-game-creator-shell run bump-version 提升版本后再发布。`,
|
||||
);
|
||||
}
|
||||
console.log(
|
||||
`[ai-game-creator-shell] 线上 OSS 版本 ${remoteVersion ?? '不存在'},发布版本 ${version}`,
|
||||
);
|
||||
}
|
||||
|
||||
export function runTauriBuild(args = []) {
|
||||
const noBundle = args.includes('--no-bundle');
|
||||
const hasTarget = args.includes('--target');
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { test } from 'node:test';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
import {
|
||||
bumpVersion,
|
||||
compareVersions,
|
||||
createUpdateManifest,
|
||||
nextPatchVersion,
|
||||
selectReleaseArtifact,
|
||||
} from './build-release.mjs';
|
||||
|
||||
test('selects an explicit release artifact when configured', () => {
|
||||
const artifactPath = new URL('../package.json', import.meta.url).pathname;
|
||||
const artifactPath = fileURLToPath(
|
||||
new URL('../package.json', import.meta.url),
|
||||
);
|
||||
const previous = process.env.AGC_UPDATE_ARTIFACT;
|
||||
process.env.AGC_UPDATE_ARTIFACT = artifactPath;
|
||||
try {
|
||||
@@ -30,7 +33,7 @@ test('does not select unsupported files', () => {
|
||||
|
||||
test('manifest contains version, download URL and integrity fields', () => {
|
||||
const manifest = createUpdateManifest(
|
||||
new URL('../package.json', import.meta.url).pathname,
|
||||
fileURLToPath(new URL('../package.json', import.meta.url)),
|
||||
);
|
||||
assert.match(manifest.version, /^\d+\.\d+\.\d+$/u);
|
||||
assert.match(
|
||||
@@ -46,7 +49,7 @@ test('manifest preserves multiline release notes', () => {
|
||||
process.env.AGC_UPDATE_RELEASE_NOTES = '第一行\n第二行\r\n第三行';
|
||||
try {
|
||||
const manifest = createUpdateManifest(
|
||||
new URL('../package.json', import.meta.url).pathname,
|
||||
fileURLToPath(new URL('../package.json', import.meta.url)),
|
||||
);
|
||||
assert.equal(manifest.releaseNotes, '第一行\n第二行\r\n第三行');
|
||||
} finally {
|
||||
@@ -55,11 +58,14 @@ test('manifest preserves multiline release notes', () => {
|
||||
}
|
||||
});
|
||||
|
||||
test('next release version follows the higher local or OSS version', () => {
|
||||
test('bump version follows the requested target', () => {
|
||||
assert.equal(compareVersions('0.1.15', '0.1.12'), 1);
|
||||
assert.equal(nextPatchVersion('0.1.12', '0.1.15'), '0.1.16');
|
||||
assert.equal(nextPatchVersion('0.1.18', '0.1.15'), '0.1.19');
|
||||
assert.equal(nextPatchVersion('0.1.12', null), '0.1.13');
|
||||
assert.equal(compareVersions('0.1.12', '0.1.12'), 0);
|
||||
assert.equal(bumpVersion('0.1.19', 'patch'), '0.1.20');
|
||||
assert.equal(bumpVersion('0.1.19'), '0.1.20');
|
||||
assert.equal(bumpVersion('0.1.19', 'minor'), '0.2.0');
|
||||
assert.equal(bumpVersion('0.1.19', 'major'), '1.0.0');
|
||||
assert.equal(bumpVersion('0.1.12', '0.1.25'), '0.1.25');
|
||||
});
|
||||
|
||||
test('release upload forces overwrite for versioned artifact and latest pointer', () => {
|
||||
@@ -72,3 +78,12 @@ test('release upload forces overwrite for versioned artifact and latest pointer'
|
||||
2,
|
||||
);
|
||||
});
|
||||
|
||||
test('release upload verifies the version is committed and not below OSS', () => {
|
||||
const source = readFileSync(
|
||||
new URL('./release-upload.mjs', import.meta.url),
|
||||
'utf8',
|
||||
);
|
||||
assert.match(source, /assertVersionCommitted\(\)/u);
|
||||
assert.match(source, /assertVersionNotBelowOss\(/u);
|
||||
});
|
||||
|
||||
@@ -0,0 +1,121 @@
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const appRoot = fileURLToPath(new URL('..', import.meta.url));
|
||||
const repoRoot = path.resolve(appRoot, '../..');
|
||||
|
||||
const {
|
||||
bumpVersion,
|
||||
readLocalVersion,
|
||||
writeVersionFiles,
|
||||
} = await import('./build-release.mjs');
|
||||
|
||||
const versionFiles = [
|
||||
'apps/ai-game-creator-shell/package.json',
|
||||
'package-lock.json',
|
||||
'apps/ai-game-creator-shell/src-tauri/tauri.conf.json',
|
||||
'apps/ai-game-creator-shell/src-tauri/Cargo.toml',
|
||||
'apps/ai-game-creator-shell/src-tauri/Cargo.lock',
|
||||
];
|
||||
|
||||
function parseArgs(argv) {
|
||||
const args = argv.slice(2);
|
||||
const explicitIndex = args.indexOf('--version');
|
||||
const explicit = explicitIndex >= 0 ? args[explicitIndex + 1] : null;
|
||||
const target =
|
||||
explicit ??
|
||||
args.find((arg) => arg === 'patch' || arg === 'minor' || arg === 'major') ??
|
||||
'patch';
|
||||
return { target, commit: args.includes('--commit') };
|
||||
}
|
||||
|
||||
function runGit(args) {
|
||||
const result = spawnSync('git', args, { cwd: repoRoot, stdio: 'inherit' });
|
||||
if (result.error) throw result.error;
|
||||
return result.status ?? 1;
|
||||
}
|
||||
|
||||
function hasUncommittedVersionChanges() {
|
||||
return (
|
||||
spawnSync('git', ['diff', '--quiet', '--', ...versionFiles], {
|
||||
cwd: repoRoot,
|
||||
}).status === 1
|
||||
);
|
||||
}
|
||||
|
||||
function otherStagedFiles() {
|
||||
const result = spawnSync(
|
||||
'git',
|
||||
['diff', '--cached', '--name-only'],
|
||||
{ cwd: repoRoot, encoding: 'utf8' },
|
||||
);
|
||||
if (result.status !== 0) {
|
||||
throw new Error('无法读取已暂存文件列表');
|
||||
}
|
||||
const versionSet = new Set(versionFiles);
|
||||
return result.stdout
|
||||
.split('\n')
|
||||
.map((file) => file.trim())
|
||||
.filter(Boolean)
|
||||
.filter((file) => !versionSet.has(file));
|
||||
}
|
||||
|
||||
const { target, commit } = parseArgs(process.argv);
|
||||
|
||||
// 提交前先确认没有其他已暂存改动,避免把无关改动一并提交;若存在则在改动任何文件前中止。
|
||||
if (commit) {
|
||||
const others = otherStagedFiles();
|
||||
if (others.length > 0) {
|
||||
console.error(
|
||||
`[bump-version] 检测到其他已暂存改动,为避免误提交,请先单独处理后再运行 --commit:\n ${others.join('\n ')}`,
|
||||
);
|
||||
console.error(
|
||||
'提示:用 git restore --staged <file> 取消暂存,或先提交这些改动。',
|
||||
);
|
||||
process.exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
const current = readLocalVersion();
|
||||
|
||||
// 若版本文件已带着一次未提交的提升(例如先默认跑过一次),再 --commit 时不再重复递增,直接提交现有改动。
|
||||
const next =
|
||||
commit && hasUncommittedVersionChanges()
|
||||
? current
|
||||
: bumpVersion(current, target);
|
||||
|
||||
writeVersionFiles(next);
|
||||
|
||||
if (!commit) {
|
||||
console.log(
|
||||
`[bump-version] 版本 ${current} -> ${next}(已写入版本文件,未创建提交;如需提交加 --commit)`,
|
||||
);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const addStatus = runGit(['add', ...versionFiles]);
|
||||
if (addStatus !== 0) process.exit(addStatus);
|
||||
|
||||
const hasDiff =
|
||||
spawnSync('git', ['diff', '--cached', '--quiet'], {
|
||||
cwd: repoRoot,
|
||||
}).status === 1;
|
||||
|
||||
if (!hasDiff) {
|
||||
console.log(`[bump-version] 版本未变化(已是 ${current}),未创建提交`);
|
||||
process.exit(0);
|
||||
}
|
||||
|
||||
const commitStatus = runGit([
|
||||
'commit',
|
||||
'-m',
|
||||
`提升 AGC 版本至 ${next}`,
|
||||
'-m',
|
||||
`- AGC 客户端版本提升至 ${next}`,
|
||||
'-m',
|
||||
'- 同步更新 package.json、根 package-lock.json、tauri.conf.json、Cargo.toml、Cargo.lock 中的 AGC 包条目',
|
||||
]);
|
||||
if (commitStatus !== 0) process.exit(commitStatus);
|
||||
|
||||
console.log(`[bump-version] 已提交版本 ${next}(本地提交,未推送)`);
|
||||
@@ -9,8 +9,13 @@ if (!/^[a-z0-9][a-z0-9.-]{1,62}$/u.test(bucket) || /[\r\n\0]/u.test(endpoint)) {
|
||||
}
|
||||
process.env.AGC_UPDATE_OSS_BASE_URL ||= `https://${bucket}.${endpoint}/agc`;
|
||||
|
||||
const { generateUpdateManifest, prepareReleaseVersion, runTauriBuild } =
|
||||
await import('./build-release.mjs');
|
||||
const {
|
||||
assertVersionCommitted,
|
||||
assertVersionNotBelowOss,
|
||||
generateUpdateManifest,
|
||||
prepareReleaseVersion,
|
||||
runTauriBuild,
|
||||
} = await import('./build-release.mjs');
|
||||
|
||||
function runOssutil(args) {
|
||||
const binary = process.env.OSSUTIL_BIN?.trim() || 'ossutil';
|
||||
@@ -36,7 +41,9 @@ function runOssutil(args) {
|
||||
if (result.status !== 0) process.exit(result.status ?? 1);
|
||||
}
|
||||
|
||||
await prepareReleaseVersion();
|
||||
const releaseVersion = await prepareReleaseVersion();
|
||||
assertVersionCommitted();
|
||||
await assertVersionNotBelowOss(releaseVersion);
|
||||
runTauriBuild([]);
|
||||
const { artifact, manifestPath, manifest } = generateUpdateManifest();
|
||||
const artifactKey = `agc/${manifest.version}/${path.basename(artifact)}`;
|
||||
|
||||
+1
-1
@@ -1703,7 +1703,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.19"
|
||||
dependencies = [
|
||||
"agent-runtime-core",
|
||||
"axum",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "genarrative-ai-game-creator-shell"
|
||||
version = "0.1.12"
|
||||
version = "0.1.19"
|
||||
edition = "2021"
|
||||
publish = false
|
||||
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
+9
-10
@@ -1,22 +1,21 @@
|
||||
---
|
||||
name: agc-web-game-development
|
||||
description: Build or modify a playable npm-managed Phaser 4 web game in the current AGC project. Use for gameplay creation, bug fixes, UI or layout changes, responsive behavior, asset integration, controls, scoring, reset flows, and other HTML, CSS, JavaScript, DOM, Canvas, or WebGL work.
|
||||
description: Build or modify a playable web game in the current AGC project. Use for gameplay creation, bug fixes, UI or layout changes, responsive behavior, asset integration, controls, scoring, reset flows, and other HTML, CSS, JavaScript, DOM, Canvas, or WebGL work.
|
||||
---
|
||||
|
||||
# AGC Web Game Development
|
||||
|
||||
Implement the user's actual game request in the current project as an npm-managed Phaser 4.2.1 game. Use Phaser scenes for gameplay and DOM only for deliberately external UI.
|
||||
Implement the user's actual game request in the current project. Choose DOM, Canvas, WebGL, or a combination based on the game rather than a fixed code template.
|
||||
|
||||
## Workflow
|
||||
|
||||
1. Read the existing package and source files before editing. New projects place `package.json`, `index.html`, `style.css`, and `game.js` under `game/`; existing root packages retain their layout. Run npm in that package directory (for example `npm --prefix game ci` and `npm --prefix game run build`).
|
||||
2. Keep `package.json` and `package-lock.json` authoritative. Import Phaser with `import Phaser from 'phaser'`; do not copy a bundle, add an import map, or use a CDN. Other npm dependencies are allowed when the game needs them.
|
||||
3. Build with the project's npm script before previewing. The playable entry is the package directory's `dist/index.html`; never report an unbuilt bare-module page as playable. Import assets or configure public assets so all runtime media is included in dist; preview and exports cannot read outside it.
|
||||
4. Build a complete playable loop: visible objective, responsive input, meaningful state changes, success or failure feedback, and a reliable restart path where the game needs one.
|
||||
5. Fit the active game scene to desktop and mobile viewports without accidental page scrollbars. Reserve deliberate safe space for HUD elements instead of covering interactive content.
|
||||
6. Reuse registered Taonier art when available through `agc_tools`. Load media defensively and keep gameplay usable when an optional derivative is absent; never relabel a local placeholder as platform art.
|
||||
7. Let Phaser own the render loop and input dispatch. Avoid duplicate scenes, stale event listeners, and state that survives restart unintentionally.
|
||||
8. After a meaningful game change, use the browser playtest Skill and fix issues shown by real evidence before reporting completion.
|
||||
1. Read the existing `index.html`, `style.css`, and `game.js` before modifying an existing game.
|
||||
2. Keep the entry self-contained and runnable from the AGC loopback preview. Avoid CDN-only dependencies and network-required runtime assets.
|
||||
3. Build a complete playable loop: visible objective, responsive input, meaningful state changes, success or failure feedback, and a reliable restart path where the game needs one.
|
||||
4. Fit the active game scene to desktop and mobile viewports without accidental page scrollbars. Reserve deliberate safe space for HUD elements instead of covering interactive content.
|
||||
5. Reuse registered Taonier art when available through `agc_tools`. Load media defensively and keep gameplay usable when an optional derivative is absent; never relabel a local placeholder as platform art.
|
||||
6. Avoid undefined animation callbacks, duplicate loops, stale event listeners, and state that survives restart unintentionally.
|
||||
7. After a meaningful game change, use the browser playtest Skill and fix issues shown by real evidence before reporting completion.
|
||||
|
||||
When implementing a new game loop or a broad gameplay revision, read `references/game-quality-checklist.md`.
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
interface:
|
||||
display_name: "Web 游戏实现"
|
||||
short_description: "在当前项目内设计、实现并验证 npm 管理的 Phaser 4 游戏"
|
||||
short_description: "在当前项目内设计、实现并验证可玩的 HTML、CSS 与 JavaScript 游戏"
|
||||
default_prompt: "Use $agc-web-game-development to build or modify the current playable web game."
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"schemaVersion": "agc-skill-pack.v1",
|
||||
"version": "2026-08-26.12",
|
||||
"version": "2026-08-26.10",
|
||||
"skills": [
|
||||
{
|
||||
"name": "agc-project-structure",
|
||||
@@ -57,7 +57,7 @@
|
||||
"agents/openai.yaml",
|
||||
"references/game-quality-checklist.md"
|
||||
],
|
||||
"sha256": "0649c72dd53e05ad7c87b28def1397c2badf61b0c308091196c40f7c48a8b36a"
|
||||
"sha256": "d7748d9ebf4324add0541daf16a2bbec09c4862b85af55bfb369c7f3b99aedff"
|
||||
},
|
||||
{
|
||||
"name": "agc-browser-playtest",
|
||||
|
||||
@@ -266,7 +266,6 @@ fn game_creator_codex_app_server_connection_error(
|
||||
) -> platform_llm::LlmError {
|
||||
match game_creator_codex_app_server_error_http_status(info, field) {
|
||||
Some(401 | 403) => game_creator_codex_app_server_error_kind("unauthorized"),
|
||||
Some(413) => game_creator_codex_app_server_error_kind("request-too-large"),
|
||||
Some(status_code) => platform_llm::LlmError::Upstream {
|
||||
status_code,
|
||||
message: "Codex app-server 连接上游失败".to_string(),
|
||||
@@ -304,30 +303,6 @@ fn game_creator_codex_app_server_error_detail_indicates_auth_failure(
|
||||
|| detail.contains("http 403")
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail_indicates_request_too_large(
|
||||
error: &serde_json::Value,
|
||||
) -> bool {
|
||||
let Some(error) = error.as_object() else {
|
||||
return false;
|
||||
};
|
||||
let detail = ["message", "additionalDetails", "code"]
|
||||
.into_iter()
|
||||
.filter_map(|field| error.get(field).and_then(serde_json::Value::as_str))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ")
|
||||
.to_ascii_lowercase();
|
||||
if detail.is_empty() {
|
||||
return false;
|
||||
}
|
||||
detail.contains("413 payload too large")
|
||||
|| detail.contains("http 413")
|
||||
|| detail.contains("status 413")
|
||||
|| detail.contains("payload_too_large")
|
||||
|| detail.contains("payload too large")
|
||||
|| detail.contains("request too large")
|
||||
|| detail.contains("provider request too large")
|
||||
}
|
||||
|
||||
fn game_creator_codex_app_server_error_detail_indicates_insufficient_mud_points(
|
||||
error: &serde_json::Value,
|
||||
) -> bool {
|
||||
@@ -358,9 +333,6 @@ fn game_creator_codex_app_server_failed_turn_error(
|
||||
message: "泥点余额不足".to_string(),
|
||||
};
|
||||
}
|
||||
if game_creator_codex_app_server_error_detail_indicates_request_too_large(error) {
|
||||
return game_creator_codex_app_server_error_kind("request-too-large");
|
||||
}
|
||||
if game_creator_codex_app_server_error_detail_indicates_auth_failure(error) {
|
||||
return game_creator_codex_app_server_error_kind("unauthorized");
|
||||
}
|
||||
@@ -1330,13 +1302,12 @@ fn codex_app_server_turn_start_params(
|
||||
"approvalPolicy": approval_policy,
|
||||
});
|
||||
if workspace_mode.allows_workspace_writes() {
|
||||
// npm install/build must resolve project dependencies. Network access
|
||||
// is enabled only for DirectProject; writableRoots keeps the file-write
|
||||
// boundary at the real game workspace.
|
||||
// Native project commands stay offline and remain bounded to the
|
||||
// real game workspace.
|
||||
params["sandboxPolicy"] = serde_json::json!({
|
||||
"type": "workspaceWrite",
|
||||
"writableRoots": [workspace_path],
|
||||
"networkAccess": true
|
||||
"networkAccess": false
|
||||
});
|
||||
}
|
||||
params
|
||||
@@ -2120,9 +2091,6 @@ impl CodexAppServerConnection {
|
||||
if workspace_mode == CodexAppServerWorkspaceMode::DirectProject && llm.web_search_enabled {
|
||||
command.env(DIRECT_TOOLS_MCP_CONTROLLED_WEB_SEARCH_ENV, "1");
|
||||
}
|
||||
if workspace_mode == CodexAppServerWorkspaceMode::DirectProject {
|
||||
command.env("npm_config_cache", workspace_path.join(".npm-cache"));
|
||||
}
|
||||
command
|
||||
.env("CODEX_HOME", &isolated_codex_home)
|
||||
.env("HOME", &isolated_os_home)
|
||||
@@ -4526,7 +4494,7 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
turn.pointer("/sandboxPolicy/networkAccess"),
|
||||
Some(&serde_json::json!(true))
|
||||
Some(&serde_json::json!(false))
|
||||
);
|
||||
let authority_paths = [
|
||||
turn.get("cwd"),
|
||||
@@ -4819,12 +4787,6 @@ mod tests {
|
||||
"codex-app-server-error:unauthorized".to_string(),
|
||||
),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"httpConnectionFailed":{"httpStatusCode":413}}),
|
||||
platform_llm::LlmError::InvalidRequest(
|
||||
"codex-app-server-error:request-too-large".to_string(),
|
||||
),
|
||||
),
|
||||
(
|
||||
serde_json::json!({"httpConnectionFailed":{"httpStatusCode":429}}),
|
||||
platform_llm::LlmError::Upstream {
|
||||
@@ -4885,31 +4847,6 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_app_server_failed_turn_maps_request_too_large_details() {
|
||||
for detail in [
|
||||
"HTTP 413 Payload Too Large",
|
||||
"status 413",
|
||||
"PAYLOAD_TOO_LARGE",
|
||||
"provider request too large",
|
||||
] {
|
||||
let error = game_creator_codex_app_server_failed_turn_error(&serde_json::json!({
|
||||
"status": "failed",
|
||||
"error": {
|
||||
"message": detail,
|
||||
"additionalDetails": "private upstream diagnostics",
|
||||
"codexErrorInfo": "other"
|
||||
}
|
||||
}));
|
||||
assert_eq!(
|
||||
error,
|
||||
platform_llm::LlmError::InvalidRequest(
|
||||
"codex-app-server-error:request-too-large".to_string(),
|
||||
)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn codex_app_server_failed_turn_maps_insufficient_mud_points_to_stable_upstream_error() {
|
||||
for detail in [
|
||||
|
||||
@@ -10,7 +10,7 @@ const MAX_DIRECT_SYSTEM_PROMPT_CHARS: usize = 16 * 1024;
|
||||
const MIN_DIRECT_CLIENT_TURN_ID_CHARS: usize = 6;
|
||||
const MAX_DIRECT_CLIENT_TURN_ID_CHARS: usize = 160;
|
||||
const DIRECT_TAONIER_IDENTITY_GUIDANCE: &str = "对外身份合同:你是“陶泥儿”,是 Genarrative 的游戏创作助手。用户询问你是谁、你的名称或能力时,以陶泥儿的身份回答;不要把 Codex、ChatGPT、OpenAI、模型、通用 AI 助手或内部执行智能体当作自己的名称或对外身份。Codex app-server 仅是客户端内部执行技术;只有用户明确询问底层实现时才可如实说明,同时仍以陶泥儿自称。";
|
||||
const DIRECT_AGC_ENGINEERING_GUIDANCE: &str = "AGC 工程合同:当前 cwd 是用户选择的项目目录。新 Web 游戏使用 npm + Vite,Phaser 固定为 4.2.1,在 `game.js` 或模块中使用 `import Phaser from 'phaser'`;可以按需使用其它 npm 依赖,不得复制 Phaser bundle、使用 import map 或 CDN。先读取当前 cwd 下适用的 AGENTS.md、README 或项目说明。源码使用 cwd 相对路径,例如 `index.html`、`style.css`、`game.js`、`package.json`、`package-lock.json`、`assets/hero.png`;依赖安装与构建使用项目自己的 npm scripts,完成后必须从 `dist/index.html` 试玩。 原生文件工具、patch 和命令参数使用 cwd 相对路径,例如 `index.html`、`style.css`、`game.js`、`assets/hero.png`;如果 Codex 原生文件修改不可用,可以按需用客户端 `agc_write_file` 把文本写入项目相对路径。调用 `agc_write_file` 时,content 必须是目标文件的完整原始 UTF-8 正文;不得把 command.exec 的 Exit code、Wall time、Output 包装、终端日志或解释文字一起复制进 content,命令结果只能用于判断,不能当作文件正文。`../`、绝对路径、`.agent/`、`.git/`、密钥文件和 Runtime 控制面属于客户端边界,不能请求扩权或直接改写。DirectProject 提供 Codex 原生文件、搜索、命令、图片查看、Skill、经客户端注入的 `agc_tools` MCP,以及客户端扩展列表中用户已启用的第三方 MCP。用户明确指定第三方 MCP Server 或工具时,先在当前可用工具中查找并直接调用;找不到时如实说明,不得伪造。你可以按需选择这些能力:`agc_write_file` 写入代码、配置、资源依赖清单或说明文件;`agc_generate_image` 生成普通图片、角色图、视觉规范图(icon-spec)、UI 设计图或发布宣传图;`agc_edit_image` 修改已登记图片;`taonier_prepare_game_art` 准备完整游戏美术包及可用的 canonical 切片;`agc_list_registered_assets`、`agc_list_project_files`、`agc_list_account_assets`、`agc_import_account_assets` 用于发现和接入资源依赖;`agc_create_or_derive_resource` 用于视频、角色动画、音效或背景音乐;`agc_browser_playtest` 用于需要时的本地试玩观察;Skill references 按需使用相对路径直接读取。切图、资源依赖、规范图和试玩都只是可选工具提示,不要求调用、固定顺序或特定产物,AGC 不会据此替你拆任务、编排 DAG、做强验收或阻止继续执行;不要等待 Supervisor、harness 或宿主规划器。不要读取或输出凭据、Token、Cookie、auth.json、.env 或宿主私密路径;项目锁、付费提交、幂等键、下载校验和客户端投影由客户端处理。游戏文件真实变化后客户端可登记资源和版本,Codex 不直接保存或伪造项目版本。";
|
||||
const DIRECT_AGC_ENGINEERING_GUIDANCE: &str = "AGC 工程合同(仅说明项目边界,不是流程门槛):当前 Codex cwd 是用户选择的项目目录(工作区根),源码、素材、音效和其它资源按项目现有结构放置;先按需读取当前 cwd 下适用的 `AGENTS.md`、README 或项目说明,把它们当作项目规范参考。原生文件工具、patch 和命令参数使用 cwd 相对路径,例如 `index.html`、`style.css`、`game.js`、`assets/hero.png`;如果 Codex 原生文件修改不可用,可以按需用客户端 `agc_write_file` 把文本写入项目相对路径。调用 `agc_write_file` 时,content 必须是目标文件的完整原始 UTF-8 正文;不得把 command.exec 的 Exit code、Wall time、Output 包装、终端日志或解释文字一起复制进 content,命令结果只能用于判断,不能当作文件正文。`../`、绝对路径、`.agent/`、`.git/`、密钥文件和 Runtime 控制面属于客户端边界,不能请求扩权或直接改写。DirectProject 提供 Codex 原生文件、搜索、命令、图片查看、Skill、经客户端注入的 `agc_tools` MCP,以及客户端扩展列表中用户已启用的第三方 MCP。用户明确指定第三方 MCP Server 或工具时,先在当前可用工具中查找并直接调用;找不到时如实说明,不得伪造。你可以按需选择这些能力:`agc_write_file` 写入代码、配置、资源依赖清单或说明文件;`agc_generate_image` 生成普通图片、角色图、视觉规范图(icon-spec)、UI 设计图或发布宣传图;`agc_edit_image` 修改已登记图片;`taonier_prepare_game_art` 准备完整游戏美术包及可用的 canonical 切片;`agc_list_registered_assets`、`agc_list_project_files`、`agc_list_account_assets`、`agc_import_account_assets` 用于发现和接入资源依赖;`agc_create_or_derive_resource` 用于视频、角色动画、音效或背景音乐;`agc_browser_playtest` 用于需要时的本地试玩观察;Skill references 按需使用相对路径直接读取。切图、资源依赖、规范图和试玩都只是可选工具提示,不要求调用、固定顺序或特定产物,AGC 不会据此替你拆任务、编排 DAG、做强验收或阻止继续执行;不要等待 Supervisor、harness 或宿主规划器。不要读取或输出凭据、Token、Cookie、auth.json、.env 或宿主私密路径;项目锁、付费提交、幂等键、下载校验和客户端投影由客户端处理。游戏文件真实变化后客户端可登记资源和版本,Codex 不直接保存或伪造项目版本。";
|
||||
const DIRECT_CODEX_ART_SPEC_ASSET_PATH: &str = "assets/art-spec.png";
|
||||
const DIRECT_CODEX_BACKGROUND_ASSET_PATH: &str = "assets/direct-game-background.png";
|
||||
const DIRECT_CODEX_SPRITESHEET_ASSET_PATH: &str = "assets/art-spritesheet.png";
|
||||
@@ -72,21 +72,6 @@ fn direct_codex_game_outputs(root: &Path) -> Vec<(String, &'static str, &'static
|
||||
(entry.to_string(), "game-entry", "text/html"),
|
||||
(format!("{prefix}style.css"), "game-style", "text/css"),
|
||||
(format!("{prefix}game.js"), "game-script", "text/javascript"),
|
||||
(
|
||||
format!("{prefix}package.json"),
|
||||
"game-package",
|
||||
"application/json",
|
||||
),
|
||||
(
|
||||
format!("{prefix}package-lock.json"),
|
||||
"game-lockfile",
|
||||
"application/json",
|
||||
),
|
||||
(
|
||||
format!("{prefix}vite.config.js"),
|
||||
"game-build-config",
|
||||
"text/javascript",
|
||||
),
|
||||
]
|
||||
}
|
||||
|
||||
@@ -3199,14 +3184,7 @@ fn direct_codex_generated_source() -> GameCreationAppAssetSource {
|
||||
|
||||
fn direct_codex_output_fingerprint(root: &Path) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
let mut paths: Vec<String> = direct_codex_game_outputs(root)
|
||||
.into_iter()
|
||||
.map(|(p, _, _)| p)
|
||||
.collect();
|
||||
paths.extend(direct_npm_source_paths(root));
|
||||
paths.sort();
|
||||
paths.dedup();
|
||||
for local_path in paths {
|
||||
for (local_path, _, _) in direct_codex_game_outputs(root) {
|
||||
hasher.update(local_path.as_bytes());
|
||||
hasher.update([0]);
|
||||
let path = root.join(local_path);
|
||||
@@ -3222,70 +3200,6 @@ fn direct_codex_output_fingerprint(root: &Path) -> String {
|
||||
format!("{:x}", hasher.finalize())
|
||||
}
|
||||
|
||||
fn direct_npm_source_paths(root: &Path) -> Vec<String> {
|
||||
let base = if root.join("package.json").is_file() {
|
||||
root.to_path_buf()
|
||||
} else if root.join("game/package.json").is_file() {
|
||||
root.join("game")
|
||||
} else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut output = Vec::new();
|
||||
let mut pending = vec![(base, 0usize)];
|
||||
let mut inspected = 0usize;
|
||||
while let Some((directory, depth)) = pending.pop() {
|
||||
if depth > 16 || inspected >= 4096 {
|
||||
break;
|
||||
}
|
||||
let Ok(entries) = fs::read_dir(directory) else {
|
||||
continue;
|
||||
};
|
||||
for entry in entries.flatten() {
|
||||
inspected += 1;
|
||||
if inspected > 4096 {
|
||||
break;
|
||||
}
|
||||
let name = entry.file_name().to_string_lossy().to_ascii_lowercase();
|
||||
if name.starts_with('.')
|
||||
|| matches!(
|
||||
name.as_str(),
|
||||
"node_modules"
|
||||
| "dist"
|
||||
| "target"
|
||||
| "memory"
|
||||
| "exports"
|
||||
| "auth.json"
|
||||
| "credentials.json"
|
||||
| "game-creator.config.json"
|
||||
| "game-creator.config.local.json"
|
||||
)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let Ok(kind) = entry.file_type() else {
|
||||
continue;
|
||||
};
|
||||
let path = entry.path();
|
||||
if kind.is_dir() {
|
||||
pending.push((path, depth + 1));
|
||||
} else if kind.is_file()
|
||||
&& matches!(
|
||||
path.extension().and_then(|e| e.to_str()),
|
||||
Some("js" | "mjs" | "cjs" | "ts" | "tsx" | "jsx" | "css" | "html" | "json")
|
||||
)
|
||||
{
|
||||
if let Ok(relative) = path.strip_prefix(root) {
|
||||
if let Some(value) = relative.to_str() {
|
||||
output.push(value.replace('\\', "/"));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
output.sort();
|
||||
output
|
||||
}
|
||||
|
||||
fn direct_browser_evidence_root(root: &Path, attempt: usize) -> Result<std::path::PathBuf, String> {
|
||||
let revision = read_game_creator_agent_runtime_project_revision(root)
|
||||
.map(|value| value.revision)
|
||||
@@ -3717,34 +3631,6 @@ fn sync_direct_codex_project_file_projection_at(
|
||||
)?;
|
||||
registered += 1;
|
||||
}
|
||||
for local_path in direct_npm_source_paths(root) {
|
||||
if direct_codex_game_outputs(root)
|
||||
.iter()
|
||||
.any(|(p, _, _)| p == &local_path)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if root.join(&local_path).is_file() {
|
||||
let media_type = if local_path.ends_with(".css") {
|
||||
"text/css"
|
||||
} else if local_path.ends_with(".json") {
|
||||
"application/json"
|
||||
} else if local_path.ends_with(".html") {
|
||||
"text/html"
|
||||
} else {
|
||||
"text/javascript"
|
||||
};
|
||||
register_local_asset_at(
|
||||
root,
|
||||
&local_path,
|
||||
"game-source",
|
||||
media_type,
|
||||
"direct-codex",
|
||||
direct_codex_generated_source(),
|
||||
)?;
|
||||
registered += 1;
|
||||
}
|
||||
}
|
||||
if registered == 0 {
|
||||
return Err("Codex 返回后没有可登记的游戏文件".to_string());
|
||||
}
|
||||
@@ -7457,7 +7343,7 @@ mod tests {
|
||||
assert_eq!(manifest.versions.len(), 1);
|
||||
assert_eq!(manifest.versions[0].version_id, "initial-1");
|
||||
assert_eq!(manifest.versions[0].project_revision, 1);
|
||||
assert_eq!(manifest.versions[0].resource_bindings.len(), 13);
|
||||
assert_eq!(manifest.versions[0].resource_bindings.len(), 10);
|
||||
for expected_path in DIRECT_CODEX_ART_ASSET_PATHS.into_iter().chain(
|
||||
DIRECT_CODEX_SPRITESHEET_SLICE_PATHS
|
||||
.iter()
|
||||
@@ -7494,7 +7380,7 @@ mod tests {
|
||||
.expect("project revision");
|
||||
assert_eq!(revision.revision, 2);
|
||||
let manifest = read_manifest(&root.path().join(".agent/manifest.json")).expect("manifest");
|
||||
assert_eq!(manifest.assets.len(), 13);
|
||||
assert_eq!(manifest.assets.len(), 10);
|
||||
assert_eq!(
|
||||
manifest
|
||||
.assets
|
||||
@@ -7514,7 +7400,7 @@ mod tests {
|
||||
manifest.versions[1].created_reason,
|
||||
GameIterationVersionCreatedReason::AgentRevision
|
||||
);
|
||||
assert_eq!(manifest.versions[1].resource_bindings.len(), 13);
|
||||
assert_eq!(manifest.versions[1].resource_bindings.len(), 10);
|
||||
|
||||
let unchanged_fingerprint = direct_codex_output_fingerprint(root.path());
|
||||
sync_direct_codex_project_outputs_at(root.path(), Some(&unchanged_fingerprint))
|
||||
@@ -8398,36 +8284,3 @@ mod tests {
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod npm_source_projection_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn npm_sources_track_nested_modules_but_ignore_dependencies_and_private_files() {
|
||||
for nested in [false, true] {
|
||||
let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap();
|
||||
let source = if nested {
|
||||
root.path().join("game")
|
||||
} else {
|
||||
root.path().to_path_buf()
|
||||
};
|
||||
fs::create_dir_all(source.join("src/scenes")).unwrap();
|
||||
fs::create_dir_all(source.join("node_modules/demo")).unwrap();
|
||||
fs::create_dir_all(source.join(".npm-cache")).unwrap();
|
||||
fs::write(source.join("package.json"), "{}").unwrap();
|
||||
fs::write(source.join("src/scenes/play.ts"), "export const value = 1;").unwrap();
|
||||
fs::write(source.join("node_modules/demo/index.js"), "private dep").unwrap();
|
||||
fs::write(source.join(".npm-cache/auth.json"), "private cache").unwrap();
|
||||
let paths = direct_npm_source_paths(root.path());
|
||||
let prefix = if nested { "game/" } else { "" };
|
||||
assert!(paths.contains(&format!("{prefix}src/scenes/play.ts")));
|
||||
assert!(!paths
|
||||
.iter()
|
||||
.any(|path| path.contains("node_modules") || path.contains(".npm-cache")));
|
||||
let before = direct_codex_output_fingerprint(root.path());
|
||||
fs::write(source.join("src/scenes/play.ts"), "export const value = 2;").unwrap();
|
||||
assert_ne!(direct_codex_output_fingerprint(root.path()), before);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ pub(crate) use draft_validation::{
|
||||
validate_llm_agent_handoffs, validate_llm_game_draft, validate_non_placeholder_game_html,
|
||||
validate_playable_game_html, validate_safe_game_html_runtime,
|
||||
};
|
||||
pub(crate) use draft_writer::{ensure_legacy_json_generator_project, write_local_game_draft_at};
|
||||
pub(crate) use draft_writer::write_local_game_draft_at;
|
||||
#[allow(unused_imports)]
|
||||
pub(crate) use loop_orchestration::{
|
||||
emit_agent_progress, game_creator_agent_llm_error_is_mud_points_insufficient,
|
||||
|
||||
@@ -9,8 +9,8 @@ pub(crate) fn write_local_game_draft_at(
|
||||
if prompt.is_empty() {
|
||||
return Err("创作想法不能为空".to_string());
|
||||
}
|
||||
ensure_legacy_json_generator_project(root)?;
|
||||
validate_llm_game_draft(prompt, draft)?;
|
||||
init_local_game_project_at(root, "local-project-draft", "未命名游戏原型")?;
|
||||
let checkpoint = create_local_project_checkpoint_at(root)?;
|
||||
let timestamp = unix_timestamp();
|
||||
let title = draft.title.trim();
|
||||
@@ -134,38 +134,3 @@ pub(crate) fn write_local_game_draft_at(
|
||||
manifest,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn ensure_legacy_json_generator_project(root: &Path) -> Result<(), String> {
|
||||
if root.join("game/package.json").exists()
|
||||
|| root.join("package.json").exists()
|
||||
|| !root.join("game/index.html").is_file()
|
||||
|| !root.join(".agent/manifest.json").is_file()
|
||||
{
|
||||
return Err("JSON Generator 仅支持已有的单文件 HTML 项目;新建游戏与 npm / Phaser 4 项目请使用 DirectProject 完成依赖安装、构建和试玩".to_string());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod legacy_generator_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn legacy_generator_rejects_npm_before_writing() {
|
||||
let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap();
|
||||
fs::create_dir_all(root.path().join("game")).unwrap();
|
||||
fs::create_dir_all(root.path().join(".agent")).unwrap();
|
||||
fs::write(root.path().join("game/index.html"), "legacy source").unwrap();
|
||||
fs::write(root.path().join(".agent/manifest.json"), "{}").unwrap();
|
||||
assert!(ensure_legacy_json_generator_project(root.path()).is_ok());
|
||||
fs::write(root.path().join("game/package.json"), "{}").unwrap();
|
||||
assert!(ensure_legacy_json_generator_project(root.path())
|
||||
.unwrap_err()
|
||||
.contains("DirectProject"));
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("game/index.html")).unwrap(),
|
||||
"legacy source"
|
||||
);
|
||||
assert!(!root.path().join(".agent/spec.md").exists());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -44,7 +44,6 @@ pub(crate) async fn run_game_creator_agent_loop_at(
|
||||
project_blackboard: &str,
|
||||
progress: Option<&AgentProgressEmitter<'_>>,
|
||||
) -> Result<GameCreatorAgentLoopResult, String> {
|
||||
ensure_legacy_json_generator_project(root)?;
|
||||
let spec_path = root.join(".agent/spec.md");
|
||||
let findings_path = root.join(".agent/findings.md");
|
||||
let run_id = format!("game-generate-draft-{}", unix_millis());
|
||||
|
||||
@@ -24,7 +24,6 @@ JSON schema:
|
||||
}
|
||||
|
||||
gameHtml 规则:
|
||||
- 此 JSON 协议仅用于已有的单文件 HTML 项目;npm / Phaser 项目必须使用 DirectProject,不能通过 gameHtml 交付 package.json 或模块源码。
|
||||
- 必须是单文件 HTML,不能加载远程脚本、远程图片、远程 CSS 或 CDN。
|
||||
- 必须包含 canvas、canvas getContext、实际绘制调用、键盘或鼠标输入、requestAnimationFrame 主循环、目标、失败或胜利状态、R 或按钮重开。
|
||||
- JavaScript 不要 eval、Function、localStorage、fetch、WebSocket、ServiceWorker。
|
||||
|
||||
@@ -294,7 +294,6 @@ pub(crate) async fn generate_local_game_draft_at(
|
||||
if prompt.is_empty() {
|
||||
return Err("创作想法不能为空".to_string());
|
||||
}
|
||||
ensure_legacy_json_generator_project(root)?;
|
||||
|
||||
init_local_game_project_at(root, "local-project-draft", "未命名游戏原型")?;
|
||||
let short_memory = read_optional_text(&root.join("memory/session.md"))?;
|
||||
|
||||
@@ -1489,12 +1489,14 @@ const DEFAULT_GAME_INDEX_HTML: &str = r#"<!doctype html>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>Genarrative Game Draft</title>
|
||||
<style>
|
||||
body { margin: 0; display: grid; min-height: 100vh; place-items: center; background: #101827; color: #d9e7ff; font: 16px system-ui, sans-serif; }
|
||||
main { width: min(720px, calc(100vw - 32px)); }
|
||||
</style>
|
||||
</head>
|
||||
<body><main id="game"></main><script type="module" src="/game.js"></script></body>
|
||||
<body><main>还没有生成游戏。回到聊天输入创意并确认生成后,这里会写入可试玩原型。</main></body>
|
||||
</html>
|
||||
"#;
|
||||
const DEFAULT_GAME_STYLE_CSS: &str = "body { margin: 0; display: grid; min-height: 100vh; place-items: center; background: #101827; color: #d9e7ff; font: 16px system-ui, sans-serif; }\nmain { width: min(720px, calc(100vw - 32px)); }\n";
|
||||
const DEFAULT_GAME_SCRIPT_JS: &str = "import Phaser from 'phaser';\nimport './style.css';\n\nclass PlaceholderScene extends Phaser.Scene {\n create() { this.add.text(24, 24, '还没有生成游戏。回到聊天输入创意并确认生成后,这里会写入可试玩原型。'); }\n}\n\nnew Phaser.Game({ type: Phaser.AUTO, width: 720, height: 420, parent: 'game', scene: PlaceholderScene });\n";
|
||||
|
||||
const DEFAULT_EDITOR_BASE_URL: &str = "http://127.0.0.1:3000";
|
||||
const GAME_CREATOR_CONFIG_FILE_NAME: &str = "game-creator.config.json";
|
||||
|
||||
@@ -1405,14 +1405,9 @@ fn find_bytes(haystack: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
.position(|candidate| candidate == needle)
|
||||
}
|
||||
|
||||
/// npm 工程只预览构建结果;单 HTML 工程保留现有入口布局。
|
||||
/// 解析项目游戏根:项目根存在 `index.html` 时使用项目根(新布局),
|
||||
/// 否则回退到旧布局的 `game/` 子目录。
|
||||
pub(crate) fn project_game_root(root: &Path) -> PathBuf {
|
||||
if root.join("package.json").is_file() || root.join("dist/index.html").is_file() {
|
||||
return root.join("dist");
|
||||
}
|
||||
if root.join("game/package.json").is_file() || root.join("game/dist/index.html").is_file() {
|
||||
return root.join("game/dist");
|
||||
}
|
||||
if root.join("index.html").is_file() {
|
||||
root.to_path_buf()
|
||||
} else {
|
||||
@@ -1424,24 +1419,9 @@ pub(crate) fn resolve_preview_path(root: &Path, url_path: &str) -> Result<PathBu
|
||||
let path = url_path.split('?').next().unwrap_or("/");
|
||||
let decoded = percent_decode_path(path).ok_or_else(|| "预览路径非法".to_string())?;
|
||||
let relative = decoded.trim_start_matches('/');
|
||||
if !relative.is_empty()
|
||||
&& relative.split('/').any(|part| {
|
||||
part.is_empty()
|
||||
|| part == "."
|
||||
|| part == ".."
|
||||
|| part.contains('\\')
|
||||
|| part.chars().any(char::is_control)
|
||||
})
|
||||
{
|
||||
return Err("预览路径非法".to_string());
|
||||
}
|
||||
if relative.is_empty() {
|
||||
return canonical_preview_path(root, &project_game_root(root).join("index.html"));
|
||||
}
|
||||
let game_root = project_game_root(root);
|
||||
if game_root == root.join("dist") || game_root == root.join("game/dist") {
|
||||
return canonical_preview_path(root, &game_root.join(relative));
|
||||
}
|
||||
|
||||
let mut file_path = root.to_path_buf();
|
||||
let mut parts = relative.split('/');
|
||||
@@ -1476,43 +1456,6 @@ fn canonical_preview_path(root: &Path, file_path: &Path) -> Result<PathBuf, Stri
|
||||
.canonicalize()
|
||||
.map_err(|error| format!("预览文件不可用:{}: {error}", file_path.display()))?;
|
||||
|
||||
let relative_requested = file_path
|
||||
.strip_prefix(root)
|
||||
.map_err(|_| "预览路径越过项目目录".to_string())?;
|
||||
let mut checked = root.to_path_buf();
|
||||
for component in relative_requested.components() {
|
||||
if !matches!(component, std::path::Component::Normal(_)) {
|
||||
return Err("预览路径非法".to_string());
|
||||
}
|
||||
if component.as_os_str().to_str().is_some_and(|name| {
|
||||
[
|
||||
".agent",
|
||||
".git",
|
||||
".codex",
|
||||
".hermes",
|
||||
"node_modules",
|
||||
"memory",
|
||||
"exports",
|
||||
"target",
|
||||
]
|
||||
.iter()
|
||||
.any(|protected| name.eq_ignore_ascii_case(protected))
|
||||
}) {
|
||||
return Err("预览路径不能访问控制或依赖目录".to_string());
|
||||
}
|
||||
checked.push(component);
|
||||
if fs::symlink_metadata(&checked)
|
||||
.map_err(|error| error.to_string())?
|
||||
.file_type()
|
||||
.is_symlink()
|
||||
{
|
||||
return Err("预览路径不能包含符号链接".to_string());
|
||||
}
|
||||
}
|
||||
if !canonical_file.is_file() {
|
||||
return Err("预览路径必须是文件".to_string());
|
||||
}
|
||||
|
||||
// New DirectProject layouts may use the project root itself as the web
|
||||
// root. The old allow-list below only considered `game/` and `assets/`,
|
||||
// which made a valid root `index.html` resolve to a 404 even though
|
||||
@@ -1549,7 +1492,7 @@ fn canonical_preview_path(root: &Path, file_path: &Path) -> Result<PathBuf, Stri
|
||||
}
|
||||
}
|
||||
|
||||
for segment in ["game", "assets", "ui", "dist"] {
|
||||
for segment in ["game", "assets", "ui"] {
|
||||
let allowed_dir = root.join(segment);
|
||||
let metadata = match fs::symlink_metadata(&allowed_dir) {
|
||||
Ok(metadata) => metadata,
|
||||
@@ -1643,43 +1586,6 @@ mod tests {
|
||||
use super::*;
|
||||
use std::fs;
|
||||
|
||||
#[test]
|
||||
fn npm_preview_requires_build_and_prefers_bundled_assets() {
|
||||
let base = PathBuf::from(std::env::var("HOME").unwrap()).join("data/tmp");
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
let root = tempfile::tempdir_in(base).unwrap();
|
||||
fs::write(root.path().join("package.json"), "{}").unwrap();
|
||||
fs::write(root.path().join("index.html"), "source").unwrap();
|
||||
assert!(resolve_preview_path(root.path(), "/").is_err());
|
||||
fs::create_dir_all(root.path().join("dist/assets")).unwrap();
|
||||
fs::create_dir_all(root.path().join("assets")).unwrap();
|
||||
fs::write(root.path().join("dist/index.html"), "<!doctype html>").unwrap();
|
||||
fs::write(root.path().join("dist/assets/main.js"), "bundled").unwrap();
|
||||
fs::write(root.path().join("assets/main.js"), "source").unwrap();
|
||||
fs::write(root.path().join("assets/hero.png"), "image").unwrap();
|
||||
assert_eq!(
|
||||
resolve_preview_path(root.path(), "/assets/main.js").unwrap(),
|
||||
root.path()
|
||||
.join("dist/assets/main.js")
|
||||
.canonicalize()
|
||||
.unwrap()
|
||||
);
|
||||
assert!(resolve_preview_path(root.path(), "/assets/hero.png").is_err());
|
||||
fs::create_dir_all(root.path().join("game")).unwrap();
|
||||
fs::write(root.path().join("game/index.html"), "source").unwrap();
|
||||
assert!(resolve_preview_path(root.path(), "/game/index.html").is_err());
|
||||
assert!(resolve_preview_path(root.path(), "/assets/%2e%2e/index.html").is_err());
|
||||
#[cfg(unix)]
|
||||
{
|
||||
std::os::unix::fs::symlink(
|
||||
root.path().join("index.html"),
|
||||
root.path().join("dist/assets/leak.html"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(resolve_preview_path(root.path(), "/assets/leak.html").is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn root_layout_serves_root_entry_and_keeps_legacy_paths_available() {
|
||||
let root = tempfile::tempdir().expect("create preview root");
|
||||
|
||||
@@ -4,7 +4,26 @@ pub(crate) fn export_local_project_package_at(
|
||||
root: &Path,
|
||||
) -> Result<LocalProjectExportPackageResult, String> {
|
||||
validate_project_root(root)?;
|
||||
super::verification::validate_project_game_entry(root)?;
|
||||
ensure_project_export_package_dir(root, "game")?;
|
||||
let game_index_path = resolve_local_project_path(root, "game/index.html")?;
|
||||
if !game_index_path.is_file() {
|
||||
return Err("导出试玩包前需要先生成 game/index.html".to_string());
|
||||
}
|
||||
let game_index_metadata = checked_export_package_metadata(&game_index_path, "game/index.html")?;
|
||||
if !game_index_metadata.is_file() {
|
||||
return Err("导出试玩包前需要先生成 game/index.html".to_string());
|
||||
}
|
||||
prepare_game_creator_private_path_for_read(&game_index_path, false, "游戏入口")?;
|
||||
let game_index = fs::read_to_string(&game_index_path)
|
||||
.map_err(|error| format!("读取游戏入口失败:{}: {error}", game_index_path.display()))?;
|
||||
if game_index.trim().is_empty() {
|
||||
return Err("导出试玩包前 game/index.html 不能为空".to_string());
|
||||
}
|
||||
let lower_game_index = game_index.to_ascii_lowercase();
|
||||
if !lower_game_index.contains("<html") && !lower_game_index.contains("<!doctype html") {
|
||||
return Err("导出试玩包前 game/index.html 必须是 HTML 文档".to_string());
|
||||
}
|
||||
validate_game_html_smoke(&game_index)?;
|
||||
ensure_project_export_package_dir(root, "exports")?;
|
||||
let readme_path = resolve_local_project_path(root, "exports/README.md")?;
|
||||
if !readme_path.is_file() {
|
||||
@@ -198,22 +217,8 @@ pub(crate) fn collect_project_export_package_files(
|
||||
root: &Path,
|
||||
) -> Result<Vec<(String, PathBuf, u64)>, String> {
|
||||
let mut files = Vec::new();
|
||||
let game_root = crate::preview::project_game_root(root);
|
||||
let built = game_root == root.join("dist") || game_root == root.join("game/dist");
|
||||
if built {
|
||||
let relative = relative_project_path(root, &game_root)?;
|
||||
collect_project_export_package_dir_files(root, &relative, &mut files)?;
|
||||
for (name, _, _) in &mut files {
|
||||
*name = format!(
|
||||
"game/{}",
|
||||
name.strip_prefix(&format!("{relative}/"))
|
||||
.ok_or("构建产物路径非法")?
|
||||
);
|
||||
}
|
||||
} else {
|
||||
collect_project_export_package_dir_files(root, "game", &mut files)?;
|
||||
}
|
||||
if !built && resolve_local_project_path(root, "assets")?.exists() {
|
||||
collect_project_export_package_dir_files(root, "game", &mut files)?;
|
||||
if resolve_local_project_path(root, "assets")?.exists() {
|
||||
collect_project_export_package_dir_files(root, "assets", &mut files)?;
|
||||
}
|
||||
let readme_path = resolve_local_project_path(root, "exports/README.md")?;
|
||||
@@ -307,42 +312,3 @@ pub(crate) fn normalize_export_package_entry_path(relative_path: &str) -> Result
|
||||
}
|
||||
normalize_relative_path(relative_path)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod npm_export_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn npm_package_contains_only_dist_and_publish_readme() {
|
||||
let base = PathBuf::from(std::env::var("HOME").unwrap()).join("data/tmp");
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
let root = tempfile::tempdir_in(base).unwrap();
|
||||
for directory in ["dist/assets", "assets", "exports", "node_modules", "game"] {
|
||||
fs::create_dir_all(root.path().join(directory)).unwrap();
|
||||
}
|
||||
for file in [
|
||||
"package.json",
|
||||
"dist/index.html",
|
||||
"dist/assets/main.js",
|
||||
"assets/hero.png",
|
||||
"exports/README.md",
|
||||
"node_modules/private.js",
|
||||
"game/source.js",
|
||||
] {
|
||||
fs::write(root.path().join(file), "test").unwrap();
|
||||
}
|
||||
let files = collect_project_export_package_files(root.path()).unwrap();
|
||||
let names = files
|
||||
.iter()
|
||||
.map(|(name, _, _)| name.as_str())
|
||||
.collect::<Vec<_>>();
|
||||
assert_eq!(
|
||||
names,
|
||||
vec![
|
||||
"exports/README.md",
|
||||
"game/assets/main.js",
|
||||
"game/index.html"
|
||||
]
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,32 +9,6 @@ static MANIFEST_LOCK_OPEN_GUARD: OnceLock<Mutex<()>> = OnceLock::new();
|
||||
|
||||
pub(crate) const GAME_CREATION_PROJECT_NAME_MAX_CHARS: usize = 80;
|
||||
|
||||
const DEFAULT_GAME_PACKAGE_JSON: &str = r#"{
|
||||
"name": "agc-game",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"build": "vite build",
|
||||
"dev": "vite"
|
||||
},
|
||||
"dependencies": {
|
||||
"phaser": "4.2.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
"vite": "^6.2.0"
|
||||
}
|
||||
}
|
||||
"#;
|
||||
|
||||
const DEFAULT_GAME_VITE_CONFIG: &str = r#"import { defineConfig } from 'vite';
|
||||
|
||||
export default defineConfig({
|
||||
root: '.',
|
||||
base: './',
|
||||
build: { outDir: 'dist', emptyOutDir: true },
|
||||
});
|
||||
"#;
|
||||
|
||||
pub(crate) fn normalize_game_creation_project_name(value: &str) -> Result<String, String> {
|
||||
let name = value.trim();
|
||||
if name.is_empty() {
|
||||
@@ -471,11 +445,6 @@ pub(crate) fn init_local_game_project_at(
|
||||
let name = normalize_game_creation_project_name(name)?;
|
||||
|
||||
prepare_game_creator_project_root_for_read(root, true, "本地项目目录")?;
|
||||
let create_npm_scaffold = !manifest_storage_exists(&root.join(".agent/manifest.json"))?
|
||||
&& !root.join("index.html").exists()
|
||||
&& !root.join("game/index.html").exists()
|
||||
&& !root.join("package.json").exists()
|
||||
&& !root.join("game/package.json").exists();
|
||||
for relative in ["game", "assets", "memory", "memory/agents", "exports"] {
|
||||
let path = root.join(relative);
|
||||
ensure_game_creator_private_directory_tree(&path, "本地项目目录")?;
|
||||
@@ -490,32 +459,6 @@ pub(crate) fn init_local_game_project_at(
|
||||
"默认游戏入口",
|
||||
)?;
|
||||
}
|
||||
if create_npm_scaffold {
|
||||
for (relative, content, label) in [
|
||||
(
|
||||
"game/package.json",
|
||||
DEFAULT_GAME_PACKAGE_JSON,
|
||||
"游戏 npm 配置",
|
||||
),
|
||||
(
|
||||
"game/package-lock.json",
|
||||
include_str!("../../resources/agc-game-package-lock.json"),
|
||||
"游戏 npm 锁文件",
|
||||
),
|
||||
(
|
||||
"game/vite.config.js",
|
||||
DEFAULT_GAME_VITE_CONFIG,
|
||||
"游戏 Vite 配置",
|
||||
),
|
||||
("game/style.css", DEFAULT_GAME_STYLE_CSS, "游戏样式"),
|
||||
("game/game.js", DEFAULT_GAME_SCRIPT_JS, "游戏入口脚本"),
|
||||
] {
|
||||
let path = root.join(relative);
|
||||
if !prepare_game_creator_private_path_for_read(&path, false, label)? {
|
||||
crate::write_game_creator_private_file(&path, content.as_bytes(), label)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let agent_db_path = root.join(".agent/agent.db");
|
||||
if !agent_db_path.exists() {
|
||||
@@ -1571,41 +1514,3 @@ pub(crate) fn trim_optional_string(value: Option<String>) -> Option<String> {
|
||||
mod import_tests;
|
||||
#[cfg(test)]
|
||||
mod recovery_tests;
|
||||
|
||||
#[cfg(test)]
|
||||
mod npm_scaffold_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn npm_scaffold_uses_package_import_and_preserves_user_changes() {
|
||||
let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap();
|
||||
init_local_game_project_at(root.path(), "npm-scaffold", "游戏").unwrap();
|
||||
let package: serde_json::Value =
|
||||
serde_json::from_slice(&fs::read(root.path().join("game/package.json")).unwrap())
|
||||
.unwrap();
|
||||
assert_eq!(package["dependencies"]["phaser"], "4.2.1");
|
||||
assert!(fs::read_to_string(root.path().join("game/game.js"))
|
||||
.unwrap()
|
||||
.contains("import Phaser from 'phaser'"));
|
||||
assert!(root.path().join("game/package-lock.json").is_file());
|
||||
fs::write(root.path().join("game/game.js"), "user source").unwrap();
|
||||
init_local_game_project_at(root.path(), "npm-scaffold", "游戏").unwrap();
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("game/game.js")).unwrap(),
|
||||
"user source"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn npm_scaffold_does_not_migrate_an_existing_html_project() {
|
||||
let root = tempfile::tempdir_in(std::env::temp_dir().canonicalize().unwrap()).unwrap();
|
||||
fs::create_dir(root.path().join("game")).unwrap();
|
||||
fs::write(root.path().join("game/index.html"), "existing html").unwrap();
|
||||
init_local_game_project_at(root.path(), "existing-html", "已有游戏").unwrap();
|
||||
assert!(!root.path().join("game/package.json").exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(root.path().join("game/index.html")).unwrap(),
|
||||
"existing html"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -400,12 +400,6 @@ pub(crate) fn build_project_resource_graph(
|
||||
.push(resource_ids[0].clone());
|
||||
}
|
||||
|
||||
let resources_by_manifest_asset_id = resource_ids_by_manifest_asset
|
||||
.iter()
|
||||
.filter(|(_, resource_ids)| resource_ids.len() == 1)
|
||||
.map(|(asset_id, resource_ids)| (asset_id.clone(), resource_ids[0].clone()))
|
||||
.collect::<BTreeMap<_, _>>();
|
||||
|
||||
let mut unresolved_reference_resource_ids = BTreeSet::new();
|
||||
let mut reference_edge_by_id = BTreeMap::<String, ProjectResourceReferenceEdge>::new();
|
||||
for (asset_id, target_resource_ids) in &resource_ids_by_manifest_asset {
|
||||
@@ -424,32 +418,16 @@ pub(crate) fn build_project_resource_graph(
|
||||
.filter(|value| !value.is_empty())
|
||||
.collect::<BTreeSet<_>>()
|
||||
{
|
||||
let mut source_candidates = resources_by_external_id
|
||||
let source_candidates = resources_by_external_id
|
||||
.get(external_reference_id)
|
||||
.map(Vec::as_slice)
|
||||
.unwrap_or(&[])
|
||||
.iter()
|
||||
.collect::<BTreeSet<_>>();
|
||||
if let Some(referenced_asset_id) = external_reference_id
|
||||
.strip_prefix("local-asset:")
|
||||
.map(str::trim)
|
||||
.filter(|value| !value.is_empty())
|
||||
{
|
||||
if let Some(source_resource_id) =
|
||||
resources_by_manifest_asset_id.get(referenced_asset_id)
|
||||
{
|
||||
source_candidates.insert(source_resource_id);
|
||||
}
|
||||
}
|
||||
.unwrap_or(&[]);
|
||||
if source_candidates.len() != 1 {
|
||||
unresolved_reference_resource_ids.insert(external_reference_id.to_string());
|
||||
continue;
|
||||
}
|
||||
let source_resource_id = source_candidates
|
||||
.iter()
|
||||
.next()
|
||||
.expect("a non-empty candidate set must have one resource");
|
||||
if !resource_by_id.contains_key(source_resource_id.as_str())
|
||||
let source_resource_id = &source_candidates[0];
|
||||
if !resource_by_id.contains_key(source_resource_id)
|
||||
|| !resource_by_id.contains_key(target_resource_id)
|
||||
{
|
||||
continue;
|
||||
@@ -460,7 +438,7 @@ pub(crate) fn build_project_resource_graph(
|
||||
ProjectResourceReferenceEdge {
|
||||
id,
|
||||
kind: "asset-reference".to_string(),
|
||||
source_resource_id: source_resource_id.to_string(),
|
||||
source_resource_id: source_resource_id.clone(),
|
||||
target_resource_id: target_resource_id.clone(),
|
||||
cyclic: false,
|
||||
},
|
||||
@@ -857,75 +835,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_resolves_local_asset_reference_identities() {
|
||||
let manifest = manifest(
|
||||
Vec::new(),
|
||||
vec![
|
||||
asset("source-1", None, &[], None),
|
||||
asset(
|
||||
"derivative-1",
|
||||
Some("local-asset:derivative-1"),
|
||||
&["local-asset:source-1"],
|
||||
None,
|
||||
),
|
||||
],
|
||||
);
|
||||
let graph = build_project_resource_graph(
|
||||
&manifest,
|
||||
vec![
|
||||
resource("asset:source-1", Some("source-1"), None),
|
||||
resource("asset:derivative-1", Some("derivative-1"), None),
|
||||
],
|
||||
&[],
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(graph.reference_edges.len(), 1);
|
||||
assert_eq!(
|
||||
graph.reference_edges[0].source_resource_id,
|
||||
"asset:source-1"
|
||||
);
|
||||
assert_eq!(
|
||||
graph.reference_edges[0].target_resource_id,
|
||||
"asset:derivative-1"
|
||||
);
|
||||
assert!(graph.unresolved_reference_resource_ids.is_empty());
|
||||
assert!(graph
|
||||
.connection_index
|
||||
.iter()
|
||||
.any(|index| index.resource_id == "asset:derivative-1"
|
||||
&& index.upstream_reference_resource_ids == vec!["asset:source-1"]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_resolves_local_asset_identity_without_ambiguous_remote_duplicate() {
|
||||
let manifest = manifest(
|
||||
Vec::new(),
|
||||
vec![
|
||||
asset("source-1", Some("external-source"), &[], None),
|
||||
asset(
|
||||
"derivative-1",
|
||||
Some("local-asset:derivative-1"),
|
||||
&["local-asset:source-1"],
|
||||
None,
|
||||
),
|
||||
],
|
||||
);
|
||||
let graph = build_project_resource_graph(
|
||||
&manifest,
|
||||
vec![
|
||||
resource("asset:source-1", Some("source-1"), None),
|
||||
resource("asset:derivative-1", Some("derivative-1"), None),
|
||||
],
|
||||
&[],
|
||||
false,
|
||||
);
|
||||
|
||||
assert_eq!(graph.reference_edges.len(), 1);
|
||||
assert!(graph.unresolved_reference_resource_ids.is_empty());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn graph_aggregates_flows_filters_missing_resources_and_detects_cycles_iteratively() {
|
||||
let manifest = manifest(
|
||||
|
||||
@@ -3950,14 +3950,9 @@ fn commit_resource_edit_asset_internal(
|
||||
})
|
||||
.transpose()?;
|
||||
let image_sequence_duration_ms = ledger.remote_sequence_duration_ms;
|
||||
let asset_kind = if input.edit_kind == LocalProjectResourceEditKind::CharacterAnimation {
|
||||
"character-animation".to_string()
|
||||
} else {
|
||||
source.asset_kind.clone()
|
||||
};
|
||||
let asset = GameCreationAppAssetManifestEntry {
|
||||
id: asset_id.clone(),
|
||||
kind: asset_kind,
|
||||
kind: source.asset_kind.clone(),
|
||||
media_type: staged_media_type.to_string(),
|
||||
local_path: relative_path.clone(),
|
||||
image_sequence_frames,
|
||||
@@ -8972,72 +8967,6 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn character_animation_commit_uses_animation_asset_kind() {
|
||||
let directory = tempfile::tempdir().expect("create animation commit fixture");
|
||||
let root = directory.path();
|
||||
init_local_game_project_at(root, PROJECT_ID, "角色动画提交类型测试")
|
||||
.expect("initialize project");
|
||||
let uploaded = upload_local_asset_at(
|
||||
root,
|
||||
"character-source.png",
|
||||
"image/png",
|
||||
&resource_editor_test_png(),
|
||||
)
|
||||
.expect("upload source image");
|
||||
let manifest = read_existing_manifest_for_project(root).expect("read source manifest");
|
||||
let source_asset = manifest
|
||||
.assets
|
||||
.iter()
|
||||
.find(|asset| asset.id == uploaded.id)
|
||||
.cloned()
|
||||
.expect("find source image");
|
||||
|
||||
let mut request = input(
|
||||
root,
|
||||
Uuid::new_v4().to_string(),
|
||||
LocalProjectResourceEditKind::CharacterAnimation,
|
||||
format!("asset:{}", source_asset.id),
|
||||
);
|
||||
request.source_asset_id = Some(source_asset.id.clone());
|
||||
request.source_path = Some(source_asset.local_path.clone());
|
||||
request.source_media_type = Some(source_asset.media_type.clone());
|
||||
request.source_subtype = Some(source_asset.kind.clone());
|
||||
let source = resolve_resource_edit_source(
|
||||
root,
|
||||
&read_existing_manifest_for_project(root).expect("reread manifest"),
|
||||
&request,
|
||||
)
|
||||
.expect("resolve animation source");
|
||||
let mut ledger = ledger_for(&request, &source, ResourceEditLedgerPhase::MediaDownloaded);
|
||||
ledger.staged_media_type = Some("video/mp4".to_string());
|
||||
ledger.staged_extension = Some("mp4".to_string());
|
||||
ledger.remote_sequence_duration_ms = Some(4_000);
|
||||
write_resource_edit_staging(
|
||||
root,
|
||||
&request.operation_id,
|
||||
b"\0\0\0\x18ftypisom\0\0\0\0isomiso2",
|
||||
)
|
||||
.expect("stage animation preview");
|
||||
|
||||
let result = commit_resource_edit_asset(
|
||||
root,
|
||||
&request,
|
||||
&source,
|
||||
&request.prompt,
|
||||
&request.asset_name,
|
||||
&mut ledger,
|
||||
)
|
||||
.expect("commit animation derivative");
|
||||
let derivative = result.asset.expect("animation derivative");
|
||||
assert_eq!(derivative.kind, "character-animation");
|
||||
assert_eq!(
|
||||
derivative.source.generation_kind.as_deref(),
|
||||
Some("character-animation")
|
||||
);
|
||||
assert_eq!(derivative.image_sequence_duration_ms, Some(4_000));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn platform_session_switch_waits_until_local_asset_commit_finishes() {
|
||||
let directory = tempfile::tempdir().expect("create commit account switch fixture");
|
||||
|
||||
@@ -14,12 +14,16 @@ pub(crate) fn run_limited_local_command_at(
|
||||
return Err("项目目录必须是绝对路径".to_string());
|
||||
}
|
||||
|
||||
let (game_index_path, html) = validate_project_game_entry(root)?;
|
||||
let output = format!(
|
||||
"通过:{},{} 字节",
|
||||
relative_project_path(root, &game_index_path)?,
|
||||
html.len()
|
||||
);
|
||||
let game_index_path = root.join("game/index.html");
|
||||
prepare_game_creator_private_path_for_read(&game_index_path, false, "游戏入口")?;
|
||||
let html = fs::read_to_string(&game_index_path)
|
||||
.map_err(|error| format!("读取游戏入口失败:{}: {error}", game_index_path.display()))?;
|
||||
if !html.contains("<html") && !html.contains("<!doctype html") {
|
||||
return Err("游戏入口不是 HTML 文档".to_string());
|
||||
}
|
||||
validate_game_html_smoke(&html)?;
|
||||
|
||||
let output = format!("通过:game/index.html,{} 字节", html.len());
|
||||
let log_path = root.join(".agent/logs/command.log");
|
||||
let updated_at = unix_timestamp();
|
||||
let line = format!("{updated_at} command.run_limited {command_id}: {output}\n");
|
||||
@@ -45,59 +49,6 @@ pub(crate) fn run_limited_local_command_at(
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn validate_project_game_entry(root: &Path) -> Result<(PathBuf, String), String> {
|
||||
let game_root = crate::preview::project_game_root(root);
|
||||
let index = crate::preview::resolve_preview_path(root, "/")?;
|
||||
prepare_game_creator_private_path_for_read(&index, false, "游戏入口")?;
|
||||
let html = fs::read_to_string(&index).map_err(|error| format!("读取游戏入口失败:{error}"))?;
|
||||
let lower = html.to_ascii_lowercase();
|
||||
if !lower.contains("<html") && !lower.contains("<!doctype html") {
|
||||
return Err("游戏入口不是 HTML 文档".to_string());
|
||||
}
|
||||
if game_root == root.join("dist") || game_root == root.join("game/dist") {
|
||||
validate_built_game_references(root, &html)?;
|
||||
} else {
|
||||
validate_game_html_smoke(&html)?;
|
||||
}
|
||||
Ok((index, html))
|
||||
}
|
||||
|
||||
fn validate_built_game_references(root: &Path, html: &str) -> Result<(), String> {
|
||||
let tags = regex::Regex::new(r"(?is)<(?:script|link|img|audio|video|source)\b[^>]*>").unwrap();
|
||||
let attributes =
|
||||
regex::Regex::new(r#"(?is)\s+([^\s=/>]+)\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))"#)
|
||||
.unwrap();
|
||||
for tag in tags.find_iter(html) {
|
||||
for attribute in attributes.captures_iter(tag.as_str()) {
|
||||
let name = attribute.get(1).unwrap().as_str();
|
||||
if !name.eq_ignore_ascii_case("src") && !name.eq_ignore_ascii_case("href") {
|
||||
continue;
|
||||
}
|
||||
let value = attribute
|
||||
.get(2)
|
||||
.or_else(|| attribute.get(3))
|
||||
.or_else(|| attribute.get(4))
|
||||
.unwrap()
|
||||
.as_str();
|
||||
if value.is_empty()
|
||||
|| value.starts_with('#')
|
||||
|| value.starts_with("//")
|
||||
|| value.contains(':')
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let path = value.split(['?', '#']).next().unwrap_or(value);
|
||||
let path = path.strip_prefix("./").unwrap_or(path);
|
||||
crate::preview::resolve_preview_path(
|
||||
root,
|
||||
&format!("/{}", path.trim_start_matches('/')),
|
||||
)
|
||||
.map_err(|error| format!("构建入口引用不可用:{value}: {error}"))?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) const PROJECT_VERIFICATION_OUTPUT_MAX_BYTES: usize = 24 * 1024;
|
||||
const PROJECT_VERIFICATION_PACKAGE_MAX_BYTES: u64 = 512 * 1024;
|
||||
const PROJECT_VERIFICATION_MIN_TIMEOUT_SECONDS: u64 = 1;
|
||||
@@ -889,25 +840,3 @@ pub(crate) fn enforce_project_auto_permission_policy(
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod npm_build_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn built_smoke_checks_module_files_without_inline_canvas() {
|
||||
let base = PathBuf::from(std::env::var("HOME").unwrap()).join("data/tmp");
|
||||
fs::create_dir_all(&base).unwrap();
|
||||
let root = tempfile::tempdir_in(base).unwrap();
|
||||
fs::create_dir_all(root.path().join("dist/assets")).unwrap();
|
||||
fs::write(root.path().join("package.json"), "{}").unwrap();
|
||||
let html = r#"<!doctype html><html><script type="module" src="./assets/main.js"></script><link href="./assets/main.css" rel="stylesheet"></html>"#;
|
||||
fs::write(root.path().join("dist/index.html"), html).unwrap();
|
||||
assert!(validate_built_game_references(root.path(), html).is_err());
|
||||
fs::write(root.path().join("dist/assets/main.js"), "export {};").unwrap();
|
||||
fs::write(root.path().join("dist/assets/main.css"), "body{}").unwrap();
|
||||
assert!(validate_built_game_references(root.path(), html).is_ok());
|
||||
let lazy_html = r#"<!doctype html><html><img data-src="later.png" data-href="missing.png" alt="src='not-a-reference.png'" src="./assets/main.js"></html>"#;
|
||||
assert!(validate_built_game_references(root.path(), lazy_html).is_ok());
|
||||
}
|
||||
}
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user