The ultimate harness for coding agents and beyond. All your agents. All your machines. One command center. Start with code, then follow your curiosity and build across disciplines: CAD, circuits, robots, games and music.
TypeScript 3d-modelingagent-frameworkagent-harnessai-agentscadclaude-codecodexcoding-agentsdeveloper-toolsesp32game-developmentmcp-servermulti-agentopen-hardwareopencodeopenharnesspcbroboticsterminaltmux
marp: cover the toolchain, the viewer and the scripts; fix six bugs
deeb185dc2adc3c
diff --git a/store/agents/marp/toolchain/art.mjs b/store/agents/marp/toolchain/art.mjsindex a72d16454..37c7e354c 100644--- a/store/agents/marp/toolchain/art.mjs+++ b/store/agents/marp/toolchain/art.mjs@@ -5,8 +5,9 @@// node art.mjs wallpaper -o assets/bg.svg [--palette aurora|sunset|ocean|graphite|spectrum] [--seed 7] [--size 1920x1080]// node art.mjs chart -o assets/chart.svg --data "2022:12,2023:31,2024:64" [--type bar|line] [--accent "#2997ff"] [--label "Revenue, $M"]// node art.mjs frame -o assets/phone.svg --image assets/screen.png [--kind phone|laptop|window] [--palette aurora]-import { writeFileSync, readFileSync, existsSync } from 'node:fs'+import { writeFileSync, readFileSync, existsSync, realpathSync } from 'node:fs'import { extname, resolve } from 'node:path'+import { fileURLToPath } from 'node:url'const PALETTES = {aurora: ['#5e5ce6', '#bf5af2', '#ff375f', '#30d158', '#64d2ff'],@@ -141,7 +142,14 @@ ${bg}`}-if (import.meta.url === `file://${process.argv[1]}`) {+// Run as a script, however it was reached: `file://${argv[1]}` never matched a path with a space in it+// (the URL escapes it) or an install linked with `harness dsh install --link` (the URL is the real path),+// and the CLI then did nothing at all, silently.+function isMain() {+ try { return realpathSync(process.argv[1]) === realpathSync(fileURLToPath(import.meta.url)) } catch { return false }+}++if (isMain()) {const a = args(process.argv.slice(2))const cmd = a._[0]const out = a.o@@ -151,10 +159,12 @@ if (import.meta.url === `file://${process.argv[1]}`) {else if (cmd === 'chart') svg = chart({ data: a.data, type: a.type, accent: a.accent, label: a.label, dark: a.light ? false : true })else if (cmd === 'frame') svg = frame({ image: a.image ? resolve(a.image) : undefined, kind: a.kind, palette: a.palette, seed: a.seed })else { console.error('usage: art.mjs wallpaper|chart|frame -o <file.svg> [options]'); process.exit(2) }- if (!out) { process.stdout.write(svg); process.exit(0) }- writeFileSync(out, svg)- console.log(`wrote ${out}`)+ // No exit after writing to stdout: on a pipe the write is asynchronous, and exiting cut the SVG off at 64 KB.+ if (!out) { process.stdout.write(svg) } else {+ writeFileSync(out, svg)+ console.log(`wrote ${out}`)+ }} catch (error) {- console.error(`art: ${error instanceof Error ? error.message : error}`); process.exit(1)+ console.error(`art: ${error.message}`); process.exit(1)}}diff --git a/store/agents/marp/toolchain/check.mjs b/store/agents/marp/toolchain/check.mjsindex 1f247be8a..fd1deece7 100644--- a/store/agents/marp/toolchain/check.mjs+++ b/store/agents/marp/toolchain/check.mjs@@ -1,14 +1,16 @@#!/usr/bin/env node// `node toolchain/check.mjs [deck.md]` — judge the deck in the current workspace and write// .harness/verdict.json. Prints the findings; exits 1 when the deck is not ready.-import { resolve, relative, dirname } from 'node:path'+import { resolve, relative, dirname, sep } from 'node:path'import { existsSync } from 'node:fs'import { lintDeck, readDeck, writeVerdict } from './lib/deck.mjs'const workspace = process.env.HARNESS_WORKSPACE ? resolve(process.env.HARNESS_WORKSPACE) : process.cwd()const arg = process.argv[2] ?? 'deck.md'const deckFile = relative(workspace, resolve(workspace, arg)) || 'deck.md'-if (!existsSync(resolve(workspace, deckFile))) {+// A deck outside the workspace is not its deck: the verdict names a workspace-relative artifact, and the+// pane will not open a ../ path, so judging one would put a deck in the header the pane cannot show.+if (deckFile.split(sep)[0] === '..' || !existsSync(resolve(workspace, deckFile))) {console.error(`check: ${deckFile} is not in ${workspace}`)process.exit(2)}diff --git a/store/agents/marp/toolchain/doctor.sh b/store/agents/marp/toolchain/doctor.shindex 8138df220..fcaa9dda9 100755--- a/store/agents/marp/toolchain/doctor.sh+++ b/store/agents/marp/toolchain/doctor.sh@@ -40,8 +40,10 @@ elsefi# Export to PDF/PPTX renders through a Chromium-family browser marp-cli finds on its own.+# MARP_APPLICATIONS_DIR is where to look instead of /Applications (the tests point it at a scratch folder).+apps="${MARP_APPLICATIONS_DIR:-/Applications}"found=""-for app in "/Applications/Google Chrome.app" "/Applications/Chromium.app" "/Applications/Microsoft Edge.app" "/Applications/Brave Browser.app"; do+for app in "$apps/Google Chrome.app" "$apps/Chromium.app" "$apps/Microsoft Edge.app" "$apps/Brave Browser.app"; do[ -d "$app" ] && { found="$app"; break; }done[ -z "$found" ] && command -v chromium >/dev/null 2>&1 && found="$(command -v chromium)"diff --git a/store/agents/marp/toolchain/lib/deck.mjs b/store/agents/marp/toolchain/lib/deck.mjsindex 77c237418..9435f089d 100644--- a/store/agents/marp/toolchain/lib/deck.mjs+++ b/store/agents/marp/toolchain/lib/deck.mjs@@ -38,6 +38,12 @@ function stripTags(html) {.replace(/&\w+;/g, ' ')}+/** A reference as a file name: percent-escapes decoded, and a name with a bare `%` ("growth-50%.png")+ * taken as written instead of throwing out of the whole lint. */+function decoded(ref) {+ try { return decodeURIComponent(ref) } catch { return ref }+}+function frontMatter(markdown) {const m = /^---\r?\n([\s\S]*?)\r?\n---(?:\r?\n|$)/.exec(markdown)return m ? m[1] : null@@ -64,7 +70,7 @@ export function renderDeck(markdown, { dir } = {}) {words: text ? text.split(' ').length : 0,title: heading ? stripTags(heading[1]).trim() : null,images: [...markup.matchAll(/(?:src|url\()=?["'(]?([^"')\s]+)/g)].map((m) => m[1]),- notes: (comments[index] ?? []).join('\n'),+ notes: comments[index].join('\n'),}})return { html, css, slides }@@ -93,7 +99,7 @@ export function lintDeck(markdown, { dir }) {try {rendered = renderDeck(markdown, { dir })} catch (error) {- findings.push({ severity: 'error', kind: 'render', message: `the deck does not render: ${error instanceof Error ? error.message : error}` })+ findings.push({ severity: 'error', kind: 'render', message: `the deck does not render: ${error.message}` })return { ready: false, findings, slides: [], html: [], css: '' }}const { slides, html, css } = rendered@@ -112,7 +118,7 @@ export function lintDeck(markdown, { dir }) {}const refs = imageRefs(markdown)for (const ref of refs) {- const file = resolve(dir, decodeURIComponent(ref.split('#')[0].split('?')[0]))+ const file = resolve(dir, decoded(ref.split('#')[0].split('?')[0]))if (!existsSync(file) || !statSync(file).isFile()) {findings.push({ severity: 'error', kind: 'image', message: `image ${ref} is not in the workspace`, ref })}@@ -153,7 +159,8 @@ export function writeVerdict(workspace, deckFile, lint) {? `${n} slides, ready to present${warnings ? ` · ${warnings} warning${warnings === 1 ? '' : 's'}` : ''}`: errors? `${errors} error${errors === 1 ? '' : 's'} · ${n} slide${n === 1 ? '' : 's'}`- : `${n} slide${n === 1 ? '' : 's'} so far${warnings ? ` · ${warnings} warning${warnings === 1 ? '' : 's'}` : ''}`+ // not ready without an error is too few slides, which is always a warning of its own+ : `${n} slide${n === 1 ? '' : 's'} so far · ${warnings} warning${warnings === 1 ? '' : 's'}`const verdict = {spec: 1,ready: lint.ready,diff --git a/store/agents/marp/toolchain/test/art.test.mjs b/store/agents/marp/toolchain/test/art.test.mjsnew file mode 100644index 000000000..381046973--- /dev/null+++ b/store/agents/marp/toolchain/test/art.test.mjs@@ -0,0 +1,91 @@+// `node art.mjs …` as the agent runs it, and the corners of the generators the deck tests do not reach.+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'+import { chart, frame, wallpaper } from '../art.mjs'++const TOOLCHAIN = fileURLToPath(new URL('..', import.meta.url))+const ART = join(TOOLCHAIN, 'art.mjs')++function art(args, { cwd, script = ART } = {}) {+ const r = spawnSync(process.execPath, [script, ...args], { cwd, encoding: 'utf8', maxBuffer: 1 << 26, env: { ...process.env, NO_COLOR: '1' } })+ return { code: r.status, stdout: r.stdout, stderr: r.stderr }+}++function scratch(t) {+ const dir = mkdtempSync(join(tmpdir(), 'marp-art-cli-'))+ t.after(() => rmSync(dir, { recursive: true, force: true }))+ return dir+}++test('the generators: light variants, seed 0, an all-zero chart, a one-point line, an image type it cannot frame', () => {+ const light = wallpaper({ dark: false, seed: 0 })+ assert.ok(light.includes('<rect width="1920" height="1080" fill="#fff"/>') && light.includes('stop-opacity="0.5"'))+ assert.equal(light, wallpaper({ dark: false, seed: 1 }), 'seed 0 is seed 1')+ const zero = chart({ data: 'a:0,b:0,c:x', dark: false })+ assert.equal((zero.match(/<rect/g) ?? []).length, 2, 'a value that is not a number is dropped')+ assert.ok(zero.includes('fill="#1d1d1f"') && zero.includes('height="0.0"'))+ const one = chart({ data: 'only:5', type: 'line' })+ assert.ok(one.includes('<circle cx="80.0"'), 'one point sits at the left edge')+ const dir = mkdtempSync(join(tmpdir(), 'marp-art-'))+ try {+ writeFileSync(join(dir, 'clip.bmp'), 'x')+ assert.throws(() => frame({ image: join(dir, 'clip.bmp') }), /frame: unsupported image .*clip\.bmp/)+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+})++test('wallpaper to a file, with every option', (t) => {+ const dir = scratch(t)+ const r = art(['wallpaper', '-o', 'bg.svg', '--palette', 'sunset', '--seed', '3', '--size', '640x360', '--light'], { cwd: dir })+ assert.equal(r.code, 0, r.stderr)+ assert.equal(r.stdout, 'wrote bg.svg\n')+ assert.equal(readFileSync(join(dir, 'bg.svg'), 'utf8'), wallpaper({ palette: 'sunset', seed: '3', size: '640x360', dark: false }))+})++test('chart to stdout; a flag followed by another flag is a switch', () => {+ const r = art(['chart', '--light', '--data', '2023:12,2024:31', '--type', 'line', '--accent', '#ff375f', '--label', 'Teams'])+ assert.equal(r.code, 0, r.stderr)+ assert.equal(r.stdout, chart({ data: '2023:12,2024:31', type: 'line', accent: '#ff375f', label: 'Teams', dark: false }))+ assert.equal(art(['chart', '--data', 'a:1']).stdout, chart({ data: 'a:1' }))+})++test('frame resolves the image from where it is run, and a large one reaches a pipe whole', (t) => {+ const dir = scratch(t)+ mkdirSync(join(dir, 'assets'))+ writeFileSync(join(dir, 'assets', 'screen.png'), Buffer.alloc(600_000, 7))+ const r = art(['frame', '--image', 'assets/screen.png', '--kind', 'window', '--palette', 'ocean', '--seed', '9'], { cwd: dir })+ assert.equal(r.code, 0, r.stderr)+ const expected = frame({ image: join(dir, 'assets', 'screen.png'), kind: 'window', palette: 'ocean', seed: '9' })+ assert.ok(expected.length > 65536)+ assert.equal(r.stdout.length, expected.length, 'not cut off at the pipe buffer')+ assert.equal(r.stdout, expected)+})++test('what it cannot do: no image, no data, an unwritable output, an unknown command', (t) => {+ const dir = scratch(t)+ assert.deepEqual(art(['frame']), { code: 1, stdout: '', stderr: 'art: frame: --image <file> is required and must exist\n' })+ assert.deepEqual(art(['chart', '-o', 'x.svg'], { cwd: dir }), { code: 1, stdout: '', stderr: 'art: chart: --data "label:value,label:value" is required\n' })+ const unwritable = art(['wallpaper', '-o', join(dir, 'missing', 'bg.svg')])+ assert.equal(unwritable.code, 1)+ assert.match(unwritable.stderr, /^art: ENOENT: no such file or directory/)+ for (const args of [[], ['poster']]) {+ assert.deepEqual(art(args), { code: 2, stdout: '', stderr: 'usage: art.mjs wallpaper|chart|frame -o <file.svg> [options]\n' })+ }+})++test('runs from a path with a space and through a linked install; importing it runs nothing', (t) => {+ const dir = scratch(t)+ mkdirSync(join(dir, 'Harness Store'))+ symlinkSync(TOOLCHAIN, join(dir, 'Harness Store', 'toolchain'))+ const linked = art(['wallpaper', '--seed', '2'], { script: join(dir, 'Harness Store', 'toolchain', 'art.mjs') })+ assert.equal(linked.code, 0, linked.stderr)+ assert.equal(linked.stdout, wallpaper({ seed: '2' }))+ const imported = spawnSync(process.execPath, ['--input-type=module', '-e', `await import(${JSON.stringify(new URL('../art.mjs', import.meta.url).href)})`], { encoding: 'utf8' })+ assert.deepEqual([imported.status, imported.stdout, imported.stderr], [0, '', ''])+})diff --git a/store/agents/marp/toolchain/test/check.test.mjs b/store/agents/marp/toolchain/test/check.test.mjsnew file mode 100644index 000000000..7cb1a079a--- /dev/null+++ b/store/agents/marp/toolchain/test/check.test.mjs@@ -0,0 +1,66 @@+// `node toolchain/check.mjs [deck]` as the agent runs it: what it prints, what it writes, how it exits.+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { fileURLToPath } from 'node:url'++const CHECK = fileURLToPath(new URL('../check.mjs', import.meta.url))+const body = 'A body with several words in it.'+const READY = `---\nmarp: true\n---\n# Talk\n\n\n\n${body}\n\n---\n\n## A\n\n${body}\n\n---\n\n## B\n\n${body}\n`++function workspace(t) {+ const root = mkdtempSync(join(tmpdir(), 'marp-check-'))+ t.after(() => rmSync(root, { recursive: true, force: true }))+ const ws = join(root, 'ws')+ mkdirSync(ws)+ writeFileSync(join(ws, 'bg.svg'), '<svg/>')+ return { root, ws }+}++function check(args, { cwd, env = {} }) {+ const { HARNESS_WORKSPACE: _, ...inherited } = process.env+ const r = spawnSync(process.execPath, [CHECK, ...args], { cwd, encoding: 'utf8', env: { ...inherited, ...env } })+ return { code: r.status, stdout: r.stdout, stderr: r.stderr }+}++const verdictOf = (ws) => JSON.parse(readFileSync(join(ws, '.harness', 'verdict.json'), 'utf8'))++test('a ready deck: one line, exit 0, the verdict written', (t) => {+ const { ws } = workspace(t)+ writeFileSync(join(ws, 'deck.md'), READY)+ assert.deepEqual(check([], { cwd: ws }), { code: 0, stdout: 'ready · 3 slides, ready to present\n', stderr: '' })+ assert.equal(verdictOf(ws).artifact, 'deck.md')+ assert.equal(check(['.'], { cwd: ws }).code, 0, 'the workspace itself means its deck')+})++test('a deck that is not ready prints its findings and exits 1', (t) => {+ const { ws } = workspace(t)+ writeFileSync(join(ws, 'deck.md'), READY.replace('bg.svg', 'gone.svg'))+ const r = check(['deck.md'], { cwd: ws })+ assert.equal(r.code, 1)+ assert.deepEqual(r.stdout.split('\n'), ['not ready · 1 error · 3 slides', ' error image gone.svg is not in the workspace', ''])+ assert.equal(verdictOf(ws).ready, false)+})++test('HARNESS_WORKSPACE wins over the working directory, and a deck in a folder is named by its path', (t) => {+ const { root, ws } = workspace(t)+ mkdirSync(join(ws, 'talks'))+ writeFileSync(join(ws, 'talks', 'keynote.md'), READY)+ writeFileSync(join(ws, 'talks', 'bg.svg'), '<svg/>')+ const r = check(['talks/keynote.md'], { cwd: root, env: { HARNESS_WORKSPACE: ws } })+ assert.equal(r.code, 0, r.stdout + r.stderr)+ assert.equal(verdictOf(ws).artifact, 'talks/keynote.md')+})++test('a deck that is missing, or outside the workspace, is not checked', (t) => {+ const { root, ws } = workspace(t)+ assert.deepEqual(check(['talk.md'], { cwd: ws }), { code: 2, stdout: '', stderr: `check: talk.md is not in ${realpathSync(ws)}\n` }, 'without HARNESS_WORKSPACE the workspace is the working directory')+ mkdirSync(join(root, 'other'))+ writeFileSync(join(root, 'other', 'deck.md'), READY)+ const outside = check(['../other/deck.md'], { cwd: root, env: { HARNESS_WORKSPACE: ws } })+ assert.deepEqual(outside, { code: 2, stdout: '', stderr: `check: ../other/deck.md is not in ${ws}\n` })+ assert.equal(existsSync(join(ws, '.harness')), false, 'and no verdict is written for it')+})diff --git a/store/agents/marp/toolchain/test/deck.test.mjs b/store/agents/marp/toolchain/test/deck.test.mjsindex 4bfbf5572..ed34ba365 100644--- a/store/agents/marp/toolchain/test/deck.test.mjs+++ b/store/agents/marp/toolchain/test/deck.test.mjs@@ -1,10 +1,10 @@// `node --test toolchain/test` — the lint and the phases, on decks small enough to read.import { test } from 'node:test'import assert from 'node:assert/strict'-import { mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'+import { chmodSync, mkdtempSync, mkdirSync, writeFileSync, readFileSync, rmSync } from 'node:fs'import { tmpdir } from 'node:os'import { join } from 'node:path'-import { lintDeck, deckPhases, renderDeck, imageRefs, writeVerdict, WORDS_PER_SLIDE, THEMES_DIR } from '../lib/deck.mjs'+import { lintDeck, deckPhases, renderDeck, imageRefs, readDeck, writeVerdict, WORDS_PER_SLIDE, THEMES_DIR } from '../lib/deck.mjs'import { wallpaper, chart, frame } from '../art.mjs'import { readdirSync } from 'node:fs'@@ -135,3 +135,81 @@ test('the verdict is spec 1 with the deck as its artifact and the phases in ordermSync(dir, { recursive: true, force: true })}})++test('themes beside the deck: an unreadable file or one without @theme is skipped, a circular import is a render error', () => {+ const dir = mkdtempSync(join(tmpdir(), 'marp-themes-'))+ try {+ mkdirSync(join(dir, 'themes'))+ writeFileSync(join(dir, 'themes', 'locked.css'), '/* @theme locked */\nsection { color: red; }\n')+ chmodSync(join(dir, 'themes', 'locked.css'), 0o000)+ writeFileSync(join(dir, 'themes', 'anonymous.css'), 'section { color: green; }\n')+ writeFileSync(join(dir, 'themes', 'a.css'), "/* @theme a */\n@import 'b';\n")+ writeFileSync(join(dir, 'themes', 'b.css'), "/* @theme b */\n@import 'a';\n")+ const { html } = renderDeck('---\nmarp: true\n---\n\n# Still renders\n', { dir })+ assert.equal(html.length, 1)+ const lint = lintDeck('---\nmarp: true\ntheme: a\n---\n\n# Loop\n', { dir })+ assert.equal(lint.ready, false)+ assert.deepEqual(lint.findings, [{ severity: 'error', kind: 'render', message: 'the deck does not render: Circular "a" theme import is detected.' }])+ assert.deepEqual([lint.slides, lint.html, lint.css], [[], [], ''])+ const verdict = writeVerdict(dir, 'deck.md', lint)+ assert.equal(verdict.summary, '1 error · 0 slides')+ assert.deepEqual(verdict.phases.map((p) => p.state), ['active', 'pending', 'pending'])+ } finally {+ chmodSync(join(dir, 'themes', 'locked.css'), 0o644)+ rmSync(dir, { recursive: true, force: true })+ }+})++test('every way a deck names a local image is checked, and a bare % in a file name is a name, not a crash', () => {+ const dir = mkdtempSync(join(tmpdir(), 'marp-images-'))+ try {+ for (const name of ['growth-50%.png', 'my shot.png', 'tag.png', 'bg.png']) writeFileSync(join(dir, name), 'x')+ const md = fm + '# T\n\n\n\n\n\n<img src="tag.png#frag">\n\n' ++ '<div style="backgroundImage: url(\'bg.png?v=2\')"></div>\n\n<img src="gone.png">\n\n<div style="backgroundImage: url(nope.png)"></div>\n'+ assert.deepEqual(imageRefs(md), ['growth-50%.png', 'my%20shot.png', 'tag.png#frag', 'gone.png', 'bg.png?v=2', 'nope.png'])+ const lint = lintDeck(md, { dir })+ assert.deepEqual(lint.findings.filter((f) => f.kind === 'image').map((f) => f.ref), ['gone.png', 'nope.png'])+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+})++test('the header line says what the deck is, in every state', () => {+ const dir = mkdtempSync(join(tmpdir(), 'marp-summary-'))+ const body = 'A body with several words in it.'+ const summary = (md) => writeVerdict(dir, 'deck.md', lintDeck(md, { dir })).summary+ try {+ assert.equal(summary(fm + 'Just a line with no heading at all.\n'), '1 slide so far · 2 warnings')+ assert.equal(summary(fm + '# One\n\n' + body + '\n\n---\n\n## Two\n\n' + body + '\n'), '2 slides so far · 1 warning')+ assert.equal(summary(fm + '# One\n\n' + body + '\n\n---\n\n\n'), '1 error · 2 slides')+ assert.equal(summary(fm + '# One\n\n\n'), '1 error · 1 slide')+ const three = fm + `# T\n\n\n\n${body}\n\n---\n\n## A\n\n${body}\n\n---\n\n## B\n\n${body}\n`+ writeFileSync(join(dir, 'shot.png'), 'x')+ assert.equal(summary(three), '3 slides, ready to present')+ assert.equal(summary(three.replace('\n\n', '')), '3 slides, ready to present · 1 warning')+ assert.equal(summary(three.replace(fm, '').replace('\n\n', '')), '3 slides, ready to present · 2 warnings')+ const broken = three.replace('shot.png', 'missing.png').replace('## B', '## B\n\n')+ assert.equal(summary(broken), '2 errors · 3 slides')+ const lint = lintDeck(broken, { dir })+ assert.deepEqual(deckPhases(lint).map((p) => p.state), ['done', 'done', 'failed'], 'a drafted deck with errors fails polish')+ assert.equal(lint.findings.find((f) => f.kind === 'title'), undefined)+ const untitled = lintDeck(fm + 'No heading here, only words.\n\n---\n\n## A\n\n---\n\n## B\n', { dir })+ assert.deepEqual(untitled.findings.find((f) => f.kind === 'title'), { severity: 'warning', kind: 'title', message: 'the first slide has no heading; open with the talk\'s title', ref: 'slide 1' })+ assert.deepEqual(deckPhases(untitled).map((p) => p.state), ['done', 'active', 'pending'], 'an untitled body counts as drafted, bare headings do not')+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+})++test('speaker notes ride with their slide, and readDeck reads the deck from the workspace', () => {+ const { slides } = renderDeck(fm + '# One\n\n<!-- say hello -->\n\n---\n\n## Two\n')+ assert.deepEqual(slides.map((s) => s.notes), ['say hello', ''])+ const dir = mkdtempSync(join(tmpdir(), 'marp-read-'))+ try {+ mkdirSync(join(dir, 'talks'))+ writeFileSync(join(dir, 'talks', 'deck.md'), '# Hi\n')+ assert.equal(readDeck(dir, 'talks/deck.md'), '# Hi\n')+ } finally {+ rmSync(dir, { recursive: true, force: true })+ }+})diff --git a/store/agents/marp/toolchain/test/scripts.test.mjs b/store/agents/marp/toolchain/test/scripts.test.mjsnew file mode 100644index 000000000..723d07b79--- /dev/null+++ b/store/agents/marp/toolchain/test/scripts.test.mjs@@ -0,0 +1,196 @@+// setup.sh, doctor.sh, init-workspace.sh and viewer.sh, run for real by /bin/bash against a scratch+// install whose PATH is only stub commands and the few coreutils the scripts use: every ok, warn and+// miss line is reached without npm, a browser or a network.+import { test } from 'node:test'+import assert from 'node:assert/strict'+import { spawnSync } from 'node:child_process'+import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { dirname, join } from 'node:path'+import { fileURLToPath } from 'node:url'++const TOOLCHAIN = fileURLToPath(new URL('..', import.meta.url))+const COREUTILS = ['dirname', 'sed', 'basename', 'mkdir']+// A bash line tracer's hooks (BASH_ENV sourcing a DEBUG trap that appends to SHCOV_OUT), passed through when set.+const TRACER = Object.fromEntries(['BASH_ENV', 'SHCOV_OUT'].filter((k) => process.env[k]).map((k) => [k, process.env[k]]))++function sandbox(t) {+ const root = mkdtempSync(join(tmpdir(), 'marp-scripts-'))+ t.after(() => rmSync(root, { recursive: true, force: true }))+ const install = join(root, 'install')+ mkdirSync(join(install, 'toolchain'), { recursive: true })+ // Linked, not copied: $0 still names the scratch install, and a line tracer can map back to the source.+ for (const script of ['doctor.sh', 'setup.sh', 'init-workspace.sh', 'viewer.sh']) symlinkSync(join(TOOLCHAIN, script), join(install, 'toolchain', script))+ const bin = join(root, 'bin')+ const home = join(root, 'home')+ const apps = join(root, 'Applications')+ for (const dir of [bin, home, apps]) mkdirSync(dir)+ for (const name of COREUTILS) symlinkSync(['/bin', '/usr/bin'].map((d) => join(d, name)).find((p) => existsSync(p)), join(bin, name))+ const calls = join(root, 'calls.log')+ writeFileSync(calls, '')+ const box = {+ root, install, bin, home, apps,+ file(rel, body = '') { const full = join(install, rel); mkdirSync(dirname(full), { recursive: true }); writeFileSync(full, body); return full },+ stub(name, body = '', where = bin) {+ const full = join(where, name)+ mkdirSync(where, { recursive: true })+ writeFileSync(full, `#!/bin/bash\necho "${name} $*" >> "$CALLS"\n${body}\n`)+ chmodSync(full, 0o755)+ return full+ },+ run(script, { cwd = install, env = {} } = {}) {+ const r = spawnSync('/bin/bash', [join(install, 'toolchain', script)], {+ cwd, encoding: 'utf8', timeout: 30_000,+ env: { PATH: bin, HOME: home, CALLS: calls, MARP_APPLICATIONS_DIR: apps, ...TRACER, ...env },+ })+ return { code: r.status, lines: r.stdout.split('\n').filter(Boolean), stderr: r.stderr }+ },+ logged: () => readFileSync(calls, 'utf8').split('\n').filter(Boolean),+ }+ return box+}++/** A machine with everything: claude, node 22, the installed toolchain, the pane, Chrome. */+function healthy(t) {+ const box = sandbox(t)+ box.stub('claude')+ box.stub('node', 'case "$1" in --version) echo v22.11.0 ;; -p) echo 4.1.0 ;; esac')+ mkdirSync(join(box.install, 'toolchain/node_modules/@marp-team/marp-core'), { recursive: true })+ chmodSync(box.file('toolchain/node_modules/.bin/marp'), 0o755)+ for (const f of ['toolchain/viewer.mjs', 'toolchain/viewer/index.html', 'toolchain/viewer/app.js']) box.file(f)+ mkdirSync(join(box.apps, 'Google Chrome.app'))+ return box+}++const OK = [+ 'ok claude on PATH',+ 'ok node 22.11.0',+ 'ok marp-core 4.1.0',+ 'ok marp-cli (PDF, PPTX and HTML export)',+ 'ok viewer pane (slide, grid, presenter, present)',+ 'ok browser for PDF/PPTX export: Google Chrome.app',+]++test('doctor: a machine with everything is ready', (t) => {+ const r = healthy(t).run('doctor.sh')+ assert.deepEqual(r.lines, OK)+ assert.equal(r.code, 0)+})++test('doctor: claude from the installer, outside PATH, counts', (t) => {+ const box = healthy(t)+ rmSync(join(box.bin, 'claude'))+ box.stub('claude', '', join(box.home, '.local', 'bin'))+ assert.deepEqual(box.run('doctor.sh').lines[0], 'ok claude on PATH')+ rmSync(join(box.home, '.local'), { recursive: true })+ const r = box.run('doctor.sh')+ assert.equal(r.lines[0], 'miss claude not found — install Claude Code: https://claude.ai/install')+ assert.equal(r.code, 1)+})++test('doctor: node missing, too old, or saying something that is not a version', (t) => {+ const box = healthy(t)+ for (const [version, line] of [['v16.20.2', 'miss node 16.20.2 is older than 18 (brew install node)'], ['nightly', 'miss node nightly is older than 18 (brew install node)']]) {+ box.stub('node', `case "$1" in --version) echo ${version} ;; -p) echo 4.1.0 ;; esac`)+ const r = box.run('doctor.sh')+ assert.equal(r.lines[1], line)+ assert.equal(r.code, 1)+ }+ rmSync(join(box.bin, 'node'))+ const r = box.run('doctor.sh')+ assert.deepEqual(r.lines.slice(1, 3), ['miss node not found (brew install node)', 'ok marp-core present'], 'the version needs node; the install is still there')+ assert.equal(r.code, 1)+})++test('doctor: no toolchain is a miss, no marp-cli only a warning, an incomplete pane a miss', (t) => {+ const box = healthy(t)+ rmSync(join(box.install, 'toolchain/node_modules/.bin/marp'))+ let r = box.run('doctor.sh')+ assert.equal(r.lines[3], 'warn marp-cli missing — decks show live but do not export')+ assert.equal(r.code, 0)+ rmSync(join(box.install, 'toolchain/node_modules'), { recursive: true })+ r = box.run('doctor.sh')+ assert.equal(r.lines[2], 'miss marp toolchain not installed — run toolchain/setup.sh')+ assert.equal(r.code, 1)+ for (const f of ['toolchain/viewer/app.js', 'toolchain/viewer/index.html', 'toolchain/viewer.mjs']) {+ const box2 = healthy(t)+ rmSync(join(box2.install, f))+ const r2 = box2.run('doctor.sh')+ assert.equal(r2.lines[4], 'miss toolchain/viewer/ is incomplete — reinstall the harness', f)+ assert.equal(r2.code, 1)+ }+})++test('doctor: each browser marp-cli can export with, or a warning when there is none', (t) => {+ for (const app of ['Chromium.app', 'Microsoft Edge.app', 'Brave Browser.app']) {+ const box = healthy(t)+ rmSync(join(box.apps, 'Google Chrome.app'), { recursive: true })+ mkdirSync(join(box.apps, app))+ assert.equal(box.run('doctor.sh').lines[5], `ok browser for PDF/PPTX export: ${app}`)+ }+ const box = healthy(t)+ rmSync(join(box.apps, 'Google Chrome.app'), { recursive: true })+ let r = box.run('doctor.sh')+ assert.equal(r.lines[5], 'warn no Chrome/Chromium/Edge — HTML export only, no PDF or PPTX')+ assert.equal(r.code, 0, 'a warning is not a miss')+ box.stub('google-chrome')+ assert.equal(box.run('doctor.sh').lines[5], 'ok browser for PDF/PPTX export: google-chrome')+ box.stub('chromium')+ assert.equal(box.run('doctor.sh').lines[5], 'ok browser for PDF/PPTX export: chromium')+})++test('setup: npm ci from the lockfile, npm install without one, and the version it got', (t) => {+ const box = sandbox(t)+ box.stub('node', 'echo 4.1.0')+ box.stub('npm')+ box.file('toolchain/package-lock.json', '{}')+ let r = box.run('setup.sh')+ assert.deepEqual([r.code, r.lines], [0, ['ok marp toolchain 4.1.0']])+ rmSync(join(box.install, 'toolchain/package-lock.json'))+ r = box.run('setup.sh')+ assert.equal(r.code, 0)+ assert.deepEqual(box.logged().filter((c) => c.startsWith('npm')), ['npm ci --no-audit --no-fund', 'npm install --no-audit --no-fund'])+})++test('setup: no node is a miss, and a failed install fails setup', (t) => {+ const box = sandbox(t)+ let r = box.run('setup.sh')+ assert.deepEqual([r.code, r.lines], [1, ['miss node — install Node 18 or newer (brew install node)']])+ box.stub('node', 'echo 4.1.0')+ box.stub('npm', 'exit 1')+ r = box.run('setup.sh')+ assert.notEqual(r.code, 0)+ assert.deepEqual(r.lines, [], 'no ok line after a failed npm')+})++test('init-workspace: makes the folders and seeds the verdict, even when the check fails', (t) => {+ const box = sandbox(t)+ const ws = join(box.root, 'ws')+ mkdirSync(ws)+ box.stub('node', 'exit 1')+ const r = box.run('init-workspace.sh', { cwd: ws, env: { HARNESS_DSH_DIR: box.install } })+ assert.equal(r.code, 0, r.stderr)+ assert.ok(existsSync(join(ws, '.harness')) && existsSync(join(ws, 'assets')))+ assert.deepEqual(box.logged(), [`node ${box.install}/toolchain/check.mjs deck.md`])+})++test('init-workspace: needs the install dir', (t) => {+ const box = sandbox(t)+ const r = box.run('init-workspace.sh', { cwd: box.root })+ assert.equal(r.code, 1)+ assert.match(r.stderr, /HARNESS_DSH_DIR: HARNESS_DSH_DIR is required/)+})++test('viewer.sh: needs a port and a workspace, then becomes the node server', (t) => {+ const box = sandbox(t)+ box.stub('node', 'echo "server $HARNESS_VIEWER_PORT $HARNESS_WORKSPACE"')+ let r = box.run('viewer.sh', { env: { HARNESS_WORKSPACE: '/Users/example/deck' } })+ assert.equal(r.code, 1)+ assert.match(r.stderr, /HARNESS_VIEWER_PORT is required/)+ r = box.run('viewer.sh', { env: { HARNESS_VIEWER_PORT: '4100' } })+ assert.equal(r.code, 1)+ assert.match(r.stderr, /HARNESS_WORKSPACE is required/)+ r = box.run('viewer.sh', { env: { HARNESS_VIEWER_PORT: '4100', HARNESS_WORKSPACE: '/Users/example/deck' } })+ assert.deepEqual([r.code, r.lines], [0, ['server 4100 /Users/example/deck']])+ assert.deepEqual(box.logged(), [`node ${box.install}/toolchain/viewer.mjs`])+})diff --git a/store/agents/marp/toolchain/test/support/child.mjs b/store/agents/marp/toolchain/test/support/child.mjsnew file mode 100644index 000000000..cb17d3acc--- /dev/null+++ b/store/agents/marp/toolchain/test/support/child.mjs@@ -0,0 +1,6 @@+// Preloaded (`node --import`) into the viewer processes the tests start and stop. V8 writes coverage+// only when a process exits cleanly, so SIGTERM exits; and the viewer's 20-second keep-alive ping is+// sent every 50 ms here, so a test can see one without waiting.+process.on('SIGTERM', () => process.exit(0))+const setIntervalOriginal = globalThis.setInterval+globalThis.setInterval = (fn, ms, ...args) => setIntervalOriginal(fn, ms === 20_000 ? 50 : ms, ...args)diff --git a/store/agents/marp/toolchain/test/support/viewer.mjs b/store/agents/marp/toolchain/test/support/viewer.mjsnew file mode 100644index 000000000..2d295040c--- /dev/null+++ b/store/agents/marp/toolchain/test/support/viewer.mjs@@ -0,0 +1,92 @@+// Start toolchain/viewer.mjs on a workspace the way Harness does, and talk to it over raw HTTP (so a+// path is sent exactly as written, without fetch normalising it first).+import { spawn } from 'node:child_process'+import { once } from 'node:events'+import http from 'node:http'+import net from 'node:net'+import { fileURLToPath } from 'node:url'++export const TOOLCHAIN = fileURLToPath(new URL('../..', import.meta.url))+const PRELOAD = new URL('./child.mjs', import.meta.url).href++export const delay = (ms) => new Promise((ok) => setTimeout(ok, ms))++export async function until(check, what, timeout = 5000) {+ const end = Date.now() + timeout+ for (;;) {+ const value = await check()+ if (value) return value+ if (Date.now() > end) throw new Error(`timed out waiting for ${what}`)+ await delay(20)+ }+}++function freePort() {+ return new Promise((ok, fail) => {+ const s = net.createServer()+ s.once('error', fail)+ s.listen(0, '127.0.0.1', () => { const { port } = s.address(); s.close(() => ok(port)) })+ })+}++export async function startViewer(workspace) {+ const port = await freePort()+ const child = spawn(process.execPath, ['--import', PRELOAD, `${TOOLCHAIN}viewer.mjs`], {+ env: { ...process.env, HARNESS_VIEWER_PORT: String(port), HARNESS_WORKSPACE: workspace, NO_COLOR: '1' },+ stdio: ['ignore', 'pipe', 'pipe'],+ })+ let output = ''+ child.stdout.on('data', (d) => { output += d })+ child.stderr.on('data', (d) => { output += d })+ await until(() => output.includes('listening on') || child.exitCode !== null, 'the viewer to listen')+ return {+ port,+ output: () => output,+ get: (path, headers = {}) => request(port, path, headers),+ events: () => events(port),+ stop: async () => { if (child.exitCode === null) { child.kill('SIGTERM'); await once(child, 'exit') } },+ }+}++function request(port, path, headers) {+ return new Promise((ok, fail) => {+ http.get({ host: '127.0.0.1', port, path, headers }, (res) => {+ const chunks = []+ res.on('data', (c) => chunks.push(c))+ res.on('end', () => {+ const body = Buffer.concat(chunks).toString('utf8')+ ok({ status: res.statusCode, type: res.headers['content-type'], cache: res.headers['cache-control'], body, json: () => JSON.parse(body) })+ })+ }).on('error', fail)+ })+}++/** An open /events stream: `next(event)` resolves with the next matching block's data. */+function events(port) {+ return new Promise((ok, fail) => {+ const req = http.get({ host: '127.0.0.1', port, path: '/events' }, (res) => {+ let buffer = ''+ const seen = []+ res.setEncoding('utf8')+ res.on('data', (chunk) => {+ buffer += chunk+ let i+ while ((i = buffer.indexOf('\n\n')) >= 0) { seen.push(buffer.slice(0, i)); buffer = buffer.slice(i + 2) }+ })+ ok({+ status: res.statusCode,+ type: res.headers['content-type'],+ seen,+ next: (event) => until(() => {+ const at = seen.findIndex((block) => block.startsWith(`event: ${event}\n`))+ if (at < 0) return null+ const [block] = seen.splice(0, at + 1).slice(-1)+ return JSON.parse(block.slice(block.indexOf('data: ') + 6))+ }, `a ${event} event`),+ comment: (text) => until(() => seen.includes(`: ${text}`), `": ${text}"`),+ close: () => req.destroy(),+ })+ })+ req.on('error', (error) => { if (error.code !== 'ECONNRESET') fail(error) })+ })+}diff --git a/store/agents/marp/toolchain/test/viewer.test.mjs b/store/agents/marp/toolchain/test/viewer.test.mjsnew file mode 100644index 000000000..189f334a7--- /dev/null+++ b/store/agents/marp/toolchain/test/viewer.test.mjs@@ -0,0 +1,146 @@+// The pane's server, run as Harness runs it: a real process on a loopback port over a scratch workspace.+import { test, before, after } from 'node:test'+import assert from 'node:assert/strict'+import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'+import { tmpdir } from 'node:os'+import { join } from 'node:path'+import { TOOLCHAIN, delay, startViewer } from './support/viewer.mjs'++const body = 'A body with several words in it.'+const DECK = `---\nmarp: true\n---\n# Talk\n\n\n\n${body}\n\n---\n\n## A\n\n${body}\n\n---\n\n## B\n\n${body}\n`++let root, ws, viewer+before(async () => {+ root = mkdtempSync(join(tmpdir(), 'marp-viewer-'))+ ws = join(root, 'ws')+ mkdirSync(join(ws, 'assets'), { recursive: true })+ mkdirSync(join(ws, 'folder.md')) // a directory that looks like a deck+ writeFileSync(join(ws, 'deck.md'), DECK)+ writeFileSync(join(ws, 'README.md'), '# Readme\n')+ writeFileSync(join(ws, 'assets', 'bg.svg'), '<svg xmlns="http://www.w3.org/2000/svg"/>')+ writeFileSync(join(ws, 'assets', 'growth 50%.png'), 'png')+ writeFileSync(join(ws, 'notes.xyz'), 'plain')+ writeFileSync(join(root, 'secret.txt'), 'outside the workspace')+ mkdirSync(join(root, 'ws-sibling'))+ writeFileSync(join(root, 'ws-sibling', 'deck.md'), '# Not this workspace\n')+ viewer = await startViewer(ws)+})+after(async () => {+ await viewer?.stop()+ rmSync(root, { recursive: true, force: true })+})++test('says where it listens', () => {+ assert.match(viewer.output(), new RegExp(`\\[marp:viewer\\] listening on http://127\\.0\\.0\\.1:${viewer.port}/ \\(workspace: `))+})++test('serves the page and its files, never a path outside viewer/', async () => {+ const page = await viewer.get('/')+ assert.equal(page.status, 200)+ assert.equal(page.type, 'text/html; charset=utf-8')+ assert.equal(page.cache, 'no-store')+ assert.match(page.body, /<script src="\/viewer\/app\.js"><\/script>/)+ assert.equal((await viewer.get('/viewer/app.js')).type, 'text/javascript; charset=utf-8')+ assert.equal((await viewer.get('/viewer/app.css')).type, 'text/css; charset=utf-8')+ assert.equal((await viewer.get('/viewer/nope.js')).status, 404)+ assert.equal((await viewer.get('/viewer/app.js.map')).status, 404, 'the page folder serves only html, js and css')+ assert.equal((await viewer.get('/viewer/')).status, 404, 'the folder itself is not a file')+ const escape = await viewer.get('/viewer/..%2F..%2Fviewer.mjs')+ assert.equal(escape.status, 404)+})++test('serves marp-core\'s browser script', async () => {+ const script = await viewer.get('/marp-browser.js')+ assert.equal(script.status, 200)+ assert.equal(script.type, 'text/javascript')+ assert.equal(script.body, readFileSync(join(TOOLCHAIN, 'node_modules/@marp-team/marp-core/lib/browser.js'), 'utf8'))+})++test('deck.json renders the deck and rewrites the verdict', async () => {+ rmSync(join(ws, '.harness'), { recursive: true, force: true })+ const deck = (await viewer.get('/deck.json')).json()+ assert.equal(deck.deck, 'deck.md')+ assert.equal(deck.missing, false)+ assert.equal(deck.html.length, 3)+ assert.equal(deck.slides[0].title, 'Talk')+ assert.ok(deck.css.length > 0)+ assert.equal(deck.verdict.ready, true)+ const written = JSON.parse(readFileSync(join(ws, '.harness', 'verdict.json'), 'utf8'))+ assert.equal(written.summary, deck.verdict.summary)+ assert.deepEqual((await viewer.get('/deck.json?file=%2Fdeck.md')).json().deck, 'deck.md', 'a leading slash is the workspace root')+})++test('another Markdown file renders but is never judged', async () => {+ rmSync(join(ws, '.harness'), { recursive: true, force: true })+ const readme = (await viewer.get('/deck.json?file=README.md')).json()+ assert.equal(readme.deck, 'README.md')+ assert.equal(readme.verdict, null)+ assert.equal(readme.slides[0].title, 'Readme')+ assert.equal(existsSync(join(ws, '.harness', 'verdict.json')), false)+})++test('deck.json falls back to deck.md for anything that is not a Markdown file in the workspace', async () => {+ for (const file of ['../ws-sibling/deck.md', 'notes.xyz', '..', '']) {+ assert.equal((await viewer.get(`/deck.json?file=${encodeURIComponent(file)}`)).json().deck, 'deck.md', file)+ }+})++test('deck.json says when the deck is missing, and reports a deck that cannot be read', async () => {+ assert.deepEqual((await viewer.get('/deck.json?file=talk.md')).json(), { html: [], css: '', slides: [], deck: 'talk.md', missing: true, verdict: null })+ const unreadable = await viewer.get('/deck.json?file=folder.md')+ assert.equal(unreadable.status, 200)+ assert.match(unreadable.json().error, /EISDIR/)+})++test('serves workspace files by the path the deck wrote, and nothing outside the workspace', async () => {+ const svg = await viewer.get('/assets/bg.svg')+ assert.equal(svg.status, 200)+ assert.equal(svg.type, 'image/svg+xml')+ assert.equal((await viewer.get('/assets/growth%2050%25.png')).body, 'png')+ assert.equal((await viewer.get('/notes.xyz')).type, 'application/octet-stream')+ assert.equal((await viewer.get('/assets/missing.png')).status, 404)+ assert.equal((await viewer.get('/assets')).status, 404, 'a folder is not a file')+ assert.equal((await viewer.get('/..%2Fsecret.txt')).status, 404)+ assert.equal((await viewer.get('/..%2Fws-sibling%2Fdeck.md')).status, 404, 'a sibling folder that shares the prefix is outside')+})++test('a malformed path is a bad request, not a crash', async () => {+ const bad = await viewer.get('/assets/growth%2050%.png')+ assert.equal(bad.status, 400)+ assert.equal((await viewer.get('/deck.json')).status, 200, 'the viewer is still up')+})++test('events: hello, a change per save naming the path, pings; state folders are not changes', async () => {+ const stream = await viewer.events()+ assert.equal(stream.status, 200)+ assert.equal(stream.type, 'text/event-stream')+ await stream.comment('hello')+ await stream.comment('ping')+ await delay(300)+ writeFileSync(join(ws, 'deck.md'), DECK + '\n')+ assert.deepEqual(await stream.next('change'), { path: 'deck.md' })+ writeFileSync(join(ws, 'assets', 'one.svg'), 'x')+ writeFileSync(join(ws, 'assets', 'two.svg'), 'x')+ assert.deepEqual(await stream.next('change'), { path: 'assets/two.svg' }, 'a burst of saves is one change naming the last')+ await delay(400)+ assert.equal(stream.seen.some((block) => block.startsWith('event: change')), false, 'and only one')+ for (const [ignored, noticed] of [['.harness/verdict.json', 'distribution.md'], ['dist/deck.pdf', 'dist-notes.md'], ['.git/HEAD', '.github.md'], ['node_modules/x.js', 'assets/chart.svg'], ['.claude/settings.json', '.harness-notes.md']]) {+ mkdirSync(join(ws, ignored, '..'), { recursive: true })+ writeFileSync(join(ws, ignored), 'x')+ await delay(400)+ writeFileSync(join(ws, noticed), 'x')+ assert.deepEqual(await stream.next('change'), { path: noticed }, `${ignored} is state; ${noticed} is a change`)+ }+ stream.close()+})++test('a workspace that cannot be watched still serves', async () => {+ const missing = join(root, 'not-yet')+ const lonely = await startViewer(missing)+ try {+ assert.match(lonely.output(), /\[marp\] cannot watch .*not-yet: /)+ assert.equal((await lonely.get('/deck.json')).json().missing, true)+ } finally {+ await lonely.stop()+ }+})diff --git a/store/agents/marp/toolchain/viewer.mjs b/store/agents/marp/toolchain/viewer.mjsindex 956c548dc..e83f2c50b 100644--- a/store/agents/marp/toolchain/viewer.mjs+++ b/store/agents/marp/toolchain/viewer.mjs@@ -54,12 +54,12 @@ const PAGE = join(toolchainDir, 'viewer')const PAGE_TYPES = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8' }const server = createServer((req, res) => {- const url = new URL(req.url ?? '/', `http://${host}:${port}`)+ const url = new URL(req.url, `http://${host}:${port}`)if (url.pathname === '/' || url.pathname.startsWith('/viewer/')) {const name = url.pathname === '/' ? 'index.html' : url.pathname.slice('/viewer/'.length)const full = normalize(join(PAGE, name))- if (!full.startsWith(PAGE + sep) || !existsSync(full) || !statSync(full).isFile()) { res.writeHead(404); res.end('not found'); return }- res.writeHead(200, { 'content-type': PAGE_TYPES[extname(full)] ?? 'application/octet-stream', 'cache-control': 'no-store' })+ if (!full.startsWith(PAGE + sep) || !PAGE_TYPES[extname(full)] || !existsSync(full) || !statSync(full).isFile()) { res.writeHead(404); res.end('not found'); return }+ res.writeHead(200, { 'content-type': PAGE_TYPES[extname(full)], 'cache-control': 'no-store' })res.end(readFileSync(full))return}@@ -75,7 +75,7 @@ const server = createServer((req, res) => {try {body = deckJson(safeDeckFile(url.searchParams.get('file')))} catch (error) {- body = { error: error instanceof Error ? error.message : String(error) }+ body = { error: error.message }}res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })res.end(JSON.stringify(body))@@ -89,7 +89,10 @@ const server = createServer((req, res) => {return}// A workspace file, by the path the deck wrote. Never a path that leaves the workspace.- const rel = decodeURIComponent(url.pathname).replace(/^\/+/, '')+ // A path that is not valid percent-encoding (an image named "50%.png" written unescaped) is a bad+ // request; left to throw, it took the whole viewer down with it.+ let rel+ try { rel = decodeURIComponent(url.pathname).replace(/^\/+/, '') } catch { res.writeHead(400); res.end('bad request'); return }const full = normalize(resolve(workspace, rel))if (!full.startsWith(workspace + sep) || !existsSync(full) || !statSync(full).isFile()) {res.writeHead(404); res.end('not found'); return@@ -102,9 +105,13 @@ const server = createServer((req, res) => {// edit (redraw) from anything else.let timer = nulllet lastPath = ''+const STATE_DIRS = new Set(['.harness', 'dist', '.git', 'node_modules', '.claude'])function changed(path) {- const rel = relative(workspace, join(workspace, path ?? '')).split(sep).join('/')- if (rel.startsWith('.harness') || rel.startsWith('dist') || rel.startsWith('.git') || rel.startsWith('node_modules') || rel.startsWith('.claude')) return+ /* c8 ignore next */ // fs.watch leaves the filename out only on platforms whose watcher cannot name it+ const name = path ?? ''+ const rel = relative(workspace, join(workspace, name)).split(sep).join('/')+ // By top-level folder: a prefix match also swallowed distribution.md, .github/ and .harness-notes.md.+ if (STATE_DIRS.has(rel.split('/')[0])) returnlastPath = relif (timer) clearTimeout(timer)timer = setTimeout(() => {@@ -116,7 +123,7 @@ function changed(path) {try {watch(workspace, { recursive: true }, (_event, filename) => changed(filename?.toString()))} catch (error) {- console.error(`[marp] cannot watch ${workspace}: ${error instanceof Error ? error.message : error}`)+ console.error(`[marp] cannot watch ${workspace}: ${error.message}`)}setInterval(() => { for (const client of clients) client.write(': ping\n\n') }, 20_000).unref()