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,858 @@
1
+ // Kebijakan proyeksi presentasi — murni, tanpa IO/clock/env/TTY/ANSI/i18n.
2
+ //
3
+ // Kenapa berkas ini ada: TUI, linear, exec, dan ACP menafsirkan
4
+ // PresentationState sendiri-sendiri sehingga status/target/durasi bisa
5
+ // divergen (OAP-001). Modul ini adalah SATU tempat keputusan node semantik:
6
+ // node mana yang tampil per mode, deskripsi activity/turn, running pin,
7
+ // envelope machine, dan digest divergensi. Renderer hanya layout, paint,
8
+ // sanitasi, dan pemotongan lebar; sanitasi tetap di sisi render
9
+ // (sanitizeAnsi) dan tidak pernah di sini.
10
+
11
+ import { LIMITS } from "../constants.ts"
12
+ import type { ContentRef, TurnSummary } from "./events.ts"
13
+ import type {
14
+ ActivityEntry,
15
+ DiagnosticEntry,
16
+ FindingEntry,
17
+ PlanEntry,
18
+ PresentationState,
19
+ ReasoningEntry,
20
+ ResultEntry,
21
+ SystemEntry,
22
+ ToolStatus,
23
+ TurnEntry,
24
+ } from "./model.ts"
25
+
26
+ export type ProjectionMode = "normal" | "verbose" | "debug" | "machine"
27
+
28
+ /**
29
+ * Provenans tampilan — BUKAN status runtime.
30
+ *
31
+ * - `live`: observasi lewat jalur adapter/bus aktif.
32
+ * - `replay`: observasi durable dimuat ulang dan di-reduce ulang.
33
+ * - `reconstructed`: status turunan inferensi saat rebuild (interrupted,
34
+ * placeholder bukti yatim) — jangan pernah disajikan sebagai terminal
35
+ * yang diobservasi runtime.
36
+ * - `unknown`: provenance tak dapat ditetapkan.
37
+ *
38
+ * Aturan render: field provenance HANYA diisi untuk non-live. Absen =
39
+ * live-atau-tak-ditentukan, dan ketiadaan itu tidak boleh dibaca sebagai
40
+ * keberhasilan. Ini menjaga bentuk output lama tetap identik.
41
+ */
42
+ export type Provenance = "live" | "replay" | "reconstructed" | "unknown"
43
+
44
+ /**
45
+ * Turunkan provenance satu baris dari penanda eksplisit + watershed replay.
46
+ *
47
+ * `replayedUpToSeq` = state.seq sesaat setelah rebuild (null bila tak ada
48
+ * rebuild dalam sesi ini). Baris di atas watershed adalah live. Baris pada
49
+ * atau di bawah watershed adalah replay, kecuali status/incomplete yang
50
+ * hanya lahir dari inferensi rebuild → reconstructed.
51
+ */
52
+ export function projectProvenance(
53
+ entry: { status?: string; incomplete?: boolean },
54
+ eventSeq: number,
55
+ replayedUpToSeq: number | null,
56
+ ): Provenance | undefined {
57
+ if (replayedUpToSeq === null || replayedUpToSeq === undefined) return undefined
58
+ if (eventSeq > replayedUpToSeq) return undefined
59
+ if (entry.status === "interrupted" || entry.incomplete === true) return "reconstructed"
60
+ return "replay"
61
+ }
62
+
63
+ export interface ProjectionContext {
64
+ mode: ProjectionMode
65
+ /** Jam tepi (ms) untuk keputusan elapsed; wajib di-inject agar murni. */
66
+ now?: number
67
+ }
68
+
69
+ // ── Deskripsi semantik (tanpa paint/sanitasi/truncate) ──
70
+
71
+ export interface ActivityDescription {
72
+ toolCallId: string
73
+ name: string
74
+ target?: string
75
+ status: ToolStatus
76
+ summary?: string
77
+ message?: string
78
+ durationMs?: number
79
+ denyReason?: string
80
+ receiptPaths: string[]
81
+ testSummary?: { passed: number; failed: number; summary: string }
82
+ retryOf?: string
83
+ childCount: number
84
+ isChild: boolean
85
+ expandRef?: ContentRef
86
+ error?: { cause?: string; message: string; hint?: string }
87
+ tsStart: number
88
+ tsEnd?: number
89
+ /** Observasi verifikasi terakhir; absen = UNKNOWN (diturunkan, bukan success). */
90
+ verification?: {
91
+ invocationId: string
92
+ verdict: "present" | "absent" | "inconclusive"
93
+ method: string
94
+ observedAt: number
95
+ }
96
+ /** Provenans tampilan; absen = live-atau-tak-ditentukan. */
97
+ provenance?: Provenance
98
+ }
99
+
100
+ /**
101
+ * Bentuk activity struktural yang diterima policy — dipenuhi ActivityEntry
102
+ * model maupun snapshot UI tanpa impor lintas lapisan.
103
+ */
104
+ export interface ActivityLike {
105
+ toolCallId: string
106
+ name?: string
107
+ target?: string
108
+ status: ToolStatus
109
+ summary?: string
110
+ durationMs?: number
111
+ denyReason?: string
112
+ receipt?: { paths?: string[]; test?: { passed: number; failed: number; summary: string } }
113
+ supersedes?: string
114
+ parentToolCallId?: string
115
+ expandRef?: ContentRef
116
+ error?: { cause?: string; message: string; hint?: string }
117
+ tsStart: number
118
+ tsEnd?: number
119
+ verification?: ActivityDescription["verification"]
120
+ provenance?: Provenance
121
+ }
122
+
123
+ export function describeActivity(
124
+ activity: ActivityEntry | ActivityLike,
125
+ opts: { childCount?: number } = {},
126
+ ): ActivityDescription {
127
+ const source = activity as ActivityLike & { identity?: { name: string } }
128
+ const name = source.identity?.name ?? source.name ?? "tool"
129
+ return {
130
+ toolCallId: activity.toolCallId,
131
+ name,
132
+ ...(activity.target ? { target: activity.target } : {}),
133
+ status: activity.status,
134
+ ...(activity.summary ? { summary: activity.summary } : {}),
135
+ ...(activity.error ? { message: activity.error.message } : {}),
136
+ ...(activity.durationMs !== undefined ? { durationMs: activity.durationMs } : {}),
137
+ ...(activity.denyReason ? { denyReason: activity.denyReason } : {}),
138
+ receiptPaths: [...(activity.receipt?.paths ?? [])],
139
+ ...(activity.receipt?.test ? { testSummary: { ...activity.receipt.test } } : {}),
140
+ ...(activity.supersedes ? { retryOf: activity.supersedes } : {}),
141
+ childCount: opts.childCount ?? 0,
142
+ isChild: activity.parentToolCallId !== undefined,
143
+ ...(activity.expandRef ? { expandRef: { ...activity.expandRef } } : {}),
144
+ ...(activity.verification ? { verification: { ...activity.verification } } : {}),
145
+ // Provenance hanya hidup di snapshot/view (ActivityLike), bukan di state
146
+ // reducer (ActivityEntry) — dibaca struktural agar state tetap murni.
147
+ ...(source.provenance ? { provenance: source.provenance } : {}),
148
+ ...(activity.error
149
+ ? {
150
+ error: {
151
+ cause: activity.error.cause,
152
+ message: activity.error.message,
153
+ ...(activity.error.hint ? { hint: activity.error.hint } : {}),
154
+ },
155
+ }
156
+ : {}),
157
+ tsStart: activity.tsStart,
158
+ ...(activity.tsEnd !== undefined ? { tsEnd: activity.tsEnd } : {}),
159
+ }
160
+ }
161
+
162
+ export interface TurnDescription {
163
+ turnId: number
164
+ status: TurnEntry["status"]
165
+ summary?: TurnSummary
166
+ checkpointId?: string
167
+ error?: string
168
+ /** Provenans tampilan; absen = live-atau-tak-ditentukan. */
169
+ provenance?: Provenance
170
+ }
171
+
172
+ /** Bentuk turn struktural — dipenuhi TurnEntry model maupun snapshot UI. */
173
+ export interface TurnLike {
174
+ turnId: number
175
+ status: TurnEntry["status"]
176
+ summary?: TurnSummary
177
+ checkpointId?: string
178
+ error?: string
179
+ provenance?: Provenance
180
+ }
181
+
182
+ export function describeTurn(turn: TurnLike): TurnDescription {
183
+ return {
184
+ turnId: turn.turnId,
185
+ status: turn.status,
186
+ ...(turn.summary ? { summary: turn.summary } : {}),
187
+ ...(turn.checkpointId ? { checkpointId: turn.checkpointId } : {}),
188
+ ...(turn.error ? { error: turn.error } : {}),
189
+ ...(turn.provenance ? { provenance: turn.provenance } : {}),
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Marker display untuk status verifikasi — keputusan policy.
195
+ *
196
+ * Renderer (transcript/simple) me-mirror pemetaan ini secara inline karena
197
+ * batas lapisan melarang src/ui mengimpor src/presentation; mirror tersebut
198
+ * dijaga test display agar tak divergen. Hanya verdict present eksplisit yang
199
+ * menjadi penanda sukses; absen field = UNKNOWN dan tidak dirender apa pun.
200
+ */
201
+ export function verificationMark(verification: ActivityDescription["verification"]): string {
202
+ if (!verification) return ""
203
+ if (verification.verdict === "present") return " [verified]"
204
+ return ` [unverified:${verification.verdict}]`
205
+ }
206
+
207
+ /**
208
+ * Marker display untuk provenans tampilan. Hanya nilai non-live yang
209
+ * dirender; absen = live-atau-tak-ditentukan.
210
+ */
211
+ export function provenanceMark(provenance: Provenance | undefined): string {
212
+ if (provenance === "reconstructed") return " [reconstructed]"
213
+ if (provenance === "replay") return " [replay]"
214
+ return ""
215
+ }
216
+
217
+ /** Ringkasan turn yang dibandingkan (hanya field yang dicocokkan). */
218
+ export interface TurnSummaryLike {
219
+ toolsOk: number
220
+ toolsFailed: number
221
+ toolsDenied: number
222
+ filesChanged: number
223
+ }
224
+
225
+ /** Cari turn pemilik sebuah summary (pengganti pencocokan lapangan di renderer). */
226
+ export function matchTurnBySummary<T extends TurnLike>(
227
+ turns: T[],
228
+ summary: TurnSummaryLike,
229
+ ): T | undefined {
230
+ return turns.find((candidate) => {
231
+ const value = candidate.summary
232
+ return (
233
+ value?.toolsOk === summary.toolsOk &&
234
+ value?.toolsFailed === summary.toolsFailed &&
235
+ value?.toolsDenied === summary.toolsDenied &&
236
+ value?.filesChanged === summary.filesChanged
237
+ )
238
+ })
239
+ }
240
+
241
+ export interface PinnedRunning<T> {
242
+ activity: T
243
+ /** Kebijakan ambang elapsed: tampilkan durasi bila berjalan >= 2 detik. */
244
+ showElapsed: boolean
245
+ }
246
+
247
+ export interface RunningLike {
248
+ toolCallId: string
249
+ status: ToolStatus
250
+ parentToolCallId?: string
251
+ tsStart: number
252
+ }
253
+
254
+ /** Satu activity berjalan yang dipin ke status bar (root didahulukan). */
255
+ export function pinnedRunningActivity<T extends RunningLike>(
256
+ activities: T[],
257
+ now: number,
258
+ ): PinnedRunning<T> | undefined {
259
+ const running = activities.filter((a) => a.status === "running")
260
+ const pinned = running.find((a) => !a.parentToolCallId) ?? running[0]
261
+ if (!pinned) return undefined
262
+ return { activity: pinned, showElapsed: elapsedVisible(pinned.tsStart, now) }
263
+ }
264
+
265
+ /** Ambang elapsed terpusat: durasi live tampil bila berjalan >= 2 detik. */
266
+ export function elapsedVisible(tsStart: number, now: number): boolean {
267
+ return now - tsStart >= 2000
268
+ }
269
+
270
+ export interface ActivitySuffixParts {
271
+ status: ToolStatus
272
+ durationMs?: number
273
+ denyReason?: string
274
+ receiptPaths: string[]
275
+ retry: boolean
276
+ }
277
+
278
+ /** Bagian suffix ledger yang dipilih policy (renderer hanya format). */
279
+ export function activitySuffixParts(desc: ActivityDescription): ActivitySuffixParts {
280
+ return {
281
+ status: desc.status,
282
+ ...(desc.durationMs !== undefined ? { durationMs: desc.durationMs } : {}),
283
+ ...(desc.denyReason ? { denyReason: desc.denyReason } : {}),
284
+ receiptPaths: [...desc.receiptPaths],
285
+ retry: desc.retryOf !== undefined,
286
+ }
287
+ }
288
+
289
+ // ── Seleksi node per mode ──
290
+
291
+ export type ProjectionNodeKind =
292
+ | "message"
293
+ | "turn"
294
+ | "tool"
295
+ | "approval"
296
+ | "reasoning"
297
+ | "system"
298
+ | "plan"
299
+ | "finding"
300
+ | "result"
301
+ | "diagnostic"
302
+
303
+ export interface ProjectionNode {
304
+ kind: ProjectionNodeKind
305
+ id: string
306
+ seq: number
307
+ data:
308
+ | ActivityEntry
309
+ | TurnEntry
310
+ | FindingEntry
311
+ | ResultEntry
312
+ | DiagnosticEntry
313
+ | SystemEntry
314
+ | PlanEntry
315
+ | { kind: "message"; text: string; role: "user" | "assistant" }
316
+ | ReasoningEntry
317
+ | { kind: "approval" }
318
+ }
319
+
320
+ function findActivity(state: PresentationState, id: string): ActivityEntry | undefined {
321
+ return [...state.activities.values()].find((a) => `${a.sessionId}:${a.toolCallId}` === id)
322
+ }
323
+
324
+ function findTurn(state: PresentationState, id: string): TurnEntry | undefined {
325
+ return state.turns.get(id)
326
+ }
327
+
328
+ /**
329
+ * Node semantik yang boleh tampil untuk satu mode. Normal menyembunyikan
330
+ * detail internal (reasoning penuh, approval mentah, progress); verbose
331
+ * membuka target/durasi/receipt/retry; debug membuka semua + identitas;
332
+ * machine mengembalikan urutan lifecycle durable.
333
+ */
334
+ export function selectNodes(state: PresentationState, mode: ProjectionMode): ProjectionNode[] {
335
+ const out: ProjectionNode[] = []
336
+ for (const ref of state.order) {
337
+ if (ref.kind === "tool") {
338
+ const activity = findActivity(state, ref.id)
339
+ if (!activity) continue
340
+ out.push({ kind: "tool", id: ref.id, seq: ref.seq, data: activity })
341
+ continue
342
+ }
343
+ if (ref.kind === "turn") {
344
+ const turn = findTurn(state, ref.id)
345
+ if (!turn) continue
346
+ out.push({ kind: "turn", id: ref.id, seq: ref.seq, data: turn })
347
+ continue
348
+ }
349
+ if (ref.kind === "message") {
350
+ if (mode === "machine") continue
351
+ const entry = state.conversation.find((m) => m.id === ref.id)
352
+ if (!entry) continue
353
+ out.push({
354
+ kind: "message",
355
+ id: ref.id,
356
+ seq: ref.seq,
357
+ data: { kind: "message", text: entry.text, role: entry.role },
358
+ })
359
+ continue
360
+ }
361
+ if (ref.kind === "reasoning") {
362
+ if (mode === "normal") continue
363
+ const entry = state.reasoning.find((r) => r.id === ref.id)
364
+ if (!entry) continue
365
+ out.push({ kind: "reasoning", id: ref.id, seq: ref.seq, data: entry })
366
+ continue
367
+ }
368
+ if (ref.kind === "system") {
369
+ const entry = state.system.find((s) => s.id === ref.id)
370
+ if (!entry) continue
371
+ if (mode === "normal" && entry.systemKind !== "checkpoint" && entry.systemKind !== "recovery")
372
+ continue
373
+ out.push({ kind: "system", id: ref.id, seq: ref.seq, data: entry })
374
+ continue
375
+ }
376
+ if (ref.kind === "plan") {
377
+ const entry = state.plans.get(ref.id)
378
+ if (!entry) continue
379
+ if (mode === "normal" && entry.status !== "open") continue
380
+ out.push({ kind: "plan", id: ref.id, seq: ref.seq, data: entry })
381
+ continue
382
+ }
383
+ if (ref.kind === "finding" || ref.kind === "result") {
384
+ const entry = ref.kind === "finding" ? state.findings.get(ref.id) : state.results.get(ref.id)
385
+ if (!entry) continue
386
+ out.push({ kind: ref.kind, id: ref.id, seq: ref.seq, data: entry })
387
+ continue
388
+ }
389
+ if (ref.kind === "diagnostic") {
390
+ const entry = state.diagnostics.find((d) => d.id === ref.id)
391
+ if (!entry) continue
392
+ if (mode === "normal" && entry.severity === "info") continue
393
+ out.push({ kind: "diagnostic", id: ref.id, seq: ref.seq, data: entry })
394
+ continue
395
+ }
396
+ if (ref.kind === "approval") {
397
+ if (mode === "normal" || mode === "machine") continue
398
+ out.push({ kind: "approval", id: ref.id, seq: ref.seq, data: { kind: "approval" } })
399
+ }
400
+ }
401
+ return out
402
+ }
403
+
404
+ // ── Observasi verifikasi (P2.11, murni, tanpa IO) ──
405
+
406
+ /** Bentuk record jurnal struktural — dipenuhi JournalRecord tanpa impor sesi. */
407
+ export interface VerificationJournalRecord {
408
+ kind?: string
409
+ state?: string
410
+ tool?: string
411
+ turn?: number | null
412
+ session?: string
413
+ invocationId?: string
414
+ argsHash?: string
415
+ verdict?: string
416
+ method?: string
417
+ observedAt?: number
418
+ }
419
+
420
+ export interface VerificationCallDescriptor {
421
+ toolCallId: string
422
+ tool: string
423
+ turn: number | null
424
+ argsHash: string
425
+ sessionId: string
426
+ }
427
+
428
+ export interface VerificationObservation {
429
+ toolCallId: string
430
+ invocationId: string
431
+ verdict: "present" | "absent" | "inconclusive"
432
+ method: string
433
+ observedAt: number
434
+ }
435
+
436
+ function isVerificationVerdict(value: unknown): value is VerificationObservation["verdict"] {
437
+ return value === "present" || value === "absent" || value === "inconclusive"
438
+ }
439
+
440
+ /**
441
+ * Selesaikan satu tool call yang selesai menjadi observasi verifikasi — atau
442
+ * null bila tak ada bukti eksplisit / atribusi ambigu.
443
+ *
444
+ * Aturan jujur: kandidat intent harus TEPAT SATU untuk (sesi, tool, turn,
445
+ * argsHash) dan HARUS punya baris verifikasi eksplisit. Nol, ganda, atau
446
+ * tanpa baris verifikasi → null (proyeksi menurunkan UNKNOWN, bukan success).
447
+ * Tidak pernah membaca teks model/tool, status Run, atau event presentasi.
448
+ */
449
+ export function pendingVerificationObservation(
450
+ call: VerificationCallDescriptor,
451
+ records: readonly VerificationJournalRecord[],
452
+ emitted: ReadonlySet<string>,
453
+ opts: { now?: number } = {},
454
+ ): VerificationObservation | null {
455
+ const candidates = records.filter(
456
+ (r) =>
457
+ (!r.kind || r.kind === "mutation") &&
458
+ r.session === call.sessionId &&
459
+ r.tool === call.tool &&
460
+ (r.turn ?? null) === (call.turn ?? null) &&
461
+ r.argsHash === call.argsHash &&
462
+ typeof r.invocationId === "string" &&
463
+ r.invocationId !== "" &&
464
+ !emitted.has(r.invocationId),
465
+ )
466
+ if (candidates.length !== 1) return null
467
+ const invocationId = candidates[0]!.invocationId!
468
+ const verifications = records.filter(
469
+ (r) => r.kind === "verification" && r.invocationId === invocationId,
470
+ )
471
+ if (verifications.length === 0) return null
472
+ const latest = verifications[verifications.length - 1]!
473
+ if (!isVerificationVerdict(latest.verdict)) return null
474
+ const observedAt =
475
+ typeof latest.observedAt === "number" && Number.isFinite(latest.observedAt)
476
+ ? latest.observedAt
477
+ : (opts.now ?? 0)
478
+ return {
479
+ toolCallId: call.toolCallId,
480
+ invocationId,
481
+ verdict: latest.verdict,
482
+ method: typeof latest.method === "string" && latest.method ? latest.method : "unknown",
483
+ observedAt,
484
+ }
485
+ }
486
+
487
+ /** Digest deterministik untuk harness divergensi (FNV-1a 32-bit, hex). */
488
+ export function projectionDigest(nodes: ProjectionNode[]): string {
489
+ let hash = 0x811c9dc5
490
+ const text = JSON.stringify(nodes.map((n) => [n.kind, n.id, n.seq]))
491
+ for (let i = 0; i < text.length; i++) {
492
+ hash ^= text.charCodeAt(i)
493
+ hash = Math.imul(hash, 0x01000193)
494
+ }
495
+ return (hash >>> 0).toString(16).padStart(8, "0")
496
+ }
497
+
498
+ // ── Machine envelope (exec JSONL; ACP memakai framing JSON-RPC + mapping sama) ──
499
+
500
+ export const MACHINE_SCHEMA = "minicode.output.v1"
501
+
502
+ export type MachineSeverity = "info" | "warning" | "error" | "critical"
503
+ export type MachineStatus =
504
+ | "started"
505
+ | "active"
506
+ | "completed"
507
+ | "failed"
508
+ | "denied"
509
+ | "cancelled"
510
+ | "interrupted"
511
+ | "partial"
512
+ | "recovered"
513
+
514
+ /**
515
+ * Input struktural untuk envelope machine. Field opsional disengaja longgar
516
+ * agar kompatibel dengan UiPresentationEvent tanpa impor src/ui (batas
517
+ * lapisan); pembacaan selalu defensif via guard asString/asNumber/asRecord.
518
+ */
519
+ export interface MachineEventInput {
520
+ type: string
521
+ seq?: number
522
+ turnId?: number
523
+ stepId?: number
524
+ toolCallId?: string
525
+ approvalId?: string
526
+ name?: string
527
+ qualified?: string
528
+ target?: string
529
+ status?: string
530
+ tsStart?: number
531
+ durationMs?: number
532
+ message?: unknown
533
+ cause?: unknown
534
+ reason?: unknown
535
+ error?: unknown
536
+ outcome?: unknown
537
+ via?: string
538
+ summary?: unknown
539
+ promptRef?: string
540
+ delta?: unknown
541
+ text?: unknown
542
+ truncated?: boolean
543
+ toolSummary?: unknown
544
+ hint?: unknown
545
+ expandRef?: unknown
546
+ receipt?: unknown
547
+ parentToolCallId?: string
548
+ paths?: unknown
549
+ journalSeq?: number
550
+ checkpointId?: string
551
+ test?: unknown
552
+ compactionReason?: string
553
+ planId?: string
554
+ findingId?: string
555
+ resultId?: string
556
+ category?: unknown
557
+ severity?: unknown
558
+ action?: unknown
559
+ steps?: unknown
560
+ evidence?: unknown
561
+ /** Provenans tampilan; hanya nilai valid yang diteruskan ke envelope. */
562
+ provenance?: unknown
563
+ /** Observasi verifikasi (tanpa evidenceReference — tetap di jurnal). */
564
+ verification?: unknown
565
+ }
566
+
567
+ const VALID_PROVENANCE: readonly string[] = ["live", "replay", "reconstructed", "unknown"]
568
+
569
+ function asProvenance(value: unknown): Provenance | undefined {
570
+ return typeof value === "string" && (VALID_PROVENANCE as readonly string[]).includes(value)
571
+ ? (value as Provenance)
572
+ : undefined
573
+ }
574
+
575
+ export interface MachineEnvelope {
576
+ schema: typeof MACHINE_SCHEMA
577
+ eventId: string
578
+ type: string
579
+ timestamp: string
580
+ sessionId: string
581
+ turnId?: number
582
+ correlationId?: string
583
+ source: "derived"
584
+ severity: MachineSeverity
585
+ status: MachineStatus
586
+ visibility: ["machine"]
587
+ /** Provenans tampilan; absen = live-atau-tak-ditentukan. */
588
+ provenance?: Provenance
589
+ payload: Record<string, unknown>
590
+ }
591
+
592
+ export interface MachineEnvelope {
593
+ schema: typeof MACHINE_SCHEMA
594
+ eventId: string
595
+ type: string
596
+ timestamp: string
597
+ sessionId: string
598
+ turnId?: number
599
+ correlationId?: string
600
+ source: "derived"
601
+ severity: MachineSeverity
602
+ status: MachineStatus
603
+ visibility: ["machine"]
604
+ payload: Record<string, unknown>
605
+ }
606
+
607
+ export interface MachineContext {
608
+ sessionId: string
609
+ /** Jam tepi (ms epoch); wajib di-inject agar deterministik di test. */
610
+ timestamp: number
611
+ }
612
+
613
+ const VALID_SEVERITIES: readonly string[] = ["info", "warning", "error", "critical"]
614
+
615
+ function asRecord(value: unknown): Record<string, unknown> | undefined {
616
+ return typeof value === "object" && value !== null
617
+ ? (value as Record<string, unknown>)
618
+ : undefined
619
+ }
620
+
621
+ function asString(value: unknown): string | undefined {
622
+ return typeof value === "string" && value.length > 0 ? value : undefined
623
+ }
624
+
625
+ function asNumber(value: unknown): number | undefined {
626
+ return typeof value === "number" && Number.isFinite(value) ? value : undefined
627
+ }
628
+
629
+ function capText(value: unknown, max: number): { text: string; truncated: boolean } | undefined {
630
+ if (typeof value !== "string" || value.length === 0) return undefined
631
+ if (value.length <= max) return { text: value, truncated: false }
632
+ return { text: value.slice(0, max), truncated: true }
633
+ }
634
+
635
+ function eventSuffix(type: string): string {
636
+ const i = type.lastIndexOf(".")
637
+ return i >= 0 ? type.slice(i + 1) : type
638
+ }
639
+
640
+ export function machineEventId(
641
+ sessionId: string,
642
+ turnId: number | undefined,
643
+ seq: number | undefined,
644
+ ): string {
645
+ return `${sessionId}:${turnId ?? 0}:${seq ?? 0}`
646
+ }
647
+
648
+ export function machineTimestamp(timestamp: number): string {
649
+ return new Date(Number.isFinite(timestamp) ? timestamp : 0).toISOString()
650
+ }
651
+
652
+ export function machineSeverity(event: MachineEventInput): MachineSeverity {
653
+ const explicit = asString(event.severity)
654
+ if (explicit && (VALID_SEVERITIES as readonly string[]).includes(explicit))
655
+ return explicit as MachineSeverity
656
+ const suffix = eventSuffix(event.type)
657
+ if (suffix === "failed" || suffix === "interrupted" || event.error !== undefined) return "error"
658
+ if (suffix === "denied" || suffix === "cancelled") return "warning"
659
+ return "info"
660
+ }
661
+
662
+ export function machineStatus(event: MachineEventInput): MachineStatus {
663
+ if (event.type === "approval.settled") {
664
+ const decision = asRecord(event.outcome)?.decision
665
+ if (decision === "deny") return "denied"
666
+ if (decision === "cancelled") return "cancelled"
667
+ return "completed"
668
+ }
669
+ if (event.type === "plan.updated") {
670
+ const status = asString(event.status)
671
+ return status === "open" ? "active" : ((status as MachineStatus | undefined) ?? "active")
672
+ }
673
+ if (event.type === "result.produced") {
674
+ const status = asString(event.status)
675
+ if (status === "failed" || status === "cancelled") return status
676
+ return "completed"
677
+ }
678
+ if (event.type === "finding.detected") return "completed"
679
+ if (event.type === "diagnostic.raised") return "active"
680
+ const suffix = eventSuffix(event.type)
681
+ if (
682
+ suffix === "started" ||
683
+ suffix === "completed" ||
684
+ suffix === "failed" ||
685
+ suffix === "denied" ||
686
+ suffix === "cancelled" ||
687
+ suffix === "interrupted" ||
688
+ suffix === "partial" ||
689
+ suffix === "recovered"
690
+ )
691
+ return suffix
692
+ if (suffix === "progress" || suffix === "delta") return "active"
693
+ return "active"
694
+ }
695
+
696
+ export function correlationId(event: MachineEventInput): string | undefined {
697
+ return (
698
+ asString(event.toolCallId) ??
699
+ asString(event.approvalId) ??
700
+ asString(event.planId) ??
701
+ asString(event.findingId) ??
702
+ asString(event.resultId) ??
703
+ asString(event.checkpointId) ??
704
+ asString(event.promptRef)
705
+ )
706
+ }
707
+
708
+ const PAYLOAD_TEXT_MAX = LIMITS.MCP_OUTPUT_MAX_CHARS
709
+
710
+ function cappedPayloadText(value: unknown): Record<string, unknown> | undefined {
711
+ const capped = capText(value, PAYLOAD_TEXT_MAX)
712
+ if (!capped) return undefined
713
+ return { text: capped.text, ...(capped.truncated ? { truncated: true } : {}) }
714
+ }
715
+
716
+ /** Payload machine: whitelist per tipe, tanpa ID internal mentah yang berlebih. */
717
+ export function machinePayload(event: MachineEventInput): Record<string, unknown> {
718
+ const payload: Record<string, unknown> = {}
719
+ const put = (key: string, value: unknown): void => {
720
+ if (value !== undefined) payload[key] = value
721
+ }
722
+ put("stepId", asNumber(event.stepId))
723
+ put("toolCallId", asString(event.toolCallId))
724
+ put("approvalId", asString(event.approvalId))
725
+ put("name", asString(event.name))
726
+ put("qualified", asString(event.qualified))
727
+ put("target", asString(event.target))
728
+ put("status", asString(event.status))
729
+ put("cause", asString(event.cause))
730
+ put("reason", asString(event.reason))
731
+ put("hint", asString(event.hint))
732
+ put("via", asString(event.via))
733
+ put("promptRef", asString(event.promptRef))
734
+ put("delta", asString(event.delta))
735
+ put("truncated", typeof event.truncated === "boolean" ? event.truncated : undefined)
736
+ put("toolSummary", asString(event.toolSummary))
737
+ put("durationMs", asNumber(event.durationMs))
738
+ put("tsStart", asNumber(event.tsStart))
739
+ put(
740
+ "paths",
741
+ Array.isArray(event.paths)
742
+ ? event.paths.filter((p) => typeof p === "string").slice(0, 100)
743
+ : undefined,
744
+ )
745
+ put("journalSeq", asNumber(event.journalSeq))
746
+ put("checkpointId", asString(event.checkpointId))
747
+ put("planId", asString(event.planId))
748
+ put("findingId", asString(event.findingId))
749
+ put("resultId", asString(event.resultId))
750
+ put("category", asString(event.category))
751
+ put("severity", asString(event.severity))
752
+ put("action", asString(event.action))
753
+ put("compactionReason", asString(event.compactionReason))
754
+ const outcome = asRecord(event.outcome)
755
+ if (outcome) payload.outcome = outcome
756
+ const summary = asRecord(event.summary)
757
+ if (summary) payload.summary = summary
758
+ const test = asRecord(event.test)
759
+ if (test) payload.test = test
760
+ const receipt = asRecord(event.receipt)
761
+ if (receipt) payload.receipt = receipt
762
+ const expandRef = asRecord(event.expandRef)
763
+ if (expandRef) payload.expandRef = expandRef
764
+ if (Array.isArray(event.steps)) payload.steps = event.steps.slice(0, 100)
765
+ if (Array.isArray(event.evidence))
766
+ payload.evidence = event.evidence.filter((e) => typeof e === "string").slice(0, 20)
767
+ if (event.parentToolCallId !== undefined) payload.parentToolCallId = event.parentToolCallId
768
+ const verification = asRecord(event.verification)
769
+ if (verification) payload.verification = verification
770
+ const provenance = asProvenance(event.provenance)
771
+ if (provenance) payload.provenance = provenance
772
+ const message = cappedPayloadText(event.message)
773
+ if (message) payload.message = message.text
774
+ const error = cappedPayloadText(event.error)
775
+ if (error) payload.error = error.text
776
+ const text = cappedPayloadText(event.text)
777
+ if (text) {
778
+ payload.text = text.text
779
+ if (text.truncated || event.truncated === true) payload.truncated = true
780
+ }
781
+ return payload
782
+ }
783
+
784
+ export function toMachineEnvelope(
785
+ event: MachineEventInput,
786
+ ctx: MachineContext,
787
+ ): MachineEnvelope | null {
788
+ if (!event || typeof event.type !== "string" || event.type.length === 0) return null
789
+ const turnId = asNumber(event.turnId)
790
+ const seq = asNumber(event.seq)
791
+ const provenance = asProvenance(event.provenance)
792
+ const envelope: MachineEnvelope = {
793
+ schema: MACHINE_SCHEMA,
794
+ eventId: machineEventId(ctx.sessionId, turnId, seq),
795
+ type: event.type,
796
+ timestamp: machineTimestamp(ctx.timestamp),
797
+ sessionId: ctx.sessionId,
798
+ ...(turnId !== undefined ? { turnId } : {}),
799
+ source: "derived",
800
+ severity: machineSeverity(event),
801
+ status: machineStatus(event),
802
+ visibility: ["machine"],
803
+ ...(provenance ? { provenance } : {}),
804
+ payload: machinePayload(event),
805
+ }
806
+ const correlation = correlationId(event)
807
+ if (correlation) envelope.correlationId = correlation
808
+ return envelope
809
+ }
810
+
811
+ export interface MachineError {
812
+ category:
813
+ | "USER_ERROR"
814
+ | "CONFIGURATION_ERROR"
815
+ | "PERMISSION_ERROR"
816
+ | "TOOL_ERROR"
817
+ | "FILESYSTEM_ERROR"
818
+ | "NETWORK_ERROR"
819
+ | "PROVIDER_ERROR"
820
+ | "MODEL_ERROR"
821
+ | "AGENT_ERROR"
822
+ | "INTERNAL_ERROR"
823
+ message: string
824
+ action?: string
825
+ }
826
+
827
+ function firstLine(value: unknown, max: number): string {
828
+ const text = typeof value === "string" ? value : String(value ?? "")
829
+ const line = text.split("\n")[0] ?? ""
830
+ const clean = line.trim()
831
+ return clean.length > max ? `${clean.slice(0, max)}…` : clean || "unknown error"
832
+ }
833
+
834
+ /** Kategori error machine dari bentuk error struktural (tanpa impor vendor). */
835
+ export function machineError(e: unknown): MachineError {
836
+ const obj = asRecord(e) ?? {}
837
+ const kind = asString(obj.kind)
838
+ const category = asString(obj.category)
839
+ const name = asString(obj.name)
840
+ const message = firstLine(
841
+ asString(obj.message) ?? (e instanceof Error ? e.message : undefined) ?? e,
842
+ 500,
843
+ )
844
+ if (name === "NoProviderError" || /no provider configured/i.test(message))
845
+ return { category: "CONFIGURATION_ERROR", message, action: "configure a provider" }
846
+ if (kind === "budget_exceeded" || /over budget|unknown cost/i.test(message))
847
+ return { category: "USER_ERROR", message, action: "raise --budget or reduce usage" }
848
+ if (kind === "timeout" || (/timeout|timed out/i.test(message) && kind !== "aborted"))
849
+ return { category: "AGENT_ERROR", message, action: "retry with a higher --timeout" }
850
+ if (kind === "max_steps_exceeded" || /max.?steps/i.test(message))
851
+ return { category: "AGENT_ERROR", message, action: "raise --max-steps" }
852
+ if (kind === "aborted" || /^(run cancelled|turn aborted|aborted)/i.test(message))
853
+ return { category: "USER_ERROR", message }
854
+ if (/refusing|denied|not allowed|not permitted/i.test(message))
855
+ return { category: "PERMISSION_ERROR", message }
856
+ if (kind === "provider" || category !== undefined) return { category: "PROVIDER_ERROR", message }
857
+ return { category: "AGENT_ERROR", message }
858
+ }