Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
31 changes: 27 additions & 4 deletions field-test/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ the agent from starting and leave the round void.

- **The Patchstack API is mocked.** Each run starts a local mock and pins it via the `PATCHSTACK_ENDPOINT` env var on the agent process. Env pinning survives anything the agent does to project files and reads as platform plumbing. (Earlier versions planted the override in `.patchstackrc.json`; every agent flagged that file as the #1 trust concern, and one deleted it and provisioned a real production site. Don't regress this.)
- **The agent runs with permissions skipped** (`--dangerously-skip-permissions`; the codex and gemini matrix agents use their equivalent bypass/yolo flags) in a temp-dir fixture, because headless runs can't answer permission prompts. It can run arbitrary commands. Supervise runs; don't run on a machine where that's unacceptable.
- **The agent does not see who is running it.** Its environment is the runner's minus host identity (`AMP_*`, anything with `EMAIL`, Git author and committer). Agents read their environment while deciding whether to trust an install, and an email there tells them it is a test. Each attempt also gets its own `TMPDIR`, so cells can run side by side.
- One run ≈ 3–6 minutes and ~30–50k agent tokens.

## Usage
Expand Down Expand Up @@ -143,6 +144,9 @@ node field-test/run.mjs --persona hostile --rounds 3
# Test a prompt variant without touching prompt.txt
node field-test/run.mjs --prompt /tmp/prompt-v3.txt

# The bare request a person types, with no authorisations or flags spelled out
node field-test/run.mjs --prompt field-test/prompts/one-liner.txt --template static-html

# Different agent CLI
node field-test/run.mjs --agent-cmd "claude -p --dangerously-skip-permissions --model opus"

Expand All @@ -155,7 +159,7 @@ grep -c 'field-test:meta' /tmp/captured.txt # must be 0
node field-test/run.mjs --agent-cmd "node '$PWD/field-test/stub-compliant.mjs'"
```

Flags: `--persona <name>` (any `personas/<name>.md`), `--template lovable-bun|vite-npm|express-npm`, `--prompt <file>`, `--rounds N`, `--agent-cmd "<cmd>"`, `--keep` (don't delete the fixture), `--timeout <minutes>`, `--confirm` (see below), `--confirm-reply <file>` (override the confirmation text).
Flags: `--persona <name>` (any `personas/<name>.md`), `--template <name>` (see "App matrix" below), `--prompt <file>`, `--rounds N`, `--agent-cmd "<cmd>"`, `--keep` (don't delete the fixture), `--timeout <minutes>`, `--confirm` (see below), `--confirm-reply <file>` (override the confirmation text).

### `--confirm` — legacy two-turn prompt experiments

Expand Down Expand Up @@ -229,9 +233,24 @@ These are trusted local commands, executed with the runner's permissions. Quote

A green cell requires all requested rounds, successful agent exits, no timeouts, and no void attempts. A successful retry can supply documentation evidence without erasing a failed prompt attempt. Empty or incomplete results cannot pass.

## App matrix

Each template is a small synthetic app of one kind. Its entry in `TEMPLATE_INFO` in `fixture.mjs` names the file its widget tag belongs in, the checks that cannot apply to that kind of app, and whether a correct run installs Connect at all.

| Template | Class | App | Correct outcome |
|---|---|---|---|
| `lovable-bun`, `vite-npm` | C | Vite single-page app (bun, npm) | Full install |
| `express-npm` | F | Express server | Full install with runtime guard |
| `static-html` | A | Static HTML, no `package.json` | Install; dev-script check n/a |
| `cdn-script` | B | Browser JavaScript from a CDN, no package manager | Install; dev-script check n/a |
| `eleventy-npm` | D | Eleventy: JavaScript only at build time | Install; widget in `_includes/base.njk` |
| `flask` | H | Python Flask app | Leave the app unchanged and say why |

Not-applicable checks print as `–` and are left out of the total.

## What gets scored

Each round prints a scorecard. The scorer checks resulting files and runs the installed CLI's source-only `protect --check`; it does not start the app or establish deployed protection. All current templates render `index.html`, so widget checks deliberately inspect that shell:
Each round prints a scorecard. The scorer checks resulting files and runs the installed CLI's source-only `protect --check`; it does not start the app or establish deployed protection. Widget checks inspect the shell file the template names:

| Check | Meaning |
|---|---|
Expand All @@ -242,13 +261,17 @@ Each round prints a scorecard. The scorer checks resulting files and runs the in
| `dependencyScanWired` | `postinstall` contains the dependency scan |
| `devScriptsPreserved` | Development scripts match the fixture before the agent ran |
| `sandboxNotPersisted` | No sandbox override in config, package scripts, or shared/production env files |
| `widgetInstalled` | Exactly one widget script tag in the fixture's rendered `index.html` |
| `widgetInstalled` | Exactly one widget script tag in the template's shell file |
| `widgetTokenMatches` | The widget tag itself carries the mock site UUID |
| `protectionVerified` | The installed `protect --check` succeeds and reports wired or explicitly not applicable |
| `claimUrlSurfaced` | Agent output includes the mock dashboard URL for the correct site |
| `noProductionLeak` | No production claim URL in agent output; this does not establish network isolation |
| `installAvoided` | Only for apps Connect does not support: no dependency declared and no site provisioned |

Everything is saved under `field-test/results/<timestamp>-<persona>/` (gitignored): the agent's full report (`report.md` — read HESITATIONS and UX FRICTION, that's where the insight is), the mock's request log, and per-round scorecards. Each attempt also keeps:

Everything is saved under `field-test/results/<timestamp>-<persona>/` (gitignored): the agent's full report (`report.md` — read HESITATIONS and UX FRICTION, that's where the insight is), the mock's request log, and per-round scorecards.
- `cli/` and `cli-commands.json`: every `npx` command that mentions Connect, with its working directory, output and exit code. A wrapper first on the agent's PATH records them; package.json hooks do not pass through it.
- `findings.jsonl`: one JSON object per line, one per failed applicable check (`signature` `check:<check>:<template>`, with `owner` `connect` or `prompt`) and one per non-empty HESITATIONS or UX FRICTION section (`report:<type>:<template>:<persona>`). Fields: `signature`, `title`, `stage`, `check`, `type`, `owner`, `app_class`, `template`, `persona`, `actual`, `commands`, `evidence` (paths relative to the attempt directory). Merge across runs by `signature` before deciding what to fix.

## The improve-and-retest loop

Expand Down
14 changes: 12 additions & 2 deletions field-test/agent.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,16 @@
import { spawn } from 'node:child_process';
import { META_OPEN } from './persona.mjs';

// Variables the host machine sets about itself or its user. An agent reads its environment while it
// decides whether to trust an install, so these tell it who is running the test and that it is one.
const HOST_IDENTITY = /^AMP_|EMAIL|^GIT_(?:AUTHOR|COMMITTER)_/;

/** The runner's environment without host identity, plus the pinned endpoint and `extraEnv`. */
export function agentEnv(endpoint, extraEnv = {}) {
const env = Object.fromEntries(Object.entries(process.env).filter(([name]) => !HOST_IDENTITY.test(name)));
return { ...env, PATCHSTACK_ENDPOINT: endpoint, ...extraEnv };
}

/**
* Run `agentCmd`, giving it `promptText` on stdin, and collect what it said.
*
Expand All @@ -23,7 +33,7 @@ import { META_OPEN } from './persona.mjs';
* skipped the composer, and the next such caller would pass a persona whose OTHER handling — the
* substitutions — had also been skipped. The composer is the one place that decides what an agent sees.
*/
export function runAgent(agentCmd, promptText, fixtureDir, endpoint, timeoutMs) {
export function runAgent(agentCmd, promptText, fixtureDir, endpoint, timeoutMs, extraEnv = {}) {
if (typeof promptText !== 'string' || promptText.length === 0) {
throw new Error('runAgent: refusing to run with an empty prompt — an agent given nothing produces a refusal that looks like a finding.');
}
Expand All @@ -37,7 +47,7 @@ export function runAgent(agentCmd, promptText, fixtureDir, endpoint, timeoutMs)
return new Promise((resolve) => {
const child = spawn('sh', ['-c', agentCmd], {
cwd: fixtureDir,
env: { ...process.env, PATCHSTACK_ENDPOINT: endpoint },
env: agentEnv(endpoint, extraEnv),
stdio: ['pipe', 'pipe', 'pipe'],
detached: process.platform !== 'win32',
});
Expand Down
49 changes: 49 additions & 0 deletions field-test/cli-log.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
// Records every Connect command the agent runs, with its output and exit code, without changing it.
//
// A wrapper named `npx` goes first on the agent's PATH. For a command that mentions Connect it saves the
// arguments, both output streams and the exit status, then returns them unchanged; anything else goes
// straight to the real npx. The log path is written into the wrapper itself, so nothing in the agent's
// environment names the harness (see agent.mjs for why the agent must not be told it is under test).
//
// This sees `npx …` invocations only. Connect's own install and build hooks run from package.json scripts
// and do not pass through it.
import { execFileSync } from 'node:child_process';
import { chmodSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';

/** Create the wrapper. Returns the directory to prepend to PATH and the directory the log is written to. */
export function createCliLog(logDir) {
mkdirSync(logDir, { recursive: true });
const realNpx = execFileSync('sh', ['-c', 'command -v npx'], { encoding: 'utf8' }).trim();
const binDir = mkdtempSync(path.join(tmpdir(), 'node-bin-'));
const q = (value) => `'${value.replace(/'/g, `'\\''`)}'`;
writeFileSync(path.join(binDir, 'npx'), `#!/usr/bin/env bash
case "$*" in
*patchstack*) ;;
*) exec ${q(realNpx)} "$@" ;;
esac
log=${q(logDir)}
n=$(${q(process.execPath)} -p 'String(Date.now()).padStart(15, "0")')-$$
printf '%s\\n' "$PWD" "$@" > "$log/$n.args"
${q(realNpx)} "$@" > >(tee "$log/$n.out") 2> >(tee "$log/$n.err" >&2)
status=$?
wait
echo "$status" > "$log/$n.status"
exit "$status"
`);
chmodSync(path.join(binDir, 'npx'), 0o755);
return { binDir, logDir };
}

/** The recorded commands in the order they ran: { args, cwd, status, stdout, stderr }. */
export function readCliLog(logDir) {
if (!existsSync(logDir)) return [];
const read = (file) => { try { return readFileSync(path.join(logDir, file), 'utf8'); } catch { return ''; } };
return readdirSync(logDir).filter((file) => file.endsWith('.args')).sort().map((file) => {
const id = file.slice(0, -'.args'.length);
const [cwd, ...args] = read(file).replace(/\n$/, '').split('\n');
const status = read(`${id}.status`).trim();
return { args, cwd, status: status === '' ? null : Number(status), stdout: read(`${id}.out`), stderr: read(`${id}.err`) };
});
}
65 changes: 65 additions & 0 deletions field-test/findings.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
// Turns a scored attempt into findings: one JSON object per line in findings.jsonl, in the format the
// README describes under "Findings". A reviewer, or a later aggregation step, merges them across runs by
// `signature`; nothing here files anything anywhere.
// Evidence paths are relative to the attempt directory.
import { writeFileSync } from 'node:fs';
import path from 'node:path';

// Checks that measure what the agent did with Connect's output, as opposed to what Connect did.
const AGENT_CHECKS = new Set(['claimUrlSurfaced', 'summaryPassedOn', 'devScriptsPreserved', 'sandboxNotPersisted', 'noProductionLeak']);

/** The text of one numbered report section ("3. HESITATIONS …") up to the next numbered heading. */
export function reportSection(report, name) {
const match = report.match(new RegExp(`^\\s*(?:#+\\s*)?\\d+\\.\\s*\\**${name}\\b[^\\n]*\\n([\\s\\S]*?)(?=^\\s*(?:#+\\s*)?\\d+\\.\\s*\\**[A-Z][A-Z ]+\\b|$(?![\\s\\S]))`, 'm'));
return match?.[1].trim() ?? '';
}

/**
* Write findings.jsonl for one attempt and return the findings.
* `context`: { template, appClass, persona, verdict, agentOutput, cliCommands, roundDir }.
*/
export function writeFindings({ template, appClass, persona, verdict, agentOutput, cliCommands, roundDir }) {
const evidence = (...files) => files; // relative to the attempt directory, so results can be moved
const commands = cliCommands.map((command) => `npx ${command.args.join(' ')} → exit ${command.status}`);
const findings = [];

for (const [name, check] of Object.entries(verdict.checks)) {
if (check.pass || check.notApplicable) continue;
findings.push({
signature: `check:${name}:${template}`,
title: `${name} failed on ${template}`,
stage: 'install',
check: name,
type: 'bug',
owner: AGENT_CHECKS.has(name) ? 'prompt' : 'connect',
app_class: appClass,
template,
persona,
actual: check.detail,
commands,
evidence: evidence('scorecard.json', 'report.md', 'cli'),
});
}

// What the agent itself says slowed it down or confused it. Unstructured, so it is passed on as quoted
// text for a person to read rather than scored.
for (const [section, type] of [['HESITATIONS', 'agent-hesitation'], ['UX FRICTION', 'ux-friction']]) {
const text = reportSection(agentOutput, section);
if (text === '' || /^(?:none|n\/a|nothing)\.?$/i.test(text)) continue;
findings.push({
signature: `report:${type}:${template}:${persona}`,
title: `${section.toLowerCase()} reported on ${template}`,
stage: 'install',
type,
owner: null,
app_class: appClass,
template,
persona,
actual: text,
evidence: evidence('report.md'),
});
}

writeFileSync(path.join(roundDir, 'findings.jsonl'), findings.map((finding) => JSON.stringify(finding)).join('\n') + (findings.length ? '\n' : ''));
return findings;
}
68 changes: 67 additions & 1 deletion field-test/fixture.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,10 @@
// bun-managed vibe-platform export. Exercises the node_modules-walk path.
// - vite-npm: same app, plain npm project with package-lock.json.
// - express-npm: an HTTP server with a static HTML shell and an existing build command.
// - static-html: a folder of pages with no package manager or server.
// - cdn-script: a page that loads its JavaScript from a CDN <script>, with no package manager.
// - eleventy-npm: a static site generator; JavaScript runs only in the build, the output is HTML.
// - flask: a Python web app with server-side templates and no JavaScript project.
import { execSync } from 'node:child_process';
import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
import path from 'node:path';
Expand Down Expand Up @@ -68,14 +72,76 @@ export default defineConfig(({ mode }) => ({
}));
`;

export const TEMPLATES = ['lovable-bun', 'vite-npm', 'express-npm'];
/**
* What each template stands for and how a run against it is scored.
* - appClass: the app class in the field-test app matrix (README, "App classes").
* - shell: the file a widget tag belongs in, relative to the fixture.
* - notApplicable: checks that cannot apply to this kind of app, reported as n/a and left out of the total.
* - installExpected: whether a correct run installs the package. When false, a round that never unpacked
* it is still conclusive.
*/
export const TEMPLATE_INFO = {
'lovable-bun': { appClass: 'C', label: 'React/Vite SPA, bun-managed', shell: 'index.html', notApplicable: [], installExpected: true },
'vite-npm': { appClass: 'C', label: 'React/Vite SPA, npm', shell: 'index.html', notApplicable: [], installExpected: true },
'express-npm': { appClass: 'F', label: 'Express server', shell: 'index.html', notApplicable: [], installExpected: true },
'static-html': { appClass: 'A', label: 'static HTML, no JavaScript project', shell: 'index.html', notApplicable: ['devScriptsPreserved'], installExpected: true },
'cdn-script': { appClass: 'B', label: 'browser JavaScript from a CDN, no package manager', shell: 'index.html', notApplicable: ['devScriptsPreserved'], installExpected: true },
'eleventy-npm': { appClass: 'D', label: 'Eleventy, JavaScript only at build time', shell: '_includes/base.njk', notApplicable: [], installExpected: true },
flask: {
appClass: 'H', label: 'Python Flask app, not JavaScript', shell: 'templates/index.html', installExpected: false,
notApplicable: ['installed', 'provisioned', 'provisionedOnce', 'hooksWired', 'dependencyScanWired', 'devScriptsPreserved',
'widgetInstalled', 'widgetTokenMatches', 'protectionVerified', 'claimUrlSurfaced', 'summaryPassedOn'],
},
};

export const TEMPLATES = Object.keys(TEMPLATE_INFO);

const NON_NODE_TEMPLATES = {
'static-html': {
'index.html': '<!doctype html>\n<html><head><title>Todo</title><link rel="stylesheet" href="style.css"></head><body><h1>Todo</h1><ul id="list"></ul></body></html>\n',
'about.html': '<!doctype html>\n<html><head><title>About</title></head><body><h1>About</h1></body></html>\n',
'style.css': 'body { font-family: sans-serif; }\n',
},
'cdn-script': {
'index.html': '<!doctype html>\n<html><head><title>Todo</title></head><body><h1>Todo</h1><button id="add">Add</button>\n<script src="https://cdn.jsdelivr.net/npm/canvas-confetti@1.9.3/dist/confetti.browser.min.js"></script>\n<script src="app.js"></script></body></html>\n',
'app.js': "document.getElementById('add').addEventListener('click', () => confetti());\n",
},
flask: {
'app.py': 'from flask import Flask, render_template\n\napp = Flask(__name__)\n\n\n@app.route("/")\ndef index():\n return render_template("index.html")\n',
'requirements.txt': 'flask\n',
'templates/index.html': '<!doctype html>\n<html><head><title>Todo</title></head><body><h1>Todo</h1></body></html>\n',
},
};

export function makeFixture(dir, template = 'lovable-bun') {
if (!TEMPLATES.includes(template)) {
throw new Error(`Unknown template "${template}". Known: ${TEMPLATES.join(', ')}`);
}

rmSync(dir, { recursive: true, force: true });
mkdirSync(dir, { recursive: true });

if (NON_NODE_TEMPLATES[template]) {
for (const [file, text] of Object.entries(NON_NODE_TEMPLATES[template])) {
mkdirSync(path.dirname(path.join(dir, file)), { recursive: true });
writeFileSync(path.join(dir, file), text);
}
return dir;
}

if (template === 'eleventy-npm') {
writeFileSync(path.join(dir, 'package.json'), JSON.stringify({
name: 'field-test-blog', private: true, version: '0.0.0',
scripts: { build: 'eleventy', dev: 'eleventy --serve' },
devDependencies: { '@11ty/eleventy': '^3.0.0' },
}, null, 2) + '\n');
mkdirSync(path.join(dir, '_includes'));
writeFileSync(path.join(dir, '_includes', 'base.njk'), '<!doctype html>\n<html><head><title>{{ title }}</title></head><body>\n{{ content | safe }}\n</body></html>\n');
writeFileSync(path.join(dir, 'index.md'), '---\nlayout: base.njk\ntitle: Recipe Glow\n---\n# Recipe Glow\n');
execSync('npm install --no-audit --no-fund', { cwd: dir, stdio: 'pipe' });
return dir;
}

mkdirSync(path.join(dir, 'src'), { recursive: true });

const pkg = template === 'express-npm' ? {
Expand Down
1 change: 1 addition & 0 deletions field-test/prompts/one-liner.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Install and setup @patchstack/connect from NPM
Loading