@auis/cli 0.2.2 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -47,10 +47,77 @@ npx @auis/cli@latest doctor
47
47
 
48
48
  `doctor` reads the repository and reports what Auis could do in it — each
49
49
  capability with a reason, and an alternative when the answer is no. It writes
50
- nothing. Installing into an existing repository (`auis init`) is not shipped yet.
50
+ nothing.
51
51
 
52
- The builder UI (Review, Edit, State Mode, the flow driver) needs **React 18+** in
53
- the host today. A mount that runs beside Vue, Svelte, Angular and others is
52
+ In a **Next.js App Router** app, `init` asks what to install:
53
+
54
+ ```bash
55
+ npx @auis/cli@latest init --dry-run # pick, then print what it would touch
56
+ npx @auis/cli@latest init
57
+ ```
58
+
59
+ ```
60
+ What should auis install? ↑↓ move · space toggle · a all · enter install · esc cancel
61
+
62
+ ❯ ◉ Review pins, comments, the drawer and agent mentions
63
+ ◯ State Mode switch a screen's states in place, and ?ge= deep links that replay clicks
64
+ it is not packaged for an existing app yet, and it needs a registry of your screens
65
+ ◯ Edit Mode visual edits an agent turns into code
66
+ it is not packaged yet, and it needs a map of your components and tokens
67
+ ◯ Styleguide a living page of your own components and tokens
68
+ it has to document your components, not Auis's, and that scanner does not exist yet
69
+ ◯ UX Flows navigable flow diagrams that are pages in your app
70
+ it is not packaged for an existing app yet
71
+ ```
72
+
73
+ Today **Review** is the one that installs — pins, comments, the drawer and the
74
+ agent mentions. The other modules stay on the menu, dimmed, with the reason they
75
+ cannot be picked yet; they light up as each one is packaged. In CI or a script,
76
+ skip the menu with `--only review` (or `--yes` for every module that installs
77
+ here). `--only` with a module that cannot install says why and writes nothing.
78
+
79
+ With Review picked, `init` prints what it touches, and touches nothing else:
80
+
81
+ ```
82
+ What init touches 7 places
83
+
84
+ create app/api/review-bridge/[...path]/route.ts 15 lines — the bridge's catch-all route
85
+ edit app/layout.tsx +2 lines — one import, one <AuisReview /> before </body>
86
+ edit package.json +1 dependency — @auis/next@^0.2.0
87
+ edit package-lock.json npm install
88
+ append .gitignore 4 lines, in a delimited block
89
+ create .auis/manifest.json what auis wrote, so uninstall can reverse it
90
+ create .auis/data/ the comment queue (gitignored)
91
+ ```
92
+
93
+ Then start your dev server and open Review from the pill at the bottom of the
94
+ page, or with ⌘⇧Y (Ctrl+Shift+Y). The review chrome carries its own scoped
95
+ styles and fonts, so your pages render exactly as before.
96
+
97
+ `init` never overwrites a file it did not create, and never touches `AGENTS.md`,
98
+ `.mcp.json`, `globals.css`, `tsconfig.json` or `components.json`. When the root
99
+ layout has more than one `<body>`, it prints the two lines for you to place
100
+ instead of guessing. Running it twice changes nothing.
101
+
102
+ ```bash
103
+ npx @auis/cli@latest uninstall
104
+ ```
105
+
106
+ `uninstall` reads `.auis/manifest.json` and reverses it: a file you have not
107
+ touched since gets its original bytes back; a file you changed loses only what
108
+ `init` inserted; a route you edited is kept, with a warning (`--force` removes
109
+ it). Your comments are moved to `~/.auis/review-bridge-backups/<project>/`, not
110
+ deleted (`--purge` deletes them).
111
+
112
+ Agent mentions (`@Claude`, `@Grok` in a comment) open the agent's CLI on your
113
+ machine when the dev server runs with `AUIS_MENTION_TRIGGER=1` (Claude starts
114
+ switched on with the `edit` ceiling; change it with
115
+ `PUT /api/review-bridge/agent-settings` — the Agents panel is Auis-only today). The runner
116
+ ships with `@auis/server`; a `.auis/mention-prompt.md` replaces the prompt it
117
+ gives the agent.
118
+
119
+ Edit Mode, State Mode and the flow driver are not installable into an existing
120
+ app yet; only Review is. The builder UI needs **React 18+** in the host today. A mount that runs beside Vue, Svelte, Angular and others is
54
121
  planned; it does not exist yet.
55
122
 
56
123
  ## Options
@@ -58,14 +125,22 @@ planned; it does not exist yet.
58
125
  ```
59
126
  npx @auis/cli@latest [directory] [options] scaffold a new project
60
127
  npx @auis/cli@latest doctor [directory] read an existing repo, write nothing
128
+ npx @auis/cli@latest init [directory] install Review into an existing Next.js app
129
+ npx @auis/cli@latest uninstall [directory] take it back out, exactly
61
130
 
62
131
  --json doctor only: the full report as JSON
132
+ --only <a,b> init only: install these and skip the menu
133
+ (review, states, edit, styleguide, flows; review installs today)
134
+ --dry-run init only: print what it would touch, write nothing
135
+ --purge uninstall only: delete the comments instead of moving them to the backups
63
136
  -r, --ref <ref> branch, tag or commit of the template (default: main)
64
137
  --pm <manager> npm | pnpm | yarn | bun (default: detected)
65
- --no-install skip dependency installation
138
+ --no-install skip dependency installation (create, init, uninstall)
66
139
  --no-git skip git init and the first commit
67
- --force scaffold into a directory that is not empty
140
+ --force create: scaffold into a directory that is not empty
141
+ uninstall: also remove files you changed since init
68
142
  -y, --yes take the defaults, never prompt
143
+ (init: every module that installs in this repository)
69
144
  -h, --help show usage
70
145
  -v, --version print the CLI version
71
146
  ```
@@ -78,10 +153,18 @@ npx @auis/cli@latest . # current directory
78
153
  npx @auis/cli@latest my-product --pm pnpm --no-git
79
154
  npx @auis/cli@latest my-product --ref v1.0.0
80
155
  npx @auis/cli@latest doctor # what Auis can do in the current repo, writes nothing
156
+ npx @auis/cli@latest init # install Review into the current Next.js app
157
+ npx @auis/cli@latest uninstall # and take it back out
81
158
  ```
82
159
 
160
+ Up to 0.2.x, `init` was a third name for creating a project. Since 0.3.0 it
161
+ installs into an existing app; use `create` or `new` (or no command) to
162
+ scaffold.
163
+
83
164
  Requires **Node.js ≥ 20**. The template is fetched as a GitHub tarball (`tar`),
84
- falling back to `git clone --depth 1`. The CLI itself has zero dependencies.
165
+ falling back to `git clone --depth 1`. The CLI itself has zero dependencies;
166
+ `init` adds `@auis/next` (and through it `@auis/server`, `@auis/ui` and
167
+ `@auis/core`) to the app it installs into.
85
168
 
86
169
  ## What the scaffold changes
87
170
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auis/cli",
3
- "version": "0.2.2",
3
+ "version": "0.4.0",
4
4
  "description": "Scaffold Auis — the code-native design builder for Next.js + Tailwind + shadcn/ui, with agent skills built in.",
5
5
  "type": "module",
6
6
  "bin": {
package/src/cli.mjs CHANGED
@@ -2,9 +2,9 @@
2
2
  * Argument parsing and dispatch for `npx @auis/cli`.
3
3
  *
4
4
  * `create` stays the default, so the bare form reads as the install line it is:
5
- * `npx @auis/cli@latest my-product`. `doctor` is the other half — it reads an
6
- * existing repository and reports what Auis could and could not do inside it,
7
- * without writing anything.
5
+ * `npx @auis/cli@latest my-product`. The other three work on an app that
6
+ * already exists: `doctor` reads it and writes nothing, `init` installs the
7
+ * Review Bridge into it, `uninstall` takes it back out.
8
8
  */
9
9
 
10
10
  import fs from "node:fs";
@@ -12,12 +12,16 @@ import { color, banner, fail, write } from "./ui.mjs";
12
12
  import { DEFAULT_REF, REPO_URL } from "./template.mjs";
13
13
  import { PACKAGE_MANAGERS, create } from "./create.mjs";
14
14
  import { doctor } from "./doctor.mjs";
15
+ import { ONLY, init, uninstall } from "./install.mjs";
15
16
 
16
17
  // Re-exported for the create-auis alias, which imports the package root.
17
18
  export { restoreCursorOnExit } from "./ui.mjs";
18
19
 
19
20
  const MIN_NODE_MAJOR = 20;
20
- const CREATE_ALIASES = new Set(["create", "init", "new"]);
21
+ // `init` used to be a third alias of create; since 0.3 it installs into an
22
+ // existing app instead.
23
+ const CREATE_ALIASES = new Set(["create", "new"]);
24
+ const COMMANDS = new Set(["doctor", "init", "uninstall"]);
21
25
 
22
26
  export const version = JSON.parse(
23
27
  fs.readFileSync(new URL("../package.json", import.meta.url), "utf8"),
@@ -34,15 +38,17 @@ export function parseArgs(argv) {
34
38
  git: true,
35
39
  force: false,
36
40
  yes: false,
41
+ dryRun: false,
42
+ only: undefined,
43
+ purge: false,
37
44
  help: false,
38
45
  version: false,
39
46
  };
40
47
 
41
48
  // `auis my-app`, `auis create my-app` and `auis new my-app` are the same call.
42
49
  const rest = [...argv];
43
- if (rest[0] === "doctor") {
44
- options.command = "doctor";
45
- rest.shift();
50
+ if (COMMANDS.has(rest[0])) {
51
+ options.command = rest.shift();
46
52
  } else if (CREATE_ALIASES.has(rest[0])) {
47
53
  rest.shift();
48
54
  }
@@ -69,6 +75,16 @@ export function parseArgs(argv) {
69
75
  case "--json":
70
76
  options.json = true;
71
77
  break;
78
+ case "--dry-run":
79
+ options.dryRun = true;
80
+ break;
81
+ case "--purge":
82
+ options.purge = true;
83
+ break;
84
+ case "--only":
85
+ options.only = rest.shift();
86
+ if (!options.only) throw new Error(`--only needs a value (${ONLY.join(", ")})`);
87
+ break;
72
88
  case "--no-install":
73
89
  case "--skip-install":
74
90
  options.install = false;
@@ -95,6 +111,10 @@ export function parseArgs(argv) {
95
111
  options.ref = arg.slice(arg.indexOf("=") + 1);
96
112
  break;
97
113
  }
114
+ if (arg.startsWith("--only=")) {
115
+ options.only = arg.slice(7);
116
+ break;
117
+ }
98
118
  if (arg.startsWith("--pm=")) {
99
119
  options.packageManager = arg.slice(5);
100
120
  if (!PACKAGE_MANAGERS.includes(options.packageManager)) {
@@ -122,15 +142,21 @@ export function help() {
122
142
  write(` ${c.bold("Usage")}`);
123
143
  write(` npx @auis/cli@latest ${c.dim("[directory] [options]")} ${c.dim("scaffold a new project")}`);
124
144
  write(` npx @auis/cli@latest doctor ${c.dim("[directory]")} ${c.dim("read an existing repo, write nothing")}`);
145
+ write(` npx @auis/cli@latest init ${c.dim("[directory]")} ${c.dim("pick what to install into an existing Next.js app")}`);
146
+ write(` npx @auis/cli@latest uninstall ${c.dim("[directory]")} ${c.dim("take it back out, exactly")}`);
125
147
  write();
126
148
  write(` ${c.bold("Options")}`);
127
149
  write(` --json doctor only: the full report as JSON`);
150
+ write(` --only ${c.dim("<a,b>")} init only: install these, skip the menu ${c.dim(`(${ONLY.join(", ")}; review installs today)`)}`);
151
+ write(` --dry-run init only: print what it would touch, write nothing`);
152
+ write(` --purge uninstall only: delete the comments instead of moving them to the backups`);
128
153
  write(` -r, --ref ${c.dim("<ref>")} branch, tag or commit of the template ${c.dim(`(default: ${DEFAULT_REF})`)}`);
129
154
  write(` --pm ${c.dim("<manager>")} ${PACKAGE_MANAGERS.join(" | ")} ${c.dim("(default: detected)")}`);
130
- write(` --no-install skip dependency installation`);
155
+ write(` --no-install skip dependency installation (create, init, uninstall)`);
131
156
  write(` --no-git skip git init and the first commit`);
132
- write(` --force scaffold into a directory that is not empty`);
133
- write(` -y, --yes take the defaults, never prompt`);
157
+ write(` --force create: scaffold into a directory that is not empty`);
158
+ write(` uninstall: also remove files you changed since init`);
159
+ write(` -y, --yes take the defaults, never prompt ${c.dim("(init: every module that installs here)")}`);
134
160
  write(` -h, --help show this`);
135
161
  write(` -v, --version print the CLI version`);
136
162
  write();
@@ -138,6 +164,8 @@ export function help() {
138
164
  write(` npx @auis/cli@latest my-product`);
139
165
  write(` npx @auis/cli@latest . --no-install`);
140
166
  write(` npx @auis/cli@latest doctor`);
167
+ write(` npx @auis/cli@latest init --dry-run`);
168
+ write(` npx @auis/cli@latest init --only review --yes`);
141
169
  write();
142
170
  write(` ${c.dim(REPO_URL)}`);
143
171
  write();
@@ -174,5 +202,23 @@ export async function run(argv = []) {
174
202
  }
175
203
 
176
204
  banner(version);
205
+ if (options.command === "init") {
206
+ return init({
207
+ directory: options.directory ?? ".",
208
+ dryRun: options.dryRun,
209
+ install: options.install,
210
+ packageManager: options.packageManager,
211
+ only: options.only,
212
+ yes: options.yes,
213
+ });
214
+ }
215
+ if (options.command === "uninstall") {
216
+ return uninstall({
217
+ directory: options.directory ?? ".",
218
+ install: options.install,
219
+ purge: options.purge,
220
+ force: options.force,
221
+ });
222
+ }
177
223
  return create({ ...options, cliVersion: version });
178
224
  }
package/src/doctor.mjs CHANGED
@@ -16,6 +16,8 @@ import fs from "node:fs";
16
16
  import path from "node:path";
17
17
  import { color, write } from "./ui.mjs";
18
18
  import { detect, detectAgentFiles } from "./detect.mjs";
19
+ import { planInstall } from "./install.mjs";
20
+ import { moduleChoices } from "./modules.mjs";
19
21
 
20
22
  export const DOCTOR_VERSION = 1;
21
23
 
@@ -33,7 +35,10 @@ const unsupported = (id, because, remedy) => ({ id, verdict: "unsupported", beca
33
35
  */
34
36
  export function capabilities(d) {
35
37
  const out = [];
36
- const serverBacked = d.devServer.fileWriting;
38
+ // `auis init` mounts the bridge's server as a Next App Router route. Other
39
+ // frameworks can write files too, but there is no adapter for them yet, so
40
+ // promising a shared queue there would be promising something init won't do.
41
+ const serverBacked = d.devServer.fileWriting && d.framework.name === "next" && d.router.name === "app-router";
37
42
 
38
43
  // --- Review -------------------------------------------------------------
39
44
  out.push(supported("review.pins", "Pins anchor through plain DOM — no markup, no wrapper, no provider in your components."));
@@ -56,8 +61,10 @@ export function capabilities(d) {
56
61
  } else {
57
62
  const why = d.framework.name === "unknown"
58
63
  ? "No JavaScript framework detected, so there is no dev server for Auis to mount routes on."
59
- : `${d.framework.name}${d.router.name === "pages-router" ? " on the Pages Router" : ""} gives Auis no file-writing route to persist through.`;
60
- out.push(degraded("review.persistence", why, "Comments live in each reviewer's browser; Export/Import moves them. A standalone server for a shared queue is planned; it does not exist yet."));
64
+ : d.devServer.fileWriting && d.framework.name !== "next"
65
+ ? `${d.framework.name} could serve the bridge, but its adapter does not exist yet — init installs into the Next.js App Router only.`
66
+ : `${d.framework.name}${d.router.name === "pages-router" ? " on the Pages Router" : ""} gives Auis no file-writing route to persist through.`;
67
+ out.push(degraded("review.persistence", why, "Comments live in each reviewer's browser; Export/Import moves them. Adapters for Vite, Express and Hono are planned; they do not exist yet."));
61
68
  out.push(degraded("review.mentions", why, "Mentions are recorded locally but no agent can read the queue until a server backs it."));
62
69
  out.push(unsupported("skills.bridges", why, "The bridge skills read a queue over HTTP; without one they have nothing to read."));
63
70
  }
@@ -166,27 +173,37 @@ export function collisions(root) {
166
173
  return out;
167
174
  }
168
175
 
169
- /** Exactly what `auis init` would touch. Same code path, so the two cannot drift. */
176
+ /**
177
+ * Exactly what `auis init` would touch — the plan init itself carries out
178
+ * (install.mjs), so the two cannot drift. Empty when init cannot install here.
179
+ */
170
180
  export function installPlan(d, root = ".") {
171
- const steps = [];
172
- if (d.framework.name === "next" && d.router.name === "app-router") {
173
- // The router detection already resolved which of the two roots is real;
174
- // reuse it rather than testing the CLI's own working directory.
175
- const base = d.rootLayout.path?.startsWith("src/") || fs.existsSync(path.join(root, "src/app"))
176
- ? "src/app"
177
- : "app";
178
- steps.push({ action: "create", path: `${base}/api/auis/[...auis]/route.ts`, detail: "6 lines — re-exports the bridge handlers" });
179
- }
180
- steps.push({ action: "create", path: ".auis/manifest.json", detail: "what auis wrote, so update and uninstall can reverse it" });
181
- steps.push({ action: "create", path: ".auis/data/", detail: "the comment and edit queues" });
182
- if (d.rootLayout.path && d.rootLayout.patchable) {
183
- steps.push({ action: "edit", path: d.rootLayout.path, detail: "+2 lines — one import, one <AuisBuilder /> before </body>" });
184
- } else if (d.rootLayout.path) {
185
- steps.push({ action: "print", path: d.rootLayout.path, detail: `${d.rootLayout.bodies} <body> tags — auis prints the two lines for you to place` });
186
- }
187
- steps.push({ action: "append", path: ".gitignore", detail: "2 lines, in a delimited block" });
188
- steps.push({ action: "edit", path: "package.json", detail: "+1 dependency" });
189
- return steps;
181
+ return planInstall(d, root).steps.map(({ action, path, detail }) => ({ action, path, detail }));
182
+ }
183
+
184
+ /**
185
+ * The verdicts say what Auis can do in this repository; `init` installs only
186
+ * part of it today. Which rows it actually brings, so nobody reads "edit.text
187
+ * supported" as "init gives me Edit Mode".
188
+ */
189
+ export const INSTALLED_BY_INIT = /^review\./;
190
+
191
+ function installable(plan, caps) {
192
+ return {
193
+ ok: plan.ok,
194
+ reason: plan.reason ?? null,
195
+ capabilities: plan.ok ? caps.filter((c) => INSTALLED_BY_INIT.test(c.id)).map((c) => c.id) : [],
196
+ };
197
+ }
198
+
199
+ /** The menu `auis init` would show here: every module, and whether it can go in. */
200
+ function modulesFor(plan) {
201
+ return moduleChoices({ planOk: plan.ok, planReason: plan.reason }).map(({ id, label, selectable, note }) => ({
202
+ id,
203
+ label,
204
+ installable: selectable,
205
+ reason: note,
206
+ }));
190
207
  }
191
208
 
192
209
  export function buildReport(root, cliVersion) {
@@ -203,6 +220,8 @@ export function buildReport(root, cliVersion) {
203
220
  collisions: collisions(root),
204
221
  capabilities: caps,
205
222
  plan: installPlan(d, root),
223
+ installable: installable(planInstall(d, root), caps),
224
+ modules: modulesFor(planInstall(d, root)),
206
225
  summary,
207
226
  };
208
227
  }
@@ -258,7 +277,7 @@ export function report(doc) {
258
277
 
259
278
  if (doc.collisions.length > 0) {
260
279
  write();
261
- write(` ${color.bold("Already yours")} ${color.dim("auis will not overwrite any of these")}`);
280
+ write(` ${color.bold("Already yours")} ${color.dim("init does not touch any of these; the notes say how a future skills install would")}`);
262
281
  write();
263
282
  for (const c of doc.collisions) {
264
283
  write(` ${color.cyan(c.path.padEnd(20))}${color.dim(c.note)}`);
@@ -266,13 +285,26 @@ export function report(doc) {
266
285
  }
267
286
 
268
287
  write();
269
- write(` ${color.bold("What installing would touch")} ${color.dim(`${doc.plan.length} places`)}`);
288
+ write(` ${color.bold("Modules")} ${color.dim("what `auis init` offers in this repository")}`);
270
289
  write();
271
- for (const step of doc.plan) {
272
- write(` ${color.dim(step.action.padEnd(8))}${step.path.padEnd(34)}${color.dim(step.detail)}`);
290
+ for (const m of doc.modules) {
291
+ const mark = m.installable ? color.green("✓") : color.dim("·");
292
+ write(` ${mark} ${(m.installable ? color.bold : color.dim)(m.label.padEnd(14))}${m.installable ? color.dim("installs with `auis init`") : color.dim(m.reason)}`);
273
293
  }
294
+
274
295
  write();
275
- write(` ${color.dim("There is no `auis init` yet — this is the footprint it will have.")}`);
296
+ if (doc.installable.ok) {
297
+ write(` ${color.bold("What `auis init` would touch")} ${color.dim(`${doc.plan.length} places`)}`);
298
+ write();
299
+ for (const step of doc.plan) {
300
+ write(` ${color.dim(step.action.padEnd(8))}${step.path.padEnd(44)}${color.dim(step.detail)}`);
301
+ }
302
+ write();
303
+ write(` ${color.dim("Pick what to install with `npx @auis/cli init`; `npx @auis/cli uninstall` reverses it.")}`);
304
+ write(` ${color.dim("Every module runs today in a project created with `npx @auis/cli <dir>`.")}`);
305
+ } else {
306
+ write(` ${color.bold("auis init")} ${color.dim(doc.installable.reason)}`);
307
+ }
276
308
 
277
309
  write();
278
310
  write(` ${color.dim("Nothing was written — doctor only reads.")}`);
@@ -0,0 +1,626 @@
1
+ /**
2
+ * `auis init` and `auis uninstall` — the Review Bridge, installed into a
3
+ * repository that is not Auis's, and taken back out.
4
+ *
5
+ * `init` writes a handful of touch points and records every one of them in
6
+ * `.auis/manifest.json`:
7
+ *
8
+ * - one route file: app/api/review-bridge/[...path]/route.ts
9
+ * - the root layout: one import and one <AuisReview /> before </body>
10
+ * - package.json: one dependency (@auis/next)
11
+ * - the lockfile: whatever the package manager's install changes
12
+ * - .gitignore: a delimited block
13
+ * - .auis/: the manifest, the original bytes of every file it
14
+ * edited, and data/ (the comment queue)
15
+ *
16
+ * It never overwrites a file it did not create, and it never touches AGENTS.md,
17
+ * .mcp.json, globals.css, tsconfig.json or components.json.
18
+ *
19
+ * `uninstall` reads the manifest and reverses it. A file that still has the
20
+ * bytes `init` left gets its original bytes back, exactly. A file the user
21
+ * changed since gets a surgical removal of only what `init` inserted. A file
22
+ * `init` created and the user edited is kept, with a warning. The comments are
23
+ * moved into the project's backup folder, never deleted (unless --purge).
24
+ *
25
+ * The plan is computed once, by `planInstall()`; `doctor` prints the same plan,
26
+ * so the footprint `doctor` promises is the footprint `init` has.
27
+ */
28
+
29
+ import crypto from "node:crypto";
30
+ import fs from "node:fs";
31
+ import os from "node:os";
32
+ import path from "node:path";
33
+ import { color, fail, pickMany, step, warn, write } from "./ui.mjs";
34
+ import { detect } from "./detect.mjs";
35
+ import { exec } from "./template.mjs";
36
+ import {
37
+ MODULE_IDS,
38
+ initialPicker,
39
+ moduleChoices,
40
+ pickedIds,
41
+ pickerReducer,
42
+ resolveOnly,
43
+ } from "./modules.mjs";
44
+
45
+ /** The kit version `init` writes. Kept equal to kit/next/package.json by a test. */
46
+ export const KIT_VERSION = "0.2.0";
47
+ export const KIT_PACKAGE = "@auis/next";
48
+ export const MANIFEST_VERSION = 1;
49
+
50
+ export const AUIS_DIR = ".auis";
51
+ export const MANIFEST = `${AUIS_DIR}/manifest.json`;
52
+ export const DATA_DIR = `${AUIS_DIR}/data`;
53
+ const ORIGINALS = `${AUIS_DIR}/originals`;
54
+
55
+ const BLOCK_START = "# >>> auis — written by `auis init`, removed by `auis uninstall`";
56
+ const BLOCK_END = "# <<< auis";
57
+ const BLOCK_LINES = [BLOCK_START, `/${DATA_DIR}/`, `/${ORIGINALS}/`, BLOCK_END];
58
+
59
+ const LOCKFILES = {
60
+ npm: ["package-lock.json"],
61
+ pnpm: ["pnpm-lock.yaml"],
62
+ yarn: ["yarn.lock"],
63
+ bun: ["bun.lock", "bun.lockb"],
64
+ };
65
+
66
+ /** Every module `--only` names; which of them install today is in modules.mjs. */
67
+ export const ONLY = MODULE_IDS;
68
+
69
+ const sha = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
70
+ const abs = (root, rel) => path.join(root, rel);
71
+ const readMaybe = (file) => (fs.existsSync(file) ? fs.readFileSync(file) : null);
72
+
73
+ // ---------------------------------------------------------------------------
74
+ // What gets written
75
+ // ---------------------------------------------------------------------------
76
+
77
+ export function routeSource() {
78
+ return `// Auis Review Bridge — written by \`auis init\`, removed by \`auis uninstall\`.
79
+ // Every /api/review-bridge/* request (pins, comments, the drawer) is answered
80
+ // by @auis/server. Comments live in .auis/data (gitignored).
81
+ import { createReviewRoute } from "@auis/next"
82
+
83
+ // Next reads these two statically, so they stay literal here.
84
+ export const runtime = "nodejs"
85
+ export const dynamic = "force-dynamic"
86
+
87
+ const route = createReviewRoute({ dataDir: ".auis/data" })
88
+ export const GET = route.GET
89
+ export const POST = route.POST
90
+ export const PUT = route.PUT
91
+ export const PATCH = route.PATCH
92
+ export const DELETE = route.DELETE
93
+ `;
94
+ }
95
+
96
+ const IMPORT_SPEC = "@auis/next/client";
97
+ const ELEMENT = "<AuisReview />";
98
+
99
+ /**
100
+ * The layout with the import after its last top-level import and the element
101
+ * before `</body>`, in the file's own quote and semicolon style. Returns null
102
+ * when there is not exactly one `</body>` to aim at.
103
+ */
104
+ export function patchLayout(source) {
105
+ if ((source.match(/<\/body>/g) ?? []).length !== 1) return null;
106
+
107
+ const imports = [...source.matchAll(/^import\b[\s\S]*?(["'])[^"'\n]+\1;?[ \t]*$/gm)];
108
+ const last = imports.at(-1);
109
+ const quote = last ? last[1] : '"';
110
+ const semi = last ? /;[ \t]*$/.test(last[0]) : true;
111
+ const importLine = `import { AuisReview } from ${quote}${IMPORT_SPEC}${quote}${semi ? ";" : ""}`;
112
+
113
+ let out;
114
+ let at;
115
+ if (last) {
116
+ at = last.index + last[0].length;
117
+ out = `${source.slice(0, at)}\n${importLine}${source.slice(at)}`;
118
+ } else {
119
+ // No imports: after a leading "use …" directive, if there is one.
120
+ const directive = source.match(/^(["'])use [a-z]+\1;?[ \t]*\n/);
121
+ at = directive ? directive[0].length : 0;
122
+ out = `${source.slice(0, at)}${importLine}\n${source.slice(at)}`;
123
+ }
124
+
125
+ const close = out.indexOf("</body>");
126
+ const lineStart = out.lastIndexOf("\n", close - 1) + 1;
127
+ const before = out.slice(lineStart, close);
128
+ let elementLine;
129
+ if (/^[ \t]*$/.test(before)) {
130
+ // `</body>` on its own line: one line above it, one indent deeper.
131
+ const unit = before.includes("\t") ? "\t" : " ";
132
+ elementLine = `${before}${unit}${ELEMENT}`;
133
+ out = `${out.slice(0, lineStart)}${elementLine}\n${out.slice(lineStart)}`;
134
+ } else {
135
+ elementLine = null; // inline: `<body>{children}</body>`
136
+ out = `${out.slice(0, close)}${ELEMENT}${out.slice(close)}`;
137
+ }
138
+ return { source: out, importLine, elementLine };
139
+ }
140
+
141
+ /** Takes out exactly what patchLayout put in, wherever the user moved it since. */
142
+ export function unpatchLayout(source, { importLine, elementLine }) {
143
+ let out = source;
144
+ const dropLine = (text, line) => {
145
+ const lines = text.split("\n");
146
+ const i = lines.findIndex((l) => l.trim() === line.trim());
147
+ if (i === -1) return null;
148
+ lines.splice(i, 1);
149
+ return lines.join("\n");
150
+ };
151
+ const a = dropLine(out, importLine);
152
+ if (a !== null) out = a;
153
+ if (elementLine) {
154
+ const b = dropLine(out, elementLine);
155
+ if (b !== null) out = b;
156
+ } else if (out.includes(`${ELEMENT}</body>`)) {
157
+ out = out.replace(`${ELEMENT}</body>`, "</body>");
158
+ }
159
+ return out;
160
+ }
161
+
162
+ function indentOf(json) {
163
+ const m = json.match(/^[ \t]+(?=")/m);
164
+ return m ? m[0] : " ";
165
+ }
166
+
167
+ /** package.json with the kit added to `dependencies`, keys kept sorted. */
168
+ export function addDependency(source, name, range) {
169
+ const pkg = JSON.parse(source);
170
+ const deps = { ...(pkg.dependencies ?? {}), [name]: range };
171
+ pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b)));
172
+ return `${JSON.stringify(pkg, null, indentOf(source))}\n`;
173
+ }
174
+
175
+ export function removeDependency(source, name) {
176
+ const pkg = JSON.parse(source);
177
+ if (pkg.dependencies?.[name] === undefined) return source;
178
+ delete pkg.dependencies[name];
179
+ if (Object.keys(pkg.dependencies).length === 0) delete pkg.dependencies;
180
+ return `${JSON.stringify(pkg, null, indentOf(source))}\n`;
181
+ }
182
+
183
+ export function addGitignoreBlock(source) {
184
+ if (source.includes(BLOCK_START)) return source;
185
+ const sep = source.length === 0 || source.endsWith("\n") ? "" : "\n";
186
+ const gap = source.length === 0 ? "" : "\n";
187
+ return `${source}${sep}${gap}${BLOCK_LINES.join("\n")}\n`;
188
+ }
189
+
190
+ export function removeGitignoreBlock(source) {
191
+ const start = source.indexOf(BLOCK_START);
192
+ if (start === -1) return source;
193
+ const endMark = source.indexOf(BLOCK_END, start);
194
+ if (endMark === -1) return source;
195
+ let end = endMark + BLOCK_END.length;
196
+ if (source[end] === "\n") end++;
197
+ let begin = start;
198
+ // The blank line init put before the block goes with it.
199
+ if (begin >= 2 && source.slice(begin - 2, begin) === "\n\n") begin--;
200
+ return source.slice(0, begin) + source.slice(end);
201
+ }
202
+
203
+ // ---------------------------------------------------------------------------
204
+ // The plan — shared with `doctor`
205
+ // ---------------------------------------------------------------------------
206
+
207
+ /**
208
+ * What `init` would do in `root`, given doctor's detections. `{ ok: false }`
209
+ * with a reason when it cannot install there; otherwise the steps, each with
210
+ * enough detail for doctor to print and for init to carry out.
211
+ */
212
+ export function planInstall(d, root, { packageManager } = {}) {
213
+ if (d.framework.name !== "next" || d.router.name !== "app-router") {
214
+ const found = d.framework.name === "unknown"
215
+ ? "no JavaScript framework"
216
+ : `${d.framework.name}${d.router.name === "pages-router" ? " on the Pages Router" : ""}`;
217
+ return {
218
+ ok: false,
219
+ reason: `auis init installs into a Next.js App Router app today; this is ${found}.`,
220
+ steps: [],
221
+ };
222
+ }
223
+ if (d.react.major !== null && d.react.major < 18) {
224
+ return { ok: false, reason: `React ${d.react.major} is below the 18 the review chrome needs.`, steps: [] };
225
+ }
226
+
227
+ const base = d.rootLayout.path?.startsWith("src/") ? "src/app" : "app";
228
+ const ts = fs.existsSync(abs(root, "tsconfig.json"));
229
+ const route = `${base}/api/review-bridge/[...path]/route.${ts ? "ts" : "js"}`;
230
+ const pm = packageManager ?? d.packageManager.name;
231
+ const lockfile = (LOCKFILES[pm] ?? []).find((f) => fs.existsSync(abs(root, f))) ?? LOCKFILES[pm]?.[0] ?? null;
232
+
233
+ const steps = [];
234
+ steps.push({ action: "create", kind: "file", path: route, detail: `${routeSource().split("\n").length - 1} lines — the bridge's catch-all route` });
235
+ if (d.rootLayout.path && d.rootLayout.patchable) {
236
+ steps.push({ action: "edit", kind: "layout", path: d.rootLayout.path, detail: "+2 lines — one import, one <AuisReview /> before </body>" });
237
+ } else if (d.rootLayout.path) {
238
+ steps.push({ action: "print", kind: "layout", path: d.rootLayout.path, detail: `${d.rootLayout.bodies} <body> tags — auis prints the two lines for you to place` });
239
+ }
240
+ steps.push({ action: "edit", kind: "dependency", path: "package.json", detail: `+1 dependency — ${KIT_PACKAGE}@^${KIT_VERSION}` });
241
+ if (lockfile) {
242
+ steps.push({ action: "edit", kind: "lockfile", path: lockfile, detail: `${pm} install` });
243
+ }
244
+ steps.push({ action: fs.existsSync(abs(root, ".gitignore")) ? "append" : "create", kind: "block", path: ".gitignore", detail: `${BLOCK_LINES.length} lines, in a delimited block` });
245
+ steps.push({ action: "create", kind: "manifest", path: MANIFEST, detail: "what auis wrote, so uninstall can reverse it" });
246
+ steps.push({ action: "create", kind: "data", path: `${DATA_DIR}/`, detail: "the comment queue (gitignored)" });
247
+ return { ok: true, route, base, packageManager: pm, lockfile, steps };
248
+ }
249
+
250
+ // ---------------------------------------------------------------------------
251
+ // init
252
+ // ---------------------------------------------------------------------------
253
+
254
+ function saveOriginal(root, rel, bytes) {
255
+ const file = abs(root, path.join(ORIGINALS, rel));
256
+ fs.mkdirSync(path.dirname(file), { recursive: true });
257
+ fs.writeFileSync(file, bytes);
258
+ return `${ORIGINALS}/${rel}`;
259
+ }
260
+
261
+ function printPlan(plan) {
262
+ write();
263
+ write(` ${color.bold("What init touches")} ${color.dim(`${plan.steps.length} places`)}`);
264
+ write();
265
+ for (const s of plan.steps) {
266
+ write(` ${color.dim(s.action.padEnd(8))}${s.path.padEnd(44)}${color.dim(s.detail)}`);
267
+ }
268
+ write();
269
+ }
270
+
271
+ /** Directories `mkdir -p` would create for `rel`, outermost first. */
272
+ function missingDirs(root, rel) {
273
+ const out = [];
274
+ let dir = path.dirname(rel);
275
+ while (dir !== "." && dir !== "/" && !fs.existsSync(abs(root, dir))) {
276
+ out.unshift(dir);
277
+ dir = path.dirname(dir);
278
+ }
279
+ return out;
280
+ }
281
+
282
+ export async function init({
283
+ directory = ".",
284
+ dryRun = false,
285
+ install = true,
286
+ packageManager,
287
+ only,
288
+ yes = false,
289
+ kitRange = `^${KIT_VERSION}`,
290
+ pick = pickMany,
291
+ } = {}) {
292
+ const root = path.resolve(directory);
293
+ if (!fs.existsSync(abs(root, "package.json"))) {
294
+ fail(
295
+ `${root} has no package.json.\n ${color.bold("auis init")} installs the Review Bridge into an existing app. ` +
296
+ `To start a new Auis project, run ${color.bold(`npx @auis/cli@latest ${directory === "." ? "my-product" : directory}`)}.`,
297
+ );
298
+ return 1;
299
+ }
300
+ const existing = readManifest(root);
301
+ if (existing) {
302
+ write(` ${color.green("✓")} Already installed ${color.dim(`(${MANIFEST}, ${existing.createdAt})`)} — nothing to do.`);
303
+ write(` ${color.dim("To start over: npx @auis/cli uninstall, then init again.")}`);
304
+ write();
305
+ return 0;
306
+ }
307
+
308
+ const d = detect(root);
309
+ const plan = planInstall(d, root, { packageManager });
310
+
311
+ // What to install: `--only`, else the menu (a TTY without --yes), else every
312
+ // module that can go in here. Today that is Review alone; the menu still
313
+ // lists the rest, each with the reason it cannot be picked yet.
314
+ const choices = moduleChoices({ planOk: plan.ok, planReason: plan.reason });
315
+ let modules;
316
+ if (only !== undefined) {
317
+ const resolved = resolveOnly(only, choices);
318
+ if (!resolved.ok) {
319
+ fail(`${resolved.message}\n Run ${color.bold("npx @auis/cli doctor")} for what Auis can do here.`);
320
+ return 1;
321
+ }
322
+ modules = resolved.ids;
323
+ } else {
324
+ const canPick = choices.some((c) => c.selectable);
325
+ const picked = canPick && !yes ? await pick("What should auis install?", choices, { initialPicker, pickerReducer }) : null;
326
+ if (picked?.cancelled) {
327
+ write();
328
+ write(` ${color.dim("Nothing was installed.")}`);
329
+ write();
330
+ return 0;
331
+ }
332
+ modules = picked ? pickedIds(picked) : choices.filter((c) => c.selectable).map((c) => c.id);
333
+ if (picked) write();
334
+ }
335
+
336
+ if (!plan.ok) {
337
+ fail(`${plan.reason}\n Run ${color.bold("npx @auis/cli doctor")} for what Auis can still do here.`);
338
+ return 1;
339
+ }
340
+ if (fs.existsSync(abs(root, plan.route)) || fs.existsSync(abs(root, path.dirname(path.dirname(plan.route))))) {
341
+ fail(`${path.dirname(path.dirname(plan.route))} already exists. auis init does not overwrite routes it did not write.`);
342
+ return 1;
343
+ }
344
+
345
+ printPlan(plan);
346
+ if (dryRun) {
347
+ write(` ${color.dim("Dry run — nothing was written.")}`);
348
+ write();
349
+ return 0;
350
+ }
351
+
352
+ const artifacts = [];
353
+
354
+ // 1. The route.
355
+ const createdDirs = missingDirs(root, plan.route);
356
+ fs.mkdirSync(path.dirname(abs(root, plan.route)), { recursive: true });
357
+ const routeBytes = Buffer.from(routeSource());
358
+ fs.writeFileSync(abs(root, plan.route), routeBytes);
359
+ artifacts.push({ kind: "file", path: plan.route, sha256: sha(routeBytes), createdDirs });
360
+ step("route", plan.route);
361
+
362
+ // 2. The layout.
363
+ let printed = null;
364
+ const layoutStep = plan.steps.find((s) => s.kind === "layout");
365
+ if (layoutStep?.action === "edit") {
366
+ const before = fs.readFileSync(abs(root, layoutStep.path));
367
+ const patched = patchLayout(before.toString("utf8"));
368
+ if (patched) {
369
+ fs.writeFileSync(abs(root, layoutStep.path), patched.source);
370
+ artifacts.push({
371
+ kind: "layout",
372
+ path: layoutStep.path,
373
+ importLine: patched.importLine,
374
+ elementLine: patched.elementLine,
375
+ before: sha(before),
376
+ after: sha(Buffer.from(patched.source)),
377
+ original: saveOriginal(root, layoutStep.path, before),
378
+ });
379
+ step("layout", `${layoutStep.path} ${color.dim("+ import, + <AuisReview />")}`);
380
+ } else {
381
+ printed = layoutStep.path;
382
+ }
383
+ } else if (layoutStep) {
384
+ printed = layoutStep.path;
385
+ }
386
+
387
+ // 3. package.json, then the install that updates the lockfile.
388
+ const pkgBefore = fs.readFileSync(abs(root, "package.json"));
389
+ fs.writeFileSync(abs(root, "package.json"), addDependency(pkgBefore.toString("utf8"), KIT_PACKAGE, kitRange));
390
+ const lockBefore = plan.lockfile ? readMaybe(abs(root, plan.lockfile)) : null;
391
+ let installed = false;
392
+ if (install) {
393
+ const { ok, stderr } = await exec(plan.packageManager, ["install"], { cwd: root, inherit: true });
394
+ if (!ok) {
395
+ warn(`${plan.packageManager} install failed${stderr ? `: ${stderr}` : ""} — the files are written; run it yourself.`);
396
+ } else {
397
+ installed = true;
398
+ }
399
+ }
400
+ const pkgAfter = fs.readFileSync(abs(root, "package.json"));
401
+ artifacts.push({
402
+ kind: "dependency",
403
+ path: "package.json",
404
+ name: KIT_PACKAGE,
405
+ range: kitRange,
406
+ before: sha(pkgBefore),
407
+ after: sha(pkgAfter),
408
+ original: saveOriginal(root, "package.json", pkgBefore),
409
+ });
410
+ step("package", `${KIT_PACKAGE}@${kitRange}${installed ? color.dim(` · ${plan.packageManager} install`) : ""}`);
411
+ if (plan.lockfile) {
412
+ const lockAfter = readMaybe(abs(root, plan.lockfile));
413
+ if (lockAfter && (!lockBefore || !lockBefore.equals(lockAfter))) {
414
+ artifacts.push({
415
+ kind: "lockfile",
416
+ path: plan.lockfile,
417
+ before: lockBefore ? sha(lockBefore) : null,
418
+ after: sha(lockAfter),
419
+ original: lockBefore ? saveOriginal(root, plan.lockfile, lockBefore) : null,
420
+ });
421
+ }
422
+ }
423
+
424
+ // 4. .gitignore.
425
+ const ignoreBefore = readMaybe(abs(root, ".gitignore"));
426
+ const ignoreAfter = addGitignoreBlock(ignoreBefore?.toString("utf8") ?? "");
427
+ fs.writeFileSync(abs(root, ".gitignore"), ignoreAfter);
428
+ artifacts.push({
429
+ kind: "block",
430
+ path: ".gitignore",
431
+ created: ignoreBefore === null,
432
+ before: ignoreBefore ? sha(ignoreBefore) : null,
433
+ after: sha(Buffer.from(ignoreAfter)),
434
+ original: ignoreBefore ? saveOriginal(root, ".gitignore", ignoreBefore) : null,
435
+ });
436
+ step("gitignore", `/${DATA_DIR}/, /${ORIGINALS}/`);
437
+
438
+ // 5. The data folder, and the manifest last: it exists only for a finished init.
439
+ fs.mkdirSync(abs(root, DATA_DIR), { recursive: true });
440
+ artifacts.push({ kind: "data", path: DATA_DIR });
441
+ const manifest = {
442
+ auisManifestVersion: MANIFEST_VERSION,
443
+ createdAt: new Date().toISOString(),
444
+ only: modules,
445
+ kit: { package: KIT_PACKAGE, range: kitRange },
446
+ packageManager: plan.packageManager,
447
+ artifacts,
448
+ };
449
+ fs.writeFileSync(abs(root, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
450
+ step("manifest", MANIFEST);
451
+
452
+ write();
453
+ if (printed) {
454
+ warn(`${printed} has more than one <body>, so auis did not edit it. Add these two lines yourself:`);
455
+ write();
456
+ write(` import { AuisReview } from "${IMPORT_SPEC}"`);
457
+ write(` ${ELEMENT} ${color.dim("← just before </body>")}`);
458
+ write();
459
+ }
460
+ write(` ${color.bold("Review is installed.")} Start your dev server, then open Review with the pill at the bottom of the page or ${color.bold("⌘⇧Y")} ${color.dim("(Ctrl+Shift+Y)")}.`);
461
+ write(` ${color.dim("Comments live in .auis/data. Agents read them at /api/review-bridge.")}`);
462
+ write(` ${color.dim("To take it all back out: npx @auis/cli uninstall")}`);
463
+ write();
464
+ return 0;
465
+ }
466
+
467
+ // ---------------------------------------------------------------------------
468
+ // uninstall
469
+ // ---------------------------------------------------------------------------
470
+
471
+ export function readManifest(root) {
472
+ try {
473
+ return JSON.parse(fs.readFileSync(abs(root, MANIFEST), "utf8"));
474
+ } catch {
475
+ return null;
476
+ }
477
+ }
478
+
479
+ /** Same key the bridge uses for this project's backups (kit/server config.ts). */
480
+ export function projectBackupDir(root) {
481
+ let cwd = root;
482
+ try {
483
+ cwd = fs.realpathSync(root);
484
+ } catch {
485
+ /* keep the given path */
486
+ }
487
+ const key = crypto.createHash("sha256").update(cwd).digest("hex").slice(0, 16);
488
+ return path.join(os.homedir(), ".auis", "review-bridge-backups", key);
489
+ }
490
+
491
+ function removeEmptyDirs(root, dirs) {
492
+ for (const dir of [...dirs].reverse()) {
493
+ try {
494
+ fs.rmdirSync(abs(root, dir));
495
+ } catch {
496
+ /* not empty or already gone: someone else's now */
497
+ }
498
+ }
499
+ }
500
+
501
+ /**
502
+ * Reverse one edited file: its original bytes when it is exactly as init left
503
+ * it, otherwise `surgical(current)`. Returns what happened, for the report.
504
+ */
505
+ function restore(root, artifact, surgical) {
506
+ const file = abs(root, artifact.path);
507
+ const current = readMaybe(file);
508
+ if (current === null) return "missing";
509
+ const original = artifact.original ? readMaybe(abs(root, artifact.original)) : null;
510
+ if (sha(current) === artifact.after && original) {
511
+ fs.writeFileSync(file, original);
512
+ return "restored";
513
+ }
514
+ const next = surgical(current.toString("utf8"));
515
+ if (next === current.toString("utf8")) return "untouched";
516
+ fs.writeFileSync(file, next);
517
+ return "edited";
518
+ }
519
+
520
+ export async function uninstall({ directory = ".", install = true, purge = false, force = false } = {}) {
521
+ const root = path.resolve(directory);
522
+ const manifest = readManifest(root);
523
+ if (!manifest) {
524
+ fail(`No ${MANIFEST} in ${root} — auis was not installed here by \`auis init\`, so there is nothing to reverse.`);
525
+ return 1;
526
+ }
527
+
528
+ let needsInstall = false;
529
+ let kept = 0;
530
+ for (const a of [...manifest.artifacts].reverse()) {
531
+ switch (a.kind) {
532
+ case "file": {
533
+ const current = readMaybe(abs(root, a.path));
534
+ if (current === null) {
535
+ step("route", `${a.path} ${color.dim("already gone")}`);
536
+ } else if (sha(current) === a.sha256 || force) {
537
+ fs.rmSync(abs(root, a.path));
538
+ removeEmptyDirs(root, a.createdDirs ?? []);
539
+ step("route", `${a.path} ${color.dim("removed")}`);
540
+ } else {
541
+ kept++;
542
+ warn(`${a.path} changed since init — kept. Delete it yourself, or run uninstall --force.`);
543
+ }
544
+ break;
545
+ }
546
+ case "layout": {
547
+ const how = restore(root, a, (src) => unpatchLayout(src, a));
548
+ step("layout", `${a.path} ${color.dim(how)}`);
549
+ break;
550
+ }
551
+ case "dependency": {
552
+ const how = restore(root, a, (src) => removeDependency(src, a.name));
553
+ if (how === "edited") needsInstall = true;
554
+ step("package", `${a.name} ${color.dim(how === "restored" ? "removed" : how)}`);
555
+ break;
556
+ }
557
+ case "lockfile": {
558
+ const current = readMaybe(abs(root, a.path));
559
+ if (current && sha(current) === a.after) {
560
+ if (a.original) fs.writeFileSync(abs(root, a.path), readMaybe(abs(root, a.original)));
561
+ else fs.rmSync(abs(root, a.path));
562
+ step("lockfile", `${a.path} ${color.dim("restored")}`);
563
+ } else {
564
+ needsInstall = true;
565
+ }
566
+ break;
567
+ }
568
+ case "block": {
569
+ const current = readMaybe(abs(root, a.path));
570
+ if (a.created && current && sha(current) === a.after) {
571
+ fs.rmSync(abs(root, a.path));
572
+ step("gitignore", color.dim("removed (auis created it)"));
573
+ } else {
574
+ const how = restore(root, a, removeGitignoreBlock);
575
+ step("gitignore", color.dim(how));
576
+ }
577
+ break;
578
+ }
579
+ case "data": {
580
+ const data = abs(root, a.path);
581
+ if (!fs.existsSync(data)) break;
582
+ if (purge) {
583
+ fs.rmSync(data, { recursive: true, force: true });
584
+ step("data", `${a.path} ${color.dim("deleted (--purge)")}`);
585
+ } else if (fs.readdirSync(data).length === 0) {
586
+ fs.rmdirSync(data);
587
+ } else {
588
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
589
+ const dest = path.join(projectBackupDir(root), `uninstalled-${stamp}`);
590
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
591
+ fs.cpSync(data, dest, { recursive: true });
592
+ fs.rmSync(data, { recursive: true, force: true });
593
+ step("data", `${a.path} ${color.dim(`moved to ${dest}`)}`);
594
+ }
595
+ break;
596
+ }
597
+ default:
598
+ break;
599
+ }
600
+ }
601
+
602
+ if (needsInstall && install) {
603
+ const pm = manifest.packageManager ?? "npm";
604
+ const { ok } = await exec(pm, ["install"], { cwd: root, inherit: true });
605
+ if (ok) step("lockfile", color.dim(`${pm} install`));
606
+ else warn(`${pm} install failed — run it yourself to drop ${manifest.kit?.package ?? KIT_PACKAGE} from the lockfile.`);
607
+ }
608
+
609
+ // The manifest and the saved originals go last, and .auis with them if empty.
610
+ fs.rmSync(abs(root, ORIGINALS), { recursive: true, force: true });
611
+ if (kept === 0) fs.rmSync(abs(root, MANIFEST), { force: true });
612
+ try {
613
+ fs.rmdirSync(abs(root, AUIS_DIR));
614
+ } catch {
615
+ /* something of the user's is still in there */
616
+ }
617
+
618
+ write();
619
+ if (kept > 0) {
620
+ write(` ${color.yellow("!")} Uninstalled, except ${kept} file${kept === 1 ? "" : "s"} you changed. ${MANIFEST} stays until you deal with ${kept === 1 ? "it" : "them"}.`);
621
+ } else {
622
+ write(` ${color.bold("Review is uninstalled.")} ${color.dim("node_modules may still hold the packages until your next install.")}`);
623
+ }
624
+ write();
625
+ return 0;
626
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * What `auis init` can install into an existing app, one module per thing a
3
+ * person would pick. Only `installable` modules can be chosen; the others are
4
+ * listed with the reason they cannot be yet, so the menu tells the truth about
5
+ * what Auis does today instead of hiding the rest.
6
+ *
7
+ * Whether an installable module can go into THIS repository is a second
8
+ * question, answered by the install plan (`planInstall`, the same one `doctor`
9
+ * prints): `moduleChoices` folds that answer in.
10
+ */
11
+
12
+ export const MODULES = [
13
+ {
14
+ id: "review",
15
+ label: "Review",
16
+ summary: "pins, comments, the drawer and agent mentions",
17
+ status: "installable",
18
+ },
19
+ {
20
+ id: "states",
21
+ label: "State Mode",
22
+ summary: "switch a screen's states in place, and ?ge= deep links that replay clicks",
23
+ status: "planned",
24
+ reason: "it is not packaged for an existing app yet, and it needs a registry of your screens",
25
+ },
26
+ {
27
+ id: "edit",
28
+ label: "Edit Mode",
29
+ summary: "visual edits an agent turns into code",
30
+ status: "planned",
31
+ reason: "it is not packaged yet, and it needs a map of your components and tokens",
32
+ },
33
+ {
34
+ id: "styleguide",
35
+ label: "Styleguide",
36
+ summary: "a living page of your own components and tokens",
37
+ status: "planned",
38
+ reason: "it has to document your components, not Auis's, and that scanner does not exist yet",
39
+ },
40
+ {
41
+ id: "flows",
42
+ label: "UX Flows",
43
+ summary: "navigable flow diagrams that are pages in your app",
44
+ status: "planned",
45
+ reason: "it is not packaged for an existing app yet",
46
+ },
47
+ ];
48
+
49
+ export const MODULE_IDS = MODULES.map((m) => m.id);
50
+
51
+ /**
52
+ * The menu rows for this repository. A module is selectable when it is
53
+ * installable AND the install plan works here; otherwise the row says why.
54
+ * The default selection is every selectable module.
55
+ */
56
+ export function moduleChoices({ planOk = true, planReason = null } = {}) {
57
+ return MODULES.map((m) => {
58
+ if (m.status !== "installable") {
59
+ return { id: m.id, label: m.label, summary: m.summary, selectable: false, checked: false, note: m.reason };
60
+ }
61
+ if (!planOk) {
62
+ return { id: m.id, label: m.label, summary: m.summary, selectable: false, checked: false, note: planReason };
63
+ }
64
+ return { id: m.id, label: m.label, summary: m.summary, selectable: true, checked: true, note: null };
65
+ });
66
+ }
67
+
68
+ /**
69
+ * `--only review` or `--only review,states`: the ids, in catalog order, or the
70
+ * reason the list cannot be installed. An unknown id names the valid ones; a
71
+ * known one that cannot be installed says why.
72
+ */
73
+ export function resolveOnly(value, choices) {
74
+ const asked = String(value ?? "")
75
+ .split(",")
76
+ .map((s) => s.trim().toLowerCase())
77
+ .filter(Boolean);
78
+ if (asked.length === 0) return { ok: false, message: `--only needs a module: ${MODULE_IDS.join(", ")}` };
79
+ const unknown = asked.filter((id) => !MODULE_IDS.includes(id));
80
+ if (unknown.length > 0) {
81
+ return { ok: false, message: `--only ${unknown.join(", ")}: unknown module. Modules: ${MODULE_IDS.join(", ")}` };
82
+ }
83
+ for (const id of asked) {
84
+ const row = choices.find((c) => c.id === id);
85
+ if (!row.selectable) return { ok: false, message: `${row.label} cannot be installed here: ${row.note}.` };
86
+ }
87
+ return { ok: true, ids: MODULE_IDS.filter((id) => asked.includes(id)) };
88
+ }
89
+
90
+ /**
91
+ * The picker's state machine, with no terminal in it so it can be tested.
92
+ * Keys: "up", "down", "space" (toggle), "all" (a: toggle every selectable),
93
+ * "enter" (confirm; refused with nothing selected), "cancel" (Esc, Ctrl-C).
94
+ */
95
+ export function initialPicker(rows) {
96
+ const first = rows.findIndex((r) => r.selectable);
97
+ return {
98
+ rows,
99
+ cursor: first === -1 ? 0 : first,
100
+ checked: rows.filter((r) => r.checked).map((r) => r.id),
101
+ done: false,
102
+ cancelled: false,
103
+ hint: null,
104
+ };
105
+ }
106
+
107
+ export function pickerReducer(state, key) {
108
+ if (state.done || state.cancelled) return state;
109
+ const { rows } = state;
110
+ const selectable = rows.filter((r) => r.selectable).map((r) => r.id);
111
+ switch (key) {
112
+ case "up":
113
+ return { ...state, cursor: (state.cursor - 1 + rows.length) % rows.length, hint: null };
114
+ case "down":
115
+ return { ...state, cursor: (state.cursor + 1) % rows.length, hint: null };
116
+ case "space": {
117
+ const row = rows[state.cursor];
118
+ if (!row.selectable) return { ...state, hint: `${row.label}: ${row.note}` };
119
+ const on = state.checked.includes(row.id);
120
+ return {
121
+ ...state,
122
+ checked: on ? state.checked.filter((id) => id !== row.id) : [...state.checked, row.id],
123
+ hint: null,
124
+ };
125
+ }
126
+ case "all": {
127
+ const allOn = selectable.every((id) => state.checked.includes(id));
128
+ return { ...state, checked: allOn ? [] : selectable, hint: null };
129
+ }
130
+ case "enter":
131
+ if (state.checked.length === 0) return { ...state, hint: "Pick at least one module, or press Esc to leave." };
132
+ return { ...state, done: true, hint: null };
133
+ case "cancel":
134
+ return { ...state, cancelled: true };
135
+ default:
136
+ return state;
137
+ }
138
+ }
139
+
140
+ /** The ids a finished picker chose, in catalog order. */
141
+ export function pickedIds(state) {
142
+ return MODULE_IDS.filter((id) => state.checked.includes(id));
143
+ }
package/src/ui.mjs CHANGED
@@ -82,3 +82,64 @@ export async function ask(question, fallback) {
82
82
  rl.close();
83
83
  }
84
84
  }
85
+
86
+ /**
87
+ * A checkbox menu in the terminal: ↑/↓ to move, space to toggle, a for all,
88
+ * enter to confirm, Esc to leave. Rows that cannot be picked stay visible,
89
+ * dimmed, with their reason. Resolves to the finished picker state (see
90
+ * modules.mjs), or null when stdin is not a TTY.
91
+ */
92
+ export async function pickMany(title, rows, { initialPicker, pickerReducer }) {
93
+ if (!process.stdin.isTTY || !process.stdout.isTTY) return null;
94
+ const readline = await import("node:readline");
95
+ let state = initialPicker(rows);
96
+ let drawn = 0;
97
+
98
+ const render = () => {
99
+ if (drawn > 0) process.stdout.write(`${ESC}[${drawn}A${ESC}[0J`);
100
+ const lines = [` ${color.bold(title)} ${color.dim("↑↓ move · space toggle · a all · enter install · esc cancel")}`, ""];
101
+ const width = Math.max(...state.rows.map((r) => r.label.length)) + 2;
102
+ state.rows.forEach((row, i) => {
103
+ const pointer = i === state.cursor ? color.cyan("❯") : " ";
104
+ const box = row.selectable ? (state.checked.includes(row.id) ? color.green("◉") : "◯") : color.dim("◯");
105
+ const label = row.selectable ? color.bold(row.label.padEnd(width)) : color.dim(row.label.padEnd(width));
106
+ lines.push(` ${pointer} ${box} ${label}${color.dim(row.summary)}`);
107
+ if (!row.selectable) lines.push(` ${" ".repeat(width)}${color.dim(row.note)}`);
108
+ });
109
+ lines.push("", state.hint ? ` ${color.yellow("!")} ${state.hint}` : "");
110
+ process.stdout.write(`${lines.join("\n")}\n`);
111
+ drawn = lines.length;
112
+ };
113
+
114
+ readline.emitKeypressEvents(process.stdin);
115
+ process.stdin.setRawMode(true);
116
+ process.stdout.write(`${ESC}[?25l`);
117
+ render();
118
+ try {
119
+ return await new Promise((resolve) => {
120
+ const onKey = (_str, key = {}) => {
121
+ const name =
122
+ key.ctrl && key.name === "c" ? "cancel"
123
+ : key.name === "escape" ? "cancel"
124
+ : key.name === "return" ? "enter"
125
+ : key.name === "space" ? "space"
126
+ : key.name === "up" || key.name === "k" ? "up"
127
+ : key.name === "down" || key.name === "j" ? "down"
128
+ : key.name === "a" ? "all"
129
+ : null;
130
+ if (!name) return;
131
+ state = pickerReducer(state, name);
132
+ render();
133
+ if (state.done || state.cancelled) {
134
+ process.stdin.off("keypress", onKey);
135
+ resolve(state);
136
+ }
137
+ };
138
+ process.stdin.on("keypress", onKey);
139
+ });
140
+ } finally {
141
+ process.stdin.setRawMode(false);
142
+ process.stdin.pause();
143
+ process.stdout.write(`${ESC}[?25h`);
144
+ }
145
+ }