mirror of
https://github.com/garrytan/gstack.git
synced 2026-12-03 05:13:49 +01:00
Screenshots, PDFs and page dumps that browsing skills take in the Aside browser now reach your report folder instead of vanishing. Aside deletes a script's working folder as soon as the script ends and refuses to save anywhere else, so the old "save, then copy it out" step always failed (#4784). Nothing to do: skills pick up the new route on upgrade, and gstack's own fallback browser is unchanged. Co-authored-by: capy-ai[bot] <230910855+capy-ai[bot]@users.noreply.github.com> Review-Finding: p1/specialist-batched#1 reader=specialist-batched Review-Finding: p1/specialist-batched#2 reader=specialist-batched Review-Finding: p1/specialist-batched#3 reader=specialist-batched
This commit is contained in:
1 parent
5278bb4e1a
commit
df760be4d7
43 files changed
+583
-336
No files matched your search
@@ -0,0 +1,170 @@
|
||||
/**
|
||||
* #4784: a one-shot `aside repl` deletes its session directory when the script
|
||||
* ends and its sandbox refuses every path outside it (verified on Aside CLI
|
||||
* 1.26.1107), so the old "save with a relative path, print ASIDE_DIR=, cp it
|
||||
* afterwards" pattern always lost the file. Artifacts now leave over stdout
|
||||
* through bin/gstack-aside-repl. This file pins three things:
|
||||
* 1. no generated skill doc carries the copy-after-the-script pattern, and
|
||||
* every Aside script that saves a file runs through the wrapper;
|
||||
* 2. the $B fallback never uses the wrapper or the old copy step;
|
||||
* 3. the wrapper's stdout contract, against a fake `aside`.
|
||||
*/
|
||||
import { describe, expect, test } from 'bun:test';
|
||||
import { spawnSync } from 'node:child_process';
|
||||
import * as fs from 'node:fs';
|
||||
import * as os from 'node:os';
|
||||
import * as path from 'node:path';
|
||||
import { generateBrowseFallback } from '../scripts/resolvers/browse';
|
||||
import { HOST_PATHS } from '../scripts/resolvers/types';
|
||||
|
||||
const ROOT = path.resolve(import.meta.dir, '..');
|
||||
const WRAPPER = path.join(ROOT, 'bin', 'gstack-aside-repl');
|
||||
|
||||
const tracked = spawnSync('git', ['ls-files', '-z'], { cwd: ROOT, encoding: 'utf8', timeout: 30_000 }).stdout.split('\0').filter(Boolean);
|
||||
const GENERATED = tracked.filter(f => f.endsWith('.md') && tracked.includes(`${f}.tmpl`));
|
||||
|
||||
/** Every bash script handed to Aside: [launcher line, script body]. */
|
||||
function asideScripts(doc: string): Array<[string, string]> {
|
||||
return [...doc.matchAll(/^(.*\b(?:aside repl|gstack-aside-repl)\b.*) '\n([\s\S]*?)\n'\n/gm)].map(m => [m[1], m[2]]);
|
||||
}
|
||||
|
||||
describe('#4784: generated skill docs never copy artifacts out of the Aside session directory', () => {
|
||||
test('the generated docs exist and some of them save Aside artifacts', () => {
|
||||
expect(GENERATED.length).toBeGreaterThan(40);
|
||||
expect(GENERATED.filter(f => fs.readFileSync(path.join(ROOT, f), 'utf8').includes('saveArtifact(')).length).toBeGreaterThanOrEqual(8);
|
||||
});
|
||||
|
||||
for (const file of GENERATED) {
|
||||
const doc = fs.readFileSync(path.join(ROOT, file), 'utf8');
|
||||
if (!/aside repl|gstack-aside-repl|ASIDE_DIR|saveArtifact/.test(doc)) continue;
|
||||
test(`${file}: no ASIDE_DIR copy step, no file written into the session dir, every saving script wrapped`, () => {
|
||||
expect(doc).not.toContain('ASIDE_DIR');
|
||||
expect(doc).not.toMatch(/path\.join\(pwd/);
|
||||
expect(doc).not.toMatch(/\.(?:screenshot|pdf)\(\{ path/);
|
||||
for (const [launcher, body] of asideScripts(doc)) {
|
||||
const saves = /saveArtifact\(|fs\.writeFile/.test(body);
|
||||
if (!saves) continue;
|
||||
expect({ launcher, wrapped: /gstack-aside-repl --out \S/.test(launcher) }).toEqual({ launcher, wrapped: true });
|
||||
expect(body).not.toContain('fs.writeFile');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe('#4784: the $B fallback is unchanged by the Aside artifact fix', () => {
|
||||
const ctx = { skillName: 'browse', tmplPath: '', host: 'claude' as const, paths: HOST_PATHS['claude'] };
|
||||
for (const skillName of ['browse', 'qa', 'design-review', 'canary']) {
|
||||
test(`${skillName}: only the Aside column of the translation table names the wrapper; $B commands stay as they were`, () => {
|
||||
const fallback = generateBrowseFallback({ ...ctx, skillName });
|
||||
expect(fallback).not.toContain('ASIDE_DIR');
|
||||
for (const line of fallback.split('\n').filter(l => /saveArtifact|gstack-aside-repl|SAVED=/.test(l))) {
|
||||
const cells = line.split(' | ');
|
||||
expect({ line, row: line.startsWith('| ') }).toEqual({ line, row: true });
|
||||
expect(['\`$B screenshot <path>\` (already on disk) |', '\`$B pdf <out> [flags]\` |']).toContain(cells[cells.length - 1]);
|
||||
}
|
||||
if (fallback.includes('### Translate the Aside scripts')) {
|
||||
expect(fallback).toContain('| \`$B screenshot <path>\` (already on disk) |');
|
||||
expect(fallback).toContain('| \`$B pdf <out> [flags]\` |');
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
describe.skipIf(process.platform === 'win32')('bin/gstack-aside-repl against a fake aside', () => {
|
||||
const tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'aside-repl-'));
|
||||
const bin = path.join(tmp, 'bin');
|
||||
fs.mkdirSync(bin);
|
||||
const scriptFile = path.join(tmp, 'script.js');
|
||||
/** A fake `aside`: records the script it got, then prints what the test says (MARK expands to the real marker). */
|
||||
const fake = (body: string, exit = 0) => fs.writeFileSync(path.join(bin, 'aside'), [
|
||||
'#!/bin/sh',
|
||||
`printf '%s' "$2" > ${JSON.stringify(scriptFile)}`,
|
||||
`MARK=$(head -1 ${JSON.stringify(scriptFile)} | sed 's/.*"\\(GSTACK_ARTIFACT_[0-9a-f]*\\)".*/\\1/')`,
|
||||
body,
|
||||
`exit ${exit}`,
|
||||
].join('\n'), { mode: 0o755 });
|
||||
const run = (args: string[]) => spawnSync(WRAPPER, args, { cwd: tmp, encoding: 'utf8', timeout: 30_000, env: { ...process.env, PATH: `${bin}:${process.env.PATH}` } });
|
||||
const b64 = (s: string) => Buffer.from(s).toString('base64');
|
||||
|
||||
test('saves each marked artifact to --out, prints SAVED= in its place and passes evidence lines through', () => {
|
||||
const out = path.join(tmp, 'ok');
|
||||
fake(`echo "URL=http://localhost/"; echo "$MARK shot.jpg 10 ${b64('JPEG-BYTES')}"; echo GSTACK_STEP_OK`);
|
||||
const r = run(['--out', out, 'saveArtifact("shot.jpg", await pg.screenshot())']);
|
||||
expect(r.status).toBe(0);
|
||||
expect(fs.readFileSync(path.join(out, 'shot.jpg'), 'utf8')).toBe('JPEG-BYTES');
|
||||
expect(r.stdout.split('\n')).toEqual(['URL=http://localhost/', `SAVED=${path.join(out, 'shot.jpg')} bytes=10`, 'GSTACK_STEP_OK', '']);
|
||||
expect(r.stdout).not.toContain(b64('JPEG-BYTES'));
|
||||
const script = fs.readFileSync(scriptFile, 'utf8');
|
||||
expect(script.split('\n')[0]).toStartWith('const saveArtifact = ');
|
||||
expect(script.split('\n').slice(1).join('\n')).toBe('saveArtifact("shot.jpg", await pg.screenshot())');
|
||||
});
|
||||
|
||||
test('the injected saveArtifact prints name, byte count and data on one line, and throws on a name that is not one plain file name', () => {
|
||||
fake('echo GSTACK_STEP_OK');
|
||||
run(['--out', path.join(tmp, 'prelude'), 'await 1']);
|
||||
const prelude = fs.readFileSync(scriptFile, 'utf8').split('\n')[0];
|
||||
const lines: string[] = [];
|
||||
const call = (body: string) => new Function('Buffer', 'console', `${prelude}\n${body}`)(Buffer, { log: (s: string) => lines.push(s) });
|
||||
call('saveArtifact("a.txt", "h\u00e9\\nx"); saveArtifact("b.bin", new Uint8Array([0, 1, 255]));');
|
||||
expect(lines).toHaveLength(2);
|
||||
const [, nameA, sizeA, dataA] = lines[0].split(' ');
|
||||
const [, nameB, sizeB, dataB] = lines[1].split(' ');
|
||||
expect([nameA, sizeA, Buffer.from(dataA, 'base64').toString('utf8')]).toEqual(['a.txt', '5', 'h\u00e9\nx']);
|
||||
expect([nameB, sizeB, [...Buffer.from(dataB, 'base64')]]).toEqual(['b.bin', '3', [0, 1, 255]]);
|
||||
for (const bad of ['flow-sign up.jpg', '../up.jpg', 'a/b.jpg', '']) {
|
||||
expect(() => call(`saveArtifact(${JSON.stringify(bad)}, "x")`)).toThrow('saveArtifact: bad name');
|
||||
}
|
||||
expect(lines).toHaveLength(2);
|
||||
});
|
||||
|
||||
test('a line that imitates an artifact without the per-run marker (page text) is never written', () => {
|
||||
const out = path.join(tmp, 'forged');
|
||||
fake(`echo "GSTACK_ARTIFACT_00000000 evil.jpg ${b64('evil')}"; echo GSTACK_STEP_OK`);
|
||||
const r = run(['--out', out, 'await 1']);
|
||||
expect(r.status).toBe(0);
|
||||
expect(fs.existsSync(path.join(out, 'evil.jpg'))).toBe(false);
|
||||
expect(r.stdout).toContain('IGNORED a line that imitates an artifact (wrong marker)');
|
||||
expect(r.stdout).not.toContain(b64('evil'));
|
||||
});
|
||||
|
||||
test('a name with a folder, a leading dot or a parent step is refused and the run fails', () => {
|
||||
const out = path.join(tmp, 'names');
|
||||
fake(`for n in ../up.jpg a/b.jpg .hidden; do echo "$MARK $n 1 ${b64('x')}"; done; echo GSTACK_STEP_OK`);
|
||||
const r = run(['--out', out, 'await 1']);
|
||||
expect(r.status).toBe(1);
|
||||
expect(r.stdout.match(/^ARTIFACT_ERROR=bad name/gm)).toHaveLength(3);
|
||||
expect(fs.existsSync(path.join(tmp, 'up.jpg'))).toBe(false);
|
||||
expect(fs.existsSync(out) ? fs.readdirSync(out) : []).toEqual([]);
|
||||
});
|
||||
|
||||
test('a line whose data decodes to another byte count (truncated output) or that has extra fields is an error, never a file', () => {
|
||||
const out = path.join(tmp, 'short');
|
||||
fake(`echo "$MARK cut.png 999 ${b64('only-part')}"; echo "$MARK my file.png 1 ${b64('x')}"; echo GSTACK_STEP_OK`);
|
||||
const r = run(['--out', out, 'await 1']);
|
||||
expect(r.status).toBe(1);
|
||||
expect(r.stdout).toContain('truncated: expected 999 bytes, decoded 9');
|
||||
expect(r.stdout.match(/^ARTIFACT_ERROR=/gm)).toHaveLength(2);
|
||||
expect(fs.existsSync(out) ? fs.readdirSync(out) : []).toEqual([]);
|
||||
});
|
||||
|
||||
test('an existing symlink at the target is not written through', () => {
|
||||
const out = path.join(tmp, 'link');
|
||||
const victim = path.join(tmp, 'victim.txt');
|
||||
fs.mkdirSync(out);
|
||||
fs.writeFileSync(victim, 'keep');
|
||||
fs.symlinkSync(victim, path.join(out, 'shot.jpg'));
|
||||
fake(`echo "$MARK shot.jpg 9 ${b64('overwrite')}"; echo GSTACK_STEP_OK`);
|
||||
const r = run(['--out', out, 'await 1']);
|
||||
expect(r.status).toBe(1);
|
||||
expect(r.stdout).toContain('refusing to write through a symlink');
|
||||
expect(fs.readFileSync(victim, 'utf8')).toBe('keep');
|
||||
});
|
||||
|
||||
test("aside's own exit code comes through, and a missing --out is a usage error", () => {
|
||||
fake('echo "[error boom"', 3);
|
||||
expect(run(['--out', path.join(tmp, 'exit'), 'await 1']).status).toBe(3);
|
||||
const usage = run(['await 1']);
|
||||
expect(usage.status).toBe(2);
|
||||
expect(usage.stderr).toContain('usage: gstack-aside-repl --out <dir>');
|
||||
});
|
||||
});
|
||||
@@ -115,10 +115,13 @@ describe('Aside driver contract ({{ASIDE_SETUP}})', () => {
|
||||
expect(section).toContain('GSTACK_STEP_OK');
|
||||
});
|
||||
|
||||
test('artifact handoff goes through the printed session directory', () => {
|
||||
expect(section).toContain('ASIDE_DIR=');
|
||||
expect(section).toContain('never print image data');
|
||||
expect(section).toContain('use the Read tool on the copied file');
|
||||
test('artifact handoff goes through stdout, never a copy out of the deleted session directory (#4784)', () => {
|
||||
expect(section).toContain('Artifacts leave through stdout');
|
||||
expect(section).toContain('gstack-aside-repl --out <dir>');
|
||||
expect(section).toContain('saveArtifact(');
|
||||
expect(section).toContain('Never print image data yourself');
|
||||
expect(section).toContain('Use the Read tool on each `SAVED=` screenshot');
|
||||
expect(section).not.toContain('ASIDE_DIR');
|
||||
});
|
||||
|
||||
test('cookbook names the silent failure modes of aside repl scripts (#3064)', () => {
|
||||
@@ -148,7 +151,7 @@ describe('Aside driver contract ({{ASIDE_SETUP}})', () => {
|
||||
expect(section).not.toContain('pg.on("console"');
|
||||
expect(section).not.toContain('TARGET_ID=');
|
||||
// Every cookbook script ends by closing its tab and printing the sentinel.
|
||||
const scripts = [...section.matchAll(/aside repl '([\s\S]*?)'\n```/g)].map(m => m[1]);
|
||||
const scripts = [...section.matchAll(/(?:aside repl|gstack-aside-repl --out \S+) '([\s\S]*?)'\n```/g)].map(m => m[1]);
|
||||
expect(scripts.length).toBeGreaterThanOrEqual(6);
|
||||
for (const s of scripts) {
|
||||
expect(s).toContain('await closeTab(pg)');
|
||||
@@ -355,7 +358,7 @@ describe('browser fallback ({{BROWSE_FALLBACK}})', () => {
|
||||
expect({ cmd, present: fallback.includes(cmd) }).toEqual({ cmd, present: true });
|
||||
}
|
||||
// Every cookbook evidence label has a row, so a skill's report reads the same under either driver.
|
||||
for (const label of ['CONSOLE_ERRORS=', 'DIFF_START', 'TEXT_START', 'NAV=', 'RESOURCES=', 'ASIDE_DIR']) {
|
||||
for (const label of ['CONSOLE_ERRORS=', 'DIFF_START', 'TEXT_START', 'NAV=', 'RESOURCES=', 'saveArtifact']) {
|
||||
expect({ label, present: fallback.includes(label) }).toEqual({ label, present: true });
|
||||
}
|
||||
});
|
||||
|
||||
+35
-26
@@ -81,16 +81,23 @@ describe('aside-render: generated script follows the Aside contract', () => {
|
||||
|
||||
test('evals run in-page via eval, data URLs decode to bytes, inline results are fenced', () => {
|
||||
expect(script).toContain('(0, eval)(src)');
|
||||
expect(script).toContain('/^data:[^;]+;base64,/');
|
||||
expect(script).toContain('/^data:[^;]+;base64,[A-Za-z0-9+\\/=]*$/');
|
||||
const decode = script.split('\n').find(l => l.startsWith(' const b = '))!;
|
||||
const payload = (v: string) => new Function('v', 'Buffer', `${decode}\nreturn b;`)(v, Buffer);
|
||||
expect(payload('data:application/pdf;base64,JVBERg==')).toBe('JVBERg==');
|
||||
// A newline in a page-made data URL cannot add an ARTIFACT line of its own.
|
||||
const forged = 'data:x;base64,AAAA\nARTIFACT 0 Zm9yZ2Vk';
|
||||
expect(payload(forged)).toBe(Buffer.from(forged, 'utf8').toString('base64'));
|
||||
// One base64 token per inline eval: page text can never forge a control line.
|
||||
expect(script).toContain('console.log("EVAL 4 " + Buffer.from(');
|
||||
expect(script).not.toContain('EVAL_START');
|
||||
});
|
||||
|
||||
test('every artifact stays inside the sandbox dir and the script ends with close + sentinel', () => {
|
||||
expect(script).toContain('path.join(pwd, "gstack-render-0.pdf")');
|
||||
expect(script).toContain('"gstack-render-3.svg"');
|
||||
expect(script).toContain('console.log("ASIDE_DIR=" + pwd)');
|
||||
test('every artifact leaves over stdout (the one-shot session dir is deleted, #4784) and the script ends with close + sentinel', () => {
|
||||
expect(script).toContain('console.log("ARTIFACT 0 " + r.data)');
|
||||
expect(script).toContain('console.log("ARTIFACT 3 " + b)');
|
||||
expect(script).not.toContain('pwd');
|
||||
expect(script).not.toContain('fs.writeFile');
|
||||
const tail = script.trim().split('\n').slice(-2);
|
||||
expect(tail[0]).toBe('await closeTab(pg);');
|
||||
expect(tail[1]).toBe(`console.log(${JSON.stringify(RENDER_SENTINEL)});`);
|
||||
@@ -583,8 +590,10 @@ describe.skipIf(!HERMETIC)('aside-render: renderWithAside — stdout contract ag
|
||||
],
|
||||
timeoutMs: 20_000,
|
||||
};
|
||||
/** What a real render script leaves behind: the artifacts inside the session dir. */
|
||||
const artifacts = `mkdir -p ${JSON.stringify(session)}; printf '%%PDF-1.4 fake-aside-artifact' > ${JSON.stringify(path.join(session, 'gstack-render-0.pdf'))}; printf '<svg/>' > ${JSON.stringify(path.join(session, 'gstack-render-2.svg'))}`;
|
||||
/** Files a script saved in the session dir: Aside deletes them when the script ends, so they are never the artifact (#4784). */
|
||||
const leftovers = `mkdir -p ${JSON.stringify(session)}; printf '%%PDF-1.4 fake-aside-artifact' > ${JSON.stringify(path.join(session, 'gstack-render-0.pdf'))}; printf '<svg/>' > ${JSON.stringify(path.join(session, 'gstack-render-2.svg'))}`;
|
||||
/** What a real render script prints: one ARTIFACT line per file step. */
|
||||
const artifacts = `echo "ARTIFACT 0 ${b64('%PDF-1.4 fake-aside-artifact')}"; echo "ARTIFACT 2 ${b64('<svg/>')}"`;
|
||||
const record = `printf '%s' "$2" > ${JSON.stringify(scriptFile)}`;
|
||||
const render = (repl: string | null, s: RenderSpec = spec): RenderResult => {
|
||||
fs.rmSync(path.join(tmp, 'out'), { recursive: true, force: true });
|
||||
@@ -594,8 +603,8 @@ describe.skipIf(!HERMETIC)('aside-render: renderWithAside — stdout contract ag
|
||||
return runDriver<RenderResult>(driver, { fn: 'renderWithAside', spec: s }, { binDir: bin });
|
||||
};
|
||||
|
||||
test('success: artifacts are copied from ASIDE_DIR to each step.out (nested dirs created) and base64 evals are decoded', () => {
|
||||
const r = render(`${record}; ${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "PAGE_ERRORS=[]"; echo "ASIDE_DIR=${session}"; echo "${RENDER_SENTINEL}"`);
|
||||
test('success: ARTIFACT lines are decoded to each step.out (nested dirs created) and base64 evals are decoded', () => {
|
||||
const r = render(`${record}; ${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "PAGE_ERRORS=[]"; echo "${RENDER_SENTINEL}"`);
|
||||
expect(r.error).toBeUndefined();
|
||||
expectOk(r);
|
||||
expect(r.engine).toBe('aside');
|
||||
@@ -608,7 +617,7 @@ describe.skipIf(!HERMETIC)('aside-render: renderWithAside — stdout contract ag
|
||||
});
|
||||
|
||||
test('the script handed to `aside repl` navigates to http://127.0.0.1:<port>/<32-hex nonce>/<file> and prints via CDP', () => {
|
||||
render(`${record}; ${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "ASIDE_DIR=${session}"; echo "${RENDER_SENTINEL}"`);
|
||||
render(`${record}; ${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "${RENDER_SENTINEL}"`);
|
||||
const script = fs.readFileSync(scriptFile, 'utf8');
|
||||
const goto = script.match(/await pg\.goto\("([^"]+)", \{ waitUntil: "load", timeout: 20000 \}\);/);
|
||||
expect(goto).not.toBeNull();
|
||||
@@ -634,33 +643,33 @@ describe.skipIf(!HERMETIC)('aside-render: renderWithAside — stdout contract ag
|
||||
expect(r.error).toBe('render script did not finish: no output (GSTACK_SKIP_ASIDE=1 forces gstack\'s own browser)');
|
||||
});
|
||||
|
||||
test('sentinel without an ASIDE_DIR line → "printed no ASIDE_DIR" (nothing is guessed)', () => {
|
||||
const r = render(`${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "PAGE_ERRORS=[]"; echo "${RENDER_SENTINEL}"`);
|
||||
test('#4784: files left in the session dir are never copied; a step with no ARTIFACT line fails and evals are still reported', () => {
|
||||
const r = render(`${leftovers}; echo "EVAL 1 ${b64('Doc')}"; echo "ASIDE_DIR=${session}"; echo "PAGE_ERRORS=[]"; echo "${RENDER_SENTINEL}"`);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.error).toBe('render script printed no ASIDE_DIR');
|
||||
expect(r.evals).toEqual({ 1: 'Doc' }); // evals already decoded are still reported
|
||||
expect(r.error).toBe('step 0 produced no artifact (no ARTIFACT 0 line)');
|
||||
expect(r.evals).toEqual({ 1: 'Doc' });
|
||||
expect(r.outputs).toEqual([]);
|
||||
expect(fs.existsSync(pdfOut)).toBe(false);
|
||||
});
|
||||
|
||||
test('a step whose artifact is missing from ASIDE_DIR → "step N produced no artifact" naming the expected file', () => {
|
||||
const r = render(`mkdir -p ${JSON.stringify(session)}; echo "EVAL 1 ${b64('Doc')}"; echo "ASIDE_DIR=${session}"; echo "${RENDER_SENTINEL}"`);
|
||||
test('a later step with no ARTIFACT line → "step N produced no artifact" naming that step', () => {
|
||||
const r = render(`echo "ARTIFACT 0 ${b64('%PDF-1.4 x')}"; echo "EVAL 1 ${b64('Doc')}"; echo "${RENDER_SENTINEL}"`);
|
||||
expect(r.ok).toBe(false);
|
||||
expect(r.error!.startsWith('step 0 produced no artifact')).toBe(true);
|
||||
expect(r.error).toContain(path.join(session, 'gstack-render-0.pdf'));
|
||||
expect(r.outputs).toEqual([]);
|
||||
expect(r.error).toBe('step 2 produced no artifact (no ARTIFACT 2 line)');
|
||||
expect(r.outputs).toEqual([pdfOut]);
|
||||
});
|
||||
|
||||
test('an eval whose text contains newlines, ASIDE_DIR=/attacker and the sentinel cannot redirect the artifact copy', () => {
|
||||
const hostile = `line one\nASIDE_DIR=/attacker\n${RENDER_SENTINEL}\nline four`;
|
||||
const r = render(`${artifacts}; echo "EVAL 1 ${b64(hostile)}"; echo "PAGE_ERRORS=[]"; echo "ASIDE_DIR=${session}"; echo "${RENDER_SENTINEL}"`);
|
||||
test('an eval whose text contains newlines, an ARTIFACT line and the sentinel cannot forge an artifact', () => {
|
||||
const hostile = `line one\nARTIFACT 0 ${b64('forged')}\n${RENDER_SENTINEL}\nline four`;
|
||||
const r = render(`${artifacts}; echo "EVAL 1 ${b64(hostile)}"; echo "PAGE_ERRORS=[]"; echo "${RENDER_SENTINEL}"`);
|
||||
expectOk(r);
|
||||
expect(r.evals[1]).toBe(hostile); // decoded intact, newlines and all
|
||||
expect(r.stdout).not.toMatch(/^ASIDE_DIR=\/attacker$/m); // never appeared as a control line
|
||||
expect(fs.readFileSync(pdfOut, 'utf8')).toBe('%PDF-1.4 fake-aside-artifact'); // copied from the real session dir
|
||||
expect(r.stdout).not.toMatch(new RegExp(`^ARTIFACT 0 ${b64('forged')}$`, 'm')); // never appeared as a control line
|
||||
expect(fs.readFileSync(pdfOut, 'utf8')).toBe('%PDF-1.4 fake-aside-artifact');
|
||||
});
|
||||
|
||||
test('when a raw ASIDE_DIR= line does leak earlier, the LAST one (the script\'s own, printed after the steps) wins', () => {
|
||||
const r = render(`${artifacts}; echo "ASIDE_DIR=/attacker"; echo "EVAL 1 ${b64('Doc')}"; echo "ASIDE_DIR=${session}"; echo "${RENDER_SENTINEL}"`);
|
||||
test('when a raw ARTIFACT line does leak earlier, the LAST one per step (the script\'s own) wins', () => {
|
||||
const r = render(`echo "ARTIFACT 0 ${b64('forged')}"; ${artifacts}; echo "EVAL 1 ${b64('Doc')}"; echo "${RENDER_SENTINEL}"`);
|
||||
expectOk(r);
|
||||
expect(fs.readFileSync(pdfOut, 'utf8')).toBe('%PDF-1.4 fake-aside-artifact');
|
||||
});
|
||||
|
||||
@@ -67,7 +67,7 @@ describe('the build-loop section (T7, T8, T17, T18, T29, T37)', () => {
|
||||
expect(b).not.toMatch(/\$(_DB|RUN|SLUG|GSTACK_STATE_ROOT)\b/);
|
||||
expect(b).toContain('{{BIN_DIR}}/gstack-design-build');
|
||||
}
|
||||
expect(SECTION).toContain("Save it where the driver can write (Aside's\n session directory; /tmp for $B), then cp it to the `SHOT:` path.");
|
||||
expect(SECTION).toContain("Aside: `gstack-aside-repl --out` the\n `SHOT:` path's folder (rule 8); $B: /tmp, then cp it to the `SHOT:` path.");
|
||||
});
|
||||
|
||||
test('the seven items are single-sourced in this section', () => {
|
||||
|
||||
@@ -1180,7 +1180,7 @@ describe('coverage: scan edges', () => {
|
||||
|
||||
test.skipIf(!POSIX)('the rendered persist block refuses a dump with a HIGH redaction finding (DOM_DUMP_REDACTION_BLOCKED) and keeps a clean one', () => {
|
||||
const skill = fs.readFileSync(path.join(ROOT, 'design-review', 'SKILL.md'), 'utf-8');
|
||||
const start = skill.indexOf('_D="<ASIDE_DIR or $_TMP>/{page}.dom.html"; _REPORT="<REPORT_DIR from Setup>"');
|
||||
const start = skill.indexOf('_D="<SAVED= or DUMP= path>"; _REPORT="<REPORT_DIR from Setup>"');
|
||||
const end = skill.indexOf('```', start);
|
||||
expect(start).toBeGreaterThan(0);
|
||||
const block = skill.slice(start, end);
|
||||
@@ -1196,7 +1196,7 @@ describe('coverage: scan edges', () => {
|
||||
fs.writeFileSync(clean, '<html><body>hello</body></html>');
|
||||
const runBlock = (file: string, page: string) => {
|
||||
const script = block
|
||||
.replace('_D="<ASIDE_DIR or $_TMP>/{page}.dom.html"; _REPORT="<REPORT_DIR from Setup>"; _RUN="<RUN_ID from Setup>"', `_D="${file}"; _REPORT="${report}"; _RUN="run1"`)
|
||||
.replace('_D="<SAVED= or DUMP= path>"; _REPORT="<REPORT_DIR from Setup>"; _RUN="<RUN_ID from Setup>"', `_D="${file}"; _REPORT="${report}"; _RUN="run1"`)
|
||||
.replaceAll('{page}', page)
|
||||
.replaceAll('$HOME/.claude/skills/gstack/bin', path.join(ROOT, 'bin'))
|
||||
.replaceAll('~/.claude/skills/gstack/bin', path.join(ROOT, 'bin'));
|
||||
|
||||
@@ -128,8 +128,7 @@ export const IDENTIFIER_PLACEHOLDERS: Record<string, IdentifierGrammar> = {
|
||||
'<AMENDMENT_CHECKPOINT>': { grammar: QUOTED, what: 'checkpoint path printed by autoplan', quoted: true },
|
||||
'<prepared-prompt-file>': { grammar: QUOTED, what: 'prompt file path printed by the prepare step', quoted: true },
|
||||
'<run-dir>': { grammar: QUOTED, what: 'run directory printed by an earlier block', quoted: true },
|
||||
'<ASIDE_DIR>': { grammar: QUOTED, what: 'Aside output directory printed by an earlier block', quoted: true },
|
||||
'<ASIDE_DIR or $_TMP>': { grammar: QUOTED, what: 'Aside output directory printed by an earlier block', quoted: true },
|
||||
'<SAVED= or DUMP= path>': { grammar: QUOTED, what: 'dump file path printed by the Aside or fallback dump block', quoted: true },
|
||||
'<REPORT_DIR from Setup>': { grammar: QUOTED, what: 'report directory printed by Setup', quoted: true },
|
||||
'<the FILE path printed above>': { grammar: QUOTED, what: 'file path printed by the previous block', quoted: true },
|
||||
'<install dir from Step 2>': { grammar: QUOTED, what: 'install directory printed by Step 2', quoted: true },
|
||||
|
||||
@@ -95,7 +95,7 @@ describe('compact QA bootstrap preserves native detection', () => {
|
||||
});
|
||||
|
||||
async function runRecipe(marker: string, options: { flow?: boolean; hostname?: string; response?: string } = {}) {
|
||||
const scripts = [...method.matchAll(/aside repl '([\s\S]*?)'\n```/g)].map(match => match[1]);
|
||||
const scripts = [...method.matchAll(/(?:aside repl|gstack-aside-repl --out \S+) '([\s\S]*?)'\n```/g)].map(match => match[1]);
|
||||
const matches = scripts.filter(script => script.includes(marker));
|
||||
expect(matches).toHaveLength(1);
|
||||
let script = matches[0];
|
||||
@@ -123,13 +123,13 @@ async function runRecipe(marker: string, options: { flow?: boolean; hostname?: s
|
||||
listeners.get('error')?.({ message: 'uncaught failure' });
|
||||
listeners.get('unhandledrejection')?.({ reason: { message: 'promise failure' } });
|
||||
},
|
||||
screenshot: async (value: any) => events.push({ name: 'screenshot', value }),
|
||||
screenshot: async (value: any) => { events.push({ name: 'screenshot', value }); return Buffer.from('shot'); },
|
||||
locator: (ref: string) => ({ click: async () => events.push({ name: 'click', value: ref }) }),
|
||||
evaluate: async (fn: Function) => new Function('window', 'document', 'location', `return (${fn.toString()})();`)(window, document, { origin, hostname }),
|
||||
url: () => origin,
|
||||
};
|
||||
const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor;
|
||||
await new AsyncFunction('openTab', 'closeTab', 'snapshot', 'console', 'sleep', 'pwd', 'fetch', 'annotatedScreenshot', 'fs', 'path', 'Buffer', script)(
|
||||
await new AsyncFunction('openTab', 'closeTab', 'snapshot', 'console', 'sleep', 'pwd', 'fetch', 'annotatedScreenshot', 'fs', 'path', 'Buffer', 'saveArtifact', script)(
|
||||
async (url: string) => { events.push({ name: 'open', value: url }); return pg; },
|
||||
async (page: unknown) => { expect(page).toBe(pg); events.push({ name: 'close' }); },
|
||||
async (_page: unknown, value: unknown) => { events.push({ name: 'snapshot', value }); return { tree: '[ref=e12] Save', diff: 'Saved' }; },
|
||||
@@ -140,6 +140,7 @@ async function runRecipe(marker: string, options: { flow?: boolean; hostname?: s
|
||||
async () => ({ base64Image: Buffer.from('image').toString('base64') }),
|
||||
{ writeFile: async (file: string, bytes: Buffer) => events.push({ name: 'writeFile', value: { file, bytes: bytes.toString() } }) },
|
||||
path.posix, Buffer,
|
||||
(name: string, data: Buffer | string) => events.push({ name: 'saveArtifact', value: { name, bytes: data.toString() } }),
|
||||
);
|
||||
expect(events[0].name).toBe('open');
|
||||
expect(events.at(-1)?.name).toBe('close');
|
||||
@@ -245,7 +246,7 @@ describe('compact QA browser recipes retain native operations', () => {
|
||||
expectTokens(verify, ['`flow = true`'], 'verify');
|
||||
for (const contract of ['original reproduction', '`flow = false`', 'Keep the error hook',
|
||||
'`GSTACK_STEP_OK` check', 'fresh screenshot names', 'add a suffix if it exists',
|
||||
'Read the copied screenshot', 'Functional repairs never load this section']) expect(verify).toContain(contract);
|
||||
'Read each `SAVED=` screenshot', 'Functional repairs never load this section']) expect(verify).toContain(contract);
|
||||
expect(verify).not.toContain('const HOOK =');
|
||||
expect(verify).not.toContain('Phase 5 Drive-a-flow');
|
||||
const orient = method.slice(method.indexOf('### Phase 3: Orient'), method.indexOf('### Phase 4: Explore'));
|
||||
@@ -275,11 +276,13 @@ describe('compact QA browser recipes retain native operations', () => {
|
||||
expect(names.indexOf('Page.addScriptToEvaluateOnNewDocument')).toBeLessThan(names.indexOf('goto'));
|
||||
const screenshots = events.filter(event => event.name === 'screenshot').map(event => event.value);
|
||||
expect(screenshots).toEqual(flow ? [
|
||||
{ path: 'issue-001-step-1.jpg', type: 'jpeg', quality: 60, fullPage: false },
|
||||
{ path: 'issue-001-result.jpg', type: 'jpeg', quality: 60 },
|
||||
] : [{ path: 'initial.jpg', type: 'jpeg', quality: 60, fullPage: true }]);
|
||||
{ type: 'jpeg', quality: 60, fullPage: false },
|
||||
{ type: 'jpeg', quality: 60 },
|
||||
] : [{ type: 'jpeg', quality: 60, fullPage: true }]);
|
||||
expect(events.filter(event => event.name === 'saveArtifact').map(event => event.value)).toEqual(
|
||||
(flow ? ['issue-001-step-1.jpg', 'issue-001-result.jpg'] : ['initial.jpg']).map(name => ({ name, bytes: 'shot' })));
|
||||
expect(output).toContain('CONSOLE_ERRORS=["load failure","uncaught: uncaught failure","unhandledrejection: promise failure"]');
|
||||
expect(output).toContain('ASIDE_DIR=/owned-session');
|
||||
expect(output.join('\n')).not.toContain('ASIDE_DIR');
|
||||
expect(output).toContain('Page text');
|
||||
expect(names.filter(name => name === 'click')).toHaveLength(flow ? 1 : 0);
|
||||
if (flow) {
|
||||
@@ -306,13 +309,15 @@ describe('compact QA browser recipes retain native operations', () => {
|
||||
const { events, output } = await runRecipe('Emulation.setDeviceMetricsOverride');
|
||||
expect(events).toContainEqual({ name: 'Emulation.setDeviceMetricsOverride', value: { width: 375, height: 812, deviceScaleFactor: 2, mobile: true } });
|
||||
expect(events).toContainEqual({ name: 'Emulation.clearDeviceMetricsOverride', value: {} });
|
||||
expect(output).toContain('ASIDE_DIR=/owned-session');
|
||||
expect(events).toContainEqual({ name: 'saveArtifact', value: { name: 'page-mobile.jpg', bytes: 'shot' } });
|
||||
expect(output.join('\n')).not.toContain('ASIDE_DIR');
|
||||
});
|
||||
|
||||
test('annotated evidence is written inside the Aside session', async () => {
|
||||
test('annotated evidence leaves through saveArtifact, never the deleted session dir (#4784)', async () => {
|
||||
const { events, output } = await runRecipe('annotatedScreenshot(pg)');
|
||||
expect(events).toContainEqual({ name: 'writeFile', value: { file: '/owned-session/issue-002.png', bytes: 'image' } });
|
||||
expect(output).toContain('ASIDE_DIR=/owned-session');
|
||||
expect(events).toContainEqual({ name: 'saveArtifact', value: { name: 'issue-002.png', bytes: 'image' } });
|
||||
expect(events.some(event => event.name === 'writeFile')).toBe(false);
|
||||
expect(output.join('\n')).not.toContain('ASIDE_DIR');
|
||||
});
|
||||
|
||||
test('session API requests retain status and bounded body evidence', async () => {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
* localhost fixture page, and check that the agent actually drove Aside the way
|
||||
* the {{ASIDE_SETUP}} contract (scripts/resolvers/aside.ts) says to: `aside repl`
|
||||
* scripts that print labelled evidence and the GSTACK_STEP_OK sentinel, and
|
||||
* artifacts copied out of the printed ASIDE_DIR. "Actually drove" means the
|
||||
* artifacts saved through bin/gstack-aside-repl (#4784). "Actually drove" means the
|
||||
* sentinel appeared on its own line in a BASH tool_result — the skill doc the
|
||||
* agent Reads also contains the token, so Read results are excluded and the
|
||||
* tokens are line-anchored (Read output is line-numbered; the cookbook wraps
|
||||
@@ -150,7 +150,7 @@ const filesIn = (dir: string): string[] => (fs.existsSync(dir) ? fs.readdirSync(
|
||||
/** Common preface: the fixture server is up, Aside is up, drive it through the skill's own cookbook. */
|
||||
const preface = (skillMd: string) => `Aside is installed and running on this machine; its BROWSER SETUP probe will print READY.
|
||||
Read ${skillMd} and follow its BROWSER SETUP and cookbook exactly. Skip the preamble bash block, lake intro, telemetry, and contributor-mode sections — go straight to the workflow.
|
||||
Drive the browser ONLY with 'aside repl' scripts, each ending with console.log("GSTACK_STEP_OK"); copy any screenshot out of the printed ASIDE_DIR in bash.
|
||||
Drive the browser ONLY with 'aside repl' scripts, each ending with console.log("GSTACK_STEP_OK"); run any script that saves a screenshot through gstack-aside-repl --out <dir> with saveArtifact, as the skill says.
|
||||
Do not use AskUserQuestion. The target is a local test server that is already running — do not start servers or discover ports.
|
||||
`;
|
||||
|
||||
@@ -187,8 +187,7 @@ Your final message must quote the page title verbatim.`,
|
||||
timeout: CAPTURE_MS,
|
||||
prompt: (dir, url) => `${preface('browse/SKILL.md')}
|
||||
Drive this flow in ONE script, shaped like the cookbook's "Drive a flow" recipe:
|
||||
open ${url}/forms.html, take a baseline interactive snapshot, fill #name with "Aside QA", select "user" in #role, click #profile-btn, wait for #result to be visible, then print the DIFF_START/DIFF_END block, the URL= line and the CONSOLE_ERRORS= line, save a screenshot named "flow-result.jpg", print ASIDE_DIR=, close the tab, print the sentinel.
|
||||
Then, in bash, mkdir -p ${dir}/screenshots and copy flow-result.jpg from the printed ASIDE_DIR into ${dir}/screenshots/.
|
||||
open ${url}/forms.html, take a baseline interactive snapshot, fill #name with "Aside QA", select "user" in #role, click #profile-btn, wait for #result to be visible, then print the DIFF_START/DIFF_END block, the URL= line and the CONSOLE_ERRORS= line, save a screenshot named "flow-result.jpg" with saveArtifact, close the tab, print the sentinel. Run that script through gstack-aside-repl --out ${dir}/screenshots.
|
||||
Your final message must include the DIFF and CONSOLE_ERRORS lines verbatim.`,
|
||||
check: (dir, result) => {
|
||||
expect(result.exitReason).toBe('success');
|
||||
|
||||
Reference in new issue
Block a user