Skip to content

feat: cut the turns agents spend looking things up - #1698

Merged
vivek7405 merged 29 commits into
mainfrom
feat/cut-lookup-turns
Nov 12, 2026
Merged

vivek7405 merged 29 commits into
mainfrom
feat/cut-lookup-turns

Conversation

@vivek7405

@vivek7405 vivek7405 commented Nov 11, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #1697

Cuts the tokens an agent spends building on the scaffold, measured: in a 24-build A/B against main (Haiku, Pollster and Roomly, 6 builds per arm per spec) the PR used 9.3% fewer real tokens (71.7M vs 79.1M) and cost 5.7% less ($5.06 vs $5.36), with all 24 apps passing check, typecheck and tests. Pollster's median was +2.0% (neutral), Roomly's −11.1%. With 12 builds per arm that is a consistent direction rather than proof.

What changed

  • npx webjs verify: whether the app works, in one call. webjs check and webjs typecheck in parallel, then webjs test, then the app's webjs.dev.before steps and an in-process boot that requests every route (webjs status --boot). One line per passing step, the output tail (no stack frames) for a failing one. It runs on the webjs ci engine. The brief tells agents to verify with it. In round 11 all 12 PR builds used it, and Playwright calls fell 59% and curl calls 23%.
  • A minimal scaffold. No UI kit code pre-installed (the first webjs ui add installs cn()), no theme toggle (dark mode follows the OS), no instrumentation.ts, and no example module: modules/ ships empty and the scaffold AGENTS.md lays out a module (actions/, queries/, components/, utils/, types.ts, test/<feature>/) and names the modules, testing and progressive-enhancement guides. All 12 PR builds looked those guides up and followed the layout (25 features, utils/ in 19, no page importing the db). The api template keeps its users endpoints, named in its AGENTS.md as an example to replace.
  • Catalogue facts in npx webjs source: the test database, how webjs db seed runs, the page-cache default, what a route handler receives.
  • Fixes:
    • notFound() / forbidden() / unauthorized() in an action over RPC answer 404 / 403 / 401 (were a logged 500) and reject with the sentinel on the client. As on the no-JS form path they evict none of the action's declared invalidates tags (a guard throw must not let any caller flush caches), and a revalidatePath() the action called first is still reported.
    • In development, a page POST missing __webjs_action gets a 405 naming the field and submitForm() (production answers the bare status).
    • submitForm refuses a lone field-less bound form (a layout's logout) when the test submits fields.
    • webjs test gives each test file its own copy of the test database on Node.
    • The kit helpers with a shadcn alias take className.
  • Eval harness: each arm runs its own CLI through npx (it ran the primary checkout's), free ports and short temp dirs, usage counted once per message, and a prompt that asks for an app that boots and serves its routes without prescribing a dev server and curl (a baseline reset: rounds before 11 are not comparable).

Tests

Unit, integration and Bun for each fix, each with a counterfactual; test/cli/verify.test.mjs drives verify on an injected spawn; scaffold tests hold the first read and the module layout; a fresh app passes npx webjs verify. The one local failure, scaffold-db-types, is this machine's stale drizzle-orm (rc.3 against the lock's rc.5); CI installs from the lock.

https://claude.ai/code/session_01JGkZj4c2xDipMrPZkR4oHV

A forbidden(), notFound() or unauthorized() thrown in a server action
called from a component answered a logged 500, while the no-JS form
path rendered the right 403, 404 or 401. An agent building on the
scaffold spent six turns reading actions.js to find out why. RPC now
answers the same status with the kind in x-webjs-control, never hands
it to onError, and the stub and invokeActionForTest rethrow the
sentinel so isForbidden(err) holds in the caller.

Refs #1697
@vivek7405 vivek7405 self-assigned this Nov 11, 2026
@pilots-run

pilots-run Bot commented Nov 11, 2026 •

Copy link
Copy Markdown

Preview for 8585480 was not built: compose file has unsupported keys

Next: fix the listed keys in the compose file

t added 6 commits November 12, 2026 00:16
Agents verifying a form with curl posted the visible fields alone, got a
bare Method Not Allowed, and read form-dispatch.js to learn why (about
five turns across three of eight eval builds). The body now names the
hidden __webjs_action field and submitForm(), and the troubleshooting
page covers the hand-posted case.

Refs #1697
Every eval build runs a bare `webjs source` first, then grepped
node_modules for facts it did not state: which database `webjs test`
uses (16 turns across five builds), what `webjs db seed` runs, whether
pages are cached by default, and what a route handler receives. The
catalogue now says each in a few words and stays at 1855 characters.

The scaffold's AGENTS.md names the `git rm -r` that removes the example
module and says the removal is already staged, since five of eight
builds ran `git add` on the removed paths and chased the pathspec error.

Refs #1697
An agent's first move on a fresh app is one cat of the source it will
build on. In six of eight eval builds that read was 43 to 60 KB, over
the 50 KB tool-output limit, so the agent re-read file by file and the
text sat in context for the rest of the run. lib/utils/cn.ts was 24.7 KB,
15 KB of it commentary on the class merger that packages/ui/AGENTS.md
already carries; it is now 12 KB with the code byte for byte the same.
The layout's comments shrink too, and the read set goes from 58 KB to
43 KB, held under 45 KB by a scaffold test.

The layout's content wrapper is a div and the home page renders its own
main, as a create-next-app page does, since agents wrote a main inside
the layout's.

Refs #1697
Auth.js v5 types the redirecting form of signIn and signOut as
Promise<never>, since inside a request it throws the redirect. WebJs
typed it Promise<Response>, so `return signIn('credentials', formData)`
in an action typed Promise<ActionResult>, the way the scaffold types
every action, failed with TS2322 and an eval build spent a round widening
the type. The agent-habits fixture now types that action as the scaffold
does.

Refs #1697
shadcn's cva exports (buttonVariants and the rest) take a className, and
the kit mirrors each under shadcn's name. An eval agent wrote the habit
under the kit's own name, buttonClass({ variant: 'link', className }),
and spent a typecheck round switching to buttonVariants. The 17 helpers
with a shadcn alias now take className themselves, merged through cn()
only when given, so every existing call returns the same string. Each
alias is now the helper itself.

Refs #1697
About 22 turns across seven of the round 7 and 8 builds went to the
harness, not to WebJs or the agent. Arms started as separate runs used
the same fixed port base, so dev servers met on one port and an agent
wrote into another build's database; and the per-build TMPDIR inside the
build directory was long enough that Playwright's socket under it passed
the 108-byte Unix limit, so the browser never launched. Each build now
asks the OS for a port (--port-base still pins them) and gets a short
mkdtemp under /tmp, linked from <build>/tmp. Without this, single-build
before and after numbers are too noisy to compare.

Refs #1697
@vivek7405
vivek7405 marked this pull request as ready for review November 11, 2026 18:59
t added 9 commits November 12, 2026 00:54
The eval harness linked node_modules/.bin into each app whole. npm writes
each bin as a relative link, so when the framework checkout is a linked
worktree whose .bin is a link into the primary checkout, every eval
app's `npx webjs` ran the PRIMARY's CLI rather than the framework under
test: an A/B arm measuring a CLI change measured nothing. The harness
now links .bin entry by entry and keeps a framework bin's relative
target, which lands on the app's own link to that package.

Refs #1697
Round 9 of the eval showed the first read of a fresh app still past
the tool-output limit, which is about 30K characters rather than 50 KB:
agents cat 26 to 58K in one call and re-read file by file. Most of it was
library code no agent needed to read: the kit's cn() and dom helpers, the
Button, Input and Label, and the theme toggle built on them.

The scaffold now writes the kit's config and theme only. The first
`webjs ui add` installs cn() as a registry dependency, as before for any
app that ran `webjs ui init`. Dark mode follows the OS from a few lines
in the layout, the home page's example form uses plain Tailwind on the
kit's tokens, and the optional instrumentation.ts hook is gone (an app
adds one when it wants an APM sink). The first-read set goes from 43 KB
to 16 KB, held under 20 KB by a scaffold test. The example module stays,
since it is the one worked copy of a bound form, actionData, a query and
a test against the test database.

Refs #1697
The catalogue named the file `webjs db seed` runs but not how, and a
round 9 build still grepped the CLI to learn whether its top-level code
would run. It runs once, as a plain script, so the line now says that and
that the script should be safe to re-run.

Refs #1697
A round 9 eval build tested a cross-user cancel on a page that rendered
no cancel form for that user. The only bound form left was the layout's
logout, submitForm posted it, and the 303 read as the cancel being
refused, so the agent spent turns finding out why. When the only bound
form holds none of the submitted fields, submitForm now refuses, names
that form and says the one the test means is not rendered for this
request. A field-less submit still posts a field-less form, and
{ match } posts it on purpose.

Refs #1697
On Node, `node --test` runs each test file in a process of its own, and
`webjs test` pointed them all at one migrated SQLite file. Two files
writing at once failed with `database is locked` (a transaction that
upgrades from read to write gets SQLITE_BUSY at once, whatever the busy
timeout), which cost two round 9 eval builds turns re-running flaky
tests. A preload passed with --import now copies the migrated template
for each test file and points DATABASE_URL at the copy, the
database-per-worker shape of Rails' parallel tests. Bun's runner keeps
every file in one process and is unchanged.

Refs #1697
stream-json writes one event per content block of an API message
(thinking, text, tool_use), each carrying the message's full usage, and
the harness summed usage per event. Input came out 2.2 to 2.9 times the
real figure and partly measured how much an agent narrated: round 9
read 72.1M against 76.6M where the real totals are 26.9M and 28.4M.
Usage is now counted once per message id, and the run's cost from the
result event is recorded and printed beside it.

Refs #1697
The scaffold no longer ships a theme toggle or stores a theme choice
(dark mode follows the OS), so its generator has no storage key for
the repo-health check to match. The gallery, the blog and the website
still share one key.

Refs #1697
`webjs verify` answers whether the app works in one call: check,
typecheck and the tests, then the app's dev before-steps (migrations,
the stylesheet) and an in-process boot that requests every route needing
no parameter. Every step runs after a failure too, a pass is one line and
a failure the tail of its output. In the round 10 eval about 19 turns per
build came after the app first booted, most of them starting a dev
server, curling routes and stopping it, and those late turns sit past
the 100K-token price tier. The brief now names verify in place of
`webjs status` after every edit.

The scaffold's modules/users example is gone, with its test and the home
page form that used it: modules/ ships as a placeholder, AGENTS.md lays
out a module (actions, queries, components, utils, types and its tests)
and points at the source guides that show it worked, and the modules
guide gains utils/. The api template keeps its users endpoints, which are
what that template is.

Refs #1697
The build prompt told every agent to boot a dev server, exercise the
routes with curl and stop it, a loop no real user asks for, and it
decided how verification is done before the framework could offer a
better way. It now asks for an app that boots and serves its routes and
leaves no server running, and says how is up to the agent. Both arms of
an A/B get the same prompt, so this resets the baseline: rounds before
this one are not comparable with rounds after it.

Refs #1697

@vivek7405 vivek7405 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review at high effort, recall-first. Ten findings, most severe first: a truncated failure tail in webjs verify, a new submitForm refusal that misfires, the dev env leaking into the verify test step, the RPC control-flow branch dropping invalidation the redirect branch keeps, two doc pages left stale by the brief and scaffold changes, the api template's example module losing its delete instruction, then altitude / efficiency / cleanup items (verify duplicating webjs ci, sequential independent steps, the kit className recursion copied 17 times, a hardcoded header string beside its new constant, and first-event usage in the eval metrics).

Comment thread packages/cli/lib/verify.js Outdated
child.stdout.on('data', (d) => { output += d; });
child.stderr.on('data', (d) => { output += d; });
child.on('error', (e) => resolve({ code: 1, output: output + String(e) }));
child.on('exit', (code, signal) => resolve({ code: code ?? (signal ? 1 : 0), output }));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

runCaptured resolves on exit, so a failing step's tail can be cut off. Node documents that stdio streams may still be open when exit fires, so data chunks still in the pipe land after the promise resolved and never reach output. The last lines are exactly what tail() prints for a FAIL step, so a failing webjs test or status --boot can report FAIL test (exit 1) with its summary or failing assertion missing. close fires after the stdio streams have ended (it is what ci-runner.js resolves on).

Suggested change
child.on('exit', (code, signal) => resolve({ code: code ?? (signal ? 1 : 0), output }));
child.on('close', (code, signal) => resolve({ code: code ?? (signal ? 1 : 0), output }));

Comment thread packages/server/src/testing.js Outdated
// means is not on the page (no row to cancel, a section the user cannot
// see), and the one left is the layout's (a logout). Posting it signed the
// user out and passed the assertion that followed (#1697).
if (candidates.length === 1 && opts.index === undefined && !opts.match && wanted.length) {

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The new single-candidate refusal fires on forms it should post, and mislabels unbound ones.

  1. formFieldNames only sees <input|select|textarea|button name=...> textually inside the <form> slice. A form whose controls sit outside it with form="id", a form-associated custom element carrying name on its host, or a field a component adds client-side all read as missing, so a test that posts exactly those fields now throws where it used to submit. So does a test that deliberately posts a field the form does not render (a mass-assignment check posting { role: 'admin' }).
  2. When the page has no bound form, candidates is ALL forms, so one unbound form trips this branch and the error says The only bound form is <form ...>, which is false, and it pre-empts the more useful carries no __webjs_action field ... Write it as <form action=${myAction}> error below.

At minimum gate it on isBound(candidates[0]), and consider counting form="<id>" controls in formFieldNames.

Comment thread packages/cli/bin/webjs.js Outdated
process.exit(1);
}
process.chdir(appDir);
loadAppEnv(appDir);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

loadAppEnv here leaks the development env into the webjs test step. With NODE_ENV unset this loads .env.development.local / .env.local / .env.development / .env into process.env, and envWithLocalBin copies that into every spawned step. webjs test then sets NODE_ENV=test, but the app's own env load is shell-wins, so every key .env.development* set shadows the same key in .env.test (an AUTH_SECRET, a SITE_URL, an API base URL). npx webjs test alone runs with the test values; npx webjs verify runs the same tests with the dev ones. Each child already loads its own env (status --boot calls loadAppEnv, webjs test runs the app's loader under NODE_ENV=test), so pass the steps the shell env (snapshot before loadAppEnv) and load the dev env only for the before-steps.

Comment thread packages/server/src/actions.js Outdated
// notFound() / forbidden() / unauthorized() (Next.js parity with the
// no-JS form path): the same 404 / 403 / 401, not a logged 500.
const cf = controlFlowStatus(e);
if (cf) return controlFlowResponse(e, cf);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The control-flow branch drops the invalidation the redirect branch right above keeps. An action that mutates, calls revalidatePath() / has invalidates, and then throws forbidden() or notFound() (a partial-permission path, a row deleted mid-flight) now returns 403/404 with neither x-webjs-invalidate nor x-webjs-refresh, and revalidateTags(inv) is never run, so the server-side tag cache keeps the stale reads. The redirect branch handles exactly this (if (ranAction && method !== 'GET') { ... revalidateTags ... } plus refreshHeaderValue()). controlFlowResponse could take the same headers the redirect branch builds; the stub already processes x-webjs-invalidate before the control check, so only the server side needs it.

Comment thread packages/mcp/src/brief.js
'After each edit run `npx webjs check` and `npx webjs status`. The framework',
'source is in `node_modules/@webjsdev/*` (no build, so it is the code that',
'runs) and the human docs are at https://webjs.dev/docs.',
'After each edit run `npx webjs check`. To verify the app, run `npx webjs verify`:',

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Two docs-site pages are left stale by this PR's brief and scaffold changes. AGENTS.md (Code workflow 2): "A task is NOT done until EVERY doc surface its change touches is in sync: the docs site ...".

  • website/app/(site)/docs/ai-first/page.ts:26 still says the brief carries "the instruction to run webjs check and webjs status after each edit"; the brief now says webjs check after each edit and webjs verify to verify.
  • website/app/(site)/docs/deployment/page.ts:202 says of instrumentation.ts "The scaffold ships that file with the call in place." This PR deletes packages/cli/templates/instrumentation.ts, so a fresh app has no such file.

(Anchored here because neither page is in the diff.)

and keep routes thin. `modules/users/` is an example of that shape: read it, then
delete it, its test and whatever uses it before you build the app.
Keep app data in the wired-up Drizzle database (`db/`), never in a JSON file or
an in-memory array. One folder per feature under `modules/`, and thin routes in `app/`:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The api template still ships modules/users/, but the shared AGENTS.md no longer tells the agent to delete it. The removed line ("modules/users/ is an example of that shape: read it, then delete it, its test and whatever uses it") was the only instruction to clear it, and create.js (around line 1120) still writes modules/users/{actions,queries,types.ts} plus app/api/users for --template api (with a modules/.gitkeep beside them from line 1400). Both templates ship this one AGENTS.md, so an api app now gets an example module described nowhere. Either drop the example from the api template too, or keep a template-conditional line.

Comment thread packages/cli/lib/verify.js Outdated
delete env.NODE_TEST_CONTEXT;
const cli = (args) => run(execPath, [cliBin, ...args], { cwd: appDir, env });
/** @type {Array<{ title: string, exec: () => Promise<{ code: number, output: string }> }>} */
const steps = [

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Altitude: this is a second, hardcoded CI runner beside webjs ci. webjs ci (lib/ci-runner.js) is already the Rails bin/ci shape, with captured output, per-step result lines, a failure list and parallel groups, driven by webjs.ci.steps. verify re-implements the runner with a fixed step list that ignores the app's own webjs.ci.steps, and the boot step re-implements runBeforeSteps (lib/run-tasks.js) with capture added. Two runners will drift (one resolves on close with a grace, this one on exit; see the line 39 comment). A simpler shape: have the scaffold declare the four steps (webjs check, webjs typecheck, webjs test, webjs status --boot) in webjs.ci.steps, and make verify run runCi over that list (or a default list when the app declares none).

Comment thread packages/cli/lib/verify.js Outdated
delete env.NODE_TEST_CONTEXT;
const cli = (args) => run(execPath, [cliBin, ...args], { cwd: appDir, env });
/** @type {Array<{ title: string, exec: () => Promise<{ code: number, output: string }> }>} */
const steps = [

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Efficiency: check and typecheck run one after the other though neither reads the other's output. typecheck (tsc) is the slow one on a real app, and verify is meant to be the one call an agent waits on at the end of a build. Running check and typecheck together (and the before-steps alongside them, since neither reads the db or the compiled CSS) cuts the wall time by about the shorter step. ci-runner.js already runs a parallel: N group with captured, replayed output, which is another reason to route through it.

/** Compose Tailwind classes for a button. Stable shape: object-arg, both optional. */
export function buttonClass(opts: ButtonClassOptions = {}): string {
export function buttonClass(opts: ButtonClassOptions & { className?: string } = {}): string {
if (opts.className) return cn(buttonClass({ ...opts, className: undefined }), opts.className);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Simplification: the same self-recursive className line is pasted into 17 helpers. if (opts.className) return cn(xClass({ ...opts, className: undefined }), opts.className); re-enters the function to strip the key, then merges. Adding the class as the last cn() argument does the same job with no recursion, since cn drops undefined and tailwind-merge lets the later class win:

return cn(BASE, VARIANTS[variant], SIZES[size], opts.className);

The *Variants aliases then reduce to return buttonClass(opts) as they do now. Side note: the hand-copied examples/blog/components/ui/button.ts and gallery/modules/gallery/ui/button.ts keep the old signature, so buttonClass({ className }) silently ignores the class there.

Comment thread packages/server/src/testing.js Outdated
}
// notFound() / forbidden() / unauthorized(): rethrow the sentinel, as the
// client stub does, so a test asserts with isForbidden(err).
const cf = res.headers.get('x-webjs-control');

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reuse: CONTROL_HEADER is exported from action-error.js for this, but this file and the generated stub (actions.js:401) both hardcode 'x-webjs-control'. A rename of the constant would update the server response and leave both readers checking the old name, so the stub and invokeActionForTest would stop rethrowing the sentinel with nothing failing at build time. Import CONTROL_HEADER here and interpolate it into the stub line with J(CONTROL_HEADER) the way __CT is.

Related, lower: in scripts/agent-eval/build.mjs:89 usage is taken from the FIRST event per message id. If stream-json ever reports a growing output_tokens across a message's split content-block events, this undercounts output; taking the max (or the last) per id is as cheap and safe either way.

t added 6 commits November 12, 2026 23:43
Review findings on #1698. verify resolved each step on exit, before its
stdio closed, so the last lines of a failing step (the failing assertion,
the summary) could be lost; it now runs on runCi, which waits for close
with a grace period, so there is one runner for captured steps instead of
two that had already drifted. check and typecheck run in one parallel
group. verify no longer loads .env.development* before its steps: each
step is the CLI run as its own command and reads the files for its own
mode, so the tests see what plain webjs test sees. It still does not run
webjs.ci.steps, which is the full gate (doctor, a network audit, browser
and e2e tests) rather than the quick check after a feature.

Refs #1697
Review finding on #1698. The refusal fired whenever none of the submitted
fields was on the only bound form, which also refused forms it should
post: controls attached with form="id", a form-associated custom
element, a field added in the browser, and a test that posts a field the
form lacks on purpose. With no bound form on the page it also called an
unbound form bound, hiding the clearer error. It now fires only when the
only bound form has no fields at all (a layout logout button) while the
test submits some, and never for a form whose id other controls point
at.

Refs #1697
Review findings on #1698. An action that changed data and then threw
notFound(), forbidden() or unauthorized() answered its status without the
x-webjs-invalidate and x-webjs-refresh the redirect branch sends, and
revalidateTags never ran, so reads cached before the action stayed stale.
Both branches now share one effects step. The generated stub applies the
refresh before it rethrows the sentinel, and the stub and
invokeActionForTest read the header through CONTROL_HEADER instead of a
copied string.

Refs #1697
Review findings on #1698. The api template still generates
modules/users and app/api/users, but the shared AGENTS.md no longer said
they are an example, so an agent would likely keep them; the api app's
AGENTS.md now carries one line saying so, which the full-stack app,
shipping no example, does not. The ai-first docs page still described
the brief as running webjs status after each edit, and the deployment
page said the scaffold ships instrumentation.ts, which it no longer does.

Refs #1697
Review finding on #1698. Each of the 17 helpers with a shadcn alias
carried the same self-recursive line to strip and re-merge className.
Every one already returns a single cn(...), and cn() skips undefined, so
className is now one more argument: the output without it is unchanged
(the bake snapshot holds every string), and with it cn(cn(a), b) was
cn(a, b) anyway. The hand-copied button.ts in examples/blog and the
gallery take className too, so the habit works there as well.

Refs #1697
Review finding on #1698. The harness took usage from the first event of
each message id, but usage is written as a message streams, so a later
event can report more output tokens and the first undercounts. Each
field now keeps its largest value per id. Round 11 reads the same under
the fix, its input tokens being the same on every event of a message.

Refs #1697

@vivek7405 vivek7405 left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Review (high effort, recall-oriented). Nine findings below, most severe first. The two that matter most: the RPC path now evicts invalidates tags on notFound() / forbidden() / unauthorized() while the no-JS form path does not (and ranAction is true for a guard that throws before any mutation), and the Promise<never> typing of signIn / signOut contradicts the runtime's Response returns. The rest are lower severity: test-helper and verify-runner edge cases, an eval-harness crash on re-run, and stale scaffold comments.

Comment thread packages/server/src/actions.js Outdated
// notFound() / forbidden() / unauthorized() (Next.js parity with the
// no-JS form path): the same 404 / 403 / 401, not a logged 500.
const cf = controlFlowStatus(e);
if (cf) return controlFlowResponse(e, cf, await effects());

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Transports disagree, and an auth guard now busts the cache. Over RPC a notFound() / forbidden() / unauthorized() now runs effects() and evicts the action's invalidates tags. The no-JS form path (form-dispatch.js around L684 to L697) returns the 404 / 403 / 401 boundary WITHOUT calling completionHeaders(), so the same action evicts on one transport and not on the other.

Also, ranAction turns true as soon as the action body starts (L613), so the common shape const user = await auth(); if (!user) unauthorized(); at the top of an action, with no mutation run, evicts every tagged cache() entry on each anonymous call. Any unauthenticated client can then flush the tagged caches by calling the action over and over. A redirect has the same shape, but a redirect usually comes after the write; a guard sentinel usually comes before it.

Suggest choosing one rule for both transports. Evicting only on a redirect, as before, is the cheaper choice and keeps the old safety.

Comment thread packages/server/index.d.ts Outdated
data?: FormData | Record<string, unknown>,
opts?: { redirectTo?: string; redirect?: true; req?: Request },
): Promise<Response>;
): Promise<never>;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Promise<never> contradicts the runtime. signIn in auth.js returns res whenever res.status !== 302 || !location (an unknown provider id, an error response), and returns signInFn(...) (a Response) when called outside a request. The docblock says this. Typed never, TS treats every statement after await signIn(...) as unreachable and narrows const r = await signIn(...) to never. Code that inspects the Response, e.g. in a script or a test that calls it bare, then fails to compile or gets no checking at all. signOut (L1699) has the same problem outside a request.

An overload or a Promise<never | Response> would still let return signIn(...) fit a Promise<ActionResult> action only if the action's type allows a Response, so the honest fix might be a separate overload keyed on req / being in a request, or keep Response and document return signIn(...) as never.

// notFound() / forbidden() / unauthorized(): rethrow the sentinel, as the
// client stub does, so a test asserts with isForbidden(err).
const cf = res.headers.get(CONTROL_HEADER);
if (cf === 'not-found') notFound();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

invokeActionForTest(..., { throwOnError: false }) now throws for a 404 / 403 / 401 control-flow answer. Before, it returned the parsed body. A test that passes throwOnError: false to assert on a forbidden result gets an exception instead. The sentinel rethrow should probably be gated on throwOnError, or the option's doc should say that control-flow sentinels always throw. (Redirect already behaves this way, but that was not true for these three status codes until this PR.)

// A nested `node --test` would report to the parent run instead of setting
// its own exit code, so no step inherits the context.
const env = { ...(opts.env || process.env) };
delete env.NODE_TEST_CONTEXT;

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

runCi (ci-runner.js L372) sets CI: 'true' on every step, so webjs verify runs the app's tests and the boot as CI. An app or test that checks process.env.CI behaves differently under verify than under npm test: it may skip tests, use stricter config, or apply Playwright-style forbidOnly and retries. That breaks verify's promise to be the local loop an agent runs. Since NODE_TEST_CONTEXT is already deleted here, consider deleting CI too, or passing a step env that unsets it, unless the shell itself set it.

Comment thread packages/cli/lib/verify.js Outdated
*/
export function tail(output, n = FAIL_TAIL_LINES) {
const lines = output.replace(/\x1b\[[0-9;]*m/g, '').split('\n')
.filter((l) => l.trim() && !/^\s+at\s/.test(l));

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The stack-frame filter /^\s+at\s/ also drops real output lines that start with indented at , such as an assertion message at least one row expected or a TAP diagnostic. Those lines are the failure an agent needs to see. Anchoring on the frame shape, e.g. /^\s+at\s.*(\(.*:\d+:\d+\)|:\d+:\d+)$/, keeps the intent and avoids dropping them.

Comment thread scripts/agent-eval/build.mjs Outdated
mkdirSync(buildDir, { recursive: true });
const tmp = mkdtempSync(join(existsSync('/tmp') ? '/tmp' : tmpdir(), 'wje-'));
const link = join(buildDir, 'tmp');
if (!existsSync(link)) symlinkSync(tmp, link);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

existsSync follows the link, so a <buildDir>/tmp left by an earlier run whose /tmp/wje-* target is gone (cleaned or after a reboot) reads as absent, and then symlinkSync throws EEXIST. When the old link is still live it is kept while TMPDIR points at the NEW mkdtemp dir, so the link and the env disagree. The mkdtemp dirs are also never removed. Using lstatSync (try/catch) with an rmSync + relink, or reusing the existing link's target, fixes both.

Comment thread packages/server/src/form-dispatch.js Outdated
if (typeof id !== 'string' || !id) {
reportFormActionMissing(url, req, formData, onError, logger, !!ssrOpts.dev, route);
return methodNotAllowed();
return methodNotAllowed(MISSING_ACTION_HINT);

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This hint is now the 405 body in production too, for any POST to a page without the field (bots, scanners). It is only useful in dev or tests, and it publishes the internal wire-field name and test-helper advice to every client. Consider sending the long hint only when ssrOpts.dev is set and keeping the bare Method Not Allowed otherwise. reportFormActionMissing already gets !!ssrOpts.dev one line above.

Comment thread packages/cli/lib/create.js Outdated
// it is replaced rather than kept in the finished app (#1697).
const agentsPath = join(appDir, 'AGENTS.md');
const agents = await readFile(agentsPath, 'utf8');
const layoutEnd = agents.indexOf('the feature\'s tests\n');

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The api template's AGENTS.md patch matches the exact text the feature's tests\n. A CRLF checkout of the template (Windows core.autocrlf) or any rewording of that layout line makes indexOf return -1, and the api app then silently ships without the sentence telling the agent to replace modules/users/. Matching with /the feature's tests\r?\n/, or throwing or asserting when the anchor is missing, keeps this from failing silently.

} catch (_) {}
var m = matchMedia('(prefers-color-scheme: dark)');
var set = function(){ document.documentElement.classList.toggle('dark', m.matches); };
set();

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale comments left by removing the theme toggle and the pre-installed kit: the generated public/input.css comment (L1300 to L1301) still says the head script keeps .dark "in step with the saved choice or the OS", but nothing saves a choice anymore. assertUiRegistryAvailable's docblock (L249 to L251) still says the scaffold "weaves [component sources, the cn() helper] into a generated app/page.ts that imports components/ui/button.ts", which this PR removed. Both ship into, or describe, every new app that an agent reads.

t added 3 commits November 13, 2026 00:11
Review finding on #1698. Promise<never> matched Auth.js v5, but here the
redirecting form still resolves to a Response outside a request (scripts
and tests call it that way and read the Response) and for a provider
that answers anything but a redirect, so never marked the code after
such a call unreachable and dropped the type of what it returned. The
honest type is back, and an action that returns signIn() is typed
ActionResult | Response.

This reverts commit e592a97.

Refs #1697
Review finding on #1698. The previous fix evicted an action's
invalidates tags when it threw notFound(), forbidden() or unauthorized(),
but ranAction is already true for a guard at the top of the action, so
any anonymous caller could flush the tagged caches over and over, and the
no-JS form path never evicted them, so the transports disagreed. Only
redirect(), the way a successful action navigates, evicts them now. A
revalidatePath() the action really called before the throw is still
reported to the browser, since the server already evicted that path.

Refs #1697
…false

Review finding on #1698. invokeActionForTest rethrew the notFound(),
forbidden() and unauthorized() sentinels even when a test passed
throwOnError: false to assert on the response, so it got an exception
instead of the parsed body. The sentinel is rethrown only when
throwOnError is on, as every other non-2xx already was.

Refs #1697
t added 4 commits November 13, 2026 00:13
Review findings on #1698. verify runs on the webjs ci engine, which sets
CI=true on every step, so an app whose tests or config branch on CI
behaved differently than under npm test; runCi takes markCi: false now,
and verify passes it, so a step sees only the shell's own CI. Its output
tail also dropped every indented line starting with "at", hiding a
failure message such as "at least one row expected"; it drops only
lines ending in a source location or <anonymous>, which is a frame.

Refs #1697
Review finding on #1698. agentEnv checked the <build>/tmp link with
existsSync, which follows it, so after /tmp was cleaned the dangling link
read as missing and symlinkSync threw EEXIST; with a live link it kept
the old one while TMPDIR pointed at a new dir, and wje-* dirs piled up.
It now replaces a previous link and removes the temp dir it named.

Refs #1697
Review finding on #1698. The 405 for a page POST without __webjs_action
named the internal field and the test helper to every client in
production, bots and scanners included. Development keeps the hint, for
the agent verifying a form with curl; production answers the bare
status.

Refs #1697
Review findings on #1698. The api template's note naming its example
module was inserted after an exact text match and skipped silently when
the text was missing, so a reworded template or a CRLF checkout shipped
without it; the match takes either line ending and a miss now throws.
The generated input.css still described a saved theme choice, and the
create.js docblocks still described a theme toggle and a page importing
the kit Button, none of which the scaffold has now.

Refs #1697
@vivek7405
vivek7405 merged commit 1824e0e into main Nov 12, 2026
9 of 11 checks passed
@vivek7405
vivek7405 deleted the feat/cut-lookup-turns branch November 12, 2026 18:55
vivek7405 pushed a commit that referenced this pull request Nov 12, 2026
bun test runs every file in one process, one after another, so the
per-file copy from #1698 is deliberately Node-only, and the two-file
assertion failed the Bun matrix on main. The docs now say Bun files
share the run database.
vivek7405 added a commit that referenced this pull request Nov 12, 2026
)

* chore: release packages for webjs verify and the minimal scaffold

server 0.10.2, ui 0.5.2, mcp 0.1.21, cli 0.12.2 for #1698.

* test: scope the per-file test database case to Node

bun test runs every file in one process, one after another, so the
per-file copy from #1698 is deliberately Node-only, and the two-file
assertion failed the Bun matrix on main. The docs now say Bun files
share the run database.

---------

Co-authored-by: t <t@t>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

dogfood: cut agent lookup turns in builds on the scaffold

1 participant