minicode-ai 0.11.0 → 0.13.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (221) hide show
  1. package/CHANGELOG.md +98 -0
  2. package/LICENSE +21 -21
  3. package/README.md +4 -4
  4. package/cli/args.ts +46 -0
  5. package/cli/commands/acp.ts +163 -10
  6. package/cli/commands/config.ts +33 -18
  7. package/cli/commands/daemon.ts +515 -0
  8. package/cli/commands/exec.ts +145 -53
  9. package/cli/commands/openwork.ts +986 -0
  10. package/cli/commands/sessions.ts +4 -1
  11. package/cli/commands/stats.ts +34 -4
  12. package/cli/commands.ts +217 -2
  13. package/cli/index.ts +146 -14
  14. package/cli/recovery-warning.ts +115 -0
  15. package/cli/router.ts +32 -1
  16. package/cli/setup.ts +2332 -171
  17. package/cli/tui.ts +113 -7
  18. package/docs/OUTPUT_ARCHITECTURE_AUDIT.md +489 -0
  19. package/docs/OUTPUT_EVENT_MODEL.md +289 -0
  20. package/docs/OUTPUT_IMPLEMENTATION_PLAN.md +391 -0
  21. package/docs/OUTPUT_PROTOCOL_SPEC.md +285 -0
  22. package/docs/OUTPUT_RENDERING_SPEC.md +248 -0
  23. package/docs/OUTPUT_UX_RULES.md +449 -0
  24. package/docs/PLAN_UIUX_V6.md +2 -2
  25. package/docs/README.md +4 -3
  26. package/docs/TERMINAL_CONTRACT.md +278 -66
  27. package/docs/architecture.md +89 -7
  28. package/docs/changelog.md +1 -1
  29. package/docs/choosing-mode.md +2 -2
  30. package/docs/cli.md +9 -5
  31. package/docs/concepts.md +1 -1
  32. package/docs/contributing.md +9 -2
  33. package/docs/environment.md +6 -2
  34. package/docs/exec.md +46 -5
  35. package/docs/memory-sessions.md +2 -0
  36. package/docs/policy-sandbox.md +1 -1
  37. package/docs/pricing-budget.md +1 -1
  38. package/docs/quickstart.md +2 -2
  39. package/docs/repl.md +6 -2
  40. package/docs/security-model.md +1 -1
  41. package/docs/security.md +1 -1
  42. package/docs/skills.md +2 -2
  43. package/docs/terminal.md +9 -5
  44. package/docs/tools.md +1 -1
  45. package/package.json +35 -5
  46. package/src/app/session.ts +261 -15
  47. package/src/app/tool-layer.ts +94 -7
  48. package/src/daemon/approvals.ts +361 -0
  49. package/src/daemon/capability.ts +145 -0
  50. package/src/daemon/children.ts +142 -0
  51. package/src/daemon/client.ts +267 -0
  52. package/src/daemon/control.ts +350 -0
  53. package/src/daemon/discovery.ts +234 -0
  54. package/src/daemon/feed.ts +155 -0
  55. package/src/daemon/framing.ts +94 -0
  56. package/src/daemon/host.ts +316 -0
  57. package/src/daemon/protocol.ts +217 -0
  58. package/src/daemon/resource.ts +170 -0
  59. package/src/daemon/sanitize.ts +57 -0
  60. package/src/daemon/server.ts +627 -0
  61. package/src/daemon/store.ts +317 -0
  62. package/src/daemon/subscription.ts +270 -0
  63. package/src/daemon/telemetry.ts +81 -0
  64. package/src/hooks/run.ts +12 -1
  65. package/src/lib/atomic-write.ts +29 -3
  66. package/src/lib/db-path.ts +26 -0
  67. package/src/lib/keystore.ts +544 -42
  68. package/src/lib/net.ts +43 -1
  69. package/src/lib/safe-open.ts +116 -1
  70. package/src/lib/session-id.ts +15 -0
  71. package/src/lsp/client.ts +123 -5
  72. package/src/mcp/client.ts +139 -17
  73. package/src/mcp/server.ts +177 -50
  74. package/src/mcp/transport.ts +16 -19
  75. package/src/memory/vector.ts +770 -55
  76. package/src/policy/allowlist.ts +14 -2
  77. package/src/policy/bash-guard.ts +105 -10
  78. package/src/policy/compaction.ts +82 -5
  79. package/src/policy/consequence-engine.ts +220 -0
  80. package/src/policy/context.ts +132 -0
  81. package/src/policy/executor.ts +187 -121
  82. package/src/policy/no-progress.ts +559 -0
  83. package/src/policy/permission.ts +4 -8
  84. package/src/policy/pricing.ts +17 -3
  85. package/src/policy/scrub.ts +69 -2
  86. package/src/policy/tool-contract.ts +515 -0
  87. package/src/policy/usage.ts +310 -24
  88. package/src/policy/verifier.ts +6 -3
  89. package/src/policy/work-mode.ts +182 -0
  90. package/src/presentation/adapter.ts +533 -26
  91. package/src/presentation/events.ts +151 -0
  92. package/src/presentation/model.ts +180 -27
  93. package/src/presentation/projection.ts +858 -0
  94. package/src/presentation/reducer.ts +645 -310
  95. package/src/presentation/store.ts +12 -7
  96. package/src/providers/anthropic.ts +18 -10
  97. package/src/providers/responses.ts +17 -7
  98. package/src/runtime/capability.ts +409 -0
  99. package/src/runtime/child-execution.ts +274 -0
  100. package/src/runtime/composition.ts +958 -0
  101. package/src/runtime/dispatch.ts +591 -0
  102. package/src/runtime/execution-backend.ts +632 -0
  103. package/src/runtime/execution-events.ts +272 -0
  104. package/src/runtime/execution-id.ts +230 -0
  105. package/src/runtime/execution-journal.ts +926 -0
  106. package/src/runtime/execution-kernel.ts +456 -0
  107. package/src/runtime/execution-registry.ts +379 -0
  108. package/src/runtime/process-supervision.ts +276 -0
  109. package/src/runtime/production-execution.ts +551 -0
  110. package/src/runtime/production-runtime.ts +217 -0
  111. package/src/runtime/recovery-safety.ts +70 -0
  112. package/src/runtime/recovery.ts +477 -0
  113. package/src/runtime/runtime-capabilities.ts +179 -0
  114. package/src/runtime/runtime-diagnostics.ts +141 -0
  115. package/src/runtime/runtime-host.ts +365 -0
  116. package/src/runtime/runtime-status-facts.ts +222 -0
  117. package/src/runtime/runtime-status-provider.ts +74 -0
  118. package/src/runtime/runtime-status.ts +459 -0
  119. package/src/runtime/runtime-task-admission.ts +101 -0
  120. package/src/runtime/supervisor.ts +444 -0
  121. package/src/session/authority.ts +168 -0
  122. package/src/session/checkpoint.ts +88 -1
  123. package/src/session/context-adapter.ts +251 -0
  124. package/src/session/context-assembly.ts +242 -0
  125. package/src/session/context-identity.ts +389 -0
  126. package/src/session/context-projection.ts +248 -0
  127. package/src/session/context-selector.ts +500 -0
  128. package/src/session/cross-session-adoption.ts +249 -0
  129. package/src/session/full-history-fold.ts +171 -0
  130. package/src/session/identity.ts +192 -0
  131. package/src/session/journal.ts +805 -102
  132. package/src/session/open-work-intent.ts +732 -0
  133. package/src/session/open-work.ts +767 -0
  134. package/src/session/pending-tools.ts +94 -0
  135. package/src/session/persistence.ts +3569 -127
  136. package/src/session/runtime-header.ts +208 -0
  137. package/src/session/shadow-git.ts +13 -5
  138. package/src/session/verification.ts +1623 -0
  139. package/src/task/assignment.ts +136 -0
  140. package/src/task/autonomous-adapter.ts +168 -0
  141. package/src/task/autonomous-context.ts +630 -0
  142. package/src/task/autonomous-policy.ts +490 -0
  143. package/src/task/continuity.ts +179 -0
  144. package/src/task/execution-cancellation.ts +165 -0
  145. package/src/task/graph-validate.ts +379 -0
  146. package/src/task/graph.ts +305 -0
  147. package/src/task/identity.ts +230 -0
  148. package/src/task/model.ts +417 -0
  149. package/src/task/production-scheduler.ts +293 -0
  150. package/src/task/readiness.ts +229 -0
  151. package/src/task/scheduler-observability.ts +387 -0
  152. package/src/task/scheduler.ts +1197 -0
  153. package/src/task/scheduling-policy.ts +165 -0
  154. package/src/task/session-authority.ts +148 -0
  155. package/src/task/session-ownership.ts +211 -0
  156. package/src/task/store.ts +2887 -0
  157. package/src/task/sync.ts +343 -0
  158. package/src/task/trigger.ts +260 -0
  159. package/src/tools/bash.ts +377 -211
  160. package/src/tools/code_run.ts +1 -1
  161. package/src/tools/delete_file.ts +1 -1
  162. package/src/tools/edit.ts +33 -6
  163. package/src/tools/evidence.ts +30 -0
  164. package/src/tools/git.ts +4 -4
  165. package/src/tools/glob.ts +12 -3
  166. package/src/tools/grep.ts +1 -1
  167. package/src/tools/lsp.ts +4 -4
  168. package/src/tools/mcp_call.ts +11 -4
  169. package/src/tools/memory.ts +153 -18
  170. package/src/tools/move_file.ts +1 -1
  171. package/src/tools/patch.ts +1 -1
  172. package/src/tools/read_file.ts +1 -1
  173. package/src/tools/read_image.ts +1 -1
  174. package/src/tools/submit_result.ts +1 -1
  175. package/src/tools/task.ts +437 -41
  176. package/src/tools/todo.ts +662 -35
  177. package/src/tools/web_fetch.ts +4 -2
  178. package/src/tools/web_search.ts +9 -3
  179. package/src/tools/write_file.ts +1 -1
  180. package/src/ui/assistant/simple.ts +123 -50
  181. package/src/ui/assistant/turn-status.ts +17 -3
  182. package/src/ui/contract.ts +184 -0
  183. package/src/ui/footer.ts +54 -18
  184. package/src/ui/i18n/en.ts +62 -6
  185. package/src/ui/i18n/id.ts +62 -6
  186. package/src/ui/input/prompt-engine.ts +120 -25
  187. package/src/ui/render/errors.ts +39 -1
  188. package/src/ui/render/markdown-table.ts +455 -0
  189. package/src/ui/render/markdown.ts +22 -1
  190. package/src/ui/render/table-grid.ts +184 -0
  191. package/src/ui/render/table.ts +15 -76
  192. package/src/ui/runtime/screen.ts +7 -2
  193. package/src/ui/runtime/statusline.ts +25 -6
  194. package/src/ui/tui/app.ts +598 -133
  195. package/src/ui/tui/transcript.ts +531 -89
  196. package/vendor/minicore/VENDOR.md +1 -1
  197. package/vendor/minicore/src/core/budget.ts +25 -25
  198. package/vendor/minicore/src/core/compact.ts +75 -75
  199. package/vendor/minicore/src/core/errors.ts +59 -59
  200. package/vendor/minicore/src/core/events.ts +73 -73
  201. package/vendor/minicore/src/core/executor.ts +139 -139
  202. package/vendor/minicore/src/core/history.ts +31 -31
  203. package/vendor/minicore/src/core/index.ts +41 -41
  204. package/vendor/minicore/src/core/loop.ts +355 -355
  205. package/vendor/minicore/src/core/permission.ts +22 -22
  206. package/vendor/minicore/src/core/provider.ts +39 -39
  207. package/vendor/minicore/src/core/recovery.ts +35 -35
  208. package/vendor/minicore/src/core/session.ts +327 -327
  209. package/vendor/minicore/src/core/snapshot.ts +146 -146
  210. package/vendor/minicore/src/core/tokens.ts +107 -107
  211. package/vendor/minicore/src/core/tool.ts +115 -115
  212. package/vendor/minicore/src/core/types.ts +50 -50
  213. package/vendor/minicore/src/providers/openai-compat.ts +417 -417
  214. package/AGENTS.md +0 -45
  215. package/PLAN.md +0 -491
  216. package/docs/ARCHITECTURE.html +0 -1248
  217. package/docs/CONTROL-PLANE-MAP.md +0 -139
  218. package/docs/HARNESS.md +0 -150
  219. package/docs/SUMMARY.md +0 -52
  220. package/docs/UI_RENDER_PIPELINE.md +0 -165
  221. package/docs/USAGE.md +0 -11
@@ -0,0 +1,343 @@
1
+ // Production canonical task synchronization — Phase 4A.4.
2
+ //
3
+ // THIS IS NEW ARCHITECTURE. The pre-wipe production writer did not survive the
4
+ // workspace wipe and has no surviving caller: `store.orig.ts` defined
5
+ // `synchronizeTasks` but nothing in any recovered file invoked it. This module
6
+ // is the FIRST production consumer of TaskStore, and its placement is a design
7
+ // decision, not a recovery.
8
+ //
9
+ // THE BOUNDARY
10
+ // todo_write payload
11
+ // -> JSON durable write (unchanged, still the legacy file)
12
+ // -> THIS module (canonical TaskStore state)
13
+ // -> plan publication (unchanged, downstream)
14
+ //
15
+ // The ordering is the one already proven in production: a durable write happens
16
+ // before the plan is published, so a failed durable write suppresses the plan
17
+ // (`src/presentation/adapter.ts`). Nothing here invents a new ordering.
18
+ //
19
+ // CLASSIFICATION (the approved distinction)
20
+ // mixed payload (>=1 taskId) -> id-bearing items are EXISTING, id-less items
21
+ // are genuinely NEW
22
+ // all-id-less payload -> NOT synchronized. The legacy JSON path stays
23
+ // exactly as it was; no automatic adoption, no
24
+ // id allocation, no manifest. Rejecting that
25
+ // case is Phase 4A.5's decision, not this one's.
26
+ //
27
+ // IDENTITY RULES
28
+ // - an explicit taskId is resolved directly through TaskStore. NEVER by array
29
+ // position, content, title or ordinal.
30
+ // - the WHOLE payload is validated before the first mutation (the Phase 3A
31
+ // resolve-before-mutate invariant, preserved).
32
+ // - only TaskStore allocates ids, via `createTask`. This module never formats
33
+ // one.
34
+ // - one `todo_write` is one `withTransaction`: every update, creation, order
35
+ // change and metadata write either all commit or all roll back.
36
+
37
+ import type { CanonicalAssignment, CanonicalAssignmentTable } from "./assignment.ts"
38
+ import { type DeclaredTask, planTaskIdentities, todoStatusToTask } from "./identity.ts"
39
+ import { isTaskId, isTerminalTaskStatus, type Task, TaskError } from "./model.ts"
40
+ import { TaskStore, type VerificationGateOutcome } from "./store.ts"
41
+
42
+ /** One declared item, already mapped out of the legacy `TodoItem` shape.
43
+ * `content` is mapped to `title` by the caller - the store requires `title`,
44
+ * and passing `content` straight through was measured to fail NOT NULL. */
45
+ export interface CanonicalTaskInput {
46
+ taskId?: string
47
+ title: string
48
+ status: "pending" | "in_progress" | "completed" | "cancelled" | "blocked"
49
+ blockedReason?: string
50
+ /**
51
+ * [Fase 3 / LOOP-INV-12, LOOP-G20] Klaim `completed` saat `requireVerified`
52
+ * aktif namun hasil verifikasi belum tersedia (`unverified`): task ditahan di
53
+ * status `VERIFYING` alih-alih diloloskan ke `COMPLETED` palsu.
54
+ */
55
+ holdVerifying?: boolean
56
+ }
57
+
58
+ export interface CanonicalSyncResult {
59
+ /** False when the payload was all-id-less and therefore left legacy. */
60
+ applied: boolean
61
+ reason?: "legacy-idless-payload"
62
+ changed: Task[]
63
+ created: Task[]
64
+ /** D7 survivors: declared in an earlier turn, omitted now, kept anyway. */
65
+ retained: Task[]
66
+ /**
67
+ * PHASE 4A.4A — one entry per DECLARED item, in declaration order: the
68
+ * canonical id that item now has, and whether it already existed or this
69
+ * operation minted it. Absent for the legacy all-id-less path, which performs
70
+ * no synchronization and therefore has nothing to assign.
71
+ *
72
+ * Built INSIDE the transaction from the ids `createTask` returned, so it is
73
+ * exactly the committed result and never a later reconstruction. A rollback
74
+ * throws, so no assignment can be published for a transaction that did not
75
+ * commit — that is a structural guarantee, not a check.
76
+ */
77
+ assignment?: CanonicalAssignmentTable
78
+ }
79
+
80
+ /** True when at least one item carries an identity. Mirrors the recovered
81
+ * artifact's `hasAnyId` switch (`store.orig.ts:480`). */
82
+ export function hasCanonicalIdentity(items: readonly { taskId?: string }[]): boolean {
83
+ return items.some((i) => typeof i.taskId === "string" && i.taskId !== "")
84
+ }
85
+
86
+ /**
87
+ * PHASE 4A.5 — does this session ALREADY have canonical identity?
88
+ *
89
+ * AUTHORITY. This asks TaskStore, and nothing else. The legacy JSON file is NOT
90
+ * consulted, on purpose:
91
+ * - a JSON file exists for every session that has ever written a todo, canonical
92
+ * or not, so its presence says nothing about canonical identity;
93
+ * - conversely, a canonical session can have its JSON rewritten by a rejected
94
+ * write, so the JSON can be a poor predictor in the other direction too.
95
+ * The duplication this guards against is duplicate DURABLE tasks, so the
96
+ * predicate has to be answered by the store that holds them.
97
+ *
98
+ * STATUS IS DELIBERATELY IGNORED. Every row counts, whatever its status. A
99
+ * session whose tasks are all COMPLETED, CANCELLED or BLOCKED still has canonical
100
+ * identity: its ids are allocated, its orders are meaningful, and an identity-blind
101
+ * re-declaration would duplicate them. Filtering by status would silently reopen
102
+ * the duplication bug the moment a todo list finished.
103
+ *
104
+ * `task_meta` (the dormant migration substrate from Phase 0C/1) is also NOT
105
+ * consulted: nothing in production writes it, and no task means no identity to
106
+ * protect. A future bootstrap must therefore CREATE tasks, not merely write a
107
+ * stamp, or this guard would not see it - see the report.
108
+ */
109
+ export function hasCanonicalTasks(cwd: string, sessionId: string): boolean {
110
+ try {
111
+ return new TaskStore(cwd).listTasks(sessionId).length > 0
112
+ } catch (e) {
113
+ // A store we cannot open cannot be proven canonical, and claiming otherwise
114
+ // would either invent identity or block a legitimate legacy write. Fail open
115
+ // to LEGACY and let the legacy path behave exactly as it always has.
116
+ if (e instanceof TaskError) throw e
117
+ return false
118
+ }
119
+ }
120
+
121
+ export function synchronizeCanonicalTasks(opts: {
122
+ cwd: string
123
+ sessionId: string
124
+ declared: readonly CanonicalTaskInput[]
125
+ /**
126
+ * [Fase 3 / LOOP-INV-12] Bukti verifikasi terstruktur bila tersedia. Saat
127
+ * klaim `completed` didasari verifikasi yang lulus, transisi melalui
128
+ * `VERIFYING -> COMPLETED` dan menyimpan `evidence_json`.
129
+ */
130
+ verificationOutcome?: VerificationGateOutcome
131
+ /**
132
+ * [Fase 8 / 8.3] Izinkan payload all-id-less di-adopsi sebagai canonical
133
+ * saat sesi BELUM punya identitas kanonik sama sekali (belum ada baris
134
+ * tasks). Tanpa ini, `todo_write` pertama yang memakai payload tanpa `taskId`
135
+ * tidak pernah masuk `tasks.db` → Live Test §3.1 (`0 rows`). Setiap item
136
+ * id-less dianggap task baru dan id dialokasikan oleh TaskStore.
137
+ */
138
+ adoptIdlessAsNew?: boolean
139
+ }): CanonicalSyncResult {
140
+ const { cwd, sessionId, declared, verificationOutcome, adoptIdlessAsNew } = opts
141
+
142
+ // All-id-less: legacy behaviour, untouched — KECUALI caller meminta adopsi
143
+ // (first canonical write). No adoption, no allocation bila tidak diminta.
144
+ if (!hasCanonicalIdentity(declared) && !adoptIdlessAsNew) {
145
+ return {
146
+ applied: false,
147
+ reason: "legacy-idless-payload",
148
+ changed: [],
149
+ created: [],
150
+ retained: [],
151
+ }
152
+ }
153
+
154
+ const store = new TaskStore(cwd)
155
+
156
+ // Pure planning + validation. Throws on a malformed or duplicated id BEFORE
157
+ // any statement runs, so a bad payload cannot half-apply.
158
+ const asDeclared: DeclaredTask[] = declared.map((d) => ({
159
+ ...(d.taskId ? { taskId: d.taskId } : {}),
160
+ title: d.title,
161
+ status: d.status,
162
+ ...(d.blockedReason ? { blockedReason: d.blockedReason } : {}),
163
+ }))
164
+ const plan = planTaskIdentities(asDeclared)
165
+
166
+ return store.withTransaction((tx) => {
167
+ // Resolve-before-mutate, second leg: every claimed id must already exist.
168
+ // An unknown id is a hard failure - never a silent "treat as new".
169
+ for (const id of plan.requiredExisting) {
170
+ if (!tx.getTask(sessionId, id)) {
171
+ throw new TaskError("TASK_NOT_FOUND", `declared unknown task ${id}`)
172
+ }
173
+ }
174
+
175
+ const seen = new Set<string>()
176
+ const changed: Task[] = []
177
+ const created: Task[] = []
178
+ // PHASE 4A.4A — pushed in `plan.entries` order, which IS declaration order,
179
+ // so index i of this table always describes declared item i.
180
+ const assignment: CanonicalAssignment[] = []
181
+
182
+ plan.entries.forEach((entry, index) => {
183
+ const decl = declared[index]
184
+ const holdVerifying = decl?.holdVerifying === true
185
+ if (entry.kind === "existing") {
186
+ const id = entry.taskId as string
187
+ seen.add(id)
188
+ assignment.push({ taskId: id, kind: "existing" })
189
+ if (holdVerifying) {
190
+ changed.push(
191
+ tx.patchTask(sessionId, id, {
192
+ title: entry.title,
193
+ status: "VERIFYING",
194
+ order: entry.order,
195
+ blockedReason: null,
196
+ }),
197
+ )
198
+ } else if (entry.status === "COMPLETED" && verificationOutcome?.ok === true) {
199
+ const cur = tx.getTask(sessionId, id)!
200
+ if (cur.status !== "COMPLETED") {
201
+ tx.patchTask(sessionId, id, {
202
+ title: entry.title,
203
+ status: "VERIFYING",
204
+ order: entry.order,
205
+ blockedReason: null,
206
+ })
207
+ changed.push(tx.completeTaskVerification(sessionId, id, verificationOutcome))
208
+ } else {
209
+ changed.push(
210
+ tx.patchTask(sessionId, id, {
211
+ title: entry.title,
212
+ status: entry.status,
213
+ order: entry.order,
214
+ blockedReason: entry.blockedReason,
215
+ }),
216
+ )
217
+ }
218
+ } else {
219
+ changed.push(
220
+ tx.patchTask(sessionId, id, {
221
+ title: entry.title,
222
+ status: entry.status,
223
+ // `order` is the declared position. It is display/execution order,
224
+ // never identity.
225
+ order: entry.order,
226
+ blockedReason: entry.blockedReason,
227
+ }),
228
+ )
229
+ }
230
+ } else {
231
+ // Only TaskStore allocates. `input` was built by planTaskIdentities with
232
+ // provenance { origin: "model", source: "todo_write" }.
233
+ const baseInput = entry.input!
234
+ const createInput = holdVerifying
235
+ ? { ...baseInput, status: "VERIFYING" as const, blockedReason: null }
236
+ : entry.status === "COMPLETED" && verificationOutcome?.ok === true
237
+ ? {
238
+ ...baseInput,
239
+ status: "VERIFYING" as const,
240
+ blockedReason: null,
241
+ }
242
+ : baseInput
243
+ let t = tx.createTask(sessionId, createInput as never)
244
+ if (!holdVerifying && entry.status === "COMPLETED" && verificationOutcome?.ok === true) {
245
+ t = tx.completeTaskVerification(sessionId, t.id, verificationOutcome)
246
+ }
247
+ seen.add(t.id)
248
+ // The id the allocator actually returned, captured here and now — never
249
+ // re-derived from position, title or content afterwards.
250
+ assignment.push({ taskId: t.id, kind: "new" })
251
+ created.push(t)
252
+ }
253
+ })
254
+
255
+ // D7 — omission is NOT deletion. A task the model did not mention this turn
256
+ // is retained: not deleted, not cancelled, not reset. The canonical payload
257
+ // is a full DECLARATION, not a replacement.
258
+ //
259
+ // Retained tasks are placed after the declared range so that
260
+ // (task_order, task_id) stays a total, collision-free ordering key. The
261
+ // recovered artifact instead renumbered survivors to 0..n-1, which could
262
+ // collide with a declared item's own order; this is a deliberate difference.
263
+ const retained: Task[] = []
264
+ tx.listTasks(sessionId)
265
+ .filter((t) => !seen.has(t.id))
266
+ .sort((a, b) => a.order - b.order || a.id.localeCompare(b.id))
267
+ .forEach((t, i) => {
268
+ const order = plan.entries.length + i
269
+ retained.push(t.order === order ? t : tx.patchTask(sessionId, t.id, { order }))
270
+ })
271
+
272
+ return { applied: true, changed, created, retained, assignment }
273
+ })
274
+ }
275
+
276
+ /** Resolve canonical identity for a plan projection.
277
+ *
278
+ * Authority: TaskStore. An id is reported ONLY when the store actually holds
279
+ * that row for this session. Anything else is `null`, which makes the plan
280
+ * fall back to the positional legacy shape rather than emit a false `v2`.
281
+ */
282
+ export function createTaskIdentityResolver(cwd: string) {
283
+ return (input: { sessionId: string; declared: readonly { taskId?: string }[] }) => {
284
+ try {
285
+ const store = new TaskStore(cwd)
286
+ return input.declared.map((d) => {
287
+ if (!d.taskId || !isTaskId(d.taskId)) return null
288
+ return store.getTask(input.sessionId, d.taskId) ? d.taskId : null
289
+ })
290
+ } catch {
291
+ return undefined
292
+ }
293
+ }
294
+ }
295
+
296
+ /** Exported for the mapping the caller performs; kept here so the status
297
+ * vocabulary has a single owner. */
298
+ export { todoStatusToTask }
299
+
300
+ /**
301
+ * [Fase 3 / LOOP-INV-12] Pindahkan task kandidat sesi ke status `VERIFYING`
302
+ * tepat sebelum verifier dieksekusi. Hanya menyentuh task non-terminal yang
303
+ * diminta eksplisit (`candidateTaskIds`).
304
+ */
305
+ export function beginSessionTasksVerification(
306
+ cwd: string,
307
+ sessionId: string,
308
+ candidateTaskIds: readonly string[],
309
+ ): Task[] {
310
+ if (candidateTaskIds.length === 0) return []
311
+ const store = new TaskStore(cwd)
312
+ return store.withTransaction((tx) => {
313
+ const out: Task[] = []
314
+ for (const id of candidateTaskIds) {
315
+ if (!isTaskId(id)) continue
316
+ const cur = tx.getTask(sessionId, id)
317
+ if (!cur || isTerminalTaskStatus(cur.status) || cur.status === "VERIFYING") {
318
+ if (cur?.status === "VERIFYING") out.push(cur)
319
+ continue
320
+ }
321
+ out.push(tx.beginTaskVerification(sessionId, id))
322
+ }
323
+ return out
324
+ })
325
+ }
326
+
327
+ /**
328
+ * [Fase 3 / LOOP-INV-12] Selesaikan seluruh task sesi yang sedang berada di
329
+ * `VERIFYING` berdasarkan hasil verifikasi aktual (`VERIFYING -> COMPLETED`
330
+ * bila `outcome.ok === true`, atau `VERIFYING -> BLOCKED` bila gagal).
331
+ * Task dalam status lain (`PENDING`, `IN_PROGRESS`, `BLOCKED`) tidak disentuh.
332
+ */
333
+ export function settleSessionVerifyingTasks(
334
+ cwd: string,
335
+ sessionId: string,
336
+ outcome: VerificationGateOutcome,
337
+ ): Task[] {
338
+ const store = new TaskStore(cwd)
339
+ return store.withTransaction((tx) => {
340
+ const verifying = tx.listTasks(sessionId).filter((t) => t.status === "VERIFYING")
341
+ return verifying.map((t) => tx.completeTaskVerification(sessionId, t.id, outcome))
342
+ })
343
+ }
@@ -0,0 +1,260 @@
1
+ // PHASE 6T — TRIGGER.
2
+ //
3
+ // A trigger says: EVALUATE NOW.
4
+ //
5
+ // It does not say which task to run, whether one is ready, or whether anything
6
+ // will be claimed. Those are the policy's job, and the claim's. Merging the three
7
+ // is how a scheduler ends up doing durable work because someone poked it.
8
+ //
9
+ // ── WHY THIS FILE IS SMALL ────────────────────────────────────────────────────
10
+ //
11
+ // [FACT] The runtime has no periodic timer anywhere (survey 6T §2: the only
12
+ // `setInterval` calls in src/ paint a spinner and a status line), no task-mutation
13
+ // event (TaskStore writes are silent), and no task-shaped event on the kernel bus
14
+ // (`AgentEvent` carries turn/step/provider events only). There is therefore
15
+ // nothing to hook and nothing to poll, and a trigger layer built on any of them
16
+ // would be inventing infrastructure to justify itself.
17
+ //
18
+ // [DESIGN DECISION] So the trigger is a DECISION, not a mechanism: "may an
19
+ // evaluation start right now, and who is allowed to ask?" Transport is injected
20
+ // and absent. A future timer or a future task-mutation hook would call `fire()`;
21
+ // neither exists, neither is assumed, and the Scheduler still cannot be reached
22
+ // from production.
23
+ //
24
+ // ── TRIGGER vs CLAIM (6T §27) ───────────────────────────────────────────────
25
+ //
26
+ // trigger → "evaluate now" no durable effect whatsoever
27
+ // claim → "this task is mine" advances generation, writes ownership
28
+ //
29
+ // A refused trigger is recorded in memory and touches no row. A refused claim is
30
+ // reported by the same atomic statement that would have performed it. The
31
+ // coordinator below can therefore never leave durable state behind, and it has no
32
+ // store reference at all — the absence is the proof.
33
+
34
+ /**
35
+ * [FACT] Where an evaluation request came from. Classification from survey §2:
36
+ *
37
+ * - `startup` AVAILABLE BUT UNUSED — a composition root exists at
38
+ * `cli/setup.ts:950`; nothing calls `cycle()` there.
39
+ * - `task-mutation` AVAILABLE BUT UNUSED — `TaskStore.patchTask`/`createTask`
40
+ * emit nothing, so there is no signal to subscribe to.
41
+ * - `explicit-command` AVAILABLE BUT UNUSED — `cli/router.ts` has 13 subcommands,
42
+ * none task-related; adding one is an enablement decision
43
+ * and out of scope.
44
+ * - `interval` NOT IMPLEMENTED, and deliberately not added: a repeating
45
+ * timer is the one option that would require assuming
46
+ * MiniCode is a long-running server. It is not.
47
+ * - `event` AVAILABLE BUT UNUSED — the kernel bus is per-session and
48
+ * carries no task events.
49
+ * - `manual` TEST ONLY — this is what the property tests use.
50
+ */
51
+ export type TriggerSource =
52
+ | "startup"
53
+ | "task-mutation"
54
+ | "explicit-command"
55
+ | "interval"
56
+ | "event"
57
+ | "manual"
58
+
59
+ /** What the coordinator did with a request. An observation, never durable state. */
60
+ export type TriggerOutcome =
61
+ /** A cycle started, or joined the one already running. */
62
+ | "EVALUATED"
63
+ /** A cycle was already running; the request was folded into the follow-up. */
64
+ | "COALESCED"
65
+ /** The scheduler is not running. Nothing was started and nothing was written. */
66
+ | "REFUSED_NOT_RUNNING"
67
+ /** A cycle is already queued to re-run, so this request changed nothing. */
68
+ | "REFUSED_ALREADY_PENDING"
69
+
70
+ export interface TriggerResult {
71
+ readonly outcome: TriggerOutcome
72
+ readonly source: TriggerSource
73
+ /** Cycle result, when a cycle actually ran. `null` for every refusal. */
74
+ readonly cycle: unknown | null
75
+ }
76
+
77
+ export interface TriggerOptions {
78
+ /**
79
+ * Runs one evaluation. Injected, and in production this is `Scheduler.cycle`.
80
+ * Kept as an argument rather than imported so the coordinator has no dependency
81
+ * on the Scheduler and therefore no way to reach one.
82
+ */
83
+ readonly runCycle: () => Promise<unknown>
84
+ /** Lifecycle probe. Absent means "assume running", which is the test default. */
85
+ readonly isRunning?: () => boolean
86
+ /** Optional observation sink. Absence means events are dropped, not queued. */
87
+ readonly onEvent?: (event: TriggerEvent) => void
88
+ }
89
+
90
+ export type TriggerEvent =
91
+ | { readonly kind: "trigger:evaluated"; readonly source: TriggerSource }
92
+ | { readonly kind: "trigger:coalesced"; readonly source: TriggerSource }
93
+ | {
94
+ readonly kind: "trigger:refused"
95
+ readonly source: TriggerSource
96
+ readonly outcome: TriggerOutcome
97
+ }
98
+ | {
99
+ readonly kind: "trigger:cycle_failed"
100
+ readonly source: TriggerSource
101
+ readonly detail: string
102
+ }
103
+
104
+ /**
105
+ * [PHASE 6T] THE TRIGGER COORDINATOR.
106
+ *
107
+ * [DESIGN DECISION] Scope is PER SESSION, and that is inherited rather than
108
+ * chosen. The Scheduler is already per-session (`Scheduler(sessionId, …)`), the
109
+ * task namespace is the session, and 6Q's incarnation makes a session's tasks
110
+ * unusable after deletion. A per-process trigger would have to reason about which
111
+ * session it meant; a per-session one has exactly one namespace and no such
112
+ * question. Per-task triggering is not expressible and is not wanted: a task
113
+ * cannot ask to be run without something already knowing it exists.
114
+ *
115
+ * Concurrency: V1 runs at most one cycle, and requests arriving during it are
116
+ * COALESCED — either joined to the running cycle, or recorded as a single pending
117
+ * re-run. There is deliberately no queue: a queue would let N rapid task
118
+ * mutations become N evaluations, which is precisely the duplicate-trigger waste
119
+ * the design is meant to prevent. One pending re-run is enough, because a cycle
120
+ * re-reads the whole snapshot and would see every change that motivated the
121
+ * intermediate requests anyway.
122
+ */
123
+ export class TriggerCoordinator {
124
+ private readonly runCycle: () => Promise<unknown>
125
+ private readonly isRunning: () => boolean
126
+ private readonly onEvent: ((e: TriggerEvent) => void) | undefined
127
+
128
+ private inFlight: Promise<unknown> | null = null
129
+ private pending = false
130
+ private disposed = false
131
+
132
+ /** Counters for observability. In-memory; an observation, not a durable fact. */
133
+ private counts = { evaluated: 0, coalesced: 0, refused: 0, cyclesRun: 0, failures: 0 }
134
+
135
+ constructor(opts: TriggerOptions) {
136
+ this.runCycle = opts.runCycle
137
+ this.isRunning = opts.isRunning ?? (() => true)
138
+ this.onEvent = opts.onEvent
139
+ }
140
+
141
+ /**
142
+ * Request an evaluation.
143
+ *
144
+ * Never throws: a trigger is a request, and a request that crashes its caller
145
+ * would take down whatever asked for it. A failing cycle is reported through
146
+ * `onEvent` and counted, then the coordinator returns to idle.
147
+ */
148
+ async fire(source: TriggerSource): Promise<TriggerResult> {
149
+ if (this.disposed) {
150
+ return this.refuse(source, "REFUSED_NOT_RUNNING")
151
+ }
152
+ if (!this.isRunning()) {
153
+ // [DESIGN DECISION] Refuse BEFORE touching anything. A trigger against a
154
+ // stopped scheduler must not read a snapshot, build a graph, or reach the
155
+ // store — the refusal is the entire behaviour, and its purity is what makes
156
+ // "a refused trigger creates no durable state" a structural claim.
157
+ return this.refuse(source, "REFUSED_NOT_RUNNING")
158
+ }
159
+
160
+ if (this.inFlight !== null) {
161
+ // A cycle is running. Record that another is wanted and join this one.
162
+ this.pending = true
163
+ this.counts.coalesced++
164
+ this.emit({ kind: "trigger:coalesced", source })
165
+ return { outcome: "COALESCED", source, cycle: null }
166
+ }
167
+
168
+ this.counts.evaluated++
169
+ this.emit({ kind: "trigger:evaluated", source })
170
+ const cycle = await this.drain(source)
171
+ return { outcome: "EVALUATED", source, cycle }
172
+ }
173
+
174
+ /**
175
+ * Run a cycle, then honour at most ONE pending re-run.
176
+ *
177
+ * The `while` is bounded because `pending` is cleared before the next cycle
178
+ * starts: triggers arriving during the follow-up set it again, and this phase
179
+ * ends with `pending === false` even under a continuous trigger storm. An
180
+ * unbounded drain would be an infinite loop wearing a queue's clothes.
181
+ */
182
+ private async drain(source: TriggerSource): Promise<unknown> {
183
+ let last: unknown = null
184
+ do {
185
+ this.pending = false
186
+ this.inFlight = this.runCycle()
187
+ this.counts.cyclesRun++
188
+ try {
189
+ last = await this.inFlight
190
+ } catch (e) {
191
+ // [DESIGN DECISION] CONTINUE, do not stop. A cycle that throws is a
192
+ // failed EVALUATION, not evidence that the scheduler is broken. The
193
+ // scheduler's own contract already resolves almost every failure into a
194
+ // CycleResult; anything reaching here is a defect in the bridge or the
195
+ // store, and neither should poison the trigger.
196
+ this.counts.failures++
197
+ const detail = e instanceof Error ? e.message : String(e)
198
+ this.emit({ kind: "trigger:cycle_failed", source, detail })
199
+ } finally {
200
+ this.inFlight = null
201
+ }
202
+ } while (this.pending && !this.disposed)
203
+ return last
204
+ }
205
+
206
+ private emit(event: TriggerEvent): void {
207
+ // A throwing sink must never take the trigger layer down: observations are
208
+ // observability, not authority, and a diagnostic that can crash a cycle is
209
+ // worse than a missing diagnostic. Same rule as Scheduler.emit.
210
+ try {
211
+ this.onEvent?.(event)
212
+ } catch {
213
+ /* deliberately swallowed */
214
+ }
215
+ }
216
+
217
+ private refuse(source: TriggerSource, outcome: TriggerOutcome): TriggerResult {
218
+ this.counts.refused++
219
+ this.emit({ kind: "trigger:refused", source, outcome })
220
+ return { outcome, source, cycle: null }
221
+ }
222
+
223
+ /** True while a cycle is running or a re-run is owed. */
224
+ get busy(): boolean {
225
+ return this.inFlight !== null || this.pending
226
+ }
227
+
228
+ getStats(): Readonly<typeof this.counts> {
229
+ return { ...this.counts }
230
+ }
231
+
232
+ /**
233
+ * [PHASE 6T] Stop accepting triggers and refuse any that arrive later.
234
+ *
235
+ * [DESIGN DECISION] Deliberately does NOT cancel an in-flight cycle. `dispose`
236
+ * is the trigger layer's half of shutdown; stopping the WORK is the Scheduler's
237
+ * half (`cancelActive`), and conflating them would let a trigger cleanup reach
238
+ * into execution — the exact layering 6T §1 forbids. `awaitSettled()` is how a
239
+ * shutdown sequence waits for the cycle without either layer overstepping.
240
+ */
241
+ dispose(): void {
242
+ this.disposed = true
243
+ this.pending = false
244
+ }
245
+
246
+ get isDisposed(): boolean {
247
+ return this.disposed
248
+ }
249
+
250
+ /** Await any running cycle. Resolves even if it rejected. Never rejects. */
251
+ async awaitSettled(): Promise<void> {
252
+ while (this.inFlight !== null) {
253
+ try {
254
+ await this.inFlight
255
+ } catch {
256
+ // Already reported through the event sink; a shutdown must not throw.
257
+ }
258
+ }
259
+ }
260
+ }