minicode-ai 0.9.26

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 (162) hide show
  1. package/CHANGELOG.md +935 -0
  2. package/LICENSE +21 -0
  3. package/README.md +200 -0
  4. package/cli/args.ts +195 -0
  5. package/cli/auto-update.ts +108 -0
  6. package/cli/commands/auth.ts +166 -0
  7. package/cli/commands/config.ts +382 -0
  8. package/cli/commands/doctor.ts +128 -0
  9. package/cli/commands/exec.ts +179 -0
  10. package/cli/commands/mcp.ts +35 -0
  11. package/cli/commands/memory.ts +107 -0
  12. package/cli/commands/pricing.ts +100 -0
  13. package/cli/commands/providers.ts +162 -0
  14. package/cli/commands/sessions.ts +128 -0
  15. package/cli/commands/skills.ts +61 -0
  16. package/cli/commands/stats.ts +82 -0
  17. package/cli/commands.ts +317 -0
  18. package/cli/index.ts +539 -0
  19. package/cli/model-manager.ts +112 -0
  20. package/cli/provider-manager.ts +111 -0
  21. package/cli/repl.ts +734 -0
  22. package/cli/router.ts +124 -0
  23. package/cli/setup.ts +780 -0
  24. package/cli/wizard.ts +21 -0
  25. package/docs/ARCHITECTURE.html +1222 -0
  26. package/docs/README.md +109 -0
  27. package/docs/architecture.md +44 -0
  28. package/docs/changelog.md +3 -0
  29. package/package.json +91 -0
  30. package/src/agents/pool.ts +43 -0
  31. package/src/app/mentions.ts +50 -0
  32. package/src/app/provider-layer.ts +118 -0
  33. package/src/app/rag-layer.ts +105 -0
  34. package/src/app/session.ts +154 -0
  35. package/src/app/tool-layer.ts +56 -0
  36. package/src/config.ts +372 -0
  37. package/src/constants.ts +119 -0
  38. package/src/hooks/run.ts +89 -0
  39. package/src/lib/atomic-write.ts +88 -0
  40. package/src/lib/db-path.ts +36 -0
  41. package/src/lib/git-hardening.ts +91 -0
  42. package/src/lib/ignore.ts +58 -0
  43. package/src/lib/keystore.ts +202 -0
  44. package/src/lib/net.ts +70 -0
  45. package/src/lib/safe-open.ts +138 -0
  46. package/src/lib/session-id.ts +23 -0
  47. package/src/lib/trash.ts +38 -0
  48. package/src/lib/trusted-exec.ts +81 -0
  49. package/src/lsp/client.ts +395 -0
  50. package/src/mcp/client.ts +400 -0
  51. package/src/mcp/http-transport.ts +344 -0
  52. package/src/mcp/server.ts +538 -0
  53. package/src/mcp/transport.ts +150 -0
  54. package/src/memory/files.ts +159 -0
  55. package/src/memory/vector.ts +775 -0
  56. package/src/policy/allowlist.ts +67 -0
  57. package/src/policy/bash-guard.ts +465 -0
  58. package/src/policy/compaction.ts +271 -0
  59. package/src/policy/context.ts +161 -0
  60. package/src/policy/executor.ts +199 -0
  61. package/src/policy/jail.ts +127 -0
  62. package/src/policy/permission.ts +517 -0
  63. package/src/policy/pricing.ts +336 -0
  64. package/src/policy/ratelimit.ts +54 -0
  65. package/src/policy/sandbox-policy.ts +157 -0
  66. package/src/policy/scrub.ts +138 -0
  67. package/src/policy/update-check.ts +200 -0
  68. package/src/policy/usage.ts +292 -0
  69. package/src/policy/verifier.ts +181 -0
  70. package/src/providers/anthropic.ts +401 -0
  71. package/src/providers/auth-store.ts +139 -0
  72. package/src/providers/build.ts +136 -0
  73. package/src/providers/detect.ts +126 -0
  74. package/src/providers/effort.ts +165 -0
  75. package/src/providers/guards.ts +107 -0
  76. package/src/providers/oauth.ts +326 -0
  77. package/src/providers/presets.ts +122 -0
  78. package/src/providers/provision.ts +298 -0
  79. package/src/providers/responses.ts +371 -0
  80. package/src/providers/router.ts +247 -0
  81. package/src/repo/repomap.ts +470 -0
  82. package/src/sandbox/docker.ts +129 -0
  83. package/src/sandbox/os.ts +193 -0
  84. package/src/session/checkpoint.ts +543 -0
  85. package/src/session/journal.ts +1347 -0
  86. package/src/session/persistence.ts +446 -0
  87. package/src/session/shadow-git.ts +351 -0
  88. package/src/session/turn-marker.ts +118 -0
  89. package/src/skills/loader.ts +117 -0
  90. package/src/telemetry/trace.ts +283 -0
  91. package/src/tools/ask_user.ts +54 -0
  92. package/src/tools/bash.ts +400 -0
  93. package/src/tools/code_run.ts +96 -0
  94. package/src/tools/delete_file.ts +31 -0
  95. package/src/tools/edit.ts +204 -0
  96. package/src/tools/git.ts +301 -0
  97. package/src/tools/glob.ts +90 -0
  98. package/src/tools/grep.ts +281 -0
  99. package/src/tools/hashline.ts +66 -0
  100. package/src/tools/index.ts +103 -0
  101. package/src/tools/lsp.ts +346 -0
  102. package/src/tools/mcp_call.ts +163 -0
  103. package/src/tools/memory.ts +144 -0
  104. package/src/tools/move_file.ts +47 -0
  105. package/src/tools/patch.ts +86 -0
  106. package/src/tools/read_file.ts +130 -0
  107. package/src/tools/read_image.ts +80 -0
  108. package/src/tools/submit_result.ts +49 -0
  109. package/src/tools/task.ts +346 -0
  110. package/src/tools/todo.ts +201 -0
  111. package/src/tools/web_fetch.ts +161 -0
  112. package/src/tools/web_search.ts +156 -0
  113. package/src/tools/write_file.ts +42 -0
  114. package/src/ui/approval/prompt.ts +76 -0
  115. package/src/ui/assistant/simple.ts +568 -0
  116. package/src/ui/assistant/turn-status.ts +303 -0
  117. package/src/ui/contract.ts +55 -0
  118. package/src/ui/footer.ts +105 -0
  119. package/src/ui/input/input.ts +805 -0
  120. package/src/ui/input/prompt-engine.ts +606 -0
  121. package/src/ui/render/collapse.ts +84 -0
  122. package/src/ui/render/detail.ts +24 -0
  123. package/src/ui/render/diff.ts +181 -0
  124. package/src/ui/render/errors.ts +239 -0
  125. package/src/ui/render/format.ts +54 -0
  126. package/src/ui/render/highlight.ts +294 -0
  127. package/src/ui/render/markdown.ts +120 -0
  128. package/src/ui/render/money.ts +12 -0
  129. package/src/ui/render/reasoning.ts +20 -0
  130. package/src/ui/render/sanitize.ts +80 -0
  131. package/src/ui/render/table.ts +88 -0
  132. package/src/ui/render/theme.ts +339 -0
  133. package/src/ui/render/width.ts +256 -0
  134. package/src/ui/render/wrap.ts +120 -0
  135. package/src/ui/runtime/bus-debug.ts +83 -0
  136. package/src/ui/runtime/chrome.ts +301 -0
  137. package/src/ui/runtime/spinner.ts +77 -0
  138. package/src/ui/runtime/statusline.ts +227 -0
  139. package/src/ui/screens/model-manager.ts +434 -0
  140. package/src/ui/screens/overlay.ts +61 -0
  141. package/src/ui/screens/picker.ts +307 -0
  142. package/src/ui/screens/provider-manager.ts +450 -0
  143. package/src/ui/screens/wizard.ts +132 -0
  144. package/vendor/minicore/VENDOR.md +29 -0
  145. package/vendor/minicore/package.json +21 -0
  146. package/vendor/minicore/src/core/budget.ts +26 -0
  147. package/vendor/minicore/src/core/compact.ts +76 -0
  148. package/vendor/minicore/src/core/errors.ts +60 -0
  149. package/vendor/minicore/src/core/events.ts +74 -0
  150. package/vendor/minicore/src/core/executor.ts +139 -0
  151. package/vendor/minicore/src/core/history.ts +32 -0
  152. package/vendor/minicore/src/core/index.ts +42 -0
  153. package/vendor/minicore/src/core/loop.ts +344 -0
  154. package/vendor/minicore/src/core/permission.ts +24 -0
  155. package/vendor/minicore/src/core/provider.ts +39 -0
  156. package/vendor/minicore/src/core/recovery.ts +34 -0
  157. package/vendor/minicore/src/core/session.ts +327 -0
  158. package/vendor/minicore/src/core/snapshot.ts +142 -0
  159. package/vendor/minicore/src/core/tokens.ts +111 -0
  160. package/vendor/minicore/src/core/tool.ts +118 -0
  161. package/vendor/minicore/src/core/types.ts +50 -0
  162. package/vendor/minicore/src/providers/openai-compat.ts +366 -0
@@ -0,0 +1,351 @@
1
+ import { spawn } from "node:child_process"
2
+ import { randomUUID } from "node:crypto"
3
+ import { rm } from "node:fs/promises"
4
+ import { join, resolve } from "node:path"
5
+ import { LIMITS } from "../constants.ts"
6
+ import { GIT_NO_DIFF_DRIVERS, GIT_SAFE_BASE, gitFilterNeutralizers } from "../lib/git-hardening.ts"
7
+ import { sanitizeSessionPart } from "../lib/session-id.ts"
8
+ import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
9
+ import { sanitizeSpawnEnv } from "../policy/scrub.ts"
10
+
11
+ // Checkpoint berbasis objek git ("shadow git").
12
+ //
13
+ // Pendekatan lama (`snapshotWorkspace`) menyalin ISI setiap file ke JSON
14
+ // manifest: O(ukuran workspace) per turn, di-cap 200 file, dan memuat
15
+ // `spawnSync git status` di jalur async. Untuk repo menengah saja manifestnya
16
+ // sudah puluhan MB dan cap-nya membuat undo tidak lengkap secara senyap.
17
+ //
18
+ // Di sini kita memakai object store git yang sudah ada:
19
+ // 1. index sementara (GIT_INDEX_FILE) → `git add -A` → `git write-tree`
20
+ // 2. tree di-pin dengan ref di namespace `refs/minicode/` supaya `gc` tidak
21
+ // membuangnya
22
+ // 3. undo = diff dua tree, lalu pulihkan hanya path yang berubah
23
+ //
24
+ // Yang penting: index dan HEAD milik user TIDAK PERNAH disentuh. Tidak ada
25
+ // `git add`, `commit`, `checkout`, `reset`, atau `stash` pada state user. Ref
26
+ // menunjuk langsung ke *tree*, bukan commit, sehingga tidak muncul di
27
+ // `git log --all` maupun `git branch`.
28
+ //
29
+ // Batas yang harus jujur: `git add -A` menghormati `.gitignore`, jadi file yang
30
+ // di-ignore tidak ter-snapshot dan perubahan padanya tidak bisa di-undo. Itu
31
+ // disengaja — kita tidak ingin menyimpan `node_modules` atau `.minicode/*.db` —
32
+ // tapi berarti undo bukan "seluruh disk", melainkan "seluruh yang dilacak git".
33
+
34
+ export interface ShadowSnapshot {
35
+ /** SHA tree git. */
36
+ tree: string
37
+ /** Nama ref yang mem-pin tree agar aman dari gc. */
38
+ ref: string
39
+ }
40
+
41
+ export interface ShadowChange {
42
+ /** A=added, M=modified, D=deleted, R=renamed (dari sudut pandang "sesudah"). */
43
+ status: "A" | "M" | "D" | "R"
44
+ path: string
45
+ /** Untuk rename: path lama. */
46
+ from?: string
47
+ }
48
+
49
+ const REF_NAMESPACE = "refs/minicode"
50
+
51
+ function git(
52
+ args: string[],
53
+ cwd: string,
54
+ opts: { env?: Record<string, string>; timeoutMs?: number } = {},
55
+ ): Promise<{ code: number; stdout: string; stderr: string }> {
56
+ return new Promise((resolveOut) => {
57
+ // `core.autocrlf=false` WAJIB: di Windows default-nya `true`, sehingga
58
+ // checkout-index menerapkan smudge filter dan memulihkan file LF sebagai
59
+ // CRLF — restore mengubah byte yang tidak diminta siapa pun. Terukur:
60
+ // `a\nb\n` menjadi `a\r\nb\r\n`. Dengan flag ini LF tetap LF, CRLF tetap
61
+ // CRLF, dan file biner utuh.
62
+ // `core.safecrlf=false` mematikan peringatan yang menyertainya.
63
+ // Audit #10 P0: GIT_SAFE_BASE mematikan hooks/fsmonitor/pager repo di
64
+ // semua pemanggilan (bahkan read-only seperti status/diff menjalankan
65
+ // fsmonitor repo tanpa ini).
66
+ const hardened = [
67
+ ...GIT_SAFE_BASE,
68
+ "-c",
69
+ "core.autocrlf=false",
70
+ "-c",
71
+ "core.safecrlf=false",
72
+ ...args,
73
+ ]
74
+ const p = spawn(resolveTrustedExecutable("git"), hardened, {
75
+ cwd,
76
+ // Env git dikendalikan penuh: GIT_INDEX_FILE mengarahkan operasi index ke
77
+ // berkas sementara kita, dan GIT_OPTIONAL_LOCKS=0 mencegah git menulis
78
+ // lock pada repo user hanya untuk membaca. Kredensial di-strip (audit
79
+ // #10): filter/hook yang lolos hardening tak boleh memanen secret env.
80
+ env: {
81
+ ...sanitizeSpawnEnv(process.env),
82
+ GIT_OPTIONAL_LOCKS: "0",
83
+ ...(opts.env ?? {}),
84
+ },
85
+ stdio: ["ignore", "pipe", "pipe"],
86
+ })
87
+ let stdout = ""
88
+ let stderr = ""
89
+ p.stdout.on("data", (d: Buffer) => {
90
+ if (stdout.length < 4_000_000) stdout += d.toString()
91
+ })
92
+ p.stderr.on("data", (d: Buffer) => {
93
+ if (stderr.length < 100_000) stderr += d.toString()
94
+ })
95
+ const timer = setTimeout(
96
+ () => p.kill("SIGKILL"),
97
+ opts.timeoutMs ?? LIMITS.SHADOW_GIT_TIMEOUT_MS,
98
+ )
99
+ p.on("error", () => {
100
+ clearTimeout(timer)
101
+ resolveOut({ code: -1, stdout: "", stderr: "git not available" })
102
+ })
103
+ p.on("close", (code) => {
104
+ clearTimeout(timer)
105
+ resolveOut({ code: code ?? -1, stdout, stderr })
106
+ })
107
+ })
108
+ }
109
+
110
+ /** Direktori `.git` (absolut) atau null bila bukan repo. */
111
+ export async function gitDir(cwd: string): Promise<string | null> {
112
+ const r = await git(["rev-parse", "--absolute-git-dir"], cwd)
113
+ if (r.code !== 0) return null
114
+ const dir = r.stdout.trim()
115
+ return dir || null
116
+ }
117
+
118
+ export async function isGitRepo(cwd: string): Promise<boolean> {
119
+ return (await gitDir(cwd)) !== null
120
+ }
121
+
122
+ /**
123
+ * Ambil snapshot state kerja saat ini sebagai tree git.
124
+ *
125
+ * `scope` membatasi ke subdirektori (`cwd` relatif terhadap toplevel repo) agar
126
+ * menjalankan minicode di dalam subfolder tidak menarik seluruh monorepo.
127
+ */
128
+ export async function snapshotTree(
129
+ cwd: string,
130
+ sessionId: string,
131
+ label: string,
132
+ ): Promise<ShadowSnapshot | null> {
133
+ const dir = await gitDir(cwd)
134
+ if (!dir) return null
135
+ // Index sementara per-snapshot: unik agar dua sesi paralel tidak saling
136
+ // menimpa, dan dibuang setelah dipakai. Nama disanitasi karena sessionId
137
+ // datang dari `--session` dan bisa memuat karakter yang ilegal sebagai nama
138
+ // berkas (mis. `:` atau `..` di Windows → git gagal membuat file .lock).
139
+ const safeId = sanitizeRefPart(sessionId)
140
+ const idx = join(dir, `minicode-idx-${safeId}-${Date.now()}-${randomUUID().slice(0, 6)}`)
141
+ const env = { GIT_INDEX_FILE: idx }
142
+ try {
143
+ // Audit #10 P0: `git add` menjalankan clean filter repo (RCE tiap turn
144
+ // di repo jahat!). Netralkan driver terkonfigurasi → cat (identitas
145
+ // byte): snapshot butuh byte worktree apa adanya, bukan hasil konversi.
146
+ // Index user tak tersentuh (temp), jadi semantik clean milik user aman.
147
+ const neutral = await gitFilterNeutralizers(cwd)
148
+ // `-- .` membatasi ke cwd; tanpa ini `add -A` memakai toplevel repo.
149
+ // Flag -c harus sebelum subcommand: helper git() menaruh hardened base
150
+ // di depan, neutral di sini tepat setelahnya, sebelum "add".
151
+ const add = await git([...neutral, "add", "-A", "--", "."], cwd, { env })
152
+ if (add.code !== 0) return null
153
+ // Audit #10 P0: `git write-tree` MENERAPKAN ULANG clean filter pada
154
+ // entri index (trace: run_command node setelah write-tree). Override
155
+ // `-c filter.*.clean=cat` WAJIB ikut ke write-tree juga — bukan hanya add.
156
+ const write = await git([...neutral, "write-tree"], cwd, { env })
157
+ if (write.code !== 0) return null
158
+ const tree = write.stdout.trim()
159
+ if (!/^[0-9a-f]{40,64}$/.test(tree)) return null
160
+
161
+ // Pin tree dengan ref supaya `git gc` tidak membuang objectnya. Ref
162
+ // menunjuk ke tree (bukan commit) sehingga tak pernah tampil di git log.
163
+ const ref = `${REF_NAMESPACE}/${safeId}/${sanitizeRefPart(label)}-${tree.slice(0, 8)}`
164
+ await git(["update-ref", ref, tree], cwd)
165
+ return { tree, ref }
166
+ } finally {
167
+ await rm(idx, { force: true }).catch(() => {})
168
+ }
169
+ }
170
+
171
+ /**
172
+ * Nama aman untuk dipakai di ref git **dan** sebagai nama berkas.
173
+ *
174
+ * Dipakai untuk keduanya karena `sessionId` datang dari luar (`--session`) dan
175
+ * pernah membuat operasi gagal total: `sess/../..~weird:id` menghasilkan path
176
+ * index `\.git\..~weird:id-...` yang ditolak Windows (`Invalid argument`), dan
177
+ * `..`/`~`/`:` juga ilegal di nama ref.
178
+ *
179
+ * F-17: delegasi ke sanitizer bersama (lib/session-id.ts) — dulu varian lokal
180
+ * dengan pemetaan `..` berbeda dari checkpoint/journal.
181
+ */
182
+ function sanitizeRefPart(s: string): string {
183
+ return sanitizeSessionPart(s)
184
+ }
185
+
186
+ /** Perubahan antara dua tree, dibatasi ke path di dalam workspace. */
187
+ export async function diffTrees(cwd: string, from: string, to: string): Promise<ShadowChange[]> {
188
+ // --no-ext-diff/--no-textconv: diff tak menjalankan driver konten repo.
189
+ // (Flag diff harus sebelum revisi `from`/`to`, bukan di ekor.)
190
+ const r = await git(
191
+ ["diff", ...GIT_NO_DIFF_DRIVERS, "--name-status", "-z", "--find-renames", from, to],
192
+ cwd,
193
+ )
194
+ if (r.code !== 0) return []
195
+ const parts = r.stdout.split("\0").filter((s) => s.length > 0)
196
+ const out: ShadowChange[] = []
197
+ for (let i = 0; i < parts.length; ) {
198
+ const raw = parts[i]!
199
+ const code = raw[0] as string
200
+ if (code === "R") {
201
+ // rename: status, old, new
202
+ const oldPath = parts[i + 1]
203
+ const newPath = parts[i + 2]
204
+ i += 3
205
+ if (oldPath && newPath) out.push({ status: "R", path: newPath, from: oldPath })
206
+ continue
207
+ }
208
+ const p = parts[i + 1]
209
+ i += 2
210
+ if (!p) continue
211
+ if (code === "A" || code === "M" || code === "D") out.push({ status: code, path: p })
212
+ }
213
+ return out
214
+ }
215
+
216
+ /** Snapshot "sekarang" tanpa mem-pin ref — untuk membandingkan saja. */
217
+ export async function ephemeralTree(cwd: string): Promise<string | null> {
218
+ const dir = await gitDir(cwd)
219
+ if (!dir) return null
220
+ const idx = join(dir, `minicode-cmp-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`)
221
+ const env = { GIT_INDEX_FILE: idx }
222
+ try {
223
+ // Netralisasi sama seperti snapshotTree (lihat di atas): write-tree juga
224
+ // menerapkan ulang clean filter — override wajib ikut ke kedua subcommand.
225
+ const neutral = await gitFilterNeutralizers(cwd)
226
+ if ((await git([...neutral, "add", "-A", "--", "."], cwd, { env })).code !== 0) return null
227
+ const w = await git([...neutral, "write-tree"], cwd, { env })
228
+ if (w.code !== 0) return null
229
+ const tree = w.stdout.trim()
230
+ return /^[0-9a-f]{40,64}$/.test(tree) ? tree : null
231
+ } finally {
232
+ await rm(idx, { force: true }).catch(() => {})
233
+ }
234
+ }
235
+
236
+ export interface RestoreResult {
237
+ applied: string[]
238
+ skipped: string[]
239
+ }
240
+
241
+ /**
242
+ * Pulihkan workspace ke `tree`, menyentuh HANYA path yang berbeda dari kondisi
243
+ * sekarang. File yang muncul setelah snapshot dihapus; yang berubah/terhapus
244
+ * ditulis ulang dari object store.
245
+ *
246
+ * Semua path dijail: apa pun yang keluar dari `cwd` dilewati dan dilaporkan.
247
+ * Ini penting karena diff tree bisa memuat path dari toplevel repo bila
248
+ * snapshot diambil dengan scope berbeda.
249
+ */
250
+ export async function restoreTree(cwd: string, tree: string): Promise<RestoreResult> {
251
+ const root = resolve(cwd)
252
+ const applied: string[] = []
253
+ const skipped: string[] = []
254
+
255
+ const now = await ephemeralTree(cwd)
256
+ if (!now) return { applied, skipped: ["(failed to read current state)"] }
257
+ if (now === tree) return { applied, skipped: [] } // sudah identik
258
+
259
+ const changes = await diffTrees(cwd, tree, now)
260
+ if (changes.length === 0) return { applied, skipped: [] }
261
+
262
+ const inside = (p: string): boolean => {
263
+ const abs = resolve(root, p)
264
+ return abs === root || abs.startsWith(root + (process.platform === "win32" ? "\\" : "/"))
265
+ }
266
+
267
+ // Path yang harus DIAMBIL dari tree lama (berubah di tree lama → sekarang
268
+ // sebagai M, atau hilang sekarang sebagai D dari sudut pandang diff).
269
+ const toCheckout: string[] = []
270
+ // Path yang tidak ada di tree lama (A) → harus dihapus.
271
+ const toDelete: string[] = []
272
+
273
+ for (const c of changes) {
274
+ if (!inside(c.path)) {
275
+ skipped.push(`${c.path} (di luar workspace)`)
276
+ continue
277
+ }
278
+ if (c.status === "A") toDelete.push(c.path)
279
+ else if (c.status === "M" || c.status === "D") toCheckout.push(c.path)
280
+ else if (c.status === "R") {
281
+ // rename: nama baru dihapus, nama lama dipulihkan
282
+ toDelete.push(c.path)
283
+ if (c.from && inside(c.from)) toCheckout.push(c.from)
284
+ }
285
+ }
286
+
287
+ if (toCheckout.length > 0) {
288
+ const dir = await gitDir(cwd)
289
+ if (!dir) return { applied, skipped: ["(not a git repository)"] }
290
+ const idx = join(dir, `minicode-restore-${Date.now()}-${randomUUID().slice(0, 6)}`)
291
+ const env = { GIT_INDEX_FILE: idx }
292
+ try {
293
+ const rt = await git(["read-tree", tree], cwd, { env })
294
+ if (rt.code !== 0) {
295
+ skipped.push(`(read-tree failed: ${rt.stderr.trim().slice(0, 120)})`)
296
+ } else {
297
+ // checkout-index per batch: daftar path bisa panjang, dan Windows
298
+ // punya batas panjang command line. Netralisasi smudge (audit #10):
299
+ // restore wajib byte-exact + tanpa eksekusi filter repo. Pasangan -c
300
+ // WAJIB sebelum subcommand (git berhenti parsing global di sana).
301
+ const neutral = await gitFilterNeutralizers(cwd)
302
+ for (let i = 0; i < toCheckout.length; i += LIMITS.SHADOW_GIT_PATH_BATCH) {
303
+ const batch = toCheckout.slice(i, i + LIMITS.SHADOW_GIT_PATH_BATCH)
304
+ const co = await git([...neutral, "checkout-index", "-f", "--", ...batch], cwd, { env })
305
+ if (co.code === 0) applied.push(...batch.map((p) => `${p} (restored)`))
306
+ else skipped.push(...batch.map((p) => `${p} (checkout failed)`))
307
+ }
308
+ }
309
+ } finally {
310
+ await rm(idx, { force: true }).catch(() => {})
311
+ }
312
+ }
313
+
314
+ for (const p of toDelete) {
315
+ await rm(resolve(root, p), { force: true, recursive: false }).catch(() => {})
316
+ applied.push(`${p} (removed)`)
317
+ }
318
+
319
+ return { applied, skipped }
320
+ }
321
+
322
+ /** Hapus semua ref shadow untuk satu sesi (dipanggil saat purge). */
323
+ export async function pruneSessionRefs(cwd: string, sessionId: string): Promise<number> {
324
+ const prefix = `${REF_NAMESPACE}/${sanitizeRefPart(sessionId)}/`
325
+ const r = await git(["for-each-ref", "--format=%(refname)", prefix], cwd)
326
+ if (r.code !== 0) return 0
327
+ const refs = r.stdout
328
+ .split("\n")
329
+ .map((s) => s.trim())
330
+ .filter(Boolean)
331
+ let n = 0
332
+ for (const ref of refs) {
333
+ if ((await git(["update-ref", "-d", ref], cwd)).code === 0) n++
334
+ }
335
+ return n
336
+ }
337
+
338
+ /** Semua ref shadow (untuk diagnostik / `minicode sessions`). */
339
+ export async function listShadowRefs(cwd: string): Promise<{ ref: string; tree: string }[]> {
340
+ const r = await git(["for-each-ref", "--format=%(refname) %(objectname)", REF_NAMESPACE], cwd)
341
+ if (r.code !== 0) return []
342
+ return r.stdout
343
+ .split("\n")
344
+ .map((l) => l.trim())
345
+ .filter(Boolean)
346
+ .map((l) => {
347
+ const [ref, tree] = l.split(" ")
348
+ return { ref: ref ?? "", tree: tree ?? "" }
349
+ })
350
+ .filter((x) => x.ref && x.tree)
351
+ }
@@ -0,0 +1,118 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
2
+ import { resolve } from "node:path"
3
+
4
+ // Penanda turn-aktif untuk deteksi mati-tak-wajar (segfault Bun, kill -9,
5
+ // hang yang dibunuh dari luar). Ditulis saat turn mulai, dihapus saat turn
6
+ // settle (sukses/gagal/abort) — jadi berkas yang TERSISA saat startup
7
+ // berarti proses sebelumnya mati di tengah turn. Berbeda dari jurnal
8
+ // recovery (yang melacak MUTASI): ini melacak KEHIDUPAN proses.
9
+ //
10
+ // Multi-sesi satu cwd: marker membawa pid + sessionId. Sesi baru menghormati
11
+ // marker milik proses yang MASIH hidup (tak disentuh); hanya marker yatim
12
+ // (pid mati) yang dilaporkan + dibersihkan. Hapus pun hanya bila sessionId
13
+ // cocok — sesi paralel tak saling menghapus.
14
+
15
+ export interface TurnMarker {
16
+ sessionId: string
17
+ pid: number
18
+ startedAt: number
19
+ }
20
+
21
+ function markerPath(cwd: string): string {
22
+ return resolve(cwd ?? ".", ".minicode", "turn.active.json")
23
+ }
24
+
25
+ function readMarker(cwd: string): TurnMarker | null {
26
+ try {
27
+ const raw = readFileSync(markerPath(cwd), "utf8")
28
+ const m = JSON.parse(raw) as Partial<TurnMarker>
29
+ if (
30
+ typeof m.sessionId === "string" &&
31
+ typeof m.pid === "number" &&
32
+ typeof m.startedAt === "number"
33
+ ) {
34
+ return { sessionId: m.sessionId, pid: m.pid, startedAt: m.startedAt }
35
+ }
36
+ } catch {}
37
+ return null
38
+ }
39
+
40
+ /** True bila pid (mungkin) masih hidup. Tak pernah melempar. */
41
+ export function isPidAlive(pid: number): boolean {
42
+ if (!Number.isInteger(pid) || pid <= 0) return false
43
+ try {
44
+ process.kill(pid, 0)
45
+ return true
46
+ } catch (e) {
47
+ // ESRCH = mati pasti. Selain itu (EPERM = ada tapi tak boleh disinyal,
48
+ // atau error tak dikenal) anggap hidup — jangan tuduh crash sesuatu
49
+ // yang mungkin berjalan.
50
+ return (e as NodeJS.ErrnoException)?.code !== "ESRCH"
51
+ }
52
+ }
53
+
54
+ /** Tulis marker milik sesi ini — kecuali ada marker sesi lain yang hidup. */
55
+ export function markTurnActive(cwd: string | undefined, sessionId: string): void {
56
+ try {
57
+ const dir = cwd ?? "."
58
+ const prev = readMarker(dir)
59
+ if (prev && prev.sessionId !== sessionId && isPidAlive(prev.pid)) return
60
+ mkdirSync(resolve(dir, ".minicode"), { recursive: true })
61
+ writeFileSync(
62
+ markerPath(dir),
63
+ JSON.stringify({ sessionId, pid: process.pid, startedAt: Date.now() }),
64
+ )
65
+ } catch {}
66
+ }
67
+
68
+ /** Hapus marker — hanya bila milik sesi ini. Tak pernah melempar. */
69
+ export function clearTurnActive(cwd: string | undefined, sessionId: string): void {
70
+ try {
71
+ const dir = cwd ?? "."
72
+ const prev = readMarker(dir)
73
+ if (!prev || prev.sessionId !== sessionId) return
74
+ rmSync(markerPath(dir), { force: true })
75
+ } catch {}
76
+ }
77
+
78
+ /**
79
+ * Cek marker yatim saat startup: ada + bukan milik sesi ini + pid mati.
80
+ * Return info untuk notice, atau null bila bersih/ada pemilik hidup.
81
+ * Tak pernah melempar; tak menghapus (penghapusan eksplisit via clear).
82
+ */
83
+ export function checkStaleTurn(cwd: string | undefined, sessionId: string): TurnMarker | null {
84
+ try {
85
+ const prev = readMarker(cwd ?? ".")
86
+ if (!prev || prev.sessionId === sessionId) return null
87
+ if (isPidAlive(prev.pid)) return null
88
+ return prev
89
+ } catch {
90
+ return null
91
+ }
92
+ }
93
+
94
+ /** Hapus marker yatim yang sudah dilaporkan. Tak pernah melempar. */
95
+ export function clearStaleTurn(cwd: string | undefined, sessionId: string): void {
96
+ try {
97
+ const prev = readMarker(cwd ?? ".")
98
+ if (!prev || prev.sessionId === sessionId) return
99
+ if (isPidAlive(prev.pid)) return
100
+ rmSync(markerPath(cwd ?? "."), { force: true })
101
+ } catch {}
102
+ }
103
+
104
+ /** Satu baris notice English-only untuk marker yatim. Murni, teruji. */
105
+ export function formatStaleNotice(info: TurnMarker): string {
106
+ const ageMs = Math.max(0, Date.now() - info.startedAt)
107
+ let age: string
108
+ if (ageMs < 60_000) age = `${Math.floor(ageMs / 1000)}s`
109
+ else if (ageMs < 3600_000)
110
+ age = `${Math.floor(ageMs / 60000)}m${String(Math.floor((ageMs % 60000) / 1000)).padStart(2, "0")}s`
111
+ else
112
+ age = `${Math.floor(ageMs / 3600000)}h${String(Math.floor((ageMs % 3600000) / 60000)).padStart(2, "0")}m`
113
+ return (
114
+ `[recovery] previous turn (session ${info.sessionId}, started ${age} ago) ` +
115
+ `did not settle cleanly — possible crash or kill. ` +
116
+ `Check /status, then /resume to continue or /undo to revert.`
117
+ )
118
+ }
@@ -0,0 +1,117 @@
1
+ import { readdir, readFile } from "node:fs/promises"
2
+ import { homedir } from "node:os"
3
+ import { join, resolve } from "node:path"
4
+ import { isRealPathOutsideRoot } from "../policy/jail.ts"
5
+
6
+ export interface Skill {
7
+ name: string
8
+ description: string
9
+ body: string // prompt template
10
+ path: string
11
+ }
12
+
13
+ const GLOBAL_SKILLS = join(homedir(), ".minicode", "skills")
14
+ const LOCAL_SKILLS = ".minicode/skills"
15
+
16
+ function parseFrontmatter(txt: string): { meta: Record<string, string>; body: string } {
17
+ const meta: Record<string, string> = {}
18
+ let body = txt
19
+ if (txt.startsWith("---")) {
20
+ // find closing --- at start of line (avoid body "---" hr)
21
+ const end = txt.indexOf("\n---", 3)
22
+ if (end !== -1) {
23
+ const closeEnd = end + 4 // \n--- + \n?
24
+ for (const line of txt.slice(3, end).split("\n")) {
25
+ const trimmed = line.trim()
26
+ if (!trimmed || trimmed.startsWith("#")) continue
27
+ const idx = trimmed.indexOf(":")
28
+ if (idx > 0) {
29
+ const key = trimmed.slice(0, idx).trim()
30
+ let val = trimmed.slice(idx + 1).trim()
31
+ if (
32
+ (val.startsWith('"') && val.endsWith('"')) ||
33
+ (val.startsWith("'") && val.endsWith("'"))
34
+ ) {
35
+ val = val.slice(1, -1)
36
+ }
37
+ meta[key] = val
38
+ }
39
+ }
40
+ body = txt.slice(closeEnd).trim()
41
+ // strip leading --- line leftover
42
+ if (body.startsWith("---")) body = body.slice(3).trim()
43
+ }
44
+ }
45
+ return { meta, body }
46
+ }
47
+
48
+ async function loadDir(dir: string, out: Skill[], root: string = dir) {
49
+ const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
50
+ for (const e of entries) {
51
+ const full = join(dir, e.name)
52
+ // Symlink escape (temuan audit #06): readdir+readFile mengikuti symlink,
53
+ // sehingga skill/dir link keluar workspace ikut dimuat. Tolak yang
54
+ // realpath-nya di luar root kepercayaannya (global vs proyek).
55
+ if (isRealPathOutsideRoot(full, root)) continue
56
+ if (e.isDirectory()) {
57
+ // recursive 1-level deep for nested skills
58
+ await loadDir(full, out, root)
59
+ continue
60
+ }
61
+ if (!e.isFile() || !e.name.endsWith(".md")) continue
62
+ const txt = await readFile(full, "utf8").catch(() => "")
63
+ if (!txt.trim()) continue
64
+ const { meta, body } = parseFrontmatter(txt)
65
+ const rawName = meta.name ?? e.name.replace(/\.md$/, "")
66
+ const name = rawName
67
+ .toLowerCase()
68
+ .replace(/\s+/g, "-")
69
+ .replace(/[^a-z0-9-]/g, "-")
70
+ .replace(/-+/g, "-")
71
+ .replace(/^-|-$/g, "")
72
+ out.push({
73
+ name: name || rawName,
74
+ description: meta.description ?? body.split("\n")[0]?.slice(0, 100) ?? "",
75
+ body,
76
+ path: full,
77
+ })
78
+ }
79
+ }
80
+
81
+ let skillsCache: { cwd: string; at: number; skills: Skill[] } | undefined
82
+ const SKILLS_CACHE_TTL_MS = 5 * 60 * 1000
83
+
84
+ export async function loadSkills(cwd = process.cwd()): Promise<Skill[]> {
85
+ // cache in-memory 5 menit — loadSkills dipanggil berulang (setup, REPL, one-shot)
86
+ const now = Date.now()
87
+ const key = resolve(cwd)
88
+ if (skillsCache && skillsCache.cwd === key && now - skillsCache.at < SKILLS_CACHE_TTL_MS) {
89
+ return skillsCache.skills
90
+ }
91
+ const skills: Skill[] = []
92
+ await loadDir(GLOBAL_SKILLS, skills)
93
+ await loadDir(resolve(cwd, LOCAL_SKILLS), skills)
94
+ // local overrides global by name
95
+ const map = new Map<string, Skill>()
96
+ for (const s of skills) map.set(s.name, s)
97
+ skillsCache = { cwd: key, at: now, skills: [...map.values()] }
98
+ return skillsCache.skills
99
+ }
100
+
101
+ export function invalidateSkillCache(): void {
102
+ skillsCache = undefined
103
+ }
104
+
105
+ export async function renderSkill(skill: Skill, args: string): Promise<string> {
106
+ return skill.body.replace(/\{\{args\}\}/g, args).replace(/\$ARGUMENTS/g, args)
107
+ }
108
+
109
+ export async function findSkill(name: string, cwd = process.cwd()): Promise<Skill | undefined> {
110
+ const all = await loadSkills(cwd)
111
+ return all.find((s) => s.name === name || s.name === name.replace(/^\//, ""))
112
+ }
113
+
114
+ export function skillsToSystemPrompt(skills: Skill[]): string {
115
+ if (skills.length === 0) return ""
116
+ return `\n# Available skills (use via /name or ask)\n${skills.map((s) => `- /${s.name}: ${s.description}`).join("\n")}`
117
+ }