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,361 @@
1
+ // P2.12 — otoritas persetujuan durable.
2
+ //
3
+ // Kenapa modul ini, bukan UI: kontrak memisahkan "UI menyetujui" dari
4
+ // "otoritas persetujuan". Di sini baris SQLite-lah yang memutuskan; konsumen
5
+ // Desktop hanya MENGUSULKAN. Persetujuan tetap ada dan bisa diaudit setelah
6
+ // prosesnya mati — bedanya dengan prompt layar yang hilang begitu jendela
7
+ // ditutup.
8
+ //
9
+ // Sifat yang dijaga:
10
+ // - expiry/denied = DENY. Tak ada jalur "habis waktu lalu diizinkan".
11
+ // - kegagalan penyimpanan = DENY (storage failure tak boleh menghasilkan
12
+ // sukses yang dikarang).
13
+ // - pending/requested pada saat daemon start -> UNKNOWN (lihat store.ts).
14
+
15
+ import { randomUUID } from "node:crypto"
16
+ import type { PermissionAsk } from "../policy/permission.ts"
17
+ import { hashArgs } from "../session/journal.ts"
18
+ import type { ApprovalView, RefusalBody } from "./protocol.ts"
19
+ import { sanitizeLabel } from "./sanitize.ts"
20
+ import {
21
+ type ApprovalRow,
22
+ createApproval,
23
+ getApproval,
24
+ listApprovals,
25
+ listOpenApprovals,
26
+ transitionApproval,
27
+ } from "./store.ts"
28
+
29
+ export type ApprovalDecision = "allow" | "deny"
30
+
31
+ export interface ApprovalRequestInput {
32
+ sid: string
33
+ runId?: string | null
34
+ tool: string
35
+ summary?: string
36
+ ttlMs?: number
37
+ /**
38
+ * [Fase 2 / LOOP-INV-08] Hash argumen kanonis. Bila diberikan, keputusan
39
+ * "allow" hanya berlaku untuk argumen yang hash-nya sama persis.
40
+ */
41
+ argsHash?: string | null
42
+ /** Identitas pemanggilan (tool call id) yang di-approve. */
43
+ invocationId?: string | null
44
+ }
45
+
46
+ interface Waiter {
47
+ resolve: (d: ApprovalDecision) => void
48
+ timer: ReturnType<typeof setTimeout> | null
49
+ }
50
+
51
+ const DEFAULT_TTL_MS = 60_000
52
+
53
+ /**
54
+ * [Fase 2 / LOOP-INV-08] Validasi pengikatan approval terhadap pemanggilan
55
+ * AKTUAL. Satu definisi, dipakai broker sebelum mengembalikan "allow" dan
56
+ * tersedia bagi konsumen yang mengonsumsi baris approval secara terpisah.
57
+ *
58
+ * Fail-closed: ketiadaan pengikat (`null`) TIDAK berarti "cocok dengan apa
59
+ * pun". Baris legacy hanya cocok bila sisi eksekusi juga tidak membawa hash/id.
60
+ */
61
+ export function verifyApprovalBinding(
62
+ row: Pick<ApprovalRow, "tool" | "argsHash" | "invocationId">,
63
+ actual: { tool: string; argsHash?: string | null; invocationId?: string | null },
64
+ ):
65
+ | { ok: true }
66
+ | { ok: false; reason: "tool-mismatch" | "args-hash-mismatch" | "invocation-mismatch" } {
67
+ if (row.tool !== actual.tool) return { ok: false, reason: "tool-mismatch" }
68
+ if ((row.argsHash ?? null) !== (actual.argsHash ?? null)) {
69
+ return { ok: false, reason: "args-hash-mismatch" }
70
+ }
71
+ if ((row.invocationId ?? null) !== (actual.invocationId ?? null)) {
72
+ return { ok: false, reason: "invocation-mismatch" }
73
+ }
74
+ return { ok: true }
75
+ }
76
+
77
+ function toView(row: ApprovalRow): ApprovalView {
78
+ return {
79
+ approvalId: row.approvalId,
80
+ sid: row.sid,
81
+ state: row.state,
82
+ tool: row.tool,
83
+ summary: row.summary,
84
+ createdAt: row.requestedAt,
85
+ expiresAt: row.expiresAt,
86
+ decidedAt: row.decidedAt,
87
+ }
88
+ }
89
+
90
+ export interface ApprovalBrokerDeps {
91
+ /** Incarnation daemon — melekat pada baris untuk melacak restart. */
92
+ incarnation: string
93
+ cwd?: string
94
+ /** Kirim usulan ke konsumen terhubung (bisa no-op bila tak ada siapa pun). */
95
+ propose: (view: ApprovalView) => void
96
+ /** Diagnostik non-fatal (storage gagal, dsb.). */
97
+ warn?: (msg: string) => void
98
+ }
99
+
100
+ export class ApprovalBroker {
101
+ readonly #deps: ApprovalBrokerDeps
102
+ readonly #waiters = new Map<string, Waiter>()
103
+
104
+ constructor(deps: ApprovalBrokerDeps) {
105
+ this.#deps = deps
106
+ }
107
+
108
+ /**
109
+ * Catat permintaan + tunggu keputusan. Mengembalikan keputusan, atau "deny"
110
+ * bila kedaluwarsa / tak ada yang menjawab / penyimpanan gagal.
111
+ *
112
+ * Sengaja TIDAK melempar: pemanggil adalah jalur permission — satu exception
113
+ * tak tertangkap di sana mengubah "ditolak" jadi "crash sesi".
114
+ */
115
+ async request(input: ApprovalRequestInput): Promise<ApprovalDecision> {
116
+ const ttl = Math.max(1_000, input.ttlMs ?? DEFAULT_TTL_MS)
117
+ const approvalId = `apr_${randomUUID()}`
118
+ const now = Date.now()
119
+ const tool = sanitizeLabel(input.tool, 64)
120
+ const argsHash = input.argsHash ?? null
121
+ const invocationId = input.invocationId ?? null
122
+ let view: ApprovalView
123
+ try {
124
+ const row = createApproval(
125
+ {
126
+ approvalId,
127
+ sid: input.sid,
128
+ runId: input.runId ?? null,
129
+ tool,
130
+ summary: sanitizeLabel(input.summary ?? "", 500),
131
+ state: "requested",
132
+ requestedAt: now,
133
+ expiresAt: now + ttl,
134
+ incarnation: this.#deps.incarnation,
135
+ argsHash,
136
+ invocationId,
137
+ },
138
+ this.#deps.cwd,
139
+ )
140
+ view = toView(row)
141
+ } catch (e) {
142
+ // Gagal mencatat = tak ada bukti yang bisa diaudit. Tolak, jangan lanjut
143
+ // seolah ada yang menyetujui.
144
+ this.#deps.warn?.(`[daemon] approval record failed: ${String((e as Error).message ?? e)}`)
145
+ return "deny"
146
+ }
147
+
148
+ const decision = await new Promise<ApprovalDecision>((resolve) => {
149
+ const waiter: Waiter = { resolve, timer: null }
150
+ this.#waiters.set(approvalId, waiter)
151
+ waiter.timer = setTimeout(() => {
152
+ this.#settle(approvalId, "deny", "expired")
153
+ }, ttl)
154
+ // Timer tak boleh menahan proses tetap hidup setelah selesai.
155
+ waiter.timer.unref?.()
156
+ try {
157
+ transitionApproval(approvalId, "pending", {}, this.#deps.cwd)
158
+ } catch (e) {
159
+ this.#deps.warn?.(`[daemon] approval pending failed: ${String((e as Error).message ?? e)}`)
160
+ }
161
+ // Usulkan SETELAH state = pending, supaya konsumen yang menjawab cepat
162
+ // tidak melihat status lama yang membuatnya menolak transisi sendiri.
163
+ this.#deps.propose({
164
+ ...view,
165
+ state: "pending",
166
+ })
167
+ })
168
+
169
+ // Konsumen mengirim "accept"; kita laporkan sebagai "allow" ke kernel.
170
+ if (decision === "allow") {
171
+ // [Fase 2 / LOOP-INV-08] Verifikasi pengikatan SEBELUM mengizinkan efek.
172
+ // Baris yang di-approve harus cocok pada tool + hash argumen + identitas
173
+ // pemanggilan. Baris hilang / legacy tanpa hash = tolak (fail-closed):
174
+ // keputusan yang tak dapat dicocokkan bukan izin untuk argumen apa pun.
175
+ const approved = getApproval(approvalId, this.#deps.cwd)
176
+ const binding = approved
177
+ ? verifyApprovalBinding(approved, { tool, argsHash, invocationId })
178
+ : { ok: false as const, reason: "approval-row-missing" }
179
+ if (!binding.ok) {
180
+ this.#deps.warn?.(
181
+ `[daemon] approval binding rejected (${binding.reason}) for ${tool}; denying`,
182
+ )
183
+ return "deny"
184
+ }
185
+ }
186
+ return decision
187
+ }
188
+
189
+ /**
190
+ * Keputusan dari konsumen. Idempoten: keputusan kedua untuk approval yang
191
+ * sudah terminal mengembalikan hasil yang sama, bukan error — konsumen yang
192
+ * retry setelah koneksi putus tidak boleh dihukum dengan penolakan palsu.
193
+ */
194
+ decide(
195
+ approvalId: string,
196
+ decision: "accept" | "deny",
197
+ now = Date.now(),
198
+ ): { ok: true; row: ApprovalRow } | { ok: false; refusal: RefusalBody } {
199
+ const row = getApproval(approvalId, this.#deps.cwd)
200
+ if (!row) {
201
+ return {
202
+ ok: false,
203
+ refusal: { code: "NOT_FOUND", message: `approval ${approvalId} tidak ditemukan` },
204
+ }
205
+ }
206
+ if (row.state === "accepted" || row.state === "denied") {
207
+ const matches =
208
+ (decision === "accept" && row.state === "accepted") ||
209
+ (decision === "deny" && row.state === "denied")
210
+ if (matches) return { ok: true, row }
211
+ return {
212
+ ok: false,
213
+ refusal: {
214
+ code: "APPROVAL_INVALID_STATE",
215
+ message: `approval sudah ${row.state}; keputusan berbeda ditolak`,
216
+ },
217
+ }
218
+ }
219
+ if (row.state === "UNKNOWN") {
220
+ // Hasil lama tak pernah diketahui — mengklaim "diterima/ditolak" sekarang
221
+ // akan menulis keputusan yang tak pernah dibuat siapa pun.
222
+ return {
223
+ ok: false,
224
+ refusal: {
225
+ code: "APPROVAL_UNKNOWN",
226
+ message: `approval ${approvalId} berstatus UNKNOWN (daemon restart)`,
227
+ },
228
+ }
229
+ }
230
+ if (row.state === "expired" || row.state === "cancelled") {
231
+ return {
232
+ ok: false,
233
+ refusal: {
234
+ code: "APPROVAL_EXPIRED",
235
+ message: `approval ${approvalId} sudah ${row.state}`,
236
+ },
237
+ }
238
+ }
239
+ if (row.expiresAt !== null && row.expiresAt <= now) {
240
+ // Lewat tenggat: tetap catat expired (bukan keputusan konsumen).
241
+ const expired = this.#settle(approvalId, "deny", "expired")
242
+ return {
243
+ ok: false,
244
+ refusal: {
245
+ code: "APPROVAL_EXPIRED",
246
+ message: `approval ${approvalId} kedaluwarsa pada ${row.expiresAt}`,
247
+ detail: { expiredBy: now - row.expiresAt, ...(expired ? {} : {}) },
248
+ },
249
+ }
250
+ }
251
+
252
+ const target = decision === "accept" ? "accepted" : "denied"
253
+ let updated: ApprovalRow
254
+ try {
255
+ updated = transitionApproval(approvalId, target, { decision, decidedAt: now }, this.#deps.cwd)
256
+ } catch (e) {
257
+ // Transisi tak sah = permintaan ganda yang saling bertabrakan; bukan
258
+ // error protokol — laporkan apa adanya.
259
+ return {
260
+ ok: false,
261
+ refusal: {
262
+ code: "APPROVAL_INVALID_STATE",
263
+ message: String((e as Error).message ?? e),
264
+ },
265
+ }
266
+ }
267
+ this.#settleWaiter(approvalId, decision === "accept" ? "allow" : "deny")
268
+ return { ok: true, row: updated }
269
+ }
270
+
271
+ /** Selesaikan waiter dengan hasil tertentu tanpa mengubah state DB. */
272
+ #settleWaiter(approvalId: string, decision: ApprovalDecision): void {
273
+ const w = this.#waiters.get(approvalId)
274
+ if (!w) return
275
+ this.#waiters.delete(approvalId)
276
+ if (w.timer) clearTimeout(w.timer)
277
+ w.resolve(decision)
278
+ }
279
+
280
+ /** Pindahkan ke terminal lalu selesaikan waiter (dipakai timer expiry). */
281
+ #settle(approvalId: string, decision: ApprovalDecision, state: "expired" | "cancelled"): boolean {
282
+ try {
283
+ transitionApproval(approvalId, state, { decision: state }, this.#deps.cwd)
284
+ } catch {
285
+ // [RC-6] Transisi gagal: settle waiter HANYA bila baris benar-benar sudah
286
+ // terminal (perorangan decide/kadaluwarsa lain menang). Baris hilang atau
287
+ // masih non-terminal = error nyata → jangan settle diam-diam.
288
+ const row = getApproval(approvalId, this.#deps.cwd)
289
+ if (!row) return false
290
+ if (row.state === "requested" || row.state === "pending") return false
291
+ }
292
+ this.#settleWaiter(approvalId, decision)
293
+ return true
294
+ }
295
+
296
+ list(sid: string): ApprovalView[] {
297
+ try {
298
+ return listApprovals(sid, this.#deps.cwd).map(toView)
299
+ } catch {
300
+ return []
301
+ }
302
+ }
303
+
304
+ listOpen(sid: string): ApprovalView[] {
305
+ try {
306
+ return listOpenApprovals(sid, this.#deps.cwd).map(toView)
307
+ } catch {
308
+ return []
309
+ }
310
+ }
311
+
312
+ /** Baca baris approval tanpa mutasi — untuk cek otoritas SEBELUM decide (RC-2). */
313
+ read(approvalId: string): ApprovalRow | null {
314
+ try {
315
+ return getApproval(approvalId, this.#deps.cwd)
316
+ } catch {
317
+ return null
318
+ }
319
+ }
320
+
321
+ /** Tutup semua waiter (daemon shutdown): keputusan tak pernah = izin. */
322
+ shutdownAll(): number {
323
+ const ids = [...this.#waiters.keys()]
324
+ for (const id of ids) this.#settle(id, "deny", "cancelled")
325
+ return ids.length
326
+ }
327
+
328
+ /**
329
+ * Pasang jalur ask permission. Ini SATU-SATUNYA jembatan dari kernel ke
330
+ * broker — composition root yang memasangnya (fail-closed tanpa injeksi).
331
+ */
332
+ asPermissionAsk(opts: { sid: () => string; runId?: () => string | null }): PermissionAsk {
333
+ return async (call) => {
334
+ const sid = opts.sid()
335
+ if (!sid) return "deny"
336
+ const tool = String(call?.name ?? "unknown")
337
+ const decision = await this.request({
338
+ sid,
339
+ runId: opts.runId ? opts.runId() : null,
340
+ tool,
341
+ summary: summarizeArgs(call?.args),
342
+ // [Fase 2 / LOOP-INV-08] Ikat keputusan ke argumen kanonis + id call.
343
+ argsHash: hashArgs(call?.args ?? {}),
344
+ invocationId: typeof call?.id === "string" && call.id !== "" ? call.id : null,
345
+ })
346
+ return decision === "allow" ? "allow" : "deny"
347
+ }
348
+ }
349
+ }
350
+
351
+ /** Ringkasan args untuk ditampilkan konsumen — dipangkas, dibasuh, dibatasi. */
352
+ function summarizeArgs(args: unknown): string {
353
+ if (args === undefined || args === null) return ""
354
+ let text: string
355
+ try {
356
+ text = typeof args === "string" ? args : JSON.stringify(args)
357
+ } catch {
358
+ return ""
359
+ }
360
+ return sanitizeLabel(text, 300)
361
+ }
@@ -0,0 +1,145 @@
1
+ // P2.12 — capability bercakupan untuk IPC loopback.
2
+ //
3
+ // Kenapa capability, bukan "PID + kepercayaan": kontrak melarang PID jadi
4
+ // otoritas (PID dapat didaur ulang/dipalsukan lintas sesi OS) dan melarang
5
+ // token penulis lewat IPC. Yang dibutuhkan konsumen hanya SATU hal: izin
6
+ // menjalankan kelas operasi tertentu selama masa berlaku tertentu — itu persis
7
+ // definisi capability.
8
+ //
9
+ // Tiga jaminan yang diuji:
10
+ // 1. Cakupan sempit dan eksplisit — tak ada "admin diam-diam".
11
+ // 2. Kedaluwarsa waktu nyata (TTL) — kebocoran tak abadi.
12
+ // 3. Terikat `incarnation` daemon — restart memutar secret → capability lama
13
+ // mati → konsumen lama menerima STALE_INCARNATION, bukan akses senyap ke
14
+ // daemon baru.
15
+ //
16
+ // Secret TIDAK PERNAH dikirim lewat IPC; hanya dipakai menandatangani.
17
+
18
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto"
19
+ import { DAEMON_SCOPES, type DaemonScope } from "./protocol.ts"
20
+ import { sanitizeLabel } from "./sanitize.ts"
21
+
22
+ export interface CapabilityPayload {
23
+ v: 1
24
+ /** Incarnation daemon yang menandatangani. */
25
+ inc: string
26
+ /** Cakupan diberikan (subset terurut, unik). */
27
+ scopes: DaemonScope[]
28
+ /** Epoch millis kedaluwarsa. */
29
+ exp: number
30
+ /** Nonce acak — tiap mint unik. */
31
+ n: string
32
+ /** Nama konsumen (label, dibasuh) — diagnosis, bukan otoritas. */
33
+ who: string
34
+ }
35
+
36
+ export type CapabilityFailure =
37
+ | "MALFORMED"
38
+ | "BAD_SIGNATURE"
39
+ | "EXPIRED"
40
+ | "STALE_INCARNATION"
41
+ | "BAD_SCOPE"
42
+
43
+ export type CapabilityCheck =
44
+ | { ok: true; payload: CapabilityPayload }
45
+ | { ok: false; reason: CapabilityFailure }
46
+
47
+ function sign(secret: Buffer, body: string): string {
48
+ return createHmac("sha256", secret).update(body).digest("base64url")
49
+ }
50
+
51
+ // Serialisasi deterministik: urutan kunci tetap agar signature stabil lintas
52
+ // proses (JSON.stringify mengikuti urutan inisialisasi objek).
53
+ function canon(p: CapabilityPayload): string {
54
+ return JSON.stringify({
55
+ v: p.v,
56
+ inc: p.inc,
57
+ scopes: [...p.scopes].sort(),
58
+ exp: p.exp,
59
+ n: p.n,
60
+ who: p.who,
61
+ })
62
+ }
63
+
64
+ export function mintCapability(
65
+ secret: Buffer,
66
+ opts: { incarnation: string; scopes: DaemonScope[]; ttlMs: number; who: string; now?: number },
67
+ ): string {
68
+ const now = opts.now ?? Date.now()
69
+ const scopes = [...new Set(opts.scopes)].filter((s) => DAEMON_SCOPES.includes(s)).sort()
70
+ if (scopes.length === 0) throw new Error("mintCapability: minimal satu cakupan valid")
71
+ const p: CapabilityPayload = {
72
+ v: 1,
73
+ inc: sanitizeLabel(opts.incarnation, 64),
74
+ scopes,
75
+ exp: now + Math.max(1_000, opts.ttlMs),
76
+ n: randomBytes(9).toString("base64url"),
77
+ who: sanitizeLabel(opts.who, 120),
78
+ }
79
+ const body = canon(p)
80
+ return `${Buffer.from(body, "utf8").toString("base64url")}.${sign(secret, body)}`
81
+ }
82
+
83
+ export function verifyCapability(
84
+ secret: Buffer,
85
+ token: string,
86
+ opts: { incarnation: string; now?: number },
87
+ ): CapabilityCheck {
88
+ if (typeof token !== "string" || token.length === 0 || token.length > 8192)
89
+ return { ok: false, reason: "MALFORMED" }
90
+ const dot = token.lastIndexOf(".")
91
+ if (dot <= 0) return { ok: false, reason: "MALFORMED" }
92
+ let body: string
93
+ try {
94
+ body = Buffer.from(token.slice(0, dot), "base64url").toString("utf8")
95
+ } catch {
96
+ return { ok: false, reason: "MALFORMED" }
97
+ }
98
+ const sig = Buffer.from(token.slice(dot + 1), "utf8")
99
+ const expect = Buffer.from(sign(secret, body), "utf8")
100
+ // timingSafeEqual menuntut panjang sama; beda panjang = sudah pasti gagal.
101
+ if (sig.length !== expect.length || !timingSafeEqual(sig, expect))
102
+ return { ok: false, reason: "BAD_SIGNATURE" }
103
+
104
+ let payload: CapabilityPayload
105
+ try {
106
+ payload = JSON.parse(body) as CapabilityPayload
107
+ } catch {
108
+ return { ok: false, reason: "MALFORMED" }
109
+ }
110
+ if (payload?.v !== 1 || !Array.isArray(payload.scopes)) return { ok: false, reason: "MALFORMED" }
111
+ if (payload.inc !== opts.incarnation) return { ok: false, reason: "STALE_INCARNATION" }
112
+ const now = opts.now ?? Date.now()
113
+ if (typeof payload.exp !== "number" || payload.exp <= now) return { ok: false, reason: "EXPIRED" }
114
+ if (!payload.scopes.every((s) => DAEMON_SCOPES.includes(s)))
115
+ return { ok: false, reason: "BAD_SCOPE" }
116
+ return { ok: true, payload }
117
+ }
118
+
119
+ export function hasScope(p: CapabilityPayload, need: DaemonScope): boolean {
120
+ // `admin` TIDAK otomatis mengandung cakupan lain: cakupan diberikan eksplisit
121
+ // agar "operator daemon" tak berubah diam-diam jadi "penyetuju persetujuan".
122
+ return p.scopes.includes(need)
123
+ }
124
+
125
+ /**
126
+ * Terbitkan capability dari berkas endpoint (dipakai klien/CLI di proses lain).
127
+ *
128
+ * `who` dan `scopes` selalu datang dari PEMANGGIL — tak ada default admin.
129
+ * Kegagalan membaca berkas dilempar sebagai error: menghasilkan capability
130
+ * kosong yang "sepertinya sah" akan menipu pemanggil sendiri.
131
+ */
132
+ export function issueCapabilityFromEndpoint(
133
+ ep: { bootstrap: string; incarnation: string },
134
+ opts: { scopes: DaemonScope[]; who: string; ttlMs?: number; now?: number },
135
+ ): string {
136
+ const secret = Buffer.from(ep.bootstrap, "base64url")
137
+ if (secret.length < 16) throw new Error("endpoint bootstrap tidak valid (terlalu pendek)")
138
+ return mintCapability(secret, {
139
+ incarnation: ep.incarnation,
140
+ scopes: opts.scopes,
141
+ ttlMs: opts.ttlMs ?? 10 * 60_000,
142
+ who: opts.who,
143
+ ...(opts.now !== undefined ? { now: opts.now } : {}),
144
+ })
145
+ }
@@ -0,0 +1,142 @@
1
+ // P2.12 — pengawas anak (child) milik daemon.
2
+ //
3
+ // Dua aturan yang dijaga di sini, bukan di pemanggil:
4
+ //
5
+ // 1. ANAK TIDAK PERNAH DIADOPSI. Bila daemon mati dan hidup lagi, anak yang
6
+ // dulu berjalan bukan miliknya lagi — ia tak tahu apakah anak itu masih
7
+ // hidup, sudah selesai, atau sudah diganti. Mengklaimnya kembali akan
8
+ // membuat dua pihak percaya diri memerintah proses yang sama. Karena itu
9
+ // dibuat. Karena itu tidak ada jalur adopsi: sisa anak dari generasi lama
10
+ // dibiarkan jatuh ke jalur tombstone kanonik yang sudah ada (resume),
11
+ // bukan diadopsi.
12
+ //
13
+ // 2. PID BUKAN otoritas. PID dicatat untuk manusia membaca log; status
14
+ // kehidupan anak TIDAK PERNAH disimpulkan dari "PID masih ada" (PID bisa
15
+ // didaur ulang). Status resmi anak = `unknown` kecuali daemon yang
16
+ // MENCIPTAKAN anak itu sendiri menerima laporan selesai.
17
+
18
+ import { sanitizeLabel } from "./sanitize.ts"
19
+ import type { Telemetry } from "./telemetry.ts"
20
+
21
+ export type ChildStatus = "running" | "finished" | "lost"
22
+
23
+ export interface ChildRecord {
24
+ childId: string
25
+ sid: string
26
+ runId: string | null
27
+ /** Diagnosis manusia saja — tidak pernah dipakai menentukan status. */
28
+ pid: number
29
+ startedAt: number
30
+ endedAt: number | null
31
+ status: ChildStatus
32
+ /** Nonce acak; dipasang daemon ini dan TIDAK pernah diteruskan ke IPC. */
33
+ token: string
34
+ }
35
+
36
+ export interface ChildSupervisorDeps {
37
+ telemetry: Telemetry
38
+ now?: () => number
39
+ }
40
+
41
+ export class ChildSupervisor {
42
+ readonly #children = new Map<string, ChildRecord>()
43
+ readonly #deps: ChildSupervisorDeps
44
+
45
+ constructor(deps: ChildSupervisorDeps) {
46
+ this.#deps = deps
47
+ }
48
+
49
+ register(init: {
50
+ childId: string
51
+ sid: string
52
+ runId?: string | null
53
+ pid: number
54
+ token: string
55
+ }): ChildRecord {
56
+ const now = this.#deps.now?.() ?? Date.now()
57
+ const rec: ChildRecord = {
58
+ childId: sanitizeLabel(init.childId, 120),
59
+ sid: sanitizeLabel(init.sid, 120),
60
+ runId: init.runId ?? null,
61
+ pid: init.pid,
62
+ startedAt: now,
63
+ endedAt: null,
64
+ status: "running",
65
+ token: init.token,
66
+ }
67
+ this.#children.set(rec.childId, rec)
68
+ this.#deps.telemetry.inc("child.registered")
69
+ return rec
70
+ }
71
+
72
+ /** Catat laporan selesai yang datang dari jalur yang menciptakan anak. */
73
+ finish(childId: string): ChildRecord | null {
74
+ const rec = this.#children.get(childId)
75
+ if (!rec) return null
76
+ if (rec.status === "running") {
77
+ rec.status = "finished"
78
+ rec.endedAt = this.#deps.now?.() ?? Date.now()
79
+ this.#deps.telemetry.inc("child.finished")
80
+ }
81
+ return rec
82
+ }
83
+
84
+ /**
85
+ * Tandai anak yang kehilangan pelapor. Sengaja BUKAN "lost = mati": kita
86
+ * tidak tahu apakah ia mati atau hanya pelapornya yang hilang. Yang pasti
87
+ * hanyalah: tak ada yang bisa dikonfirmasi lagi.
88
+ */
89
+ markUnknown(childId: string): ChildRecord | null {
90
+ const rec = this.#children.get(childId)
91
+ if (rec?.status !== "running") return null
92
+ rec.status = "lost"
93
+ rec.endedAt = this.#deps.now?.() ?? Date.now()
94
+ return rec
95
+ }
96
+
97
+ get(childId: string): ChildRecord | null {
98
+ return this.#children.get(childId) ?? null
99
+ }
100
+
101
+ list(sid?: string): ChildRecord[] {
102
+ const all = [...this.#children.values()]
103
+ return sid ? all.filter((c) => c.sid === sid) : all
104
+ }
105
+
106
+ /** Anak yang masih diklaim berjalan oleh generasi ini. */
107
+ running(): ChildRecord[] {
108
+ return this.list().filter((c) => c.status === "running")
109
+ }
110
+
111
+ /**
112
+ * Tutup pengawasan: semua yang masih `running` menjadi `lost`.
113
+ *
114
+ * Sengaja tidak "finished" dan tidak "failed" — keduanya adalah KLAIM atas
115
+ * hasil. Daemon berhenti tanpa menerima laporan selesai; yang jujur hanya
116
+ * "tak bisa dikonfirmasi".
117
+ */
118
+ shutdown(): number {
119
+ let n = 0
120
+ for (const rec of this.#children.values()) {
121
+ if (rec.status === "running") {
122
+ rec.status = "lost"
123
+ rec.endedAt = this.#deps.now?.() ?? Date.now()
124
+ n++
125
+ }
126
+ }
127
+ return n
128
+ }
129
+
130
+ get size(): number {
131
+ return this.#children.size
132
+ }
133
+
134
+ clear(): void {
135
+ this.#children.clear()
136
+ }
137
+
138
+ /** Laporan ringkas — TIDAK memuat token (token tak pernah keluar modul ini). */
139
+ report(): Array<Omit<ChildRecord, "token">> {
140
+ return this.list().map(({ token: _token, ...rest }) => rest)
141
+ }
142
+ }