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
@@ -21,13 +21,130 @@
21
21
  // menghentikan turn karena log gagal akan merusak lebih banyak daripada gap.
22
22
 
23
23
  import { createHash } from "node:crypto"
24
- import { mkdir, open, readFile } from "node:fs/promises"
24
+ import { mkdir, open, readFile, stat } from "node:fs/promises"
25
25
  import { dirname, isAbsolute, join, relative, resolve } from "node:path"
26
26
  import { atomicWriteText } from "../lib/atomic-write.ts"
27
27
  import { sanitizeSessionPart } from "../lib/session-id.ts"
28
+ import { scrubSecrets } from "../policy/scrub.ts"
29
+ import { classifyContractTool } from "../policy/tool-contract.ts"
28
30
  import { isMcpToolName } from "../presentation/label.ts"
29
31
 
30
- export type JournalState = "pending" | "committed" | "failed"
32
+ /**
33
+ * [Fase 10 / 10.1] Otoritas penyimpanan kanonik.
34
+ * `session/journal.ts` adalah Canonical Recovery Authority: satu-satunya
35
+ * sumber kebenaran intent/receipt/verification untuk crash recovery.
36
+ * `runtime/execution-journal.ts` adalah Diagnostic Audit Projection: history
37
+ * audit yang MEREKAM, bukan memutus recovery. Matriks lengkap 7 penyimpanan
38
+ * didefinisikan di `runtime/execution-journal.ts#STORAGE_AUTHORITY_MATRIX`
39
+ * (diimpor balik untuk menghindari siklus impor) — konstanta ini adalah
40
+ * penanda local authority agar tak pernah tertukar source of truth.
41
+ */
42
+ export const SESSION_JOURNAL_AUTHORITY = "canonical_recovery_ledger" as const
43
+
44
+ // [Fase 2 / LOOP-INV-07] `unknown` = terminal AMBIGU: eksekusi berhenti tanpa
45
+ // bukti apakah efeknya terjadi (mis. timeout bash). Bukan `failed` (yang
46
+ // menyiratkan "tidak terjadi") dan bukan `pending` (yang menyiratkan "belum
47
+ // selesai"): recovery wajib memverifikasi sebelum mengulang.
48
+ export type JournalState = "pending" | "committed" | "failed" | "unknown"
49
+
50
+ /**
51
+ * [Fase 2] SATU definisi "terminal". Sebelumnya predicate
52
+ * `state === "committed" || state === "failed"` disalin di banyak tempat;
53
+ * menambah `unknown` tanpa helper akan membuat record ambigu dianggap pending
54
+ * (dan di-stitch sebagai sukses) di jalur yang terlewat.
55
+ */
56
+ const TERMINAL_JOURNAL_STATES: ReadonlySet<string> = new Set(["committed", "failed", "unknown"])
57
+
58
+ export function isTerminalJournalState(state: JournalState | undefined): boolean {
59
+ return state !== undefined && TERMINAL_JOURNAL_STATES.has(state)
60
+ }
61
+
62
+ export type VerificationMethod =
63
+ | "filesystem-read-back"
64
+ | "checkpoint-diff"
65
+ | "git-state"
66
+ | "external-acknowledgement"
67
+ | "existing-verifier"
68
+ | "human-resolution"
69
+
70
+ export type VerificationVerdict = "present" | "absent" | "inconclusive"
71
+
72
+ const VERIFICATION_METHODS: ReadonlySet<VerificationMethod> = new Set([
73
+ "filesystem-read-back",
74
+ "checkpoint-diff",
75
+ "git-state",
76
+ "external-acknowledgement",
77
+ "existing-verifier",
78
+ "human-resolution",
79
+ ])
80
+
81
+ export function isVerificationMethod(method: string): method is VerificationMethod {
82
+ return VERIFICATION_METHODS.has(method as VerificationMethod)
83
+ }
84
+
85
+ export interface JournalOutcome {
86
+ code?: number | null
87
+ note?: string
88
+ /** Application-observed acknowledgement only; never universal effect proof. */
89
+ ack?: string | number | boolean | null
90
+ ackSource?: "bash-exit" | "sandbox-exit" | "git-commit" | "external-response" | "absent"
91
+ ackAuthority?: "application-observed"
92
+ truncated?: true
93
+ timeout?: true
94
+ aborted?: true
95
+ loss?: "none" | "response" | "persistence" | "unknown"
96
+ uncertainty?: "none" | "ambiguous-effect" | "unverified-external" | "evidence-incomplete"
97
+ observedAt?: number
98
+ /**
99
+ * Bounded child-execution observation (P9.2.1, delegate-task only).
100
+ * Dilaporkan apa yang teramati dari turn anak — BUKAN otoritas baru:
101
+ * tak mengubah makna `committed`/`failed`, tak mempublikasikan histori,
102
+ * tak menggantikan verifikasi/bukti lain. Opsional agar record lama tetap
103
+ * terbaca; pembaca tak boleh menjadikannya bukti efek.
104
+ */
105
+ childResult?: ChildResultEnvelope
106
+ }
107
+
108
+ /**
109
+ * Status observasi anak (P9.2.1): apa yang terlihat dari sisi pemanggil,
110
+ * bukan rekonstruksi kausal lengkap. `returned` = runner kembali normal
111
+ * (isi ringkasan boleh berupa teks error anak — itu observasi, bukan vonis);
112
+ * `failed_to_start` = runner tak pernah jalan (factory/provider/pool).
113
+ */
114
+ export type ChildStatus =
115
+ | "returned"
116
+ | "timeout"
117
+ | "aborted"
118
+ | "max_steps_exceeded"
119
+ | "error"
120
+ | "failed_to_start"
121
+
122
+ /**
123
+ * Amplop hasil anak yang bounded + disanitasi (P9.2.1). `resultSummary`
124
+ * adalah salinan sanitasi dari string yang sudah dilihat parent (batas
125
+ * panjang sama), BUKAN transkrip anak. Absent (`null`) = data memang tak
126
+ * tersedia di jalur itu — jangan difabrikasi.
127
+ */
128
+ /** [Fase 7 / LOOP-INV-13/15] Verdict consequence-engine (ACE-Lite) dari hasil anak. */
129
+ export interface AceResultSnapshot {
130
+ readonly verdict: import("../policy/consequence-engine.ts").AceVerdict
131
+ readonly failureClass: import("../policy/consequence-engine.ts").AceFailureClass
132
+ readonly nextAction: import("../policy/consequence-engine.ts").AceNextAction
133
+ readonly rationale?: string
134
+ }
135
+
136
+ export interface ChildResultEnvelope {
137
+ readonly childStatus: ChildStatus
138
+ readonly resultSummary: string
139
+ readonly runId: string | null
140
+ readonly steps: number | null
141
+ readonly truncated: boolean
142
+ /** [Fase 7 / LOOP-INV-13/15] Hasil deterministik consequence-engine pada penyelesaian/
143
+ * kegagalan turn anak — tersurat di amplop agar parent dan auditor bisa verifikasi
144
+ * apakah outcome layak diterima apa adanya (PASS) atau perlu review/retry (FAIL).
145
+ * Absent = test khusus / legacy runner yang belum hitung ACE. */
146
+ readonly aceVerdict?: AceResultSnapshot
147
+ }
31
148
 
32
149
  export interface JournalRecord {
33
150
  v: 1
@@ -40,8 +157,8 @@ export interface JournalRecord {
40
157
  turn?: number | null
41
158
  seq: number
42
159
  tool: string
43
- /** mutation (default) | undo | redo | finalize. Marker bukan intent. */
44
- kind?: "mutation" | "undo" | "redo" | "finalize"
160
+ /** mutation (default) | verification | undo | redo | finalize. Marker bukan intent. */
161
+ kind?: "mutation" | "verification" | "undo" | "redo" | "finalize"
45
162
  /** true = klaim sukses berasal dari pihak remote (MCP), bukan komit lokal. */
46
163
  remote?: true
47
164
  /** Backend code_run ("docker"|"os"|...) — alat interpretasi, bukan kontrol. */
@@ -50,10 +167,57 @@ export interface JournalRecord {
50
167
  cwd: string
51
168
  /** Path relatif-workspace untuk verification (allowlist per kelas-tool). */
52
169
  paths?: string[]
170
+ /** Canonical history thread for this intent (P2.10 invocation scope). */
171
+ threadId?: string
172
+ /** Application-owned invocation key (provider call identifiers are locators only). */
173
+ invocationId?: string
174
+ /** Provider call identifier, when available; never canonical by itself. */
175
+ providerToolCallId?: string
53
176
  /** SHA-256 JSON kanonisal argumen — identitas, BUKAN replay (tanpa raw args). */
54
177
  argsHash?: string
178
+ /**
179
+ * [Fase 2 / LOOP-G06, LOOP-G07] Hash isi target SEBELUM efek (SHA-256 hex),
180
+ * atau `null` bila file belum ada. Hanya ditulis jalur pre-flight (barrier
181
+ * durable), karena hanya di sana waktu "sebelum efek" benar-benar dijamin.
182
+ * Absent = record legacy / jalur fallback → rekonsiliasi wajib UNKNOWN.
183
+ */
184
+ preTargetHash?: string | null
185
+ /**
186
+ * Hash isi target yang DIHARAPKAN setelah efek sukses. `null` = target
187
+ * diharapkan tidak ada (delete_file). Absent = tidak dapat dihitung dari
188
+ * argumen (edit/apply_patch) → rekonsiliasi jatuh ke UNKNOWN bila isi
189
+ * berubah dari preTargetHash.
190
+ */
191
+ postTargetHash?: string | null
55
192
  /** Tautan delegasi: id sesi anak (parent-side record). */
56
193
  childSessionId?: string
194
+ // M1 correlator (ADR-002, additive-optional): korelasi execution pada intent
195
+ // + terminal. Absent = record legacy / jalur belum wiring; recovery lama
196
+ // (consolidate per `id` session:seq) tak berubah. Jangan jadikan pengganti
197
+ // `id` — `id` tetap identity utama jurnal.
198
+ //
199
+ // [P1 M15][DEPRECATED] Lima field di bawah USED to be the staged place for
200
+ // runtime correlation. Produksi TIDAK PERNAH mengisinya (nol caller), dan M15
201
+ // menetapkan satu history eksekusi durable: jurnal runtime M11
202
+ // (`src/runtime/execution-journal.ts`) yang memegang executionId/parent/
203
+ // lineageRoot/version. Jurnal ini tetap milik domain mutation/undo (git
204
+ // checkpoints), dan sengaja TIDAK menjadi bridge kedua ke runtime.
205
+ //
206
+ // Aturan: JANGAN menambah caller produksi yang mengisinya. Kalau sebuah record
207
+ // butuh korelasi runtime, tulislah ke jurnal runtime; kalau butuh jejak
208
+ // mutation, field ini tetap `absent`. Field tak dihapus agar record lama
209
+ // (yang mungkin sudah tertulis) tetap terbaca — penghapusan adalah M16+ dan
210
+ // butuh migrasi reader.
211
+ /** Identity instance execution (allocated / derived stabil). DEPRECATED — see above. */
212
+ executionId?: string
213
+ /** Parent execution (absen pada root). DEPRECATED — see above. */
214
+ parentExecutionId?: string
215
+ /** Root forest korelasi (immutable). DEPRECATED — see above. */
216
+ rootExecutionId?: string
217
+ /** Kind datar M1. DEPRECATED — see above. */
218
+ executionKind?: string
219
+ /** Owner menurut arsitektur; bukan authority user input. DEPRECATED — see above. */
220
+ ownerId?: string
57
221
  /** Marker finalize: semua seq ≤ ini durable. */
58
222
  uptoSeq?: number
59
223
  /** Marker undo/redo: turn target manifest. */
@@ -68,7 +232,14 @@ export interface JournalRecord {
68
232
  files?: number
69
233
  /** Hanya untuk kind mutation. Terminal immutable (lihat consolidate). */
70
234
  state?: JournalState
71
- outcome?: { code?: number | null; note?: string }
235
+ outcome?: JournalOutcome
236
+ /** Hanya untuk kind verification: explicit observation method and verdict. */
237
+ method?: VerificationMethod
238
+ verdict?: VerificationVerdict
239
+ /** Scrubbed, length-capped pointer to the external observation (never raw content). */
240
+ evidenceReference?: string
241
+ /** When the external observation occurred (may differ from append time). */
242
+ observedAt?: number
72
243
  /**
73
244
  * Bukti dedup idempotency (audit #08 P0): terminal yang ditandai ini
74
245
  * dipertahankan sweep (lihat sweepInner) agar retry id-sama pasca-restart
@@ -85,56 +256,13 @@ export interface JournalRecord {
85
256
  // MUTATION = execute() dapat menimbulkan efek eksternal durable.
86
257
  // "none" = terbukti tanpa efek durable (read, kontrol, full-replace
87
258
  // idempoten seperti todo_write, memori-proses seperti submit_result).
88
- // Nama bertitik (server.tool runtime MCP) = kelas mcp_call.
89
- const MUTATION_TOOLS: ReadonlySet<string> = new Set([
90
- "write_file",
91
- "edit",
92
- "apply_patch",
93
- "move_file",
94
- "delete_file",
95
- "bash",
96
- "git_commit",
97
- "mcp_call",
98
- "code_run",
99
- "delegate_task",
100
- "write_memory",
101
- "forget_memory",
102
- ])
103
-
104
- const NON_MUTATION_TOOLS: ReadonlySet<string> = new Set([
105
- "read_file",
106
- "glob",
107
- "grep",
108
- "read_image",
109
- "bash_output",
110
- "bash_kill",
111
- "git_status",
112
- "git_diff",
113
- "git_log",
114
- "lsp_diagnostics",
115
- "lsp_definition",
116
- "lsp_references",
117
- "lsp_hover",
118
- "lsp_symbols",
119
- "lsp_workspace_symbols",
120
- "mcp_list",
121
- "mcp_read",
122
- "mcp_prompt",
123
- "read_memory",
124
- "todo_write",
125
- "todo_read",
126
- "submit_result",
127
- "ask_user",
128
- "web_fetch",
129
- "web_search",
130
- ])
259
+ // [Fase 2 / TOOL-01] Klasifikasi diturunkan dari registry kontrak tool.
260
+ // Tool tak dikenal tetap fail-closed: `classifyContractTool` mengembalikan
261
+ // "unknown" dan `isMutationTool` memperlakukannya sebagai mutasi.
131
262
 
132
263
  export function classifyTool(name: string): "mutation" | "none" | "unknown" {
133
- // Tool runtime MCP (server.tool) mewarisi kelas mcp_call: efek arbitrer.
134
- const base = isMcpToolName(name) ? "mcp_call" : name
135
- if (MUTATION_TOOLS.has(base)) return "mutation"
136
- if (NON_MUTATION_TOOLS.has(base)) return "none"
137
- return "unknown"
264
+ // Nama bertitik (server.tool) = kelas mcp_call; sudah ditangani kontrak.
265
+ return classifyContractTool(name)
138
266
  }
139
267
 
140
268
  export function isMutationTool(name: string): boolean {
@@ -147,6 +275,14 @@ export function isMutationTool(name: string): boolean {
147
275
  return classifyTool(name) !== "none"
148
276
  }
149
277
 
278
+ /** P2.10 canonical coverage: plain registry tools handled by an awaited wrapper. */
279
+ export function isCanonicalEvidenceCovered(name: string): boolean {
280
+ // Independent special paths keep their own single intent/terminal pair:
281
+ // delegate_task writes explicitly, and dotted runtime MCP tools remain on
282
+ // the event path while MCP server mode has its own awaited instrumentation.
283
+ return isMutationTool(name) && !NO_AUTO_JOURNAL.has(name) && !isMcpToolName(name)
284
+ }
285
+
150
286
  // delegate_task dicatat eksplisit oleh tool-nya sendiri (butuh childSessionId
151
287
  // yang hanya diketahui di sana) — wiring generik melewatinya agar tak ganda.
152
288
  const NO_AUTO_JOURNAL: ReadonlySet<string> = new Set(["delegate_task"])
@@ -166,6 +302,45 @@ export function hashArgs(args: unknown): string {
166
302
  .digest("hex")
167
303
  }
168
304
 
305
+ // ── [Fase 2 / LOOP-INV-07] Tag hasil tool yang ambigu ──────────────────────
306
+ //
307
+ // `ToolResult` kernel FROZEN hanya punya `{content, isError}`. Karena itu
308
+ // status UNKNOWN diwakili prefix deterministik di awal `content`, bukan field
309
+ // baru di kernel. Format sengaja stabil dan sempit supaya bisa diparse tanpa
310
+ // menebak isi bebas:
311
+ //
312
+ // [TOOL_OUTCOME state=UNKNOWN reason=TIMEOUT side_effect_tier=LOCAL_ENV_MUTATION duration_ms=… timeout_ms=…]
313
+ //
314
+ // Parser mengembalikan `null` untuk hasil normal, sehingga pemanggil lama tak
315
+ // berubah perilakunya.
316
+ export interface ToolOutcomeTag {
317
+ readonly state: "UNKNOWN"
318
+ readonly reason: string
319
+ readonly sideEffectTier: string
320
+ readonly durationMs: number | null
321
+ readonly timeoutMs: number | null
322
+ }
323
+
324
+ const TOOL_OUTCOME_RE =
325
+ /^\[TOOL_OUTCOME state=UNKNOWN reason=([A-Z_]+) side_effect_tier=([A-Z_]+)([^\]]*)\]/
326
+
327
+ export function parseToolOutcomeTag(content: string): ToolOutcomeTag | null {
328
+ if (typeof content !== "string") return null
329
+ const m = TOOL_OUTCOME_RE.exec(content)
330
+ if (!m) return null
331
+ const numeric = (key: string): number | null => {
332
+ const mm = new RegExp(`(?:^|\\s)${key}=(\\d+)(?:\\s|$)`).exec(m[3] ?? "")
333
+ return mm ? Number(mm[1]) : null
334
+ }
335
+ return {
336
+ state: "UNKNOWN",
337
+ reason: m[1]!,
338
+ sideEffectTier: m[2]!,
339
+ durationMs: numeric("duration_ms"),
340
+ timeoutMs: numeric("timeout_ms"),
341
+ }
342
+ }
343
+
169
344
  /** Ambil path verifikasi (relatif, di dalam root) sesuai kelas tool. */
170
345
  export function verifyPaths(tool: string, args: unknown, cwd: string): string[] {
171
346
  const a = (args ?? {}) as Record<string, unknown>
@@ -199,6 +374,146 @@ export function verifyPaths(tool: string, args: unknown, cwd: string): string[]
199
374
  }
200
375
  }
201
376
 
377
+ // ── [Fase 2 / LOOP-G06, LOOP-G07] Hash target pra/pasca mutasi ─────────────
378
+ //
379
+ // Tujuan: setelah crash, recovery bisa membedakan "belum terjadi" dari "sudah
380
+ // selesai" dari "setengah tertulis" TANPA menjalankan ulang mutasi. Bukti ini
381
+ // hanya mungkin dikumpulkan SEBELUM efek, jadi hanya jalur pre-flight (barrier
382
+ // Fase 1) yang menulisnya. Batas ukuran mencegah barrier membaca file raksasa.
383
+
384
+ const TARGET_HASH_TOOLS: ReadonlySet<string> = new Set([
385
+ "write_file",
386
+ "edit",
387
+ "apply_patch",
388
+ "move_file",
389
+ "delete_file",
390
+ ])
391
+
392
+ /** Batas baca hash: di atas ini bukti hash dilewati (rekonsiliasi = UNKNOWN). */
393
+ const TARGET_HASH_MAX_BYTES = 8 * 1024 * 1024
394
+
395
+ async function hashFileOrNull(
396
+ abs: string,
397
+ ): Promise<{ ok: true; hash: string | null } | { ok: false }> {
398
+ try {
399
+ const st = await stat(abs)
400
+ if (!st.isFile() || st.size > TARGET_HASH_MAX_BYTES) return { ok: false }
401
+ const bytes = await readFile(abs)
402
+ return { ok: true, hash: createHash("sha256").update(bytes).digest("hex") }
403
+ } catch (e) {
404
+ if ((e as NodeJS.ErrnoException)?.code === "ENOENT") return { ok: true, hash: null }
405
+ return { ok: false }
406
+ }
407
+ }
408
+
409
+ function sha256Text(text: string): string {
410
+ return createHash("sha256").update(text, "utf8").digest("hex")
411
+ }
412
+
413
+ /**
414
+ * Hitung hash pra-efek (dan pasca-efek bila dapat diturunkan dari argumen).
415
+ * Tak pernah melempar: kegagalan baca = bukti tidak tersedia (field absen),
416
+ * bukan alasan menggagalkan tool.
417
+ */
418
+ async function targetHashesFor(
419
+ name: string,
420
+ args: Record<string, unknown>,
421
+ root: string,
422
+ ): Promise<{ preTargetHash?: string | null; postTargetHash?: string | null }> {
423
+ if (!TARGET_HASH_TOOLS.has(name)) return {}
424
+ const rel = verifyPaths(name, args, root)[0]
425
+ if (!rel) return {}
426
+ const pre = await hashFileOrNull(resolve(root, rel))
427
+ if (!pre.ok) return {}
428
+ const out: { preTargetHash?: string | null; postTargetHash?: string | null } = {
429
+ preTargetHash: pre.hash,
430
+ }
431
+ if (name === "write_file" && typeof args.content === "string") {
432
+ out.postTargetHash = sha256Text(args.content)
433
+ } else if (name === "delete_file") {
434
+ // Field hadir dengan nilai null = "diharapkan tidak ada setelah efek".
435
+ out.postTargetHash = null
436
+ }
437
+ // edit/apply_patch/move_file: isi akhir tidak dapat diturunkan dari argumen
438
+ // tanpa menerapkan patch → postTargetHash absen (rekonsiliasi = UNKNOWN bila
439
+ // isi berubah dari pre).
440
+ return out
441
+ }
442
+
443
+ export type WorkspaceMutationVerdict = "CONFIRMED_NOT_EXECUTED" | "CONFIRMED_EXECUTED" | "UNKNOWN"
444
+
445
+ export interface WorkspaceReconciliation {
446
+ readonly verdict: WorkspaceMutationVerdict
447
+ readonly targetPath: string | null
448
+ readonly observedHash: string | null
449
+ readonly reason: string
450
+ }
451
+
452
+ /**
453
+ * [Fase 2 / LOOP-G06, LOOP-G07] Rekonsiliasi deterministik satu intent mutasi
454
+ * terhadap kondisi disk SEKARANG.
455
+ *
456
+ * Aturan (urutan penting):
457
+ * 1. isi == preTargetHash DAN != postTargetHash → CONFIRMED_NOT_EXECUTED
458
+ * 2. postTargetHash diketahui DAN isi == post → CONFIRMED_EXECUTED
459
+ * 3. selain itu (berubah tapi bukan post yang diketahui, record legacy tanpa
460
+ * hash, path di luar root, file tak terbaca) → UNKNOWN
461
+ *
462
+ * `UNKNOWN` adalah jawaban aman: pemanggil wajib memverifikasi/meminta
463
+ * keputusan, bukan mengulang mutasi.
464
+ */
465
+ export async function reconcileWorkspaceMutationIntent(
466
+ record: Pick<JournalRecord, "paths" | "preTargetHash" | "postTargetHash">,
467
+ workspaceRoot: string,
468
+ ): Promise<WorkspaceReconciliation> {
469
+ const root = resolve(workspaceRoot)
470
+ const rel = record.paths?.[0]
471
+ if (!rel) {
472
+ return { verdict: "UNKNOWN", targetPath: null, observedHash: null, reason: "no-target-path" }
473
+ }
474
+ const abs = resolve(root, rel)
475
+ const back = relative(root, abs).replace(/\\/g, "/")
476
+ if (!back || back.startsWith("..") || isAbsolute(back)) {
477
+ return { verdict: "UNKNOWN", targetPath: rel, observedHash: null, reason: "path-outside-root" }
478
+ }
479
+ if (record.preTargetHash === undefined) {
480
+ return {
481
+ verdict: "UNKNOWN",
482
+ targetPath: rel,
483
+ observedHash: null,
484
+ reason: "no-pre-target-hash",
485
+ }
486
+ }
487
+ const observed = await hashFileOrNull(abs)
488
+ if (!observed.ok) {
489
+ return { verdict: "UNKNOWN", targetPath: rel, observedHash: null, reason: "target-unreadable" }
490
+ }
491
+ const pre = record.preTargetHash
492
+ const post = record.postTargetHash
493
+ if (observed.hash === pre && post !== pre) {
494
+ return {
495
+ verdict: "CONFIRMED_NOT_EXECUTED",
496
+ targetPath: rel,
497
+ observedHash: observed.hash,
498
+ reason: "content-matches-pre",
499
+ }
500
+ }
501
+ if (post !== undefined && observed.hash === post) {
502
+ return {
503
+ verdict: "CONFIRMED_EXECUTED",
504
+ targetPath: rel,
505
+ observedHash: observed.hash,
506
+ reason: "content-matches-post",
507
+ }
508
+ }
509
+ return {
510
+ verdict: "UNKNOWN",
511
+ targetPath: rel,
512
+ observedHash: observed.hash,
513
+ reason: "content-differs-from-known-states",
514
+ }
515
+ }
516
+
202
517
  // ── Lokasi & state penulis ──
203
518
 
204
519
  function sanitizeId(s: string): string {
@@ -381,11 +696,21 @@ export interface IntentInput {
381
696
  childOf?: string
382
697
  turn?: number | null
383
698
  tool: string
699
+ threadId?: string
700
+ /** Provisional or canonical application-owned invocation key. */
701
+ invocationId?: string
702
+ providerToolCallId?: string
703
+ /** Allocate the canonical key from the reserved journal sequence inside the lock. */
704
+ allocateInvocationId?: (allocationSequence: number) => string
384
705
  remote?: true
385
706
  backend?: string
386
707
  cwd?: string
387
708
  paths?: string[]
388
709
  argsHash?: string
710
+ /** [Fase 2 / LOOP-G06] Hash isi target sebelum efek (lihat JournalRecord). */
711
+ preTargetHash?: string | null
712
+ /** [Fase 2 / LOOP-G07] Hash target yang diharapkan setelah efek sukses. */
713
+ postTargetHash?: string | null
389
714
  childSessionId?: string
390
715
  /**
391
716
  * Kunci idempotency (audit #08): ditulis ke outcome.note SEJAK intent agar
@@ -394,6 +719,15 @@ export interface IntentInput {
394
719
  * retry id-sama pasca-crash dieksekusi ulang buta).
395
720
  */
396
721
  note?: string
722
+ // M1 correlator (ADR-002, passthrough): korelasi execution opsional dari
723
+ // pemanggil (Host M3+). Absent = jalur belum wiring — perilaku lama utuh.
724
+ // Validasi bentuk BUKAN di sini (allocator/helper yang menjamin); jurnal
725
+ // hanya menyalin string yang diberikan (tanpa rahasia: id/korelasi publik).
726
+ executionId?: string
727
+ parentExecutionId?: string
728
+ rootExecutionId?: string
729
+ executionKind?: string
730
+ ownerId?: string
397
731
  }
398
732
 
399
733
  /** Tulis intent pending. Tak pernah throw (degraded-loud, lihat header). */
@@ -406,6 +740,9 @@ export async function appendMutationIntent(input: IntentInput): Promise<JournalR
406
740
  // Alokasi seq SYNCHRONOUS di dalam lock: tanpa ini dua pemanggil konkuren
407
741
  // mendapat seq sama (tabrakan id — P0, ditemukan AUDIT #01D).
408
742
  const seq = st.nextSeq
743
+ const invocationId = input.allocateInvocationId
744
+ ? input.allocateInvocationId(seq)
745
+ : input.invocationId
409
746
  const rec: JournalRecord = {
410
747
  v: 1,
411
748
  id: `${input.session}:${seq}`,
@@ -414,12 +751,23 @@ export async function appendMutationIntent(input: IntentInput): Promise<JournalR
414
751
  turn: input.turn ?? null,
415
752
  seq,
416
753
  tool: input.tool,
754
+ ...(input.threadId ? { threadId: input.threadId } : {}),
755
+ ...(invocationId ? { invocationId } : {}),
756
+ ...(input.providerToolCallId ? { providerToolCallId: input.providerToolCallId } : {}),
417
757
  ...(input.remote ? { remote: true as const } : {}),
418
758
  ...(input.backend ? { backend: input.backend } : {}),
419
759
  cwd: root,
420
760
  ...(input.paths?.length ? { paths: input.paths } : {}),
421
761
  ...(input.argsHash ? { argsHash: input.argsHash } : {}),
762
+ ...(input.preTargetHash !== undefined ? { preTargetHash: input.preTargetHash } : {}),
763
+ ...(input.postTargetHash !== undefined ? { postTargetHash: input.postTargetHash } : {}),
422
764
  ...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
765
+ // M1 correlator passthrough (absent = tak ada perubahan perilaku).
766
+ ...(input.executionId ? { executionId: input.executionId } : {}),
767
+ ...(input.parentExecutionId ? { parentExecutionId: input.parentExecutionId } : {}),
768
+ ...(input.rootExecutionId ? { rootExecutionId: input.rootExecutionId } : {}),
769
+ ...(input.executionKind ? { executionKind: input.executionKind } : {}),
770
+ ...(input.ownerId ? { ownerId: input.ownerId } : {}),
423
771
  // Kunci idempotency sejak intent (lihat IntentInput.note).
424
772
  ...(input.note ? { outcome: { note: input.note } } : {}),
425
773
  state: "pending",
@@ -443,10 +791,23 @@ export async function appendMutationTerminal(
443
791
  id: string,
444
792
  seq: number,
445
793
  tool: string,
446
- state: "committed" | "failed",
447
- outcome?: { code?: number | null; note?: string },
794
+ state: "committed" | "failed" | "unknown",
795
+ outcome?: JournalOutcome,
448
796
  childSessionId?: string,
449
- opts: { dedup?: boolean } = {},
797
+ opts: {
798
+ dedup?: boolean
799
+ threadId?: string
800
+ invocationId?: string
801
+ providerToolCallId?: string
802
+ argsHash?: string
803
+ receipt?: Omit<JournalOutcome, "code" | "note">
804
+ // M1 correlator passthrough (absent = terminal legacy tanpa korelasi).
805
+ executionId?: string
806
+ parentExecutionId?: string
807
+ rootExecutionId?: string
808
+ executionKind?: string
809
+ ownerId?: string
810
+ } = {},
450
811
  ): Promise<void> {
451
812
  const root = resolve(cwd ?? process.cwd())
452
813
  const path = journalPath(session, root)
@@ -461,12 +822,30 @@ export async function appendMutationTerminal(
461
822
  tool,
462
823
  state,
463
824
  cwd: root,
464
- ...(outcome ? { outcome } : {}),
825
+ ...(opts.threadId ? { threadId: opts.threadId } : {}),
826
+ ...(opts.invocationId ? { invocationId: opts.invocationId } : {}),
827
+ ...(opts.providerToolCallId ? { providerToolCallId: opts.providerToolCallId } : {}),
828
+ ...(opts.argsHash ? { argsHash: opts.argsHash } : {}),
829
+ ...(outcome || opts.receipt
830
+ ? {
831
+ outcome: {
832
+ ...(outcome ?? {}),
833
+ ...(opts.receipt ?? {}),
834
+ ...(opts.receipt?.observedAt === undefined ? { observedAt: Date.now() } : {}),
835
+ },
836
+ }
837
+ : {}),
465
838
  // Tautan delegasi diwariskan ke terminal agar pembaca tak perlu
466
839
  // join intent-terminal untuk mengetahui anak mana yang dirujuk.
467
840
  ...(childSessionId ? { childSessionId } : {}),
468
841
  // Bukti dedup idempotency (mis. MCP request id): dipertahankan sweep.
469
842
  ...(opts.dedup ? { dedup: true as const } : {}),
843
+ // M1 correlator passthrough terminal (diwariskan dari intent pemanggil).
844
+ ...(opts.executionId ? { executionId: opts.executionId } : {}),
845
+ ...(opts.parentExecutionId ? { parentExecutionId: opts.parentExecutionId } : {}),
846
+ ...(opts.rootExecutionId ? { rootExecutionId: opts.rootExecutionId } : {}),
847
+ ...(opts.executionKind ? { executionKind: opts.executionKind } : {}),
848
+ ...(opts.ownerId ? { ownerId: opts.ownerId } : {}),
470
849
  ts: Date.now(),
471
850
  }
472
851
  const st = writers.get(key)
@@ -474,6 +853,71 @@ export async function appendMutationTerminal(
474
853
  })
475
854
  }
476
855
 
856
+ /** Append a standalone explicit external-effect observation (P2.10 VerificationRecord). */
857
+ export async function appendVerificationRecord(input: {
858
+ session: string
859
+ threadId?: string
860
+ tool: string
861
+ invocationId: string
862
+ method: VerificationMethod
863
+ verdict: VerificationVerdict
864
+ evidenceReference: string
865
+ observedAt?: number
866
+ cwd?: string
867
+ childOf?: string
868
+ childSessionId?: string
869
+ providerToolCallId?: string
870
+ }): Promise<{ record: JournalRecord; durable: boolean }> {
871
+ if (!input.tool) throw new Error("verification: refusing record without tool")
872
+ if (!input.invocationId) throw new Error("verification: refusing record without invocationId")
873
+ if (!VERIFICATION_METHODS.has(input.method)) {
874
+ throw new Error(`verification: unsupported method ${String(input.method)}`)
875
+ }
876
+ if (
877
+ input.verdict !== "present" &&
878
+ input.verdict !== "absent" &&
879
+ input.verdict !== "inconclusive"
880
+ ) {
881
+ throw new Error(`verification: unsupported verdict ${String(input.verdict)}`)
882
+ }
883
+ const evidenceReference = scrubSecrets(String(input.evidenceReference ?? "")).slice(0, 1000)
884
+ if (!evidenceReference) throw new Error("verification: refusing record without evidenceReference")
885
+ const root = resolve(input.cwd ?? process.cwd())
886
+ const path = journalPath(input.session, root)
887
+ const key = writerKey(input.session, root)
888
+ return withFileLock(key, async () => {
889
+ const st = await stateFor(path, key)
890
+ const seq = st.nextSeq
891
+ const observedAt =
892
+ typeof input.observedAt === "number" && Number.isFinite(input.observedAt)
893
+ ? input.observedAt
894
+ : Date.now()
895
+ const rec: JournalRecord = {
896
+ v: 1,
897
+ id: `${input.session}:v${seq}`,
898
+ session: input.session,
899
+ seq,
900
+ tool: input.tool,
901
+ kind: "verification",
902
+ ...(input.childOf ? { childOf: input.childOf } : {}),
903
+ ...(input.threadId ? { threadId: input.threadId } : {}),
904
+ invocationId: input.invocationId,
905
+ ...(input.providerToolCallId ? { providerToolCallId: input.providerToolCallId } : {}),
906
+ ...(input.childSessionId ? { childSessionId: input.childSessionId } : {}),
907
+ method: input.method,
908
+ verdict: input.verdict,
909
+ evidenceReference,
910
+ observedAt,
911
+ cwd: root,
912
+ ts: Date.now(),
913
+ }
914
+ const durable = await appendLine(path, rec)
915
+ if (durable) st.nextSeq = seq + 1
916
+ else markDegraded(input.session, root, "verification append gagal")
917
+ return { record: rec, durable }
918
+ })
919
+ }
920
+
477
921
  /** Marker finalize: semua seq ≤ uptoSeq durable (post-persistCurrent). */
478
922
  export async function appendFinalize(
479
923
  session: string,
@@ -578,14 +1022,21 @@ async function sweepInner(sessionId: string, root: string): Promise<number> {
578
1022
  // dibuang — statusnya hidup di record terminal (satu semantik mutasi).
579
1023
  const paired = new Set<string>()
580
1024
  for (const r of loaded.records) {
581
- if ((!r.kind || r.kind === "mutation") && (r.state === "committed" || r.state === "failed")) {
1025
+ if ((!r.kind || r.kind === "mutation") && isTerminalJournalState(r.state)) {
582
1026
  paired.add(r.id)
583
1027
  }
584
1028
  }
585
1029
  const committedKeys = committedPathsKeys(loaded.records)
1030
+ // [Audit #2 C.F8] Hoist maxFinalizeSeq ke konstanta — semula dihitung ulang
1031
+ // di dalam `.filter` untuk setiap record (O(n²)). Sekali jalan = O(n).
1032
+ const maxFinalize = maxFinalizeSeq(loaded.records)
586
1033
  const keep = loaded.records.filter((r) => {
587
- if (r.kind === "finalize") return r.seq === maxFinalizeSeq(loaded.records)
1034
+ if (r.kind === "finalize") return r.seq === maxFinalize
588
1035
  if (r.kind === "undo" || r.kind === "redo") return r.seq > maxUpto
1036
+ // P2.10 verification evidence is retained like dedup terminals: it may be
1037
+ // the only durable external-effect observation after finalize/sweep.
1038
+ // Bound by per-session files + orphan TTL, not by finalize.
1039
+ if (r.kind === "verification") return true
589
1040
  if (r.state === "pending" && paired.has(r.id)) return false
590
1041
  if (r.state === "pending") return !isSuperseded(r, committedKeys)
591
1042
  // Bukti dedup idempotency (dedup: true, mis. MCP request id) BUKAN sampah
@@ -593,11 +1044,7 @@ async function sweepInner(sessionId: string, root: string): Promise<number> {
593
1044
  // ulang buta (audit #08 P0 — reproducer: note hilang setelah sweep).
594
1045
  // Intent pasangannya tetap dibuang (aturan paired di atas); terminal ini
595
1046
  // yang menjadi bukti. Batas pertumbuhan: file per sesi + purge yatim TTL.
596
- if (
597
- (!r.kind || r.kind === "mutation") &&
598
- (r.state === "committed" || r.state === "failed") &&
599
- r.dedup === true
600
- )
1047
+ if ((!r.kind || r.kind === "mutation") && isTerminalJournalState(r.state) && r.dedup === true)
601
1048
  return true
602
1049
  return (r.seq ?? 0) > maxUpto // committed/failed muda bertahan
603
1050
  })
@@ -664,7 +1111,7 @@ export async function resolvePending(
664
1111
  (r) => (!r.kind || r.kind === "mutation") && r.session === sessionId && r.seq === seq,
665
1112
  )
666
1113
  if (mine.length === 0) return false
667
- if (mine.some((r) => r.state === "committed" || r.state === "failed")) return false
1114
+ if (mine.some((r) => isTerminalJournalState(r.state))) return false
668
1115
  const first = mine[0]!
669
1116
  await appendMutationTerminal(
670
1117
  sessionId,
@@ -710,8 +1157,22 @@ function isRecordShape(r: unknown): r is JournalRecord {
710
1157
  if (o.v !== 1 || typeof o.id !== "string" || typeof o.session !== "string") return false
711
1158
  if (typeof o.seq !== "number" || !Number.isFinite(o.seq)) return false
712
1159
  if (o.kind === "finalize" || o.kind === "undo" || o.kind === "redo") return true
1160
+ if (o.kind === "verification") {
1161
+ return (
1162
+ typeof o.tool === "string" &&
1163
+ o.tool !== "" &&
1164
+ typeof o.invocationId === "string" &&
1165
+ o.invocationId !== "" &&
1166
+ VERIFICATION_METHODS.has(o.method as VerificationMethod) &&
1167
+ (o.verdict === "present" || o.verdict === "absent" || o.verdict === "inconclusive") &&
1168
+ typeof o.evidenceReference === "string" &&
1169
+ o.evidenceReference !== "" &&
1170
+ typeof o.observedAt === "number" &&
1171
+ Number.isFinite(o.observedAt)
1172
+ )
1173
+ }
713
1174
  if (typeof o.tool !== "string" || !o.tool) return false
714
- return o.state === "pending" || o.state === "committed" || o.state === "failed"
1175
+ return o.state === "pending" || isTerminalJournalState(o.state as JournalState)
715
1176
  }
716
1177
 
717
1178
  export async function loadJournal(sessionId: string, cwd?: string): Promise<JournalLoad> {
@@ -816,7 +1277,7 @@ export interface AttentionItem {
816
1277
  id: string
817
1278
  seq: number
818
1279
  tool: string
819
- state: "pending" | "committed" | "failed"
1280
+ state: JournalState
820
1281
  remote: boolean
821
1282
  paths: string[]
822
1283
  childSessionId?: string
@@ -830,7 +1291,15 @@ export interface RecoveryPlan {
830
1291
  warnings: string[]
831
1292
  attention: AttentionItem[]
832
1293
  stitched: { id: string; tool: string; turn?: number | null }[]
833
- stats: { pending: number; failed: number; committed: number; finalized: number; markers: number }
1294
+ stats: {
1295
+ pending: number
1296
+ failed: number
1297
+ committed: number
1298
+ /** [Fase 2 / LOOP-INV-07] Terminal ambigu: efek belum bisa dipastikan. */
1299
+ unknown: number
1300
+ finalized: number
1301
+ markers: number
1302
+ }
834
1303
  }
835
1304
 
836
1305
  const MAX_DIRECTIVE_ITEMS = 10
@@ -880,7 +1349,7 @@ export function decideRecovery(
880
1349
  for (const [, list] of byId) {
881
1350
  const first = list[0]!
882
1351
  if (first.tool !== "delegate_task" || !first.childSessionId) continue
883
- const term = list.find((r) => r.state === "committed" || r.state === "failed")
1352
+ const term = list.find((r) => isTerminalJournalState(r.state))
884
1353
  if (term?.state === "committed" && covered(term)) coveredChild.add(first.childSessionId)
885
1354
  }
886
1355
  // Gap seq = kemungkinan penulis ganda/hilang (peringatan, bukan blokir).
@@ -893,7 +1362,14 @@ export function decideRecovery(
893
1362
  break
894
1363
  }
895
1364
  }
896
- const stats = { pending: 0, failed: 0, committed: 0, finalized: 0, markers: undoRedoCount }
1365
+ const stats = {
1366
+ pending: 0,
1367
+ failed: 0,
1368
+ committed: 0,
1369
+ unknown: 0,
1370
+ finalized: 0,
1371
+ markers: undoRedoCount,
1372
+ }
897
1373
  const attention: AttentionItem[] = []
898
1374
  const stitched: { id: string; tool: string; turn?: number | null }[] = []
899
1375
  const remoteVerify: AttentionItem[] = []
@@ -901,7 +1377,7 @@ export function decideRecovery(
901
1377
  for (const [, list] of [...byId.entries()].sort((a, b) => a[1][0]!.seq - b[1][0]!.seq)) {
902
1378
  const first = list[0]!
903
1379
  if (list.length > 1) {
904
- const terminals = list.filter((r) => r.state === "committed" || r.state === "failed")
1380
+ const terminals = list.filter((r) => isTerminalJournalState(r.state))
905
1381
  if (terminals.length > 1) {
906
1382
  warnings.push(
907
1383
  `journal id duplikat ${first.id} (${terminals.length} terminal) — pakai yang pertama`,
@@ -912,7 +1388,7 @@ export function decideRecovery(
912
1388
  warnings.push(`journal id duplikat ${first.id} — abaikan tulisan basi`)
913
1389
  }
914
1390
  }
915
- const eff = list.find((r) => r.state === "committed" || r.state === "failed") ?? first
1391
+ const eff = list.find((r) => isTerminalJournalState(r.state)) ?? first
916
1392
  if (!eff.state || eff.state === "pending") {
917
1393
  // Superseded = mutasi sama berhasil belakangan = bukti verifikasi
918
1394
  // implisit (sweep akan membuangnya). Jangan nagih yang sudah terjawab.
@@ -928,6 +1404,18 @@ export function decideRecovery(
928
1404
  attention.push(toItem(first, "pending"))
929
1405
  continue
930
1406
  }
1407
+ if (eff.state === "unknown") {
1408
+ // [Fase 2 / LOOP-INV-07] Terminal ambigu SELALU butuh verifikasi, bahkan
1409
+ // bila sudah ter-cover finalize: finalize membuktikan record durable,
1410
+ // bukan membuktikan efek terjadi/tidak. Menyembunyikannya = auto-retry
1411
+ // buta pada perintah yang mungkin sudah setengah berjalan.
1412
+ stats.unknown += 1
1413
+ warnings.push(
1414
+ `journal ${first.id} (${first.tool}) berakhir UNKNOWN — efek belum dapat dipastikan; verifikasi sebelum mengulang`,
1415
+ )
1416
+ attention.push(toItem(first, "unknown"))
1417
+ continue
1418
+ }
931
1419
  if (eff.state === "failed") {
932
1420
  stats.failed += 1
933
1421
  if (covered(first)) {
@@ -983,7 +1471,7 @@ export function decideRecovery(
983
1471
  const shown = attention.slice(0, maxItems)
984
1472
  if (shown.length > 0) {
985
1473
  blocks.push(
986
- "MUTASI TAK-PASTI (pending/failed) — verifikasi SEBELUM mengulang; DILARANG redo buta:",
1474
+ "MUTASI TAK-PASTI (pending/failed/unknown) — verifikasi SEBELUM mengulang; DILARANG redo buta:",
987
1475
  ...shown.map(
988
1476
  (a) =>
989
1477
  `- [seq ${a.seq}] ${a.tool} (${a.state})${a.paths.length ? ` paths: ${a.paths.join(", ")}` : " (tanpa path — diff workspace vs checkpoint)"}${a.childSessionId ? ` child: ${a.childSessionId}` : ""}`,
@@ -1021,7 +1509,7 @@ export function decideRecovery(
1021
1509
  }
1022
1510
  }
1023
1511
 
1024
- function toItem(first: JournalRecord, state: "pending" | "committed" | "failed"): AttentionItem {
1512
+ function toItem(first: JournalRecord, state: JournalState): AttentionItem {
1025
1513
  return {
1026
1514
  id: first.id,
1027
1515
  seq: first.seq,
@@ -1048,7 +1536,7 @@ interface SessionLike {
1048
1536
  interface ExecutionEvent {
1049
1537
  execution?: {
1050
1538
  call?: { name?: unknown; args?: unknown; id?: unknown }
1051
- result?: { isError?: unknown }
1539
+ result?: { isError?: unknown; content?: unknown }
1052
1540
  }
1053
1541
  /** Ditandai task.ts saat event child di-forward ke bus parent: catat di
1054
1542
  * jurnal ANAK saja (bus asal), bukan ganda di parent. Checkpoint, trace,
@@ -1060,6 +1548,21 @@ interface ExecutionEvent {
1060
1548
  * Pasang jurnal pada sesi apa pun (parent maupun anak). Total: kegagalan
1061
1549
  * I/O jurnal tak pernah melempar ke bus turn (degraded-loud).
1062
1550
  */
1551
+ export interface MutationJournalHandle {
1552
+ /**
1553
+ * [Fase 1] Tulis record intent dan tunggu sampai durable. Dipanggil
1554
+ * SEBELUM tool dieksekusi. No-op untuk tool yang tak dijurnal (read-only,
1555
+ * NO_AUTO_JOURNAL, atau sudah dicakup jalur canonical).
1556
+ */
1557
+ preflightIntent(call: { id: string; name: string; args: unknown }): Promise<void>
1558
+ /**
1559
+ * [Fase 1] Tunggu seluruh penulisan terminal yang masih berjalan selesai.
1560
+ * Dipanggil composition root sebelum turn dinyatakan selesai, sehingga
1561
+ * "selesai" tidak pernah mendahului bukti.
1562
+ */
1563
+ flushPending(): Promise<void>
1564
+ }
1565
+
1063
1566
  export function attachMutationJournal(
1064
1567
  session: SessionLike,
1065
1568
  opts: {
@@ -1068,12 +1571,24 @@ export function attachMutationJournal(
1068
1571
  childOf?: string
1069
1572
  /**
1070
1573
  * Fase 4 V2.1: kabar terminal committed (paths+journalSeq) → composition
1071
- * root memancarkan file.changed (receipt). Opsional — tanpa hook, jurnal
1072
- * tetap berjalan seperti dulu.
1574
+ * root memancarkan file.changed (receipt paths+journalSeq) ke adapter.
1575
+ * Opsional — tanpa hook, jurnal tetap berjalan seperti dulu.
1576
+ */
1577
+ onCommitted?: (info: {
1578
+ toolCallId: string
1579
+ paths: string[]
1580
+ journalSeq: number
1581
+ sessionId: string
1582
+ turnId?: number
1583
+ }) => void
1584
+ /**
1585
+ * P2.10 canonical mode: registry tools covered by an awaited wrapper
1586
+ * already wrote one intent/terminal pair. Event fallback stays only for
1587
+ * special paths and uncovered tools, so production has no double evidence.
1073
1588
  */
1074
- onCommitted?: (info: { toolCallId: string; paths: string[]; journalSeq: number }) => void
1589
+ evidenceMode?: "events" | "canonical"
1075
1590
  },
1076
- ): void {
1591
+ ): MutationJournalHandle {
1077
1592
  const root = resolve(opts.cwd ?? process.cwd())
1078
1593
  // Eager creation (AUDIT #01E §1): file jurnal dibuat saat wiring dipasang
1079
1594
  // — SEBELUM mutasi pertama — agar ABSENT vs EMPTY dapat dibedakan saat
@@ -1104,6 +1619,14 @@ export function attachMutationJournal(
1104
1619
  // tak boleh saling menimpa: completed mengambil pasangan TERTUA yang belum
1105
1620
  // berpasangan. Map-overwrite = terminal salah pasangan = pending hantu.
1106
1621
  const inflight = new Map<string, Promise<JournalRecord>[]>()
1622
+ // [Fase 1 / LOOP-INV-03] toolCallId yang intent-nya sudah ditulis oleh
1623
+ // PRE-FLIGHT (jalur awaited sebelum efek). Listener `execution:started`
1624
+ // melewatkannya supaya satu efek tidak menghasilkan dua record intent.
1625
+ const preflighted = new Set<string>()
1626
+ // [Fase 1 / LOOP-INV-03] Terminal yang masih menulis. `execution:completed`
1627
+ // adalah event SINKRON, sedangkan append terminal async; tanpa daftar ini
1628
+ // turn bisa dinyatakan selesai saat bukti terminal masih di jalan.
1629
+ const pendingTerminals = new Set<Promise<void>>()
1107
1630
  const turnOf = (): number | null => {
1108
1631
  try {
1109
1632
  const n = session.state?.turnCount
@@ -1112,30 +1635,53 @@ export function attachMutationJournal(
1112
1635
  return null
1113
1636
  }
1114
1637
  }
1638
+ /**
1639
+ * [Fase 1] Satu-satunya tempat membangun input intent, dipakai bersama oleh
1640
+ * listener event (fallback) dan pre-flight (jalur utama). Duplikasi di sini
1641
+ * akan membuat dua jalur menulis bentuk record yang berbeda.
1642
+ */
1643
+ const intentInputFor = (
1644
+ name: string,
1645
+ args: Record<string, unknown>,
1646
+ hashes: { preTargetHash?: string | null; postTargetHash?: string | null } = {},
1647
+ ) => {
1648
+ const base = base_of(name)
1649
+ return {
1650
+ session: opts.sessionId,
1651
+ ...(opts.childOf ? { childOf: opts.childOf } : {}),
1652
+ turn: turnOf(),
1653
+ tool: name,
1654
+ ...(base === "mcp_call" ? { remote: true as const } : {}),
1655
+ ...(base === "code_run" ? { backend: process.env.MINICODE_SANDBOX || "none" } : {}),
1656
+ cwd: root,
1657
+ paths: verifyPaths(base, args, root),
1658
+ argsHash: hashArgs(args),
1659
+ ...(hashes.preTargetHash !== undefined ? { preTargetHash: hashes.preTargetHash } : {}),
1660
+ ...(hashes.postTargetHash !== undefined ? { postTargetHash: hashes.postTargetHash } : {}),
1661
+ }
1662
+ }
1663
+ const shouldJournal = (name: string): boolean =>
1664
+ name !== "" &&
1665
+ !NO_AUTO_JOURNAL.has(name) &&
1666
+ isMutationTool(name) &&
1667
+ !(opts.evidenceMode === "canonical" && isCanonicalEvidenceCovered(name))
1115
1668
  session.events.on("execution:started", (e) => {
1116
1669
  const ev = e as unknown as ExecutionEvent
1117
1670
  // Forward dari child: ground truth ada di jurnal anak (bus asal).
1118
1671
  // Mencatatnya juga di sini = bukti ganda (satu efek, dua id/sesi).
1119
1672
  if (ev.forwardedChild != null) return
1120
1673
  const name = typeof ev.execution?.call?.name === "string" ? ev.execution.call.name : ""
1121
- if (!name || NO_AUTO_JOURNAL.has(name) || !isMutationTool(name)) return
1674
+ if (!shouldJournal(name)) return
1122
1675
  const callId =
1123
1676
  typeof ev.execution?.call?.id === "string" ? (ev.execution.call.id as string) : ""
1124
- const base = isMcpToolName(name) ? "mcp_call" : name
1677
+ // [Fase 1 / LOOP-INV-03] Pre-flight sudah menulis intent untuk call ini
1678
+ // SEBELUM tool dieksekusi. Menulis lagi di sini = dua record untuk satu
1679
+ // efek, dan recovery akan melihat satu intent menggantung selamanya.
1680
+ if (callId !== "" && preflighted.has(callId)) return
1125
1681
  const args = (ev.execution?.call?.args ?? {}) as Record<string, unknown>
1126
1682
  // Daftarkan promise SEBELUM await: completed dijamin datang sesudah
1127
1683
  // started, dan kini pasti menunggu intent selesai dulu.
1128
- const intentP = appendMutationIntent({
1129
- session: opts.sessionId,
1130
- ...(opts.childOf ? { childOf: opts.childOf } : {}),
1131
- turn: turnOf(),
1132
- tool: name,
1133
- ...(base === "mcp_call" ? { remote: true as const } : {}),
1134
- ...(base === "code_run" ? { backend: process.env.MINICODE_SANDBOX || "none" } : {}),
1135
- cwd: root,
1136
- paths: verifyPaths(base, args, root),
1137
- argsHash: hashArgs(args),
1138
- })
1684
+ const intentP = appendMutationIntent(intentInputFor(name, args))
1139
1685
  if (callId) {
1140
1686
  const q = inflight.get(callId) ?? []
1141
1687
  q.push(
@@ -1151,12 +1697,12 @@ export function attachMutationJournal(
1151
1697
  })
1152
1698
  })
1153
1699
  session.events.on("execution:completed", (e) => {
1154
- void (async () => {
1700
+ const task = (async () => {
1155
1701
  try {
1156
1702
  const ev = e as unknown as ExecutionEvent
1157
1703
  if (ev.forwardedChild != null) return
1158
1704
  const name = typeof ev.execution?.call?.name === "string" ? ev.execution.call.name : ""
1159
- if (!name || NO_AUTO_JOURNAL.has(name) || !isMutationTool(name)) return
1705
+ if (!shouldJournal(name)) return
1160
1706
  const callId =
1161
1707
  typeof ev.execution?.call?.id === "string" ? (ev.execution.call.id as string) : ""
1162
1708
  const q = callId ? (inflight.get(callId) ?? []) : []
@@ -1165,7 +1711,13 @@ export function attachMutationJournal(
1165
1711
  // Tanpa pasangan intent (mis. intent gagal tulis / degraded): jangan
1166
1712
  // karang terminal yatim — biarkan absen (jalur advisory + warn).
1167
1713
  if (!found) return
1168
- const failed = ev.execution?.result?.isError === true
1714
+ const result = ev.execution?.result
1715
+ const failed = result?.isError === true
1716
+ // [Fase 2 / LOOP-INV-07] Hasil ber-tag UNKNOWN bukan "failed" biasa:
1717
+ // efeknya mungkin sudah terjadi. Terminal ditandai `unknown` supaya
1718
+ // recovery tidak pernah memperlakukannya sebagai aman-diulang.
1719
+ const outcomeTag = failed ? parseToolOutcomeTag(String(result?.content ?? "")) : null
1720
+ const state = outcomeTag ? "unknown" : failed ? "failed" : "committed"
1169
1721
  let note: string | undefined
1170
1722
  if (base_of(name) === "mcp_call") {
1171
1723
  const a = (ev.execution?.call?.args ?? {}) as Record<string, unknown>
@@ -1178,23 +1730,34 @@ export function attachMutationJournal(
1178
1730
  : ""
1179
1731
  if (srv || t) note = `${srv ? `${srv}.` : ""}${t}`
1180
1732
  }
1733
+ const outcome: JournalOutcome | undefined = outcomeTag
1734
+ ? {
1735
+ ...(note ? { note } : {}),
1736
+ uncertainty: "ambiguous-effect",
1737
+ ...(outcomeTag.reason === "TIMEOUT" ? { timeout: true as const } : {}),
1738
+ }
1739
+ : note
1740
+ ? { note }
1741
+ : undefined
1181
1742
  await appendMutationTerminal(
1182
1743
  opts.sessionId,
1183
1744
  root,
1184
1745
  found.id,
1185
1746
  found.seq,
1186
1747
  found.tool,
1187
- failed ? "failed" : "committed",
1188
- note ? { note } : undefined,
1748
+ state,
1749
+ outcome,
1189
1750
  )
1190
1751
  // Fase 4: kabar committed ke composition root (file.changed/receipt).
1191
1752
  // Gagal hook tak boleh menggagalkan jurnal (degraded-loud).
1192
- if (!failed && opts.onCommitted && callId) {
1753
+ if (state === "committed" && opts.onCommitted && callId) {
1193
1754
  try {
1194
1755
  opts.onCommitted({
1195
1756
  toolCallId: callId,
1196
1757
  paths: found.paths ?? [],
1197
1758
  journalSeq: found.seq,
1759
+ sessionId: opts.sessionId,
1760
+ ...(found.turn != null ? { turnId: found.turn } : {}),
1198
1761
  })
1199
1762
  } catch {}
1200
1763
  }
@@ -1202,13 +1765,105 @@ export function attachMutationJournal(
1202
1765
  process.stderr.write(`[warn] journal: terminal failed: ${(err as Error).message}\n`)
1203
1766
  }
1204
1767
  })()
1768
+ // [Fase 1] Daftarkan supaya composition root bisa MENUNGGU terminal selesai
1769
+ // sebelum turn dinyatakan selesai. Body di atas menangkap semua error, jadi
1770
+ // promise ini tidak pernah reject; `finally` hanya membersihkan daftar.
1771
+ pendingTerminals.add(task)
1772
+ void task.finally(() => pendingTerminals.delete(task)).catch(() => {})
1205
1773
  })
1774
+
1775
+ /**
1776
+ * [Fase 1 / LOOP-INV-03, LOOP-INV-04] Handle untuk composition root.
1777
+ *
1778
+ * `preflightIntent` menulis record intent dan MENUNGGU-nya sampai durable.
1779
+ * Pemanggil (`src/app/session.ts` lewat `beforeToolEffect`, dipasang
1780
+ * `cli/setup.ts`) menjalankannya SEBELUM tool dieksekusi, sehingga
1781
+ * "durability-before-effect" menjadi urutan yang benar-benar di-await, bukan
1782
+ * harapan pada scheduling microtask.
1783
+ *
1784
+ * Idempoten per `toolCallId`: panggilan kedua (mis. retry hook) tidak
1785
+ * menulis record kedua, dan listener `execution:started` melewatkan id yang
1786
+ * sudah di-preflight.
1787
+ */
1788
+ return {
1789
+ async flushPending(): Promise<void> {
1790
+ // Tunggu sampai TIDAK ADA terminal tertunda. Loop karena penulisan baru
1791
+ // bisa lahir selama await (batch berurutan); sekali kosong, selesai.
1792
+ while (pendingTerminals.size > 0) {
1793
+ await Promise.allSettled([...pendingTerminals])
1794
+ }
1795
+ },
1796
+ async preflightIntent(call: { id: string; name: string; args: unknown }): Promise<void> {
1797
+ const name = typeof call.name === "string" ? call.name : ""
1798
+ if (!shouldJournal(name)) return
1799
+ const callId = typeof call.id === "string" ? call.id : ""
1800
+ if (callId === "" || preflighted.has(callId)) return
1801
+ // Tandai SEBELUM await: dua preflight paralel untuk id yang sama tidak
1802
+ // boleh sama-sama menulis.
1803
+ preflighted.add(callId)
1804
+ const args = (call.args ?? {}) as Record<string, unknown>
1805
+ // [Fase 2 / LOOP-G06] Hash pra-efek dihitung SEBELUM intent ditulis,
1806
+ // sehingga record intent sudah membawa bukti yang bisa direkonsiliasi
1807
+ // setelah crash. Kegagalan baca = field absen (UNKNOWN saat reconcile).
1808
+ const hashes = await targetHashesFor(name, args, root)
1809
+ const p = appendMutationIntent(intentInputFor(name, args, hashes))
1810
+ const q = inflight.get(callId) ?? []
1811
+ q.push(p)
1812
+ inflight.set(callId, q)
1813
+ try {
1814
+ await p
1815
+ } catch (err) {
1816
+ // Durabilitas gagal: jangan biarkan efek berjalan (pemanggil akan
1817
+ // menolak tool). Bersihkan state supaya tidak ada intent hantu yang
1818
+ // ditunggu terminal yang tak akan pernah datang.
1819
+ preflighted.delete(callId)
1820
+ const idx = q.indexOf(p)
1821
+ if (idx !== -1) q.splice(idx, 1)
1822
+ if (q.length === 0) inflight.delete(callId)
1823
+ throw err
1824
+ }
1825
+ },
1826
+ }
1206
1827
  }
1207
1828
 
1208
1829
  function base_of(name: string): string {
1209
1830
  return isMcpToolName(name) ? "mcp_call" : name
1210
1831
  }
1211
1832
 
1833
+ /**
1834
+ * Record mutasi dengan turn lebih baru dari turn bukti (P10.1.1, freshness
1835
+ * bukti completion). Murni baca: tanpa tulis/ubah/compact jurnal.
1836
+ *
1837
+ * Aturan (disetujui owner): relevan = klasifikasi `isMutationTool` (tulis,
1838
+ * bash, delegasi, memori, MCP, tak-dikenal-fail-closed); record turn null
1839
+ * (legacy) DIKECUALIKAN agar sesi lama tak terkunci permanen; state record
1840
+ * (pending/committed/failed) tak membedakan — upaya mutasi yang tercatat
1841
+ * sudah cukup untuk meragukan bukti lama. Gagal baca DILEMPAR ke pemanggil
1842
+ * (konteks gate: pemanggil wajib fail-closed); bedakan dari pembaca display
1843
+ * (committedDelegatesSince) yang gagal-lembut.
1844
+ */
1845
+ export async function mutationsSinceTurn(
1846
+ sessionId: string,
1847
+ cwd: string | undefined,
1848
+ evidenceTurn: number,
1849
+ ): Promise<readonly JournalRecord[]> {
1850
+ const loaded = await loadJournal(sessionId, cwd)
1851
+ // Jurnal tak-terbaca/korup = buktinya sendiri tak bisa diaudit: tolak
1852
+ // diam-diam BUKAN pilihan — lempar agar pemanggil (gate) fail-closed.
1853
+ // `absent` (belum ada berkas) dan `empty` aman: nol record = nol mutasi.
1854
+ if (loaded.status !== "absent" && loaded.status !== "empty" && loaded.status !== "valid") {
1855
+ throw new Error(`journal unreadable for freshness check (status: ${loaded.status})`)
1856
+ }
1857
+ const { records } = loaded
1858
+ return records.filter(
1859
+ (r) =>
1860
+ typeof r.turn === "number" &&
1861
+ r.turn > evidenceTurn &&
1862
+ typeof r.tool === "string" &&
1863
+ isMutationTool(r.tool),
1864
+ )
1865
+ }
1866
+
1212
1867
  // ── Resume: muat jurnal (+anak) → putuskan ──
1213
1868
 
1214
1869
  export interface RecoveryInput {
@@ -1222,11 +1877,44 @@ export interface RecoveryInput {
1222
1877
  * anak tetap ada walau riwayat bersih"). Kembalikan childSessionId + seq + ts.
1223
1878
  * Murni baca; tak pernah melempar (gagal baca = [] + warn stderr).
1224
1879
  */
1880
+ export interface CommittedDelegate {
1881
+ readonly childSessionId: string
1882
+ readonly seq: number
1883
+ readonly ts: number
1884
+ /**
1885
+ * Observasi amplop anak (P9.2.2.1, display-only): disalin dari terminal
1886
+ * record yang sama — BUKAN bacaan jurnal anak baru. Absen = record
1887
+ * legacy/rusak → pemanggil wajib fallback baris legacy.
1888
+ */
1889
+ readonly childStatus?: ChildStatus
1890
+ readonly resultSummary?: string
1891
+ readonly truncated?: boolean
1892
+ }
1893
+
1894
+ /** Status amplop yang boleh tampil (di luar ini = rusak → absen). */
1895
+ const DISPLAYABLE_CHILD_STATUS: ReadonlySet<string> = new Set([
1896
+ "returned",
1897
+ "timeout",
1898
+ "aborted",
1899
+ "max_steps_exceeded",
1900
+ "error",
1901
+ "failed_to_start",
1902
+ ])
1903
+
1904
+ /**
1905
+ * Predikat bersama untuk status tampil (dipakai pembaca committedDelegatesSince
1906
+ * DAN formatter cli/recovery-warning.ts — satu sumber kebenaran agar status
1907
+ * asing tak pernah menjadi teks status menyesatkan di lapisan mana pun).
1908
+ */
1909
+ export function isDisplayableChildStatus(value: unknown): value is ChildStatus {
1910
+ return typeof value === "string" && DISPLAYABLE_CHILD_STATUS.has(value)
1911
+ }
1912
+
1225
1913
  export async function committedDelegatesSince(
1226
1914
  sessionId: string,
1227
1915
  cwd: string | undefined,
1228
1916
  sinceTs: number,
1229
- ): Promise<{ childSessionId: string; seq: number; ts: number }[]> {
1917
+ ): Promise<CommittedDelegate[]> {
1230
1918
  try {
1231
1919
  const { records } = await loadJournal(sessionId, cwd)
1232
1920
  // Tautan dari terminal, fallback ke intent se-id (jurnal lama).
@@ -1236,13 +1924,28 @@ export async function committedDelegatesSince(
1236
1924
  intentChild.set(r.id, r.childSessionId)
1237
1925
  }
1238
1926
  }
1239
- const out: { childSessionId: string; seq: number; ts: number }[] = []
1927
+ const out: CommittedDelegate[] = []
1240
1928
  for (const r of records) {
1241
1929
  if (r.tool !== "delegate_task" || r.state !== "committed") continue
1242
1930
  const cid = r.childSessionId ?? intentChild.get(r.id)
1243
1931
  if (!cid) continue
1244
1932
  if (typeof r.ts !== "number" || r.ts < sinceTs) continue
1245
- out.push({ childSessionId: cid, seq: r.seq, ts: r.ts })
1933
+ // Amplop usang/rusak = absen (fallback baris legacy di pemanggil, tak
1934
+ // pernah gagal): childStatus harus dikenal (status asing tak boleh
1935
+ // jadi teks status menyesatkan) dan ringkasan harus string.
1936
+ const env = r.outcome?.childResult
1937
+ const envelope =
1938
+ env !== null &&
1939
+ typeof env === "object" &&
1940
+ isDisplayableChildStatus(env.childStatus) &&
1941
+ typeof env.resultSummary === "string"
1942
+ ? {
1943
+ childStatus: env.childStatus as ChildStatus,
1944
+ resultSummary: env.resultSummary,
1945
+ ...(env.truncated === true ? { truncated: true as const } : {}),
1946
+ }
1947
+ : {}
1948
+ out.push({ childSessionId: cid, seq: r.seq, ts: r.ts, ...envelope })
1246
1949
  }
1247
1950
  return out.sort((a, b) => a.seq - b.seq)
1248
1951
  } catch (e) {
@@ -1363,7 +2066,7 @@ export async function planRecoveryForSession(
1363
2066
  directive: null,
1364
2067
  warnings: [`recovery journal gagal dimuat: ${(e as Error).message} — lanjut jalur advisory`],
1365
2068
  clean: false,
1366
- stats: { pending: 0, failed: 0, committed: 0, finalized: 0, markers: 0 },
2069
+ stats: { pending: 0, failed: 0, committed: 0, unknown: 0, finalized: 0, markers: 0 },
1367
2070
  }
1368
2071
  }
1369
2072
  }