@auis/cli 0.2.2 → 0.3.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,56 @@ 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` installs **Review** — pins, comments,
53
+ the drawer and the agent mentions — and nothing else:
54
+
55
+ ```bash
56
+ npx @auis/cli@latest init --dry-run # print what it would touch
57
+ npx @auis/cli@latest init
58
+ ```
59
+
60
+ ```
61
+ What init touches 7 places
62
+
63
+ create app/api/review-bridge/[...path]/route.ts 15 lines — the bridge's catch-all route
64
+ edit app/layout.tsx +2 lines — one import, one <AuisReview /> before </body>
65
+ edit package.json +1 dependency — @auis/next@^0.1.0
66
+ edit package-lock.json npm install
67
+ append .gitignore 4 lines, in a delimited block
68
+ create .auis/manifest.json what auis wrote, so uninstall can reverse it
69
+ create .auis/data/ the comment queue (gitignored)
70
+ ```
71
+
72
+ Then start your dev server and open Review from the pill at the bottom of the
73
+ page, or with ⌘⇧Y (Ctrl+Shift+Y). The review chrome carries its own scoped
74
+ styles and fonts, so your pages render exactly as before.
75
+
76
+ `init` never overwrites a file it did not create, and never touches `AGENTS.md`,
77
+ `.mcp.json`, `globals.css`, `tsconfig.json` or `components.json`. When the root
78
+ layout has more than one `<body>`, it prints the two lines for you to place
79
+ instead of guessing. Running it twice changes nothing.
80
+
81
+ ```bash
82
+ npx @auis/cli@latest uninstall
83
+ ```
84
+
85
+ `uninstall` reads `.auis/manifest.json` and reverses it: a file you have not
86
+ touched since gets its original bytes back; a file you changed loses only what
87
+ `init` inserted; a route you edited is kept, with a warning (`--force` removes
88
+ it). Your comments are moved to `~/.auis/review-bridge-backups/<project>/`, not
89
+ deleted (`--purge` deletes them).
90
+
91
+ Agent mentions (`@Claude`, `@Grok` in a comment) open the agent's CLI on your
92
+ machine when the dev server runs with `AUIS_MENTION_TRIGGER=1` (Claude starts
93
+ switched on with the `edit` ceiling; change it with
94
+ `PUT /api/review-bridge/agent-settings` — the Agents panel is Auis-only today). The runner
95
+ ships with `@auis/server`; a `.auis/mention-prompt.md` replaces the prompt it
96
+ gives the agent.
97
+
98
+ Edit Mode, State Mode and the flow driver are not installable into an existing
99
+ 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
100
  planned; it does not exist yet.
55
101
 
56
102
  ## Options
@@ -58,13 +104,19 @@ planned; it does not exist yet.
58
104
  ```
59
105
  npx @auis/cli@latest [directory] [options] scaffold a new project
60
106
  npx @auis/cli@latest doctor [directory] read an existing repo, write nothing
107
+ npx @auis/cli@latest init [directory] install Review into an existing Next.js app
108
+ npx @auis/cli@latest uninstall [directory] take it back out, exactly
61
109
 
62
110
  --json doctor only: the full report as JSON
111
+ --only <what> init only: what to install (review; the default)
112
+ --dry-run init only: print what it would touch, write nothing
113
+ --purge uninstall only: delete the comments instead of moving them to the backups
63
114
  -r, --ref <ref> branch, tag or commit of the template (default: main)
64
115
  --pm <manager> npm | pnpm | yarn | bun (default: detected)
65
- --no-install skip dependency installation
116
+ --no-install skip dependency installation (create, init, uninstall)
66
117
  --no-git skip git init and the first commit
67
- --force scaffold into a directory that is not empty
118
+ --force create: scaffold into a directory that is not empty
119
+ uninstall: also remove files you changed since init
68
120
  -y, --yes take the defaults, never prompt
69
121
  -h, --help show usage
70
122
  -v, --version print the CLI version
@@ -78,10 +130,18 @@ npx @auis/cli@latest . # current directory
78
130
  npx @auis/cli@latest my-product --pm pnpm --no-git
79
131
  npx @auis/cli@latest my-product --ref v1.0.0
80
132
  npx @auis/cli@latest doctor # what Auis can do in the current repo, writes nothing
133
+ npx @auis/cli@latest init # install Review into the current Next.js app
134
+ npx @auis/cli@latest uninstall # and take it back out
81
135
  ```
82
136
 
137
+ Up to 0.2.x, `init` was a third name for creating a project. Since 0.3.0 it
138
+ installs into an existing app; use `create` or `new` (or no command) to
139
+ scaffold.
140
+
83
141
  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.
142
+ falling back to `git clone --depth 1`. The CLI itself has zero dependencies;
143
+ `init` adds `@auis/next` (and through it `@auis/server`, `@auis/ui` and
144
+ `@auis/core`) to the app it installs into.
85
145
 
86
146
  ## What the scaffold changes
87
147
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auis/cli",
3
- "version": "0.2.2",
3
+ "version": "0.3.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: "review",
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,14 +142,20 @@ 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("install Review 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("<what>")} init only: what to install ${c.dim(`(${ONLY.join(", ")}; the default)`)}`);
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`);
157
+ write(` --force create: scaffold into a directory that is not empty`);
158
+ write(` uninstall: also remove files you changed since init`);
133
159
  write(` -y, --yes take the defaults, never prompt`);
134
160
  write(` -h, --help show this`);
135
161
  write(` -v, --version print the CLI version`);
@@ -138,6 +164,7 @@ 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`);
141
168
  write();
142
169
  write(` ${c.dim(REPO_URL)}`);
143
170
  write();
@@ -174,5 +201,22 @@ export async function run(argv = []) {
174
201
  }
175
202
 
176
203
  banner(version);
204
+ if (options.command === "init") {
205
+ return init({
206
+ directory: options.directory ?? ".",
207
+ dryRun: options.dryRun,
208
+ install: options.install,
209
+ packageManager: options.packageManager,
210
+ only: options.only,
211
+ });
212
+ }
213
+ if (options.command === "uninstall") {
214
+ return uninstall({
215
+ directory: options.directory ?? ".",
216
+ install: options.install,
217
+ purge: options.purge,
218
+ force: options.force,
219
+ });
220
+ }
177
221
  return create({ ...options, cliVersion: version });
178
222
  }
package/src/doctor.mjs CHANGED
@@ -16,6 +16,7 @@ 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";
19
20
 
20
21
  export const DOCTOR_VERSION = 1;
21
22
 
@@ -33,7 +34,10 @@ const unsupported = (id, because, remedy) => ({ id, verdict: "unsupported", beca
33
34
  */
34
35
  export function capabilities(d) {
35
36
  const out = [];
36
- const serverBacked = d.devServer.fileWriting;
37
+ // `auis init` mounts the bridge's server as a Next App Router route. Other
38
+ // frameworks can write files too, but there is no adapter for them yet, so
39
+ // promising a shared queue there would be promising something init won't do.
40
+ const serverBacked = d.devServer.fileWriting && d.framework.name === "next" && d.router.name === "app-router";
37
41
 
38
42
  // --- Review -------------------------------------------------------------
39
43
  out.push(supported("review.pins", "Pins anchor through plain DOM — no markup, no wrapper, no provider in your components."));
@@ -56,8 +60,10 @@ export function capabilities(d) {
56
60
  } else {
57
61
  const why = d.framework.name === "unknown"
58
62
  ? "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."));
63
+ : d.devServer.fileWriting && d.framework.name !== "next"
64
+ ? `${d.framework.name} could serve the bridge, but its adapter does not exist yet — init installs into the Next.js App Router only.`
65
+ : `${d.framework.name}${d.router.name === "pages-router" ? " on the Pages Router" : ""} gives Auis no file-writing route to persist through.`;
66
+ 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
67
  out.push(degraded("review.mentions", why, "Mentions are recorded locally but no agent can read the queue until a server backs it."));
62
68
  out.push(unsupported("skills.bridges", why, "The bridge skills read a queue over HTTP; without one they have nothing to read."));
63
69
  }
@@ -166,27 +172,27 @@ export function collisions(root) {
166
172
  return out;
167
173
  }
168
174
 
169
- /** Exactly what `auis init` would touch. Same code path, so the two cannot drift. */
175
+ /**
176
+ * Exactly what `auis init` would touch — the plan init itself carries out
177
+ * (install.mjs), so the two cannot drift. Empty when init cannot install here.
178
+ */
170
179
  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;
180
+ return planInstall(d, root).steps.map(({ action, path, detail }) => ({ action, path, detail }));
181
+ }
182
+
183
+ /**
184
+ * The verdicts say what Auis can do in this repository; `init` installs only
185
+ * part of it today. Which rows it actually brings, so nobody reads "edit.text
186
+ * supported" as "init gives me Edit Mode".
187
+ */
188
+ export const INSTALLED_BY_INIT = /^review\./;
189
+
190
+ function installable(plan, caps) {
191
+ return {
192
+ ok: plan.ok,
193
+ reason: plan.reason ?? null,
194
+ capabilities: plan.ok ? caps.filter((c) => INSTALLED_BY_INIT.test(c.id)).map((c) => c.id) : [],
195
+ };
190
196
  }
191
197
 
192
198
  export function buildReport(root, cliVersion) {
@@ -203,6 +209,7 @@ export function buildReport(root, cliVersion) {
203
209
  collisions: collisions(root),
204
210
  capabilities: caps,
205
211
  plan: installPlan(d, root),
212
+ installable: installable(planInstall(d, root), caps),
206
213
  summary,
207
214
  };
208
215
  }
@@ -258,7 +265,7 @@ export function report(doc) {
258
265
 
259
266
  if (doc.collisions.length > 0) {
260
267
  write();
261
- write(` ${color.bold("Already yours")} ${color.dim("auis will not overwrite any of these")}`);
268
+ write(` ${color.bold("Already yours")} ${color.dim("init does not touch any of these; the notes say how a future skills install would")}`);
262
269
  write();
263
270
  for (const c of doc.collisions) {
264
271
  write(` ${color.cyan(c.path.padEnd(20))}${color.dim(c.note)}`);
@@ -266,13 +273,19 @@ export function report(doc) {
266
273
  }
267
274
 
268
275
  write();
269
- write(` ${color.bold("What installing would touch")} ${color.dim(`${doc.plan.length} places`)}`);
270
- write();
271
- for (const step of doc.plan) {
272
- write(` ${color.dim(step.action.padEnd(8))}${step.path.padEnd(34)}${color.dim(step.detail)}`);
276
+ if (doc.installable.ok) {
277
+ write(` ${color.bold("What `auis init` would touch")} ${color.dim(`${doc.plan.length} places`)}`);
278
+ write();
279
+ for (const step of doc.plan) {
280
+ write(` ${color.dim(step.action.padEnd(8))}${step.path.padEnd(44)}${color.dim(step.detail)}`);
281
+ }
282
+ write();
283
+ write(` ${color.dim("Install Review with `npx @auis/cli init`; `npx @auis/cli uninstall` reverses it.")}`);
284
+ write(` ${color.dim("init brings the review.* rows above. Edit, flows, State Mode and the skills run in a project")}`);
285
+ write(` ${color.dim("created with `npx @auis/cli <dir>`; they are not installable into an existing app yet.")}`);
286
+ } else {
287
+ write(` ${color.bold("auis init")} ${color.dim(doc.installable.reason)}`);
273
288
  }
274
- write();
275
- write(` ${color.dim("There is no `auis init` yet — this is the footprint it will have.")}`);
276
289
 
277
290
  write();
278
291
  write(` ${color.dim("Nothing was written — doctor only reads.")}`);
@@ -0,0 +1,594 @@
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, step, warn, write } from "./ui.mjs";
34
+ import { detect } from "./detect.mjs";
35
+ import { exec } from "./template.mjs";
36
+
37
+ /** The kit version `init` writes. Kept equal to kit/next/package.json by a test. */
38
+ export const KIT_VERSION = "0.1.0";
39
+ export const KIT_PACKAGE = "@auis/next";
40
+ export const MANIFEST_VERSION = 1;
41
+
42
+ export const AUIS_DIR = ".auis";
43
+ export const MANIFEST = `${AUIS_DIR}/manifest.json`;
44
+ export const DATA_DIR = `${AUIS_DIR}/data`;
45
+ const ORIGINALS = `${AUIS_DIR}/originals`;
46
+
47
+ const BLOCK_START = "# >>> auis — written by `auis init`, removed by `auis uninstall`";
48
+ const BLOCK_END = "# <<< auis";
49
+ const BLOCK_LINES = [BLOCK_START, `/${DATA_DIR}/`, `/${ORIGINALS}/`, BLOCK_END];
50
+
51
+ const LOCKFILES = {
52
+ npm: ["package-lock.json"],
53
+ pnpm: ["pnpm-lock.yaml"],
54
+ yarn: ["yarn.lock"],
55
+ bun: ["bun.lock", "bun.lockb"],
56
+ };
57
+
58
+ export const ONLY = ["review"];
59
+
60
+ const sha = (buf) => crypto.createHash("sha256").update(buf).digest("hex");
61
+ const abs = (root, rel) => path.join(root, rel);
62
+ const readMaybe = (file) => (fs.existsSync(file) ? fs.readFileSync(file) : null);
63
+
64
+ // ---------------------------------------------------------------------------
65
+ // What gets written
66
+ // ---------------------------------------------------------------------------
67
+
68
+ export function routeSource() {
69
+ return `// Auis Review Bridge — written by \`auis init\`, removed by \`auis uninstall\`.
70
+ // Every /api/review-bridge/* request (pins, comments, the drawer) is answered
71
+ // by @auis/server. Comments live in .auis/data (gitignored).
72
+ import { createReviewRoute } from "@auis/next"
73
+
74
+ // Next reads these two statically, so they stay literal here.
75
+ export const runtime = "nodejs"
76
+ export const dynamic = "force-dynamic"
77
+
78
+ const route = createReviewRoute({ dataDir: ".auis/data" })
79
+ export const GET = route.GET
80
+ export const POST = route.POST
81
+ export const PUT = route.PUT
82
+ export const PATCH = route.PATCH
83
+ export const DELETE = route.DELETE
84
+ `;
85
+ }
86
+
87
+ const IMPORT_SPEC = "@auis/next/client";
88
+ const ELEMENT = "<AuisReview />";
89
+
90
+ /**
91
+ * The layout with the import after its last top-level import and the element
92
+ * before `</body>`, in the file's own quote and semicolon style. Returns null
93
+ * when there is not exactly one `</body>` to aim at.
94
+ */
95
+ export function patchLayout(source) {
96
+ if ((source.match(/<\/body>/g) ?? []).length !== 1) return null;
97
+
98
+ const imports = [...source.matchAll(/^import\b[\s\S]*?(["'])[^"'\n]+\1;?[ \t]*$/gm)];
99
+ const last = imports.at(-1);
100
+ const quote = last ? last[1] : '"';
101
+ const semi = last ? /;[ \t]*$/.test(last[0]) : true;
102
+ const importLine = `import { AuisReview } from ${quote}${IMPORT_SPEC}${quote}${semi ? ";" : ""}`;
103
+
104
+ let out;
105
+ let at;
106
+ if (last) {
107
+ at = last.index + last[0].length;
108
+ out = `${source.slice(0, at)}\n${importLine}${source.slice(at)}`;
109
+ } else {
110
+ // No imports: after a leading "use …" directive, if there is one.
111
+ const directive = source.match(/^(["'])use [a-z]+\1;?[ \t]*\n/);
112
+ at = directive ? directive[0].length : 0;
113
+ out = `${source.slice(0, at)}${importLine}\n${source.slice(at)}`;
114
+ }
115
+
116
+ const close = out.indexOf("</body>");
117
+ const lineStart = out.lastIndexOf("\n", close - 1) + 1;
118
+ const before = out.slice(lineStart, close);
119
+ let elementLine;
120
+ if (/^[ \t]*$/.test(before)) {
121
+ // `</body>` on its own line: one line above it, one indent deeper.
122
+ const unit = before.includes("\t") ? "\t" : " ";
123
+ elementLine = `${before}${unit}${ELEMENT}`;
124
+ out = `${out.slice(0, lineStart)}${elementLine}\n${out.slice(lineStart)}`;
125
+ } else {
126
+ elementLine = null; // inline: `<body>{children}</body>`
127
+ out = `${out.slice(0, close)}${ELEMENT}${out.slice(close)}`;
128
+ }
129
+ return { source: out, importLine, elementLine };
130
+ }
131
+
132
+ /** Takes out exactly what patchLayout put in, wherever the user moved it since. */
133
+ export function unpatchLayout(source, { importLine, elementLine }) {
134
+ let out = source;
135
+ const dropLine = (text, line) => {
136
+ const lines = text.split("\n");
137
+ const i = lines.findIndex((l) => l.trim() === line.trim());
138
+ if (i === -1) return null;
139
+ lines.splice(i, 1);
140
+ return lines.join("\n");
141
+ };
142
+ const a = dropLine(out, importLine);
143
+ if (a !== null) out = a;
144
+ if (elementLine) {
145
+ const b = dropLine(out, elementLine);
146
+ if (b !== null) out = b;
147
+ } else if (out.includes(`${ELEMENT}</body>`)) {
148
+ out = out.replace(`${ELEMENT}</body>`, "</body>");
149
+ }
150
+ return out;
151
+ }
152
+
153
+ function indentOf(json) {
154
+ const m = json.match(/^[ \t]+(?=")/m);
155
+ return m ? m[0] : " ";
156
+ }
157
+
158
+ /** package.json with the kit added to `dependencies`, keys kept sorted. */
159
+ export function addDependency(source, name, range) {
160
+ const pkg = JSON.parse(source);
161
+ const deps = { ...(pkg.dependencies ?? {}), [name]: range };
162
+ pkg.dependencies = Object.fromEntries(Object.entries(deps).sort(([a], [b]) => a.localeCompare(b)));
163
+ return `${JSON.stringify(pkg, null, indentOf(source))}\n`;
164
+ }
165
+
166
+ export function removeDependency(source, name) {
167
+ const pkg = JSON.parse(source);
168
+ if (pkg.dependencies?.[name] === undefined) return source;
169
+ delete pkg.dependencies[name];
170
+ if (Object.keys(pkg.dependencies).length === 0) delete pkg.dependencies;
171
+ return `${JSON.stringify(pkg, null, indentOf(source))}\n`;
172
+ }
173
+
174
+ export function addGitignoreBlock(source) {
175
+ if (source.includes(BLOCK_START)) return source;
176
+ const sep = source.length === 0 || source.endsWith("\n") ? "" : "\n";
177
+ const gap = source.length === 0 ? "" : "\n";
178
+ return `${source}${sep}${gap}${BLOCK_LINES.join("\n")}\n`;
179
+ }
180
+
181
+ export function removeGitignoreBlock(source) {
182
+ const start = source.indexOf(BLOCK_START);
183
+ if (start === -1) return source;
184
+ const endMark = source.indexOf(BLOCK_END, start);
185
+ if (endMark === -1) return source;
186
+ let end = endMark + BLOCK_END.length;
187
+ if (source[end] === "\n") end++;
188
+ let begin = start;
189
+ // The blank line init put before the block goes with it.
190
+ if (begin >= 2 && source.slice(begin - 2, begin) === "\n\n") begin--;
191
+ return source.slice(0, begin) + source.slice(end);
192
+ }
193
+
194
+ // ---------------------------------------------------------------------------
195
+ // The plan — shared with `doctor`
196
+ // ---------------------------------------------------------------------------
197
+
198
+ /**
199
+ * What `init` would do in `root`, given doctor's detections. `{ ok: false }`
200
+ * with a reason when it cannot install there; otherwise the steps, each with
201
+ * enough detail for doctor to print and for init to carry out.
202
+ */
203
+ export function planInstall(d, root, { packageManager } = {}) {
204
+ if (d.framework.name !== "next" || d.router.name !== "app-router") {
205
+ const found = d.framework.name === "unknown"
206
+ ? "no JavaScript framework"
207
+ : `${d.framework.name}${d.router.name === "pages-router" ? " on the Pages Router" : ""}`;
208
+ return {
209
+ ok: false,
210
+ reason: `auis init installs into a Next.js App Router app today; this is ${found}.`,
211
+ steps: [],
212
+ };
213
+ }
214
+ if (d.react.major !== null && d.react.major < 18) {
215
+ return { ok: false, reason: `React ${d.react.major} is below the 18 the review chrome needs.`, steps: [] };
216
+ }
217
+
218
+ const base = d.rootLayout.path?.startsWith("src/") ? "src/app" : "app";
219
+ const ts = fs.existsSync(abs(root, "tsconfig.json"));
220
+ const route = `${base}/api/review-bridge/[...path]/route.${ts ? "ts" : "js"}`;
221
+ const pm = packageManager ?? d.packageManager.name;
222
+ const lockfile = (LOCKFILES[pm] ?? []).find((f) => fs.existsSync(abs(root, f))) ?? LOCKFILES[pm]?.[0] ?? null;
223
+
224
+ const steps = [];
225
+ steps.push({ action: "create", kind: "file", path: route, detail: `${routeSource().split("\n").length - 1} lines — the bridge's catch-all route` });
226
+ if (d.rootLayout.path && d.rootLayout.patchable) {
227
+ steps.push({ action: "edit", kind: "layout", path: d.rootLayout.path, detail: "+2 lines — one import, one <AuisReview /> before </body>" });
228
+ } else if (d.rootLayout.path) {
229
+ 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` });
230
+ }
231
+ steps.push({ action: "edit", kind: "dependency", path: "package.json", detail: `+1 dependency — ${KIT_PACKAGE}@^${KIT_VERSION}` });
232
+ if (lockfile) {
233
+ steps.push({ action: "edit", kind: "lockfile", path: lockfile, detail: `${pm} install` });
234
+ }
235
+ steps.push({ action: fs.existsSync(abs(root, ".gitignore")) ? "append" : "create", kind: "block", path: ".gitignore", detail: `${BLOCK_LINES.length} lines, in a delimited block` });
236
+ steps.push({ action: "create", kind: "manifest", path: MANIFEST, detail: "what auis wrote, so uninstall can reverse it" });
237
+ steps.push({ action: "create", kind: "data", path: `${DATA_DIR}/`, detail: "the comment queue (gitignored)" });
238
+ return { ok: true, route, base, packageManager: pm, lockfile, steps };
239
+ }
240
+
241
+ // ---------------------------------------------------------------------------
242
+ // init
243
+ // ---------------------------------------------------------------------------
244
+
245
+ function saveOriginal(root, rel, bytes) {
246
+ const file = abs(root, path.join(ORIGINALS, rel));
247
+ fs.mkdirSync(path.dirname(file), { recursive: true });
248
+ fs.writeFileSync(file, bytes);
249
+ return `${ORIGINALS}/${rel}`;
250
+ }
251
+
252
+ function printPlan(plan) {
253
+ write();
254
+ write(` ${color.bold("What init touches")} ${color.dim(`${plan.steps.length} places`)}`);
255
+ write();
256
+ for (const s of plan.steps) {
257
+ write(` ${color.dim(s.action.padEnd(8))}${s.path.padEnd(44)}${color.dim(s.detail)}`);
258
+ }
259
+ write();
260
+ }
261
+
262
+ /** Directories `mkdir -p` would create for `rel`, outermost first. */
263
+ function missingDirs(root, rel) {
264
+ const out = [];
265
+ let dir = path.dirname(rel);
266
+ while (dir !== "." && dir !== "/" && !fs.existsSync(abs(root, dir))) {
267
+ out.unshift(dir);
268
+ dir = path.dirname(dir);
269
+ }
270
+ return out;
271
+ }
272
+
273
+ export async function init({
274
+ directory = ".",
275
+ dryRun = false,
276
+ install = true,
277
+ packageManager,
278
+ only = "review",
279
+ kitRange = `^${KIT_VERSION}`,
280
+ } = {}) {
281
+ const root = path.resolve(directory);
282
+ if (!fs.existsSync(abs(root, "package.json"))) {
283
+ fail(
284
+ `${root} has no package.json.\n ${color.bold("auis init")} installs the Review Bridge into an existing app. ` +
285
+ `To start a new Auis project, run ${color.bold(`npx @auis/cli@latest ${directory === "." ? "my-product" : directory}`)}.`,
286
+ );
287
+ return 1;
288
+ }
289
+ if (!ONLY.includes(only)) {
290
+ fail(`--only ${only}: only ${ONLY.join(", ")} can be installed into an existing app today.`);
291
+ return 1;
292
+ }
293
+
294
+ const existing = readManifest(root);
295
+ if (existing) {
296
+ write(` ${color.green("✓")} Already installed ${color.dim(`(${MANIFEST}, ${existing.createdAt})`)} — nothing to do.`);
297
+ write(` ${color.dim("To start over: npx @auis/cli uninstall, then init again.")}`);
298
+ write();
299
+ return 0;
300
+ }
301
+
302
+ const d = detect(root);
303
+ const plan = planInstall(d, root, { packageManager });
304
+ if (!plan.ok) {
305
+ fail(`${plan.reason}\n Run ${color.bold("npx @auis/cli doctor")} for what Auis can still do here.`);
306
+ return 1;
307
+ }
308
+ if (fs.existsSync(abs(root, plan.route)) || fs.existsSync(abs(root, path.dirname(path.dirname(plan.route))))) {
309
+ fail(`${path.dirname(path.dirname(plan.route))} already exists. auis init does not overwrite routes it did not write.`);
310
+ return 1;
311
+ }
312
+
313
+ printPlan(plan);
314
+ if (dryRun) {
315
+ write(` ${color.dim("Dry run — nothing was written.")}`);
316
+ write();
317
+ return 0;
318
+ }
319
+
320
+ const artifacts = [];
321
+
322
+ // 1. The route.
323
+ const createdDirs = missingDirs(root, plan.route);
324
+ fs.mkdirSync(path.dirname(abs(root, plan.route)), { recursive: true });
325
+ const routeBytes = Buffer.from(routeSource());
326
+ fs.writeFileSync(abs(root, plan.route), routeBytes);
327
+ artifacts.push({ kind: "file", path: plan.route, sha256: sha(routeBytes), createdDirs });
328
+ step("route", plan.route);
329
+
330
+ // 2. The layout.
331
+ let printed = null;
332
+ const layoutStep = plan.steps.find((s) => s.kind === "layout");
333
+ if (layoutStep?.action === "edit") {
334
+ const before = fs.readFileSync(abs(root, layoutStep.path));
335
+ const patched = patchLayout(before.toString("utf8"));
336
+ if (patched) {
337
+ fs.writeFileSync(abs(root, layoutStep.path), patched.source);
338
+ artifacts.push({
339
+ kind: "layout",
340
+ path: layoutStep.path,
341
+ importLine: patched.importLine,
342
+ elementLine: patched.elementLine,
343
+ before: sha(before),
344
+ after: sha(Buffer.from(patched.source)),
345
+ original: saveOriginal(root, layoutStep.path, before),
346
+ });
347
+ step("layout", `${layoutStep.path} ${color.dim("+ import, + <AuisReview />")}`);
348
+ } else {
349
+ printed = layoutStep.path;
350
+ }
351
+ } else if (layoutStep) {
352
+ printed = layoutStep.path;
353
+ }
354
+
355
+ // 3. package.json, then the install that updates the lockfile.
356
+ const pkgBefore = fs.readFileSync(abs(root, "package.json"));
357
+ fs.writeFileSync(abs(root, "package.json"), addDependency(pkgBefore.toString("utf8"), KIT_PACKAGE, kitRange));
358
+ const lockBefore = plan.lockfile ? readMaybe(abs(root, plan.lockfile)) : null;
359
+ let installed = false;
360
+ if (install) {
361
+ const { ok, stderr } = await exec(plan.packageManager, ["install"], { cwd: root, inherit: true });
362
+ if (!ok) {
363
+ warn(`${plan.packageManager} install failed${stderr ? `: ${stderr}` : ""} — the files are written; run it yourself.`);
364
+ } else {
365
+ installed = true;
366
+ }
367
+ }
368
+ const pkgAfter = fs.readFileSync(abs(root, "package.json"));
369
+ artifacts.push({
370
+ kind: "dependency",
371
+ path: "package.json",
372
+ name: KIT_PACKAGE,
373
+ range: kitRange,
374
+ before: sha(pkgBefore),
375
+ after: sha(pkgAfter),
376
+ original: saveOriginal(root, "package.json", pkgBefore),
377
+ });
378
+ step("package", `${KIT_PACKAGE}@${kitRange}${installed ? color.dim(` · ${plan.packageManager} install`) : ""}`);
379
+ if (plan.lockfile) {
380
+ const lockAfter = readMaybe(abs(root, plan.lockfile));
381
+ if (lockAfter && (!lockBefore || !lockBefore.equals(lockAfter))) {
382
+ artifacts.push({
383
+ kind: "lockfile",
384
+ path: plan.lockfile,
385
+ before: lockBefore ? sha(lockBefore) : null,
386
+ after: sha(lockAfter),
387
+ original: lockBefore ? saveOriginal(root, plan.lockfile, lockBefore) : null,
388
+ });
389
+ }
390
+ }
391
+
392
+ // 4. .gitignore.
393
+ const ignoreBefore = readMaybe(abs(root, ".gitignore"));
394
+ const ignoreAfter = addGitignoreBlock(ignoreBefore?.toString("utf8") ?? "");
395
+ fs.writeFileSync(abs(root, ".gitignore"), ignoreAfter);
396
+ artifacts.push({
397
+ kind: "block",
398
+ path: ".gitignore",
399
+ created: ignoreBefore === null,
400
+ before: ignoreBefore ? sha(ignoreBefore) : null,
401
+ after: sha(Buffer.from(ignoreAfter)),
402
+ original: ignoreBefore ? saveOriginal(root, ".gitignore", ignoreBefore) : null,
403
+ });
404
+ step("gitignore", `/${DATA_DIR}/, /${ORIGINALS}/`);
405
+
406
+ // 5. The data folder, and the manifest last: it exists only for a finished init.
407
+ fs.mkdirSync(abs(root, DATA_DIR), { recursive: true });
408
+ artifacts.push({ kind: "data", path: DATA_DIR });
409
+ const manifest = {
410
+ auisManifestVersion: MANIFEST_VERSION,
411
+ createdAt: new Date().toISOString(),
412
+ only: [only],
413
+ kit: { package: KIT_PACKAGE, range: kitRange },
414
+ packageManager: plan.packageManager,
415
+ artifacts,
416
+ };
417
+ fs.writeFileSync(abs(root, MANIFEST), `${JSON.stringify(manifest, null, 2)}\n`);
418
+ step("manifest", MANIFEST);
419
+
420
+ write();
421
+ if (printed) {
422
+ warn(`${printed} has more than one <body>, so auis did not edit it. Add these two lines yourself:`);
423
+ write();
424
+ write(` import { AuisReview } from "${IMPORT_SPEC}"`);
425
+ write(` ${ELEMENT} ${color.dim("← just before </body>")}`);
426
+ write();
427
+ }
428
+ 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)")}.`);
429
+ write(` ${color.dim("Comments live in .auis/data. Agents read them at /api/review-bridge.")}`);
430
+ write(` ${color.dim("To take it all back out: npx @auis/cli uninstall")}`);
431
+ write();
432
+ return 0;
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // uninstall
437
+ // ---------------------------------------------------------------------------
438
+
439
+ export function readManifest(root) {
440
+ try {
441
+ return JSON.parse(fs.readFileSync(abs(root, MANIFEST), "utf8"));
442
+ } catch {
443
+ return null;
444
+ }
445
+ }
446
+
447
+ /** Same key the bridge uses for this project's backups (kit/server config.ts). */
448
+ export function projectBackupDir(root) {
449
+ let cwd = root;
450
+ try {
451
+ cwd = fs.realpathSync(root);
452
+ } catch {
453
+ /* keep the given path */
454
+ }
455
+ const key = crypto.createHash("sha256").update(cwd).digest("hex").slice(0, 16);
456
+ return path.join(os.homedir(), ".auis", "review-bridge-backups", key);
457
+ }
458
+
459
+ function removeEmptyDirs(root, dirs) {
460
+ for (const dir of [...dirs].reverse()) {
461
+ try {
462
+ fs.rmdirSync(abs(root, dir));
463
+ } catch {
464
+ /* not empty or already gone: someone else's now */
465
+ }
466
+ }
467
+ }
468
+
469
+ /**
470
+ * Reverse one edited file: its original bytes when it is exactly as init left
471
+ * it, otherwise `surgical(current)`. Returns what happened, for the report.
472
+ */
473
+ function restore(root, artifact, surgical) {
474
+ const file = abs(root, artifact.path);
475
+ const current = readMaybe(file);
476
+ if (current === null) return "missing";
477
+ const original = artifact.original ? readMaybe(abs(root, artifact.original)) : null;
478
+ if (sha(current) === artifact.after && original) {
479
+ fs.writeFileSync(file, original);
480
+ return "restored";
481
+ }
482
+ const next = surgical(current.toString("utf8"));
483
+ if (next === current.toString("utf8")) return "untouched";
484
+ fs.writeFileSync(file, next);
485
+ return "edited";
486
+ }
487
+
488
+ export async function uninstall({ directory = ".", install = true, purge = false, force = false } = {}) {
489
+ const root = path.resolve(directory);
490
+ const manifest = readManifest(root);
491
+ if (!manifest) {
492
+ fail(`No ${MANIFEST} in ${root} — auis was not installed here by \`auis init\`, so there is nothing to reverse.`);
493
+ return 1;
494
+ }
495
+
496
+ let needsInstall = false;
497
+ let kept = 0;
498
+ for (const a of [...manifest.artifacts].reverse()) {
499
+ switch (a.kind) {
500
+ case "file": {
501
+ const current = readMaybe(abs(root, a.path));
502
+ if (current === null) {
503
+ step("route", `${a.path} ${color.dim("already gone")}`);
504
+ } else if (sha(current) === a.sha256 || force) {
505
+ fs.rmSync(abs(root, a.path));
506
+ removeEmptyDirs(root, a.createdDirs ?? []);
507
+ step("route", `${a.path} ${color.dim("removed")}`);
508
+ } else {
509
+ kept++;
510
+ warn(`${a.path} changed since init — kept. Delete it yourself, or run uninstall --force.`);
511
+ }
512
+ break;
513
+ }
514
+ case "layout": {
515
+ const how = restore(root, a, (src) => unpatchLayout(src, a));
516
+ step("layout", `${a.path} ${color.dim(how)}`);
517
+ break;
518
+ }
519
+ case "dependency": {
520
+ const how = restore(root, a, (src) => removeDependency(src, a.name));
521
+ if (how === "edited") needsInstall = true;
522
+ step("package", `${a.name} ${color.dim(how === "restored" ? "removed" : how)}`);
523
+ break;
524
+ }
525
+ case "lockfile": {
526
+ const current = readMaybe(abs(root, a.path));
527
+ if (current && sha(current) === a.after) {
528
+ if (a.original) fs.writeFileSync(abs(root, a.path), readMaybe(abs(root, a.original)));
529
+ else fs.rmSync(abs(root, a.path));
530
+ step("lockfile", `${a.path} ${color.dim("restored")}`);
531
+ } else {
532
+ needsInstall = true;
533
+ }
534
+ break;
535
+ }
536
+ case "block": {
537
+ const current = readMaybe(abs(root, a.path));
538
+ if (a.created && current && sha(current) === a.after) {
539
+ fs.rmSync(abs(root, a.path));
540
+ step("gitignore", color.dim("removed (auis created it)"));
541
+ } else {
542
+ const how = restore(root, a, removeGitignoreBlock);
543
+ step("gitignore", color.dim(how));
544
+ }
545
+ break;
546
+ }
547
+ case "data": {
548
+ const data = abs(root, a.path);
549
+ if (!fs.existsSync(data)) break;
550
+ if (purge) {
551
+ fs.rmSync(data, { recursive: true, force: true });
552
+ step("data", `${a.path} ${color.dim("deleted (--purge)")}`);
553
+ } else if (fs.readdirSync(data).length === 0) {
554
+ fs.rmdirSync(data);
555
+ } else {
556
+ const stamp = new Date().toISOString().replace(/[:.]/g, "-");
557
+ const dest = path.join(projectBackupDir(root), `uninstalled-${stamp}`);
558
+ fs.mkdirSync(path.dirname(dest), { recursive: true });
559
+ fs.cpSync(data, dest, { recursive: true });
560
+ fs.rmSync(data, { recursive: true, force: true });
561
+ step("data", `${a.path} ${color.dim(`moved to ${dest}`)}`);
562
+ }
563
+ break;
564
+ }
565
+ default:
566
+ break;
567
+ }
568
+ }
569
+
570
+ if (needsInstall && install) {
571
+ const pm = manifest.packageManager ?? "npm";
572
+ const { ok } = await exec(pm, ["install"], { cwd: root, inherit: true });
573
+ if (ok) step("lockfile", color.dim(`${pm} install`));
574
+ else warn(`${pm} install failed — run it yourself to drop ${manifest.kit?.package ?? KIT_PACKAGE} from the lockfile.`);
575
+ }
576
+
577
+ // The manifest and the saved originals go last, and .auis with them if empty.
578
+ fs.rmSync(abs(root, ORIGINALS), { recursive: true, force: true });
579
+ if (kept === 0) fs.rmSync(abs(root, MANIFEST), { force: true });
580
+ try {
581
+ fs.rmdirSync(abs(root, AUIS_DIR));
582
+ } catch {
583
+ /* something of the user's is still in there */
584
+ }
585
+
586
+ write();
587
+ if (kept > 0) {
588
+ write(` ${color.yellow("!")} Uninstalled, except ${kept} file${kept === 1 ? "" : "s"} you changed. ${MANIFEST} stays until you deal with ${kept === 1 ? "it" : "them"}.`);
589
+ } else {
590
+ write(` ${color.bold("Review is uninstalled.")} ${color.dim("node_modules may still hold the packages until your next install.")}`);
591
+ }
592
+ write();
593
+ return 0;
594
+ }