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
package/src/tools/todo.ts CHANGED
@@ -3,39 +3,255 @@ import { resolve } from "node:path"
3
3
  import type { Tool } from "#minicore"
4
4
  import { LIMITS } from "../constants.ts"
5
5
  import { atomicWriteText } from "../lib/atomic-write.ts"
6
+ import { sanitizeSessionPart } from "../lib/session-id.ts"
7
+ import { isJournalHealthy, loadJournal, mutationsSinceTurn } from "../session/journal.ts"
8
+ import {
9
+ checkWorkspaceIntegrity,
10
+ collectModifiedFilesFromJournal,
11
+ detectEvaluationTampering,
12
+ } from "../session/verification.ts"
13
+ import { type CanonicalAssignmentTable, encodeCanonicalAssignments } from "../task/assignment.ts"
14
+ import { isTaskId, TaskError } from "../task/model.ts"
15
+ import { TaskStore } from "../task/store.ts"
16
+ import { hasCanonicalIdentity, hasCanonicalTasks, synchronizeCanonicalTasks } from "../task/sync.ts"
6
17
 
7
18
  // Todo list per sesi — state eksplisit untuk task multi-langkah.
8
19
  // Tanpa ini agent tidak punya tempat menyimpan rencana antar step, sehingga
9
20
  // pada task panjang ia lupa langkah yang belum dikerjakan.
10
21
 
11
- export type TodoStatus = "pending" | "in_progress" | "completed" | "cancelled"
22
+ export type TodoStatus = "pending" | "in_progress" | "completed" | "cancelled" | "blocked"
12
23
 
13
24
  export interface TodoItem {
14
25
  content: string
15
26
  status: TodoStatus
27
+ /** Alasan `blocked` - WAJIB ada kalau status=blocked (INV: blocker harus
28
+ * bisa dijelaskan). Tidak ada di schema tool: diisi runtime dari bukti. */
29
+ blockedReason?: string
30
+ /**
31
+ * PHASE 4A.1 - canonical task identity, OPTIONAL.
32
+ *
33
+ * This field only TRANSPORTS an id that already exists. The protocol layer
34
+ * never mints, derives, rewrites or infers one: an id that is absent stays
35
+ * absent, and an id that is present is passed through byte-for-byte. The sole
36
+ * allocator remains `TaskStore`.
37
+ *
38
+ * Validity is checked with the one canonical guard, `isTaskId` from
39
+ * `src/task/model.ts` - there is deliberately no second regex in this file.
40
+ */
41
+ taskId?: string
16
42
  }
17
43
 
18
- const STATUSES: TodoStatus[] = ["pending", "in_progress", "completed", "cancelled"]
44
+ const STATUSES: TodoStatus[] = ["pending", "in_progress", "completed", "cancelled", "blocked"]
19
45
 
20
46
  const GLYPH: Record<TodoStatus, string> = {
21
47
  pending: "[ ]",
22
48
  in_progress: "[~]",
23
49
  completed: "[x]",
24
50
  cancelled: "[-]",
51
+ blocked: "[!]",
52
+ }
53
+
54
+ // ── Completion evidence (INV-003 / INV-009) ──────────────────────────────────
55
+ // "Agent bilang selesai" BUKAN bukti. Kebijakan ini bisa disuntik: composition
56
+ // root menyuntikkan sumber bukti (di CLI: hasil verify terakhir); tanpa
57
+ // injeksi, default `unverified` — completion tetap diizinkan, tapi statusnya
58
+ // tercatat sebagai belum diverifikasi, bukan diam-diam dianggap sah.
59
+ //
60
+ // Fail-closed hanya di arah yang berbahaya: `failed` MENOLAK `completed`.
61
+ // Menolak tanpa bukti (default) akan mematikan pemakaian normal yang tidak
62
+ // menjalankan verify, jadi itu tidak dilakukan.
63
+ export type CompletionVerdict = "unverified" | "passed" | "failed" | "stale"
64
+
65
+ export interface CompletionEvidence {
66
+ verdict: CompletionVerdict
67
+ detail?: string
68
+ /**
69
+ * P10.1.1: turn yang diobservasi bukti ini (diisi produsen verify,
70
+ * yaitu runner `--verify`). Absen/null = bukti tanpa ikatan turn
71
+ * (bukti lama/test) → diperlakukan `unverified` untuk freshness, BUKAN
72
+ * passed: tak ada ikatan, tak ada klaim kesegaran.
73
+ */
74
+ turn?: number | null
75
+ /**
76
+ * [Fase 3 / LOOP-INV-12, LOOP-G20] Mode wajib verifikasi: bila `true` dan
77
+ * bukti masih `unverified`, klaim `completed` ditahan di `VERIFYING` /
78
+ * diturunkan — tidak diloloskan ke `COMPLETED` secara fail-open.
79
+ */
80
+ requireVerified?: boolean
81
+ /** Kode keluar proses verifier (0 = lulus). */
82
+ exitCode?: number | null
83
+ /** Ringkasan hasil verifier untuk disimpan ke `evidence_json`. */
84
+ summary?: string
85
+ }
86
+
87
+ const UNVERIFIED: CompletionEvidence = { verdict: "unverified" }
88
+ let completionEvidence: () => CompletionEvidence = () => UNVERIFIED
89
+
90
+ /** Dipanggil composition root (cli/setup.ts). Tanpa ini: `unverified`. */
91
+ export function setCompletionEvidence(fn: () => CompletionEvidence): void {
92
+ completionEvidence = fn
93
+ }
94
+
95
+ /** Kembalikan ke default (seam uji / isolasi antar test file). */
96
+ export function clearCompletionEvidence(): void {
97
+ completionEvidence = () => UNVERIFIED
98
+ }
99
+
100
+ export function currentCompletionEvidence(): CompletionEvidence {
101
+ try {
102
+ return completionEvidence() ?? UNVERIFIED
103
+ } catch {
104
+ // Sumber bukti yang melempar TIDAK boleh menuntaskan task diam-diam.
105
+ return { verdict: "failed", detail: "completion evidence source failed" }
106
+ }
107
+ }
108
+
109
+ /**
110
+ * Selesaikan bukti completion terhadap kesegaran mutasi (P10.1.1).
111
+ * Dipakai jalur tulis `todo_write` (async) — BUKAN di dalam `normalizeTodos`
112
+ * yang kontraknya murni tanpa I/O.
113
+ *
114
+ * - `passed` + turn + tanpa mutasi lebih baru → `passed` apa adanya.
115
+ * - `passed` + mutasi lebih baru → `stale` (tolak klaim; label dipertahankan).
116
+ * - `passed` tanpa turn → `unverified` (tak ada ikatan = perilaku legacy,
117
+ * izinkan-tanpa-klaim; BUKAN passed).
118
+ * - Gagal baca jurnal → `failed` (fail-closed, konsisten dengan
119
+ * `currentCompletionEvidence`: ketidakpastian kesegaran tak boleh
120
+ * mengotorisasi completion).
121
+ * - Verdict lain (`failed`/`unverified`) diteruskan tanpa disentuh.
122
+ */
123
+ export async function resolveFreshEvidence(
124
+ sessionId: string,
125
+ cwd: string,
126
+ ): Promise<CompletionEvidence> {
127
+ const base = currentCompletionEvidence()
128
+ if (base.verdict === "failed" || base.verdict === "stale") return base
129
+ if (base.verdict === "passed" && typeof base.turn !== "number") {
130
+ return base.requireVerified
131
+ ? { verdict: "unverified", requireVerified: true }
132
+ : { verdict: "unverified" }
133
+ }
134
+ if (base.verdict === "unverified") {
135
+ // [Fase 3 / LOOP-INV-12] Tier 1 integrity check pada file yang benar-benar
136
+ // telah di-commit ke jurnal sesi ini. Best-effort pada jurnal absent/empty/
137
+ // corrupt agar kompatibilitas legacy turn-less & sesi tanpa jurnal tetap utuh.
138
+ const loaded = await loadJournal(sessionId, cwd).catch(() => null)
139
+ if (loaded?.status === "valid") {
140
+ const modified = collectModifiedFilesFromJournal(loaded.records)
141
+ if (modified.length > 0) {
142
+ const integrity = await checkWorkspaceIntegrity(modified, cwd)
143
+ if (!integrity.ok) {
144
+ return {
145
+ verdict: "failed",
146
+ detail: integrity.summary,
147
+ ...(base.requireVerified ? { requireVerified: true } : {}),
148
+ }
149
+ }
150
+ // [Fase 6A / ACE-02] Tamper guard fail-closed: evaluator/gate yang
151
+ // disentuh membuat SEMUA klaim completion tak bisa dipercaya.
152
+ const tamper = await detectEvaluationTampering(modified, cwd)
153
+ if (tamper.tampered) {
154
+ return {
155
+ verdict: "failed",
156
+ detail: `EVALUATOR_TAMPER_ATTEMPT: ${tamper.reason}`,
157
+ ...(base.requireVerified ? { requireVerified: true } : {}),
158
+ }
159
+ }
160
+ }
161
+ }
162
+ return base
163
+ }
164
+ // P10.1.2: jurnal degraded (kegagalan tulis intent — jalur produksi
165
+ // "intent append gagal" pada tool event-path seperti MCP dotted) berarti
166
+ // riwayat mutasi TAK LENGKAP: kesegaran tak bisa dipercaya → fail-closed
167
+ // `failed`, BUKAN passed palsu-fresh. `isJournalHealthy` melaporkan `true`
168
+ // untuk sesi baru/sehat (default `?? true` — semantics dipin test C2) dan
169
+ // `false` hanya bila path tulis jurnal SESI INI pernah gagal, jadi cek ini
170
+ // tak mengubah sesi sehat.
171
+ if (!isJournalHealthy(sessionId, cwd)) {
172
+ return {
173
+ verdict: "failed",
174
+ detail: "journal degraded — freshness unverifiable; re-verify, then re-claim",
175
+ }
176
+ }
177
+ let newer: readonly unknown[]
178
+ try {
179
+ newer = await mutationsSinceTurn(sessionId, cwd, base.turn!)
180
+ } catch (e) {
181
+ return {
182
+ verdict: "failed",
183
+ detail: `freshness check failed: ${String((e as Error)?.message ?? e).slice(0, 200)}`,
184
+ }
185
+ }
186
+ if (newer.length > 0) {
187
+ return {
188
+ verdict: "stale",
189
+ detail:
190
+ `verification stale — ${newer.length} mutation(s) since turn ${base.turn}; ` +
191
+ `re-verify, then re-claim`,
192
+ }
193
+ }
194
+ // [Fase 3 / LOOP-INV-12, LOOP-G21] Tier 1 integrity check sebelum mengizinkan
195
+ // bukti `passed` mengunci `COMPLETED`.
196
+ const loaded = await loadJournal(sessionId, cwd).catch(() => null)
197
+ if (loaded?.status === "valid") {
198
+ const modified = collectModifiedFilesFromJournal(loaded.records)
199
+ if (modified.length > 0) {
200
+ const integrity = await checkWorkspaceIntegrity(modified, cwd)
201
+ if (!integrity.ok) {
202
+ return {
203
+ verdict: "failed",
204
+ detail: integrity.summary,
205
+ ...(base.requireVerified ? { requireVerified: true } : {}),
206
+ }
207
+ }
208
+ // [Fase 6A / ACE-02] Tamper guard: bukti `passed` batal bila evaluator
209
+ // atau test diubah untuk meloloskan verifikasi.
210
+ const tamper = await detectEvaluationTampering(modified, cwd)
211
+ if (tamper.tampered) {
212
+ return {
213
+ verdict: "failed",
214
+ detail: `EVALUATOR_TAMPER_ATTEMPT: ${tamper.reason}`,
215
+ ...(base.requireVerified ? { requireVerified: true } : {}),
216
+ }
217
+ }
218
+ }
219
+ }
220
+ return base
25
221
  }
26
222
 
27
223
  function sanitizeTodoId(id: string): string {
224
+ return sanitizeSessionPart(id)
225
+ }
226
+
227
+ /**
228
+ * OLD mapping (pre-N2). No longer the source of truth — kept ONLY so files
229
+ * already written to disk stay reachable for one compatibility version.
230
+ * `a/b` used to become `a_b.json`; under the canonical mapping that file is
231
+ * `a-b.json`, so `loadTodos` must try both. Once the compatibility window
232
+ * closes, this function is deleted.
233
+ */
234
+ function legacySanitizeTodoId(id: string): string {
28
235
  return id.replace(/[^A-Za-z0-9._-]/g, "_").slice(0, 64) || "default"
29
236
  }
30
237
 
238
+ /** Todo filename. Canonical (N2) — the source of truth for all writes. */
31
239
  function todoPath(sessionId: string, cwd: string): string {
32
- const safe = sanitizeTodoId(sessionId)
33
- return resolve(cwd, ".minicode", "todos", `${safe}.json`)
240
+ return resolve(cwd, ".minicode", "todos", `${sanitizeTodoId(sessionId)}.json`)
241
+ }
242
+
243
+ /** Legacy filename. Read fallback only; never written. */
244
+ function legacyTodoPath(sessionId: string, cwd: string): string {
245
+ return resolve(cwd, ".minicode", "todos", `${legacySanitizeTodoId(sessionId)}.json`)
34
246
  }
35
247
 
36
248
  function planPath(sessionId: string, cwd: string): string {
37
- const safe = sanitizeTodoId(sessionId)
38
- return resolve(cwd, ".minicode", "plans", `${safe}.md`)
249
+ return resolve(cwd, ".minicode", "plans", `${sanitizeTodoId(sessionId)}.md`)
250
+ }
251
+
252
+ /** Same as `legacyTodoPath`, for the plan snapshot. */
253
+ function legacyPlanPath(sessionId: string, cwd: string): string {
254
+ return resolve(cwd, ".minicode", "plans", `${legacySanitizeTodoId(sessionId)}.md`)
39
255
  }
40
256
 
41
257
  // Audit #13 chain 28: todo + plan snapshot adalah state milik sesi —
@@ -43,51 +259,222 @@ function planPath(sessionId: string, cwd: string): string {
43
259
  // residual reachable pasca-hapus. Best-effort (kegagalan tak menggagalkan hapus).
44
260
  export async function deleteTodoFiles(sessionId: string, cwd: string): Promise<void> {
45
261
  const { rm } = await import("node:fs/promises")
46
- await rm(todoPath(sessionId, cwd), { force: true }).catch(() => {})
47
- await rm(planPath(sessionId, cwd), { force: true }).catch(() => {})
262
+ // Both are removed: canonical (N2) and legacy, because old files can still
263
+ // exist in a workspace that was never rewritten after the upgrade.
264
+ for (const p of [
265
+ todoPath(sessionId, cwd),
266
+ legacyTodoPath(sessionId, cwd),
267
+ planPath(sessionId, cwd),
268
+ legacyPlanPath(sessionId, cwd),
269
+ ]) {
270
+ await rm(p, { force: true }).catch(() => {})
271
+ }
48
272
  }
49
273
 
50
- /** Sanitasi + batasi daftar. Diekspor untuk test. */
51
- export function normalizeTodos(input: unknown): TodoItem[] {
274
+ /** Sanitasi + batasi daftar + terapkan kebijakan completion. Diekspor untuk test.
275
+ *
276
+ * `evidence` default = `currentCompletionEvidence()` (sumber yang disuntik
277
+ * composition root). Pemanggil yang sudah punya bukti bisa mengoper nilainya
278
+ * eksplisit supaya deterministik di test.
279
+ */
280
+ /**
281
+ * Terapkan kebijakan completion pada daftar yang sudah ternormalisasi.
282
+ *
283
+ * Murni (tanpa I/O) dan dipakai oleh DUA jalur agar aturan "completed butuh
284
+ * bukti" hanya ada di satu tempat:
285
+ * 1. `todo_write` (jalur tulis) - sebelum disimpan;
286
+ * 2. `reconcileCompletionEvidence` (jalur rekonsiliasi) - setelah verify
287
+ * selesai, karena verify sebuah turn berjalan SETELAH `todo_write`.
288
+ *
289
+ * Mengembalikan array BARU bila ada yang berubah, `null` bila tidak -
290
+ * pemanggil memakai ini untuk memutuskan apakah perlu menulis/menerbitkan
291
+ * event (idempoten: tidak ada event plan palsu saat tidak ada perubahan).
292
+ */
293
+ export function applyCompletionPolicy(
294
+ list: readonly TodoItem[],
295
+ evidence: CompletionEvidence,
296
+ opts?: { requireVerified?: boolean },
297
+ ): TodoItem[] | null {
298
+ const requireVerified = opts?.requireVerified === true || evidence.requireVerified === true
299
+ // `failed` DAN `stale` menolak `completed` — tapi labelnya dipertahankan
300
+ // berbeda: gagal uji vs bukti basi. Jangan samakan keduanya.
301
+ // [Fase 3 / LOOP-INV-12, LOOP-G20] Saat `requireVerified` aktif dan bukti
302
+ // masih `unverified`, klaim `completed` juga ditahan (tidak fail-open).
303
+ if (evidence.verdict === "failed" || evidence.verdict === "stale") {
304
+ const reason =
305
+ evidence.detail?.trim().slice(0, 300) ||
306
+ (evidence.verdict === "stale" ? "verification stale" : "verification failed")
307
+ if (!list.some((t) => t.status === "completed")) return null
308
+ return list.map((t) =>
309
+ t.status === "completed" ? { ...t, status: "blocked" as const, blockedReason: reason } : t,
310
+ )
311
+ }
312
+ if (requireVerified && evidence.verdict === "unverified") {
313
+ if (!list.some((t) => t.status === "completed")) return null
314
+ const reason =
315
+ evidence.detail?.trim().slice(0, 300) ||
316
+ "verification required: run verifier before marking completed"
317
+ return list.map((t) =>
318
+ t.status === "completed" ? { ...t, status: "blocked" as const, blockedReason: reason } : t,
319
+ )
320
+ }
321
+ return null
322
+ }
323
+
324
+ export function normalizeTodos(
325
+ input: unknown,
326
+ evidence?: CompletionEvidence,
327
+ opts?: { requireVerified?: boolean },
328
+ ): TodoItem[] {
52
329
  if (!Array.isArray(input)) throw new Error("todos must be an array")
330
+ const ev = evidence ?? currentCompletionEvidence()
53
331
  const out: TodoItem[] = []
54
332
  for (const raw of input.slice(0, LIMITS.TODO_MAX_ITEMS)) {
55
333
  if (!raw || typeof raw !== "object") continue
56
- const r = raw as { content?: unknown; status?: unknown }
334
+ const r = raw as {
335
+ content?: unknown
336
+ status?: unknown
337
+ blockedReason?: unknown
338
+ taskId?: unknown
339
+ }
57
340
  const content = String(r.content ?? "")
58
341
  .trim()
59
342
  .slice(0, LIMITS.TODO_CONTENT_MAX_CHARS)
60
343
  if (!content) continue
61
344
  const status = STATUSES.includes(r.status as TodoStatus) ? (r.status as TodoStatus) : "pending"
62
- out.push({ content, status })
345
+ // `blockedReason` HARUS ikut dibaca: tanpanya alasan blocker hilang
346
+ // tepat setelah restart (durable write, non-durable read).
347
+ const reason = typeof r.blockedReason === "string" ? r.blockedReason.trim().slice(0, 300) : ""
348
+ // PHASE 4A.1 - `taskId` is the ONE identity-bearing field that survives
349
+ // normalization. It is validated with the canonical guard and then passed
350
+ // through unchanged: never trimmed, renumbered, generated or coerced. An
351
+ // absent id stays absent - this layer must not invent durable identity.
352
+ if (r.taskId !== undefined && r.taskId !== null && !isTaskId(r.taskId)) {
353
+ throw new Error(`todo item has a non-canonical taskId: ${String(r.taskId)}`)
354
+ }
355
+ const taskId = isTaskId(r.taskId) ? r.taskId : undefined
356
+ out.push(
357
+ reason
358
+ ? { content, status, blockedReason: reason, ...(taskId ? { taskId } : {}) }
359
+ : { content, status, ...(taskId ? { taskId } : {}) },
360
+ )
63
361
  }
64
362
  if (out.length === 0) throw new Error("todos is empty — provide at least one item with content")
363
+ // `blocked` tanpa alasan adalah state tak terjelaskan (PF-04). Selain
364
+ // `blocked` dikeluarkan dari enum model, ada pagar kedua di sini: file yang
365
+ // ditulis tangan atau jalur argumen lain tidak boleh menciptakan blocker
366
+ // yang tak bisa dijelaskan. Tanpa alasan -> turun ke `pending`.
367
+ for (const t of out) {
368
+ if (t.status !== "blocked" || t.blockedReason) continue
369
+ t.status = "pending"
370
+ }
371
+ // Bukti merah MENOLAK `completed`: task turun ke `blocked` beserta alasannya.
372
+ // Ini yang menutup INV-003 - sebelumnya model bisa menandai "selesai" sambil
373
+ // verify merah dan tak ada satu pun jalur kode yang mencegahnya.
374
+ const gated = applyCompletionPolicy(out, ev, opts)
375
+ const final = gated ?? out
65
376
  // Satu in_progress saja: kalau model menandai beberapa, sisanya turun ke
66
377
  // pending supaya daftar tetap punya satu fokus yang jelas.
67
378
  let seenActive = false
68
- for (const t of out) {
379
+ for (const t of final) {
69
380
  if (t.status !== "in_progress") continue
70
381
  if (seenActive) t.status = "pending"
71
382
  seenActive = true
72
383
  }
73
- return out
384
+ return final
74
385
  }
75
386
 
76
387
  export function renderTodos(todos: TodoItem[]): string {
77
388
  const done = todos.filter((t) => t.status === "completed").length
389
+ const blocked = todos.filter((t) => t.status === "blocked").length
78
390
  const active = todos.find((t) => t.status === "in_progress")
79
- const head = `todos ${done}/${todos.length}${active ? ` · sekarang: ${active.content}` : ""}`
80
- const body = todos.map((t) => ` ${GLYPH[t.status]} ${t.content}`).join("\n")
391
+ const head =
392
+ `todos ${done}/${todos.length}` +
393
+ (blocked > 0 ? ` · ${blocked} blocked` : "") +
394
+ (active ? ` · sekarang: ${active.content}` : "")
395
+ const body = todos
396
+ .map(
397
+ // PHASE 4A.1 - identity is echoed so the model can reference the task
398
+ // later. It is rendered only when present; an id-less item is rendered
399
+ // exactly as before. No id is ever synthesised for display.
400
+ (t) =>
401
+ ` ${GLYPH[t.status]} ${t.taskId ? `${t.taskId} — ` : ""}${t.content}${t.blockedReason ? ` — ${t.blockedReason}` : ""}`,
402
+ )
403
+ .join("\n")
81
404
  return `${head}\n${body}`
82
405
  }
83
406
 
407
+ /**
408
+ * Baca daftar todo dari disk. **PASIF**: tidak menerapkan kebijakan
409
+ * completion apa pun.
410
+ *
411
+ * Dulu jalur baca ini melewati `normalizeTodos` tanpa argumen bukti, sehingga
412
+ * ia memakai `currentCompletionEvidence()` - akibatnya `todo_read` melaporkan
413
+ * `blocked` sementara file tetap `completed`. Durable dan observed berbeda, dan
414
+ * tak ada yang menyelaraskan. Sekarang bentuk di disk adalah satu-satunya
415
+ * kebenaran; kebijakan hanya berlaku di jalur tulis (`todo_write`) dan di
416
+ * rekonsiliasi eksplisit (`reconcileCompletionEvidence`) yang menulis balik.
417
+ */
84
418
  export async function loadTodos(sessionId: string, cwd = process.cwd()): Promise<TodoItem[]> {
419
+ // N2: try the canonical name first, then the legacy name. A file written by an
420
+ // older process only exists at the legacy path, so without this fallback a
421
+ // workspace that was upgraded but never ran `todo_write` again would lose its
422
+ // task list silently.
423
+ for (const p of [todoPath(sessionId, cwd), legacyTodoPath(sessionId, cwd)]) {
424
+ const parsed = await readTodoFile(p)
425
+ if (parsed) return parsed
426
+ }
427
+ return []
428
+ }
429
+
430
+ async function readTodoFile(p: string): Promise<TodoItem[] | null> {
85
431
  try {
86
- const raw = await readFile(todoPath(sessionId, cwd), "utf8")
432
+ const raw = await readFile(p, "utf8")
87
433
  const parsed = JSON.parse(raw) as { todos?: unknown }
88
- return normalizeTodos(parsed.todos ?? [])
434
+ if (!Array.isArray(parsed.todos)) return null
435
+ // Bentuk tersimpan sudah ternormalisasi saat ditulis. Normalisasi di sini
436
+ // hanya untuk mem-namedai file yang ditulis tangan, dengan bukti
437
+ // `unverified` supaya TIDAK ada kebijakan yang diam-diam berlaku saat baca.
438
+ return normalizeTodos(parsed.todos, UNVERIFIED)
89
439
  } catch {
90
- return []
440
+ return null
441
+ }
442
+ }
443
+
444
+ /**
445
+ * Rekonsiliasi completion SETELAH verify selesai.
446
+ *
447
+ * Menutup gap PF-01: `todo_write` berjalan sebelum verify sebuah turn, jadi
448
+ * klaim `completed` bisa sudah tersimpan ketika verify turn itu berubah merah.
449
+ * Fungsi ini menutup celah itu dari arah yang sama seperti gerbang tulis:
450
+ * penurunan `completed` menjadi `blocked` + alasan, ditulis balik ke disk, dan
451
+ * pemanggil menerbitkan `plan.updated` baru.
452
+ *
453
+ * Idempoten dan pasif-bila-tak-perlu: mengembalikan `null` bila tidak ada
454
+ * perubahan, supaya tidak terbit event plan yang tidak mencerminkan kenyataan.
455
+ */
456
+ export async function reconcileCompletionEvidence(
457
+ sessionId: string,
458
+ cwd: string,
459
+ evidence: CompletionEvidence,
460
+ ): Promise<TodoItem[] | null> {
461
+ // `stale` diperlakukan seperti `failed` untuk otorisasi (tolak klaim),
462
+ // dengan label + alasan basi dipertahankan apa adanya.
463
+ if (evidence.verdict !== "failed" && evidence.verdict !== "stale") return null
464
+ try {
465
+ const current = await loadTodos(sessionId, cwd)
466
+ const next = applyCompletionPolicy(current, evidence)
467
+ if (!next) return null
468
+ await saveTodos(sessionId, next, cwd)
469
+ await savePlanSnapshot(sessionId, next, cwd).catch(() => {})
470
+ return next
471
+ } catch (e) {
472
+ // Best-effort: kegagalan rekonsiliasi TIDAK boleh menggagalkan turn yang
473
+ // sudah selesai. Diagnostik ditulis di modul pemilik kegagalan, bukan di
474
+ // pemanggil — menambah `process.stderr.write` di `cli/setup.ts` menaikkan
475
+ // writer ke-27 dan melanggar pagu invaris OAP-008 (test/writer-inventory).
476
+ process.stderr.write(`[warn] completion reconcile failed: ${(e as Error).message}\n`)
477
+ return null
91
478
  }
92
479
  }
93
480
 
@@ -107,15 +494,28 @@ export async function saveTodos(
107
494
  * Best-effort: gagal tulis tak boleh menggagalkan todo_write. */
108
495
  export function renderPlan(sessionId: string, todos: TodoItem[]): string {
109
496
  const done = todos.filter((t) => t.status === "completed").length
497
+ const blocked = todos.filter((t) => t.status === "blocked").length
110
498
  const lines = [
111
499
  `# Plan — ${sessionId}`,
112
500
  ``,
113
- `Progress: ${done}/${todos.length} completed.`,
501
+ `Progress: ${done}/${todos.length} completed.${blocked ? ` · ${blocked} blocked.` : ""}`,
114
502
  ``,
115
- ...todos.map(
116
- (t) =>
117
- `- [${t.status === "completed" ? "x" : t.status === "in_progress" ? "~" : t.status === "cancelled" ? "-" : " "}] ${t.content} (${t.status})`,
118
- ),
503
+ ...todos.map((t) => {
504
+ const box =
505
+ t.status === "completed"
506
+ ? "x"
507
+ : t.status === "in_progress"
508
+ ? "~"
509
+ : t.status === "cancelled"
510
+ ? "-"
511
+ : t.status === "blocked"
512
+ ? "!"
513
+ : " "
514
+ // Alasan blocker WAJIB ikut: tanpa ini artefak ini tidak bisa
515
+ // menjelaskan kenapa sebuah task tidak bisa diselesaikan.
516
+ const why = t.blockedReason ? ` — ${t.blockedReason}` : ""
517
+ return `- [${box}] ${t.content} (${t.status})${why}`
518
+ }),
119
519
  ``,
120
520
  `_Updated: ${new Date().toISOString()}_`,
121
521
  ``,
@@ -145,10 +545,44 @@ export async function loadPlan(sessionId: string, cwd = process.cwd()): Promise<
145
545
  /** Session id aktif — di-set CLI supaya todo tersimpan per sesi. */
146
546
  export const todoSession = { id: "default", cwd: undefined as string | undefined }
147
547
 
548
+ /**
549
+ * PHASE 4A.4B — the identity ONE todo operation runs under.
550
+ *
551
+ * WHY THIS EXISTS. `todoSession` is a process-level singleton. The write path used
552
+ * to read it *after* an `await`, so a second request that rebound the global could
553
+ * silently steal the first request's session: the JSON write, the TaskStore
554
+ * namespace, the assignment's session stamp and the plan snapshot could all end
555
+ * up under the wrong session.
556
+ *
557
+ * The fix is deliberately NOT a new global and NOT a new context abstraction. It
558
+ * is the existing per-request `ToolContext` — which MCP already builds fresh for
559
+ * every request and already populates with the execution root — plus ONE capture
560
+ * at operation entry. Everything after an `await` then reads the immutable local,
561
+ * so the operation stays bound to the session it was invoked with no matter what
562
+ * another request does to the global.
563
+ *
564
+ * Resolution order (preserved from the original code, which preferred `ctx` over
565
+ * the global):
566
+ * sessionId: ctx.sessionId -> todoSession.id
567
+ * cwd: ctx.cwd -> todoSession.cwd -> process.cwd()
568
+ *
569
+ * `todoSession` remains the composition-root DEFAULT — `cli/setup.ts` binds it
570
+ * once at startup and never mutates it during operation. It is read here exactly
571
+ * once per operation, at entry, which is what makes it safe rather than what makes
572
+ * it correct on its own.
573
+ */
574
+ export function todoOperationContext(ctx: unknown): { sessionId: string; cwd: string } {
575
+ const c = (ctx ?? {}) as { sessionId?: string; cwd?: string }
576
+ return {
577
+ sessionId: typeof c.sessionId === "string" && c.sessionId !== "" ? c.sessionId : todoSession.id,
578
+ cwd: c.cwd ?? todoSession.cwd ?? process.cwd(),
579
+ }
580
+ }
581
+
148
582
  export const todoWriteTool: Tool = {
149
583
  name: "todo_write",
150
584
  description:
151
- "Write/replace the todo list for this task. Send the ENTIRE list every time (not a delta). Use for tasks with 3+ steps: keep exactly one item in_progress at a time, mark it completed as soon as it is done.",
585
+ "Write/replace the todo list for this task. Send the ENTIRE list every time (not a delta). Use for tasks with 3+ steps: keep exactly one item in_progress at a time, mark it completed as soon as it is done. Marking an item completed while verification is failing or stale is REFUSED — it comes back as blocked with the reason, so fix the failing check (or re-verify after newer changes) first.",
152
586
  parameters: {
153
587
  type: "object",
154
588
  properties: {
@@ -159,10 +593,24 @@ export const todoWriteTool: Tool = {
159
593
  type: "object",
160
594
  properties: {
161
595
  content: { type: "string", description: "short, actionable task item" },
596
+ // `blocked` SENGAJA tidak ada di enum model: itu status yang
597
+ // ditegakkan runtime (verifikasi merah) dan selalu membawa alasan.
598
+ // Jika model boleh memilihnya, `blocked` berubah menjadi generic
599
+ // non-completed state - tercampur "verify merah" dengan "agen
600
+ // menyerah" (PF-04).
162
601
  status: {
163
602
  type: "string",
164
603
  enum: ["pending", "in_progress", "completed", "cancelled"],
165
604
  },
605
+ // PHASE 4A.1 - the single identity-bearing field the model may
606
+ // supply. Optional, so every existing id-less payload still
607
+ // validates. `additionalProperties: false` below is retained, so
608
+ // this is the ONLY new accepted property.
609
+ taskId: {
610
+ type: "string",
611
+ description:
612
+ "Canonical task id (e.g. t1) of an EXISTING task, as returned by todo_read. Omit for a new task. Never invent one.",
613
+ },
166
614
  },
167
615
  required: ["content", "status"],
168
616
  additionalProperties: false,
@@ -174,16 +622,193 @@ export const todoWriteTool: Tool = {
174
622
  },
175
623
  async execute({ todos }, ctx) {
176
624
  ctx.signal.throwIfAborted()
177
- const list = normalizeTodos(todos)
178
- // cwd sesi dari ToolContext dulu (skenario --cwd / sub-agen), lalu global
179
- // yang di-set composition root (cli/setup.ts, MCP serve), terakhir cwd
180
- // proses. Urutan lama (global-dulu) buta terhadap ctx.
181
- const cwd = (ctx as { cwd?: string }).cwd ?? todoSession.cwd ?? process.cwd()
182
- await saveTodos(todoSession.id, list, cwd)
625
+ // PHASE 4A.4B - bind ONCE, before the first await. `sessionId` and `cwd` are
626
+ // immutable for the rest of this operation, so no later request can redirect
627
+ // the JSON write, the TaskStore namespace, the assignment stamp or the plan
628
+ // snapshot to another session.
629
+ //
630
+ // cwd resolution order is unchanged: ToolContext first (--cwd / sub-agent),
631
+ // then the composition-root global, then the process cwd.
632
+ const { sessionId, cwd } = todoOperationContext(ctx)
633
+ // P10.1.1: bukti diselesaikan terhadap kesegaran mutasi (async) SEBELUM
634
+ // gate murni — `normalizeTodos` tetap sync tanpa I/O.
635
+ const evidence = await resolveFreshEvidence(sessionId, cwd)
636
+ // Indeks item valid (setelah pemangkasan content kosong, persis urutan
637
+ // `normalizeTodos`) yang diajukan `completed` oleh model. Dipakai saat
638
+ // `requireVerified && unverified` agar TaskStore menahan baris di VERIFYING.
639
+ const rawDeclaredCompleted = new Set<number>()
640
+ if (Array.isArray(todos)) {
641
+ let validIdx = 0
642
+ for (const raw of todos.slice(0, LIMITS.TODO_MAX_ITEMS)) {
643
+ if (!raw || typeof raw !== "object") continue
644
+ const r = raw as { content?: unknown; status?: unknown }
645
+ if (!String(r.content ?? "").trim()) continue
646
+ if (r.status === "completed") rawDeclaredCompleted.add(validIdx)
647
+ validIdx += 1
648
+ }
649
+ }
650
+ const list = normalizeTodos(todos, evidence)
651
+
652
+ // PHASE 4A.5 — reject an identity-blind full declaration once canonical
653
+ // identity already exists for this session (NEW ARCHITECTURE).
654
+ //
655
+ // `todo_write` is a FULL DECLARATION, so re-sending the same work without
656
+ // ids is indistinguishable from creating it again. That is precisely the
657
+ // duplication debc295 documents. Once canonical tasks exist, an all-id-less
658
+ // payload carries too little information to address them, so it is rejected
659
+ // rather than guessed at — identity is never manufactured to make an
660
+ // ambiguous payload "work".
661
+ //
662
+ // PLACEMENT. This sits BEFORE `saveTodos`, so a rejected write is a complete
663
+ // no-op: no JSON replacement, no TaskStore mutation, no id allocation, no
664
+ // plan (the throw makes the tool result an error, which the adapter already
665
+ // treats as "do not publish"). Rejecting after the JSON write would leave the
666
+ // legacy file describing a state TaskStore never accepted.
667
+ //
668
+ // EMPTY PAYLOAD is excluded. `todos: []` declares nothing, so there is no
669
+ // item to misaddress; it keeps its existing meaning (clear the legacy list,
670
+ // D7 retention keeps canonical tasks untouched). The guard cannot be laundered
671
+ // through it: canonical rows survive, so the NEXT all-id-less write is still
672
+ // rejected.
673
+ if (list.length > 0 && !hasCanonicalIdentity(list) && hasCanonicalTasks(cwd, sessionId)) {
674
+ const count = new TaskStore(cwd).listTasks(sessionId).length
675
+ throw new TaskError(
676
+ "TASK_IDENTITY_REQUIRED",
677
+ `this task already has ${count} canonical task(s), so this full declaration must identify them. ` +
678
+ `Call todo_read and re-send every item with its taskId (e.g. {"taskId":"t1", ...}); ` +
679
+ `omit taskId only on items that are genuinely new. ` +
680
+ `Nothing was written: the todo list and canonical tasks are unchanged.`,
681
+ )
682
+ }
683
+
684
+ await saveTodos(sessionId, list, cwd)
685
+ // PHASE 4A.4 - canonical TaskStore synchronization (NEW ARCHITECTURE).
686
+ //
687
+ // Placement follows the ordering production already proves: the durable JSON
688
+ // write happens first, so a failure here still suppresses plan publication
689
+ // (the adapter only publishes when the tool did not error). All-id-less
690
+ // payloads are left alone - the legacy path stays legacy.
691
+ //
692
+ // `content` is mapped to `title` here because TaskStore requires `title`;
693
+ // passing the legacy `content` through was measured to fail NOT NULL.
694
+ //
695
+ // PHASE 4A.4A - the resulting assignment is captured here and emitted on the
696
+ // return value, which is the only per-operation channel the kernel itself
697
+ // correlates (the reasoning, and the rejected alternatives, are in
698
+ // `src/task/assignment.ts`). The legacy all-id-less path appends nothing, so
699
+ // its output is byte-identical to what it was before this phase.
700
+ let assignment: CanonicalAssignmentTable | undefined
701
+ const holdInVerifying = evidence.verdict === "unverified" && evidence.requireVerified === true
702
+ // [Fase 8 / 8.3] Todo→TaskStore sync untuk payload all-id-less.
703
+ //
704
+ // Live Test §3.1: `todo_write` dengan payload tanpa `taskId` (all-id-less)
705
+ // TIDAK pernah menyinkronkan ke `.minicode/tasks.db` → query tasks selalu
706
+ // `0 rows`. `synchronizeCanonicalTasks` sengaja menolak payload id-less
707
+ // (legacy). Namun untuk sesi yang BELUM punya identitas kanonik sama sekali
708
+ // (belum ada baris tasks), payload id-less adalah deklarasi pertama — item
709
+ // di dalamnya memang task baru, jadi mengalokasikan id via TaskStore adalah
710
+ // aman dan justru menghilangkan `0 rows`. Guard 4A.5 (reject id-less bila
711
+ // canonical tasks sudah ada) tetap berjalan di atas — jadi alur ini hanya
712
+ // menjangkau sesi yang benar-benar baru (dup yang sudah ada tetap ditolak).
713
+ const firstCanonicalWrite = !hasCanonicalIdentity(list) && !hasCanonicalTasks(cwd, sessionId)
714
+ if (hasCanonicalIdentity(list) || firstCanonicalWrite) {
715
+ try {
716
+ const sync = synchronizeCanonicalTasks({
717
+ cwd,
718
+ sessionId,
719
+ declared: list.map((t, idx) => ({
720
+ ...(t.taskId ? { taskId: t.taskId } : {}),
721
+ title: t.content,
722
+ status: t.status,
723
+ ...(t.blockedReason ? { blockedReason: t.blockedReason } : {}),
724
+ ...(holdInVerifying && rawDeclaredCompleted.has(idx) ? { holdVerifying: true } : {}),
725
+ })),
726
+ ...(firstCanonicalWrite ? { adoptIdlessAsNew: true } : {}),
727
+ ...(evidence.verdict === "passed"
728
+ ? {
729
+ verificationOutcome: {
730
+ ok: true,
731
+ verdict: "passed",
732
+ exitCode: evidence.exitCode ?? 0,
733
+ ...(evidence.detail ? { command: evidence.detail } : {}),
734
+ summary: evidence.summary ?? evidence.detail ?? "verification passed",
735
+ integrityOk: true,
736
+ },
737
+ }
738
+ : {}),
739
+ })
740
+ if (sync.assignment && sync.assignment.length > 0) assignment = sync.assignment
741
+ } catch (e) {
742
+ // DIVERGENCE, made visible rather than silent: the JSON file is already
743
+ // committed, TaskStore rolled back. Surfacing the code keeps the failure
744
+ // machine-checkable while the message states the real state of the world.
745
+ const err = e as TaskError
746
+ throw new TaskError(
747
+ err.code ?? "TASK_PERSISTENCE_FAILURE",
748
+ `canonical task sync failed (${err.message}); the todo JSON file was already written, TaskStore rolled back - the two are now out of step`,
749
+ )
750
+ }
751
+ }
752
+ // PHASE 4B.1 - write the RESOLVED identities back to the durable todo file.
753
+ //
754
+ // THE DEFECT THIS FIXES. `saveTodos` above persists the *declared* payload,
755
+ // which by definition carries no id for a task the sync was about to create.
756
+ // The id minted by TaskStore reached the plan builder (4A.4A) but never the
757
+ // JSON, and `todo_read` reads the JSON - so the model could never learn the id
758
+ // of a task it had just created. On the next turn it re-sent that item
759
+ // id-less, 4A.5 classified it as a mixed payload, and a SECOND durable row was
760
+ // created for the same logical task. Measured before the fix: t3=C then
761
+ // t4=C, two canonical rows for one task.
762
+ //
763
+ // The ids merged here are the allocator's own, returned by the transaction
764
+ // that committed them. Nothing is inferred from position, content or title.
765
+ //
766
+ // ORDERING IS PRESERVED. The first `saveTodos` still happens BEFORE the
767
+ // canonical sync, so a durable-write failure still suppresses plan
768
+ // publication (4A.4) and the 4A.5 guard still runs before anything is
769
+ // written. This is an ADDITIONAL write that only happens once the canonical
770
+ // state is committed.
771
+ //
772
+ // The legacy all-id-less path produces no assignment, so it performs no
773
+ // second write and its file is byte-identical to before.
774
+ let current = list
775
+ if (assignment) {
776
+ const merged = list.map((t, i) =>
777
+ // Only ever ADD an id the store just minted. A declared id is never
778
+ // rewritten, and an item with no assignment entry is left untouched.
779
+ !t.taskId && assignment[i] ? { ...t, taskId: assignment[i]!.taskId } : t,
780
+ )
781
+ if (merged.some((t, i) => t.taskId !== list[i]?.taskId)) {
782
+ current = merged
783
+ // Awaited, not swallowed: leaving a stale view file behind is precisely
784
+ // what made this defect invisible. If this write fails the operation
785
+ // reports failure rather than pretending the identity is observable.
786
+ await saveTodos(sessionId, current, cwd)
787
+ }
788
+ }
183
789
  // Plan artifact ditulis tiap save — murah (atomik, kecil) dan membuat
184
790
  // resume lintas sesi tidak butuh memutar ulang seluruh percakapan.
185
- await savePlanSnapshot(todoSession.id, list, cwd).catch(() => {})
186
- return renderTodos(list)
791
+ // Now fed with the RESOLVED list, so the persisted plan carries canonical ids.
792
+ await savePlanSnapshot(sessionId, current, cwd).catch(() => {})
793
+ // Penolakan completion harus TERLIHAT oleh model, bukan hanya tersimpan di
794
+ // file: tanpa baris ini model mengira item-nya completed lalu mencoba
795
+ // lanjut — persis pola "false completion" yang INV-003 larang.
796
+ const refused = current.filter((t) => t.status === "blocked" && t.blockedReason)
797
+ // P10.1.1: stale ≠ failed — pesannya dibedakan agar model memperbaiki
798
+ // hal yang benar (re-verify untuk basi, perbaiki check untuk gagal).
799
+ const notice =
800
+ refused.length > 0
801
+ ? evidence.verdict === "stale"
802
+ ? `refused ${refused.length} completion claim(s): verification evidence is stale — code changed since the last green run; re-verify, then re-claim.\n`
803
+ : holdInVerifying
804
+ ? `refused ${refused.length} completion claim(s): verification is required before completion — tasks are held in VERIFYING until the verifier runs green.\n`
805
+ : `refused ${refused.length} completion claim(s): verification is failing, so they are blocked instead of completed. Fix the failing check first.\n`
806
+ : ""
807
+ return (
808
+ notice +
809
+ renderTodos(current) +
810
+ (assignment ? `\n${encodeCanonicalAssignments(sessionId, assignment)}` : "")
811
+ )
187
812
  },
188
813
  }
189
814
 
@@ -193,8 +818,10 @@ export const todoReadTool: Tool = {
193
818
  parameters: { type: "object", properties: {}, additionalProperties: false },
194
819
  async execute(_args, ctx) {
195
820
  ctx.signal.throwIfAborted()
196
- const cwd = (ctx as { cwd?: string }).cwd ?? todoSession.cwd ?? process.cwd()
197
- const list = await loadTodos(todoSession.id, cwd)
821
+ // PHASE 4A.4B - same single entry capture as the write path. A concurrent
822
+ // write rebinding the global must not decide which session this read observes.
823
+ const { sessionId, cwd } = todoOperationContext(ctx)
824
+ const list = await loadTodos(sessionId, cwd)
198
825
  if (list.length === 0) return "(no todos yet — use todo_write to create one)"
199
826
  return renderTodos(list)
200
827
  },