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
@@ -18,6 +18,7 @@
18
18
 
19
19
  import { spawnSync } from "node:child_process"
20
20
  import { createHash, randomUUID } from "node:crypto"
21
+ import { lstat } from "node:fs/promises"
21
22
  import { isAbsolute, relative, resolve } from "node:path"
22
23
  import type { Tool, ToolContext } from "#minicore"
23
24
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
@@ -1330,7 +1331,10 @@ export async function correlateChildEffect(
1330
1331
 
1331
1332
  export interface WorkspaceIntegrityIssue {
1332
1333
  readonly path: string
1333
- readonly reason: "missing-written-file" | "unresolved-conflict-marker"
1334
+ readonly reason:
1335
+ | "missing-written-file"
1336
+ | "unresolved-conflict-marker"
1337
+ | "integrity-check-unavailable"
1334
1338
  readonly line?: number
1335
1339
  readonly detail: string
1336
1340
  }
@@ -1346,6 +1350,44 @@ const INTEGRITY_MAX_BYTES = 8 * 1024 * 1024
1346
1350
  const CONFLICT_START_RE = /^<{7}(?: |$)/
1347
1351
  const CONFLICT_END_RE = /^>{7}(?: |$)/
1348
1352
 
1353
+ function isMissingPathError(error: unknown): boolean {
1354
+ const code = (error as NodeJS.ErrnoException | null)?.code
1355
+ return code === "ENOENT" || code === "ENOTDIR"
1356
+ }
1357
+
1358
+ async function addIntegrityReadIssue(
1359
+ issues: WorkspaceIntegrityIssue[],
1360
+ abs: string,
1361
+ rel: string,
1362
+ error: unknown,
1363
+ operation: "stat" | "read",
1364
+ ): Promise<void> {
1365
+ // Sebagian filesystem/adapter Windows membungkus error open dan tidak
1366
+ // meneruskan code ENOENT. Probe lstat membedakan file yang memang hilang
1367
+ // dari target yang ada tetapi tak dapat diperiksa secara aman.
1368
+ let missing = isMissingPathError(error)
1369
+ if (!missing) {
1370
+ try {
1371
+ await lstat(abs)
1372
+ } catch (probeError) {
1373
+ missing = isMissingPathError(probeError)
1374
+ }
1375
+ }
1376
+ issues.push(
1377
+ missing
1378
+ ? {
1379
+ path: rel,
1380
+ reason: "missing-written-file",
1381
+ detail: `expected written file '${rel}' is missing on disk`,
1382
+ }
1383
+ : {
1384
+ path: rel,
1385
+ reason: "integrity-check-unavailable",
1386
+ detail: `could not securely ${operation} expected written file '${rel}'`,
1387
+ },
1388
+ )
1389
+ }
1390
+
1349
1391
  function findConflictMarkerLine(text: string): number | null {
1350
1392
  const lines = text.split("\n")
1351
1393
  for (let i = 0; i < lines.length; i++) {
@@ -1383,28 +1425,25 @@ export async function checkWorkspaceIntegrity(
1383
1425
  try {
1384
1426
  st = await safeStat(abs, root)
1385
1427
  } catch (err) {
1386
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
1387
- issues.push({
1388
- path: rel,
1389
- reason: "missing-written-file",
1390
- detail: `expected written file '${rel}' is missing on disk`,
1391
- })
1392
- }
1428
+ await addIntegrityReadIssue(issues, abs, rel, err, "stat")
1429
+ continue
1430
+ }
1431
+ if (!st.isFile() || st.size > INTEGRITY_MAX_BYTES) {
1432
+ issues.push({
1433
+ path: rel,
1434
+ reason: "integrity-check-unavailable",
1435
+ detail: !st.isFile()
1436
+ ? `expected written path '${rel}' is not a regular file`
1437
+ : `expected written file '${rel}' exceeds the integrity scan limit`,
1438
+ })
1393
1439
  continue
1394
1440
  }
1395
- if (!st.isFile() || st.size > INTEGRITY_MAX_BYTES) continue
1396
1441
 
1397
1442
  let contentText: string
1398
1443
  try {
1399
1444
  contentText = await safeReadFile(abs, root)
1400
1445
  } catch (err) {
1401
- if ((err as NodeJS.ErrnoException)?.code === "ENOENT") {
1402
- issues.push({
1403
- path: rel,
1404
- reason: "missing-written-file",
1405
- detail: `expected written file '${rel}' disappeared during check`,
1406
- })
1407
- }
1446
+ await addIntegrityReadIssue(issues, abs, rel, err, "read")
1408
1447
  continue
1409
1448
  }
1410
1449
  // Lewati file biner (ada karakter NUL pada 8 KiB pertama).
@@ -1,7 +1,9 @@
1
1
  import type { Dirent } from "node:fs"
2
- import { readdir, readFile, stat } from "node:fs/promises"
2
+ import { readdir, stat } from "node:fs/promises"
3
3
  import { homedir } from "node:os"
4
4
  import { basename, dirname, join, resolve } from "node:path"
5
+ import { LIMITS } from "../constants.ts"
6
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
5
7
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
6
8
 
7
9
  export interface Skill {
@@ -72,9 +74,20 @@ async function loadDir(dir: string, out: Skill[], root: string = dir) {
72
74
  continue
73
75
  }
74
76
  if (!e.isFile() || !e.name.endsWith(".md")) continue
75
- const txt = await readFile(full, "utf8").catch(() => "")
77
+ let txt = ""
78
+ let truncated = false
79
+ try {
80
+ const loaded = await safeReadFileCapped(full, root, LIMITS.SKILL_FILE_MAX_BYTES)
81
+ txt = loaded.text
82
+ truncated = loaded.truncated
83
+ } catch {
84
+ continue
85
+ }
76
86
  if (!txt.trim()) continue
77
- const { meta, body } = parseFrontmatter(txt)
87
+ const { meta, body: parsedBody } = parseFrontmatter(txt)
88
+ const body = truncated
89
+ ? `${parsedBody}\n\n… [skill truncated after first ${LIMITS.SKILL_FILE_MAX_BYTES} bytes]`
90
+ : parsedBody
78
91
  const rawName = meta.name ?? e.name.replace(/\.md$/, "")
79
92
  const name = rawName
80
93
  .toLowerCase()
package/src/tools/bash.ts CHANGED
@@ -4,6 +4,7 @@ import { resolve as resolvePath } from "node:path"
4
4
  import type { Tool, ToolContext } from "#minicore"
5
5
  import { LIMITS } from "../constants.ts"
6
6
  import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
7
+ import { requireToolCwd } from "./context.ts"
7
8
 
8
9
  // re-export untuk backward compat (helper kini terpusat di policy/scrub)
9
10
  export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
@@ -298,7 +299,7 @@ function makeBashTool(ownerSid: string | null): Tool {
298
299
  additionalProperties: false,
299
300
  },
300
301
  async execute({ cmd, cwd, timeoutMs, background }, ctx) {
301
- const sessionRoot = ctx.cwd ?? process.cwd()
302
+ const sessionRoot = requireToolCwd(ctx)
302
303
  const c = cwd as string | undefined
303
304
  if (c && (isCwdOutsideRoot(c, sessionRoot) || isPathOutsideRoot(c, sessionRoot)))
304
305
  throw new Error(`cwd outside workspace: ${c}`)
@@ -336,10 +337,12 @@ function makeBashTool(ownerSid: string | null): Tool {
336
337
  const res = await runInDocker(cmd as string, effectiveCwd, {
337
338
  timeoutMs: timeout,
338
339
  env: sanitizeSpawnEnv(process.env) as Record<string, string>,
340
+ signal: ctx.signal,
339
341
  })
342
+ ctx.signal.throwIfAborted()
340
343
  const text = scrubSecrets(res.output)
341
- if (res.code !== 0 && res.code !== null)
342
- return `exit ${res.code}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
344
+ if (res.code !== 0)
345
+ return `exit ${res.code ?? "unknown"}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
343
346
  return capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)
344
347
  }
345
348
  if (sandboxStrict() || !sandboxExplicitFallbackAllowed()) {
@@ -4,6 +4,7 @@ import { scrubSecrets } from "../policy/scrub.ts"
4
4
  import { dockerAvailable, runInDocker } from "../sandbox/docker.ts"
5
5
  import { osSandboxAvailable, runInOsSandbox } from "../sandbox/os.ts"
6
6
  import { capMarked } from "./bash.ts"
7
+ import { requireToolCwd } from "./context.ts"
7
8
 
8
9
  // code_run: snippet python/node dieksekusi LEWAT sandbox runner (docker atau
9
10
  // OS sandbox), bukan spawn host langsung — versi lama hanya mengecek env flag
@@ -14,8 +15,8 @@ import { capMarked } from "./bash.ts"
14
15
  // fallback diam-diam ke host).
15
16
  // - docker image default (node:22-alpine) membawa node, bukan python3 —
16
17
  // python butuh MINICODE_SANDBOX_IMAGE yang menyediakannya.
17
- // - Pembatalan menghentikan PENUNGGUAN; container/proses bisa hidup sampai
18
- // timeout runner-nya sendiri (terdokumentasi, sama seperti MCP stdio).
18
+ // - Timeout/abort meminta daemon menghapus container bernama; hasil cleanup
19
+ // dilaporkan, tetapi tetap best-effort bila daemon tak merespons.
19
20
 
20
21
  /** Escape untuk disisip sebagai satu argumen single-quoted di `sh -c`. */
21
22
  export function shSingleQuote(s: string): string {
@@ -46,7 +47,7 @@ export const codeRunTool: Tool = {
46
47
  }
47
48
  const src = code as string
48
49
  if (src.includes("\0")) throw new Error("code contains NUL byte")
49
- const root = ctx.cwd ?? process.cwd()
50
+ const root = requireToolCwd(ctx)
50
51
  const timeoutMs =
51
52
  typeof timeout === "number" && Number.isFinite(timeout) && timeout > 0 ? timeout : 10000
52
53
  // Tanpa shell perantara di sisi kita: kode jadi SATU argumen single-quoted
@@ -61,7 +62,7 @@ export const codeRunTool: Tool = {
61
62
  if (!dockerAvailable()) {
62
63
  throw new Error("code_run: MINICODE_SANDBOX=docker but docker is not available")
63
64
  }
64
- return runInDocker(inner, root, { timeoutMs })
65
+ return runInDocker(inner, root, { timeoutMs, signal: ctx.signal })
65
66
  }
66
67
  : () => {
67
68
  if (!osSandboxAvailable()) {
@@ -90,7 +91,7 @@ export const codeRunTool: Tool = {
90
91
  ),
91
92
  ])
92
93
  const text = capMarked(scrubSecrets(settled.output), LIMITS.BASH_OUTPUT_MAX_CHARS).trim()
93
- if (settled.code !== 0) return `exit ${settled.code}\n${text}`
94
+ if (settled.code !== 0) return `exit ${settled.code ?? "unknown"}\n${text}`
94
95
  return text
95
96
  },
96
97
  }
@@ -0,0 +1,8 @@
1
+ /** Workspace root wajib datang dari context eksekusi yang dirakit runtime. */
2
+ export function requireToolCwd(context: unknown): string {
3
+ const cwd = (context as { cwd?: unknown } | null)?.cwd
4
+ if (typeof cwd !== "string" || cwd.length === 0) {
5
+ throw new Error("ToolContext.cwd is required; refusing to use process.cwd()")
6
+ }
7
+ return cwd
8
+ }
@@ -2,6 +2,7 @@ import { stat } from "node:fs/promises"
2
2
  import type { Tool } from "#minicore"
3
3
  import { resolveSafePath } from "../lib/safe-open.ts"
4
4
  import { trashFile } from "../lib/trash.ts"
5
+ import { requireToolCwd } from "./context.ts"
5
6
 
6
7
  export const deleteFileTool: Tool = {
7
8
  name: "delete_file",
@@ -18,7 +19,7 @@ export const deleteFileTool: Tool = {
18
19
  async execute({ path }, ctx) {
19
20
  ctx.signal.throwIfAborted()
20
21
  const p = path as string
21
- const root = ctx.cwd ?? process.cwd()
22
+ const root = requireToolCwd(ctx)
22
23
  // Verifikasi path terpusat (logis + target nyata) — detail di safe-open.ts.
23
24
  const { abs, real } = await resolveSafePath(p, root)
24
25
  const st = await stat(real).catch(() => null)
package/src/tools/edit.ts CHANGED
@@ -3,6 +3,7 @@ import { LIMITS } from "../constants.ts"
3
3
  import { atomicWriteText } from "../lib/atomic-write.ts"
4
4
  import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
5
5
  import { appendLspDiagnostics } from "../policy/verifier.ts"
6
+ import { requireToolCwd } from "./context.ts"
6
7
  import { applyHashline } from "./hashline.ts"
7
8
 
8
9
  function normalizeLf(s: string): string {
@@ -145,7 +146,7 @@ export const editTool: Tool = {
145
146
  async execute({ path, oldString, newString }, ctx) {
146
147
  ctx.signal.throwIfAborted()
147
148
  const p = path as string
148
- const root = ctx.cwd ?? process.cwd()
149
+ const root = requireToolCwd(ctx)
149
150
  // Verifikasi path terpusat (logis + target nyata, induk symlink ikut
150
151
  // ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
151
152
  const { abs, real: realAbs } = await resolveSafePath(p, root)
package/src/tools/git.ts CHANGED
@@ -1,5 +1,7 @@
1
1
  import { spawn } from "node:child_process"
2
- import { resolve } from "node:path"
2
+ import { mkdtemp, rm } from "node:fs/promises"
3
+ import { tmpdir } from "node:os"
4
+ import { join, resolve } from "node:path"
3
5
  import type { Tool } from "#minicore"
4
6
  import { LIMITS } from "../constants.ts"
5
7
  import {
@@ -11,8 +13,14 @@ import {
11
13
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
12
14
  import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
13
15
  import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
16
+ import { requireToolCwd } from "./context.ts"
14
17
 
15
- function runGit(args: string[], cwd: string | undefined, signal: AbortSignal): Promise<string> {
18
+ function runGit(
19
+ args: string[],
20
+ cwd: string | undefined,
21
+ signal: AbortSignal,
22
+ envPatch?: Record<string, string>,
23
+ ): Promise<string> {
16
24
  return new Promise((resolve, reject) => {
17
25
  // Audit #10 P0: SEMUA pemanggilan git lewat sini membawa netralisasi
18
26
  // repo-controlled execution (hooks/fsmonitor/pager via GIT_SAFE_BASE).
@@ -24,7 +32,7 @@ function runGit(args: string[], cwd: string | undefined, signal: AbortSignal): P
24
32
  // env ini — kredensial (API_KEY/TOKEN/...) di-strip agar hook nakal tak
25
33
  // bisa memanen secret dari env. Auth tetap via credential helper / agen
26
34
  // SSH (SSH_AUTH_SOCK bukan pola secret) — lihat policy/scrub.ts.
27
- env: sanitizeSpawnEnv(process.env),
35
+ env: sanitizeSpawnEnv(process.env, envPatch),
28
36
  // Timeout dari LIMITS, bukan hardcode: `git_commit` menjalankan beberapa
29
37
  // operasi berurutan (rev-parse → add → commit → log), dan di mesin yang
30
38
  // sibuk (mis. CI menjalankan test dengan coverage) spawn git bisa jauh
@@ -62,6 +70,24 @@ function runGit(args: string[], cwd: string | undefined, signal: AbortSignal): P
62
70
  })
63
71
  }
64
72
 
73
+ const gitCommitLocks = new Map<string, Promise<void>>()
74
+
75
+ async function withGitCommitLock<T>(cwd: string, operation: () => Promise<T>): Promise<T> {
76
+ const key = resolve(cwd)
77
+ const previous = gitCommitLocks.get(key) ?? Promise.resolve()
78
+ let release!: () => void
79
+ const current = new Promise<void>((resolvePromise) => (release = resolvePromise))
80
+ const queued = previous.then(() => current)
81
+ gitCommitLocks.set(key, queued)
82
+ await previous
83
+ try {
84
+ return await operation()
85
+ } finally {
86
+ release()
87
+ if (gitCommitLocks.get(key) === queued) gitCommitLocks.delete(key)
88
+ }
89
+ }
90
+
65
91
  /** cwd tool harus di dalam workspace — sama seperti bash/glob/grep. */
66
92
  function assertCwd(cwd: string | undefined, sessionRoot: string): void {
67
93
  if (!cwd) return
@@ -92,7 +118,7 @@ export const gitStatusTool: Tool = {
92
118
  },
93
119
  async execute({ cwd }, ctx) {
94
120
  const c = cwd as string | undefined
95
- const sessionRoot = ctx.cwd ?? process.cwd()
121
+ const sessionRoot = requireToolCwd(ctx)
96
122
  assertCwd(c, sessionRoot)
97
123
  const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
98
124
  if (!(await isGitRepo(resolvedCwd, ctx.signal))) return "not a git repository"
@@ -131,7 +157,7 @@ export const gitDiffTool: Tool = {
131
157
  additionalProperties: false,
132
158
  },
133
159
  async execute({ cwd, staged }, ctx) {
134
- const sessionRoot = ctx.cwd ?? process.cwd()
160
+ const sessionRoot = requireToolCwd(ctx)
135
161
  assertCwd(cwd as string | undefined, sessionRoot)
136
162
  const resolvedCwd = (cwd as string | undefined)
137
163
  ? resolve(sessionRoot, cwd as string)
@@ -160,7 +186,7 @@ export const gitLogTool: Tool = {
160
186
  additionalProperties: false,
161
187
  },
162
188
  async execute({ cwd, limit }, ctx) {
163
- const sessionRoot = ctx.cwd ?? process.cwd()
189
+ const sessionRoot = requireToolCwd(ctx)
164
190
  assertCwd(cwd as string | undefined, sessionRoot)
165
191
  const resolvedCwd = (cwd as string | undefined)
166
192
  ? resolve(sessionRoot, cwd as string)
@@ -200,7 +226,7 @@ function assertPaths(paths: unknown, cwd: string | undefined, sessionRoot: strin
200
226
  export const gitCommitTool: Tool = {
201
227
  name: "git_commit",
202
228
  description:
203
- "Create a git commit. Stage specific paths (paths) or all tracked changes (all:true). Does not support push/amend/reset — that is beyond the agent's authority. Never runs repository hooks (--no-verify + isolated hooks path), unlike terminal git commit.",
229
+ "Create a git commit. Stage specific paths (paths) or all tracked changes (all:true). Does not support push/amend/reset — that is beyond the agent's authority. Never runs repository hooks and refuses configured custom filters before staging; use manual Git only after reviewing trusted filters.",
204
230
  parameters: {
205
231
  type: "object",
206
232
  properties: {
@@ -222,7 +248,7 @@ export const gitCommitTool: Tool = {
222
248
  async execute({ message, paths, all, cwd }, ctx) {
223
249
  ctx.signal.throwIfAborted()
224
250
  const c = cwd as string | undefined
225
- const sessionRoot = ctx.cwd ?? process.cwd()
251
+ const sessionRoot = requireToolCwd(ctx)
226
252
  assertCwd(c, sessionRoot)
227
253
  const resolvedCwd = c ? resolve(sessionRoot, c) : sessionRoot
228
254
  const msg = String(message ?? "").trim()
@@ -244,58 +270,106 @@ export const gitCommitTool: Tool = {
244
270
  ).catch(() => "")
245
271
  if (!inside.startsWith("true")) throw new Error("not a git repository (git rev-parse failed)")
246
272
 
247
- if (files.length > 0) {
248
- // `--` memisahkan path dari opsi: nama file bernama `-f` tak jadi flag.
249
- await runGit(["add", "--", ...files], resolvedCwd, ctx.signal)
250
- }
251
- // F-04: clean/smudge TIDAK dinetralkan di add/commit — semantik clean
252
- // milik user (LFS), lihat git-hardening.ts. Sebagai gantinya, staging yang
253
- // melewati filter repo yang DITEMUKAN dilaporkan eksplisit di hasil (bukan
254
- // diam-diam): approval gate permission + peringatan ini adalah kontrolnya.
255
- // Berlaku untuk paths MAUPUN all:true (`commit -a` juga menjalankan clean).
256
- let filterWarning = ""
257
- try {
273
+ return await withGitCommitLock(resolvedCwd, async () => {
274
+ ctx.signal.throwIfAborted()
275
+ // Tool authority tidak mencakup eksekusi command dari filter repo.
276
+ // Discovery juga fail-closed: kegagalan membaca config berhenti sebelum
277
+ // temporary index dibuat atau `git add` dapat menjalankan filter.
258
278
  const drivers = await discoverFilterDrivers(resolvedCwd)
259
279
  if (drivers.length > 0) {
260
280
  const names = drivers.map((d) => `filter.${d.name}`).join(", ")
261
- filterWarning =
262
- `\n\n[warn] repo defines custom git filters (${names}) that ran during staging — ` +
263
- `review .gitattributes/.git/config in untrusted repos before committing.`
281
+ throw new Error(
282
+ `git_commit blocked before staging: repository Git filters are configured (${names}). ` +
283
+ "Review .gitattributes and Git config, then perform the commit manually if the filters are trusted.",
284
+ )
264
285
  }
265
- } catch {}
266
-
267
- // `-m` dengan pesan sebagai satu argumen: tak ada shell yang menginterpretasi
268
- // isinya, jadi backtick/`$()` di pesan commit tidak dieksekusi.
269
- // Audit #10 P0: `--no-verify` mematikan pre-commit/commit-msg repo;
270
- // post-commit (+ override hooksPath repo) dimatikan GIT_SAFE_BASE di
271
- // runGit. Commit agen tak pernah menjalankan kode repo — bedakan dari
272
- // `git commit` terminal yang menjalankan hooks.
273
- const args = ["commit", "--no-verify", "-m", msg]
274
- if (files.length === 0 && all === true) args.push("-a")
275
286
 
276
- const out = await runGit(args, resolvedCwd, ctx.signal)
277
- // `git commit` keluar non-zero saat tak ada perubahan; runGit sudah
278
- // meneruskan teksnya, jadi model membaca alasan sebenarnya.
279
- if (/nothing to commit|no changes added/i.test(out)) {
280
- // Audit #08 P1 (retry setelah sukses-yang-responsnya-hilang): tree
281
- // bersih + subjek HEAD sama dengan pesan yang diminta = commit pertama
282
- // sudah durable. Kembalikan SHA-nya (tanpa commit baru) agar pemanggil
283
- // tak mengira tak ada yang ter-commit. Beda subjek = kondisi orang
284
- // lain yang commit duluan → perilaku lama (tanpa klaim palsu).
287
+ const tempIndexDir = await mkdtemp(join(tmpdir(), "minicode-git-index-"))
288
+ const indexEnv = { GIT_INDEX_FILE: join(tempIndexDir, "index") }
285
289
  try {
286
- const subject = (
287
- await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
288
- ).trim()
289
- if (subject && subject === msg.split("\n")[0]?.trim()) {
290
- const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
291
- () => "",
292
- )
293
- return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}${filterWarning}`
290
+ // Seed a private index from HEAD. Existing staged changes stay in the
291
+ // user's index and can never leak into this scoped commit.
292
+ const headRef = await runGit(
293
+ ["rev-parse", "--verify", "HEAD"],
294
+ resolvedCwd,
295
+ ctx.signal,
296
+ ).catch(() => "")
297
+ await runGit(
298
+ ["read-tree", headRef.trim() ? "HEAD" : "--empty"],
299
+ resolvedCwd,
300
+ ctx.signal,
301
+ indexEnv,
302
+ )
303
+ if (files.length > 0) {
304
+ // `--` memisahkan path dari opsi: nama file bernama `-f` tak jadi flag.
305
+ await runGit(["add", "--", ...files], resolvedCwd, ctx.signal, indexEnv)
294
306
  }
295
- } catch {}
296
- return `nothing to commit:\n${out}${filterWarning}`
297
- }
298
- const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(() => "")
299
- return `${out}${head ? `\n\nHEAD: ${head}` : ""}${filterWarning}`
307
+
308
+ // `-m` satu argumen; --no-verify menonaktifkan hook yang sudah
309
+ // dinetralkan GIT_SAFE_BASE. `-a` hanya berlaku pada index privat.
310
+ const args = ["commit", "--no-verify", "-m", msg]
311
+ if (files.length === 0 && all === true) args.push("-a")
312
+ const out = await runGit(args, resolvedCwd, ctx.signal, indexEnv)
313
+ if (/nothing to commit|no changes added/i.test(out)) {
314
+ try {
315
+ const subject = (
316
+ await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
317
+ ).trim()
318
+ if (subject && subject === msg.split("\n")[0]?.trim()) {
319
+ const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
320
+ () => "",
321
+ )
322
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
323
+ }
324
+ } catch {}
325
+ return `nothing to commit:\n${out}`
326
+ }
327
+ let indexWarning = ""
328
+ const newHead = await runGit(
329
+ ["rev-parse", "--verify", "HEAD"],
330
+ resolvedCwd,
331
+ ctx.signal,
332
+ ).catch(() => "")
333
+ if (newHead.trim() && newHead.trim() !== headRef.trim()) {
334
+ try {
335
+ const committedPaths = await runGit(
336
+ [
337
+ "--literal-pathspecs",
338
+ "diff-tree",
339
+ "--root",
340
+ "--no-renames",
341
+ "--no-commit-id",
342
+ "--name-only",
343
+ "-r",
344
+ "-z",
345
+ "HEAD",
346
+ ],
347
+ resolvedCwd,
348
+ ctx.signal,
349
+ )
350
+ const paths = committedPaths.split("\0").filter(Boolean)
351
+ if (paths.length > 0) {
352
+ // Reconcile only committed entries in the shared index. This
353
+ // leaves unrelated staged paths intact while keeping the normal
354
+ // post-commit status clean for files this operation authorized.
355
+ await runGit(
356
+ ["--literal-pathspecs", "reset", "--quiet", "HEAD", "--", ...paths],
357
+ resolvedCwd,
358
+ ctx.signal,
359
+ )
360
+ }
361
+ } catch {
362
+ indexWarning =
363
+ "\n\n[warn] commit succeeded, but the shared index could not be reconciled; review `git status` before the next commit."
364
+ }
365
+ }
366
+ const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
367
+ () => "",
368
+ )
369
+ return `${out}${head ? `\n\nHEAD: ${head}` : ""}${indexWarning}`
370
+ } finally {
371
+ await rm(tempIndexDir, { recursive: true, force: true }).catch(() => {})
372
+ }
373
+ })
300
374
  },
301
375
  }
package/src/tools/glob.ts CHANGED
@@ -4,6 +4,7 @@ import type { Tool } from "#minicore"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { isIgnored, loadIgnoreMatchers } from "../lib/ignore.ts"
6
6
  import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
7
+ import { requireToolCwd } from "./context.ts"
7
8
 
8
9
  async function walk(
9
10
  dir: string,
@@ -78,7 +79,7 @@ export const globTool: Tool = {
78
79
  additionalProperties: false,
79
80
  },
80
81
  async execute({ pattern, cwd, limit }, ctx) {
81
- const sessionRoot = ctx.cwd ?? process.cwd()
82
+ const sessionRoot = requireToolCwd(ctx)
82
83
  const rawRoot = (cwd as string) ?? "."
83
84
  const root = resolve(sessionRoot, rawRoot)
84
85
  if (isPathOutsideRoot(root, sessionRoot)) throw new Error(`cwd outside workspace: ${rawRoot}`)
package/src/tools/grep.ts CHANGED
@@ -1,12 +1,14 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
2
  import { readdir, realpath, stat } from "node:fs/promises"
3
- import { join, relative, resolve } from "node:path"
3
+ import { isAbsolute, join, relative, resolve } from "node:path"
4
4
  import type { Tool } from "#minicore"
5
5
  import { LIMITS } from "../constants.ts"
6
6
  import { isIgnored, loadIgnoreMatchers } from "../lib/ignore.ts"
7
7
  import { safeReadFile } from "../lib/safe-open.ts"
8
+ import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
8
9
  import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
9
- import { scrubSecrets } from "../policy/scrub.ts"
10
+ import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
11
+ import { requireToolCwd } from "./context.ts"
10
12
 
11
13
  async function walkGrep(
12
14
  dir: string,
@@ -80,8 +82,22 @@ let rgPath: string | null | undefined
80
82
  export function ripgrepAvailable(): boolean {
81
83
  if (rgPath !== undefined) return rgPath !== null
82
84
  try {
83
- const r = spawnSync("rg", ["--version"], { stdio: "ignore", timeout: 3000 })
84
- rgPath = r.status === 0 ? "rg" : null
85
+ const executable = resolveTrustedExecutable("rg")
86
+ // Resolver fallback berupa nama telanjang tidak aman untuk workspace
87
+ // Windows: CreateProcess dapat mencari executable bernama sama di cwd.
88
+ // Tanpa PATH tepercaya, gunakan walker JS alih-alih mencari ulang dari cwd.
89
+ if (!isAbsolute(executable)) {
90
+ rgPath = null
91
+ return false
92
+ }
93
+ const env = sanitizeSpawnEnv(process.env)
94
+ delete env.RIPGREP_CONFIG_PATH
95
+ const r = spawnSync(executable, ["--no-config", "--version"], {
96
+ stdio: "ignore",
97
+ timeout: 3000,
98
+ env,
99
+ })
100
+ rgPath = r.status === 0 ? executable : null
85
101
  } catch {
86
102
  rgPath = null
87
103
  }
@@ -118,6 +134,7 @@ function runRipgrep(
118
134
  include?: string,
119
135
  ): Promise<string[]> {
120
136
  const args = [
137
+ "--no-config", // config ripgrep dapat menjalankan --pre pada berkas workspace
121
138
  "--vimgrep", // path:line:col:text
122
139
  "--no-heading",
123
140
  "--color=never",
@@ -138,7 +155,15 @@ function runRipgrep(
138
155
  args.push("--regexp", pattern, "--", ".")
139
156
 
140
157
  return new Promise((resolveOut, reject) => {
141
- const p = spawn("rg", args, { cwd: root, stdio: ["ignore", "pipe", "pipe"] })
158
+ const env = sanitizeSpawnEnv(process.env)
159
+ // Config pengguna tidak ikut diterapkan pada operasi pencarian agent.
160
+ // --no-config tetap dipasang sebagai pagar kedua pada argv ripgrep.
161
+ delete env.RIPGREP_CONFIG_PATH
162
+ const p = spawn(resolveTrustedExecutable("rg"), args, {
163
+ cwd: root,
164
+ stdio: ["ignore", "pipe", "pipe"],
165
+ env,
166
+ })
142
167
  const out: string[] = []
143
168
  let buf = ""
144
169
  let stderr = ""
@@ -219,7 +244,7 @@ export const grepTool: Tool = {
219
244
  additionalProperties: false,
220
245
  },
221
246
  async execute({ pattern, cwd, include, limit }, ctx) {
222
- const sessionRoot = ctx.cwd ?? process.cwd()
247
+ const sessionRoot = requireToolCwd(ctx)
223
248
  const rawRoot = (cwd as string) ?? "."
224
249
  const root = resolve(sessionRoot, rawRoot)
225
250
  if (isPathOutsideRoot(root, sessionRoot)) throw new Error(`cwd outside workspace: ${rawRoot}`)
package/src/tools/lsp.ts CHANGED
@@ -12,6 +12,7 @@ import {
12
12
  } from "../lsp/client.ts"
13
13
  import { isPathOutsideRoot, isRealPathOutsideRoot, isSensitive } from "../policy/jail.ts"
14
14
  import { scrubSecrets } from "../policy/scrub.ts"
15
+ import { requireToolCwd } from "./context.ts"
15
16
 
16
17
  const SEVERITY = ["Error", "Warn", "Info", "Hint"]
17
18
 
@@ -126,7 +127,7 @@ function posTool(
126
127
  },
127
128
  async execute(args, ctx) {
128
129
  ctx.signal.throwIfAborted()
129
- const cwd = ctx.cwd ?? process.cwd()
130
+ const cwd = requireToolCwd(ctx)
130
131
  try {
131
132
  const resolved = await resolvePosition(args as PosArgs, cwd)
132
133
  if (typeof resolved === "string") return resolved
@@ -168,7 +169,7 @@ export const lspDiagnosticsTool: Tool = {
168
169
  },
169
170
  async execute({ file }, ctx) {
170
171
  ctx.signal.throwIfAborted()
171
- const cwd = ctx.cwd ?? process.cwd()
172
+ const cwd = requireToolCwd(ctx)
172
173
  try {
173
174
  const { abs, text } = await readTarget(String(file), cwd)
174
175
  const { items } = await raceAbort(lspDiagnostics(abs, text, undefined, cwd), ctx.signal)
@@ -225,7 +226,7 @@ export const lspSymbolsTool: Tool = {
225
226
  },
226
227
  async execute({ file }, ctx) {
227
228
  ctx.signal.throwIfAborted()
228
- const cwd = ctx.cwd ?? process.cwd()
229
+ const cwd = requireToolCwd(ctx)
229
230
  try {
230
231
  const { abs, text } = await readTarget(String(file), cwd)
231
232
  const result = await raceAbort(
@@ -273,7 +274,7 @@ export const lspWorkspaceSymbolsTool: Tool = {
273
274
  if (getConfiguredExts().length === 0)
274
275
  return "(no LSP servers configured — add via minicode config lsp add)"
275
276
  try {
276
- const cwd = ctx.cwd ?? process.cwd()
277
+ const cwd = requireToolCwd(ctx)
277
278
  const symbols = await raceAbort(
278
279
  workspaceSymbols((query as string) ?? "", 5000, cwd),
279
280
  ctx.signal,