minicode-ai 0.11.0 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -1,7 +1,9 @@
1
1
  import { spawnSync } from "node:child_process"
2
- import { chmod, mkdir, readFile } from "node:fs/promises"
3
- import { homedir } from "node:os"
4
- import { join } from "node:path"
2
+ import { randomUUID } from "node:crypto"
3
+ import { readlinkSync } from "node:fs"
4
+ import { chmod, mkdir, open, readdir, readFile, unlink } from "node:fs/promises"
5
+ import { homedir, hostname } from "node:os"
6
+ import { basename, join } from "node:path"
5
7
  import { atomicWriteText } from "./atomic-write.ts"
6
8
 
7
9
  // Penyimpanan rahasia berlapis (tanpa dependensi):
@@ -14,6 +16,17 @@ import { atomicWriteText } from "./atomic-write.ts"
14
16
  // `"dpapi"` berarti base64 blob DPAPI, `"plain"` berarti teks biasa.
15
17
  // Fallback ke plain OTOMATIS bila backend OS tak tersedia (bukan error),
16
18
  // supaya CLI tetap jalan di CI/container. Tak pernah melempar.
19
+ //
20
+ // Fail-closed pada jalur TULIS: credential yang ada tak boleh hilang.
21
+ // Store yang tak bisa dibaca (EACCES/EISDIR) atau tak bisa di-parse (JSON
22
+ // rusak) TIDAK boleh diperlakukan sebagai "store kosong" lalu ditimpa —
23
+ // itu menghapus seluruh credential lama tanpa jejak. Jalur tulis membeda-
24
+ // kan "store belum ada" (boleh dibuat) dari "store ada tapi rusak" (tolak
25
+ // menulis, laporkan, biarkan berkasnya apa adanya).
26
+ //
27
+ // Jalur tulis juga DISERIALISASI (kunci lintas proses, lihat acquireStoreLock):
28
+ // store dibaca-modifikasi-ditulis, jadi dua penulis konkuren tanpa kunci
29
+ // berarti credential yang baru ditulis lenyap diam-diam (lost update).
17
30
 
18
31
  export type SecretRunner = (
19
32
  cmd: string,
@@ -21,19 +34,34 @@ export type SecretRunner = (
21
34
  input?: string,
22
35
  ) => { status: number | null; stdout: string }
23
36
 
37
+ /** Penulis store (seam uji: mensimulasikan "gagal tulis"). */
38
+ export type StoreWriter = (path: string, data: string) => Promise<void>
39
+
24
40
  let runnerOverride: SecretRunner | null = null
41
+ let writerOverride: StoreWriter | null = null
25
42
 
26
43
  /** Seam uji: ganti eksekutor powershell. */
27
44
  export function __setKeystoreRunnerForTest(r: SecretRunner | null): void {
28
45
  runnerOverride = r
29
46
  }
30
47
 
48
+ /**
49
+ * Seam uji: ganti penulis store. Dipakai untuk mensimulasikan kegagalan
50
+ * tulis secara deterministik (tanpa bergantung permission/filesystem spesifik
51
+ * OS). Default = tulis atomik sungguhan.
52
+ */
53
+ export function __setKeystoreWriterForTest(w: StoreWriter | null): void {
54
+ writerOverride = w
55
+ }
56
+
31
57
  const secretCache = new Map<string, string | null>()
32
58
 
33
- /** Reset cache + runner (test saja). */
59
+ /** Reset cache + runner + writer + timing kunci (test saja). */
34
60
  export function __resetKeystoreForTest(): void {
35
61
  secretCache.clear()
36
62
  runnerOverride = null
63
+ writerOverride = null
64
+ lockTimingOverride = null
37
65
  }
38
66
 
39
67
  function defaultRunner(
@@ -60,32 +88,447 @@ function storePath(): string {
60
88
  return join(home, ".minicode", "secrets.json")
61
89
  }
62
90
 
91
+ /** File kunci — satu folder dengan store (filesystem sama). */
92
+ function lockPath(): string {
93
+ return `${storePath()}.lock`
94
+ }
95
+
96
+ // ── Serialisasi penulis store ─────────────────────────────────────────────
97
+ // Store dibaca-modifikasi-tulis. Dua penulis pada store yang sama =
98
+ // lost update: credential yang baru ditulis lenyap diam-diam (reproducer:
99
+ // dua set-key konkuren → hanya satu credential tersisa, keduanya melaporkan
100
+ // "sukses"). atomicWriteText mencegah TORN write, bukan lost update.
101
+ //
102
+ // Kunci: file "wx" (O_EXCL — atomik di POSIX dan Windows) di folder yang sama
103
+ // dengan store.
104
+ //
105
+ // ATURAN PEMILIKAN (hasil design review + koreksi akhir):
106
+ // - Kunci HANYA boleh dilepas oleh PEMILIKNYA SENDIRI (token cocok). Kunci
107
+ // milik orang lain TAK PERNAH diambil alih otomatis — bukan karena umurnya,
108
+ // dan bukan karena pemiliknya terlihat mati.
109
+ //
110
+ // Kenapa tidak ada reclaim otomatis: "baca payload → nilai → hapus path kunci"
111
+ // adalah TOCTOU/ABA. Antara baca dan hapus, path yang sama bisa sudah menunjuk
112
+ // objek LAIN — kunci milik penulis lain yang HIDUP. Primitive yang tersedia
113
+ // tak bisa menutup itu: open("wx") (O_EXCL) atomik untuk MEMBUAT, tapi
114
+ // rename()/unlink() bekerja pada NAMA PATH tanpa syarat identitas (tak ada
115
+ // flock/LockFileEx/renameat2/unlinkat-by-fd di Node/Bun). Tanpa fencing,
116
+ // penulis yang tergeser tetap menulis store dan menimpa credential milik
117
+ // penulis baru — kehilangan diam-diam. Karena itu jalur reclaim dihapus:
118
+ // kunci yang tertinggal dari proses yang crash diselesaikan MANUAL (pesan
119
+ // di stderr menyebut path kunci + apakah pemiliknya tampak hidup).
120
+ //
121
+ // Identitas pemilik tetap disimpan (payload v2: pid, token, ts, host, ns)
122
+ // untuk DIAGNOSTIK — membantu operator memutuskan boleh atau tidak menghapus
123
+ // file kunci yang tersisa.
124
+ //
125
+ // - Ambil : buat file kunci O_EXCL + tulis payload v2. Kalau sudah ada →
126
+ // tunggu (poll) sampai batas tunggu habis → fail-closed (tak ada yang
127
+ // ditulis, cache tak disentuh, pesan pemulihan menyebut path kunci).
128
+ // - Lepas : unlink HANYA kalau token di file kunci masih milik kita. Balapan
129
+ // release (cek-lalu-unlink tak atomik) tak terjangkau: selama lock dipegang
130
+ // pemiliknya, path kunci terisi terus (hanya owner's release yang menghapus),
131
+ // jadi path tak pernah di-rebind di antara cek dan unlink.
132
+ // - Crash : file kunci tertinggal → semua penulis lain fail-closed sampai
133
+ // operator menghapusnya (fail-closed, bukan diam-diam).
134
+ // - Gagal : kunci tak bisa dibuat (folder tak writable) → fail-closed; tak ada
135
+ // yang ditulis dan tak ada credential hilang diam-diam.
136
+ //
137
+ // JAMINAN YANG DIDOKUMENTASIKAN (bukan klaim kriptografis):
138
+ // - Filesystem lokal (NTFS/ext4/APFS/XFS): O_EXCL create atomik → paling
139
+ // banyak satu pemegang kunci sepanjang waktu; tidak ada jalur yang menghapus
140
+ // kunci milik orang lain → EKSLUSIVITAS MUTLAK (strict mutual exclusion)
141
+ // untuk bagian kritis.
142
+ // - Windows/macOS: ruang PID milik SELURUH host → (host, pid) cukup untuk
143
+ // menentukan pemiliknya. Identitas host = hostname OS; dua mesin dengan
144
+ // hostname sama melemahkan jaminan ini (jarang, tak diklaim aman).
145
+ // - Linux: identitas namespace PID (/proc/self/ns/pid) membedakan container
146
+ // yang berbagi home; pid check hanya valid bila namespace cocok.
147
+ // - NFS/SMB: O_EXCL/rename umumnya atomik di sisi server, TAPI metadata
148
+ // (payload) bisa basi karena attribute caching. Karena tak ada reclaim,
149
+ // metadata basi hanya memengaruhi DIAGNOSTIK pesan — bukan keputusan
150
+ // penulisan. Jaminan lintas-host tetap TIDAK diklaim.
151
+ const LOCK_POLL_MS = 25
152
+ const LOCK_WAIT_MS = 10_000
153
+ const LOCK_PAYLOAD_VERSION = 2
154
+
155
+ /**
156
+ * Seam uji: batasi waktu tunggu/poll kunci. Default = nilai produksi; test
157
+ * boleh memendekkannya supaya kasus "kunci tak bisa didapat" selesai cepat.
158
+ * BUKAN env toggle produksi — hanya lewat API eksplisit.
159
+ */
160
+ let lockTimingOverride: { waitMs?: number; pollMs?: number } | null = null
161
+
162
+ export function __setKeystoreLockTimingForTest(
163
+ t: { waitMs?: number; pollMs?: number } | null,
164
+ ): void {
165
+ lockTimingOverride = t
166
+ }
167
+
168
+ function lockWaitMs(): number {
169
+ return lockTimingOverride?.waitMs ?? LOCK_WAIT_MS
170
+ }
171
+
172
+ function lockPollMs(): number {
173
+ return lockTimingOverride?.pollMs ?? LOCK_POLL_MS
174
+ }
175
+
176
+ interface LockPayload {
177
+ v: number
178
+ pid: number
179
+ token: string
180
+ ts: number
181
+ host: string
182
+ ns: string
183
+ }
184
+
185
+ /** Identitas host — stabil per proses, di-cache. */
186
+ let hostIdCache: string | null = null
187
+ function hostIdentity(): string {
188
+ if (hostIdCache !== null) return hostIdCache
189
+ try {
190
+ hostIdCache = hostname()
191
+ } catch {
192
+ hostIdCache = "unknown-host"
193
+ }
194
+ return hostIdCache
195
+ }
196
+
197
+ /**
198
+ * Identitas namespace PID. Linux: inode namespace dari /proc/self/ns/pid —
199
+ * inilah yang membuat pid check bermakna (dua container bisa punya pid sama).
200
+ * Platform tanpa namespace PID: "none" (ruang pid = satu host).
201
+ * "pidns:unknown" = /proc tak terbaca → identitas tak bisa dipastikan →
202
+ * TIDAK BOLEH dipakai untuk reclaim.
203
+ */
204
+ let nsIdCache: string | null = null
205
+ function pidNamespaceIdentity(): string {
206
+ if (nsIdCache !== null) return nsIdCache
207
+ if (process.platform !== "linux") {
208
+ nsIdCache = "none"
209
+ return nsIdCache
210
+ }
211
+ try {
212
+ nsIdCache = `pidns:${readlinkSync("/proc/self/ns/pid")}`
213
+ } catch {
214
+ nsIdCache = "pidns:unknown"
215
+ }
216
+ return nsIdCache
217
+ }
218
+
219
+ /** Parse payload kunci. null = tak terbaca / tak valid / format lama. */
220
+ function parseLockPayload(raw: string): LockPayload | null {
221
+ let parsed: unknown
222
+ try {
223
+ parsed = JSON.parse(raw)
224
+ } catch {
225
+ return null
226
+ }
227
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return null
228
+ const p = parsed as Partial<LockPayload>
229
+ if (p.v !== LOCK_PAYLOAD_VERSION) return null
230
+ if (typeof p.pid !== "number" || !Number.isInteger(p.pid) || p.pid <= 0) return null
231
+ if (typeof p.token !== "string" || !p.token) return null
232
+ if (typeof p.ts !== "number") return null
233
+ if (typeof p.host !== "string" || !p.host) return null
234
+ if (typeof p.ns !== "string" || !p.ns) return null
235
+ return { v: p.v, pid: p.pid, token: p.token, ts: p.ts, host: p.host, ns: p.ns }
236
+ }
237
+
238
+ async function readLockPayload(path: string): Promise<LockPayload | null> {
239
+ try {
240
+ return parseLockPayload(await readFile(path, "utf8"))
241
+ } catch {
242
+ return null
243
+ }
244
+ }
245
+
246
+ /**
247
+ * Kepemilikan: true HANYA kalau pid benar-benar tidak ada (ESRCH). EPERM =
248
+ * proses hidup tapi hak akses berbeda → anggap hidup (konservatif).
249
+ */
250
+ function pidAbsent(pid: number): boolean {
251
+ try {
252
+ process.kill(pid, 0)
253
+ return false
254
+ } catch (e) {
255
+ return (e as NodeJS.ErrnoException)?.code === "ESRCH"
256
+ }
257
+ }
258
+
259
+ /**
260
+ * TRUE hanya kalau pemilik kunci terbukti mati di konteks yang sama.
261
+ * Semua kondisi lain (host beda, namespace beda, namespace tak diketahui,
262
+ * payload tak valid) → ownership UNKNOWN → JANGAN ambil alih.
263
+ *
264
+ * CATATAN: dipakai untuk DIAGNOSTIK saja (pesan fail-closed memberi tahu
265
+ * apakah pemilik kunci tampaknya masih hidup). Otomatik reclaim sudah
266
+ * DIHAPUS: validate-and-remove pada nama path punya celah ABA (lihat
267
+ * acquireStoreLock).
268
+ */
269
+
270
+ interface StoreLock {
271
+ release: () => Promise<void>
272
+ }
273
+
274
+ async function acquireStoreLock(): Promise<StoreLock | null> {
275
+ const path = lockPath()
276
+ const token = randomUUID()
277
+ const host = hostIdentity()
278
+ const ns = pidNamespaceIdentity()
279
+ const waitMs = lockWaitMs()
280
+ const pollMs = lockPollMs()
281
+ const deadline = Date.now() + waitMs
282
+ // Folder store harus ada sebelum kunci dibuat (kunci duduk di folder yang
283
+ // sama). Best-effort: kalau gagal, open() di bawah yang melaporkan.
284
+ await mkdir(join(storePath(), ".."), { recursive: true, mode: 0o700 }).catch(() => {})
285
+ for (;;) {
286
+ try {
287
+ const fh = await open(path, "wx", 0o600)
288
+ try {
289
+ const payload: LockPayload = {
290
+ v: LOCK_PAYLOAD_VERSION,
291
+ pid: process.pid,
292
+ token,
293
+ ts: Date.now(),
294
+ host,
295
+ ns,
296
+ }
297
+ await fh.writeFile(JSON.stringify(payload), "utf8")
298
+ } finally {
299
+ await fh.close().catch(() => {})
300
+ }
301
+ // Sisa reclaim dari implementasi SEBELUMNYA (yang memakai jalur
302
+ // rename+unlink) bisa tertinggal sebagai "<nama>.lock.stale.*". Sekarang
303
+ // reclaim sudah dihapus, jadi tak ada lagi file baru seperti itu; sweep
304
+ // ini hanya membersihkan sisa versi lama. Yang boleh dihapus HANYA
305
+ // prefix PERSIS "<nama>.stale." — path kunci aktif tak pernah disentuh.
306
+ await sweepStaleLockResidue(path)
307
+ return {
308
+ release: async () => {
309
+ // Hanya lepas kalau file kunci masih milik kita. Kalau kita sudah
310
+ // "dicuri" dan orang lain membuat ulang, unlink kita akan melepas
311
+ // kunci orang itu. Payload tak terbaca = kunci sedang dibuat orang
312
+ // lain (jendela sepersekian detik) ATAU file rusak → JANGAN unlink
313
+ // (kehilangan mutual exclusion lebih buruk daripada kunci nyasar).
314
+ const cur = await readLockPayload(path)
315
+ if (!cur || cur.token !== token) return
316
+ await unlink(path).catch(() => {})
317
+ },
318
+ }
319
+ } catch (e) {
320
+ const code = (e as NodeJS.ErrnoException)?.code
321
+ if (code !== "EEXIST") return null // tak bisa mengunci → fail-closed
322
+ // Kunci milik orang lain. TIDAK PERNAH diambil alih otomatis.
323
+ //
324
+ // Kenapa tidak: "baca payload → nilai → hapus path" adalah TOCTOU/ABA.
325
+ // Antara baca dan hapus, path kunci bisa sudah menunjuk objek LAIN —
326
+ // filepath kunci yang sama dibuat ulang oleh penulis lain yang hidup.
327
+ // validate-and-remove pada nama path tidak bisa dibuktikan aman di
328
+ // filesystem yang didukung: hanya ada open("wx") (atomik) untuk
329
+ // membuat, sedangkan rename()/unlink() tidak punya syarat identitas
330
+ // (tak ada flock/LockFileEx/renameat2/unlinkat-by-fd di Node/Bun).
331
+ // Tanpa fencing, penulis yang tergeser tetap akan menulis store dan
332
+ // menimpa credential milik penulis baru — kehilangan diam-diam, tepat
333
+ // hal yang lock ini harus cegah.
334
+ //
335
+ // Jadi: tunggu sampai batas waktu, lalu fail-closed dengan pesan yang
336
+ // menyebut path kunci dan memberi petunjuk pemulihan.
337
+ if (Date.now() >= deadline) {
338
+ await reportLockHeld(path, waitMs)
339
+ return null
340
+ }
341
+ await new Promise((r) => setTimeout(r, pollMs))
342
+ }
343
+ }
344
+ }
345
+
346
+ /**
347
+ * Pesan fail-closed saat kunci tak diperoleh: menyebut PATH KUNCI (bukan
348
+ * nilai rahasia) + apakah pemiliknya tampaknya masih hidup + langkah pemulihan
349
+ * yang bisa dikerjakan user.
350
+ *
351
+ * Yang dicetak HANYA: path (milik kita), pid (integer yang sudah divalidasi)
352
+ * dan status "tampaknya tak berjalan". String bebas dari payload (host/ns)
353
+ * TIDAK dicetak — file kunci bisa berisi apa saja bila attacker bisa menulis
354
+ * ke home user, dan stderr tak boleh jadi vektor injeksi.
355
+ */
356
+ async function reportLockHeld(path: string, waitMs: number): Promise<void> {
357
+ const cur = await readLockPayload(path)
358
+ const host = hostIdentity()
359
+ const ns = pidNamespaceIdentity()
360
+ let owner = "owner unknown"
361
+ if (cur) {
362
+ // Hanya pid integer yang dicetak; string bebas dari payload (host/ns)
363
+ // tidak pernah ikut ke stderr.
364
+ if (cur.host !== host || cur.ns !== ns || ns === "pidns:unknown")
365
+ owner = `owner pid=${cur.pid} (another host or pid namespace — liveness not verifiable here)`
366
+ else if (pidAbsent(cur.pid)) owner = `owner pid=${cur.pid} (appears not to be running)`
367
+ else owner = `owner pid=${cur.pid} (still running)`
368
+ }
369
+ process.stderr.write(
370
+ `[keystore] keystore is locked by another process (${path}); ${owner}; waited ${waitMs}ms and refused to write. ` +
371
+ `If no other minicode process is running, delete that file and retry.\n`,
372
+ )
373
+ }
374
+
375
+ /**
376
+ * Sisa reclaim yang tertinggal. Hanya file dengan prefix PERSIS
377
+ * "<nama-kunci>.stale." yang boleh dihapus; path kunci aktif dan berkas lain
378
+ * di folder store tak pernah disentuh.
379
+ */
380
+ async function sweepStaleLockResidue(path: string): Promise<void> {
381
+ const dir = join(path, "..")
382
+ const prefix = `${basename(path)}.stale.`
383
+ let entries: string[]
384
+ try {
385
+ entries = await readdir(dir)
386
+ } catch {
387
+ return
388
+ }
389
+ for (const name of entries) {
390
+ if (!name.startsWith(prefix)) continue
391
+ await unlink(join(dir, name)).catch(() => {})
392
+ }
393
+ }
394
+
395
+ /**
396
+ * Seam uji: bangun payload kunci yang sah (identitas host + namespace ikut
397
+ * proses ini). Dipakai untuk menguji jalur reclaim (pemilik mati) dan varian
398
+ * yang TAK dikenal (host/namespace berbeda, format lama, payload korup).
399
+ */
400
+ export function __keystoreLockPayloadForTest(
401
+ over: { pid?: number; token?: string; host?: string; ns?: string } = {},
402
+ ): Record<string, unknown> {
403
+ return {
404
+ v: LOCK_PAYLOAD_VERSION,
405
+ pid: over.pid ?? process.pid,
406
+ token: over.token ?? randomUUID(),
407
+ ts: Date.now(),
408
+ host: over.host ?? hostIdentity(),
409
+ ns: over.ns ?? pidNamespaceIdentity(),
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Jalankan bagian kritis baca-modifikasi-tulis di bawah kunci. null = kunci
415
+ * tak diperoleh dalam batas waktu → pemanggil harus fail-closed (tak menulis).
416
+ */
417
+ async function withStoreLock<T>(fn: () => Promise<T>): Promise<T | null> {
418
+ const lock = await acquireStoreLock()
419
+ if (!lock) {
420
+ // acquireStoreLock sudah mencetak pesan pemulihan yang menyebut path kunci.
421
+ return null
422
+ }
423
+ try {
424
+ return await fn()
425
+ } finally {
426
+ await lock.release()
427
+ }
428
+ }
429
+
63
430
  interface SecretStore {
64
431
  version: 1
65
432
  entries: Record<string, { enc: string; alg: "dpapi" | "plain" }>
66
433
  }
67
434
 
68
- async function loadStore(): Promise<SecretStore> {
435
+ /**
436
+ * Hasil baca store. Kegagalan baca TIDAK pernah disamakan dengan "store
437
+ * kosong": dulu semua kegagalan (ENOENT, EACCES, EISDIR, JSON rusak) lanjut
438
+ * sebagai `{entries:{}}`, sehingga setSecret menimpa store yang tak bisa
439
+ * dibaca dan seluruh credential lama hilang permanen.
440
+ */
441
+ type StoreLoad =
442
+ | { ok: true; store: SecretStore }
443
+ /** Store belum pernah dibuat (first use) — boleh dibuat. */
444
+ | { ok: false; reason: "absent" }
445
+ /** Store ada tapi tak bisa dibaca (EACCES, EISDIR, …). */
446
+ | { ok: false; reason: "unreadable"; code: string }
447
+ /** Store ada tapi isinya bukan bentuk store yang valid. */
448
+ | { ok: false; reason: "corrupt" }
449
+
450
+ async function loadStore(): Promise<StoreLoad> {
451
+ let raw: string
69
452
  try {
70
- const raw = await readFile(storePath(), "utf8")
71
- const parsed = JSON.parse(raw) as Partial<SecretStore>
72
- if (
73
- parsed &&
74
- typeof parsed === "object" &&
75
- parsed.entries &&
76
- typeof parsed.entries === "object"
453
+ raw = await readFile(storePath(), "utf8")
454
+ } catch (e) {
455
+ const code = (e as NodeJS.ErrnoException)?.code
456
+ // ENOENT = belum ada → ini satu-satunya kondisi yang legitimately
457
+ // berarti "store kosong". Error lain (EACCES/EISDIR/EPERM) berarti store
458
+ // ADA tapi tak bisa dibaca — tidak boleh diasumsikan kosong.
459
+ if (code === "ENOENT") return { ok: false, reason: "absent" }
460
+ return { ok: false, reason: "unreadable", code: code ?? "error" }
461
+ }
462
+ let parsed: unknown
463
+ try {
464
+ parsed = JSON.parse(raw)
465
+ } catch {
466
+ return { ok: false, reason: "corrupt" }
467
+ }
468
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed))
469
+ return { ok: false, reason: "corrupt" }
470
+ const entries = (parsed as { entries?: unknown }).entries
471
+ // Array lolos cek lama (`typeof [] === "object"`), lalu `entries[key] = …`
472
+ // menempelkan properti non-indeks yang `JSON.stringify` BUANG → secret baru
473
+ // hilang diam-diam padahal setSecret melaporkan sukses. Tolak array.
474
+ if (!entries || typeof entries !== "object" || Array.isArray(entries))
475
+ return { ok: false, reason: "corrupt" }
476
+ return { ok: true, store: { version: 1, entries: entries as SecretStore["entries"] } }
477
+ }
478
+
479
+ /**
480
+ * Baca saja (getSecret). Kontrak lama: "tak ada / tak bisa dibuka" → null.
481
+ * Jalur ini tidak pernah menulis, jadi kegagalan load tak merusak apa pun.
482
+ */
483
+ async function loadStoreForRead(): Promise<SecretStore> {
484
+ const loaded = await loadStore()
485
+ return loaded.ok ? loaded.store : { version: 1, entries: {} }
486
+ }
487
+
488
+ /**
489
+ * Laporkan masalah store ke stderr. Hanya path + kode/penyebab — TIDAK
490
+ * pernah nilai rahasia maupun cuplikan isi berkas (cuplikan JSON bisa
491
+ * memuat secret dalam bentuk base64/teks).
492
+ */
493
+ function reportStoreProblem(loaded: { reason: "corrupt" | "unreadable"; code?: string }): void {
494
+ if (loaded.reason === "corrupt")
495
+ process.stderr.write(
496
+ `[keystore] store ${storePath()} is corrupt (invalid JSON) — refusing to write; repair or remove it manually\n`,
497
+ )
498
+ else
499
+ process.stderr.write(
500
+ `[keystore] cannot read store ${storePath()} (${loaded.code ?? "error"}) — refusing to write\n`,
77
501
  )
78
- return { version: 1, entries: parsed.entries as SecretStore["entries"] }
79
- } catch {}
80
- return { version: 1, entries: {} }
81
502
  }
82
503
 
83
504
  async function saveStore(store: SecretStore): Promise<void> {
505
+ await mkdir(join(storePath(), ".."), { recursive: true, mode: 0o700 }).catch(() => {})
506
+ const data = JSON.stringify(store)
507
+ // Seam uji: penulis yang gagal mensimulasikan "tulis gagal" tanpa
508
+ // bergantung pada permission/filesystem spesifik OS.
509
+ if (writerOverride) {
510
+ await writerOverride(storePath(), data)
511
+ return
512
+ }
513
+ // Kegagalan tulis HARUS keluar ke pemanggil. Dulu error ditelan di sini,
514
+ // sehingga setSecret melaporkan "sukses" + men-cache nilai padahal tak ada
515
+ // yang tersimpan — user mengira API key aman, nyatanya hilang saat restart.
516
+ await atomicWriteText(storePath(), data)
517
+ await chmod(storePath(), 0o600).catch(() => {})
518
+ }
519
+
520
+ /** Tulis store. false = gagal (pesan dicetak, tanpa nilai rahasia). */
521
+ async function persistStore(store: SecretStore): Promise<boolean> {
84
522
  try {
85
- await mkdir(join(storePath(), ".."), { recursive: true, mode: 0o700 }).catch(() => {})
86
- await atomicWriteText(storePath(), JSON.stringify(store))
87
- await chmod(storePath(), 0o600).catch(() => {})
88
- } catch {}
523
+ await saveStore(store)
524
+ return true
525
+ } catch (e) {
526
+ const code = (e as NodeJS.ErrnoException)?.code
527
+ process.stderr.write(
528
+ `[keystore] cannot write store ${storePath()} (${code ?? "error"}) — secret NOT stored\n`,
529
+ )
530
+ return false
531
+ }
89
532
  }
90
533
 
91
534
  // DPAPI user-scope roundtrip via powershell bawaan (5.1 maupun 7.x).
@@ -118,7 +561,13 @@ const DPAPI_UNPROTECT = [
118
561
 
119
562
  function dpapiAvailable(): boolean {
120
563
  if (process.env.MINICODE_KEYSTORE_DISABLE === "1") return false
121
- if (process.platform !== "win32" && !process.env.MINICODE_KEYSTORE_FORCE_DPAPI) return false
564
+ // [Audit #2 A.8] Force DPAPI HANYA saat env eksplisit "1"/"true" — nilai "0"
565
+ // atau "false" tak boleh mengaktifkan jalur DPAPI (sebelumnya `!env` membuat
566
+ // string "0" yang truthy ikut memaksa DPAPI).
567
+ const forceDpapi =
568
+ process.env.MINICODE_KEYSTORE_FORCE_DPAPI === "1" ||
569
+ process.env.MINICODE_KEYSTORE_FORCE_DPAPI === "true"
570
+ if (process.platform !== "win32" && !forceDpapi) return false
122
571
  return true
123
572
  }
124
573
 
@@ -141,25 +590,55 @@ function dpapiUnprotect(blob: string): string | null {
141
590
  return r.stdout.replace(/\r?\n$/, "")
142
591
  }
143
592
 
144
- /** Simpan rahasia. Return backend yang dipakai ("dpapi"|"plain"), null bila gagal total. */
593
+ /**
594
+ * Simpan rahasia. Return backend yang dipakai ("dpapi"|"plain"), null bila
595
+ * gagal total. null juga dipakai saat store tak bisa dibaca/di-parse:
596
+ * menimpanya dengan store kosong = menghapus semua credential lama.
597
+ *
598
+ * Proteksi DPAPI dijalankan DI LUAR kunci: powershell bisa berjalan sampai
599
+ * 15 detik dan tidak menyentuh store sama sekali — menahannya di dalam kunci
600
+ * hanya memperlebar jendela di mana penulis lain menunggu (atau, pada
601
+ * implementasi lama, salah dinilai "basi" lalu digeser). Kalau proteksi
602
+ * gagal: tak ada yang ditulis dan cache tak disentuh.
603
+ *
604
+ * Seluruh baca-modifikasi-tulis dijalankan di bawah kunci store: dua
605
+ * penulis konkuren (proses berbeda ATAU dua panggilan dalam satu proses)
606
+ * tak boleh saling menimpa credential.
607
+ */
145
608
  export async function setSecret(key: string, value: string): Promise<"dpapi" | "plain" | null> {
146
609
  if (!key || !value) return null
147
- const store = await loadStore()
610
+ const useDpapi = dpapiAvailable()
148
611
  // Platform ber-DPAPI tapi proteksi GAGAL = jangan turun diam-diam ke
149
612
  // plaintext (user mengira secret-nya terproteksi OS). Tanpa backend
150
613
  // (non-Windows) = plain jujur berlabel.
151
- if (dpapiAvailable()) {
152
- const blob = dpapiProtect(value)
614
+ let blob: string | null = null
615
+ if (useDpapi) {
616
+ blob = dpapiProtect(value)
153
617
  if (!blob) return null
154
- store.entries[key] = { enc: blob, alg: "dpapi" }
155
- await saveStore(store)
156
- secretCache.set(key, value)
157
- return "dpapi"
158
618
  }
159
- store.entries[key] = { enc: value, alg: "plain" }
160
- await saveStore(store)
161
- secretCache.set(key, value)
162
- return "plain"
619
+ return await withStoreLock(async (): Promise<"dpapi" | "plain" | null> => {
620
+ const loaded = await loadStore()
621
+ let store: SecretStore
622
+ if (loaded.ok) store = loaded.store
623
+ else if (loaded.reason === "absent") store = { version: 1, entries: {} }
624
+ else {
625
+ // Fail-closed: store ada tapi tak bisa dibaca/di-parse. Menulis di sini
626
+ // berarti menimpa store itu dengan isi baru — credential lama lenyap
627
+ // tanpa jejak dan tanpa backup.
628
+ reportStoreProblem(loaded)
629
+ return null
630
+ }
631
+ if (useDpapi) {
632
+ store.entries[key] = { enc: blob as string, alg: "dpapi" }
633
+ if (!(await persistStore(store))) return null
634
+ secretCache.set(key, value)
635
+ return "dpapi"
636
+ }
637
+ store.entries[key] = { enc: value, alg: "plain" }
638
+ if (!(await persistStore(store))) return null
639
+ secretCache.set(key, value)
640
+ return "plain"
641
+ })
163
642
  }
164
643
 
165
644
  /** Baca rahasia. null = tak ada / tak bisa dibuka. Tak pernah melempar. */
@@ -168,7 +647,7 @@ export async function getSecret(key: string): Promise<string | null> {
168
647
  if (secretCache.has(key)) return secretCache.get(key) ?? null
169
648
  let value: string | null = null
170
649
  try {
171
- const store = await loadStore()
650
+ const store = await loadStoreForRead()
172
651
  const entry = store.entries[key]
173
652
  if (entry) {
174
653
  if (entry.alg === "dpapi") {
@@ -184,16 +663,39 @@ export async function getSecret(key: string): Promise<string | null> {
184
663
  return value
185
664
  }
186
665
 
187
- /** Hapus rahasia. Selalu "sukses" semu (idempoten, tak melempar). */
188
- export async function deleteSecret(key: string): Promise<void> {
189
- secretCache.delete(key)
190
- try {
191
- const store = await loadStore()
192
- if (store.entries[key]) {
666
+ /**
667
+ * Hapus rahasia.
668
+ * - true = key tidak ada lagi di store (dihapus, atau memang tak ada).
669
+ * - false = store tak bisa dibaca/di-parse/tak bisa ditulis, ATAU kunci store
670
+ * tak diperoleh dalam batas waktu → TIDAK ADA yang berubah dan key masih
671
+ * ada di berkas (fail-closed).
672
+ *
673
+ * Cache tak disentuh saat gagal: dulu cache dihapus lebih dulu sehingga sesi
674
+ * mengira key terhapus padahal berkasnya masih memegangnya.
675
+ */
676
+ export async function deleteSecret(key: string): Promise<boolean> {
677
+ // null = kunci tak diperoleh (fail-closed) → false, bukan "sukses semu".
678
+ return (
679
+ (await withStoreLock(async (): Promise<boolean> => {
680
+ const loaded = await loadStore()
681
+ let store: SecretStore
682
+ if (loaded.ok) store = loaded.store
683
+ else if (loaded.reason === "absent") store = { version: 1, entries: {} }
684
+ else {
685
+ // Fail-closed: jangan tulis apa pun, jangan pretend key terhapus.
686
+ reportStoreProblem(loaded)
687
+ return false
688
+ }
689
+ if (!store.entries[key]) {
690
+ secretCache.delete(key)
691
+ return true
692
+ }
193
693
  delete store.entries[key]
194
- await saveStore(store)
195
- }
196
- } catch {}
694
+ if (!(await persistStore(store))) return false
695
+ secretCache.delete(key)
696
+ return true
697
+ })) === true
698
+ )
197
699
  }
198
700
 
199
701
  /** Backend aktif untuk pesan/diagnostik (bukan rahasia). */