hermes-pilot 0.0.0-stage → 0.2.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.
Files changed (74) hide show
  1. package/LICENSE +21 -0
  2. package/README.ja.md +390 -0
  3. package/README.md +398 -2
  4. package/__init__.py +15 -0
  5. package/apps/bridge/src/api-errors.js +165 -0
  6. package/apps/bridge/src/architect.js +1298 -0
  7. package/apps/bridge/src/auth.js +202 -0
  8. package/apps/bridge/src/capabilities.js +256 -0
  9. package/apps/bridge/src/capture.js +145 -0
  10. package/apps/bridge/src/chat-profile.js +95 -0
  11. package/apps/bridge/src/config.js +73 -0
  12. package/apps/bridge/src/discord.js +89 -0
  13. package/apps/bridge/src/gitinfo.js +211 -0
  14. package/apps/bridge/src/hermes.js +97 -0
  15. package/apps/bridge/src/inbox.js +347 -0
  16. package/apps/bridge/src/kanban.js +361 -0
  17. package/apps/bridge/src/lang.js +60 -0
  18. package/apps/bridge/src/live.js +285 -0
  19. package/apps/bridge/src/memos.js +150 -0
  20. package/apps/bridge/src/ops.js +201 -0
  21. package/apps/bridge/src/pair-codes.js +125 -0
  22. package/apps/bridge/src/pipeline-optimizer.js +358 -0
  23. package/apps/bridge/src/pipeline-watcher.js +1018 -0
  24. package/apps/bridge/src/qr.js +808 -0
  25. package/apps/bridge/src/repos.js +544 -0
  26. package/apps/bridge/src/review-watcher.js +271 -0
  27. package/apps/bridge/src/review.js +1749 -0
  28. package/apps/bridge/src/search.js +162 -0
  29. package/apps/bridge/src/server.js +1738 -0
  30. package/apps/bridge/src/snippets.js +373 -0
  31. package/apps/bridge/src/specs.js +734 -0
  32. package/apps/bridge/src/tail.js +28 -0
  33. package/apps/bridge/src/telemetry.js +667 -0
  34. package/apps/bridge/src/term-snippets.js +228 -0
  35. package/apps/bridge/src/transcript.js +231 -0
  36. package/apps/bridge/src/usage.js +294 -0
  37. package/apps/bridge/src/workerFeed.js +72 -0
  38. package/apps/dashboard/index.js +2014 -0
  39. package/apps/dashboard/manifest.json +14 -0
  40. package/apps/dashboard/pilot_dashboard.py +1466 -0
  41. package/apps/dashboard/plugin_api.py +237 -0
  42. package/apps/dashboard/plugin_init.py +15 -0
  43. package/apps/dashboard/style.css +928 -0
  44. package/apps/web/dist/assets/TermPane-DYP7pi_n.css +32 -0
  45. package/apps/web/dist/assets/TermPane-U500JD2P.js +12 -0
  46. package/apps/web/dist/assets/index-6iFDsB0G.css +1 -0
  47. package/apps/web/dist/assets/index-X4Bi2FWB.js +94 -0
  48. package/apps/web/dist/favicon.ico +0 -0
  49. package/apps/web/dist/icon-180-v6.png +0 -0
  50. package/apps/web/dist/icon-192-v6.png +0 -0
  51. package/apps/web/dist/icon-512-v6.png +0 -0
  52. package/apps/web/dist/icon-maskable-192-v6.png +0 -0
  53. package/apps/web/dist/icon-maskable-512-v6.png +0 -0
  54. package/apps/web/dist/icon-v6.svg +15 -0
  55. package/apps/web/dist/index.html +21 -0
  56. package/apps/web/dist/manifest.webmanifest +49 -0
  57. package/apps/web/dist/sw.js +69 -0
  58. package/bin/hermes-pilot.mjs +964 -0
  59. package/dashboard/dist/index.js +2014 -0
  60. package/dashboard/dist/style.css +928 -0
  61. package/dashboard/manifest.json +14 -0
  62. package/dashboard/pilot_dashboard.py +1466 -0
  63. package/dashboard/plugin_api.py +237 -0
  64. package/package.json +75 -4
  65. package/plugin.json +70 -0
  66. package/plugin.yaml +4 -0
  67. package/scripts/deploy.mjs +58 -0
  68. package/scripts/migrate-to-hermes-pilot.mjs +472 -0
  69. package/scripts/postinstall.mjs +32 -0
  70. package/scripts/sync-dashboard.mjs +98 -0
  71. package/skills/annotation/SKILL.md +103 -0
  72. package/skills/quick-review/SKILL.md +170 -0
  73. package/skills/quick-review/assets/sheet-template.html +175 -0
  74. package/skills/spec-architect/SKILL.md +175 -0
@@ -0,0 +1,237 @@
1
+ """FastAPI routes for the Hermes Pilot tab on the standard dashboard.
2
+
3
+ The dashboard imports this file from disk without adding ``dashboard/`` to
4
+ ``sys.path`` (``hermes_cli/web_server_dashboard.py`` → ``import_user_code``), so
5
+ the sibling logic module is loaded explicitly under a unique name instead of a
6
+ bare ``import pilot_dashboard``. That keeps a generic module name from colliding
7
+ with anything else in the dashboard process.
8
+
9
+ All routes are plain ``def`` so FastAPI runs them in its threadpool (the bridge
10
+ calls are blocking ``urllib``). Paths are relative: the host mounts this router
11
+ at ``/api/plugins/hermes-pilot``.
12
+
13
+ Response contract
14
+ -----------------
15
+ ``GET /status`` → ``{ok, service:{manager,unit,state}, port, dataDir, lanUrl,
16
+ tailscaleUrl, bridge:{reachable,version}, capabilities}``
17
+ ``GET /pairing`` → ``{ok, qrPng, targets, expiresAt, port, tlsPort, tailscale}``
18
+ ``GET /config`` → ``{ok, config, dataDir, scanDirsSource, reposPath}``
19
+ ``PUT /config`` → ``{ok, config, sync?}`` or ``400 {ok:false, code:"INVALID_CONFIG",
20
+ errors:{field:code}, messages:{field:text}}``
21
+ ``POST /service/{install|restart|status}`` → ``{ok, action, code, stdout}``
22
+ ``GET /repos`` → ``{ok, source:"bridge"|"file", repos, scanDirs}``
23
+ ``POST /repos`` → ``{ok, action, repos, scanDirs}`` (``add|hide|unhide|pin|unpin|createBoard``)
24
+ ``GET /snippets?kind=chat|term&lang=en|ja`` → ``{ok, source, kind, lang, allSnippets, custom, ...}``
25
+ ``PUT /snippets?kind=…&lang=…`` → same shape, after saving
26
+ ``GET /logs?file=gateway|errors|pilot|audit&lines=120`` → ``{ok, file, lines, shown, missing, path}``
27
+
28
+ The app token is never part of any response — see ``pilot_dashboard.redact``.
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import importlib.util
34
+ import sys
35
+ from pathlib import Path
36
+ from typing import Any, Optional
37
+
38
+ from fastapi import APIRouter, Body, Query
39
+ from fastapi.responses import JSONResponse
40
+
41
+ _DIR = Path(__file__).resolve().parent
42
+ _LOGIC_MODULE = "hermes_dashboard_hermes_pilot_logic"
43
+
44
+
45
+ def _load_logic() -> Any:
46
+ """Load ``pilot_dashboard.py`` as a uniquely named module (idempotent)."""
47
+ existing = sys.modules.get(_LOGIC_MODULE)
48
+ if existing is not None:
49
+ return existing
50
+ spec = importlib.util.spec_from_file_location(_LOGIC_MODULE, _DIR / "pilot_dashboard.py")
51
+ if spec is None or spec.loader is None: # pragma: no cover - defensive
52
+ raise ImportError(f"hermes-pilot: cannot load logic from {_DIR}")
53
+ module = importlib.util.module_from_spec(spec)
54
+ sys.modules[_LOGIC_MODULE] = module
55
+ try:
56
+ spec.loader.exec_module(module)
57
+ except Exception: # pragma: no cover - keep sys.modules clean on failure
58
+ sys.modules.pop(_LOGIC_MODULE, None)
59
+ raise
60
+ return module
61
+
62
+
63
+ logic = _load_logic()
64
+
65
+ VERSION = "0.1.0"
66
+ router = APIRouter()
67
+
68
+
69
+ def fail(status: int, code: str, message: str, detail: Any = None) -> JSONResponse:
70
+ """Machine-readable error envelope (SPEC §6.3: ``code`` + English message)."""
71
+ body: dict[str, Any] = {"ok": False, "code": code, "error": message}
72
+ if detail is not None:
73
+ body["detail"] = detail
74
+ return JSONResponse(body, status_code=status)
75
+
76
+
77
+ @router.get("/status")
78
+ def get_status() -> Any:
79
+ """Service + port + bridge reachability + capabilities. Never carries the token."""
80
+ try:
81
+ return logic.build_status()
82
+ except Exception as exc: # health: surface the reason instead of a 500 traceback
83
+ return fail(500, "STATUS_FAILED", str(exc))
84
+
85
+
86
+ @router.get("/pairing")
87
+ def get_pairing() -> Any:
88
+ """Proxy the bridge's one-time pairing code as a PNG QR the browser can show."""
89
+ try:
90
+ return logic.build_pairing()
91
+ except logic.BridgeUnavailable as exc:
92
+ return fail(502, "BRIDGE_UNREACHABLE", str(exc))
93
+ except Exception as exc:
94
+ return fail(500, "PAIRING_FAILED", str(exc))
95
+
96
+
97
+ @router.get("/config")
98
+ def get_config() -> Any:
99
+ """Current config, with ``repos.json``'s ``scanDirs`` as the source of truth (G3)."""
100
+ return logic.build_config()
101
+
102
+
103
+ @router.put("/config")
104
+ def put_config(payload: Optional[dict] = Body(default=None)) -> Any:
105
+ """Validate then write atomically (tmp → rename, 0600).
106
+
107
+ A partial body is merged onto the current file, so the tab can save one field
108
+ without shipping the whole document back. When ``scanDirs`` changes it is
109
+ pushed to the bridge and ``repos.json`` in the same request (G3).
110
+ """
111
+ paths = logic.resolve_paths()
112
+ current = logic.build_config(paths)["config"]
113
+ merged: dict[str, Any] = dict(current)
114
+ if isinstance(payload, dict):
115
+ merged.update(payload)
116
+ result = logic.validate_config(merged)
117
+ if not result["ok"]:
118
+ return JSONResponse(
119
+ {
120
+ "ok": False,
121
+ "code": "INVALID_CONFIG",
122
+ "errors": result["errors"],
123
+ "messages": result["messages"],
124
+ },
125
+ status_code=400,
126
+ )
127
+ try:
128
+ logic.write_config_atomic(paths["configPath"], result["value"])
129
+ except OSError as exc:
130
+ return fail(500, "WRITE_FAILED", str(exc))
131
+ body: dict[str, Any] = {"ok": True, "config": logic.build_config(paths)["config"]}
132
+ if isinstance(payload, dict) and "scanDirs" in payload:
133
+ try:
134
+ body["sync"] = logic.sync_scan_dirs(paths, result["value"].get("scanDirs"))
135
+ except OSError as exc:
136
+ body["sync"] = {"ok": False, "error": f"repos.json could not be written: {exc}"}
137
+ return body
138
+
139
+
140
+ @router.get("/repos")
141
+ def get_repos() -> Any:
142
+ """Merged repository list + ``scanDirs`` (bridge when up, ``repos.json`` when not)."""
143
+ try:
144
+ return logic.build_repos()
145
+ except Exception as exc: # health: surface the reason instead of a 500 traceback
146
+ return fail(500, "REPOS_FAILED", str(exc))
147
+
148
+
149
+ @router.post("/repos")
150
+ def post_repos(payload: Optional[dict] = Body(default=None)) -> Any:
151
+ """``add|hide|unhide|pin|unpin|createBoard`` — then return the fresh list."""
152
+ try:
153
+ result = logic.repos_action(payload=payload)
154
+ except Exception as exc:
155
+ return fail(500, "REPOS_FAILED", str(exc))
156
+ if not result.get("ok"):
157
+ return JSONResponse(result, status_code=400)
158
+ return result
159
+
160
+
161
+ @router.get("/snippets")
162
+ def get_snippets(
163
+ kind: str = Query("chat", pattern="^(chat|term)$"),
164
+ lang: str = Query("en", pattern="^(en|ja)$"),
165
+ ) -> Any:
166
+ """Chat/terminal snippets through the bridge, or the saved store when it is down."""
167
+ try:
168
+ return logic.build_snippets(kind=kind, lang=lang)
169
+ except ValueError as exc:
170
+ return fail(400, "INVALID_KIND", str(exc))
171
+ except Exception as exc:
172
+ return fail(500, "SNIPPETS_FAILED", str(exc))
173
+
174
+
175
+ @router.put("/snippets")
176
+ def put_snippets(
177
+ payload: Optional[dict] = Body(default=None),
178
+ kind: str = Query("chat", pattern="^(chat|term)$"),
179
+ lang: str = Query("en", pattern="^(en|ja)$"),
180
+ ) -> Any:
181
+ """Save Hot/Hidden overrides and custom snippets (`reset:true` restores defaults)."""
182
+ try:
183
+ return logic.save_snippets(kind=kind, lang=lang, payload=payload)
184
+ except ValueError as exc:
185
+ return fail(400, "INVALID_KIND", str(exc))
186
+ except OSError as exc:
187
+ return fail(500, "WRITE_FAILED", str(exc))
188
+ except Exception as exc:
189
+ return fail(500, "SNIPPETS_FAILED", str(exc))
190
+
191
+
192
+ @router.get("/pipeline")
193
+ def get_pipeline(board: Optional[str] = Query(None)) -> Any:
194
+ """Architect runner + SOUL/skill 適用状態 + 未起票 SPEC(SPEC V5 §3.2 / D25)。"""
195
+ try:
196
+ return logic.build_pipeline(board=board)
197
+ except Exception as exc: # health: surface the reason instead of a 500 traceback
198
+ return fail(500, "PIPELINE_FAILED", str(exc))
199
+
200
+
201
+ @router.post("/pipeline")
202
+ def post_pipeline(payload: Optional[dict] = Body(default=None)) -> Any:
203
+ """``optimize``(SOUL.md + スキル配置)または ``setRunner``(hermes 固定 / Hermes Native)。"""
204
+ try:
205
+ result = logic.pipeline_action(payload=payload)
206
+ except Exception as exc:
207
+ return fail(500, "PIPELINE_FAILED", str(exc))
208
+ if not result.get("ok"):
209
+ return JSONResponse(result, status_code=400)
210
+ return result
211
+
212
+
213
+ @router.get("/logs")
214
+ def get_logs(
215
+ file_name: str = Query("gateway", alias="file", pattern="^(gateway|errors|pilot|audit)$"),
216
+ lines: int = Query(120, ge=1, le=1000),
217
+ ) -> Any:
218
+ """Tail of one whitelisted log — redacted before it leaves the process."""
219
+ try:
220
+ return logic.build_logs(name=file_name, lines=lines)
221
+ except ValueError as exc:
222
+ return fail(400, "INVALID_FILE", str(exc))
223
+ except Exception as exc:
224
+ return fail(500, "LOGS_FAILED", str(exc))
225
+
226
+
227
+ @router.post("/service/{action}")
228
+ def post_service(action: str) -> Any:
229
+ """Spawn ``hermes-pilot service <action>`` and return its stdout."""
230
+ try:
231
+ return logic.run_service(action)
232
+ except ValueError as exc:
233
+ return fail(400, "UNKNOWN_ACTION", str(exc))
234
+ except logic.MissingCli as exc:
235
+ return fail(409, "CLI_MISSING", str(exc))
236
+ except Exception as exc:
237
+ return fail(500, "SERVICE_FAILED", str(exc))
package/package.json CHANGED
@@ -1,6 +1,77 @@
1
1
  {
2
2
  "name": "hermes-pilot",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.2.0",
4
+ "description": "Drive an autonomous Hermes Agent from your phone or tablet: Quick Review, annotation, kanban and chat in one installable PWA.",
5
+ "license": "MIT",
6
+ "homepage": "https://github.com/hajimemanila/hermes-pilot#readme",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "git+https://github.com/hajimemanila/hermes-pilot.git"
10
+ },
11
+ "type": "module",
12
+ "bin": {
13
+ "hermes-pilot": "bin/hermes-pilot.mjs"
14
+ },
15
+ "files": [
16
+ "bin/",
17
+ "__init__.py",
18
+ "dashboard/",
19
+ "apps/bridge/src/",
20
+ "apps/web/dist/",
21
+ "apps/dashboard/*.py",
22
+ "apps/dashboard/*.js",
23
+ "apps/dashboard/*.css",
24
+ "apps/dashboard/*.json",
25
+ "!**/__pycache__/**",
26
+ "!**/*.pyc",
27
+ "skills/quick-review/",
28
+ "skills/annotation/",
29
+ "skills/spec-architect/",
30
+ "scripts/postinstall.mjs",
31
+ "scripts/deploy.mjs",
32
+ "scripts/migrate-to-hermes-pilot.mjs",
33
+ "scripts/sync-dashboard.mjs",
34
+ "plugin.json",
35
+ "plugin.yaml",
36
+ "README.md",
37
+ "README.ja.md",
38
+ "LICENSE"
39
+ ],
40
+ "engines": {
41
+ "node": ">=22.19.0"
42
+ },
43
+ "scripts": {
44
+ "probe": "node scripts/probe-ws.mjs",
45
+ "bridge": "node apps/bridge/src/server.js",
46
+ "dev": "vite --config apps/web/vite.config.js",
47
+ "build": "vite build --config apps/web/vite.config.js",
48
+ "build:demo": "VITE_DEMO_MODE=1 vite build --config apps/web/vite.config.js --outDir dist-demo --base ./ && node scripts/build-demo-embed.mjs",
49
+ "test": "node --test apps/bridge/test/*.test.js apps/web/test/*.test.js",
50
+ "postinstall": "node scripts/postinstall.mjs",
51
+ "start": "node apps/bridge/src/server.js",
52
+ "probe:bridge": "node scripts/probe-bridge.mjs",
53
+ "revoke": "node scripts/revoke.mjs",
54
+ "check:pwa": "python3 scripts/check-pwa.py --dir apps/web/public",
55
+ "check:oauth": "node scripts/check-oauth-boundary.mjs",
56
+ "check:dashboard": "node scripts/sync-dashboard.mjs --check",
57
+ "sync:dashboard": "node scripts/sync-dashboard.mjs",
58
+ "check:pwa:live": "python3 scripts/check-pwa.py --url http://127.0.0.1:4097",
59
+ "check:pwa:selftest": "python3 scripts/check-pwa.py --self-test",
60
+ "audit:responsive": "node scripts/audit-responsive.mjs",
61
+ "verify": "npm test && npm run check:dashboard && npm run check:pwa && npm run check:oauth && npm run build && npm run audit:responsive",
62
+ "deploy": "node scripts/deploy.mjs",
63
+ "migrate:pilot": "node scripts/migrate-to-hermes-pilot.mjs"
64
+ },
65
+ "dependencies": {
66
+ "@xterm/addon-fit": "^0.10.0",
67
+ "@xterm/xterm": "^5.5.0",
68
+ "node-pty": "^1.1.0",
69
+ "ws": "^8.18.0"
70
+ },
71
+ "devDependencies": {
72
+ "@vitejs/plugin-react": "^4.3.3",
73
+ "react": "^18.3.1",
74
+ "react-dom": "^18.3.1",
75
+ "vite": "^5.4.10"
76
+ }
77
+ }
package/plugin.json ADDED
@@ -0,0 +1,70 @@
1
+ {
2
+ "name": "hermes-pilot",
3
+ "displayName": "Hermes Pilot",
4
+ "version": "0.2.0",
5
+ "description": "The A2B pipeline for an autonomous Hermes Agent, in your pocket: turn a one-line Spec Seed into a Quick Review interview, a spec the batch runner can execute, filed kanban batches, live monitoring and a Mission Receipt — plus annotation, chat, terminal and usage in one installable PWA.",
6
+ "author": "Hermes Pilot contributors",
7
+ "license": "MIT",
8
+ "kind": "app",
9
+ "homepage": "https://github.com/hajimemanila/hermes-pilot",
10
+ "entrypoints": {
11
+ "cli": "bin/hermes-pilot.mjs",
12
+ "bridge": "apps/bridge/src/server.js",
13
+ "ui": "apps/web/dist/index.html"
14
+ },
15
+ "commands": {
16
+ "init": "First-run setup: data directories, 256-bit token (0600), bundled skills, pairing QR",
17
+ "start": "Build the UI when needed and run the bridge (--port, --host, --tls-port)",
18
+ "qr": "Print the pairing URL candidates and a terminal QR code",
19
+ "service": "install | uninstall | restart | status (launchd on macOS, systemd --user on Linux)",
20
+ "migrate": "Copy data from the legacy akapen / mobile-pwa layout"
21
+ },
22
+ "skills": [
23
+ "skills/quick-review/SKILL.md",
24
+ "skills/annotation/SKILL.md",
25
+ "skills/spec-architect/SKILL.md"
26
+ ],
27
+ "storage": {
28
+ "data": "~/.hermes/plugin-data/hermes-pilot",
29
+ "review": "~/.hermes/plugin-data/hermes-pilot/review",
30
+ "env": ["HP_DATA_DIR", "HM_DATA", "HM_PORT", "HM_HOST", "HERMES_HOME"]
31
+ },
32
+ "service": {
33
+ "darwin": {
34
+ "label": "ai.hermes.pilot",
35
+ "plist": "~/Library/LaunchAgents/ai.hermes.pilot.plist"
36
+ },
37
+ "linux": {
38
+ "unit": "hermes-pilot.service",
39
+ "path": "~/.config/systemd/user/hermes-pilot.service"
40
+ },
41
+ "legacy": "ai.hermes.hermes-mobile is intentionally left running during migration; see README"
42
+ },
43
+ "api": {
44
+ "auth": ["POST /api/auth/login", "GET /api/auth/pairing"],
45
+ "pipeline": ["GET /api/pipeline/status", "POST /api/pipeline/optimize"],
46
+ "architect": [
47
+ "POST /api/architect/seed",
48
+ "GET /api/architect/jobs",
49
+ "POST /api/architect/jobs/:id/dismiss",
50
+ "GET /api/architect/config",
51
+ "PUT /api/architect/config"
52
+ ],
53
+ "specs": [
54
+ "GET /api/specs",
55
+ "GET /api/specs/content",
56
+ "POST /api/specs/launch",
57
+ "GET /api/specs/reports"
58
+ ],
59
+ "review": "/api/review/*",
60
+ "boards": "/api/boards/*",
61
+ "telemetry": "GET /api/telemetry/receipt",
62
+ "live": "GET /api/live",
63
+ "usage": "GET /api/usage",
64
+ "capabilities": "GET /api/capabilities"
65
+ },
66
+ "i18n": ["en", "ja"],
67
+ "engines": {
68
+ "node": ">=22.19.0"
69
+ }
70
+ }
package/plugin.yaml ADDED
@@ -0,0 +1,4 @@
1
+ name: hermes-pilot
2
+ version: 0.2.0
3
+ description: "Hermes Pilot — drive an autonomous Hermes Agent from your phone or tablet. Ships a Hermes dashboard tab (pairing QR, bridge status, scan directories, service control) and the PWA bridge it talks to."
4
+ requires_hermes: ">=0.23.0"
@@ -0,0 +1,58 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * 無停止デプロイ: ビルド → 検証 → 入れ替え(`dist.prev` に直前の正常ビルドを残す)。
4
+ *
5
+ * 背景(実測): `dist` を直接作り替えると、ビルド中・失敗時に PWA が
6
+ * 「ブリッジに接続できません」で使えなくなる。ブリッジは `dist` が無いとき
7
+ * `dist.prev` を配るので、ここで「成功したものだけ」を入れ替える。
8
+ *
9
+ * node scripts/deploy.mjs # ビルドして入れ替え
10
+ * node scripts/deploy.mjs --check # ビルドせず現状の検証だけ
11
+ */
12
+ import { execFileSync } from 'node:child_process'
13
+ import fs from 'node:fs'
14
+ import path from 'node:path'
15
+
16
+ const root = path.resolve(import.meta.dirname, '..')
17
+ const dist = path.join(root, 'apps/web/dist')
18
+ const next = path.join(root, 'apps/web/dist.next')
19
+ const prev = path.join(root, 'apps/web/dist.prev')
20
+ const checkOnly = process.argv.includes('--check')
21
+
22
+ function verify(dir, label) {
23
+ const index = path.join(dir, 'index.html')
24
+ if (!fs.existsSync(index)) throw new Error(`${label}: index.html がありません (${dir})`)
25
+ const html = fs.readFileSync(index, 'utf8')
26
+ const refs = [...html.matchAll(/(?:src|href)="(\/assets\/[^"]+)"/g)].map((m) => m[1])
27
+ if (!refs.length) throw new Error(`${label}: index.html に /assets/ 参照がありません`)
28
+ for (const ref of refs) {
29
+ const file = path.join(dir, ref.replace(/^\//, ''))
30
+ if (!fs.existsSync(file)) throw new Error(`${label}: 参照先が欠けています ${ref}`)
31
+ }
32
+ return { assets: refs.length, bytes: fs.statSync(index).size }
33
+ }
34
+
35
+ if (checkOnly) {
36
+ const v = verify(dist, 'dist')
37
+ console.log(`検証: dist (index ${v.bytes}B / assets 参照 ${v.assets} 件)`)
38
+ process.exit(0)
39
+ }
40
+
41
+ fs.rmSync(next, { recursive: true, force: true })
42
+ console.log('build → apps/web/dist.next')
43
+ execFileSync('npx', ['vite', 'build', '--config', 'apps/web/vite.config.js', '--outDir', 'dist.next'], {
44
+ cwd: root,
45
+ stdio: 'inherit',
46
+ })
47
+
48
+ const v = verify(next, 'dist.next')
49
+ console.log(`検証: index ${v.bytes}B / assets 参照 ${v.assets} 件`)
50
+
51
+ // 入れ替え(失敗しない限り dist は常に完全なビルド)
52
+ if (fs.existsSync(dist)) {
53
+ fs.rmSync(prev, { recursive: true, force: true })
54
+ fs.renameSync(dist, prev)
55
+ }
56
+ fs.renameSync(next, dist)
57
+ verify(dist, 'dist')
58
+ console.log(`反映: dist ← 新ビルド(直前の正常ビルドは dist.prev)`)