@intra-mart/accel 0.5.0 → 0.6.0-dev.202609070354

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 (48) hide show
  1. package/README.md +21 -3
  2. package/assets/runtime/ensure.mjs +914 -0
  3. package/dist/asset/dependencies.d.ts +7 -0
  4. package/dist/asset/dependencies.js +23 -0
  5. package/dist/asset/deployer.d.ts +1 -0
  6. package/dist/asset/deployer.js +11 -3
  7. package/dist/asset/installer.js +3 -8
  8. package/dist/asset/updater.d.ts +2 -0
  9. package/dist/asset/updater.js +3 -0
  10. package/dist/asset/walker.d.ts +1 -0
  11. package/dist/asset/walker.js +65 -3
  12. package/dist/commands/attach.d.ts +4 -1
  13. package/dist/commands/attach.js +8 -1
  14. package/dist/commands/detach.d.ts +2 -0
  15. package/dist/commands/detach.js +4 -0
  16. package/dist/commands/init.d.ts +4 -1
  17. package/dist/commands/init.js +8 -1
  18. package/dist/commands/switch.d.ts +3 -0
  19. package/dist/commands/switch.js +12 -3
  20. package/dist/commands/update.d.ts +4 -0
  21. package/dist/commands/update.js +26 -5
  22. package/dist/core/constants.d.ts +10 -1
  23. package/dist/core/constants.js +22 -1
  24. package/dist/core/errors.d.ts +11 -0
  25. package/dist/core/errors.js +6 -0
  26. package/dist/core/gitignore-entries.d.ts +7 -0
  27. package/dist/core/gitignore-entries.js +16 -0
  28. package/dist/core/paths.d.ts +1 -0
  29. package/dist/core/paths.js +1 -0
  30. package/dist/core/types.d.ts +2 -1
  31. package/dist/core/variable-interpolator.js +4 -0
  32. package/dist/i18n/en.js +14 -0
  33. package/dist/i18n/ja.js +14 -0
  34. package/dist/i18n/zh_CN.js +14 -0
  35. package/dist/interactive/next-steps.d.ts +1 -0
  36. package/dist/interactive/next-steps.js +3 -0
  37. package/dist/utils/credentials.d.ts +2 -1
  38. package/dist/utils/credentials.js +3 -2
  39. package/dist/utils/gitignore.d.ts +1 -0
  40. package/dist/utils/gitignore.js +8 -6
  41. package/dist/utils/mcp-generate.js +1 -1
  42. package/dist/utils/runtime-ensure.d.ts +55 -0
  43. package/dist/utils/runtime-ensure.js +391 -0
  44. package/dist/utils/sanitize-text.d.ts +2 -0
  45. package/dist/utils/sanitize-text.js +7 -0
  46. package/dist/utils/settings-io.d.ts +2 -1
  47. package/dist/utils/settings-io.js +2 -1
  48. package/package.json +7 -2
@@ -0,0 +1,914 @@
1
+ #!/usr/bin/env node
2
+ // @accel-cli-managed
3
+ //
4
+ // skill 依存の install・リンク作成・GC を行うスクリプト(accel-cli が配置する)。
5
+ //
6
+ // 依存ディレクトリ(settings.json の dependencies)ごとに package.json とロック
7
+ // ファイルの内容ハッシュ(id)を計算し、未完成なら .accel/runtime/<id>/ へ
8
+ // ci 相当の install を行い、依存ディレクトリの node_modules から
9
+ // .accel/runtime/<id>/node_modules へのリンクを作る。完成済みの id は何もしない。
10
+ //
11
+ // 起動形式:
12
+ // node .accel/ensure.mjs ensure のみ(フック・CLI から)
13
+ // node .accel/ensure.mjs <script> [args...] ensure 成功後に <script> を起動する
14
+ // (packageManager が bun のプロジェクトでは `bun .accel/ensure.mjs`。案内の再実行
15
+ // コマンドは自分を起動したランタイムに合わせる)
16
+ //
17
+ // Node 組み込み API のみで実装し、npm 依存を持たない。Node と Bun のどちらでも動く。
18
+ // プロジェクトルートはこのファイルの位置(<root>/.accel/ensure.mjs)から決め、
19
+ // カレントディレクトリには依存しない。
20
+
21
+ import fs from "node:fs";
22
+ import path from "node:path";
23
+ import crypto from "node:crypto";
24
+ import { spawnSync } from "node:child_process";
25
+ import { fileURLToPath } from "node:url";
26
+
27
+ // =============================================================================
28
+ // 定数
29
+ // =============================================================================
30
+
31
+ export const LOCKFILES = {
32
+ bun: "bun.lock",
33
+ npm: "package-lock.json",
34
+ yarn: "yarn.lock",
35
+ pnpm: "pnpm-lock.yaml",
36
+ };
37
+
38
+ export const INSTALL_ARGS = {
39
+ bun: ["ci", "--ignore-scripts"],
40
+ npm: ["ci", "--ignore-scripts"],
41
+ yarn: ["install", "--frozen-lockfile", "--ignore-scripts"],
42
+ pnpm: ["install", "--frozen-lockfile", "--ignore-scripts"],
43
+ };
44
+
45
+ const DEFAULT_PM = "bun";
46
+ const RERUN_COMMAND = `${process.versions.bun ? "bun" : "node"} .accel/ensure.mjs`;
47
+ const GC_AGE_MS = 30 * 24 * 60 * 60 * 1000;
48
+ // 同一 id への並行 install の排他(.accel/runtime/<id>.lock/ を mkdir で取得)
49
+ const LOCK_SUFFIX = ".lock";
50
+ const LOCK_STALE_MS = 10 * 60 * 1000;
51
+ const LOCK_WAIT_MS = 10 * 60 * 1000;
52
+ const LOCK_POLL_MS = 500;
53
+ const OUTPUT_TAIL_LINES = 20;
54
+ // 読み込むプロジェクト内ファイル(package.json / ロック)の上限。git 共有のパスが
55
+ // デバイスファイル等へのリンクだった場合の無限読みを防ぐ
56
+ const MAX_INPUT_BYTES = 64 * 1024 * 1024;
57
+ const ID_PATTERN = /^[0-9a-f]{16}$/;
58
+ // 表示テキスト(settings 由来のパス・PM 出力)の 1 値あたりの上限
59
+ const MAX_TEXT_LENGTH = 500;
60
+ const MAX_OUTPUT_BUFFER = 16 * 1024 * 1024;
61
+
62
+ // install 失敗の原因を出力から分類するパターン(大文字小文字を区別しない)
63
+ export const FAILURE_PATTERNS = {
64
+ lockMismatch: {
65
+ bun: [
66
+ /lockfile had changes, but lockfile is frozen/i,
67
+ /lockfile (is )?missing/i,
68
+ /frozen lockfile/i,
69
+ ],
70
+ npm: [
71
+ /can only install packages when your package\.json and package-lock\.json/i,
72
+ /Missing: .+ from lock file/i,
73
+ /Invalid: lock file/i,
74
+ ],
75
+ yarn: [/lockfile needs to be updated/i, /YN0028/i, /lockfile would have been modified/i],
76
+ pnpm: [
77
+ /ERR_PNPM_OUTDATED_LOCKFILE/i,
78
+ /ERR_PNPM_LOCKFILE_/i,
79
+ /frozen-lockfile.*not up to date/i,
80
+ ],
81
+ },
82
+ network: [
83
+ /ENOTFOUND|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|ENETUNREACH|EHOSTUNREACH|getaddrinfo|socket hang up|fetch failed|ERR_PNPM_(META_)?FETCH|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|DNS lookup failed|Unable to connect|trouble with your network connection|network (error|request failed)/i,
84
+ ],
85
+ };
86
+
87
+ // =============================================================================
88
+ // メッセージ(ja が正。en / zh_CN は忠実な翻訳)
89
+ // =============================================================================
90
+
91
+ export const MESSAGES = {
92
+ ja: {
93
+ installed: "skill の依存を install しました: {dir}(id: {id})",
94
+ summary: "skill の依存の準備に失敗しました({count}件)。",
95
+ "cause.conflict":
96
+ "原因: {dir} の package.json / ロックファイルに、update のコンフリクトマーカーが未解決のまま残っています。",
97
+ "remedy.conflict": "対処: {dir} のコンフリクトを解決してから、再実行してください。",
98
+ "cause.lockMissing": "原因: {dir} に {pm} 用のロックファイル({file})がありません。",
99
+ "remedy.lockMissing":
100
+ "対処: 資材リポジトリの不備の可能性があります。資材の管理者に連絡してください。",
101
+ "cause.packageJsonMissing": "原因: {dir} に package.json がありません。",
102
+ "remedy.packageJsonMissing":
103
+ "対処: 資材リポジトリの不備の可能性があります。資材の管理者に連絡してください。",
104
+ "cause.lockMismatch": "原因: {dir} の package.json とロックファイルの内容が一致していません。",
105
+ "remedy.lockMismatch":
106
+ "対処: {dir} を手元で編集した場合は、{dir} で `{pm} install` を実行してロックファイルを更新し、生成された node_modules を削除してから再実行してください。",
107
+ "cause.pmNotFound": "原因: パッケージマネージャ {pm} の実行ファイルが見つかりません。",
108
+ "remedy.pmNotFound":
109
+ "対処: {pm} をインストールするか、.accel/settings.json の packageManager を変更してください。",
110
+ "cause.network": "原因: パッケージレジストリに接続できません。",
111
+ "remedy.network": "対処: ネットワークに接続してから再実行してください。",
112
+ "cause.linkBlocked": "原因: {path} にリンク以外のディレクトリまたはファイルが存在します。",
113
+ "remedy.linkBlocked":
114
+ "対処: {path} にある既存のディレクトリ・ファイルには触れません。リンクに置き換える場合は {path} を削除してから再実行してください。",
115
+ "cause.unsafeLayout": "原因: {path} がシンボリックリンクです(CLI が作るディレクトリではありません)。",
116
+ "remedy.unsafeLayout":
117
+ "対処: {path} を削除してから再実行してください。",
118
+ "cause.unsafePath": "原因: 依存ディレクトリ {dir} がプロジェクトの外を指しています。",
119
+ "remedy.unsafePath":
120
+ "対処: {dir} のシンボリックリンクを外してから再実行してください。",
121
+ "cause.lockTimeout": "原因: 別のプロセスが {dir} の依存を準備中のまま、待ち時間内に完了しませんでした。",
122
+ "remedy.lockTimeout":
123
+ "対処: しばらく待ってから再実行してください。止まったままなら .accel/runtime/{id}.lock を削除してから再実行してください。",
124
+ "cause.installFailed":
125
+ "原因: install コマンドが失敗しました。コマンド: {command} / 作業ディレクトリ: {cwd}",
126
+ "remedy.installFailed": "対処: 出力を確認して原因を取り除いてから、再実行してください。",
127
+ outputTail: "出力(末尾):",
128
+ runnerSkipped: "skill の依存の準備に失敗したため、{script} は起動しませんでした。",
129
+ rerun: "再実行コマンド: {command}",
130
+ },
131
+ en: {
132
+ installed: "Installed skill dependencies: {dir} (id: {id})",
133
+ summary: "Failed to prepare skill dependencies ({count} failure(s)).",
134
+ "cause.conflict":
135
+ "Cause: package.json / lockfile in {dir} still contain unresolved conflict markers (an update conflict has not been resolved).",
136
+ "remedy.conflict": "Remedy: resolve the conflict in {dir}, then rerun.",
137
+ "cause.lockMissing": "Cause: {dir} has no lockfile for {pm} ({file}).",
138
+ "remedy.lockMissing":
139
+ "Remedy: the asset repository may be incomplete. Contact the asset maintainer.",
140
+ "cause.packageJsonMissing": "Cause: {dir} has no package.json.",
141
+ "remedy.packageJsonMissing":
142
+ "Remedy: the asset repository may be incomplete. Contact the asset maintainer.",
143
+ "cause.lockMismatch": "Cause: package.json and the lockfile in {dir} do not match.",
144
+ "remedy.lockMismatch":
145
+ "Remedy: if you edited {dir} locally, run `{pm} install` in {dir} to refresh the lockfile, delete the generated node_modules, then rerun.",
146
+ "cause.pmNotFound": "Cause: the package manager executable {pm} was not found.",
147
+ "remedy.pmNotFound": "Remedy: install {pm}, or change packageManager in .accel/settings.json.",
148
+ "cause.network": "Cause: the package registry is unreachable.",
149
+ "remedy.network": "Remedy: connect to the network, then rerun.",
150
+ "cause.linkBlocked": "Cause: {path} is a directory or file, not a link.",
151
+ "remedy.linkBlocked":
152
+ "Remedy: the existing directory or file at {path} is left untouched. To replace it with a link, delete {path}, then rerun.",
153
+ "cause.unsafeLayout": "Cause: {path} is a symbolic link (not a directory created by the CLI).",
154
+ "remedy.unsafeLayout": "Remedy: delete {path}, then rerun.",
155
+ "cause.unsafePath": "Cause: the dependency directory {dir} points outside the project.",
156
+ "remedy.unsafePath": "Remedy: remove the symbolic link at {dir}, then rerun.",
157
+ "cause.lockTimeout": "Cause: another process is still preparing the dependencies in {dir} and did not finish within the wait time.",
158
+ "remedy.lockTimeout":
159
+ "Remedy: wait a moment and rerun. If it stays stuck, delete .accel/runtime/{id}.lock, then rerun.",
160
+ "cause.installFailed":
161
+ "Cause: the install command failed. Command: {command} / Working directory: {cwd}",
162
+ "remedy.installFailed": "Remedy: check the output, fix the cause, then rerun.",
163
+ outputTail: "Output (tail):",
164
+ runnerSkipped: "{script} was not started because preparing skill dependencies failed.",
165
+ rerun: "Rerun command: {command}",
166
+ },
167
+ zh_CN: {
168
+ installed: "已安装 skill 依赖: {dir}(id: {id})",
169
+ summary: "skill 依赖准备失败({count} 项)。",
170
+ "cause.conflict":
171
+ "原因: {dir} 的 package.json / 锁文件中仍残留未解决的冲突标记(update 的冲突尚未解决)。",
172
+ "remedy.conflict": "处理: 解决 {dir} 的冲突后,重新执行。",
173
+ "cause.lockMissing": "原因: {dir} 中没有 {pm} 对应的锁文件({file})。",
174
+ "remedy.lockMissing": "处理: 资源仓库可能存在缺陷。请联系资源的维护者。",
175
+ "cause.packageJsonMissing": "原因: {dir} 中没有 package.json。",
176
+ "remedy.packageJsonMissing":
177
+ "处理: 资源仓库可能不完整。请联系资材维护者。",
178
+ "cause.lockMismatch": "原因: {dir} 的 package.json 与锁文件的内容不一致。",
179
+ "remedy.lockMismatch":
180
+ "处理: 如果你在本地编辑过 {dir},请在 {dir} 中执行 `{pm} install` 更新锁文件,删除生成的 node_modules 后重新执行。",
181
+ "cause.pmNotFound": "原因: 找不到包管理器 {pm} 的可执行文件。",
182
+ "remedy.pmNotFound": "处理: 请安装 {pm},或修改 .accel/settings.json 中的 packageManager。",
183
+ "cause.network": "原因: 无法连接到包注册表。",
184
+ "remedy.network": "处理: 连接网络后重新执行。",
185
+ "cause.linkBlocked": "原因: {path} 处存在非链接的目录或文件。",
186
+ "remedy.linkBlocked":
187
+ "处理: 不会触碰 {path} 处现有的目录或文件。如需替换为链接,请删除 {path} 后重新执行。",
188
+ "cause.unsafeLayout": "原因: {path} 是符号链接(不是 CLI 创建的目录)。",
189
+ "remedy.unsafeLayout": "处理: 请删除 {path} 后重新执行。",
190
+ "cause.unsafePath": "原因: 依赖目录 {dir} 指向了项目之外。",
191
+ "remedy.unsafePath": "处理: 请移除 {dir} 处的符号链接后重新执行。",
192
+ "cause.lockTimeout": "原因: 另一个进程仍在准备 {dir} 的依赖,且未在等待时间内完成。",
193
+ "remedy.lockTimeout":
194
+ "处理: 请稍候再重新执行。如果一直停滞,请删除 .accel/runtime/{id}.lock 后重新执行。",
195
+ "cause.installFailed": "原因: install 命令执行失败。命令: {command} / 工作目录: {cwd}",
196
+ "remedy.installFailed": "处理: 请查看输出并排除原因后,重新执行。",
197
+ outputTail: "输出(末尾):",
198
+ runnerSkipped: "由于 skill 依赖准备失败,未启动 {script}。",
199
+ rerun: "重新执行命令: {command}",
200
+ },
201
+ };
202
+
203
+ /** ロケールとキーからメッセージを得る(`{param}` を置換。未知のロケールは en)。 */
204
+ /**
205
+ * 表示用テキストの無害化。settings.json(git 共有)由来のパスや PM の出力が
206
+ * エージェントのコンテキストや端末へそのまま流れるため、ANSI・制御文字を除き
207
+ * 長さを抑える(CLI の sanitizeDisplayText と同じ方針)。
208
+ */
209
+ export function cleanText(value) {
210
+ const text = String(value)
211
+ .replace(/\u001b\[[0-9;?]*[ -\/]*[@-~]/g, "")
212
+ .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)/g, "")
213
+ .replace(/\r\n|[\n\t]/g, " ")
214
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "");
215
+ const points = Array.from(text);
216
+ return points.length <= MAX_TEXT_LENGTH
217
+ ? text
218
+ : `${points.slice(0, MAX_TEXT_LENGTH).join("")}...`;
219
+ }
220
+
221
+ export function t(locale, key, params) {
222
+ const table = Object.prototype.hasOwnProperty.call(MESSAGES, locale)
223
+ ? MESSAGES[locale]
224
+ : MESSAGES.en;
225
+ const template = table[key] ?? MESSAGES.en[key] ?? key;
226
+ return template.replace(/\{(\w+)\}/g, (match, name) =>
227
+ params && Object.prototype.hasOwnProperty.call(params, name)
228
+ ? cleanText(params[name])
229
+ : match,
230
+ );
231
+ }
232
+
233
+ // =============================================================================
234
+ // 純粋なヘルパー
235
+ // =============================================================================
236
+
237
+ /** 改行コードを LF に正規化する。 */
238
+ export function normalizeLf(text) {
239
+ return text.replace(/\r\n/g, "\n");
240
+ }
241
+
242
+ /**
243
+ * package.json とロックファイルの内容から id を計算する
244
+ * (LF 正規化した両ファイルをこの順に連結した SHA-256 の先頭 16 桁)。
245
+ */
246
+ export function computeId(pkgText, lockText) {
247
+ const hash = crypto.createHash("sha256");
248
+ hash.update(normalizeLf(pkgText));
249
+ hash.update(normalizeLf(lockText));
250
+ return hash.digest("hex").slice(0, 16);
251
+ }
252
+
253
+ /** 行頭のコンフリクトマーカー(<<<<<<< / ======= / >>>>>>>)が残っているか。 */
254
+ export function hasConflictMarkers(text) {
255
+ return /^(<<<<<<<|>>>>>>>)|^=======[ \t]*$/m.test(normalizeLf(text));
256
+ }
257
+
258
+ /**
259
+ * リポジトリ相対パス(POSIX)として安全か(CLI 側の isSafeRelPath と同じ規則)。
260
+ * settings.json 由来のパスによる書き込みがプロジェクトの外へ届かないようにする。
261
+ */
262
+ export function isSafeRelPath(p) {
263
+ return (
264
+ typeof p === "string" &&
265
+ p.length > 0 &&
266
+ !p.startsWith("/") &&
267
+ !p.includes("\\") &&
268
+ !/^[A-Za-z]:/.test(p) &&
269
+ !p.split("/").includes("..")
270
+ );
271
+ }
272
+
273
+ /**
274
+ * 依存ディレクトリとして受け入れるパス。プロジェクトルート自身("."。ルートの
275
+ * package.json はユーザーのもの)と `.accel/` / `.git/` 配下は対象外。
276
+ */
277
+ export function isAllowedDependencyDir(p) {
278
+ if (!isSafeRelPath(p) || p === ".") return false;
279
+ const head = p.split("/")[0];
280
+ return head !== ".accel" && head !== ".git" && head !== ".";
281
+ }
282
+
283
+ /** 通常ファイルをサイズ上限付きで読む(リンク先がデバイスファイル等でも止まらない)。 */
284
+ function readProjectFile(file) {
285
+ const fd = fs.openSync(file, "r");
286
+ try {
287
+ const st = fs.fstatSync(fd);
288
+ if (!st.isFile()) throw new Error(`not a regular file: ${file}`);
289
+ if (st.size > MAX_INPUT_BYTES) throw new Error(`file too large: ${file}`);
290
+ const buf = Buffer.alloc(st.size);
291
+ let off = 0;
292
+ while (off < st.size) {
293
+ const n = fs.readSync(fd, buf, off, st.size - off, off);
294
+ if (n === 0) break;
295
+ off += n;
296
+ }
297
+ return buf.subarray(0, off).toString("utf8");
298
+ } finally {
299
+ fs.closeSync(fd);
300
+ }
301
+ }
302
+
303
+ /** p の実体が root の内側か(root 自身は含まない)。 */
304
+ function isInsideRoot(rootReal, p) {
305
+ let real;
306
+ try {
307
+ real = fs.realpathSync(p);
308
+ } catch {
309
+ return false;
310
+ }
311
+ return real.startsWith(rootReal + path.sep);
312
+ }
313
+
314
+ /**
315
+ * `.accel` / `.accel/runtime` が CLI の作るディレクトリでない(シンボリックリンク等)
316
+ * 場合はそのパス(ルート相対)を返す。GC が runtime 配下を削除するため、リンク経由で
317
+ * プロジェクト外へ届くレイアウトでは何もしない。
318
+ */
319
+ function findUnsafeLayout(root, rootReal) {
320
+ for (const rel of [".accel", path.join(".accel", "runtime")]) {
321
+ const abs = path.join(root, rel);
322
+ let st;
323
+ try {
324
+ st = fs.lstatSync(abs);
325
+ } catch {
326
+ continue;
327
+ }
328
+ if (st.isSymbolicLink() || !st.isDirectory()) return rel.split(path.sep).join("/");
329
+ if (!isInsideRoot(rootReal, abs)) return rel.split(path.sep).join("/");
330
+ }
331
+ return null;
332
+ }
333
+
334
+ /** install 失敗の出力を原因で分類する(ロック不整合をネットワークより優先)。 */
335
+ export function classifyInstallFailure(pm, output) {
336
+ const lockPatterns = FAILURE_PATTERNS.lockMismatch[pm] ?? [];
337
+ if (lockPatterns.some((re) => re.test(output))) return "lockMismatch";
338
+ if (FAILURE_PATTERNS.network.some((re) => re.test(output))) return "network";
339
+ return "other";
340
+ }
341
+
342
+ /** ANSI エスケープシーケンスを除去する。 */
343
+ function stripAnsi(text) {
344
+ return text
345
+ .replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g, "")
346
+ .replace(/\x1b\[[0-9;?]*[ -/]*[@-~]/g, "");
347
+ }
348
+
349
+ /** 出力の末尾 N 行を得る。 */
350
+ function tailLines(output, count) {
351
+ const lines = normalizeLf(output).replace(/\s+$/, "").split("\n");
352
+ return lines.slice(-count);
353
+ }
354
+
355
+ // =============================================================================
356
+ // 設定・状態ファイル
357
+ // =============================================================================
358
+
359
+ /**
360
+ * `.accel/settings.json` を読む。読めない・形が違う場合は null。
361
+ * dependencies は安全な相対パスだけを残し、重複を除いてソートする。
362
+ */
363
+ function readSettings(root) {
364
+ let parsed;
365
+ try {
366
+ parsed = JSON.parse(fs.readFileSync(path.join(root, ".accel", "settings.json"), "utf8"));
367
+ } catch {
368
+ return null;
369
+ }
370
+ if (!parsed || typeof parsed !== "object") return null;
371
+ const packageManager =
372
+ typeof parsed.packageManager === "string" &&
373
+ Object.prototype.hasOwnProperty.call(LOCKFILES, parsed.packageManager)
374
+ ? parsed.packageManager
375
+ : DEFAULT_PM;
376
+ const locale = typeof parsed.locale === "string" ? parsed.locale : "en";
377
+ const raw = Array.isArray(parsed.dependencies) ? parsed.dependencies : [];
378
+ // 辞書順(コードポイント順。CLI 側の collectDependencyDirs と同じ規則)
379
+ const dependencies = [...new Set(raw.filter(isAllowedDependencyDir))].sort();
380
+ return { packageManager, locale, dependencies };
381
+ }
382
+
383
+ /** `.accel/runtime/state.json` を読む。読めない・壊れている場合は空として扱う。 */
384
+ function readState(file) {
385
+ try {
386
+ const parsed = JSON.parse(fs.readFileSync(file, "utf8"));
387
+ if (!parsed || typeof parsed !== "object") return { ids: {} };
388
+ if (!parsed.ids || typeof parsed.ids !== "object" || Array.isArray(parsed.ids)) {
389
+ return { ids: {} };
390
+ }
391
+ const ids = {};
392
+ for (const [id, entry] of Object.entries(parsed.ids)) {
393
+ // id は内容ハッシュ(16 桁の 16 進)に限る。state.json は git 共有されない前提だが、
394
+ // 誤ってコミットされた・書き換えられた場合でも rmSync の対象を runtime 配下に閉じる
395
+ if (!ID_PATTERN.test(id)) continue;
396
+ if (!entry || typeof entry !== "object" || typeof entry.completedAt !== "string") continue;
397
+ ids[id] = {
398
+ completedAt: entry.completedAt,
399
+ lastReferencedAt:
400
+ typeof entry.lastReferencedAt === "string" ? entry.lastReferencedAt : entry.completedAt,
401
+ };
402
+ }
403
+ return { ids };
404
+ } catch {
405
+ return { ids: {} };
406
+ }
407
+ }
408
+
409
+ /** state.json を一時ファイル経由で書き出す(途中で落ちても壊れた状態を残さない)。 */
410
+ function writeState(file, state) {
411
+ fs.mkdirSync(path.dirname(file), { recursive: true });
412
+ const tmp = `${file}.${crypto.randomBytes(6).toString("hex")}.tmp`;
413
+ fs.writeFileSync(tmp, `${JSON.stringify(state, null, 2)}\n`);
414
+ fs.renameSync(tmp, file);
415
+ }
416
+
417
+ // =============================================================================
418
+ // 同一 id への並行 install の排他
419
+ // =============================================================================
420
+
421
+ function isProcessAlive(pid) {
422
+ try {
423
+ process.kill(pid, 0);
424
+ return true;
425
+ } catch (err) {
426
+ return err && err.code === "EPERM";
427
+ }
428
+ }
429
+
430
+ function sleepSync(ms) {
431
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
432
+ }
433
+
434
+ /** ロックの所有者情報(pid・開始時刻)を読む。無い・壊れている場合は null。 */
435
+ function readLockOwner(lockDir) {
436
+ try {
437
+ const parsed = JSON.parse(fs.readFileSync(path.join(lockDir, "owner.json"), "utf8"));
438
+ return parsed && typeof parsed === "object" ? parsed : null;
439
+ } catch {
440
+ return null;
441
+ }
442
+ }
443
+
444
+ /**
445
+ * ロックが放置されたものか。所有プロセスが死んでいる、または開始から一定時間を
446
+ * 過ぎていれば stale とみなす(所有者情報が無い場合はディレクトリの更新時刻で判定)。
447
+ */
448
+ function lockIsStale(lockDir, nowMs) {
449
+ const owner = readLockOwner(lockDir);
450
+ if (owner === null) {
451
+ try {
452
+ return nowMs - fs.statSync(lockDir).mtimeMs > LOCK_STALE_MS;
453
+ } catch {
454
+ return true;
455
+ }
456
+ }
457
+ if (typeof owner.pid === "number" && !isProcessAlive(owner.pid)) return true;
458
+ const started = Date.parse(owner.startedAt);
459
+ return !Number.isFinite(started) || nowMs - started > LOCK_STALE_MS;
460
+ }
461
+
462
+ function lockWaitMs() {
463
+ const raw = Number(process.env.ACCEL_ENSURE_LOCK_WAIT_MS);
464
+ return Number.isFinite(raw) && raw >= 0 ? raw : LOCK_WAIT_MS;
465
+ }
466
+
467
+ /**
468
+ * id のロックを取得する。取得できたら解放関数を返す。別プロセスが保持中なら
469
+ * 完了を待ち(stale なら引き継ぐ)、待ち時間の上限を超えたら null を返す。
470
+ */
471
+ function acquireLock(runtimeDir, id) {
472
+ const lockDir = path.join(runtimeDir, `${id}${LOCK_SUFFIX}`);
473
+ const deadline = Date.now() + lockWaitMs();
474
+ fs.mkdirSync(runtimeDir, { recursive: true });
475
+ for (;;) {
476
+ try {
477
+ fs.mkdirSync(lockDir);
478
+ fs.writeFileSync(
479
+ path.join(lockDir, "owner.json"),
480
+ JSON.stringify({ pid: process.pid, startedAt: new Date().toISOString() }),
481
+ );
482
+ return () => {
483
+ try {
484
+ fs.rmSync(lockDir, { recursive: true, force: true });
485
+ } catch {
486
+ // 解放に失敗しても stale 判定で回収される
487
+ }
488
+ };
489
+ } catch (err) {
490
+ if (!err || err.code !== "EEXIST") throw err;
491
+ }
492
+ if (lockIsStale(lockDir, Date.now())) {
493
+ try {
494
+ fs.rmSync(lockDir, { recursive: true, force: true });
495
+ } catch {
496
+ // 相手が同時に解放した等。次の周回で再試行する
497
+ }
498
+ continue;
499
+ }
500
+ if (Date.now() >= deadline) return null;
501
+ sleepSync(LOCK_POLL_MS);
502
+ }
503
+ }
504
+
505
+ // =============================================================================
506
+ // パッケージマネージャの実行
507
+ // =============================================================================
508
+
509
+ /**
510
+ * パッケージマネージャの実行ファイルを解決する。
511
+ * POSIX はそのまま(spawn が PATH を探す)。Windows は PATH × PATHEXT を走査し、
512
+ * 見つからなければ null(→ pmNotFound)。
513
+ */
514
+ function resolveExecutable(pm) {
515
+ if (process.platform !== "win32") return pm;
516
+ const dirs = (process.env.PATH ?? process.env.Path ?? "").split(";").filter(Boolean);
517
+ const exts = (process.env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter(Boolean);
518
+ for (const dir of dirs) {
519
+ for (const ext of exts) {
520
+ const candidate = path.join(dir, pm + ext);
521
+ try {
522
+ if (fs.statSync(candidate).isFile()) return candidate;
523
+ } catch {
524
+ // 次の候補へ
525
+ }
526
+ }
527
+ }
528
+ return null;
529
+ }
530
+
531
+ /**
532
+ * install コマンドを実行する。
533
+ * 戻り値: { kind: "ok" } | { kind: "pmNotFound" } | { kind: "failed", command, output }
534
+ */
535
+ function runPackageManager(pm, cwd) {
536
+ const args = INSTALL_ARGS[pm] ?? INSTALL_ARGS[DEFAULT_PM];
537
+ const command = `${pm} ${args.join(" ")}`;
538
+ const exe = resolveExecutable(pm);
539
+ if (exe === null) return { kind: "pmNotFound" };
540
+ const options = {
541
+ cwd,
542
+ env: { ...process.env, NO_COLOR: "1", FORCE_COLOR: "0" },
543
+ encoding: "utf8",
544
+ windowsHide: true,
545
+ maxBuffer: MAX_OUTPUT_BUFFER,
546
+ stdio: ["ignore", "pipe", "pipe"],
547
+ };
548
+ // Windows の .cmd / .bat はシェル経由でしか起動できない。引数は固定の定数なので
549
+ // 実行ファイルのパスだけ引用符で囲む
550
+ const result =
551
+ process.platform === "win32" && /\.(cmd|bat)$/i.test(exe)
552
+ ? spawnSync(`"${exe}" ${args.join(" ")}`, { ...options, shell: true })
553
+ : spawnSync(exe, args, options);
554
+ if (result.error) {
555
+ if (result.error.code === "ENOENT") return { kind: "pmNotFound" };
556
+ return {
557
+ kind: "failed",
558
+ command,
559
+ output: String(result.error.message ?? result.error),
560
+ };
561
+ }
562
+ const output = stripAnsi(`${result.stdout ?? ""}${result.stderr ?? ""}`);
563
+ if (result.status === 0) return { kind: "ok" };
564
+ return { kind: "failed", command, output };
565
+ }
566
+
567
+ // =============================================================================
568
+ // リンク
569
+ // =============================================================================
570
+
571
+ /** Windows の `\\?\` 接頭辞を除き、比較用に正規化する。 */
572
+ function normalizeForCompare(p) {
573
+ let out = path.resolve(p);
574
+ if (process.platform === "win32") {
575
+ out = out.replace(/^\\\\\?\\/, "").toLowerCase();
576
+ }
577
+ return out;
578
+ }
579
+
580
+ /** リンクの参照先を絶対パスで得る(読めなければ null)。 */
581
+ function readLinkTarget(link) {
582
+ try {
583
+ const raw = fs.readlinkSync(link);
584
+ const stripped = process.platform === "win32" ? raw.replace(/^\\\\\?\\/, "") : raw;
585
+ return path.resolve(path.dirname(link), stripped);
586
+ } catch {
587
+ return null;
588
+ }
589
+ }
590
+
591
+ function removeLink(link) {
592
+ try {
593
+ fs.unlinkSync(link);
594
+ } catch (error) {
595
+ if (error && (error.code === "EPERM" || error.code === "EISDIR")) {
596
+ fs.rmdirSync(link);
597
+ return;
598
+ }
599
+ throw error;
600
+ }
601
+ }
602
+
603
+ function createLink(link, targetAbs) {
604
+ if (process.platform === "win32") {
605
+ fs.symlinkSync(targetAbs, link, "junction");
606
+ } else {
607
+ fs.symlinkSync(path.relative(path.dirname(link), targetAbs), link, "dir");
608
+ }
609
+ }
610
+
611
+ /**
612
+ * 依存ディレクトリの node_modules を .accel/runtime/<id>/node_modules へのリンクにする。
613
+ * 存在しない → 作成、正しい先を指すリンク → 何もしない、別の先を指すリンク → 作り直す、
614
+ * リンク以外 → 触らずに失敗として返す。
615
+ */
616
+ function ensureLink(depDirAbs, targetAbs) {
617
+ const link = path.join(depDirAbs, "node_modules");
618
+ let stat = null;
619
+ try {
620
+ stat = fs.lstatSync(link);
621
+ } catch (error) {
622
+ if (!error || error.code !== "ENOENT") throw error;
623
+ }
624
+ if (stat) {
625
+ if (!stat.isSymbolicLink()) return { kind: "linkBlocked" };
626
+ const current = readLinkTarget(link);
627
+ if (current !== null && normalizeForCompare(current) === normalizeForCompare(targetAbs)) {
628
+ return { kind: "ok" };
629
+ }
630
+ removeLink(link);
631
+ }
632
+ createLink(link, targetAbs);
633
+ return { kind: "ok" };
634
+ }
635
+
636
+ // =============================================================================
637
+ // ensure 本体
638
+ // =============================================================================
639
+
640
+ /**
641
+ * 依存ディレクトリを処理し、結果を返す。
642
+ * 戻り値: { installed: [{ dir, id }], failures: [{ kind, params, tail? }] }
643
+ */
644
+ export function ensure(root, settings) {
645
+ const { packageManager: pm, dependencies } = settings;
646
+ const lockName = LOCKFILES[pm] ?? LOCKFILES[DEFAULT_PM];
647
+ const runtimeDir = path.join(root, ".accel", "runtime");
648
+ const stateFile = path.join(runtimeDir, "state.json");
649
+ const installed = [];
650
+ const failures = [];
651
+
652
+ // 0. レイアウトの検査。.accel / .accel/runtime がリンクなら GC も install も行わない
653
+ const rootReal = fs.realpathSync(root);
654
+ const unsafe = findUnsafeLayout(root, rootReal);
655
+ if (unsafe !== null) {
656
+ failures.push({ kind: "unsafeLayout", params: { path: unsafe } });
657
+ return { installed, failures };
658
+ }
659
+
660
+ const state = readState(stateFile);
661
+ const referenced = new Set();
662
+ const now = new Date().toISOString();
663
+
664
+ for (const dep of dependencies) {
665
+ const depDirAbs = path.resolve(root, dep);
666
+ const pkgFile = path.join(depDirAbs, "package.json");
667
+ const lockFile = path.join(depDirAbs, lockName);
668
+
669
+ // 1. 依存ディレクトリの実体がプロジェクト内にあること、両ファイルの存在確認
670
+ if (fs.existsSync(depDirAbs) && !isInsideRoot(rootReal, depDirAbs)) {
671
+ failures.push({ kind: "unsafePath", params: { dir: dep } });
672
+ continue;
673
+ }
674
+ let pkgText;
675
+ let lockText;
676
+ try {
677
+ pkgText = readProjectFile(pkgFile);
678
+ } catch {
679
+ failures.push({ kind: "packageJsonMissing", params: { dir: dep } });
680
+ continue;
681
+ }
682
+ try {
683
+ lockText = readProjectFile(lockFile);
684
+ } catch {
685
+ failures.push({
686
+ kind: "lockMissing",
687
+ params: { dir: dep, file: lockName, pm },
688
+ });
689
+ continue;
690
+ }
691
+
692
+ // 2. コンフリクトマーカー
693
+ if (hasConflictMarkers(pkgText) || hasConflictMarkers(lockText)) {
694
+ failures.push({ kind: "conflict", params: { dir: dep } });
695
+ continue;
696
+ }
697
+
698
+ // 3. id と完成記録
699
+ const id = computeId(pkgText, lockText);
700
+ referenced.add(id);
701
+ const idDir = path.join(runtimeDir, id);
702
+
703
+ // 4. 未完成なら install(同一 id への並行 install はロックで排他する。
704
+ // 別プロセスが準備中なら完了を待ち、完成していれば install を省略する)
705
+ if (!state.ids[id]) {
706
+ const release = acquireLock(runtimeDir, id);
707
+ if (release === null) {
708
+ failures.push({ kind: "lockTimeout", params: { dir: dep, id } });
709
+ continue;
710
+ }
711
+ let installFailure = null;
712
+ try {
713
+ const fresh = readState(stateFile);
714
+ if (fresh.ids[id]) {
715
+ state.ids[id] = fresh.ids[id];
716
+ } else {
717
+ fs.mkdirSync(idDir, { recursive: true });
718
+ fs.writeFileSync(path.join(idDir, "package.json"), normalizeLf(pkgText));
719
+ fs.writeFileSync(path.join(idDir, lockName), normalizeLf(lockText));
720
+ const result = runPackageManager(pm, idDir);
721
+ if (result.kind === "pmNotFound") {
722
+ installFailure = { kind: "pmNotFound", params: { pm } };
723
+ } else if (result.kind === "failed") {
724
+ const cause = classifyInstallFailure(pm, result.output);
725
+ const tail = tailLines(result.output, OUTPUT_TAIL_LINES);
726
+ if (cause === "lockMismatch") {
727
+ installFailure = { kind: "lockMismatch", params: { dir: dep, pm }, tail };
728
+ } else if (cause === "network") {
729
+ installFailure = { kind: "network", params: {}, tail };
730
+ } else {
731
+ installFailure = {
732
+ kind: "installFailed",
733
+ params: { command: result.command, cwd: idDir },
734
+ tail,
735
+ };
736
+ }
737
+ } else {
738
+ // 依存 0 件の ci は node_modules を作らないが、リンク先は存在させる
739
+ fs.mkdirSync(path.join(idDir, "node_modules"), { recursive: true });
740
+ state.ids[id] = { completedAt: now, lastReferencedAt: now };
741
+ installed.push({ dir: dep, id });
742
+ // 完成記録はロック保持中に書く(他プロセスが待たずに済むよう即時反映)
743
+ const latest = readState(stateFile);
744
+ latest.ids[id] = state.ids[id];
745
+ writeState(stateFile, latest);
746
+ }
747
+ }
748
+ } finally {
749
+ release();
750
+ }
751
+ if (installFailure !== null) {
752
+ failures.push(installFailure);
753
+ continue;
754
+ }
755
+ }
756
+
757
+ // 5. リンク(完成済みの id だけ)
758
+ const link = ensureLink(depDirAbs, path.join(idDir, "node_modules"));
759
+ if (link.kind === "linkBlocked") {
760
+ failures.push({
761
+ kind: "linkBlocked",
762
+ params: { path: `${dep}/node_modules` },
763
+ });
764
+ }
765
+ }
766
+
767
+ // 参照中の id の最終参照日時を更新する
768
+ for (const id of referenced) {
769
+ if (state.ids[id]) state.ids[id].lastReferencedAt = now;
770
+ }
771
+
772
+ // GC(失敗は無視する)
773
+ const nowMs = Date.parse(now);
774
+ const removedByGc = new Set();
775
+ for (const [id, entry] of Object.entries(state.ids)) {
776
+ if (referenced.has(id)) continue;
777
+ const last = Date.parse(entry.lastReferencedAt);
778
+ if (Number.isFinite(last) && nowMs - last < GC_AGE_MS) continue;
779
+ try {
780
+ fs.rmSync(path.join(runtimeDir, id), { recursive: true, force: true });
781
+ delete state.ids[id];
782
+ removedByGc.add(id);
783
+ } catch {
784
+ // 次回に持ち越す
785
+ }
786
+ }
787
+ let entries = [];
788
+ try {
789
+ entries = fs.readdirSync(runtimeDir, { withFileTypes: true });
790
+ } catch {
791
+ // runtime ディレクトリが無ければ残骸も無い
792
+ }
793
+ for (const entry of entries) {
794
+ if (entry.name === "state.json") continue;
795
+ if (entry.isDirectory() && entry.name.endsWith(LOCK_SUFFIX)) {
796
+ // 排他ロックは所有者が生きていれば残す。放置されたものだけ回収する
797
+ const lockDir = path.join(runtimeDir, entry.name);
798
+ if (lockIsStale(lockDir, nowMs)) {
799
+ try {
800
+ fs.rmSync(lockDir, { recursive: true, force: true });
801
+ } catch {
802
+ // 次回に持ち越す
803
+ }
804
+ }
805
+ continue;
806
+ }
807
+ if (referenced.has(entry.name) || state.ids[entry.name]) continue;
808
+ const isLeftover = entry.isDirectory() || /^state\.json\..*\.tmp$/.test(entry.name);
809
+ if (!isLeftover) continue;
810
+ try {
811
+ fs.rmSync(path.join(runtimeDir, entry.name), {
812
+ recursive: true,
813
+ force: true,
814
+ });
815
+ } catch {
816
+ // 次回に持ち越す
817
+ }
818
+ }
819
+
820
+ // state.json を書き出す(書くものが無く runtime ディレクトリも無ければ作らない)。
821
+ // 並行して完成した他プロセスの記録を失わないよう、最新の内容に自分の更新を重ねる
822
+ if (Object.keys(state.ids).length > 0 || fs.existsSync(runtimeDir)) {
823
+ const latest = readState(stateFile);
824
+ for (const [id, entry] of Object.entries(state.ids)) latest.ids[id] = entry;
825
+ for (const id of removedByGc) delete latest.ids[id];
826
+ writeState(stateFile, latest);
827
+ }
828
+
829
+ return { installed, failures };
830
+ }
831
+
832
+ // =============================================================================
833
+ // 出力
834
+ // =============================================================================
835
+
836
+ function formatGuidance(locale, failures) {
837
+ const lines = [t(locale, "summary", { count: failures.length })];
838
+ failures.forEach((failure, index) => {
839
+ if (index > 0) lines.push("");
840
+ lines.push(t(locale, `cause.${failure.kind}`, failure.params));
841
+ lines.push(t(locale, `remedy.${failure.kind}`, failure.params));
842
+ if (failure.tail && failure.tail.length > 0) {
843
+ lines.push(t(locale, "outputTail"));
844
+ for (const line of failure.tail) lines.push(` ${cleanText(line)}`);
845
+ }
846
+ });
847
+ lines.push(t(locale, "rerun", { command: RERUN_COMMAND }));
848
+ return `${lines.join("\n")}\n`;
849
+ }
850
+
851
+ // =============================================================================
852
+ // エントリポイント
853
+ // =============================================================================
854
+
855
+ function main() {
856
+ const root = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
857
+ const args = process.argv.slice(2);
858
+ const settings = readSettings(root);
859
+ const locale = settings ? settings.locale : "en";
860
+
861
+ let outcome = { installed: [], failures: [] };
862
+ if (settings && settings.dependencies.length > 0) {
863
+ try {
864
+ outcome = ensure(root, settings);
865
+ } catch (error) {
866
+ // 予期しない例外はスタックトレースを出さず、案内として扱う
867
+ const message = error && error.message ? String(error.message) : String(error);
868
+ outcome = {
869
+ installed: [],
870
+ failures: [
871
+ {
872
+ kind: "installFailed",
873
+ params: { command: RERUN_COMMAND, cwd: root },
874
+ tail: [message],
875
+ },
876
+ ],
877
+ };
878
+ }
879
+ }
880
+
881
+ for (const { dir, id } of outcome.installed) {
882
+ process.stdout.write(`${t(locale, "installed", { dir, id })}\n`);
883
+ }
884
+ const failed = outcome.failures.length > 0;
885
+ if (failed) process.stdout.write(formatGuidance(locale, outcome.failures));
886
+
887
+ if (args.length === 0) {
888
+ // ensure のみ: フック・CLI から。失敗しても 0(標準出力の案内をエージェントへ渡す)
889
+ // ただし CLI の子プロセス(ACCEL_ENSURE_STRICT=1)では失敗を終了コードで伝える
890
+ process.exitCode = failed && process.env.ACCEL_ENSURE_STRICT === "1" ? 1 : 0;
891
+ return;
892
+ }
893
+
894
+ // ランナー: 失敗時は <script> を起動しない
895
+ const [script, ...scriptArgs] = args;
896
+ if (failed) {
897
+ process.stdout.write(`${t(locale, "runnerSkipped", { script })}\n`);
898
+ process.exitCode = 1;
899
+ return;
900
+ }
901
+ const result = spawnSync(process.execPath, [script, ...scriptArgs], {
902
+ stdio: "inherit",
903
+ cwd: process.cwd(),
904
+ });
905
+ if (result.error) {
906
+ process.stderr.write(`${String(result.error.message ?? result.error)}\n`);
907
+ process.exit(1);
908
+ }
909
+ process.exit(result.status === null ? 1 : result.status);
910
+ }
911
+
912
+ const isMain =
913
+ Boolean(process.argv[1]) && path.resolve(process.argv[1]) === fileURLToPath(import.meta.url);
914
+ if (isMain) main();