minicode-ai 0.15.0 → 0.21.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 (108) hide show
  1. package/README.md +6 -4
  2. package/cli/auto-update.ts +24 -15
  3. package/cli/commands/exec.ts +3 -2
  4. package/cli/commands/openwork.ts +1 -1
  5. package/cli/commands.ts +6 -6
  6. package/cli/index.ts +61 -22
  7. package/cli/model-manager.ts +1 -1
  8. package/cli/setup.ts +119 -62
  9. package/cli/tui.ts +128 -13
  10. package/docs/CONTROL-PLANE-MAP.md +6 -4
  11. package/docs/OUTPUT_EVENT_MODEL.md +4 -3
  12. package/docs/OUTPUT_PROTOCOL_SPEC.md +1 -1
  13. package/docs/OUTPUT_RENDERING_SPEC.md +16 -4
  14. package/docs/OUTPUT_UX_RULES.md +38 -32
  15. package/docs/P14_OPEN_WORK.md +290 -0
  16. package/docs/README.md +1 -1
  17. package/docs/SUMMARY.md +36 -22
  18. package/docs/TERMINAL_CONTRACT.md +74 -11
  19. package/docs/UI_RENDER_PIPELINE.md +53 -11
  20. package/docs/agents.md +1 -1
  21. package/docs/architecture.md +9 -8
  22. package/docs/autonomous-scheduler.md +142 -0
  23. package/docs/choosing-mode.md +2 -2
  24. package/docs/cli.md +4 -4
  25. package/docs/concepts.md +5 -5
  26. package/docs/config-providers.md +3 -3
  27. package/docs/contributing.md +7 -9
  28. package/docs/environment.md +6 -4
  29. package/docs/getting-started.md +4 -4
  30. package/docs/mcp-lsp.md +2 -2
  31. package/docs/memory-sessions.md +1 -1
  32. package/docs/policy-sandbox.md +7 -4
  33. package/docs/pricing-budget.md +3 -3
  34. package/docs/quickstart.md +1 -1
  35. package/docs/repl.md +5 -5
  36. package/docs/security-model.md +1 -1
  37. package/docs/security.md +9 -8
  38. package/docs/skills.md +2 -2
  39. package/docs/terminal.md +10 -2
  40. package/docs/tools.md +4 -4
  41. package/docs/troubleshooting.md +3 -3
  42. package/docs/verify-benchmark.md +0 -3
  43. package/package.json +9 -18
  44. package/src/app/session.ts +40 -7
  45. package/src/constants.ts +31 -0
  46. package/src/hooks/run.ts +5 -6
  47. package/src/mcp/http-transport.ts +1 -1
  48. package/src/policy/bash-guard.ts +26 -6
  49. package/src/policy/compaction.ts +107 -17
  50. package/src/policy/consequence-engine.ts +3 -3
  51. package/src/policy/context-window.ts +24 -1
  52. package/src/policy/context.ts +16 -4
  53. package/src/policy/permission.ts +219 -4
  54. package/src/policy/update-check.ts +6 -4
  55. package/src/presentation/adapter.ts +1 -1
  56. package/src/presentation/events.ts +2 -2
  57. package/src/presentation/label.ts +3 -3
  58. package/src/presentation/model.ts +4 -0
  59. package/src/presentation/store.ts +2 -2
  60. package/src/runtime/child-execution.ts +1 -1
  61. package/src/runtime/composition.ts +5 -5
  62. package/src/runtime/execution-registry.ts +1 -1
  63. package/src/runtime/production-execution.ts +3 -3
  64. package/src/runtime/production-runtime.ts +2 -2
  65. package/src/runtime/runtime-capabilities.ts +1 -1
  66. package/src/runtime/runtime-status-facts.ts +1 -1
  67. package/src/runtime/runtime-task-admission.ts +2 -2
  68. package/src/session/context-assembly.ts +8 -1
  69. package/src/session/context-identity.ts +2 -2
  70. package/src/session/context-projection.ts +36 -11
  71. package/src/session/persistence.ts +1 -1
  72. package/src/task/autonomous-context.ts +2 -2
  73. package/src/task/autonomous-policy.ts +3 -3
  74. package/src/task/model.ts +2 -2
  75. package/src/task/production-scheduler.ts +2 -2
  76. package/src/task/scheduler.ts +3 -2
  77. package/src/task/scheduling-policy.ts +2 -1
  78. package/src/task/trigger.ts +5 -5
  79. package/src/tools/read_image.ts +2 -1
  80. package/src/tools/task.ts +1 -1
  81. package/src/ui/assistant/simple.ts +47 -30
  82. package/src/ui/footer.ts +48 -9
  83. package/src/ui/i18n/en.ts +21 -0
  84. package/src/ui/i18n/id.ts +21 -0
  85. package/src/ui/input/prompt-engine.ts +36 -10
  86. package/src/ui/render/activity-group.ts +53 -0
  87. package/src/ui/render/activity-panel.ts +91 -0
  88. package/src/ui/render/cells.ts +347 -0
  89. package/src/ui/render/composer-wrap.ts +73 -0
  90. package/src/ui/render/detail.ts +2 -2
  91. package/src/ui/render/diff.ts +7 -0
  92. package/src/ui/render/ledger.ts +47 -0
  93. package/src/ui/render/markdown.ts +6 -1
  94. package/src/ui/render/session-summary.ts +7 -2
  95. package/src/ui/render/theme.ts +40 -4
  96. package/src/ui/render/width.ts +2 -2
  97. package/src/ui/render/wrap.ts +5 -3
  98. package/src/ui/runtime/loading-bar.ts +125 -0
  99. package/src/ui/runtime/screen.ts +84 -7
  100. package/src/ui/runtime/statusline.ts +26 -0
  101. package/src/ui/screens/model-manager.ts +1 -1
  102. package/src/ui/session-state.ts +22 -0
  103. package/src/ui/tui/app.ts +336 -65
  104. package/src/ui/tui/transcript.ts +407 -106
  105. package/vendor/minicore/VENDOR.md +15 -11
  106. package/vendor/minicore/src/core/events.ts +1 -0
  107. package/vendor/minicore/src/core/loop.ts +10 -0
  108. package/vendor/minicore/src/core/session.ts +39 -0
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,
@@ -373,6 +369,12 @@ export interface CliSessionOptions {
373
369
  * prefiks prompt. Dicetak di sini (setelah provider layer lolos) supaya
374
370
  * invokasi yang mati sebelumnya tetap senyap. */
375
371
  sandboxNotice?: string
372
+ /**
373
+ * Hook fase startup (bar loading). Dipanggil saat fase panjang mulai:
374
+ * "provider-layer", "rag-layer", "tool-layer", "kernel-session", "resume".
375
+ * Optional — absen = tanpa progres (perilaku lama).
376
+ */
377
+ onPhase?: (phase: string) => void
376
378
  }
377
379
 
378
380
  export interface CliSession {
@@ -519,6 +521,12 @@ export interface CliSession {
519
521
  * membaca ulang pesan stderr.
520
522
  */
521
523
  adoption: AdoptionResult | null
524
+ /**
525
+ * Baris diagnostik startup yang didefer (hanya terisi saat enterRepl —
526
+ * bar loading menggantikan teks proses). Di-flush ke transcript TUI oleh
527
+ * cli/tui.ts. Absen/undefined = tidak ada deferral (perilaku lama).
528
+ */
529
+ startupNotices?: string[]
522
530
  }
523
531
 
524
532
  function mapPresentationEvent(event: DomainEvent): UiPresentationEvent | null {
@@ -914,6 +922,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
914
922
  timeoutMs,
915
923
  rateLimiter,
916
924
  sandboxNotice,
925
+ onPhase,
917
926
  } = opts
918
927
  // [Area A · PROMPT 06] State UI milik SESI ini. Dibuat SEKALI per sesi dan
919
928
  // dipakai bersama oleh TUI (Transcript) + printer linier sesi yang sama.
@@ -921,6 +930,25 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
921
930
  // sendiri sehingga tak saling menimpa collapse/compact/reasoning.
922
931
  const uiState = new UiSessionState()
923
932
  const modelRef = { current: modelOverride }
933
+ // Collector diagnostik startup. Saat REPL + stderr TTY, bar loading
934
+ // menggantikan teks proses verbose — baris diagnostik (resume/recovery/
935
+ // context/dll) DITUNDA dan di-flush ke transcript TUI setelah sesi siap
936
+ // (lihat cli/tui.ts). Non-interaktif ATAU non-TTY (pipe/CI) tetap
937
+ // mencetak langsung seperti sebelumnya — tidak ada diagnostik yang bisa
938
+ // hilang di jalur yang tak punya transcript.
939
+ const deferStartup = enterRepl && process.stderr.isTTY === true
940
+ const startupNotices: string[] = []
941
+ const startupWrite = (s: string): void => {
942
+ if (deferStartup) startupNotices.push(s)
943
+ else process.stderr.write(s)
944
+ }
945
+ // `console.error` dipertahankan pada jalur non-interaktif (spy test
946
+ // menangkap baris provenance resume lewat console.error), tapi didefer
947
+ // saat REPL agar bar loading tetap satu-baris.
948
+ const startupConsoleError = (s: string): void => {
949
+ if (deferStartup) startupNotices.push(s)
950
+ else console.error(s)
951
+ }
924
952
  // P2.1 — SATU-SATUNYA keputusan identitas sesi. Sesudah baris ini,
925
953
  // `sessionId` adalah identitas kanonik durable; id volatil hanya `bootId`
926
954
  // (diagnostik). Tak ada jalur persistensi khusus alias: semua turunan
@@ -935,7 +963,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
935
963
  })
936
964
  const sessionId = identity.sid
937
965
  const bootId = identity.bootId
938
- process.stderr.write(`${c.dim(formatSessionIdentityLine(identity))}\n`)
966
+ startupWrite(`${c.dim(formatSessionIdentityLine(identity))}\n`)
939
967
 
940
968
  // P2.2 — admission penulis tunggal. Lease = admission; pagar mutasi =
941
969
  // writer_epoch (CAS di transaksi tulis). Komposisi ini MEMEGANG lease
@@ -952,12 +980,12 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
952
980
  if (!writerStale) {
953
981
  writerStale = true
954
982
  writerStaleNote = note
955
- process.stderr.write(
983
+ startupWrite(
956
984
  `${c.yellow(`[writer] STALE sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}: ${note} — history NOT durable; resume/restart to re-acquire\n`)}`,
957
985
  )
958
986
  }
959
987
  }
960
- process.stderr.write(
988
+ startupWrite(
961
989
  `${c.dim(`[writer] admitted sid=${sessionId} boot=${bootId} epoch=${expectedEpoch}${admission.admission.tookOver ? " (takeover)" : ""}${admission.admission.fresh ? " (fresh)" : ""}\n`)}`,
962
990
  )
963
991
  // [P14] Adopsi eksplisit berjalan SETELAH admission target (token target
@@ -979,7 +1007,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
979
1007
  throw new AdoptionRefusedError(adoption)
980
1008
  }
981
1009
  const moved = adoption.task
982
- process.stderr.write(
1010
+ startupWrite(
983
1011
  `${c.dim(`[adopt] ADOPTED ${adoptTask.taskId} ${adoptTask.sourceSessionId} -> ${sessionId} revision=${moved?.revision ?? "?"} status=${moved?.status ?? "?"} exec=${adoption.transfer?.execGeneration ?? "?"}${adoption.fencedFormerOwner ? " (former owner fenced)" : ""}\n`)}`,
984
1012
  )
985
1013
  }
@@ -992,9 +1020,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
992
1020
  const planAsWorkMode =
993
1021
  plan && !workModeExplicit && workMode === "DISCUSS" ? ("PLAN" as const) : workMode
994
1022
  if (plan && !workModeExplicit && workMode === "DISCUSS") {
995
- process.stderr.write(
996
- `${c.dim("[deprecated] --plan is now WorkMode PLAN; use --work-mode PLAN\n")}`,
997
- )
1023
+ startupWrite(`${c.dim("[deprecated] --plan is now WorkMode PLAN; use --work-mode PLAN\n")}`)
998
1024
  }
999
1025
  const effectiveWorkMode: "DISCUSS" | "PLAN" | "EXECUTE" =
1000
1026
  identity.resumed && !workModeExplicit && !plan
@@ -1017,7 +1043,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1017
1043
  try {
1018
1044
  const orphans = tombstoneOrphanChildRuns(sessionId, cwd, { expectedEpoch })
1019
1045
  if (orphans.length > 0) {
1020
- process.stderr.write(
1046
+ startupWrite(
1021
1047
  `${c.yellow(`[child] ${orphans.length} orphaned sub-agent run(s) tombstoned (INTERRUPTED/UNKNOWN)\n`)}`,
1022
1048
  )
1023
1049
  }
@@ -1032,7 +1058,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1032
1058
  const out = renewSessionWriter(sessionId, writerToken, cwd)
1033
1059
  if (out === "AUTHORITY_LOST" && !renewWarned) {
1034
1060
  renewWarned = true
1035
- process.stderr.write(
1061
+ startupWrite(
1036
1062
  `${c.yellow(`[writer] lease lost sid=${sessionId} boot=${bootId} — another writer took over; next mutation will be refused unless re-acquired\n`)}`,
1037
1063
  )
1038
1064
  try {
@@ -1056,7 +1082,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1056
1082
  const re = acquireSessionWriter({ sessionId, cwd, bootId, token: writerToken })
1057
1083
  if (re.ok) {
1058
1084
  if (re.admission.epoch !== expectedEpoch) {
1059
- process.stderr.write(
1085
+ startupWrite(
1060
1086
  `${c.dim(`[writer] re-acquired sid=${sessionId} boot=${bootId} epoch=${re.admission.epoch}\n`)}`,
1061
1087
  )
1062
1088
  }
@@ -1114,25 +1140,26 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1114
1140
  // fase session-setup ke stderr (`[startup] rag 8432ms`). Tanpa env = diam.
1115
1141
  const startupPhase = async <T>(name: string, fn: () => Promise<T>): Promise<T> => {
1116
1142
  const s = Date.now()
1143
+ onPhase?.(name)
1117
1144
  try {
1118
1145
  return await fn()
1119
1146
  } finally {
1120
1147
  if (process.env.MINICODE_DEBUG_STARTUP === "1")
1121
- process.stderr.write(`[startup] ${name} ${Date.now() - s}ms\n`)
1148
+ startupWrite(`[startup] ${name} ${Date.now() - s}ms\n`)
1122
1149
  }
1123
1150
  }
1124
1151
 
1125
- // Timeout default: --timeout > MINICODE_TIMEOUT_MS env > 15 min. 0 = Infinity.
1152
+ // Timeout default: --timeout > MINICODE_TIMEOUT_MS env > 1 jam. 0 = Infinity.
1153
+ // Default interaktif 1 jam (audit panjang tak macet di tengah); jalur exec
1154
+ // meneruskan default 15 menit sendiri (lebih konservatif untuk CI).
1126
1155
  const envTimeout = process.env.MINICODE_TIMEOUT_MS
1127
1156
  let effectiveTimeoutMs =
1128
- timeoutMs ?? (envTimeout != null && envTimeout !== "" ? Number(envTimeout) : 900_000)
1157
+ timeoutMs ?? (envTimeout != null && envTimeout !== "" ? Number(envTimeout) : 3_600_000)
1129
1158
  if (!Number.isFinite(effectiveTimeoutMs) || effectiveTimeoutMs < 0) {
1130
- process.stderr.write(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 900000\n`)
1131
- effectiveTimeoutMs = 900_000
1159
+ startupWrite(`[warn] invalid timeout ${effectiveTimeoutMs}, fallback to 3600000\n`)
1160
+ effectiveTimeoutMs = 3_600_000
1132
1161
  } else if (effectiveTimeoutMs > LIMITS.MAX_TIMER_DELAY_MS) {
1133
- process.stderr.write(
1134
- `[warn] timeout exceeds runtime limit; capped at ${LIMITS.MAX_TIMER_DELAY_MS}ms\n`,
1135
- )
1162
+ startupWrite(`[warn] timeout exceeds runtime limit; capped at ${LIMITS.MAX_TIMER_DELAY_MS}ms\n`)
1136
1163
  effectiveTimeoutMs = LIMITS.MAX_TIMER_DELAY_MS
1137
1164
  }
1138
1165
  // `--timeout` adalah deadline satu pemanggilan prompt. Jangan menyalakan
@@ -1166,7 +1193,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1166
1193
  const home = homeDir()
1167
1194
  const cur = resolvePath(cwd ?? process.cwd())
1168
1195
  if (resolvePath(home) === cur) {
1169
- process.stderr.write(
1196
+ startupWrite(
1170
1197
  c.yellow(
1171
1198
  `[warn] workspace is home directory — consider --cwd <project> to avoid scanning the entire home\n`,
1172
1199
  ),
@@ -1183,7 +1210,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1183
1210
  )
1184
1211
  const stale = checkStaleTurn(cwd, sessionId)
1185
1212
  if (stale) {
1186
- process.stderr.write(`${c.yellow(formatStaleNotice(stale))}\n`)
1213
+ startupWrite(`${c.yellow(formatStaleNotice(stale))}\n`)
1187
1214
  clearStaleTurn(cwd, sessionId)
1188
1215
  }
1189
1216
  } catch {}
@@ -1204,9 +1231,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1204
1231
  // ada, jadi tak ada noise pada alur normal.
1205
1232
  try {
1206
1233
  const notice = localConfigNotice(cwd ?? process.cwd(), allowLocalConfig === true)
1207
- if (notice) process.stderr.write(`${c.dim(notice)}\n`)
1234
+ if (notice) startupWrite(`${c.dim(notice)}\n`)
1208
1235
  } catch {}
1209
- if (sandboxNotice && !plan) process.stderr.write(`${sandboxNotice}\n`)
1236
+ if (sandboxNotice && !plan) startupWrite(`${sandboxNotice}\n`)
1210
1237
  // Default model = terakhir dipakai (global), bila tanpa --model dan masih
1211
1238
  // ada di config. Flag selalu menang; tak ada simpanan = provider pertama.
1212
1239
  if (!modelRef.current) {
@@ -1217,6 +1244,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1217
1244
  }
1218
1245
  const effectiveDefaultModel = () => modelRef.current ?? cfg.providers[0]?.models[0]
1219
1246
  const warnedContextModels = new Set<string>()
1247
+ const warnedCatalogDrift = new Set<string>()
1220
1248
  const routedContextModel = (model?: string) =>
1221
1249
  router.contextModelIdentity(model ?? effectiveDefaultModel()) ?? model ?? "default"
1222
1250
  const contextModelId = (requested?: string): string => {
@@ -1230,11 +1258,24 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1230
1258
  : (resolved.model ?? "default")
1231
1259
  if (!warnedContextModels.has(key)) {
1232
1260
  warnedContextModels.add(key)
1233
- process.stderr.write(
1261
+ startupWrite(
1234
1262
  `${c.yellow(`[context] no configured window for ${sanitizeAnsi(key)}; using fallback ${resolved.tokens} tokens. Set provider.contextWindows or --context-window for the exact limit.\n`)}`,
1235
1263
  )
1236
1264
  }
1237
1265
  }
1266
+ // R9/T8 — katalog vs models.dev beda >2×: katalog mungkin basi. Peringatkan
1267
+ // sekali per model agar user tahu harus `pricing sync`/set contextWindows.
1268
+ if (resolved.drift) {
1269
+ const key = resolved.providerId
1270
+ ? `${resolved.providerId}::${resolved.model ?? "default"}`
1271
+ : (resolved.model ?? "default")
1272
+ if (!warnedCatalogDrift.has(key)) {
1273
+ warnedCatalogDrift.add(key)
1274
+ startupWrite(
1275
+ `${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`)}`,
1276
+ )
1277
+ }
1278
+ }
1238
1279
  return resolved.tokens
1239
1280
  }
1240
1281
  const getReportedContextWindowTokens = (model?: string) => {
@@ -1307,7 +1348,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1307
1348
  : persistedWorkMode !== undefined && persistedWorkMode !== effectiveWorkMode
1308
1349
  ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} (overriding saved ${persistedWorkMode === "EXECUTE" ? "BUILD" : persistedWorkMode})\n`
1309
1350
  : ""
1310
- if (resumeNotice) process.stderr.write(resumeNotice)
1351
+ if (resumeNotice) startupWrite(resumeNotice)
1311
1352
  // P2.4: aktivasi default Thread SEBELUM seed kernel — backfill aditif
1312
1353
  // berpagar (konten/seq tak tersentuh). Basi di sini = gagal loud
1313
1354
  // (dunia bergerak pasca-admission); warn-swallow di bawah tak berlaku.
@@ -1315,7 +1356,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1315
1356
  // idempoten) agar SEMUA baris durable beridentitas stabil.
1316
1357
  const defaultThread = ensureDefaultThread(sessionId, cwd, { expectedEpoch })
1317
1358
  const backfilled = backfillHistoryEventIds(sessionId, cwd, { expectedEpoch })
1318
- process.stderr.write(
1359
+ startupWrite(
1319
1360
  `${c.dim(`[thread sid=${sessionId} tid=${defaultThread.thread_id} head=${defaultThread.head_seq}${backfilled > 0 ? ` backfilled=${backfilled}` : ""}]\n`)}`,
1320
1361
  )
1321
1362
  try {
@@ -1324,12 +1365,6 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1324
1365
  resumeUsageSnapshot = loadSessionUsageSummary(sessionId, cwd)
1325
1366
  }
1326
1367
  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
1368
  // [Fase 4 / LOOP-13, LOOP-INV-16] Kumpulkan snapshot state operasional
1334
1369
  // deterministik dari sumber durable (TaskStore + usage historis) agar
1335
1370
  // header [RUNTIME_STATE_HEADER] ikut ke konteks resume — tak hilang
@@ -1370,18 +1405,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1370
1405
  const rowsForSelector = loadThreadHistoryWithSeq(sessionId, defaultThread.thread_id, cwd)
1371
1406
  // P3.4: proyeksi kanonik durable adalah sumber UTAMA untuk selector
1372
1407
  // (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.
1408
+ // sehingga `summary-plus-tail` menjadi perilaku produksi nyata.
1375
1409
  const durableProjection = readConsumableSummaryProjection(
1376
1410
  sessionId,
1377
1411
  cwd,
1378
1412
  defaultThread.thread_id,
1379
1413
  )
1380
- const projectionSummary =
1381
- durableProjection ??
1382
- (view.source === "projection" && view.summary
1383
- ? { baseSeq: view.coveredSeq, summaryText: view.summary }
1384
- : undefined)
1414
+ const projectionSummary = durableProjection
1385
1415
  const selectedWindow = getContextWindowTokens()
1386
1416
  const messageBudget = selectedWindow
1387
1417
  // N1: turunkan frontier kanonis dari baris yang BARU DIBACA (sumber
@@ -1425,21 +1455,15 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1425
1455
  contextCanonicalBaseline = prev.messages
1426
1456
  }
1427
1457
  resumeTurnCount = prev.turnCount
1428
- console.error(
1458
+ startupConsoleError(
1429
1459
  c.dim(
1430
1460
  // "(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.
1461
+ // sudah dipakai test/CLI).
1433
1462
  `[resumed session ${sessionId} (${prev.messages.length} messages)]\n`,
1434
1463
  ),
1435
1464
  )
1436
- console.error(
1437
- c.dim(
1438
- `[context sid=${sessionId} source=${view.source} status=${view.status} covered=${view.coveredSeq}]\n`,
1439
- ),
1440
- )
1441
1465
  // P3.3 — jejak provenance seleksi (baca-saja; tak mengubah perilaku).
1442
- console.error(
1466
+ startupConsoleError(
1443
1467
  c.dim(
1444
1468
  `[select sid=${sessionId} basis=${selection.selectionBasis} freshness=${selection.freshness} head=${selection.frontier?.headSeq ?? "-"}]\n`,
1445
1469
  ),
@@ -1449,7 +1473,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1449
1473
  // /undo tersedia bila perlu kembali. Best-effort, tak menggagalkan resume.
1450
1474
  const div = await validateResumeWorkspace(cwd ?? ".", sessionId).catch(() => null)
1451
1475
  if (div && div.diverged > 0) {
1452
- console.error(
1476
+ startupConsoleError(
1453
1477
  c.yellow(
1454
1478
  `[resume] workspace berubah sejak checkpoint terakhir (${div.diverged} file) — /undo tersedia bila perlu kembali\n`,
1455
1479
  ),
@@ -1457,13 +1481,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1457
1481
  }
1458
1482
  } else {
1459
1483
  // Defensif (tak terjangkau normal: resolver menjamin baris ada).
1460
- console.error(c.yellow(`[resume] session ${sessionId} has no messages yet\n`))
1484
+ startupConsoleError(c.yellow(`[resume] session ${sessionId} has no messages yet\n`))
1461
1485
  }
1462
1486
  } catch (e) {
1463
1487
  // P2.2/P2.4: pagar basi TIDAK boleh jadi warning — lempar ulang agar
1464
1488
  // startup gagal loud (dunia bergerak pasca-admission).
1465
1489
  if (e instanceof StaleWriterError || e instanceof ThreadArchivedError) throw e
1466
- process.stderr.write(`[warn] resume failed: ${(e as Error).message}\n`)
1490
+ startupWrite(`[warn] resume failed: ${(e as Error).message}\n`)
1467
1491
  }
1468
1492
  }
1469
1493
 
@@ -1474,22 +1498,22 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1474
1498
  try {
1475
1499
  const persistedTurns = listPersistedTurns(sessionId, cwd)
1476
1500
  const rec = await planRecoveryForSession(sessionId, cwd, { persistedTurns })
1477
- for (const w of rec.warnings) process.stderr.write(c.yellow(`[recovery] ${w}\n`))
1501
+ for (const w of rec.warnings) startupWrite(c.yellow(`[recovery] ${w}\n`))
1478
1502
  if (rec.directive) {
1479
- process.stderr.write(
1503
+ startupWrite(
1480
1504
  c.yellow(`[recovery] unfinished mutations need verification — see system note\n`),
1481
1505
  )
1482
1506
  recoveryAppendix = `\n\n# Recovery note (interrupted session — verify before re-executing)\n${rec.directive}`
1483
1507
  }
1484
1508
  } catch (e) {
1485
- process.stderr.write(`[warn] recovery plan failed: ${(e as Error).message}\n`)
1509
+ startupWrite(`[warn] recovery plan failed: ${(e as Error).message}\n`)
1486
1510
  }
1487
1511
 
1488
1512
  let durablePresentationEvents: DomainEvent[] = []
1489
1513
  try {
1490
1514
  durablePresentationEvents = loadPresentationEvents(sessionId, cwd)
1491
1515
  } catch (e) {
1492
- process.stderr.write(`[warn] presentation replay load failed: ${(e as Error).message}\n`)
1516
+ startupWrite(`[warn] presentation replay load failed: ${(e as Error).message}\n`)
1493
1517
  }
1494
1518
  let rebuiltPresentation: ReturnType<typeof rebuildFromDurable> | null = null
1495
1519
  try {
@@ -1499,7 +1523,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1499
1523
  sessionId,
1500
1524
  )
1501
1525
  } catch (e) {
1502
- process.stderr.write(`[warn] presentation replay failed: ${(e as Error).message}\n`)
1526
+ startupWrite(`[warn] presentation replay failed: ${(e as Error).message}\n`)
1503
1527
  }
1504
1528
  // P2.11 — replay watershed: state.seq sesaat setelah rebuild. Baris snapshot
1505
1529
  // pada/di bawah ini = replay/reconstructed; di atasnya = live (provenance
@@ -1520,7 +1544,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1520
1544
  try {
1521
1545
  await reconcileUndoRedoPointer(sessionId, cwd)
1522
1546
  } catch (e) {
1523
- process.stderr.write(`[warn] checkpoint reconcile failed: ${(e as Error).message}\n`)
1547
+ startupWrite(`[warn] checkpoint reconcile failed: ${(e as Error).message}\n`)
1524
1548
  }
1525
1549
 
1526
1550
  // Kontrak control-plane (Phase 6, E5): usage kompaksi LLM dikirim ke bus
@@ -1627,8 +1651,30 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1627
1651
  orphanEvidence: shadowDiag?.orphanEvidence ?? 0,
1628
1652
  unsupportedProjection,
1629
1653
  })
1654
+ // Fase 1 perf (butir 1): cache snapshot presentasi. Snapshot dibangun ulang
1655
+ // penuh pada tiap panggil — padahal panggil terjadi tiap paint (ketikan/scroll),
1656
+ // dan nilai yang dibangun tidak berubah di antara event. Reducer immutable:
1657
+ // shadowState hanya bermutasi via reduce(event); reduce menaikkan `state.seq`
1658
+ // HANYA pada event durable, dan semata field yang dipetakan ke snapshot pun
1659
+ // hanya diubah oleh event durable (model.delta/tool.progress/context.window
1660
+ // kembali awal / hanya menulis `progress` yang tak masuk snapshot). Karena itu
1661
+ // cache ber-key (objek state, seq) aman: seq berubah ⟺ snapshot berubah.
1662
+ let snapshotCache: {
1663
+ state: PresentationState
1664
+ seq: number
1665
+ value: UiPresentationSnapshot
1666
+ } | null = null
1630
1667
  const getPresentationSnapshot = (): UiPresentationSnapshot => {
1631
1668
  if (!shadowState) return { activities: [], turns: [] }
1669
+ // Objek `shadowState` identik + seq identik = konten tak berubah (lihat
1670
+ // alasan di atas); reuse tanpa membangun ulang ratusan objek per paint.
1671
+ if (
1672
+ snapshotCache &&
1673
+ snapshotCache.state === shadowState &&
1674
+ snapshotCache.seq === shadowState.seq
1675
+ ) {
1676
+ return snapshotCache.value
1677
+ }
1632
1678
  const activities: UiPresentationActivity[] = [...shadowState.activities.values()].map((a) => ({
1633
1679
  seq: a.seq,
1634
1680
  turnId: a.turnId,
@@ -1752,7 +1798,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1752
1798
  ...(entry.cause ? { cause: entry.cause } : {}),
1753
1799
  ...(entry.action ? { action: entry.action } : {}),
1754
1800
  }))
1755
- return {
1801
+ const snapshot: UiPresentationSnapshot = {
1756
1802
  activities,
1757
1803
  turns,
1758
1804
  conversation,
@@ -1763,6 +1809,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1763
1809
  results,
1764
1810
  diagnostics,
1765
1811
  }
1812
+ snapshotCache = { state: shadowState, seq: shadowState.seq, value: snapshot }
1813
+ return snapshot
1766
1814
  }
1767
1815
  const onPresentationEvent = (handler: (event: UiPresentationEvent) => void): (() => void) => {
1768
1816
  presentationSubscribers.add(handler)
@@ -2995,6 +3043,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2995
3043
  const { attachBusDebug } = await import("../src/ui/runtime/bus-debug.ts")
2996
3044
  const detachBusDebug = attachBusDebug(session.events)
2997
3045
  const usage = createUsageCollector(session.events, effectiveInitialModel, resumeUsageSnapshot)
3046
+ // B3 — persist parsial saat turn terputus (timeout/abort/error): kernel sudah
3047
+ // commit turnStore sampai batas aman ke committed store (RAM); di sini kita
3048
+ // flush ke SQLite (durable) supaya `--resume` tak amnesia. Fire-and-forget:
3049
+ // listener bus tak boleh melempar/blocking, dan persist gagal (mis. stale
3050
+ // writer) = best-effort. Penting untuk REPL+resume lintas proses.
3051
+ session.events.on("turn:interrupted", () => {
3052
+ void persistCurrent(usage.getSession()).catch(() => {})
3053
+ })
2998
3054
  // Statusline kaya = opt-in (default mati, shell tetap bersih). Data biaya
2999
3055
  // disuntik sebagai callback agar UI tak perlu impor lapisan policy.
3000
3056
  const richStatus = process.env.MINICODE_STATUSLINE === "rich"
@@ -3657,6 +3713,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3657
3713
  productionScheduler,
3658
3714
  schedulerObservability,
3659
3715
  adoption,
3716
+ startupNotices: deferStartup ? startupNotices : undefined,
3660
3717
  // [P1 M14] Same rule as the Scheduler handle above: one session owns one
3661
3718
  // runtime, reachable only through the session, never through a registry.
3662
3719
  productionRuntime,