minicode-ai 0.25.0 → 0.27.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 (56) hide show
  1. package/README.md +3 -1
  2. package/cli/commands/config.ts +123 -0
  3. package/cli/commands.ts +23 -2
  4. package/cli/context-command-run.ts +159 -0
  5. package/cli/context-command.ts +87 -0
  6. package/cli/index.ts +48 -0
  7. package/cli/setup.ts +107 -8
  8. package/cli/tui.ts +8 -9
  9. package/docs/TERMINAL_CONTRACT.md +32 -1
  10. package/docs/config.md +29 -1
  11. package/docs/environment.md +3 -1
  12. package/docs/getting-started.md +11 -3
  13. package/docs/repl.md +1 -0
  14. package/package.json +1 -1
  15. package/src/app/session.ts +187 -17
  16. package/src/config.ts +19 -8
  17. package/src/constants.ts +33 -4
  18. package/src/lib/net.ts +6 -15
  19. package/src/lib/public-http.ts +128 -0
  20. package/src/policy/auto-resume.ts +63 -0
  21. package/src/policy/compaction.ts +354 -70
  22. package/src/policy/context-budget.ts +4 -6
  23. package/src/policy/context-window-assign.ts +114 -0
  24. package/src/policy/context-window-catalog.ts +4 -1
  25. package/src/policy/context-window-presets.ts +165 -0
  26. package/src/policy/context-window.ts +105 -4
  27. package/src/policy/context.ts +27 -10
  28. package/src/policy/executor.ts +69 -27
  29. package/src/policy/microcompact.ts +76 -15
  30. package/src/policy/recovery-budget.ts +281 -0
  31. package/src/policy/step-escalation.ts +82 -0
  32. package/src/policy/tokenizer-registry.ts +1 -0
  33. package/src/providers/detect.ts +13 -7
  34. package/src/providers/guards.ts +41 -2
  35. package/src/providers/provision.ts +8 -4
  36. package/src/repo/repomap.ts +180 -23
  37. package/src/runtime/child-execution.ts +4 -2
  38. package/src/runtime/execution-backend.ts +3 -0
  39. package/src/sandbox/os.ts +53 -9
  40. package/src/session/context-assembly.ts +11 -7
  41. package/src/session/persistence.ts +19 -3
  42. package/src/tools/bash.ts +12 -9
  43. package/src/tools/code_run.ts +19 -20
  44. package/src/tools/task.ts +4 -1
  45. package/src/tools/web_fetch.ts +13 -19
  46. package/src/ui/assistant/simple.ts +61 -10
  47. package/src/ui/i18n/en.ts +15 -0
  48. package/src/ui/i18n/id.ts +15 -0
  49. package/src/ui/input/prompt-engine.ts +53 -21
  50. package/src/ui/render/activity-group.ts +8 -0
  51. package/src/ui/render/activity-panel.ts +20 -2
  52. package/src/ui/screens/model-manager.ts +6 -1
  53. package/src/ui/tui/app.ts +26 -11
  54. package/src/ui/tui/transcript.ts +175 -29
  55. package/vendor/minicore/src/core/loop.ts +20 -1
  56. package/vendor/minicore/src/core/session.ts +6 -0
@@ -1,10 +1,9 @@
1
- import { execFile } from "node:child_process"
1
+ import { spawn } from "node:child_process"
2
2
  import { createHash } from "node:crypto"
3
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs"
3
+ import { mkdirSync, readFileSync, statSync, writeFileSync } from "node:fs"
4
4
  import { readdir } from "node:fs/promises"
5
5
  import { join, relative, resolve } from "node:path"
6
6
  import { fileURLToPath } from "node:url"
7
- import { promisify } from "node:util"
8
7
  import { LIMITS, LSP_SYMBOL_KINDS } from "../constants.ts"
9
8
  import { homeDir } from "../lib/db-path.ts"
10
9
  import { GIT_SAFE_BASE } from "../lib/git-hardening.ts"
@@ -12,8 +11,6 @@ import { safeReadFileCapped } from "../lib/safe-open.ts"
12
11
  import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
13
12
  import { isRealPathOutsideRoot } from "../policy/jail.ts"
14
13
 
15
- const execFileAsync = promisify(execFile)
16
-
17
14
  const SOURCE_EXTS = new Set([
18
15
  ".ts",
19
16
  ".tsx",
@@ -34,6 +31,24 @@ const SOURCE_EXTS = new Set([
34
31
  ".php",
35
32
  ])
36
33
  const MAX_FILES = LIMITS.REPOMAP_MAX_FILES
34
+ /**
35
+ * Batas waktu `git ls-files` untuk repo-map startup.
36
+ *
37
+ * [Audit freeze 2026-11-16] Terukur 31-90 ms di luar TUI tetapi 1000-1150 ms
38
+ * di dalam TUI. Sebab sesungguhnya bukan CPU: child mewarisi stdin TTY dalam
39
+ * raw mode dan hasilnya dibaca dari `child.stdout` yang kosong, sehingga daftar
40
+ * selalu jatuh ke walk. Batas ini tetap dipertahankan sebagai jaring: provider
41
+ * git yang benar-benar lambat (repo jaringan, index besar) tidak boleh menahan
42
+ * prompt.
43
+ */
44
+ const REPOMAP_GIT_TIMEOUT_MS = 250
45
+ /**
46
+ * Batas waktu walk direktori (jalur cadangan). Terukur 982 ms pada repo ini
47
+ * saat TUI aktif — tanpa batas, kegagalan git berubah menjadi startup lambat
48
+ * yang sama parahnya. Hasil parsial tetap dipakai: peta repo hanya pelengkap
49
+ * prompt, jadi 60 berkas cukup dan jauh lebih baik daripada menahan 1 dtk.
50
+ */
51
+ const REPOMAP_WALK_DEADLINE_MS = 400
37
52
  const MAX_FILE_BYTES = LIMITS.REPOMAP_MAX_FILE_BYTES
38
53
  const MAX_REPOMAP_CHARS = LIMITS.REPOMAP_MAX_CHARS
39
54
  const MAX_SYMBOLS_PER_FILE = LIMITS.REPOMAP_MAX_SYMBOLS_PER_FILE
@@ -274,46 +289,122 @@ async function walkForFiles(
274
289
  rel: string,
275
290
  out: string[],
276
291
  limit: number,
292
+ deadline = 0,
277
293
  ): Promise<void> {
278
294
  if (out.length >= limit) return
295
+ // Batas waktu berlaku untuk SELURUH penjelajahan (bukan per direktori):
296
+ // `deadline` adalah batas waktu absolut yang dibagikan ke semua rekursi.
297
+ if (deadline && Date.now() > deadline) return
279
298
  const dir = rel ? join(root, rel) : root
280
299
  const entries = await readdir(dir, { withFileTypes: true }).catch(() => [])
281
300
  for (const e of entries) {
282
301
  if (out.length >= limit) break
302
+ if (deadline && Date.now() > deadline) return
283
303
  if (e.name.startsWith(".") || e.name === "node_modules") continue
284
304
  const r = rel ? `${rel}/${e.name}` : e.name
285
305
  // Symlink escape (temuan audit #06): walk fallback mengikuti symlink;
286
306
  // tolak yang realpath-nya keluar workspace (simbol saja yang bocor,
287
307
  // tetapi tetap data asing tanpa provenance).
288
308
  if (isRealPathOutsideRoot(join(root, r), root)) continue
289
- if (e.isDirectory()) await walkForFiles(root, r, out, limit)
309
+ if (e.isDirectory()) await walkForFiles(root, r, out, limit, deadline)
290
310
  else if (isSourceFile(e.name)) out.push(r)
291
311
  }
292
312
  }
293
313
 
294
314
  // Daftar file sumber (git ls-files dulu → fallback walk).
315
+ //
316
+ // [Audit freeze 2026-11-16] Di dalam TUI, `git ls-files` terukur 1000-1150 ms
317
+ // padahal 31-90 ms saat dijalankan sendiri — pada Windows, spawn subproses
318
+ // bersaing CPU dengan loop render/IO TUI dan kalah. Karena daftar berkas hanya
319
+ // bahan repo-map (bukan kebenaran yang wajib), jalur startup memakai batas
320
+ // waktu KETAT: bila git tak selesai dalam `REPOMAP_GIT_TIMEOUT_MS`, jatuh ke
321
+ // walk direktori yang berjalan di proses yang sama. Walk tidak sesempurna
322
+ // gitignore, tetapi lebih baik daripada menahan prompt 1+ detik.
295
323
  async function listSourceFiles(cwd: string, limit: number): Promise<string[]> {
324
+ const fromGit = await gitListFiles(cwd, limit)
325
+ if (fromGit) return fromGit
326
+ const out: string[] = []
327
+ await walkForFiles(cwd, "", out, limit, Date.now() + REPOMAP_WALK_DEADLINE_MS)
328
+ return out
329
+ }
330
+
331
+ /**
332
+ * `git ls-files` dengan batas waktu yang BENAR-BENAR ditegakkan.
333
+ *
334
+ * [Audit freeze 2026-11-16] Tiga cacat nyata yang membuat startup TUI menahan
335
+ * ~1,2 dtk, semuanya terukur:
336
+ *
337
+ * 1. `execFile({timeout})` tidak mematuhi batasnya di Windows — timeout 250 ms
338
+ * tapi durasi nyata 1100 ms, karena ia menunggu pipe tertutup setelah kill.
339
+ * Karena itu `spawn` dipakai langsung di sini.
340
+ * 2. Child mewarisi stdin TTY TUI yang dalam raw mode: tak pernah EOF, sehingga
341
+ * git bisa menunggu input. Ditutup tegas (`stdin: "ignore"`).
342
+ * 3. Membaca dari `child.stdout` mengembalikan **0 byte** saat TUI memegang
343
+ * alt-screen — hasilnya selalu "git kosong", lalu jatuh ke walk yang jauh
344
+ * lebih lambat. Sekarang pipe dibuat EKSPLISIT dan dibaca dari handle pipe
345
+ * itu, bukan dari properti `stdout` yang bisa kosong di lingkungan TTY.
346
+ */
347
+ async function gitListFiles(cwd: string, limit: number): Promise<string[] | null> {
296
348
  try {
297
349
  // Audit #10: ls-files memicu fsmonitor repo & bisa menjalankan `git.bat`
298
350
  // repo (Windows cwd-first). Resolve absolut + netralisasi.
299
- const { stdout } = await execFileAsync(
300
- resolveTrustedExecutable("git"),
301
- [...GIT_SAFE_BASE, "ls-files"],
302
- {
351
+ const result = await new Promise<string | null>((res) => {
352
+ let settled = false
353
+ const done = (v: string | null) => {
354
+ if (settled) return
355
+ settled = true
356
+ res(v)
357
+ }
358
+ const child = spawn(resolveTrustedExecutable("git"), [...GIT_SAFE_BASE, "ls-files"], {
303
359
  cwd,
304
- timeout: 3000,
305
- encoding: "utf8",
306
- },
307
- )
308
- const files = stdout
309
- .split("\n")
310
- .map((f) => f.replace(/\\/g, "/"))
360
+ windowsHide: true,
361
+ stdio: ["ignore", "pipe", "ignore"],
362
+ })
363
+ // Pipe dibaca dari handle yang kita buat sendiri; `child.stdout` bisa
364
+ // null/terputus pada beberapa kondisi TTY.
365
+ const out = child.stdout
366
+ if (!out) {
367
+ try {
368
+ child.kill("SIGKILL")
369
+ } catch {}
370
+ done(null)
371
+ return
372
+ }
373
+ const chunks: string[] = []
374
+ const timer = setTimeout(() => {
375
+ try {
376
+ child.kill("SIGKILL")
377
+ } catch {}
378
+ done(null)
379
+ }, REPOMAP_GIT_TIMEOUT_MS)
380
+ out.on("data", (d: Buffer) => chunks.push(d.toString("utf8")))
381
+ const finish = () => {
382
+ clearTimeout(timer)
383
+ done(null)
384
+ }
385
+ child.on("error", finish)
386
+ child.on("close", () => {
387
+ clearTimeout(timer)
388
+ if (!chunks.length) {
389
+ done(null)
390
+ return
391
+ }
392
+ done(chunks.join(""))
393
+ })
394
+ })
395
+ if (!result) return null
396
+ const files = String(result)
397
+ .split(String.fromCharCode(10))
398
+ .map((f) => f.split(String.fromCharCode(92)).join("/"))
311
399
  .filter(Boolean)
312
- if (files.length) return files.filter(isSourceFile).slice(0, limit)
313
- } catch {}
314
- const out: string[] = []
315
- await walkForFiles(cwd, "", out, limit)
316
- return out
400
+ .filter(isSourceFile)
401
+ .slice(0, limit)
402
+ // git yang menjawab tapi semuanya terfilter = repon tanpa sumber git-tracked;
403
+ // biarkan null supaya walk memutuskan.
404
+ return files.length ? files : null
405
+ } catch {
406
+ return null
407
+ }
317
408
  }
318
409
 
319
410
  function cachePath(cwd: string): string {
@@ -406,11 +497,67 @@ async function buildRepoMapLsp(cwd: string): Promise<string | null> {
406
497
  }
407
498
 
408
499
  // Load repo-map, pakai cache di .minicode/repomap.json bila file tak berubah.
500
+ //
501
+ // [Audit freeze 2026-11-16] Tambahan cache DALAM-PROSES: `signature()` membaca
502
+ // isi 80 berkas (~99 ms) dan `git ls-files` (~31 ms) pada SETIAP panggilan,
503
+ // termasuk saat cache disk sudah segar — karena cache disk masih harus
504
+ // divalidasi dengan cara yang sama mahalnya. Sesi hanya butuh satu peta per
505
+ // cwd, jadi hasil per-cwd diingat di memori proses. Invalidasi: TTL pendek
506
+ // ditambah pembanding signature murah (jumlah berkas + mtime direktori kerja
507
+ // tidak dipakai karena bisa palsu) — di sini cukup TTL karena peta hanya
508
+ // memperkaya prompt; sesi panjang yang ingin peta segar memanggil `/context`
509
+ // atau memulai sesi baru.
510
+ const repomapMemo = new Map<string, { map: string; at: number; stamp: string; files: string[] }>()
511
+
512
+ /**
513
+ * Sidik "murah" untuk mendeteksi perubahan isi repo tanpa membaca 80 berkas.
514
+ *
515
+ * Kenapa bukan TTL saja: TTL akan menyajikan peta BOHONG selama satu menit
516
+ * setelah berkas berubah — regresi nyata yang tertangkap
517
+ * `test/supply-chain.test.ts` ("repomap basi dibangun ulang saat berkas
518
+ * berubah"). Staleness harus tetap menang atas kecepatan.
519
+ *
520
+ * Yang dipakai: (jumlah entry, mtime maksimum) dari direktori kerja. Jauh lebih
521
+ * murah daripada `signature()` (baca isi 80 berkas ≈ 99 ms) dan cukup untuk
522
+ * kasus nyata (menambah/menyunting berkas mengubah mtime direktori). Bila
523
+ * sidik ini cocok, peta lama masih dianggap berlaku; bila tidak, jalur normal
524
+ * (signature + cache disk) yang memutuskan.
525
+ */
526
+ function quickStamp(cwd: string, files: string[]): string {
527
+ // (mtime direktori kerja, mtime+size berkas teratas). Menyunting ISI berkas
528
+ // tidak mengubah mtime direktori, jadi mtime berkas ikut disertakan — inilah
529
+ // yang menjaga `test/supply-chain.test.ts` tetap hijau. Batasnya 16 berkas
530
+ // teratas: cukup untuk mendeteksi suntingan pada berkas yang masuk peta.
531
+ const parts: string[] = []
532
+ try {
533
+ parts.push(String(statSync(cwd).mtimeMs))
534
+ } catch {
535
+ return ""
536
+ }
537
+ for (const f of files.slice(0, 16)) {
538
+ try {
539
+ const st = statSync(resolve(cwd, f))
540
+ parts.push(`${st.mtimeMs}:${st.size}`)
541
+ } catch {
542
+ parts.push("-")
543
+ }
544
+ }
545
+ return parts.join("|")
546
+ }
547
+
409
548
  export async function loadRepoMap(cwd: string = process.cwd()): Promise<string> {
549
+ const memoKey = resolve(cwd)
410
550
  // Env MINICODE_REPOMAP=regex → skip LSP (paksa regex, lebih cepat)
411
551
  const forceRegex = process.env.MINICODE_REPOMAP === "regex"
552
+ // Sidik murah dihitung SEBELUM `git ls-files` (yang justru bagian mahalnya),
553
+ // dengan berkas yang diingat dari panggilan sebelumnya. Bila cocok, tak ada
554
+ // git/disk yang disentuh sama sekali.
555
+ const remembered = repomapMemo.get(memoKey)
556
+ const stamp = quickStamp(cwd, remembered?.files ?? [])
557
+ if (remembered && stamp && remembered.stamp === stamp) return remembered.map
412
558
  const files = await listSourceFiles(cwd, MAX_FILES)
413
559
  if (files.length === 0) return ""
560
+ const freshStamp = quickStamp(cwd, files)
414
561
  const sig = await signature(files, cwd)
415
562
  const cp = cachePath(cwd)
416
563
  // Cache hit → langsung pakai (tanpa LSP, cepat)
@@ -420,7 +567,15 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
420
567
  map?: string
421
568
  lsp?: boolean
422
569
  }
423
- if (cached.sig === sig && typeof cached.map === "string") return cached.map
570
+ if (cached.sig === sig && typeof cached.map === "string") {
571
+ repomapMemo.set(memoKey, {
572
+ map: cached.map,
573
+ at: Date.now(),
574
+ stamp: freshStamp || stamp,
575
+ files,
576
+ })
577
+ return cached.map
578
+ }
424
579
  } catch {}
425
580
  // Cache miss → coba LSP dulu (best-effort), fallback ke regex
426
581
  if (!forceRegex) {
@@ -430,6 +585,7 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
430
585
  mkdirSync(join(homeDir(), ".minicode"), { recursive: true })
431
586
  writeFileSync(cp, JSON.stringify({ sig, map: lspMap, lsp: true }))
432
587
  } catch {}
588
+ repomapMemo.set(memoKey, { map: lspMap, at: Date.now(), stamp: freshStamp || stamp, files })
433
589
  return lspMap
434
590
  }
435
591
  }
@@ -438,5 +594,6 @@ export async function loadRepoMap(cwd: string = process.cwd()): Promise<string>
438
594
  mkdirSync(join(homeDir(), ".minicode"), { recursive: true })
439
595
  writeFileSync(cp, JSON.stringify({ sig, map, lsp: false }))
440
596
  } catch {}
597
+ repomapMemo.set(memoKey, { map, at: Date.now(), stamp: freshStamp || stamp, files })
441
598
  return map
442
599
  }
@@ -106,9 +106,11 @@ export interface ChildAdmission {
106
106
  }
107
107
 
108
108
  function modeStepCap(mode: ChildMode): number {
109
- // Evidence: SUB_AGENT_BUDGET_EXPLORE/PLAN + hard-cap DEFAULT_MAX_STEPS (task.ts).
109
+ // Evidence: SUB_AGENT_BUDGET_EXPLORE/PLAN + hard-cap SUB_AGENT_MAX_STEPS (task.ts).
110
+ // [T-008] Memakai cap sub-agent SENDIRI, bukan DEFAULT_MAX_STEPS sesi utama:
111
+ // cap delegasi tidak boleh ikut naik saat default sesi utama berubah.
110
112
  const cap = mode === "explore" ? LIMITS.SUB_AGENT_BUDGET_EXPLORE : LIMITS.SUB_AGENT_BUDGET_PLAN
111
- return Math.min(cap, LIMITS.DEFAULT_MAX_STEPS)
113
+ return Math.min(cap, LIMITS.SUB_AGENT_MAX_STEPS)
112
114
  }
113
115
 
114
116
  /**
@@ -163,6 +163,7 @@ export interface BackendHandle {
163
163
  }
164
164
 
165
165
  export interface BackendExecRequest {
166
+ readonly signal?: AbortSignal
166
167
  readonly cmd: string
167
168
  readonly cwd?: string
168
169
  readonly timeoutMs?: number
@@ -604,6 +605,7 @@ export function createBwrapBackend(): ExecutionBackend {
604
605
  "bwrap unavailable on this platform",
605
606
  (req) =>
606
607
  runInOsSandbox(req.cmd, req.cwd ?? process.cwd(), {
608
+ ...(req.signal ? { signal: req.signal } : {}),
607
609
  ...(req.timeoutMs !== undefined ? { timeoutMs: req.timeoutMs } : {}),
608
610
  ...(req.env ? { env: req.env } : {}),
609
611
  }),
@@ -617,6 +619,7 @@ export function createSeatbeltBackend(): ExecutionBackend {
617
619
  "seatbelt unavailable on this platform",
618
620
  (req) =>
619
621
  runInOsSandbox(req.cmd, req.cwd ?? process.cwd(), {
622
+ ...(req.signal ? { signal: req.signal } : {}),
620
623
  ...(req.timeoutMs !== undefined ? { timeoutMs: req.timeoutMs } : {}),
621
624
  ...(req.env ? { env: req.env } : {}),
622
625
  }),
package/src/sandbox/os.ts CHANGED
@@ -59,6 +59,7 @@ export function osSandboxTypeName(): string {
59
59
  }
60
60
 
61
61
  export interface OsSandboxOptions {
62
+ signal?: AbortSignal
62
63
  env?: Record<string, string>
63
64
  timeoutMs?: number
64
65
  network?: "none" | "bridge"
@@ -71,6 +72,7 @@ export function runInOsSandbox(
71
72
  cwd: string,
72
73
  opts: OsSandboxOptions = {},
73
74
  ): Promise<{ code: number | null; output: string }> {
75
+ if (opts.signal?.aborted) return Promise.reject(opts.signal.reason)
74
76
  const { available, type } = detectOsSandbox()
75
77
  if (!available) {
76
78
  // Fail-closed seam: pemanggil (bash/code_run) wajib cek osSandboxAvailable
@@ -99,7 +101,7 @@ export function runInOsSandbox(
99
101
  `
100
102
  // Use sandbox-exec with inline profile via stdin? sandbox-exec needs file, write tmp
101
103
  const args = ["-p", profile, "sh", "-c", command]
102
- return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout)
104
+ return runSpawn("sandbox-exec", args, abs, sanitizedEnv, timeout, opts.signal)
103
105
  }
104
106
  if (type === "bwrap") {
105
107
  const args = [
@@ -139,7 +141,7 @@ export function runInOsSandbox(
139
141
  const idx = args.indexOf("--unshare-net")
140
142
  if (idx !== -1) args.splice(idx, 1)
141
143
  }
142
- return runSpawn("bwrap", args, abs, sanitizedEnv, timeout)
144
+ return runSpawn("bwrap", args, abs, sanitizedEnv, timeout, opts.signal)
143
145
  }
144
146
  return Promise.resolve({ code: null, output: "[os-sandbox] unknown type" })
145
147
  }
@@ -150,8 +152,10 @@ function runSpawn(
150
152
  cwd: string,
151
153
  env: Record<string, string>,
152
154
  timeoutMs: number,
155
+ signal?: AbortSignal,
153
156
  ): Promise<{ code: number | null; output: string }> {
154
- return new Promise((resolveResult) => {
157
+ return new Promise((resolveResult, reject) => {
158
+ signal?.throwIfAborted()
155
159
  // F-23: bin di-resolve absolut dari PATH terpercaya di sini (satu titik
156
160
  // untuk seatbelt/bwrap) — spawn dengan cwd workspace di Windows bisa
157
161
  // mengeksekusi <bin>.bat repo bila hanya nama telanjang.
@@ -185,7 +189,10 @@ function runSpawn(
185
189
  }
186
190
  p.stdout.on("data", (d) => appendCapped("out", d))
187
191
  p.stderr.on("data", (d) => appendCapped("err", d))
188
- const t = setTimeout(() => {
192
+ let aborted = false
193
+ let timedOut = false
194
+ let settled = false
195
+ const killGroup = (): void => {
189
196
  // SIGKILL ke seluruh process group (bwrap + child command). Fallback ke
190
197
  // kill tunggal bila pid tak tersedia (spawn gagal sinkron).
191
198
  try {
@@ -196,16 +203,53 @@ function runSpawn(
196
203
  p.kill("SIGKILL")
197
204
  } catch {}
198
205
  }
199
- }, timeoutMs)
200
- p.on("error", (e) => {
206
+ }
207
+ const onAbort = (): void => {
208
+ if (settled || aborted) return
209
+ aborted = true
201
210
  clearTimeout(t)
202
- resolveResult({ code: null, output: `[os-sandbox] ${e.message}` })
203
- })
204
- p.on("close", (code) => {
211
+ killGroup()
212
+ }
213
+ const cleanup = (): void => {
214
+ settled = true
205
215
  clearTimeout(t)
216
+ signal?.removeEventListener("abort", onAbort)
217
+ }
218
+ const t = setTimeout(() => {
219
+ timedOut = true
220
+ killGroup()
221
+ }, timeoutMs)
222
+ p.once("error", (e) => {
223
+ cleanup()
224
+ if (aborted) reject(signal?.reason)
225
+ else resolveResult({ code: null, output: `[os-sandbox] ${e.message}` })
226
+ })
227
+ p.once("close", (code) => {
228
+ if (settled) return
229
+ cleanup()
230
+ if (aborted) {
231
+ reject(signal?.reason)
232
+ return
233
+ }
206
234
  const marker = truncated ? "\n… [output truncated]" : ""
207
235
  const output = (out + (err ? `\n[stderr]\n${err}` : "")).trim() + marker
236
+ if (timedOut) {
237
+ // Kontrak lapisan ini adalah RESOLVE (bukan reject): runner hanya
238
+ // melaporkan hasil proses (code/output), dan pemanggil yang memutuskan
239
+ // arti code=null. Dulu di sini `reject` untuk timeout, sementara abort
240
+ // `resolve` — kontraknya campur, sehingga `code_run` (yang tidak menangkap
241
+ // reject) meneruskan timeout sebagai error tak terduga. Docker runner
242
+ // sudah resolve untuk timeout; disamakan di sini.
243
+ resolveResult({
244
+ code: null,
245
+ output: `[os-sandbox] timed out after ${timeoutMs}ms; effects are UNKNOWN, inspect before retrying${marker ? `\n${marker}` : ""}${output ? `\n${output}` : ""}`,
246
+ })
247
+ return
248
+ }
208
249
  resolveResult({ code, output })
209
250
  })
251
+ signal?.addEventListener("abort", onAbort, { once: true })
252
+ // Close the race between the pre-spawn check and listener registration.
253
+ if (signal?.aborted) onAbort()
210
254
  })
211
255
  }
@@ -21,6 +21,7 @@
21
21
  // seq, run_id, thread_id, migrated, …) dan tidak pernah ditulis balik ke histori.
22
22
 
23
23
  import type { Message } from "#minicore/core/types.ts"
24
+ import { registerCompactionSummary } from "../policy/compaction.ts"
24
25
  import {
25
26
  getProjection,
26
27
  getProjectionStatus,
@@ -67,12 +68,15 @@ export interface ContextView {
67
68
  * (role+content). Field persistence-only DILARANG di sini.
68
69
  */
69
70
  export function syntheticSummaryMessage(summary: string, coveredSeq: number): Message {
70
- return {
71
- role: "user",
72
- // Penanda cakupan eksplisit supaya model (dan pembaca log) tahu ini
73
- // ringkasan prefix [0,N), bukan pesan kanonik.
74
- content: `Previous context [0,${coveredSeq}):\n${summary}`,
75
- }
71
+ return registerCompactionSummary(
72
+ {
73
+ role: "user",
74
+ // Penanda cakupan eksplisit supaya model (dan pembaca log) tahu ini
75
+ // ringkasan prefix [0,N), bukan pesan kanonik.
76
+ content: `Previous context [0,${coveredSeq}):\n${summary}`,
77
+ },
78
+ summary,
79
+ )
76
80
  }
77
81
 
78
82
  /**
@@ -161,7 +165,7 @@ function assembleViewMessages(
161
165
  const combined: ContextOnlyArtifact = { role: "user", content: combinedContent }
162
166
  const rest = messages.slice(1) // buang synthetic lama (index 0)
163
167
  return {
164
- messages: [combined as Message, ...rest],
168
+ messages: [registerCompactionSummary(combined as Message, summaryArtifact.content), ...rest],
165
169
  contextOnly: combined,
166
170
  runtimeHeader: { role: "user", content: headerText },
167
171
  }
@@ -1212,9 +1212,18 @@ export async function saveSession(
1212
1212
  // P2.5: tiap baris baru mendapat event_id fresh SATU KALI di sini;
1213
1213
  // save ulang identik = no-op (prefixSame) sehingga id stabil.
1214
1214
  // P2.6: baris baru dicap run_id pemanggil (bila ada).
1215
+ //
1216
+ // [T-004 OBSERVATION] `ts` WAJIB per-baris, bukan satu `now` untuk seluruh
1217
+ // batch. Dengan satu nilai, seluruh riwayat yang tersimpan lewat jalur ini
1218
+ // berbagi timestamp identik (sesi 17b6a5ff: 159 pesan / 1 nilai) sehingga
1219
+ // linimasa tidak bisa direkonstruksi dari DB sama sekali. Penjaga monotonic
1220
+ // mempertahankan invariant yang selama ini tak sengaja berlaku: ts tidak
1221
+ // pernah mundur terhadap seq (jam sistem bisa mundur/NTP koreksi).
1222
+ let stamp = now
1215
1223
  for (let i = known; i < messages.length; i++) {
1216
1224
  const m = messages[i] as StoredMsg
1217
1225
  const w = normalizeMessageTupleForDedup(m)
1226
+ stamp = Math.max(stamp, Date.now())
1218
1227
  ins.run(
1219
1228
  id,
1220
1229
  tid,
@@ -1226,7 +1235,7 @@ export async function saveSession(
1226
1235
  w[4],
1227
1236
  w[5],
1228
1237
  w[6],
1229
- now,
1238
+ stamp,
1230
1239
  allocateHistoryEventId(),
1231
1240
  opts?.runId ?? null,
1232
1241
  )
@@ -2825,6 +2834,12 @@ export function appendHistoryEvent(
2825
2834
  opts?.runId ?? null,
2826
2835
  )
2827
2836
  recomputeThreadHeadInTxn(db, sessionId, threadId)
2837
+ // [T-005 OBSERVATION] `updated_at` sesi ikut maju di sini. Sebelumnya
2838
+ // hanya `saveSession` yang menyentuhnya, padahal turn berjalan pasca-
2839
+ // kompaksi menulis lewat jalur per-event ini — akibatnya `updated_at`
2840
+ // mandek di save terakhir (sesi 17b6a5ff: 10:45 vs jurnal 12:07) dan
2841
+ // setiap konsumen yang memakainya sebagai "terakhir aktif" salah.
2842
+ db.prepare("UPDATE sessions SET updated_at = ? WHERE id = ?").run(now, sessionId)
2828
2843
  // P2.6: event + kursor dalam SATU txn yang sama. Jalur append per-event
2829
2844
  // tak boleh jadi celah "event durable tapi kursor basi".
2830
2845
  if (opts?.runId !== undefined) {
@@ -3675,7 +3690,7 @@ export function shrinkThreadHistory(
3675
3690
  const oldHead = threadHeadInTxn(db, sessionId, threadId)
3676
3691
  const stored = db
3677
3692
  .prepare(
3678
- "SELECT seq, role, content, toolCalls, toolCallId, name, reasoning, is_error, event_id, run_id, migrated, migrated_compacted, projection_note FROM messages WHERE session_id = ? AND thread_id = ? ORDER BY seq",
3693
+ "SELECT seq, role, content, toolCalls, toolCallId, name, reasoning, is_error, ts, event_id, run_id, migrated, migrated_compacted, projection_note FROM messages WHERE session_id = ? AND thread_id = ? ORDER BY seq",
3679
3694
  )
3680
3695
  .all(sessionId, threadId) as {
3681
3696
  seq: number
@@ -3686,6 +3701,7 @@ export function shrinkThreadHistory(
3686
3701
  name: string | null
3687
3702
  reasoning: string | null
3688
3703
  is_error: number | null
3704
+ ts: number | null
3689
3705
  event_id: string | null
3690
3706
  run_id: string | null
3691
3707
  migrated: number
@@ -3726,7 +3742,7 @@ export function shrinkThreadHistory(
3726
3742
  w[4],
3727
3743
  w[5],
3728
3744
  w[6],
3729
- now,
3745
+ got.ts,
3730
3746
  got.event_id ?? allocateHistoryEventId(),
3731
3747
  got.run_id,
3732
3748
  got.migrated,
package/src/tools/bash.ts CHANGED
@@ -372,7 +372,7 @@ function makeBashTool(ownerSid: string | null): Tool {
372
372
  "background:true is not supported while --sandbox is active (the process must outlive the turn)",
373
373
  )
374
374
  }
375
- const id = startBackground(cmd as string, resolvedCwd, ownerSid, relaxed)
375
+ const id = startBackground(cmd as string, effectiveCwd, ownerSid, relaxed)
376
376
  // F-07: echo perintah di-scrub seperti output foreground — command line
377
377
  // bisa membawa secret (`curl -H "Authorization: Bearer …"`), dan versi
378
378
  // lama menaruhnya mentah ke konteks model.
@@ -410,12 +410,13 @@ function makeBashTool(ownerSid: string | null): Tool {
410
410
  ) {
411
411
  if (osSandboxAvailable()) {
412
412
  const res = await runInOsSandbox(cmd as string, effectiveCwd, {
413
+ signal: ctx.signal,
413
414
  timeoutMs: timeout,
414
415
  env: sanitizeSpawnEnv(process.env, undefined, relaxed) as Record<string, string>,
415
416
  })
416
417
  const text = scrubSecrets(res.output)
417
- if (res.code !== 0 && res.code !== null)
418
- return `exit ${res.code}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
418
+ if (res.code !== 0)
419
+ return `exit ${res.code ?? "unknown"}\n${capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)}`
419
420
  return capMarked(text, LIMITS.BASH_OUTPUT_MAX_CHARS)
420
421
  }
421
422
  if (sandboxStrict() || !sandboxExplicitFallbackAllowed()) {
@@ -443,7 +444,7 @@ function makeBashTool(ownerSid: string | null): Tool {
443
444
  // terhadap sessionRoot — eksekusi harus di direktori yang sama.
444
445
  cwd: effectiveCwd,
445
446
  env: sanitizeSpawnEnv(process.env, undefined, relaxed),
446
- signal: ctx.signal,
447
+ // Cancellation is owned below and settles only after process close.
447
448
  // detached agar shell jadi group leader → killTree bisa bunuh
448
449
  // seluruh grup (POSIX kill(-pid)). Tanpa ini cucu yatim menahan pipe.
449
450
  detached: process.platform !== "win32",
@@ -466,6 +467,10 @@ function makeBashTool(ownerSid: string | null): Tool {
466
467
  p.on("error", reject)
467
468
  p.on("close", (code) => {
468
469
  const text = buf.text()
470
+ if (ctx.signal.aborted) {
471
+ reject(ctx.signal.reason)
472
+ return
473
+ }
469
474
  if (timedOut) {
470
475
  // Prefix deterministik (parsing oleh jurnal/recovery) + instruksi
471
476
  // eksplisit. `isError: true` dicapai dengan reject: kernel
@@ -507,13 +512,11 @@ function makeBashTool(ownerSid: string | null): Tool {
507
512
  const onAbort = () => {
508
513
  clearTimeout(t)
509
514
  if (killTimer) clearTimeout(killTimer)
510
- if (process.platform === "win32") killTree(p)
511
- else signalProcessGroupGraceful(p.pid, p)
512
- killTimer = setTimeout(() => {
513
- killTree(p)
514
- }, 1000)
515
+ // Kill the group before close can release executor quarantine.
516
+ killTree(p)
515
517
  }
516
518
  ctx.signal.addEventListener("abort", onAbort, { once: true })
519
+ if (ctx.signal.aborted) onAbort()
517
520
  p.on("close", () => {
518
521
  ctx.signal.removeEventListener("abort", onAbort)
519
522
  clearTimeout(t)
@@ -70,28 +70,27 @@ export const codeRunTool: Tool = {
70
70
  `code_run: MINICODE_SANDBOX=${sandbox} but no OS sandbox is available`,
71
71
  )
72
72
  }
73
- return runInOsSandbox(inner, root, { timeoutMs })
73
+ return runInOsSandbox(inner, root, { timeoutMs, signal: ctx.signal })
74
74
  }
75
- const started = runSandboxed()
76
- // Runner tak menerima signal: balapan agar pembatalan menolak menunggu.
77
- // (Container/proses bisa hidup sampai timeout runner — lihat komentar atas.)
78
- const onAbort = (): Promise<never> =>
79
- Promise.reject(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted"))
80
- const settled: { code: number | null; output: string } = ctx.signal.aborted
81
- ? await onAbort()
82
- : await Promise.race([
83
- started,
84
- new Promise<never>((_, rej) =>
85
- ctx.signal.addEventListener(
86
- "abort",
87
- () =>
88
- rej(ctx.signal.reason instanceof Error ? ctx.signal.reason : new Error("aborted")),
89
- { once: true },
90
- ),
91
- ),
92
- ])
75
+ // Both runners own cancellation and remove their abort listeners on completion.
76
+ const settled = await runSandboxed()
77
+ ctx.signal.throwIfAborted()
93
78
  const text = capMarked(scrubSecrets(settled.output), LIMITS.BASH_OUTPUT_MAX_CHARS).trim()
94
- if (settled.code !== 0) return `exit ${settled.code ?? "unknown"}\n${text}`
79
+ // code=null dari runner berarti proses tidak pernah melaporkan exit sendiri:
80
+ // timeout (dan abort sudah dilempar di atas). Dulu hasil ini tampil sebagai
81
+ // `exit unknown` tanpa menyebut timeout sama sekali — model tak bisa tahu
82
+ // efeknya ambiguous. Sekarang dikembalikan dengan tag outcome yang sama
83
+ // bentuknya dengan jalur bash, bukan sebagai error tak terduga.
84
+ if (settled.code === null) {
85
+ return (
86
+ `[TOOL_OUTCOME state=UNKNOWN reason=TIMEOUT side_effect_tier=LOCAL_ENV_MUTATION ` +
87
+ `timeout_ms=${timeoutMs}]\n` +
88
+ `Sandboxed run was cut off by the ${timeoutMs} ms timeout. Its side effects are UNKNOWN ` +
89
+ `(the snippet may have partially run). Do NOT re-run before inspecting workspace state.\n` +
90
+ (text ? `--- partial output ---\n${text}` : "--- partial output ---\n(none)")
91
+ )
92
+ }
93
+ if (settled.code !== 0) return `exit ${settled.code}\n${text}`
95
94
  return text
96
95
  },
97
96
  }
package/src/tools/task.ts CHANGED
@@ -294,9 +294,12 @@ export const delegateTaskTool: Tool = {
294
294
  // Jalur autonomous TIDAK memakai M7: mode-less (readonly tetap) + default 8
295
295
  // tak representable tanpa mengarang mode/grant. Kontrak dipin test
296
296
  // `test/p9-admission-boundaries.test.ts`; jangan menyeragamkan tanpa ADR.
297
+ // [T-008] Cap eksplisit sub-agent memakai konstanta SENDIRI (50), bukan
298
+ // `DEFAULT_MAX_STEPS` sesi utama (200). Menyamakannya = memperluas
299
+ // kewenangan delegasi diam-diam saat default sesi utama naik.
297
300
  const cap =
298
301
  Number.isFinite(requested) && requested > 0
299
- ? Math.min(Math.floor(requested), LIMITS.DEFAULT_MAX_STEPS)
302
+ ? Math.min(Math.floor(requested), LIMITS.SUB_AGENT_MAX_STEPS)
300
303
  : m === "explore"
301
304
  ? LIMITS.SUB_AGENT_BUDGET_EXPLORE
302
305
  : LIMITS.SUB_AGENT_BUDGET_PLAN