@babylonjs-toolkit/agent 1.1.60 → 1.1.62

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.
package/README.md CHANGED
@@ -1,4 +1,4 @@
1
- # Babylon Toolkit Desktop Agent (1.1.60)
1
+ # Babylon Toolkit Desktop Agent (1.1.62)
2
2
 
3
3
  The desktop agent owns the entire pipeline end to end — frontend and UI design, gameplay code, shaders, generated art and audio, 3D models in headless Blender, whole game levels and prefabs in a terminal-driven Unity Editor, the interactive glTF export, the web build, the dev server, and visual QA by screenshotting both Unity and the running browser.
4
4
 
@@ -283,7 +283,10 @@ minutes), and each task's result appears the moment it is built. An open tab kee
283
283
  re-reads its data in the background (every 10 s during a run, every 30 s otherwise) and refreshes
284
284
  only when something changed — a task result, a finished run, the next run starting, or a plan
285
285
  reopened because you added a task after it was complete (the dashboard drops back to *paused* and
286
- the After Action Report is revised when the new work is done). Phase by phase and task by task it shows what was actually done, files, tests,
286
+ the After Action Report is revised when the new work is done). A watchdog runs alongside every run:
287
+ when an agent has written nothing for 10 minutes it writes a heartbeat naming the latest file the work
288
+ changed (or warns that the run may be stalled), and it corrects a status that still names a finished
289
+ task — so the dashboard never sits silent or wrong while a long task is running. Phase by phase and task by task it shows what was actually done, files, tests,
287
290
  verifier verdicts, attempts, commits, decisions, deferrals and follow-ups. The snapshots tell the
288
291
  story of the build: **progressions** captured from the same camera each time a meaningful layer
289
292
  lands (a terrain: heightmap → textures → roads → trees → foliage → lighting), played back as a
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@babylonjs-toolkit/agent",
3
- "version": "1.1.60",
3
+ "version": "1.1.62",
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",
@@ -33,7 +33,7 @@ Run tasks from a plan: build each one with its tests, have an independent verifi
33
33
 
34
34
  - **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".
35
35
  - **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)*.
36
- - **Open the run before anything else.** The first actions of every run — before fetching docs, reading code, checking the repo or any other pre-flight work — are, in order: take the clock; append the `⏱ Run <n> start` line to the run log; sync the dashboard with the plan and set `status: "in-progress"` (*Run start* under *Feature folder and dashboard*); and write the live file (`role: "orchestrator"`, `title: "Starting run <n> — <what you are checking first>"`). From then on the pre-flight work is narrated in the live file like any other step. Until the run is opened the dashboard still shows the last run's end state — a user who restarts a run and refreshes must see it running within a minute, not after the pre-flight is over.
36
+ - **Open the run before anything else.** The first actions of every run — before fetching docs, reading code, checking the repo or any other pre-flight work — are, in order: take the clock; append the `⏱ Run <n> start` line to the run log; sync the dashboard with the plan and set `status: "in-progress"` (*Run start* under *Feature folder and dashboard*); write the live file (`role: "orchestrator"`, `title: "Starting run <n> — <what you are checking first>"`); and launch the watchdog in the background (*Never let the dashboard go stale*). From then on the pre-flight work is narrated in the live file like any other step. Until the run is opened the dashboard still shows the last run's end state — a user who restarts a run and refreshes must see it running within a minute, not after the pre-flight is over.
37
37
  - **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.
38
38
  - **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.
39
39
  - **Say what you are doing** — one short line at each task and phase boundary, and before anything slow.
@@ -82,15 +82,21 @@ Every feature lives in one folder, created by bt-spec (or by bt-plan for a Quick
82
82
 
83
83
  **The dashboard.** `dashboard.html` is a fixed template; `documents/<slug>_dashboard.js` holds everything it shows. Both come from this skill's `templates/dashboard/` *(where skills load through a tool: `load_skill` + `read_skill_resource`; where they are files: the skills directory this skill was loaded from)*: `dashboard.html` copied with `{{slug}}` replaced — never otherwise edited — and the starter data `dashboard.template.js`. A third file, `documents/<slug>_live.js` (from `live.template.js`), carries what is happening this minute. **`data-schema.md` documents every field and the update recipe — read it once per run and put the parts a role writes into its brief.** bt-plan writes all three in the `planned` state; if any is missing, create it now from the plan.
84
84
 
85
- **Update per task, not per phase — the user watches this page instead of asking "what are you doing?"** Whoever is doing the work writes: the implementer while it builds, the verifier while it checks, you (the orchestrator) between them. Only one agent works at a time in this loop, so writes never collide; if you ever run subagents in parallel, they report back and you write. Every implementer and verifier brief carries the three paths and these rules. Every timestamp comes from the shell clock.
85
+ **Update per task, not per phase — the user watches this page instead of asking "what are you doing?"** Whoever is doing the work writes: the implementer while it builds, the verifier while it checks, you (the orchestrator) between them. Only one agent works at a time in this loop, so writes never collide; if you ever run subagents in parallel, they report back and you write. Every implementer and verifier brief carries the helper's exact command lines with the paths filled in, and these rules. Every timestamp comes from the local clock (the helper takes it for you).
86
+
87
+ **Never let the dashboard go stale — three guards, because an agent deep in a long task forgets to write:**
88
+
89
+ 1. **The watchdog.** At run start, launch `node <skills>/bt-execute/scripts/dashboard.mjs watch <feature-folder> --watch <your scratch folder>` in the background (add `--watch` for any other folder where the work leaves files — exports, logs, captures). Every minute it checks the live file: after 10 quiet minutes it writes a heartbeat naming the latest file that changed ("still working — latest activity: t19/gp3.log at 21:48"); after 30 minutes with no file change either it says the run may be stalled; and if the live file still names a finished task while another is in progress, it points it at the active task. It exits by itself when the status leaves `in-progress`. A heartbeat is a safety net, not a substitute — the agents' own writes say what is actually happening.
90
+ 2. **Hand-off writes.** Before you launch any implementer or verifier, set its task(s) `in-progress` (implementer) or `verifying` (verifier) and point the live file at it (`--task T19 --role implementer --activity "Implementer started on T19 — <its first step>" --reset`); when it returns, write what it reported. The live file must never still name the previous task while a new one is being worked on.
91
+ 3. **Long commands are narrated.** Before any command that may run more than a few minutes (a full test chain, an export or bake, a multi-race or multi-scene browser run), write a step saying what it is and roughly how long it takes; run it in the background where the host allows, and write a step at each milestone its output shows ("race 2 of 4 reached results"). A long run is exactly when the user is watching.
86
92
 
87
93
  - **The live file — at every meaningful step.** Rewrite `documents/<slug>_live.js` whole (it is small) when a task starts, at each milestone inside it, before anything slow (a build, an export, a bake, a capture, a test run), at each fix attempt, at the hand-over to the verifier and while it checks each task, and at the commit: the phase, the task, the role, one plain-language sentence on what is happening now, and the task's step log. Never let it go 15 minutes without a write during active work — the page flags a 20-minute silence. Between tasks, `task: ""` and a `title` (`Verifying phase 2`, `Committing phase 2`).
88
94
  - **The dashboard data — at every task boundary:** a task becomes `in-progress` when it starts; `built` the moment it is built and its tests are green — with its summary of what was actually done (and anything surprising), files, tests and snapshots filled in **right then**, not at the phase end; `verifying` while the verifier checks it; `done` when it passes (verifier result, attempts, commit, done time, its `DECISION` lines); back to `in-progress` with `attempts` + 1 on a FAIL. Each change also adds an `activity` line and refreshes `updatedAt`.
89
- - **Data, written through a parser — never hand-edited.** Each data file is one `window.… =` prefix and one strict-JSON value (the prefix only lets a page opened from disk load it). Every update reads the file, parses the JSON, changes the fields and writes the whole file back — the Python recipe in `data-schema.md`, or Node's `JSON.parse` / `JSON.stringify`. One stray comma written by hand would blank the page; a parser cannot write one.
95
+ - **Every write goes through this skill's `scripts/dashboard.mjs` — never hand-edited.** Each data file is one `window.… =` prefix and one strict-JSON value (the prefix only lets a page opened from disk load it); the helper parses it, changes it, checks the shapes and writes it back atomically, so the page never sees a half-written or malformed file. Use it, not a one-off script of your own: `node <skills>/bt-execute/scripts/dashboard.mjs live <feature-folder> --task T7 --role implementer --activity "…" --step "…"` · `task <feature-folder> T7 --set '{"status":"built","summary":"…"}'` · `activity <feature-folder> "…"` · `status <feature-folder> in-progress` · `check <feature-folder>` (all options in the script's header). Only where Node cannot run, fall back to the parse-and-write-back recipe in `data-schema.md`. Keep each field its documented shape too — a list stays a list (`updates`, `snapshots`, `files`, `decisions`, `notes` …: append, never assign a string); a helper script you give subagents checks the shapes before it writes.
90
96
 
91
97
  On top of the per-task updates:
92
98
 
93
- - **Run start — the first thing the run does** (*Open the run before anything else*): **sync the dashboard with the plan file** — re-read its checklist and add any phase or task (including sub-tasks like `T3.1`) the dashboard lacks, in plan order, as `pending`, with an `updates` note on it (`Added to the plan after <the plan was complete / phase 2 ran> — <why, if the plan says>`); a task the plan no longer has is removed with an `activity` line saying so. Then `status: "in-progress"`, `runs` + 1, the run-log document link, an `activity` line, and the first live-file write. In a git repository, check `.gitignore` has `.agents/specs/*/documents/*_live.js` and append it once if not — the live file is never staged or committed; `<slug>_dashboard.js` and `snapshots/` are.
99
+ - **Run start — the first thing the run does** (*Open the run before anything else*): **refresh `dashboard.html`** — copy it again from the template with `{{slug}}` replaced (it is never edited, so this is always safe, and it is how layout fixes reach dashboards created by older versions); then **sync the dashboard with the plan file** — re-read its checklist and add any phase or task (including sub-tasks like `T3.1`) the dashboard lacks, in plan order, as `pending`, with an `updates` note on it (`Added to the plan after <the plan was complete / phase 2 ran> — <why, if the plan says>`); a task the plan no longer has is removed with an `activity` line saying so. Then `status: "in-progress"`, `runs` + 1, the run-log document link, an `activity` line, the first live-file write, and the watchdog launched in the background. In a git repository, check `.gitignore` has `.agents/specs/*/documents/*_live.js` and append it once if not — the live file is never staged or committed; `<slug>_dashboard.js` and `snapshots/` are.
94
100
  - **Each phase, after its ticks and before its commit:** the phase's status, times and minutes (from its `⏱` line), its verifier result and a two-or-three-sentence summary of what it delivered; the phase-level snapshots (a progression spanning several tasks — below); `decisions`; `activeTime`; an `activity` line; and a current "so far" `outcome` headline.
95
101
  - **A deferral:** the task's `status: "deferred"` and `deferredReason`, an `activity` line.
96
102
  - **Run end — the After Action Report.** **decide the status by re-reading the plan file's checkboxes, never from memory:** `complete` when every task in the plan is `- [x]`; `incomplete` when every task is either ticked or marked ⏭️ DEFERRED; otherwise `paused` (the run covered only a slice, or tasks were added). The page refuses a `complete` it can see is false — it shows the plan as paused with a warning — but the plan file is the authority; never leave `in-progress` behind, because the status picks the page's top slot: `in-progress` shows *Current run activity* (the live file and the milestones), any other run-ended status shows the After Action Report in its place. Write `followUps` for a human, and `afterAction` — the whole plan's execution, start to finish: a one-sentence headline of what the plan delivered; two to four paragraphs on what was built, how it was proven and what surprised; highlights; and **one before/after for the plan as a whole** (`comparison`) — the plan-wide "before" frame beside a final "after" taken now from the same camera or viewport (the end-to-end check's session supplies it). Add the plan's key progression to `afterAction.snapshots` if one tells the story better than any single phase. The figures (tasks, tests, retries, time) are computed by the page — never type them in. A run that ends before the plan is finished writes it too; the page marks it *Interim* while `paused`, and the next run revises it with an `updates` entry. **A reopened plan** (tasks added after it was complete) works the same way: the run that finishes the added tasks rewrites the After Action Report to cover them, notes the change in its `updates` (`Revised — T7 added after completion: <why>`), and retakes the plan-wide "after" from the same camera so the comparison shows the plan as it now stands.
@@ -0,0 +1,397 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * Feature dashboard helper for bt-execute: the one way agents write a feature's dashboard data, plus the
4
+ * watchdog that keeps the live status honest while an agent is busy with a long task.
5
+ *
6
+ * Every write reads the data file, parses its strict JSON, changes it and writes it back atomically (a temp file
7
+ * renamed over the original), so the page can never load a half-written file and no hand edit can break it.
8
+ *
9
+ * node dashboard.mjs live <feature-folder> --task T19 --role implementer --activity "…" [--phase 7] [--step "…"]… [--reset] [--title "…"]
10
+ * node dashboard.mjs task <feature-folder> <task-id> --set '{"status":"built","summary":"…"}' [--note "why an earlier result changed" --by T21]
11
+ * node dashboard.mjs activity <feature-folder> "Phase 2 verified — T4–T6 PASS"
12
+ * node dashboard.mjs status <feature-folder> in-progress|paused|complete|incomplete
13
+ * node dashboard.mjs check <feature-folder>
14
+ * node dashboard.mjs watch <feature-folder> [--watch <folder>]… [--interval-seconds 60] [--quiet-minutes 10] [--stall-minutes 30] [--max-hours 12]
15
+ *
16
+ * <feature-folder> is .agents/specs/<slug>. Timestamps come from this machine's local clock.
17
+ */
18
+ import { existsSync, readFileSync, readdirSync, renameSync, statSync, writeFileSync } from 'node:fs';
19
+ import { basename, join, relative } from 'node:path';
20
+
21
+ /** How many entries a task's live step log keeps. */
22
+ const MAXIMUM_LIVE_STEPS = 12;
23
+ /** Folders the watchdog never descends into when looking for signs of work. */
24
+ const IGNORED_FOLDERS = new Set(['node_modules', '.git', 'Library', 'Temp', 'Logs', 'obj', 'dist', 'build', '.cache', 'profile']);
25
+ /** How deep the watchdog looks inside each watched folder. */
26
+ const MAXIMUM_SCAN_DEPTH = 5;
27
+ /** Task fields that are always lists — appended to, never replaced by a string. */
28
+ const TASK_LIST_FIELDS = ['files', 'decisions', 'snapshots', 'updates'];
29
+ /** Task fields that are an object or null. */
30
+ const TASK_OBJECT_FIELDS = ['tests', 'details'];
31
+ /** Statuses that mean a task is being worked on right now. */
32
+ const ACTIVE_TASK_STATUSES = new Set(['in-progress', 'built', 'verifying']);
33
+
34
+ const [command, featureFolder, ...rest] = process.argv.slice(2);
35
+
36
+ /**
37
+ * Reads the paths of a feature folder's two data files.
38
+ * @param {string} folder The feature folder, `.agents/specs/<slug>`.
39
+ * @returns {{ slug: string, dashboardPath: string, livePath: string }}
40
+ */
41
+ function dataPaths(folder) {
42
+ const slug = basename(folder.replace(/[\\/]+$/, ''));
43
+ return {
44
+ slug,
45
+ dashboardPath: join(folder, 'documents', `${slug}_dashboard.js`),
46
+ livePath: join(folder, 'documents', `${slug}_live.js`),
47
+ };
48
+ }
49
+
50
+ /**
51
+ * Parses a data file: one `window.NAME =` prefix followed by a strict-JSON value.
52
+ * @param {string} path The data file.
53
+ * @returns {{ prefix: string, data: any }}
54
+ */
55
+ function readData(path) {
56
+ const text = readFileSync(path, 'utf8');
57
+ const separator = text.indexOf('=');
58
+ if (separator < 0) throw new Error(`${path} has no "window.… =" prefix`);
59
+ const body = text.slice(separator + 1).trim().replace(/;\s*$/, '');
60
+ return { prefix: text.slice(0, separator).trim(), data: JSON.parse(body) };
61
+ }
62
+
63
+ /**
64
+ * Writes a data file atomically: a temp file next to it, then renamed over it.
65
+ * @param {string} path The data file.
66
+ * @param {string} prefix Its `window.NAME` prefix.
67
+ * @param {any} data The value to write.
68
+ */
69
+ function writeData(path, prefix, data) {
70
+ const temporaryPath = `${path}.${process.pid}.tmp`;
71
+ writeFileSync(temporaryPath, `${prefix} = ${JSON.stringify(data, null, 2)};\n`, 'utf8');
72
+ renameSync(temporaryPath, path);
73
+ }
74
+
75
+ /**
76
+ * The local time as the dashboard expects it.
77
+ * @param {Date} [moment] Defaults to now.
78
+ * @returns {{ stamp: string, clock: string }} `YYYY-MM-DD HH:MM` and `HH:MM`.
79
+ */
80
+ function localTime(moment = new Date()) {
81
+ const pad = (value) => String(value).padStart(2, '0');
82
+ const clock = `${pad(moment.getHours())}:${pad(moment.getMinutes())}`;
83
+ return { stamp: `${moment.getFullYear()}-${pad(moment.getMonth() + 1)}-${pad(moment.getDate())} ${clock}`, clock };
84
+ }
85
+
86
+ /**
87
+ * Reads `--name value` options; names listed in `repeatable` collect every occurrence.
88
+ * @param {string[]} argumentList The remaining command-line arguments.
89
+ * @param {string[]} [repeatable] Option names that may appear more than once.
90
+ * @returns {{ options: Record<string, any>, positional: string[] }}
91
+ */
92
+ function parseOptions(argumentList, repeatable = []) {
93
+ const options = Object.fromEntries(repeatable.map((name) => [name, []]));
94
+ const positional = [];
95
+ for (let index = 0; index < argumentList.length; index += 1) {
96
+ const argument = argumentList[index];
97
+ if (!argument.startsWith('--')) {
98
+ positional.push(argument);
99
+ continue;
100
+ }
101
+ const name = argument.slice(2);
102
+ const next = argumentList[index + 1];
103
+ const value = next === undefined || next.startsWith('--') ? true : argumentList[++index];
104
+ if (repeatable.includes(name)) options[name].push(value);
105
+ else options[name] = value;
106
+ }
107
+ return { options, positional };
108
+ }
109
+
110
+ /**
111
+ * Rewrites the live status: what is happening this minute.
112
+ * @param {string} folder The feature folder.
113
+ * @param {string[]} argumentList Command options.
114
+ */
115
+ function writeLive(folder, argumentList) {
116
+ const { options } = parseOptions(argumentList, ['step']);
117
+ const { livePath } = dataPaths(folder);
118
+ const existing = existsSync(livePath) ? readData(livePath) : { prefix: 'window.FEATURE_LIVE', data: {} };
119
+ const live = existing.data;
120
+ const now = localTime();
121
+ const taskChanged = options.task !== undefined && options.task !== live.task;
122
+ const steps = options.reset || taskChanged ? [] : Array.isArray(live.steps) ? live.steps : [];
123
+ for (const step of options.step) steps.push({ at: now.clock, text: String(step) });
124
+ const updated = {
125
+ updatedAt: now.stamp,
126
+ phase: options.phase !== undefined ? Number(options.phase) : live.phase,
127
+ task: options.task !== undefined ? String(options.task) : live.task || '',
128
+ title: options.title !== undefined ? String(options.title) : options.task !== undefined ? '' : live.title || '',
129
+ role: options.role !== undefined ? String(options.role) : live.role || 'orchestrator',
130
+ activity: options.activity !== undefined ? String(options.activity) : live.activity || '',
131
+ steps: steps.slice(-MAXIMUM_LIVE_STEPS),
132
+ source: 'agent',
133
+ };
134
+ writeData(livePath, existing.prefix, updated);
135
+ }
136
+
137
+ /**
138
+ * Finds a task anywhere in the dashboard data.
139
+ * @param {any} dashboard The dashboard data.
140
+ * @param {string} taskId The task id, e.g. `T12.2`.
141
+ * @returns {any | undefined}
142
+ */
143
+ function findTask(dashboard, taskId) {
144
+ for (const phase of dashboard.phases || []) {
145
+ const task = (phase.tasks || []).find((candidate) => candidate.id === taskId);
146
+ if (task) return task;
147
+ }
148
+ return undefined;
149
+ }
150
+
151
+ /**
152
+ * Merges fields into one task, optionally recording why an earlier result changed.
153
+ * @param {string} folder The feature folder.
154
+ * @param {string[]} argumentList The task id and options.
155
+ */
156
+ function writeTask(folder, argumentList) {
157
+ const { options, positional } = parseOptions(argumentList);
158
+ const [taskId] = positional;
159
+ if (!taskId || typeof options.set !== 'string') throw new Error('usage: task <feature-folder> <task-id> --set \'{"status":"built"}\'');
160
+ const { dashboardPath } = dataPaths(folder);
161
+ const { prefix, data } = readData(dashboardPath);
162
+ const task = findTask(data, taskId);
163
+ if (!task) throw new Error(`task ${taskId} is not in ${dashboardPath} — sync the dashboard with the plan first`);
164
+ const changes = JSON.parse(options.set);
165
+ checkTaskShape(changes);
166
+ Object.assign(task, changes);
167
+ const now = localTime();
168
+ if (typeof options.note === 'string') {
169
+ task.updates = Array.isArray(task.updates) ? task.updates : [];
170
+ task.updates.push({ at: now.stamp, by: typeof options.by === 'string' ? options.by : taskId, note: options.note });
171
+ }
172
+ data.updatedAt = now.stamp;
173
+ writeData(dashboardPath, prefix, data);
174
+ }
175
+
176
+ /**
177
+ * Refuses a change that would give a task field the wrong shape (a list replaced by a string, …), which would
178
+ * break the page.
179
+ * @param {Record<string, any>} changes The fields about to be merged into a task.
180
+ */
181
+ function checkTaskShape(changes) {
182
+ for (const field of TASK_LIST_FIELDS) {
183
+ if (field in changes && !Array.isArray(changes[field])) throw new Error(`"${field}" must be a list — append to it, never assign a string`);
184
+ }
185
+ for (const field of TASK_OBJECT_FIELDS) {
186
+ const value = changes[field];
187
+ if (field in changes && value !== null && (typeof value !== 'object' || Array.isArray(value))) throw new Error(`"${field}" must be an object or null`);
188
+ }
189
+ }
190
+
191
+ /**
192
+ * Appends one milestone to the activity log.
193
+ * @param {string} folder The feature folder.
194
+ * @param {string[]} argumentList The milestone text.
195
+ */
196
+ function writeActivity(folder, argumentList) {
197
+ const text = argumentList.join(' ').trim();
198
+ if (!text) throw new Error('usage: activity <feature-folder> "text"');
199
+ const { dashboardPath } = dataPaths(folder);
200
+ const { prefix, data } = readData(dashboardPath);
201
+ const now = localTime();
202
+ data.activity = Array.isArray(data.activity) ? data.activity : [];
203
+ data.activity.push({ at: now.stamp, text });
204
+ data.updatedAt = now.stamp;
205
+ writeData(dashboardPath, prefix, data);
206
+ }
207
+
208
+ /**
209
+ * Sets the dashboard's run status.
210
+ * @param {string} folder The feature folder.
211
+ * @param {string[]} argumentList The new status.
212
+ */
213
+ function writeStatus(folder, argumentList) {
214
+ const [status] = argumentList;
215
+ const allowed = ['planned', 'in-progress', 'paused', 'complete', 'incomplete'];
216
+ if (!allowed.includes(status)) throw new Error(`status must be one of: ${allowed.join(', ')}`);
217
+ const { dashboardPath } = dataPaths(folder);
218
+ const { prefix, data } = readData(dashboardPath);
219
+ data.status = status;
220
+ data.updatedAt = localTime().stamp;
221
+ writeData(dashboardPath, prefix, data);
222
+ }
223
+
224
+ /**
225
+ * Confirms both data files parse.
226
+ * @param {string} folder The feature folder.
227
+ */
228
+ function checkData(folder) {
229
+ const { dashboardPath, livePath } = dataPaths(folder);
230
+ readData(dashboardPath);
231
+ if (existsSync(livePath)) readData(livePath);
232
+ console.log(`ok: ${dashboardPath}${existsSync(livePath) ? ` and ${livePath}` : ''} parse`);
233
+ }
234
+
235
+ /**
236
+ * The most recently changed file under some folders, skipping dependency, build and cache folders.
237
+ * @param {string[]} roots Folders to search.
238
+ * @returns {{ path: string, modified: number } | null}
239
+ */
240
+ function latestChange(roots) {
241
+ let latest = null;
242
+ const visit = (folder, depth) => {
243
+ let entries;
244
+ try {
245
+ entries = readdirSync(folder, { withFileTypes: true });
246
+ } catch {
247
+ return;
248
+ }
249
+ for (const entry of entries) {
250
+ const path = join(folder, entry.name);
251
+ if (entry.isDirectory()) {
252
+ if (depth < MAXIMUM_SCAN_DEPTH && !IGNORED_FOLDERS.has(entry.name)) visit(path, depth + 1);
253
+ continue;
254
+ }
255
+ // The dashboard's own data files are written by agents and the watchdog itself — not a sign of work.
256
+ if (!entry.isFile() || entry.name.endsWith('.tmp') || /_(dashboard|live)\.js$/.test(entry.name)) continue;
257
+ try {
258
+ const modified = statSync(path).mtimeMs;
259
+ if (!latest || modified > latest.modified) latest = { path, modified };
260
+ } catch {
261
+ /* file vanished between listing and stat — ignore it */
262
+ }
263
+ }
264
+ };
265
+ roots.forEach((root) => visit(root, 0));
266
+ return latest;
267
+ }
268
+
269
+ /**
270
+ * The live file's last write as a Date, or null when it cannot be read.
271
+ * @param {string} stamp `YYYY-MM-DD HH:MM`.
272
+ * @returns {Date | null}
273
+ */
274
+ function parseStamp(stamp) {
275
+ const match = /^(\d{4})-(\d{2})-(\d{2})[ T](\d{2}):(\d{2})/.exec(String(stamp || ''));
276
+ if (!match) return null;
277
+ const [, year, month, day, hour, minute] = match.map(Number);
278
+ return new Date(year, month - 1, day, hour, minute);
279
+ }
280
+
281
+ /**
282
+ * The watchdog. While the dashboard says a run is in progress it checks the live status every interval:
283
+ * - the live status names a task that is already finished while another task is active → it points the live
284
+ * status at the active task (the agent working on it has not written yet);
285
+ * - nothing has been written for `quiet-minutes` → it writes a heartbeat naming the latest file that changed in
286
+ * the watched folders, so the page shows the work is alive and where;
287
+ * - no file has changed for `stall-minutes` either → the heartbeat says the run may be stalled.
288
+ * It exits by itself as soon as the dashboard status is anything but in-progress, or after `max-hours` (a run that
289
+ * was killed leaves the status at in-progress, and the watchdog must not outlive it forever).
290
+ * @param {string} folder The feature folder.
291
+ * @param {string[]} argumentList Watch options.
292
+ */
293
+ async function watch(folder, argumentList) {
294
+ const { options } = parseOptions(argumentList, ['watch']);
295
+ const intervalSeconds = Number(options['interval-seconds'] || 60);
296
+ const quietMinutes = Number(options['quiet-minutes'] || 10);
297
+ const stallMinutes = Number(options['stall-minutes'] || 30);
298
+ const stopAt = Date.now() + Number(options['max-hours'] || 12) * 3600000;
299
+ const roots = [folder, ...options.watch.map(String)];
300
+ const { dashboardPath, livePath } = dataPaths(folder);
301
+ const projectRoot = process.cwd();
302
+ console.log(`watchdog: watching ${roots.join(', ')} every ${intervalSeconds} s (quiet after ${quietMinutes} min, stalled after ${stallMinutes} min)`);
303
+
304
+ for (;;) {
305
+ if (Date.now() > stopAt) {
306
+ console.log('watchdog: reached its maximum lifetime — exiting');
307
+ return;
308
+ }
309
+ let dashboard;
310
+ try {
311
+ dashboard = readData(dashboardPath).data;
312
+ } catch {
313
+ dashboard = null; // caught mid-write or briefly missing — try again next round
314
+ }
315
+ if (dashboard && dashboard.status !== 'in-progress') {
316
+ console.log(`watchdog: dashboard status is "${dashboard.status}" — the run is over, exiting`);
317
+ return;
318
+ }
319
+ if (dashboard && existsSync(livePath)) {
320
+ try {
321
+ checkLive(dashboard, livePath, roots, projectRoot, quietMinutes, stallMinutes);
322
+ } catch (error) {
323
+ console.log(`watchdog: skipped a round — ${error.message}`);
324
+ }
325
+ }
326
+ await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000));
327
+ }
328
+ }
329
+
330
+ /**
331
+ * One watchdog round (see `watch`).
332
+ * @param {any} dashboard The dashboard data.
333
+ * @param {string} livePath The live file.
334
+ * @param {string[]} roots Folders that show signs of work.
335
+ * @param {string} projectRoot Paths are reported relative to this.
336
+ * @param {number} quietMinutes Minutes without a live write before a heartbeat.
337
+ * @param {number} stallMinutes Minutes without any file change before the stall warning.
338
+ */
339
+ function checkLive(dashboard, livePath, roots, projectRoot, quietMinutes, stallMinutes) {
340
+ const { prefix, data: live } = readData(livePath);
341
+ const tasks = (dashboard.phases || []).flatMap((phase) => (phase.tasks || []).map((task) => ({ ...task, phaseNumber: phase.number })));
342
+ const liveTask = tasks.find((task) => task.id === live.task);
343
+ const activeTasks = tasks.filter((task) => ACTIVE_TASK_STATUSES.has(task.status));
344
+ const now = new Date();
345
+ const lastWrite = parseStamp(live.updatedAt);
346
+ const quietFor = lastWrite ? Math.floor((now - lastWrite) / 60000) : Infinity;
347
+ const pointsAtFinishedTask = liveTask && !ACTIVE_TASK_STATUSES.has(liveTask.status) && activeTasks.length > 0;
348
+ if (!pointsAtFinishedTask && quietFor < quietMinutes) return;
349
+
350
+ const change = latestChange(roots);
351
+ const changedAgo = change ? Math.floor((now - change.modified) / 60000) : Infinity;
352
+ const where = change ? `${relative(projectRoot, change.path) || change.path} at ${localTime(new Date(change.modified)).clock}` : 'no file changes found';
353
+ const clock = localTime(now).clock;
354
+ const steps = Array.isArray(live.steps) ? live.steps : [];
355
+ let task = live.task;
356
+ let activity;
357
+
358
+ if (pointsAtFinishedTask) {
359
+ const active = activeTasks[0];
360
+ task = active.id;
361
+ activity = `Working on ${active.id} — ${active.title}. The agent has not written its own status yet; latest activity: ${where}.`;
362
+ steps.length = 0;
363
+ steps.push({ at: clock, text: `Watchdog: the status still named ${live.task}, which is finished — ${active.id} is the task in progress.` });
364
+ } else if (changedAgo >= stallMinutes) {
365
+ activity = `No update for ${quietFor} min and no file has changed for ${changedAgo === Infinity ? 'the whole watch' : `${changedAgo} min`} — the run may be stalled or waiting on something.`;
366
+ steps.push({ at: clock, text: `Watchdog: possible stall — last file change: ${where}.` });
367
+ } else {
368
+ activity = `Still working — no update from the agent for ${quietFor} min; latest activity: ${where}.`;
369
+ steps.push({ at: clock, text: `Watchdog: still working — ${where}.` });
370
+ }
371
+
372
+ writeData(livePath, prefix, {
373
+ ...live,
374
+ updatedAt: localTime(now).stamp,
375
+ phase: pointsAtFinishedTask ? activeTasks[0].phaseNumber : live.phase,
376
+ task,
377
+ title: '',
378
+ role: pointsAtFinishedTask ? 'implementer' : live.role,
379
+ activity,
380
+ steps: steps.slice(-MAXIMUM_LIVE_STEPS),
381
+ source: 'watchdog',
382
+ });
383
+ console.log(`watchdog ${clock}: ${activity}`);
384
+ }
385
+
386
+ const commands = { live: writeLive, task: writeTask, activity: writeActivity, status: writeStatus, check: checkData, watch };
387
+
388
+ if (!commands[command] || !featureFolder) {
389
+ console.error('usage: node dashboard.mjs <live|task|activity|status|check|watch> <feature-folder> [options] — see the header of this file');
390
+ process.exit(2);
391
+ }
392
+ try {
393
+ await commands[command](featureFolder, rest);
394
+ } catch (error) {
395
+ console.error(`dashboard.mjs ${command}: ${error.message}`);
396
+ process.exit(1);
397
+ }
@@ -181,7 +181,7 @@
181
181
  font: 700 11.5px/1.4 var(--font-mono);
182
182
  letter-spacing: 0.08em;
183
183
  text-transform: uppercase;
184
- white-space: nowrap;
184
+ max-width: 100%;
185
185
  }
186
186
  .status::before { content: ""; width: 7px; height: 7px; border-radius: 50%; background: currentColor; }
187
187
  .status-done, .status-complete { color: var(--done); background: var(--done-soft); }
@@ -314,9 +314,6 @@
314
314
  margin-top: 7px;
315
315
  font: 500 11.5px/1.3 var(--font-mono);
316
316
  color: var(--text-muted);
317
- white-space: nowrap;
318
- overflow: hidden;
319
- text-overflow: ellipsis;
320
317
  }
321
318
 
322
319
  /* ---------- Summary ---------- */
@@ -495,9 +492,6 @@
495
492
  padding: 6px 8px 7px;
496
493
  font: 600 11.5px/1.3 var(--font-sans);
497
494
  color: var(--text-muted);
498
- white-space: nowrap;
499
- overflow: hidden;
500
- text-overflow: ellipsis;
501
495
  }
502
496
  .film-frame .film-step {
503
497
  position: absolute;
@@ -518,7 +512,7 @@
518
512
  .stage-caption .stage-note { color: var(--text-muted); font-size: 13.5px; }
519
513
 
520
514
  /* ---------- Phases ---------- */
521
- .phase { margin-top: 20px; overflow: hidden; }
515
+ .phase { margin-top: 20px; }
522
516
  .phase-head {
523
517
  display: grid;
524
518
  grid-template-columns: auto minmax(0, 1fr) auto;
@@ -604,6 +598,10 @@
604
598
  .live-steps time { font: 600 12px/1.6 var(--font-mono); color: var(--text-faint); }
605
599
  .live-steps li:last-child { color: var(--text); font-weight: 600; }
606
600
  .task-live { padding: 12px 14px; border-radius: var(--radius-small); background: var(--active-soft); }
601
+ .now-warning { margin: 8px 0 0; padding: 8px 12px; border-left: 3px solid var(--failed); border-radius: 0 var(--radius-small) var(--radius-small) 0; background: var(--failed-soft); font-size: 13.5px; }
602
+ .tag.tag-watchdog { color: var(--updated); border-color: color-mix(in srgb, var(--updated) 45%, transparent); background: var(--updated-soft); letter-spacing: 0.06em; }
603
+ .tag.tag-snapshots { display: inline-flex; align-items: center; gap: 4px; color: var(--accent); border-color: color-mix(in srgb, var(--accent) 40%, transparent); background: color-mix(in srgb, var(--accent) 10%, transparent); }
604
+ .tag-snapshots svg { width: 13px; height: 13px; flex: none; }
607
605
  .task-live .now-head { font-size: 10.5px; }
608
606
  .task-id { font: 700 13px/1 var(--font-mono); color: var(--text-muted); }
609
607
  .task-title { font-weight: 600; min-width: 0; }
@@ -639,11 +637,11 @@
639
637
  .detail-block p { margin: 0 0 8px; color: var(--text-muted); }
640
638
  .detail-block ul { margin: 0; padding-left: 18px; color: var(--text-muted); display: grid; gap: 4px; }
641
639
  .detail-scroll { overflow-x: auto; }
642
- .detail-table { width: 100%; border-collapse: collapse; font-size: 13px; }
643
- .detail-table th { padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--line-strong); font: 600 10.5px/1.4 var(--font-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--text-faint); white-space: nowrap; }
640
+ .detail-table { width: 100%; table-layout: fixed; border-collapse: collapse; font-size: 13px; }
641
+ .detail-table th { padding: 6px 10px; text-align: left; border-bottom: 1px solid var(--line-strong); font: 600 10.5px/1.4 var(--font-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--text-faint); }
644
642
  .detail-table td { padding: 8px 10px; border-bottom: 1px solid var(--line); vertical-align: top; overflow-wrap: anywhere; }
645
- .detail-table td:first-child { min-width: 140px; }
646
- .verdict { padding: 2px 7px; border-radius: 5px; font: 700 11px/1.5 var(--font-mono); white-space: nowrap; }
643
+ .verdict-note { color: var(--text); }
644
+ .verdict { display: inline-block; max-width: 100%; padding: 2px 7px; border-radius: 5px; font: 700 11px/1.5 var(--font-mono); }
647
645
  .verdict-pass { color: var(--done); background: var(--done-soft); }
648
646
  .verdict-fail { color: var(--failed); background: var(--failed-soft); }
649
647
  .verdict-other { color: var(--text-muted); background: var(--pending-soft); }
@@ -666,7 +664,7 @@
666
664
  font: 700 10.5px/1.4 var(--font-mono);
667
665
  letter-spacing: 0.08em;
668
666
  text-transform: uppercase;
669
- white-space: nowrap;
667
+ max-width: 100%;
670
668
  }
671
669
  .updated-badge::before { content: "↻"; font-size: 12px; letter-spacing: 0; }
672
670
  .updated-badge.is-new { box-shadow: 0 0 0 3px var(--updated-soft); }
@@ -713,6 +711,15 @@
713
711
  .activity-log > summary { cursor: pointer; }
714
712
  .activity-log[open] > summary { margin-bottom: 8px; }
715
713
 
714
+ /* ---------- Containment: nothing is ever wider than its card ---------- */
715
+ /* A single-column grid's column defaults to the width of its longest unbreakable line (a long path,
716
+ a hash), which pushes every paragraph in it past the card's edge. Size those columns to the card. */
717
+ .tasks, .task-body, .task-details, .highlights, .figures, .live-steps, .update-notes,
718
+ .detail-block ul, .aar-section ul { grid-template-columns: minmax(0, 1fr); }
719
+ .highlights li { grid-template-columns: 22px minmax(0, 1fr); }
720
+ /* Long paths, identifiers and URLs wrap wherever they must instead of running off the edge. */
721
+ .page, .masthead h1, .masthead .lede { overflow-wrap: anywhere; }
722
+
716
723
  /* ---------- Lightbox ---------- */
717
724
  .lightbox {
718
725
  position: fixed;
@@ -747,6 +754,12 @@
747
754
  .after-action { padding: 18px; }
748
755
  .after-action-columns { grid-template-columns: 1fr; }
749
756
  .route-label { display: none; }
757
+ /* Detail tables stack on phones: one block per row, each value under its column's label. */
758
+ .detail-table, .detail-table tbody, .detail-table tr, .detail-table td { display: block; width: 100%; }
759
+ .detail-table colgroup, .detail-table thead { display: none; }
760
+ .detail-table tr { padding: 10px 0; border-bottom: 1px solid var(--line); }
761
+ .detail-table td { padding: 3px 0; border-bottom: 0; }
762
+ .detail-table td::before { content: attr(data-label); display: block; font: 600 10.5px/1.6 var(--font-mono); letter-spacing: 0.1em; text-transform: uppercase; color: var(--text-faint); }
750
763
  }
751
764
  @media (prefers-reduced-motion: reduce) {
752
765
  *, *::before { animation: none !important; transition: none !important; }
@@ -772,6 +785,8 @@
772
785
  /** Seconds between refreshes of the "updated N min ago" labels. */
773
786
  const AGE_REFRESH_SECONDS = 30;
774
787
  const STATUS_ICONS = { done: '✓', 'in-progress': '◐', built: '◆', verifying: '⟳', pending: '○', deferred: '⏭', failed: '✕' };
788
+ /** Longest test or acceptance result still shown as a single badge; anything longer is wrapping text. */
789
+ const VERDICT_BADGE_MAX_LENGTH = 16;
775
790
  /** Where the Babylon Toolkit Desktop Agent, whose skills generate this dashboard, is published. */
776
791
  const SKILLS_DOWNLOAD_URL = 'https://www.npmjs.com/package/@babylonjs-toolkit/agent';
777
792
  /** Minutes without a live update before the Now banner warns that the run has gone quiet. */
@@ -808,8 +823,15 @@
808
823
  const storageKey = `dashboard:${report.feature && report.feature.slug ? report.feature.slug : location.pathname}`;
809
824
  const lastVisit = readStorage(localStorage, `${storageKey}:lastSeen`) || '';
810
825
 
811
- render();
812
- wireLightbox();
826
+ normalizeReport(report);
827
+ try {
828
+ render();
829
+ wireLightbox();
830
+ } catch (error) {
831
+ // A malformed field must never leave a blank page: say what broke, and keep checking for a repaired file.
832
+ console.error('Dashboard render failed', error);
833
+ renderBrokenData(error);
834
+ }
813
835
  wireAutoUpdate();
814
836
  restoreScroll();
815
837
  writeStorage(localStorage, `${storageKey}:lastSeen`, report.updatedAt || '');
@@ -955,7 +977,7 @@
955
977
  <article class="card after-action">
956
978
  <div class="after-action-head">
957
979
  <span class="kicker">After Action Report${afterAction.writtenAt ? ` <span>· ${escapeHtml(afterAction.writtenAt)}</span>` : ''}</span>
958
- <span class="meta">${isFinal ? '' : '<span class="status status-in-progress">Interim — plan not finished</span>'}${updatedBadge(afterAction.updates)}</span>
980
+ <span class="meta">${snapshotBadge([...(comparison && comparison.before && comparison.after ? [comparison] : []), ...(afterAction.snapshots || [])])}${isFinal ? '' :'<span class="status status-in-progress">Interim — plan not finished</span>'}${updatedBadge(afterAction.updates)}</span>
959
981
  </div>
960
982
  ${afterAction.headline ? `<h3 class="headline">${formatInline(afterAction.headline)}</h3>` : ''}
961
983
  ${comparison && comparison.before && comparison.after ? `<div class="plan-compare">${renderSnapshot(comparison)}</div>` : ''}
@@ -1040,10 +1062,20 @@
1040
1062
  </article>`;
1041
1063
  }
1042
1064
 
1065
+ // A camera badge on a task's row, so tasks with pictures stand out without opening them.
1066
+ function snapshotBadge(snapshots) {
1067
+ const list = Array.isArray(snapshots) ? snapshots : [];
1068
+ if (!list.length) return '';
1069
+ const images = list.reduce((total, snapshot) => total + (Array.isArray(snapshot.frames) ? snapshot.frames.length : snapshot.before || snapshot.after ? 2 : 1), 0);
1070
+ const label = `${list.length} snapshot${list.length === 1 ? '' : 's'}${images !== list.length ? ` · ${images} images` : ''}`;
1071
+ return `<span class="tag tag-snapshots" title="${escapeAttribute(label)}" aria-label="${escapeAttribute(label)}"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M4 8h3l2-3h6l2 3h3a1 1 0 0 1 1 1v9a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V9a1 1 0 0 1 1-1z"/><circle cx="12" cy="13" r="3.5"/></svg>${list.length}</span>`;
1072
+ }
1073
+
1043
1074
  function renderTask(task) {
1044
1075
  const status = task.status || 'pending';
1045
1076
  const tags = [
1046
- task.kind ? `<span class="tag">${escapeHtml(task.kind)}</span>` : '',
1077
+ snapshotBadge(task.snapshots),
1078
+ task.kind ?`<span class="tag">${escapeHtml(task.kind)}</span>` : '',
1047
1079
  task.verifyLevel === 'live' ? '<span class="tag">live check</span>' : '',
1048
1080
  task.attempts > 1 ? `<span class="tag">${escapeHtml(task.attempts)} attempts</span>` : '',
1049
1081
  status === 'built' || status === 'verifying' ? `<span class="status status-${status}">${STATUS_LABELS[status]}</span>` : '',
@@ -1092,11 +1124,19 @@
1092
1124
  ].filter(Boolean).join(' · ');
1093
1125
  const title = task ? `${escapeHtml(task.id)} — ${escapeHtml(task.title || '')}` : escapeHtml(live.title || live.task || 'Between tasks');
1094
1126
  const age = describeAge(live.updatedAt);
1127
+ // The live status can lag: it may still name a finished task while the agent works on the next one.
1128
+ const activeTasks = allTasks.filter((candidate) => ['in-progress', 'built', 'verifying'].includes(candidate.status));
1129
+ const namesFinishedTask = task && !['in-progress', 'built', 'verifying'].includes(task.status) && activeTasks.length > 0;
1130
+ const lagWarning = namesFinishedTask
1131
+ ? `<p class="now-warning">This status still names ${escapeHtml(task.id)}, which is ${escapeHtml(STATUS_LABELS[task.status] || task.status).toLowerCase()}. ${escapeHtml(activeTasks.map((candidate) => candidate.id).join(', '))} ${activeTasks.length === 1 ? 'is' : 'are'} in progress — the agent has not written its own status yet.</p>`
1132
+ : '';
1133
+ const watchdogTag = live.source === 'watchdog' ? '<span class="tag tag-watchdog" title="Written by the watchdog because the agent has been quiet">watchdog</span>' : '';
1095
1134
  return `
1096
1135
  <div class="card now ${age.isStale ? 'is-stale' : ''}" aria-live="polite">
1097
- <div class="now-head"><span class="live-dot"></span>Now${heading ? ` · ${heading}` : ''}<span class="now-age" data-age="${escapeAttribute(live.updatedAt || '')}">${escapeHtml(age.text)}</span></div>
1136
+ <div class="now-head"><span class="live-dot"></span>Now${heading ? ` · ${heading}` : ''}${watchdogTag}<span class="now-age" data-age="${escapeAttribute(live.updatedAt || '')}">${escapeHtml(age.text)}</span></div>
1098
1137
  <a class="now-task" href="#task-${escapeAttribute(live.task || '')}">${title}</a>
1099
1138
  ${live.activity ? `<p class="now-activity">${formatInline(live.activity)}</p>` : ''}
1139
+ ${lagWarning}
1100
1140
  ${renderLiveSteps(NOW_STEP_COUNT)}
1101
1141
  </div>`;
1102
1142
  }
@@ -1148,13 +1188,13 @@
1148
1188
  : '';
1149
1189
  const blocks = [
1150
1190
  detailBlock('Approach', paragraphs(details.approach)),
1151
- detailBlock('Changes by file', detailTable(['File', 'What changed and why'],
1191
+ detailBlock('Changes by file', detailTable(['File', 'What changed and why'], [34, 66],
1152
1192
  (details.changes || []).map((change) => [`<code>${escapeHtml(change.file || '')}</code>`, formatInline(change.change || '')]))),
1153
- detailBlock('Test cases', detailTable(['Case', 'Expected', 'Result'],
1193
+ detailBlock('Test cases', detailTable(['Case', 'Expected', 'Result'], [28, 36, 36],
1154
1194
  (details.testCases || []).map((testCase) => [formatInline(testCase.name || ''), formatInline(testCase.expected || ''), verdict(testCase.result)]))),
1155
- detailBlock('Acceptance', detailTable(['Criterion', 'Verdict', 'Evidence'],
1195
+ detailBlock('Acceptance', detailTable(['Criterion', 'Verdict', 'Evidence'], [32, 18, 50],
1156
1196
  (details.acceptance || []).map((item) => [formatInline(item.criterion || ''), verdict(item.result), formatInline(item.evidence || '')]))),
1157
- detailBlock('Problems &amp; fixes', detailTable(['Attempt', 'What failed', 'Root cause', 'Fix'],
1197
+ detailBlock('Problems &amp; fixes', detailTable(['Attempt', 'What failed', 'Root cause', 'Fix'], [10, 30, 30, 30],
1158
1198
  (details.problems || []).map((problem) => [escapeHtml(problem.attempt || ''), formatInline(problem.failed || ''), formatInline(problem.cause || ''), formatInline(problem.fix || '')]))),
1159
1199
  detailBlock('Live check', paragraphs(details.liveCheck)),
1160
1200
  detailBlock('Notes', (details.notes || []).length ? `<ul>${details.notes.map((note) => `<li>${formatInline(note)}</li>`).join('')}</ul>` : ''),
@@ -1184,18 +1224,35 @@
1184
1224
  return list.map((paragraph) => `<p>${formatInline(paragraph)}</p>`).join('');
1185
1225
  }
1186
1226
 
1187
- function detailTable(headings, rows) {
1227
+ /**
1228
+ * A verbose-detail table with fixed column shares, so no single long cell can widen its column and
1229
+ * squeeze the others. Each cell carries its heading as `data-label` for the stacked phone layout.
1230
+ */
1231
+ function detailTable(headings, columnPercents, rows) {
1188
1232
  if (!rows.length) return '';
1189
1233
  return `<div class="detail-scroll"><table class="detail-table">
1234
+ <colgroup>${columnPercents.map((percent) => `<col style="width:${percent}%">`).join('')}</colgroup>
1190
1235
  <thead><tr>${headings.map((heading) => `<th>${heading}</th>`).join('')}</tr></thead>
1191
- <tbody>${rows.map((cells) => `<tr>${cells.map((cell) => `<td>${cell}</td>`).join('')}</tr>`).join('')}</tbody>
1236
+ <tbody>${rows.map((cells) => `<tr>${cells.map((cell, index) => `<td data-label="${escapeAttribute(headings[index])}">${cell}</td>`).join('')}</tr>`).join('')}</tbody>
1192
1237
  </table></div>`;
1193
1238
  }
1194
1239
 
1240
+ /**
1241
+ * A test or acceptance result. "PASS" / "FAIL" lead with a coloured badge and any explanation follows as
1242
+ * normal wrapping text; a short other result is a neutral badge; a long one is plain text.
1243
+ */
1195
1244
  function verdict(result) {
1196
- const text = String(result || '');
1197
- const tone = /^pass/i.test(text) ? 'pass' : /^fail/i.test(text) ? 'fail' : 'other';
1198
- return text ? `<span class="verdict verdict-${tone}">${escapeHtml(text)}</span>` : '';
1245
+ const text = String(result || '').trim();
1246
+ if (!text) return '';
1247
+ const leading = /^(pass(?:ed)?|fail(?:ed)?)\b[\s:—–-]*/i.exec(text);
1248
+ if (leading) {
1249
+ const tone = /^pass/i.test(leading[1]) ? 'pass' : 'fail';
1250
+ const rest = text.slice(leading[0].length);
1251
+ return `<span class="verdict verdict-${tone}">${escapeHtml(leading[1].toUpperCase())}</span>${rest ? ` <span class="verdict-note">${formatInline(rest)}</span>` : ''}`;
1252
+ }
1253
+ return text.length <= VERDICT_BADGE_MAX_LENGTH
1254
+ ? `<span class="verdict verdict-other">${escapeHtml(text)}</span>`
1255
+ : `<span class="verdict-note">${formatInline(text)}</span>`;
1199
1256
  }
1200
1257
 
1201
1258
  function factRow(label, valueHtml) {
@@ -1378,6 +1435,79 @@
1378
1435
  </main>`;
1379
1436
  }
1380
1437
 
1438
+ /** Shown instead of a blank page when the data parses but a field has a shape the page cannot render. */
1439
+ function renderBrokenData(error) {
1440
+ appRoot.innerHTML = `
1441
+ <main class="page">
1442
+ <div class="card error-panel">
1443
+ <h2>The dashboard data could not be shown</h2>
1444
+ <p>A field in <code>documents/&lt;slug&gt;_dashboard.js</code> has an unexpected shape: ${escapeHtml(error && error.message ? error.message : String(error))}.
1445
+ This page keeps checking and redraws itself as soon as the file is repaired (open the browser console for details).</p>
1446
+ </div>
1447
+ </main>`;
1448
+ }
1449
+
1450
+ /* ===================== Data repair ===================== */
1451
+
1452
+ /**
1453
+ * Repairs the list fields a hand or script slip most often breaks, so one bad value cannot blank the page:
1454
+ * an update written as plain text becomes one update note, and any other non-list value becomes an empty list.
1455
+ */
1456
+ function normalizeReport(data) {
1457
+ const asList = (value) => (Array.isArray(value) ? value : []);
1458
+ const asUpdates = (value) => {
1459
+ if (typeof value === 'string' && value) return [{ note: value }];
1460
+ return asList(value).map((update) => (typeof update === 'string' ? { note: update } : update)).filter((update) => update && typeof update === 'object');
1461
+ };
1462
+ const repairSnapshots = (snapshots) => asList(snapshots)
1463
+ .filter((snapshot) => snapshot && typeof snapshot === 'object')
1464
+ .map((snapshot) => Object.assign(snapshot, { updates: asUpdates(snapshot.updates) }, snapshot.frames !== undefined ? { frames: asList(snapshot.frames) } : {}));
1465
+ data.phases = asList(data.phases);
1466
+ data.decisions = asList(data.decisions).map((decision) => Object.assign(decision, { updates: asUpdates(decision.updates) }));
1467
+ data.followUps = asList(data.followUps);
1468
+ data.activity = asList(data.activity);
1469
+ if (data.afterAction && typeof data.afterAction === 'object') {
1470
+ const afterAction = data.afterAction;
1471
+ afterAction.updates = asUpdates(afterAction.updates);
1472
+ afterAction.snapshots = repairSnapshots(afterAction.snapshots);
1473
+ ['body', 'highlights', 'sections'].forEach((key) => { if (afterAction[key] !== undefined) afterAction[key] = asList(afterAction[key]); });
1474
+ }
1475
+ data.phases.forEach((phase) => {
1476
+ phase.updates = asUpdates(phase.updates);
1477
+ phase.snapshots = repairSnapshots(phase.snapshots);
1478
+ phase.tasks = asList(phase.tasks);
1479
+ phase.tasks.forEach((task) => {
1480
+ task.updates = asUpdates(task.updates);
1481
+ task.snapshots = repairSnapshots(task.snapshots);
1482
+ task.files = typeof task.files === 'string' ? [task.files] : asList(task.files);
1483
+ task.decisions = typeof task.decisions === 'string' ? [task.decisions] : asList(task.decisions);
1484
+ if (task.tests !== null && typeof task.tests !== 'object') task.tests = null;
1485
+ if (task.details !== null && task.details !== undefined && typeof task.details !== 'object') task.details = null;
1486
+ if (task.details) repairDetails(task.details);
1487
+ });
1488
+ });
1489
+ if (data.afterAction && Array.isArray(data.afterAction.sections)) {
1490
+ data.afterAction.sections.forEach((section) => {
1491
+ if (section && typeof section === 'object' && section.items !== undefined) section.items = asTextList(section.items);
1492
+ });
1493
+ }
1494
+
1495
+ /** A verbose write-up: tables need lists of rows; notes may be one sentence or a list of them. */
1496
+ function repairDetails(details) {
1497
+ ['changes', 'testCases', 'acceptance', 'problems'].forEach((key) => {
1498
+ if (details[key] !== undefined) details[key] = asList(details[key]).filter((row) => row && typeof row === 'object');
1499
+ });
1500
+ if (details.notes !== undefined) details.notes = asTextList(details.notes);
1501
+ if (details.timing !== undefined && (details.timing === null || typeof details.timing !== 'object')) details.timing = null;
1502
+ }
1503
+
1504
+ /** One string becomes a one-item list; a list keeps only its non-empty entries. */
1505
+ function asTextList(value) {
1506
+ if (typeof value === 'string') return value ? [value] : [];
1507
+ return asList(value).filter((item) => item !== null && item !== undefined && item !== '');
1508
+ }
1509
+ }
1510
+
1381
1511
  /* ===================== Updated notifications ===================== */
1382
1512
 
1383
1513
  function updatedBadge(updates) {
@@ -1591,11 +1721,13 @@
1591
1721
  */
1592
1722
  function wireAutoUpdate() {
1593
1723
  const toggle = document.getElementById('live-toggle');
1594
- toggle.addEventListener('click', () => {
1595
- writeStorage(localStorage, `${storageKey}:live`, isLiveEnabled() ? 'off' : 'on');
1596
- toggle.setAttribute('aria-pressed', String(isLiveEnabled()));
1597
- toggle.textContent = autoUpdateLabel();
1598
- });
1724
+ if (toggle) {
1725
+ toggle.addEventListener('click', () => {
1726
+ writeStorage(localStorage, `${storageKey}:live`, isLiveEnabled() ? 'off' : 'on');
1727
+ toggle.setAttribute('aria-pressed', String(isLiveEnabled()));
1728
+ toggle.textContent = autoUpdateLabel();
1729
+ });
1730
+ }
1599
1731
  const dashboardSource = scriptSource('_dashboard.js');
1600
1732
  const liveSource = scriptSource('_live.js');
1601
1733
  const renderedFingerprint = fingerprint(report, live);
@@ -19,7 +19,13 @@ The `window.… =` prefix exists only because a page opened from disk (`file://`
19
19
  JSON — double-quoted keys and strings, no comments, no trailing commas — so any JSON parser can read it.
20
20
  The status of the plan itself lives in the plan file's checkboxes; the dashboard mirrors it (see *Status*).
21
21
 
22
- ## Updating a data file — parse, change, write back
22
+ ## Updating a data file
23
+
24
+ Use bt-execute's helper — `node <skills>/bt-execute/scripts/dashboard.mjs live|task|activity|status|check|watch <feature-folder> …`
25
+ (every option is in its header). It parses, checks field shapes and writes atomically. Its `watch` command is the
26
+ watchdog that writes a heartbeat into the live file when an agent has been quiet for 10 minutes.
27
+
28
+ ### Fallback — parse, change, write back
23
29
 
24
30
  Never edit the text by hand: one stray comma blanks the page. Read the file, parse the JSON, change the
25
31
  fields, and write the whole file back. Every write then produces valid data by construction.
@@ -39,6 +45,15 @@ PY
39
45
  Node works the same way (`JSON.parse` / `JSON.stringify(data, null, 2)`). Where neither runs, write the
40
46
  whole file from a complete JSON value, never a partial patch. `<slug>_live.js` is small — always write it whole.
41
47
 
48
+ **Keep every field its documented shape.** Valid JSON is not enough: a list field written as plain text
49
+ (`"updates": "note"` instead of `"updates": [{ "at", "by", "note" }]`) once blanked a dashboard mid-run. The
50
+ lists are `updates`, `snapshots`, `files`, `decisions`, `activity`, `followUps`, `phases`, `tasks`, a snapshot's
51
+ `frames`, and in `details` the tables `changes`, `testCases`, `acceptance`, `problems` and the list `notes`.
52
+ Add to a list (`.append(...)`), never assign a string to it, and when you give a helper script to subagents,
53
+ make it check these shapes before it writes. The page repairs the common slips on load (a text `updates`
54
+ becomes one note, a text `notes` a one-item list, any other non-list an empty list) and shows an error panel
55
+ instead of a blank page if something still cannot render — it keeps checking and redraws once the file is fixed.
56
+
42
57
  ## Conventions
43
58
 
44
59
  - **Paths** (documents, snapshots) are relative to the feature folder: `"snapshots/…"`, `"documents/…"`.
@@ -144,7 +159,7 @@ Each task:
144
159
  | `acceptance` | `[{ "criterion", "result": "PASS" \| "FAIL", "evidence" }]` |
145
160
  | `problems` | `[{ "attempt": "1", "failed", "cause", "fix" }]` |
146
161
  | `liveCheck` | what was looked at, where, at what resolution, how it was judged |
147
- | `notes` | anything a maintainer should know |
162
+ | `notes` | `["…"]` — anything a maintainer should know, one string per point |
148
163
  | `timing` | `{ "build": 12, "verify": 6, "fix": 4 }` — minutes |
149
164
 
150
165
  ## Snapshot shapes
@@ -174,4 +189,5 @@ The page shows it only while `status` is `in-progress`.
174
189
  | `title` | only when there is no task: `"Verifying phase 1"`, `"Committing phase 1"` |
175
190
  | `role` | `implementer` · `verifier` · `orchestrator` |
176
191
  | `activity` | one plain-language sentence on what is happening this minute |
192
+ | `source` | `agent` (an agent wrote it) or `watchdog` (a heartbeat written because the agent was quiet — the page tags it) |
177
193
  | `steps` | `[{ "at": "HH:MM", "text" }]` — the current task's log, oldest first; start fresh for each task, keep the last 12. Plain language a non-developer follows: "Painting the road mask from the spline", not "edit RoadNetwork.ts L120" |