minicode-ai 0.15.0 → 0.20.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 (99) hide show
  1. package/README.md +6 -4
  2. package/cli/commands/exec.ts +3 -2
  3. package/cli/commands/openwork.ts +1 -1
  4. package/cli/commands.ts +6 -6
  5. package/cli/index.ts +4 -4
  6. package/cli/model-manager.ts +1 -1
  7. package/cli/setup.ts +57 -30
  8. package/cli/tui.ts +106 -11
  9. package/docs/CONTROL-PLANE-MAP.md +6 -4
  10. package/docs/OUTPUT_EVENT_MODEL.md +4 -3
  11. package/docs/OUTPUT_PROTOCOL_SPEC.md +1 -1
  12. package/docs/OUTPUT_RENDERING_SPEC.md +16 -4
  13. package/docs/OUTPUT_UX_RULES.md +38 -32
  14. package/docs/P14_OPEN_WORK.md +290 -0
  15. package/docs/README.md +1 -1
  16. package/docs/SUMMARY.md +36 -22
  17. package/docs/TERMINAL_CONTRACT.md +54 -7
  18. package/docs/UI_RENDER_PIPELINE.md +47 -8
  19. package/docs/agents.md +1 -1
  20. package/docs/architecture.md +9 -8
  21. package/docs/autonomous-scheduler.md +142 -0
  22. package/docs/choosing-mode.md +2 -2
  23. package/docs/cli.md +4 -4
  24. package/docs/concepts.md +5 -5
  25. package/docs/config-providers.md +3 -3
  26. package/docs/contributing.md +7 -9
  27. package/docs/environment.md +5 -4
  28. package/docs/getting-started.md +4 -4
  29. package/docs/mcp-lsp.md +2 -2
  30. package/docs/memory-sessions.md +1 -1
  31. package/docs/policy-sandbox.md +7 -4
  32. package/docs/pricing-budget.md +3 -3
  33. package/docs/quickstart.md +1 -1
  34. package/docs/repl.md +5 -5
  35. package/docs/security-model.md +1 -1
  36. package/docs/security.md +9 -8
  37. package/docs/skills.md +2 -2
  38. package/docs/terminal.md +10 -2
  39. package/docs/tools.md +4 -4
  40. package/docs/troubleshooting.md +3 -3
  41. package/docs/verify-benchmark.md +0 -3
  42. package/package.json +9 -18
  43. package/src/app/session.ts +40 -7
  44. package/src/constants.ts +31 -0
  45. package/src/hooks/run.ts +5 -6
  46. package/src/mcp/http-transport.ts +1 -1
  47. package/src/policy/bash-guard.ts +26 -6
  48. package/src/policy/compaction.ts +107 -17
  49. package/src/policy/consequence-engine.ts +3 -3
  50. package/src/policy/context-window.ts +24 -1
  51. package/src/policy/context.ts +16 -4
  52. package/src/policy/permission.ts +219 -4
  53. package/src/presentation/adapter.ts +1 -1
  54. package/src/presentation/events.ts +2 -2
  55. package/src/presentation/label.ts +3 -3
  56. package/src/presentation/model.ts +4 -0
  57. package/src/presentation/store.ts +2 -2
  58. package/src/runtime/child-execution.ts +1 -1
  59. package/src/runtime/composition.ts +5 -5
  60. package/src/runtime/execution-registry.ts +1 -1
  61. package/src/runtime/production-execution.ts +3 -3
  62. package/src/runtime/production-runtime.ts +2 -2
  63. package/src/runtime/runtime-capabilities.ts +1 -1
  64. package/src/runtime/runtime-status-facts.ts +1 -1
  65. package/src/runtime/runtime-task-admission.ts +2 -2
  66. package/src/session/context-assembly.ts +8 -1
  67. package/src/session/context-identity.ts +2 -2
  68. package/src/session/context-projection.ts +36 -11
  69. package/src/session/persistence.ts +1 -1
  70. package/src/task/autonomous-context.ts +2 -2
  71. package/src/task/autonomous-policy.ts +3 -3
  72. package/src/task/model.ts +2 -2
  73. package/src/task/production-scheduler.ts +2 -2
  74. package/src/task/scheduler.ts +3 -2
  75. package/src/task/scheduling-policy.ts +2 -1
  76. package/src/task/trigger.ts +5 -5
  77. package/src/tools/read_image.ts +2 -1
  78. package/src/tools/task.ts +1 -1
  79. package/src/ui/assistant/simple.ts +33 -30
  80. package/src/ui/footer.ts +48 -9
  81. package/src/ui/i18n/en.ts +1 -0
  82. package/src/ui/i18n/id.ts +1 -0
  83. package/src/ui/input/prompt-engine.ts +36 -10
  84. package/src/ui/render/cells.ts +320 -0
  85. package/src/ui/render/composer-wrap.ts +73 -0
  86. package/src/ui/render/detail.ts +2 -2
  87. package/src/ui/render/ledger.ts +47 -0
  88. package/src/ui/render/theme.ts +32 -4
  89. package/src/ui/render/width.ts +2 -2
  90. package/src/ui/render/wrap.ts +5 -3
  91. package/src/ui/runtime/screen.ts +84 -7
  92. package/src/ui/runtime/statusline.ts +26 -0
  93. package/src/ui/screens/model-manager.ts +1 -1
  94. package/src/ui/tui/app.ts +336 -65
  95. package/src/ui/tui/transcript.ts +247 -88
  96. package/vendor/minicore/VENDOR.md +15 -11
  97. package/vendor/minicore/src/core/events.ts +1 -0
  98. package/vendor/minicore/src/core/loop.ts +10 -0
  99. package/vendor/minicore/src/core/session.ts +39 -0
package/README.md CHANGED
@@ -1,8 +1,8 @@
1
1
  # MiniCode
2
2
 
3
- MiniCode is a terminal coding agent built on the vendored MiniCore runtime. It can inspect and edit a workspace, run local tools, and connect to configured AI providers and external MCP/LSP servers.
3
+ MiniCode is an open-source terminal coding agent built on the frozen MiniCore kernel. It is zero-dependency (Bun is the only runtime). It inspects and edits a workspace, runs local tools, and connects to the AI providers and MCP/LSP servers you configure.
4
4
 
5
- Interactive sessions use a fullscreen TUI. One-shot and automation runs use the shell scrollback or a machine-readable stream. Prompts and relevant workspace context are sent to the provider you configure; MCP and LSP servers may receive data or perform external effects.
5
+ Interactive sessions run as a fullscreen TUI; one-shot and automation runs flow to the shell scrollback or a machine-readable JSONL stream. Every tool action is visible in the ledger, file changes are jailed to the workspace, and sensitive actions are gated behind your permission. Prompts and relevant workspace context are sent to the provider you configure; MCP and LSP servers may receive data or perform external effects. MiniCode itself sends no telemetry — traces are local-only (`MINICODE_TELEMETRY=0` to disable).
6
6
 
7
7
  ## Install
8
8
 
@@ -16,7 +16,7 @@ minicode
16
16
  To run from a clone:
17
17
 
18
18
  ```bash
19
- git clone https://github.com/startupmini/minicode.git
19
+ git clone https://github.com/minilabs-id/minicode.git
20
20
  cd minicode
21
21
  bun install
22
22
  bun run dev
@@ -36,12 +36,14 @@ WorkMode controls how the agent works (`DISCUSS`, `PLAN`, or `BUILD`); permissio
36
36
 
37
37
  ## Documentation
38
38
 
39
+ The full manual lives in [`docs/`](docs/) and is rendered at [minilabs.id/projects/minicode/docs](https://minilabs.id/projects/minicode/docs/). Quick links:
40
+
39
41
  - [Documentation index](docs/README.md) and [full navigation](docs/SUMMARY.md)
40
42
  - [Installation](docs/getting-started.md) · [Quickstart](docs/quickstart.md) · [CLI](docs/cli.md) · [TUI](docs/repl.md)
41
43
  - [Configuration and providers](docs/config.md) · [Environment variables](docs/environment.md) · [Tools](docs/tools.md)
42
44
  - [Security model](docs/security-model.md) · [Policy and sandbox](docs/policy-sandbox.md)
43
45
  - [Architecture and repository map](docs/architecture.md)
44
- - [Contributing](docs/contributing.md) · [Release history](https://github.com/startupmini/minicode/releases)
46
+ - [Contributing](docs/contributing.md) · [Release history](https://github.com/minilabs-id/minicode/releases)
45
47
 
46
48
  ## Development checks
47
49
 
@@ -178,12 +178,13 @@ export async function handleExec(
178
178
  `[warn] MINICODE_COMPACT_KEEP_TURNS requires an integer >= 1, ignoring "${keepTurnsRaw}"\n`,
179
179
  )
180
180
  const timeoutRaw = getArg("--timeout")
181
- let timeoutMs = timeoutRaw ? Number(timeoutRaw) : undefined
181
+ // exec (one-shot/CI) default 15 menit — lebih konservatif dari interaktif (1 jam).
182
+ let timeoutMs = timeoutRaw ? Number(timeoutRaw) : 900_000
182
183
  if (timeoutRaw && (!Number.isFinite(timeoutMs) || (timeoutMs as number) < 0)) {
183
184
  process.stderr.write(
184
185
  `[warn] --timeout requires a non-negative number, ignoring "${timeoutRaw}"\n`,
185
186
  )
186
- timeoutMs = undefined
187
+ timeoutMs = 900_000
187
188
  }
188
189
 
189
190
  const ignoredFlags = flagsAfterPromptBoundary(subArgs)
@@ -19,7 +19,7 @@
19
19
  // kebijakan (termasuk kegagalan tulis ekspor) · 2 salah pakai.
20
20
  //
21
21
  // Teks tak-terpercaya (judul task, ringkasan intent, evidence operator, id
22
- // sesi dari DB) tidak pernah dicetak mentah di luar tabel: renderList
22
+ // sesi dari DB) tidak pernah dicetak mentah di luar tabel: renderListHuman
23
23
  // menyani tiap sel, dan baris bebas (ringkasan merge, refusal, ekspor MD)
24
24
  // lewat sanitizeAnsi eksplisit.
25
25
  //
package/cli/commands.ts CHANGED
@@ -40,9 +40,9 @@ export interface CommandContext {
40
40
  workMode?: string
41
41
  permissionMode?: string
42
42
  setModelOverride: (model: string) => void
43
- /** Dipanggil sebelum spawn anak stdio-inherit — composition root (tui.ts)
44
- * mengisinya (saat ini no-op; DECSTBM tak pernah dipakai lagi). Tanpa
45
- * injeksi tetap jalan. */
43
+ /** Dipanggil sebelum spawn anak stdio-inherit — composition root (cli/tui.ts)
44
+ * mengisinya untuk melepas terminal alt-screen + raw mode. Tanpa injeksi
45
+ * tetap jalan (no-op). */
46
46
  onBeforeSpawn?: () => void
47
47
  /** Kontrak control-plane (Phase 6): angka konteks SAAT INI dari sumber
48
48
  * kebenaran kernel (estimateSessionContext) — bukan usage kumulatif.
@@ -205,8 +205,8 @@ function pad(text: string, width: number): string {
205
205
  }
206
206
 
207
207
  /**
208
- * Isi readout /status sebagai data (tanpa dekorasi cetak) — dipakai Jendela
209
- * info transient dan jalur cetak (non-TTY/pin) yang formatnya harus identik.
208
+ * Isi readout /status sebagai data (tanpa dekorasi cetak) — dipakai jalur cetak
209
+ * (non-TTY) via `printStatus` yang formatnya harus identik dengan TUI.
210
210
  */
211
211
  function statusLines(ctx: CommandContext): string[] {
212
212
  // Kumulatif sesi, bukan turn terakhir — judulnya menjanjikan "biaya sesi".
@@ -244,7 +244,7 @@ function statusLines(ctx: CommandContext): string[] {
244
244
  ]
245
245
  }
246
246
 
247
- /** Cetak /status seperti dulu (jalur non-TTY + pin jendela). Struktur panggilan
247
+ /** Cetak /status (jalur non-TTY + TUI). Struktur panggilan
248
248
  * dipertahankan (satu console.log per baris): helper test captureOutput
249
249
  * mencatat per panggilan, bukan per baris newline. */
250
250
  function printStatus(ctx: CommandContext): void {
package/cli/index.ts CHANGED
@@ -73,10 +73,10 @@ Options:
73
73
  --allowlist bash allowlist only (see MINICODE_BASH_ALLOWLIST)
74
74
  --max-steps <n> max tool steps (default 50)
75
75
  --context-window <n> context window tokens
76
- --timeout <ms> hard deadline per run (default 900000, 0 = off)
76
+ --timeout <ms> hard deadline per run (default 3600000 = 1h, 0 = off)
77
77
  --interactive interactive TUI (default bila tanpa prompt di TTY)
78
78
  --verify auto-verify + self-heal (typecheck/test/tsconfig)
79
- --sandbox <mode> bash sandbox: docker (ephemeral, no network)
79
+ --sandbox <mode> bash sandbox: docker (ephemeral, no network) | os (bwrap/seatbelt)
80
80
  --ratelimit <rpm> LLM requests per minute
81
81
  --budget <usd> session cost limit
82
82
  --budget-strict unknown cost + spend counts as over budget (fail-closed default)
@@ -254,7 +254,7 @@ if (args.includes("-h") || args.includes("--help")) {
254
254
  { flag: "--context-window <n>", desc: "context window tokens" },
255
255
  {
256
256
  flag: "--timeout <ms>",
257
- desc: "hard deadline per run (default 900000 = 15min; 0 = Infinity)",
257
+ desc: "hard deadline per run (default 3600000 = 60min; 0 = Infinity)",
258
258
  },
259
259
  { flag: "--allow-all", desc: "allow all tools (privileged access profile)" },
260
260
  { flag: "--ask", desc: "ask per tool (human-supervised)" },
@@ -711,7 +711,7 @@ if (enterRepl) {
711
711
  })
712
712
  } catch (e) {
713
713
  // Error provider biasanya sudah dirender ramah oleh event handler
714
- // (takePendingError) — cetak sekali saja, jangan dua blok ✗.
714
+ // (takePendingError) — cetak sekali saja, jangan dua blok error.
715
715
  const shown = ctx.uiState.takePendingError()
716
716
  process.stderr.write(`\n${c.red(glyphs.cross)} ${shown ?? formatError(e)}\n`)
717
717
  // Audit #04 P1: sama seperti REPL — turn gagal setelah delegasi
@@ -51,7 +51,7 @@ export async function runModelManager(opts: {
51
51
  // scope asal jadi tak terlihat ("balik lagi"). SEMUA salinan diupdate (bila
52
52
  // duplikat lintas file sudah terlanjur ada) agar tak ada yang menghidupkan
53
53
  // data basi. Lempar bila provider tak ada di scope mana pun — view
54
- // menampilkan ✗ (dulu ditelan diam-diam).
54
+ // menampilkan pesan error berwarna (dulu ditelan diam-diam).
55
55
  const updateProviderInScopes = async (
56
56
  id: string,
57
57
  mutate: (p: ProviderEntry) => void,
package/cli/setup.ts CHANGED
@@ -114,11 +114,7 @@ import {
114
114
  type RuntimeContextMetadata,
115
115
  runtimeMetadataFromSelection,
116
116
  } from "../src/session/context-adapter.ts"
117
- import {
118
- assembleContext,
119
- type ContextOnlyArtifact,
120
- stripContextOnly,
121
- } from "../src/session/context-assembly.ts"
117
+ import { type ContextOnlyArtifact, stripContextOnly } from "../src/session/context-assembly.ts"
122
118
  import {
123
119
  countDurableCompactions,
124
120
  deriveFrontierFromDurable,
@@ -1122,13 +1118,15 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1122
1118
  }
1123
1119
  }
1124
1120
 
1125
- // Timeout default: --timeout > MINICODE_TIMEOUT_MS env > 15 min. 0 = Infinity.
1121
+ // Timeout default: --timeout > MINICODE_TIMEOUT_MS env > 1 jam. 0 = Infinity.
1122
+ // Default interaktif 1 jam (audit panjang tak macet di tengah); jalur exec
1123
+ // meneruskan default 15 menit sendiri (lebih konservatif untuk CI).
1126
1124
  const envTimeout = process.env.MINICODE_TIMEOUT_MS
1127
1125
  let effectiveTimeoutMs =
1128
- timeoutMs ?? (envTimeout != null && envTimeout !== "" ? Number(envTimeout) : 900_000)
1126
+ timeoutMs ?? (envTimeout != null && envTimeout !== "" ? Number(envTimeout) : 3_600_000)
1129
1127
  if (!Number.isFinite(effectiveTimeoutMs) || effectiveTimeoutMs < 0) {
1130
- process.stderr.write(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 900000\n`)
1131
- effectiveTimeoutMs = 900_000
1128
+ process.stderr.write(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 3600000\n`)
1129
+ effectiveTimeoutMs = 3_600_000
1132
1130
  } else if (effectiveTimeoutMs > LIMITS.MAX_TIMER_DELAY_MS) {
1133
1131
  process.stderr.write(
1134
1132
  `[warn] timeout exceeds runtime limit; capped at ${LIMITS.MAX_TIMER_DELAY_MS}ms\n`,
@@ -1217,6 +1215,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1217
1215
  }
1218
1216
  const effectiveDefaultModel = () => modelRef.current ?? cfg.providers[0]?.models[0]
1219
1217
  const warnedContextModels = new Set<string>()
1218
+ const warnedCatalogDrift = new Set<string>()
1220
1219
  const routedContextModel = (model?: string) =>
1221
1220
  router.contextModelIdentity(model ?? effectiveDefaultModel()) ?? model ?? "default"
1222
1221
  const contextModelId = (requested?: string): string => {
@@ -1235,6 +1234,19 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1235
1234
  )
1236
1235
  }
1237
1236
  }
1237
+ // R9/T8 — katalog vs models.dev beda >2×: katalog mungkin basi. Peringatkan
1238
+ // sekali per model agar user tahu harus `pricing sync`/set contextWindows.
1239
+ if (resolved.drift) {
1240
+ const key = resolved.providerId
1241
+ ? `${resolved.providerId}::${resolved.model ?? "default"}`
1242
+ : (resolved.model ?? "default")
1243
+ if (!warnedCatalogDrift.has(key)) {
1244
+ warnedCatalogDrift.add(key)
1245
+ process.stderr.write(
1246
+ `${c.yellow(`[context] catalog window ${resolved.drift.catalogTokens} for ${sanitizeAnsi(key)} differs >2x from models.dev (${resolved.drift.overlayTokens}); catalog may be stale — run \`minicode pricing sync\` or set provider.contextWindows.\n`)}`,
1247
+ )
1248
+ }
1249
+ }
1238
1250
  return resolved.tokens
1239
1251
  }
1240
1252
  const getReportedContextWindowTokens = (model?: string) => {
@@ -1324,12 +1336,6 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1324
1336
  resumeUsageSnapshot = loadSessionUsageSummary(sessionId, cwd)
1325
1337
  }
1326
1338
  if (prev?.messages.length) {
1327
- // P2.8 — perakitan konteks (baca-saja, turunan, RAM): pakai ringkasan
1328
- // proyeksi HANYA bila CURRENT; state lain/absen → fallback histori
1329
- // kanonik utuh (identik replay sebelum P2.8). Tak pernah menulis apa pun.
1330
- // `view` tetap dipakai untuk diagnostik + kompatibilitas P2.8.
1331
- const view = assembleContext(sessionId, defaultThread.thread_id, cwd)
1332
-
1333
1339
  // [Fase 4 / LOOP-13, LOOP-INV-16] Kumpulkan snapshot state operasional
1334
1340
  // deterministik dari sumber durable (TaskStore + usage historis) agar
1335
1341
  // header [RUNTIME_STATE_HEADER] ikut ke konteks resume — tak hilang
@@ -1370,18 +1376,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1370
1376
  const rowsForSelector = loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd)
1371
1377
  // P3.4: proyeksi kanonik durable adalah sumber UTAMA untuk selector
1372
1378
  // (cakupan-valid: CURRENT atau STALE berjangkar utuh, P3.0 §8 D6),
1373
- // sehingga `summary-plus-tail` menjadi perilaku produksi nyata. P2.8
1374
- // `assembleContext` (CURRENT-only) tetap jadi fallback kompatibel.
1379
+ // sehingga `summary-plus-tail` menjadi perilaku produksi nyata.
1375
1380
  const durableProjection = readConsumableSummaryProjection(
1376
1381
  sessionId,
1377
1382
  cwd,
1378
1383
  defaultThread.thread_id,
1379
1384
  )
1380
- const projectionSummary =
1381
- durableProjection ??
1382
- (view.source === "projection" && view.summary
1383
- ? { baseSeq: view.coveredSeq, summaryText: view.summary }
1384
- : undefined)
1385
+ const projectionSummary = durableProjection
1385
1386
  const selectedWindow = getContextWindowTokens()
1386
1387
  const messageBudget = selectedWindow
1387
1388
  // N1: turunkan frontier kanonis dari baris yang BARU DIBACA (sumber
@@ -1428,16 +1429,10 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1428
1429
  console.error(
1429
1430
  c.dim(
1430
1431
  // "(N messages)" dipertahankan VERBATIM (kontrak diagnostik yang
1431
- // sudah dipakai test/CLI); detail perakitan P2.8 menyusul sebagai
1432
- // segmen terpisah agar tak mengubah string yang sudah diam.
1432
+ // sudah dipakai test/CLI).
1433
1433
  `[resumed session ${sessionId} (${prev.messages.length} messages)]\n`,
1434
1434
  ),
1435
1435
  )
1436
- console.error(
1437
- c.dim(
1438
- `[context sid=${sessionId} source=${view.source} status=${view.status} covered=${view.coveredSeq}]\n`,
1439
- ),
1440
- )
1441
1436
  // P3.3 — jejak provenance seleksi (baca-saja; tak mengubah perilaku).
1442
1437
  console.error(
1443
1438
  c.dim(
@@ -1627,8 +1622,30 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1627
1622
  orphanEvidence: shadowDiag?.orphanEvidence ?? 0,
1628
1623
  unsupportedProjection,
1629
1624
  })
1625
+ // Fase 1 perf (butir 1): cache snapshot presentasi. Snapshot dibangun ulang
1626
+ // penuh pada tiap panggil — padahal panggil terjadi tiap paint (ketikan/scroll),
1627
+ // dan nilai yang dibangun tidak berubah di antara event. Reducer immutable:
1628
+ // shadowState hanya bermutasi via reduce(event); reduce menaikkan `state.seq`
1629
+ // HANYA pada event durable, dan semata field yang dipetakan ke snapshot pun
1630
+ // hanya diubah oleh event durable (model.delta/tool.progress/context.window
1631
+ // kembali awal / hanya menulis `progress` yang tak masuk snapshot). Karena itu
1632
+ // cache ber-key (objek state, seq) aman: seq berubah ⟺ snapshot berubah.
1633
+ let snapshotCache: {
1634
+ state: PresentationState
1635
+ seq: number
1636
+ value: UiPresentationSnapshot
1637
+ } | null = null
1630
1638
  const getPresentationSnapshot = (): UiPresentationSnapshot => {
1631
1639
  if (!shadowState) return { activities: [], turns: [] }
1640
+ // Objek `shadowState` identik + seq identik = konten tak berubah (lihat
1641
+ // alasan di atas); reuse tanpa membangun ulang ratusan objek per paint.
1642
+ if (
1643
+ snapshotCache &&
1644
+ snapshotCache.state === shadowState &&
1645
+ snapshotCache.seq === shadowState.seq
1646
+ ) {
1647
+ return snapshotCache.value
1648
+ }
1632
1649
  const activities: UiPresentationActivity[] = [...shadowState.activities.values()].map((a) => ({
1633
1650
  seq: a.seq,
1634
1651
  turnId: a.turnId,
@@ -1752,7 +1769,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1752
1769
  ...(entry.cause ? { cause: entry.cause } : {}),
1753
1770
  ...(entry.action ? { action: entry.action } : {}),
1754
1771
  }))
1755
- return {
1772
+ const snapshot: UiPresentationSnapshot = {
1756
1773
  activities,
1757
1774
  turns,
1758
1775
  conversation,
@@ -1763,6 +1780,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1763
1780
  results,
1764
1781
  diagnostics,
1765
1782
  }
1783
+ snapshotCache = { state: shadowState, seq: shadowState.seq, value: snapshot }
1784
+ return snapshot
1766
1785
  }
1767
1786
  const onPresentationEvent = (handler: (event: UiPresentationEvent) => void): (() => void) => {
1768
1787
  presentationSubscribers.add(handler)
@@ -2995,6 +3014,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2995
3014
  const { attachBusDebug } = await import("../src/ui/runtime/bus-debug.ts")
2996
3015
  const detachBusDebug = attachBusDebug(session.events)
2997
3016
  const usage = createUsageCollector(session.events, effectiveInitialModel, resumeUsageSnapshot)
3017
+ // B3 — persist parsial saat turn terputus (timeout/abort/error): kernel sudah
3018
+ // commit turnStore sampai batas aman ke committed store (RAM); di sini kita
3019
+ // flush ke SQLite (durable) supaya `--resume` tak amnesia. Fire-and-forget:
3020
+ // listener bus tak boleh melempar/blocking, dan persist gagal (mis. stale
3021
+ // writer) = best-effort. Penting untuk REPL+resume lintas proses.
3022
+ session.events.on("turn:interrupted", () => {
3023
+ void persistCurrent(usage.getSession()).catch(() => {})
3024
+ })
2998
3025
  // Statusline kaya = opt-in (default mati, shell tetap bersih). Data biaya
2999
3026
  // disuntik sebagai callback agar UI tak perlu impor lapisan policy.
3000
3027
  const richStatus = process.env.MINICODE_STATUSLINE === "rich"
package/cli/tui.ts CHANGED
@@ -26,7 +26,12 @@ import {
26
26
  } from "../src/presentation/projection.ts"
27
27
  import { redoLastCheckpoint, undoLastCheckpoint } from "../src/session/checkpoint.ts"
28
28
  import { renderSkill } from "../src/skills/loader.ts"
29
- import { MAX_COPY_TURNS, writeClipboardOsc52 } from "../src/ui/assistant/simple.ts"
29
+ import {
30
+ clipboardByteLength,
31
+ MAX_CLIPBOARD_BYTES,
32
+ MAX_COPY_TURNS,
33
+ writeClipboardOsc52,
34
+ } from "../src/ui/assistant/simple.ts"
30
35
  import type { UiBus } from "../src/ui/contract.ts"
31
36
  import { t } from "../src/ui/i18n/locale.ts"
32
37
  import { loadHistory } from "../src/ui/input/input.ts"
@@ -77,14 +82,16 @@ function fmtCtx(n: number): string | undefined {
77
82
  * F-CTX-1: metrik usage footer (biaya + window %) dari angka NYATA, tanpa
78
83
  * perkiraan. Kosong = tak ada data relevan (belum belanja / flag window tak
79
84
  * disetel) — footer tak pernah menampilkan persentase/biaya palsu.
85
+ *
86
+ * P1.4: persentase footer = OCCUPANCY konteks saat ini (param `used`), bukan
87
+ * total token yang sudah dibelanjakan sepanjang sesi. Memakai spend membuat
88
+ * footer mentok 100% setelah beberapa step meski konteks masih jauh di bawah
89
+ * window. `used` di-inject oleh pemanggil (cache per turn) agar angka
90
+ * O(history) `session.contextTokens` tak dihitung ulang tiap paint.
80
91
  */
81
- function fmtUsageMetrics(ctx: CliSession): string | undefined {
92
+ function fmtUsageMetrics(ctx: CliSession, used: number): string | undefined {
82
93
  const cost: number | undefined = ctx.usage.getSession().cost
83
94
  const windowTokens: number | undefined = ctx.getContextWindowTokens?.() ?? ctx.contextWindowTokens
84
- // P1.4: persentase footer = OCCUPANCY konteks saat ini, bukan total token
85
- // yang sudah dibelanjakan sepanjang sesi. Memakai spend membuat footer
86
- // mentok 100% setelah beberapa step meski konteks masih jauh di bawah window.
87
- const used: number = ctx.session.contextTokens
88
95
  const parts: string[] = []
89
96
  if (cost !== undefined && Number.isFinite(cost) && cost > 0) parts.push(formatUsd(cost))
90
97
  if (
@@ -102,7 +109,7 @@ function fmtUsageMetrics(ctx: CliSession): string | undefined {
102
109
  /**
103
110
  * Tangkap console.log/error selama `fn` → baris teks (tanpa warna liar:
104
111
  * caller yang mewarnai). Dipakai membungkus handleBuiltinCommand supaya
105
- * readout warisan (/help, pin jendela, pesan undo) mendarat di transkrip,
112
+ * readout warisan (/help, pesan status/undo) mendarat di transkrip,
106
113
  * bukan menimpa frame alt-screen. View modal menulis via stdout.write
107
114
  * langsung (bukan console) sehingga tak ikut tertangkap — layarnya tetap
108
115
  * tampil normal (nested refcount screen.ts). Baris yang sudah tercetak
@@ -180,6 +187,55 @@ export async function runTui(ctx: CliSession): Promise<void> {
180
187
  let warned80 = false
181
188
  let abort: AbortController | null = null
182
189
 
190
+ // Fase 1 perf (butir 2b): `session.contextTokens` adalah getter O(history)
191
+ // (estimateMessages mengiterasi SELURUH store + estimator per pesan). Footer
192
+ // membacanya tiap paint/ketikan — untuk chat panjang ini pengulangan token
193
+ // estimation penuh per ketikan. Committed store hanya berubah saat turn
194
+ // selesai (turnCount naik), jadi cache keyed turnCount aman + output-identik.
195
+ let cachedContext: { turn: number; tokens: number } | null = null
196
+ // Item 16 (live context): nilai per-step yang di-emit kernel (loop.ts, event
197
+ // `provider:extension` kind `context-window`). Saat turn berjalan nilainya
198
+ // O(1) dan terus diperbarui tiap step; direset di batas turn agar idle
199
+ // kembali ke nilai committed.
200
+ let liveContextTokens: number | undefined
201
+ const liveContextUnsubs: (() => void)[] = []
202
+ const uiBus = session.events as unknown as UiBus
203
+ try {
204
+ liveContextUnsubs.push(
205
+ uiBus.on("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
206
+ if (e?.kind !== "context-window") return
207
+ const d = e.data as { usedTokens?: unknown } | undefined
208
+ if (typeof d?.usedTokens === "number") liveContextTokens = d.usedTokens
209
+ }),
210
+ )
211
+ } catch {}
212
+ try {
213
+ liveContextUnsubs.push(
214
+ uiBus.on("turn:started", () => {
215
+ liveContextTokens = undefined
216
+ }),
217
+ )
218
+ } catch {}
219
+ try {
220
+ liveContextUnsubs.push(
221
+ uiBus.on("turn:completed", () => {
222
+ liveContextTokens = undefined
223
+ }),
224
+ )
225
+ } catch {}
226
+ const getContextTokens = (): number => {
227
+ // Live (per-step) menang saat turn berjalan; idle → committed (cache).
228
+ if (liveContextTokens !== undefined) return liveContextTokens
229
+ // Beberapa fixture test menyediakan `session` parsial (tanpa `state`): tanpa
230
+ // sinyal turn yang andal, baca langsung seperti perilaku lama.
231
+ const turn = (session.state as { turnCount?: number } | undefined)?.turnCount
232
+ if (turn === undefined) return session.contextTokens
233
+ if (!cachedContext || cachedContext.turn !== turn) {
234
+ cachedContext = { turn, tokens: session.contextTokens }
235
+ }
236
+ return cachedContext.tokens
237
+ }
238
+
183
239
  // Bahasa UI: state.json (sesi bisa menimpa via /lang). Gagal baca = default.
184
240
  const { setConfigLocale } = await import("../src/ui/i18n/locale.ts")
185
241
  try {
@@ -203,6 +259,28 @@ export async function runTui(ctx: CliSession): Promise<void> {
203
259
  },
204
260
  })
205
261
 
262
+ // [resume] Rebuild riwayat transkrip dari event presentasi durable. Hanya sesi
263
+ // yang BENAR-BENAR di-resume (turnCount > 0) yang punya histori — `--session
264
+ // <id>` reuse tanpa `--resume` tak boleh menampilkan riwayat lama. Sesi baru
265
+ // (tanpa event) = no-op. Tak double-render: replay memproses event LAMA,
266
+ // turn live baru menyusul dengan event baru.
267
+ try {
268
+ const turnCount = (session.state as { turnCount?: number } | undefined)?.turnCount ?? 0
269
+ if (turnCount > 0) {
270
+ const { loadPresentationEvents } = await import("../src/session/persistence.ts")
271
+ const { toPresentationEvent } = await import("./setup.ts")
272
+ const durable = await loadPresentationEvents(sessionId, cwd)
273
+ if (durable.length > 0) {
274
+ const events = durable
275
+ .map((e) => toPresentationEvent(e))
276
+ .filter((e): e is import("../src/ui/contract.ts").UiPresentationEvent => e !== null)
277
+ transcript.replayHistory(events)
278
+ }
279
+ }
280
+ } catch {
281
+ // Replay best-effort: gagal membaca histori bukan alasan membatalkan TUI.
282
+ }
283
+
206
284
  const commandCtx: CommandContext = {
207
285
  cwd,
208
286
  sessionId,
@@ -443,6 +521,15 @@ export async function runTui(ctx: CliSession): Promise<void> {
443
521
  transcript.pushInfo([c.muted(t("tui.copyNone"))])
444
522
  return
445
523
  }
524
+ // Guard byte SEBELUM base64: 10 turn panjang bisa melewati batas OSC 52;
525
+ // memberi pesan spesifik lebih baik daripada gagal "butuh TTY" yang keliru.
526
+ const bytes = clipboardByteLength(txt)
527
+ if (bytes > MAX_CLIPBOARD_BYTES) {
528
+ transcript.pushInfo([
529
+ c.warning(t("tui.copyTooLarge", { n: bytes, max: MAX_CLIPBOARD_BYTES })),
530
+ ])
531
+ return
532
+ }
446
533
  if (writeClipboardOsc52(txt)) {
447
534
  const key = turns.length > 1 ? "tui.copyOkMany" : "tui.copyOk"
448
535
  transcript.pushInfo([c.muted(t(key, { n: txt.length, turns: turns.length }))])
@@ -691,6 +778,7 @@ export async function runTui(ctx: CliSession): Promise<void> {
691
778
  const host: TuiHost = {
692
779
  bus: session.events as unknown as TuiHost["bus"],
693
780
  getStatus: () => {
781
+ const busy = abort != null
694
782
  const status = {
695
783
  footer: {
696
784
  // Normalisasi: sumbu persetujuan hanya AUTO/ASK. Profil warisan
@@ -706,13 +794,15 @@ export async function runTui(ctx: CliSession): Promise<void> {
706
794
  workMode: workModeControl?.getWorkMode() ?? "DISCUSS",
707
795
  model: modelRef.current ?? cfg.providers[0]?.models[0] ?? t("tui.noModel"),
708
796
  cwd: cwd ?? process.cwd(),
709
- context: fmtCtx(session.contextTokens),
710
- metrics: fmtUsageMetrics(ctx),
797
+ context: fmtCtx(getContextTokens()),
798
+ metrics: fmtUsageMetrics(ctx, getContextTokens()),
711
799
  },
712
- busy: abort != null,
800
+ busy,
713
801
  }
802
+ // Fase 1 perf (butir 2): pinnedActivity hanya ditampilkan saat busy —
803
+ // jangan memindai seluruh activities pada tiap ketikan idle.
804
+ if (!busy) return { ...status, pinnedActivity: undefined }
714
805
  const activities = getPresentationSnapshot().activities
715
-
716
806
  return {
717
807
  ...status,
718
808
  pinnedActivity:
@@ -764,6 +854,11 @@ export async function runTui(ctx: CliSession): Promise<void> {
764
854
  }
765
855
  } finally {
766
856
  setApprovalSink(null)
857
+ for (const unsub of liveContextUnsubs.splice(0)) {
858
+ try {
859
+ unsub()
860
+ } catch {}
861
+ }
767
862
  transcript.dispose()
768
863
  await close()
769
864
  }
@@ -59,9 +59,12 @@ diselaraskan 0.9.27 saat seam dihilirkan; sebelumnya `budget:<…>`):
59
59
  - *What is eligible?* — hanya messages; system prompt di-cap di hulu
60
60
  (`SYSTEM_PROMPT_MAX_CHARS` 8000), tool schema TIDAK pernah terkompaksi.
61
61
  - *What must be preserved?* — pasangan assistant(toolCalls)→tool results tidak
62
- pernah dipecah (`compact.ts`); summary LLM terpin verbatim (anti-drift).
63
- - *What may be removed?* — hasil tool sukses (ditinggal `<result omitted>` di
64
- mechanical; LLM menulis ringkasan fakta), reasoning, tail lama.
62
+ pernah dipecah (folder mekanis kernel `vendor/minicore/src/core/compact.ts`);
63
+ summary LLM terpin verbatim (anti-drift).
64
+ - *What may be removed?* — teks di luar head per peran: jalur host
65
+ (`src/policy/compaction.ts`) mempertahankan hasil tool pembawa fakta ~800 char
66
+ dan prosa ~250/180 char (TIDAK lagi `<result omitted>` seperti folder mekanis
67
+ kernel), plus reasoning dan tail lama.
65
68
  - *What if compaction fails?* — LLM gagal/timeout (10s) → fallback sync
66
69
  mekanis; async compactor tak pernah bisa crash loop.
67
70
  - *Can it retry?* — budget: tidak (flag); recovery: sekali per turn (flag).
@@ -140,6 +143,5 @@ Operator harus bisa membedakan (tanpa ambigu):
140
143
  - `test/control-plane.test.ts` — compaction budget≠recovery (F-10), anti-loop,
141
144
  contextTokens getter + konsistensi estimator, termination reason.
142
145
  - `test/cli-help-language.test.ts` — /status membedakan Context/Usage/Budget.
143
- - `test/repl-linear.test.ts` — footer membaca kernel contextTokens.
144
146
  - `test/usage-session.test.ts` / `budget-unknown.test.ts` — budget contract.
145
147
  - `test/pack-integrity.test.ts` — vendor hash + VENDOR.md sinkron.
@@ -2,7 +2,8 @@
2
2
 
3
3
  **Status:** Phase 2 core state/replay contract landed; renderer/wire protocol masih target
4
4
  **Tanggal:** 2026-09-25
5
- **Kontrak aktif:** implementasi dan producer event di `src/presentation/events.ts`.
5
+ **Kontrak aktif:** definisi tipe + registry durability di `src/presentation/events.ts`;
6
+ producer event di `src/presentation/adapter.ts` (events.ts tidak mem-`publish`).
6
7
 
7
8
  ## Status implementasi
8
9
 
@@ -133,8 +134,8 @@ mengarang final message.
133
134
  | `diagnostic.raised` | adapter/policy | diagnostic actionable | ya |
134
135
 
135
136
  Tool `completed` harus membawa `summary`, `durationMs`, `expandRef`, dan bila ada
136
- `receipt`. Tool `failed` harus membawa `cause`, `message`, `hint`, dan `expandRef`.
137
- Tool `denied` harus membawa `reason`; `denied` tidak boleh berubah menjadi generic
137
+ `receipt`. Tool `failed` harus membawa `cause` dan `message` (`hint` dan `expandRef`
138
+ opsional). Tool `denied` harus membawa `reason`; `denied` tidak boleh berubah menjadi generic
138
139
  `failed` hanya karena satu renderer tidak tahu policy.
139
140
 
140
141
  ### Error, recovery, dan lifecycle
@@ -248,7 +248,7 @@ APA YANG BISA DILAKUKAN NEXT
248
248
  Contoh:
249
249
 
250
250
  ```text
251
- ✕ Build failed
251
+ Build failed
252
252
  TypeScript reported errors in 2 files.
253
253
  → Fix the reported errors, then retry.
254
254
  ```
@@ -59,6 +59,14 @@ interface RendererInput {
59
59
  }
60
60
  ```
61
61
 
62
+ > **Catatan sinkronisasi:** blok tipe di atas adalah **sketsa target**. Implementasi
63
+ > aktif memakai `UiPresentationSnapshot`/`PresentationPolicy` (`src/ui/contract.ts`)
64
+ > dan `ProjectionNode` berbentuk `{ kind, id, seq, data }` dengan kind
65
+ > `message|turn|tool|approval|reasoning|system|plan|finding|result|diagnostic`
66
+ > (`src/presentation/projection.ts`). Tipe `PresentationSnapshot`, `ContentResolver`,
67
+ > `RendererClock`, `SourceRef`, `EvidenceRef`, dan `SemanticError` belum ada sebagai
68
+ > tipe runtime.
69
+
62
70
  `PresentationSnapshot` harus read-only. `ContentResolver` mengembalikan `ContentEntry`
63
71
  dengan marker retention; tidak mengembalikan seluruh raw database tanpa batas.
64
72
  `RendererClock` adalah satu-satunya sumber waktu visual; `Date.now()` tidak boleh
@@ -132,7 +140,8 @@ popup tidak boleh membuat listener stdin kedua.
132
140
  - Assistant stream: live buffer yang di-cap; final node dipisah dari stream.
133
141
  - Whitespace jawaban dirapikan hanya pada layer tampilan: baris kosong tepi dibuang,
134
142
  jeda berulang di luar code fence dirapatkan, isi fenced code tetap literal.
135
- - Activity: started → running → terminal, dengan glyph + status word.
143
+ - Activity: started → running → terminal, dengan status word (glyph status dihapus;
144
+ bukan lagi penanda `✓`/`✗` — lihat `OUTPUT_UX_RULES.md` §3).
136
145
  - Tool child: default dikelompokkan ke parent `delegate_task`; child detail tersedia
137
146
  pada verbose/debug.
138
147
  - Context compaction: system entry, tidak menghapus history.
@@ -263,9 +272,12 @@ untuk regressions visual dan protocol.
263
272
  3. TUI/linear dapat membandingkan canonical projection dengan legacy output pada test.
264
273
  4. Exec/ACP memakai canonical projection lebih dulu karena machine parity paling mudah
265
274
  diukur.
266
- 5. After one release and green golden tests, raw semantic subscriptions were
267
- removed from user-facing TUI. Raw EventBus remains for streaming content and
268
- diagnostics/trace only.
275
+ 5. Raw EventBus tetap dipakai untuk streaming content, trace, dan sebagian
276
+ lifecycle turn/execution yang dibaca TUI (`src/ui/tui/transcript.ts`,
277
+ `src/ui/tui/app.ts`); keputusan user-facing tetap lewat semantic
278
+ projection/policy. Klaim lama "raw semantic subscriptions dihapus dari TUI"
279
+ tidak akurat: TUI masih melanggan `turn:*`/`execution:*`/`provider:extension`
280
+ untuk transcript dan status.
269
281
 
270
282
  ## 13. Definition of done renderer
271
283