minicode-ai 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -2,6 +2,7 @@ import { Database } from "bun:sqlite"
2
2
  import { existsSync, mkdirSync } from "node:fs"
3
3
  import { dirname, join, resolve } from "node:path"
4
4
  import { homeDir } from "../../src/lib/db-path.ts"
5
+ import { resolveSessionDisplayTarget } from "../../src/session/identity.ts"
5
6
  import { deleteJournalFile, findOrphanJournals } from "../../src/session/journal.ts"
6
7
  import {
7
8
  getSessionTtlDays,
@@ -64,7 +65,9 @@ export async function handleSessions(
64
65
  console.error("usage: minicode sessions export <id> [--jsonl]")
65
66
  process.exit(2)
66
67
  }
67
- const sess = loadSession(id, getArg("--cwd"))
68
+ // P2.1 read-compat: alias eksak resolve ke kanonik; selain itu input
69
+ // apa adanya (lenien untuk baca; tulis tetap jalur kanonik tunggal).
70
+ const sess = loadSession(resolveSessionDisplayTarget(id, getArg("--cwd")), getArg("--cwd"))
68
71
  if (!sess) {
69
72
  console.error(`session "${id}" not found - see: minicode sessions list`)
70
73
  process.exit(1)
@@ -1,5 +1,7 @@
1
1
  import { readFileSync } from "node:fs"
2
2
  import { resolve } from "node:path"
3
+ import type { RuntimeView } from "../../src/runtime/runtime-status.ts"
4
+ import { currentRuntimeView } from "../../src/runtime/runtime-status-provider.ts"
3
5
  import { type StepTrace, summarizeStepTraces } from "../../src/telemetry/trace.ts"
4
6
  import { c } from "../../src/ui/render/theme.ts"
5
7
 
@@ -11,6 +13,23 @@ interface TraceRow {
11
13
  durationMs?: number
12
14
  }
13
15
 
16
+ /**
17
+ * Ringkasan status runtime untuk output manusia.
18
+ *
19
+ * Memakai model kanonik yang SAMA dengan yang dipakai daemon (runtime-status.ts)
20
+ * — bukan hitungan status sendiri. Kalau perhitungan ini diulang di tempat
21
+ * lain, kita punya dua sumber status; itu yang dilarang pemilik repo ini.
22
+ */
23
+ function runtimeStatusSummary(view: RuntimeView): string {
24
+ const caps = view.advertisedCapabilities.length > 0 ? view.advertisedCapabilities.join(",") : "-"
25
+ const missing =
26
+ view.unavailableCapabilities.length > 0
27
+ ? ` · tak-tersedia=${view.unavailableCapabilities.join(",")}`
28
+ : ""
29
+ const note = view.note ? ` · ${view.note}` : ""
30
+ return `phase=${view.phase} · admission=${view.admission} · health=${view.health} · termination=${view.termination} · bukti=${view.evidenceState} · kapabilitas=${caps} · anak-ter-supervisi=${view.supervisedChildren}${missing}${note}`
31
+ }
32
+
14
33
  export async function handleStats(getArg: (name: string) => string | undefined): Promise<never> {
15
34
  const cwdArg = getArg("--cwd")
16
35
  const asJson = getArg("--json") !== undefined || process.argv.includes("--json")
@@ -52,6 +71,11 @@ export async function handleStats(getArg: (name: string) => string | undefined):
52
71
  } catch {}
53
72
  const steps = summarizeStepTraces(stepRows)
54
73
 
74
+ // [P13.1] Status runtime: dari model kanonik, bukan sumber status kedua.
75
+ // Proses `minicode stats` berdiri sendiri (tak ada sesi runtime di dalamnya),
76
+ // jadi view-nya ABSENT — itu jawaban jujur, bukan kegagalan.
77
+ const runtimeView = currentRuntimeView()
78
+
55
79
  // --json dulu diterima tanpa keluhan lalu diabaikan; kini benar-benar bekerja.
56
80
  if (asJson) {
57
81
  console.log(
@@ -63,22 +87,28 @@ export async function handleStats(getArg: (name: string) => string | undefined):
63
87
  cost,
64
88
  avgMs,
65
89
  steps,
90
+ runtime: runtimeView,
66
91
  }),
67
92
  )
68
93
  process.exit(0)
69
94
  }
70
- console.log(
95
+ // [P13.1] Keluaran manusia dikumpulkan lalu ditulis SEKALI (OAP-008: jumlah
96
+ // writer di berkas ini hanya boleh turun, bukan naik). Baris status runtime
97
+ // masuk ke kumpulan yang sama — bukan writer tambahan.
98
+ const human: string[] = [
71
99
  `Runs: ${total} · Resolved: ${ok}/${total} · Tokens in=${inputTokens} out=${outputTokens} · Cost: $${cost.toFixed(4)} · Avg ${avgMs}ms`,
72
- )
73
- if (total === 0) console.log(c.dim(` (no traces yet in ${file})`))
100
+ `Runtime: ${runtimeStatusSummary(runtimeView)}`,
101
+ ]
102
+ if (total === 0) human.push(c.dim(` (no traces yet in ${file})`))
74
103
  if (steps.tools > 0) {
75
104
  const topDeny = steps.topDenied.map((t) => `${t.tool}×${t.n}`).join(", ")
76
105
  const topReason = steps.topDenyReasons.map((r) => `${r.reason}×${r.n}`).join(", ")
77
106
  // F1.2: peak token kumulatif antar step — satu angka "seboros apa sesi ini".
78
107
  const peak = steps.peakTotalTokens > 0 ? ` · Peak tok: ${steps.peakTotalTokens}` : ""
79
- console.log(
108
+ human.push(
80
109
  `Tools: ${steps.tools} · Denied: ${steps.denied} (${(steps.denyRate * 100).toFixed(1)}%) · Errors: ${steps.errors}${topDeny ? ` · Top denied: ${topDeny}` : ""}${topReason ? ` · Reason: ${topReason}` : ""}${steps.sandboxes.length ? ` · Sandbox: ${steps.sandboxes.join(",")}` : ""}${peak}`,
81
110
  )
82
111
  }
112
+ console.log(human.join("\n"))
83
113
  process.exit(0)
84
114
  }
package/cli/commands.ts CHANGED
@@ -2,8 +2,14 @@ import { basename, resolve as resolvePath } from "node:path"
2
2
  import { loadConfig, saveLastModel } from "../src/config.ts"
3
3
  import type { Usage } from "../src/policy/usage.ts"
4
4
  import { refreshProviderModels } from "../src/providers/provision.ts"
5
+ import type { RuntimeProductionMode } from "../src/runtime/production-execution.ts"
5
6
  import { listSessions, loadSession } from "../src/session/persistence.ts"
6
7
  import type { Skill } from "../src/skills/loader.ts"
8
+ import type { ProductionSchedulerHandle } from "../src/task/production-scheduler.ts"
9
+ import {
10
+ describeOperatorState,
11
+ type SchedulerObservability,
12
+ } from "../src/task/scheduler-observability.ts"
7
13
  import { type MsgKey, t } from "../src/ui/i18n/locale.ts"
8
14
  import { formatUsd } from "../src/ui/render/money.ts"
9
15
  import { glyphs } from "../src/ui/render/theme.ts"
@@ -43,6 +49,29 @@ export interface CommandContext {
43
49
  * budgetStatus; /status menampilkannya eksplisit, bukan menyimpulkan dari
44
50
  * angka. */
45
51
  budgetState: () => "ok" | "over" | "unknown-strict"
52
+ /**
53
+ * [PHASE 6AB] The operator control surface for the Scheduler.
54
+ *
55
+ * [DESIGN DECISION] Optional and structurally narrow: it carries exactly two
56
+ * references, both owned by the composition root that built THIS session. A
57
+ * command handler therefore cannot reach another session's Scheduler, cannot
58
+ * reach a process-global one, and — when absent — has no scheduler vocabulary at
59
+ * all. `cli/router.ts`'s one-shot subcommands never set it, so `/scheduler` in a
60
+ * piped invocation reports the truthful OFF rather than pretending.
61
+ */
62
+ scheduler?: SchedulerControl
63
+ /**
64
+ * [P1 M15] Runtime mode sesi ini — diteruskan ke proses resume agar mode
65
+ * tidak turun diam-diam (F1b). Opsional dan narrow seperti `scheduler`:
66
+ * absen = child default `off` (fail-closed, perilaku sebelum F1b).
67
+ */
68
+ runtimeMode?: RuntimeProductionMode
69
+ }
70
+
71
+ /** The two objects `/scheduler` needs, injected by the composition root. */
72
+ export interface SchedulerControl {
73
+ readonly handle: ProductionSchedulerHandle
74
+ readonly observability: SchedulerObservability
46
75
  }
47
76
 
48
77
  /**
@@ -117,12 +146,18 @@ export const BUILTIN_COMMANDS: BuiltinCommand[] = [
117
146
  * Opsi A audit UX: undo/redo/clear/copy/history tidak punya duplikat lain. */
118
147
  export const DRIVER_HELP_COMMANDS: BuiltinCommand[] = [
119
148
  { name: "mode", args: "[name]", descKey: "help.desc.mode" },
149
+ { name: "work-mode", args: "[DISCUSS|PLAN|EXECUTE]", descKey: "help.desc.work-mode" },
120
150
  { name: "lang", args: "[en|id]", descKey: "help.desc.lang" },
121
151
  { name: "undo", descKey: "help.desc.undo" },
122
152
  { name: "redo", descKey: "help.desc.redo" },
123
153
  { name: "clear", descKey: "help.desc.clear" },
124
- { name: "copy", descKey: "help.desc.copy" },
154
+ { name: "copy", args: "[n]", descKey: "help.desc.copy" },
125
155
  { name: "history", descKey: "help.desc.history" },
156
+ // [PHASE 6AB] Help-only, not in the dropdown: the scheduler is off in every
157
+ // default session, so advertising it in completion would put a command that
158
+ // always answers "not enabled" one keystroke away. It stays fully discoverable
159
+ // in /help, which is where an operator enabling the flag will look.
160
+ { name: "scheduler", args: "[status|run|stop]", descKey: "help.desc.scheduler" },
126
161
  ]
127
162
 
128
163
  /** Pintasan papan tombol TUI — didokumentasikan di /help, bukan hanya di kode. */
@@ -130,6 +165,7 @@ const KEYBOARD_HELP: [string, MsgKey][] = [
130
165
  ["enter", "help.k.submit"],
131
166
  ["tab / shift+tab", "help.k.cycleMode"],
132
167
  ["up / down", "help.k.history"],
168
+ ["mouse wheel", "help.k.mouse"],
133
169
  ["pgup / pgdn", "help.k.scroll"],
134
170
  ["home / end (prompt)", "help.k.jumpTop"],
135
171
  ["left / right", "help.k.move"],
@@ -228,7 +264,7 @@ async function resumeById(target: string, ctx: CommandContext): Promise<boolean>
228
264
  const entryPath = resolvePath(import.meta.dir, "index.ts")
229
265
  const child = spawn(
230
266
  process.execPath,
231
- [entryPath, `--resume=${target}`, ...(ctx.cwd ? [`--cwd=${ctx.cwd}`] : [])],
267
+ buildResumeSpawnArgs(entryPath, target, ctx.cwd, ctx.runtimeMode),
232
268
  { stdio: "inherit", env: { ...process.env, MINICODE_RESUME_NEW: "1" } },
233
269
  )
234
270
  void waitChildExit(child).then((code) => process.exit(code ?? 0))
@@ -236,8 +272,179 @@ async function resumeById(target: string, ctx: CommandContext): Promise<boolean>
236
272
  return true
237
273
  }
238
274
 
275
+ /**
276
+ * [P1 Hygiene F1b] Argv untuk proses resume. Murni + diekspor untuk test.
277
+ *
278
+ * Mode runtime diteruskan apa adanya (`off`/`constructed`/`owned`): anak
279
+ * mem-parse argv-nya sendiri dan default `off` bila flag absen, jadi TIDAK
280
+ * meneruskan = diam-diam downgrade. Tidak ada derivasi dari env, tidak ada
281
+ * upgrade diam-diam, dan identitas resume (`--resume=<target>`) tak berubah.
282
+ */
283
+ export function buildResumeSpawnArgs(
284
+ entryPath: string,
285
+ target: string,
286
+ cwd: string | undefined,
287
+ runtimeMode: RuntimeProductionMode | undefined,
288
+ ): string[] {
289
+ return [
290
+ entryPath,
291
+ `--resume=${target}`,
292
+ ...(cwd ? [`--cwd=${cwd}`] : []),
293
+ ...(runtimeMode ? ["--runtime", runtimeMode] : []),
294
+ ]
295
+ }
296
+
239
297
  /** Petunjuk ke daftar pintasan lengkap, dipakai di /help. */
240
298
 
299
+ /**
300
+ * [PHASE 6AB] `/scheduler [status|run|stop]`.
301
+ *
302
+ * Three subcommands, because §2 asks for the MINIMUM justified surface:
303
+ *
304
+ * - `run` - one explicit scheduling cycle. This is the trigger.
305
+ * - `stop` - the operator stop §9 asked for, replacing "kill the process".
306
+ * - `status` (default) - the observability §7 asked for, as a readable surface.
307
+ *
308
+ * [DESIGN DECISION] No `start`. Once stopped, an operator restarts the process. A
309
+ * hot-toggle would need a runtime switch 6U already rejected as unable to stop a
310
+ * live turn, and §11 explicitly says not to introduce one.
311
+ *
312
+ * [DESIGN DECISION] `run` awaits the cycle, so the operator sees the outcome on the
313
+ * same screen. That is a deliberate consequence of choosing the explicit-command
314
+ * surface over a background timer: there is no other moment at which the answer
315
+ * becomes available.
316
+ */
317
+ async function handleSchedulerCommand(args: string, ctx: CommandContext): Promise<void> {
318
+ const sub = args.trim().toLowerCase()
319
+ const ctl = ctx.scheduler
320
+ // [DESIGN DECISION] One writer, not twenty-three.
321
+ //
322
+ // OAP-008 (test/writer-inventory.test.ts) caps direct console writers per file and
323
+ // refuses a silent increase. The first draft of this command emitted one line per
324
+ // output, which added 23 writers to `cli/commands.ts` - exactly the pattern the
325
+ // audit exists to prevent, and the audit was right to fail.
326
+ //
327
+ // Collecting into an array and emitting once keeps the whole command at a single
328
+ // writer. The bound still moves, 29 -> 30, and that one step is declared in the
329
+ // inventory with its reason rather than absorbed quietly.
330
+ const out: string[] = []
331
+ const emit = (): void => {
332
+ if (out.length) console.log(out.join("\n"))
333
+ }
334
+
335
+ // [DESIGN DECISION] An absent control surface and an inert handle are DIFFERENT
336
+ // failures and get different words. "OFF" is a decision the operator made;
337
+ // "unavailable" means this command has no route at all, and conflating them
338
+ // would hide a wiring regression behind a reassuring message.
339
+ if (!ctl) {
340
+ out.push(t("sched.unavailable"))
341
+ emit()
342
+ return
343
+ }
344
+
345
+ const { handle, observability } = ctl
346
+
347
+ if (sub === "" || sub === "status") {
348
+ schedulerStatusLines(ctx, ctl, out)
349
+ emit()
350
+ return
351
+ }
352
+
353
+ if (sub === "run") {
354
+ if (!handle.enabled) {
355
+ out.push(t("sched.notEnabled"))
356
+ emit()
357
+ return
358
+ }
359
+ if (!handle.isActive()) {
360
+ // Reachable after `/scheduler stop`, after `close()`, or after the renewal
361
+ // heartbeat observed a lost lease. Report it; do NOT silently succeed.
362
+ out.push(t("sched.notActive"))
363
+ schedulerStatusLines(ctx, ctl, out)
364
+ emit()
365
+ return
366
+ }
367
+ out.push(t("sched.running"))
368
+ const result = await handle.fire("explicit-command")
369
+ if (result === null) {
370
+ // The handle returns null only when inactive, which was just checked;
371
+ // reaching here means state changed underneath us. Report, never fake.
372
+ out.push(t("sched.refusedUnknown"))
373
+ schedulerStatusLines(ctx, ctl, out)
374
+ emit()
375
+ return
376
+ }
377
+ switch (result.outcome) {
378
+ case "EVALUATED":
379
+ out.push(
380
+ observability.lastCycleStopReason === "no-candidates"
381
+ ? t("sched.ranNothing")
382
+ : t("sched.ranDone"),
383
+ )
384
+ break
385
+ case "COALESCED":
386
+ out.push(t("sched.coalesced"))
387
+ break
388
+ case "REFUSED_NOT_RUNNING":
389
+ out.push(t("sched.refusedNotRunning"))
390
+ break
391
+ case "REFUSED_ALREADY_PENDING":
392
+ out.push(t("sched.refusedPending"))
393
+ break
394
+ }
395
+ schedulerStatusLines(ctx, ctl, out)
396
+ emit()
397
+ return
398
+ }
399
+
400
+ if (sub === "stop") {
401
+ if (!handle.enabled) {
402
+ out.push(t("sched.notEnabled"))
403
+ emit()
404
+ return
405
+ }
406
+ if (!handle.isActive()) {
407
+ // [PHASE 6AB] Section 10 idempotency, in the operator's hands: stopping a
408
+ // stopped scheduler is a no-op that says so, not an error.
409
+ out.push(t("sched.alreadyStopped"))
410
+ emit()
411
+ return
412
+ }
413
+ // [DESIGN DECISION] `scheduler-stopped`, not `emergency-stop`. The latter is
414
+ // reserved for authority loss; an operator deliberately pressing stop is the
415
+ // supported path, and the reason lands in the activity log.
416
+ await handle.stop("scheduler-stopped")
417
+ observability.noteStopped("scheduler-stopped")
418
+ out.push(t("sched.stopped"))
419
+ emit()
420
+ return
421
+ }
422
+
423
+ out.push(t("sched.usage"))
424
+ emit()
425
+ }
426
+
427
+ function schedulerStatusLines(ctx: CommandContext, ctl: SchedulerControl, out: string[]): void {
428
+ const { handle, observability } = ctl
429
+ const snap = observability.status(handle)
430
+ out.push(`\n${t("sched.title")}`)
431
+ out.push(` ${t("sched.state")}: ${describeOperatorState(snap.state)}`)
432
+ out.push(` ${t("sched.session")}: ${ctx.sessionId}`)
433
+ out.push(` ${t("sched.authority")}: ${handle.isActive() ? t("sched.held") : t("sched.none")}`)
434
+ out.push(
435
+ ` ${t("sched.counts")}: ${t("sched.cEvaluated")}=${snap.counts.evaluations} ` +
436
+ `${t("sched.cCoalesced")}=${snap.counts.coalesced} ${t("sched.cRefused")}=${snap.counts.refused} ` +
437
+ `${t("sched.cExec")}=${snap.counts.executions} ${t("sched.cFail")}=${snap.counts.failures}`,
438
+ )
439
+ if (snap.lastTaskId) out.push(` ${t("sched.lastTask")}: ${snap.lastTaskId}`)
440
+ if (snap.lastCycleStop) out.push(` ${t("sched.lastStop")}: ${snap.lastCycleStop}`)
441
+ if (snap.lastError) out.push(` ${t("sched.lastError")}: ${snap.lastError}`)
442
+ if (snap.recent.length > 0) {
443
+ out.push(`\n ${t("sched.recent")}`)
444
+ for (const n of snap.recent.slice(-5)) out.push(` ${n.line}`)
445
+ }
446
+ }
447
+
241
448
  export async function handleBuiltinCommand(
242
449
  rawInput: string,
243
450
  ctx: CommandContext,
@@ -342,6 +549,14 @@ export async function handleBuiltinCommand(
342
549
  return { handled: true }
343
550
  }
344
551
 
552
+ case "scheduler": {
553
+ // [PHASE 6AB] THE production-reachable trigger. 6AA's blocker was that
554
+ // `fire()` had no caller: the handle existed, held a lease, and was reachable
555
+ // from nowhere. This case is that caller.
556
+ await handleSchedulerCommand(args, ctx)
557
+ return { handled: true }
558
+ }
559
+
345
560
  case "sync": {
346
561
  // Re-detect model dari semua provider -> config diperbarui otomatis.
347
562
  // Meneruskan flag local sesi: tanpa opt-in /sync tak boleh menghubungi
package/cli/index.ts CHANGED
@@ -1,5 +1,4 @@
1
1
  #!/usr/bin/env bun
2
- import { randomUUID } from "node:crypto"
3
2
  import { readFileSync } from "node:fs"
4
3
  import { resolve as resolvePath } from "node:path"
5
4
  import { NoProviderError } from "../src/app/provider-layer.ts"
@@ -8,8 +7,14 @@ import { parseCompactKeepTurns } from "../src/policy/compaction.ts"
8
7
  import { createRateLimiter } from "../src/policy/ratelimit.ts"
9
8
  import { resolveSandbox, sandboxRefusalReason } from "../src/policy/sandbox-policy.ts"
10
9
  import { budgetStatus } from "../src/policy/usage.ts"
10
+ import { resolveRuntimeMode } from "../src/runtime/production-execution.ts"
11
+ import { AdoptionRefusedError, parseAdoptTaskArg } from "../src/session/cross-session-adoption.ts"
12
+ import { mintSessionId } from "../src/session/identity.ts"
11
13
  import { attachMutationJournal } from "../src/session/journal.ts"
12
14
  import { findSkill, renderSkill } from "../src/skills/loader.ts"
15
+ // [PHASE 6X] The ONE production gate resolver, imported directly so the call site
16
+ // and its tests cannot drift apart. See the note at the `schedulerEnabled` line.
17
+ import { GATE_ENABLED, resolveSchedulerGate } from "../src/task/production-scheduler.ts"
13
18
  import { writeTrace } from "../src/telemetry/trace.ts"
14
19
  import { setSubAgentSessionFactory } from "../src/tools/task.ts"
15
20
  import { formatError, takePendingError } from "../src/ui/assistant/simple.ts"
@@ -21,6 +26,7 @@ import {
21
26
  promptFromArgs,
22
27
  getArg as rawGetArg,
23
28
  readPrompt,
29
+ resolveWorkModeFlag,
24
30
  } from "./args.ts"
25
31
  import { dispatch } from "./router.ts"
26
32
  import { createCliSession } from "./setup.ts"
@@ -41,8 +47,10 @@ Usage:
41
47
  minicode "prompt" [options] # one-shot run
42
48
  minicode exec "prompt" [--json] # headless CI mode (JSON stream)
43
49
  minicode acp # JSON-RPC stdio server for IDEs (minimal subset)
50
+ minicode daemon <cmd> # daemon host / status / stop / issue / sessions
44
51
  echo "prompt" | minicode # via pipe
45
52
  minicode sync # refresh models from all providers
53
+ minicode openwork # cross-session unfinished work (P14, read-only)
46
54
  Options:
47
55
  -h, --help show help
48
56
  -v, --version show version
@@ -50,6 +58,9 @@ Options:
50
58
  --cwd <dir> workspace root (default .)
51
59
  --allow-local-config trust .minicode/config.json in workspace (default: ignore)
52
60
  --resume <id> resume session id
61
+ --adopt-task <source>/<taskId>
62
+ P14: adopt one unfinished task from another session into this
63
+ session (explicit authority; scheduler is NOT started)
53
64
  --model <name> override model (provider::model)
54
65
  --provider <id> force provider id
55
66
  --session <id> session id (default random)
@@ -67,11 +78,21 @@ Options:
67
78
  --budget <usd> session cost limit
68
79
  --budget-strict unknown cost + spend counts as over budget (fail-closed default)
69
80
  --tool-scope <s> full (default) | explore (read-only subset)
81
+ --work-mode <m> DISCUSS | PLAN | EXECUTE (default). Intent layer above the
82
+ permission mode: DISCUSS = read-only, PLAN = plan tools only.
70
83
  --tui deprecated no-op (interactive mode is always the fullscreen TUI)
84
+ --enable-scheduler EXPERIMENTAL: opt in to the autonomous scheduler (default: off).
85
+ Manual only - run /scheduler run. No timer; autonomous turns are
86
+ readonly. Inspect with /scheduler status; release with /scheduler stop.
87
+ --runtime <mode> off (default) | constructed | owned. Execution architecture:
88
+ off = current behaviour, unchanged. constructed = runtime + durable
89
+ journal built, turns still run the legacy way. owned = every turn is
90
+ admitted through the runtime (kernel + durable journal); a rejected
91
+ admission runs nothing. Unknown value = off.
71
92
 
72
93
  TUI: /help /provider /model /sync /status /sessions /init /exit /mode /undo /redo /clear /copy /history /compact /thinking /minimize
73
- Keys: Enter submit · Tab/Shift+Tab mode · Up/Down history · PgUp/PgDn scroll (Shift = half page)
74
- Home/End jump to transcript top/tail · Ctrl+R search · Esc/Ctrl+C abort turn (twice = quit) · Ctrl+D exit
94
+ Keys: Enter submit · Tab/Shift+Tab mode · Up/Down history · Mouse wheel/PgUp/PgDn scroll (Shift = half page)
95
+ Home/End jump to transcript top/tail · Ctrl+R search · Esc abort turn (twice = quit) · Ctrl+D exit
75
96
  Subcommand flags (config/mcp/sessions/skills/exec/...): see 'minicode <cmd> --help'.
76
97
  `
77
98
 
@@ -128,10 +149,25 @@ setSubAgentSessionFactory(async (spec) => {
128
149
  const { journal, ...coreSpec } = spec
129
150
  const session = await createMinicodeSession(coreSpec)
130
151
  if (journal) {
152
+ const childPresentation = (
153
+ await import("../src/presentation/adapter.ts")
154
+ ).createPresentationAdapter(session.events, { sessionId: journal.sessionId })
155
+ const { appendPresentationEvents } = await import("../src/session/persistence.ts")
156
+ let childWrite = Promise.resolve()
157
+ childPresentation.onEvent((event) => {
158
+ childWrite = childWrite
159
+ .then(() => appendPresentationEvents(journal.sessionId, spec.cwd, [event]).then(() => {}))
160
+ .catch(() => {})
161
+ })
162
+ session.events.on("turn:completed", () => {
163
+ void childWrite.finally(() => childPresentation.dispose())
164
+ })
131
165
  attachMutationJournal(session, {
132
166
  sessionId: journal.sessionId,
133
167
  cwd: spec.cwd,
134
168
  childOf: journal.parentSessionId,
169
+ evidenceMode: "canonical",
170
+ onCommitted: (info) => childPresentation.noteFileChanged(info),
135
171
  })
136
172
  }
137
173
  return session
@@ -164,7 +200,9 @@ if (args.includes("-h") || args.includes("--help")) {
164
200
  'minicode "prompt" [options]',
165
201
  'minicode exec "prompt" [--json]',
166
202
  "minicode acp",
203
+ "minicode daemon <start|status|stop|issue|sessions>",
167
204
  "minicode providers|models|sync|config|mcp|skills|sessions|stats|memory",
205
+ "minicode openwork — cross-session unfinished work portfolio (P14)",
168
206
  ],
169
207
  options: [
170
208
  { flag: "--version", desc: "show version" },
@@ -175,6 +213,26 @@ if (args.includes("-h") || args.includes("--help")) {
175
213
  desc: "trust .minicode/config.json in workspace (default: ignore)",
176
214
  },
177
215
  { flag: "--resume <id>", desc: "resume session id" },
216
+ {
217
+ flag: "--adopt-task <source>/<taskId>",
218
+ desc:
219
+ "P14: explicitly adopt ONE unfinished task from another session into this " +
220
+ "session (workspace-local; requires both sessions' writer authority; " +
221
+ "does not start the scheduler)",
222
+ },
223
+ {
224
+ flag: "--enable-scheduler",
225
+ // [PHASE 6AB] REWRITTEN. 6AA recorded this text as the single most
226
+ // misleading fact an operator would meet: it promised "autonomous
227
+ // background task execution" for a process that could not execute
228
+ // anything at all. The replacement says what the flag does, how to
229
+ // make it act, and — the part the old text omitted — that triggering
230
+ // is MANUAL and there is no recurring background loop.
231
+ desc:
232
+ "EXPERIMENTAL: opt in to the autonomous scheduler for this session (default: off). " +
233
+ "Runs on manual /scheduler run only — no background timer, no recurring polling. " +
234
+ "Autonomous turns are readonly. Use /scheduler status|stop inside the session.",
235
+ },
178
236
  { flag: "--model <name>", desc: "override model (provider::model)" },
179
237
  { flag: "--provider <id>", desc: "force provider id" },
180
238
  { flag: "--session <id>", desc: "session id" },
@@ -195,6 +253,10 @@ if (args.includes("-h") || args.includes("--help")) {
195
253
  { flag: "--budget <usd>", desc: "session cost limit" },
196
254
  { flag: "--budget-strict", desc: "unknown cost + spend counts as over budget (default)" },
197
255
  { flag: "--tool-scope <full|explore>", desc: "tool subset (explore = read-only)" },
256
+ {
257
+ flag: "--work-mode <DISCUSS|PLAN|EXECUTE>",
258
+ desc: "intent layer: DISCUSS (read-only), PLAN (plan tools only), EXECUTE (default)",
259
+ },
198
260
  { flag: "--json", desc: "JSON output (help/exec)" },
199
261
  { flag: "--tui", desc: "deprecated no-op (interactive is always the fullscreen TUI)" },
200
262
  ],
@@ -220,14 +282,61 @@ const cwd = cwdRaw ? resolvePath(cwdRaw) : undefined
220
282
  // eksplisit per-invokasi (flag atau env). Tanpa ini repo clone-an bisa
221
283
  // men-spawn MCP server dan menyedot prompt ke endpoint penyerang.
222
284
  const allowLocal = allowLocalConfig(args)
285
+ // P12 S2.2 — WorkMode (lapis intent di ATAS permission mode). Flag mengalahkan
286
+ // env; keduanya tak ada = EXECUTE. Nilai tak dikenal = EXECUTE + warning
287
+ // (fail-closed, jangan pernah melebar). `--plan` (permission mode) TIDAK
288
+ // disamakan dengan WorkMode PLAN — keduanya lapisan terpisah.
289
+ const workModeResolved = resolveWorkModeFlag(getArg)
290
+ const workMode = workModeResolved.workMode
291
+ if (workModeResolved.warning) process.stderr.write(`[warn] ${workModeResolved.warning}\n`)
292
+ // [PHASE 6U] Autonomous Scheduler opt-in. DEFAULT OFF.
293
+ //
294
+ // [DESIGN DECISION] `hasFlag` and nothing else - deliberately NOT `|| process.env.`,
295
+ // unlike the permission and plan flags above. This one must not be inheritable:
296
+ // `process.env` is passed to sub-agents, MCP servers and LSP servers, so an env
297
+ // gate would switch autonomous execution on for children the person running the
298
+ // process never asked for. This flag is the only mechanism, and it is per-invocation.
299
+ //
300
+ // [PHASE 6X] ...but `hasFlag` is the WRONG matcher here (6V FINDING-01). It accepts
301
+ // any `name=value` form, so `--enable-scheduler=false`, `=0` and even `=whatever`
302
+ // all ENABLED the Scheduler - the exact opposite of what the person asked for. The
303
+ // gate itself was already correct and unit-tested; the production CALLER was not
304
+ // using it. So the call site now uses the same resolver the tests pin, which makes
305
+ // "the flag is absent" and "the flag is negated" the same answer, as they must be.
306
+ //
307
+ // The generic `hasFlag` is deliberately left alone: its value-form behaviour is
308
+ // correct for the permission and plan flags, and changing it would alter unrelated
309
+ // CLI semantics. The bug was in choosing it for a valueless flag.
310
+ const schedulerEnabled = resolveSchedulerGate(args) === GATE_ENABLED
311
+ // [P1 M15] Mode runtime produksi. Deterministik per invokasi (flag CLI, bukan
312
+ // env): `off` (default) = jalur legacy utuh, `constructed` = runtime + jurnal
313
+ // dibangun tanpa memiliki eksekusi, `owned` = admission wajib lewat M13 →
314
+ // Kernel. Nilai tak dikenal gagal ke `off` + warning (fail-closed, bukan
315
+ // jatuh ke mode yang lebih agresif tanpa diminta).
316
+ const runtimeModeResolution = resolveRuntimeMode(args)
317
+ if (runtimeModeResolution.warning) {
318
+ process.stderr.write(`[warn] ${runtimeModeResolution.warning}\n`)
319
+ }
320
+ const runtimeMode = runtimeModeResolution.mode
223
321
  const resumeId = getArg("--resume")
224
- ?.replace(/[^A-Za-z0-9._-]/g, "-")
225
- .slice(0, 64)
322
+ // P2.1: flag mentah diteruskan apa adanya; sanitasi + keputusan identitas
323
+ // tunggal milik resolveSessionIdentity (SATU aturan sanitizer, tak ada drift
324
+ // 64-vs-60 di call-site). bootId volatil hanya untuk korelasi diagnostik.
325
+ const sessionFlag = getArg("--session")
326
+ // [P14] Adopsi task eksplisit. Format salah = tolak SEBELUM sesi/lease dibuat;
327
+ // jangan biarkan operator mengira adopsi berjalan padahal argumennya diabaikan.
328
+ const adoptTaskRaw = getArg("--adopt-task")
329
+ const adoptTaskParsed = adoptTaskRaw === undefined ? null : parseAdoptTaskArg(adoptTaskRaw)
330
+ if (adoptTaskRaw !== undefined && adoptTaskParsed === null) {
331
+ console.error(
332
+ `[adopt] invalid --adopt-task value: "${adoptTaskRaw}" (expected <source-session>/<taskId>, task id like t1)`,
333
+ )
334
+ process.exit(1)
335
+ }
336
+ const adoptTask = adoptTaskParsed ?? undefined
337
+ const bootId = mintSessionId()
226
338
  const modelOverride = getArg("--model")
227
339
  const providerOverride = getArg("--provider")
228
- const rawSessionId = getArg("--session") ?? randomUUID().slice(0, 8)
229
- const sessionId =
230
- rawSessionId.replace(/[^A-Za-z0-9._-]/g, "-").slice(0, 64) || randomUUID().slice(0, 8)
231
340
  const maxStepsRaw = getArg("--max-steps")
232
341
  let maxSteps = maxStepsRaw ? Number(maxStepsRaw) : undefined
233
342
  if (maxStepsRaw && (!Number.isFinite(maxSteps) || (maxSteps as number) <= 0)) {
@@ -384,8 +493,10 @@ let ctx: Awaited<ReturnType<typeof createCliSession>>
384
493
  try {
385
494
  ctx = await createCliSession({
386
495
  cwd,
387
- sessionId,
496
+ sessionId: sessionFlag ?? "",
388
497
  resumeId,
498
+ bootId,
499
+ ...(adoptTask ? { adoptTask } : {}),
389
500
  modelOverride,
390
501
  providerOverride,
391
502
  prompt,
@@ -397,9 +508,15 @@ try {
397
508
  allowlist: effectiveAllowlist,
398
509
  verify,
399
510
  allowLocalConfig: allowLocal,
511
+ // [PHASE 6U] Off unless the token was literally passed.
512
+ schedulerEnabled,
513
+ // [P1 M15] Reroute runtime (default `off`).
514
+ runtimeMode,
400
515
  budget,
401
516
  budgetStrict,
402
517
  toolScope,
518
+ // P12 S2.2 — WorkMode efektif (sudah di-resolve, default EXECUTE).
519
+ workMode,
403
520
  maxSteps,
404
521
  contextWindowTokens,
405
522
  ...(keepRecentTurns !== undefined ? { keepRecentTurns } : {}),
@@ -415,6 +532,16 @@ try {
415
532
  console.error(e.message)
416
533
  process.exit(1)
417
534
  }
535
+ // [P14] Refusal adopsi adalah keputusan kebijakan, bukan crash: tampilkan
536
+ // satu baris, bukan stack trace. Detail sudah memuat alasan yang bisa
537
+ // ditindaklanjuti operator (stale, busy, conflict, unresolved relation).
538
+ // DIGABUNG ke cabang NoProvider di atas (satu writer untuk kelas
539
+ // "setup menolak, bukan gagal"): menambah penulis kedua hanya untuk satu
540
+ // format pesan menaikkan inventaris writer tanpa menambah informasi.
541
+ if (e instanceof AdoptionRefusedError) {
542
+ console.error(e.message)
543
+ process.exit(1)
544
+ }
418
545
  throw e
419
546
  } finally {
420
547
  setupSpin?.stop()
@@ -461,6 +588,10 @@ if (enterRepl) {
461
588
  } else if (b != null && u.cost != null && u.cost > b * 0.8)
462
589
  process.stderr.write(c.yellow(`[budget] ${formatUsd(u.cost)} / ${formatUsd(b)} (80% used)\n`))
463
590
  await persistCurrent(u)
591
+ // P2.2: histori yang tak durable = kegagalan jujur (bukan exit 0 diam).
592
+ if (ctx.isWriterStale()) {
593
+ throw new Error(`[writer] stale writer, history NOT durable: ${ctx.writerStaleNote()}`)
594
+ }
464
595
  if (overBudget) {
465
596
  await close()
466
597
  process.exit(1)
@@ -508,13 +639,14 @@ if (enterRepl) {
508
639
  // user yang menjalankan ulang manual butuh peringatan yang sama.
509
640
  try {
510
641
  const { committedDelegatesSince } = await import("../src/session/journal.ts")
642
+ const { formatDelegateRecoveryLine } = await import("./recovery-warning.ts")
511
643
  const done = await committedDelegatesSince(sid, wcwd, t0)
644
+ // P9.2.2.1: tiap baris diperkaya observasi amplop anak (status +
645
+ // preview ringkasan, sudah disanitasi display di formatter); record
646
+ // legacy/rusak jatuh ke baris legacy byte-identik. Display-only di
647
+ // dalam catch yang selalu exit — tanpa retry, tanpa tulis baru.
512
648
  for (const d of done) {
513
- process.stderr.write(
514
- c.yellow(
515
- `[recovery] turn failed after sub-agent ${d.childSessionId} completed — its effects stand; verify before re-delegating\n`,
516
- ),
517
- )
649
+ process.stderr.write(c.yellow(`${formatDelegateRecoveryLine(d)}\n`))
518
650
  }
519
651
  } catch {}
520
652
  const uErr = usage.getSession(modelRef.current)