minicode-ai 0.11.1 → 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 +89 -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 -71
  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 +2 -2
  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 +52 -19
  184. package/src/ui/i18n/en.ts +58 -6
  185. package/src/ui/i18n/id.ts +58 -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 +507 -169
  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 -169
  221. package/docs/USAGE.md +0 -11
@@ -12,7 +12,9 @@
12
12
  // sama dengan isolasi per-handler di events kernel). Dual-subscribe dengan
13
13
  // sink lama — perilaku user NOL berubah pada Fase 1.
14
14
 
15
+ import { type CanonicalAssignmentTable, decodeCanonicalAssignments } from "../task/assignment.ts"
15
16
  import { classifyToolResult, denyReasonOf, summarizeArgs } from "../telemetry/trace.ts"
17
+ import { normalizeTodos } from "../tools/todo.ts"
16
18
  import type {
17
19
  ApprovalEventHook,
18
20
  ApprovalHookEvent,
@@ -24,10 +26,13 @@ import type {
24
26
  DomainEvent,
25
27
  EventBusLike,
26
28
  FailCause,
29
+ PlanStep,
30
+ SemanticSeverity,
27
31
  ToolIdentity,
28
32
  TurnSummary,
33
+ VerificationDisplayVerdict,
29
34
  } from "./events.ts"
30
- import type { ContentStore } from "./store.ts"
35
+ import { type ContentStore, MAX_SECTION_CHARS } from "./store.ts"
31
36
 
32
37
  export interface AdapterDiagnostics {
33
38
  eventsIn: number
@@ -40,6 +45,7 @@ export interface AdapterDiagnostics {
40
45
  errors: number
41
46
  /** Forward anak tanpa pasangan delegate_task yang bisa ditebak (Fase 2). */
42
47
  orphanChild: number
48
+ userMessages: number
43
49
  /** Bentuk execution rusak — event dilewati, bukan crash (Fase 2). */
44
50
  malformedExecution: number
45
51
  }
@@ -51,22 +57,75 @@ export interface RunSettleInfo {
51
57
  parentAborted: boolean
52
58
  }
53
59
 
60
+ export type TurnSummaryProvider = (input: {
61
+ sessionId: string
62
+ turnId: number
63
+ fallback: TurnSummary
64
+ }) => TurnSummary
65
+
66
+ /**
67
+ * PHASE 3B: resolves canonical task identity for a declared plan.
68
+ *
69
+ * Returns one canonical task id (`t<n>`) per declared step, positionally
70
+ * aligned, or `null` where no canonical identity exists yet. The implementation
71
+ * is expected to read the authoritative TaskStore; the adapter must never
72
+ * resolve or allocate identity itself.
73
+ */
74
+ export type TaskIdentityProvider = (input: {
75
+ sessionId: string
76
+ declared: readonly PlanStep[]
77
+ }) => readonly (string | null)[] | undefined
78
+
54
79
  export interface PresentationAdapter {
55
80
  onEvent(handler: (e: DomainEvent) => void): () => void
56
81
  /** Dipanggil permission/ask_user via hook DI (bukan event bus). */
57
82
  publishApproval(e: ApprovalHookEvent): void
83
+ noteUserMessage(info: { text: string; promptRef?: string; turnId?: number }): void
58
84
  /** Dipanggil driver (runOnce) saat session.run reject — kernel diam di sini. */
59
85
  noteRunSettled(error: unknown, info: RunSettleInfo): void
60
- /**
61
- * Fase 4: jurnal committed → file.changed (receipt paths+seq). Dipanggil
62
- * composition root via hook journal — kernel tidak meng-emit event ini.
63
- */
64
86
  noteFileChanged(info: {
65
87
  toolCallId: string
66
88
  paths: string[]
67
89
  journalSeq?: number
68
90
  checkpointId?: string
91
+ sessionId?: string
92
+ turnId?: number
93
+ }): void
94
+ noteTestCompleted(info: {
95
+ toolCallId: string
96
+ passed: number
97
+ failed: number
98
+ summary: string
99
+ sessionId?: string
100
+ turnId?: number
69
101
  }): void
102
+ noteCheckpoint(info: { checkpointId: string; paths?: string[]; turnId?: number }): void
103
+ /**
104
+ * Terbitkan `plan.updated` dari daftar yang SUDAH dinormalisasi di domain
105
+ * task (hasil rekonsiliasi pasca-verify), bukan dari argumen mentah.
106
+ *
107
+ * Dipakai jalur yang tidak melalui `todo_write` — reconcile setelah verify
108
+ * selesai. Tanpa ini, file di disk sudah `blocked` sementara durable event
109
+ * log masih berbunyi `completed`: dua bentuk kebenaran untuk satu state.
110
+ */
111
+ notePlanReconciled(info: { todos: readonly unknown[]; sessionId?: string; turnId?: number }): void
112
+ /**
113
+ * Terbitkan observasi verifikasi yang SUDAH durable di jurnal mutasi
114
+ * (intent/terminal/VerificationRecord). Pemanggil (composition root)
115
+ * membaca bukti dari jurnal; adaptor hanya memproyeksikan ke event
116
+ * observasi. Tidak pernah mengubah status/history/lifecycle.
117
+ */
118
+ noteVerificationObserved(info: {
119
+ toolCallId: string
120
+ invocationId: string
121
+ verdict: VerificationDisplayVerdict
122
+ method: string
123
+ observedAt: number
124
+ sessionId?: string
125
+ turnId?: number
126
+ parentLink?: ChildSessionLink
127
+ }): void
128
+ setTurnSummaryProvider(provider: TurnSummaryProvider | undefined): void
70
129
  getDiagnostics(): AdapterDiagnostics
71
130
  dispose(): void
72
131
  }
@@ -155,16 +214,94 @@ export function assertExecutionShape(e: unknown): e is {
155
214
  return typeof id === "string" && id.length > 0 && typeof name === "string" && name.length > 0
156
215
  }
157
216
 
217
+ export interface SubmittedFinding {
218
+ findingId: string
219
+ category: string
220
+ severity: SemanticSeverity
221
+ summary: string
222
+ evidence: string[]
223
+ }
224
+
225
+ // Temuan hanya boleh lahir dari struktur eksplisit `submit_result`, bukan dari
226
+ // menebak teks bebas. Bentuk tak valid dilewati agar kontrak ketat.
227
+ const findingSeverities: readonly SemanticSeverity[] = ["info", "warning", "error", "critical"]
228
+ function cleanFindingText(value: unknown, max: number): string | undefined {
229
+ if (typeof value !== "string") return undefined
230
+ const text = value.trim().replace(/\s+/g, " ")
231
+ if (!text) return undefined
232
+ return text.length > max ? `${text.slice(0, max)}…` : text
233
+ }
234
+ function cleanFindingEvidence(value: unknown): string[] {
235
+ const items = Array.isArray(value) ? value : typeof value === "string" ? [value] : []
236
+ const out: string[] = []
237
+ for (const item of items.slice(0, 10)) {
238
+ const text = cleanFindingText(item, 200)
239
+ if (text) out.push(text)
240
+ }
241
+ return out
242
+ }
243
+ export function findingsFromSubmitResult(args: unknown, callId: string): SubmittedFinding[] {
244
+ if (typeof args !== "object" || args === null || !callId) return []
245
+ const result = (args as { result?: unknown }).result
246
+ if (typeof result !== "object" || result === null) return []
247
+ const raw = (result as { findings?: unknown }).findings
248
+ if (!Array.isArray(raw)) return []
249
+ const findings: SubmittedFinding[] = []
250
+ for (const [index, item] of raw.slice(0, 5).entries()) {
251
+ if (typeof item !== "object" || item === null) continue
252
+ const value = item as {
253
+ category?: unknown
254
+ severity?: unknown
255
+ summary?: unknown
256
+ evidence?: unknown
257
+ }
258
+ const category = cleanFindingText(value.category, 80)
259
+ const summary = cleanFindingText(value.summary, 500)
260
+ if (!category || !summary) continue
261
+ if (!findingSeverities.includes(value.severity as SemanticSeverity)) continue
262
+ findings.push({
263
+ findingId: `finding:${callId}:${index + 1}`,
264
+ category,
265
+ severity: value.severity as SemanticSeverity,
266
+ summary,
267
+ evidence: cleanFindingEvidence(value.evidence),
268
+ })
269
+ }
270
+ return findings
271
+ }
272
+
158
273
  export function createPresentationAdapter(
159
274
  source: EventBusLike,
160
- opts: { sessionId: string; contentStore?: ContentStore },
275
+ opts: {
276
+ sessionId: string
277
+ contentStore?: ContentStore
278
+ /**
279
+ * PHASE 3B: the single seam through which canonical task identity reaches
280
+ * the plan. Given the owning session and the declared steps, return one
281
+ * canonical task id per declared step, positionally aligned, or `null` for
282
+ * one that has no canonical identity yet. Returning `undefined`, throwing,
283
+ * or returning a mismatched length all mean "no canonical identity", and
284
+ * the plan falls back to the positional legacy shape.
285
+ *
286
+ * The adapter deliberately does NOT implement this. Resolution belongs to
287
+ * TaskStore, which is the sole allocator of task identity.
288
+ */
289
+ taskIdentityProvider?: TaskIdentityProvider
290
+ initialSeq?: number
291
+ initialTurn?: number
292
+ initialTurnStartTs?: number
293
+ },
161
294
  ): PresentationAdapter {
162
295
  const sessionId = opts.sessionId
163
296
  const contentStore = opts.contentStore
164
- let seq = 0
165
- let currentTurn = 0
166
- let turnStartTs = 0
297
+ const taskIdentityProvider = opts.taskIdentityProvider
298
+ let seq = opts.initialSeq ?? 0
299
+ let currentTurn = opts.initialTurn ?? 0
300
+ let turnStartTs = opts.initialTurnStartTs ?? 0
301
+ let turnSummaryProvider: TurnSummaryProvider | undefined
167
302
  let currentStep = 0
303
+ let reasoningText = ""
304
+ let reasoningTruncated = false
168
305
  const toolStarts = new Map<string, number>()
169
306
  const openTools = new Map<
170
307
  string,
@@ -188,6 +325,7 @@ export function createPresentationAdapter(
188
325
  anomalies: 0,
189
326
  errors: 0,
190
327
  orphanChild: 0,
328
+ userMessages: 0,
191
329
  malformedExecution: 0,
192
330
  }
193
331
 
@@ -201,15 +339,194 @@ export function createPresentationAdapter(
201
339
  }
202
340
  }
203
341
  }
204
- const base = (turnId: number) => ({ eventSeq: ++seq, ts: Date.now(), sessionId, turnId })
342
+ const base = (turnId: number, rootExecutionId?: string) => ({
343
+ eventSeq: ++seq,
344
+ ts: Date.now(),
345
+ sessionId,
346
+ turnId,
347
+ executionId: `exec_${Date.now()}:${rootExecutionId || ""}:${Math.random().toString(36).slice(2, 8)}`,
348
+ ...(rootExecutionId ? { rootExecutionId } : {}),
349
+ })
205
350
  /** Forward anak: sessionId DomainEvent = anak; parentLink bila sudah dipasangkan. */
206
- const childBase = (turnId: number, childId: string, parentLink?: ChildSessionLink) => ({
351
+ const childBase = (
352
+ turnId: number,
353
+ childId: string,
354
+ parentLink?: ChildSessionLink,
355
+ rootExecutionId?: string,
356
+ ) => ({
207
357
  eventSeq: ++seq,
208
358
  ts: Date.now(),
209
359
  sessionId: childId,
210
360
  turnId,
211
361
  ...(parentLink ? { parentLink } : {}),
362
+ ...(rootExecutionId ? { rootExecutionId } : {}),
363
+ parentExecutionId: `exec_${Date.now()}:${rootExecutionId || ""}:${Math.random().toString(36).slice(2, 8)}`, // PSEUDO-UPPER: actual parent will be set by caller
212
364
  })
365
+ const reasoningRef = (): { toolCallId: string; idx: number; kind: "reasoning" } => ({
366
+ toolCallId: `reasoning:${sessionId}:${currentTurn}`,
367
+ idx: 0,
368
+ kind: "reasoning",
369
+ })
370
+ const finishReasoning = (): void => {
371
+ if (!reasoningText) return
372
+ const ref = reasoningRef()
373
+ if (contentStore) {
374
+ try {
375
+ contentStore.put(ref, reasoningText, {
376
+ kind: "reasoning",
377
+ stream: "stderr",
378
+ truncated: reasoningTruncated,
379
+ })
380
+ } catch {
381
+ diag.errors++
382
+ }
383
+ }
384
+ publish({
385
+ ...base(currentTurn),
386
+ type: "reasoning.completed",
387
+ turnId: currentTurn,
388
+ truncated: reasoningTruncated,
389
+ expandRef: ref,
390
+ })
391
+ reasoningText = ""
392
+ reasoningTruncated = false
393
+ }
394
+ // Pemetaan task domain → plan presentational. Sengaja memakai
395
+ // `normalizeTodos` (pemilik semantik domain) alih-alih memetakan status
396
+ // sendiri: dua normalizer independen pasti bisa berbeda pendapat (mis. 2 item
397
+ // `in_progress` → file menyimpan satu `in_progress`, adaptor lama poked dua
398
+ // `active`), dan yang tampil ke manusia/mesin adalah adaptor.
399
+ //
400
+ // `normalizeTodos` juga menerapkan kebijakan completion, jadi plan mencerminkan
401
+ // keputusan blocked yang sama dengan file.
402
+ // PHASE 3B - two identities, one authority.
403
+ //
404
+ // `stepId` below is a POSITIONAL label and is not identity. Canonical identity
405
+ // is `taskId`, and it is NEVER computed here: the adapter must not allocate or
406
+ // resolve task identity, so it cannot even express a `t<n>`. Identity arrives
407
+ // only through the injected `taskIdentityProvider`, the single seam through
408
+ // which TaskStore authority reaches the plan.
409
+ //
410
+ // With no provider injected - the production case today, see the boundary note
411
+ // in PHASE-3B-PLAN-PIPELINE-RECOVERY-REPORT.md - behaviour is identical to
412
+ // before this change: positional `stepId`, no `payloadVersion`. Presentation
413
+ // stays an observation, never an authority.
414
+ const planFromTodos = (
415
+ args: unknown,
416
+ ownerSessionId: string,
417
+ /**
418
+ * PHASE 4A.4A - the canonical assignment produced by the SAME todo_write
419
+ * operation, already decoded off that call's own result. Optional: absent
420
+ * whenever the operation produced no assignment (legacy all-id-less payload,
421
+ * truncated result, foreign session), and every one of those cases must fall
422
+ * back to the legacy positional shape rather than claim `v2`.
423
+ */
424
+ assignment?: CanonicalAssignmentTable,
425
+ ):
426
+ | {
427
+ steps: PlanStep[]
428
+ status: "open" | "completed" | "cancelled"
429
+ /** True only when EVERY step resolved to a canonical taskId. */
430
+ canonical: boolean
431
+ }
432
+ | undefined => {
433
+ if (typeof args !== "object" || args === null) return undefined
434
+ const raw = (args as { todos?: unknown }).todos
435
+ if (!Array.isArray(raw) || raw.length === 0) return undefined
436
+ let list: ReturnType<typeof normalizeTodos>
437
+ try {
438
+ list = normalizeTodos(raw)
439
+ } catch {
440
+ return undefined
441
+ }
442
+ if (list.length === 0) return undefined
443
+ const steps: PlanStep[] = list.map((t, i) => ({
444
+ stepId: String(i + 1),
445
+ // PHASE 4A.4 - the declared id is passed to the resolver as a HINT only. It
446
+ // is kept on the step solely when TaskStore confirms that row exists for
447
+ // this session; otherwise it is stripped below, so an unverified id can
448
+ // never appear on a published plan.
449
+ ...(t.taskId ? { taskId: t.taskId } : {}),
450
+ title: t.content,
451
+ status:
452
+ t.status === "completed" || t.status === "cancelled" || t.status === "blocked"
453
+ ? t.status
454
+ : t.status === "in_progress"
455
+ ? "active"
456
+ : "pending",
457
+ }))
458
+ const status = steps.every((step) => step.status === "completed")
459
+ ? "completed"
460
+ : steps.every((step) => step.status === "cancelled")
461
+ ? "cancelled"
462
+ : "open"
463
+
464
+ // Resolve identity through the seam only. A provider that throws, returns
465
+ // the wrong length, or leaves any entry unresolved yields the legacy
466
+ // positional plan. A partially-identified v2 event is never emitted: that
467
+ // would falsely claim the event is taskId-based.
468
+ //
469
+ // PHASE 4A.4A - an assignment from THIS operation is the strongest identity
470
+ // evidence available: it is the committed result of the transaction that
471
+ // created the row, not a later lookup and not a re-query. It is accepted only
472
+ // when it is exactly as long as the declaration AND never contradicts an id
473
+ // the model actually declared. A mismatch means the assignment is stale or
474
+ // belongs to another operation, and is rejected outright.
475
+ //
476
+ // Every rejection falls through to the provider path, which itself refuses
477
+ // partial resolution - so no failure mode in this block can yield `v2`.
478
+ let canonical = false
479
+ const table = assignment
480
+ let assigned = false
481
+ if (table && table.length > 0 && table.length === steps.length) {
482
+ const declaredIds = list.map((t) => t.taskId)
483
+ let consistent = true
484
+ for (let i = 0; i < table.length; i++) {
485
+ const claimed = declaredIds[i]
486
+ const a = table[i]
487
+ if (!a || (claimed !== undefined && claimed !== a.taskId)) {
488
+ consistent = false
489
+ break
490
+ }
491
+ }
492
+ if (consistent) {
493
+ steps.forEach((step, i) => {
494
+ const a = table[i]
495
+ if (!a) return
496
+ step.taskId = a.taskId
497
+ step.ordinal = i
498
+ })
499
+ canonical = true
500
+ assigned = true
501
+ }
502
+ }
503
+ if (!assigned && taskIdentityProvider) {
504
+ let resolved: readonly (string | null)[] | undefined
505
+ try {
506
+ resolved = taskIdentityProvider({ sessionId: ownerSessionId, declared: steps })
507
+ } catch {
508
+ resolved = undefined
509
+ }
510
+ if (resolved && resolved.length === steps.length) {
511
+ const ids = resolved.map((id) => (typeof id === "string" && id.length > 0 ? id : null))
512
+ if (ids.every((id) => id !== null)) {
513
+ steps.forEach((step, i) => {
514
+ step.taskId = ids[i] as string
515
+ step.ordinal = i
516
+ })
517
+ canonical = true
518
+ } else {
519
+ // Not fully resolved: drop every unconfirmed hint so this plan stays
520
+ // purely positional rather than advertising identity nobody verified.
521
+ for (const step of steps) delete step.taskId
522
+ }
523
+ } else {
524
+ for (const step of steps) delete step.taskId
525
+ }
526
+ }
527
+
528
+ return { steps, status, canonical }
529
+ }
213
530
 
214
531
  const markTerminal = (id: string): boolean => {
215
532
  if (terminalTools.has(id)) {
@@ -291,15 +608,18 @@ export function createPresentationAdapter(
291
608
  }
292
609
  }
293
610
 
294
- const turnSummary = (): TurnSummary => ({
295
- toolsOk: counts.ok,
296
- toolsFailed: counts.failed,
297
- toolsDenied: counts.denied,
298
- toolsCancelled: counts.cancelled,
299
- toolsInterrupted: 0,
300
- filesChanged: 0,
301
- durationMs: Math.max(0, Date.now() - turnStartTs),
302
- })
611
+ const turnSummary = (): TurnSummary => {
612
+ const fallback: TurnSummary = {
613
+ toolsOk: counts.ok,
614
+ toolsFailed: counts.failed,
615
+ toolsDenied: counts.denied,
616
+ toolsCancelled: counts.cancelled,
617
+ toolsInterrupted: 0,
618
+ filesChanged: 0,
619
+ durationMs: Math.max(0, Date.now() - turnStartTs),
620
+ }
621
+ return turnSummaryProvider?.({ sessionId, turnId: currentTurn, fallback }) ?? fallback
622
+ }
303
623
 
304
624
  const resetTurnCounters = (): void => {
305
625
  counts.ok = 0
@@ -335,14 +655,22 @@ export function createPresentationAdapter(
335
655
  }
336
656
  currentTurn = typeof e?.turn === "number" ? e.turn : currentTurn + 1
337
657
  currentStep = 0
658
+ reasoningText = ""
659
+ reasoningTruncated = false
338
660
  turnStartTs = Date.now()
339
661
  resetTurnCounters()
340
- publish({ ...base(currentTurn), type: "turn.started", turnId: currentTurn, promptRef: "" })
662
+ publish({
663
+ ...base(currentTurn),
664
+ type: "turn.started",
665
+ turnId: currentTurn,
666
+ promptRef: `turn:${currentTurn}`,
667
+ })
341
668
  })
342
669
 
343
670
  sub("turn:completed", (e: { result?: unknown }) => {
344
671
  const r = (e?.result ?? {}) as { finalText?: unknown }
345
672
  const text = typeof r.finalText === "string" ? r.finalText : ""
673
+ finishReasoning()
346
674
  if (text) {
347
675
  publish({
348
676
  ...base(currentTurn),
@@ -352,6 +680,14 @@ export function createPresentationAdapter(
352
680
  truncated: false,
353
681
  })
354
682
  }
683
+ publish({
684
+ ...base(currentTurn),
685
+ type: "result.produced",
686
+ turnId: currentTurn,
687
+ resultId: `result:${sessionId}:${currentTurn}`,
688
+ status: "completed",
689
+ summary: firstLine(text, 200) || "turn completed",
690
+ })
355
691
  diag.turnsSettled++
356
692
  publish({
357
693
  ...base(currentTurn),
@@ -482,7 +818,10 @@ export function createPresentationAdapter(
482
818
  // Anak tidak menghitung ke summary parent — ledger parent = 1 baris
483
819
  // delegasi (delegate_task sendiri), bukan N tool anak.
484
820
  const count = !childId
485
- const emitBase = childId ? childBase(currentTurn, childId, parentLink) : base(currentTurn)
821
+ // Setiap event terminal butuh eventSeq sendiri: basis bersama membuat
822
+ // INSERT OR IGNORE durable melewatkan event berikutnya dengan seq sama.
823
+ const nextBase = () =>
824
+ childId ? childBase(currentTurn, childId, parentLink) : base(currentTurn)
486
825
  const withLink = <T extends DomainEvent>(ev: T): T =>
487
826
  parentLink ? { ...ev, parentLink } : ev
488
827
  // Fase 4: konten completed → store (put selalu jalan — zero user-visible
@@ -503,9 +842,66 @@ export function createPresentationAdapter(
503
842
  }
504
843
  if (!result.isError) {
505
844
  if (count) counts.ok++
845
+ if (call.name === "todo_write") {
846
+ // Plan event terbit DI SINI — setelah tool sukses — bukan di
847
+ // `execution:started`. Sebelumnya published dari argumen SEBELUM
848
+ // tool jalan, sehingga `plan.updated` berstatus "completed" bisa
849
+ // tertahan durable meski `saveTodos` gagal (disk penuh/EACCES):
850
+ // presentasi menyatakan selesai padahal tak ada file-nya.
851
+ //
852
+ // Sumber kebenaran = `normalizeTodos` yang sama dengan file todo,
853
+ // jadi status/cap tidak bisa berbeda dua arah (sebelumnya adaptor
854
+ // memetakan status sendiri: 2 item `in_progress` jadi dua `active`
855
+ // padahal file menyimpan satu).
856
+ const planSessionId = childId ?? sessionId
857
+ // PHASE 4A.4A - the assignment is read off THIS call's own result, the
858
+ // one object the kernel emitted together with this `call`. Nothing is
859
+ // remembered between events, so there is no state for another turn or
860
+ // another session to consume.
861
+ const plan = planFromTodos(
862
+ call.args,
863
+ planSessionId,
864
+ decodeCanonicalAssignments(result.content, { sessionId: planSessionId }),
865
+ )
866
+ if (plan) {
867
+ publish({
868
+ ...(childId ? childBase(currentTurn, childId, parentLink) : base(currentTurn)),
869
+ type: "plan.updated",
870
+ planId: `plan:${planSessionId}:${currentTurn}`,
871
+ status: plan.status,
872
+ // `2` asserts this event's step identity is taskId-based. Emitted
873
+ // only on total resolution, so the claim is always truthful.
874
+ ...(plan.canonical ? { payloadVersion: 2 as const } : {}),
875
+ steps: plan.steps,
876
+ })
877
+ }
878
+ }
879
+ if (call.name === "submit_result") {
880
+ const args = call.args as { summary?: unknown }
881
+ publish(
882
+ withLink({
883
+ ...nextBase(),
884
+ type: "result.produced",
885
+ resultId: `submit:${call.id}`,
886
+ status: "completed",
887
+ summary:
888
+ typeof args.summary === "string" ? args.summary : "structured result submitted",
889
+ }),
890
+ )
891
+ for (const finding of findingsFromSubmitResult(call.args, call.id)) {
892
+ publish(
893
+ withLink({
894
+ ...nextBase(),
895
+ type: "finding.detected",
896
+ turnId: currentTurn,
897
+ ...finding,
898
+ }),
899
+ )
900
+ }
901
+ }
506
902
  publish(
507
903
  withLink({
508
- ...emitBase,
904
+ ...nextBase(),
509
905
  type: "tool.completed" as const,
510
906
  toolCallId: call.id,
511
907
  durationMs,
@@ -522,7 +918,7 @@ export function createPresentationAdapter(
522
918
  diag.deniedReconstructed++
523
919
  publish(
524
920
  withLink({
525
- ...emitBase,
921
+ ...nextBase(),
526
922
  type: "tool.denied" as const,
527
923
  toolCallId: call.id,
528
924
  reason: denyReasonOf({ isError: true, content: result.content }) ?? "unknown",
@@ -534,7 +930,7 @@ export function createPresentationAdapter(
534
930
  if (count) counts.failed++
535
931
  publish(
536
932
  withLink({
537
- ...emitBase,
933
+ ...nextBase(),
538
934
  type: "tool.failed" as const,
539
935
  toolCallId: call.id,
540
936
  durationMs,
@@ -552,9 +948,34 @@ export function createPresentationAdapter(
552
948
  })
553
949
 
554
950
  sub("provider:extension", (e: { kind?: unknown; data?: unknown }) => {
951
+ if (e?.kind === "error") {
952
+ const data = e.data as { message?: unknown; error?: unknown } | null
953
+ const message =
954
+ typeof data?.message === "string"
955
+ ? data.message
956
+ : typeof data?.error === "string"
957
+ ? data.error
958
+ : "provider extension error"
959
+ publish({
960
+ ...base(currentTurn),
961
+ type: "diagnostic.raised",
962
+ turnId: currentTurn,
963
+ category: "PROVIDER_ERROR",
964
+ severity: "error",
965
+ message: message.slice(0, 500),
966
+ })
967
+ return
968
+ }
555
969
  if (e?.kind !== "reasoning") return
556
970
  const text = (e.data as { text?: unknown } | null)?.text
557
971
  if (typeof text !== "string" || !text) return
972
+ if (reasoningText.length < MAX_SECTION_CHARS) {
973
+ const remaining = MAX_SECTION_CHARS - reasoningText.length
974
+ reasoningText += text.slice(0, remaining)
975
+ if (text.length > remaining) reasoningTruncated = true
976
+ } else {
977
+ reasoningTruncated = true
978
+ }
558
979
  publish({ ...base(currentTurn), type: "reasoning.delta", turnId: currentTurn, delta: text })
559
980
  })
560
981
 
@@ -566,6 +987,22 @@ export function createPresentationAdapter(
566
987
  })
567
988
  })
568
989
 
990
+ const noteUserMessage: PresentationAdapter["noteUserMessage"] = ({ text, promptRef, turnId }) => {
991
+ try {
992
+ if (!text) return
993
+ diag.userMessages++
994
+ const resolvedTurn = turnId ?? currentTurn
995
+ publish({
996
+ ...base(resolvedTurn),
997
+ type: "user.message",
998
+ text,
999
+ promptRef: promptRef ?? `turn:${resolvedTurn}`,
1000
+ })
1001
+ } catch {
1002
+ diag.errors++
1003
+ }
1004
+ }
1005
+
569
1006
  const publishApproval: PresentationAdapter["publishApproval"] = (e) => {
570
1007
  try {
571
1008
  const identity = parseQualifiedName(String(e.call?.name ?? "tool"))
@@ -603,7 +1040,8 @@ export function createPresentationAdapter(
603
1040
  const noteFileChanged: PresentationAdapter["noteFileChanged"] = (info) => {
604
1041
  try {
605
1042
  publish({
606
- ...base(currentTurn),
1043
+ ...base(info.turnId ?? currentTurn),
1044
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
607
1045
  type: "file.changed",
608
1046
  toolCallId: info.toolCallId,
609
1047
  paths: info.paths,
@@ -615,6 +1053,53 @@ export function createPresentationAdapter(
615
1053
  }
616
1054
  }
617
1055
 
1056
+ const noteTestCompleted: PresentationAdapter["noteTestCompleted"] = (info) => {
1057
+ try {
1058
+ publish({
1059
+ ...base(info.turnId ?? currentTurn),
1060
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
1061
+ type: "test.completed",
1062
+ toolCallId: info.toolCallId,
1063
+ passed: info.passed,
1064
+ failed: info.failed,
1065
+ summary: info.summary,
1066
+ })
1067
+ } catch {
1068
+ diag.errors++
1069
+ }
1070
+ }
1071
+
1072
+ const noteVerificationObserved: PresentationAdapter["noteVerificationObserved"] = (info) => {
1073
+ try {
1074
+ publish({
1075
+ ...base(info.turnId ?? currentTurn),
1076
+ ...(info.sessionId ? { sessionId: info.sessionId } : {}),
1077
+ type: "verification.observed",
1078
+ toolCallId: info.toolCallId,
1079
+ invocationId: info.invocationId,
1080
+ verdict: info.verdict,
1081
+ method: info.method,
1082
+ observedAt: info.observedAt,
1083
+ ...(info.parentLink ? { parentLink: info.parentLink } : {}),
1084
+ })
1085
+ } catch {
1086
+ diag.errors++
1087
+ }
1088
+ }
1089
+
1090
+ const noteCheckpoint: PresentationAdapter["noteCheckpoint"] = (info) => {
1091
+ try {
1092
+ publish({
1093
+ ...base(info.turnId ?? currentTurn),
1094
+ type: "checkpoint.created",
1095
+ checkpointId: info.checkpointId,
1096
+ ...(info.paths ? { paths: info.paths } : {}),
1097
+ })
1098
+ } catch {
1099
+ diag.errors++
1100
+ }
1101
+ }
1102
+
618
1103
  const noteRunSettled: PresentationAdapter["noteRunSettled"] = (error, info) => {
619
1104
  try {
620
1105
  diag.turnsSettled++
@@ -692,9 +1177,30 @@ export function createPresentationAdapter(
692
1177
  handlers.delete(handler)
693
1178
  }
694
1179
  },
1180
+ noteUserMessage,
695
1181
  publishApproval,
696
1182
  noteRunSettled,
697
1183
  noteFileChanged,
1184
+ noteTestCompleted,
1185
+ noteVerificationObserved,
1186
+ noteCheckpoint,
1187
+ notePlanReconciled(info) {
1188
+ const owner = info.sessionId ?? sessionId
1189
+ const plan = planFromTodos({ todos: info.todos }, owner)
1190
+ if (!plan) return
1191
+ publish({
1192
+ ...base(currentTurn),
1193
+ type: "plan.updated",
1194
+ planId: `plan:${owner}:${currentTurn}`,
1195
+ status: plan.status,
1196
+ ...(plan.canonical ? { payloadVersion: 2 as const } : {}),
1197
+ steps: plan.steps,
1198
+ ...(info.turnId !== undefined ? { turnId: info.turnId } : {}),
1199
+ })
1200
+ },
1201
+ setTurnSummaryProvider(provider) {
1202
+ turnSummaryProvider = provider
1203
+ },
698
1204
  getDiagnostics() {
699
1205
  return { ...diag }
700
1206
  },
@@ -714,6 +1220,7 @@ export function createPresentationAdapter(
714
1220
  toolStarts.clear()
715
1221
  openApprovals.clear()
716
1222
  terminalTools.clear()
1223
+ turnSummaryProvider = undefined
717
1224
  },
718
1225
  }
719
1226
  }