@babylonjs-toolkit/agent 1.1.36 → 1.1.42

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,169 @@
1
+ 'use strict';
2
+
3
+ /**
4
+ * Runs one child process for the bridge (T24 step 4, D41): never through a shell, always with a hard
5
+ * timeout, stdout capped, stderr streamed line by line.
6
+ */
7
+
8
+ const { spawn: defaultSpawn } = require('child_process');
9
+
10
+ const MAX_STDOUT_BYTES = 5 * 1024 * 1024;
11
+ const MAX_STDERR_BYTES = 1024 * 1024;
12
+ const KILL_GRACE_MS = 5_000;
13
+
14
+ /**
15
+ * @typedef {{ code: number|null, stdout: string, stderr: string, timedOut: boolean, aborted: boolean }} RunResult
16
+ * @typedef {(file: string, args: string[], opts?: RunOptions) => Promise<RunResult>} RunProcess
17
+ * @typedef {{ cwd?: string, timeoutMs?: number, signal?: AbortSignal, onLine?: (line: string) => void, env?: NodeJS.ProcessEnv, spawn?: typeof defaultSpawn }} RunOptions
18
+ * @typedef {(file: string, args: string[], opts?: LaunchOptions) => Promise<RunResult>} LaunchDetached
19
+ * @typedef {{ cwd?: string, env?: NodeJS.ProcessEnv, waitMs?: number, signal?: AbortSignal, spawn?: typeof defaultSpawn }} LaunchOptions
20
+ */
21
+
22
+ /**
23
+ * An ordinary job: in the helper's process group, so Ctrl-C and a cancel stop it with the helper.
24
+ * @type {RunProcess}
25
+ */
26
+ function runProcess(file, args, { cwd, timeoutMs = 120_000, signal, onLine, env, spawn = defaultSpawn } = {}) {
27
+ return new Promise((resolve) => {
28
+ /** @type {Buffer[]} */
29
+ const out = [];
30
+ let outBytes = 0;
31
+ let err = '';
32
+ let partial = '';
33
+ let timedOut = false;
34
+ let aborted = false;
35
+ let settled = false;
36
+ /** @type {NodeJS.Timeout|undefined} */
37
+ let killTimer;
38
+
39
+ /** @type {import('child_process').ChildProcess} */
40
+ let child;
41
+ try {
42
+ child = spawn(file, args, { cwd, env, shell: false, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
43
+ } catch (e) {
44
+ resolve({ code: null, stdout: '', stderr: String(e && e.message ? e.message : e), timedOut, aborted });
45
+ return;
46
+ }
47
+
48
+ const stop = () => {
49
+ if (child.exitCode !== null || child.signalCode !== null) return;
50
+ child.kill('SIGTERM');
51
+ killTimer = setTimeout(() => {
52
+ if (child.exitCode === null && child.signalCode === null) child.kill('SIGKILL');
53
+ }, KILL_GRACE_MS);
54
+ killTimer.unref();
55
+ };
56
+
57
+ const timer = setTimeout(() => {
58
+ timedOut = true;
59
+ stop();
60
+ }, timeoutMs);
61
+ timer.unref();
62
+
63
+ const onAbort = () => {
64
+ aborted = true;
65
+ stop();
66
+ };
67
+ if (signal) {
68
+ if (signal.aborted) onAbort();
69
+ else signal.addEventListener('abort', onAbort, { once: true });
70
+ }
71
+
72
+ /** @param {string} line */
73
+ const emitLine = (line) => {
74
+ const trimmed = line.replace(/\r$/, '');
75
+ if (onLine && trimmed.trim()) {
76
+ try {
77
+ onLine(trimmed);
78
+ } catch {
79
+ // a progress sink must never break the run
80
+ }
81
+ }
82
+ };
83
+
84
+ child.stdout.on('data', (/** @type {Buffer} */ chunk) => {
85
+ if (outBytes >= MAX_STDOUT_BYTES) return;
86
+ const room = MAX_STDOUT_BYTES - outBytes;
87
+ const piece = chunk.length > room ? chunk.subarray(0, room) : chunk;
88
+ out.push(piece);
89
+ outBytes += piece.length;
90
+ });
91
+
92
+ child.stderr.on('data', (/** @type {Buffer} */ chunk) => {
93
+ const text = chunk.toString('utf8');
94
+ if (err.length < MAX_STDERR_BYTES) err += text;
95
+ partial += text;
96
+ const lines = partial.split('\n');
97
+ partial = lines.pop() || '';
98
+ for (const line of lines) emitLine(line);
99
+ });
100
+
101
+ /** @param {number|null} code @param {string} [extraErr] */
102
+ const finish = (code, extraErr) => {
103
+ if (settled) return;
104
+ settled = true;
105
+ clearTimeout(timer);
106
+ if (killTimer) clearTimeout(killTimer);
107
+ if (signal) signal.removeEventListener('abort', onAbort);
108
+ if (partial) emitLine(partial);
109
+ resolve({
110
+ code,
111
+ stdout: Buffer.concat(out).toString('utf8'),
112
+ stderr: extraErr ? `${err}${err ? '\n' : ''}${extraErr}` : err,
113
+ timedOut,
114
+ aborted,
115
+ });
116
+ };
117
+
118
+ child.on('error', (e) => finish(null, e.message));
119
+ child.on('close', (code) => finish(code));
120
+ });
121
+ }
122
+
123
+ /**
124
+ * Starts something that must OUTLIVE the helper — the Unity Editor (`unity open`). The launcher runs
125
+ * detached (its own process group/session, so Ctrl-C in the helper's terminal never reaches the Editor
126
+ * it starts), with no pipes (an Editor that inherited a pipe to a dead helper dies on its next write),
127
+ * and unref'd (the helper can exit while it runs). It is never killed on cancel or timeout: stopping
128
+ * the launcher would stop the Editor it is starting.
129
+ *
130
+ * Resolves with the launcher's exit code when it exits within `waitMs` (`unity open` returns at once;
131
+ * a non-zero code means the Editor was not started), else as launched (code 0). Output is not
132
+ * captured — the caller confirms the Editor by polling `unity status`. A cancel ends the WAIT (never
133
+ * the launcher).
134
+ * @type {LaunchDetached}
135
+ */
136
+ function launchDetached(file, args, { cwd, env, waitMs = 30_000, signal, spawn = defaultSpawn } = {}) {
137
+ return new Promise((resolve) => {
138
+ /** @type {import('child_process').ChildProcess} */
139
+ let child;
140
+ try {
141
+ child = spawn(file, args, { cwd, env, detached: true, stdio: 'ignore', shell: false, windowsHide: true });
142
+ } catch (e) {
143
+ resolve({ code: null, stdout: '', stderr: String(e && e.message ? e.message : e), timedOut: false, aborted: false });
144
+ return;
145
+ }
146
+ child.unref();
147
+ let settled = false;
148
+ /** @param {number|null} code @param {string} [stderr] */
149
+ const finish = (code, stderr = '') => {
150
+ if (settled) return;
151
+ settled = true;
152
+ clearTimeout(timer);
153
+ if (signal) signal.removeEventListener('abort', onAbort);
154
+ resolve({ code, stdout: '', stderr, timedOut: false, aborted: Boolean(signal && signal.aborted) });
155
+ };
156
+ // NOT unref'd: the child is, so this timer is what keeps the helper alive while it waits for the
157
+ // launcher to exit (found live — with both unref'd, a process with nothing else pending exited mid-job).
158
+ const timer = setTimeout(() => finish(0), waitMs);
159
+ const onAbort = () => finish(null);
160
+ if (signal) {
161
+ if (signal.aborted) onAbort();
162
+ else signal.addEventListener('abort', onAbort, { once: true });
163
+ }
164
+ child.on('error', (e) => finish(null, e.message));
165
+ child.on('exit', (code) => finish(code));
166
+ });
167
+ }
168
+
169
+ module.exports = { runProcess, launchDetached, MAX_STDOUT_BYTES, KILL_GRACE_MS };
@@ -0,0 +1,39 @@
1
+ // SOURCE: AgentReference references/scripts/bt-bootstrap.cs (the babylontoolkit/agent repo) - keep in sync.
2
+ // Everything below the marker line is a VERBATIM copy of that file. tests/bridge-unity-scaffold.test.js pins its
3
+ // sha256 (7970a089b7600e344e8c2ac482d1480bcd8d9567853fc8248f0e792d8b66f824), recorded from the source at copy time: re-copy the file and update the hash together.
4
+ // ---- verbatim from here ----
5
+ // Headless replication of CVPanel.OnEnable() - the Scene Exporter bootstrap.
6
+ // Safe to run in a GUI Editor too (it is idempotent).
7
+ var sb = new System.Text.StringBuilder();
8
+ CanvasTools.CanvasToolsExporter.Initialize();
9
+ CanvasToolsInfo.DefaultProjectFolder = UnityTools.GetDefaultExportFolder();
10
+ UnityTools.ValidateRequirements();
11
+ UnityTools.ValidateImageLibrary();
12
+ UnityTools.ValidateProjectScript();
13
+ UnityTools.ValidateProjectLayers();
14
+ UnityTools.ValidateColorSpaceSettings();
15
+ UnityTools.ValidateGraphicsLibSettings();
16
+ UnityTools.ValidateProjectRootNamespace();
17
+ UnityTools.ValidateProjectShaderSettings();
18
+ UnityTools.ValidateReflectionProbeSettings();
19
+ // The GPU Resident Drawer is Unity-only batching the export never uses; left on, a failed registration makes
20
+ // camera captures render only the sky. Toolkit 9.25+, dialog-free.
21
+ sb.Append("residentDrawerOff=" + RenderPathTools.DisableResidentDrawer(false) + " ");
22
+ if (System.String.IsNullOrWhiteSpace(CanvasToolsInfo.Instance.ProductShortName)
23
+ && !System.String.IsNullOrWhiteSpace(UnityEngine.Application.productName))
24
+ CanvasToolsInfo.Instance.ProductShortName = UnityEngine.Application.productName;
25
+ if (CanvasToolsInfo.Instance.InlineNonceHash == null) CanvasToolsInfo.Instance.InlineNonceHash = "";
26
+ string root = UnityTools.GetRootPath();
27
+ string pj = System.IO.Path.Combine(root, "package.json");
28
+ if (!System.IO.File.Exists(pj)) {
29
+ string j = "{\r\n\t\"name\": \"" + BabylonCore.Info.NAME + "\",\r\n\t\"version\": \"" + BabylonCore.Info.VERSION
30
+ + "\",\r\n\t\"description\": \"Babylon Toolkit Project\",\r\n\t\"license\": \"MIT\",\r\n\t\"devDependencies\": {\r\n\t\t\"typescript\": \"^"
31
+ + BabylonCore.Info.TYPESCRIPT + "\"\r\n\t}\r\n}\r\n";
32
+ System.IO.File.WriteAllText(pj, j);
33
+ sb.Append("packageJson=written ");
34
+ } else sb.Append("packageJson=present ");
35
+ CanvasToolsInfo.SaveSettings();
36
+ UnityEditor.AssetDatabase.Refresh();
37
+ sb.Append("exportRoot=" + CanvasToolsInfo.DefaultProjectFolder);
38
+ sb.Append(" pro=" + ToolkitManager.IsPro());
39
+ return sb.ToString();
@@ -0,0 +1,27 @@
1
+ // SOURCE: AgentReference references/scripts/bt-newscene.cs (the babylontoolkit/agent repo) - keep in sync.
2
+ // Everything below the marker line is a VERBATIM copy of that file. tests/bridge-unity-scaffold.test.js pins its
3
+ // sha256 (00829f0a2eb162dcf63d56f54a69e16dd1d5decd3c7addcfef41e34af3d2ff97), recorded from the source at copy time: re-copy the file and update the hash together.
4
+ // ---- verbatim from here ----
5
+ // Create a starter scene WITH LightingSettings (order: NewScene -> build -> save -> lighting).
6
+ string sceneName = "Level01";
7
+ var scene = UnityEditor.SceneManagement.EditorSceneManager.NewScene(
8
+ UnityEditor.SceneManagement.NewSceneSetup.DefaultGameObjects,
9
+ UnityEditor.SceneManagement.NewSceneMode.Single);
10
+ var ground = UnityEngine.GameObject.CreatePrimitive(UnityEngine.PrimitiveType.Plane);
11
+ ground.name = "Ground"; ground.transform.localScale = new UnityEngine.Vector3(5f,1f,5f);
12
+ UnityEngine.RenderSettings.ambientMode = UnityEngine.Rendering.AmbientMode.Skybox;
13
+ System.IO.Directory.CreateDirectory(UnityEngine.Application.dataPath + "/Scenes");
14
+ UnityEditor.SceneManagement.EditorSceneManager.SaveScene(scene, "Assets/Scenes/" + sceneName + ".unity");
15
+ UnityEngine.LightingSettings ls = null;
16
+ if (!UnityEditor.Lightmapping.TryGetLightingSettings(out ls) || ls == null) {
17
+ var nls = new UnityEngine.LightingSettings(); nls.name = "BtLightingSettings";
18
+ System.IO.Directory.CreateDirectory(UnityEngine.Application.dataPath + "/Settings");
19
+ UnityEditor.AssetDatabase.CreateAsset(nls, "Assets/Settings/BtLightingSettings.lighting");
20
+ UnityEditor.Lightmapping.lightingSettings = nls;
21
+ }
22
+ // Assigning lightingSettings does NOT mark the scene dirty, so SaveOpenScenes() skips it
23
+ // and the reference is lost the next time the scene is loaded (sec 8.1).
24
+ UnityEditor.SceneManagement.EditorSceneManager.MarkSceneDirty(scene);
25
+ UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes();
26
+ UnityEditor.AssetDatabase.SaveAssets();
27
+ return "scene=Assets/Scenes/" + sceneName + ".unity lighting=ok";
package/lib/doctor.js CHANGED
@@ -7,6 +7,10 @@ const { resolveTargets } = require('./targets');
7
7
  const { listSkills } = require('./payload');
8
8
  const { hasPersona } = require('./persona');
9
9
  const { hasCodexNetwork } = require('./codex-config');
10
+ const { readSettings } = require('./bridge/config');
11
+ const { serviceStatus, hostDeps } = require('./bridge/service');
12
+ const { discoverUnity } = require('./bridge/unity/discover');
13
+ const { discoverBlender } = require('./bridge/blender/discover');
10
14
 
11
15
  /**
12
16
  * Verify an install.
@@ -49,6 +53,26 @@ function doctor(opts = {}) {
49
53
  if (!hasCodexNetwork(file)) missing.push(`${file} (sandbox_workspace_write.network_access = true)`);
50
54
  }
51
55
 
56
+ // Informational only (D46): a user who only wants skills must still get INSTALL OK.
57
+ const { servers } = readSettings();
58
+ let unityCli = false;
59
+ let blender = null;
60
+ /** @type {{ installed: boolean, running: boolean|null }} */
61
+ let svc = { installed: false, running: null };
62
+ try {
63
+ const st = serviceStatus(opts.serviceDeps || hostDeps());
64
+ svc = { installed: st.installed, running: st.running };
65
+ } catch {
66
+ // informational only — never affects ok
67
+ }
68
+ try {
69
+ unityCli = Boolean(discoverUnity({ cwd: process.cwd() }).cli);
70
+ const found = discoverBlender({});
71
+ blender = found ? found.version : null;
72
+ } catch {
73
+ // informational only — never affects ok
74
+ }
75
+
52
76
  return {
53
77
  ok: missing.length === 0,
54
78
  missing,
@@ -59,6 +83,15 @@ function doctor(opts = {}) {
59
83
  instructionFiles: resolved.instructionFiles.map((f) => f.file),
60
84
  configFiles: resolved.configFiles.map((f) => f.file),
61
85
  },
86
+ bridge: {
87
+ paired: servers.length > 0,
88
+ server: servers.length ? servers[0].server : null,
89
+ servers: servers.map((c) => c.server),
90
+ service: svc.installed ? 'installed' : 'not installed',
91
+ serviceRunning: svc.running,
92
+ unityCli,
93
+ blender,
94
+ },
62
95
  };
63
96
  }
64
97
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.1.36",
3
+ "version": "1.1.42",
4
4
  "description": "Installs the Babylon Toolkit Desktop Agent for Claude Code, Codex, GitHub Copilot, Gemini CLI and Antigravity.",
5
5
  "keywords": [
6
6
  "babylonjs",
@@ -7,7 +7,7 @@ allowed-tools: Read, Grep, Glob, Edit, Write, Bash, WebFetch(domain:raw.githubus
7
7
  Run tasks from a plan: build each one with its tests, have an independent verifier check it, and only then tick its box. Follow the project's agent instructions (AGENTS.md / CLAUDE.md / .github/copilot-instructions.md). The user's message after the skill name is the `arguments`.
8
8
 
9
9
  ```
10
- /bt-execute [--auto-pilot] [--strict] <plan> [task] [brief]
10
+ /bt-execute [--auto-pilot] [--strict] [--no-time-limit] <plan> [task] [brief]
11
11
 
12
12
  /bt-execute @plan.md # NEXT: the next unchecked task
13
13
  /bt-execute @plan.md T4 # one task
@@ -17,15 +17,17 @@ Run tasks from a plan: build each one with its tests, have an independent verifi
17
17
  /bt-execute @plan.md "mind the physics layer" # a brief shapes HOW, never WHICH task
18
18
  /bt-execute --strict @plan.md ALL # adversarial verifier on every task
19
19
  /bt-execute --auto-pilot @plan.md ALL # unattended; combine with --strict if wanted
20
+ /bt-execute --no-time-limit @plan.md ALL # turn off the default TIME MATTERS mode
20
21
  ```
21
22
 
22
- - Strip `--auto-pilot` / `--strict` first (anywhere in the arguments, never part of the brief). `<plan>` is required — if missing, ask (auto-pilot: say so and end). Never guess a path.
23
+ - Strip `--auto-pilot` / `--strict` / `--no-time-limit`, and any literal `TIME MATTERS`, first (anywhere in the arguments, never part of the brief). `<plan>` is required — if missing, ask (auto-pilot: say so and end). Never guess a path.
23
24
  - `[task]` is the token right after the plan, only if it is `T<id>`, `T<a>-T<b>`, `T<a>-`, `NEXT`, `NEXT:<n>` or `ALL` (case-insensitive). Otherwise it is part of the brief, and the task defaults to `NEXT` (`ALL` under auto-pilot). Never ask which task to run.
24
25
  - A range is a slice of the checklist **in file order** (sub-tasks like `T3.1` between the endpoints included). An unknown id → list the available ids and stop. A reversed range → error; never swap it. Tasks outside the slice are never touched.
25
26
  - Tasks already `- [x]` are skipped — that is what makes every mode resumable. Nothing left to do → say so and stop. Except in `ALL` / range / `NEXT:<n>` runs, do one task and do not continue to the next.
26
27
 
27
28
  ## Ground rules
28
29
 
30
+ - **TIME MATTERS** — on by default; `--no-time-limit` turns it off. Treat the arguments as ending with `TIME MATTERS`: the user is waiting on this run, so finish quickly — follow the *Work fast* rules below to the letter, take the direct route to each task's Acceptance, and do not re-read what you already have. Begin every implementer and verifier prompt with `TIME MATTERS.` Print `⏱️ [bt-execute] TIME MATTERS` at the start (`--no-time-limit`: print `⏱️ [bt-execute] No time limit`, and do not add it). Speed never relaxes tests, the independent verifier, live checks, or "tick only on PASS".
29
31
  - **Scope.** Implement only the selected task(s). No "while I'm here" work on other tasks. Ambiguous, or blocked by an unfinished task → stop and tell the user *(auto-pilot: decide and log it)*.
30
32
  - **Read the docs once.** For Babylon work, if you have not read the Agent Reference this session, fetch it once — https://raw.githubusercontent.com/babylontoolkit/agent/main/reference.md — plus only the sub-documents the plan's tasks need. It is the authority for conventions and API. Fetch fails → stop and tell the user *(auto-pilot: retry 3×, then continue on what you know and log it)*. Read the plan's checklist and the parts of `SPEC.md` the tasks touch; re-read after a context compaction.
31
33
  - **SPEC.md** constrains how you build. If the code and SPEC.md disagree, stop and tell the user *(auto-pilot: decide which is right, fix SPEC.md in the same task, log it)*. When a task changes architecture, a system, a convention or a dependency, SPEC.md must end up matching — normally the plan's final `Update SPEC.md` task; if the plan has none, do it anyway; a new dependency is recorded in SPEC.md by the task that introduces it. Follow SPEC.md's "How to update this spec". **Write the product, never the procedure** — no capture protocols, tool lists, ledgers or gates: recorded there, they become a bar every later feature must clear.
@@ -42,7 +44,7 @@ Work in **phases**: a `### Phase N` group in the plan, or — if the plan has no
42
44
  4. **Fix loop** for a task that failed: fix the code in the context that wrote it; re-run its tests; re-verify with a **fresh** verifier given only the failed items and the evidence (`--strict`: the whole task). A records-only slip (a stale number or note) is fixed directly and re-checked by you. 3 attempts (`--strict`: 5), each changing something material; stop early if two attempts fail the same way with no new idea. Still failing → leave it unticked, stop and report *(auto-pilot: defer and continue)*.
43
45
  5. **Report:** tasks done (for `ALL` / ranges: the range asked for, completed/total, and whether the plan is now finished; if fewer than `n` tasks remained for `NEXT:<n>`, say so), files changed, tests run (`tests: 4 passed (implementer) · verifier-checked`), verifier result (`verified (independent subagent)` or `verified (self)`), and the next task id — for reference only.
44
46
 
45
- **The verifier is told:** *"Confirm each task's Acceptance is genuinely met and run its `Verify` commands against the stated expected output. Re-run the tests and the relevant suite once; check they really cover the Acceptance and named edge cases and could fail — missing or vacuous tests are a FAIL. Read the diff for real defects: logic errors, broken callers, unhandled edge cases the plan names, a documented behavior dropped or inverted, a sibling-skill template re-implemented instead of copied. For any task whose correctness shows only at runtime — rendering, UI, interaction, Unity↔Babylon parity — check it live in the browser (and Unity where relevant) whether or not the plan marks it `live`, and do the plan's final end-to-end check live: look at the running result, beside the reference image when there is one, and judge it as a user would; passing unit tests never substitute. Do all of a phase's live checks in one session on the already-running dev server, and re-export from Unity only if the phase changed Unity-side content. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence, listing records-only slips separately."*
47
+ **The verifier is told:** *"Confirm each task's Acceptance is genuinely met and run its `Verify` commands against the stated expected output. Re-run the tests and the relevant suite once; check they really cover the Acceptance and named edge cases and could fail — missing or vacuous tests are a FAIL. Read the diff for real defects: logic errors, broken callers, unhandled edge cases the plan names, a documented behavior dropped or inverted, a sibling-skill template re-implemented instead of copied. For any task whose correctness shows only at runtime — rendering, UI, interaction, Unity↔Babylon parity — check it live in the browser (and Unity where relevant) whether or not the plan marks it `live`, and do the plan's final end-to-end check live: look at the running result, beside the reference image when there is one, and judge it as a user would; passing unit tests never substitute. Do all of a phase's live checks in one session on the already-running dev server, and re-export from Unity only if the phase changed that scene's export — then only the project and the scenes the phase works on. Treat an absolute count in the plan as 'named tests pass, no new failures'. [SCOPE] Return PASS/FAIL per task with evidence, listing records-only slips separately."*
46
48
 
47
49
  `[SCOPE]` is one of two sentences. **Standard:** *"Do not add mutation testing, fuzzing, restarts or audits of untouched files unless something you found points there; aim for about 25 tool calls and report rather than expand."* **`--strict`:** *"Be adversarial: actively look for any reason the Acceptance is NOT met, using whatever you judge worthwhile — mutation checks against the tests, randomized inputs, re-deriving values from the plan's Decisions and Design Reference, live QA of every rendered or exported surface."*
48
50
 
@@ -55,6 +57,7 @@ For a task built on a sibling skill (e.g. bt-design's 3D-Hero-Scroll), give the
55
57
  Writing the code is about a tenth of a run; keep the loop around it short.
56
58
 
57
59
  - **Iterate narrow, confirm wide.** While getting something to work, run only that task's tests, the fastest build the repo has, and one low-resolution capture on one engine. The full test chain, full build and any wider check (second engine, full resolution, numeric parity gates) run **once**, when the phase is ready to verify. A parity gate is never loosened to pass.
60
+ - **Export minimally.** Re-export only the Unity project being tested, only the scenes the task works on, and only when the change actually alters that scene's export. Never re-export other scenes or projects "for consistency" — they pick the change up at their next natural export. Exports are the slowest step of a run; brief every implementer and verifier with this rule, and never widen a plan's export step in a brief.
58
61
  - **Never sleep-poll.** No `until …; do sleep N; done`. Run long commands in the foreground with a generous timeout, or in the background and wait for the completion notice.
59
62
  - **Judge visuals by looking** — screenshot the running result and compare it to what it must match. Build numeric gates only when the plan asks for them.
60
63
  - **Reuse the project's tools; keep evidence light.** No one-off tools per task; no ledgers, md5 or environment records, archives or checked-in capture trees unless the plan asks. The report (and the run log) is the record.
@@ -1,6 +1,6 @@
1
1
  ---
2
2
  name: bt-gauntlet
3
- description: "The Babylon Toolkit Gauntlet Skill runs a loop-engineering gauntlet: builders versus fresh harsh critics, scored against a LOCKED target image from LOCKED cameras, looping until a success condition, boundary, or stall rule stops it. Two deliverable kinds share one loop — BabylonJS / Babylon Toolkit web games, and anything authored in Unity (game levels and the individual assets in them: baked GI, IBL, reflection probes, terrain, fog, tonemapping, materials, models), with headless Blender as the tool for low-level model work. Unity plus the Toolkit exporter is the content-creation surface and asset manager, shipping interactive glTF that BabylonJS loads; iteration stays inside Unity on camera snapshots and the export is a deliberate checkpoint, not a per-round tax. Fully RESUMABLE: each job lives in its own _gauntlet/<name>/ workspace, so the user can stop any time (daily limits, calling it a night) and continue weeks later in a brand-new session with `/bt-gauntlet --resume <name>`. Use for a long-running, self-improving build of an ambitious game artifact, level, or asset (e.g. `/bt-gauntlet build me a rain-soaked neon alley level at the fidelity of this reference image`)."
3
+ description: "The Babylon Toolkit Gauntlet Skill runs a loop-engineering gauntlet: builders versus fresh harsh critics, scored against a LOCKED target image from LOCKED cameras, looping until a success condition, boundary, or stall rule stops it. Two deliverable kinds share one loop — BabylonJS / Babylon Toolkit web games, and anything authored in Unity (game levels and the individual assets in them: baked GI, IBL, reflection probes, terrain, fog, tonemapping, materials, models), with headless Blender as the tool for low-level model work. Unity plus the Toolkit exporter is the content-creation surface and asset manager, shipping interactive glTF that BabylonJS loads; iteration stays inside Unity on camera snapshots, relying on Unity→Babylon parity, with export + browser checkpoints at milestones rather than every round. Fully RESUMABLE: each job lives in its own _gauntlet/<name>/ workspace, so the user can stop any time (daily limits, calling it a night) and continue weeks later in a brand-new session with `/bt-gauntlet --resume <name>`. Use for a long-running, self-improving build of an ambitious game artifact, level, or asset (e.g. `/bt-gauntlet build me a rain-soaked neon alley level at the fidelity of this reference image`)."
4
4
  allowed-tools: Read, Grep, Glob, Edit, Write, Bash, WebFetch(domain:raw.githubusercontent.com), Agent, Task
5
5
  ---
6
6
 
@@ -98,13 +98,13 @@ The loop may not start until **every slot of the chosen template is filled**. Th
98
98
  Interview batches:
99
99
 
100
100
  0. **NAME** — Confirm the job's slug. It becomes `_gauntlet/<name>/` and must not collide with an existing job.
101
- 1. **DELIVERABLE KIND + DELIVERABLE** — Which of the three kinds is this: a **web game**, a **Unity level for export**, or a **Blender model**? Then what exactly ships (playable browser demo, one polished level, a hero asset with LODs...)? Module style: ES6/ESM default; UMD only if explicitly demanded. New project or existing? Target folder. **Read the matching pipeline reference now** and run its prerequisite gate before going further — a failed gate (no Pro licence, no GUI bootstrap, no Blender) changes what is worth agreeing to.
101
+ 1. **DELIVERABLE KIND + DELIVERABLE** — Which of the three kinds is this: a **web game**, a **Unity level for export**, or a **Blender model**? Then what exactly ships (playable browser demo, one polished level, a hero asset with LODs...)? Module style: ES6/ESM default; UMD only if explicitly demanded. New project or existing? Target folder. **Read the matching pipeline reference now** and run its prerequisite gate before going further — a failed gate (no Pro licence, no toolkit bootstrap, no rendering Editor for snapshots, no Blender) changes what is worth agreeing to.
102
102
  2. **OBJECTIVE** — The exact outcome that must become true, as one testable sentence. Rewrite with the user until it is inspectable.
103
103
  3. **THE TARGET + CAMERAS** — Per `references/target-images.md`: does the user have reference media, is there an existing artifact to refine, or do we generate the target? Agree the target image(s), run the **reachability pass** (Reachable / Approximable / **OUT OF REACH**), and agree the **locked cameras** — one per target, three to five, including a detail crop. Settle the **image-generation backend** too (kie by default, the Higgsfield CLI if it is installed and signed in or the user asks for it — `target-images.md` §1a) and record it in `pipeline.md`. Plus numeric benchmarks: target FPS @ resolution, max load time, draw-call / texture / triangle budgets. If the user has no benchmark, making a defensible one is part of the interview, not skipped.
104
104
  4. **RUBRIC + PASS THRESHOLD** — Confirm the rubric axes from `references/critic-rubrics.md` (or amend them for this job) and the score a part must reach to pass. Default: **8.0 / 10 plus every hard gate green.**
105
105
  5. **SUCCESS CONDITION** — When is the loop DONE? (e.g. "every part scores ≥8/10 from a fresh critic; sustained 60 FPS @1080p in Chrome; zero console errors; the final integration critic passes"). Success and failure defined separately.
106
106
  6. **BOUNDARIES** — Time/cost expressed in **rounds and attempts, not wall-clock** (wall-clock cannot survive a two-week pause; counters can): max total rounds, max attempts per part before a forced strategy change, max consecutive no-improvement rounds. Permission gates: no deploy, no purchases/paid services, no credentials, no destructive ops, no contacting anyone — without explicit approval. For `unity`: the **bake tier policy** (how many rounds at preview tier before a production bake). Escalation rules: what blocks and waits for the user.
107
- 7. **Kind specifics** — For `web-game`: genre & camera, physics (Havok default), input, audio, asset pipeline, scene scale, target browsers, and explicit scope cuts. For `unity`: which scene (that is where the work is authored, rendered and judged), render pipeline, terrain in scope?, existing lighting to preserve, whether Blender model work is in scope (and if so which assets, in-place or new path, tri budget, texel density, rig to match), the bake tier policy, and the checkpoint cadence (round 1 + when done, by default). The Editor runs in **copilot mode** — `-nographics` cannot render the in-loop snapshots. What finally gets exported — the whole level, or an individual asset as a container — is the user's call at checkpoint time, not something to decide now.
107
+ 7. **Kind specifics** — For `web-game`: genre & camera, physics (Havok default), input, audio, asset pipeline, scene scale, target browsers, and explicit scope cuts. For `unity`: which scene (that is where the work is authored, rendered and judged), render pipeline, terrain in scope?, existing lighting to preserve, whether Blender model work is in scope (and if so which assets, in-place or new path, tri budget, texel density, rig to match), the bake tier policy, and the **milestone checkpoints** (round 1, each major part group as it passes, and the end — by default). The Editor runs **with graphics** (never `-nographics`) and with the GPU Resident Drawer off, or its snapshots show only the sky. The level is authored like a full Unity game level and relies on Unity→Babylon parity; checkpoints confirm it. What finally gets exported — the whole level, or an individual asset as a container — is the user's call at checkpoint time, not something to decide now.
108
108
 
109
109
  8. **Loop mechanics** — confirm `--template` choice, rounds-per-session default, and any parts the user wants prioritized first.
110
110
 
@@ -140,7 +140,7 @@ _gauntlet/<name>/
140
140
  1. **Inspect** the current state: `progress.md` + `pipeline.md` + the actual project — plus `components.md` when supplied assets carry component metadata (write it now if it is owed and missing).
141
141
  2. **Select** the highest-impact unmet criterion — normally the top entries of the **standing gap list** from the last critic, respecting user priorities from the brief.
142
142
  3. **Build** — make one coherent improvement, through the deliverable kind's build surface. **Template A:** fan out builder subagents only for *genuinely independent* parts; **keep tightly coupled systems under one sequential owner** (broad fan-out performs WORSE than sequential ownership for coupled visual systems). **Template B:** single-track. When a stall tier is active, obey it — incremental tweaks are forbidden and the round must carry a `STRATEGY:` line.
143
- 4. **Verify with the real artifact** — run the pipeline's verify recipe and capture evidence **from the locked cameras** into `_gauntlet/<name>/evidence/`: screenshots plus whatever metrics that pipeline can measure in-loop. **Use the pipeline's cheap in-loop mode every round** — for `unity` that is a Unity camera snapshot, *not* a bake-export-serve-browser round trip; the expensive engine verification is a deliberate checkpoint (round 1, and when the work is done), never a per-round tax. **Screenshots are required for visual parts.** If the host cannot produce the evidence, mark the part `unverified` — it can NEVER be flipped to `- [x]` on the builder's word.
143
+ 4. **Verify with the real artifact** — run the pipeline's verify recipe and capture evidence **from the locked cameras** into `_gauntlet/<name>/evidence/`: screenshots plus whatever metrics that pipeline can measure in-loop. **Use the pipeline's cheap in-loop mode every round** — for `unity` that is a Unity camera snapshot, *not* a bake-export-serve-browser round trip; the expensive engine verification is a deliberate checkpoint (round 1, each milestone, and when the work is done), never a per-round tax. **Screenshots are required for visual parts.** If the host cannot produce the evidence, mark the part `unverified` — it can NEVER be flipped to `- [x]` on the builder's word.
144
144
 
145
145
  5. **Criticize (fresh context)** — spawn a harsh critic subagent per `references/critic-rubrics.md`. It receives the loop card, the part's spec, the target, the evidence, the metrics, **the previous round's screenshot and verdict**, and the pipeline's extra inputs — **never the builder's rationale**. It returns a **scored rubric**, the **FULL prioritized gap list** (not one gap), every **hard gate** as pass/fail, a regression note, and PASS/FAIL. It grades pixels, numbers and behaviour — never effort or intent.
146
146
  6. **Record** — append `rounds/round-NN.md` with the score and the whole gap list; update `progress.md`: on PASS flip the part to `- [x]`; on FAIL log the top gap and increment the attempt counter; update the best/last scores and the stall tier. Persist BEFORE the next round.
@@ -180,9 +180,9 @@ generate_image(
180
180
 
181
181
  **Interview settles:** kind `unity`; three locked cameras (`gauntlet_hero` down the alley, `gauntlet_side` across the puddles, `gauntlet_detail` on a sign); pass threshold 8.0; budgets 60 FPS @1080p, ≤900 draws; bake policy *preview until round 8, then production*.
182
182
 
183
- **The reachability pass matters here.** Screen-space reflections in the target have no export key — the declared approach becomes *a reflection probe per puddle group plus a wet-mask material*, recorded as **Approximable**. True volumetric light shafts go to `OUT OF REACH`; height fog stands in. Without this the critic names "no SSR" every round forever.
183
+ **The reachability pass matters here.** URP has no screen-space reflections to export — the declared approach becomes *a reflection probe per puddle group plus a wet-mask material*, recorded as **Approximable**. True volumetric light shafts go to `OUT OF REACH`; height fog stands in. Without this the critic names "no SSR" every round forever.
184
184
 
185
- **Round 1** runs the prerequisite gate (`bt_status` → `pro : True` or park), writes `pipeline.md`, authors the blockout via `eval_file`, creates the LightingSettings asset (`NewScene → build → SaveScene → assign → MarkSceneDirty → SaveOpenScenes`), places the three `gauntlet_*` cameras, and decomposes into the P1–P11 part checklist.
185
+ **Round 1** runs the prerequisite gate (`bt_status` → `pro : True` or park), writes `pipeline.md`, authors the blockout via `run_script` builders, creates the LightingSettings asset (`NewScene → build → SaveScene → assign → MarkSceneDirty → SaveOpenScenes`), places the three `gauntlet_*` cameras, and decomposes into the P1–P11 part checklist.
186
186
 
187
187
  Round 1 also runs the **one calibration checkpoint** — a single export + browser load — to prove the whole chain works before investing 12 rounds, and to record what actually crosses the export boundary.
188
188
 
@@ -190,16 +190,17 @@ Round 1 also runs the **one calibration checkpoint** — a single export + brows
190
190
 
191
191
  ```bash
192
192
  # bake (preview tier) only if this round touched anything GI-dependent
193
- unity command eval 'UnityEditor.Lightmapping.BakeAsync(); return "started";' --project-path "$PROJ"
194
- unity command eval 'return UnityEditor.Lightmapping.isRunning;' --project-path "$PROJ" # poll to False
193
+ unity command bake_lighting --project-path "$PROJ"
194
+ until unity command lighting_bake_status --project-path "$PROJ" --result-only 2>/dev/null | grep -q completed; do sleep 5; done
195
195
 
196
196
  # snapshot each locked camera straight to PNG — no export, no server, no browser
197
- unity command eval_file /tmp/snap-hero.cs --project-path "$PROJ" # -> evidence/round-NN-p7-hero.png
197
+ unity command capture_game_view --camera gauntlet_hero --width 1920 --height 1080 --project-path "$PROJ" \
198
+ --result-only | jq -r .base64 | base64 -d > _gauntlet/neon-alley/evidence/round-NN-p7-hero.png
198
199
  ```
199
200
 
200
201
  Seconds, not minutes. The critic scores hero + side + detail against their targets and returns the full gap list.
201
202
 
202
- **The export runs twice in the whole job:** the round-1 calibration, and the final pass — production bake, export the finished scene, serve it, and let the integration critic judge the real deliverable while the perf, console and export-boundary gates are measured for real. *Did `reflectionprobeintensity` actually cross, or did the round only move a Unity slider?* — that question gets answered there, not forty times over.
203
+ **The export runs at milestones, not every round:** the round-1 calibration; a checkpoint each time a part group passes (landform, light rig + GI bake + probes, materials + dressing, atmosphere + post); and the final pass — production bake, export the finished scene, serve it, and let the integration critic judge the real deliverable while the perf, console and export-boundary gates are measured for real. *Did `reflectionprobeintensity` actually cross, or did the round only move a Unity slider?* — each milestone answers that for the parts it covers, instead of forty times over or only at the very end.
203
204
 
204
205
  **Parks** at round 12 with `/bt-gauntlet --resume neon-alley`. Weeks later that resumes cold: re-read the workspace, re-launch the Editor, re-run the gate, continue at `NEXT ACTION`.
205
206
 
@@ -229,7 +230,7 @@ generate_image(
229
230
  4. **Capture the baseline score.** Round 1's critic scores the untouched level against the target. That number is the floor — every later round is measured against it, and a regression below it is a gate failure, not a preference.
230
231
  5. Bake tiering matters more here than anywhere, because the scene is already heavy: preview tier for the convergence rounds, one production bake before the integration critic — and with the export out of the loop, the bake is the only per-round cost left, so skip it entirely on rounds that change nothing GI-dependent.
231
232
 
232
- Because the scene was authored in the GUI it already has a LightingSettings asset — but **always pass `--scene`** at checkpoint exports anyway, or a fresh Editor session silently exports the template's default scene instead. Note this pipeline needs a **copilot-mode resident Editor**: `-nographics` has no graphics device and cannot render the in-loop snapshots.
233
+ Because the scene was authored in the GUI it already has a LightingSettings asset — but **always pass `--scene`** at checkpoint exports anyway, or a fresh Editor session silently exports the template's default scene instead. Note this pipeline needs an Editor that can render for the in-loop snapshots: never `-nographics`, and the GPU Resident Drawer off (`unity-pipeline.md` § 1).
233
234
 
234
235
  ## Example 3 — A high-fidelity model, polished in Blender and shipped as an interactive prefab
235
236
 
@@ -240,7 +241,7 @@ It needs a rigidbody, an LOD group and the Animator wired up. Reference is the a
240
241
  turntable.
241
242
  ```
242
243
 
243
- **Interview settles:** kind `unity`, with Blender model work in scope; **write mode IN PLACE** so the GUID and importer settings survive every round; the **render scene** is `Assets/Scenes/Level01.unity` — the level the mech actually lives in, so it is judged under the lighting it will really have (a dedicated lookdev scene only if the asset has no home yet), with its rig frozen for the run; four locked `gauntlet_*` cameras in it including a detail crop; model root `Props/Mech`; budgets 45k tris, 512 px/m texel density; checkpoints at round 1 and the finish.
244
+ **Interview settles:** kind `unity`, with Blender model work in scope; **write mode IN PLACE** so the GUID and importer settings survive every round; the **render scene** is `Assets/Scenes/Level01.unity` — the level the mech actually lives in, so it is judged under the lighting it will really have (a dedicated lookdev scene only if the asset has no home yet), with its rig frozen for the run; four locked `gauntlet_*` cameras in it including a detail crop; model root `Props/Mech`; budgets 45k tris, 512 px/m texel density; checkpoints at round 1, after the Blender parts pass, and at the finish.
244
245
 
245
246
  **Blender hands off to Unity and stops there.** Blender does geometry, UVs, bakes and skinning, editing the FBX in place; Unity assigns materials, colliders, the LODGroup, the Animator and the Babylon Toolkit script components — Blender cannot write `extras.metadata.components`, and under a community licence Unity won't either. After the hand-off the mech is just an asset in `Level01`.
246
247
 
@@ -251,7 +252,8 @@ cp "$FBX" "$FBX.bak" # the write is destructive — always
251
252
  blender --background --factory-startup --python-exit-code 1 \
252
253
  --python /tmp/round-07-bevels.py -- "$FBX" "$FBX" # same path in and out
253
254
  unity command eval 'UnityEditor.AssetDatabase.Refresh(UnityEditor.ImportAssetOptions.ForceSynchronousImport); return "ok";' --project-path "$PROJ"
254
- unity command eval_file /tmp/snap-hero.cs --project-path "$PROJ" # -> evidence/round-07-p2-hero.png
255
+ unity command capture_game_view --camera gauntlet_hero --width 1920 --height 1080 --project-path "$PROJ" \
256
+ --result-only | jq -r .base64 | base64 -d > _gauntlet/hero-mech/evidence/round-07-p2-hero.png
255
257
  ```
256
258
 
257
259
  Without `--python-exit-code 1` a crashed script exits `0` and the loop records a failed round as a success. Without in-place writing, every round mints a new GUID and quietly detaches the model from every scene that used it. Both are hard gates.
@@ -280,6 +282,47 @@ thing done at AAA quality—from textures to physics to anything you could think
280
282
 
281
283
  The interview turns that into a filled loop card built with **BabylonJS + the Babylon Toolkit, not ThreeJS** — and, because "AAA quality" is not a bar, into a locked target image, locked cameras, a rubric and a pass threshold before a single round runs.
282
284
 
285
+ ## Example 5 — A design-heavy kart-racing level, built in Unity, verified at milestones
286
+
287
+ ```
288
+ /bt-gauntlet --name:candy-circuit --rounds:40 Build a Mario Kart style race track — a bright
289
+ candy-themed circuit with a jump, a tunnel, boost pads and scenery everywhere. Karts must drive it.
290
+ ```
291
+
292
+ **Unity is the level editor; BabylonJS runs the race.** The track is authored in Unity the way a Unity game level would be — and relies on Unity→Babylon parity rather than exporting every round.
293
+
294
+ **Interview settles:**
295
+ - kind `unity`, with four locked cameras: start grid, the jump, the tunnel exit, and a detail crop on a boost pad;
296
+ - budgets: 60 FPS @1080p desktop, and a mobile tier with a draw-call ceiling;
297
+ - **milestones:**
298
+ - M1 landform + track spline;
299
+ - M2 light rig + GI bake + probes;
300
+ - M3 materials + set dressing;
301
+ - M4 atmosphere + post-processing;
302
+ - M5 gameplay components.
303
+
304
+ **Parts:**
305
+
306
+ | Part | Owns |
307
+ |---|---|
308
+ | Landform | terrain, road mesh along the spline, banking |
309
+ | Blockout + composition | sightlines at each locked camera, readable turns |
310
+ | Materials | candy PBR, emissive boost pads |
311
+ | Light rig | Mixed sun, Baked practicals in the tunnel |
312
+ | GI bake | lightmaps + shadowmask, `LightProbeGroup` along the racing line for the karts |
313
+ | Reflection probes | baked, box-projected in the tunnel |
314
+ | Atmosphere + post | fog, a Volume with ACES and bloom |
315
+ | Physics | road and wall colliders, boost-pad triggers |
316
+ | Karts | Rigidbody chassis, `WheelCollider`s + `RaycastWheel`s |
317
+ | Gameplay | the racing starter's `RaceTrackManager`, `CheckpointManager`, `VehicleInputController` (human + AI autopilot), `StandardCarController` |
318
+ | Perf | the draw-call and FPS budgets |
319
+
320
+ **The rhythm:**
321
+ - **Most rounds stay in Unity:** a `run_script` builder, a preview bake when GI changed, and locked-camera snapshots.
322
+ - **When a milestone's parts pass, run a checkpoint:** export (`--geometryOnly false`), serve, load the same cameras in the browser, and have the critic say which side of the export any gap is on.
323
+ - **M5 is judged driving:** a kart actually laps the track in the browser.
324
+ - **The integration pass** runs the production bake and the full perf gates, desktop and mobile.
325
+
283
326
  ---
284
327
 
285
328
  # Failure-Mode Guardrails (loop rules, non-negotiable)