Enforce agent documentation and project invariants

This commit is contained in:
WuYongJie 2026-12-05 14:00:21 +08:00
parent 3b81e6f449
commit c9b0e33a30
19 changed files with 801 additions and 4 deletions

View File

@ -224,6 +224,8 @@ temp_*.sql
!prisma/migrations/**
!data/team-function-initial-content.json
!lib/desktop-client/agent-rule-catalog.json
!lib/desktop-client/template-packs/gj-desk-dnz0385-native-v1.json
!lib/desktop-client/template-packs/yjd-desk-dnz0385-native-v1.json
# Private generated data never belongs to a build context.
/detail-generator-private

168
.env.example Normal file
View File

@ -0,0 +1,168 @@
# Copy to .env and supply the settings needed for your environment.
ADMIN_API_KEY=
API_KEY_ENCRYPTION_KEY=
APP_PUBLIC_URL=
ART_WORKFLOW_POINTS_CONFIG_DIR=
ART_WORKFLOW_POINTS_DASHBOARD_URL=
AUTO_LISTING_INTERNAL_CALLBACK_ORIGINS=
BUILD_ID=
COMMIT_SHA=
CORS_ALLOWED_ORIGINS=
DATABASE_URL=
DEBUG_NETWORK_DETECTION=
DEPLOYMENT_COMMIT=
DEPLOYMENT_VERSION=
DETAIL_FONT_DIR=
DETAIL_GENERATOR_API_KEY=
DETAIL_GENERATOR_BASE_URL=
DETAIL_GENERATOR_ENABLED=
DETAIL_GENERATOR_STORAGE_DIR=
DETAIL_GENERATOR_VALIDATED_MODELS_JSON=
DETAIL_RENDERER_ENTRY=
DETAIL_RENDERER_NODE=
DETAIL_RENDER_TEST_ARTIFACTS=
DINGTALK_AGENT_ID=
DINGTALK_APP_KEY=
DINGTALK_APP_SECRET=
DINGTALK_CLIENT_ID=
DINGTALK_CLIENT_SECRET=
DINGTALK_CORPID=
DINGTALK_CORP_ID=
DINGTALK_INTERNAL_RETURN_ORIGINS=
DINGTALK_PERFORMANCE_SESSION_TTL_SECONDS=
DINGTALK_PERFORMANCE_SURVEY_NOTIFICATION_CHANNEL=
DINGTALK_ROBOT_CODE=
DINGTALK_ROBOT_OTO_TEST_USER_IDS=
DINGTALK_WORK_NOTICE_AGENT_ID=
DINGTALK_WORK_NOTICE_APP_KEY=
DINGTALK_WORK_NOTICE_APP_SECRET=
DINGTALK_WORK_NOTICE_CLIENT_ID=
DINGTALK_WORK_NOTICE_CLIENT_SECRET=
DINGTALK_WORK_NOTICE_CORP_ID=
DING_WORKFLOW_SYNC_INTERVAL_HOURS=
DISABLE_CACHE=
DOWNLOAD_TOKEN_SECRET=
EMPLOYEE_ROSTER_HISTORY_INITIAL_DELAY_SECONDS=
EMPLOYEE_ROSTER_HISTORY_INTERVAL_HOURS=
EXTERNAL_NOTIFICATION_WORKER_PAUSED=
EXTERNAL_TASK_DETAIL_API_KEY=
FEEDBACK_AGENT_WEBHOOK_SECRET=
FEEDBACK_AGENT_WEBHOOK_URL=
FEEDBACK_DINGTALK_OWNER_USER_ID=
FEEDBACK_GITHUB_REPO=
FEEDBACK_GITHUB_TOKEN=
FINISHED_WEB_ACCESS_KEY=
GEMINI_API_BASE_URL=
GEMINI_API_KEY=
GEMINI_MODEL=
HISTORY_IMPORT_ALL_ZIP_TIMEOUT_MS=
HISTORY_IMPORT_REMOTE_UPLOADS_DIR=
HISTORY_IMPORT_REMOTE_UPLOADS_HOST=
HISTORY_IMPORT_ZIP_TIMEOUT_MS=
IMAGE_PROCESSING_MAX_CONCURRENT=
MIGRATION_AUDIT_SOURCE_COMMIT=
MINIO_API_PORT=
NEXTAUTH_SECRET=
NEXTAUTH_URL=
NEXT_BUILD=
NEXT_PUBLIC_APP_PUBLIC_URL=
NEXT_PUBLIC_DINGTALK_CALLBACK_ORIGIN=
NEXT_PUBLIC_DINGTALK_CLIENT_ID=
NEXT_PUBLIC_DINGTALK_CORP_ID=
ORGANIZATION_SYNC_HOUR=
PERFORMANCE_SALARY_LOCAL_TEST_FALLBACK=
PERFORMANCE_SURVEY_ACCOUNT_PROFILE_WHERE_CACHE_SECONDS=
PERFORMANCE_SURVEY_DAILY_SYNC_INITIAL_DELAY_SECONDS=
PERFORMANCE_SURVEY_DAILY_SYNC_INTERVAL_HOURS=
PERFORMANCE_SURVEY_DAILY_SYNC_LIMIT=
PERFORMANCE_SURVEY_DEPARTMENT_CACHE_MAX_ENTRIES=
PERFORMANCE_SURVEY_DEPARTMENT_CACHE_SECONDS=
PERFORMANCE_SURVEY_PROFILE_BACKGROUND_REFRESH_MIN_SECONDS=
PERFORMANCE_SURVEY_PROFILE_SYNC_HOURS=
PERFORMANCE_SURVEY_PUBLIC_DASHBOARD_DELETER_DINGTALK_IDS=
PORT=
PRODUCT_PACKAGE_INTERNAL_DOWNLOAD_ORIGINS=
PRODUCT_PLATFORM_BASE_URL=
PRODUCT_PLATFORM_BY_SPU_API_KEY=
PUBLIC_TRAFFIC_LOG_PATHS=
PUBLIC_TRAFFIC_MAX_LINES=
PUBLIC_TRAFFIC_ROLLUP_TOKEN=
PUBLIC_TRAFFIC_STATS_CACHE_TTL_SECONDS=
PUBLIC_TRAFFIC_STATS_DB_CACHE=
REDIS_URL=
REMOTE_SYNC_RETRY_COUNT=
REMOTE_SYNC_SCP_TIMEOUT_MS=
REMOTE_SYNC_SSH_TIMEOUT_MS=
REPORT_DB_DATABASE=
REPORT_DB_DIMISSION_SCHEMA=
REPORT_DB_DIMISSION_TABLE=
REPORT_DB_EMPLOYEE_SCHEMA=
REPORT_DB_EMPLOYEE_TABLE=
REPORT_DB_ENCRYPT=
REPORT_DB_FLOWER_NAME_SCHEMA=
REPORT_DB_FLOWER_NAME_TABLE=
REPORT_DB_GROUP_SCHEMA=
REPORT_DB_GROUP_TABLE=
REPORT_DB_PASSWORD=
REPORT_DB_PORT=
REPORT_DB_REGISTER_SCHEMA=
REPORT_DB_REGISTER_TABLE=
REPORT_DB_SERVER=
REPORT_DB_TRUST_SERVER_CERTIFICATE=
REPORT_DB_USER=
REPORT_DB_WORKFLOW_SCHEMA=
REPORT_DB_WORKFLOW_SCHEME_TABLE=
REPORT_DB_WORKFLOW_TABLE=
REPORT_DB_WORKFLOW_TASK_TABLE=
S3_ACCESS_KEY_ID=
S3_BUCKET=
S3_ENDPOINT=
S3_FILE_PATH=
S3_PUBLIC_DOMAIN=
S3_REGION=
S3_SECRET_ACCESS_KEY=
SERVER_IP=
SHARP_CONCURRENCY=
TAOBAO_DETAIL_PLUS_API_BASE_URL=
TAOBAO_DETAIL_PLUS_API_KEY=
TAOBAO_DETAIL_PLUS_TIMEOUT_MS=
TASK_DETAIL_PREVIEW_MAX_BYTES=
TASK_DETAIL_UPLOAD_HEARTBEAT_MS=
TASK_DETAIL_UPLOAD_INSTANCE_ID=
TASK_DETAIL_UPLOAD_LEASE_MS=
TASK_DETAIL_UPLOAD_RUNTIME_DIR=
TASK_DETAIL_UPLOAD_STALE_MS=
TASK_DETAIL_UPLOAD_WORKER_ID=
TASK_DETAIL_ZIP_COMPRESSION_LEVEL=
TEST_MODE=
UPLOAD_DIR=
UPLOAD_REMOTE_SYNC_HOST=
UPLOAD_REMOTE_SYNC_ROOT=
USE_REDIS=
VIDEO_CLIP_CRF=
VIDEO_CLIP_DURATION=
VIDEO_MAX_TEMP_FILE_SIZE=
VIDEO_PREVIEW_CRF=
VIDEO_PREVIEW_RESOLUTION=
VIDEO_TRANSCODE_INSTANCE_ID=
VIDEO_TRANSCODE_MAX_CONCURRENT=
VIDEO_TRANSCODE_RUNTIME_DIR=
VIDEO_TRANSCODE_THREADS=
VIDEO_TRANSCODE_TIMEOUT=
VIDEO_TRANSCODE_WORKER_ID=
WORK_REVIEW_SINGLE_REVIEW_TEST_EXPIRES_AT=
WORK_REVIEW_SINGLE_REVIEW_TEST_MANAGER_EMPLOYEE_ID=
WORK_REVIEW_SINGLE_REVIEW_TEST_PROJECT_ID=
WORK_REVIEW_SYNC_INTERVAL_HOURS=
XIAOYI_KNOWLEDGE_FALLBACK_ORIGIN=
XIAOYI_KNOWLEDGE_SESSION_SECRET=
XIAOYI_KNOWLEDGE_UPSTREAM_ORIGIN=
YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_ID=
YYD_DESKTOP_FEEDBACK_RECIPIENT_USER_IDS=
YYD_NOTIFICATION_CENTER_ADMIN_API_SECRET=
YYD_NOTIFICATION_CENTER_ADMIN_TIMEOUT_MS=
YYD_NOTIFICATION_CENTER_ADMIN_URL=
YYD_NOTIFICATION_CENTER_PROJECT_CODE=
YYD_NOTIFICATION_CENTER_PROJECT_SECRET=
YYD_NOTIFICATION_CENTER_TEST_USER_IDS=
YYD_NOTIFICATION_CENTER_URL=

3
.gitattributes vendored
View File

@ -4,3 +4,6 @@ prisma/migrations/**/migration.sql text eol=lf
# 2026-10-08. Preserve their recorded bytes instead of rewriting DB checksums.
prisma/migrations/20261008_permission_group_department_identity/migration.sql text eol=crlf
prisma/migrations/20261008_team_function_configs/migration.sql text eol=crlf
# The native brand import verifies this package by byte hash.
lib/detail-generator/knowledge/enterprise-20261013.json text eol=lf

View File

@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"test": "node --test test/*.test.mjs",
"skill-runtime:build": "node scripts/build-skill-runtime.mjs",
"test:skill-runtime": "node --test test/project-shell.integration.mjs",
"verify:live": "node scripts/acceptance.mjs"
},

View File

@ -0,0 +1,39 @@
import { spawnSync } from 'node:child_process';
import { copyFileSync, mkdirSync, mkdtempSync, rmSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { basename, join, resolve } from 'node:path';
import { fileURLToPath, pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
const source = fileURLToPath(new URL('../skill-runtime/', import.meta.url));
const images = ['bash:5.2', 'python:3.13-alpine'];
const pillow = '12.3.0';
const docker = ['--context', 'desktop-linux'];
function run(command, args) {
const result = spawnSync(command, args, { stdio: 'inherit' });
if (result.error) throw result.error;
if (result.status !== 0) throw Error(command + ' failed (' + (result.status ?? result.signal) + ')');
}
export function buildSkillRuntime({ tempDir = tmpdir(), wheel } = {}, execute = run) {
execute('docker', [...docker, 'image', 'inspect', '--format', '{{.Id}}', ...images]);
mkdirSync(tempDir, { recursive: true });
const context = mkdtempSync(join(resolve(tempDir), 'xiaoyi-skill-'));
try {
for (const file of ['Dockerfile', '.dockerignore']) copyFileSync(join(source, file), join(context, file));
if (wheel) copyFileSync(wheel, join(context, basename(wheel)));
else execute('python', ['-m', 'pip', 'download', '--only-binary=:all:', '--no-deps',
'--platform', 'musllinux_1_2_x86_64', '--implementation', 'cp', '--python-version', '3.13',
'--abi', 'cp313', '--dest', context, 'Pillow==' + pillow]);
execute('docker', [...docker, 'build', '--builder', 'desktop-linux', '--pull=false', '--network=none',
'-t', 'gongxiangp2-skill-runtime:python3.13-pillow' + pillow, context]);
} finally {
rmSync(context, { recursive: true, force: true });
}
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const { values } = parseArgs({ options: { 'temp-dir': { type: 'string' }, wheel: { type: 'string' } } });
buildSkillRuntime({ tempDir: values['temp-dir'], wheel: values.wheel });
}

View File

@ -0,0 +1,124 @@
{
"judge": {
"minimumScore": 4,
"pricing": {
"currency": "CNY",
"inputPerMillion": 2,
"outputPerMillion": 8
}
},
"runs": [
{
"id": "gujia-desk-first",
"templateId": "GJ-DESK-DNZ0385",
"deliveryDir": "原木长桌-成品",
"contract": {
"sku": [
{
"barcode": "0001-Ab",
"specId": "desk-1",
"variantId": "variant-1",
"colorName": "原木",
"sizes": [
{
"width": 8,
"height": 4,
"count": 2
},
{
"width": 8,
"height": 6
}
]
},
{
"barcode": "0002-cd",
"specId": "desk-2",
"variantId": "variant-2",
"colorName": "原木",
"sizes": [
{
"width": 8,
"height": 4
}
]
}
],
"images": [
{
"relativePath": "详情页切片/01 原木/详情页-01.jpg",
"width": 8,
"height": 4
}
],
"layout": {
"screenIds": [
"S17"
],
"thresholds": {
"textClippingMax": 0,
"contrastP10Min": 3,
"contrastP50Min": 4.5,
"nearWhiteFlatRatioMax": 0.08,
"resolutionRatioMin": 1
}
}
},
"evidence": {
"visibleText": [
"小壹已导出详情、主图和商品规格图。"
],
"candidateIds": [
"generated-a",
"unused-b"
],
"screens": [
{
"id": "S17",
"textClipping": [],
"contrastP10": 4.5,
"contrastP50": 8,
"slotImageFacts": [
{
"nearWhiteFlatRatio": 0.04,
"resolutionRatio": 1.5
}
]
}
]
},
"visual": {
"productFacts": {
"材质": "橡木"
},
"assets": [
{
"id": "实拍一",
"role": "product",
"path": "实拍/桌子.jpg"
},
{
"id": "模板一",
"role": "template",
"path": "模板/S17.png"
},
{
"id": "成品一",
"role": "result",
"path": "原木长桌-成品/详情页切片/01 原木/详情页-01.jpg"
}
],
"replay": "在线报告/replays/gujia-desk-first.json"
},
"production": {
"modelId": "生产模型版本",
"protocol": "生产协议",
"firstPass": true,
"cost": {
"currency": "CNY",
"amount": 1.23
}
}
}
]
}

View File

@ -1,5 +1,5 @@
import assert from 'node:assert/strict';
import { mkdir, rename, rm, writeFile } from 'node:fs/promises';
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
import path from 'node:path';
import test from 'node:test';
import { scoreObjective } from '../src/objective-scorer.mjs';
@ -140,3 +140,12 @@ test('fails layout independently for clipping, contrast, white rectangles and lo
assert.equal(result.layout.status, 'failed');
assert.equal(result.layout.issues.filter(issue => issue.code === 'layout-threshold').length, 5);
});
test('example plan passes the objective scoring entry point with its matching delivery', async t => {
const { workspace } = await fixture(t);
const plan = JSON.parse(await readFile(new URL('../cases/plan.example.json', import.meta.url), 'utf8'));
const [run] = plan.runs;
const result = await scoreObjective({ ...run, deliveryDir: path.resolve(workspace, run.deliveryDir) });
assert.equal(result.status, 'passed', JSON.stringify(result));
assert.equal(result.layout.status, 'passed');
});

View File

@ -11,7 +11,7 @@
* 3. 建立"江澄"账号 ↔ 该档案的活跃绑定(MANUAL_VERIFIED)
* 4. "江澄"账号角色升为 DEPT_ADMIN(M1 负责人)
*
* 用法:npx tsx --env-file=.env scripts/fix-liuwei-jiangcheng.ts --apply
* 用法:npx tsx --env-file=.env scripts/archive/fix-liuwei-jiangcheng.ts --apply
* 不加 --apply 为预演
*/
import { PrismaClient } from '@prisma/client'

View File

@ -0,0 +1,25 @@
import { globSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
// Lower this ceiling as part of any cleanup that removes variants.
export const DARK_VARIANT_BASELINE = 1389;
export function countDarkVariants(root) {
const sources = globSync(['app', 'components', 'hooks'].map(dir => dir + '/**/*.{ts,tsx,css}'), { cwd: root });
let count = 0;
for (const file of sources) {
count += (readFileSync(join(root, file), 'utf8').match(/dark:/g) ?? []).length;
}
return count;
}
export function checkDarkVariants(root, baseline = DARK_VARIANT_BASELINE) {
const count = countDarkVariants(root);
if (count > baseline) throw Error('dark: 出现 ' + count + ' 次,超过基线 ' + baseline + ' 次');
return count;
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
console.log('dark: ' + checkDarkVariants(process.cwd()) + ' / ' + DARK_VARIANT_BASELINE);
}

View File

@ -0,0 +1,25 @@
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { checkDarkVariants } from './check-dark-variants.mjs';
test('UI sources stay within the dark variant baseline', () => {
checkDarkVariants(fileURLToPath(new URL('../', import.meta.url)));
});
test('counts every occurrence in TS, TSX and CSS and rejects an increase', t => {
const root = mkdtempSync(join(tmpdir(), 'dark-variants-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
for (const [dir, file] of [['app', 'page.tsx'], ['components', 'theme.css'], ['hooks', 'use-theme.ts']]) {
mkdirSync(join(root, dir));
writeFileSync(join(root, dir, file), 'dark:bg-black dark:text-white\n');
}
writeFileSync(join(root, 'hooks', 'notes.md'), 'dark:example');
writeFileSync(join(root, 'theme.css'), 'dark:outside');
assert.equal(checkDarkVariants(root, 6), 6);
assert.equal(checkDarkVariants(root, 7), 6);
assert.throws(() => checkDarkVariants(root, 5), /超过基线 5/);
});

View File

@ -0,0 +1,113 @@
import { existsSync, globSync, readFileSync } from 'node:fs';
import { join, posix, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { parseArgs } from 'node:util';
const controlledDocuments = [
'AGENTS.md', 'CLAUDE.md', 'README.md', 'PRODUCT.md', 'DESIGN.md',
'.claude/**/*.md', '.kiro/steering/**/*.md',
'apps/detail-photocraft/AGENTS.md', 'apps/detail-photocraft/JIANSUN.md',
];
// Remove resolved entries when the pointer documents are cleaned up.
const baseline = new Set([
".claude/Claude-命令速查.md -> uploads/temp/",
".claude/Claude-命令速查.md -> uploads/assembled/",
".claude/Claude-命令速查.md -> ./deploy-remote-build.ps1",
".claude/skills/cleanup-temp.md -> uploads/temp/",
".claude/skills/cleanup-temp.md -> uploads/assembled/",
".claude/skills/cleanup-temp.md -> uploads/cleanup/",
".claude/skills/cleanup-temp.md -> uploads/materials/",
".claude/skills/cleanup-temp.md -> uploads/",
".kiro/steering/项目记忆库.md -> 由壹点AI/",
".kiro/steering/项目记忆库.md -> download/",
".kiro/steering/项目记忆库.md -> transcode/",
".kiro/steering/项目记忆库.md -> deploy-with-log.ps1",
".kiro/steering/项目记忆库.md -> ./deploy-remote-build.ps1",
".kiro/steering/项目记忆库.md -> deploy-local-build.ps1",
".kiro/steering/项目记忆库.md -> deploy-git-build.ps1",
"AGENTS.md -> .private/gongxiangp2-完整敏感接管清单-2026-08-13.md",
"CLAUDE.md -> TeamFunctionsDashboard.tsx",
"CLAUDE.md -> PermissionGroupsDashboard.tsx",
"CLAUDE.md -> UserPermissionsDashboard.tsx",
"CLAUDE.md -> 由壹点AI/",
"CLAUDE.md -> deploy-remote-build.ps1",
"CLAUDE.md -> upload-sessions.ts",
"DESIGN.md -> .impeccable/surfaces/app-assets-detail-generator-page-tsx.md",
"DESIGN.md -> .impeccable/surfaces/components-admin-aimodelmanagementpanel-tsx.md",
"README.md -> release.json",
"apps/detail-photocraft/AGENTS.md -> corpus/",
"apps/detail-photocraft/AGENTS.md -> src/macos.rs",
"apps/detail-photocraft/AGENTS.md -> src/windows.rs",
"apps/detail-photocraft/AGENTS.md -> crates/ui-egui/src/parity.rs",
"apps/detail-photocraft/AGENTS.md -> ui-egui/src/state.rs",
"apps/detail-photocraft/AGENTS.md -> log/devlog.md",
"apps/detail-photocraft/AGENTS.md -> engine/src/lib.rs",
"apps/detail-photocraft/AGENTS.md -> engine/src/commands.rs",
"apps/detail-photocraft/AGENTS.md -> ui-egui/src/menus.rs",
"apps/detail-photocraft/AGENTS.md -> plan/",
"apps/detail-photocraft/AGENTS.md -> log/",
"apps/detail-photocraft/AGENTS.md -> contributors.json",
"apps/detail-photocraft/AGENTS.md -> storytold/craft-common-actions",
"apps/detail-photocraft/JIANSUN.md -> jiansun/accounts/",
"apps/detail-photocraft/JIANSUN.md -> target/",
"apps/detail-photocraft/JIANSUN.md -> agent/node.exe",
"apps/detail-photocraft/JIANSUN.md -> agent/src/desktop-host.mjs",
"apps/detail-photocraft/JIANSUN.md -> jiansun/lifecycle/",
]);
function pointer(text) {
const candidate = text.replaceAll('\\', '/').replace(/(?::\d+(?:[-,]\d+)*|#[\p{L}\w-]+)$/u, '');
if (/[\r\n*?[\]{}<>|"'$:=]|^\/|\s--?/u.test(candidate)) return;
if (/^\d+\/(?:tcp|udp)$/i.test(candidate) || /(?:^|\/)\.\.\.(?:\/|$)/.test(candidate) ||
/^[\w.-]+\.(?:com|net|org|vip|hk)\//i.test(candidate)) return;
if (/^(?:\.\.?\/|\.private(?:\/|$)|[\p{L}\w.@-]+\/)/u.test(candidate) ||
/^[\w.-]+\.(?:md|json|mjs|js|ts|tsx|toml|ya?ml|txt|sh|ps1|prisma|css)$/i.test(candidate)) {
return candidate;
}
}
export function documentReferenceIssues(root, files = globSync(controlledDocuments, { cwd: root })) {
const issues = [];
for (const file of files.map(name => name.replaceAll('\\', '/')).sort()) {
const source = readFileSync(join(root, file), 'utf8');
let fence = '';
for (const line of source.split(/\r?\n/)) {
const marker = line.match(/^\s{0,3}(~~~+|```+)/)?.[1];
if (marker && !fence) { fence = marker; continue; }
if (fence) {
if (marker?.[0] === fence[0] && marker.length >= fence.length) fence = '';
continue;
}
for (const [, text] of line.matchAll(/(?<!`)`([^`]+)`(?!`)/g)) {
const reference = pointer(text);
if (!reference) continue;
const relativeToDoc = posix.normalize(posix.join(posix.dirname(file), reference));
const repositoryPath = /^\.\.?\//.test(reference)
? relativeToDoc : posix.normalize(reference);
const candidates = /^\.\.?\//.test(reference) ? [repositoryPath] : [repositoryPath, relativeToDoc];
const forbidden = candidates.some(name => /^(?:\.\.(?:\/|$))|(?:^|\/)\.private(?:\/|$)/i.test(name));
const exists = !forbidden && candidates.some(name => !/^资料(?:\/|$)/.test(name) && existsSync(join(root, name)));
if (!exists) issues.push({ file, reference, reason: forbidden ? 'outside-repository' : 'missing' });
}
}
}
return [...new Map(issues.map(issue => [referenceKey(issue), issue])).values()];
}
function referenceKey({ file, reference }) {
return file + ' -> ' + reference;
}
export function newDocumentReferenceIssues(root) {
return documentReferenceIssues(root).filter(issue => !baseline.has(referenceKey(issue)));
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const { values } = parseArgs({ options: { files: { type: 'string', multiple: true }, strict: { type: 'boolean' } } });
const issues = values.files || values.strict
? documentReferenceIssues(process.cwd(), values.files)
: newDocumentReferenceIssues(process.cwd());
for (const issue of issues) console.error(referenceKey(issue) + ' (' + issue.reason + ')');
if (issues.length) process.exitCode = 1;
}

View File

@ -0,0 +1,30 @@
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { documentReferenceIssues, newDocumentReferenceIssues } from './check-doc-references.mjs';
test('controlled documents introduce no dangling or private references', () => {
assert.deepEqual(newDocumentReferenceIssues(fileURLToPath(new URL('../', import.meta.url))), []);
});
test('resolves repository and document relative pointers, ignoring URLs, commands and wildcards', t => {
const root = mkdtempSync(join(tmpdir(), 'doc-references-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
for (const dir of ['scripts', 'docs', '.private']) mkdirSync(join(root, dir));
writeFileSync(join(root, 'scripts/example.mjs'), '');
writeFileSync(join(root, '.private/secret.md'), '');
writeFileSync(join(root, 'docs/guide.md'), [
'`scripts/example.mjs:6` `../scripts/example.mjs` `./guide.md`',
'`https://example.test/guide.md` `node scripts/example.mjs` `scripts/*.mjs`',
'`scripts/not-found.mjs` `.private\\secret.md` `../../outside.md`',
'```sh', 'node `scripts/not-a-pointer.mjs`', '```',
].join('\n'));
assert.deepEqual(documentReferenceIssues(root, ['docs/guide.md']), [
{ file: 'docs/guide.md', reference: 'scripts/not-found.mjs', reason: 'missing' },
{ file: 'docs/guide.md', reference: '.private/secret.md', reason: 'outside-repository' },
{ file: 'docs/guide.md', reference: '../../outside.md', reason: 'outside-repository' },
]);
});

View File

@ -0,0 +1,37 @@
import { globSync, readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const frameworkVariables = new Set([
'NODE_ENV', 'NEXT_PHASE', 'NEXT_RUNTIME', '__NEXT_PRIVATE_PREBUNDLED_REACT',
'npm_lifecycle_event', 'npm_package_version', 'SystemRoot', 'HOSTNAME',
]);
const sourcePaths = [
...['lib', 'app', 'workers', 'hooks'].map(dir => dir + '/**/*.{ts,tsx,js,jsx,mjs,cjs,mts,cts}'),
'instrumentation.ts', 'middleware.ts',
];
export function referencedEnvironment(root) {
const names = new Set();
for (const file of globSync(sourcePaths, { cwd: root, exclude: ['**/node_modules', '**/dist'] })) {
const source = readFileSync(join(root, file), 'utf8');
for (const [, name] of source.matchAll(/\bprocess\s*\.\s*env\s*\.\s*([A-Za-z_$][\w$]*)/g)) {
if (!frameworkVariables.has(name)) names.add(name);
}
}
return [...names].sort();
}
export function missingEnvironment(root) {
const example = readFileSync(join(root, '.env.example'), 'utf8');
const declared = new Set([...example.matchAll(/^([A-Za-z_$][\w$]*)=/gm)].map(([, name]) => name));
return referencedEnvironment(root).filter(name => !declared.has(name));
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const missing = missingEnvironment(process.cwd());
if (missing.length) {
console.error('.env.example 缺少登记:' + missing.join(', '));
process.exitCode = 1;
}
}

View File

@ -0,0 +1,28 @@
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { missingEnvironment } from './check-env-example.mjs';
const root = fileURLToPath(new URL('../', import.meta.url));
test('application environment reads are registered with empty example values', () => {
assert.deepEqual(missingEnvironment(root), []);
const entries = readFileSync(join(root, '.env.example'), 'utf8').split(/\r?\n/);
for (const entry of entries) assert.match(entry, /^(?:[A-Za-z_$][\w$]*=|#.*)?$/);
});
test('finds unregistered dotted environment reads across the requested source paths', t => {
const dir = mkdtempSync(join(tmpdir(), 'env-example-'));
t.after(() => rmSync(dir, { recursive: true, force: true }));
for (const section of ['lib', 'app', 'workers', 'hooks']) {
mkdirSync(join(dir, section));
writeFileSync(join(dir, section, 'source.ts'), 'process.env.' + section.toUpperCase());
}
writeFileSync(join(dir, 'instrumentation.ts'), 'process . env . INIT; process.env.NODE_ENV');
writeFileSync(join(dir, 'middleware.ts'), 'process.env.MIDDLE; process.env.NEXT_RUNTIME');
writeFileSync(join(dir, '.env.example'), '# APP=\nLIB=\nUNUSED=\n');
assert.deepEqual(missingEnvironment(dir), ['APP', 'HOOKS', 'INIT', 'MIDDLE', 'WORKERS']);
});

View File

@ -0,0 +1,36 @@
import { execFileSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
const forbidden = [
/\b(?:prisma|tx)\s*\.\s*user\s*\.\s*delete(?:Many)?\s*\(/g,
/\bDELETE\s+FROM\s+"users"/gi,
];
export function userHardDeletes(root, files = execFileSync('git', [
'ls-files', '-z', '--cached', '--others', '--exclude-standard',
], { cwd: root, encoding: 'utf8' }).split('\0')) {
const violations = [];
for (const file of new Set(files)) {
if (file.startsWith('scripts/archive/') ||
file.startsWith('资料/') || file.startsWith('.private/') ||
/(?:^|\/)__tests__\/|\.test\.[^.]+$/.test(file) ||
!/\.(?:[cm]?[jt]sx?|sql|ps1|sh|py)$/i.test(file)) continue;
const source = readFileSync(join(root, file), 'utf8');
for (const pattern of forbidden) {
for (const { index } of source.matchAll(pattern)) {
violations.push(file + ':' + source.slice(0, index).split('\n').length);
}
}
}
return violations;
}
if (process.argv[1] && pathToFileURL(resolve(process.argv[1])).href === import.meta.url) {
const violations = userHardDeletes(process.cwd());
if (violations.length) {
console.error('禁止物理删除用户:\n' + violations.join('\n'));
process.exitCode = 1;
}
}

View File

@ -0,0 +1,31 @@
import assert from 'node:assert/strict';
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
import { userHardDeletes } from './check-no-user-hard-delete.mjs';
test('active repository source does not physically delete users', () => {
assert.deepEqual(userHardDeletes(fileURLToPath(new URL('../', import.meta.url))), []);
});
test('reports ORM and SQL deletes while allowing soft deletes and ignoring test and archive files', t => {
const root = mkdtempSync(join(tmpdir(), 'user-hard-delete-'));
t.after(() => rmSync(root, { recursive: true, force: true }));
const sources = {
'lib/user.ts': 'prisma.user.update({ data: { deletedAt: now } });\nprisma.user.delete({});\nprisma.user.deleteMany({});',
'app/admin.ts': 'tx.user.delete ({});',
'prisma/migration.sql': 'delete\nFROM "users" WHERE id = 1;',
'lib/__tests__/user.ts': 'tx.user.delete({});',
'lib/user.test.ts': 'tx.user.delete({});',
'scripts/archive/repair.ts': 'tx.user.delete({});',
};
for (const [file, source] of Object.entries(sources)) {
mkdirSync(join(root, dirname(file)), { recursive: true });
writeFileSync(join(root, file), source);
}
assert.deepEqual(userHardDeletes(root, Object.keys(sources)), [
'lib/user.ts:2', 'lib/user.ts:3', 'app/admin.ts:1', 'prisma/migration.sql:1',
]);
});

View File

@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import { globSync, readFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import test from 'node:test';
const prisma = fileURLToPath(new URL('../prisma/', import.meta.url));
const logTables = new Map([
['MaterialLog', 'material_logs'],
['MaterialDownloadLog', 'material_download_logs'],
]);
test('material log schemas keep the source identifier without a foreign key', () => {
const schema = readFileSync(join(prisma, 'schema.prisma'), 'utf8');
for (const model of logTables.keys()) {
const body = schema.match(new RegExp('^model ' + model + ' \\{([\\s\\S]*?)^\\}', 'm'))?.[1];
assert.ok(body, model + ' must remain in the schema');
assert.match(body, /^\s*materialId\s+\w+/m);
assert.doesNotMatch(body, /@relation\([^)]*\bfields\s*:\s*\[[^\]]*\bmaterialId\b/s);
assert.doesNotMatch(body, /^\s*materialId\b[^\r\n]*@relation/m);
}
});
function materialLogForeignKeys(sql) {
const tables = [...logTables.values()].join('|');
const ddl = new RegExp(String.raw`\b(?:ALTER|CREATE)\s+TABLE\s+(?:(?:IF\s+(?:NOT\s+)?EXISTS|ONLY)\s+)*(?:(?:"[\w]+"|\w+)\.)?"?(` + tables + String.raw`)"?\s`, 'i');
const foreignKey = /\bFOREIGN\s+KEY\s*\([^)]*\bmaterial_?id\b[^)]*\)\s*REFERENCES\b/i;
const inlineReference = /(?:\(|,|\bADD\s+(?:COLUMN\s+)?)\s*"?material_?id"?\s+[^,;]*?\bREFERENCES\b/i;
return sql.replace(/\/\*[\s\S]*?\*\/|--[^\r\n]*/g, '').split(';').flatMap(statement => {
const table = statement.match(ddl)?.[1];
return table && (foreignKey.test(statement) || inlineReference.test(statement)) ? [table.toLowerCase()] : [];
});
}
test('accepted historical migrations do not gain new material-log foreign keys', () => {
const historical = 'migrations/20251206000000_add_soft_delete_and_favorites/migration.sql';
for (const file of globSync('migrations/**/*.sql', { cwd: prisma })) {
const relative = file.replaceAll('\\', '/');
const actual = materialLogForeignKeys(readFileSync(join(prisma, file), 'utf8')).sort();
const expected = relative === historical ? [...logTables.values()].sort() : [];
assert.deepEqual(actual, expected, relative);
}
});
test('migration check detects ALTER and inline CREATE foreign keys on either log table', () => {
assert.deepEqual(materialLogForeignKeys([
'ALTER TABLE ONLY "public"."material_logs" ADD CONSTRAINT new_key FOREIGN KEY ("materialId") REFERENCES "materials"("id")',
'CREATE TABLE material_download_logs (material_id TEXT REFERENCES materials(id))',
'ALTER TABLE material_logs DROP CONSTRAINT material_id_fkey',
'ALTER TABLE material_logs ADD FOREIGN KEY ("userId") REFERENCES users(id)',
'-- ALTER TABLE material_logs ADD FOREIGN KEY ("materialId") REFERENCES materials(id)\nSELECT 1',
].join(';\n')), ['material_logs', 'material_download_logs']);
});

View File

@ -0,0 +1,45 @@
import assert from 'node:assert/strict';
import { mkdtempSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import test from 'node:test';
import { buildSkillRuntime } from '../apps/detail-agent-pi/scripts/build-skill-runtime.mjs';
test('builds the locked skill image with an isolated temporary Docker context', t => {
const tempDir = mkdtempSync(join(tmpdir(), 'skill-runtime-build-test-'));
t.after(() => rmSync(tempDir, { recursive: true, force: true }));
const calls = [];
buildSkillRuntime({ tempDir }, (command, args) => {
calls.push([command, args]);
if (command === 'python') {
assert.ok(args.includes('Pillow==12.3.0'));
assert.ok(args.includes('musllinux_1_2_x86_64'));
const context = args[args.indexOf('--dest') + 1];
assert.deepEqual(readdirSync(context).sort(), ['.dockerignore', 'Dockerfile']);
writeFileSync(join(context, 'pillow-12.3.0-fixture.whl'), '');
}
if (args.includes('build')) {
assert.ok(args.includes('--pull=false'));
assert.ok(args.includes('--network=none'));
assert.ok(args.includes('gongxiangp2-skill-runtime:python3.13-pillow12.3.0'));
assert.ok(readdirSync(args.at(-1)).includes('pillow-12.3.0-fixture.whl'));
}
});
assert.deepEqual(calls.map(([command]) => command), ['docker', 'python', 'docker']);
assert.deepEqual(readdirSync(tempDir), []);
});
test('accepts an offline wheel and clears its temporary copy when Docker fails', t => {
const tempDir = mkdtempSync(join(tmpdir(), 'skill-runtime-build-test-'));
t.after(() => rmSync(tempDir, { recursive: true, force: true }));
const wheel = join(tempDir, 'pillow-12.3.0-fixture.whl');
writeFileSync(wheel, 'fixture');
assert.throws(() => buildSkillRuntime({ tempDir, wheel }, (command, args) => {
assert.equal(command, 'docker');
if (args.includes('build')) {
assert.ok(readdirSync(args.at(-1)).includes('pillow-12.3.0-fixture.whl'));
throw Error('fixture build failure');
}
}), /fixture build failure/);
assert.deepEqual(readdirSync(tempDir), ['pillow-12.3.0-fixture.whl']);
});

View File

@ -1,11 +1,12 @@
import assert from 'node:assert/strict'
import { existsSync, readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
import { existsSync, globSync, readFileSync, mkdtempSync, writeFileSync, rmSync } from 'node:fs'
import { spawnSync } from 'node:child_process'
import test from 'node:test'
import { runInNewContext } from 'node:vm'
import { createHash } from 'node:crypto'
import os from 'node:os'
import path from 'node:path'
import path, { matchesGlob, posix } from 'node:path'
import { fileURLToPath } from 'node:url'
import { aiModelRegistryEvidence } from './fixtures/ai-model-registry-evidence.mjs'
const bash = process.platform === 'win32' && existsSync('C:/Program Files/Git/bin/bash.exe') ? 'C:/Program Files/Git/bin/bash.exe' : 'bash'
@ -732,3 +733,30 @@ test('brand knowledge upload stays bounded in the route and stable proxy', () =>
assert.doesNotMatch(routeSource, /instanceof File/)
assert.match(routeSource, /releaseRequestSlot\?\.\(\)/)
})
function ignoredUploadRoutes(dockerignore, paths) {
const rules = dockerignore.split(/\r?\n/).map(line => line.trim())
.filter(line => line && !line.startsWith('#') && !line.startsWith('!'))
.map(line => posix.normalize(line.replace(/^\/+|\/+$/g, '')));
return rules.filter(rule => paths.some(file => {
const segments = file.split('/');
return segments.some((_, index) => matchesGlob(segments.slice(0, index + 1).join('/'), rule));
}));
}
test('Docker context contains the uploads API and page route trees', () => {
const root = fileURLToPath(new URL('../', import.meta.url));
const routes = ['app/api/uploads', 'app/uploads'];
const sources = [...routes, ...globSync(routes.map(dir => dir + '/**/*'), { cwd: root })
.map(file => file.replaceAll('\\', '/'))];
const dockerignore = readFileSync(new URL('../.dockerignore', import.meta.url), 'utf8');
assert.deepEqual(ignoredUploadRoutes(dockerignore, sources), []);
});
test('Docker ignore guard detects direct, parent and glob rules while allowing root uploads', () => {
const routes = ['app/api/uploads/[...path]/route.ts', 'app/uploads/[...path]/route.ts'];
const unsafe = ['app/api/uploads', '/app/uploads/', 'app/api', '**/uploads/**',
'app/**/uploads', 'a?p/api/uplo[ae]ds', 'app/**/uploads/**/route.ts'];
assert.deepEqual(ignoredUploadRoutes(['/uploads', '/uploads/**', '# app/api/uploads',
'!app/uploads/', ...unsafe].join('\n'), routes), unsafe.map(rule => rule.replace(/^\/+|\/+$/g, '')));
});