From 2c70489bd0df4b2e34c143dbe89c38d575a8bae7 Mon Sep 17 00:00:00 2001 From: Sambit Biswas Date: Tue, 24 Nov 2026 01:50:02 -0500 Subject: [PATCH 01/14] docs(plan): design mode v2 Phase 2a (app detection) plan, reviewed Co-Authored-By: Claude --- ...-11-24-design-mode-v2-p2a-app-detection.md | 759 ++++++++++++++++++ 1 file changed, 759 insertions(+) create mode 100644 docs/superpowers/plans/2026-11-24-design-mode-v2-p2a-app-detection.md diff --git a/docs/superpowers/plans/2026-11-24-design-mode-v2-p2a-app-detection.md b/docs/superpowers/plans/2026-11-24-design-mode-v2-p2a-app-detection.md new file mode 100644 index 000000000..383218f5f --- /dev/null +++ b/docs/superpowers/plans/2026-11-24-design-mode-v2-p2a-app-detection.md @@ -0,0 +1,759 @@ +# Design mode v2 — Phase 2a: app detection — Implementation Plan + +> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking. + +**Goal:** Give design mode a tested way to find a workspace's web app and the tools to run it, before anything runs. +- The device helpers stop putting an empty entry on PATH. That is a small safety fix, with its own commit, made before the lift. +- The Node and package-manager lookup that devices use moves into a shared `main/services/node-toolchain.ts`. Devices behave as they do after that fix. +- `detectWebApp(root)` finds the workspace's app candidates and classifies each as `web`, `react-nonweb` or `none`. For each it gives the framework, dev script, package manager, install root and install state. +- Lockfile and package-manager rules are pure functions, and so are the fixed install and run commands built from them. +- `resolveAppToolchain` turns a missing Node or package manager into a typed reason that 2b and 2c can show. + +**Architecture:** +- **Shared toolchain.** `node-toolchain.ts` holds: + - the generic resolver (PATH, then the login shell, then Homebrew), with an optional cache of validated paths; + - the standalone-Node check; + - the PATH and environment helpers. + + `devices/device-toolchain.ts` keeps every export it has today, as thin wrappers that pass the device's own settings (Node 22, `npm` and `node` only, no cache). Device callers don't change. +- **Pure core.** `main/services/design-canvas/app-server/app-server-core.ts` takes parsed inputs (a package.json object, lockfile names, a few existence flags) and returns the classification. It does no I/O. +- **Reader.** `app-detect.ts` reads the disk with bounded, no-follow reads and feeds the core. It is the only 2a file that touches the filesystem for detection. The spec put `detectWebApp` in `app-server-core.ts`; S23 records the move. +- **Toolchain join.** `app-toolchain.ts` combines a detected app with `node-toolchain.ts` and returns either the resolved binaries or a typed problem. + +Nothing in the running app calls the new design modules in 2a. 2b is their first caller. + +**Tech Stack:** TypeScript (ESM), Electron 43 main, `tsx --test` for unit tests. No renderer or E2E changes. + +**Spec:** `docs/superpowers/specs/2026-11-23-design-mode-live-app-design.md`: +- §4 (constraints), §5.2; +- §6.2.1 (detection), §6.2.2 (Node toolchain), §6.2.3 (the install rule; 2a uses it only for the command table); +- §6.8 (non-web React projects, missing Node); +- §7 (pure-core tests), §8 (row 2a), §10 (builder's choices), §11 item 3 (E2E fixture); +- §12 S2, S6, S8 and S14, which 2b builds on top of this. + +Stacked on PR #908 (Phase 1b), which is stacked on PR #894 (Phase 1a). + +## Scope + +In scope: +- the device PATH fix: `deviceNodeEnvironment`, `androidSdkEnv` and `createNpmRunner` stop adding empty PATH entries (Task 1); +- lifting `resolveExecutable`, the login-shell lookup, the standalone-Node check and the environment helpers out of `device-toolchain.ts` into `node-toolchain.ts`. They're generalised to a fixed set of commands (`node`, `npm`, `pnpm`, `yarn`, `bun`), and devices don't change; +- an optional cache of validated login-shell answers, which only design callers use (§6.2.2 "with a cache"); +- `detectWebApp(root)`: candidates at the root, in the spec's fixed folders and in declared workspace patterns, each classified (§6.2.1); +- package-manager and lockfile detection, covering: + - conflicting lockfiles and the `packageManager` field; + - `pnpm-workspace.yaml` as a pnpm signal, and Deno markers; + - workspace members; + - a workspace folder that sits inside a larger repo; +- the fixed install and run-script argv for each manager (§6.2.3 "Install", S2 "the resolved command"); +- `designTarget(detection)`: what design mode should do with a detection (start one app, ask which, offer mocks, or nothing); +- `resolveAppToolchain(app)`: Node and the package manager resolved, or a typed reason with a short message; +- the spec amendments recording 2a's decisions, the memory files and the plan index. + +Out of scope: +- starting, stopping or installing anything: `DesignAppServers`, `backgroundJobs` changes, the `design` job owner, consent and the install stamp (2b: S2, S7, S8); +- the dev-server command environment: `agentShellCommandEnvironment()`, `BROWSER=none`, `FORCE_COLOR=0`, `PORT`, `COREPACK_ENABLE_DOWNLOAD_PROMPT=0` and the loopback host flags (S14). §8 lists §6.2.2 under 2a, but these are launch facts with no caller until 2b, so they land there with the process (S19). 2a settles the signatures 2b needs (`nodeCommandEnvironment(env, binDirs)`, `runScriptCommand(info, script, extraArgs)`) so 2b doesn't change them; +- `.aiden/canvas.json`: reading `apps`, `mock`, a project naming itself `react-nonweb`, and saving the monorepo choice (3b for the file, 2b for the saved choice); +- the monorepo question card, the status chip and any message shown to the person (2b, 2c); +- route discovery (3b), mock apps and the scaffold questions (3d); +- a corepack fallback for a missing `pnpm` or `yarn` (settled: none); +- running Deno projects (reported as `unsupported-manager`); +- Windows. Design live needs `backgroundJobs`, which `hostPlatformCapabilities()` gives only on darwin and linux. 2a makes no platform claim and changes nothing in `host-platform-capabilities.ts`; +- analytics. `design_app_started` belongs to 2b (§6.10). + +**Feature flag.** 2a ships without `AIDEN_EXPERIMENTAL_DESIGN_LIVE`. It has no user-facing surface: no IPC channel, no tool, no UI and no new process. The flag starts in 2b (S6), the first phase that calls these modules. The device fix and lift aren't design work; they stay under the devices' own flag, as today. + +## What exists today (checked against the code at `e88271d63`) + +| Item | Today | 2a action | +|---|---|---| +| `resolveExecutable(command: "npm" \| "node", deps)` (`device-toolchain.ts:197`) | PATH entries (absolute only), then the `$SHELL -ilc` output (last absolute line, checked with `isExecutable`), then `/opt/homebrew/bin` and `/usr/local/bin`. Not exported. | Moves to `node-toolchain.ts`, exported, with a wider command union and an optional `cache` dependency (Task 2). | +| `NpmResolutionDeps` (`:185`) | `{ env, isExecutable(path), loginShellLookup(shell) }`. The lookup has its command baked in. | Becomes an alias of `ExecutableResolutionDeps`, whose lookup takes `(shell, command)`. A one-argument function still fits the type, so device code and tests compile unchanged. | +| `resolveNpm` (`:193`), `defaultNpmResolutionDeps` (`:219`) | npm: a plain `X_OK` check. The lookup runs `command -v npm` with `env: process.env`, a 5 s timeout and the default `maxBuffer`. Used by `main/handlers/devices.ts:53` and `scripts/devices-acceptance.mjs:56`. | Stay in `device-toolchain.ts` as wrappers, with the same argv, timeout, env and buffer. A guard test pins the argv before the lift. | +| `resolveDeviceNode` (`:284`), `defaultDeviceNodeResolutionDeps` (`:322`) | Node is checked with the `isDeviceNodeExecutable` probe. The lookup runs `command -v node` with the given env and `maxBuffer: 16384`. No cache. Used by `local-device-host.ts:850`. | Wrappers over `resolveExecutable` and `isStandaloneNodeExecutable(…, { minMajor: 22 })`. A guard test pins the argv and buffer. | +| `isDeviceNodeExecutable` (`:295`) | Rejects the app binary by realpath and inode, then runs `-p` and wants `electron === false` and major ≥ 22. It probes with `deviceNodeEnvironment`. Defaults: `process.execPath`, `!!process.versions.electron`. | Wrapper over `isStandaloneNodeExecutable` with `minMajor: 22`, keeping both defaults. | +| `deviceNodeEnvironment` (`:288`) | PATH = `[dirname(node), env.PATH ?? ""].join(path.delimiter)`, then deletes `ELECTRON_RUN_AS_NODE`. With PATH unset or `""` it leaves a trailing `:`, and it keeps any empty entry in the inherited PATH. An empty entry puts the working folder on PATH. Used by `local-device-host.ts` (`:315`, `:358`, `:363`) and `device-tool-maintenance.ts:168`. | **Task 1 fixes it:** no empty entries, by the rule `nodeCommandEnvironment` uses. Task 2 makes it a wrapper over `nodeCommandEnvironment(env, [dirname(node)])`. | +| `androidSdkEnv` (`local-device-host.ts:264`, PATH built at `:274`) | Joins the SDK folders with `env.PATH ?? ""`, which gives the same trailing `:`. No direct test; `local-device-host.test.ts:769` and `:800` test the SDK lookup around it. | Task 1 fixes it, with a new test next to `:800`. | +| `createNpmRunner` (`device-toolchain.ts:243`) | `[dirname(npm), env.PATH].filter(Boolean)` drops a missing PATH, but keeps empty entries inside the inherited PATH. | Task 1 uses the same helper here (see Review amendments, B-M1 note). | +| `NODE_REQUIRED_REASON`, `DeviceNodeUnavailableError`, tool specs and installs | Device-only. | No change. | +| Device tests | `device-toolchain.test.ts` covers npm and Node resolution order, app-binary rejection, old runtimes and the environment (`:294-301`). It is in `test:devices` and the `runtime-subagents` registry lane. | Task 1 extends `:294-301` with three PATH cases. After that, the lift's oracle is the existing device tests unedited, plus Task 1's cases and Task 2's two argv guards. | +| `packages/cli` | Bundles no `devices/` or `design-canvas/` module (`grep` over `packages/cli/src` finds neither). | `npm run cli:build` is a guard only. | +| Lockfile or framework detection | None in `main/` or `renderer/`. Only CI scripts mention lockfiles. | New. | +| `tests/fixtures/design-live-app/` (§7, §11 item 3) | Doesn't exist yet; 3a adds it. | 2a's tests build their own trees in temp folders. One case copies the fixture's shape (Vite + React, `node_modules` as a symlink). | +| `yaml` | Runtime dependency, `2.9.0`. | Used to read `pnpm-workspace.yaml`. | + +## Review amendments (2026-11-24) + +Two adversarial reviews (A: detection rules; B: lift safety and tests) were accepted in full. The decision file named minor findings without ids, so this table numbers them B-m1… and A-m1… in the order given. + +| Id | Decision | Where the plan handles it | +|---|---|---| +| B-M1 | Device PATH fix first, own commit; fix `androidSdkEnv`; three cases in `device-toolchain.test.ts:294-301` and one in `local-device-host.test.ts`; drop `probeEnv`; new lift oracle | Task 1; "What exists today"; Interfaces (no `probeEnv`); Task 2 Step 4; Risk 1; S24. Also applied to `createNpmRunner`, which keeps empty entries from the inherited PATH (same file, same rule). | +| B-M2 | Explicit lookup limits: `timeoutMs` defaults to 5000, `maxBuffer` only when defined; > 1 MiB test; real `defaultNpmResolutionDeps` argv test | Interfaces (`loginShellCommandLookup`); Task 2 Step 1 (both tests, plus the same guard for the Node lookup) | +| B-M3 | Cache only validated paths, inside `resolveExecutable` through a `cache` dependency; drop stale entries | R9; Interfaces (`ExecutableCache`); Task 2 Step 1 tests; Risk 4 | +| B-M4 | `lockfileLevelsUp: number` | R8 type; R6; Task 5 enclosing test | +| B-M5 | `runScriptCommand(info, script, extraArgs?)` with per-manager `--`; `nodeCommandEnvironment(env, binDirs[])` | R10; Interfaces; Task 2 and Task 4 tests | +| B-m1 | Line references fixed against HEAD | "What exists today" (checked at `e88271d63`) | +| B-m2 | `isStandaloneNodeExecutable` keeps the defaults `process.execPath` and `!!process.versions.electron` | Interfaces | +| B-m3 | S-amendments for the `detectWebApp` move and the PATH fix | Task 7 (S23, S24) | +| B-m4 | Docs: `.memory/devices-ssh-hosts-toolchain.md:59`; wider docs search | Task 7 Steps 3–4 | +| B-m5 | Tests: a dangling `node_modules` symlink, and a symlinked `node_modules` at the enclosing root | Task 5 Step 1 | +| B-m6 | Drop the framework-table loop test | Task 3 (removed) | +| A-M1 | Dev-script choice prefers the framework's dev command and skips builds, production runs and workspace runners | R3; Task 3 tests; Risk 10 settled | +| A-M2 | Angular, Nuxt, `@tanstack/start`, `remix@3`; reason `unknown-framework` | R2; R4 rule 8; Task 3; S22 | +| A-M3 | Tauri is desktop, like Electron | R4 rules 2–3, reason `desktop` plus `desktopShell`; Task 3 | +| A-M4 | Node 22 for design, the same as devices | R9; message text; Q2 settled; the old S22 (Node 20) dropped | +| A-M5 | The field wins only with no lockfile or its own; `pnpm-workspace.yaml` means pnpm; Deno gives `unsupported-manager` | R5; R6; R9; Task 4 tests; S20 | +| A-M6 | `O_NOFOLLOW \| O_NONBLOCK`, `fstat().isFile()`, cap+1 reads; `lstat` containers and pattern parents; drop absolute and `..` patterns; FIFO and `packages → /` tests | Global Constraints ("Bounded reads"); R1; Task 5 | +| A-m1 | No upward walk when the workspace root holds `.git`; compare `stopAt` and home after `realpath` | R6; Task 5 tests | +| A-m2 | A conflict with exactly one manager's `node_modules` marker picks it (`source: "installed"`) and still lists the conflict | R5 step 5; Task 4 and Task 5 tests; Q3 settled | +| A-m3 | npm is resolved first from `dirname(resolvedNode)` | R9 step 3; Task 6 test | +| A-m4 | Yarn flavour: the field's major, else `.yarnrc.yml`, `.pnp.cjs` or a non-v1 `yarn.lock` | R5 "Yarn flavour"; Task 4 and Task 5 tests | +| A-m5 | No corepack fallback; S19 says 2b always sets `COREPACK_ENABLE_DOWNLOAD_PROMPT=0` | Scope; Task 7 (S19); Q1 settled | +| A-m6 | Q5 agreed, with `binDirs` | Scope; Interfaces; Q5 settled | +| A-m7 | `@react-router/dev` before `@remix-run/dev` | R2 order; Task 3 test | +| A-m8 | Edge tests: no `scripts`, array `scripts`, `dev: 42` and `dev: null`, a Storybook-only repo, an Nx integrated repo with no member `package.json`; none may give a misleading "add a dev script" | R4 (`no-dev-script` narrowed, `workspace-runner`); Task 3 and Task 5 tests | + +## Global Constraints + +- **Device behaviour.** After Task 1, devices behave exactly as before, except that they never put an empty entry on PATH. Every export of `device-toolchain.ts` keeps its name and signature. The existing tests in `device-toolchain.test.ts`, `local-device-host.test.ts`, `android-device-features.test.ts` and `renderer/components/settings/simulator-settings.test.tsx` pass without edits. Only Task 1's new cases and Task 2's guards are added. If an existing test needs an edit, the change is wrong. +- **Fixed commands only.** `resolveExecutable` and the login-shell lookup accept only the `ToolCommand` union. The lookup also checks at runtime, so a string from a package.json can never reach `command -v`. +- **Pure core.** `app-server-core.ts` imports nothing from `node:fs`, `node:child_process` or Electron. +- **Bounded reads** (A-M6). Every file `detectWebApp` reads (`package.json`, `pnpm-workspace.yaml`, the head of `yarn.lock`) goes through one `readBounded(path, cap)`: + - it opens with `O_RDONLY | O_NOFOLLOW | O_NONBLOCK`; + - it checks `fstat().isFile()`; + - it reads at most `cap + 1` bytes, and over the cap counts as unreadable; + - a symlink, FIFO, socket, device or folder is unreadable, never followed or waited on. + + Caps: + - 512 KiB per `package.json`, 64 KiB for `pnpm-workspace.yaml`, 512 bytes of `yarn.lock`; + - 200 entries per scanned folder; + - 100 candidates in total (then `truncated: true`). + + Containers (`apps/`, `packages/`) and every parent folder of a workspace pattern are checked with `lstat` and skipped when they're a symlink or not a folder. Candidate folders that are symlinks are skipped. `node_modules` and dot folders are never entered. Existence checks for lockfiles and markers use `lstat` and never read. Nothing throws for a bad file: a bad candidate gets a reason. +- **Relative output.** Every path in a detection is POSIX and relative to the workspace root (`.` for the root). Absolute paths stay inside main and never go into a result. Enclosing folders show up only as `lockfileLevelsUp`. +- **Script names.** A script name is used only when its value is a string, it is at most 100 characters, it has no control characters, and it doesn't start with `-`. So a script name can never be read as a manager option. Extra run arguments must have no control characters. +- **AGENTS.md:** + - no source-grep tests; + - each new test file goes in `scripts/ci-test-registry.json` and a `package.json` script, then `npm run test:ci-policy` runs; + - docs change in this PR; + - platform claims match `host-platform-capabilities.ts` (2a makes none). +- **Each task stands alone.** Every task ends with its own tests, `npx tsc --noEmit -p .` and `npm run test:ci-policy` passing, and one commit. +- **Tests.** Detection tests use real temp folders and call the real functions. Toolchain tests use injected `isExecutable` and lookup fakes, plus temp-folder executables and shells where the real behaviour matters. A test that can't fail before its task's change is marked **(guard)**. + +## Detection rules + +**R1. Candidates** (§6.2.1, §10). `detectWebApp(root)` looks at: +1. the root itself; +2. each folder directly inside `apps/` and `packages/`, and the folders `web/`, `frontend/` and `site/` (the spec's fixed list); +3. the root's declared workspace patterns: `workspaces` in `package.json` (an array, or `{ packages: [...] }`) and `packages:` in `pnpm-workspace.yaml`. + +A folder is a candidate when it has a `package.json`. Supported pattern forms: +- `a`, `a/b`, `a/b/c` (exact); +- `a/*`, `a/b/*` (one level); +- `a/*-app` (a `*` inside the last segment); +- a leading `./` is stripped, and `**` counts as `*`, so `packages/**` searches one level, per §6.2.1 and §10; +- `!pattern` removes matches. + +Patterns that are absolute or contain a `..` segment are dropped. Other forms (braces, deeper wildcards, more than three segments) are ignored. Every parent folder of a pattern is checked with `lstat`, so a symlinked `packages/` pointing at `/` is never listed. Candidates are deduplicated and sorted: root first, then by path. + +**R2. Framework** (§6.2.1; widened by S22). Read from `dependencies` and `devDependencies`, never `peerDependencies`. The first match in this order wins. Later entries also appear inside earlier frameworks' apps: Remix, React Router, TanStack Start and SvelteKit apps all list `vite`, and migrated React Router apps may still list `@remix-run/dev`. + +| Dependency | `framework` | Label | Default port | Dev commands (R3) | +|---|---|---|---|---| +| `next` | `next` | Next.js | 3000 | `next dev` | +| `@react-router/dev` | `react-router` | React Router | 5173 | `react-router dev` | +| `@remix-run/dev` | `remix` | Remix | 5173 | `remix vite:dev`, `remix dev` | +| `remix` at major 3 or later | `remix-3` | Remix | check | check | +| `@tanstack/react-start` | `tanstack-start` | TanStack Start | 3000 | `vite`, `vinxi dev` | +| `@tanstack/start` | `tanstack-start` | TanStack Start | 3000 | `vinxi dev`, `vite` | +| `nuxt` | `nuxt` | Nuxt | 3000 | `nuxt dev`, `nuxi dev` | +| `@angular/build`, `@angular-devkit/build-angular` | `angular` | Angular | 4200 | `ng serve` | +| `astro` | `astro` | Astro | 4321 | `astro dev` | +| `gatsby` | `gatsby` | Gatsby | 8000 | `gatsby develop` | +| `react-scripts` | `create-react-app` | Create React App | 3000 | `react-scripts start` | +| `@tanstack/router-plugin` | `tanstack-router` | Vite | 5173 | `vite` | +| `vite` | `vite` | Vite | 5173 | `vite` | + +Notes: +- "React Router v7 framework mode" in the spec is read as `@react-router/dev`. A plain `react-router` dependency is library mode inside some other framework, usually Vite, and matches that framework instead. +- The `remix` package's major version comes from its range (`^3`, `3.x`, `~3.0.0`, `>=3`). Below 3 it is the old v1 meta package and is ignored. Task 3 confirms Remix 3's dev command and default port from its docs. If Remix 3 has no stable dev command yet, the row is dropped and S22 says so. +- `vite` as a dev command means the word `vite` (also `npx vite`, `vite dev`, `vite serve`) not followed by `build`, `preview` or `optimize`. +- The label and default port feed 2c's chip ("Vite · :5173") and its port suggestion. Task 3 checks each port against the framework's current docs and corrects the table if one is wrong. +- Non-React frameworks (Angular, Nuxt, Remix 3, and Vue or Svelte apps through `vite`) run as live frames. Source mapping and component cards stay React-only (§3 non-goals). + +**R3. Dev script** (A-M1). Look only at `dev`, `start` and `serve`, in that order, and only at string values with safe names. +1. **Prefer** the first whose text contains one of the framework's dev commands (R2). So `"dev": "next dev || next start"` and `"dev": "tsc -w & vite"` are picked. +2. **Otherwise** take the first that isn't skipped. A script is skipped when its text contains: + - a build: `vite build`, `next build` (without `next dev`), `tsc`, `tsup`, `rollup`; + - a production run: `next start`, `vite preview`, `astro preview`, `gatsby serve`, `remix-serve`, `react-router-serve`, `NODE_ENV=production`, `serve -s`; + - Storybook: `storybook`; + - a workspace runner: `turbo`, `nx ` (word, then a space), `lerna`, `pnpm -r`, `pnpm --recursive`, `--filter`, `--workspaces`, `yarn workspaces`. +3. **Otherwise** there's no script. + +The check is word-based, so the tokens match only as words: `tsc` doesn't match `tscx`. The scan also records whether a dev/start/serve script existed at all and whether one was skipped as a workspace runner, for R4. The list of safe script names (at most 50) is returned too, for 2b's `choose`. + +**R4. Kind** (§6.2.1, §6.8, decision 9; widened by S21). For each candidate, in order: + +| # | Condition | `kind` | `reason` | +|---|---|---|---| +| 1 | `package.json` unreadable, over the cap, not a regular file, or not a JSON object | `none` | `invalid-package-json` | +| 2 | a desktop shell in deps (`electron`, `@tauri-apps/api`, `@tauri-apps/cli`) and React (`react` or `react-dom`) | `react-nonweb` | `desktop` | +| 3 | a desktop shell, no React | `none` | `desktop` | +| 4 | a framework (R2) and a dev script (R3) | `web` | `ok` | +| 5 | a dev/start/serve script was skipped as a workspace runner, or the folder holds `nx.json`, `turbo.json` or `lerna.json` | `none` | `workspace-runner` | +| 6 | `react-native` or `expo` in deps | `react-nonweb` | `react-native` | +| 7 | a framework, no dev/start/serve string script at all, and no Storybook (`storybook` or any `@storybook/` dependency) | `none` | `no-dev-script` | +| 8 | a usable (not skipped) dev/start/serve script, and no framework matched | `none` | `unknown-framework` | +| 9 | React in deps | `react-nonweb` | `no-web-framework` | +| 10 | anything else | `none` | `no-web-framework` | + +Notes: +- `desktop` apps also carry `desktopShell: "electron" | "tauri"`, so 3d's question can name the shell (§6.8). Rule 2 before rule 4 is the spec's "no `electron` dependency", extended to Tauri (A-M3). An Electron + Vite + React app, such as Aiden itself, is `react-nonweb`. +- `no-dev-script` means exactly "this is a framework app with nothing to run", so "add a dev script" is the right advice. A Storybook-only repo, or a library whose `dev` is `vite build --watch`, falls through to rule 9 (React mocks) or rule 10 instead. +- `workspace-runner` covers a turbo or Nx root and an Nx integrated repo whose apps have no `package.json`. Its members, when they have one, are found as their own candidates. 2c and 3d say "this repo runs its apps through a workspace tool", and never offer to scaffold. +- `unknown-framework` is an app with a runnable script that design mode doesn't recognise, such as a custom webpack server. 3d must not scaffold for it (A-M2). 2b can still offer it later through `choose`; that's 2b's call. +- Rule 6 is the spec's "uses React but can't run as a web page by itself". A React Native package that also lists `vite` and a dev command runs on the web and is caught by rule 4. +- A `scripts` value that is missing, an array, or not an object counts as no scripts. A script whose value isn't a string (`42`, `null`) counts as missing. +- `.aiden/canvas.json` can later mark a project `react-nonweb` (§6.2.1). That override is 3b's. + +**R5. Package manager and lockfiles** (A-M5, A-m2, A-m4; S20). Signals, per folder: + +| File | Manager | +|---|---| +| `pnpm-lock.yaml` | pnpm | +| `yarn.lock` | yarn | +| `bun.lock`, `bun.lockb` | bun | +| `package-lock.json`, `npm-shrinkwrap.json` | npm | + +Two files of the same manager (`bun.lock` with `bun.lockb`, `package-lock.json` with `npm-shrinkwrap.json`) are not a conflict. The manager is decided at the candidate's install root (R6). Let L be the set of managers with a lockfile there, and F the manager named by the `packageManager` field (`"pnpm@9.15.0+sha512…"`; only `npm`, `pnpm`, `yarn` or `bun` count). +1. **F set, and L empty or `{F}`:** F, `source: "packageManager"`. +2. **F set, and L holds another manager:** `name: null`, `conflict` = L ∪ {F}, sorted. +3. **No F, one manager in L:** that manager, `source: "lockfile"`. +4. **No F, several managers in L:** `name: null`, `conflict` = L, sorted. +5. **Conflict tie-break:** when `node_modules` at the install root holds markers of exactly one manager in the conflict, pick it with `source: "installed"`, and keep `conflict`. The markers are `.package-lock.json` (npm), `.modules.yaml` (pnpm), `.yarn-integrity` or `.yarn-state.yml` (yarn). A `null` name otherwise; 2b refuses to install or start that app, with a message saying how to fix it. Guessing could rewrite the wrong lockfile. +6. **No F, L empty, `pnpm-workspace.yaml` present:** pnpm, `source: "workspace-file"`. +7. **No F, L empty, `deno.lock`, `deno.json` or `deno.jsonc` present:** `name: null`, `unsupported: "deno"`. +8. **Nothing at the install root:** the enclosing walk (R6). If it finds nothing either, npm with `source: "none"`; install is `npm install`, not `npm ci` (§6.2.3). + +**Yarn flavour.** The field's major version decides when the field names yarn (1 is `classic`, 2 or more `berry`). Otherwise it's `berry` when the folder holding the yarn signal has `.yarnrc.yml` or `.pnp.cjs`, or the first 512 bytes of its `yarn.lock` contain `__metadata:`. Anything else is `classic`, including an empty `yarn.lock`. + +**R6. Install root, workspaces and enclosing repos.** +- **Own signals:** a candidate with its own lockfile (or `pnpm-workspace.yaml`) is its own install root, even inside a declared workspace. This covers a standalone `frontend/` in a Python repo, and pnpm's `shared-workspace-lockfile=false`. +- **Workspace member:** a candidate without its own lockfile that matches a root workspace pattern (R1, step 3) has `installRoot: "."`. Its manager comes from the root's signals and `packageManager` field; the candidate's own field wins when it has one. +- **Fixed-folder candidate:** a candidate found only through the fixed list, with no lockfile and no matching pattern, is its own install root. +- **Workspace inside a bigger repo:** a workspace opened at `apps/web` of a pnpm monorepo has no lockfile of its own. Installing with `npm install` there would write a `package-lock.json` and a second `node_modules` into the person's repo. So `detectWebApp` walks upward when all of these hold: + - the root has no lockfile; + - the root has no `packageManager` field, `pnpm-workspace.yaml` or Deno marker; + - the root has no `.git` (A-m1). + + The walk: + - checks each parent folder for the R5 lockfile names, `pnpm-workspace.yaml`, the yarn-flavour markers and `node_modules`; + - stops at the first folder with a lockfile or `pnpm-workspace.yaml`, and after checking a folder that holds `.git` (file or folder); + - never reads the home folder, `stopAt`, anything above them, or past 5 levels. Both `stopAt` and home are compared after `realpath`; + - a signal found there decides the manager by R5, with `source: "enclosing"` (or `"installed"` after a tie-break) and `lockfileLevelsUp` set to how many folders up it was. `installRoot` stays the candidate's own path, because every manager finds its workspace root from a member folder. + + The walk reads only names and the 512-byte `yarn.lock` head, never returns the enclosing path, and never runs Deno checks. Tests pass `stopAt` to keep it inside the temp folder. + +**R7. Install state.** `installed` is true when `node_modules` at the install root `stat`s as a folder, or `.pnp.cjs` exists there (Yarn PnP). For an enclosing signal, `node_modules` at that enclosing folder counts too, since npm and yarn hoist there. `stat` follows symlinks: 3a's E2E fixture symlinks its `node_modules` to the repo root's (§7). A dangling symlink is `installed: false`, not an error. This is a hint only: 2b's install stamp (S8) decides whether to reinstall. + +**R8. What a detection returns.** + +```ts +type AppKind = "web" | "react-nonweb" | "none"; +type AppReason = "ok" | "desktop" | "workspace-runner" | "react-native" | "no-dev-script" + | "unknown-framework" | "no-web-framework" | "invalid-package-json"; +type FrameworkId = "next" | "react-router" | "remix" | "remix-3" | "tanstack-start" | "nuxt" | "angular" + | "astro" | "gatsby" | "create-react-app" | "tanstack-router" | "vite"; +type PackageManagerName = "npm" | "pnpm" | "yarn" | "bun"; + +interface PackageManagerInfo { + name: PackageManagerName | null; // null on an unresolved conflict or an unsupported manager + source: "packageManager" | "lockfile" | "installed" | "workspace-file" | "enclosing" | "none"; + lockfile?: string; // the file R5 chose, e.g. "pnpm-lock.yaml" + lockfileLevelsUp: number; // 0 inside the workspace; ≥ 1 for an enclosing signal + conflict?: PackageManagerName[]; // R5 steps 2, 4 (kept after a step-5 tie-break) + unsupported?: "deno"; // R5 step 7 + yarn?: "classic" | "berry"; +} + +interface DetectedApp { + root: string; // "." or "apps/web" + name?: string; // package name, ≤ 214 chars, control characters stripped + kind: AppKind; + reason: AppReason; + desktopShell?: "electron" | "tauri"; + framework?: FrameworkId; + script?: string; // R3 + scripts: string[]; // safe script names, ≤ 50 + usesReact: boolean; + packageManager: PackageManagerInfo; + installRoot: string; // R6 + installed: boolean; // R7 +} + +interface WebAppDetection { apps: DetectedApp[]; truncated: boolean } +``` + +`designTarget(detection)` sums it up for 2b: + +| Detection | `designTarget` | What 2b does (for reviewers; not built here) | +|---|---|---| +| exactly one `web` app | `{ kind: "single", app }` | Turning design mode on starts it (after S2 consent). | +| two or more `web` apps | `{ kind: "choose", apps }` (only the `web` ones) | Nothing starts. Aiden asks which apps, and the chip shows **Choose apps…** (§6.2.1). | +| no `web`, one or more `react-nonweb` | `{ kind: "react-nonweb", apps }` | Nothing starts. 3d's mock-app question. | +| no `web`, no `react-nonweb` | `{ kind: "none", apps }` (all candidates, so `no-dev-script`, `workspace-runner` and `unknown-framework` stay visible) | Nothing starts. 3d's scaffold question only when no candidate has `workspace-runner` or `unknown-framework`; otherwise a hint from the reason. | +| no `package.json` anywhere | `{ kind: "none", apps: [] }` | As above. | + +A `react-nonweb` package next to a `web` app (for example `packages/ui` beside `apps/web`) doesn't change the target. A web app whose manager is `null` is still `web`. Refusing it is 2b's job, so the person sees why. + +**R9. Missing Node or package manager** (§6.8, §4, A-M4, A-m3). `resolveAppToolchain(app, deps)`: +1. **Node first:** `resolveExecutable("node")` with `isStandaloneNodeExecutable(…, { minMajor: 22 })`, the same floor as devices. None found: `{ ok: false, problem: "node-missing" }`. Node is needed even with pnpm's standalone build or bun, because the frameworks' own CLIs run on Node. +2. **No manager name:** + - `unsupported`: `{ ok: false, problem: "unsupported-manager", manager: "deno" }`; + - a conflict: `{ ok: false, problem: "manager-conflict", conflict }`. +3. **The manager:** + - npm is looked for first at `dirname(node)/npm`, then through `resolveExecutable("npm")`; + - other managers go through `resolveExecutable(name)` with a plain executable check. + + None found: `{ ok: false, problem: "manager-missing", manager }`. There's no fallback to npm for a pnpm, yarn or bun project, because that would write a second lockfile, and no corepack fallback (S19). +4. Otherwise `{ ok: true, node, manager: { name, path } }`. + +`toolchainProblemMessage(problem)` gives one fixed sentence per problem, for 2b's tool answers and 2c's chip: +- `node-missing`: "Node.js 22 or newer wasn't found. Install it from nodejs.org or Homebrew, then try again." +- `manager-missing`: "This app uses pnpm, which wasn't found. Install pnpm, then try again." (the manager's name filled in) +- `manager-conflict`: "This app has lockfiles for npm and yarn. Delete the one you don't use, or set packageManager in package.json." (the names filled in; a field-and-lockfile conflict says "packageManager says pnpm, but the lockfile is npm's.") +- `unsupported-manager`: "This app uses Deno, which design mode can't run yet." + +The design callers pass a shared `ExecutableCache` to `resolveExecutable` (B-M3): +- it keeps only a login-shell answer that is absolute and passed `isExecutable`; +- before using a kept path, `resolveExecutable` checks it again and drops it when the check fails; +- junk output and misses are never kept, so installing Node and pressing Retry works without a restart (§6.8 "offers Retry"). + +**R10. Commands** (§6.2.3, S2, B-M5). Pure argv builders. The caller chooses the cwd. + +| Manager | `installCommand` with a lockfile | without | `runScriptCommand(info, script, extraArgs)` | +|---|---|---|---| +| npm | `npm ci` | `npm install` | `npm run