@kousaku-maron/diffshape 0.5.0 → 0.7.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
@@ -6,7 +6,7 @@ git の差分の「形」を、push 前のローカルレビューで確かめ
6
6
  - **依存**([depshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/depshape)): フォルダ・ファイル間の依存関係がどう変わったかを、既存の構造と並べて見せます(Go / TypeScript / JavaScript)
7
7
  - **DB**([dbshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/dbshape)): PostgreSQL のスキーマ(テーブル・カラム・制約・外部キー・CHECK の値)がどう変わったかを、ER 図の差分で見せます
8
8
 
9
- どれも git から直接ファイルを読みます。ビルドツールのインストール、DB への接続、外部サービスは要りません。事実だけを見せ、判断はレビューする人が行います。
9
+ どれも git から直接ファイルを読みます。ビルドツールのインストール、DB への接続、外部サービスは要りません。事実だけを見せ、判断はレビューする人が行います。手元に Claude Code か Codex があれば、同じ画面からレビューと修正を任せることもできます(「AI レビューと修正」)。
10
10
 
11
11
  ## 使い方
12
12
 
@@ -42,11 +42,28 @@ npx @kousaku-maron/diffshape . main --merge-base
42
42
  ## 画面
43
43
 
44
44
  - **左のアイコンバー**: 「ファイル」「依存」「DB」を切り替えます。アイコンの数字は変更の件数、青い点は未対応のコメントがあることを示します。読むものがないモジュール(SQL ファイルがないリポジトリの DB など)は薄く表示します。表示中のモジュールは URL(`#file` / `#dep` / `#db`)に残るので、再読み込みしても同じ画面が開きます
45
- - **ヘッダー**: 比較の対象、「AI 用にコピー」、「再読み込み」。切り替えても、各モジュールで開いていた箱・選んだテーブル・書きかけのコメントはそのまま残ります
45
+ - **ヘッダー**: 比較の対象、「AI 用にコピー」、「AI」(下の「AI レビューと修正」)、「再読み込み」。切り替えても、各モジュールで開いていた箱・選んだテーブル・書きかけのコメントはそのまま残ります
46
46
  - **AI 用にコピー**: すべてのモジュールの未対応のコメントを、1つのプロンプトにまとめてコピーします(ファイルは `path:L12` とその行のコード、依存は import の状態と既存の依存のパターン、DB は SQL ファイルの定義位置つき)。Claude Code / Codex などにそのまま貼れます
47
47
  - **再読み込み**: AI がファイルを書き換えたあとに、すべてを解析し直します。開いていた状態はそのまま残ります
48
48
  - **DB が複数ある monorepo**: DB モジュールの中で DB を切り替えます(`atlas.hcl` ごと、または名前付きの `--schema` ごと)
49
49
 
50
+ ## AI レビューと修正
51
+
52
+ 作業ディレクトリとの比較(`diffshape` / `diffshape . main --merge-base` / `diffshape working`)では、ヘッダーの「AI」から、手元の Claude Code か Codex にレビューと修正をさせられます。diffshape はその PC に入っている `claude` / `codex` コマンドをそのまま起動するだけで、API キーやログインは扱いません(ターミナルで使えていれば動きます)。どちらも入っていないとき、コミット同士の比較のときは、ボタンを出しません。
53
+
54
+ | 実行 | すること |
55
+ |---|---|
56
+ | レビュー | 差分を読んでコメントを付けます。ファイルは変えません。コメントは自分で付けたものと同じ場所に「AI」の印つきで並び、編集も削除もできます |
57
+ | 修正 | 未対応のコメント(自分のものも AI のものも)に対応するよう、作業ディレクトリのファイルを編集します。終わると自動で読み直すので、コメントの「解消済み?」「コメント後に変更あり」で結果を確かめられます |
58
+ | レビューして修正 | レビューのあと、付いたコメントを続けて修正します |
59
+
60
+ - **エージェント・モデル・Effort** は、レビュー用と修正用を別々に選べます(Codex にレビューさせて Claude Code に直させる、など)。モデルと Effort の一覧は、入っている CLI から読みます。選ばなければ CLI の設定どおりです
61
+ - **範囲**: 表示中の画面だけか、すべての画面か。依存の画面では追加した import やファイルに、DB の画面ではテーブル・カラム・制約などにコメントが付きます
62
+ - **レビューは読むだけ**(`claude -p --permission-mode plan` / `codex exec --sandbox read-only`)、**修正は編集とコマンドの実行を許して**起動します(`--permission-mode auto` / `--sandbox workspace-write`)。確認なしで全部を通すオプションは使いません
63
+ - **修正の前の状態は残ります**: 修正を始める前の作業ディレクトリを `refs/diffshape/before-fix` に取っておきます(作業ディレクトリとステージ済みの状態は変えません)。`diffshape . refs/diffshape/before-fix` で AI が変えた分だけを見られ、`git restore --source=refs/diffshape/before-fix --worktree -- <path>` でファイルを戻せます
64
+ - **起動できるのはこの画面からだけ**です。別のサイトのページからのリクエストでは始まらず、`--host` でほかの端末に公開しているときは、AI の機能そのものを止めます
65
+ - `claude` / `codex` が PATH にないときは、環境変数 `DIFFSHAPE_CLAUDE` / `DIFFSHAPE_CODEX` に実行ファイルのパスを指定できます
66
+
50
67
  それぞれの画面の見方は、[fileshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/fileshape)、[depshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/depshape)、[dbshape](https://github.com/kousaku-maron/diffshape/tree/main/packages/dbshape) の README を見てください。
51
68
 
52
69
  ## ライセンス
@@ -1,13 +1,15 @@
1
1
  // ../core/src/git.ts
2
2
  import { execFile, spawn } from "node:child_process";
3
- import { readFile, stat } from "node:fs/promises";
3
+ import { copyFile, mkdtemp, readFile, rm, stat } from "node:fs/promises";
4
+ import { tmpdir } from "node:os";
4
5
  import { join } from "node:path";
5
6
  import { promisify } from "node:util";
6
7
  var execFileAsync = promisify(execFile);
7
- async function git(cwd, args) {
8
+ async function git(cwd, args, env) {
8
9
  const { stdout } = await execFileAsync("git", args, {
9
10
  cwd,
10
- maxBuffer: 512 * 1024 * 1024
11
+ maxBuffer: 512 * 1024 * 1024,
12
+ ...env ? { env: { ...process.env, ...env } } : {}
11
13
  });
12
14
  return stdout;
13
15
  }
@@ -84,6 +86,37 @@ async function untrackedFiles(root) {
84
86
  );
85
87
  return files.filter((f) => f !== null);
86
88
  }
89
+ async function worktreeTree(root) {
90
+ const tmp = await mkdtemp(join(tmpdir(), "diffshape-index-"));
91
+ try {
92
+ const env = { GIT_INDEX_FILE: join(tmp, "index") };
93
+ const real = (await git(root, ["rev-parse", "--path-format=absolute", "--git-path", "index"])).trim();
94
+ await copyFile(real, env.GIT_INDEX_FILE).catch(() => {
95
+ });
96
+ await git(root, ["add", "-A"], env);
97
+ return (await git(root, ["write-tree"], env)).trim();
98
+ } finally {
99
+ await rm(tmp, { recursive: true, force: true });
100
+ }
101
+ }
102
+ var SNAPSHOT_REF = "refs/diffshape/before-fix";
103
+ async function snapshotWorktree(root) {
104
+ const tree = await worktreeTree(root);
105
+ const head = await git(root, ["rev-parse", "--verify", "--quiet", "HEAD^{commit}"]).then(
106
+ (s) => s.trim(),
107
+ () => ""
108
+ // no commit yet
109
+ );
110
+ const who = { GIT_AUTHOR_NAME: "diffshape", GIT_AUTHOR_EMAIL: "diffshape@localhost", GIT_COMMITTER_NAME: "diffshape", GIT_COMMITTER_EMAIL: "diffshape@localhost" };
111
+ const commit = (await git(root, ["commit-tree", tree, ...head ? ["-p", head] : [], "-m", "diffshape: the working tree before an AI fix"], who)).trim();
112
+ await git(root, ["update-ref", SNAPSHOT_REF, commit]);
113
+ return commit;
114
+ }
115
+ async function changedSince(root, commit) {
116
+ const tree = await worktreeTree(root);
117
+ const out = await git(root, ["-c", "core.quotePath=false", "diff", "--name-only", "-z", "--no-renames", commit, tree, "--"]);
118
+ return out.split("\0").filter(Boolean);
119
+ }
87
120
  async function readBlob(root, source, path) {
88
121
  if (source.kind === "worktree") {
89
122
  try {
@@ -204,6 +237,31 @@ function hostAllowed(listenHost, hostHeader) {
204
237
  return false;
205
238
  }
206
239
  }
240
+ var isLoopback = (host) => LOOPBACK.has(host);
241
+ function postAllowed(listenHost, headers) {
242
+ if (!LOOPBACK.has(listenHost) || !headers.host || !headers.origin) return false;
243
+ if (!(headers["content-type"] ?? "").toLowerCase().startsWith("application/json")) return false;
244
+ try {
245
+ return new URL(headers.origin).host === headers.host;
246
+ } catch {
247
+ return false;
248
+ }
249
+ }
250
+ var MAX_BODY = 2 * 1024 * 1024;
251
+ async function readJSON(req) {
252
+ const chunks = [];
253
+ let size = 0;
254
+ for await (const chunk of req) {
255
+ size += chunk.length;
256
+ if (size > MAX_BODY) throw new HttpError(413, "request too large");
257
+ chunks.push(chunk);
258
+ }
259
+ try {
260
+ return JSON.parse(Buffer.concat(chunks).toString("utf8") || "null");
261
+ } catch {
262
+ throw new HttpError(400, "invalid JSON");
263
+ }
264
+ }
207
265
  var MIME = {
208
266
  ".html": "text/html; charset=utf-8",
209
267
  ".js": "text/javascript; charset=utf-8",
@@ -219,6 +277,15 @@ async function startServer(opts) {
219
277
  return;
220
278
  }
221
279
  const url = new URL(req.url ?? "/", "http://localhost");
280
+ const post = opts.post?.[url.pathname];
281
+ if (post) {
282
+ if (req.method !== "POST") throw new HttpError(405, "POST only");
283
+ if (!postAllowed(opts.host, req.headers)) throw new HttpError(403, "forbidden origin");
284
+ const body2 = await post(await readJSON(req), url);
285
+ res.writeHead(200, { "content-type": MIME[".json"], "cache-control": "no-store" });
286
+ res.end(JSON.stringify(body2 ?? null));
287
+ return;
288
+ }
222
289
  const handler = opts.api[url.pathname];
223
290
  if (handler) {
224
291
  const body2 = await handler(url);
@@ -278,6 +345,320 @@ function openBrowser(url) {
278
345
  }).unref();
279
346
  }
280
347
 
348
+ // ../core/src/agent.ts
349
+ import { execFile as execFile2, spawn as spawn3 } from "node:child_process";
350
+ import { access, constants, mkdtemp as mkdtemp2, readFile as readFile3, realpath, rm as rm2, writeFile } from "node:fs/promises";
351
+ import { homedir, tmpdir as tmpdir2 } from "node:os";
352
+ import { delimiter, join as join3 } from "node:path";
353
+ var AGENT_IDS = ["claude", "codex"];
354
+ var AGENT_LABEL = { claude: "Claude Code", codex: "Codex" };
355
+ var CLAUDE_EFFORTS = ["low", "medium", "high", "xhigh", "max"];
356
+ var FALLBACK_OPTIONS = {
357
+ claude: {
358
+ label: AGENT_LABEL.claude,
359
+ models: [
360
+ { id: "opus", label: "Opus", efforts: CLAUDE_EFFORTS },
361
+ { id: "fable", label: "Fable", efforts: CLAUDE_EFFORTS },
362
+ { id: "sonnet", label: "Sonnet", efforts: CLAUDE_EFFORTS },
363
+ { id: "haiku", label: "Haiku", efforts: CLAUDE_EFFORTS }
364
+ ],
365
+ defaultEfforts: CLAUDE_EFFORTS
366
+ },
367
+ codex: { label: AGENT_LABEL.codex, models: [], defaultEfforts: ["low", "medium", "high"] }
368
+ };
369
+ var validModel = (m) => /^[A-Za-z0-9][A-Za-z0-9._:/\[\]-]{0,99}$/.test(m);
370
+ var validEffort = (e) => /^[a-z]{1,20}$/.test(e);
371
+ var nullable = (type) => ({ type: [type, "null"] });
372
+ var REVIEW_SCHEMA = {
373
+ type: "object",
374
+ additionalProperties: false,
375
+ required: ["comments"],
376
+ properties: {
377
+ comments: {
378
+ type: "array",
379
+ items: {
380
+ type: "object",
381
+ additionalProperties: false,
382
+ required: ["module", "body", "target", "path", "side", "line", "endLine", "code"],
383
+ properties: {
384
+ module: { type: "string" },
385
+ body: { type: "string" },
386
+ target: nullable("string"),
387
+ path: nullable("string"),
388
+ side: { type: ["string", "null"], enum: ["old", "new", null] },
389
+ line: nullable("integer"),
390
+ endLine: nullable("integer"),
391
+ code: nullable("string")
392
+ }
393
+ }
394
+ }
395
+ }
396
+ };
397
+ var ENV = { claude: "DIFFSHAPE_CLAUDE", codex: "DIFFSHAPE_CODEX" };
398
+ var FALLBACK = { claude: [join3(homedir(), ".claude", "local", "claude")], codex: [] };
399
+ var executable = (path) => access(path, constants.X_OK).then(
400
+ () => true,
401
+ () => false
402
+ );
403
+ async function findAgent(id) {
404
+ const forced = process.env[ENV[id]];
405
+ if (forced !== void 0) return forced && await executable(forced) ? forced : null;
406
+ const names2 = process.platform === "win32" ? [`${id}.exe`] : [id];
407
+ const dirs = (process.env.PATH ?? "").split(delimiter).filter(Boolean);
408
+ for (const p of [...dirs.flatMap((d) => names2.map((n) => join3(d, n))), ...FALLBACK[id]]) if (await executable(p)) return p;
409
+ return null;
410
+ }
411
+ async function detectAgents() {
412
+ const found = await Promise.all(AGENT_IDS.map(findAgent));
413
+ return AGENT_IDS.filter((_, i) => found[i] !== null);
414
+ }
415
+ function capture(bin, args, cwd, input = "", timeout = 15e3) {
416
+ return new Promise((resolve, reject) => {
417
+ const child = execFile2(bin, args, { cwd, timeout, maxBuffer: 32 * 1024 * 1024 }, (err, stdout) => err ? reject(err) : resolve(stdout));
418
+ child.stdin?.on("error", () => {
419
+ });
420
+ child.stdin?.end(input);
421
+ });
422
+ }
423
+ var strings = (v) => Array.isArray(v) ? v.filter((x) => typeof x === "string" && validEffort(x)) : [];
424
+ var union = (lists) => [...new Set(lists.flat())];
425
+ async function claudeOptions(bin, cwd) {
426
+ const ask = JSON.stringify({ type: "control_request", request_id: "diffshape-models", request: { subtype: "initialize" } });
427
+ const out = await capture(bin, ["-p", "--input-format", "stream-json", "--output-format", "stream-json", "--verbose"], cwd, `${ask}
428
+ `);
429
+ for (const line of out.split("\n")) {
430
+ let o;
431
+ try {
432
+ o = JSON.parse(line);
433
+ } catch {
434
+ continue;
435
+ }
436
+ const list = o?.type === "control_response" ? (o.response?.response ?? o.response)?.models : void 0;
437
+ if (!Array.isArray(list)) continue;
438
+ const all = list.filter((m) => typeof m?.value === "string" && validModel(m.value));
439
+ const models = all.filter((m) => m.value !== "default").map((m) => ({ id: m.value, label: String(m.displayName ?? m.value), ...m.description ? { description: String(m.description) } : {}, efforts: strings(m.supportedEffortLevels) }));
440
+ if (!models.length) break;
441
+ const byDefault = all.find((m) => m.value === "default");
442
+ return { label: AGENT_LABEL.claude, models, defaultEfforts: byDefault ? strings(byDefault.supportedEffortLevels) : union(models.map((m) => m.efforts)) };
443
+ }
444
+ throw new Error("no models in the answer");
445
+ }
446
+ async function codexOptions(bin, cwd) {
447
+ const list = JSON.parse(await capture(bin, ["debug", "models"], cwd)).models;
448
+ if (!Array.isArray(list)) throw new Error("no models in the answer");
449
+ const models = list.filter((m) => typeof m?.slug === "string" && validModel(m.slug) && m.visibility === "list").map((m) => ({
450
+ id: m.slug,
451
+ label: String(m.display_name ?? m.slug),
452
+ ...m.description ? { description: String(m.description) } : {},
453
+ efforts: strings((m.supported_reasoning_levels ?? []).map((l) => l?.effort))
454
+ }));
455
+ if (!models.length) throw new Error("no models in the answer");
456
+ return { label: AGENT_LABEL.codex, models, defaultEfforts: union(models.map((m) => m.efforts)) };
457
+ }
458
+ async function agentOptions(id, cwd) {
459
+ const bin = await findAgent(id);
460
+ if (!bin) return FALLBACK_OPTIONS[id];
461
+ const [options, version] = await Promise.all([
462
+ (id === "claude" ? claudeOptions(bin, cwd) : codexOptions(bin, cwd)).catch(() => FALLBACK_OPTIONS[id]),
463
+ // "codex-cli 0.153.4", "2.1.0 (Claude Code)"
464
+ capture(bin, ["--version"], cwd).then(
465
+ (out) => /\d+\.\d+\.\d+[\w.-]*/.exec(out)?.[0],
466
+ () => void 0
467
+ )
468
+ ]);
469
+ return { ...options, ...version ? { version } : {} };
470
+ }
471
+ var AgentCancelled = class extends Error {
472
+ constructor() {
473
+ super("cancelled");
474
+ }
475
+ };
476
+ var firstLine = (s, max = 200) => {
477
+ const l = s.trim().split("\n")[0] ?? "";
478
+ return l.length > max ? `${l.slice(0, max)}\u2026` : l;
479
+ };
480
+ function claudeEvent(o, out, log) {
481
+ if (o.type === "assistant" && Array.isArray(o.message?.content)) {
482
+ for (const c of o.message.content) {
483
+ if (c.type === "text" && c.text?.trim()) log(firstLine(c.text));
484
+ if (c.type === "tool_use" && c.name !== "StructuredOutput") {
485
+ const i = c.input ?? {};
486
+ const what = i.description ?? i.file_path ?? i.path ?? i.pattern ?? i.command ?? "";
487
+ log(what ? `${c.name}: ${firstLine(String(what))}` : String(c.name));
488
+ }
489
+ }
490
+ }
491
+ if (o.type === "result") {
492
+ out.text = typeof o.result === "string" ? o.result : "";
493
+ out.structured = o.structured_output;
494
+ if (o.is_error) out.error = out.text || String(o.subtype ?? "error");
495
+ }
496
+ }
497
+ function errorText(message2) {
498
+ const s = String(message2 ?? "");
499
+ try {
500
+ const o = JSON.parse(s);
501
+ return String(o?.error?.message ?? o?.message ?? s);
502
+ } catch {
503
+ return s;
504
+ }
505
+ }
506
+ function shellWord(w) {
507
+ let out = "";
508
+ let i = 0;
509
+ while (i < w.length) {
510
+ const c = w[i];
511
+ if (c === "'") {
512
+ const end = w.indexOf("'", i + 1);
513
+ if (end < 0) return null;
514
+ out += w.slice(i + 1, end);
515
+ i = end + 1;
516
+ } else if (c === '"') {
517
+ for (i++; i < w.length && w[i] !== '"'; i++) {
518
+ if (w[i] === "\\" && '"\\$`'.includes(w[i + 1] ?? "")) i++;
519
+ out += w[i];
520
+ }
521
+ if (i >= w.length) return null;
522
+ i++;
523
+ } else if (/\s/.test(c)) {
524
+ return null;
525
+ } else {
526
+ if (c === "\\" && i + 1 < w.length) i++;
527
+ out += w[i++];
528
+ }
529
+ }
530
+ return out;
531
+ }
532
+ function codexEvent(o, out, log, review) {
533
+ const item = o.item;
534
+ if (o.type === "item.started" && item?.type === "command_execution") {
535
+ const m = /^\S+ -lc ([\s\S]+)$/.exec(String(item.command));
536
+ log(`$ ${firstLine((m && shellWord(m[1])) ?? String(item.command))}`);
537
+ }
538
+ if (o.type === "item.completed" && item) {
539
+ if (item.type === "agent_message" && typeof item.text === "string") {
540
+ out.text = item.text;
541
+ if (!(review && item.text.trimStart().startsWith("{"))) log(firstLine(item.text));
542
+ }
543
+ if (item.type === "file_change" && Array.isArray(item.changes)) log(`Edit: ${item.changes.map((c) => String(c.path)).join(", ")}`);
544
+ if (item.type === "error") log(firstLine(String(item.message)));
545
+ }
546
+ if (o.type === "error") out.error = errorText(o.message);
547
+ if (o.type === "turn.failed") out.error = errorText(o.error?.message);
548
+ }
549
+ function toItems(value) {
550
+ const list = value?.comments;
551
+ if (!Array.isArray(list)) throw new Error("\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u7B54\u3048\u306B\u30B3\u30E1\u30F3\u30C8\u306E\u4E00\u89A7\u304C\u3042\u308A\u307E\u305B\u3093");
552
+ const str2 = (v) => typeof v === "string" && v !== "" ? v : null;
553
+ const int = (v) => typeof v === "number" && Number.isInteger(v) && v > 0 ? v : null;
554
+ return list.filter((c) => !!c && typeof c === "object" && typeof c.module === "string" && typeof c.body === "string" && c.body.trim() !== "").map((c) => ({
555
+ module: c.module,
556
+ body: c.body.trim(),
557
+ target: str2(c.target),
558
+ path: str2(c.path),
559
+ side: c.side === "old" || c.side === "new" ? c.side : null,
560
+ line: int(c.line),
561
+ endLine: int(c.endLine),
562
+ // not trimmed: the code is matched against the file's lines
563
+ code: typeof c.code === "string" ? c.code : null
564
+ }));
565
+ }
566
+ function parseAnswer(text) {
567
+ try {
568
+ return JSON.parse(text);
569
+ } catch {
570
+ throw new Error(`\u30A8\u30FC\u30B8\u30A7\u30F3\u30C8\u306E\u7B54\u3048\u3092\u8AAD\u3081\u307E\u305B\u3093\u3067\u3057\u305F: ${firstLine(text) || "\uFF08\u7A7A\uFF09"}`);
571
+ }
572
+ }
573
+ async function runAgent(run2) {
574
+ const bin = await findAgent(run2.agent);
575
+ if (!bin) throw new Error(`${run2.agent} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
576
+ const review = run2.kind === "review";
577
+ if (run2.model !== void 0 && !validModel(run2.model)) throw new Error(`\u30E2\u30C7\u30EB\u540D\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${run2.model}`);
578
+ if (run2.effort !== void 0 && !validEffort(run2.effort)) throw new Error(`effort \u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${run2.effort}`);
579
+ const tmp = await mkdtemp2(join3(tmpdir2(), "diffshape-agent-"));
580
+ try {
581
+ let args;
582
+ const last = join3(tmp, "last.txt");
583
+ if (run2.agent === "claude") {
584
+ args = ["-p", "--permission-mode", review ? "plan" : "auto", "--output-format", "stream-json", "--verbose"];
585
+ if (run2.model) args.push("--model", run2.model);
586
+ if (run2.effort) args.push("--effort", run2.effort);
587
+ if (review) args.push("--json-schema", JSON.stringify(REVIEW_SCHEMA));
588
+ } else {
589
+ args = ["exec", "--sandbox", review ? "read-only" : "workspace-write", "--json", "-o", last, "-C", run2.cwd];
590
+ if (run2.model) args.push("-m", run2.model);
591
+ if (run2.effort) args.push("-c", `model_reasoning_effort="${run2.effort}"`);
592
+ if (review) {
593
+ const schema = join3(tmp, "schema.json");
594
+ await writeFile(schema, JSON.stringify(REVIEW_SCHEMA));
595
+ args.push("--output-schema", schema);
596
+ }
597
+ args.push("-");
598
+ }
599
+ const roots = [.../* @__PURE__ */ new Set([run2.cwd, await realpath(run2.cwd).catch(() => run2.cwd)])].map((r) => `${r}/`).sort((x, y) => y.length - x.length);
600
+ const fromRoot = (text) => roots.reduce((l, r) => l.split(r).join(""), text);
601
+ let lastLine = "";
602
+ const log = (text) => {
603
+ const line = fromRoot(text);
604
+ if (line !== lastLine) run2.onLog(lastLine = line);
605
+ };
606
+ const out = { text: "" };
607
+ const code = await new Promise((resolve, reject) => {
608
+ const proc = spawn3(bin, args, { cwd: run2.cwd, stdio: ["pipe", "pipe", "pipe"], detached: process.platform !== "win32" });
609
+ const kill = (sig) => {
610
+ try {
611
+ if (process.platform !== "win32" && proc.pid) process.kill(-proc.pid, sig);
612
+ else proc.kill(sig);
613
+ } catch {
614
+ }
615
+ };
616
+ const stop = () => {
617
+ kill("SIGTERM");
618
+ setTimeout(() => kill("SIGKILL"), 3e3).unref();
619
+ };
620
+ if (run2.signal?.aborted) stop();
621
+ run2.signal?.addEventListener("abort", stop, { once: true });
622
+ let buf = "";
623
+ proc.stdout.setEncoding("utf8").on("data", (d) => {
624
+ buf += d;
625
+ let nl;
626
+ while ((nl = buf.indexOf("\n")) >= 0) {
627
+ const line = buf.slice(0, nl);
628
+ buf = buf.slice(nl + 1);
629
+ let o;
630
+ try {
631
+ o = JSON.parse(line);
632
+ } catch {
633
+ continue;
634
+ }
635
+ if (run2.agent === "claude") claudeEvent(o, out, log);
636
+ else codexEvent(o, out, log, review);
637
+ }
638
+ });
639
+ let err = "";
640
+ proc.stderr.setEncoding("utf8").on("data", (d) => err = (err + d).slice(-2e3));
641
+ proc.on("error", reject);
642
+ proc.on("close", (c) => {
643
+ run2.signal?.removeEventListener("abort", stop);
644
+ if (c !== 0 && !out.error && !out.text) out.error = err.trim() || `${run2.agent} \u304C\u7D42\u4E86\u30B3\u30FC\u30C9 ${c} \u3067\u7D42\u308F\u308A\u307E\u3057\u305F`;
645
+ resolve(c);
646
+ });
647
+ proc.stdin.on("error", () => {
648
+ });
649
+ proc.stdin.end(run2.prompt);
650
+ });
651
+ if (run2.signal?.aborted) throw new AgentCancelled();
652
+ if (out.error) throw new Error(out.error);
653
+ if (code !== 0) throw new Error(`${run2.agent} \u304C\u7D42\u4E86\u30B3\u30FC\u30C9 ${code} \u3067\u7D42\u308F\u308A\u307E\u3057\u305F`);
654
+ if (run2.agent === "codex") out.text = await readFile3(last, "utf8").catch(() => "") || out.text;
655
+ if (!review) return { text: fromRoot(out.text.trim()) };
656
+ return { text: "", comments: toItems(out.structured ?? parseAnswer(out.text)) };
657
+ } finally {
658
+ await rm2(tmp, { recursive: true, force: true });
659
+ }
660
+ }
661
+
281
662
  // ../dbshape/src/analyze.ts
282
663
  import { posix as posix2 } from "node:path";
283
664
  import { loadModule, parseSync } from "libpg-query";
@@ -2493,16 +2874,112 @@ var fileApi = {
2493
2874
  // ../fileshape/src/index.ts
2494
2875
  var fileAnalyzer = { id: "file", analyze: analyzeFiles, api: fileApi };
2495
2876
 
2877
+ // src/agent.ts
2878
+ var LOG_LINES = 300;
2879
+ var MAX_PROMPT = 1024 * 1024;
2880
+ var bad = (message2) => {
2881
+ throw new HttpError(400, message2);
2882
+ };
2883
+ function parseStart(body) {
2884
+ const b = body && typeof body === "object" ? body : {};
2885
+ if (b.kind !== "review" && b.kind !== "fix") bad("kind \u306F review \u304B fix \u3067\u3059");
2886
+ if (!AGENT_IDS.includes(b.agent)) bad("agent \u306F claude \u304B codex \u3067\u3059");
2887
+ if (typeof b.prompt !== "string" || !b.prompt.trim() || b.prompt.length > MAX_PROMPT) bad("prompt \u304C\u306A\u3044\u304B\u3001\u9577\u3059\u304E\u307E\u3059");
2888
+ const agent = b.agent;
2889
+ const model = typeof b.model === "string" && b.model.trim() ? b.model.trim() : void 0;
2890
+ const effort = typeof b.effort === "string" && b.effort ? b.effort : void 0;
2891
+ if (model !== void 0 && !validModel(model)) bad(`\u30E2\u30C7\u30EB\u540D\u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${model}`);
2892
+ if (effort !== void 0 && !validEffort(effort)) bad(`effort \u304C\u6B63\u3057\u304F\u3042\u308A\u307E\u305B\u3093: ${effort}`);
2893
+ return { kind: b.kind, agent, prompt: b.prompt, ...model ? { model } : {}, ...effort ? { effort } : {} };
2894
+ }
2895
+ var AgentJobs = class {
2896
+ /** `enabled` is false when the server is open to the network: nobody else may start an agent here */
2897
+ constructor(enabled) {
2898
+ this.enabled = enabled;
2899
+ }
2900
+ job = null;
2901
+ abort = null;
2902
+ running = Promise.resolve();
2903
+ found = null;
2904
+ seq = 0;
2905
+ /** The agents on this machine with their models, asked once: they do not change while the app runs */
2906
+ agents(root) {
2907
+ return this.found ??= detectAgents().then((ids) => Promise.all(ids.map(async (id) => ({ id, ...await agentOptions(id, root) }))));
2908
+ }
2909
+ async state(sources) {
2910
+ const agents = this.enabled ? await this.agents(sources.root) : [];
2911
+ const ids = agents.map((a) => a.id);
2912
+ const reason = !this.enabled ? "--host \u3067\u307B\u304B\u306E\u30DE\u30B7\u30F3\u306B\u516C\u958B\u3057\u3066\u3044\u308B\u3068\u304D\u306F\u4F7F\u3048\u307E\u305B\u3093" : sources.target.kind !== "worktree" ? "\u4F5C\u696D\u30C7\u30A3\u30EC\u30AF\u30C8\u30EA\u3068\u306E\u6BD4\u8F03\uFF08target \u304C . \u304B working\uFF09\u306E\u3068\u304D\u3060\u3051\u4F7F\u3048\u307E\u3059" : ids.length === 0 ? "claude \u3082 codex \u3082\u898B\u3064\u304B\u308A\u307E\u305B\u3093" : void 0;
2913
+ return { available: !reason, ...reason ? { reason } : {}, agents, job: this.job };
2914
+ }
2915
+ async start(sources, body) {
2916
+ const req = parseStart(body);
2917
+ const state = await this.state(sources);
2918
+ if (!state.available) throw new HttpError(409, state.reason);
2919
+ const agent = state.agents.find((a) => a.id === req.agent);
2920
+ if (!agent) throw new HttpError(409, `${req.agent} \u304C\u898B\u3064\u304B\u308A\u307E\u305B\u3093`);
2921
+ const model = req.model === void 0 ? void 0 : agent.models.find((m) => m.id === req.model);
2922
+ if (req.model !== void 0 && !model) throw new HttpError(400, `${agent.label} \u306B\u306A\u3044\u30E2\u30C7\u30EB\u3067\u3059: ${req.model}`);
2923
+ if (req.effort !== void 0 && !(model?.efforts ?? agent.defaultEfforts).includes(req.effort)) throw new HttpError(400, `${model?.label ?? agent.label} \u306B\u306A\u3044 effort \u3067\u3059: ${req.effort}`);
2924
+ if (this.job?.status === "running") throw new HttpError(409, "\u307B\u304B\u306E AI \u306E\u5B9F\u884C\u304C\u7D42\u308F\u3063\u3066\u3044\u307E\u305B\u3093");
2925
+ const { prompt, ...chosen } = req;
2926
+ const job = { id: ++this.seq, ...chosen, status: "running", startedAt: Date.now(), log: [] };
2927
+ const abort = new AbortController();
2928
+ this.job = job;
2929
+ this.abort = abort;
2930
+ this.running = (async () => {
2931
+ let status = "done";
2932
+ let commit;
2933
+ try {
2934
+ if (req.kind === "fix") {
2935
+ commit = await snapshotWorktree(sources.root);
2936
+ job.snapshot = SNAPSHOT_REF;
2937
+ }
2938
+ const r = await runAgent({
2939
+ ...chosen,
2940
+ cwd: sources.root,
2941
+ prompt,
2942
+ signal: abort.signal,
2943
+ onLog: (line) => {
2944
+ job.log.push(line);
2945
+ if (job.log.length > LOG_LINES) job.log.splice(0, job.log.length - LOG_LINES);
2946
+ }
2947
+ });
2948
+ job.text = r.text;
2949
+ if (r.comments) job.comments = r.comments;
2950
+ } catch (e) {
2951
+ status = e instanceof AgentCancelled ? "cancelled" : "failed";
2952
+ if (status === "failed") job.error = e instanceof Error ? e.message : String(e);
2953
+ }
2954
+ if (commit) job.changedFiles = await changedSince(sources.root, commit).catch(() => void 0);
2955
+ job.endedAt = Date.now();
2956
+ job.status = status;
2957
+ })();
2958
+ return job;
2959
+ }
2960
+ /** Stops the running job (nothing happens when none runs) */
2961
+ cancel() {
2962
+ if (this.job?.status === "running") this.abort?.abort();
2963
+ return this.job;
2964
+ }
2965
+ /** Resolves when no job runs any more */
2966
+ idle() {
2967
+ return this.running;
2968
+ }
2969
+ };
2970
+
2496
2971
  // src/app.ts
2497
2972
  var message = (e) => (e instanceof Error ? e.stderr || e.message : String(e)).trim();
2498
2973
  var App = class {
2499
- constructor(cwd, opts, analyzers) {
2974
+ constructor(cwd, opts, analyzers, appOpts = {}) {
2500
2975
  this.cwd = cwd;
2501
2976
  this.opts = opts;
2502
2977
  this.analyzers = analyzers;
2978
+ this.jobs = new AgentJobs(appOpts.agents ?? true);
2503
2979
  }
2504
2980
  sources;
2505
2981
  results = /* @__PURE__ */ new Map();
2982
+ jobs;
2506
2983
  /** Resolves the comparison (errors like an unknown revision are thrown) and starts every module */
2507
2984
  async refresh() {
2508
2985
  this.sources = await resolveSources(this.cwd, this.opts);
@@ -2518,8 +2995,8 @@ var App = class {
2518
2995
  return this.info();
2519
2996
  }
2520
2997
  info() {
2521
- const { root, targetLabel, baseLabel } = this.sources;
2522
- return { repoRoot: root, targetLabel, baseLabel, modules: this.analyzers.map((a) => a.id) };
2998
+ const { root, targetLabel, baseLabel, base } = this.sources;
2999
+ return { repoRoot: root, targetLabel, baseLabel, baseRev: base.kind === "rev" ? base.rev : null, modules: this.analyzers.map((a) => a.id) };
2523
3000
  }
2524
3001
  result(id) {
2525
3002
  return this.results.get(id) ?? Promise.resolve({ error: `unknown module: ${id}` });
@@ -2533,6 +3010,21 @@ var App = class {
2533
3010
  if ("error" in r) throw new HttpError(409, r.error);
2534
3011
  return handler(url, { sources: this.sources, data: r.data });
2535
3012
  }
3013
+ /** Whether an AI review or fix can run here, with which agents, and the running (or last) job */
3014
+ agentState() {
3015
+ return this.jobs.state(this.sources);
3016
+ }
3017
+ /** Starts an AI review or fix from what the screen posted ({ kind, agent, prompt, model?, effort? }) */
3018
+ startAgent(body) {
3019
+ return this.jobs.start(this.sources, body);
3020
+ }
3021
+ cancelAgent() {
3022
+ return this.jobs.cancel();
3023
+ }
3024
+ /** Resolves when no AI job runs any more */
3025
+ agentIdle() {
3026
+ return this.jobs.idle();
3027
+ }
2536
3028
  };
2537
3029
 
2538
3030
  // src/server.ts
@@ -2540,13 +3032,18 @@ import { fileURLToPath } from "node:url";
2540
3032
  var UI_DIR = fileURLToPath(new URL("./ui/", import.meta.url));
2541
3033
  function startServer2(app, host, port) {
2542
3034
  const api = {
2543
- "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info()
3035
+ "/api/info": async (url) => url.searchParams.get("refresh") === "1" ? app.refresh() : app.info(),
3036
+ "/api/agent": () => app.agentState()
3037
+ };
3038
+ const post = {
3039
+ "/api/agent/start": (body) => app.startAgent(body),
3040
+ "/api/agent/cancel": async () => app.cancelAgent()
2544
3041
  };
2545
3042
  for (const a of app.analyzers) {
2546
3043
  api[`/api/module/${a.id}`] = () => app.result(a.id);
2547
3044
  for (const name of Object.keys(a.api ?? {})) api[`/api/module/${a.id}/${name}`] = (url) => app.call(a.id, name, url);
2548
3045
  }
2549
- return startServer({ uiDir: UI_DIR, host, port, api });
3046
+ return startServer({ uiDir: UI_DIR, host, port, api, post });
2550
3047
  }
2551
3048
 
2552
3049
  // src/cli.ts
@@ -2706,7 +3203,7 @@ async function run(command, argv) {
2706
3203
  }
2707
3204
  const all = [fileAnalyzer, depAnalyzer, dbAnalyzer({ schema: args.schema })];
2708
3205
  const analyzers = args.only ? all.filter((a) => a.id === args.only) : all;
2709
- const app = new App(process.cwd(), args, analyzers);
3206
+ const app = new App(process.cwd(), args, analyzers, { agents: isLoopback(args.host) });
2710
3207
  try {
2711
3208
  await app.refresh();
2712
3209
  if (args.json || args.text) {
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-O2FOVHLS.js";
5
5
 
6
6
  // src/bin/dbshape.ts
7
7
  void run("dbshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-O2FOVHLS.js";
5
5
 
6
6
  // src/bin/depshape.ts
7
7
  void run("depshape", process.argv.slice(2));
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  run
4
- } from "./chunk-AKBOSCJ7.js";
4
+ } from "./chunk-O2FOVHLS.js";
5
5
 
6
6
  // src/bin/diffshape.ts
7
7
  void run("diffshape", process.argv.slice(2));