docs: publish game development reference V3.1

This commit is contained in:
2026-10-07 22:46:45 +08:00
commit 404936243a
90 changed files with 10702 additions and 0 deletions
+104
View File
@@ -0,0 +1,104 @@
"""Read public GitHub repository facts at a fixed commit; execute no downloaded code."""
import argparse
from concurrent.futures import ThreadPoolExecutor, as_completed
from datetime import datetime, timezone
import hashlib
import json
import os
from pathlib import Path
import re
import signal
import time
from urllib.parse import quote
from urllib.request import Request, urlopen
def read_json(url):
req = Request(url, headers={'User-Agent': 'game-reference-research',
'Accept': 'application/vnd.github+json'})
with urlopen(req, timeout=12) as response:
return json.loads(response.read())
def inspect_repository(repository, cache):
result = {'repository': repository, 'runtime_tested': False,
'checked_at_utc': datetime.now(timezone.utc).isoformat()}
try:
base = 'https://api.github.com/repos/' + repository
metadata = read_json(base)
branch = metadata['default_branch']
commit = read_json(base + '/commits/' + quote(branch, safe=''))
sha = commit['sha']
result.update(default_branch=branch, commit=sha,
commit_date=commit['commit']['committer']['date'],
description=metadata.get('description'),
license_metadata=(metadata.get('license') or {}).get('spdx_id', 'NOASSERTION'),
archived=metadata['archived'], fork=metadata['fork'],
html_url=metadata['html_url'], status='metadata_verified')
if cache:
tree = read_json(base + '/git/trees/' + sha + '?recursive=1')
tree_file = cache / (repository.replace('/', '__') + '.tree.json')
content = json.dumps(tree, ensure_ascii=False, indent=2).encode('utf-8')
with tree_file.open('xb') as handle:
handle.write(content)
result.update(tree_truncated=tree.get('truncated', False),
tree_entries=len(tree.get('tree', [])),
tree_sha256=hashlib.sha256(content).hexdigest())
except Exception as error:
result['error'] = type(error).__name__ + ': ' + str(error)
result['status'] = 'incomplete' if result.get('commit') else 'unavailable_this_check'
return result
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--repo', action='append', required=True)
parser.add_argument('--output', type=Path, required=True,
help='New result path; existing evidence is never overwritten')
parser.add_argument('--cache', type=Path, help='New tree files outside the delivered library')
parser.add_argument('--hard-timeout', type=int, default=120)
args = parser.parse_args()
if args.output.exists():
parser.error('output already exists')
if not 1 <= args.hard_timeout <= 180:
parser.error('hard timeout must be between 1 and 180 seconds')
if not all(re.fullmatch(r'[A-Za-z0-9_.-]+/[A-Za-z0-9_.-]+', r) for r in args.repo):
parser.error('repo must be owner/name')
repositories = list(dict.fromkeys(args.repo))
if args.cache:
args.cache.mkdir(parents=True, exist_ok=True)
if any((args.cache / (r.replace('/', '__') + '.tree.json')).exists() for r in repositories):
parser.error('cache would overwrite an existing tree receipt')
# No child processes are started. On macOS/Linux this also bounds executor
# shutdown, even when an individual network call is slow.
if not hasattr(signal, 'SIGALRM'):
parser.error('this helper needs Unix SIGALRM for its hard deadline')
start = time.monotonic()
process = {'pid': os.getpid(), 'pgid': os.getpgid(0), 'children_started': 0,
'start_utc': datetime.now(timezone.utc).isoformat(),
'hard_timeout_seconds': args.hard_timeout}
print(json.dumps({'process_started': process}), flush=True)
signal.alarm(args.hard_timeout)
results = []
with ThreadPoolExecutor(max_workers=4) as executor:
jobs = [executor.submit(inspect_repository, r, args.cache) for r in repositories]
for job in as_completed(jobs):
result = job.result()
results.append(result)
print(json.dumps({'repository': result['repository'],
'status': result['status']}), flush=True)
signal.alarm(0)
process['elapsed_seconds'] = round(time.monotonic() - start, 3)
report = {'schema_version': 1,
'scope': 'Public metadata and tree only; no install or runtime claim',
'process': process,
'repositories': sorted(results, key=lambda r: r['repository'])}
args.output.parent.mkdir(parents=True, exist_ok=True)
with args.output.open('x', encoding='utf-8') as handle:
json.dump(report, handle, ensure_ascii=False, indent=2)
handle.write('\n')
return 0 if all(r['status'] == 'metadata_verified' for r in results) else 1
if __name__ == '__main__':
raise SystemExit(main())
+251
View File
@@ -0,0 +1,251 @@
"""Validate reference documents and source-bound historical receipts; run no games."""
from pathlib import Path
from urllib.parse import unquote, urlsplit
import argparse
import ast
import hashlib
import json
import re
import sys
from datetime import datetime, timezone
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--report', type=Path, help='New output JSON, created exclusively')
args = parser.parse_args()
root = Path(__file__).resolve().parent.parent
# The pack can now be maintained as its own Git checkout. Repository
# metadata is outside the tutorial corpus and its content manifest.
all_files = sorted(path for path in root.rglob('*') if path.is_file()
and '.git' not in path.relative_to(root).parts)
failures = []
links = 0
for path in (p for p in all_files if p.suffix == '.md'):
contents = path.read_text(encoding='utf-8')
if re.search(r'turn\d+(?:view|search)\d+', contents):
failures.append('%s exposes an internal browser reference' % path.relative_to(root))
for target in re.findall(r'!?\[[^\]]*\]\(([^)]+)\)', contents):
parts = urlsplit(target.strip('<>'))
if parts.scheme or parts.netloc or not parts.path:
continue
links += 1
if not (path.parent / unquote(parts.path)).exists():
failures.append('%s has a missing relative link: %s' % (path.relative_to(root), target))
json_files = [p for p in all_files if p.suffix == '.json']
parsed = {}
for path in json_files:
try:
parsed[str(path.relative_to(root))] = json.loads(path.read_text(encoding='utf-8'))
except (ValueError, OSError) as error:
failures.append('%s invalid JSON: %s' % (path.relative_to(root), error))
required = ['README.md', 'AI_START_HERE.md', '01_learning_path.md',
'02_gameplay_and_architecture.md', '03_ui_layout_and_readability.md',
'04_art_animation_and_audio.md', '05_open_source_projects.md',
'06_ai_tools_and_skills.md', '07_testing_and_acceptance.md',
'08_applied_cases.md', 'sources/catalog.json',
'sources/repository_snapshots.json', 'sources/local_tool_evidence.json',
'examples/ui_styles/provenance.json', 'SHA256SUMS.json',
'09_music_and_sound.md', '10_gameplay_genres_and_content.md',
'11_public_skills.md', '12_practical_labs.md',
'13_source_walkthroughs.md', '14_npc_ai_and_procedural_content.md',
'READINESS.md', 'sources/skill_catalog.json', 'sources/research_v2.json',
'examples/godot_workshop/project.godot',
'evidence/godot_lab/attempt_02/report.json',
'15_source_recipes.md', '16_new_game_workflow.md',
'17_art_audio_implementation.md', '18_research_maintenance.md',
'sources/research_v3.json', 'history/v2_content_manifest.json',
'templates/new_game_brief.md', 'templates/source_application_record.json',
'skills/learn-from-game-source/SKILL.md',
'skills/learn-from-game-source/references/case-map.md',
'scripts/snapshot_github.py', '19_visual_consistency_workflow.md',
'templates/game_visual_contract.md', 'history/v3_content_manifest.json',
'skills/game-visual-consistency/SKILL.md',
'skills/game-visual-consistency/references/runtime-checks.md']
for name in required:
if not (root / name).is_file():
failures.append('Missing required file: ' + name)
catalog = parsed.get('sources/catalog.json', {})
entries = catalog.get('entries', [])
ids = [entry.get('id') for entry in entries]
if len(ids) != len(set(ids)) or not all(ids):
failures.append('Source IDs are missing or duplicated')
definitions = catalog.get('definitions', {})
for entry in entries:
if not entry.get('url', '').startswith('https://'):
failures.append('Non-HTTPS source: %s' % entry.get('id'))
if entry.get('evidence_status') not in definitions:
failures.append('Undefined source status: %s' % entry.get('id'))
for key in ['commit', 'tested_commit']:
if key in entry and not re.fullmatch(r'[0-9a-f]{40}', entry[key]):
failures.append('Invalid pinned SHA: %s' % entry.get('id'))
skill_catalog = parsed.get('sources/skill_catalog.json', {})
skills = skill_catalog.get('entries', [])
skill_ids = [entry.get('id') for entry in skills]
if not all(skill_ids) or len(skill_ids) != len(set(skill_ids)):
failures.append('Missing or duplicate Skill IDs')
for entry in skills:
if not re.fullmatch(r'[0-9a-f]{40}', entry.get('commit', '')):
failures.append('Invalid Skill SHA: ' + str(entry.get('id')))
if entry.get('status') not in skill_catalog.get('definitions', {}):
failures.append('Undefined Skill status: ' + str(entry.get('id')))
if entry.get('runtime_tested') is not False or entry.get('installed') is not False:
failures.append('Unexpected runtime/install claim for this research: ' + str(entry.get('id')))
if '/blob/' + entry.get('commit', '') + '/' not in entry.get('url', ''):
failures.append('Skill URL not pinned: ' + str(entry.get('id')))
research = parsed.get('sources/research_v3.json', {})
researched_files = research.get('files', [])
researched_repos = {item['repository']: item for item in research.get('repositories', [])}
source_keys = [(item.get('repository'), item.get('path')) for item in researched_files]
if len(source_keys) != len(set(source_keys)):
failures.append('V3 research has duplicate file records')
known_urls = set()
for item in researched_files:
label = '%s/%s' % (item.get('repository'), item.get('path'))
commit = item.get('commit', '')
if not re.fullmatch(r'[0-9a-f]{40}', commit) or commit != researched_repos.get(item.get('repository'), {}).get('commit'):
failures.append('V3 file not bound to repository snapshot: ' + label)
expected_url = 'https://github.com/%s/blob/%s/%s' % (item.get('repository'), commit, item.get('path'))
if item.get('url') != expected_url:
failures.append('V3 file URL mismatch: ' + label)
known_urls.add(expected_url)
if not re.fullmatch(r'[0-9a-f]{64}', item.get('sha256', '')):
failures.append('V3 file hash invalid: ' + label)
if item.get('runtime_tested') is not False or item.get('status') not in research.get('definitions', {}):
failures.append('V3 file inspection/runtime claim invalid: ' + label)
ranges = item.get('inspected_ranges', [])
if (item.get('status') == 'downloaded_not_inspected') != (not ranges):
failures.append('V3 download/read status disagrees with ranges: ' + label)
for span in ranges:
if len(span) != 2 or not 1 <= span[0] <= span[1] <= item.get('lines', 0):
failures.append('V3 inspection range out of bounds: ' + label)
if item.get('status') == 'skill_entrypoint_inspected':
matches = [s for s in skills if s.get('url') == expected_url]
if len(matches) != 1 or matches[0].get('source_sha256') != item.get('sha256'):
failures.append('V3 public Skill hash/catalog mismatch: ' + label)
if item.get('references_or_scripts_inspected') is not False:
failures.append('V3 Skill reference claim expanded: ' + label)
v3_summary = research.get('summary', {})
actual_summary = {
'metadata_pinned': sum(bool(i.get('commit')) for i in researched_repos.values()),
'metadata_unavailable': sum(not i.get('commit') for i in researched_repos.values()),
'downloaded_files': len(researched_files),
'selected_files_inspected': sum(i.get('status') != 'downloaded_not_inspected' for i in researched_files),
'download_only': sum(i.get('status') == 'downloaded_not_inspected' for i in researched_files),
'new_public_skill_entrypoints': sum(i.get('status') == 'skill_entrypoint_inspected' for i in researched_files),
'source_entries_total': len(entries), 'skill_entries_total': len(skills)}
if v3_summary != actual_summary:
failures.append('V3 research totals disagree with actual records')
recipes = research.get('recipes', [])
if len(recipes) != 10 or len({r.get('id') for r in recipes}) != 10:
failures.append('V3 requires ten distinct source recipes')
for recipe in recipes:
if not set(recipe.get('source_ids', [])).issubset(set(ids)) or not recipe.get('source_ids'):
failures.append('Recipe source ID missing: ' + str(recipe.get('id')))
chapter = root / recipe.get('chapter', '')
if not chapter.is_file() or '\n## %s.' % recipe.get('section') not in chapter.read_text(encoding='utf-8'):
failures.append('Recipe section missing: ' + str(recipe.get('id')))
if recipe.get('application_status') != 'recipe_not_executed':
failures.append('Unexpected V3 recipe runtime claim: ' + str(recipe.get('id')))
# Catch guessed source paths in the new recipes/workflow, using the exact
# pinned files already inspected, without making fresh network requests.
new_docs = [root / name for name in ['15_source_recipes.md', '16_new_game_workflow.md',
'17_art_audio_implementation.md', '18_research_maintenance.md']]
new_docs.extend((root / 'skills/learn-from-game-source').rglob('*.md'))
for path in new_docs:
for url in re.findall(r'https://github\.com/[^\s)]+', path.read_text(encoding='utf-8')):
base_url = url.split('#', 1)[0]
if '/blob/' in base_url and base_url not in known_urls:
failures.append('New recipe has unrecorded pinned source path: ' + str(path.relative_to(root)) + ': ' + base_url)
lab = parsed.get('evidence/godot_lab/attempt_02/report.json', {})
runtime_root = root / 'examples/godot_workshop'
lab_files = set()
for item in lab.get('source_files', []):
lab_files.add(item['path'])
path = runtime_root / item['path']
if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != item['sha256']:
failures.append('Godot lab receipt source mismatch: ' + item['path'])
actual_runtime = {str(p.relative_to(runtime_root)) for p in runtime_root.rglob('*')
if p.is_file() and p.suffix in ['.gd', '.tscn', '.godot']}
if lab_files != actual_runtime:
failures.append('Godot lab receipt does not cover its complete runtime source')
lab_result = lab.get('lab_result', {})
if lab.get('classification') != 'PASS' or lab_result.get('failures') != [] or not lab_result.get('passed'):
failures.append('Godot lab passing result missing')
if len(lab.get('runs', [])) != 2 or any(r.get('exit_code') != 0 or r.get('timed_out')
or r.get('log_errors') or r.get('owned_group_remaining') for r in lab.get('runs', [])):
failures.append('Godot lab process/log boundary not satisfied')
lab_log = root / 'evidence/godot_lab/attempt_02/tests.log'
if not lab_log.exists() or 'LAB_RESULT ' not in lab_log.read_text():
failures.append('Godot lab raw final marker missing')
if not (root / 'evidence/godot_lab/attempt_01/tests.log').is_file():
failures.append('Godot lab prior failed attempt missing')
provenance = parsed.get('examples/ui_styles/provenance.json', {})
copies = provenance.get('files', [])
for item in copies:
path = root / 'examples/ui_styles' / item['destination']
if not path.is_file() or hashlib.sha256(path.read_bytes()).hexdigest() != item['sha256']:
failures.append('Example copy/hash mismatch: ' + item['destination'])
html = root / 'examples/ui_styles/ui-styles.html'
receipt = parsed.get('examples/ui_styles/original-check-results.json', {})
if not html.exists() or receipt.get('source_sha256') != hashlib.sha256(html.read_bytes()).hexdigest():
failures.append('Original UI receipt does not bind the copied HTML')
if receipt.get('classification') != 'PASS' or len(receipt.get('checks', [])) != 37 or len(receipt.get('layouts', [])) != 12:
failures.append('Unexpected original UI receipt scope')
if not all(item.get('pass') is True for item in receipt.get('checks', [])):
failures.append('Original UI receipt contains a non-passing check')
for path in (p for p in all_files if p.suffix == '.py'):
try:
ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
except SyntaxError as error:
failures.append('Python syntax issue: %s: %s' % (path.relative_to(root), error))
manifest = parsed.get('SHA256SUMS.json', {})
manifest_paths = set()
for item in manifest.get('files', []):
name = item['path']
manifest_paths.add(name)
path = root / name
if not path.is_file() or path.stat().st_size != item['bytes'] or hashlib.sha256(path.read_bytes()).hexdigest() != item['sha256']:
failures.append('Manifest mismatch: ' + name)
# Verification receipts are append-only outputs and explicitly excluded from
# their own input manifest. Delivery ZIP verification covers all entries.
actual_paths = {str(path.relative_to(root)) for path in all_files
if str(path.relative_to(root)) not in ['SHA256SUMS.json', 'verification.json']
and not (path.parent == root / 'verification' and path.suffix == '.json')}
if manifest_paths != actual_paths:
failures.append('Manifest does not enumerate the complete reference content')
secret_pattern = re.compile(rb'(?:sk-[A-Za-z0-9_-]{24,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|Bearer [A-Za-z0-9_-]{24,})')
for path in all_files:
if path.suffix in ['.md', '.json', '.py', '.css', '.html', '.txt']:
if secret_pattern.search(path.read_bytes()):
failures.append('Potential credential material in: ' + str(path.relative_to(root)))
result = {'classification': 'PASS' if not failures else 'FAIL',
'scope': 'Reference integrity and historical receipt/source binding only; no new game/browser/device run',
'checked_at_utc': datetime.now(timezone.utc).isoformat(),
'relative_links_checked': links, 'source_entries': len(entries),
'skill_entries': len(skills), 'godot_lab_source_files': len(lab_files),
'copied_example_files': len(copies), 'manifest_files': len(manifest_paths),
'v3_research_files': len(researched_files), 'v3_source_recipes': len(recipes),
'failures': failures}
if args.report:
with args.report.open('x', encoding='utf-8') as handle:
json.dump(result, handle, ensure_ascii=False, indent=2)
handle.write('\n')
print(json.dumps(result, ensure_ascii=False, indent=2))
return 1 if failures else 0
if __name__ == '__main__':
sys.exit(main())
+135
View File
@@ -0,0 +1,135 @@
"""Run the original lab in a fresh POSIX evidence directory; never install tools."""
from pathlib import Path
from datetime import datetime, timezone
import argparse
import hashlib
import json
import os
import re
import shutil
import signal
import subprocess
import time
def group_alive(pgid):
# macOS can briefly return EPERM while a reaped process group disappears.
# Retry that ambiguity; persistent EPERM conservatively means not cleared.
for attempt in range(5):
try:
os.killpg(pgid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
if attempt == 4:
return True
time.sleep(0.01)
def stop_owned_group(child):
"""TERM, reap/check, then KILL only the session created for this child."""
for sig in (signal.SIGTERM, signal.SIGKILL):
if group_alive(child.pid):
try:
os.killpg(child.pid, sig)
except (ProcessLookupError, PermissionError):
pass
deadline = time.monotonic() + 2
while time.monotonic() < deadline:
child.poll()
if not group_alive(child.pid):
return False
time.sleep(0.05)
child.poll()
return group_alive(child.pid)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--godot', required=True, help='Exact Godot executable')
parser.add_argument('--output', type=Path, required=True, help='Must not exist')
args = parser.parse_args()
if os.name != 'posix':
parser.error('This bounded process-group wrapper is POSIX-only; use your platform runner.')
root = Path(__file__).resolve().parent.parent
source = root / 'examples/godot_workshop'
out = args.output.resolve()
out.mkdir(parents=True, exist_ok=False)
print(json.dumps({'owned_pid': os.getpid(), 'pgid': os.getpgid(0),
'output': str(out), 'stage_timeout_seconds': 20}), flush=True)
project = out / 'project'
shutil.copytree(source, project, ignore=shutil.ignore_patterns('.godot', '__pycache__'))
manifest = [{'path': str(p.relative_to(source)), 'bytes': p.stat().st_size,
'sha256': hashlib.sha256(p.read_bytes()).hexdigest()}
for p in sorted(source.rglob('*')) if p.is_file()
and '.godot' not in p.parts and p.suffix != '.pyc']
(out / 'source.json').write_text(json.dumps(manifest, indent=2) + '\n')
version = subprocess.Popen([args.godot, '--headless', '--version'],
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
text=True, start_new_session=True)
print(json.dumps({'stage': 'version', 'owned_pid': version.pid,
'pgid': version.pid, 'timeout_seconds': 5}), flush=True)
try:
version_stdout, version_stderr = version.communicate(timeout=5)
except subprocess.TimeoutExpired:
remaining = stop_owned_group(version)
(out / 'version-error.json').write_text(json.dumps({
'classification': 'INVALID', 'reason': 'version timeout',
'owned_pid': version.pid, 'owned_group_remaining': remaining}, indent=2) + '\n')
return 1
version_remaining = group_alive(version.pid)
if version.returncode != 0 or version_remaining:
remaining = stop_owned_group(version) if version_remaining else False
(out / 'version-error.json').write_text(json.dumps({
'classification': 'INVALID', 'reason': 'version command failed or left a child',
'exit_code': version.returncode, 'stderr': version_stderr,
'owned_pid': version.pid, 'owned_group_remaining': remaining}, indent=2) + '\n')
return 1
report = {'engine': version_stdout.strip(), 'started_at_utc': datetime.now(timezone.utc).isoformat(),
'runner_sha256': hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
'source_files': manifest, 'runs': [], 'scope':
'Headless domain, parsed input, layout geometry and PCM only; no visual/listening/device acceptance'}
bad_log = re.compile(r'SCRIPT ERROR|Parse Error|ERROR:|ObjectDB instances leaked|resources still in use', re.I)
for stage, flags in [('import', ['--import']), ('tests', ['--script', 'res://tests/run_tests.gd'])]:
command = [args.godot, '--headless', '--audio-driver', 'Dummy', '--path', str(project)] + flags
with (out / (stage + '.log')).open('xb') as log:
child = subprocess.Popen(command, stdout=log, stderr=subprocess.STDOUT, start_new_session=True)
print(json.dumps({'stage': stage, 'owned_pid': child.pid, 'pgid': child.pid,
'timeout_seconds': 20}), flush=True)
timed_out = False
try:
code = child.wait(timeout=20)
except subprocess.TimeoutExpired:
timed_out = True
stop_owned_group(child)
code = child.poll()
log_text = (out / (stage + '.log')).read_text(errors='replace')
cleanup_required = group_alive(child.pid)
group_remaining = stop_owned_group(child) if cleanup_required else False
run = {'stage': stage, 'command': command, 'owned_pid': child.pid,
'exit_code': code, 'timed_out': timed_out,
'log_errors': bad_log.findall(log_text), 'cleanup_required': cleanup_required,
'owned_group_remaining': group_remaining}
report['runs'].append(run)
print(json.dumps(run), flush=True)
if code != 0 or timed_out or run['log_errors'] or cleanup_required:
break
if stage == 'tests':
lines = [line[len('LAB_RESULT '):] for line in log_text.splitlines() if line.startswith('LAB_RESULT ')]
if len(lines) == 1:
report['lab_result'] = json.loads(lines[0])
ok = len(report['runs']) == 2 and all(r['exit_code'] == 0 and not r['timed_out']
and not r['log_errors'] and not r['cleanup_required']
and not r['owned_group_remaining'] for r in report['runs'])
ok = ok and bool(report.get('lab_result')) and not report.get('lab_result', {}).get('failures', ['missing marker'])
report['classification'] = 'PASS' if ok else ('INVALID' if any(r['timed_out'] or r['cleanup_required']
or r['owned_group_remaining']
for r in report['runs']) else 'FAIL')
(out / 'report.json').write_text(json.dumps(report, ensure_ascii=False, indent=2) + '\n')
print(report['classification'], flush=True)
return 0 if ok else 1
if __name__ == '__main__':
raise SystemExit(main())