minicode-ai 0.11.1 → 0.13.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 (221) hide show
  1. package/CHANGELOG.md +89 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -71
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +2 -2
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +507 -169
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -169
  221. package/docs/USAGE.md +0 -11
package/CHANGELOG.md CHANGED
@@ -1,7 +1,96 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.13.0] - 2026-11-01
4
+
5
+ ### Frontier Harness — 6 dimensi frontier terintegrasi penuh (Fase 1–12)
6
+
7
+ - Integrasi penuh keenam dimensi Frontier Harness — **LOOP**, **TOOL**, **MEMORY**, **CONTEXT**, **CONTROL**, dan **ACE-Lite** — lengkap dengan sakelar rollback `MINICODE_ACE_ENABLED` dan evaluator ablasi **ACE-4** untuk membandingkan precondition klasik dengan ACE-Lite secara setara.
8
+
9
+ ### Keamanan
10
+
11
+ - Penguatan normalizers `bash-guard` (line-continuation, ANSI-C, env-dump, redirect, powershell), pinning fingerprint skema MCP, pagar output tool tak-terpercaya, dan pemetaan standar **OWASP Agentic 2026** / **NIST AI RMF** / **MITRE ATLAS**.
12
+
13
+ ### Ketahanan penyimpanan & performa
14
+
15
+ - Memory provenance & temporal supersession, matriks otoritas penyimpanan `STORAGE_AUTHORITY_MATRIX`, akuntansi delta token streaming, gating DDL, dan ketahanan kontensi Windows WAL lewat predikat `isSqliteContention`.
16
+
3
17
  ## [Unreleased]
4
18
 
19
+ ### Added — P12 S2.2 WorkMode: ceiling izin, visibilitas tool, dan kontrol runtime
20
+
21
+ - **WorkMode = lapis intent di ATAS permission mode** (`DISCUSS` / `PLAN` / `EXECUTE`), bukan pengganti. Default `EXECUTE` = perilaku lama. WorkMode hanya **mempersempit**: otoritas efektif tetap irisan ceiling WorkMode ∧ permission mode ∧ policy terinjeksi ∧ jail/bash-guard (INV-WM1). Sumber: `src/policy/work-mode.ts` — ceiling memakai handler `readonly`/`plan` yang sudah ada (tak ada engine kedua), dan `describeDenial` kini sinkron dengan kontrak `PermissionHandler` vendor (dapat sinkron atau `Promise`).
22
+ - **Visibilitas tool sadar WorkMode** (`src/app/tool-layer.ts`): daftar tool = **irisan** filter permission mode ∧ filter WorkMode, jadi `PLAN × readonly` tidak pernah lebih luas daripada `readonly`. Tool MCP runtime (nama bertitik) ikut dibatasi pada posture `plan`/`readonly` dan pada WorkMode ≠ `EXECUTE`. Batas yang jujur: visibilitas membatasi daftar yang **dilihat model**, bukan gerbang keamanan — yang menolak tetap permission handler.
23
+ - **Wiring CLI / exec / ACP**: flag `--work-mode <DISCUSS|PLAN|EXECUTE>` + env `MINICODE_WORK_MODE` (flag > env > default `EXECUTE`; nilai tak dikenal → `EXECUTE` + peringatan, tak pernah melebar). `minicode exec` menerima flag yang sama; `minicode acp` menambah parameter `workMode` yang **terpisah** dari `mode` (permission) — `mode:"plan"` tetap bermakna lama, tak berubah jadi WorkMode.
24
+ - **Pewarisan WorkMode ke subagent** (`src/tools/task.ts`): `delegate_task` mewarisi WorkMode parent yang **aktif** dan menerapkannya pada sesi anak (ceiling anak menahan tulis). Menutup jalur `PLAN × auto`, di mana delegasi yang di-approve melahirkan anak `auto` dengan tool penuh. Argumen mode delegasi tak dapat menaikkan WorkMode parent.
25
+ - **Hooks sadar WorkMode** (`src/hooks/run.ts`): `DISCUSS` tidak menjalankan hook pre/post (walau `permissionMode=auto`); `PLAN`/`EXECUTE` tetap mengikuti permission mode; pemanggil lama tanpa WorkMode tetap kompatibel.
26
+ - **Kontrol runtime + footer** (`cli/tui.ts`, `src/ui/footer.ts`): command `/work-mode <DISCUSS|PLAN|EXECUTE>` (aksi operator eksplisit; tanpa argumen → mode aktif + usage; nilai invalid → error tanpa mengubah mode). Transisi berlaku pada **sesi yang sedang berjalan**: ceiling permission dievaluasi per pemanggilan tool, daftar tool yang dilihat kernel ikut berubah, hooks dievaluasi terhadap WorkMode aktif, dan delegasi berikutnya mewarisi mode terbaru. Footer menampilkan `<WorkMode>·<permission mode>` saat WorkMode ≠ `EXECUTE` (`PLAN·auto`, `DISCUSS·auto`, `PLAN·readonly`); `EXECUTE` mempertahankan label permission mode seperti sebelumnya. Tab/Shift+Tab dan `/mode` **tetap khusus permission mode** — WorkMode tak masuk siklus Tab.
27
+ - **Regresi**: `test/work-mode-contract.test.ts`, `test/work-mode-tool-visibility.test.ts`, `test/work-mode-cli.test.ts`, `test/work-mode-subagent.test.ts`, `test/work-mode-hooks.test.ts`, `test/work-mode-runtime.test.ts` (baru, 21 test termasuk transisi runtime pada satu sesi + TUI end-to-end). Perbaiki pula tipe `describeDenial` yang menyalakan `bun x tsc` (TS2322) dan shortfall inventaris writer untuk warning `--work-mode`.
28
+ - Kontrak terminal diperbarui (v7.4, invarian I35) dan peta arsitektur `docs/ARCHITECTURE.html` memuat alur WorkMode; `docs/environment.md` mendokumentasikan `MINICODE_WORK_MODE`. Minimum coverage fungsi pada `scripts/coverage-gate.ts` dinaikkan dari **85 → 86** mengikuti aturan repo ("coverage naik → naikkan juga minimum"; coverage fungsi terukur 87,20% pada dua sampel identik, baseline 87,05); minimum lines **tetap 86** (kenaikan lines hanya +0,11 pp — kelas "noise" yang secara historis repo tahapkan, dan menaikkan ambang lines tak menambah deteksi regresi bermakna). Status gate saat branch ini: `bun x tsc --noEmit` = 28 error (seluruhnya di test lama yang tak terkait), `bun test` = 4730 pass / 20 fail (sisa failure baseline persist/journal + PTY + encoding + nested-list + lease, bukan work-mode), liputan terukur 87,20% funcs / 88,17% lines (lantai per-berkas kritis 19/19 hijau) — `gate:coverage`/`gate:pack` belum hijau karena failure baseline tersebut, bukan karena perubahan ini. **Belum ada commit/push — perubahan masih di working tree untuk review.**
29
+
30
+ ### Docs — P12.1 Work Modes & Permission Architecture: catatan keputusan pemilik (REV-2)
31
+
32
+ - Paket keputusan arsitektur P12.1 dimuat ke repo: `P12_ENTRY_GATE_AND_SCOPE_AUDIT.md` (audit entry-gate/scope P12.0), `P12_1_ARCHITECTURE_DECISION_PACKAGE.md` (baseline) dengan revisi `REV-1` + laporan diff-nya, serta `P12_1_ARCHITECTURE_DECISION_PACKAGE_REV2.md` + `P12_1_REV2_OWNER_DECISION_REPORT.md` (catatan keputusan). Isi inti: pemisahan **WorkMode** (DISCUSS/PLAN/EXECUTE — lapis intent tipis, bukan engine baru) dari **PermissionMode**, matriks kompatibilitas 18 sel sebagai baseline arah, invarian tanpa eskalasi implisit (WorkMode hanya memperketat; policy terinjeksi tak lemah; transisi kapabilitas wajib aksi operator), koreksi K-1 (jawaban approval `always` menulis persisten ke `.minicode/allowlist.json` repo-lokal via `saveAlways`, inert tanpa `--allow-local-config`), dan rencana S1 contract tests. Arah D-1…D-7 `OWNER APPROVED — DIRECTION` (2026-10-18); detail implementasi tetap PENDING; setiap edit `vendor/minicore` tetap tertahan bukti. **Dokumen saja — tanpa perubahan source/test/konfigurasi; implementasi P12 belum dimulai.**
33
+
34
+ ### Docs — Klarifikasi kontrak `verify` pada summary `exec --json` (N-1)
35
+
36
+ - `docs/exec.md` + `docs/OUTPUT_PROTOCOL_SPEC.md` §7 kini menyatakan eksplisit: field opsional `verify` hanya berlaku pada **success summary**; **failure summary tidak menyertakannya**, termasuk bila verifikasi sudah berjalan sebelum proses gagal — hasil verifikasi terakhir tidak dapat diandalkan lewat summary pada jalur itu karena field-nya memang tidak ada. Ini kontrak saat ini yang sengaja diterima untuk P11 (keputusan pemilik atas temuan N-1); perluasan `verify` ke failure summary adalah pekerjaan protokol tersendiri di luar P11. **Tidak ada perubahan implementasi/perilaku — klarifikasi dokumentasi saja.**
37
+
38
+ ### Added — P11 presentation: hasil verifikasi pada summary `exec --json`
39
+
40
+ - `exec --json`: summary mesin **sukses** dapat memuat field opsional `verify: { active: true, ok, command }` — cermin hasil verifikasi terakhir (final pasca self-heal) ketika `--verify` dijalankan; kunci absen bila verifikasi tidak berjalan. `verify.ok` bukan pengganti top-level `ok`: kegagalan verifikasi tidak mengubah `ok` maupun exit code. Failure summary tidak menyertakan `verify` (keputusan pemilik N-1: Opsi A, keterbatasan terdokumentasi di `609a417`; perluasan field = pekerjaan protokol tersendiri). Commit `8cbda02`.
41
+
42
+ ### Fixed — P11 routing: argv scoped untuk prompt `exec` dan dispatch `daemon`
43
+
44
+ - `exec`: prompt tidak lagi membocorkan token routing `exec` ketika flag global mendahului subcommand (`minicode --json exec "tugas"` dulu mengirim `"exec tugas"` ke model dan summary). Handler kini mengonsumsi argv scoped dari router — tanpa pengirisan lokal yang mengasumsikan `exec` argumen pertama. Teks user yang sah (termasuk kata `exec` di dalamnya) tetap utuh. Commit `9e1e550`.
45
+ - `daemon`: dispatch memakai argv scoped yang sama — `minicode --json daemon status` dulu gagal sebagai `unknown daemon subcommand: daemon` (exit 2 palsu) karena guard lokal `args[0] === "daemon"`; sekarang aksi `status` tercapai dengan output JSON dan exit code state daemon yang mapan. Aksi, opsi, exit code, dan lifecycle daemon tidak berubah. Commit `04c1e1e`.
46
+
47
+ ### Fixed — P11 daemon JSON integrity (D-1)
48
+
49
+ - Jalur gagal `daemon stop --json` dan `daemon sessions --json` meng-encode payload dua kali (`fail()` men-`JSON.stringify` string yang sudah JSON), sehingga konsumen menerima string yang membungkus objek. `fail()` kini menerima objek mentah dan meng-encode sekali; jalur sukses tetap satu-encode. Tiga tes regresi di `test/cli-subcommands.test.ts` mengunci bentuk objek + exit code. Commit `dbcf836`.
50
+
51
+ ### Fixed — Task system durability & evidence-gated completion
52
+
53
+ - Task state sekarang bertahan lintas `--resume`. `cli/index.ts` menurunkan `sessionId` dari `--session` atau sebuah id acak, **tidak** dari `--resume`, sedangkan todo diikat ke `sessionId`. Akibatnya `minicode --resume foo` mengikat task ke `.minicode/todos/<acak>.json` dan `todo_read` mengembalikan `"(no todos yet)"` padahal `.minicode/todos/foo.json` ada — task state hilang tepat di batas yang seharusnya dilewatinya, dan setiap resume meninggalkan file todo yatim. Todo kini terikat ke id kanonik `presentationSessionId` (`resumeId ?? sessionId`), sama dengan history dan presentation events.
54
+ - `completed` kini **memerlukan bukti**. Sebelumnya status itu hanya string yang ditulis model, dan **tidak ada satu pun jalur kode** yang mencegah task ditandai selesai saat verify merah — bahkan setelah 3 siklus self-heal gagal. Composition root sekarang menyuntikkan bukti (hasil verify terakhir) lewat `setCompletionEvidence()`; `failed` menolak `completed`, task turun ke status baru `blocked` beserta alasannya, dan model diberi tahu lewat hasil tool (bukan diam-diam tersimpan di file). Tanpa `--verify` (opt-in) verdict `unverified`: completion tetap diizinkan karena memblokirnya akan mematikan pemakaian normal, tapi tidak diklaim terverifikasi.
55
+ - `plan.updated` sekarang terbit di `execution:completed`, bukan `execution:started`. Dulu plan disintesis dari argumen mentah **sebelum** tool jalan, sehingga `plan.updated` berstatus `completed` bisa tertahan durable di `presentation_events` meski `saveTodos` gagal (disk penuh/EACCES) — presentasi menyatakan selesai tanpa file-nya.
56
+ - Satu normalizer untuk dua store. Adaptor punya pemetaan status sendiri, sehingga 2 item `in_progress` menjadi dua `active` di plan padahal file todo menyimpan satu (`normalizeTodos` menurunkan yang kedua ke `pending`); cap juga berbeda (adaptor 100, file 50) sehingga item 51-100 hanya hidup di event log. `planFromTodos` kini memakai `normalizeTodos` yang sama dengan file, jadi status, cap, dan keputusan `blocked` tidak bisa berbeda arah.
57
+ - Status `blocked` masuk ke kontrak plan presentational (`PlanStepStatus` + `UiPresentationPlan`/`UiPresentationEvent`).
58
+
59
+ ### Fixed — Context long-horizon (agent-context-architect)
60
+
61
+ - Ringkasan hasil kompaksi LLM sekarang dipagu keras di `LIMITS.COMPACTION_SUMMARY_MAX_CHARS` (1.500 char, sebelumnya konstanta ini ada tapi tak pernah dipakai). Sebelumnya prior summary dibawa verbatim lalu digabung dengan summary baru, sehingga tiap siklus kompaksi menambah ~2.700 char ke pesan pertama yang selalu ikut dikirim: 30 siklus terukur tumbuh jadi 80.838 char (~20rb token sia-sia per request) dan jendela penuh karena summary-nya sendiri. Sesudah pagu: datar di 1.500 char sejak siklus ke-2, pertumbuhan 30 siklus +0 char (53,9× lebih kecil di siklus ke-30). Arah pemotongan disengaja: summary baru dipangkas dari akhir (fakta terstruktur model ditulis di awal), summary lama dari awal (ekornya = siklus terakhir); yang dipangkas ditandai eksplisit agar model tak menyimpulkan ringkasan lengkap. Jalur mechanical sudah self-limiting (head 400 char/garis) dan tidak diubah.
62
+ - Anggaran jawaban di prompt kompaksi diturunkan dari pagu yang sama, supaya model tidak menulis 600 token yang sebagian besar dibuang diam-diam.
63
+
64
+ ### Fixed — Fidelity resume
65
+
66
+ - `reasoning` (thinking) dan `is_error` (tool gagal) adalah field kernel `Message` yang ikut dibawa ke history, tapi tabel `messages` tidak punya kolomnya — resume lama menghasilkan konteks buta dan model kehilangan konteks kegagalannya. Keduanya kini menjadi kolom `messages` (addeditive, DB lama tetap terbaca) dan dipulihkan di `loadSession`.
67
+ - Kedua field baru itu **wajib ikut prefix comparison** di `saveSession`: kalau tidak, perubahan hanya pada `reasoning`/`isError` dianggap "tak berubah" dan incremental append melewatkannya — kelas bug F-05 yang sama.
68
+ - Field absen tetap absen saat reload (`reasoning: ""` / `isError: false` tidak disetel), agar bentuk pesan tidak berubah saat kernel membandingkan.
69
+
70
+ ### Removed — Phase 8 shadow cleanup
71
+
72
+ - Rollback flag `MINICODE_PRESENTATION_V2` dihapus; jalur presentasi kanonik selalu aktif.
73
+ - Raw ledger TUI (`execution:completed` → baris manual) dihapus; ledger kini selalu dari event presentasi + snapshot.
74
+
75
+ ## [0.12.0] - 2026-09-25
76
+
77
+ ### Changed — Minimal TUI feedback and model tables
78
+
79
+ - TUI fullscreen sekarang memakai prompt `minicode ›` langsung saat boot/idle, hilang saat proses berjalan, dan kembali otomatis setelah turn selesai; dots thinking berbasis clock tanpa marker `… thinking` di transcript, timer `HH.MM.SS` di sebelah sparkle dengan level warna detik/menit/jam, dan satu spacer sebelum footer; label `Working`/`Thinking`/`Running` serta bullet separator footer dihapus.
80
+ - Pipe-table Markdown dari model kini diparse dan dirender sebagai grid terminal di linear output dan TUI, termasuk streaming, escaped pipe/code span, alignment, CJK/ANSI, resize, dan fallback terminal sempit; output machine tetap raw.
81
+ - Mouse tracking TUI memakai `?1002h + ?1006h`: wheel tetap menggeser viewport, drag-kiri membuat selection app-level, dan `Ctrl+C` menyalin selection; `MINICODE_MOUSE_SELECTION=0` menjadi kill switch emergency.
82
+ - `/copy [n]` sekarang dapat menyalin 1–10 turn terakhir secara kronologis; TUI memakai `Esc` untuk abort, sementara `Ctrl+C` tanpa selection tidak lagi memicu abort turn.
83
+
84
+ ### Added — Output architecture audit
85
+
86
+ - Audit architecture-first MiniCode ditambahkan sebagai enam artefak di `docs/`: audit, event model, protocol, rendering, UX, dan implementation plan; navigasi docs/web serta `llms-full.txt` sudah disinkronkan.
87
+ - `scripts/pack-check.ts` menaikkan batas ukuran unpacked dari 2 MiB ke 2.25 MiB karena artefak audit wajib ikut paket; guard import, vendor, secret, test, dan relative-link tetap aktif.
88
+ - Temuan utama: raw EventBus masih menjadi jalur utama TUI/linear/exec/ACP, presentation bridge belum exhaustive, dan durable semantic rebuild belum production-wired; remediation sengaja belum dimulai.
89
+ - Phase 1 canonical bridge selesai: `user.message` durable, mapper seluruh 20 `DomainEventType`, proposed marker untuk event tanpa producer, dan regression coverage baru; renderer masih belum dipindahkan.
90
+ - Phase 2 core selesai: semantic state collections, derived summaries, late evidence, bounded retention, durable SQLite event log/replay, checkpoint/structured verify evidence, child event persistence, dan `MINICODE_PRESENTATION_V2=0` rollback flag.
91
+ - Phase 2 parity selesai: producer `finding.detected` dari `result.findings` eksplisit, contract restart/branch/child/delete/TTL/resume, `eventSeq` unik untuk durable writes; hanya `tool.progress` yang masih `proposed` karena live-only.
92
+ - Phase 3–7 selesai: modul policy proyeksi murni `src/presentation/projection.ts` (seleksi node, envelope `minicode.output.v1`, digest divergensi) di-inject ke TUI/linear/machine; `exec --json` + ACP memakai lifecycle kanonik dengan sanitasi ANSI dan persist headless; test inventaris writer (OAP-008); ambang coverage naik ke 84/85. Penghapusan jalur raw (Phase 8) menunggu satu rilis hijau.
93
+
5
94
  ## [0.11.1] - 2026-09-24
6
95
 
7
96
  ### Fixed — TUI runtime feedback
package/LICENSE CHANGED
@@ -1,21 +1,21 @@
1
- MIT License
2
-
3
- Copyright (c) 2026 startupmini
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ MIT License
2
+
3
+ Copyright (c) 2026 startupmini
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -28,7 +28,7 @@ minicode (coding-agent — self-contained, tanpa sibling clone)
28
28
  │ approval prompt, screens (picker/wizard/managers) — tanpa impor core/#minicore
29
29
  ├─ experiments/ → harness adversarial (fuzz bash, stress shadow-git, server MCP jahat)
30
30
  ├─ docs/ → ARCHITECTURE.html (peta struktur hidup) · USAGE.md
31
- └─ cli/ → REPL (tab completion, multiline, history, slash commands) + controller tipis
31
+ └─ cli/ → TUI fullscreen (tab completion, multiline, history, slash commands) + controller tipis
32
32
  wizard/model-manager/provider-manager (logic config tetap di src/)
33
33
  ```
34
34
 
@@ -52,12 +52,12 @@ minicode models --match gemini # cari model lintas provider
52
52
  minicode sync # refresh model baru dari semua provider
53
53
  ```
54
54
 
55
- Kernel MiniCore di-vendor ke `vendor/minicore` (20 file, ~81 KB) sehingga repo ini self-contained. Sumber kebenaran tetap repo `minicore`; kontributor yang punya clone sibling `../minicore` menyinkronkan dengan `bun run vendor:minicore`, dan CI menjaga kesinkronan lewat `bun run vendor:check`.
55
+ Kernel MiniCore di-vendor ke `vendor/minicore` (isi, jumlah file, dan hash dicatat di `vendor/minicore/VENDOR.md`) sehingga repo ini self-contained. Sumber kebenaran tetap repo `minicore`; kontributor yang punya clone sibling `../minicore` menyinkronkan dengan `bun run vendor:minicore`, dan CI menjaga kesinkronan lewat `bun run vendor:check`.
56
56
 
57
57
  Wizard & `/provider` (add: `[0] OpenAI` … `[14] Custom URL` — hanya label, tanpa URL) + `/model` (Enter = pilih `provider::model` + picker `default/low/medium/high` untuk thinking effort, tersimpan di provider dan berlaku sesi berikutnya; Esc = batal total) menyajikan preset gateway (OpenAI, Anthropic, OpenRouter, DeepSeek, OpenCode Zen, Google, Ollama, Qwen, Groq, dll), API Key ter-masking, auto-detect models, dan provider otomatis pindah saat pilih model beda provider (tanpa restart).
58
58
 
59
59
  ```bash
60
- minicode --interactive # REPL linier (agentic Unix shell, output di scrollback)
60
+ minicode --interactive # TUI fullscreen (alternate screen; default bila tanpa prompt di TTY)
61
61
  minicode --ask "deploy script" # human-in-loop confirmation card
62
62
  minicode --verify "fix bugs lalu typecheck" # auto-verify + self-heal setelah run
63
63
  minicode --sandbox docker "task" # eksekusi bash dalam container ephemeral
@@ -197,4 +197,4 @@ Catatan lingkungan:
197
197
 
198
198
  **MIT License.** Bebas pakai, modifikasi, distribusi — lihat [LICENSE](LICENSE). Copyright (c) 2026 startupmini.
199
199
 
200
- Lihat `docs/ARCHITECTURE.html` + `docs/HARNESS.md` + `PLAN.md`.
200
+ Lihat `docs/ARCHITECTURE.html` + `docs/HARNESS.md` + `ROADMAP.md` (roadmap arsitektur aktif) + `PLAN.md` (ledger legacy).
package/cli/args.ts CHANGED
@@ -11,6 +11,12 @@ const BOOLEAN_FLAGS = new Set([
11
11
  "--json", // dipakai `exec --json` dan `--help --json`
12
12
  "--budget-strict", // penegasan eksplisit fail-closed (kini juga default --budget)
13
13
  "--allow-local-config", // opt-in: baca .minicode/config.json + allowlist lokal (default mati)
14
+ // [PHASE 6U] Experimental. Opt-in gate for autonomous Scheduler execution.
15
+ // DEFAULT OFF. A CLI flag and not a config key or env var on purpose: env is
16
+ // inherited by sub-agents and MCP servers, and config is inherited globally or
17
+ // per-repo — both would let autonomous execution switch on without the person
18
+ // running the process asking for it. See src/task/production-scheduler.ts.
19
+ "--enable-scheduler",
14
20
  ])
15
21
  const VALUE_FLAGS = new Set([
16
22
  "--cwd",
@@ -25,6 +31,12 @@ const VALUE_FLAGS = new Set([
25
31
  "--ratelimit",
26
32
  "--budget",
27
33
  "--tool-scope", // full | explore (read-only) — tanpa ini jadi kata prompt!
34
+ "--work-mode", // DISCUSS | PLAN | EXECUTE — HARUS dikenal agar tak bocor ke prompt.
35
+ // [P1 M15] Mode runtime produksi (off | constructed | owned). HARUS terdaftar:
36
+ // flag tak dikenal menghentikan scan `hasFlag`/`getArg` (dianggap prompt
37
+ // boundary), sehingga flag yang diletakkan SETELAH `--runtime` akan hilang
38
+ // diam-diam — tepat kebocoran semantik yang ingin dicegah audit flag.
39
+ "--runtime",
28
40
  "--output-format", // `exec --output-format=json`
29
41
  "--prompt",
30
42
  // subcommand flags — harus dikenal agar tidak bocor ke prompt one-shot
@@ -90,6 +102,40 @@ export function allowLocalConfig(argv: string[]): boolean {
90
102
  return hasFlag(argv, "--allow-local-config") || process.env.MINICODE_ALLOW_LOCAL_CONFIG === "1"
91
103
  }
92
104
 
105
+ export type CliWorkMode = "DISCUSS" | "PLAN" | "EXECUTE"
106
+
107
+ /**
108
+ * P12 S2.2 — Parse nilai WorkMode dari argumen operator (command `/work-mode`).
109
+ * Murni + diekspor untuk test. Hanya tiga nilai yang sah; nilai lain = tak
110
+ * dikenal (undefined) agar pemanggil bisa menolak tanpa mengubah state.
111
+ */
112
+ export function parseWorkModeValue(raw: string): CliWorkMode | undefined {
113
+ const norm = raw.trim().toUpperCase()
114
+ if (norm === "DISCUSS" || norm === "PLAN" || norm === "EXECUTE") return norm
115
+ return undefined
116
+ }
117
+
118
+ /**
119
+ * P12 S2.2 — Resolusi WorkMode dari flag CLI + env, murni & diekspor untuk
120
+ * test (pola repo). Flag `--work-mode` mengalahkan env `MINICODE_WORK_MODE`;
121
+ * keduanya tak ada = EXECUTE (perilaku lama). Nilai tak dikenal TIDAK
122
+ * melebar diam-diam — gagal ke EXECUTE + pesan peringatan (fail-closed).
123
+ * Case-insensitive agar konsisten dengan flag permission lainnya.
124
+ */
125
+ export function resolveWorkModeFlag(getArg: (n: string) => string | undefined): {
126
+ workMode: CliWorkMode
127
+ warning?: string
128
+ } {
129
+ const raw = getArg("--work-mode") ?? process.env.MINICODE_WORK_MODE
130
+ if (raw === undefined) return { workMode: "EXECUTE" }
131
+ const parsed = parseWorkModeValue(raw)
132
+ if (parsed) return { workMode: parsed }
133
+ return {
134
+ workMode: "EXECUTE",
135
+ warning: `--work-mode requires DISCUSS|PLAN|EXECUTE, ignoring "${raw}" (using EXECUTE)`,
136
+ }
137
+ }
138
+
93
139
  export function getArg(argv: string[], name: string): string | undefined {
94
140
  // dukung bentuk --name value DAN --name=value; ambil kemunculan terakhir
95
141
  // (flag berulang -> yang terakhir menang, konsisten dengan CLI umum)
@@ -1,13 +1,20 @@
1
- import { randomUUID } from "node:crypto"
2
1
  import { resolve as resolvePath } from "node:path"
3
2
  import { createInterface } from "node:readline"
4
3
  import { LIMITS } from "../../src/constants.ts"
5
4
  import { scrubSecrets } from "../../src/policy/scrub.ts"
6
5
  import { budgetStatus } from "../../src/policy/usage.ts"
6
+ import {
7
+ correlationId,
8
+ machineError,
9
+ machineSeverity,
10
+ machineStatus,
11
+ } from "../../src/presentation/projection.ts"
12
+ import { mintSessionId } from "../../src/session/identity.ts"
7
13
  import { clearSubmittedResult, getSubmittedResult } from "../../src/tools/submit_result.ts"
8
14
  import { formatError } from "../../src/ui/assistant/simple.ts"
9
15
  import type { UiPresentationEvent, UiPresentationSnapshot } from "../../src/ui/contract.ts"
10
16
  import { formatUsd } from "../../src/ui/render/money.ts"
17
+ import { cleanUntrusted } from "../../src/ui/render/sanitize.ts"
11
18
  import { createCliSession } from "../setup.ts"
12
19
 
13
20
  // minicode acp — server JSON-RPC via stdio untuk IDE (Fase 5, subset minimal).
@@ -26,6 +33,8 @@ import { createCliSession } from "../setup.ts"
26
33
  // <- {"type":"tool.completed|failed|denied|cancelled",...} ...
27
34
  // <- {"type":"approval.requested|settled",...} ...
28
35
  // <- {"type":"turn.started|completed|failed|cancelled",...} ...
36
+ // <- {"type":"file.changed|test.completed|diagnostic.raised|checkpoint.created",...} ...
37
+ // <- {"type":"plan.updated|finding.detected|result.produced|context.compacted",...} ...
29
38
  // <- {"id":2,"result":{"ok":true,"tokens":123,"steps":4,"turns":1,"text":"..."}}
30
39
  // -> {"id":3,"method":"cancel"} (menggugurkan run yang berjalan)
31
40
  // -> {"id":4,"method":"shutdown"} (keluar 0 setelah run selesai/dibatalkan)
@@ -60,8 +69,19 @@ export function acpOk(id: number | string | undefined, result: unknown): string
60
69
  return JSON.stringify({ id: id ?? null, result })
61
70
  }
62
71
 
63
- export function acpErr(id: number | string | undefined, message: string): string {
64
- return JSON.stringify({ id: id ?? null, error: { message } })
72
+ export function acpErr(
73
+ id: number | string | undefined,
74
+ message: string,
75
+ detail?: { category?: string; action?: string },
76
+ ): string {
77
+ return JSON.stringify({
78
+ id: id ?? null,
79
+ error: {
80
+ message,
81
+ ...(detail?.category ? { category: detail.category } : {}),
82
+ ...(detail?.action ? { action: detail.action } : {}),
83
+ },
84
+ })
65
85
  }
66
86
 
67
87
  export interface AcpRunParams {
@@ -72,6 +92,8 @@ export interface AcpRunParams {
72
92
  timeoutMs?: number
73
93
  budget?: number
74
94
  mode?: "auto" | "plan"
95
+ /** P12 S2.2 — WorkMode terpisah dari `mode` (permission). Default EXECUTE. */
96
+ workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
75
97
  }
76
98
 
77
99
  /** Validasi params `run`: prompt wajib non-kosong; angka harus hingga-positif;
@@ -97,7 +119,20 @@ export function parseRunParams(
97
119
  const mode =
98
120
  p.mode === undefined || p.mode === "auto" ? "auto" : p.mode === "plan" ? "plan" : null
99
121
  if (mode === null) return { ok: false, error: 'params.mode must be "auto" or "plan"' }
100
- const out: AcpRunParams = { prompt, mode }
122
+ // P12 S2.2 — WorkMode default EXECUTE; nilai invalid → error (bukan diam
123
+ // melebar). Case-insensitive agar konsisten dengan flag CLI.
124
+ const wmRaw = p.workMode === undefined ? "EXECUTE" : String(p.workMode).toUpperCase()
125
+ const workMode =
126
+ wmRaw === "DISCUSS"
127
+ ? "DISCUSS"
128
+ : wmRaw === "PLAN"
129
+ ? "PLAN"
130
+ : wmRaw === "EXECUTE"
131
+ ? "EXECUTE"
132
+ : null
133
+ if (workMode === null)
134
+ return { ok: false, error: 'params.workMode must be "DISCUSS" | "PLAN" | "EXECUTE"' }
135
+ const out: AcpRunParams = { prompt, mode, workMode }
101
136
  if (typeof p.cwd === "string" && p.cwd) out.cwd = p.cwd
102
137
  if (typeof p.model === "string" && p.model) out.model = p.model
103
138
  const ms = num(p.maxSteps)
@@ -157,6 +192,8 @@ function projectAcpLifecycle(
157
192
  ...(event.target ? { target: event.target } : {}),
158
193
  status: "running",
159
194
  ...(event.tsStart !== undefined ? { tsStart: event.tsStart } : {}),
195
+ ...(event.parentToolCallId ? { parentToolCallId: event.parentToolCallId } : {}),
196
+ ...(event.provenance ? { provenance: event.provenance } : {}),
160
197
  }
161
198
  if (
162
199
  event.type === "tool.completed" ||
@@ -164,6 +201,9 @@ function projectAcpLifecycle(
164
201
  event.type === "tool.denied" ||
165
202
  event.type === "tool.cancelled"
166
203
  ) {
204
+ // P2.11: pertahankan tautan anak bila ada di event ATAU snapshot —
205
+ // sebelumnya hilang untuk tool.* (hanya finding yang membawa).
206
+ const parentLink = event.parentToolCallId ?? activity?.parentToolCallId
167
207
  return {
168
208
  ...base,
169
209
  ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
@@ -182,8 +222,88 @@ function projectAcpLifecycle(
182
222
  ...(event.type === "tool.failed" && activity?.error ? { error: activity.error } : {}),
183
223
  ...(activity?.denyReason ? { denyReason: activity.denyReason } : {}),
184
224
  ...(activity?.receipt ? { receipt: activity.receipt } : {}),
225
+ ...(parentLink ? { parentToolCallId: parentLink } : {}),
226
+ ...(event.provenance ? { provenance: event.provenance } : {}),
185
227
  }
186
228
  }
229
+ if (event.type === "file.changed")
230
+ return {
231
+ ...base,
232
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
233
+ ...(event.paths ? { paths: event.paths } : {}),
234
+ ...(event.journalSeq !== undefined ? { journalSeq: event.journalSeq } : {}),
235
+ ...(event.checkpointId ? { checkpointId: event.checkpointId } : {}),
236
+ }
237
+ if (event.type === "test.completed")
238
+ return {
239
+ ...base,
240
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
241
+ ...(event.test ? { test: event.test } : {}),
242
+ }
243
+ if (event.type === "verification.observed")
244
+ return {
245
+ ...base,
246
+ ...(event.toolCallId ? { toolCallId: event.toolCallId } : {}),
247
+ ...(event.invocationId ? { invocationId: event.invocationId } : {}),
248
+ ...(event.verification
249
+ ? {
250
+ verification: {
251
+ invocationId: event.verification.invocationId,
252
+ verdict: event.verification.verdict,
253
+ method: event.verification.method,
254
+ observedAt: event.verification.observedAt,
255
+ },
256
+ }
257
+ : {}),
258
+ ...(event.parentToolCallId ? { parentToolCallId: event.parentToolCallId } : {}),
259
+ ...(event.provenance ? { provenance: event.provenance } : {}),
260
+ }
261
+ if (event.type === "diagnostic.raised")
262
+ return {
263
+ ...base,
264
+ ...(event.category ? { category: event.category } : {}),
265
+ severity: machineSeverity(event),
266
+ ...(event.message ? { message: event.message } : {}),
267
+ ...(event.cause ? { cause: event.cause } : {}),
268
+ ...(event.action ? { action: event.action } : {}),
269
+ }
270
+ if (event.type === "checkpoint.created")
271
+ return {
272
+ ...base,
273
+ ...(event.checkpointId ? { checkpointId: event.checkpointId } : {}),
274
+ ...(event.paths ? { paths: event.paths } : {}),
275
+ }
276
+ if (event.type === "plan.updated")
277
+ return {
278
+ ...base,
279
+ ...(event.planId ? { planId: event.planId } : {}),
280
+ status: machineStatus(event),
281
+ ...(event.steps ? { steps: event.steps } : {}),
282
+ }
283
+ if (event.type === "finding.detected")
284
+ return {
285
+ ...base,
286
+ ...(event.findingId ? { findingId: event.findingId } : {}),
287
+ ...(event.category ? { category: event.category } : {}),
288
+ ...(event.severity ? { severity: event.severity } : {}),
289
+ ...(event.text ? { text: event.text } : {}),
290
+ ...(event.evidence ? { evidence: event.evidence } : {}),
291
+ ...(event.parentToolCallId ? { parentToolCallId: event.parentToolCallId } : {}),
292
+ }
293
+ if (event.type === "result.produced")
294
+ return {
295
+ ...base,
296
+ ...(event.resultId ? { resultId: event.resultId } : {}),
297
+ status: machineStatus(event),
298
+ ...(event.toolSummary ? { toolSummary: event.toolSummary } : {}),
299
+ ...(event.action ? { action: event.action } : {}),
300
+ ...(correlationId(event) ? { correlationId: correlationId(event) } : {}),
301
+ }
302
+ if (event.type === "context.compacted")
303
+ return {
304
+ ...base,
305
+ ...(event.compactionReason ? { compactionReason: event.compactionReason } : {}),
306
+ }
187
307
  return null
188
308
  }
189
309
 
@@ -251,7 +371,9 @@ export async function runAcpSession(
251
371
  return
252
372
  }
253
373
  const rp = parsed.value
254
- const sessionId = randomUUID().slice(0, 8)
374
+ // P2.1: tiap run = sesi kanonik BARU (tanpa thread/resume); id fresh
375
+ // sekali via mint terpusat.
376
+ const sessionId = mintSessionId()
255
377
  const ac = new AbortController()
256
378
  deps.startFlight(() => ac.abort())
257
379
  const t0 = Date.now()
@@ -263,12 +385,15 @@ export async function runAcpSession(
263
385
  modelOverride: rp.model,
264
386
  prompt: rp.prompt,
265
387
  enterRepl: false,
388
+ machineOutput: true,
266
389
  verbose: false,
267
390
  allowAll: false,
268
391
  ask: false,
269
392
  plan: rp.mode === "plan",
270
393
  allowlist: false,
271
394
  verify: false,
395
+ // P12 S2.2 — WorkMode terpisah dari `mode` (permission). Default EXECUTE.
396
+ workMode: rp.workMode,
272
397
  budget: rp.budget,
273
398
  budgetStrict: false,
274
399
  ...(rp.maxSteps ? { maxSteps: rp.maxSteps } : {}),
@@ -283,7 +408,7 @@ export async function runAcpSession(
283
408
  if (lifecycle) {
284
409
  unsubPresentation = projection.onPresentationEvent!((event) => {
285
410
  const note = projectAcpLifecycle(event, projection.getPresentationSnapshot?.())
286
- if (note) write(scrubSecrets(JSON.stringify(note)))
411
+ if (note) write(cleanUntrusted(scrubSecrets(JSON.stringify(note)), false))
287
412
  })
288
413
  }
289
414
  const unsub = ctx.session.events.on("*", (ev) => {
@@ -293,7 +418,20 @@ export async function runAcpSession(
293
418
  // Cap akumulasi juga (bukan hanya slice akhir): run panjang bisa
294
419
  // menumpuk megabyte di memori sebelum result dirakit.
295
420
  if (text.length < LIMITS.MCP_OUTPUT_MAX_CHARS) text += e.text
296
- write(scrubSecrets(JSON.stringify({ type: "text", delta: e.text })))
421
+ const max = LIMITS.MCP_OUTPUT_MAX_CHARS
422
+ const delta = e.text.length > max ? e.text.slice(0, max) : e.text
423
+ write(
424
+ cleanUntrusted(
425
+ scrubSecrets(
426
+ JSON.stringify({
427
+ type: "text",
428
+ delta,
429
+ ...(e.text.length > max ? { truncated: true } : {}),
430
+ }),
431
+ ),
432
+ false,
433
+ ),
434
+ )
297
435
  } else if (e.type === "execution:started" && !lifecycle) {
298
436
  const name = e.execution?.call?.name ?? "?"
299
437
  write(JSON.stringify({ type: "tool", name }))
@@ -309,7 +447,7 @@ export async function runAcpSession(
309
447
  bStatus === "over" && ue.cost != null && rp.budget != null
310
448
  ? `[budget] ${formatUsd(ue.cost)} > ${formatUsd(rp.budget)} - over budget, stopping.`
311
449
  : `[budget] cost unknown (model without pricing) with ${ue.totalTokens} tokens spent - over budget, stopping.`
312
- write(acpErr(id, msg))
450
+ write(acpErr(id, msg, machineError(new Error(msg))))
313
451
  } else {
314
452
  const submitted = getSubmittedResult()
315
453
  // submitted verbatim seperti exec --json (pipeline tak menebak
@@ -317,7 +455,7 @@ export async function runAcpSession(
317
455
  write(
318
456
  acpOk(id, {
319
457
  ok: true,
320
- sessionId,
458
+ sessionId: ctx.sessionId,
321
459
  model: ctx.modelRef.current,
322
460
  tokens: ue.totalTokens,
323
461
  inputTokens: ue.inputTokens,
@@ -334,6 +472,21 @@ export async function runAcpSession(
334
472
  } finally {
335
473
  unsub()
336
474
  unsubPresentation()
475
+ // Headless run tetap durable: flush presentation events + saveSession +
476
+ // finalize journal agar --resume berikutnya melihat run ini.
477
+ try {
478
+ const persist = (ctx as { persistCurrent?: (usage: unknown) => Promise<void> })
479
+ .persistCurrent
480
+ if (typeof persist === "function") await persist(ctx.usage.getSession(ctx.modelRef.current))
481
+ // P2.2: respons sukses sudah terkirim di atas (tepat-sekali per run);
482
+ // histori yang tak durable dilaporkan via stderr diagnostik, bukan
483
+ // pesan protokol kedua.
484
+ if (ctx.isWriterStale()) {
485
+ process.stderr.write(
486
+ `[writer] stale writer sid=${ctx.sessionId}, history NOT durable: ${ctx.writerStaleNote()}\n`,
487
+ )
488
+ }
489
+ } catch {}
337
490
  await ctx.close()
338
491
  }
339
492
  } catch (e) {
@@ -341,7 +494,7 @@ export async function runAcpSession(
341
494
  // provider — koneksi tetap hidup untuk request berikut), run gagal,
342
495
  // atau dibatalkan user. formatError menutupi NoProviderError juga.
343
496
  const msg = ac.signal.aborted ? "run cancelled" : formatError(e)
344
- write(acpErr(id, msg))
497
+ write(acpErr(id, msg, machineError(ac.signal.aborted ? new Error("run cancelled") : e)))
345
498
  } finally {
346
499
  deps.onDone()
347
500
  if (deps.shouldExit()) deps.exit(0)