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,316 @@
1
+ // P2.12 — host daemon: siklus hidup, berkas endpoint/lease, dan shutdown
2
+ // berurutan.
3
+ //
4
+ // Kenapa satu tempat mengatur urutan: shutdown yang salah urutan meninggalkan
5
+ // sisa yang mahal — konsumen yang mengira masih terhubung, persetujuan yang
6
+ // menggantung tanpa jawab, lease basi yang membuat daemon baru terlihat hidup
7
+ // padahal sudah mati. Urutan di bawah diekspos sebagai langkah bernomor agar
8
+ // bisa DIUJI, bukan cuma dikomentari.
9
+
10
+ import { randomBytes, randomUUID } from "node:crypto"
11
+ import { currentRuntimeView } from "../runtime/runtime-status-provider.ts"
12
+ import { ApprovalBroker } from "./approvals.ts"
13
+ import { mintCapability } from "./capability.ts"
14
+ import { ChildSupervisor } from "./children.ts"
15
+ import { type ControlActions, IdempotencyStore } from "./control.ts"
16
+ import { clearDiscovery, type DaemonEndpoint, writeEndpoint, writeLease } from "./discovery.ts"
17
+ import type { DaemonScope } from "./protocol.ts"
18
+ import { ResourceMonitor } from "./resource.ts"
19
+ import { sanitizeLabel } from "./sanitize.ts"
20
+ import { DaemonServer, type FeedRegistry } from "./server.ts"
21
+ import { markPendingApprovalsUnknown } from "./store.ts"
22
+ import { Telemetry } from "./telemetry.ts"
23
+
24
+ export type ShutdownStep =
25
+ | "mark-closing"
26
+ | "halt-consumers"
27
+ | "settle-approvals"
28
+ | "close-hosted-session"
29
+ | "stop-monitors"
30
+ | "close-connections"
31
+ | "retire-children"
32
+ | "clear-discovery"
33
+
34
+ export interface DaemonHostOptions {
35
+ cwd?: string
36
+ host?: string
37
+ /** 0 = port ephemeral (dipilih OS) — dipakai test & starter yang tak tahu port. */
38
+ port?: number
39
+ feeds: FeedRegistry
40
+ actions?: ControlActions | null
41
+ /** Label workspace untuk diagnosis (dibasuh). */
42
+ workspace?: string
43
+ leaseIntervalMs?: number
44
+ /** TTL default capability yang diterbitkan host. */
45
+ capabilityTtlMs?: number
46
+ /**
47
+ * Kanal diagnostik host. Bukan sekadar kenyamanan: test & pengendali
48
+ * non-interaktif harus bisa menangkap pesan tanpa menempel di stderr
49
+ * proses, dan satu kanal artinya tak ada tulis yang lolos dari audit.
50
+ */
51
+ warn?: (msg: string) => void
52
+ /**
53
+ * [P13.2] Penutup sesi yang di-host.
54
+ *
55
+ * Seam, bukan dependensi: lapisan daemon tak boleh tahu apa itu "sesi CLI".
56
+ * Yang diterimanya hanyalah "ada lifecycle yang harus DITUNGGU selesai sebelum
57
+ * daemon menutup dirinya" — runtime yang di-host menutup jurnalnya dan
58
+ * membersihkan anak prosesnya DI SINI. Tanpa seam ini, daemon berhenti
59
+ * sementara sesi yang di-host masih hidup: proses anak Supervisi bisa
60
+ * tertinggal (yatim) dan jurnal tak pernah ditutup rapi.
61
+ */
62
+ closeHostedSession?: (() => Promise<void>) | null
63
+ /**
64
+ * Seam uji: batas antrean per langganan. `0` meniru socket yang sudah
65
+ * tertahan sejak awal sehingga overflow deterministik. Produksi memakai
66
+ * `MAX_QUEUE_PER_CONN` (default server).
67
+ */
68
+ maxQueuePerSubscription?: number
69
+ /**
70
+ * Seam uji: batas antrean per identitas konsumen logis. Dipakai agar satu
71
+ * konsumen bisa dibuat "tertahan" tanpa ikut menahan konsumen lain.
72
+ */
73
+ maxQueuePerConsumer?: (consumerId: string) => number | undefined
74
+ }
75
+
76
+ export class DaemonHost {
77
+ readonly incarnation: string
78
+ readonly telemetry = new Telemetry()
79
+ readonly approvals: ApprovalBroker
80
+ readonly children: ChildSupervisor
81
+ readonly idem = new IdempotencyStore()
82
+ readonly server: DaemonServer
83
+ readonly resource: ResourceMonitor
84
+
85
+ readonly #secret: Buffer
86
+ readonly #opts: DaemonHostOptions
87
+ readonly #warn: (msg: string) => void
88
+ #leaseTimer: ReturnType<typeof setInterval> | null = null
89
+ #closing = false
90
+ #shutdownSteps: ShutdownStep[] = []
91
+ /** Kegagalan yang tercatat saat shutdown — tak boleh hilang (cleanup tak boleh dilewati diam-diam). */
92
+ #shutdownErrors: Error[] = []
93
+ #endpointPath: string | null = null
94
+ #port = 0
95
+
96
+ private constructor(opts: DaemonHostOptions) {
97
+ this.#opts = opts
98
+ this.#warn = opts.warn ?? ((msg) => process.stderr.write(`${msg}\n`))
99
+ this.incarnation = `inc_${randomUUID()}`
100
+ // Secret HANYA di memori proses ini. Bila bocor ke berkas, siapa pun yang
101
+ // bisa membaca berkas itu bisa menerbitkan capability admin.
102
+ this.#secret = randomBytes(32)
103
+ this.children = new ChildSupervisor({ telemetry: this.telemetry })
104
+ this.approvals = new ApprovalBroker({
105
+ incarnation: this.incarnation,
106
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
107
+ propose: (view) => {
108
+ this.telemetry.inc("approval.requested")
109
+ this.server.broadcastApproval(view)
110
+ },
111
+ warn: (msg) => this.#warn(msg),
112
+ })
113
+ this.server = new DaemonServer({
114
+ incarnation: this.incarnation,
115
+ secret: this.#secret,
116
+ host: opts.host ?? "127.0.0.1",
117
+ port: opts.port ?? 0,
118
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
119
+ feeds: opts.feeds,
120
+ approvals: this.approvals,
121
+ control: {
122
+ actions: opts.actions ?? null,
123
+ idem: this.idem,
124
+ telemetry: this.telemetry,
125
+ storageOk: () => this.resource.state === "ok",
126
+ shuttingDown: () => this.#closing,
127
+ // P13.1: status runtime kanonik dibaca dari SEAM yang sama dengan CLI
128
+ // (composition root memasang penyedia). Tanpa runtime terpasang, view
129
+ // ABSENT kanonik yang disajikan — bukan status karangan.
130
+ runtimeStatus: () => currentRuntimeView(),
131
+ },
132
+ telemetry: this.telemetry,
133
+ ...(opts.maxQueuePerSubscription !== undefined
134
+ ? { maxQueuePerSubscription: opts.maxQueuePerSubscription }
135
+ : {}),
136
+ ...(opts.maxQueuePerConsumer !== undefined
137
+ ? { maxQueuePerConsumer: opts.maxQueuePerConsumer }
138
+ : {}),
139
+ })
140
+ this.resource = new ResourceMonitor({
141
+ ...(opts.cwd !== undefined ? { cwd: opts.cwd } : {}),
142
+ onPressure: (state, snap) => {
143
+ if (state === "storage") {
144
+ this.telemetry.inc("storage.pressure")
145
+ this.#warn(
146
+ `[daemon] tekanan penyimpanan: ${snap.reason ?? "unknown"} — pekerjaan baru ditahan`,
147
+ )
148
+ }
149
+ },
150
+ })
151
+ }
152
+
153
+ static async start(opts: DaemonHostOptions): Promise<DaemonHost> {
154
+ const host = new DaemonHost(opts)
155
+ await host.#boot()
156
+ return host
157
+ }
158
+
159
+ async #boot(): Promise<void> {
160
+ const { port } = await this.server.start()
161
+ this.#port = port
162
+
163
+ const ep: DaemonEndpoint = {
164
+ version: 1,
165
+ port,
166
+ host: this.#opts.host ?? "127.0.0.1",
167
+ incarnation: this.incarnation,
168
+ startedAt: Date.now(),
169
+ workspace: sanitizeLabel(this.#opts.workspace ?? "", 120),
170
+ // Akar kepercayaan untuk klien menerbitkan capability sendiri —
171
+ // lihat komentar panjang di `DaemonEndpoint.bootstrap`.
172
+ bootstrap: this.#secret.toString("base64url"),
173
+ }
174
+ this.#endpointPath = writeEndpoint(ep, this.#opts.cwd)
175
+ this.#beatLease()
176
+ const interval = Math.max(1_000, this.#opts.leaseIntervalMs ?? 5_000)
177
+ this.#leaseTimer = setInterval(() => this.#beatLease(), interval)
178
+ this.#leaseTimer.unref?.()
179
+
180
+ // UNKNOWN untuk persetujuan yang menggantung: dilakukan SEBELUM konsumen
181
+ // mana pun boleh melihat — kalau tidak, ada jendela di mana konsumen
182
+ // membaca "pending" yang tak pernah akan dijawab siapa pun.
183
+ const unknown = this.approvalsUnknownOnStart()
184
+ if (unknown > 0) {
185
+ this.#warn(`[daemon] ${unknown} persetujuan tak terjawab dari generasi sebelumnya -> UNKNOWN`)
186
+ }
187
+
188
+ this.resource.start()
189
+ }
190
+
191
+ /** Transisi persetujuan lama ke UNKNOWN saat start. Jumlah baris berpindah. */
192
+ approvalsUnknownOnStart(): number {
193
+ const n = markPendingApprovalsUnknown(this.incarnation, this.#opts.cwd)
194
+ if (n > 0) this.telemetry.inc("approval.unknown.onRestart", n)
195
+ return n
196
+ }
197
+
198
+ #beatLease(): void {
199
+ if (this.#closing) return
200
+ writeLease(
201
+ {
202
+ version: 1,
203
+ incarnation: this.incarnation,
204
+ pid: process.pid,
205
+ updatedAt: Date.now(),
206
+ },
207
+ this.#opts.cwd,
208
+ )
209
+ }
210
+
211
+ get port(): number {
212
+ return this.#port
213
+ }
214
+
215
+ get closing(): boolean {
216
+ return this.#closing
217
+ }
218
+
219
+ get shutdownSteps(): readonly ShutdownStep[] {
220
+ return this.#shutdownSteps
221
+ }
222
+
223
+ /**
224
+ * Kegagalan shutdown yang tercatat (mis. sesi yang di-host tak bisa
225
+ * ditutup). Kosong = shutdown bersih. Kegagalan ini juga membuat
226
+ * `shutdown()` menolak — jadi tak bisa "hilang" tanpa jejak.
227
+ */
228
+ get shutdownErrors(): readonly Error[] {
229
+ return [...this.#shutdownErrors]
230
+ }
231
+
232
+ get endpointPath(): string | null {
233
+ return this.#endpointPath
234
+ }
235
+
236
+ /** Terbitkan capability bercakupan untuk konsumen. Secret tak pernah ikut. */
237
+ issueCapability(opts: { scopes: DaemonScope[]; who: string; ttlMs?: number }): string {
238
+ return mintCapability(this.#secret, {
239
+ incarnation: this.incarnation,
240
+ scopes: opts.scopes,
241
+ ttlMs: opts.ttlMs ?? this.#opts.capabilityTtlMs ?? 10 * 60_000,
242
+ who: opts.who,
243
+ })
244
+ }
245
+
246
+ /**
247
+ * Shutdown berurutan. Idempoten — dipanggil lagi setelah selesai hanya
248
+ * mengembalikan langkah yang sama, bukan menjalankan ulang.
249
+ *
250
+ * Urutan (dites satu per satu):
251
+ * 1 mark-closing -> kontrol baru ditolak SHUTTING_DOWN
252
+ * 2 halt-consumers -> konsumen berhenti mengirim pekerjaan
253
+ * 3 settle-approvals -> persetujuan menggantung = DENY, tak digantung
254
+ * 4 close-hosted-session -> lifecycle sesi yang di-host SELESAI (jurnal
255
+ * ditutup, anak proses yang disupervisi dibersihkan)
256
+ * 5 stop-monitors -> lease + resource berhenti menulis
257
+ * 6 close-connections -> socket ditutup
258
+ * 7 retire-children -> anak yang tak teronfirmasi -> lost (bukan finished)
259
+ * 8 clear-discovery -> berkas endpoint/lease milik kita dilepas
260
+ */
261
+ async shutdown(reason: string): Promise<ShutdownStep[]> {
262
+ if (this.#closing) return [...this.#shutdownSteps]
263
+ this.#closing = true
264
+ this.#track("mark-closing")
265
+
266
+ this.server.broadcastHalt("SHUTTING_DOWN")
267
+ this.#track("halt-consumers")
268
+
269
+ this.approvals.shutdownAll()
270
+ this.#track("settle-approvals")
271
+
272
+ // [P13.2] Sesi yang di-host ditutup dan DITUNGGU: lifecycle-nya (jurnal +
273
+ // anak proses yang disupervisi) harus selesai sebelum daemon menutup
274
+ // dirinya. Tanpa ini, proses anak bisa tertinggal (yatim).
275
+ const closeSession = this.#opts.closeHostedSession
276
+ if (closeSession) {
277
+ try {
278
+ await closeSession()
279
+ } catch (e) {
280
+ this.#shutdownErrors.push(e instanceof Error ? e : new Error(String(e)))
281
+ }
282
+ this.#track("close-hosted-session")
283
+ }
284
+
285
+ if (this.#leaseTimer) clearInterval(this.#leaseTimer)
286
+ this.#leaseTimer = null
287
+ this.resource.stop()
288
+ this.#track("stop-monitors")
289
+
290
+ await this.server.close()
291
+ this.#track("close-connections")
292
+
293
+ this.children.shutdown()
294
+ this.#track("retire-children")
295
+
296
+ clearDiscovery(this.incarnation, this.#opts.cwd)
297
+ this.#track("clear-discovery")
298
+
299
+ this.telemetry.inc("shutdown.ordered")
300
+ void reason
301
+ // Kegagalan sesi yang di-host dilaporkan SETELAH semua langkah cleanup
302
+ // selesai: sisa cleanup tak boleh dilewati, tapi kegagalannya juga tak
303
+ // boleh hilang (diam-diam = klaim "semua beres" yang tidak benar).
304
+ if (this.#shutdownErrors.length > 0) {
305
+ throw new AggregateError(
306
+ this.#shutdownErrors,
307
+ `daemon: shutdown selesai dengan ${this.#shutdownErrors.length} kegagalan`,
308
+ )
309
+ }
310
+ return [...this.#shutdownSteps]
311
+ }
312
+
313
+ #track(step: ShutdownStep): void {
314
+ if (!this.#shutdownSteps.includes(step)) this.#shutdownSteps.push(step)
315
+ }
316
+ }
@@ -0,0 +1,217 @@
1
+ // P2.12 — kontrak wire antara konsumen Desktop dan daemon host.
2
+ //
3
+ // Kenapa dipisah dari implementasi: nomor protokol, kode penolakan, dan kelas
4
+ // cakupan adalah FROZEN CONTRACT. Menempelkannya di server/framing membuat
5
+ // refactor internal berisiko menggeser nilai yang justru diuji silang proses
6
+ // (daemon lama × konsumen baru). Di sini hanya tipe + konstanta — tanpa I/O.
7
+
8
+ /** Nomor protokol. Naik = breaking; konsumen lama wajib ditolak tegas. */
9
+ export const DAEMON_PROTOCOL = 1
10
+
11
+ /** Batas satu frame: jejak / payload snapshot tak boleh menahan memori daemon. */
12
+ export const MAX_FRAME_BYTES = 8 * 1024 * 1024
13
+
14
+ /** Antrean per-koneksi sebelum melanggar aturan "tak ada memori tak terbatas". */
15
+ export const MAX_QUEUE_PER_CONN = 512
16
+
17
+ /** Kelas cakupan capability — bukan role global, selalu daftar sempit. */
18
+ export type DaemonScope =
19
+ | "subscribe" // terima snapshot + event live (baca saja)
20
+ | "read:session" // tanya frontiers/status sesi
21
+ | "control:session" // opsi kontrol sesi (interrupt, dll.)
22
+ | "approve" // keputusan persetujuan durable
23
+ | "admin" // shutdown daemon, minta daftar sesi
24
+
25
+ export const DAEMON_SCOPES: readonly DaemonScope[] = [
26
+ "subscribe",
27
+ "read:session",
28
+ "control:session",
29
+ "approve",
30
+ "admin",
31
+ ] as const
32
+
33
+ /**
34
+ * Kode penolakan. Setiap penolakan kontrol WAJIB memakai salah satu dari ini
35
+ * agar konsumen bisa membedakan "stale (ulangi dengan lease baru)" dari
36
+ * "terminal (jangan diulang)" — dua hal yang sering tertukar saat daemon restart.
37
+ */
38
+ export type RefusalCode =
39
+ | "INVALID_CAPABILITY"
40
+ | "SCOPE_DENIED"
41
+ | "STALE_EPOCH"
42
+ | "STALE_INCARNATION"
43
+ | "LEASE_LOST"
44
+ | "RUN_TERMINAL"
45
+ | "SESSION_MISMATCH"
46
+ | "APPROVAL_EXPIRED"
47
+ | "APPROVAL_UNKNOWN"
48
+ | "APPROVAL_INVALID_STATE"
49
+ | "QUEUE_OVERFLOW"
50
+ | "STORAGE_PRESSURE"
51
+ | "PROTOCOL_ERROR"
52
+ | "NOT_FOUND"
53
+ | "IDEMPOTENT_REPLAY"
54
+ | "SHUTTING_DOWN"
55
+ | "SCOPE_UNSUPPORTED"
56
+
57
+ /** Alasan konsumen diminta berhenti mengirim pekerjaan baru. */
58
+ export type HaltReason =
59
+ | "SHUTTING_DOWN"
60
+ | "STORAGE_PRESSURE"
61
+ | "QUEUE_OVERFLOW"
62
+ | "PROTOCOL_ERROR"
63
+ | "REVOKED"
64
+
65
+ /** Identitas konsumen — nama/logikal, TIDAK PERNAH PID. */
66
+ export interface ConsumerIdentity {
67
+ consumerId: string
68
+ label?: string
69
+ }
70
+
71
+ export type SubscribeFrom =
72
+ /** Hanya event BARU sesudah kepala saat ini — tanpa replay. */
73
+ | "tail"
74
+ /** Lanjut dari offset ack terakhir; bila belum pernah, sama dengan tail. */
75
+ | "resume"
76
+ /** Replay eksplisit mulai seq ini (0 = dari awal), lalu tail. */
77
+ | number
78
+
79
+ export type ClientMessage =
80
+ | { t: "hello"; protocol: number; cap: string; consumer: string }
81
+ | { t: "subscribe"; sid: string; from: SubscribeFrom; consumer: string }
82
+ | { t: "ack"; sid: string; seq: number; consumer: string }
83
+ | { t: "control"; op: string; idem: string; args: Record<string, unknown>; consumer: string }
84
+ | { t: "ping"; id: string }
85
+ | { t: "goodbye" }
86
+
87
+ export type ServerMessage =
88
+ | {
89
+ t: "welcome"
90
+ protocol: number
91
+ incarnation: string
92
+ scopes: DaemonScope[]
93
+ consumer: string
94
+ }
95
+ | {
96
+ t: "subscribed"
97
+ sid: string
98
+ consumer: string
99
+ fromSeq: number
100
+ cursor: number
101
+ /**
102
+ * Jumlah baris snapshot yang gagal didekode. WAJIB dilaporkan — bila
103
+ * disembunyikan, konsumen mengira snapshot lengkap padahal ada lubang
104
+ * yang tak pernah bisa ia deteksi sendiri.
105
+ */
106
+ snapshotRejected: number
107
+ }
108
+ | { t: "frontiers"; sid: string; frontiers: SessionFrontiers }
109
+ | { t: "snapshot"; sid: string; consumer: string; snapshot: SessionSnapshot }
110
+ | {
111
+ t: "event"
112
+ sid: string
113
+ consumer: string
114
+ seq: number
115
+ provenance: Provenance
116
+ event: unknown
117
+ }
118
+ | { t: "replay_done"; sid: string; consumer: string; upToSeq: number }
119
+ | { t: "tail_marker"; sid: string; consumer: string; atSeq: number }
120
+ | { t: "ack_ok"; sid: string; consumer: string; seq: number }
121
+ | { t: "approval"; consumer: string; approval: ApprovalView }
122
+ | { t: "control_result"; idem: string; ok: boolean; result?: unknown; refusal?: RefusalBody }
123
+ | { t: "halt"; reason: HaltReason }
124
+ | { t: "pong"; id: string }
125
+ | { t: "error"; code: RefusalCode; message: string }
126
+
127
+ export interface RefusalBody {
128
+ code: RefusalCode
129
+ message: string
130
+ /** Nilai yang cocok hanya untuk diagnosis — bukan otoritas. */
131
+ detail?: Record<string, string | number | boolean | null>
132
+ }
133
+
134
+ /**
135
+ * Provenance sebuah event di mata konsumen. LIVE = dari penulis sesi sekarang;
136
+ * REPLAY = dibaca dari durable store; RECONSTRUCTED = hasil rebuild presentasi;
137
+ * UNKNOWN = tak dapat dipastikan. Tak boleh pernah diratakan ke satu nilai.
138
+ */
139
+ export type Provenance = "LIVE" | "REPLAY" | "RECONSTRUCTED" | "UNKNOWN"
140
+
141
+ /** Frontier = batas pengetahuan terakhir per toko (bukan kepemilikan). */
142
+ export interface SessionFrontiers {
143
+ writerEpoch: number
144
+ presentationHead: number
145
+ messageHead: number
146
+ runId: string | null
147
+ runStatus: string | null
148
+ }
149
+
150
+ /**
151
+ * Snapshot lintas toko. SENGAJA non-atomik (kontrak §): members+head+run
152
+ * diambil dari query terpisah — yang dijanjikan hanyalah angka-angka frontier
153
+ * beserta provenance-nya, bukan satu transaksi serentak.
154
+ */
155
+ export interface SessionSnapshot {
156
+ sid: string
157
+ frontiers: SessionFrontiers
158
+ presentation: unknown[]
159
+ provenance: Provenance
160
+ capturedAt: number
161
+ }
162
+
163
+ export type ApprovalState =
164
+ | "requested"
165
+ | "pending"
166
+ | "accepted"
167
+ | "denied"
168
+ | "expired"
169
+ | "cancelled"
170
+ | "UNKNOWN"
171
+
172
+ export interface ApprovalView {
173
+ approvalId: string
174
+ sid: string
175
+ state: ApprovalState
176
+ tool: string
177
+ summary: string
178
+ createdAt: number
179
+ expiresAt: number | null
180
+ decidedAt: number | null
181
+ }
182
+
183
+ /** Operasi kontrol yang didukung (whitelist eksplisit — tanpa evaluasi dinamis). */
184
+ export const CONTROL_OPS = [
185
+ "session.status",
186
+ "session.list",
187
+ "run.interrupt",
188
+ "run.cancel",
189
+ "approval.decide",
190
+ "approval.list",
191
+ "daemon.status",
192
+ "daemon.shutdown",
193
+ ] as const
194
+
195
+ export type ControlOp = (typeof CONTROL_OPS)[number]
196
+
197
+ export function isControlOp(v: string): v is ControlOp {
198
+ return (CONTROL_OPS as readonly string[]).includes(v)
199
+ }
200
+
201
+ /** Cakupan minimum per operasi kontrol — ditolak lebih awal, bukan di tengah. */
202
+ export function requiredScope(op: ControlOp): DaemonScope {
203
+ switch (op) {
204
+ case "session.list":
205
+ case "daemon.status":
206
+ return "read:session"
207
+ case "session.status":
208
+ case "run.interrupt":
209
+ case "run.cancel":
210
+ return "control:session"
211
+ case "approval.decide":
212
+ case "approval.list":
213
+ return "approve"
214
+ case "daemon.shutdown":
215
+ return "admin"
216
+ }
217
+ }
@@ -0,0 +1,170 @@
1
+ // P2.12 — pengawas sumber daya: tekanan penyimpanan + pembersihan.
2
+ //
3
+ // Kenapa tekanan disk masuk ke kontrak, bukan sekadar warning: saat SQLite
4
+ // tak bisa menulis, yang terjadi bukan "operasi gagal rapi" — sebagian transaksi
5
+ // sudah berjalan dan gagal di tengah. Kontrak menuntut daemon MENGHENTIKAN
6
+ // pekerjaan baru saat itu, bukan terus mencoba dan akhirnya mengarang hasil
7
+ // yang tampak sukses. Jadi tekanan = gerbang, bukan catatan.
8
+
9
+ import { statfsSync } from "node:fs"
10
+ import { homedir } from "node:os"
11
+ import { dirname } from "node:path"
12
+
13
+ /**
14
+ * Sisa ruang minimum agar SQLite WAL + checkpoint tetap bisa bergerak.
15
+ * 64 MiB dipilih dari pengalaman: WAL yang tak bisa di-checkpoint tumbuh tak
16
+ * terbatas lalu mengunci write berikutnya — menunggu sampai 0 berarti sudah
17
+ * terlambat jauh sebelum itu.
18
+ */
19
+ export const MIN_FREE_BYTES = 64 * 1024 * 1024
20
+
21
+ export type StorageCheck =
22
+ | { ok: true; freeBytes: number }
23
+ | { ok: false; freeBytes: number; minFreeBytes: number; reason: string }
24
+
25
+ /**
26
+ * Cek ruang bebas pada volume tujuan. Gagal membaca = TIDAK ok (fail-closed):
27
+ * kita tidak tahu apakah aman, dan "tidak tahu" tidak boleh diperlakukan
28
+ * sebagai "aman" pada jalur yang menulis durable.
29
+ */
30
+ export function checkStorage(target: string, minFreeBytes = MIN_FREE_BYTES): StorageCheck {
31
+ let probe = target
32
+ try {
33
+ // statfsSync menolak path yang bukan direktori; naikkan sampai ketemu.
34
+ // (target bisa berupa berkas DB.)
35
+ let cur = probe
36
+ for (let i = 0; i < 8; i++) {
37
+ const next = dirname(cur)
38
+ if (next === cur) break
39
+ cur = next
40
+ }
41
+ probe = cur
42
+ } catch {
43
+ probe = process.cwd()
44
+ }
45
+ try {
46
+ const st = statfsSync(probe)
47
+ const free = Number(st.bavail) * Number(st.bsize)
48
+ if (!Number.isFinite(free)) {
49
+ return {
50
+ ok: false,
51
+ freeBytes: 0,
52
+ minFreeBytes,
53
+ reason: "statfs mengembalikan nilai tak valid",
54
+ }
55
+ }
56
+ if (free < minFreeBytes) {
57
+ return {
58
+ ok: false,
59
+ freeBytes: free,
60
+ minFreeBytes,
61
+ reason: `sisa ${free}B < minimum ${minFreeBytes}B`,
62
+ }
63
+ }
64
+ return { ok: true, freeBytes: free }
65
+ } catch (e) {
66
+ return {
67
+ ok: false,
68
+ freeBytes: 0,
69
+ minFreeBytes,
70
+ reason: `statfs gagal: ${String((e as Error).message ?? e)}`,
71
+ }
72
+ }
73
+ }
74
+
75
+ export type PressureState = "ok" | "storage"
76
+
77
+ export interface ResourceSnapshot {
78
+ pressure: PressureState
79
+ freeBytes: number
80
+ rssBytes: number
81
+ checkedAt: number
82
+ reason?: string
83
+ }
84
+
85
+ export interface ResourceMonitorDeps {
86
+ cwd?: string
87
+ minFreeBytes?: number
88
+ intervalMs?: number
89
+ onPressure: (state: PressureState, snap: ResourceSnapshot) => void
90
+ }
91
+
92
+ /**
93
+ * Periodik memeriksa ruang + memori. Perubahan tekanan SAJA yang memicu
94
+ * callback (edge-triggered) supaya shutdown loop tak membanjiri konsumen
95
+ * dengan pesan sama tiap tick.
96
+ */
97
+ export class ResourceMonitor {
98
+ readonly #deps: ResourceMonitorDeps
99
+ #timer: ReturnType<typeof setInterval> | null = null
100
+ #state: PressureState = "ok"
101
+ #last: ResourceSnapshot | null = null
102
+ #checks = 0
103
+ #pressureEvents = 0
104
+
105
+ constructor(deps: ResourceMonitorDeps) {
106
+ this.#deps = deps
107
+ }
108
+
109
+ get state(): PressureState {
110
+ return this.#state
111
+ }
112
+
113
+ get last(): ResourceSnapshot | null {
114
+ return this.#last
115
+ }
116
+
117
+ get stats(): { checks: number; pressureEvents: number } {
118
+ return { checks: this.#checks, pressureEvents: this.#pressureEvents }
119
+ }
120
+
121
+ probe(now = Date.now()): ResourceSnapshot {
122
+ const check = checkStorage(this.#deps.cwd ?? process.cwd(), this.#deps.minFreeBytes)
123
+ const next: PressureState = check.ok ? "ok" : "storage"
124
+ const snap: ResourceSnapshot = {
125
+ pressure: next,
126
+ freeBytes: check.ok ? check.freeBytes : check.freeBytes,
127
+ rssBytes: readRss(),
128
+ checkedAt: now,
129
+ ...(check.ok ? {} : { reason: check.reason }),
130
+ }
131
+ this.#checks++
132
+ this.#last = snap
133
+ if (next !== this.#state) {
134
+ this.#state = next
135
+ if (next === "storage") this.#pressureEvents++
136
+ this.#deps.onPressure(next, snap)
137
+ }
138
+ return snap
139
+ }
140
+
141
+ start(): void {
142
+ if (this.#timer) return
143
+ this.probe()
144
+ this.#timer = setInterval(() => this.probe(), Math.max(1_000, this.#deps.intervalMs ?? 30_000))
145
+ // Jangan menahan proses hanya karena monitor hidup.
146
+ this.#timer.unref?.()
147
+ }
148
+
149
+ stop(): void {
150
+ if (this.#timer) clearInterval(this.#timer)
151
+ this.#timer = null
152
+ }
153
+ }
154
+
155
+ function readRss(): number {
156
+ try {
157
+ return process.memoryUsage().rss
158
+ } catch {
159
+ return -1
160
+ }
161
+ }
162
+
163
+ /** Path default saat tak ada cwd eksplisit — dipakai diagnosa startup. */
164
+ export function defaultProbePath(): string {
165
+ try {
166
+ return process.cwd()
167
+ } catch {
168
+ return homedir()
169
+ }
170
+ }