minicode-ai 0.14.0 → 0.14.2

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 (88) hide show
  1. package/README.md +1 -1
  2. package/cli/args.ts +16 -3
  3. package/cli/auto-update.ts +32 -2
  4. package/cli/commands/exec.ts +9 -0
  5. package/cli/index.ts +31 -13
  6. package/cli/setup.ts +31 -19
  7. package/cli/tui.ts +63 -40
  8. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  9. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  10. package/docs/README.md +2 -2
  11. package/docs/TERMINAL_CONTRACT.md +52 -26
  12. package/docs/agents.md +2 -2
  13. package/docs/choosing-mode.md +20 -13
  14. package/docs/cli.md +11 -11
  15. package/docs/environment.md +3 -3
  16. package/docs/getting-started.md +14 -12
  17. package/docs/glossary.md +1 -1
  18. package/docs/mcp-lsp.md +1 -1
  19. package/docs/policy-sandbox.md +7 -1
  20. package/docs/security-model.md +2 -2
  21. package/docs/security.md +7 -1
  22. package/docs/tools.md +4 -4
  23. package/docs/verify-benchmark.md +16 -0
  24. package/package.json +1 -3
  25. package/src/app/mentions.ts +4 -3
  26. package/src/app/session.ts +19 -9
  27. package/src/app/tool-layer.ts +10 -3
  28. package/src/constants.ts +17 -0
  29. package/src/lib/git-hardening.ts +27 -22
  30. package/src/lib/safe-open.ts +73 -19
  31. package/src/lib/trusted-exec.ts +7 -4
  32. package/src/mcp/client.ts +34 -9
  33. package/src/mcp/transport.ts +96 -42
  34. package/src/memory/files.ts +15 -4
  35. package/src/memory/vector.ts +5 -1
  36. package/src/policy/context.ts +21 -13
  37. package/src/policy/permission.ts +75 -16
  38. package/src/policy/tool-contract.ts +21 -10
  39. package/src/policy/update-check.ts +83 -6
  40. package/src/policy/usage.ts +17 -7
  41. package/src/policy/work-mode.ts +51 -17
  42. package/src/presentation/adapter.ts +64 -2
  43. package/src/presentation/events.ts +6 -0
  44. package/src/presentation/model.ts +1 -0
  45. package/src/presentation/projection.ts +2 -0
  46. package/src/presentation/reducer.ts +1 -0
  47. package/src/providers/anthropic.ts +52 -19
  48. package/src/providers/guards.ts +98 -13
  49. package/src/providers/responses.ts +61 -23
  50. package/src/providers/sse-bounds.ts +170 -0
  51. package/src/repo/repomap.ts +10 -11
  52. package/src/runtime/execution-backend.ts +7 -8
  53. package/src/sandbox/docker.ts +113 -9
  54. package/src/session/checkpoint.ts +9 -2
  55. package/src/session/persistence.ts +5 -2
  56. package/src/session/verification.ts +55 -16
  57. package/src/skills/loader.ts +16 -3
  58. package/src/tools/bash.ts +6 -3
  59. package/src/tools/code_run.ts +6 -5
  60. package/src/tools/context.ts +8 -0
  61. package/src/tools/delete_file.ts +2 -1
  62. package/src/tools/edit.ts +2 -1
  63. package/src/tools/git.ts +128 -54
  64. package/src/tools/glob.ts +2 -1
  65. package/src/tools/grep.ts +31 -6
  66. package/src/tools/lsp.ts +5 -4
  67. package/src/tools/mcp_call.ts +3 -1
  68. package/src/tools/memory.ts +175 -180
  69. package/src/tools/move_file.ts +2 -1
  70. package/src/tools/patch.ts +2 -1
  71. package/src/tools/read_file.ts +94 -1
  72. package/src/tools/read_image.ts +2 -1
  73. package/src/tools/task.ts +2 -1
  74. package/src/tools/todo.ts +4 -5
  75. package/src/tools/web_fetch.ts +28 -12
  76. package/src/tools/web_search.ts +28 -9
  77. package/src/tools/write_file.ts +2 -1
  78. package/src/ui/assistant/simple.ts +72 -3
  79. package/src/ui/footer.ts +17 -12
  80. package/src/ui/i18n/en.ts +6 -3
  81. package/src/ui/i18n/id.ts +6 -3
  82. package/src/ui/render/width.ts +107 -79
  83. package/src/ui/runtime/screen.ts +49 -37
  84. package/src/ui/tui/app.ts +261 -209
  85. package/src/ui/tui/transcript.ts +39 -0
  86. package/CHANGELOG.md +0 -1167
  87. package/docs/PLAN_UIUX_V6.md +0 -209
  88. package/docs/changelog.md +0 -3
@@ -1,11 +1,10 @@
1
1
  import { type ChildProcess, spawn } from "node:child_process"
2
- import { createInterface } from "node:readline"
3
2
  import { LIMITS } from "../constants.ts"
4
3
  import { sanitizeSpawnEnv } from "../policy/scrub.ts"
5
4
 
6
5
  export class McpTransport {
7
6
  private proc: ChildProcess | null = null
8
- private rl: ReturnType<typeof createInterface> | null = null
7
+ private stdoutFrame = Buffer.alloc(0)
9
8
  private pending = new Map<
10
9
  string | number,
11
10
  {
@@ -37,35 +36,22 @@ export class McpTransport {
37
36
  })
38
37
 
39
38
  this.proc.on("error", (err) => this.failAll(err))
39
+ this.proc.stdin?.on("error", (err) => {
40
+ // Server dapat keluar tepat sebelum request ditulis. EPIPE pada stdin
41
+ // tetap harus menjadi penolakan request, bukan uncaught exception proses.
42
+ this.closed = true
43
+ this.writeQueue = []
44
+ this.draining = false
45
+ this.failAll(err)
46
+ })
40
47
  this.proc.on("exit", (code) => {
41
48
  if (!this.closed) this.failAll(new Error(`MCP server exited with code ${code}`))
42
49
  })
43
50
  this.proc.stderr?.on("data", (d: Buffer) =>
44
51
  process.stderr.write(`[mcp:${command}] ${d.toString().trim()}\n`),
45
52
  )
46
- // ensure previous rl closed if reconnecting (defensive)
47
- if (this.rl)
48
- try {
49
- this.rl.close()
50
- } catch {}
51
-
52
- this.rl = createInterface({ input: this.proc.stdout! })
53
- this.rl.on("line", (line) => {
54
- if (!line.trim()) return
55
- try {
56
- const msg = JSON.parse(line)
57
- if (msg.id != null && this.pending.has(msg.id)) {
58
- const p = this.pending.get(msg.id)!
59
- clearTimeout(p.timer)
60
- p.unsubscribe?.()
61
- this.pending.delete(msg.id)
62
- if (msg.error) p.reject(new Error(msg.error.message || JSON.stringify(msg.error)))
63
- else p.resolve(msg.result)
64
- }
65
- } catch (e) {
66
- process.stderr.write(`[mcp] ignoring invalid JSON from server: ${(e as Error).message}\n`)
67
- }
68
- })
53
+ this.stdoutFrame = Buffer.alloc(0)
54
+ this.proc.stdout!.on("data", (chunk: Buffer) => this.consumeStdout(chunk))
69
55
  }
70
56
 
71
57
  async request(
@@ -107,36 +93,43 @@ export class McpTransport {
107
93
  }
108
94
 
109
95
  async close(): Promise<void> {
110
- if (this.closed) return
96
+ if (this.closed && !this.proc) return
111
97
  this.closed = true
112
98
  this.writeQueue = []
113
99
  this.draining = false
114
100
  this.failAll(new Error("transport closed"))
115
- if (this.rl) this.rl.close()
116
101
  try {
117
102
  this.proc?.stdin?.end()
118
103
  } catch {}
119
104
  this.killSignal.abort()
120
105
  if (this.proc) {
121
- await new Promise<void>((r) => {
122
- const p = this.proc!
123
- const t = setTimeout(() => {
124
- try {
125
- p.kill("SIGKILL")
126
- } catch {}
127
- r()
128
- }, 2_000)
129
- p.once("exit", () => {
130
- clearTimeout(t)
131
- r()
106
+ const p = this.proc
107
+ if (p.exitCode === null && p.signalCode === null) {
108
+ await new Promise<void>((r) => {
109
+ const t = setTimeout(() => {
110
+ try {
111
+ p.kill("SIGKILL")
112
+ } catch {}
113
+ r()
114
+ }, 2_000)
115
+ p.once("exit", () => {
116
+ clearTimeout(t)
117
+ r()
118
+ })
132
119
  })
133
- })
120
+ }
134
121
  }
135
122
  this.proc = null
136
123
  }
137
124
 
138
125
  private write(msg: unknown) {
139
- if (!this.proc?.stdin) throw new Error("transport not connected")
126
+ const proc = this.proc
127
+ if (!proc?.stdin) throw new Error("transport not connected")
128
+ if (this.closed || proc.exitCode !== null || proc.stdin.destroyed) {
129
+ throw new Error(
130
+ `MCP transport is closed${proc.exitCode === null ? "" : ` (exit ${proc.exitCode})`}`,
131
+ )
132
+ }
140
133
  let line: string
141
134
  try {
142
135
  line = `${JSON.stringify(msg)}\n`
@@ -147,10 +140,10 @@ export class McpTransport {
147
140
  this.writeQueue.push(line)
148
141
  return
149
142
  }
150
- const ok = this.proc.stdin.write(line)
143
+ const ok = proc.stdin.write(line)
151
144
  if (!ok) {
152
145
  this.draining = true
153
- this.proc.stdin.once("drain", () => {
146
+ proc.stdin.once("drain", () => {
154
147
  this.draining = false
155
148
  this.flushQueue()
156
149
  })
@@ -173,6 +166,67 @@ export class McpTransport {
173
166
  }
174
167
  }
175
168
 
169
+ /** Frame parsing stays incremental so a peer cannot make readline buffer an unlimited line. */
170
+ private consumeStdout(chunk: Buffer): void {
171
+ let start = 0
172
+ for (let i = 0; i < chunk.length; i++) {
173
+ if (chunk[i] !== 0x0a) continue
174
+ const part = chunk.subarray(start, i)
175
+ if (this.stdoutFrame.length + part.length > LIMITS.MCP_STDIO_FRAME_MAX_BYTES) {
176
+ this.rejectOversizedFrame(this.stdoutFrame.length + part.length)
177
+ return
178
+ }
179
+ const frame = this.stdoutFrame.length === 0 ? part : Buffer.concat([this.stdoutFrame, part])
180
+ this.stdoutFrame = Buffer.alloc(0)
181
+ this.handleFrame(frame)
182
+ if (this.closed) return
183
+ start = i + 1
184
+ }
185
+ if (start < chunk.length) {
186
+ const remainder = chunk.subarray(start)
187
+ if (this.stdoutFrame.length + remainder.length > LIMITS.MCP_STDIO_FRAME_MAX_BYTES) {
188
+ this.rejectOversizedFrame(this.stdoutFrame.length + remainder.length)
189
+ return
190
+ }
191
+ this.stdoutFrame =
192
+ this.stdoutFrame.length === 0
193
+ ? Buffer.from(remainder)
194
+ : Buffer.concat([this.stdoutFrame, remainder])
195
+ }
196
+ }
197
+
198
+ private handleFrame(frame: Buffer): void {
199
+ if (frame.length === 0) return
200
+ try {
201
+ const msg = JSON.parse(frame.toString("utf8"))
202
+ if (msg.id != null && this.pending.has(msg.id)) {
203
+ const p = this.pending.get(msg.id)!
204
+ clearTimeout(p.timer)
205
+ p.unsubscribe?.()
206
+ this.pending.delete(msg.id)
207
+ if (msg.error) p.reject(new Error(msg.error.message || "MCP server returned an error"))
208
+ else p.resolve(msg.result)
209
+ }
210
+ } catch {
211
+ process.stderr.write("[mcp] ignoring invalid JSON from server\n")
212
+ }
213
+ }
214
+
215
+ private rejectOversizedFrame(size: number): void {
216
+ const error = new Error(
217
+ `MCP stdio frame exceeds ${LIMITS.MCP_STDIO_FRAME_MAX_BYTES} bytes (at least ${size})`,
218
+ )
219
+ this.closed = true
220
+ this.stdoutFrame = Buffer.alloc(0)
221
+ this.writeQueue = []
222
+ this.draining = false
223
+ this.failAll(error)
224
+ this.killSignal.abort(error)
225
+ try {
226
+ this.proc?.kill("SIGKILL")
227
+ } catch {}
228
+ }
229
+
176
230
  private failAll(err: Error) {
177
231
  for (const p of this.pending.values()) {
178
232
  clearTimeout(p.timer)
@@ -3,6 +3,7 @@ import { homedir } from "node:os"
3
3
  import { dirname, join, resolve } from "node:path"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { homeDir } from "../lib/db-path.ts"
6
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
6
7
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
7
8
  import { scrubSecrets } from "../policy/scrub.ts"
8
9
 
@@ -36,8 +37,15 @@ export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
36
37
  // symlink keluar workspace. globalMem (home) sengaja dikecualikan —
37
38
  // di luar cwd by design. Samakan rules/ di bawah ke realpath.
38
39
  if (p !== globalMem && isRealPathOutsideRoot(p, cwd)) continue
39
- const txt = await readFile(p, "utf8")
40
- if (txt.trim()) parts.push(`# ${tildePath(p)}\n${scrubSecrets(txt.slice(0, 6000))}`)
40
+ const { text, truncated } = await safeReadFileCapped(
41
+ p,
42
+ p === globalMem ? dirname(p) : cwd,
43
+ 6000,
44
+ )
45
+ if (text.trim())
46
+ parts.push(
47
+ `# ${tildePath(p)}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 6000 bytes]" : ""}`,
48
+ )
41
49
  } catch {}
42
50
  }
43
51
  // Load .minicode/rules/*.md (Kiro steering style)
@@ -57,8 +65,11 @@ export async function loadMemoryFiles(cwd = process.cwd()): Promise<string> {
57
65
  try {
58
66
  const full = join(rulesDir, f as string)
59
67
  if (isRealPathOutsideRoot(full, cwd)) continue
60
- const txt = await readFile(full, "utf8")
61
- if (txt.trim()) parts.push(`# rules/${f}\n${scrubSecrets(txt.slice(0, 3000))}`)
68
+ const { text, truncated } = await safeReadFileCapped(full, cwd, 3000)
69
+ if (text.trim())
70
+ parts.push(
71
+ `# rules/${f}\n${scrubSecrets(text)}${truncated ? "\n… [truncated: showing first 3000 bytes]" : ""}`,
72
+ )
62
73
  } catch {}
63
74
  }
64
75
  } catch {}
@@ -1278,7 +1278,11 @@ export async function searchHybrid(
1278
1278
  if (rows.length === 0) return []
1279
1279
 
1280
1280
  let queryVec: number[] | null = null
1281
- if (opts.baseUrl && opts.apiKey) {
1281
+ // F-07: bila semua kandidat hanya memiliki teks (mis. memori manual atau
1282
+ // fallback provider tanpa embedding), vektor query tidak dapat mengubah
1283
+ // skor satu pun. Jangan melakukan DNS/HTTP embedding yang hasilnya tak dipakai.
1284
+ const hasVectorCandidates = rows.some((row) => row.embedding !== null)
1285
+ if (hasVectorCandidates && opts.baseUrl && opts.apiKey) {
1282
1286
  const vecs = await embedTexts(opts.baseUrl, opts.apiKey, [query], opts.embeddingModel)
1283
1287
  if (vecs?.[0]) queryVec = vecs[0]
1284
1288
  }
@@ -1,11 +1,12 @@
1
1
  import { execFile } from "node:child_process"
2
- import { readFile } from "node:fs/promises"
3
- import { resolve } from "node:path"
2
+ import { readdir, realpath } from "node:fs/promises"
3
+ import { join, resolve } from "node:path"
4
4
  import { promisify } from "node:util"
5
5
  import type { TokenEstimator } from "#minicore"
6
6
  import { DEFAULT_CHARS_PER_TOKEN } from "#minicore/core/tokens.ts"
7
7
  import { LIMITS } from "../constants.ts"
8
8
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
9
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
9
10
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
10
11
  import { loadMemoryFiles } from "../memory/files.ts"
11
12
  import { loadRepoMap } from "../repo/repomap.ts"
@@ -259,13 +260,13 @@ export async function buildSystemPrompt(
259
260
  for (const p of agentFiles) {
260
261
  if (signal.aborted) throw new Error("aborted")
261
262
  try {
262
- // Symlink escape (temuan audit #06): AGENTS.md symlink keluar workspace
263
- // ikut terbaca tanpa ini. Samakan dengan guard rules/ di bawah.
264
263
  const full = resolve(cwd, p)
265
- if (isRealPathOutsideRoot(full, cwd)) continue
266
- const txt = await readFile(full, "utf8")
264
+ const loaded = await safeReadFileCapped(full, cwd, 3000)
267
265
  if (signal.aborted) throw new Error("aborted")
268
- parts.push(`\n# ${p}\n${cutMarked(txt, 3000)}`)
266
+ const body = loaded.truncated
267
+ ? `${loaded.text}\n… [truncated: showing first 3000 bytes]`
268
+ : loaded.text
269
+ parts.push(`\n# ${p}\n${cutMarked(body, 3000)}`)
269
270
  loadedAgent = true
270
271
  if (p === "AGENTS.md") break // prefer AGENTS.md, else collect all
271
272
  } catch (e) {
@@ -275,13 +276,20 @@ export async function buildSystemPrompt(
275
276
  // Also load steering if not already
276
277
  if (!loadedAgent) {
277
278
  try {
278
- const { readdir } = await import("node:fs/promises")
279
- const steeringDir = `${cwd}/.minicode/steering`
280
- const files = await readdir(steeringDir).catch(() => [] as unknown as string[])
281
- for (const f of (files as string[]).slice(0, 3)) {
279
+ const steeringDir = resolve(cwd, ".minicode/steering")
280
+ // Resolve direktori sebelum enumerasi: junction/reparse yang keluar
281
+ // workspace tidak boleh menjadi sumber instruksi fallback.
282
+ const realSteeringDir = await realpath(steeringDir)
283
+ if (isRealPathOutsideRoot(realSteeringDir, cwd))
284
+ throw new Error("steering directory outside workspace")
285
+ const files = (await readdir(realSteeringDir)).sort().slice(0, 3)
286
+ for (const f of files) {
282
287
  try {
283
- const txt = await readFile(`${steeringDir}/${f}`, "utf8")
284
- parts.push(`\n# steering/${f}\n${cutMarked(txt, 2000)}`)
288
+ const loaded = await safeReadFileCapped(join(realSteeringDir, f), cwd, 2000)
289
+ const body = loaded.truncated
290
+ ? `${loaded.text}\n… [truncated: showing first 2000 bytes]`
291
+ : loaded.text
292
+ parts.push(`\n# steering file\n${cutMarked(body, 2000)}`)
285
293
  } catch {}
286
294
  }
287
295
  } catch {}
@@ -27,9 +27,40 @@ import {
27
27
  } from "./jail.ts"
28
28
  import { scrubSecrets } from "./scrub.ts"
29
29
  // [Fase 2 / TOOL-01] Diimpor dari registry kontrak tool (satu sumber).
30
- import { contractForTool, GATED_TOOLS, READONLY_TOOL_NAMES } from "./tool-contract.ts"
30
+ import {
31
+ contractForTool,
32
+ GATED_TOOLS,
33
+ PLAN_EXTRA_TOOL_NAMES,
34
+ READONLY_TOOL_NAMES,
35
+ } from "./tool-contract.ts"
31
36
 
32
- export type PermissionMode = "auto" | "readonly" | "plan" | "allow-all" | "ask" | "allowlist"
37
+ /**
38
+ * Approval policy — DUA nilai yang berhadapan dengan pengguna.
39
+ *
40
+ * `auto` (AUTO) = eksekusi otonom penuh: selama capability & scope diizinkan,
41
+ * aksi berjalan TANPA henti persetujuan rutin. Bukan "izinkan semuanya" —
42
+ * hard-deny (jail/owned-state/bash-guard) tetap berlaku di atasnya.
43
+ * `ask` (ASK) = pengawasan manusia: aksi yang dicakup kebijakan persetujuan
44
+ * meminta izin sebelum jalan. Hard-deny tetap tak bisa di-override.
45
+ *
46
+ * Ejaan lowercase dipertahankan sebagai identitas internal/kompatibilitas
47
+ * untuk AUTO/ASK (persistence & ToolContext memakai nilai ini).
48
+ */
49
+ export type ApprovalMode = "auto" | "ask"
50
+
51
+ /**
52
+ * Union kompatibilitas selama migrasi arsitektur mode.
53
+ *
54
+ * HANYA `"auto"`/`"ask"` adalah kebijakan persetujuan. Sisanya adalah profil
55
+ * capability WARISAN yang kini menjadi tanggung jawab Tool Access Policy:
56
+ * - `"readonly"` → capability read-only internal (bukan permukaan; batas
57
+ * scheduler adalah injected AutonomousPermissionHandler,
58
+ * BUKAN nilai ini).
59
+ * - `"plan"` → ceiling WorkMode PLAN (perencanaan user-facing = PLAN).
60
+ * - `"allowlist"` → kebijakan akses bash/tool (flag warisan --allowlist).
61
+ * - `"allow-all"` → profil akses privileged (flag warisan --allow-all).
62
+ */
63
+ export type PermissionMode = ApprovalMode | "readonly" | "plan" | "allow-all" | "allowlist"
33
64
 
34
65
  /**
35
66
  * View persetujuan yang di-inject dari composition root (cli/setup.ts memakai
@@ -303,6 +334,14 @@ export function createPermissionHandler(
303
334
  * Tanpa store = perilaku lama persis (tanpa verifikasi tambahan).
304
335
  */
305
336
  approvalBindings?: ApprovalBindingStore
337
+ /**
338
+ * Tool Access Policy — set nama tool yang DIOTORISASI sesi ini (tool yang
339
+ * terlihat/terdaftar, termasuk MCP runtime `server.tool` yang servernya
340
+ * terkonfigurasi). Dipakai `auto` untuk membedakan MCP terotorisasi dari
341
+ * MCP tak-dikenal/tak-terkonfigurasi: hanya nama bertitik yang ADA di set
342
+ * ini yang boleh auto-allow. Absen = fail-closed (semua MCP bertitik deny).
343
+ */
344
+ authorizedTools?: ReadonlySet<string> | null
306
345
  } = {},
307
346
  ): PermissionHandler {
308
347
  const state = { mode: (opts.mode ?? "auto") as PermissionMode }
@@ -310,6 +349,7 @@ export function createPermissionHandler(
310
349
  const approvalBindings = opts.approvalBindings
311
350
  const askUser = opts.ask
312
351
  const allowLocal = opts.allowLocalConfig === true
352
+ const authorizedTools = opts.authorizedTools
313
353
  let allowlistCache: string[] | null = null
314
354
  // Persetujuan "always" sesi ini — in-memory, bukan dari disk. Tanpa ini,
315
355
  // jawaban always yang baru disimpan ke berkas lokal tak terlihat saat local
@@ -418,17 +458,13 @@ export function createPermissionHandler(
418
458
  "allow-all": async () => "allow",
419
459
  readonly: async (call) =>
420
460
  READONLY_TOOLS.has(call.name) ? "allow" : deny(call, "read-only mode"),
421
- // Plan = readonly + tiga perkecualian aman: todo_write (artefak rencana
422
- // .minicode/plans, bukan file workspace), delegate_task (penelahan
423
- // rencana, bukan eksekusi — dipaksa explore/read-only di task.ts bila
424
- // parent plan/readonly, permission hanya membuka gerbangnya), dan
425
- // submit_result (singleton memori-proses untuk exec --json, tanpa tulis
426
- // file/state sesi; terlihat di PLAN_EXTRA tool-layer jadi harus boleh).
461
+ // Plan = readonly + tiga perkecualian aman (PLAN_EXTRA_TOOL_NAMES):
462
+ // todo_write (artefak rencana .minicode/plans, bukan file workspace),
463
+ // delegate_task (penelahan rencana, bukan eksekusi — dipaksa explore/
464
+ // read-only di task.ts bila parent plan/readonly, permission hanya membuka
465
+ // gerbangnya), dan submit_result (singleton memori-proses untuk exec --json).
427
466
  plan: async (call) =>
428
- READONLY_TOOLS.has(call.name) ||
429
- call.name === "todo_write" ||
430
- call.name === "delegate_task" ||
431
- call.name === "submit_result"
467
+ READONLY_TOOLS.has(call.name) || PLAN_EXTRA_TOOL_NAMES.has(call.name)
432
468
  ? "allow"
433
469
  : deny(call, "plan mode"),
434
470
  allowlist: async (call, args) => {
@@ -480,10 +516,33 @@ export function createPermissionHandler(
480
516
  }
481
517
  return ans === "allow" ? "allow" : "deny"
482
518
  },
483
- auto: async (call, args, signal) => {
519
+ // AUTO = otonomi penuh. Selama tool diotorisasi oleh Tool Access Policy dan
520
+ // scope mengizinkan, jalankan TANPA prompt persetujuan rutin. Ini berbeda
521
+ // dari `ask` (di bawah) yang menahan tulis/eksekusi untuk izin manusia.
522
+ //
523
+ // Keputusan desain (mode-architecture recon): `gatedByDefault` TIDAK lagi
524
+ // berarti "auto wajib prompt". Tool gated (git_commit, delegate_task,
525
+ // mcp_call/read/prompt) adalah capability yang WAJIB Otorisasi — di ASK
526
+ // mereka butuh izin manusia, tetapi di AUTO mereka jalan bila authorized.
527
+ // Hard-deny (jail/owned-state/bash-guard) tetap berlaku di semua jalur.
528
+ auto: async (call, args, _signal) => {
484
529
  if (READONLY_TOOLS.has(call.name)) return "allow"
485
- if (isGated(call.name))
486
- return await promptAskOr(call, () => deny(call, "gated approval unavailable"), signal)
530
+ // ask_user = interaksi-user, bukan eksekusi. Di AUTO dilarang deterministik
531
+ // (BLOCKED) supaya model memakai asumsi default sendiri — jangan biarkan
532
+ // pergantian tanya-jawab rutin mengubah AUTO jadi ASK.
533
+ if (call.name === "ask_user")
534
+ return deny(call, "ask_user unavailable in AUTO (autonomous mode)")
535
+ // Tool MCP bertitik: hanya diotorisasi bila terdaftar di sesi (server
536
+ // terkonfigurasi). Tak dikenal/tak terkonfigurasi = deny, bukan prompt
537
+ // (AUTO tak boleh bertanya sebagai jalan pintas hard-restriction).
538
+ if (isMcpToolName(call.name)) {
539
+ if (authorizedTools?.has(call.name)) return "allow"
540
+ return deny(call, "MCP tool not configured/authorized")
541
+ }
542
+ // Capability gated (git_commit, delegate_task, mcp_call/read/prompt):
543
+ // otonom di AUTO bila authorized. Scope dijaga tool-nya sendiri + jail
544
+ // (git_commit: path/staged dijail; delegate: anak ter-ceiling WorkMode).
545
+ if (GATED_TOOLS.has(call.name)) return "allow"
487
546
  if (FILE_WRITE_TOOLS.has(call.name)) return "allow"
488
547
  if (INTERNAL_WRITE_TOOLS.has(call.name)) return "allow"
489
548
  if (call.name === "code_run") {
@@ -498,7 +557,7 @@ export function createPermissionHandler(
498
557
  if (br) return deny(call, `bash-guard: ${br}`)
499
558
  return "allow"
500
559
  }
501
- return "deny"
560
+ return deny(call, "not authorized in AUTO mode")
502
561
  },
503
562
  }
504
563
 
@@ -22,13 +22,8 @@
22
22
  // keduanya akan mengubah perilaku recovery yang sudah teruji. Karena itu
23
23
  // `journalMutation` dieksplisitkan, bukan disimpulkan.
24
24
  //
25
- // KEPUTUSAN PENTING — `code_run` sengaja `parallel-read`:
26
- //
27
- // Executor hari ini memperlakukan `code_run` sebagai non-write (bukan anggota
28
- // WRITE_TOOLS/EXCLUSIVE_TOOLS), sehingga batch membacanya paralel. Mengubahnya
29
- // menjadi `exclusive` di sini akan mengubah penjadwalan yang sudah teruji, yang
30
- // bukan tujuan Fase 2. Klasifikasi disamakan dengan perilaku nyata; perbaikan
31
- // penjadwalan (bila diinginkan) harus menjadi perubahan terpisah dengan bukti.
25
+ // `code_run` mutasi workspace melalui sandbox RW. Karena itu ia harus menjadi
26
+ // exclusive di batch yang juga dapat membaca atau menulis file yang sama.
32
27
 
33
28
  /** Kelas efek samping yang dideklarasikan sebuah tool. */
34
29
  export type SideEffectTier =
@@ -348,11 +343,10 @@ export const TOOL_CONTRACTS: readonly ToolContractMetadata[] = [
348
343
  idempotent: false,
349
344
  journalMutation: false,
350
345
  }),
351
- // Lihat catatan modul: perilaku paralel `code_run` dipertahankan apa adanya.
352
346
  C({
353
347
  name: "code_run",
354
348
  sideEffectTier: "LOCAL_ENV_MUTATION",
355
- concurrencyClass: "parallel-read",
349
+ concurrencyClass: "exclusive",
356
350
  gatedByDefault: false,
357
351
  allowedInExplore: false,
358
352
  allowedInAutonomous: false,
@@ -420,7 +414,7 @@ export const TOOL_CONTRACTS: readonly ToolContractMetadata[] = [
420
414
  C({
421
415
  name: "git_commit",
422
416
  sideEffectTier: "EXTERNAL_IRREVERSIBLE",
423
- concurrencyClass: "parallel-read",
417
+ concurrencyClass: "exclusive",
424
418
  gatedByDefault: true,
425
419
  allowedInExplore: false,
426
420
  allowedInAutonomous: false,
@@ -575,6 +569,23 @@ export const NETWORK_READ_TOOL_NAMES: ReadonlySet<string> = new Set(
575
569
  ),
576
570
  )
577
571
 
572
+ /**
573
+ * Derivasi Tool Access Policy: tool ekstra yang diizinkan pada ceiling PLAN
574
+ * (di atas 18 `READONLY_TOOL_NAMES`). Tiga artefak perencanaan yang aman:
575
+ * - `todo_write` → artefak rencana `.minicode/plans` (bukan file workspace)
576
+ * - `delegate_task` → penelahan rencana (dipaksa explore/read-only di task.ts
577
+ * bila parent PLAN — permission hanya membuka gerbangnya)
578
+ * - `submit_result` → singleton memori-proses (exec --json) tanpa tulis file
579
+ *
580
+ * Satu sumber untuk ceiling WorkMode PLAN (`work-mode.ts`), visibilitas tool
581
+ * (`tool-layer.ts`), dan handler PermissionMode `plan` warisan (`permission.ts`).
582
+ */
583
+ export const PLAN_EXTRA_TOOL_NAMES: ReadonlySet<string> = new Set([
584
+ "todo_write",
585
+ "delegate_task",
586
+ "submit_result",
587
+ ])
588
+
578
589
  /**
579
590
  * Derivasi klasifikasi jurnal. Tool tak dikenal = "unknown", dan pemanggil
580
591
  * (`isMutationTool`) memperlakukannya sebagai mutasi (fail-closed).
@@ -3,7 +3,8 @@
3
3
  // Hormat offline: gagal fetch = diam. Hormat NO_UPDATE_CHECK=1 / CI=1.
4
4
 
5
5
  import { spawnSync } from "node:child_process"
6
- import { homedir } from "node:os"
6
+ import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"
7
+ import { homedir, tmpdir } from "node:os"
7
8
  import { join } from "node:path"
8
9
 
9
10
  const PKG_NAME = "minicode-ai"
@@ -175,14 +176,38 @@ export async function checkForUpdateFresh(
175
176
  return isNewer(currentVersion, eff) ? eff : null
176
177
  }
177
178
 
178
- export type InstallRunner = (cmd: string, args: string[]) => { status: number | null }
179
+ export type InstallRunner = (
180
+ cmd: string,
181
+ args: string[],
182
+ opts?: { cwd?: string },
183
+ ) => { status: number | null }
179
184
 
180
- /** Install versi latest via npm global. Return true bila exit 0. Tak melempar. */
181
- export function installUpdate(runner?: InstallRunner): boolean {
185
+ const NPM_REGISTRY = "https://registry.npmjs.org/"
186
+
187
+ export function verifyInstalledVersion(expected: string, readVersion: () => string): boolean {
188
+ try {
189
+ return readVersion() === expected
190
+ } catch {
191
+ return false
192
+ }
193
+ }
194
+
195
+ const SEMVER_VERSION_RE =
196
+ /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-((?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*)(?:\.(?:0|[1-9]\d*|\d*[A-Za-z-][0-9A-Za-z-]*))*))?(?:\+([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?$/
197
+
198
+ /**
199
+ * Verifikasi versi dari registry (signature + provenance) di prefix sementara,
200
+ * lalu pasang versi persis dari registry yang sama secara global. Skrip paket
201
+ * tidak dijalankan. Npm lama atau paket tanpa bukti registry tepercaya = gagal
202
+ * tertutup; pemanggil tetap melanjutkan versi yang sedang berjalan.
203
+ */
204
+ export function installUpdate(version: string, runner?: InstallRunner): boolean {
205
+ if (version.length > 128 || !SEMVER_VERSION_RE.test(version)) return false
206
+ let verifyRoot: string | undefined
182
207
  try {
183
208
  const run: InstallRunner =
184
209
  runner ??
185
- ((cmd, args) => {
210
+ ((cmd, args, opts) => {
186
211
  // Windows: npm adalah .cmd → butuh shell; stdio inherit agar user
187
212
  // melihat progres install (interaktif, bukan CI).
188
213
  // Timeout 120 dtk: tanpa ini spawnSync memblokir event-loop selamanya
@@ -192,12 +217,64 @@ export function installUpdate(runner?: InstallRunner): boolean {
192
217
  const r = spawnSync(cmd, args, {
193
218
  stdio: "inherit",
194
219
  shell: process.platform === "win32",
220
+ ...(opts?.cwd ? { cwd: opts.cwd } : {}),
195
221
  timeout: 120_000,
196
222
  })
197
223
  return { status: typeof r.status === "number" ? r.status : null }
198
224
  })
199
- return run("npm", ["install", "-g", `${PKG_NAME}@latest`]).status === 0
225
+ verifyRoot = mkdtempSync(join(tmpdir(), "minicode-update-verify-"))
226
+ writeFileSync(
227
+ join(verifyRoot, "package.json"),
228
+ JSON.stringify({ name: "minicode-update-verification", version: "1.0.0", private: true }),
229
+ "utf8",
230
+ )
231
+ const verifiedInstall = run(
232
+ "npm",
233
+ [
234
+ "install",
235
+ "--ignore-scripts",
236
+ "--no-audit",
237
+ "--save-exact",
238
+ "--package-lock=true",
239
+ "--registry",
240
+ NPM_REGISTRY,
241
+ `${PKG_NAME}@${version}`,
242
+ ],
243
+ { cwd: verifyRoot },
244
+ )
245
+ if (verifiedInstall.status !== 0) return false
246
+ const lock = JSON.parse(readFileSync(join(verifyRoot, "package-lock.json"), "utf8")) as {
247
+ packages?: Record<string, unknown>
248
+ }
249
+ const installedPackages = Object.keys(lock.packages ?? {}).filter((path) =>
250
+ path.startsWith("node_modules/"),
251
+ )
252
+ // Global npm install does not consume this local lockfile. Today this CLI
253
+ // has no runtime dependencies; refuse silent graph drift until updater can
254
+ // install and verify every locked dependency identically.
255
+ if (installedPackages.length !== 1 || installedPackages[0] !== `node_modules/${PKG_NAME}`)
256
+ return false
257
+ const signatures = run("npm", ["audit", "signatures", "--registry", NPM_REGISTRY], {
258
+ cwd: verifyRoot,
259
+ })
260
+ if (signatures.status !== 0) return false
261
+ return (
262
+ run("npm", [
263
+ "install",
264
+ "-g",
265
+ "--ignore-scripts",
266
+ "--registry",
267
+ NPM_REGISTRY,
268
+ `${PKG_NAME}@${version}`,
269
+ ]).status === 0
270
+ )
200
271
  } catch {
201
272
  return false
273
+ } finally {
274
+ if (verifyRoot && existsSync(verifyRoot)) {
275
+ try {
276
+ rmSync(verifyRoot, { recursive: true, force: true })
277
+ } catch {}
278
+ }
202
279
  }
203
280
  }