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
@@ -0,0 +1,379 @@
1
+ // M2 — Read-only execution registry: RAM metadata index, BUKAN authority.
2
+ //
3
+ // Kenapa berkas ini ada (P1 ADR-001/010, FINAL QA P2/P5): runtime butuh satu
4
+ // tempat observasi untuk menemukan + menginspeksi execution yang hidup/barusan
5
+ // terminal, tanpa menjadikannya source of truth kedua. Sebelum M2, observasi
6
+ // tersebar (adapter maps, journal inflight, job table) dan tak ada yang bisa
7
+ // menjawab "execution apa yang dikenal host saat ini" tanpa menebak.
8
+ //
9
+ // BUKAN: source of truth, durable store, lifecycle authority, scheduler/task
10
+ // authority, cancellation controller, terminal writer, persistence. Aturan yang
11
+ // dikunci (jangan dilonggarkan tanpa ADR baru):
12
+ // - Key = executionId M1 (tak pernah dibuat di sini; tak pernah ganti domain IDs).
13
+ // - Satu-satunya jalur tulis = observe() (sink observasi internal). TIDAK ADA
14
+ // complete()/fail()/cancel()/setState() — API semacam itu DILARANG eksis di
15
+ // modul ini (negative authority tests menjaganya).
16
+ // - Snapshot defensif: yang disimpan frozen-copy; yang dikembalikan frozen-copy.
17
+ // Mutasi hasil inspect TAK PERNAH menyentuh internal.
18
+ // - Retensi terkontestasi (BUKAN arbitrasi — FINAL QA P2): bila dua observasi
19
+ // terminal BERBEDA tiba untuk satu id, registry TIDAK TAHU mana yang commit
20
+ // duluan (otoritas serialisasi = Kernel M8, belum ada). Yang disimpan adalah
21
+ // observasi pertama (retensi deterministik anti-flap) + flag `contested:true`
22
+ // yang menyatakan "butuh kernel truth untuk resolve — JANGAN baca snapshot
23
+ // ini sebagai keputusan lifecycle". Observasi non-terminal sesudah terminal
24
+ // ditolak sebagai basi (terminal absorbing di semua model lifecycle — ini
25
+ // properti retensi, bukan klaim authority).
26
+ // Prinsip: Kernel decides. Registry observes.
27
+ // - RAM-only: restart = kosong (normal, bukan kehilangan data — truth durable
28
+ // direkonstruksi milestone persistence/recovery, bukan di sini).
29
+ // - Bounded: cap entries + TTL snapshot terminal; evict terhitung (observable).
30
+
31
+ import { type ExecutionKind, isExecutionId } from "./execution-id.ts"
32
+
33
+ /**
34
+ * Status observasi — LABEL snapshot, bukan taksonomi otoritatif (itu M8).
35
+ * Registry tidak memvalidasi makna; ia hanya menyimpan string yang dilaporkan
36
+ * lifecycle integration dan menandai terminalitas via TERMINAL_SNAPSHOT.
37
+ */
38
+ export type ExecutionStateSnapshot = string
39
+
40
+ /** Label yang dianggap terminal untuk kebijakan retensi + TTL + cleanup.
41
+ * Heuristik observasi (absorbing-label), BUKAN otoritas lifecycle. */
42
+ export const TERMINAL_SNAPSHOT: ReadonlySet<string> = new Set([
43
+ "COMPLETED",
44
+ "FAILED",
45
+ "CANCELLED",
46
+ "TIMED_OUT",
47
+ "BUDGET_EXCEEDED",
48
+ "AUTHORITY_LOST",
49
+ "RESOURCE_EXCEEDED",
50
+ ])
51
+
52
+ export function isTerminalSnapshot(state: unknown): boolean {
53
+ return typeof state === "string" && TERMINAL_SNAPSHOT.has(state)
54
+ }
55
+
56
+ /** Metadata kontrol per execution — TANPA prompt/history/output/secret. */
57
+ export interface RegistryEntryInput {
58
+ readonly executionId: string
59
+ readonly parentExecutionId?: string
60
+ readonly rootExecutionId: string
61
+ readonly kind: ExecutionKind
62
+ readonly ownerId: string
63
+ /** Snapshot observasi (label; kebenaran milik Kernel, bukan registry). */
64
+ readonly stateSnapshot: ExecutionStateSnapshot
65
+ /** Referensi opaque (sisa deadline; bukan deadline authority). */
66
+ readonly deadlineRef?: number
67
+ /** Referensi opaque (handle budget; bukan budget authority). */
68
+ readonly budgetRef?: string
69
+ /** Referensi opaque (handle backend; BUKAN kill/terminate/wait/dispose). */
70
+ readonly backendRef?: string
71
+ }
72
+
73
+ /** Snapshot yang dikembalikan ke caller — selalu frozen copy. */
74
+ export interface ExecutionSnapshot {
75
+ readonly executionId: string
76
+ readonly parentExecutionId?: string
77
+ readonly rootExecutionId: string
78
+ readonly kind: ExecutionKind
79
+ readonly ownerId: string
80
+ readonly stateSnapshot: ExecutionStateSnapshot
81
+ readonly deadlineRef?: number
82
+ readonly budgetRef?: string
83
+ readonly backendRef?: string
84
+ readonly createdAt: number
85
+ readonly updatedAt: number
86
+ /**
87
+ * True bila ≥2 observasi terminal BERBEDA pernah tiba untuk id ini.
88
+ * Artinya: snapshot yang tersimpan adalah retensi observasi pertama,
89
+ * BUKAN keputusan pemenang race — resolve via kernel truth (M8).
90
+ * Absent = tak ada kontestasi teramati.
91
+ */
92
+ readonly contested?: true
93
+ }
94
+
95
+ /** Ringkasan ringan untuk list() — tanpa detail refs. */
96
+ export interface ExecutionSummary {
97
+ readonly executionId: string
98
+ readonly kind: ExecutionKind
99
+ readonly ownerId: string
100
+ readonly stateSnapshot: ExecutionStateSnapshot
101
+ readonly updatedAt: number
102
+ readonly contested?: true
103
+ }
104
+
105
+ export interface RegistryMetrics {
106
+ registered: number
107
+ lookupHit: number
108
+ lookupMiss: number
109
+ terminalCleanup: number
110
+ staleObservation: number
111
+ /** Observasi terminal konflik (label beda, id sama) — butuh kernel truth. */
112
+ conflictingTerminal: number
113
+ evicted: number
114
+ evictedLive: number
115
+ entryCount: number
116
+ }
117
+
118
+ export interface RegistryOptions {
119
+ /** Batas total entries (default 1000). Evict: terminal tertua dulu. */
120
+ readonly maxEntries?: number
121
+ /** Retensi snapshot terminal ms (default 1 jam). BUKAN lifecycle policy. */
122
+ readonly terminalTtlMs?: number
123
+ }
124
+
125
+ const DEFAULT_MAX_ENTRIES = 1000
126
+ const DEFAULT_TERMINAL_TTL_MS = 3_600_000
127
+
128
+ interface Stored {
129
+ snapshot: ExecutionSnapshot
130
+ terminalAt: number | null
131
+ }
132
+
133
+ function freezeSnapshot(s: ExecutionSnapshot): ExecutionSnapshot {
134
+ return Object.freeze({ ...s })
135
+ }
136
+
137
+ function assertInput(input: RegistryEntryInput): void {
138
+ if (!input || !isExecutionId(input.executionId))
139
+ throw new Error("registry.observe: valid M1 executionId is required (registry never mints ids)")
140
+ if (!isExecutionId(input.rootExecutionId))
141
+ throw new Error("registry.observe: valid rootExecutionId is required")
142
+ if (input.parentExecutionId !== undefined && !isExecutionId(input.parentExecutionId))
143
+ throw new Error("registry.observe: invalid parentExecutionId (no guessing)")
144
+ if (!input.kind || !input.ownerId)
145
+ throw new Error("registry.observe: kind and ownerId are required metadata")
146
+ if (typeof input.stateSnapshot !== "string" || input.stateSnapshot.length === 0)
147
+ throw new Error("registry.observe: non-empty stateSnapshot label is required")
148
+ }
149
+
150
+ export interface ExecutionRegistry {
151
+ /** Sink observasi internal SATU-SATUNYA. Bukan mutation authority. */
152
+ observe(input: RegistryEntryInput, now?: number): void
153
+ /** Lookup → frozen copy atau undefined (miss terhitung). */
154
+ find(executionId: string): ExecutionSnapshot | undefined
155
+ /** Inspeksi detail → frozen copy atau undefined (miss terhitung). */
156
+ inspect(executionId: string): ExecutionSnapshot | undefined
157
+ /** Daftar ringkasan terurut updatedAt menaik. */
158
+ list(): ExecutionSummary[]
159
+ /** Hapus snapshot terminal kedaluwarsa TTL; kembalikan jumlah terhapus. */
160
+ sweep(now?: number): number
161
+ /** Metrik observasi (copy). */
162
+ metrics(): RegistryMetrics
163
+ /** Jumlah entries saat ini. */
164
+ size(): number
165
+ }
166
+
167
+ /**
168
+ * Registry observasi RAM-only. Single-threaded JS: operasi Map atomik;
169
+ * tak ada torn object (simpan frozen-copy, upsert = replace, tak pernah
170
+ * mutasi in-place). Tanpa clock bisnis: `now` injectable untuk determinisme.
171
+ */
172
+ export function createExecutionRegistry(opts: RegistryOptions = {}): ExecutionRegistry {
173
+ const maxEntries = opts.maxEntries ?? DEFAULT_MAX_ENTRIES
174
+ const terminalTtlMs = opts.terminalTtlMs ?? DEFAULT_TERMINAL_TTL_MS
175
+ const store = new Map<string, Stored>()
176
+ const m = {
177
+ registered: 0,
178
+ lookupHit: 0,
179
+ lookupMiss: 0,
180
+ terminalCleanup: 0,
181
+ staleObservation: 0,
182
+ conflictingTerminal: 0,
183
+ evicted: 0,
184
+ evictedLive: 0,
185
+ entryCount: 0,
186
+ }
187
+
188
+ const copyOut = (stored: Stored): ExecutionSnapshot => freezeSnapshot({ ...stored.snapshot })
189
+
190
+ const enforceBound = (): void => {
191
+ while (store.size > maxEntries) {
192
+ // Evict terminal tertua dulu; live hanya bila tak ada pilihan.
193
+ let victim: string | null = null
194
+ let victimTs = Infinity
195
+ for (const [id, st] of store) {
196
+ if (st.terminalAt !== null && st.snapshot.updatedAt < victimTs) {
197
+ victim = id
198
+ victimTs = st.snapshot.updatedAt
199
+ }
200
+ }
201
+ if (victim === null) {
202
+ for (const [id, st] of store) {
203
+ if (st.snapshot.updatedAt < victimTs) {
204
+ victim = id
205
+ victimTs = st.snapshot.updatedAt
206
+ }
207
+ }
208
+ if (victim !== null) m.evictedLive++
209
+ }
210
+ if (victim === null) break
211
+ store.delete(victim)
212
+ m.evicted++
213
+ m.entryCount = store.size
214
+ }
215
+ }
216
+
217
+ return {
218
+ observe(input: RegistryEntryInput, now: number = Date.now()): void {
219
+ assertInput(input)
220
+ const prev = store.get(input.executionId)
221
+ if (prev) {
222
+ const prevTerminal = prev.terminalAt !== null
223
+ const nextTerminal = isTerminalSnapshot(input.stateSnapshot)
224
+ if (prevTerminal) {
225
+ if (prev.snapshot.stateSnapshot === input.stateSnapshot) {
226
+ // Refresh updatedAt terminal yang sama (bukan overwrite makna).
227
+ store.set(input.executionId, freezeStored({ ...prev.snapshot, updatedAt: now }))
228
+ return
229
+ }
230
+ if (!nextTerminal) {
231
+ // Event basi non-terminal tiba sesudah terminal: stale, ditolak.
232
+ // Terminal absorbing di semua model lifecycle — properti retensi,
233
+ // bukan klaim authority atas race terminal-vs-terminal.
234
+ m.staleObservation++
235
+ return
236
+ }
237
+ // KONTESTASI terminal (BUKAN arbitrasi): registry tak tahu mana yang
238
+ // commit duluan — otoritas serialisasi milik Kernel (M8). Simpan
239
+ // observasi pertama (retensi deterministik anti-flap) + tandai
240
+ // contested agar TAK ADA pembaca yang menjadikannya keputusan
241
+ // lifecycle. Urutan observasi ≠ authority.
242
+ m.conflictingTerminal++
243
+ store.set(
244
+ input.executionId,
245
+ freezeStored({ ...prev.snapshot, contested: true as const, updatedAt: now }),
246
+ )
247
+ return
248
+ }
249
+ if (!nextTerminal || prev.snapshot.stateSnapshot === input.stateSnapshot) {
250
+ store.set(
251
+ input.executionId,
252
+ freezeStored({
253
+ ...prev.snapshot,
254
+ ...stripUndefined(input),
255
+ updatedAt: now,
256
+ }),
257
+ )
258
+ return
259
+ }
260
+ // Transisi non-terminal → terminal: catat terminalAt (retensi TTL).
261
+ const terminalSnapshot = freezeSnapshot({
262
+ ...prev.snapshot,
263
+ ...stripUndefined(input),
264
+ updatedAt: now,
265
+ })
266
+ store.set(input.executionId, { snapshot: terminalSnapshot, terminalAt: now })
267
+ return
268
+ }
269
+ const snapshot = freezeSnapshot({
270
+ executionId: input.executionId,
271
+ ...(input.parentExecutionId ? { parentExecutionId: input.parentExecutionId } : {}),
272
+ rootExecutionId: input.rootExecutionId,
273
+ kind: input.kind,
274
+ ownerId: input.ownerId,
275
+ stateSnapshot: input.stateSnapshot,
276
+ ...(input.deadlineRef !== undefined ? { deadlineRef: input.deadlineRef } : {}),
277
+ ...(input.budgetRef !== undefined ? { budgetRef: input.budgetRef } : {}),
278
+ ...(input.backendRef !== undefined ? { backendRef: input.backendRef } : {}),
279
+ createdAt: now,
280
+ updatedAt: now,
281
+ })
282
+ store.set(input.executionId, {
283
+ snapshot,
284
+ terminalAt: isTerminalSnapshot(input.stateSnapshot) ? now : null,
285
+ })
286
+ m.registered++
287
+ m.entryCount = store.size
288
+ enforceBound()
289
+ },
290
+
291
+ find(executionId: string): ExecutionSnapshot | undefined {
292
+ const stored = store.get(executionId)
293
+ if (!stored) {
294
+ m.lookupMiss++
295
+ return undefined
296
+ }
297
+ m.lookupHit++
298
+ return copyOut(stored)
299
+ },
300
+
301
+ inspect(executionId: string): ExecutionSnapshot | undefined {
302
+ const stored = store.get(executionId)
303
+ if (!stored) {
304
+ m.lookupMiss++
305
+ return undefined
306
+ }
307
+ m.lookupHit++
308
+ return copyOut(stored)
309
+ },
310
+
311
+ list(): ExecutionSummary[] {
312
+ return [...store.values()]
313
+ .map((st) => st.snapshot)
314
+ .sort((a, b) => a.updatedAt - b.updatedAt)
315
+ .map((s) =>
316
+ Object.freeze({
317
+ executionId: s.executionId,
318
+ kind: s.kind,
319
+ ownerId: s.ownerId,
320
+ stateSnapshot: s.stateSnapshot,
321
+ updatedAt: s.updatedAt,
322
+ ...(s.contested === true ? { contested: true as const } : {}),
323
+ }),
324
+ )
325
+ },
326
+
327
+ sweep(now: number = Date.now()): number {
328
+ let removed = 0
329
+ for (const [id, st] of store) {
330
+ if (st.terminalAt !== null && now - st.terminalAt >= terminalTtlMs) {
331
+ store.delete(id)
332
+ removed++
333
+ }
334
+ }
335
+ if (removed > 0) {
336
+ m.terminalCleanup += removed
337
+ m.entryCount = store.size
338
+ }
339
+ return removed
340
+ },
341
+
342
+ metrics(): RegistryMetrics {
343
+ return { ...m, entryCount: store.size }
344
+ },
345
+
346
+ size(): number {
347
+ return store.size
348
+ },
349
+ }
350
+ }
351
+
352
+ function stripUndefined(input: RegistryEntryInput): {
353
+ stateSnapshot: ExecutionStateSnapshot
354
+ kind: ExecutionKind
355
+ ownerId: string
356
+ rootExecutionId: string
357
+ parentExecutionId?: string
358
+ deadlineRef?: number
359
+ budgetRef?: string
360
+ backendRef?: string
361
+ } {
362
+ return {
363
+ stateSnapshot: input.stateSnapshot,
364
+ kind: input.kind,
365
+ ownerId: input.ownerId,
366
+ rootExecutionId: input.rootExecutionId,
367
+ ...(input.parentExecutionId !== undefined
368
+ ? { parentExecutionId: input.parentExecutionId }
369
+ : {}),
370
+ ...(input.deadlineRef !== undefined ? { deadlineRef: input.deadlineRef } : {}),
371
+ ...(input.budgetRef !== undefined ? { budgetRef: input.budgetRef } : {}),
372
+ ...(input.backendRef !== undefined ? { backendRef: input.backendRef } : {}),
373
+ }
374
+ }
375
+
376
+ function freezeStored(snapshot: ExecutionSnapshot): Stored {
377
+ const terminalAt = isTerminalSnapshot(snapshot.stateSnapshot) ? snapshot.updatedAt : null
378
+ return { snapshot: freezeSnapshot(snapshot), terminalAt }
379
+ }
@@ -0,0 +1,276 @@
1
+ // P13.2 — Supervision proses: SATU jalur ownership proses milik runtime.
2
+ //
3
+ // Kenapa berkas ini ada: P13.1 mengunci KONTRAK status runtime, tapi belum
4
+ // ada SATU tempat yang memiliki proses anak milik runtime. Tiap subsystem
5
+ // menggulirkan cara kill-nya sendiri (bash.ts killTree, mcp/transport.ts,
6
+ // lsp/client.ts), sehingga "tidak ada child process yang terlepas" mustahil
7
+ // dibuktikan dan crash bisa meninggalkan yatim.
8
+ //
9
+ // Batas yang dikunci:
10
+ // - Modul ini TIDAK menjalankan proses (guard arsitektur G10: hanya M5 boleh
11
+ // spawn). Ia MEMILIKI daftar anak, MEMUTUSKAN recovery bounded, dan
12
+ // MENGAWAT cleanup saat shutdown.
13
+ // - Bukan process management OS-wide: yang dikelola hanya anak yang runtime
14
+ // ini spawn/miliki. Tak ada apa pun di luar runtime ini yang disentuh.
15
+ // - Pemulihan task durable = P13.3. Modul ini tak pernah mengulang kerja
16
+ // pengguna: restart HANYA untuk anak yang restart-nya tak bisa mengulang efek
17
+ // samping (restartSafety === "safe"). Anak "unsafe" di-eskalasi jujur, bukan
18
+ // direstart.
19
+ // - Tak ada antrean durable dan bukan task store kedua: TaskStore tetap
20
+ // otoritas task.
21
+ //
22
+ // Policy TAK dikarang di sini: percobaan/backoff/eskalasi memakai kembali
23
+ // SupervisionPolicy (supervisor.ts) dan nextBackoffMs().
24
+
25
+ import { nextBackoffMs, type SupervisionPolicy } from "./supervisor.ts"
26
+
27
+ /**
28
+ * Whether restarting this child can repeat a user-visible side effect.
29
+ *
30
+ * "safe" — restarting cannot replay user work (e.g. a helper server that
31
+ * only answers requests). Bounded restart is allowed.
32
+ * "unsafe" — restarting could repeat work (e.g. a background command). It is
33
+ * NEVER auto-restarted; the supervisor escalates instead.
34
+ */
35
+ export type ManagedChildRestartSafety = "safe" | "unsafe"
36
+
37
+ /** Observation of one managed child (physical observation, not a lifecycle decision). */
38
+ export interface ManagedChildObservation {
39
+ readonly status: "running" | "exited" | "failed" | "unknown"
40
+ readonly exitCode?: number | null
41
+ readonly detail?: string
42
+ }
43
+
44
+ /**
45
+ * Port of a managed child.
46
+ *
47
+ * The registrar (the layer that spawns the process) implements this; the
48
+ * runtime only observes, decides recovery, and awaits cleanup. That keeps the
49
+ * runtime free of process execution while still being the single owner.
50
+ */
51
+ export interface ManagedChild {
52
+ /** Stable id (used as the recovery key). */
53
+ readonly id: string
54
+ /** Kind of child (diagnostic only, e.g. "lsp-server"). */
55
+ readonly kind: string
56
+ /** Whether an automatic restart may repeat user work. */
57
+ readonly restartSafety: ManagedChildRestartSafety
58
+ /** Current physical observation. */
59
+ observe(): ManagedChildObservation
60
+ /** Stop the child and wait until it is gone (best effort, must not throw). */
61
+ stop(reason: string): Promise<void>
62
+ /** Start the child again. Only called when restartSafety === "safe". */
63
+ restart?(): Promise<void>
64
+ }
65
+
66
+ /** Truthful snapshot of the supervision state. */
67
+ export interface ProcessSupervisionStatus {
68
+ /** The supervision path is attached to this runtime. */
69
+ readonly attached: boolean
70
+ /** Number of children currently registered. */
71
+ readonly managed: number
72
+ /** Successful bounded restarts performed. */
73
+ readonly restarts: number
74
+ /** Number of truthful escalations (recovery gave up). */
75
+ readonly escalations: number
76
+ /** Last escalation reason (diagnostic, no secrets). */
77
+ readonly lastEscalation: string | null
78
+ /**
79
+ * True while the supervision is operational. False after an escalation —
80
+ * a runtime whose supervision gave up must not claim it is supervised.
81
+ */
82
+ readonly operational: boolean
83
+ }
84
+
85
+ /** The single process-ownership path of a runtime. */
86
+ export interface ProcessSupervision {
87
+ /** Register (or replace) a managed child. */
88
+ register(child: ManagedChild): void
89
+ /**
90
+ * Report that a child exited unexpectedly. Resolves when the recovery
91
+ * attempt (restart + backoff) has finished. Never throws.
92
+ */
93
+ notifyExit(childId: string, observation: ManagedChildObservation): Promise<void>
94
+ /** Stop every registered child and await the cleanup. */
95
+ shutdown(): Promise<{ stopped: number; failed: number }>
96
+ /** Truthful snapshot. */
97
+ status(): ProcessSupervisionStatus
98
+ }
99
+
100
+ export interface ProcessSupervisionOptions {
101
+ /** Existing supervision policy (attempts, backoff, intensity, escalation wait). */
102
+ readonly policy?: SupervisionPolicy
103
+ /** Clock (injected for deterministic tests). */
104
+ readonly now?: () => number
105
+ /** Sleeper (injected for deterministic tests — the backoff must be awaitable). */
106
+ readonly sleep?: (ms: number) => Promise<void>
107
+ /** Upper bound of managed children (guards against unbounded registries). */
108
+ readonly maxManagedChildren?: number
109
+ }
110
+
111
+ const DEFAULT_MAX_MANAGED_CHILDREN = 64
112
+
113
+ function defaultSleep(ms: number): Promise<void> {
114
+ return new Promise((resolve) => {
115
+ const t = setTimeout(resolve, ms)
116
+ t.unref?.()
117
+ })
118
+ }
119
+
120
+ /**
121
+ * Create the runtime's process-ownership path.
122
+ *
123
+ * Recovery is BOUNDED twice, using the existing policy:
124
+ * - `maxAttempts` — consecutive restart attempts per child.
125
+ * - `maxIntensity` within `intensityWindowMs` — a flapping child is escalated
126
+ * instead of being restarted forever.
127
+ */
128
+ export function createProcessSupervision(opts: ProcessSupervisionOptions = {}): ProcessSupervision {
129
+ const policy = opts.policy ?? {}
130
+ const now = opts.now ?? Date.now
131
+ const sleep = opts.sleep ?? defaultSleep
132
+ const maxManagedChildren = opts.maxManagedChildren ?? DEFAULT_MAX_MANAGED_CHILDREN
133
+
134
+ const children = new Map<string, ManagedChild>()
135
+ /** Percobaan restart berurutan per anak (dibuang bila anak lama sehat). */
136
+ const attempts = new Map<string, number>()
137
+ /** Waktu keluar terakhir per anak — dasar untuk reset anggaran percobaan. */
138
+ const lastExitAt = new Map<string, number>()
139
+ /** Exit timestamps per child, for the intensity window. */
140
+ const exits = new Map<string, number[]>()
141
+ /** Children whose recovery was given up — they are no longer restarted. */
142
+ const escalated = new Set<string>()
143
+
144
+ let restarts = 0
145
+ let escalationCount = 0
146
+ let lastEscalation: string | null = null
147
+ let shuttingDown = false
148
+
149
+ const escalate = (child: ManagedChild, reason: string): void => {
150
+ escalated.add(child.id)
151
+ escalationCount += 1
152
+ lastEscalation = `${child.kind}:${child.id}: ${reason}`
153
+ }
154
+
155
+ const inIntensityWindow = (childId: string, at: number): boolean => {
156
+ const windowMs = policy.intensityWindowMs ?? 60_000
157
+ const max = policy.maxIntensity ?? 5
158
+ const stamps = (exits.get(childId) ?? []).filter((t) => at - t < windowMs)
159
+ stamps.push(at)
160
+ exits.set(childId, stamps)
161
+ return stamps.length > max
162
+ }
163
+
164
+ const notifyExit = async (
165
+ childId: string,
166
+ observation: ManagedChildObservation,
167
+ ): Promise<void> => {
168
+ const child = children.get(childId)
169
+ if (!child) return
170
+ // Shutdown is not an "unexpected exit" — the owner asked for the stop.
171
+ if (shuttingDown) return
172
+ if (escalated.has(child.id)) return
173
+
174
+ const at = now()
175
+ // Anggaran percobaan bersifat "burst": anak yang sudah lama sehat (keluar
176
+ // terakhirnya di luar window) mendapat anggaran BARU. Tanpa ini, anak
177
+ // yang mati sekali sebulan akan kehabisan anggaran setelah tiga kali —
178
+ // dan kehabisan anggaran berarti tak pernah lagi disupervisi.
179
+ const windowMs = policy.intensityWindowMs ?? 60_000
180
+ const previousExit = lastExitAt.get(child.id)
181
+ if (previousExit === undefined || at - previousExit > windowMs) attempts.set(child.id, 0)
182
+ lastExitAt.set(child.id, at)
183
+
184
+ const attempt = (attempts.get(child.id) ?? 0) + 1
185
+ attempts.set(child.id, attempt)
186
+ // Observasi fisik ikut dibawa ke pesan eskalasi (kode keluar = bukti, bukan
187
+ // tebakan) — tapi TIDAK jadi keputusan: keputusan diambil dari policy.
188
+ const observed = `exit=${observation.exitCode ?? "?"} status=${observation.status}`
189
+
190
+ const maxAttempts = policy.maxAttempts ?? 3
191
+ if (attempt > maxAttempts) {
192
+ escalate(child, `restart attempts exhausted (${maxAttempts}) · ${observed}`)
193
+ return
194
+ }
195
+ if (inIntensityWindow(child.id, at)) {
196
+ escalate(child, `restart intensity exceeded · ${observed}`)
197
+ return
198
+ }
199
+ if (child.restartSafety !== "safe") {
200
+ // NEVER auto-restart a child whose restart could repeat user work.
201
+ escalate(
202
+ child,
203
+ `restart unsafe (would repeat side effects) — escalated, not restarted · ${observed}`,
204
+ )
205
+ return
206
+ }
207
+ if (!child.restart) {
208
+ escalate(child, `child cannot be restarted · ${observed}`)
209
+ return
210
+ }
211
+
212
+ const delay = nextBackoffMs(attempt, policy)
213
+ try {
214
+ await sleep(delay)
215
+ } catch {
216
+ // Sleeper failure is not a child failure — do not escalate on it.
217
+ return
218
+ }
219
+ try {
220
+ await child.restart()
221
+ restarts += 1
222
+ } catch (e) {
223
+ // Restart yang GAGAL = jalur pemulihan rusak (bukan anak yang lagi
224
+ // flapping). Eskalasi SEKARANG: diam-diam mencoba lagi hanya menyembunyikan
225
+ // breakage sampai kehabisan waktu.
226
+ escalate(child, `restart failed: ${e instanceof Error ? e.message : String(e)}`)
227
+ }
228
+ }
229
+
230
+ return {
231
+ register(child: ManagedChild): void {
232
+ if (!child || typeof child.id !== "string" || child.id.length === 0) return
233
+ if (!children.has(child.id) && children.size >= maxManagedChildren) {
234
+ // Anak tak boleh didaftarkan lewat batas: anak tanpa pemilik adalah
235
+ // persis "child yang terlepas" yang modul ini ada untuk mencegahnya.
236
+ // Penolakan ini DIKABARKAN lewat eskalasi, bukan diam-diam.
237
+ escalate(child, `managed child limit reached (${maxManagedChildren})`)
238
+ return
239
+ }
240
+ children.set(child.id, child)
241
+ if (!attempts.has(child.id)) attempts.set(child.id, 0)
242
+ },
243
+
244
+ notifyExit,
245
+
246
+ async shutdown(): Promise<{ stopped: number; failed: number }> {
247
+ shuttingDown = true
248
+ let stopped = 0
249
+ let failed = 0
250
+ for (const child of [...children.values()]) {
251
+ try {
252
+ await child.stop("runtime shutdown")
253
+ stopped += 1
254
+ } catch {
255
+ failed += 1
256
+ }
257
+ }
258
+ children.clear()
259
+ attempts.clear()
260
+ lastExitAt.clear()
261
+ exits.clear()
262
+ return { stopped, failed }
263
+ },
264
+
265
+ status(): ProcessSupervisionStatus {
266
+ return {
267
+ attached: true,
268
+ managed: children.size,
269
+ restarts,
270
+ escalations: escalationCount,
271
+ lastEscalation,
272
+ operational: escalationCount === 0,
273
+ }
274
+ },
275
+ }
276
+ }