minicode-ai 0.27.0 → 0.28.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/cli/args.ts +120 -16
  2. package/cli/commands/acp.ts +38 -28
  3. package/cli/commands/auth.ts +17 -17
  4. package/cli/commands/config.ts +65 -66
  5. package/cli/commands/daemon.ts +44 -16
  6. package/cli/commands/doctor.ts +11 -12
  7. package/cli/commands/exec.ts +35 -73
  8. package/cli/commands/mcp.ts +25 -8
  9. package/cli/commands/memory.ts +16 -24
  10. package/cli/commands/openwork.ts +6 -2
  11. package/cli/commands/pricing.ts +14 -12
  12. package/cli/commands/providers.ts +36 -57
  13. package/cli/commands/sessions.ts +24 -18
  14. package/cli/commands/skills.ts +33 -18
  15. package/cli/commands/stats.ts +15 -30
  16. package/cli/commands.ts +73 -44
  17. package/cli/context-command-run.ts +30 -18
  18. package/cli/index.ts +48 -98
  19. package/cli/model-manager.ts +7 -2
  20. package/cli/provider-manager.ts +33 -18
  21. package/cli/router.ts +41 -12
  22. package/cli/setup.ts +246 -123
  23. package/cli/tui.ts +303 -100
  24. package/docs/TERMINAL_CONTRACT.md +254 -69
  25. package/docs/UI_RENDER_PIPELINE.md +9 -1
  26. package/docs/agents.md +2 -2
  27. package/docs/architecture.md +3 -3
  28. package/docs/choosing-mode.md +7 -9
  29. package/docs/cli.md +3 -5
  30. package/docs/environment.md +1 -2
  31. package/docs/policy-sandbox.md +3 -3
  32. package/docs/repl.md +2 -2
  33. package/docs/tools.md +1 -1
  34. package/package.json +1 -1
  35. package/src/app/mentions.ts +60 -13
  36. package/src/app/rag-layer.ts +17 -20
  37. package/src/app/session.ts +119 -66
  38. package/src/app/tool-layer.ts +12 -17
  39. package/src/config.ts +64 -104
  40. package/src/constants.ts +4 -6
  41. package/src/daemon/capability.ts +8 -1
  42. package/src/daemon/control.ts +3 -2
  43. package/src/daemon/server.ts +57 -0
  44. package/src/hooks/run.ts +73 -41
  45. package/src/lib/db-path.ts +47 -0
  46. package/src/lib/process-tree.ts +62 -0
  47. package/src/lib/public-http.ts +88 -23
  48. package/src/lib/trusted-exec.ts +48 -1
  49. package/src/lsp/client.ts +62 -17
  50. package/src/mcp/client.ts +85 -38
  51. package/src/mcp/http-transport.ts +28 -16
  52. package/src/mcp/transport.ts +42 -6
  53. package/src/memory/files.ts +164 -134
  54. package/src/memory/vector.ts +371 -420
  55. package/src/policy/approval-binding.ts +122 -45
  56. package/src/policy/bash-guard.ts +18 -7
  57. package/src/policy/compaction.ts +51 -18
  58. package/src/policy/context-window.ts +31 -8
  59. package/src/policy/context.ts +62 -36
  60. package/src/policy/executor.ts +17 -7
  61. package/src/policy/microcompact.ts +4 -3
  62. package/src/policy/no-progress.ts +103 -22
  63. package/src/policy/permission.ts +36 -12
  64. package/src/policy/tool-contract.ts +74 -416
  65. package/src/policy/usage.ts +24 -2
  66. package/src/policy/verifier.ts +50 -2
  67. package/src/policy/work-mode.ts +28 -54
  68. package/src/presentation/adapter.ts +24 -16
  69. package/src/providers/provision.ts +6 -56
  70. package/src/providers/responses.ts +1 -0
  71. package/src/runtime/execution-journal.ts +4 -29
  72. package/src/sandbox/docker.ts +58 -34
  73. package/src/sandbox/mask.ts +157 -0
  74. package/src/sandbox/os.ts +107 -73
  75. package/src/session/authority.ts +29 -10
  76. package/src/session/context-projection.ts +6 -5
  77. package/src/session/open-work.ts +26 -3
  78. package/src/session/persistence.ts +25 -58
  79. package/src/session/verification.ts +170 -20
  80. package/src/skills/loader.ts +31 -16
  81. package/src/task/production-scheduler.ts +13 -1
  82. package/src/task/store.ts +20 -37
  83. package/src/telemetry/trace.ts +27 -0
  84. package/src/tools/ask_user.ts +1 -13
  85. package/src/tools/bash.ts +27 -92
  86. package/src/tools/code_run.ts +1 -1
  87. package/src/tools/context.ts +133 -0
  88. package/src/tools/delete_file.ts +3 -2
  89. package/src/tools/edit.ts +37 -72
  90. package/src/tools/git.ts +86 -9
  91. package/src/tools/glob.ts +26 -51
  92. package/src/tools/grep.ts +67 -57
  93. package/src/tools/hashline.ts +4 -0
  94. package/src/tools/lsp.ts +11 -8
  95. package/src/tools/mcp_call.ts +9 -6
  96. package/src/tools/memory.ts +56 -33
  97. package/src/tools/move_file.ts +36 -10
  98. package/src/tools/patch.ts +13 -21
  99. package/src/tools/read_file.ts +18 -25
  100. package/src/tools/read_image.ts +35 -33
  101. package/src/tools/submit_result.ts +29 -8
  102. package/src/tools/task.ts +74 -17
  103. package/src/tools/todo.ts +181 -74
  104. package/src/tools/web_fetch.ts +42 -2
  105. package/src/tools/web_search.ts +47 -8
  106. package/src/ui/approval/prompt.ts +206 -47
  107. package/src/ui/assistant/turn-status.ts +14 -5
  108. package/src/ui/footer.ts +4 -4
  109. package/src/ui/i18n/en.ts +47 -23
  110. package/src/ui/i18n/id.ts +76 -51
  111. package/src/ui/input/input.ts +4 -3
  112. package/src/ui/input/prompt-engine.ts +35 -5
  113. package/src/ui/render/activity-panel.ts +4 -2
  114. package/src/ui/render/hint.ts +7 -4
  115. package/src/ui/render/list.ts +32 -0
  116. package/src/ui/render/markdown.ts +6 -3
  117. package/src/ui/render/notice.ts +19 -0
  118. package/src/ui/render/table-grid.ts +7 -8
  119. package/src/ui/render/theme.ts +113 -39
  120. package/src/ui/runtime/screen.ts +74 -10
  121. package/src/ui/runtime/spinner.ts +19 -6
  122. package/src/ui/screens/dialog.ts +19 -1
  123. package/src/ui/screens/form.ts +80 -35
  124. package/src/ui/screens/model-manager.ts +82 -61
  125. package/src/ui/screens/output-window.ts +263 -0
  126. package/src/ui/screens/picker.ts +94 -81
  127. package/src/ui/screens/provider-manager.ts +100 -69
  128. package/src/ui/screens/wizard.ts +117 -28
  129. package/src/ui/tui/app.ts +196 -33
  130. package/src/ui/tui/transcript.ts +154 -25
  131. package/vendor/minicore/src/core/executor.ts +2 -0
  132. package/vendor/minicore/src/core/loop.ts +17 -6
  133. package/vendor/minicore/src/core/session.ts +3 -0
  134. package/vendor/minicore/src/core/tool.ts +1 -0
  135. package/vendor/minicore/src/providers/openai-compat.ts +28 -19
package/cli/setup.ts CHANGED
@@ -30,6 +30,7 @@ import {
30
30
  isAceEnabled,
31
31
  } from "../src/policy/consequence-engine.ts"
32
32
  import { minicodeEstimator } from "../src/policy/context.ts"
33
+ import { outputReserveFor } from "../src/policy/context-budget.ts"
33
34
  import { loadContextWindowOverlay, resolveContextWindow } from "../src/policy/context-window.ts"
34
35
  import type { NoProgressDetector } from "../src/policy/no-progress.ts"
35
36
  import type { PermissionAsk } from "../src/policy/permission.ts"
@@ -51,6 +52,7 @@ import {
51
52
  buildBaselineNote,
52
53
  buildVerifySnippet,
53
54
  checkBaseline,
55
+ classifyVerifyFailure,
54
56
  detectVerifyCommand,
55
57
  formatVerifyNotice,
56
58
  runVerify,
@@ -103,6 +105,7 @@ import { admitTaskWork } from "../src/runtime/runtime-task-admission.ts"
103
105
  import {
104
106
  acquireSessionWriter,
105
107
  checkWriterFresh,
108
+ describeSessionHolder,
106
109
  releaseSessionWriter,
107
110
  renewSessionWriter,
108
111
  StaleWriterError,
@@ -167,6 +170,7 @@ import {
167
170
  loadThreadHistoryWithSeq,
168
171
  type PresentationPersistStats,
169
172
  RefusedHistoryRewriteError,
173
+ readWriterEpoch,
170
174
  saveSession,
171
175
  saveSessionWorkMode,
172
176
  shrinkThreadHistory,
@@ -179,8 +183,9 @@ import {
179
183
  import { collectOperationalState } from "../src/session/runtime-header.ts"
180
184
  import { snapshotTree } from "../src/session/shadow-git.ts"
181
185
  import {
186
+ captureSessionEvaluationBaseline,
182
187
  checkWorkspaceIntegrity,
183
- collectModifiedFilesFromJournal,
188
+ collectSessionModifiedFiles,
184
189
  detectEvaluationTampering,
185
190
  } from "../src/session/verification.ts"
186
191
  import type { Skill } from "../src/skills/loader.ts"
@@ -204,6 +209,7 @@ import { setAskApprovalHook, setAskTextFn } from "../src/tools/ask_user.ts"
204
209
  import { killAllBackgroundJobs } from "../src/tools/bash.ts"
205
210
  import {
206
211
  setSubAgentExecutionRunner,
212
+ setSubAgentGovernance,
207
213
  setSubAgentParentRouting,
208
214
  setSubAgentParentRunId,
209
215
  setSubAgentWorkMode,
@@ -211,6 +217,7 @@ import {
211
217
  import {
212
218
  reconcileCompletionEvidence,
213
219
  setCompletionEvidence,
220
+ syncTodoViewsFromTaskStore,
214
221
  todoSession,
215
222
  } from "../src/tools/todo.ts"
216
223
  import { promptAsk, promptAskText } from "../src/ui/approval/prompt.ts"
@@ -292,7 +299,6 @@ export interface CliSessionOptions {
292
299
  * konsumen Desktop yang mengusulkan keputusan lewat op `approval.decide`.
293
300
  */
294
301
  permissionAsk?: PermissionAsk
295
- plan: boolean
296
302
  allowlist: boolean
297
303
  verify: boolean
298
304
  /** Audit #07 P0 opt-in: baca .minicode/config.json + allowlist lokal.
@@ -305,13 +311,13 @@ export interface CliSessionOptions {
305
311
  /** Harness-P2: scope tool sesi — explore = subset read-only. */
306
312
  toolScope?: "full" | "explore"
307
313
  /**
308
- * WorkMode (lapis intent di atas profil izin). Default DISCUSS = read-only;
309
- * PLAN = ceiling
310
- * rencana (explore + tool rencana). TIDAK pernah memperluas permission mode
314
+ * WorkMode (lapis intent 2-mode di atas profil izin). Default DISCUSS =
315
+ * ceiling read-only/investigasi/diskusi/rencana; EXECUTE (UI: BUILD) =
316
+ * eksekusi penuh sesuai profil izin. TIDAK pernah memperluas permission mode
311
317
  * (INV-WM1). Diisi CLI dari --work-mode / MINICODE_WORK_MODE; diserahkan ke
312
318
  * setupToolLayer (visibilitas) dan createMinicodeSession (handler ceiling).
313
319
  */
314
- workMode?: "DISCUSS" | "PLAN" | "EXECUTE"
320
+ workMode?: "DISCUSS" | "EXECUTE"
315
321
  /**
316
322
  * Transparansi resume. Benar bila operator memberi sinyal WorkMode eksplisit
317
323
  * (--work-mode / MINICODE_WORK_MODE). Saat resume tanpa sinyal eksplisit,
@@ -412,7 +418,7 @@ export interface CliSession {
412
418
  permissionMode: string
413
419
  /** WorkMode efektif sesi ini (default DISCUSS). Dipakai label/
414
420
  * readout TUI; diisi composition root dari flag/env. */
415
- workMode: "DISCUSS" | "PLAN" | "EXECUTE"
421
+ workMode: "DISCUSS" | "EXECUTE"
416
422
  /** P12 S2.2 Slice 5 — handle kontrol WorkMode runtime (transisi operator
417
423
  * lewat command `/work-mode`). Undefined bila sesi memakai handler izin
418
424
  * terinjeksi (policy, bukan mode — fail-closed). */
@@ -896,6 +902,24 @@ export function parseVerifyTestEvidence(
896
902
  }
897
903
  }
898
904
 
905
+ /** Kompaksi LLM child session bersama (`canPersistMemory: false` mencegah polusi global). */
906
+ export function createChildCompaction(opts: {
907
+ provider: unknown
908
+ model?: string
909
+ cwd?: string
910
+ contextWindowTokensForModel?: (model?: string) => number
911
+ getContextModel?: () => string | undefined
912
+ }) {
913
+ const getWindow = opts.contextWindowTokensForModel
914
+ return createLlmCompaction({
915
+ provider: opts.provider as never,
916
+ getModel: () => opts.getContextModel?.() ?? opts.model,
917
+ cwd: opts.cwd ?? process.cwd(),
918
+ ...(getWindow ? { getContextWindowTokens: () => getWindow(opts.model) } : {}),
919
+ canPersistMemory: () => false,
920
+ })
921
+ }
922
+
899
923
  export async function createCliSession(opts: CliSessionOptions): Promise<CliSession> {
900
924
  const {
901
925
  cwd,
@@ -910,7 +934,6 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
910
934
  verbose,
911
935
  allowAll,
912
936
  ask,
913
- plan,
914
937
  allowlist,
915
938
  verify,
916
939
  budget,
@@ -1016,27 +1039,18 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1016
1039
  throw new AdoptionRefusedError(adoption)
1017
1040
  }
1018
1041
  const moved = adoption.task
1042
+ await syncTodoViewsFromTaskStore(sessionId, cwd ?? process.cwd()).catch(() => undefined)
1019
1043
  startupWrite(
1020
1044
  `${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`)}`,
1021
1045
  )
1022
1046
  }
1023
1047
  // P0.2 (Q5): saat `--resume` tanpa sinyal WorkMode eksplisit, pulihkan
1024
- // WorkMode tersimpan dari metadata sesi (NULL legacy → default DISCUSS).
1025
- //
1026
- // [mode-architecture] --plan = alias warisan WorkMode PLAN (bukan permission
1027
- // mode). Dilipat di sini (satu titik untuk semua pemanggil: index/exec/acp).
1048
+ // WorkMode tersimpan dari metadata sesi (NULL/PLAN legacy → default DISCUSS).
1028
1049
  const persistedWorkMode = identity.resumed ? loadSessionWorkMode(sessionId, cwd) : undefined
1029
- const planAsWorkMode =
1030
- plan && !workModeExplicit && workMode === "DISCUSS" ? ("PLAN" as const) : workMode
1031
- if (plan && !workModeExplicit && workMode === "DISCUSS") {
1032
- startupWrite(`${c.dim("[deprecated] --plan is now WorkMode PLAN; use --work-mode PLAN\n")}`)
1033
- }
1034
- const effectiveWorkMode: "DISCUSS" | "PLAN" | "EXECUTE" =
1035
- identity.resumed && !workModeExplicit && !plan
1036
- ? (persistedWorkMode ?? "DISCUSS")
1037
- : planAsWorkMode
1050
+ const effectiveWorkMode: "DISCUSS" | "EXECUTE" =
1051
+ identity.resumed && !workModeExplicit ? (persistedWorkMode ?? "DISCUSS") : workMode
1038
1052
  // P0.2 (Q4): tolak startup (fail-closed) bila `--verify` digabung dengan
1039
- // WorkMode DISCUSS atau PLAN (baik dari flag/env maupun pulihan `--resume`).
1053
+ // WorkMode DISCUSS (baik dari flag/env maupun pulihan `--resume`).
1040
1054
  if (verify && effectiveWorkMode !== "EXECUTE") {
1041
1055
  releaseSessionWriter(sessionId, writerToken, cwd)
1042
1056
  throw new VerifyWorkModeConflictError(effectiveWorkMode)
@@ -1063,20 +1077,36 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1063
1077
  // Perpanjangan TAK PERNAH menyentuh writer_epoch (§16).
1064
1078
  let writerRenewTimer: ReturnType<typeof setInterval> | undefined
1065
1079
  let renewWarned = false
1066
- writerRenewTimer = setInterval(() => {
1067
- const out = renewSessionWriter(sessionId, writerToken, cwd)
1068
- if (out === "AUTHORITY_LOST" && !renewWarned) {
1069
- renewWarned = true
1070
- startupWrite(
1071
- `${c.yellow(`[writer] lease lost sid=${sessionId} boot=${bootId} — another writer took over; next mutation will be refused unless re-acquired\n`)}`,
1072
- )
1073
- try {
1074
- if (writerRenewTimer !== undefined) clearInterval(writerRenewTimer)
1075
- } catch {}
1076
- writerRenewTimer = undefined
1077
- }
1078
- }, SESSION_RENEW_INTERVAL_MS)
1079
- writerRenewTimer.unref?.()
1080
+ let writerClosed = false
1081
+ const stopWriterRenewTimer = () => {
1082
+ try {
1083
+ if (writerRenewTimer !== undefined) clearInterval(writerRenewTimer)
1084
+ } catch {}
1085
+ writerRenewTimer = undefined
1086
+ }
1087
+ const startWriterRenewTimer = () => {
1088
+ if (writerClosed || writerRenewTimer !== undefined) return
1089
+ renewWarned = false
1090
+ writerRenewTimer = setInterval(() => {
1091
+ const out = renewSessionWriter(sessionId, writerToken, cwd)
1092
+ if (out === "AUTHORITY_LOST") {
1093
+ stopWriterRenewTimer()
1094
+ // Lease tanpa pemilik aktif & epoch sama = dilepas bersih `/scheduler stop`; re-acquire di turn berikutnya.
1095
+ const holder = describeSessionHolder(sessionId, cwd)
1096
+ if (!holder.active && readWriterEpoch(sessionId, cwd) === expectedEpoch) {
1097
+ return
1098
+ }
1099
+ if (!renewWarned) {
1100
+ renewWarned = true
1101
+ startupWrite(
1102
+ `${c.yellow(`[writer] lease lost sid=${sessionId} boot=${bootId} — another writer took over; next mutation will be refused unless re-acquired\n`)}`,
1103
+ )
1104
+ }
1105
+ }
1106
+ }, SESSION_RENEW_INTERVAL_MS)
1107
+ writerRenewTimer.unref?.()
1108
+ }
1109
+ startWriterRenewTimer()
1080
1110
 
1081
1111
  // P2.2 — pagar pra-turn. JANGAN belanjakan provider untuk turn yang tak
1082
1112
  // bisa persist: basi → lewati turn (histori kernel utuh) + flag untuk
@@ -1096,6 +1126,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1096
1126
  )
1097
1127
  }
1098
1128
  expectedEpoch = re.admission.epoch
1129
+ startWriterRenewTimer()
1099
1130
  return true
1100
1131
  }
1101
1132
  markWriterStale("pre-turn authority refused (lease held by another writer)")
@@ -1242,7 +1273,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1242
1273
  const notice = localConfigNotice(cwd ?? process.cwd(), allowLocalConfig === true)
1243
1274
  if (notice) startupWrite(`${c.dim(notice)}\n`)
1244
1275
  } catch {}
1245
- if (sandboxNotice && !plan) startupWrite(`${sandboxNotice}\n`)
1276
+ if (sandboxNotice) startupWrite(`${sandboxNotice}\n`)
1246
1277
  // Default model = terakhir dipakai (global), bila tanpa --model dan masih
1247
1278
  // ada di config. Flag selalu menang; tak ada simpanan = provider pertama.
1248
1279
  if (!modelRef.current) {
@@ -1254,14 +1285,31 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1254
1285
  const effectiveDefaultModel = () => modelRef.current ?? cfg.providers[0]?.models[0]
1255
1286
  const warnedContextModels = new Set<string>()
1256
1287
  const warnedCatalogDrift = new Set<string>()
1288
+ // Eskalasi jendela konteks adaptif per model selama sesi ini hidup.
1289
+ // Menyimpan baseline saat eskalasi terjadi supaya jika user mengubah pin
1290
+ // lewat `/context set`, perubahan manual menang atas eskalasi sebelumnya.
1291
+ const escalatedWindows = new Map<string, { baseTokens: number; escalatedTokens: number }>()
1257
1292
  const routedContextModel = (model?: string) =>
1258
1293
  router.contextModelIdentity(model ?? effectiveDefaultModel()) ?? model ?? "default"
1259
1294
  const contextModelId = (requested?: string): string => {
1260
1295
  return routedContextModel(requested)
1261
1296
  }
1297
+ const resolveEffectiveContextWindow = (model?: string) => {
1298
+ const key = routedContextModel(model)
1299
+ const resolved = resolveContextWindow(cfg, key, contextWindowTokens)
1300
+ const esc = escalatedWindows.get(key)
1301
+ if (esc) {
1302
+ if (esc.baseTokens !== resolved.tokens) {
1303
+ escalatedWindows.delete(key)
1304
+ } else if (esc.escalatedTokens > resolved.tokens) {
1305
+ return { ...resolved, key, tokens: esc.escalatedTokens, escalated: true }
1306
+ }
1307
+ }
1308
+ return { ...resolved, key, escalated: false }
1309
+ }
1262
1310
  const getContextWindowTokens = (model?: string) => {
1263
- const resolved = resolveContextWindow(cfg, routedContextModel(model), contextWindowTokens)
1264
- if (resolved.source === "safe-default") {
1311
+ const resolved = resolveEffectiveContextWindow(model)
1312
+ if (resolved.source === "safe-default" && !resolved.escalated) {
1265
1313
  const key = resolved.providerId
1266
1314
  ? `${resolved.providerId}::${resolved.model ?? "default"}`
1267
1315
  : (resolved.model ?? "default")
@@ -1288,8 +1336,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1288
1336
  return resolved.tokens
1289
1337
  }
1290
1338
  const getReportedContextWindowTokens = (model?: string) => {
1291
- const resolved = resolveContextWindow(cfg, routedContextModel(model), contextWindowTokens)
1292
- return resolved.source === "safe-default" ? undefined : resolved.tokens
1339
+ const resolved = resolveEffectiveContextWindow(model)
1340
+ return resolved.source === "safe-default" && !resolved.escalated ? undefined : resolved.tokens
1293
1341
  }
1294
1342
  router.updateContextWindowResolver(getContextWindowTokens)
1295
1343
  // Muat overlay jendela konteks models.dev sekali sebelum resolusi dipakai;
@@ -1306,6 +1354,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1306
1354
  cfg,
1307
1355
  prompt,
1308
1356
  cwd,
1357
+ allowLocalConfig: allowLocalConfig === true,
1309
1358
  // RAG retrieval tak boleh menulis access_count di mode tanpa-mutasi.
1310
1359
  // [mode-architecture] PermissionMode readonly/plan tak lagi ada sebagai sumbu
1311
1360
  // persetujuan; ceiling tanpa-mutasi kini diekspresikan via WorkMode
@@ -1341,10 +1390,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1341
1390
  let lastAceDecision: ConsequenceDecision | null = null
1342
1391
  // Streak kegagalan verify (dipakai ACE sebagai `repeatedFailureCount`).
1343
1392
  let verifyFailureStreak = 0
1344
- // Baseline kanonik saat resume (isi `messages` yang SUDAH durable). Setelah
1345
- // proyeksi menutupi prefix, buffer konteks TIDAK lagi superset histori
1346
- // kanonik — jadi persist harus menyusun ulang: baseline ++ ekor baru.
1393
+ // Baseline kanonik saat resume (hanya prefix sebelum tail/proyeksi). Setelah
1394
+ // proyeksi/budget-tail memotong prefix, persist harus menyusun ulang prefix + ekor.
1347
1395
  let contextCanonicalBaseline: readonly unknown[] | undefined
1396
+ let budgetTailPrefix: readonly unknown[] | undefined
1397
+ let budgetTailInitialMessages: readonly Message[] | undefined
1348
1398
  if (identity.resumed) {
1349
1399
  // P0.2 (Q5 / Invariant #6) — transparansi resume: WorkMode dipulihkan dari
1350
1400
  // metadata sesi bila operator tidak memberi sinyal eksplisit (NULL legacy
@@ -1352,8 +1402,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1352
1402
  // otoritas sesi hasil resume selalu terlihat eksplisit.
1353
1403
  const resumeNotice = !workModeExplicit
1354
1404
  ? persistedWorkMode !== undefined
1355
- ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} restored from session; pass --work-mode DISCUSS|PLAN|BUILD to override\n`
1356
- : `[resume] WorkMode default DISCUSS (legacy session without saved workMode); pass --work-mode PLAN|BUILD to change\n`
1405
+ ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} restored from session; pass --work-mode DISCUSS|BUILD to override\n`
1406
+ : `[resume] WorkMode default DISCUSS (legacy session without saved workMode); pass --work-mode BUILD to change\n`
1357
1407
  : persistedWorkMode !== undefined && persistedWorkMode !== effectiveWorkMode
1358
1408
  ? `[resume] WorkMode ${effectiveWorkMode === "EXECUTE" ? "BUILD" : effectiveWorkMode} (overriding saved ${persistedWorkMode === "EXECUTE" ? "BUILD" : persistedWorkMode})\n`
1359
1409
  : ""
@@ -1427,7 +1477,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1427
1477
  )
1428
1478
  const projectionSummary = durableProjection
1429
1479
  const selectedWindow = getContextWindowTokens()
1430
- const messageBudget = selectedWindow
1480
+ const selectionReserve = selectedWindow > 16_384 ? outputReserveFor(selectedWindow) : 0
1481
+ const messageBudget = Math.max(0, selectedWindow - selectionReserve)
1431
1482
  // N1: turunkan frontier kanonis dari baris yang BARU DIBACA (sumber
1432
1483
  // kebenaran saat ini) dan teruskan ke selector — freshness dihitung
1433
1484
  // via assessContextFreshness (BUKAN hard-code "fresh"). Selector tetap
@@ -1468,7 +1519,17 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1468
1519
  runtimeContextMetadata = runtimeMetadataFromSelection(selection, revision)
1469
1520
  if (selection.contextOnly) {
1470
1521
  contextOnlyArtifact = selection.contextOnly
1471
- contextCanonicalBaseline = rowsForSelector.map((r) => r.message)
1522
+ // Hanya prefix sebelum `coveredSeq` — ekor `[coveredSeq..N-1]` SUDAH ada di `initialMessages[1..]`.
1523
+ contextCanonicalBaseline = rowsForSelector
1524
+ .filter((r) => r.seq < selection.coveredSeq)
1525
+ .map((r) => r.message)
1526
+ } else if (selection.selectionBasis === "budget-tail") {
1527
+ const baseSeq =
1528
+ selection.messages.length === 0 ? Infinity : (selection.frontier?.baseSeq ?? 0)
1529
+ if (baseSeq > 0) {
1530
+ budgetTailPrefix = rowsForSelector.filter((r) => r.seq < baseSeq).map((r) => r.message)
1531
+ budgetTailInitialMessages = selection.messages
1532
+ }
1472
1533
  }
1473
1534
  resumeTurnCount = meta.turnCount
1474
1535
  startupConsoleError(
@@ -1873,10 +1934,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1873
1934
  }
1874
1935
  : {
1875
1936
  provider: router,
1876
- model: modelRef.current ?? cfg.providers[0]?.models[0] ?? "deepseek-chat",
1937
+ getModel: () => modelRef.current ?? cfg.providers[0]?.models[0] ?? "deepseek-chat",
1877
1938
  }),
1878
1939
  cwd: cwd ?? process.cwd(),
1879
1940
  getContextWindowTokens,
1941
+ canPersistMemory: () =>
1942
+ (workModeControl?.getWorkMode() ?? effectiveWorkMode) === "EXECUTE" &&
1943
+ (permissions?.getMode() ?? permissionMode) !== "readonly" &&
1944
+ (permissions?.getMode() ?? permissionMode) !== "plan",
1880
1945
  onUsage: (u) => {
1881
1946
  try {
1882
1947
  // Angka sudah dinormalisasi di compactWithLlm (negatif/NaN → skip).
@@ -1956,12 +2021,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1956
2021
  // (hanya PM, bukan WorkMode) membuat delegate_task melahirkan anak tanpa
1957
2022
  // ceiling WorkMode.
1958
2023
  setSubAgentWorkMode(() => workModeControl?.getWorkMode() ?? effectiveWorkMode)
2024
+ setSubAgentGovernance(() => ({
2025
+ restrictBash,
2026
+ allowLocalConfig: allowLocalConfig === true,
2027
+ }))
1959
2028
 
1960
2029
  let permissions: PermissionControl | undefined
1961
2030
  let noProgressDetector: NoProgressDetector | null = null
1962
- // Jendela konteks hasil eskalasi adaptif (0 = belum ada). Dipakai /status
1963
- // untuk menampilkan angka efektif, bukan tebakan awal.
1964
- const escalatedWindowRef = { current: 0 }
1965
2031
  const effectiveMaxTurns = (() => {
1966
2032
  const raw = (opts as { maxTurns?: number }).maxTurns ?? Number(process.env.MINICODE_MAX_TURNS)
1967
2033
  return typeof raw === "number" && Number.isFinite(raw) && raw >= 1 ? Math.floor(raw) : undefined
@@ -1983,6 +2049,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
1983
2049
  provider: router,
1984
2050
  tools: sessionTools,
1985
2051
  cwd,
2052
+ sessionId,
1986
2053
  permissionMode,
1987
2054
  restrictBash,
1988
2055
  allowLocalConfig,
@@ -2000,6 +2067,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2000
2067
  // (daemon → ApprovalBroker). Tanpa injeksi tetap prompt TTY; non-TTY ⇒
2001
2068
  // deny (fail-closed), bukan izin diam-diam.
2002
2069
  ask: opts.permissionAsk ?? promptAsk,
2070
+ allowNonTtyAsk: opts.permissionAsk !== undefined,
2003
2071
  // Cermin observability persetujuan → adaptor presentasi. Keputusan gate
2004
2072
  // tetap milik permission handler; hook ini hanya melaporkan.
2005
2073
  onApprovalEvent: (e) => {
@@ -2044,16 +2112,39 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2044
2112
  onNoProgress: (detector) => {
2045
2113
  noProgressDetector = detector
2046
2114
  },
2115
+ isExplicitContextWindow: (m) => {
2116
+ const resolved = resolveContextWindow(cfg, routedContextModel(m), contextWindowTokens)
2117
+ return resolved.source === "override" || resolved.origin === "user"
2118
+ },
2047
2119
  // Eskalasi jendela konteks: beritahu user secara eksplisit. Tanpa ini,
2048
2120
  // jendela yang naik otomatis terasa seperti angka ajaib — user perlu tahu
2049
2121
  // bahwa ada BUKTI overflow dan berapa nilai barunya, agar bisa memutuskan
2050
2122
  // menyetel `contextWindows` permanen bila perlu.
2051
2123
  onContextWindowEscalated: (info) => {
2052
- startupWrite(
2053
- `${c.yellow(`[context] window raised ${info.fromTokens} → ${info.toTokens} tokens for ${sanitizeAnsi(info.model)} after a verified context overflow (observed ${info.observedTokens}). Set provider.contextWindows to make it permanent.
2054
- `)}`,
2055
- )
2056
- escalatedWindowRef.current = info.toTokens
2124
+ const currentKey = routedContextModel()
2125
+ const baseForInfo = resolveContextWindow(cfg, info.model, contextWindowTokens).tokens
2126
+ const baseForCurrent = resolveContextWindow(cfg, currentKey, contextWindowTokens).tokens
2127
+ escalatedWindows.set(info.model, {
2128
+ baseTokens: baseForInfo,
2129
+ escalatedTokens: info.toTokens,
2130
+ })
2131
+ if (currentKey !== info.model && info.model.endsWith(`::${currentKey}`)) {
2132
+ escalatedWindows.set(currentKey, {
2133
+ baseTokens: baseForCurrent,
2134
+ escalatedTokens: info.toTokens,
2135
+ })
2136
+ }
2137
+ const msg = `[context] window raised ${info.fromTokens} → ${info.toTokens} tokens for ${sanitizeAnsi(info.model)} after a verified context overflow (observed ${info.observedTokens}). Set provider.contextWindows to make it permanent.`
2138
+ if (enterRepl) {
2139
+ presentation?.noteContextCutoff({
2140
+ reason: msg,
2141
+ usedTokens: info.observedTokens,
2142
+ windowTokens: info.toTokens,
2143
+ turnId: session.state.turnCount,
2144
+ })
2145
+ } else {
2146
+ startupWrite(`${c.yellow(`${msg}\n`)}`)
2147
+ }
2057
2148
  },
2058
2149
  ...(maxSteps ? { maxSteps } : {}),
2059
2150
  ...(keepRecentTurns ? { keepRecentTurns } : {}),
@@ -2094,36 +2185,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2094
2185
  // setelah verify-settle). Dedupe per (id,status,revision) agar tidak
2095
2186
  // double-report saat verify menyelesaikan task yang sama.
2096
2187
  const taskStatusSeen = new Map<string, string>()
2097
- const emitTaskStatuses = (): void => {
2098
- try {
2099
- // Sinkron: one-shot/exec dapat keluar tepat setelah turn selesai; dynamic
2100
- // import async bisa tidak sempat berjalan sebelum proses berhenti.
2101
- const tasks = new TaskStore(cwd ?? process.cwd()).listTasks(sessionId)
2102
- for (const task of tasks) {
2103
- const key = `${task.status}:${task.revision}`
2104
- if (taskStatusSeen.get(task.id) === key) continue
2105
- taskStatusSeen.set(task.id, key)
2106
- presentation?.noteTaskStatus({
2107
- taskId: task.id,
2108
- status: task.status,
2109
- ...(task.parentId ? { parentId: task.parentId } : {}),
2110
- ...(task.dependsOn?.length ? { dependsOn: [...task.dependsOn] } : {}),
2111
- revision: task.revision,
2112
- verification: task.verification
2113
- ? { verdict: task.verification.verdict, checkedAt: task.verification.checkedAt }
2114
- : { verdict: "unverified", checkedAt: "" },
2115
- turnId: session.state.turnCount,
2116
- })
2117
- }
2118
- } catch {}
2119
- }
2120
- session.events.on("execution:completed", (e) => {
2121
- const call = (e as { execution?: { call?: { name?: unknown } } }).execution?.call
2122
- if (call?.name === "todo_write") emitTaskStatuses()
2123
- })
2124
- // P2.3: transisi AUTHORITATIVE (claim/verify/merge/cancel/fail) diproyeksikan
2125
- // setelah commit DB oleh sink TaskStore — bukan ditebak dari perubahan teks.
2126
- setTaskTransitionSink(({ task }) => {
2188
+ const noteTaskChanged = (task: ReturnType<TaskStore["listTasks"]>[number]) => {
2127
2189
  const key = `${task.status}:${task.revision}`
2128
2190
  if (taskStatusSeen.get(task.id) === key) return
2129
2191
  taskStatusSeen.set(task.id, key)
@@ -2138,7 +2200,20 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2138
2200
  : { verdict: "unverified", checkedAt: "" },
2139
2201
  turnId: session.state.turnCount,
2140
2202
  })
2203
+ }
2204
+ const emitTaskStatuses = (): void => {
2205
+ try {
2206
+ for (const task of new TaskStore(cwd ?? process.cwd()).listTasks(sessionId)) {
2207
+ noteTaskChanged(task)
2208
+ }
2209
+ } catch {}
2210
+ }
2211
+ session.events.on("execution:completed", (e) => {
2212
+ const call = (e as { execution?: { call?: { name?: unknown } } }).execution?.call
2213
+ if (call?.name === "todo_write") emitTaskStatuses()
2141
2214
  })
2215
+ // P2.3: proyeksi transisi AUTHORITATIVE pasca-commit DB.
2216
+ setTaskTransitionSink(({ task }) => noteTaskChanged(task))
2142
2217
  try {
2143
2218
  if (!shadowState) shadowState = createInitialState(sessionId)
2144
2219
  if (!shadowDiag) shadowDiag = createReducerDiagnostics()
@@ -2291,6 +2366,14 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2291
2366
  }
2292
2367
 
2293
2368
  session.events.on("turn:started", () => {
2369
+ // Temuan #10: hanya rekam git snapshot sebelum turn ketika sesi dalam mode
2370
+ // eksekusi penuh (BUILD / EXECUTE) dan bukan mode izin read-only/plan.
2371
+ const liveWm = workModeControl?.getWorkMode() ?? effectiveWorkMode
2372
+ const livePm = permissions?.getMode() ?? permissionMode
2373
+ if (liveWm !== "EXECUTE" || livePm === "readonly" || livePm === "plan") {
2374
+ preTurnPromise = null
2375
+ return
2376
+ }
2294
2377
  preTurnPromise = beginTurnSnapshot(sessionId, cwd ?? ".")
2295
2378
  })
2296
2379
  session.events.on("execution:completed", (e) => {
@@ -2536,6 +2619,9 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2536
2619
  ? (process.env.MINICODE_VERIFY_CMD ?? cfg.verifyCommand ?? detectVerifyCommand(cwd) ?? "")
2537
2620
  : ""
2538
2621
  const verifyActive = verifyCommand.length > 0
2622
+ if (verifyActive) {
2623
+ await captureSessionEvaluationBaseline(sessionId, cwd ?? process.cwd()).catch(() => {})
2624
+ }
2539
2625
  // Sumber bukti completion untuk domain task (INV-003). Menyimpan hasil
2540
2626
  // verify TERAKHIR: pada saat `todo_write` berjalan, verify untuk turn ini
2541
2627
  // BELUM pernah jalan (verify terjadi setelah turn selesai), jadi bukti yang
@@ -2555,8 +2641,11 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2555
2641
  setCompletionEvidence(() => {
2556
2642
  const liveWm = workModeControl?.getWorkMode() ?? effectiveWorkMode
2557
2643
  const livePm = permissions?.getMode() ?? permissionMode
2558
- if (!verifyActive || liveWm !== "EXECUTE" || livePm === "readonly" || livePm === "plan") {
2559
- return { verdict: "unverified" }
2644
+ if (!verifyActive) return { verdict: "unverified" }
2645
+ // Jangan pernah meloloskan `completed` tanpa bukti hanya karena user
2646
+ // beralih mode BUILD -> DISCUSS/readonly/plan di tengah sesi `--verify`.
2647
+ if (liveWm !== "EXECUTE" || livePm === "readonly" || livePm === "plan") {
2648
+ return { verdict: "unverified", requireVerified: true }
2560
2649
  }
2561
2650
  // [Fase 3 / LOOP-INV-12, LOOP-G20] Saat `--verify` aktif tetapi verifier
2562
2651
  // belum menghasilkan verdict pertama, tandai `requireVerified: true` agar
@@ -2592,17 +2681,19 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2592
2681
  let integrityDetail = ""
2593
2682
  let tamperReason = ""
2594
2683
  const loaded = await loadJournal(sessionId, effectiveRoot).catch(() => null)
2595
- if (loaded?.status === "valid") {
2596
- const modified = collectModifiedFilesFromJournal(loaded.records)
2597
- if (modified.length > 0) {
2598
- const integrity = await checkWorkspaceIntegrity(modified, effectiveRoot)
2599
- integrityOk = integrity.ok
2600
- if (!integrity.ok) integrityDetail = integrity.summary
2601
- // [Fase 6A / ACE-02] Evaluator/gate yang disentuh membatalkan seluruh
2602
- // klaim verifikasi (fail-closed) — tidak ada jalan "hijau" via curang.
2603
- const tamper = await detectEvaluationTampering(modified, effectiveRoot)
2604
- if (tamper.tampered) tamperReason = tamper.reason
2605
- }
2684
+ const modified = await collectSessionModifiedFiles(
2685
+ sessionId,
2686
+ effectiveRoot,
2687
+ loaded?.status === "valid" ? loaded.records : undefined,
2688
+ )
2689
+ if (modified.length > 0) {
2690
+ const integrity = await checkWorkspaceIntegrity(modified, effectiveRoot)
2691
+ integrityOk = integrity.ok
2692
+ if (!integrity.ok) integrityDetail = integrity.summary
2693
+ // [Fase 6A / ACE-02] Evaluator/gate yang disentuh membatalkan seluruh
2694
+ // klaim verifikasi (fail-closed) — tidak ada jalan "hijau" via curang.
2695
+ const tamper = await detectEvaluationTampering(modified, effectiveRoot)
2696
+ if (tamper.tampered) tamperReason = tamper.reason
2606
2697
  }
2607
2698
  const effectiveOk = result.ok && integrityOk && tamperReason === ""
2608
2699
  const effectiveOutput = !integrityOk
@@ -2628,14 +2719,13 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2628
2719
  // consequence deterministik. `repeatedFailureCount` memakai streak
2629
2720
  // SEBELUM percobaan ini (kontrak evaluateConsequence).
2630
2721
  const tampered = tamperReason.length > 0
2631
- const transient =
2632
- !effectiveOk &&
2633
- /ECONN|ETIMEDOUT|timed? ?out|rate.?limit|429|503|network|EAI_AGAIN|socket hang up/i.test(
2634
- effectiveOutput,
2635
- )
2636
- const permissionBlocked =
2637
- !effectiveOk &&
2638
- /permission denied|EACCES|EPERM|operation not permitted/i.test(effectiveOutput)
2722
+ const { transient, permissionBlocked } = effectiveOk
2723
+ ? { transient: false, permissionBlocked: false }
2724
+ : classifyVerifyFailure({
2725
+ ok: false,
2726
+ output: effectiveOutput,
2727
+ timedOut: result.timedOut,
2728
+ })
2639
2729
  const failureType: AceFailureType = effectiveOk ? null : transient ? "timeout" : "functional"
2640
2730
  const repeatedBefore = verifyFailureStreak
2641
2731
  verifyFailureStreak = effectiveOk ? 0 : verifyFailureStreak + 1
@@ -2694,7 +2784,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2694
2784
  noProgressDetector?.noteVerificationPassed()
2695
2785
  }
2696
2786
  try {
2697
- settleSessionVerifyingTasks(effectiveRoot, sessionId, {
2787
+ const settled = settleSessionVerifyingTasks(effectiveRoot, sessionId, {
2698
2788
  ok: effectiveOk,
2699
2789
  verdict: effectiveOk ? "passed" : "failed",
2700
2790
  exitCode: effectiveExitCode,
@@ -2706,6 +2796,16 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2706
2796
  // bukan hanya efek samping TaskStore. Dedupe yang sama dengan jalur
2707
2797
  // todo_write agar satu transisi tidak dilaporkan dua kali.
2708
2798
  emitTaskStatuses()
2799
+ if (settled.length > 0) {
2800
+ const synced = await syncTodoViewsFromTaskStore(sessionId, effectiveRoot).catch(() => null)
2801
+ if (synced) {
2802
+ presentation?.notePlanReconciled({
2803
+ todos: synced,
2804
+ sessionId,
2805
+ turnId: session.state.turnCount,
2806
+ })
2807
+ }
2808
+ }
2709
2809
  } catch {}
2710
2810
  const evidence = parseVerifyTestEvidence(verifyCommand, effectiveOutput)
2711
2811
  if (evidence) {
@@ -2752,7 +2852,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
2752
2852
  }
2753
2853
  return
2754
2854
  }
2755
- await runRunHooks(phase, ctx, signal)
2855
+ await runRunHooks(phase, ctx, signal, { allowLocal: allowLocalConfig === true })
2756
2856
  }
2757
2857
 
2758
2858
  /**
@@ -3083,14 +3183,15 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3083
3183
  const verifyRunnableNow =
3084
3184
  verifyActive && liveWm === "EXECUTE" && livePm !== "readonly" && livePm !== "plan"
3085
3185
  if (!verifyRunnableNow) {
3086
- // P0.2 (Q4 / Invariant #8): bila operator menurunkan WorkMode ke DISCUSS/
3087
- // PLAN (atau PM ke readonly/plan) di tengah sesi TUI, lewati baseline
3186
+ // P0.2 (Q4 / Invariant #8): bila operator menurunkan WorkMode ke DISCUSS
3187
+ // (atau PM ke readonly/plan) di tengah sesi TUI, lewati baseline
3088
3188
  // shell verify, self-heal, dan auto-memory write secara otomatis.
3089
3189
  if (verifyActive && !verifySkippedNotice) {
3090
3190
  verifySkippedNotice = true
3091
3191
  const modeLabel = liveWm !== "EXECUTE" ? `work-mode ${liveWm}` : `${livePm} mode`
3092
3192
  warnLine(`verify skipped in ${modeLabel} (read-only contract)`)
3093
3193
  }
3194
+ await runHooksGated("pre", { phase: "pre", prompt: p, cwd }, signal)
3094
3195
  await runOnce(p, signal)
3095
3196
  await runHooksGated(
3096
3197
  "post",
@@ -3099,6 +3200,7 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3099
3200
  )
3100
3201
  return
3101
3202
  }
3203
+ await runHooksGated("pre", { phase: "pre", prompt: p, cwd }, signal)
3102
3204
  // P2.1 — baseline-first: bila baseline sudah merah sebelum agen menyentuh
3103
3205
  // apa pun, tempelkan catatan agar agen memperbaiki dulu, bukan menumpuk
3104
3206
  // fitur di atas baseline rusak (yang hanya memperparah keadaan).
@@ -3162,10 +3264,15 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3162
3264
  // `reconcileCompletionEvidence` sudah best-effort + menulis diagnostik
3163
3265
  // sendiri, jadi pemanggil tak perlu try/catch (dan tak perlu menambah
3164
3266
  // writer di file ini — pagu OAP-008).
3165
- const reconciled = await reconcileCompletionEvidence(sessionId, cwd ?? ".", {
3166
- verdict: "failed",
3167
- detail: `last verification failed (${lastVerify.command}): ${lastVerify.output.slice(0, 200)}`,
3168
- })
3267
+ const reconciled = await reconcileCompletionEvidence(
3268
+ sessionId,
3269
+ cwd ?? ".",
3270
+ {
3271
+ verdict: "failed",
3272
+ detail: `last verification failed (${lastVerify.command}): ${lastVerify.output.slice(0, 200)}`,
3273
+ },
3274
+ { syncTaskStore: true },
3275
+ )
3169
3276
  if (reconciled) {
3170
3277
  presentation?.notePlanReconciled({
3171
3278
  todos: reconciled,
@@ -3292,12 +3399,22 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3292
3399
  // sudah bersaproven (migrated_compacted=1).
3293
3400
  const buffer = session.state.history
3294
3401
  const tail = stripContextOnly(buffer, contextOnlyArtifact)
3402
+ const hasBudgetPrefixIntact =
3403
+ budgetTailPrefix !== undefined &&
3404
+ budgetTailInitialMessages !== undefined &&
3405
+ buffer.length >= budgetTailInitialMessages.length &&
3406
+ budgetTailInitialMessages.every((m, idx) => {
3407
+ const cur = buffer[idx]
3408
+ return cur === m || JSON.stringify(cur) === JSON.stringify(m)
3409
+ })
3295
3410
  const durableHistory: readonly unknown[] =
3296
3411
  contextOnlyArtifact !== undefined &&
3297
3412
  contextCanonicalBaseline !== undefined &&
3298
3413
  tail.length !== buffer.length
3299
3414
  ? [...contextCanonicalBaseline, ...tail]
3300
- : buffer
3415
+ : hasBudgetPrefixIntact
3416
+ ? [...budgetTailPrefix!, ...buffer]
3417
+ : buffer
3301
3418
  try {
3302
3419
  await saveSession(sessionId, cwd, undefined, durableHistory, usageData, {
3303
3420
  expectedEpoch,
@@ -3499,18 +3616,26 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3499
3616
  contextModelIdentity?: (model?: string) => string | undefined
3500
3617
  }
3501
3618
  const contextWindowTokensForModel = childProvider.contextWindowTokensForModel
3619
+ const getContextModel = () =>
3620
+ childProvider.contextModelIdentity?.(spec.model) ?? spec.model
3502
3621
  const child = await createMinicodeSession({
3503
3622
  provider: spec.provider as never,
3504
3623
  tools: spec.tools as never,
3505
3624
  cwd: spec.cwd,
3506
3625
  systemExtra: spec.systemExtra,
3507
3626
  model: spec.model,
3627
+ compaction: createChildCompaction({
3628
+ provider: spec.provider,
3629
+ model: spec.model,
3630
+ cwd: spec.cwd,
3631
+ contextWindowTokensForModel,
3632
+ getContextModel,
3633
+ }),
3508
3634
  ...(contextWindowTokensForModel
3509
3635
  ? {
3510
3636
  contextWindowTokens: contextWindowTokensForModel(spec.model),
3511
3637
  contextWindowTokensForModel,
3512
- getContextModel: () =>
3513
- childProvider.contextModelIdentity?.(spec.model) ?? spec.model,
3638
+ getContextModel,
3514
3639
  }
3515
3640
  : {}),
3516
3641
  // [PHASE 6U] The child conversation id is NOT a kernel config field.
@@ -3779,10 +3904,8 @@ export async function createCliSession(opts: CliSessionOptions): Promise<CliSess
3779
3904
  } catch (e) {
3780
3905
  warnLine(`run terminal mark failed: ${(e as Error).message}`)
3781
3906
  }
3782
- try {
3783
- if (writerRenewTimer !== undefined) clearInterval(writerRenewTimer)
3784
- } catch {}
3785
- writerRenewTimer = undefined
3907
+ writerClosed = true
3908
+ stopWriterRenewTimer()
3786
3909
  releaseSessionWriter(sessionId, writerToken, cwd)
3787
3910
  // SATU-SATUNYA pause() mid-process yang tersisa: teardown sesi. stdin
3788
3911
  // TTY kini mengalir seumur proses (tanpa pause per prompt) agar siklus