minicode-ai 0.14.1 → 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 (79) hide show
  1. package/README.md +1 -1
  2. package/cli/auto-update.ts +32 -2
  3. package/cli/index.ts +10 -2
  4. package/cli/setup.ts +8 -3
  5. package/cli/tui.ts +18 -15
  6. package/docs/OUTPUT_PROTOCOL_SPEC.md +6 -0
  7. package/docs/OUTPUT_RENDERING_SPEC.md +28 -4
  8. package/docs/README.md +2 -2
  9. package/docs/TERMINAL_CONTRACT.md +52 -26
  10. package/docs/getting-started.md +14 -12
  11. package/docs/glossary.md +1 -1
  12. package/docs/mcp-lsp.md +1 -1
  13. package/docs/policy-sandbox.md +7 -1
  14. package/docs/security-model.md +2 -2
  15. package/docs/security.md +7 -1
  16. package/docs/tools.md +4 -4
  17. package/docs/verify-benchmark.md +16 -0
  18. package/package.json +1 -3
  19. package/src/app/mentions.ts +4 -3
  20. package/src/app/session.ts +13 -9
  21. package/src/app/tool-layer.ts +6 -0
  22. package/src/constants.ts +17 -0
  23. package/src/lib/git-hardening.ts +27 -22
  24. package/src/lib/safe-open.ts +73 -19
  25. package/src/lib/trusted-exec.ts +7 -4
  26. package/src/mcp/client.ts +34 -9
  27. package/src/mcp/transport.ts +96 -42
  28. package/src/memory/files.ts +15 -4
  29. package/src/memory/vector.ts +5 -1
  30. package/src/policy/context.ts +21 -13
  31. package/src/policy/tool-contract.ts +4 -10
  32. package/src/policy/update-check.ts +83 -6
  33. package/src/policy/usage.ts +17 -7
  34. package/src/presentation/adapter.ts +64 -2
  35. package/src/presentation/events.ts +6 -0
  36. package/src/presentation/model.ts +1 -0
  37. package/src/presentation/projection.ts +2 -0
  38. package/src/presentation/reducer.ts +1 -0
  39. package/src/providers/anthropic.ts +52 -19
  40. package/src/providers/guards.ts +98 -13
  41. package/src/providers/responses.ts +61 -23
  42. package/src/providers/sse-bounds.ts +170 -0
  43. package/src/repo/repomap.ts +10 -11
  44. package/src/runtime/execution-backend.ts +7 -8
  45. package/src/sandbox/docker.ts +113 -9
  46. package/src/session/checkpoint.ts +9 -2
  47. package/src/session/persistence.ts +5 -2
  48. package/src/session/verification.ts +55 -16
  49. package/src/skills/loader.ts +16 -3
  50. package/src/tools/bash.ts +6 -3
  51. package/src/tools/code_run.ts +6 -5
  52. package/src/tools/context.ts +8 -0
  53. package/src/tools/delete_file.ts +2 -1
  54. package/src/tools/edit.ts +2 -1
  55. package/src/tools/git.ts +128 -54
  56. package/src/tools/glob.ts +2 -1
  57. package/src/tools/grep.ts +31 -6
  58. package/src/tools/lsp.ts +5 -4
  59. package/src/tools/mcp_call.ts +3 -1
  60. package/src/tools/memory.ts +175 -180
  61. package/src/tools/move_file.ts +2 -1
  62. package/src/tools/patch.ts +2 -1
  63. package/src/tools/read_file.ts +94 -1
  64. package/src/tools/read_image.ts +2 -1
  65. package/src/tools/task.ts +2 -1
  66. package/src/tools/todo.ts +4 -5
  67. package/src/tools/web_fetch.ts +28 -12
  68. package/src/tools/web_search.ts +28 -9
  69. package/src/tools/write_file.ts +2 -1
  70. package/src/ui/assistant/simple.ts +72 -3
  71. package/src/ui/i18n/en.ts +3 -0
  72. package/src/ui/i18n/id.ts +3 -0
  73. package/src/ui/render/width.ts +107 -79
  74. package/src/ui/runtime/screen.ts +49 -37
  75. package/src/ui/tui/app.ts +255 -205
  76. package/src/ui/tui/transcript.ts +39 -0
  77. package/CHANGELOG.md +0 -1185
  78. package/docs/PLAN_UIUX_V6.md +0 -209
  79. package/docs/changelog.md +0 -3
@@ -1,13 +1,14 @@
1
1
  import { execFile } from "node:child_process"
2
2
  import { createHash } from "node:crypto"
3
- import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
4
- import { readdir, readFile, stat } from "node:fs/promises"
3
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
4
+ import { readdir } from "node:fs/promises"
5
5
  import { join, relative, resolve } from "node:path"
6
6
  import { fileURLToPath } from "node:url"
7
7
  import { promisify } from "node:util"
8
8
  import { LIMITS, LSP_SYMBOL_KINDS } from "../constants.ts"
9
9
  import { homeDir } from "../lib/db-path.ts"
10
10
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
11
+ import { safeReadFileCapped } from "../lib/safe-open.ts"
11
12
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
12
13
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
13
14
 
@@ -233,10 +234,8 @@ async function readSourceContents(
233
234
  for (const f of files) {
234
235
  try {
235
236
  const abs = resolve(cwd, f)
236
- const st = await stat(abs)
237
- if (!st.isFile() || st.size > MAX_FILE_BYTES) continue
238
- const content = await readFile(abs, "utf8")
239
- out.push({ path: f, content })
237
+ const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
238
+ if (!loaded.truncated) out.push({ path: f, content: loaded.text })
240
239
  } catch {}
241
240
  }
242
241
  return out
@@ -358,15 +357,15 @@ export async function buildRepoMap(
358
357
  // disajikan tanpa baca ulang. Dengan sig isi, cache palsu hanya cocok bila
359
358
  // isinya benar-benar sama — dan bila sama, petanya pun benar. Cache lama
360
359
  // (format mtime) otomatis miss → dibangun ulang sekali, tanpa migrasi.
361
- function signature(files: string[], cwd: string): string {
360
+ async function signature(files: string[], cwd: string): Promise<string> {
362
361
  const h = createHash("sha256")
363
362
  for (const f of files.slice(0, 80)) {
364
363
  try {
365
364
  const abs = resolve(cwd, f)
366
- const st = statSync(abs)
367
- if (!st.isFile() || st.size > MAX_FILE_BYTES) continue
365
+ const loaded = await safeReadFileCapped(abs, cwd, MAX_FILE_BYTES)
366
+ if (loaded.truncated) continue
368
367
  h.update(f)
369
- h.update(readFileSync(abs))
368
+ h.update(loaded.text)
370
369
  } catch {}
371
370
  }
372
371
  return `v2:${h.digest("hex")}`
@@ -412,7 +411,7 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
412
411
  const forceRegex = process.env.MINICODE_REPOMAP === "regex"
413
412
  const files = await listSourceFiles(cwd, MAX_FILES)
414
413
  if (files.length === 0) return ""
415
- const sig = signature(files, cwd)
414
+ const sig = await signature(files, cwd)
416
415
  const cp = cachePath(cwd)
417
416
  // Cache hit → langsung pakai (tanpa LSP, cepat)
418
417
  try {
@@ -16,10 +16,9 @@
16
16
  // - Backend tak membuat executionId (M1); handle `be_*` = namespace backend
17
17
  // sendiri, opaque, non-user-controlled, bukan lifecycle authority.
18
18
  // - Opaque handle: caller tak pernah memegang raw ChildProcess.
19
- // - Sandbox shims membungkus runner existing run-to-completion; kill
20
- // preemptif mid-flight = unsupported yang DINYATAKAN (jujur, sesuai evidence
21
- // code_run: abort menghentikan penungguan, container bisa hidup sampai
22
- // timeout runner). Jangan klaim D untuk container.
19
+ // - Sandbox shims membungkus runner existing run-to-completion. Docker runner
20
+ // meminta daemon menghapus container saat timeout; cancel dari backend tetap
21
+ // belum mengirim signal fisik ke runner. Jangan klaim D untuk container.
23
22
  // - MCP/LSP/background-jobs TIDAK dibungkus di sini (lifecycle berbeda:
24
23
  // closeAll/closeAllLsp tetap pemilik; background = tool scope, detached = M7).
25
24
  // - Security parity: spawn SELALU via sanitizeSpawnEnv + resolveTrustedExecutable
@@ -72,7 +71,7 @@ export interface BackendCapability {
72
71
  * - host: killTree grup/taskkill ADA (bash.ts:96-124); tanpa flag CPU/mem/pids;
73
72
  * network hanya guard; FS hanya jail pre-check (TOCTOU terdokumentasi).
74
73
  * - docker: invocation --cpus/--memory/--pids-limit/--network/--read-only ADA
75
- * (docker.ts:58-87); kill eksplisit container TAK ADA (hanya wrapper SIGKILL).
74
+ * (docker.ts:58-87); timeout meminta daemon menjalankan `docker rm --force`.
76
75
  * - bwrap: --unshare-net/--die-with-parent/--cap-drop/bind ADA, tanpa limit
77
76
  * CPU/mem/pids (os.ts:104-135). seatbelt: deny default + deny network* ADA,
78
77
  * policy = restriksi BUKAN kill guarantee (os.ts:91-98).
@@ -109,10 +108,10 @@ export const BACKEND_CAPABILITIES: Record<BackendKind, BackendCapability> = {
109
108
  network: "SUPPORTED",
110
109
  fs: "SUPPORTED",
111
110
  notes: [
112
- "A: timeout wrapper SIGKILL + close observation (docker.ts:116-127).",
111
+ "A: timeout wrapper meminta daemon remove lalu menunggu close Docker CLI (docker.ts).",
113
112
  "B: DELEGATED_TO_RUNTIME — logical stop diputuskan runtime.",
114
- "C: BEST_EFFORT — kill eksplisit container TAK ADA di invocation; hanya wrapper.",
115
- "D: BEST_EFFORT — close wrapper ≠ bukti container mati; jangan klaim D container.",
113
+ "C: BEST_EFFORT — timeout meminta docker rm --force; kegagalan daemon dilaporkan.",
114
+ "D: BEST_EFFORT — permintaan remove bukan bukti fisik mandiri; jangan klaim D container.",
116
115
  "CPU/mem/PID/net/FS: --cpus/--memory/--pids-limit 32/--network none/--read-only+cap-drop+user (docker.ts:58-87).",
117
116
  ],
118
117
  },
@@ -1,4 +1,5 @@
1
1
  import { spawn, spawnSync } from "node:child_process"
2
+ import { randomUUID } from "node:crypto"
2
3
  import { resolve } from "node:path"
3
4
  import { LIMITS } from "../constants.ts"
4
5
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
@@ -44,6 +45,45 @@ export interface DockerRunOptions {
44
45
  cpus?: number
45
46
  env?: Record<string, string>
46
47
  timeoutMs?: number
48
+ signal?: AbortSignal
49
+ }
50
+
51
+ let dockerSpawnForTest: typeof spawn | null = null
52
+
53
+ /** Seam untuk mensimulasikan lifecycle Docker tanpa daemon dalam tes. */
54
+ export function setDockerSpawnForTest(spawner: typeof spawn | null): void {
55
+ dockerSpawnForTest = spawner
56
+ }
57
+
58
+ function dockerExecutable(): string {
59
+ return dockerSpawnForTest ? "docker" : resolveTrustedExecutable("docker")
60
+ }
61
+
62
+ function spawnDocker(args: string[], env: NodeJS.ProcessEnv) {
63
+ return (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
64
+ stdio: "ignore",
65
+ env,
66
+ })
67
+ }
68
+
69
+ /** Minta daemon menghapus container; timeout membuat kegagalan cleanup eksplisit. */
70
+ function removeContainer(name: string, env: NodeJS.ProcessEnv): Promise<boolean> {
71
+ return new Promise((resolveResult) => {
72
+ let done = false
73
+ const p = spawnDocker(["rm", "--force", name], env)
74
+ const finish = (removed: boolean) => {
75
+ if (done) return
76
+ done = true
77
+ clearTimeout(timer)
78
+ resolveResult(removed)
79
+ }
80
+ const timer = setTimeout(() => {
81
+ p.kill("SIGKILL")
82
+ finish(false)
83
+ }, LIMITS.DOCKER_CLEANUP_TIMEOUT_MS)
84
+ p.on("error", () => finish(false))
85
+ p.on("close", (code) => finish(code === 0))
86
+ })
47
87
  }
48
88
 
49
89
  // Run command di dalam container ephemeral, terisolasi (--network none,
@@ -53,11 +93,17 @@ export function runInDocker(
53
93
  cwd: string,
54
94
  opts: DockerRunOptions = {},
55
95
  ): Promise<{ code: number | null; output: string }> {
96
+ if (opts.signal?.aborted) {
97
+ return Promise.resolve({ code: null, output: "[docker] aborted before container start" })
98
+ }
56
99
  const image = opts.image ?? process.env.MINICODE_SANDBOX_IMAGE ?? "node:22-alpine"
57
100
  const mount = workspaceMount(cwd)
101
+ const containerName = `minicode-${randomUUID()}`
58
102
  const args = [
59
103
  "run",
60
104
  "--rm",
105
+ "--name",
106
+ containerName,
61
107
  "-i",
62
108
  "--read-only",
63
109
  "--cap-drop",
@@ -89,9 +135,10 @@ export function runInDocker(
89
135
  return new Promise((resolveResult) => {
90
136
  // env selalu disanitasi dari hasil merge final — secret (API_KEY/TOKEN/...)
91
137
  // tidak pernah diwarisi container walau caller lupa strip.
92
- const p = spawn(resolveTrustedExecutable("docker"), args, {
138
+ const env = sanitizeSpawnEnv(process.env, opts.env)
139
+ const p = (dockerSpawnForTest ?? spawn)(dockerExecutable(), args, {
93
140
  stdio: ["ignore", "pipe", "pipe"],
94
- env: sanitizeSpawnEnv(process.env, opts.env),
141
+ env,
95
142
  })
96
143
  // Cap buffer saat streaming — output container raksasa tidak menumpuk di RAM.
97
144
  const OUT_CAP = LIMITS.DOCKER_OUTPUT_MAX_CHARS
@@ -113,17 +160,74 @@ export function runInDocker(
113
160
  }
114
161
  p.stdout.on("data", (d) => appendCapped("out", d))
115
162
  p.stderr.on("data", (d) => appendCapped("err", d))
116
- const timeout = opts.timeoutMs ?? LIMITS.DOCKER_TIMEOUT_MS
117
- const t = setTimeout(() => p.kill("SIGKILL"), timeout)
118
- p.on("error", (e) => {
163
+ const timeout =
164
+ typeof opts.timeoutMs === "number" && Number.isFinite(opts.timeoutMs) && opts.timeoutMs > 0
165
+ ? opts.timeoutMs
166
+ : LIMITS.DOCKER_TIMEOUT_MS
167
+ let settled = false
168
+ let closed = false
169
+ let stopReason: "timeout" | "abort" | undefined
170
+ let stopPromise: Promise<boolean> | undefined
171
+ let t: ReturnType<typeof setTimeout>
172
+ const signal = opts.signal
173
+ const finalize = (code: number | null, suffix = "") => {
174
+ if (settled) return
175
+ settled = true
119
176
  clearTimeout(t)
120
- resolveResult({ code: null, output: `[docker] ${e.message}` })
177
+ signal?.removeEventListener("abort", onAbort)
178
+ const marker = truncated ? "\n… [output truncated]" : ""
179
+ const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker + suffix
180
+ resolveResult({ code, output })
181
+ }
182
+ const requestStop = (reason: "timeout" | "abort") => {
183
+ if (stopReason || settled) return
184
+ stopReason = reason
185
+ clearTimeout(t)
186
+ stopPromise = removeContainer(containerName, env).catch(() => false)
187
+ void stopPromise.then((removed) => {
188
+ if (!closed) p.kill("SIGKILL")
189
+ if (closed) {
190
+ const detail = removed
191
+ ? "daemon container removal confirmed"
192
+ : "daemon cleanup unconfirmed"
193
+ const reasonText = reason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
194
+ finalize(null, `\n[docker] ${reasonText}; ${detail}`)
195
+ }
196
+ })
197
+ }
198
+ const onAbort = () => requestStop("abort")
199
+ t = setTimeout(() => requestStop("timeout"), timeout)
200
+ if (signal) {
201
+ signal.addEventListener("abort", onAbort, { once: true })
202
+ if (signal.aborted) requestStop("abort")
203
+ }
204
+ p.on("error", (e) => {
205
+ closed = true
206
+ if (stopReason) {
207
+ void (stopPromise ?? Promise.resolve(false)).then((removed) => {
208
+ const detail = removed
209
+ ? "daemon container removal confirmed"
210
+ : "daemon cleanup unconfirmed"
211
+ finalize(null, `\n[docker] ${stopReason}; ${detail}`)
212
+ })
213
+ } else {
214
+ finalize(null, `[docker] ${e.message}`)
215
+ }
121
216
  })
122
217
  p.on("close", (code) => {
218
+ closed = true
123
219
  clearTimeout(t)
124
- const marker = truncated ? "\n… [output truncated]" : ""
125
- const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
126
- resolveResult({ code, output })
220
+ if (stopReason) {
221
+ void (stopPromise ?? Promise.resolve(false)).then((removed) => {
222
+ const detail = removed
223
+ ? "daemon container removal confirmed"
224
+ : "daemon cleanup unconfirmed"
225
+ const reasonText = stopReason === "timeout" ? `timed out after ${timeout}ms` : "aborted"
226
+ finalize(null, `\n[docker] ${reasonText}; ${detail}`)
227
+ })
228
+ } else {
229
+ finalize(code)
230
+ }
127
231
  })
128
232
  })
129
233
  }
@@ -8,7 +8,7 @@ import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
8
8
  import { sanitizeSessionPart } from "../lib/session-id.ts"
9
9
  import { isPathOutsideRoot } from "../policy/jail.ts"
10
10
  import { appendUndoMarker, loadJournal } from "./journal.ts"
11
- import { diffTrees, ephemeralTree, restoreTree, snapshotTree } from "./shadow-git.ts"
11
+ import { diffTrees, ephemeralTree, isGitRepo, restoreTree, snapshotTree } from "./shadow-git.ts"
12
12
 
13
13
  /** Alias back-compat: satu-satunya sanitizer kini di lib/session-id.ts (F-17). */
14
14
  export function sanitizeSessionId(id: string): string {
@@ -335,9 +335,16 @@ export async function snapshotWorkspace(
335
335
  export async function beginTurnSnapshot(
336
336
  sessionId: string,
337
337
  cwd: string = process.cwd(),
338
- ): Promise<{ mode: "git"; tree: string } | { mode: "files"; snapshots: FileSnapshot[] }> {
338
+ ): Promise<
339
+ | { mode: "git"; tree: string }
340
+ | { mode: "files"; snapshots: FileSnapshot[] }
341
+ | { mode: "unavailable"; reason: "git-snapshot-failed" }
342
+ > {
339
343
  const shadow = await snapshotTree(cwd, sessionId, "pre")
340
344
  if (shadow) return { mode: "git", tree: shadow.tree }
345
+ // Fallback file snapshot dibatasi 200 path. Memakainya saat repo Git gagal
346
+ // membuat snapshot dapat memberi kesan rollback lengkap padahal parsial.
347
+ if (await isGitRepo(cwd)) return { mode: "unavailable", reason: "git-snapshot-failed" }
341
348
  return { mode: "files", snapshots: await snapshotWorkspace(cwd, LIMITS.WORKSPACE_SNAPSHOT_LIMIT) }
342
349
  }
343
350
 
@@ -739,6 +739,9 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
739
739
  const isStr = (k: string): boolean => typeof value[k] === "string"
740
740
  const isNum = (k: string): boolean => typeof value[k] === "number"
741
741
  const isArr = (k: string): boolean => Array.isArray(value[k])
742
+ const validAttemptId =
743
+ value.attemptId === undefined ||
744
+ (Number.isSafeInteger(value.attemptId) && (value.attemptId as number) > 0)
742
745
  if (!isValidParentLink(value.parentLink)) return false
743
746
  switch (value.type) {
744
747
  case "plan.updated":
@@ -778,7 +781,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
778
781
  return true
779
782
  case "model.delta":
780
783
  case "reasoning.delta":
781
- return isStr("delta")
784
+ return isStr("delta") && validAttemptId
782
785
  case "model.completed":
783
786
  case "reasoning.completed":
784
787
  return isStr("text")
@@ -805,7 +808,7 @@ function isValidEventShape(value: Record<string, unknown>): boolean {
805
808
  case "result.produced":
806
809
  return isStr("resultId") && !!value.status
807
810
  case "diagnostic.raised":
808
- return isStr("category") && isStr("message")
811
+ return isStr("category") && isStr("message") && validAttemptId
809
812
  case "consequence.decided":
810
813
  return isStr("verdict") && isStr("failureClass") && isStr("nextAction") && isStr("rationale")
811
814
  case "context.cutoff":
@@ -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)