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
@@ -1487,18 +1487,8 @@ export async function checkWorkspaceIntegrity(
1487
1487
  }
1488
1488
 
1489
1489
  // ── [Fase 6A / ACE-02] Anti-Reward-Hacking Tamper Guard ──────────────────────
1490
- //
1491
- // Verifikasi yang jujur mensyaratkan evaluator TIDAK ikut berubah selama agen
1492
- // bekerja. Dua jalur curang yang paling murah:
1493
- // 1. menyentuh skrip gate/evaluator (`bench/eval-gate.ts`,
1494
- // `scripts/telemetry-gate.ts`) atau mengganti script test/verify di
1495
- // `package.json`, dan
1496
- // 2. menyuntik `.skip(` / `.todo(` baru ke file `test/**/*.test.ts` yang
1497
- // sedang dimodifikasi agar test yang gagal berhenti dieksekusi.
1498
- //
1499
- // Deteksi ini SANGAT konservatif pada arah yang aman (fail-closed): tanpa
1500
- // baseline yang bisa dibaca, file gate dianggap tersentuh. Baseline diambil
1501
- // dari parameter eksplisit (test hermetik) atau `git show HEAD:<path>`.
1490
+ // Tolak klaim selesai bila permukaan evaluator/gate/test dimanipulasi selama sesi
1491
+ // (fail-closed terhadap `HEAD` / baseline pra-sesi).
1502
1492
 
1503
1493
  export interface EvaluationTamperingReport {
1504
1494
  readonly tampered: boolean
@@ -1513,13 +1503,168 @@ export interface EvaluationTamperingOptions {
1513
1503
  readonly baselineContentByFile?: ReadonlyMap<string, string>
1514
1504
  }
1515
1505
 
1516
- const EVALUATOR_GATE_FILES = new Set(["bench/eval-gate.ts", "scripts/telemetry-gate.ts"])
1506
+ const EVALUATOR_GATE_FILES = new Set([
1507
+ "bench/eval-gate.ts",
1508
+ "bench/harness-audit.ts",
1509
+ "scripts/telemetry-gate.ts",
1510
+ "scripts/coverage-gate.ts",
1511
+ "scripts/pack-budget.ts",
1512
+ "tsconfig.json",
1513
+ "biome.json",
1514
+ ])
1517
1515
  const SKIP_TODO_RE = /\.(?:skip|skipIf|only|todo|fails)\s*\(/g
1516
+ const ASSERTION_CALL_RE = /\b(?:expect|assert(?:\.[A-Za-z_]+)?)\s*\(/g
1517
+ const TAUTOLOGY_RE =
1518
+ /\bexpect\s*\(\s*(?:true|false|1|0|"[^"]*"|'[^']*')\s*\)\s*\.(?:toBe|toEqual|toStrictEqual)\s*\(\s*(?:true|false|1|0|"[^"]*"|'[^']*')\s*\)/g
1519
+ const EVALUATION_SCAN_ROOTS = [
1520
+ "test",
1521
+ "bench",
1522
+ "scripts",
1523
+ "package.json",
1524
+ "tsconfig.json",
1525
+ "biome.json",
1526
+ ".github",
1527
+ ] as const
1528
+
1529
+ /** Baseline status git pra-sesi per (root::sessionId) agar edit user sebelum sesi tak jadi false-positive. */
1530
+ const sessionEvaluationBaselines = new Map<string, Map<string, string>>()
1531
+
1532
+ function sessionBaselineKey(sessionId: string, workspaceRoot: string): string {
1533
+ return `${resolve(workspaceRoot)}::${sessionId}`
1534
+ }
1535
+
1536
+ function isProtectedEvaluatorSurface(rel: string): boolean {
1537
+ return EVALUATOR_GATE_FILES.has(rel) || rel.startsWith(".github/workflows/")
1538
+ }
1518
1539
 
1519
1540
  function countSkipTodo(text: string): number {
1520
1541
  return (text.match(SKIP_TODO_RE) ?? []).length
1521
1542
  }
1522
1543
 
1544
+ function countAssertions(text: string): number {
1545
+ return (text.match(ASSERTION_CALL_RE) ?? []).length
1546
+ }
1547
+
1548
+ function countTautologies(text: string): number {
1549
+ return (text.match(TAUTOLOGY_RE) ?? []).length
1550
+ }
1551
+
1552
+ function listDirtyEvaluationPaths(root: string): string[] {
1553
+ if (!isGitRepo(root)) return []
1554
+ try {
1555
+ const r = spawnSync(
1556
+ resolveTrustedExecutable("git"),
1557
+ [
1558
+ ...GIT_SAFE_BASE,
1559
+ "status",
1560
+ "--porcelain",
1561
+ "--untracked-files=all",
1562
+ "--",
1563
+ ...EVALUATION_SCAN_ROOTS,
1564
+ ],
1565
+ {
1566
+ cwd: root,
1567
+ encoding: "utf8",
1568
+ timeout: GIT_OBSERVE_TIMEOUT_MS,
1569
+ maxBuffer: INTEGRITY_MAX_BYTES,
1570
+ },
1571
+ )
1572
+ if (r.status !== 0 || typeof r.stdout !== "string") return []
1573
+ const out: string[] = []
1574
+ for (const rawLine of r.stdout.split(/\r?\n/)) {
1575
+ if (rawLine.length < 4) continue
1576
+ let p = rawLine.slice(3).trim()
1577
+ const arrow = p.indexOf(" -> ")
1578
+ if (arrow !== -1) p = p.slice(arrow + 4).trim()
1579
+ if ((p.startsWith('"') && p.endsWith('"')) || (p.startsWith("'") && p.endsWith("'"))) {
1580
+ p = p.slice(1, -1)
1581
+ }
1582
+ if (p) out.push(p.replace(/\\/g, "/"))
1583
+ }
1584
+ return out
1585
+ } catch {
1586
+ return []
1587
+ }
1588
+ }
1589
+
1590
+ async function hashWorkspaceRel(root: string, rel: string): Promise<string> {
1591
+ try {
1592
+ const raw = await safeReadFile(resolve(root, rel), root)
1593
+ return createHash("sha256").update(raw, "utf8").digest("hex")
1594
+ } catch {
1595
+ return "MISSING"
1596
+ }
1597
+ }
1598
+
1599
+ /**
1600
+ * Rekam sidik jari permukaan evaluator/test yang sudah kotor SEBELUM sesi
1601
+ * dimulai, sehingga perubahan lokal sah milik developer tidak memicu false-positive
1602
+ * EVALUATOR_TAMPER_ATTEMPT saat `--verify` berjalan.
1603
+ */
1604
+ export async function captureSessionEvaluationBaseline(
1605
+ sessionId: string,
1606
+ workspaceRoot: string,
1607
+ ): Promise<void> {
1608
+ const root = resolve(workspaceRoot)
1609
+ const key = sessionBaselineKey(sessionId, root)
1610
+ const baseline = new Map<string, string>()
1611
+ for (const rel of listDirtyEvaluationPaths(root)) {
1612
+ baseline.set(rel, await hashWorkspaceRel(root, rel))
1613
+ }
1614
+ sessionEvaluationBaselines.set(key, baseline)
1615
+ }
1616
+
1617
+ /**
1618
+ * Kumpulkan SEMUA file dimutasi milik sesi ini — menggabungkan jurnal induk,
1619
+ * jurnal seluruh child sub-agent (`delegate_task`), dan perubahan in-session pada
1620
+ * permukaan evaluator/test melalui `bash`/`code_run` (terdeteksi lewat git status).
1621
+ */
1622
+ export async function collectSessionModifiedFiles(
1623
+ sessionId: string,
1624
+ workspaceRoot: string,
1625
+ parentRecords?: readonly JournalRecord[],
1626
+ ): Promise<string[]> {
1627
+ const root = resolve(workspaceRoot)
1628
+ let records = parentRecords
1629
+ if (!records) {
1630
+ const loaded = await loadJournal(sessionId, root).catch(() => null)
1631
+ if (loaded?.status === "valid") records = loaded.records
1632
+ }
1633
+ const combined = new Set<string>(records ? collectModifiedFilesFromJournal(records) : [])
1634
+ if (records) {
1635
+ const childIds = new Set<string>()
1636
+ for (const r of records) {
1637
+ if (r.tool === "delegate_task" && typeof r.childSessionId === "string" && r.childSessionId) {
1638
+ childIds.add(r.childSessionId)
1639
+ }
1640
+ }
1641
+ for (const cid of [...childIds].slice(0, 20)) {
1642
+ const childLoaded = await loadJournal(cid, root).catch(() => null)
1643
+ if (childLoaded?.status === "valid") {
1644
+ for (const p of collectModifiedFilesFromJournal(childLoaded.records)) {
1645
+ combined.add(p)
1646
+ }
1647
+ }
1648
+ }
1649
+ }
1650
+ const dirtyPaths = listDirtyEvaluationPaths(root)
1651
+ if (dirtyPaths.length > 0) {
1652
+ const baseline = sessionEvaluationBaselines.get(sessionBaselineKey(sessionId, root))
1653
+ for (const rel of dirtyPaths) {
1654
+ if (!baseline) {
1655
+ combined.add(rel)
1656
+ continue
1657
+ }
1658
+ const prevHash = baseline.get(rel)
1659
+ const nowHash = await hashWorkspaceRel(root, rel)
1660
+ if (prevHash === undefined || prevHash !== nowHash) {
1661
+ combined.add(rel)
1662
+ }
1663
+ }
1664
+ }
1665
+ return [...combined]
1666
+ }
1667
+
1523
1668
  function verificationScriptsFingerprint(text: string): string | null {
1524
1669
  try {
1525
1670
  const parsed = JSON.parse(text) as { scripts?: Record<string, unknown> }
@@ -1576,8 +1721,8 @@ export async function detectEvaluationTampering(
1576
1721
  if (!rel || rel.startsWith("..") || isAbsolute(rel) || seen.has(rel)) continue
1577
1722
  seen.add(rel)
1578
1723
 
1579
- // 1. Skrip gate/evaluator kritis tidak boleh berubah sama sekali.
1580
- if (EVALUATOR_GATE_FILES.has(rel)) {
1724
+ // 1. Skrip gate/evaluator kritis & workflow CI tidak boleh berubah sama sekali.
1725
+ if (isProtectedEvaluatorSurface(rel)) {
1581
1726
  offending.push(rel)
1582
1727
  continue
1583
1728
  }
@@ -1602,8 +1747,9 @@ export async function detectEvaluationTampering(
1602
1747
  continue
1603
1748
  }
1604
1749
 
1605
- // 3. File test: hanya `.skip(`/`.todo(` BARU yang dihitung manipulasi.
1606
- if (rel.startsWith("test/") && rel.endsWith(".test.ts")) {
1750
+ // 3. Berkas test & helper (`test/**/*.ts`): deteksi .skip/.todo baru,
1751
+ // penghapusan assertion (`expect`/`assert`), atau assertion tautologi.
1752
+ if (rel.startsWith("test/") && rel.endsWith(".ts")) {
1607
1753
  let current: string
1608
1754
  try {
1609
1755
  current = await safeReadFile(abs, root)
@@ -1611,9 +1757,13 @@ export async function detectEvaluationTampering(
1611
1757
  continue
1612
1758
  }
1613
1759
  const baselineText = opts.baselineContentByFile?.get(rel) ?? gitBaselineContent(root, rel)
1614
- // Tanpa baseline di git (file baru): semua skip/todo dianggap baru.
1615
- const beforeCount = baselineText == null ? 0 : countSkipTodo(baselineText)
1616
- if (countSkipTodo(current) > beforeCount) offending.push(rel)
1760
+ const beforeSkip = baselineText == null ? 0 : countSkipTodo(baselineText)
1761
+ const beforeAsserts = baselineText == null ? 0 : countAssertions(baselineText)
1762
+ const beforeTaut = baselineText == null ? 0 : countTautologies(baselineText)
1763
+ const skipAdded = countSkipTodo(current) > beforeSkip
1764
+ const assertsDropped = beforeAsserts > 0 && countAssertions(current) < beforeAsserts
1765
+ const tautologyAdded = countTautologies(current) > beforeTaut
1766
+ if (skipAdded || assertsDropped || tautologyAdded) offending.push(rel)
1617
1767
  }
1618
1768
  }
1619
1769
 
@@ -154,32 +154,43 @@ async function loadSkillAssets(
154
154
  return out
155
155
  }
156
156
 
157
- let skillsCache: { cwd: string; at: number; skills: Skill[] } | undefined
157
+ let skillsCache: { key: string; at: number; skills: Skill[] } | undefined
158
158
  const SKILLS_CACHE_TTL_MS = 5 * 60 * 1000
159
159
 
160
- export async function loadSkills(cwd = process.cwd()): Promise<Skill[]> {
160
+ export interface LoadSkillsOptions {
161
+ /** Izinkan pemuatan skill lokal `<cwd>/.minicode/skills` (butuh `--allow-local-config`). */
162
+ allowLocal?: boolean
163
+ }
164
+
165
+ export async function loadSkills(
166
+ cwd = process.cwd(),
167
+ opts: LoadSkillsOptions = {},
168
+ ): Promise<Skill[]> {
161
169
  // cache in-memory 5 menit — loadSkills dipanggil berulang (setup, REPL, one-shot)
162
170
  const now = Date.now()
163
- const key = resolve(cwd)
164
- if (skillsCache && skillsCache.cwd === key && now - skillsCache.at < SKILLS_CACHE_TTL_MS) {
171
+ const allowLocal = opts.allowLocal === true
172
+ const cacheKey = `${resolve(cwd)}::local=${allowLocal ? 1 : 0}`
173
+ if (skillsCache && skillsCache.key === cacheKey && now - skillsCache.at < SKILLS_CACHE_TTL_MS) {
165
174
  return skillsCache.skills
166
175
  }
167
176
  const skills: Skill[] = []
168
177
  await loadDir(GLOBAL_SKILLS, skills)
169
- const localSkills: Skill[] = []
170
- await loadDir(resolve(cwd, LOCAL_SKILLS), localSkills, resolve(cwd, LOCAL_SKILLS))
171
- if (localSkills.length > 0) {
172
- try {
173
- process.stderr.write(
174
- `[warn] skills: loaded ${localSkills.length} project skill(s) from ${LOCAL_SKILLS} (untrusted repo instructions)\n`,
175
- )
176
- } catch {}
177
- skills.push(...localSkills)
178
+ if (allowLocal) {
179
+ const localSkills: Skill[] = []
180
+ await loadDir(resolve(cwd, LOCAL_SKILLS), localSkills, resolve(cwd, LOCAL_SKILLS))
181
+ if (localSkills.length > 0) {
182
+ try {
183
+ process.stderr.write(
184
+ `[warn] skills: loaded ${localSkills.length} project skill(s) from ${LOCAL_SKILLS} (untrusted repo instructions)\n`,
185
+ )
186
+ } catch {}
187
+ skills.push(...localSkills)
188
+ }
178
189
  }
179
190
  // local overrides global by name
180
191
  const map = new Map<string, Skill>()
181
192
  for (const s of skills) map.set(s.name, s)
182
- skillsCache = { cwd: key, at: now, skills: [...map.values()] }
193
+ skillsCache = { key: cacheKey, at: now, skills: [...map.values()] }
183
194
  return skillsCache.skills
184
195
  }
185
196
 
@@ -191,8 +202,12 @@ export async function renderSkill(skill: Skill, args: string): Promise<string> {
191
202
  return skill.body.replace(/\{\{args\}\}/g, args).replace(/\$ARGUMENTS/g, args)
192
203
  }
193
204
 
194
- export async function findSkill(name: string, cwd = process.cwd()): Promise<Skill | undefined> {
195
- const all = await loadSkills(cwd)
205
+ export async function findSkill(
206
+ name: string,
207
+ cwd = process.cwd(),
208
+ opts: LoadSkillsOptions = {},
209
+ ): Promise<Skill | undefined> {
210
+ const all = await loadSkills(cwd, opts)
196
211
  return all.find((s) => s.name === name || s.name === name.replace(/^\//, ""))
197
212
  }
198
213
 
@@ -217,6 +217,18 @@ export async function createProductionScheduler(
217
217
  // here would create a THIRD copy of one policy, furthest from the tests that
218
218
  // justify it and therefore most likely to drift.
219
219
 
220
+ const onEvent = (e: SchedulerEvent): void => {
221
+ try {
222
+ d.onSchedulerEvent?.(e)
223
+ } finally {
224
+ if (e.kind === "task:claimed" || e.kind === "task:recovered") {
225
+ void import("../tools/todo.ts")
226
+ .then(({ syncTodoViewsFromTaskStore }) => syncTodoViewsFromTaskStore(d.sessionId, d.cwd))
227
+ .catch(() => {})
228
+ }
229
+ }
230
+ }
231
+
220
232
  const scheduler = new Scheduler(d.sessionId, {
221
233
  store: d.store,
222
234
  runTurn: buildAutonomousRunTurn(d.bindingFor, d.adapter),
@@ -225,7 +237,7 @@ export async function createProductionScheduler(
225
237
  // P2.2: teruskan token komposisi (bila ada) — satu penulis per boot.
226
238
  ...(d.authorityToken ? { authorityToken: d.authorityToken } : {}),
227
239
  ...(d.continuity ? { continuity: d.continuity } : {}),
228
- ...(d.onSchedulerEvent ? { onEvent: d.onSchedulerEvent } : {}),
240
+ onEvent,
229
241
  })
230
242
 
231
243
  const trigger = new TriggerCoordinator({
package/src/task/store.ts CHANGED
@@ -28,7 +28,7 @@
28
28
  import { Database } from "bun:sqlite"
29
29
  import { randomUUID } from "node:crypto"
30
30
  import { LIMITS } from "../constants.ts"
31
- import { resolveLocalDbPath } from "../lib/db-path.ts"
31
+ import { resolveLocalDbPath, withSqliteBusyRetrySync } from "../lib/db-path.ts"
32
32
  import { scrubSecrets } from "../policy/scrub.ts"
33
33
  import type { CompletionEvidence } from "../tools/todo.ts"
34
34
  import {
@@ -103,43 +103,11 @@ const MAX_EVIDENCE = 32
103
103
  // version-dependent, that change should bump this constant deliberately.
104
104
  const TASK_DATA_VERSION = 1
105
105
 
106
- /** Bounded schema-DDL retry. Matches the Phase 0C contract: at most `attempts`
107
- * tries, only transient SQLite contention is retried, every other error
108
- * (corruption, constraint, …) propagates immediately, and exhaustion yields
109
- * `null` so the caller raises its own domain error.
110
- *
111
- * [Phase 12.2] Dibanding Phase 0C, predikat kontensi diperluas dari hanya
112
- * SQLITE_BUSY/"database is locked" → mencakup kontensi WAL lintas-proses Windows
113
- * (SQLITE_IOERR_TRUNCATE / SHMOPEN / LOCK / PROTOCOL / LOCKED), yang transien dan
114
- * aman di-retry. Bun menaruh kode simbolik di `error.code`, teks di `error.message`. */
115
106
  const SCHEMA_ATTEMPTS = 8
116
107
  const SCHEMA_BACKOFF_MS = 25
117
108
 
118
- const SQLITE_CONTENTION_RE =
119
- /SQLITE_BUSY|database is locked|database table is locked|SQLITE_LOCKED|SQLITE_PROTOCOL|SQLITE_IOERR_TRUNCATE|SQLITE_IOERR_SHMOPEN|SQLITE_IOERR_LOCK|disk I\/O error/i
120
-
121
- function isSqliteContention(e: unknown): boolean {
122
- const code = (e as { code?: unknown } | null)?.code
123
- if (typeof code === "string" && SQLITE_CONTENTION_RE.test(code)) return true
124
- const msg = e instanceof Error ? String(e.message ?? e) : String(e)
125
- return SQLITE_CONTENTION_RE.test(msg)
126
- }
127
-
128
109
  function withBusyRetrySync<T>(fn: () => T, attempts = SCHEMA_ATTEMPTS): T | null {
129
- for (let i = 1; i <= attempts; i++) {
130
- try {
131
- return fn()
132
- } catch (e) {
133
- if (!isSqliteContention(e)) throw e
134
- if (i === attempts) return null
135
- sleepSync(SCHEMA_BACKOFF_MS * 2 ** (i - 1))
136
- }
137
- }
138
- return null
139
- }
140
-
141
- function sleepSync(ms: number): void {
142
- Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
110
+ return withSqliteBusyRetrySync(fn, { attempts, backoffMs: SCHEMA_BACKOFF_MS })
143
111
  }
144
112
 
145
113
  interface TaskRow {
@@ -1396,6 +1364,16 @@ export class TaskStore {
1396
1364
  }
1397
1365
  const ev = buildVerificationTaskEvidence(outcome)
1398
1366
  const mergedEvidence = [...(base.evidence ?? []).slice(-(MAX_EVIDENCE - 1)), ev]
1367
+ const verification: TaskVerification = {
1368
+ verdict:
1369
+ outcome.verdict === "passed"
1370
+ ? "passed"
1371
+ : outcome.verdict === "failed" || outcome.verdict === "stale"
1372
+ ? "failed"
1373
+ : "unverified",
1374
+ ...(ev.detail ? { detail: ev.detail } : {}),
1375
+ checkedAt: ev.at,
1376
+ }
1399
1377
  if (outcome.ok) {
1400
1378
  return this.patchTask(
1401
1379
  sessionId,
@@ -1403,6 +1381,7 @@ export class TaskStore {
1403
1381
  {
1404
1382
  status: "COMPLETED",
1405
1383
  blockedReason: null,
1384
+ verification,
1406
1385
  evidence: mergedEvidence,
1407
1386
  },
1408
1387
  nextOpts,
@@ -1417,6 +1396,7 @@ export class TaskStore {
1417
1396
  {
1418
1397
  status: "BLOCKED",
1419
1398
  blockedReason: reason,
1399
+ verification,
1420
1400
  evidence: mergedEvidence,
1421
1401
  },
1422
1402
  nextOpts,
@@ -2736,12 +2716,15 @@ export class TaskStore {
2736
2716
  *
2737
2717
  * Errors from `fn` propagate unchanged after rollback.
2738
2718
  */
2739
- withTransaction<T>(fn: (tx: TaskStore) => T): T {
2719
+ withTransaction<T>(fn: (tx: TaskStore) => T, immediate = false): T {
2740
2720
  const p = dbFile(this.cwd)
2741
2721
  const db = handle(this.cwd)
2742
- txDepth.set(p, (txDepth.get(p) ?? 0) + 1)
2722
+ const depth = txDepth.get(p) ?? 0
2723
+ txDepth.set(p, depth + 1)
2743
2724
  try {
2744
- return db.transaction(() => fn(this))()
2725
+ const txn = db.transaction(() => fn(this))
2726
+ // IMMEDIATE mengambil lock tulis sejak awal agar pola baca-lalu-tulis lintas koneksi tidak terkena deadlock upgrade SQLite.
2727
+ return immediate && depth === 0 ? txn.immediate() : txn()
2745
2728
  } finally {
2746
2729
  const d = (txDepth.get(p) ?? 1) - 1
2747
2730
  if (d <= 0) txDepth.delete(p)
@@ -1,9 +1,36 @@
1
+ import { readFileSync } from "node:fs"
1
2
  import { appendFile, chmod, mkdir, readFile, unlink } from "node:fs/promises"
2
3
  import { join, resolve } from "node:path"
3
4
  import { LIMITS } from "../constants.ts"
4
5
  import { atomicWriteText } from "../lib/atomic-write.ts"
5
6
  import { scrubSecrets } from "../policy/scrub.ts"
6
7
 
8
+ /**
9
+ * Baca berkas JSONL trace (`.minicode/traces.jsonl` atau `step-traces.jsonl`)
10
+ * secara toleran: baris kosong/korup dilewati, berkas tak ada -> `[]`.
11
+ * Dipakai bersama oleh `stats`, `providers`, dan `memory` agar tidak ada
12
+ * tiga duplikat parser JSONL manual di `cli/commands/*.ts`.
13
+ */
14
+ export function readTraceRows<T = RunTrace>(
15
+ cwd?: string,
16
+ filename: "traces.jsonl" | "step-traces.jsonl" = "traces.jsonl",
17
+ ): T[] {
18
+ try {
19
+ return readFileSync(resolve(cwd ?? ".", ".minicode", filename), "utf8")
20
+ .split("\n")
21
+ .filter(Boolean)
22
+ .flatMap((line) => {
23
+ try {
24
+ return [JSON.parse(line) as T]
25
+ } catch {
26
+ return []
27
+ }
28
+ })
29
+ } catch {
30
+ return []
31
+ }
32
+ }
33
+
7
34
  export interface RunTrace {
8
35
  sessionId: string
9
36
  timestamp: string
@@ -1,5 +1,6 @@
1
1
  import type { Tool } from "#minicore"
2
2
  import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/events.ts"
3
+ import { sliceSafeChars } from "./context.ts"
3
4
 
4
5
  // Tanya user di tengah run — untuk pilihan yang tidak bisa diputuskan model
5
6
  // sendiri (ambiguitas kebutuhan, kredensial, "lanjut/tidak").
@@ -11,19 +12,6 @@ import type { ApprovalEventHook, ApprovalHookEvent } from "../presentation/event
11
12
 
12
13
  export type AskTextFn = (question: string, options?: string[]) => Promise<string | null>
13
14
 
14
- /**
15
- * Potong tanpa membelah pasangan surrogate: `slice` mentah menyisakan surrogate
16
- * tinggi yatim → U+FFFD (AUD-010). Lapisan tool tak boleh impor src/ui.
17
- */
18
- function sliceSafeChars(s: string, max: number): string {
19
- if (s.length <= max) return s
20
- let end = max
21
- const code = s.charCodeAt(end - 1)
22
- // Surrogate tinggi di posisi terakhir = pasangannya ikut terpotong; mundur 1.
23
- if (code >= 0xd800 && code <= 0xdbff) end -= 1
24
- return s.slice(0, Math.max(0, end))
25
- }
26
-
27
15
  let askTextFn: AskTextFn | undefined
28
16
 
29
17
  export function setAskTextFn(fn: AskTextFn | undefined): void {
package/src/tools/bash.ts CHANGED
@@ -1,15 +1,20 @@
1
- import { spawn, spawnSync } from "node:child_process"
1
+ import { spawn } from "node:child_process"
2
2
  import { randomUUID } from "node:crypto"
3
3
  import { resolve as resolvePath } from "node:path"
4
4
  import type { Tool, ToolContext } from "#minicore"
5
5
  import { LIMITS } from "../constants.ts"
6
+ import {
7
+ killProcessTree,
8
+ signalProcessGroup,
9
+ signalProcessGroupGraceful,
10
+ } from "../lib/process-tree.ts"
6
11
  import { isCwdOutsideRoot, isPathOutsideRoot } from "../policy/jail.ts"
7
12
  import { contextUnrestricted, requireToolCwd } from "./context.ts"
8
13
 
9
- // re-export untuk backward compat (helper kini terpusat di policy/scrub)
10
14
  export { SECRET_ENV_RE, sanitizeSpawnEnv, stripSecretsEnv } from "../policy/scrub.ts"
15
+ // re-export untuk backward compat (helper kini terpusat di policy/scrub & lib/process-tree)
16
+ export { signalProcessGroupGraceful }
11
17
 
12
- import { resolveTrustedExecutable } from "../lib/trusted-exec.ts"
13
18
  import { sandboxExplicitFallbackAllowed, sandboxStrict } from "../policy/sandbox-policy.ts"
14
19
  import { sanitizeSpawnEnv, scrubSecrets } from "../policy/scrub.ts"
15
20
  import { dockerAvailable, runInDocker } from "../sandbox/docker.ts"
@@ -140,90 +145,8 @@ function reapFinishedJobs(): void {
140
145
  }
141
146
  }
142
147
 
143
- /**
144
- * Sinyal ke SELURUH grup proses (POSIX). Butuh spawn `detached:true` agar
145
- * shell jadi group leader — tanpa itu `-pid` bukan grup yang valid dan
146
- * group-kill jadi tak mungkin (cucu selamat). true = sinyal sampai ke grup.
147
- */
148
- function signalProcessGroup(p: ReturnType<typeof spawn>, signal: NodeJS.Signals): boolean {
149
- if (process.platform === "win32" || p.pid === undefined) return false
150
- try {
151
- process.kill(-p.pid, signal)
152
- return true
153
- } catch {
154
- return false
155
- }
156
- }
157
-
158
- /**
159
- * [Fase 2 / LOOP-INV-10] Eskalasi AWAL yang sopan: SIGTERM ke seluruh process
160
- * group, bukan hanya shell induk.
161
- *
162
- * Kenapa penting: `p.kill("SIGTERM")` hanya menyentuh shell wrapper. Cucu
163
- * (`node -e`, dev server) tetap hidup, menahan pipe, dan baru mati 2 detik
164
- * kemudian oleh SIGKILL grup — padahal banyak proses menangani SIGTERM dengan
165
- * flush/cleanup yang benar bila sinyalnya sampai. Helper ini dipakai sebelum
166
- * timer eskalasi `killTree` (SIGKILL), di jalur timeout DAN abort.
167
- *
168
- * `opts` adalah seam deterministik untuk test: perilaku POSIX dapat diuji di
169
- * Windows tanpa benar-benar mengirim sinyal ke proses nyata.
170
- */
171
- export function signalProcessGroupGraceful(
172
- pid: number | undefined,
173
- fallback: { kill: (signal?: NodeJS.Signals | number) => boolean },
174
- opts: {
175
- platform?: NodeJS.Platform
176
- killGroup?: (pid: number, signal: NodeJS.Signals) => boolean
177
- } = {},
178
- ): "group" | "fallback" {
179
- const platform = opts.platform ?? process.platform
180
- if (platform !== "win32" && typeof pid === "number" && pid > 0) {
181
- const killGroup =
182
- opts.killGroup ??
183
- ((target: number, signal: NodeJS.Signals): boolean => process.kill(target, signal))
184
- try {
185
- // Negatif = process group id (shell adalah group leader karena detached).
186
- if (killGroup(-pid, "SIGTERM")) return "group"
187
- } catch {
188
- // Grup sudah hilang / ESRCH: jatuh ke sinyal proses tunggal di bawah.
189
- }
190
- }
191
- try {
192
- fallback.kill("SIGTERM")
193
- } catch {}
194
- return "fallback"
195
- }
196
-
197
- /**
198
- * Bunuh proses + seluruh subtree-nya. Di Windows `p.kill()` hanya membunuh
199
- * wrapper `cmd.exe` — cucu seperti `node -e "while(true){}"` tetap hidup,
200
- * menahan pipe stdio sehingga event `close` tidak pernah datang (hang
201
- * selamanya walau timeout sudah lewat). `taskkill /T` menutup tree-nya.
202
- */
203
148
  function killTree(p: ReturnType<typeof spawn>): void {
204
- try {
205
- if (process.platform === "win32" && p.pid !== undefined) {
206
- // F-23: resolve absolut dari PATH terpercaya — spawn dengan cwd
207
- // workspace bisa mengeksekusi taskkill.bat repo (hijack CWD Windows).
208
- // Env juga disanitasi: proses ini berjalan di timeout dengan hak penuh.
209
- const r = spawnSync(
210
- resolveTrustedExecutable("taskkill"),
211
- ["/pid", String(p.pid), "/T", "/F"],
212
- {
213
- stdio: "ignore",
214
- env: sanitizeSpawnEnv(process.env),
215
- },
216
- )
217
- if (r.status === 0) return
218
- } else if (signalProcessGroup(p, "SIGKILL")) {
219
- // POSIX: bunuh seluruh grup proses (shell wrapper + cucu seperti
220
- // `node -e`). Spawn memakai detached:true agar shell jadi group leader.
221
- return
222
- }
223
- } catch {}
224
- try {
225
- p.kill("SIGKILL")
226
- } catch {}
149
+ killProcessTree(p, { env: sanitizeSpawnEnv(process.env) })
227
150
  }
228
151
 
229
152
  /**
@@ -256,10 +179,19 @@ function startBackground(
256
179
  relaxed = false,
257
180
  ): string {
258
181
  reapFinishedJobs()
259
- const live = [...jobs.values()].filter((j) => !j.done).length
260
- if (live >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
182
+ // Isolasi kuota per pemilik sesi agar satu sesi tidak menghabiskan slot sesi lain,
183
+ // tetap dibatasi backstop global proses agar jumlah anak OS terkendali.
184
+ const ownerLive = [...jobs.values()].filter((j) => !j.done && j.ownerSid === ownerSid).length
185
+ if (ownerLive >= LIMITS.BASH_BACKGROUND_MAX_JOBS) {
186
+ throw new Error(
187
+ `too many background jobs (${ownerLive}/${LIMITS.BASH_BACKGROUND_MAX_JOBS}) — stop one with bash_kill first`,
188
+ )
189
+ }
190
+ const totalLive = [...jobs.values()].filter((j) => !j.done).length
191
+ const totalCap = LIMITS.BASH_BACKGROUND_MAX_JOBS * 4
192
+ if (totalLive >= totalCap) {
261
193
  throw new Error(
262
- `too many background jobs (${live}/${LIMITS.BASH_BACKGROUND_MAX_JOBS}) — stop one with bash_kill first`,
194
+ `too many active background jobs (${totalLive}/${totalCap}) — stop one with bash_kill first`,
263
195
  )
264
196
  }
265
197
  const id = `bg_${randomUUID().slice(0, 8)}`
@@ -360,8 +292,11 @@ function makeBashTool(ownerSid: string | null): Tool {
360
292
  // Unrestricted: default timeout jauh lebih lega; timeoutMs eksplisit
361
293
  // tetap menang.
362
294
  const timeout =
363
- timeoutMs ??
364
- (relaxed ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS : LIMITS.BASH_DEFAULT_TIMEOUT_MS)
295
+ typeof timeoutMs === "number" && Number.isFinite(timeoutMs) && timeoutMs > 0
296
+ ? timeoutMs
297
+ : relaxed
298
+ ? LIMITS.UNRESTRICTED_BASH_TIMEOUT_MS
299
+ : LIMITS.BASH_DEFAULT_TIMEOUT_MS
365
300
 
366
301
  if (background === true) {
367
302
  // Sandbox tidak diterapkan di jalur background: container/namespace
@@ -535,7 +470,7 @@ function makeBashOutputTool(ownerSid: string | null): Tool {
535
470
  parameters: {
536
471
  type: "object",
537
472
  properties: {
538
- id: { type: "string", description: "job id dari bash background:true" },
473
+ id: { type: "string", description: "job id from bash with background:true" },
539
474
  },
540
475
  required: ["id"],
541
476
  additionalProperties: false,
@@ -26,7 +26,7 @@ export function shSingleQuote(s: string): string {
26
26
  export const codeRunTool: Tool = {
27
27
  name: "code_run",
28
28
  description:
29
- "Run a code snippet (python -c / node -e) inside the configured sandbox (docker or OS sandbox, network-isolated). Requires MINICODE_SANDBOX=os|docker with a working backend; refuses otherwise. Python needs an image containing python3.",
29
+ "Run a code snippet (python -c / node -e) inside the configured sandbox (Docker, Linux bwrap, or macOS seatbelt — network-isolated). Requires MINICODE_SANDBOX=os|docker with an available backend (unavailable natively on Windows without Docker); refuses otherwise. Python needs an image/environment containing python3.",
30
30
  parameters: {
31
31
  type: "object",
32
32
  properties: {