minicode-ai 0.26.0 → 0.28.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 (139) hide show
  1. package/cli/args.ts +120 -16
  2. package/cli/commands/acp.ts +38 -28
  3. package/cli/commands/auth.ts +17 -17
  4. package/cli/commands/config.ts +65 -66
  5. package/cli/commands/daemon.ts +44 -16
  6. package/cli/commands/doctor.ts +11 -12
  7. package/cli/commands/exec.ts +35 -73
  8. package/cli/commands/mcp.ts +25 -8
  9. package/cli/commands/memory.ts +16 -24
  10. package/cli/commands/openwork.ts +6 -2
  11. package/cli/commands/pricing.ts +14 -12
  12. package/cli/commands/providers.ts +36 -57
  13. package/cli/commands/sessions.ts +24 -18
  14. package/cli/commands/skills.ts +33 -18
  15. package/cli/commands/stats.ts +15 -30
  16. package/cli/commands.ts +96 -46
  17. package/cli/context-command-run.ts +171 -0
  18. package/cli/context-command.ts +87 -0
  19. package/cli/index.ts +96 -98
  20. package/cli/model-manager.ts +7 -2
  21. package/cli/provider-manager.ts +33 -18
  22. package/cli/router.ts +41 -12
  23. package/cli/setup.ts +246 -123
  24. package/cli/tui.ts +311 -109
  25. package/docs/TERMINAL_CONTRACT.md +254 -69
  26. package/docs/UI_RENDER_PIPELINE.md +9 -1
  27. package/docs/agents.md +2 -2
  28. package/docs/architecture.md +3 -3
  29. package/docs/choosing-mode.md +7 -9
  30. package/docs/cli.md +3 -5
  31. package/docs/config.md +16 -0
  32. package/docs/environment.md +3 -3
  33. package/docs/policy-sandbox.md +3 -3
  34. package/docs/repl.md +3 -2
  35. package/docs/tools.md +1 -1
  36. package/package.json +1 -1
  37. package/src/app/mentions.ts +60 -13
  38. package/src/app/rag-layer.ts +17 -20
  39. package/src/app/session.ts +119 -66
  40. package/src/app/tool-layer.ts +12 -17
  41. package/src/config.ts +64 -104
  42. package/src/constants.ts +23 -9
  43. package/src/daemon/capability.ts +8 -1
  44. package/src/daemon/control.ts +3 -2
  45. package/src/daemon/server.ts +57 -0
  46. package/src/hooks/run.ts +73 -41
  47. package/src/lib/db-path.ts +47 -0
  48. package/src/lib/process-tree.ts +62 -0
  49. package/src/lib/public-http.ts +88 -23
  50. package/src/lib/trusted-exec.ts +48 -1
  51. package/src/lsp/client.ts +62 -17
  52. package/src/mcp/client.ts +85 -38
  53. package/src/mcp/http-transport.ts +28 -16
  54. package/src/mcp/transport.ts +42 -6
  55. package/src/memory/files.ts +164 -134
  56. package/src/memory/vector.ts +371 -420
  57. package/src/policy/approval-binding.ts +122 -45
  58. package/src/policy/bash-guard.ts +18 -7
  59. package/src/policy/compaction.ts +51 -18
  60. package/src/policy/context-window.ts +109 -0
  61. package/src/policy/context.ts +78 -37
  62. package/src/policy/executor.ts +17 -7
  63. package/src/policy/microcompact.ts +4 -3
  64. package/src/policy/no-progress.ts +103 -22
  65. package/src/policy/permission.ts +36 -12
  66. package/src/policy/tool-contract.ts +74 -416
  67. package/src/policy/usage.ts +24 -2
  68. package/src/policy/verifier.ts +50 -2
  69. package/src/policy/work-mode.ts +28 -54
  70. package/src/presentation/adapter.ts +24 -16
  71. package/src/providers/guards.ts +41 -2
  72. package/src/providers/provision.ts +6 -60
  73. package/src/providers/responses.ts +1 -0
  74. package/src/repo/repomap.ts +180 -23
  75. package/src/runtime/execution-journal.ts +4 -29
  76. package/src/sandbox/docker.ts +58 -34
  77. package/src/sandbox/mask.ts +157 -0
  78. package/src/sandbox/os.ts +107 -73
  79. package/src/session/authority.ts +29 -10
  80. package/src/session/context-projection.ts +6 -5
  81. package/src/session/open-work.ts +26 -3
  82. package/src/session/persistence.ts +25 -58
  83. package/src/session/verification.ts +170 -20
  84. package/src/skills/loader.ts +31 -16
  85. package/src/task/production-scheduler.ts +13 -1
  86. package/src/task/store.ts +20 -37
  87. package/src/telemetry/trace.ts +27 -0
  88. package/src/tools/ask_user.ts +1 -13
  89. package/src/tools/bash.ts +27 -92
  90. package/src/tools/code_run.ts +1 -1
  91. package/src/tools/context.ts +133 -0
  92. package/src/tools/delete_file.ts +3 -2
  93. package/src/tools/edit.ts +37 -72
  94. package/src/tools/git.ts +86 -9
  95. package/src/tools/glob.ts +26 -51
  96. package/src/tools/grep.ts +67 -57
  97. package/src/tools/hashline.ts +4 -0
  98. package/src/tools/lsp.ts +11 -8
  99. package/src/tools/mcp_call.ts +9 -6
  100. package/src/tools/memory.ts +56 -33
  101. package/src/tools/move_file.ts +36 -10
  102. package/src/tools/patch.ts +13 -21
  103. package/src/tools/read_file.ts +18 -25
  104. package/src/tools/read_image.ts +35 -33
  105. package/src/tools/submit_result.ts +29 -8
  106. package/src/tools/task.ts +74 -17
  107. package/src/tools/todo.ts +181 -74
  108. package/src/tools/web_fetch.ts +42 -2
  109. package/src/tools/web_search.ts +47 -8
  110. package/src/ui/approval/prompt.ts +206 -47
  111. package/src/ui/assistant/turn-status.ts +14 -5
  112. package/src/ui/footer.ts +4 -4
  113. package/src/ui/i18n/en.ts +59 -23
  114. package/src/ui/i18n/id.ts +88 -51
  115. package/src/ui/input/input.ts +4 -3
  116. package/src/ui/input/prompt-engine.ts +35 -5
  117. package/src/ui/render/activity-panel.ts +4 -2
  118. package/src/ui/render/hint.ts +7 -4
  119. package/src/ui/render/list.ts +32 -0
  120. package/src/ui/render/markdown.ts +6 -3
  121. package/src/ui/render/notice.ts +19 -0
  122. package/src/ui/render/table-grid.ts +7 -8
  123. package/src/ui/render/theme.ts +113 -39
  124. package/src/ui/runtime/screen.ts +74 -10
  125. package/src/ui/runtime/spinner.ts +19 -6
  126. package/src/ui/screens/dialog.ts +19 -1
  127. package/src/ui/screens/form.ts +80 -35
  128. package/src/ui/screens/model-manager.ts +88 -62
  129. package/src/ui/screens/output-window.ts +263 -0
  130. package/src/ui/screens/picker.ts +94 -81
  131. package/src/ui/screens/provider-manager.ts +100 -69
  132. package/src/ui/screens/wizard.ts +117 -28
  133. package/src/ui/tui/app.ts +196 -33
  134. package/src/ui/tui/transcript.ts +154 -25
  135. package/vendor/minicore/src/core/executor.ts +2 -0
  136. package/vendor/minicore/src/core/loop.ts +17 -6
  137. package/vendor/minicore/src/core/session.ts +3 -0
  138. package/vendor/minicore/src/core/tool.ts +1 -0
  139. package/vendor/minicore/src/providers/openai-compat.ts +28 -19
@@ -1,43 +1,31 @@
1
- // [Area B · PROMPT 06] Pengikatan persetujuan ↔ operasi yang BENAR-BENAR
2
- // dieksekusi.
3
- //
4
- // Masalah yang ditutup: `edit`/`apply_patch` MEMBACA ULANG file saat eksekusi,
5
- // sementara preview yang dilihat user berasal dari state SAAT approval. Bila
6
- // file berubah di antara keduanya (proses lain, tool paralel, sub-agent),
7
- // operasi yang dijalankan bukan yang disetujui — persetujuan jadi basi.
8
- //
9
- // Mekanisme (dua titik, satu objek state):
10
- // · CAPTURE (sebelum prompt): sidik jari argumen (SHA-256 kanonis) + isi file
11
- // target — "apa yang dilihat user".
12
- // · GRANT (setelah user setuju): simpan sidik jari itu untuk operasi ini saja.
13
- // · VERIFY (batas eksekusi): hitung ulang; beda ⇒ basi ⇒ TOLAK (fail-closed).
14
- //
15
- // Kenapa verifikasi di barrier efek (`src/app/session.ts` `beforeToolEffect`):
16
- // antara `permissions.check()` dan `tool.execute` kernel hanya menjalankan
17
- // langkah sinkron, TAPI aplikasi menambah await (intent jurnal + no-progress)
18
- // di dalam handler. Barrier adalah titik terakhir sesudah semua await itu dan
19
- // sebelum "allow" kembali ke kernel — efektif batas eksekusi, tanpa membungkus
20
- // tool (yang merusak identitas array tool live milik WorkMode).
21
- //
22
- // Lapis pertama diverifikasi SAAT user menyetujui supaya persetujuan basi
23
- // ditolak sebelum intent jurnal ditulis.
24
- //
25
- // Batas jujur: efek `bash` tak bisa difingerprint — yang terikat hanya
26
- // argumennya. Pada `always`/allowlist tak ada prompt ⇒ tak ada grant yang bisa
27
- // diverifikasi untuk call berikutnya; grant tetap dibuat untuk call berjalan.
1
+ // [Area B · PROMPT 06] Pengikatan persetujuan ↔ operasi yang dieksekusi.
2
+ // CAPTURE (sebelum prompt): hash argumen kanonis + isi target (anti-symlink) / state git.
3
+ // GRANT (setelah setuju): simpan per operasi (callId/FIFO).
4
+ // VERIFY (barrier efek sebelum & sesudah await): hitung ulang; beda ⇒ basi ⇒ TOLAK.
28
5
 
6
+ import { spawnSync } from "node:child_process"
29
7
  import { createHash } from "node:crypto"
30
- import { readFileSync, statSync } from "node:fs"
8
+ import {
9
+ closeSync,
10
+ constants,
11
+ fstatSync,
12
+ lstatSync,
13
+ openSync,
14
+ readFileSync,
15
+ readlinkSync,
16
+ } from "node:fs"
31
17
  import { resolve } from "node:path"
18
+ import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
32
19
  import { canonicalArgsHash } from "./no-progress.ts"
33
20
 
34
21
  /** Tool yang TARGET-nya file di workspace — satu-satunya yang bisa di-fingerprint. */
35
22
  const FILE_TARGET_TOOLS = new Set(["write_file", "edit", "apply_patch", "delete_file", "move_file"])
23
+ const GIT_STATE_TOOLS = new Set(["git_commit", "git_push"])
36
24
 
37
25
  /**
38
26
  * Batas fingerprint KONTEN. File lebih besar dari ini di-fingerprint lewat
39
- * size+mtime (bukan hash isi): approval untuk file raksasa tetap bisa
40
- * dideteksi berubah, tanpa membaca ratusan MB dua kali per prompt.
27
+ * size+mtime+ctime+ino: approval untuk file raksasa tetap bisa dideteksi
28
+ * berubah, tanpa membaca ratusan MB dua kali per prompt.
41
29
  */
42
30
  export const MAX_CONTENT_FINGERPRINT_BYTES = 2 * 1024 * 1024
43
31
 
@@ -50,18 +38,28 @@ export const NOT_A_FILE = "not-a-file"
50
38
  export interface ApprovalTarget {
51
39
  /** Path absolut target. */
52
40
  readonly path: string
53
- /** Hash isi (file kecil) / size+mtime (file besar) / MISSING_TARGET. */
41
+ /** Hash isi (file kecil) / size+mtime / symlink / MISSING_TARGET. */
54
42
  readonly fingerprint: string
55
43
  }
56
44
 
45
+ /** Sidik jari state repo git untuk tool commit/push yang disetujui. */
46
+ export interface ApprovalGitState {
47
+ readonly cwd: string
48
+ readonly digest: string
49
+ }
50
+
57
51
  /** Bukti persetujuan untuk SATU operasi. */
58
52
  export interface ApprovalBinding {
53
+ /** ID tool call paralel agar konsumsi binding tak tertukar FIFO. */
54
+ readonly callId?: string
59
55
  /** Nama tool yang disetujui. */
60
56
  readonly tool: string
61
57
  /** SHA-256 argumen kanonis (identik dengan `hashArgs`/`canonicalArgsHash`). */
62
58
  readonly argsHash: string
63
59
  /** Target file yang jadi bukti (kosong untuk tool tanpa target file). */
64
60
  readonly targets: readonly ApprovalTarget[]
61
+ /** State git HEAD + working tree saat prompt untuk tool git tulis/push. */
62
+ readonly gitState?: ApprovalGitState
65
63
  }
66
64
 
67
65
  /**
@@ -83,18 +81,65 @@ export function approvalTargetPaths(tool: string, args: unknown, root: string):
83
81
  return p ? [resolve(root, p)] : []
84
82
  }
85
83
 
86
- /** Sidik jari target saat ini (hash isi / size+mtime / marker). */
84
+ /**
85
+ * Sidik jari target saat ini (anti-symlink: pakai lstat + O_NOFOLLOW + fstat
86
+ * agar swap symlink/file di antara check dan baca tidak diikuti diam-diam).
87
+ */
87
88
  export function fingerprintTarget(path: string): string {
89
+ let lst: ReturnType<typeof lstatSync>
88
90
  try {
89
- const st = statSync(path)
90
- if (!st.isFile()) return NOT_A_FILE
91
- if (st.size > MAX_CONTENT_FINGERPRINT_BYTES)
92
- return `size:${st.size}:mtime:${Math.trunc(st.mtimeMs)}`
93
- return createHash("sha256").update(readFileSync(path)).digest("hex")
91
+ lst = lstatSync(path)
94
92
  } catch {
95
- // Tidak ada / tak bisa dibaca = "missing" (bukan hash kosong).
96
93
  return MISSING_TARGET
97
94
  }
95
+ if (lst.isSymbolicLink()) {
96
+ try {
97
+ return `symlink:${readlinkSync(path)}`
98
+ } catch {
99
+ return NOT_A_FILE
100
+ }
101
+ }
102
+ if (!lst.isFile()) return NOT_A_FILE
103
+ const flags = constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0)
104
+ let fd: number | undefined
105
+ try {
106
+ fd = openSync(path, flags)
107
+ const fst = fstatSync(fd)
108
+ if (!fst.isFile()) return NOT_A_FILE
109
+ if (fst.size > MAX_CONTENT_FINGERPRINT_BYTES) {
110
+ return `size:${fst.size}:mtime:${fst.mtimeMs}:ctime:${fst.ctimeMs}:ino:${fst.ino}`
111
+ }
112
+ return createHash("sha256").update(readFileSync(fd)).digest("hex")
113
+ } catch {
114
+ return MISSING_TARGET
115
+ } finally {
116
+ if (fd !== undefined) {
117
+ try {
118
+ closeSync(fd)
119
+ } catch {}
120
+ }
121
+ }
122
+ }
123
+
124
+ function captureGitDigest(cwd: string): string | null {
125
+ try {
126
+ const git = resolveTrustedExecutable("git")
127
+ const head = spawnSync(git, ["-c", "safe.directory=*", "rev-parse", "HEAD"], {
128
+ cwd,
129
+ encoding: "utf8",
130
+ timeout: 2_000,
131
+ })
132
+ const status = spawnSync(git, ["-c", "safe.directory=*", "status", "--porcelain"], {
133
+ cwd,
134
+ encoding: "utf8",
135
+ timeout: 2_000,
136
+ })
137
+ if (status.status !== 0) return null
138
+ const headOut = head.status === 0 ? head.stdout.trim() : "UNBORN"
139
+ return createHash("sha256").update(`${headOut}\0${status.stdout}`).digest("hex")
140
+ } catch {
141
+ return null
142
+ }
98
143
  }
99
144
 
100
145
  /**
@@ -105,14 +150,28 @@ export function fingerprintTarget(path: string): string {
105
150
  * lama (user berpikir), dan kalau sidik jari diambil SETELAH prompt kita
106
151
  * memverifikasi state yang tidak pernah dilihat user.
107
152
  */
108
- export function captureApprovalBinding(tool: string, args: unknown, root: string): ApprovalBinding {
153
+ export function captureApprovalBinding(
154
+ tool: string,
155
+ args: unknown,
156
+ root: string,
157
+ callId?: string,
158
+ ): ApprovalBinding {
159
+ let gitState: ApprovalGitState | undefined
160
+ if (GIT_STATE_TOOLS.has(tool)) {
161
+ const a = (args ?? {}) as Record<string, unknown>
162
+ const gitCwd = typeof a.cwd === "string" && a.cwd.trim() ? resolve(root, a.cwd) : root
163
+ const digest = captureGitDigest(gitCwd)
164
+ if (digest !== null) gitState = { cwd: gitCwd, digest }
165
+ }
109
166
  return {
167
+ ...(callId ? { callId } : {}),
110
168
  tool,
111
169
  argsHash: canonicalArgsHash(args),
112
170
  targets: approvalTargetPaths(tool, args, root).map((path) => ({
113
171
  path,
114
172
  fingerprint: fingerprintTarget(path),
115
173
  })),
174
+ ...(gitState ? { gitState } : {}),
116
175
  }
117
176
  }
118
177
 
@@ -134,7 +193,6 @@ export type BindingVerdict =
134
193
  */
135
194
  export function verifyApprovalBinding(binding: ApprovalBinding | undefined): BindingVerdict {
136
195
  if (!binding) return { kind: "no-binding" }
137
- if (binding.targets.length === 0) return { kind: "ok" }
138
196
  for (const t of binding.targets) {
139
197
  const now = fingerprintTarget(t.path)
140
198
  if (now === t.fingerprint) continue
@@ -146,6 +204,15 @@ export function verifyApprovalBinding(binding: ApprovalBinding | undefined): Bin
146
204
  : `target ${t.path} berubah sejak approval — approval basi, minta ulang`,
147
205
  }
148
206
  }
207
+ if (binding.gitState) {
208
+ const nowDigest = captureGitDigest(binding.gitState.cwd)
209
+ if (nowDigest !== binding.gitState.digest) {
210
+ return {
211
+ kind: "stale",
212
+ reason: `state git di ${binding.gitState.cwd} berubah sejak approval — approval basi, minta ulang`,
213
+ }
214
+ }
215
+ }
149
216
  return { kind: "ok" }
150
217
  }
151
218
 
@@ -157,7 +224,7 @@ export function verifyApprovalBinding(binding: ApprovalBinding | undefined): Bin
157
224
  */
158
225
  export class ApprovalBindingStore {
159
226
  readonly root: string
160
- /** Antre per (tool, argsHash) — FIFO agar urut grant = urut eksekusi. */
227
+ /** Antre per (tool, argsHash) — cocokkan callId bila ada, FIFO jika tidak. */
161
228
  readonly #pending = new Map<string, ApprovalBinding[]>()
162
229
 
163
230
  constructor(root: string) {
@@ -176,14 +243,24 @@ export class ApprovalBindingStore {
176
243
  else this.#pending.set(k, [binding])
177
244
  }
178
245
 
179
- /** Ambil satu binding untuk (tool, argsHash) — consume-once. */
180
- take(tool: string, argsHash: string): ApprovalBinding | undefined {
246
+ /** Ambil satu binding untuk (tool, argsHash, callId?) — consume-once. */
247
+ take(tool: string, argsHash: string, callId?: string): ApprovalBinding | undefined {
181
248
  const k = ApprovalBindingStore.key(tool, argsHash)
182
249
  const arr = this.#pending.get(k)
183
250
  if (!arr || arr.length === 0) return undefined
184
- const first = arr.shift()!
251
+ let idx = 0
252
+ if (callId) {
253
+ const exactIdx = arr.findIndex((b) => b.callId === callId)
254
+ if (exactIdx !== -1) idx = exactIdx
255
+ else {
256
+ const legacyIdx = arr.findIndex((b) => b.callId === undefined)
257
+ if (legacyIdx === -1) return undefined
258
+ idx = legacyIdx
259
+ }
260
+ }
261
+ const [picked] = arr.splice(idx, 1)
185
262
  if (arr.length === 0) this.#pending.delete(k)
186
- return first
263
+ return picked
187
264
  }
188
265
 
189
266
  /** Jumlah binding yang masih tertunda (diagnostik/test). */
@@ -239,7 +239,7 @@ export function decodeAnsiCQuotes(cmd: string): string {
239
239
 
240
240
  export function stripCommandWrappers(cmd: string): string {
241
241
  const WRAPPER =
242
- /(^|[;&|]\s*)(?:command|exec|builtin|eval|nice(?:\s+-n\s*-?\d+)?|nohup|time|timeout\s+[\d.]+[smhd]?|stdbuf(?:\s+-\S+)*|env(?=\s+[A-Za-z_][A-Za-z0-9_]*=)|setsid|ionice(?:\s+-\S+)*|xargs(?:\s+-\S+)*|sudo(?:\s+-\S+)*|doas)\s+/gi
242
+ /(^|[;&|\n]\s*)(?:command|exec|builtin|eval|nice(?:\s+-n\s*-?\d+)?|nohup|time|timeout\s+[\d.]+[smhd]?|stdbuf(?:\s+-\S+)*|env(?=\s+[A-Za-z_][A-Za-z0-9_]*=)|setsid|ionice(?:\s+-\S+)*|xargs(?:\s+-\S+)*|sudo(?:\s+-\S+)*|doas)\s+/gi
243
243
  // Wrapper privilese/konteks (audit 2026-09-16 B2): `su -c 'env'`,
244
244
  // `runuser -u x -- printenv`, `cmd /c set` menyembunyikan perintah
245
245
  // sebenarnya dari aturan konten yang ter-anchor ke awal (ENV_DUMP dkk).
@@ -248,7 +248,7 @@ export function stripCommandWrappers(cmd: string): string {
248
248
  // 'cat /etc/shadow'` tetap kena SENSITIVE_TARGET. Jangkar awal mencegah
249
249
  // strip di tengah perintah (`echo su -c env` tak tersentuh).
250
250
  const WRAPPER_SHELL =
251
- /(^|[;&|]\s*)(?:(?:su|runuser|gosu|chroot|nsenter)(?:\s+(?:-[^\s;|]+|--[^\s;|]*|\/[^\s;|]*|[^-;\s|/][^;\s|]*))*\s+|cmd(?:\.exe)?(?:\s+\/[a-zA-Z]+)*\s+\/c\s+|powershell(?:\.exe)?(?:\s+-(?:Command|c|EncodedCommand|enc|ec))?\s+|pwsh(?:\.exe)?(?:\s+-(?:Command|c|EncodedCommand|enc|ec))?\s+)/gi
251
+ /(^|[;&|\n]\s*)(?:(?:su|runuser|gosu|chroot|nsenter)(?:\s+(?:-[^\s;|]+|--[^\s;|]*|\/[^\s;|]*|[^-;\s|/][^;\s|]*))*\s+|cmd(?:\.exe)?(?:\s+\/[a-zA-Z]+)*\s+\/c\s+|powershell(?:\.exe)?(?:\s+-(?:Command|c|EncodedCommand|enc|ec))?\s+|pwsh(?:\.exe)?(?:\s+-(?:Command|c|EncodedCommand|enc|ec))?\s+)/gi
252
252
  let out = cmd
253
253
  for (let pass = 0; pass < 4; pass++) {
254
254
  const next = out.replace(WRAPPER, "$1").replace(WRAPPER_SHELL, "$1")
@@ -408,7 +408,7 @@ const ENV_SECRET_REF =
408
408
 
409
409
  /** Flag upload berkas pada klien HTTP — jalur exfiltrasi paling langsung. */
410
410
  const UPLOAD_FLAG =
411
- /\b(?:curl|wget|http|httpie|nc|ncat|socat)\b[^\n]*(?:-F\s*\S*=@|--form\s*\S*=@|-d\s*@|--data(?:-binary|-raw)?\s*@|-T\s+|--upload-file|--post-file=|-b\s*@)/i
411
+ /\b(?:curl|wget|http|httpie|nc|ncat|socat)\b[^\n]*(?:-F\s*\S*=@|--form\s*\S*=@|(?:-d|--data(?:-binary|-raw|-ascii)?)(?:\s*=\s*|\s*)@|(?:-T|--upload-file|--post-file)(?:=|\s+)|-T[./~]|-b\s*@)/i
412
412
 
413
413
  /** Upload DATA dari variabel bare (`-d $X`, bukan `@file` yang sudah ditahan
414
414
  * UPLOAD_FLAG): bentuk exfiltrasi terakhir yang lolos — nama var arbitrer
@@ -446,7 +446,7 @@ const GIT_EXEC_ENV = /(?:^|[;&|\n]\s*)GIT_(?:PAGER|SSH|ASKPASS|EDITOR|DIR|WORK_T
446
446
  * memperluas allowlist ke bahasa baru membuka jalur kode-inline pada bahasa itu.
447
447
  */
448
448
  const INLINE_INTERPRETER =
449
- /\b(?:pyw?|python[\d.]*|pypy[\d.]*|sh|bash|dash|zsh|ksh|node|deno|bun|perl|ruby|php|Rscript|lua|luajit|julia|elixir|escript|erl|groovy|scala|tclsh|dotnet|swift|swiftc|dart|java|raku)(?:\.exe)?\b\s+(?:-\w*\s+)*(?:-c|-e|-E|--eval|-eval|--print|-p|--command|-r|--execute|--require|--import|--loader)\b/i
449
+ /(?:^|[;&|\n(\s/\\])(?:pyw?|python[\d.]*|pypy[\d.]*|sh|bash|dash|zsh|ksh|node|deno|bun|perl|ruby|php|Rscript|lua|luajit|julia|elixir|escript|erl|groovy|scala|tclsh|dotnet|swift|swiftc|dart|java|raku)(?:\.exe)?\b\s+(?:--[A-Za-z0-9_-]+(?:=[^\s;&|]+)?\s+|-(?:W|X|I|M)\s+[^\s;&|]+\s+|-[A-Za-z0-9]+\s+){0,8}(?:-c|-e|-E|--eval|-eval|--print|-p|--command|-r|--execute|--require|--import|--loader)\b/i
450
450
  // Residual jujur (audit 2026-09-16 B3): eksekusi via stdin/redirect TANPA
451
451
  // flag inline (`bash -s < skrip`, `python3 < prog`, `... | python3 -`) tidak
452
452
  // ditahan — menahan `| python3 -` mematahkan pipeline sah, dan `bash berkas`
@@ -621,7 +621,10 @@ const STATIC_DENY: [RegExp, string][] = [
621
621
  /\b(?:powershell|pwsh)(\.exe)?\b[^\n]*\s-e\w*\s+[A-Za-z0-9+/]{60,}={0,2}/i,
622
622
  "encoded powershell payload",
623
623
  ],
624
- [/>\s*\/dev\/(?:sda|nvme|hd[a-z])/i, "raw device write"],
624
+ [
625
+ />\s*\/dev\/(?:sd[a-z]\d*|nvme\d+n\d+(?:p\d+)?|hd[a-z]\d*|vd[a-z]\d*|xvd[a-z]\d*|mmcblk\d+(?:p\d+)?|disk\d+(?:s\d+)?)/i,
626
+ "raw device write",
627
+ ],
625
628
  [/\b(?:del|erase)\b[^\n]*\/[sfaq]/i, "windows recursive delete"],
626
629
  [/\brmdir\b[^\n]*\/s/i, "windows recursive rmdir"],
627
630
  [/\bRemove-Item\b[^\n]*-Recurse/i, "powershell recursive delete"],
@@ -907,12 +910,20 @@ export function inspectBashCommand(rawCmd: string, cwd?: string): BashVerdict {
907
910
  const readerTargets = (() => {
908
911
  const out: string[] = []
909
912
  const re =
910
- /\b(?:cat|bat|less|more|head|tail|nl|od|xxd|strings|type|Get-Content|gc|certutil|tac|findstr|fc|comp|cp|copy|mv|move|scp|rsync|tar|zip|gzip|base64|openssl|awk|sed|grep|egrep|fgrep|rg|cut|sort|uniq|tee|dd|install|xcopy|robocopy|Out-File|Set-Content|Add-Content|New-Item|Copy-Item|Move-Item)\b\s+([^\n;&|]+)/gi
913
+ /\b(cat|bat|less|more|head|tail|nl|od|xxd|strings|type|Get-Content|gc|certutil|tac|findstr|fc|comp|cp|copy|mv|move|scp|rsync|tar|zip|gzip|base64|openssl|awk|sed|grep|egrep|fgrep|rg|cut|sort|uniq|tee|dd|install|xcopy|robocopy|Out-File|Set-Content|Add-Content|New-Item|Copy-Item|Move-Item)\b\s+([^\n;&|]+)/gi
914
+ const WIN_SWITCH_CMDS = /^(?:findstr|fc|comp|copy|xcopy|robocopy|sort)$/i
911
915
  for (const m of norm.matchAll(re)) {
912
- const args = m[1]!.split(/\s+/)
916
+ const cmdName = m[1]!
917
+ const isWinSwitchCmd = process.platform === "win32" || WIN_SWITCH_CMDS.test(cmdName)
918
+ const args = m[2]!.split(/\s+/)
913
919
  for (const a of args) {
914
920
  if (!a) continue
915
921
  if (a.startsWith("-")) continue
922
+ // Flag cmd.exe Windows berawalan `/` (mis. `findstr /n /c:err log.txt`,
923
+ // `copy /y`, `fc /b`) bukan path root POSIX — lewati agar tidak ditolak
924
+ // sebagai `outside workspace`, sambil tetap menjaga `/etc/...` atau `/f:...`.
925
+ if (isWinSwitchCmd && /^\/[a-zA-Z]{1,2}$/.test(a)) continue
926
+ if (/^findstr$/i.test(cmdName) && /^\/c:/i.test(a)) continue
916
927
  const t = a.trim()
917
928
  if (!t) continue
918
929
  out.push(t)
@@ -7,6 +7,7 @@ import { createOpenAICompatProvider } from "#minicore/providers/openai-compat.ts
7
7
  import { LIMITS } from "../constants.ts"
8
8
  import { isPrivateHostWithDns } from "../lib/net.ts"
9
9
  import { minicodeEstimator } from "./context.ts"
10
+ import { outputReserveFor } from "./context-budget.ts"
10
11
  import { applyMicrocompact } from "./microcompact.ts"
11
12
  import { planRecovery, type RecoveryState } from "./recovery-budget.ts"
12
13
 
@@ -106,6 +107,8 @@ const FACT_TOOLS = new Set([
106
107
  "code_run",
107
108
  "web_fetch",
108
109
  "web_search",
110
+ "todo_write",
111
+ "todo_read",
109
112
  ])
110
113
  const FACT_HEAD_CHARS = 800
111
114
 
@@ -117,7 +120,9 @@ function toolHeadLen(name: string | null | undefined, fallback: number): number
117
120
 
118
121
  export interface LlmCompactionOptions {
119
122
  provider?: ModelProvider
120
- model?: string // deepseek v4 flash
123
+ model?: string
124
+ /** Resolver live model aktif (mis. pasca `/model` di tengah sesi). */
125
+ getModel?: () => string | undefined // deepseek v4 flash
121
126
  baseUrl?: string
122
127
  apiKey?: string
123
128
  keepRecentTurns?: number
@@ -138,6 +143,8 @@ export interface LlmCompactionOptions {
138
143
  /** Live per-model limit used to keep the active message set below the
139
144
  * system/tool/output reserve before the kernel makes its admission check. */
140
145
  getContextWindowTokens?: () => number
146
+ /** Cegah persistensi auto-memory pada mode baca-saja (DISCUSS / readonly / plan). */
147
+ canPersistMemory?: () => boolean
141
148
  }
142
149
 
143
150
  const COMPACTION_ELISION =
@@ -314,8 +321,9 @@ function activeTurnProtected(messages: readonly import("#minicore/core/types.ts"
314
321
  break
315
322
  }
316
323
  }
324
+ const scanFrom = Math.max(0, latestUser)
317
325
  let pendingStart = messages.length
318
- for (let i = 0; i < messages.length; i++) {
326
+ for (let i = scanFrom; i < messages.length; i++) {
319
327
  const message = messages[i]!
320
328
  if (message.role !== "assistant" || !message.toolCalls?.length) continue
321
329
  const results = new Set(
@@ -564,12 +572,26 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
564
572
  mOpts: { budgetTokens?: number },
565
573
  ): readonly import("#minicore/core/types.ts").Message[] {
566
574
  if (!microcompactEnabled) return store.messages
575
+ // Skala penghematan minimum mengikuti budget jendela: konstanta keras 20k
576
+ // tak pernah tercapai pada model <=64k, memaksa kompaksi LLM penuh lebih awal.
577
+ const budget = mOpts.budgetTokens
578
+ const effBudget =
579
+ typeof budget === "number" && Number.isFinite(budget) && budget > 0
580
+ ? Math.max(1, budget - outputReserveFor(budget))
581
+ : budget
582
+ const minSavingTokens =
583
+ typeof effBudget === "number" && Number.isFinite(effBudget) && effBudget > 0
584
+ ? Math.min(
585
+ LIMITS.MICROCOMPACT_MIN_SAVING_TOKENS,
586
+ Math.max(1_000, Math.floor(effBudget * 0.12)),
587
+ )
588
+ : LIMITS.MICROCOMPACT_MIN_SAVING_TOKENS
567
589
  const result = applyMicrocompact(store.messages, {
568
590
  keepRecent: LIMITS.MICROCOMPACT_KEEP_RECENT,
569
- minSavingTokens: LIMITS.MICROCOMPACT_MIN_SAVING_TOKENS,
591
+ minSavingTokens,
570
592
  minToolShare: LIMITS.MICROCOMPACT_MIN_TOOL_SHARE,
571
593
  estimateTokens: (text) => minicodeEstimator(text),
572
- budgetTokens: mOpts.budgetTokens,
594
+ budgetTokens: effBudget,
573
595
  })
574
596
  return result.clearedCount > 0 ? result.messages : store.messages
575
597
  },
@@ -613,7 +635,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
613
635
  const attemptOpts = {
614
636
  keepRecentTurns: cOpts.keepRecentTurns,
615
637
  provider: opts.provider,
616
- model: opts.model,
638
+ model: opts.getModel?.() ?? opts.model,
617
639
  baseUrl: opts.baseUrl,
618
640
  apiKey: opts.apiKey,
619
641
  cwd: opts.cwd,
@@ -628,6 +650,7 @@ export function createLlmCompaction(opts: LlmCompactionOptions = {}): Compaction
628
650
  maxSummaryChars: summaryCharBudgetForWindow(opts.getContextWindowTokens?.()),
629
651
  maxInputChars: summaryInputCharBudget(opts.getContextWindowTokens?.()),
630
652
  ...(opts.onUsage ? { onUsage: opts.onUsage } : {}),
653
+ ...(opts.canPersistMemory ? { canPersistMemory: opts.canPersistMemory } : {}),
631
654
  }
632
655
  let out: readonly import("#minicore/core/types.ts").Message[] | undefined
633
656
  for (let round = 0; ; round++) {
@@ -866,6 +889,10 @@ export async function compactWithLlm(
866
889
  maxInputChars?: number
867
890
  provider?: ModelProvider
868
891
  model?: string
892
+ /** Resolver live model aktif (mis. pasca `/model` di tengah sesi). */
893
+ getModel?: () => string | undefined
894
+ /** Cegah persistensi auto-memory pada mode baca-saja (DISCUSS / readonly / plan). */
895
+ canPersistMemory?: () => boolean
869
896
  baseUrl?: string
870
897
  apiKey?: string
871
898
  cwd?: string
@@ -906,11 +933,14 @@ export async function compactWithLlm(
906
933
  const keptTail = activeTurn ? activeTurnProtected(messages) : messages.slice(-kept)
907
934
 
908
935
  const baseUrl = opts.baseUrl ?? "https://api.deepseek.com/v1"
909
- try {
910
- const hostname = new URL(baseUrl).hostname
911
- if (await isPrivateHostWithDns(hostname)) throw new Error(`private host rejected: ${hostname}`)
912
- } catch (e) {
913
- if (e instanceof Error && e.message.includes("private host")) throw e
936
+ if (!opts.provider && opts.apiKey) {
937
+ try {
938
+ const hostname = new URL(baseUrl).hostname
939
+ if (await isPrivateHostWithDns(hostname))
940
+ throw new Error(`private host rejected: ${hostname}`)
941
+ } catch (e) {
942
+ if (e instanceof Error && e.message.includes("private host")) throw e
943
+ }
914
944
  }
915
945
  const provider =
916
946
  opts.provider ??
@@ -969,11 +999,14 @@ export async function compactWithLlm(
969
999
  const goalContext = continuity.length
970
1000
  ? `User goal and recent steering (chronological, excerpts):\n${continuity.join("\n")}\n\n`
971
1001
  : ""
972
- const scrubbedPrefix = scrubSecrets(
973
- (currentRequest + goalContext + prefix.map(lineFor).join("\n")).slice(
974
- 0,
975
- opts.maxInputChars ?? LIMITS.COMPACTION_LLM_INPUT_MIN_CHARS,
976
- ),
1002
+ const taskState = latestTaskState(all)
1003
+ const taskContext = taskState
1004
+ ? `Latest task list (verbatim):\n${safeHead(taskState, 1200)}\n\n`
1005
+ : ""
1006
+ const maxIn = opts.maxInputChars ?? LIMITS.COMPACTION_LLM_INPUT_MIN_CHARS
1007
+ const scrubbedPrefix = safeHead(
1008
+ scrubSecrets(currentRequest + taskContext + goalContext + prefix.map(lineFor).join("\n")),
1009
+ maxIn,
977
1010
  )
978
1011
  // Guard anti-injeksi (temuan audit #02): prefix berisi output tool/web/repo
979
1012
  // tak-terpercaya yang bisa memuat "abaikan instruksi". Tanpa pagar, payload
@@ -1072,9 +1105,9 @@ export async function compactWithLlm(
1072
1105
  )
1073
1106
  summaryEvidence.set(lruSummary, scrubSecrets(headWithMarker(summary, 1600)))
1074
1107
  // P13 S1 — persist summary ke vector (opt-out via MINICODE_AUTO_MEMORY=0).
1075
- // cwd diteruskan eksplisit: tanpa ini summary mendarat di DB global/sembarang
1076
- // tergantung process.cwd() saat compact jalan (temuan audit #02).
1077
- if (process.env.MINICODE_AUTO_MEMORY !== "0") {
1108
+ // Wajib membawa `opts.cwd` eksplisit agar kompaksi di library/test tanpa
1109
+ // workspace tidak mempolusi DB `process.cwd()`, serta menghormati mode baca-saja.
1110
+ if (process.env.MINICODE_AUTO_MEMORY !== "0" && opts.cwd && opts.canPersistMemory?.() !== false) {
1078
1111
  try {
1079
1112
  const { addMemory } = await import("../memory/vector.ts")
1080
1113
  // fire-and-forget, jangan gagalkan compaction bila embedding gagal.
@@ -113,6 +113,105 @@ export function findContextWindowFromOverlay(model: string): number | undefined
113
113
  return best?.v
114
114
  }
115
115
 
116
+ /**
117
+ * Nilai jendela yang ditulis operator SELAMA proses berjalan (in-process
118
+ * registry di bawah). Dipisah dari `config` karena `cli/setup.ts` menangkap
119
+ * config sekali di awal; tanpa lapis ini setiap setelan baru butuh restart.
120
+ */
121
+ const liveUserWindows = new Map<string, number>()
122
+ /**
123
+ * Pasangan yang operator-nya MEMILIH `auto`. Nilai `null` sengaja dipakai
124
+ * sebagai penanda, bukan penghapusan entri: config snapshot muat menahan angka
125
+ * lama (dibaca saat start), jadi menghapus entri live saja membuat angka basi
126
+ * itu muncul kembali — `auto` lalu tampak "balik ke nilai lama" alih-alih ke
127
+ * deteksi otomatis.
128
+ */
129
+ const liveAutoClears = new Set<string>()
130
+
131
+ /** Catat pilihan operator untuk sesi yang sedang berjalan. */
132
+ export function setLiveContextWindow(providerId: string, model: string, tokens: number): void {
133
+ const key = `${providerId}::${model}`
134
+ liveAutoClears.delete(key)
135
+ liveUserWindows.set(key, tokens)
136
+ }
137
+
138
+ /** Hapus pilihan operator (`auto`) — resolusi kembali ke rantai normal. */
139
+ export function clearLiveContextWindow(providerId: string, model: string): void {
140
+ const key = `${providerId}::${model}`
141
+ liveUserWindows.delete(key)
142
+ liveAutoClears.add(key)
143
+ }
144
+
145
+ /** Reset seluruh registry (test saja). */
146
+ export function __resetLiveContextWindows(): void {
147
+ liveUserWindows.clear()
148
+ liveAutoClears.clear()
149
+ }
150
+
151
+ /** `"cleared"` = operator baru saja memilih `auto`; angka di config snapshot
152
+ * harus DILEWATI (bukan dipakai) selama proses ini hidup. */
153
+ type LiveOverlay = ContextWindowResolution | "cleared" | undefined
154
+
155
+ function readLiveWindowOverlay(model: string, config?: MinicodeConfig): LiveOverlay {
156
+ let providerId: string | undefined
157
+ let modelId = model
158
+ if (model.includes("::")) {
159
+ const sep = model.indexOf("::")
160
+ providerId = model.slice(0, sep)
161
+ modelId = model.slice(sep + 2)
162
+ } else if (config) {
163
+ providerId = config.providers.find((entry) => entry.models?.includes(model))?.id
164
+ }
165
+ if (!providerId) return undefined
166
+ if (liveAutoClears.has(`${providerId}::${modelId}`)) return "cleared"
167
+ const tokens = liveUserWindows.get(`${providerId}::${modelId}`)
168
+ if (validWindow(tokens)) {
169
+ return { tokens, source: "model", origin: "user", model: modelId, providerId }
170
+ }
171
+ // Wildcard live (`provider::*`) hanya berlaku bila model ini tidak punya nilai
172
+ // persis di config snapshot (menjaga prioritas eksak > wildcard).
173
+ const cfgExact = config?.providers.find((entry) => entry.id === providerId)?.contextWindows?.[
174
+ modelId
175
+ ]
176
+ if (validWindow(cfgExact)) return undefined
177
+ if (liveAutoClears.has(`${providerId}::*`)) return "cleared"
178
+ const wildcardTokens = liveUserWindows.get(`${providerId}::*`)
179
+ if (!validWindow(wildcardTokens)) return undefined
180
+ return {
181
+ tokens: wildcardTokens,
182
+ source: "provider-default",
183
+ origin: "user",
184
+ model: modelId,
185
+ providerId,
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Lanjutkan rantai resolusi TANPA nilai `contextWindows` di config.
191
+ *
192
+ * Dipakai saat operator memilih `auto` selama sesi hidup: aturan "auto" adalah
193
+ * kembali ke deteksi otomatis, bukan ke angka yang kebetulan masih tersimpan di
194
+ * objek config yang sudah dibaca di awal. Bila `auto` juga sedang tertulis di
195
+ * disk (sesi baru), fungsi ini tidak dipanggil sama sekali — hasilnya identik.
196
+ */
197
+ function resolveIgnoringConfigWindows(
198
+ config: MinicodeConfig,
199
+ model?: string,
200
+ ): ContextWindowResolution {
201
+ const stripped: MinicodeConfig = {
202
+ ...config,
203
+ providers: config.providers.map((p) => {
204
+ const { contextWindows: _w, contextWindowSources: _s, ...rest } = p
205
+ return rest
206
+ }),
207
+ }
208
+ // `ignoreLive` WAJIB: tanpa penanda ini, cabang `cleared` di pemanggilan
209
+ // rekursif membaca kunci yang sama dan memanggil fungsi ini lagi — rekursi
210
+ // tak berujung (satu sesi `auto` langsung menggantung tanpa stack overflow
211
+ // karena Bun hanya menumpuk frame sampai memori habis).
212
+ return resolveContextWindow(stripped, model, undefined, true)
213
+ }
214
+
116
215
  /** Resolve a budget in the same order as the router: explicit provider pin,
117
216
  * then first provider advertising a bare model, then the provider fallback.
118
217
  * Unknown aliases use a conservative budget and remain visible to callers. */
@@ -120,9 +219,19 @@ export function resolveContextWindow(
120
219
  config: MinicodeConfig,
121
220
  model?: string,
122
221
  override?: number,
222
+ /** Internal: lewati overlay live (dipakai `resolveIgnoringConfigWindows`). */
223
+ ignoreLive = false,
123
224
  ): ContextWindowResolution {
124
225
  if (validWindow(override))
125
226
  return { tokens: override, source: "override", ...(model ? { model } : {}) }
227
+ // Nilai operator yang BARU ditulis (`/context`, `config context-window`)
228
+ // menang atas snapshot `config` yang dibekukan saat sesi start: sesi hidup
229
+ // harus langsung memakai pilihan yang baru saja dibuat. Tanpa lapis ini
230
+ // perintah "set 200k" tampak sukses tapi turn berikutnya tetap memakai angka
231
+ // lama sampai restart — persis keluhan "fitur ini tidak berefek".
232
+ const live = model && !ignoreLive ? readLiveWindowOverlay(model, config) : undefined
233
+ if (live === "cleared") return resolveIgnoringConfigWindows(config, model)
234
+ if (live) return live
126
235
 
127
236
  let providerId: string | undefined
128
237
  let modelId = model