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,3 +1,17 @@
1
+ import { readdir, realpath, stat } from "node:fs/promises"
2
+ import { isAbsolute, join, relative, resolve } from "node:path"
3
+ import { LIMITS } from "../constants.ts"
4
+ import { atomicWriteText } from "../lib/atomic-write.ts"
5
+ import { isIgnored } from "../lib/ignore.ts"
6
+ import {
7
+ assertSafeWriteTarget,
8
+ resolveSafePath,
9
+ safeOpenRead,
10
+ safeReadFile,
11
+ } from "../lib/safe-open.ts"
12
+ import { isCwdOutsideRoot, isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
13
+ import { appendLspDiagnostics } from "../policy/verifier.ts"
14
+
1
15
  /** Workspace root wajib datang dari context eksekusi yang dirakit runtime. */
2
16
  export function requireToolCwd(context: unknown): string {
3
17
  const cwd = (context as { cwd?: unknown } | null)?.cwd
@@ -16,3 +30,122 @@ export function requireToolCwd(context: unknown): string {
16
30
  export function contextUnrestricted(context: unknown): boolean {
17
31
  return (context as { permissionMode?: unknown } | null)?.permissionMode === "unrestricted"
18
32
  }
33
+
34
+ /**
35
+ * Potong string tanpa membelah pasangan surrogate UTF-16: `slice` mentah pada
36
+ * batas tinggi menghasilkan kode pengganti `U+FFFD`. Dipakai bersama oleh tool
37
+ * yang memotong baris/teks panjang (`read_file`, `ask_user`).
38
+ */
39
+ export function sliceSafeChars(s: string, max: number): string {
40
+ if (s.length <= max) return s
41
+ let end = max
42
+ const code = s.charCodeAt(end - 1)
43
+ if (code >= 0xd800 && code <= 0xdbff) end -= 1
44
+ return s.slice(0, Math.max(0, end))
45
+ }
46
+
47
+ export async function openSafeToolReadHandle(rawPath: string, ctx: unknown) {
48
+ const root = requireToolCwd(ctx)
49
+ const relaxed = contextUnrestricted(ctx)
50
+ const abs = isAbsolute(rawPath) ? resolve(rawPath) : resolve(root, rawPath)
51
+ let handle: Awaited<ReturnType<typeof safeOpenRead>>["handle"]
52
+ try {
53
+ ;({ handle } = await safeOpenRead(abs, root, relaxed))
54
+ } catch (e) {
55
+ const msg = (e as Error).message ?? ""
56
+ if ((e as NodeJS.ErrnoException).code === "ENOENT" || msg.includes("ENOENT"))
57
+ throw new Error(`file not found: ${rawPath}`)
58
+ throw e
59
+ }
60
+ const st = await handle.stat().catch(() => null)
61
+ if (!st) {
62
+ await handle.close().catch(() => {})
63
+ throw new Error(`file not found: ${rawPath}`)
64
+ }
65
+ return { handle, st, root, relaxed, abs }
66
+ }
67
+
68
+ /** Baca teks siap-edit dengan cek jail, anti-symlink overwrite, cap ukuran, & O_NOFOLLOW. */
69
+ export async function readSafeTextForEdit(rawPath: string, ctx: unknown) {
70
+ const root = requireToolCwd(ctx)
71
+ const relaxed = contextUnrestricted(ctx)
72
+ const { abs, real: realAbs } = await resolveSafePath(rawPath, root, relaxed)
73
+ await assertSafeWriteTarget(abs, root, relaxed)
74
+ const st = await stat(realAbs).catch(() => null)
75
+ if (!st) throw new Error(`file not found: ${rawPath}`)
76
+ if (st.size > LIMITS.READ_FILE_MAX_BYTES)
77
+ throw new Error(`file too large: ${rawPath} (${st.size})`)
78
+ const content = await safeReadFile(abs, root, relaxed).catch(() => {
79
+ throw new Error(`file not found: ${rawPath}`)
80
+ })
81
+ return { root, realAbs, content }
82
+ }
83
+
84
+ /** Tulis hasil edit dengan cek batas char + atomic write + LSP diagnostics. */
85
+ export async function commitSafeTextEdit(
86
+ realAbs: string,
87
+ root: string,
88
+ content: string,
89
+ message: string,
90
+ ): Promise<string> {
91
+ if (content.length > LIMITS.WRITE_FILE_MAX_CHARS)
92
+ throw new Error(`result too large: ${content.length} chars (max 5M)`)
93
+ await atomicWriteText(realAbs, content)
94
+ return await appendLspDiagnostics(realAbs, content, message, undefined, root)
95
+ }
96
+
97
+ /** Validasi dan resolve `cwd` tool terhadap batas workspace. */
98
+ export function resolveSearchRoot(
99
+ cwdArg: unknown,
100
+ ctx: unknown,
101
+ ): { root: string; rawRoot: string; relaxed: boolean } {
102
+ const sessionRoot = requireToolCwd(ctx)
103
+ const relaxed = contextUnrestricted(ctx)
104
+ const rawRoot = (cwdArg as string) ?? "."
105
+ const root = resolve(sessionRoot, rawRoot)
106
+ if (
107
+ !relaxed &&
108
+ (isPathOutsideRoot(root, sessionRoot) || isCwdOutsideRoot(rawRoot, sessionRoot))
109
+ ) {
110
+ throw new Error(`cwd outside workspace: ${rawRoot}`)
111
+ }
112
+ return { root, rawRoot, relaxed }
113
+ }
114
+
115
+ /** Walk workspace aman (hormat .gitignore, skip dotfile default & symlink escape/sensitif). */
116
+ export async function walkWorkspaceFiles(
117
+ opts: {
118
+ dir: string
119
+ root: string
120
+ signal: AbortSignal
121
+ ignoreMatchers: ((rel: string) => boolean)[]
122
+ relaxed?: boolean
123
+ includeDotfiles?: boolean
124
+ shouldStop?: () => boolean
125
+ },
126
+ onFile: (info: { full: string; rel: string; name: string; real: string }) => Promise<void> | void,
127
+ ): Promise<void> {
128
+ if (opts.signal.aborted) throw new Error("aborted")
129
+ if (opts.shouldStop?.()) return
130
+ const entries = await readdir(opts.dir, { withFileTypes: true }).catch(() => [])
131
+ for (const e of entries) {
132
+ if (opts.shouldStop?.()) break
133
+ if (e.name === "node_modules" || e.name === ".git") continue
134
+ if (!opts.includeDotfiles && e.name.startsWith(".")) continue
135
+ const full = join(opts.dir, e.name)
136
+ const rel = relative(opts.root, full).replace(/\\/g, "/")
137
+ if (isIgnored(rel, opts.ignoreMatchers)) continue
138
+ if (e.isDirectory()) {
139
+ await walkWorkspaceFiles({ ...opts, dir: full }, onFile)
140
+ } else {
141
+ const real = await realpath(full).catch(() => full)
142
+ if (
143
+ (!opts.relaxed && isPathOutsideRoot(real, resolve(opts.root))) ||
144
+ isSensitive(real) ||
145
+ isSensitive(rel)
146
+ )
147
+ continue
148
+ await onFile({ full, rel, name: e.name, real })
149
+ }
150
+ }
151
+ }
@@ -11,7 +11,7 @@ export const deleteFileTool: Tool = {
11
11
  parameters: {
12
12
  type: "object",
13
13
  properties: {
14
- path: { type: "string", description: "path file relatif" },
14
+ path: { type: "string", description: "relative file path" },
15
15
  },
16
16
  required: ["path"],
17
17
  additionalProperties: false,
@@ -25,7 +25,8 @@ export const deleteFileTool: Tool = {
25
25
  const { abs, real } = await resolveSafePath(p, root, relaxed)
26
26
  const st = await stat(real).catch(() => null)
27
27
  if (!st) throw new Error(`file not found: ${p}`)
28
- if (st.isDirectory()) throw new Error(`path is directory, use bash rm -r: ${p}`)
28
+ if (st.isDirectory())
29
+ throw new Error(`path is a directory, cannot delete directories with delete_file: ${p}`)
29
30
  // soft-delete ke .minicode/.trash (gitignored, cap 100) — restore via move_file
30
31
  const dest = await trashFile(root, abs)
31
32
  return `deleted ${p} -> ${dest} (soft-delete, restore via move_file if needed)`
package/src/tools/edit.ts CHANGED
@@ -1,9 +1,5 @@
1
1
  import type { Tool } from "#minicore"
2
- import { LIMITS } from "../constants.ts"
3
- import { atomicWriteText } from "../lib/atomic-write.ts"
4
- import { assertSafeWriteTarget, resolveSafePath, safeReadFile } from "../lib/safe-open.ts"
5
- import { appendLspDiagnostics } from "../policy/verifier.ts"
6
- import { contextUnrestricted, requireToolCwd } from "./context.ts"
2
+ import { commitSafeTextEdit, readSafeTextForEdit } from "./context.ts"
7
3
  import { applyHashline } from "./hashline.ts"
8
4
 
9
5
  function normalizeLf(s: string): string {
@@ -71,16 +67,29 @@ export function flexibleMatch(content: string, needle: string): MatchResult | nu
71
67
  }
72
68
 
73
69
  const cLfLines = cLf.split("\n")
74
- // 3. Trailing whitespace tolerance
70
+ // 3. Trailing whitespace tolerance — hanya terima kecocokan yang menempel di
71
+ // batas baris utuh, karena lineRange() mengganti seluruh baris awal..akhir.
72
+ // Match substring di tengah baris bisa menelan token sebelum/sesudah match.
75
73
  const cTrimmed = stripTrailingWhitespace(cLf)
76
74
  const nTrimmed = stripTrailingWhitespace(nLf)
77
- const trimStart = cTrimmed.indexOf(nTrimmed)
78
- if (trimStart !== -1) {
79
- const lineCountBefore = cTrimmed.slice(0, trimStart).split("\n").length - 1
80
- const needleLineCount = nTrimmed.split("\n").length
81
- if (lineCountBefore + needleLineCount <= cLfLines.length) {
82
- const r = lineRange(cLfLines, lineCountBefore, needleLineCount, content)
83
- return { ...r, mode: "trimmed" }
75
+ if (nTrimmed.length > 0) {
76
+ let searchFrom = 0
77
+ while (searchFrom <= cTrimmed.length - nTrimmed.length) {
78
+ const trimStart = cTrimmed.indexOf(nTrimmed, searchFrom)
79
+ if (trimStart === -1) break
80
+ const trimEnd = trimStart + nTrimmed.length
81
+ const atLineStart = trimStart === 0 || cTrimmed[trimStart - 1] === "\n"
82
+ const atLineEnd = trimEnd === cTrimmed.length || cTrimmed[trimEnd] === "\n"
83
+ if (atLineStart && atLineEnd) {
84
+ const lineCountBefore =
85
+ trimStart === 0 ? 0 : cTrimmed.slice(0, trimStart).split("\n").length - 1
86
+ const needleLineCount = nTrimmed.split("\n").length
87
+ if (lineCountBefore + needleLineCount <= cLfLines.length) {
88
+ const r = lineRange(cLfLines, lineCountBefore, needleLineCount, content)
89
+ return { ...r, mode: "trimmed" }
90
+ }
91
+ }
92
+ searchFrom = trimStart + 1
84
93
  }
85
94
  }
86
95
 
@@ -146,88 +155,44 @@ export const editTool: Tool = {
146
155
  async execute({ path, oldString, newString }, ctx) {
147
156
  ctx.signal.throwIfAborted()
148
157
  const p = path as string
149
- const root = requireToolCwd(ctx)
150
- const relaxed = contextUnrestricted(ctx)
151
- // Verifikasi path terpusat (logis + target nyata, induk symlink ikut
152
- // ter-resolusi) — symlink internal tetap bisa diedit, targetnya yang dicek.
153
- const { abs, real: realAbs } = await resolveSafePath(p, root, relaxed)
154
- // Tolak menimpa symlink final (swap antara cek dan tulis gagal tutup).
155
- await assertSafeWriteTarget(abs, root, relaxed)
156
- // Cek ukuran sebelum baca penuh — hindari OOM 1GB via safeReadFile.
157
- // Pakai byte length via stat pada realAbs (handle belum ada), fallback ke content length.
158
- const { stat } = await import("node:fs/promises")
159
- const st = await stat(realAbs).catch(() => null)
160
- if (!st) throw new Error(`file not found: ${p}`)
161
- if (st.size > LIMITS.READ_FILE_MAX_BYTES) throw new Error(`file too large: ${p} (${st.size})`)
162
- // Baca via safeReadFile (O_NOFOLLOW) agar TOCTOU swap gagal ELOOP, bukan baca luar.
163
- const content = await safeReadFile(abs, root, relaxed).catch(() => {
164
- throw new Error(`file not found: ${p}`)
165
- })
158
+ const { root, realAbs, content } = await readSafeTextForEdit(p, ctx)
166
159
  const oldS = oldString as string
167
160
  const newS = newString as string
168
161
  if (oldS === newS) throw new Error("oldString == newString (no change)")
169
- // Hashline fast path (OpenCode): hanya bila line endings konsisten (hindari CRLF→LF corrupt)
170
- // CRLF vs LF ditangani oleh flexibleMatch mode "crlf" yang preservasi original.
162
+ // Hashline fast path: hanya bila line endings konsisten (CRLF vs LF dijaga flexibleMatch).
171
163
  const canHashline = content.includes("\r\n") === oldS.includes("\r\n")
172
- let hashApply: string | null = null
173
164
  if (canHashline) {
174
165
  const hunk = applyHashline(content, oldS, newS)
175
166
  if (hunk !== null) {
176
- // Uniqueness: aturan YANG SAMA dengan jalur flexibleMatch di bawah
177
- // (exact → crlf → trimmed → fuzzy). Pemeriksaan lama hanya mencari
178
- // duplikat SUBSTRING PERSIS, jadi needle yang unik-persis tapi
179
- // ambigu-fuzzy (mis. "\tfoo" vs " foo") lolos dan blok PERTAMA
180
- // diedit diam-diam — kelas bug yang sama dengan "duplikat diam-diam
181
- // edit blok pertama" yang sudah ditutup di jalur bawah.
182
- //
183
- // flexibleMatch di sini TIDAK memilih target (itu tetap hashline) —
184
- // hanya menjawab "apakah needle ini unik?", supaya kedua jalur
185
- // menjawab pertanyaan yang sama.
186
167
  const first = flexibleMatch(content, oldS)
187
- if (!first) {
188
- // Hashline menemukan, flexibleMatch tidak (atau fuzzy-nya ambigu →
189
- // flexibleMatch sengaja null). Jalur bawah menolak dengan "not
190
- // found"; jalur cepat tidak boleh lebih longgar.
191
- throw new Error(`oldString not found in ${p}`)
192
- }
168
+ if (!first) throw new Error(`oldString not found in ${p}`)
193
169
  if (isAmbiguousMatch(content, oldS, first)) {
194
170
  throw new Error(
195
171
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
196
172
  )
197
173
  }
198
- hashApply = hunk
174
+ return await commitSafeTextEdit(
175
+ realAbs,
176
+ root,
177
+ hunk,
178
+ `edited ${realAbs} (hashline match) (${oldS.length} → ${newS.length} chars)`,
179
+ )
199
180
  }
200
181
  }
201
- if (hashApply !== null) {
202
- if (hashApply.length > LIMITS.WRITE_FILE_MAX_CHARS)
203
- throw new Error(`result too large: ${hashApply.length} chars (max 5M)`)
204
- await atomicWriteText(realAbs, hashApply)
205
- return await appendLspDiagnostics(
206
- realAbs,
207
- hashApply,
208
- `edited ${realAbs} (hashline match) (${oldS.length} → ${newS.length} chars)`,
209
- undefined,
210
- root,
211
- )
212
- }
213
182
  const match = flexibleMatch(content, oldS)
214
183
  if (!match) throw new Error(`oldString not found in ${p}`)
215
-
216
- // ensure uniqueness untuk semua mode (exact/crlf/trimmed/fuzzy) — trimmed/fuzzy
217
- // sebelumnya hanya dicek untuk exact/crlf sehingga duplikat diam-diam edit blok pertama
218
184
  if (isAmbiguousMatch(content, oldS, match)) {
219
185
  throw new Error(
220
186
  `oldString found multiple times in ${p} — provide more surrounding lines to make it unique`,
221
187
  )
222
188
  }
223
-
224
189
  const next = content.slice(0, match.start) + newS + content.slice(match.end)
225
- if (next.length > LIMITS.WRITE_FILE_MAX_CHARS)
226
- throw new Error(`result too large: ${next.length} chars (max 5M)`)
227
- // atomic (O_EXCL + randomUUID tmp)
228
- await atomicWriteText(realAbs, next)
229
190
  const note = match.mode !== "exact" ? ` (${match.mode} match)` : ""
230
- const base = `edited ${realAbs}${note} (${oldS.length} → ${newS.length} chars)`
231
- return await appendLspDiagnostics(realAbs, next, base, undefined, root)
191
+ return await commitSafeTextEdit(
192
+ realAbs,
193
+ root,
194
+ next,
195
+ `edited ${realAbs}${note} (${oldS.length} → ${newS.length} chars)`,
196
+ )
232
197
  },
233
198
  }
package/src/tools/git.ts CHANGED
@@ -337,19 +337,96 @@ export const gitCommitTool: Tool = {
337
337
  const args = ["commit", "--no-verify", "-m", msg]
338
338
  if (files.length === 0 && all === true) args.push("-a")
339
339
  const out = await runGit(args, resolvedCwd, ctx.signal, indexEnv)
340
+ const firstLine = msg.split("\n")[0]?.trim()
341
+ // runGit mengembalikan "(exit 0)" saat stdout+stderr kosong (lihat baris 82).
342
+ const isCleanGitOut = (s: string): boolean => !s || /^\(exit \d+\)$/.test(s)
340
343
  if (/nothing to commit|no changes added/i.test(out)) {
341
344
  try {
342
- const subject = (
343
- await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
344
- ).trim()
345
- if (subject && subject === msg.split("\n")[0]?.trim()) {
346
- const head = await runGit(["log", "--oneline", "-1"], resolvedCwd, ctx.signal).catch(
347
- () => "",
348
- )
349
- return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
345
+ if (files.length > 0) {
346
+ // Hanya klaim "already committed" bila file target bersih sekarang,
347
+ // benar-benar tersentuh di HEAD, DAN subjek commit terakhir atas
348
+ // file tersebut cocok — mencegah false positive saat staging gagal.
349
+ const pending = (
350
+ await runGit(
351
+ ["status", "--porcelain", "--", ...files],
352
+ resolvedCwd,
353
+ ctx.signal,
354
+ ).catch(() => "DIRTY")
355
+ ).trim()
356
+ const inHead = (
357
+ await runGit(
358
+ [
359
+ "--literal-pathspecs",
360
+ "diff-tree",
361
+ "--root",
362
+ "--no-renames",
363
+ "--no-commit-id",
364
+ "--name-only",
365
+ "-r",
366
+ "HEAD",
367
+ "--",
368
+ ...files,
369
+ ],
370
+ resolvedCwd,
371
+ ctx.signal,
372
+ ).catch(() => "")
373
+ ).trim()
374
+ const subject = (
375
+ await runGit(
376
+ ["log", "-1", "--format=%s", "--", ...files],
377
+ resolvedCwd,
378
+ ctx.signal,
379
+ ).catch(() => "")
380
+ ).trim()
381
+ if (
382
+ isCleanGitOut(pending) &&
383
+ !isCleanGitOut(inHead) &&
384
+ subject &&
385
+ subject === firstLine
386
+ ) {
387
+ const head = await runGit(
388
+ ["log", "--oneline", "-1"],
389
+ resolvedCwd,
390
+ ctx.signal,
391
+ ).catch(() => "")
392
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
393
+ }
394
+ } else {
395
+ const trackedDirty = (
396
+ await runGit(
397
+ ["status", "--porcelain", "--untracked-files=no"],
398
+ resolvedCwd,
399
+ ctx.signal,
400
+ ).catch(() => "DIRTY")
401
+ ).trim()
402
+ const subject = (
403
+ await runGit(["log", "-1", "--format=%s"], resolvedCwd, ctx.signal).catch(() => "")
404
+ ).trim()
405
+ if (isCleanGitOut(trackedDirty) && subject && subject === firstLine) {
406
+ const head = await runGit(
407
+ ["log", "--oneline", "-1"],
408
+ resolvedCwd,
409
+ ctx.signal,
410
+ ).catch(() => "")
411
+ return `already committed (retry aman — tanpa commit baru):\n${out}${head ? `\n\nHEAD: ${head}` : ""}`
412
+ }
350
413
  }
351
414
  } catch {}
352
- return `nothing to commit:\n${out}`
415
+ let untrackedHint = ""
416
+ if (files.length === 0 && all === true) {
417
+ const untracked = (
418
+ await runGit(
419
+ ["ls-files", "--others", "--exclude-standard"],
420
+ resolvedCwd,
421
+ ctx.signal,
422
+ ).catch(() => "")
423
+ ).trim()
424
+ if (!isCleanGitOut(untracked)) {
425
+ untrackedHint =
426
+ "\n(note: `all: true` only stages modified tracked files; pass `paths` explicitly to commit untracked files)"
427
+ }
428
+ }
429
+ return `nothing to commit:\n${out}${untrackedHint}`
353
430
  }
354
431
  let indexWarning = ""
355
432
  const newHead = await runGit(
package/src/tools/glob.ts CHANGED
@@ -1,45 +1,8 @@
1
- import { readdir, realpath, stat } from "node:fs/promises"
2
- import { join, relative, resolve } from "node:path"
1
+ import { stat } from "node:fs/promises"
3
2
  import type { Tool } from "#minicore"
4
3
  import { LIMITS } from "../constants.ts"
5
- import { isIgnored, loadIgnoreMatchers } from "../lib/ignore.ts"
6
- import { isPathOutsideRoot, isSensitive } from "../policy/jail.ts"
7
- import { contextUnrestricted, requireToolCwd } from "./context.ts"
8
-
9
- async function walk(
10
- dir: string,
11
- pattern: RegExp,
12
- out: string[],
13
- root: string,
14
- limit: number,
15
- signal: AbortSignal,
16
- ignoreMatchers: ((rel: string) => boolean)[],
17
- relaxed = false,
18
- ) {
19
- if (signal.aborted) throw new Error("aborted")
20
- if (out.length >= limit) return
21
- const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
22
- for (const e of entries) {
23
- if (out.length >= limit) break
24
- if (e.name.startsWith(".") || e.name === "node_modules" || e.name === ".git") continue
25
- const full = join(dir, e.name)
26
- const rel = relative(root, full).replace(/\\/g, "/")
27
- // Hormati .gitignore subset (bukan hard-coded saja).
28
- if (isIgnored(rel, ignoreMatchers)) continue
29
- if (e.isDirectory()) {
30
- await walk(full, pattern, out, root, limit, signal, ignoreMatchers, relaxed)
31
- } else if (pattern.test(rel) || pattern.test(e.name)) {
32
- const real = await realpath(full).catch(() => full)
33
- if (
34
- (!relaxed && isPathOutsideRoot(real, resolve(root))) ||
35
- isSensitive(real) ||
36
- isSensitive(rel)
37
- )
38
- continue
39
- out.push(rel)
40
- }
41
- }
42
- }
4
+ import { loadIgnoreMatchers } from "../lib/ignore.ts"
5
+ import { resolveSearchRoot, walkWorkspaceFiles } from "./context.ts"
43
6
 
44
7
  export function globToRegExp(glob: string): RegExp {
45
8
  // Tangani brace expansion {a,b} tanpa double-escape
@@ -73,24 +36,25 @@ export function globToRegExp(glob: string): RegExp {
73
36
  export const globTool: Tool = {
74
37
  name: "glob",
75
38
  description:
76
- "Search files with a glob pattern (e.g. **/*.ts, src/**/*.js). Returns relative paths, capped at 100 by default. Skips .git, node_modules, and dotfiles.",
39
+ "Search files with a glob pattern (e.g. **/*.ts, src/**/*.js). Returns relative paths, capped at 100 by default. Skips .git, node_modules, and dotfiles by default (set includeDotfiles:true for .github/.eslintrc/etc.).",
77
40
  parameters: {
78
41
  type: "object",
79
42
  properties: {
80
43
  pattern: { type: "string", description: "glob pattern (e.g. **/*.ts)" },
81
44
  cwd: { type: "string", description: "root directory (default: workspace root)" },
82
45
  limit: { type: "number", description: "max results (default 100)" },
46
+ includeDotfiles: {
47
+ type: "boolean",
48
+ description: "include dotfiles/dotdirs like .github or .eslintrc (default false)",
49
+ },
83
50
  },
84
51
  required: ["pattern"],
85
52
  additionalProperties: false,
86
53
  },
87
- async execute({ pattern, cwd, limit }, ctx) {
88
- const sessionRoot = requireToolCwd(ctx)
89
- const relaxed = contextUnrestricted(ctx)
90
- const rawRoot = (cwd as string) ?? "."
91
- const root = resolve(sessionRoot, rawRoot)
92
- if (!relaxed && isPathOutsideRoot(root, sessionRoot))
93
- throw new Error(`cwd outside workspace: ${rawRoot}`)
54
+ async execute({ pattern, cwd, limit, includeDotfiles }, ctx) {
55
+ const { root, rawRoot, relaxed } = resolveSearchRoot(cwd, ctx)
56
+ const st = await stat(root).catch(() => null)
57
+ if (!st?.isDirectory()) return `cwd not found: ${rawRoot}`
94
58
  const rawLim = limit as number | undefined
95
59
  const lim = Number.isFinite(rawLim)
96
60
  ? Math.min(Math.max(Math.floor(rawLim!), 1), LIMITS.SEARCH_MAX_LIMIT)
@@ -98,9 +62,20 @@ export const globTool: Tool = {
98
62
  const re = globToRegExp(pattern as string)
99
63
  const ignoreMatchers = await loadIgnoreMatchers(root)
100
64
  const out: string[] = []
101
- await walk(root, re, out, root, lim, ctx.signal, ignoreMatchers, relaxed)
102
- const st = await stat(root).catch(() => null)
103
- if (!st) return `cwd not found: ${rawRoot}`
65
+ await walkWorkspaceFiles(
66
+ {
67
+ dir: root,
68
+ root,
69
+ signal: ctx.signal,
70
+ ignoreMatchers,
71
+ relaxed,
72
+ includeDotfiles: includeDotfiles === true,
73
+ shouldStop: () => out.length >= lim,
74
+ },
75
+ ({ rel, name }) => {
76
+ if (re.test(rel) || re.test(name)) out.push(rel)
77
+ },
78
+ )
104
79
  if (out.length === 0) return `no files match ${pattern} in ${rawRoot}`
105
80
  return out.slice(0, lim).join("\n")
106
81
  },